service.go 45 KB

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