service.go 35 KB

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