broadcast.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at http://mozilla.org/MPL/2.0/.
  6. package beacon
  7. import (
  8. "fmt"
  9. "net"
  10. "time"
  11. "github.com/thejerf/suture"
  12. )
  13. type Broadcast struct {
  14. *suture.Supervisor
  15. port int
  16. inbox chan []byte
  17. outbox chan recv
  18. br *broadcastReader
  19. bw *broadcastWriter
  20. }
  21. func NewBroadcast(port int) *Broadcast {
  22. b := &Broadcast{
  23. Supervisor: suture.New("broadcastBeacon", suture.Spec{
  24. // Don't retry too frenetically: an error to open a socket or
  25. // whatever is usually something that is either permanent or takes
  26. // a while to get solved...
  27. FailureThreshold: 2,
  28. FailureBackoff: 60 * time.Second,
  29. // Only log restarts in debug mode.
  30. Log: func(line string) {
  31. l.Debugln(line)
  32. },
  33. }),
  34. port: port,
  35. inbox: make(chan []byte),
  36. outbox: make(chan recv, 16),
  37. }
  38. b.br = &broadcastReader{
  39. port: port,
  40. outbox: b.outbox,
  41. }
  42. b.Add(b.br)
  43. b.bw = &broadcastWriter{
  44. port: port,
  45. inbox: b.inbox,
  46. }
  47. b.Add(b.bw)
  48. return b
  49. }
  50. func (b *Broadcast) Send(data []byte) {
  51. b.inbox <- data
  52. }
  53. func (b *Broadcast) Recv() ([]byte, net.Addr) {
  54. recv := <-b.outbox
  55. return recv.data, recv.src
  56. }
  57. func (b *Broadcast) Error() error {
  58. if err := b.br.Error(); err != nil {
  59. return err
  60. }
  61. return b.bw.Error()
  62. }
  63. type broadcastWriter struct {
  64. port int
  65. inbox chan []byte
  66. conn *net.UDPConn
  67. errorHolder
  68. }
  69. func (w *broadcastWriter) Serve() {
  70. l.Debugln(w, "starting")
  71. defer l.Debugln(w, "stopping")
  72. var err error
  73. w.conn, err = net.ListenUDP("udp4", nil)
  74. if err != nil {
  75. l.Debugln(err)
  76. w.setError(err)
  77. return
  78. }
  79. defer w.conn.Close()
  80. for bs := range w.inbox {
  81. addrs, err := net.InterfaceAddrs()
  82. if err != nil {
  83. l.Debugln(err)
  84. w.setError(err)
  85. continue
  86. }
  87. var dsts []net.IP
  88. for _, addr := range addrs {
  89. if iaddr, ok := addr.(*net.IPNet); ok && len(iaddr.IP) >= 4 && iaddr.IP.IsGlobalUnicast() && iaddr.IP.To4() != nil {
  90. baddr := bcast(iaddr)
  91. dsts = append(dsts, baddr.IP)
  92. }
  93. }
  94. if len(dsts) == 0 {
  95. // Fall back to the general IPv4 broadcast address
  96. dsts = append(dsts, net.IP{0xff, 0xff, 0xff, 0xff})
  97. }
  98. l.Debugln("addresses:", dsts)
  99. success := 0
  100. for _, ip := range dsts {
  101. dst := &net.UDPAddr{IP: ip, Port: w.port}
  102. w.conn.SetWriteDeadline(time.Now().Add(time.Second))
  103. _, err := w.conn.WriteTo(bs, dst)
  104. w.conn.SetWriteDeadline(time.Time{})
  105. if err, ok := err.(net.Error); ok && err.Timeout() {
  106. // Write timeouts should not happen. We treat it as a fatal
  107. // error on the socket.
  108. l.Debugln(err)
  109. w.setError(err)
  110. return
  111. }
  112. if err, ok := err.(net.Error); ok && err.Temporary() {
  113. // A transient error. Lets hope for better luck in the future.
  114. l.Debugln(err)
  115. continue
  116. }
  117. if err != nil {
  118. // Some other error that we don't expect. Bail and retry.
  119. l.Debugln(err)
  120. w.setError(err)
  121. return
  122. }
  123. l.Debugf("sent %d bytes to %s", len(bs), dst)
  124. success++
  125. }
  126. if success > 0 {
  127. w.setError(nil)
  128. }
  129. }
  130. }
  131. func (w *broadcastWriter) Stop() {
  132. w.conn.Close()
  133. }
  134. func (w *broadcastWriter) String() string {
  135. return fmt.Sprintf("broadcastWriter@%p", w)
  136. }
  137. type broadcastReader struct {
  138. port int
  139. outbox chan recv
  140. conn *net.UDPConn
  141. errorHolder
  142. }
  143. func (r *broadcastReader) Serve() {
  144. l.Debugln(r, "starting")
  145. defer l.Debugln(r, "stopping")
  146. var err error
  147. r.conn, err = net.ListenUDP("udp4", &net.UDPAddr{Port: r.port})
  148. if err != nil {
  149. l.Debugln(err)
  150. r.setError(err)
  151. return
  152. }
  153. defer r.conn.Close()
  154. bs := make([]byte, 65536)
  155. for {
  156. n, addr, err := r.conn.ReadFrom(bs)
  157. if err != nil {
  158. l.Debugln(err)
  159. r.setError(err)
  160. return
  161. }
  162. r.setError(nil)
  163. l.Debugf("recv %d bytes from %s", n, addr)
  164. c := make([]byte, n)
  165. copy(c, bs)
  166. select {
  167. case r.outbox <- recv{c, addr}:
  168. default:
  169. l.Debugln("dropping message")
  170. }
  171. }
  172. }
  173. func (r *broadcastReader) Stop() {
  174. r.conn.Close()
  175. }
  176. func (r *broadcastReader) String() string {
  177. return fmt.Sprintf("broadcastReader@%p", r)
  178. }
  179. func bcast(ip *net.IPNet) *net.IPNet {
  180. var bc = &net.IPNet{}
  181. bc.IP = make([]byte, len(ip.IP))
  182. copy(bc.IP, ip.IP)
  183. bc.Mask = ip.Mask
  184. offset := len(bc.IP) - len(bc.Mask)
  185. for i := range bc.IP {
  186. if i-offset >= 0 {
  187. bc.IP[i] = ip.IP[i] | ^ip.Mask[i-offset]
  188. }
  189. }
  190. return bc
  191. }