client_udp.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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. conn, err := net.ListenUDP(d.url.Scheme, d.listenAddress)
  80. for err != nil {
  81. l.Warnf("Global UDP discovery (%s): %v; trying again in %v", d.url, err, d.errorRetryInterval)
  82. select {
  83. case <-d.stop:
  84. return
  85. case <-time.After(d.errorRetryInterval):
  86. }
  87. conn, err = net.ListenUDP(d.url.Scheme, d.listenAddress)
  88. }
  89. defer conn.Close()
  90. remote, err := net.ResolveUDPAddr(d.url.Scheme, d.url.Host)
  91. for err != nil {
  92. l.Warnf("Global UDP discovery (%s): %v; trying again in %v", d.url, err, d.errorRetryInterval)
  93. select {
  94. case <-d.stop:
  95. return
  96. case <-time.After(d.errorRetryInterval):
  97. }
  98. remote, err = net.ResolveUDPAddr(d.url.Scheme, d.url.Host)
  99. }
  100. timer := time.NewTimer(0)
  101. for {
  102. select {
  103. case <-d.stop:
  104. return
  105. case <-timer.C:
  106. var ok bool
  107. if debug {
  108. l.Debugf("Global UDP discovery (%s): send announcement -> %v\n%s", d.url, remote, hex.Dump(pkt))
  109. }
  110. _, err := conn.WriteTo(pkt, remote)
  111. if err != nil {
  112. if debug {
  113. l.Debugf("discover %s: warning: %s", d.url, err)
  114. }
  115. ok = false
  116. } else {
  117. // Verify that the announce server responds positively for our device ID
  118. time.Sleep(1 * time.Second)
  119. res := d.Lookup(d.id)
  120. if debug {
  121. l.Debugf("discover %s: external lookup check: %v", d.url, res)
  122. }
  123. ok = len(res) > 0
  124. }
  125. d.mut.Lock()
  126. d.status = ok
  127. d.mut.Unlock()
  128. if ok {
  129. timer.Reset(d.globalBroadcastInterval)
  130. } else {
  131. timer.Reset(d.errorRetryInterval)
  132. }
  133. }
  134. }
  135. }
  136. func (d *UDPClient) Lookup(device protocol.DeviceID) []string {
  137. extIP, err := net.ResolveUDPAddr(d.url.Scheme, d.url.Host)
  138. if err != nil {
  139. if debug {
  140. l.Debugf("discover %s: %v; no external lookup", d.url, err)
  141. }
  142. return nil
  143. }
  144. conn, err := net.DialUDP(d.url.Scheme, d.listenAddress, extIP)
  145. if err != nil {
  146. if debug {
  147. l.Debugf("discover %s: %v; no external lookup", d.url, err)
  148. }
  149. return nil
  150. }
  151. defer conn.Close()
  152. err = conn.SetDeadline(time.Now().Add(5 * time.Second))
  153. if err != nil {
  154. if debug {
  155. l.Debugf("discover %s: %v; no external lookup", d.url, err)
  156. }
  157. return nil
  158. }
  159. buf := Query{QueryMagic, device[:]}.MustMarshalXDR()
  160. _, err = conn.Write(buf)
  161. if err != nil {
  162. if debug {
  163. l.Debugf("discover %s: %v; no external lookup", d.url, err)
  164. }
  165. return nil
  166. }
  167. buf = make([]byte, 2048)
  168. n, err := conn.Read(buf)
  169. if err != nil {
  170. if err, ok := err.(net.Error); ok && err.Timeout() {
  171. // Expected if the server doesn't know about requested device ID
  172. return nil
  173. }
  174. if debug {
  175. l.Debugf("discover %s: %v; no external lookup", d.url, err)
  176. }
  177. return nil
  178. }
  179. if debug {
  180. l.Debugf("discover %s: read external:\n%s", d.url, hex.Dump(buf[:n]))
  181. }
  182. var pkt Announce
  183. err = pkt.UnmarshalXDR(buf[:n])
  184. if err != nil && err != io.EOF {
  185. if debug {
  186. l.Debugln("discover %s:", d.url, err)
  187. }
  188. return nil
  189. }
  190. var addrs []string
  191. for _, a := range pkt.This.Addresses {
  192. deviceAddr := net.JoinHostPort(net.IP(a.IP).String(), strconv.Itoa(int(a.Port)))
  193. addrs = append(addrs, deviceAddr)
  194. }
  195. return addrs
  196. }
  197. func (d *UDPClient) Stop() {
  198. if d.stop != nil {
  199. close(d.stop)
  200. d.wg.Wait()
  201. }
  202. }
  203. func (d *UDPClient) StatusOK() bool {
  204. d.mut.RLock()
  205. defer d.mut.RUnlock()
  206. return d.status
  207. }
  208. func (d *UDPClient) Address() string {
  209. return d.url.String()
  210. }