broadcast.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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. if debug {
  32. l.Debugln(line)
  33. }
  34. },
  35. }),
  36. port: port,
  37. inbox: make(chan []byte),
  38. outbox: make(chan recv, 16),
  39. }
  40. b.br = &broadcastReader{
  41. port: port,
  42. outbox: b.outbox,
  43. }
  44. b.Add(b.br)
  45. b.bw = &broadcastWriter{
  46. port: port,
  47. inbox: b.inbox,
  48. }
  49. b.Add(b.bw)
  50. return b
  51. }
  52. func (b *Broadcast) Send(data []byte) {
  53. b.inbox <- data
  54. }
  55. func (b *Broadcast) Recv() ([]byte, net.Addr) {
  56. recv := <-b.outbox
  57. return recv.data, recv.src
  58. }
  59. func (b *Broadcast) Error() error {
  60. if err := b.br.Error(); err != nil {
  61. return err
  62. }
  63. return b.bw.Error()
  64. }
  65. type broadcastWriter struct {
  66. port int
  67. inbox chan []byte
  68. conn *net.UDPConn
  69. errorHolder
  70. }
  71. func (w *broadcastWriter) Serve() {
  72. if debug {
  73. l.Debugln(w, "starting")
  74. defer l.Debugln(w, "stopping")
  75. }
  76. var err error
  77. w.conn, err = net.ListenUDP("udp4", nil)
  78. if err != nil {
  79. if debug {
  80. l.Debugln(err)
  81. }
  82. w.setError(err)
  83. return
  84. }
  85. defer w.conn.Close()
  86. for bs := range w.inbox {
  87. addrs, err := net.InterfaceAddrs()
  88. if err != nil {
  89. if debug {
  90. l.Debugln(err)
  91. }
  92. w.setError(err)
  93. continue
  94. }
  95. var dsts []net.IP
  96. for _, addr := range addrs {
  97. if iaddr, ok := addr.(*net.IPNet); ok && len(iaddr.IP) >= 4 && iaddr.IP.IsGlobalUnicast() && iaddr.IP.To4() != nil {
  98. baddr := bcast(iaddr)
  99. dsts = append(dsts, baddr.IP)
  100. }
  101. }
  102. if len(dsts) == 0 {
  103. // Fall back to the general IPv4 broadcast address
  104. dsts = append(dsts, net.IP{0xff, 0xff, 0xff, 0xff})
  105. }
  106. if debug {
  107. l.Debugln("addresses:", dsts)
  108. }
  109. for _, ip := range dsts {
  110. dst := &net.UDPAddr{IP: ip, Port: w.port}
  111. w.conn.SetWriteDeadline(time.Now().Add(time.Second))
  112. _, err := w.conn.WriteTo(bs, dst)
  113. w.conn.SetWriteDeadline(time.Time{})
  114. if err, ok := err.(net.Error); ok && err.Timeout() {
  115. // Write timeouts should not happen. We treat it as a fatal
  116. // error on the socket.
  117. if debug {
  118. l.Debugln(err)
  119. }
  120. w.setError(err)
  121. return
  122. } else if err, ok := err.(net.Error); ok && err.Temporary() {
  123. // A transient error. Lets hope for better luck in the future.
  124. if debug {
  125. l.Debugln(err)
  126. }
  127. continue
  128. } else if err != nil {
  129. // Some other error that we don't expect. Bail and retry.
  130. if debug {
  131. l.Debugln(err)
  132. }
  133. w.setError(err)
  134. return
  135. } else if debug {
  136. l.Debugf("sent %d bytes to %s", len(bs), dst)
  137. w.setError(nil)
  138. }
  139. }
  140. }
  141. }
  142. func (w *broadcastWriter) Stop() {
  143. w.conn.Close()
  144. }
  145. func (w *broadcastWriter) String() string {
  146. return fmt.Sprintf("broadcastWriter@%p", w)
  147. }
  148. type broadcastReader struct {
  149. port int
  150. outbox chan recv
  151. conn *net.UDPConn
  152. errorHolder
  153. }
  154. func (r *broadcastReader) Serve() {
  155. if debug {
  156. l.Debugln(r, "starting")
  157. defer l.Debugln(r, "stopping")
  158. }
  159. var err error
  160. r.conn, err = net.ListenUDP("udp4", &net.UDPAddr{Port: r.port})
  161. if err != nil {
  162. if debug {
  163. l.Debugln(err)
  164. }
  165. r.setError(err)
  166. return
  167. }
  168. defer r.conn.Close()
  169. bs := make([]byte, 65536)
  170. for {
  171. n, addr, err := r.conn.ReadFrom(bs)
  172. if err != nil {
  173. if debug {
  174. l.Debugln(err)
  175. }
  176. r.setError(err)
  177. return
  178. }
  179. r.setError(nil)
  180. if debug {
  181. l.Debugf("recv %d bytes from %s", n, addr)
  182. }
  183. c := make([]byte, n)
  184. copy(c, bs)
  185. select {
  186. case r.outbox <- recv{c, addr}:
  187. default:
  188. if debug {
  189. l.Debugln("dropping message")
  190. }
  191. }
  192. }
  193. }
  194. func (r *broadcastReader) Stop() {
  195. r.conn.Close()
  196. }
  197. func (r *broadcastReader) String() string {
  198. return fmt.Sprintf("broadcastReader@%p", r)
  199. }
  200. func bcast(ip *net.IPNet) *net.IPNet {
  201. var bc = &net.IPNet{}
  202. bc.IP = make([]byte, len(ip.IP))
  203. copy(bc.IP, ip.IP)
  204. bc.Mask = ip.Mask
  205. offset := len(bc.IP) - len(bc.Mask)
  206. for i := range bc.IP {
  207. if i-offset >= 0 {
  208. bc.IP[i] = ip.IP[i] | ^ip.Mask[i-offset]
  209. }
  210. }
  211. return bc
  212. }