discover.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. // Copyright (C) 2014 Jakob Borg and Contributors (see the CONTRIBUTORS file).
  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. "bytes"
  18. "encoding/hex"
  19. "errors"
  20. "io"
  21. "net"
  22. "strconv"
  23. "sync"
  24. "time"
  25. "github.com/syncthing/syncthing/internal/beacon"
  26. "github.com/syncthing/syncthing/internal/events"
  27. "github.com/syncthing/syncthing/internal/protocol"
  28. )
  29. type Discoverer struct {
  30. myID protocol.DeviceID
  31. listenAddrs []string
  32. localBcastIntv time.Duration
  33. globalBcastIntv time.Duration
  34. errorRetryIntv time.Duration
  35. cacheLifetime time.Duration
  36. broadcastBeacon beacon.Interface
  37. multicastBeacon beacon.Interface
  38. registry map[protocol.DeviceID][]CacheEntry
  39. registryLock sync.RWMutex
  40. extServer string
  41. extPort uint16
  42. localBcastTick <-chan time.Time
  43. stopGlobal chan struct{}
  44. globalWG sync.WaitGroup
  45. forcedBcastTick chan time.Time
  46. extAnnounceOK bool
  47. extAnnounceOKmut sync.Mutex
  48. }
  49. type CacheEntry struct {
  50. Address string
  51. Seen time.Time
  52. }
  53. var (
  54. ErrIncorrectMagic = errors.New("incorrect magic number")
  55. )
  56. func NewDiscoverer(id protocol.DeviceID, addresses []string) *Discoverer {
  57. return &Discoverer{
  58. myID: id,
  59. listenAddrs: addresses,
  60. localBcastIntv: 30 * time.Second,
  61. globalBcastIntv: 1800 * time.Second,
  62. errorRetryIntv: 60 * time.Second,
  63. cacheLifetime: 5 * time.Minute,
  64. registry: make(map[protocol.DeviceID][]CacheEntry),
  65. }
  66. }
  67. func (d *Discoverer) StartLocal(localPort int, localMCAddr string) {
  68. if localPort > 0 {
  69. bb, err := beacon.NewBroadcast(localPort)
  70. if err != nil {
  71. if debug {
  72. l.Debugln(err)
  73. }
  74. l.Infoln("Local discovery over IPv4 unavailable")
  75. } else {
  76. d.broadcastBeacon = bb
  77. go d.recvAnnouncements(bb)
  78. }
  79. }
  80. if len(localMCAddr) > 0 {
  81. mb, err := beacon.NewMulticast(localMCAddr)
  82. if err != nil {
  83. if debug {
  84. l.Debugln(err)
  85. }
  86. l.Infoln("Local discovery over IPv6 unavailable")
  87. } else {
  88. d.multicastBeacon = mb
  89. go d.recvAnnouncements(mb)
  90. }
  91. }
  92. if d.broadcastBeacon == nil && d.multicastBeacon == nil {
  93. l.Warnln("Local discovery unavailable")
  94. } else {
  95. d.localBcastTick = time.Tick(d.localBcastIntv)
  96. d.forcedBcastTick = make(chan time.Time)
  97. go d.sendLocalAnnouncements()
  98. }
  99. }
  100. func (d *Discoverer) StartGlobal(server string, extPort uint16) {
  101. // Wait for any previous announcer to stop before starting a new one.
  102. d.globalWG.Wait()
  103. d.extServer = server
  104. d.extPort = extPort
  105. d.stopGlobal = make(chan struct{})
  106. d.globalWG.Add(1)
  107. go d.sendExternalAnnouncements()
  108. }
  109. func (d *Discoverer) StopGlobal() {
  110. if d.stopGlobal != nil {
  111. close(d.stopGlobal)
  112. d.globalWG.Wait()
  113. }
  114. }
  115. func (d *Discoverer) ExtAnnounceOK() bool {
  116. d.extAnnounceOKmut.Lock()
  117. defer d.extAnnounceOKmut.Unlock()
  118. return d.extAnnounceOK
  119. }
  120. func (d *Discoverer) Lookup(device protocol.DeviceID) []string {
  121. d.registryLock.RLock()
  122. cached := d.filterCached(d.registry[device])
  123. d.registryLock.RUnlock()
  124. if len(cached) > 0 {
  125. addrs := make([]string, len(cached))
  126. for i := range cached {
  127. addrs[i] = cached[i].Address
  128. }
  129. return addrs
  130. } else if len(d.extServer) != 0 {
  131. addrs := d.externalLookup(device)
  132. cached = make([]CacheEntry, len(addrs))
  133. for i := range addrs {
  134. cached[i] = CacheEntry{
  135. Address: addrs[i],
  136. Seen: time.Now(),
  137. }
  138. }
  139. d.registryLock.Lock()
  140. d.registry[device] = cached
  141. d.registryLock.Unlock()
  142. }
  143. return nil
  144. }
  145. func (d *Discoverer) Hint(device string, addrs []string) {
  146. resAddrs := resolveAddrs(addrs)
  147. var id protocol.DeviceID
  148. id.UnmarshalText([]byte(device))
  149. d.registerDevice(nil, Device{
  150. Addresses: resAddrs,
  151. ID: id[:],
  152. })
  153. }
  154. func (d *Discoverer) All() map[protocol.DeviceID][]CacheEntry {
  155. d.registryLock.RLock()
  156. devices := make(map[protocol.DeviceID][]CacheEntry, len(d.registry))
  157. for device, addrs := range d.registry {
  158. addrsCopy := make([]CacheEntry, len(addrs))
  159. copy(addrsCopy, addrs)
  160. devices[device] = addrsCopy
  161. }
  162. d.registryLock.RUnlock()
  163. return devices
  164. }
  165. func (d *Discoverer) announcementPkt() []byte {
  166. var addrs []Address
  167. for _, astr := range d.listenAddrs {
  168. addr, err := net.ResolveTCPAddr("tcp", astr)
  169. if err != nil {
  170. l.Warnln("%v: not announcing %s", err, astr)
  171. continue
  172. } else if debug {
  173. l.Debugf("discover: announcing %s: %#v", astr, addr)
  174. }
  175. if len(addr.IP) == 0 || addr.IP.IsUnspecified() {
  176. addrs = append(addrs, Address{Port: uint16(addr.Port)})
  177. } else if bs := addr.IP.To4(); bs != nil {
  178. addrs = append(addrs, Address{IP: bs, Port: uint16(addr.Port)})
  179. } else if bs := addr.IP.To16(); bs != nil {
  180. addrs = append(addrs, Address{IP: bs, Port: uint16(addr.Port)})
  181. }
  182. }
  183. var pkt = Announce{
  184. Magic: AnnouncementMagic,
  185. This: Device{d.myID[:], addrs},
  186. }
  187. return pkt.MustMarshalXDR()
  188. }
  189. func (d *Discoverer) sendLocalAnnouncements() {
  190. var addrs = resolveAddrs(d.listenAddrs)
  191. var pkt = Announce{
  192. Magic: AnnouncementMagic,
  193. This: Device{d.myID[:], addrs},
  194. }
  195. msg := pkt.MustMarshalXDR()
  196. for {
  197. if d.multicastBeacon != nil {
  198. d.multicastBeacon.Send(msg)
  199. }
  200. if d.broadcastBeacon != nil {
  201. d.broadcastBeacon.Send(msg)
  202. }
  203. select {
  204. case <-d.localBcastTick:
  205. case <-d.forcedBcastTick:
  206. }
  207. }
  208. }
  209. func (d *Discoverer) sendExternalAnnouncements() {
  210. defer d.globalWG.Done()
  211. remote, err := net.ResolveUDPAddr("udp", d.extServer)
  212. for err != nil {
  213. l.Warnf("Global discovery: %v; trying again in %v", err, d.errorRetryIntv)
  214. time.Sleep(d.errorRetryIntv)
  215. remote, err = net.ResolveUDPAddr("udp", d.extServer)
  216. }
  217. conn, err := net.ListenUDP("udp", nil)
  218. for err != nil {
  219. l.Warnf("Global discovery: %v; trying again in %v", err, d.errorRetryIntv)
  220. time.Sleep(d.errorRetryIntv)
  221. conn, err = net.ListenUDP("udp", nil)
  222. }
  223. var buf []byte
  224. if d.extPort != 0 {
  225. var pkt = Announce{
  226. Magic: AnnouncementMagic,
  227. This: Device{d.myID[:], []Address{{Port: d.extPort}}},
  228. }
  229. buf = pkt.MustMarshalXDR()
  230. } else {
  231. buf = d.announcementPkt()
  232. }
  233. var bcastTick = time.Tick(d.globalBcastIntv)
  234. var errTick <-chan time.Time
  235. sendOneAnnouncement := func() {
  236. var ok bool
  237. if debug {
  238. l.Debugf("discover: send announcement -> %v\n%s", remote, hex.Dump(buf))
  239. }
  240. _, err := conn.WriteTo(buf, remote)
  241. if err != nil {
  242. if debug {
  243. l.Debugln("discover: warning:", err)
  244. }
  245. ok = false
  246. } else {
  247. // Verify that the announce server responds positively for our device ID
  248. time.Sleep(1 * time.Second)
  249. res := d.externalLookup(d.myID)
  250. if debug {
  251. l.Debugln("discover: external lookup check:", res)
  252. }
  253. ok = len(res) > 0
  254. }
  255. d.extAnnounceOKmut.Lock()
  256. d.extAnnounceOK = ok
  257. d.extAnnounceOKmut.Unlock()
  258. if ok {
  259. errTick = nil
  260. } else if errTick != nil {
  261. errTick = time.Tick(d.errorRetryIntv)
  262. }
  263. }
  264. // Announce once, immediately
  265. sendOneAnnouncement()
  266. loop:
  267. for {
  268. select {
  269. case <-d.stopGlobal:
  270. break loop
  271. case <-errTick:
  272. sendOneAnnouncement()
  273. case <-bcastTick:
  274. sendOneAnnouncement()
  275. }
  276. }
  277. if debug {
  278. l.Debugln("discover: stopping global")
  279. }
  280. }
  281. func (d *Discoverer) recvAnnouncements(b beacon.Interface) {
  282. for {
  283. buf, addr := b.Recv()
  284. if debug {
  285. l.Debugf("discover: read announcement from %s:\n%s", addr, hex.Dump(buf))
  286. }
  287. var pkt Announce
  288. err := pkt.UnmarshalXDR(buf)
  289. if err != nil && err != io.EOF {
  290. continue
  291. }
  292. var newDevice bool
  293. if bytes.Compare(pkt.This.ID, d.myID[:]) != 0 {
  294. newDevice = d.registerDevice(addr, pkt.This)
  295. }
  296. if newDevice {
  297. select {
  298. case d.forcedBcastTick <- time.Now():
  299. }
  300. }
  301. }
  302. }
  303. func (d *Discoverer) registerDevice(addr net.Addr, device Device) bool {
  304. var id protocol.DeviceID
  305. copy(id[:], device.ID)
  306. d.registryLock.RLock()
  307. current := d.filterCached(d.registry[id])
  308. d.registryLock.RUnlock()
  309. orig := current
  310. for _, a := range device.Addresses {
  311. var deviceAddr string
  312. if len(a.IP) > 0 {
  313. deviceAddr = net.JoinHostPort(net.IP(a.IP).String(), strconv.Itoa(int(a.Port)))
  314. } else if addr != nil {
  315. ua := addr.(*net.UDPAddr)
  316. ua.Port = int(a.Port)
  317. deviceAddr = ua.String()
  318. }
  319. for i := range current {
  320. if current[i].Address == deviceAddr {
  321. current[i].Seen = time.Now()
  322. goto done
  323. }
  324. }
  325. current = append(current, CacheEntry{
  326. Address: deviceAddr,
  327. Seen: time.Now(),
  328. })
  329. done:
  330. }
  331. if debug {
  332. l.Debugf("discover: register: %v -> %v", id, current)
  333. }
  334. d.registryLock.Lock()
  335. d.registry[id] = current
  336. d.registryLock.Unlock()
  337. if len(current) > len(orig) {
  338. addrs := make([]string, len(current))
  339. for i := range current {
  340. addrs[i] = current[i].Address
  341. }
  342. events.Default.Log(events.DeviceDiscovered, map[string]interface{}{
  343. "device": id.String(),
  344. "addrs": addrs,
  345. })
  346. }
  347. return len(current) > len(orig)
  348. }
  349. func (d *Discoverer) externalLookup(device protocol.DeviceID) []string {
  350. extIP, err := net.ResolveUDPAddr("udp", d.extServer)
  351. if err != nil {
  352. if debug {
  353. l.Debugf("discover: %v; no external lookup", err)
  354. }
  355. return nil
  356. }
  357. conn, err := net.DialUDP("udp", nil, extIP)
  358. if err != nil {
  359. if debug {
  360. l.Debugf("discover: %v; no external lookup", err)
  361. }
  362. return nil
  363. }
  364. defer conn.Close()
  365. err = conn.SetDeadline(time.Now().Add(5 * time.Second))
  366. if err != nil {
  367. if debug {
  368. l.Debugf("discover: %v; no external lookup", err)
  369. }
  370. return nil
  371. }
  372. buf := Query{QueryMagic, device[:]}.MustMarshalXDR()
  373. _, err = conn.Write(buf)
  374. if err != nil {
  375. if debug {
  376. l.Debugf("discover: %v; no external lookup", err)
  377. }
  378. return nil
  379. }
  380. buf = make([]byte, 2048)
  381. n, err := conn.Read(buf)
  382. if err != nil {
  383. if err, ok := err.(net.Error); ok && err.Timeout() {
  384. // Expected if the server doesn't know about requested device ID
  385. return nil
  386. }
  387. if debug {
  388. l.Debugf("discover: %v; no external lookup", err)
  389. }
  390. return nil
  391. }
  392. if debug {
  393. l.Debugf("discover: read external:\n%s", hex.Dump(buf[:n]))
  394. }
  395. var pkt Announce
  396. err = pkt.UnmarshalXDR(buf[:n])
  397. if err != nil && err != io.EOF {
  398. if debug {
  399. l.Debugln("discover:", err)
  400. }
  401. return nil
  402. }
  403. var addrs []string
  404. for _, a := range pkt.This.Addresses {
  405. deviceAddr := net.JoinHostPort(net.IP(a.IP).String(), strconv.Itoa(int(a.Port)))
  406. addrs = append(addrs, deviceAddr)
  407. }
  408. return addrs
  409. }
  410. func (d *Discoverer) filterCached(c []CacheEntry) []CacheEntry {
  411. for i := 0; i < len(c); {
  412. if ago := time.Since(c[i].Seen); ago > d.cacheLifetime {
  413. if debug {
  414. l.Debugf("removing cached address %s: seen %v ago", c[i].Address, ago)
  415. }
  416. c[i] = c[len(c)-1]
  417. c = c[:len(c)-1]
  418. } else {
  419. i++
  420. }
  421. }
  422. return c
  423. }
  424. func addrToAddr(addr *net.TCPAddr) Address {
  425. if len(addr.IP) == 0 || addr.IP.IsUnspecified() {
  426. return Address{Port: uint16(addr.Port)}
  427. } else if bs := addr.IP.To4(); bs != nil {
  428. return Address{IP: bs, Port: uint16(addr.Port)}
  429. } else if bs := addr.IP.To16(); bs != nil {
  430. return Address{IP: bs, Port: uint16(addr.Port)}
  431. }
  432. return Address{}
  433. }
  434. func resolveAddrs(addrs []string) []Address {
  435. var raddrs []Address
  436. for _, addrStr := range addrs {
  437. addrRes, err := net.ResolveTCPAddr("tcp", addrStr)
  438. if err != nil {
  439. continue
  440. }
  441. addr := addrToAddr(addrRes)
  442. if len(addr.IP) > 0 {
  443. raddrs = append(raddrs, addr)
  444. } else {
  445. raddrs = append(raddrs, Address{Port: addr.Port})
  446. }
  447. }
  448. return raddrs
  449. }