client_udp.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This program is free software: you can redistribute it and/or modify it
  4. // under the terms of the GNU General Public License as published by the Free
  5. // Software Foundation, either version 3 of the License, or (at your option)
  6. // any later version.
  7. //
  8. // This program is distributed in the hope that it will be useful, but WITHOUT
  9. // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  10. // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  11. // more details.
  12. //
  13. // You should have received a copy of the GNU General Public License along
  14. // with this program. If not, see <http://www.gnu.org/licenses/>.
  15. package discover
  16. import (
  17. "encoding/hex"
  18. "io"
  19. "net"
  20. "net/url"
  21. "strconv"
  22. "sync"
  23. "time"
  24. "github.com/syncthing/syncthing/internal/protocol"
  25. )
  26. func init() {
  27. for _, proto := range []string{"udp", "udp4", "udp6"} {
  28. Register(proto, func(uri *url.URL, pkt *Announce) (Client, error) {
  29. c := &UDPClient{}
  30. err := c.Start(uri, pkt)
  31. if err != nil {
  32. return nil, err
  33. }
  34. return c, nil
  35. })
  36. }
  37. }
  38. type UDPClient struct {
  39. url *url.URL
  40. id protocol.DeviceID
  41. stop chan struct{}
  42. wg sync.WaitGroup
  43. listenAddress *net.UDPAddr
  44. globalBroadcastInterval time.Duration
  45. errorRetryInterval time.Duration
  46. status bool
  47. mut sync.RWMutex
  48. }
  49. func (d *UDPClient) Start(uri *url.URL, pkt *Announce) error {
  50. d.url = uri
  51. d.id = protocol.DeviceIDFromBytes(pkt.This.ID)
  52. d.stop = make(chan struct{})
  53. params := uri.Query()
  54. // The address must not have a port, as otherwise both announce and lookup
  55. // sockets would try to bind to the same port.
  56. addr, err := net.ResolveUDPAddr(d.url.Scheme, params.Get("listenaddress")+":0")
  57. if err != nil {
  58. return err
  59. }
  60. d.listenAddress = addr
  61. broadcastSeconds, err := strconv.ParseUint(params.Get("broadcast"), 0, 0)
  62. if err != nil {
  63. d.globalBroadcastInterval = DefaultGlobalBroadcastInterval
  64. } else {
  65. d.globalBroadcastInterval = time.Duration(broadcastSeconds) * time.Second
  66. }
  67. retrySeconds, err := strconv.ParseUint(params.Get("retry"), 0, 0)
  68. if err != nil {
  69. d.errorRetryInterval = DefaultErrorRetryInternval
  70. } else {
  71. d.errorRetryInterval = time.Duration(retrySeconds) * time.Second
  72. }
  73. d.wg.Add(1)
  74. go d.broadcast(pkt.MustMarshalXDR())
  75. return nil
  76. }
  77. func (d *UDPClient) broadcast(pkt []byte) {
  78. defer d.wg.Done()
  79. timer := time.NewTimer(0)
  80. conn, err := net.ListenUDP(d.url.Scheme, d.listenAddress)
  81. for err != nil {
  82. timer.Reset(d.errorRetryInterval)
  83. l.Warnf("Global UDP discovery (%s): %v; trying again in %v", d.url, err, d.errorRetryInterval)
  84. select {
  85. case <-d.stop:
  86. return
  87. case <-timer.C:
  88. }
  89. conn, err = net.ListenUDP(d.url.Scheme, d.listenAddress)
  90. }
  91. defer conn.Close()
  92. remote, err := net.ResolveUDPAddr(d.url.Scheme, d.url.Host)
  93. for err != nil {
  94. timer.Reset(d.errorRetryInterval)
  95. l.Warnf("Global UDP discovery (%s): %v; trying again in %v", d.url, err, d.errorRetryInterval)
  96. select {
  97. case <-d.stop:
  98. return
  99. case <-timer.C:
  100. }
  101. remote, err = net.ResolveUDPAddr(d.url.Scheme, d.url.Host)
  102. }
  103. timer.Reset(0)
  104. for {
  105. select {
  106. case <-d.stop:
  107. return
  108. case <-timer.C:
  109. var ok bool
  110. if debug {
  111. l.Debugf("Global UDP discovery (%s): send announcement -> %v\n%s", d.url, remote, hex.Dump(pkt))
  112. }
  113. _, err := conn.WriteTo(pkt, remote)
  114. if err != nil {
  115. if debug {
  116. l.Debugf("discover %s: warning: %s", d.url, err)
  117. }
  118. ok = false
  119. } else {
  120. // Verify that the announce server responds positively for our device ID
  121. time.Sleep(1 * time.Second)
  122. res := d.Lookup(d.id)
  123. if debug {
  124. l.Debugf("discover %s: external lookup check: %v", d.url, res)
  125. }
  126. ok = len(res) > 0
  127. }
  128. d.mut.Lock()
  129. d.status = ok
  130. d.mut.Unlock()
  131. if ok {
  132. timer.Reset(d.globalBroadcastInterval)
  133. } else {
  134. timer.Reset(d.errorRetryInterval)
  135. }
  136. }
  137. }
  138. }
  139. func (d *UDPClient) Lookup(device protocol.DeviceID) []string {
  140. extIP, err := net.ResolveUDPAddr(d.url.Scheme, d.url.Host)
  141. if err != nil {
  142. if debug {
  143. l.Debugf("discover %s: %v; no external lookup", d.url, err)
  144. }
  145. return nil
  146. }
  147. conn, err := net.DialUDP(d.url.Scheme, d.listenAddress, extIP)
  148. if err != nil {
  149. if debug {
  150. l.Debugf("discover %s: %v; no external lookup", d.url, err)
  151. }
  152. return nil
  153. }
  154. defer conn.Close()
  155. err = conn.SetDeadline(time.Now().Add(5 * time.Second))
  156. if err != nil {
  157. if debug {
  158. l.Debugf("discover %s: %v; no external lookup", d.url, err)
  159. }
  160. return nil
  161. }
  162. buf := Query{QueryMagic, device[:]}.MustMarshalXDR()
  163. _, err = conn.Write(buf)
  164. if err != nil {
  165. if debug {
  166. l.Debugf("discover %s: %v; no external lookup", d.url, err)
  167. }
  168. return nil
  169. }
  170. buf = make([]byte, 2048)
  171. n, err := conn.Read(buf)
  172. if err != nil {
  173. if err, ok := err.(net.Error); ok && err.Timeout() {
  174. // Expected if the server doesn't know about requested device ID
  175. return nil
  176. }
  177. if debug {
  178. l.Debugf("discover %s: %v; no external lookup", d.url, err)
  179. }
  180. return nil
  181. }
  182. if debug {
  183. l.Debugf("discover %s: read external:\n%s", d.url, hex.Dump(buf[:n]))
  184. }
  185. var pkt Announce
  186. err = pkt.UnmarshalXDR(buf[:n])
  187. if err != nil && err != io.EOF {
  188. if debug {
  189. l.Debugln("discover %s:", d.url, err)
  190. }
  191. return nil
  192. }
  193. var addrs []string
  194. for _, a := range pkt.This.Addresses {
  195. deviceAddr := net.JoinHostPort(net.IP(a.IP).String(), strconv.Itoa(int(a.Port)))
  196. addrs = append(addrs, deviceAddr)
  197. }
  198. return addrs
  199. }
  200. func (d *UDPClient) Stop() {
  201. if d.stop != nil {
  202. close(d.stop)
  203. d.wg.Wait()
  204. }
  205. }
  206. func (d *UDPClient) StatusOK() bool {
  207. d.mut.RLock()
  208. defer d.mut.RUnlock()
  209. return d.status
  210. }
  211. func (d *UDPClient) Address() string {
  212. return d.url.String()
  213. }