broadcast.go 4.5 KB

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