service.go 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264
  1. // Copyright (C) 2015 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 -command counterfeiter go run github.com/maxbrunsfeld/counterfeiter/v6
  7. //go:generate counterfeiter -o mocks/service.go --fake-name Service . Service
  8. package connections
  9. import (
  10. "context"
  11. "crypto/tls"
  12. "crypto/x509"
  13. "errors"
  14. "fmt"
  15. "math"
  16. "net"
  17. "net/url"
  18. "sort"
  19. "strings"
  20. stdsync "sync"
  21. "time"
  22. "github.com/syncthing/syncthing/lib/config"
  23. "github.com/syncthing/syncthing/lib/connections/registry"
  24. "github.com/syncthing/syncthing/lib/discover"
  25. "github.com/syncthing/syncthing/lib/events"
  26. "github.com/syncthing/syncthing/lib/nat"
  27. "github.com/syncthing/syncthing/lib/osutil"
  28. "github.com/syncthing/syncthing/lib/protocol"
  29. "github.com/syncthing/syncthing/lib/svcutil"
  30. "github.com/syncthing/syncthing/lib/sync"
  31. "github.com/syncthing/syncthing/lib/util"
  32. // Registers NAT service providers
  33. _ "github.com/syncthing/syncthing/lib/pmp"
  34. _ "github.com/syncthing/syncthing/lib/upnp"
  35. "github.com/thejerf/suture/v4"
  36. "golang.org/x/time/rate"
  37. )
  38. var (
  39. dialers = make(map[string]dialerFactory)
  40. listeners = make(map[string]listenerFactory)
  41. )
  42. var (
  43. // Dialers and listeners return errUnsupported (or a wrapped variant)
  44. // when they are intentionally out of service due to configuration,
  45. // build, etc. This is not logged loudly.
  46. errUnsupported = errors.New("unsupported protocol")
  47. // These are specific explanations for errUnsupported.
  48. errDisabled = fmt.Errorf("%w: disabled by configuration", errUnsupported)
  49. errDeprecated = fmt.Errorf("%w: deprecated", errUnsupported)
  50. // Various reasons to reject a connection
  51. errNetworkNotAllowed = errors.New("network not allowed")
  52. errDeviceAlreadyConnected = errors.New("already connected to this device")
  53. errDeviceIgnored = errors.New("device is ignored")
  54. errConnLimitReached = errors.New("connection limit reached")
  55. errDevicePaused = errors.New("device is paused")
  56. )
  57. const (
  58. perDeviceWarningIntv = 15 * time.Minute
  59. tlsHandshakeTimeout = 10 * time.Second
  60. minConnectionReplaceAge = 10 * time.Second
  61. minConnectionLoopSleep = 5 * time.Second
  62. stdConnectionLoopSleep = time.Minute
  63. worstDialerPriority = math.MaxInt32
  64. recentlySeenCutoff = 7 * 24 * time.Hour
  65. shortLivedConnectionThreshold = 5 * time.Second
  66. dialMaxParallel = 64
  67. dialMaxParallelPerDevice = 8
  68. )
  69. // From go/src/crypto/tls/cipher_suites.go
  70. var tlsCipherSuiteNames = map[uint16]string{
  71. // TLS 1.2
  72. 0x0005: "TLS_RSA_WITH_RC4_128_SHA",
  73. 0x000a: "TLS_RSA_WITH_3DES_EDE_CBC_SHA",
  74. 0x002f: "TLS_RSA_WITH_AES_128_CBC_SHA",
  75. 0x0035: "TLS_RSA_WITH_AES_256_CBC_SHA",
  76. 0x003c: "TLS_RSA_WITH_AES_128_CBC_SHA256",
  77. 0x009c: "TLS_RSA_WITH_AES_128_GCM_SHA256",
  78. 0x009d: "TLS_RSA_WITH_AES_256_GCM_SHA384",
  79. 0xc007: "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA",
  80. 0xc009: "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA",
  81. 0xc00a: "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA",
  82. 0xc011: "TLS_ECDHE_RSA_WITH_RC4_128_SHA",
  83. 0xc012: "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA",
  84. 0xc013: "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",
  85. 0xc014: "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA",
  86. 0xc023: "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256",
  87. 0xc027: "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256",
  88. 0xc02f: "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
  89. 0xc02b: "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
  90. 0xc030: "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
  91. 0xc02c: "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
  92. 0xcca8: "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305",
  93. 0xcca9: "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305",
  94. // TLS 1.3
  95. 0x1301: "TLS_AES_128_GCM_SHA256",
  96. 0x1302: "TLS_AES_256_GCM_SHA384",
  97. 0x1303: "TLS_CHACHA20_POLY1305_SHA256",
  98. }
  99. var tlsVersionNames = map[uint16]string{
  100. tls.VersionTLS12: "TLS1.2",
  101. tls.VersionTLS13: "TLS1.3",
  102. }
  103. // Service listens and dials all configured unconnected devices, via supported
  104. // dialers. Successful connections are handed to the model.
  105. type Service interface {
  106. suture.Service
  107. discover.AddressLister
  108. ListenerStatus() map[string]ListenerStatusEntry
  109. ConnectionStatus() map[string]ConnectionStatusEntry
  110. NATType() string
  111. }
  112. type ListenerStatusEntry struct {
  113. Error *string `json:"error"`
  114. LANAddresses []string `json:"lanAddresses"`
  115. WANAddresses []string `json:"wanAddresses"`
  116. }
  117. type ConnectionStatusEntry struct {
  118. When time.Time `json:"when"`
  119. Error *string `json:"error"`
  120. }
  121. type connWithHello struct {
  122. c internalConn
  123. hello protocol.Hello
  124. err error
  125. remoteID protocol.DeviceID
  126. remoteCert *x509.Certificate
  127. }
  128. type service struct {
  129. *suture.Supervisor
  130. connectionStatusHandler
  131. cfg config.Wrapper
  132. myID protocol.DeviceID
  133. model Model
  134. tlsCfg *tls.Config
  135. discoverer discover.Finder
  136. conns chan internalConn
  137. hellos chan *connWithHello
  138. bepProtocolName string
  139. tlsDefaultCommonName string
  140. limiter *limiter
  141. natService *nat.Service
  142. evLogger events.Logger
  143. registry *registry.Registry
  144. dialNow chan struct{}
  145. dialNowDevices map[protocol.DeviceID]struct{}
  146. dialNowDevicesMut sync.Mutex
  147. listenersMut sync.RWMutex
  148. listeners map[string]genericListener
  149. listenerTokens map[string]suture.ServiceToken
  150. }
  151. func NewService(cfg config.Wrapper, myID protocol.DeviceID, mdl Model, tlsCfg *tls.Config, discoverer discover.Finder, bepProtocolName string, tlsDefaultCommonName string, evLogger events.Logger, registry *registry.Registry) Service {
  152. spec := svcutil.SpecWithInfoLogger(l)
  153. service := &service{
  154. Supervisor: suture.New("connections.Service", spec),
  155. connectionStatusHandler: newConnectionStatusHandler(),
  156. cfg: cfg,
  157. myID: myID,
  158. model: mdl,
  159. tlsCfg: tlsCfg,
  160. discoverer: discoverer,
  161. conns: make(chan internalConn),
  162. hellos: make(chan *connWithHello),
  163. bepProtocolName: bepProtocolName,
  164. tlsDefaultCommonName: tlsDefaultCommonName,
  165. limiter: newLimiter(myID, cfg),
  166. natService: nat.NewService(myID, cfg),
  167. evLogger: evLogger,
  168. registry: registry,
  169. dialNowDevicesMut: sync.NewMutex(),
  170. dialNow: make(chan struct{}, 1),
  171. dialNowDevices: make(map[protocol.DeviceID]struct{}),
  172. listenersMut: sync.NewRWMutex(),
  173. listeners: make(map[string]genericListener),
  174. listenerTokens: make(map[string]suture.ServiceToken),
  175. }
  176. cfg.Subscribe(service)
  177. raw := cfg.RawCopy()
  178. // Actually starts the listeners and NAT service
  179. // Need to start this before service.connect so that any dials that
  180. // try punch through already have a listener to cling on.
  181. service.CommitConfiguration(raw, raw)
  182. // There are several moving parts here; one routine per listening address
  183. // (handled in configuration changing) to handle incoming connections,
  184. // one routine to periodically attempt outgoing connections, one routine to
  185. // the common handling regardless of whether the connection was
  186. // incoming or outgoing.
  187. service.Add(svcutil.AsService(service.connect, fmt.Sprintf("%s/connect", service)))
  188. service.Add(svcutil.AsService(service.handleConns, fmt.Sprintf("%s/handleConns", service)))
  189. service.Add(svcutil.AsService(service.handleHellos, fmt.Sprintf("%s/handleHellos", service)))
  190. service.Add(service.natService)
  191. svcutil.OnSupervisorDone(service.Supervisor, func() {
  192. service.cfg.Unsubscribe(service.limiter)
  193. service.cfg.Unsubscribe(service)
  194. })
  195. return service
  196. }
  197. func (s *service) handleConns(ctx context.Context) error {
  198. for {
  199. var c internalConn
  200. select {
  201. case <-ctx.Done():
  202. return ctx.Err()
  203. case c = <-s.conns:
  204. }
  205. cs := c.ConnectionState()
  206. // We should have negotiated the next level protocol "bep/1.0" as part
  207. // of the TLS handshake. Unfortunately this can't be a hard error,
  208. // because there are implementations out there that don't support
  209. // protocol negotiation (iOS for one...).
  210. if cs.NegotiatedProtocol != s.bepProtocolName {
  211. l.Infof("Peer at %s did not negotiate bep/1.0", c)
  212. }
  213. // We should have received exactly one certificate from the other
  214. // side. If we didn't, they don't have a device ID and we drop the
  215. // connection.
  216. certs := cs.PeerCertificates
  217. if cl := len(certs); cl != 1 {
  218. l.Infof("Got peer certificate list of length %d != 1 from peer at %s; protocol error", cl, c)
  219. c.Close()
  220. continue
  221. }
  222. remoteCert := certs[0]
  223. remoteID := protocol.NewDeviceID(remoteCert.Raw)
  224. // The device ID should not be that of ourselves. It can happen
  225. // though, especially in the presence of NAT hairpinning, multiple
  226. // clients between the same NAT gateway, and global discovery.
  227. if remoteID == s.myID {
  228. l.Debugf("Connected to myself (%s) at %s", remoteID, c)
  229. c.Close()
  230. continue
  231. }
  232. if err := s.connectionCheckEarly(remoteID, c); err != nil {
  233. l.Infof("Connection from %s at %s (%s) rejected: %v", remoteID, c.RemoteAddr(), c.Type(), err)
  234. c.Close()
  235. continue
  236. }
  237. _ = c.SetDeadline(time.Now().Add(20 * time.Second))
  238. go func() {
  239. hello, err := protocol.ExchangeHello(c, s.model.GetHello(remoteID))
  240. select {
  241. case s.hellos <- &connWithHello{c, hello, err, remoteID, remoteCert}:
  242. case <-ctx.Done():
  243. }
  244. }()
  245. }
  246. }
  247. func (s *service) connectionCheckEarly(remoteID protocol.DeviceID, c internalConn) error {
  248. if s.cfg.IgnoredDevice(remoteID) {
  249. return errDeviceIgnored
  250. }
  251. if max := s.cfg.Options().ConnectionLimitMax; max > 0 && s.model.NumConnections() >= max {
  252. // We're not allowed to accept any more connections.
  253. return errConnLimitReached
  254. }
  255. cfg, ok := s.cfg.Device(remoteID)
  256. if !ok {
  257. // We do go ahead exchanging hello messages to get information about the device.
  258. return nil
  259. }
  260. if cfg.Paused {
  261. return errDevicePaused
  262. }
  263. if len(cfg.AllowedNetworks) > 0 && !IsAllowedNetwork(c.RemoteAddr().String(), cfg.AllowedNetworks) {
  264. // The connection is not from an allowed network.
  265. return errNetworkNotAllowed
  266. }
  267. // Lower priority is better, just like nice etc.
  268. if ct, ok := s.model.Connection(remoteID); ok {
  269. if ct.Priority() > c.priority || time.Since(ct.Statistics().StartedAt) > minConnectionReplaceAge {
  270. l.Debugf("Switching connections %s (existing: %s new: %s)", remoteID, ct, c)
  271. } else {
  272. // We should not already be connected to the other party. TODO: This
  273. // could use some better handling. If the old connection is dead but
  274. // hasn't timed out yet we may want to drop *that* connection and keep
  275. // this one. But in case we are two devices connecting to each other
  276. // in parallel we don't want to do that or we end up with no
  277. // connections still established...
  278. return errDeviceAlreadyConnected
  279. }
  280. }
  281. return nil
  282. }
  283. func (s *service) handleHellos(ctx context.Context) error {
  284. var c internalConn
  285. var hello protocol.Hello
  286. var err error
  287. var remoteID protocol.DeviceID
  288. var remoteCert *x509.Certificate
  289. for {
  290. select {
  291. case <-ctx.Done():
  292. return ctx.Err()
  293. case withHello := <-s.hellos:
  294. c = withHello.c
  295. hello = withHello.hello
  296. err = withHello.err
  297. remoteID = withHello.remoteID
  298. remoteCert = withHello.remoteCert
  299. }
  300. if err != nil {
  301. if protocol.IsVersionMismatch(err) {
  302. // The error will be a relatively user friendly description
  303. // of what's wrong with the version compatibility. By
  304. // default identify the other side by device ID and IP.
  305. remote := fmt.Sprintf("%v (%v)", remoteID, c.RemoteAddr())
  306. if hello.DeviceName != "" {
  307. // If the name was set in the hello return, use that to
  308. // give the user more info about which device is the
  309. // affected one. It probably says more than the remote
  310. // IP.
  311. remote = fmt.Sprintf("%q (%s %s, %v)", hello.DeviceName, hello.ClientName, hello.ClientVersion, remoteID)
  312. }
  313. msg := fmt.Sprintf("Connecting to %s: %s", remote, err)
  314. warningFor(remoteID, msg)
  315. } else {
  316. // It's something else - connection reset or whatever
  317. l.Infof("Failed to exchange Hello messages with %s at %s: %s", remoteID, c, err)
  318. }
  319. c.Close()
  320. continue
  321. }
  322. _ = c.SetDeadline(time.Time{})
  323. // The Model will return an error for devices that we don't want to
  324. // have a connection with for whatever reason, for example unknown devices.
  325. if err := s.model.OnHello(remoteID, c.RemoteAddr(), hello); err != nil {
  326. l.Infof("Connection from %s at %s (%s) rejected: %v", remoteID, c.RemoteAddr(), c.Type(), err)
  327. c.Close()
  328. continue
  329. }
  330. deviceCfg, ok := s.cfg.Device(remoteID)
  331. if !ok {
  332. l.Infof("Device %s removed from config during connection attempt at %s", remoteID, c)
  333. c.Close()
  334. continue
  335. }
  336. // Verify the name on the certificate. By default we set it to
  337. // "syncthing" when generating, but the user may have replaced
  338. // the certificate and used another name.
  339. certName := deviceCfg.CertName
  340. if certName == "" {
  341. certName = s.tlsDefaultCommonName
  342. }
  343. if remoteCert.Subject.CommonName == certName {
  344. // All good. We do this check because our old style certificates
  345. // have "syncthing" in the CommonName field and no SANs, which
  346. // is not accepted by VerifyHostname() any more as of Go 1.15.
  347. } else if err := remoteCert.VerifyHostname(certName); err != nil {
  348. // Incorrect certificate name is something the user most
  349. // likely wants to know about, since it's an advanced
  350. // config. Warn instead of Info.
  351. l.Warnf("Bad certificate from %s at %s: %v", remoteID, c, err)
  352. c.Close()
  353. continue
  354. }
  355. // Determine only once whether a connection is considered local
  356. // according to our configuration, then cache the decision.
  357. c.isLocal = s.isLAN(c.RemoteAddr())
  358. // Wrap the connection in rate limiters. The limiter itself will
  359. // keep up with config changes to the rate and whether or not LAN
  360. // connections are limited.
  361. rd, wr := s.limiter.getLimiters(remoteID, c, c.IsLocal())
  362. protoConn := protocol.NewConnection(remoteID, rd, wr, c, s.model, c, deviceCfg.Compression, s.cfg.FolderPasswords(remoteID))
  363. go func() {
  364. <-protoConn.Closed()
  365. s.dialNowDevicesMut.Lock()
  366. s.dialNowDevices[remoteID] = struct{}{}
  367. s.scheduleDialNow()
  368. s.dialNowDevicesMut.Unlock()
  369. }()
  370. l.Infof("Established secure connection to %s at %s", remoteID, c)
  371. s.model.AddConnection(protoConn, hello)
  372. continue
  373. }
  374. }
  375. func (s *service) connect(ctx context.Context) error {
  376. // Map of when to earliest dial each given device + address again
  377. nextDialAt := make(nextDialRegistry)
  378. // Used as delay for the first few connection attempts (adjusted up to
  379. // minConnectionLoopSleep), increased exponentially until it reaches
  380. // stdConnectionLoopSleep, at which time the normal sleep mechanism
  381. // kicks in.
  382. initialRampup := time.Second
  383. for {
  384. cfg := s.cfg.RawCopy()
  385. bestDialerPriority := s.bestDialerPriority(cfg)
  386. isInitialRampup := initialRampup < stdConnectionLoopSleep
  387. l.Debugln("Connection loop")
  388. if isInitialRampup {
  389. l.Debugln("Connection loop in initial rampup")
  390. }
  391. // Used for consistency throughout this loop run, as time passes
  392. // while we try connections etc.
  393. now := time.Now()
  394. // Attempt to dial all devices that are unconnected or can be connection-upgraded
  395. s.dialDevices(ctx, now, cfg, bestDialerPriority, nextDialAt, isInitialRampup)
  396. var sleep time.Duration
  397. if isInitialRampup {
  398. // We are in the initial rampup time, so we slowly, statically
  399. // increase the sleep time.
  400. sleep = initialRampup
  401. initialRampup *= 2
  402. } else {
  403. // The sleep time is until the next dial scheduled in nextDialAt,
  404. // clamped by stdConnectionLoopSleep as we don't want to sleep too
  405. // long (config changes might happen).
  406. sleep = nextDialAt.sleepDurationAndCleanup(now)
  407. }
  408. // ... while making sure not to loop too quickly either.
  409. if sleep < minConnectionLoopSleep {
  410. sleep = minConnectionLoopSleep
  411. }
  412. l.Debugln("Next connection loop in", sleep)
  413. timeout := time.NewTimer(sleep)
  414. select {
  415. case <-s.dialNow:
  416. // Remove affected devices from nextDialAt to dial immediately,
  417. // regardless of when we last dialed it (there's cool down in the
  418. // registry for too many repeat dials).
  419. s.dialNowDevicesMut.Lock()
  420. for device := range s.dialNowDevices {
  421. nextDialAt.redialDevice(device, now)
  422. }
  423. s.dialNowDevices = make(map[protocol.DeviceID]struct{})
  424. s.dialNowDevicesMut.Unlock()
  425. timeout.Stop()
  426. case <-timeout.C:
  427. case <-ctx.Done():
  428. return ctx.Err()
  429. }
  430. }
  431. }
  432. func (*service) bestDialerPriority(cfg config.Configuration) int {
  433. bestDialerPriority := worstDialerPriority
  434. for _, df := range dialers {
  435. if df.Valid(cfg) != nil {
  436. continue
  437. }
  438. if prio := df.Priority(); prio < bestDialerPriority {
  439. bestDialerPriority = prio
  440. }
  441. }
  442. return bestDialerPriority
  443. }
  444. func (s *service) dialDevices(ctx context.Context, now time.Time, cfg config.Configuration, bestDialerPriority int, nextDialAt nextDialRegistry, initial bool) {
  445. // Figure out current connection limits up front to see if there's any
  446. // point in resolving devices and such at all.
  447. allowAdditional := 0 // no limit
  448. connectionLimit := cfg.Options.LowestConnectionLimit()
  449. if connectionLimit > 0 {
  450. current := s.model.NumConnections()
  451. allowAdditional = connectionLimit - current
  452. if allowAdditional <= 0 {
  453. l.Debugf("Skipping dial because we've reached the connection limit, current %d >= limit %d", current, connectionLimit)
  454. return
  455. }
  456. }
  457. // Get device statistics for the last seen time of each device. This
  458. // isn't critical, so ignore the potential error.
  459. stats, _ := s.model.DeviceStatistics()
  460. queue := make(dialQueue, 0, len(cfg.Devices))
  461. for _, deviceCfg := range cfg.Devices {
  462. // Don't attempt to connect to ourselves...
  463. if deviceCfg.DeviceID == s.myID {
  464. continue
  465. }
  466. // Don't attempt to connect to paused devices...
  467. if deviceCfg.Paused {
  468. continue
  469. }
  470. // See if we are already connected and, if so, what our cutoff is
  471. // for dialer priority.
  472. priorityCutoff := worstDialerPriority
  473. connection, connected := s.model.Connection(deviceCfg.DeviceID)
  474. if connected {
  475. priorityCutoff = connection.Priority()
  476. if bestDialerPriority >= priorityCutoff {
  477. // Our best dialer is not any better than what we already
  478. // have, so nothing to do here.
  479. continue
  480. }
  481. }
  482. dialTargets := s.resolveDialTargets(ctx, now, cfg, deviceCfg, nextDialAt, initial, priorityCutoff)
  483. if len(dialTargets) > 0 {
  484. queue = append(queue, dialQueueEntry{
  485. id: deviceCfg.DeviceID,
  486. lastSeen: stats[deviceCfg.DeviceID].LastSeen,
  487. shortLived: stats[deviceCfg.DeviceID].LastConnectionDurationS < shortLivedConnectionThreshold.Seconds(),
  488. targets: dialTargets,
  489. })
  490. }
  491. }
  492. // Sort the queue in an order we think will be useful (most recent
  493. // first, deprioriting unstable devices, randomizing those we haven't
  494. // seen in a long while). If we don't do connection limiting the sorting
  495. // doesn't have much effect, but it may result in getting up and running
  496. // quicker if only a subset of configured devices are actually reachable
  497. // (by prioritizing those that were reachable recently).
  498. queue.Sort()
  499. // Perform dials according to the queue, stopping when we've reached the
  500. // allowed additional number of connections (if limited).
  501. numConns := 0
  502. var numConnsMut stdsync.Mutex
  503. dialSemaphore := util.NewSemaphore(dialMaxParallel)
  504. dialWG := new(stdsync.WaitGroup)
  505. dialCtx, dialCancel := context.WithCancel(ctx)
  506. defer func() {
  507. dialWG.Wait()
  508. dialCancel()
  509. }()
  510. for i := range queue {
  511. select {
  512. case <-dialCtx.Done():
  513. return
  514. default:
  515. }
  516. dialWG.Add(1)
  517. go func(entry dialQueueEntry) {
  518. defer dialWG.Done()
  519. conn, ok := s.dialParallel(dialCtx, entry.id, entry.targets, dialSemaphore)
  520. if !ok {
  521. return
  522. }
  523. numConnsMut.Lock()
  524. if allowAdditional == 0 || numConns < allowAdditional {
  525. select {
  526. case s.conns <- conn:
  527. numConns++
  528. if allowAdditional > 0 && numConns >= allowAdditional {
  529. dialCancel()
  530. }
  531. case <-dialCtx.Done():
  532. }
  533. }
  534. numConnsMut.Unlock()
  535. }(queue[i])
  536. }
  537. }
  538. func (s *service) resolveDialTargets(ctx context.Context, now time.Time, cfg config.Configuration, deviceCfg config.DeviceConfiguration, nextDialAt nextDialRegistry, initial bool, priorityCutoff int) []dialTarget {
  539. deviceID := deviceCfg.DeviceID
  540. addrs := s.resolveDeviceAddrs(ctx, deviceCfg)
  541. l.Debugln("Resolved device", deviceID, "addresses:", addrs)
  542. dialTargets := make([]dialTarget, 0, len(addrs))
  543. for _, addr := range addrs {
  544. // Use both device and address, as you might have two devices connected
  545. // to the same relay
  546. if !initial && nextDialAt.get(deviceID, addr).After(now) {
  547. l.Debugf("Not dialing %s via %v as it's not time yet", deviceID, addr)
  548. continue
  549. }
  550. // If we fail at any step before actually getting the dialer
  551. // retry in a minute
  552. nextDialAt.set(deviceID, addr, now.Add(time.Minute))
  553. uri, err := url.Parse(addr)
  554. if err != nil {
  555. s.setConnectionStatus(addr, err)
  556. l.Infof("Parsing dialer address %s: %v", addr, err)
  557. continue
  558. }
  559. if len(deviceCfg.AllowedNetworks) > 0 {
  560. if !IsAllowedNetwork(uri.Host, deviceCfg.AllowedNetworks) {
  561. s.setConnectionStatus(addr, errors.New("network disallowed"))
  562. l.Debugln("Network for", uri, "is disallowed")
  563. continue
  564. }
  565. }
  566. dialerFactory, err := getDialerFactory(cfg, uri)
  567. if err != nil {
  568. s.setConnectionStatus(addr, err)
  569. }
  570. if errors.Is(err, errUnsupported) {
  571. l.Debugf("Dialer for %v: %v", uri, err)
  572. continue
  573. } else if err != nil {
  574. l.Infof("Dialer for %v: %v", uri, err)
  575. continue
  576. }
  577. priority := dialerFactory.Priority()
  578. if priority >= priorityCutoff {
  579. l.Debugf("Not dialing using %s as priority is not better than current connection (%d >= %d)", dialerFactory, dialerFactory.Priority(), priorityCutoff)
  580. continue
  581. }
  582. dialer := dialerFactory.New(s.cfg.Options(), s.tlsCfg, s.registry)
  583. nextDialAt.set(deviceID, addr, now.Add(dialer.RedialFrequency()))
  584. // For LAN addresses, increase the priority so that we
  585. // try these first.
  586. switch {
  587. case dialerFactory.AlwaysWAN():
  588. // Do nothing.
  589. case s.isLANHost(uri.Host):
  590. priority--
  591. }
  592. dialTargets = append(dialTargets, dialTarget{
  593. addr: addr,
  594. dialer: dialer,
  595. priority: priority,
  596. deviceID: deviceID,
  597. uri: uri,
  598. })
  599. }
  600. return dialTargets
  601. }
  602. func (s *service) resolveDeviceAddrs(ctx context.Context, cfg config.DeviceConfiguration) []string {
  603. var addrs []string
  604. for _, addr := range cfg.Addresses {
  605. if addr == "dynamic" {
  606. if s.discoverer != nil {
  607. if t, err := s.discoverer.Lookup(ctx, cfg.DeviceID); err == nil {
  608. addrs = append(addrs, t...)
  609. }
  610. }
  611. } else {
  612. addrs = append(addrs, addr)
  613. }
  614. }
  615. return util.UniqueTrimmedStrings(addrs)
  616. }
  617. func (s *service) isLANHost(host string) bool {
  618. // Probably we are called with an ip:port combo which we can resolve as
  619. // a TCP address.
  620. if addr, err := net.ResolveTCPAddr("tcp", host); err == nil {
  621. return s.isLAN(addr)
  622. }
  623. // ... but this function looks general enough that someone might try
  624. // with just an IP as well in the future so lets allow that.
  625. if addr, err := net.ResolveIPAddr("ip", host); err == nil {
  626. return s.isLAN(addr)
  627. }
  628. return false
  629. }
  630. func (s *service) isLAN(addr net.Addr) bool {
  631. var ip net.IP
  632. switch addr := addr.(type) {
  633. case *net.IPAddr:
  634. ip = addr.IP
  635. case *net.TCPAddr:
  636. ip = addr.IP
  637. case *net.UDPAddr:
  638. ip = addr.IP
  639. default:
  640. // From the standard library, just Unix sockets.
  641. // If you invent your own, handle it.
  642. return false
  643. }
  644. if ip.IsLoopback() {
  645. return true
  646. }
  647. for _, lan := range s.cfg.Options().AlwaysLocalNets {
  648. _, ipnet, err := net.ParseCIDR(lan)
  649. if err != nil {
  650. l.Debugln("Network", lan, "is malformed:", err)
  651. continue
  652. }
  653. if ipnet.Contains(ip) {
  654. return true
  655. }
  656. }
  657. lans, _ := osutil.GetLans()
  658. for _, lan := range lans {
  659. if lan.Contains(ip) {
  660. return true
  661. }
  662. }
  663. return false
  664. }
  665. func (s *service) createListener(factory listenerFactory, uri *url.URL) bool {
  666. // must be called with listenerMut held
  667. l.Debugln("Starting listener", uri)
  668. listener := factory.New(uri, s.cfg, s.tlsCfg, s.conns, s.natService, s.registry)
  669. listener.OnAddressesChanged(s.logListenAddressesChangedEvent)
  670. // Retrying a listener many times in rapid succession is unlikely to help,
  671. // thus back off quickly. A listener may soon be functional again, e.g. due
  672. // to a network interface coming back online - retry every minute.
  673. spec := svcutil.SpecWithInfoLogger(l)
  674. spec.FailureThreshold = 2
  675. spec.FailureBackoff = time.Minute
  676. sup := suture.New(fmt.Sprintf("listenerSupervisor@%v", listener), spec)
  677. sup.Add(listener)
  678. s.listeners[uri.String()] = listener
  679. s.listenerTokens[uri.String()] = s.Add(sup)
  680. return true
  681. }
  682. func (s *service) logListenAddressesChangedEvent(l ListenerAddresses) {
  683. s.evLogger.Log(events.ListenAddressesChanged, map[string]interface{}{
  684. "address": l.URI,
  685. "lan": l.LANAddresses,
  686. "wan": l.WANAddresses,
  687. })
  688. }
  689. func (s *service) CommitConfiguration(from, to config.Configuration) bool {
  690. newDevices := make(map[protocol.DeviceID]bool, len(to.Devices))
  691. for _, dev := range to.Devices {
  692. newDevices[dev.DeviceID] = true
  693. }
  694. for _, dev := range from.Devices {
  695. if !newDevices[dev.DeviceID] {
  696. warningLimitersMut.Lock()
  697. delete(warningLimiters, dev.DeviceID)
  698. warningLimitersMut.Unlock()
  699. }
  700. }
  701. s.checkAndSignalConnectLoopOnUpdatedDevices(from, to)
  702. s.listenersMut.Lock()
  703. seen := make(map[string]struct{})
  704. for _, addr := range to.Options.ListenAddresses() {
  705. if addr == "" {
  706. // We can get an empty address if there is an empty listener
  707. // element in the config, indicating no listeners should be
  708. // used. This is not an error.
  709. continue
  710. }
  711. uri, err := url.Parse(addr)
  712. if err != nil {
  713. l.Warnf("Skipping malformed listener URL %q: %v", addr, err)
  714. continue
  715. }
  716. // Make sure we always have the canonical representation of the URL.
  717. // This is for consistency as we use it as a map key, but also to
  718. // avoid misunderstandings. We do not just use the canonicalized
  719. // version, because an URL that looks very similar to a human might
  720. // mean something entirely different to the computer (e.g.,
  721. // tcp:/127.0.0.1:22000 in fact being equivalent to tcp://:22000).
  722. if canonical := uri.String(); canonical != addr {
  723. l.Warnf("Skipping malformed listener URL %q (not canonical)", addr)
  724. continue
  725. }
  726. if _, ok := s.listeners[addr]; ok {
  727. seen[addr] = struct{}{}
  728. continue
  729. }
  730. factory, err := getListenerFactory(to, uri)
  731. if errors.Is(err, errUnsupported) {
  732. l.Debugf("Listener for %v: %v", uri, err)
  733. continue
  734. } else if err != nil {
  735. l.Infof("Listener for %v: %v", uri, err)
  736. continue
  737. }
  738. s.createListener(factory, uri)
  739. seen[addr] = struct{}{}
  740. }
  741. for addr, listener := range s.listeners {
  742. if _, ok := seen[addr]; !ok || listener.Factory().Valid(to) != nil {
  743. l.Debugln("Stopping listener", addr)
  744. s.Remove(s.listenerTokens[addr])
  745. delete(s.listenerTokens, addr)
  746. delete(s.listeners, addr)
  747. }
  748. }
  749. s.listenersMut.Unlock()
  750. return true
  751. }
  752. func (s *service) checkAndSignalConnectLoopOnUpdatedDevices(from, to config.Configuration) {
  753. oldDevices := from.DeviceMap()
  754. dial := false
  755. s.dialNowDevicesMut.Lock()
  756. for _, dev := range to.Devices {
  757. if dev.Paused {
  758. continue
  759. }
  760. if oldDev, ok := oldDevices[dev.DeviceID]; !ok || oldDev.Paused {
  761. s.dialNowDevices[dev.DeviceID] = struct{}{}
  762. dial = true
  763. } else if !util.EqualStrings(oldDev.Addresses, dev.Addresses) {
  764. dial = true
  765. }
  766. }
  767. if dial {
  768. s.scheduleDialNow()
  769. }
  770. s.dialNowDevicesMut.Unlock()
  771. }
  772. func (s *service) scheduleDialNow() {
  773. select {
  774. case s.dialNow <- struct{}{}:
  775. default:
  776. // channel is blocked - a config update is already pending for the connection loop.
  777. }
  778. }
  779. func (s *service) AllAddresses() []string {
  780. s.listenersMut.RLock()
  781. var addrs []string
  782. for _, listener := range s.listeners {
  783. for _, lanAddr := range listener.LANAddresses() {
  784. addrs = append(addrs, lanAddr.String())
  785. }
  786. for _, wanAddr := range listener.WANAddresses() {
  787. addrs = append(addrs, wanAddr.String())
  788. }
  789. }
  790. s.listenersMut.RUnlock()
  791. return util.UniqueTrimmedStrings(addrs)
  792. }
  793. func (s *service) ExternalAddresses() []string {
  794. if s.cfg.Options().AnnounceLANAddresses {
  795. return s.AllAddresses()
  796. }
  797. s.listenersMut.RLock()
  798. var addrs []string
  799. for _, listener := range s.listeners {
  800. for _, wanAddr := range listener.WANAddresses() {
  801. addrs = append(addrs, wanAddr.String())
  802. }
  803. }
  804. s.listenersMut.RUnlock()
  805. return util.UniqueTrimmedStrings(addrs)
  806. }
  807. func (s *service) ListenerStatus() map[string]ListenerStatusEntry {
  808. result := make(map[string]ListenerStatusEntry)
  809. s.listenersMut.RLock()
  810. for addr, listener := range s.listeners {
  811. var status ListenerStatusEntry
  812. if err := listener.Error(); err != nil {
  813. errStr := err.Error()
  814. status.Error = &errStr
  815. }
  816. status.LANAddresses = urlsToStrings(listener.LANAddresses())
  817. status.WANAddresses = urlsToStrings(listener.WANAddresses())
  818. result[addr] = status
  819. }
  820. s.listenersMut.RUnlock()
  821. return result
  822. }
  823. type connectionStatusHandler struct {
  824. connectionStatusMut sync.RWMutex
  825. connectionStatus map[string]ConnectionStatusEntry // address -> latest error/status
  826. }
  827. func newConnectionStatusHandler() connectionStatusHandler {
  828. return connectionStatusHandler{
  829. connectionStatusMut: sync.NewRWMutex(),
  830. connectionStatus: make(map[string]ConnectionStatusEntry),
  831. }
  832. }
  833. func (s *connectionStatusHandler) ConnectionStatus() map[string]ConnectionStatusEntry {
  834. result := make(map[string]ConnectionStatusEntry)
  835. s.connectionStatusMut.RLock()
  836. for k, v := range s.connectionStatus {
  837. result[k] = v
  838. }
  839. s.connectionStatusMut.RUnlock()
  840. return result
  841. }
  842. func (s *connectionStatusHandler) setConnectionStatus(address string, err error) {
  843. if errors.Is(err, context.Canceled) {
  844. return
  845. }
  846. status := ConnectionStatusEntry{When: time.Now().UTC().Truncate(time.Second)}
  847. if err != nil {
  848. errStr := err.Error()
  849. status.Error = &errStr
  850. }
  851. s.connectionStatusMut.Lock()
  852. s.connectionStatus[address] = status
  853. s.connectionStatusMut.Unlock()
  854. }
  855. func (s *service) NATType() string {
  856. s.listenersMut.RLock()
  857. defer s.listenersMut.RUnlock()
  858. for _, listener := range s.listeners {
  859. natType := listener.NATType()
  860. if natType != "unknown" {
  861. return natType
  862. }
  863. }
  864. return "unknown"
  865. }
  866. func getDialerFactory(cfg config.Configuration, uri *url.URL) (dialerFactory, error) {
  867. dialerFactory, ok := dialers[uri.Scheme]
  868. if !ok {
  869. return nil, fmt.Errorf("unknown address scheme %q", uri.Scheme)
  870. }
  871. if err := dialerFactory.Valid(cfg); err != nil {
  872. return nil, err
  873. }
  874. return dialerFactory, nil
  875. }
  876. func getListenerFactory(cfg config.Configuration, uri *url.URL) (listenerFactory, error) {
  877. listenerFactory, ok := listeners[uri.Scheme]
  878. if !ok {
  879. return nil, fmt.Errorf("unknown address scheme %q", uri.Scheme)
  880. }
  881. if err := listenerFactory.Valid(cfg); err != nil {
  882. return nil, err
  883. }
  884. return listenerFactory, nil
  885. }
  886. func urlsToStrings(urls []*url.URL) []string {
  887. strings := make([]string, len(urls))
  888. for i, url := range urls {
  889. strings[i] = url.String()
  890. }
  891. return strings
  892. }
  893. var warningLimiters = make(map[protocol.DeviceID]*rate.Limiter)
  894. var warningLimitersMut = sync.NewMutex()
  895. func warningFor(dev protocol.DeviceID, msg string) {
  896. warningLimitersMut.Lock()
  897. defer warningLimitersMut.Unlock()
  898. lim, ok := warningLimiters[dev]
  899. if !ok {
  900. lim = rate.NewLimiter(rate.Every(perDeviceWarningIntv), 1)
  901. warningLimiters[dev] = lim
  902. }
  903. if lim.Allow() {
  904. l.Warnln(msg)
  905. }
  906. }
  907. func tlsTimedHandshake(tc *tls.Conn) error {
  908. tc.SetDeadline(time.Now().Add(tlsHandshakeTimeout))
  909. defer tc.SetDeadline(time.Time{})
  910. return tc.Handshake()
  911. }
  912. // IsAllowedNetwork returns true if the given host (IP or resolvable
  913. // hostname) is in the set of allowed networks (CIDR format only).
  914. func IsAllowedNetwork(host string, allowed []string) bool {
  915. if hostNoPort, _, err := net.SplitHostPort(host); err == nil {
  916. host = hostNoPort
  917. }
  918. addr, err := net.ResolveIPAddr("ip", host)
  919. if err != nil {
  920. return false
  921. }
  922. for _, n := range allowed {
  923. result := true
  924. if strings.HasPrefix(n, "!") {
  925. result = false
  926. n = n[1:]
  927. }
  928. _, cidr, err := net.ParseCIDR(n)
  929. if err != nil {
  930. continue
  931. }
  932. if cidr.Contains(addr.IP) {
  933. return result
  934. }
  935. }
  936. return false
  937. }
  938. func (s *service) dialParallel(ctx context.Context, deviceID protocol.DeviceID, dialTargets []dialTarget, parentSema *util.Semaphore) (internalConn, bool) {
  939. // Group targets into buckets by priority
  940. dialTargetBuckets := make(map[int][]dialTarget, len(dialTargets))
  941. for _, tgt := range dialTargets {
  942. dialTargetBuckets[tgt.priority] = append(dialTargetBuckets[tgt.priority], tgt)
  943. }
  944. // Get all available priorities
  945. priorities := make([]int, 0, len(dialTargetBuckets))
  946. for prio := range dialTargetBuckets {
  947. priorities = append(priorities, prio)
  948. }
  949. // Sort the priorities so that we dial lowest first (which means highest...)
  950. sort.Ints(priorities)
  951. sema := util.MultiSemaphore{util.NewSemaphore(dialMaxParallelPerDevice), parentSema}
  952. for _, prio := range priorities {
  953. tgts := dialTargetBuckets[prio]
  954. res := make(chan internalConn, len(tgts))
  955. wg := stdsync.WaitGroup{}
  956. for _, tgt := range tgts {
  957. sema.Take(1)
  958. wg.Add(1)
  959. go func(tgt dialTarget) {
  960. defer func() {
  961. wg.Done()
  962. sema.Give(1)
  963. }()
  964. conn, err := tgt.Dial(ctx)
  965. if err == nil {
  966. // Closes the connection on error
  967. err = s.validateIdentity(conn, deviceID)
  968. }
  969. s.setConnectionStatus(tgt.addr, err)
  970. if err != nil {
  971. l.Debugln("dialing", deviceID, tgt.uri, "error:", err)
  972. } else {
  973. l.Debugln("dialing", deviceID, tgt.uri, "success:", conn)
  974. res <- conn
  975. }
  976. }(tgt)
  977. }
  978. // Spawn a routine which will unblock main routine in case we fail
  979. // to connect to anyone.
  980. go func() {
  981. wg.Wait()
  982. close(res)
  983. }()
  984. // Wait for the first connection, or for channel closure.
  985. if conn, ok := <-res; ok {
  986. // Got a connection, means more might come back, hence spawn a
  987. // routine that will do the discarding.
  988. l.Debugln("connected to", deviceID, prio, "using", conn, conn.priority)
  989. go func(deviceID protocol.DeviceID, prio int) {
  990. wg.Wait()
  991. l.Debugln("discarding", len(res), "connections while connecting to", deviceID, prio)
  992. for conn := range res {
  993. conn.Close()
  994. }
  995. }(deviceID, prio)
  996. return conn, ok
  997. }
  998. // Failed to connect, report that fact.
  999. l.Debugln("failed to connect to", deviceID, prio)
  1000. }
  1001. return internalConn{}, false
  1002. }
  1003. func (s *service) validateIdentity(c internalConn, expectedID protocol.DeviceID) error {
  1004. cs := c.ConnectionState()
  1005. // We should have received exactly one certificate from the other
  1006. // side. If we didn't, they don't have a device ID and we drop the
  1007. // connection.
  1008. certs := cs.PeerCertificates
  1009. if cl := len(certs); cl != 1 {
  1010. l.Infof("Got peer certificate list of length %d != 1 from peer at %s; protocol error", cl, c)
  1011. c.Close()
  1012. return fmt.Errorf("expected 1 certificate, got %d", cl)
  1013. }
  1014. remoteCert := certs[0]
  1015. remoteID := protocol.NewDeviceID(remoteCert.Raw)
  1016. // The device ID should not be that of ourselves. It can happen
  1017. // though, especially in the presence of NAT hairpinning, multiple
  1018. // clients between the same NAT gateway, and global discovery.
  1019. if remoteID == s.myID {
  1020. l.Debugf("Connected to myself (%s) at %s", remoteID, c)
  1021. c.Close()
  1022. return errors.New("connected to self")
  1023. }
  1024. // We should see the expected device ID
  1025. if !remoteID.Equals(expectedID) {
  1026. c.Close()
  1027. return fmt.Errorf("unexpected device id, expected %s got %s", expectedID, remoteID)
  1028. }
  1029. return nil
  1030. }
  1031. type nextDialRegistry map[protocol.DeviceID]nextDialDevice
  1032. type nextDialDevice struct {
  1033. nextDial map[string]time.Time
  1034. coolDownIntervalStart time.Time
  1035. attempts int
  1036. }
  1037. func (r nextDialRegistry) get(device protocol.DeviceID, addr string) time.Time {
  1038. return r[device].nextDial[addr]
  1039. }
  1040. const (
  1041. dialCoolDownInterval = 2 * time.Minute
  1042. dialCoolDownDelay = 5 * time.Minute
  1043. dialCoolDownMaxAttemps = 3
  1044. )
  1045. // redialDevice marks the device for immediate redial, unless the remote keeps
  1046. // dropping established connections. Thus we keep track of when the first forced
  1047. // re-dial happened, and how many attempts happen in the dialCoolDownInterval
  1048. // after that. If it's more than dialCoolDownMaxAttempts, don't force-redial
  1049. // that device for dialCoolDownDelay (regular dials still happen).
  1050. func (r nextDialRegistry) redialDevice(device protocol.DeviceID, now time.Time) {
  1051. dev, ok := r[device]
  1052. if !ok {
  1053. r[device] = nextDialDevice{
  1054. nextDial: make(map[string]time.Time),
  1055. coolDownIntervalStart: now,
  1056. attempts: 1,
  1057. }
  1058. return
  1059. }
  1060. if dev.attempts == 0 || now.Before(dev.coolDownIntervalStart.Add(dialCoolDownInterval)) {
  1061. if dev.attempts >= dialCoolDownMaxAttemps {
  1062. // Device has been force redialed too often - let it cool down.
  1063. return
  1064. }
  1065. if dev.attempts == 0 {
  1066. dev.coolDownIntervalStart = now
  1067. }
  1068. dev.attempts++
  1069. dev.nextDial = make(map[string]time.Time)
  1070. return
  1071. }
  1072. if dev.attempts >= dialCoolDownMaxAttemps && now.Before(dev.coolDownIntervalStart.Add(dialCoolDownDelay)) {
  1073. return // Still cooling down
  1074. }
  1075. delete(r, device)
  1076. }
  1077. func (r nextDialRegistry) set(device protocol.DeviceID, addr string, next time.Time) {
  1078. if _, ok := r[device]; !ok {
  1079. r[device] = nextDialDevice{nextDial: make(map[string]time.Time)}
  1080. }
  1081. r[device].nextDial[addr] = next
  1082. }
  1083. func (r nextDialRegistry) sleepDurationAndCleanup(now time.Time) time.Duration {
  1084. sleep := stdConnectionLoopSleep
  1085. for id, dev := range r {
  1086. for address, next := range dev.nextDial {
  1087. if next.Before(now) {
  1088. // Expired entry, address was not seen in last pass(es)
  1089. delete(dev.nextDial, address)
  1090. continue
  1091. }
  1092. if cur := next.Sub(now); cur < sleep {
  1093. sleep = cur
  1094. }
  1095. }
  1096. if dev.attempts > 0 {
  1097. interval := dialCoolDownInterval
  1098. if dev.attempts >= dialCoolDownMaxAttemps {
  1099. interval = dialCoolDownDelay
  1100. }
  1101. if now.After(dev.coolDownIntervalStart.Add(interval)) {
  1102. dev.attempts = 0
  1103. }
  1104. }
  1105. if len(dev.nextDial) == 0 && dev.attempts == 0 {
  1106. delete(r, id)
  1107. }
  1108. }
  1109. return sleep
  1110. }