local.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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 discover
  7. import (
  8. "context"
  9. "encoding/binary"
  10. "encoding/hex"
  11. "fmt"
  12. "io"
  13. "net"
  14. "net/url"
  15. "strconv"
  16. "time"
  17. "github.com/syncthing/syncthing/lib/beacon"
  18. "github.com/syncthing/syncthing/lib/events"
  19. "github.com/syncthing/syncthing/lib/protocol"
  20. "github.com/syncthing/syncthing/lib/rand"
  21. "github.com/syncthing/syncthing/lib/svcutil"
  22. "github.com/thejerf/suture/v4"
  23. )
  24. type localClient struct {
  25. *suture.Supervisor
  26. myID protocol.DeviceID
  27. addrList AddressLister
  28. name string
  29. evLogger events.Logger
  30. beacon beacon.Interface
  31. localBcastStart time.Time
  32. localBcastTick <-chan time.Time
  33. forcedBcastTick chan time.Time
  34. *cache
  35. }
  36. const (
  37. BroadcastInterval = 30 * time.Second
  38. CacheLifeTime = 3 * BroadcastInterval
  39. Magic = uint32(0x2EA7D90B) // same as in BEP
  40. v13Magic = uint32(0x7D79BC40) // previous version
  41. )
  42. func NewLocal(id protocol.DeviceID, addr string, addrList AddressLister, evLogger events.Logger) (FinderService, error) {
  43. c := &localClient{
  44. Supervisor: suture.New("local", svcutil.SpecWithDebugLogger(l)),
  45. myID: id,
  46. addrList: addrList,
  47. evLogger: evLogger,
  48. localBcastTick: time.NewTicker(BroadcastInterval).C,
  49. forcedBcastTick: make(chan time.Time),
  50. localBcastStart: time.Now(),
  51. cache: newCache(),
  52. }
  53. host, port, err := net.SplitHostPort(addr)
  54. if err != nil {
  55. return nil, err
  56. }
  57. if len(host) == 0 {
  58. // A broadcast client
  59. c.name = "IPv4 local"
  60. bcPort, err := strconv.Atoi(port)
  61. if err != nil {
  62. return nil, err
  63. }
  64. c.beacon = beacon.NewBroadcast(bcPort)
  65. } else {
  66. // A multicast client
  67. c.name = "IPv6 local"
  68. c.beacon = beacon.NewMulticast(addr)
  69. }
  70. c.Add(c.beacon)
  71. c.Add(svcutil.AsService(c.recvAnnouncements, fmt.Sprintf("%s/recv", c)))
  72. c.Add(svcutil.AsService(c.sendLocalAnnouncements, fmt.Sprintf("%s/sendLocal", c)))
  73. return c, nil
  74. }
  75. // Lookup returns a list of addresses the device is available at.
  76. func (c *localClient) Lookup(_ context.Context, device protocol.DeviceID) (addresses []string, err error) {
  77. if cache, ok := c.Get(device); ok {
  78. if time.Since(cache.when) < CacheLifeTime {
  79. addresses = cache.Addresses
  80. }
  81. }
  82. return
  83. }
  84. func (c *localClient) String() string {
  85. return c.name
  86. }
  87. func (c *localClient) Error() error {
  88. return c.beacon.Error()
  89. }
  90. // announcementPkt appends the local discovery packet to send to msg. Returns
  91. // true if the packet should be sent, false if there is nothing useful to
  92. // send.
  93. func (c *localClient) announcementPkt(instanceID int64, msg []byte) ([]byte, bool) {
  94. addrs := c.addrList.AllAddresses()
  95. if len(addrs) == 0 {
  96. // Nothing to announce
  97. return msg, false
  98. }
  99. if cap(msg) >= 4 {
  100. msg = msg[:4]
  101. } else {
  102. msg = make([]byte, 4)
  103. }
  104. binary.BigEndian.PutUint32(msg, Magic)
  105. pkt := Announce{
  106. ID: c.myID,
  107. Addresses: addrs,
  108. InstanceID: instanceID,
  109. }
  110. bs, _ := pkt.Marshal()
  111. msg = append(msg, bs...)
  112. return msg, true
  113. }
  114. func (c *localClient) sendLocalAnnouncements(ctx context.Context) error {
  115. var msg []byte
  116. var ok bool
  117. instanceID := rand.Int63()
  118. for {
  119. if msg, ok = c.announcementPkt(instanceID, msg[:0]); ok {
  120. c.beacon.Send(msg)
  121. }
  122. select {
  123. case <-c.localBcastTick:
  124. case <-c.forcedBcastTick:
  125. case <-ctx.Done():
  126. return ctx.Err()
  127. }
  128. }
  129. }
  130. func (c *localClient) recvAnnouncements(ctx context.Context) error {
  131. b := c.beacon
  132. warnedAbout := make(map[string]bool)
  133. for {
  134. select {
  135. case <-ctx.Done():
  136. return ctx.Err()
  137. default:
  138. }
  139. buf, addr := b.Recv()
  140. if addr == nil {
  141. continue
  142. }
  143. if len(buf) < 4 {
  144. l.Debugf("discover: short packet from %s", addr.String())
  145. continue
  146. }
  147. magic := binary.BigEndian.Uint32(buf)
  148. switch magic {
  149. case Magic:
  150. // All good
  151. case v13Magic:
  152. // Old version
  153. if !warnedAbout[addr.String()] {
  154. l.Warnf("Incompatible (v0.13) local discovery packet from %v - upgrade that device to connect", addr)
  155. warnedAbout[addr.String()] = true
  156. }
  157. continue
  158. default:
  159. l.Debugf("discover: Incorrect magic %x from %s", magic, addr)
  160. continue
  161. }
  162. var pkt Announce
  163. err := pkt.Unmarshal(buf[4:])
  164. if err != nil && err != io.EOF {
  165. l.Debugf("discover: Failed to unmarshal local announcement from %s:\n%s", addr, hex.Dump(buf))
  166. continue
  167. }
  168. l.Debugf("discover: Received local announcement from %s for %s", addr, pkt.ID)
  169. var newDevice bool
  170. if pkt.ID != c.myID {
  171. newDevice = c.registerDevice(addr, pkt)
  172. }
  173. if newDevice {
  174. // Force a transmit to announce ourselves, if we are ready to do
  175. // so right away.
  176. select {
  177. case c.forcedBcastTick <- time.Now():
  178. default:
  179. }
  180. }
  181. }
  182. }
  183. func (c *localClient) registerDevice(src net.Addr, device Announce) bool {
  184. // Remember whether we already had a valid cache entry for this device.
  185. // If the instance ID has changed the remote device has restarted since
  186. // we last heard from it, so we should treat it as a new device.
  187. ce, existsAlready := c.Get(device.ID)
  188. isNewDevice := !existsAlready || time.Since(ce.when) > CacheLifeTime || ce.instanceID != device.InstanceID
  189. // Any empty or unspecified addresses should be set to the source address
  190. // of the announcement. We also skip any addresses we can't parse.
  191. l.Debugln("discover: Registering addresses for", device.ID)
  192. var validAddresses []string
  193. for _, addr := range device.Addresses {
  194. u, err := url.Parse(addr)
  195. if err != nil {
  196. continue
  197. }
  198. tcpAddr, err := net.ResolveTCPAddr("tcp", u.Host)
  199. if err != nil {
  200. continue
  201. }
  202. if len(tcpAddr.IP) == 0 || tcpAddr.IP.IsUnspecified() {
  203. srcAddr, err := net.ResolveTCPAddr("tcp", src.String())
  204. if err != nil {
  205. continue
  206. }
  207. // Do not use IPv6 source address if requested scheme is tcp4
  208. if u.Scheme == "tcp4" && srcAddr.IP.To4() == nil {
  209. continue
  210. }
  211. // Do not use IPv4 source address if requested scheme is tcp6
  212. if u.Scheme == "tcp6" && srcAddr.IP.To4() != nil {
  213. continue
  214. }
  215. host, _, err := net.SplitHostPort(src.String())
  216. if err != nil {
  217. continue
  218. }
  219. u.Host = net.JoinHostPort(host, strconv.Itoa(tcpAddr.Port))
  220. l.Debugf("discover: Reconstructed URL is %#v", u)
  221. validAddresses = append(validAddresses, u.String())
  222. l.Debugf("discover: Replaced address %v in %s to get %s", tcpAddr.IP, addr, u.String())
  223. } else {
  224. validAddresses = append(validAddresses, addr)
  225. l.Debugf("discover: Accepted address %s verbatim", addr)
  226. }
  227. }
  228. c.Set(device.ID, CacheEntry{
  229. Addresses: validAddresses,
  230. when: time.Now(),
  231. found: true,
  232. instanceID: device.InstanceID,
  233. })
  234. if isNewDevice {
  235. c.evLogger.Log(events.DeviceDiscovered, map[string]interface{}{
  236. "device": device.ID.String(),
  237. "addrs": validAddresses,
  238. })
  239. }
  240. return isNewDevice
  241. }