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