broadcast.go 4.7 KB

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