local.go 6.8 KB

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