service.go 37 KB

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