service.go 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487
  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. if ip.IsLinkLocalUnicast() {
  688. return true
  689. }
  690. for _, lan := range s.cfg.Options().AlwaysLocalNets {
  691. _, ipnet, err := net.ParseCIDR(lan)
  692. if err != nil {
  693. l.Debugln("Network", lan, "is malformed:", err)
  694. continue
  695. }
  696. if ipnet.Contains(ip) {
  697. return true
  698. }
  699. }
  700. lans, err := osutil.GetLans()
  701. if err != nil {
  702. l.Debugln("Failed to retrieve interface IPs:", err)
  703. priv := ip.IsPrivate()
  704. l.Debugf("Assuming isLAN=%v for IP %v", priv, ip)
  705. return priv
  706. }
  707. for _, lan := range lans {
  708. if lan.Contains(ip) {
  709. return true
  710. }
  711. }
  712. return false
  713. }
  714. func (s *service) createListener(factory listenerFactory, uri *url.URL) bool {
  715. // must be called with listenerMut held
  716. l.Debugln("Starting listener", uri)
  717. listener := factory.New(uri, s.cfg, s.tlsCfg, s.conns, s.natService, s.registry, s.lanChecker)
  718. listener.OnAddressesChanged(s.logListenAddressesChangedEvent)
  719. // Retrying a listener many times in rapid succession is unlikely to help,
  720. // thus back off quickly. A listener may soon be functional again, e.g. due
  721. // to a network interface coming back online - retry every minute.
  722. spec := svcutil.SpecWithInfoLogger(l)
  723. spec.FailureThreshold = 2
  724. spec.FailureBackoff = time.Minute
  725. sup := suture.New(fmt.Sprintf("listenerSupervisor@%v", listener), spec)
  726. sup.Add(listener)
  727. s.listeners[uri.String()] = listener
  728. s.listenerTokens[uri.String()] = s.Add(sup)
  729. return true
  730. }
  731. func (s *service) logListenAddressesChangedEvent(l ListenerAddresses) {
  732. s.evLogger.Log(events.ListenAddressesChanged, map[string]interface{}{
  733. "address": l.URI,
  734. "lan": l.LANAddresses,
  735. "wan": l.WANAddresses,
  736. })
  737. }
  738. func (s *service) CommitConfiguration(from, to config.Configuration) bool {
  739. newDevices := make(map[protocol.DeviceID]bool, len(to.Devices))
  740. for _, dev := range to.Devices {
  741. newDevices[dev.DeviceID] = true
  742. }
  743. for _, dev := range from.Devices {
  744. if !newDevices[dev.DeviceID] {
  745. warningLimitersMut.Lock()
  746. delete(warningLimiters, dev.DeviceID)
  747. warningLimitersMut.Unlock()
  748. }
  749. }
  750. s.checkAndSignalConnectLoopOnUpdatedDevices(from, to)
  751. s.listenersMut.Lock()
  752. seen := make(map[string]struct{})
  753. for _, addr := range to.Options.ListenAddresses() {
  754. if addr == "" {
  755. // We can get an empty address if there is an empty listener
  756. // element in the config, indicating no listeners should be
  757. // used. This is not an error.
  758. continue
  759. }
  760. uri, err := url.Parse(addr)
  761. if err != nil {
  762. l.Warnf("Skipping malformed listener URL %q: %v", addr, err)
  763. continue
  764. }
  765. // Make sure we always have the canonical representation of the URL.
  766. // This is for consistency as we use it as a map key, but also to
  767. // avoid misunderstandings. We do not just use the canonicalized
  768. // version, because an URL that looks very similar to a human might
  769. // mean something entirely different to the computer (e.g.,
  770. // tcp:/127.0.0.1:22000 in fact being equivalent to tcp://:22000).
  771. if canonical := uri.String(); canonical != addr {
  772. l.Warnf("Skipping malformed listener URL %q (not canonical)", addr)
  773. continue
  774. }
  775. if _, ok := s.listeners[addr]; ok {
  776. seen[addr] = struct{}{}
  777. continue
  778. }
  779. factory, err := getListenerFactory(to, uri)
  780. if errors.Is(err, errUnsupported) {
  781. l.Debugf("Listener for %v: %v", uri, err)
  782. continue
  783. } else if err != nil {
  784. l.Infof("Listener for %v: %v", uri, err)
  785. continue
  786. }
  787. s.createListener(factory, uri)
  788. seen[addr] = struct{}{}
  789. }
  790. for addr, listener := range s.listeners {
  791. if _, ok := seen[addr]; !ok || listener.Factory().Valid(to) != nil {
  792. l.Debugln("Stopping listener", addr)
  793. s.Remove(s.listenerTokens[addr])
  794. delete(s.listenerTokens, addr)
  795. delete(s.listeners, addr)
  796. }
  797. }
  798. s.listenersMut.Unlock()
  799. return true
  800. }
  801. func (s *service) checkAndSignalConnectLoopOnUpdatedDevices(from, to config.Configuration) {
  802. oldDevices := from.DeviceMap()
  803. dial := false
  804. s.dialNowDevicesMut.Lock()
  805. for _, dev := range to.Devices {
  806. if dev.Paused {
  807. continue
  808. }
  809. if oldDev, ok := oldDevices[dev.DeviceID]; !ok || oldDev.Paused {
  810. s.dialNowDevices[dev.DeviceID] = struct{}{}
  811. dial = true
  812. } else if !slices.Equal(oldDev.Addresses, dev.Addresses) {
  813. dial = true
  814. }
  815. }
  816. if dial {
  817. s.scheduleDialNow()
  818. }
  819. s.dialNowDevicesMut.Unlock()
  820. }
  821. func (s *service) scheduleDialNow() {
  822. select {
  823. case s.dialNow <- struct{}{}:
  824. default:
  825. // channel is blocked - a config update is already pending for the connection loop.
  826. }
  827. }
  828. func (s *service) AllAddresses() []string {
  829. s.listenersMut.RLock()
  830. var addrs []string
  831. for _, listener := range s.listeners {
  832. for _, lanAddr := range listener.LANAddresses() {
  833. addrs = append(addrs, lanAddr.String())
  834. }
  835. for _, wanAddr := range listener.WANAddresses() {
  836. addrs = append(addrs, wanAddr.String())
  837. }
  838. }
  839. s.listenersMut.RUnlock()
  840. return stringutil.UniqueTrimmedStrings(addrs)
  841. }
  842. func (s *service) ExternalAddresses() []string {
  843. if s.cfg.Options().AnnounceLANAddresses {
  844. return s.AllAddresses()
  845. }
  846. s.listenersMut.RLock()
  847. var addrs []string
  848. for _, listener := range s.listeners {
  849. for _, wanAddr := range listener.WANAddresses() {
  850. addrs = append(addrs, wanAddr.String())
  851. }
  852. }
  853. s.listenersMut.RUnlock()
  854. return stringutil.UniqueTrimmedStrings(addrs)
  855. }
  856. func (s *service) ListenerStatus() map[string]ListenerStatusEntry {
  857. result := make(map[string]ListenerStatusEntry)
  858. s.listenersMut.RLock()
  859. for addr, listener := range s.listeners {
  860. var status ListenerStatusEntry
  861. if err := listener.Error(); err != nil {
  862. errStr := err.Error()
  863. status.Error = &errStr
  864. }
  865. status.LANAddresses = urlsToStrings(listener.LANAddresses())
  866. status.WANAddresses = urlsToStrings(listener.WANAddresses())
  867. result[addr] = status
  868. }
  869. s.listenersMut.RUnlock()
  870. return result
  871. }
  872. type connectionStatusHandler struct {
  873. connectionStatusMut sync.RWMutex
  874. connectionStatus map[string]ConnectionStatusEntry // address -> latest error/status
  875. }
  876. func newConnectionStatusHandler() connectionStatusHandler {
  877. return connectionStatusHandler{
  878. connectionStatusMut: sync.NewRWMutex(),
  879. connectionStatus: make(map[string]ConnectionStatusEntry),
  880. }
  881. }
  882. func (s *connectionStatusHandler) ConnectionStatus() map[string]ConnectionStatusEntry {
  883. result := make(map[string]ConnectionStatusEntry)
  884. s.connectionStatusMut.RLock()
  885. for k, v := range s.connectionStatus {
  886. result[k] = v
  887. }
  888. s.connectionStatusMut.RUnlock()
  889. return result
  890. }
  891. func (s *connectionStatusHandler) setConnectionStatus(address string, err error) {
  892. if errors.Is(err, context.Canceled) {
  893. return
  894. }
  895. status := ConnectionStatusEntry{When: time.Now().UTC().Truncate(time.Second)}
  896. if err != nil {
  897. errStr := err.Error()
  898. status.Error = &errStr
  899. }
  900. s.connectionStatusMut.Lock()
  901. s.connectionStatus[address] = status
  902. s.connectionStatusMut.Unlock()
  903. }
  904. func (s *service) NATType() string {
  905. s.listenersMut.RLock()
  906. defer s.listenersMut.RUnlock()
  907. for _, listener := range s.listeners {
  908. natType := listener.NATType()
  909. if natType != "unknown" {
  910. return natType
  911. }
  912. }
  913. return "unknown"
  914. }
  915. func getDialerFactory(cfg config.Configuration, uri *url.URL) (dialerFactory, error) {
  916. dialerFactory, ok := dialers[uri.Scheme]
  917. if !ok {
  918. return nil, fmt.Errorf("unknown address scheme %q", uri.Scheme)
  919. }
  920. if err := dialerFactory.Valid(cfg); err != nil {
  921. return nil, err
  922. }
  923. return dialerFactory, nil
  924. }
  925. func getListenerFactory(cfg config.Configuration, uri *url.URL) (listenerFactory, error) {
  926. listenerFactory, ok := listeners[uri.Scheme]
  927. if !ok {
  928. return nil, fmt.Errorf("unknown address scheme %q", uri.Scheme)
  929. }
  930. if err := listenerFactory.Valid(cfg); err != nil {
  931. return nil, err
  932. }
  933. return listenerFactory, nil
  934. }
  935. func urlsToStrings(urls []*url.URL) []string {
  936. strings := make([]string, len(urls))
  937. for i, url := range urls {
  938. strings[i] = url.String()
  939. }
  940. return strings
  941. }
  942. var (
  943. warningLimiters = make(map[protocol.DeviceID]*rate.Limiter)
  944. warningLimitersMut = sync.NewMutex()
  945. )
  946. func warningFor(dev protocol.DeviceID, msg string) {
  947. warningLimitersMut.Lock()
  948. defer warningLimitersMut.Unlock()
  949. lim, ok := warningLimiters[dev]
  950. if !ok {
  951. lim = rate.NewLimiter(rate.Every(perDeviceWarningIntv), 1)
  952. warningLimiters[dev] = lim
  953. }
  954. if lim.Allow() {
  955. l.Warnln(msg)
  956. }
  957. }
  958. func tlsTimedHandshake(tc *tls.Conn) error {
  959. tc.SetDeadline(time.Now().Add(tlsHandshakeTimeout))
  960. defer tc.SetDeadline(time.Time{})
  961. return tc.Handshake()
  962. }
  963. // IsAllowedNetwork returns true if the given host (IP or resolvable
  964. // hostname) is in the set of allowed networks (CIDR format only).
  965. func IsAllowedNetwork(host string, allowed []string) bool {
  966. if hostNoPort, _, err := net.SplitHostPort(host); err == nil {
  967. host = hostNoPort
  968. }
  969. addr, err := net.ResolveIPAddr("ip", host)
  970. if err != nil {
  971. return false
  972. }
  973. for _, n := range allowed {
  974. result := true
  975. if strings.HasPrefix(n, "!") {
  976. result = false
  977. n = n[1:]
  978. }
  979. _, cidr, err := net.ParseCIDR(n)
  980. if err != nil {
  981. continue
  982. }
  983. if cidr.Contains(addr.IP) {
  984. return result
  985. }
  986. }
  987. return false
  988. }
  989. func (s *service) dialParallel(ctx context.Context, deviceID protocol.DeviceID, dialTargets []dialTarget, parentSema *semaphore.Semaphore) (internalConn, bool) {
  990. // Group targets into buckets by priority
  991. dialTargetBuckets := make(map[int][]dialTarget, len(dialTargets))
  992. for _, tgt := range dialTargets {
  993. dialTargetBuckets[tgt.priority] = append(dialTargetBuckets[tgt.priority], tgt)
  994. }
  995. // Get all available priorities
  996. priorities := make([]int, 0, len(dialTargetBuckets))
  997. for prio := range dialTargetBuckets {
  998. priorities = append(priorities, prio)
  999. }
  1000. // Sort the priorities so that we dial lowest first (which means highest...)
  1001. sort.Ints(priorities)
  1002. sema := semaphore.MultiSemaphore{semaphore.New(dialMaxParallelPerDevice), parentSema}
  1003. for _, prio := range priorities {
  1004. tgts := dialTargetBuckets[prio]
  1005. res := make(chan internalConn, len(tgts))
  1006. wg := stdsync.WaitGroup{}
  1007. for _, tgt := range tgts {
  1008. sema.Take(1)
  1009. wg.Add(1)
  1010. go func(tgt dialTarget) {
  1011. defer func() {
  1012. wg.Done()
  1013. sema.Give(1)
  1014. }()
  1015. conn, err := tgt.Dial(ctx)
  1016. if err == nil {
  1017. // Closes the connection on error
  1018. err = s.validateIdentity(conn, deviceID)
  1019. }
  1020. s.setConnectionStatus(tgt.addr, err)
  1021. if err != nil {
  1022. l.Debugln("dialing", deviceID, tgt.uri, "error:", err)
  1023. } else {
  1024. l.Debugln("dialing", deviceID, tgt.uri, "success:", conn)
  1025. res <- conn
  1026. }
  1027. }(tgt)
  1028. }
  1029. // Spawn a routine which will unblock main routine in case we fail
  1030. // to connect to anyone.
  1031. go func() {
  1032. wg.Wait()
  1033. close(res)
  1034. }()
  1035. // Wait for the first connection, or for channel closure.
  1036. if conn, ok := <-res; ok {
  1037. // Got a connection, means more might come back, hence spawn a
  1038. // routine that will do the discarding.
  1039. l.Debugln("connected to", deviceID, prio, "using", conn, conn.priority)
  1040. go func(deviceID protocol.DeviceID, prio int) {
  1041. wg.Wait()
  1042. l.Debugln("discarding", len(res), "connections while connecting to", deviceID, prio)
  1043. for conn := range res {
  1044. conn.Close()
  1045. }
  1046. }(deviceID, prio)
  1047. return conn, ok
  1048. }
  1049. // Failed to connect, report that fact.
  1050. l.Debugln("failed to connect to", deviceID, prio)
  1051. }
  1052. return internalConn{}, false
  1053. }
  1054. func (s *service) validateIdentity(c internalConn, expectedID protocol.DeviceID) error {
  1055. cs := c.ConnectionState()
  1056. // We should have received exactly one certificate from the other
  1057. // side. If we didn't, they don't have a device ID and we drop the
  1058. // connection.
  1059. certs := cs.PeerCertificates
  1060. if cl := len(certs); cl != 1 {
  1061. l.Infof("Got peer certificate list of length %d != 1 from peer at %s; protocol error", cl, c)
  1062. c.Close()
  1063. return fmt.Errorf("expected 1 certificate, got %d", cl)
  1064. }
  1065. remoteCert := certs[0]
  1066. remoteID := protocol.NewDeviceID(remoteCert.Raw)
  1067. // The device ID should not be that of ourselves. It can happen
  1068. // though, especially in the presence of NAT hairpinning, multiple
  1069. // clients between the same NAT gateway, and global discovery.
  1070. if remoteID == s.myID {
  1071. l.Debugf("Connected to myself (%s) at %s", remoteID, c)
  1072. c.Close()
  1073. return errors.New("connected to self")
  1074. }
  1075. // We should see the expected device ID
  1076. if !remoteID.Equals(expectedID) {
  1077. c.Close()
  1078. return fmt.Errorf("unexpected device id, expected %s got %s", expectedID, remoteID)
  1079. }
  1080. return nil
  1081. }
  1082. type nextDialRegistry map[protocol.DeviceID]nextDialDevice
  1083. type nextDialDevice struct {
  1084. nextDial map[string]time.Time
  1085. coolDownIntervalStart time.Time
  1086. attempts int
  1087. }
  1088. func (r nextDialRegistry) get(device protocol.DeviceID, addr string) time.Time {
  1089. return r[device].nextDial[addr]
  1090. }
  1091. const (
  1092. dialCoolDownInterval = 2 * time.Minute
  1093. dialCoolDownDelay = 5 * time.Minute
  1094. dialCoolDownMaxAttempts = 3
  1095. )
  1096. // redialDevice marks the device for immediate redial, unless the remote keeps
  1097. // dropping established connections. Thus we keep track of when the first forced
  1098. // re-dial happened, and how many attempts happen in the dialCoolDownInterval
  1099. // after that. If it's more than dialCoolDownMaxAttempts, don't force-redial
  1100. // that device for dialCoolDownDelay (regular dials still happen).
  1101. func (r nextDialRegistry) redialDevice(device protocol.DeviceID, now time.Time) {
  1102. dev, ok := r[device]
  1103. if !ok {
  1104. r[device] = nextDialDevice{
  1105. nextDial: make(map[string]time.Time),
  1106. coolDownIntervalStart: now,
  1107. attempts: 1,
  1108. }
  1109. return
  1110. }
  1111. if dev.attempts == 0 || now.Before(dev.coolDownIntervalStart.Add(dialCoolDownInterval)) {
  1112. if dev.attempts >= dialCoolDownMaxAttempts {
  1113. // Device has been force redialed too often - let it cool down.
  1114. return
  1115. }
  1116. if dev.attempts == 0 {
  1117. dev.coolDownIntervalStart = now
  1118. }
  1119. dev.attempts++
  1120. dev.nextDial = make(map[string]time.Time)
  1121. return
  1122. }
  1123. if dev.attempts >= dialCoolDownMaxAttempts && now.Before(dev.coolDownIntervalStart.Add(dialCoolDownDelay)) {
  1124. return // Still cooling down
  1125. }
  1126. delete(r, device)
  1127. }
  1128. func (r nextDialRegistry) set(device protocol.DeviceID, addr string, next time.Time) {
  1129. if _, ok := r[device]; !ok {
  1130. r[device] = nextDialDevice{nextDial: make(map[string]time.Time)}
  1131. }
  1132. r[device].nextDial[addr] = next
  1133. }
  1134. func (r nextDialRegistry) sleepDurationAndCleanup(now time.Time) time.Duration {
  1135. sleep := stdConnectionLoopSleep
  1136. for id, dev := range r {
  1137. for address, next := range dev.nextDial {
  1138. if next.Before(now) {
  1139. // Expired entry, address was not seen in last pass(es)
  1140. delete(dev.nextDial, address)
  1141. continue
  1142. }
  1143. if cur := next.Sub(now); cur < sleep {
  1144. sleep = cur
  1145. }
  1146. }
  1147. if dev.attempts > 0 {
  1148. interval := dialCoolDownInterval
  1149. if dev.attempts >= dialCoolDownMaxAttempts {
  1150. interval = dialCoolDownDelay
  1151. }
  1152. if now.After(dev.coolDownIntervalStart.Add(interval)) {
  1153. dev.attempts = 0
  1154. }
  1155. }
  1156. if len(dev.nextDial) == 0 && dev.attempts == 0 {
  1157. delete(r, id)
  1158. }
  1159. }
  1160. return sleep
  1161. }
  1162. func (s *service) desiredConnectionsToDevice(deviceID protocol.DeviceID) int {
  1163. cfg, ok := s.cfg.Device(deviceID)
  1164. if !ok {
  1165. // We want no connections to an unknown device.
  1166. return 0
  1167. }
  1168. otherSide := s.wantConnectionsForDevice(deviceID)
  1169. thisSide := cfg.NumConnections()
  1170. switch {
  1171. case otherSide <= 0:
  1172. // The other side doesn't support multiple connections, or we
  1173. // haven't yet connected to them so we don't know what they support
  1174. // or not. Use a single connection until we know better.
  1175. return 1
  1176. case otherSide == 1:
  1177. // The other side supports multiple connections, but only wants
  1178. // one. We should honour that.
  1179. return 1
  1180. case thisSide == 1:
  1181. // We want only one connection, so we should honour that.
  1182. return 1
  1183. // Finally, we allow negotiation and use the higher of the two values,
  1184. // while keeping at or below the max allowed value.
  1185. default:
  1186. return min(max(thisSide, otherSide), maxNumConnections)
  1187. }
  1188. }
  1189. // The deviceConnectionTracker keeps track of how many devices we are
  1190. // connected to and how many connections we have to each device. It also
  1191. // tracks how many connections they are willing to use.
  1192. type deviceConnectionTracker struct {
  1193. connectionsMut stdsync.Mutex
  1194. connections map[protocol.DeviceID][]protocol.Connection // current connections
  1195. wantConnections map[protocol.DeviceID]int // number of connections they want
  1196. }
  1197. func (c *deviceConnectionTracker) accountAddedConnection(conn protocol.Connection, h protocol.Hello, upgradeThreshold int) {
  1198. c.connectionsMut.Lock()
  1199. defer c.connectionsMut.Unlock()
  1200. // Lazily initialize the maps
  1201. if c.connections == nil {
  1202. c.connections = make(map[protocol.DeviceID][]protocol.Connection)
  1203. c.wantConnections = make(map[protocol.DeviceID]int)
  1204. }
  1205. // Add the connection to the list of current connections and remember
  1206. // how many total connections they want
  1207. d := conn.DeviceID()
  1208. c.connections[d] = append(c.connections[d], conn)
  1209. c.wantConnections[d] = int(h.NumConnections)
  1210. l.Debugf("Added connection for %s (now %d), they want %d connections", d.Short(), len(c.connections[d]), h.NumConnections)
  1211. // Close any connections we no longer want to retain.
  1212. c.closeWorsePriorityConnectionsLocked(d, conn.Priority()-upgradeThreshold)
  1213. }
  1214. func (c *deviceConnectionTracker) accountRemovedConnection(conn protocol.Connection) {
  1215. c.connectionsMut.Lock()
  1216. defer c.connectionsMut.Unlock()
  1217. d := conn.DeviceID()
  1218. cid := conn.ConnectionID()
  1219. // Remove the connection from the list of current connections
  1220. for i, conn := range c.connections[d] {
  1221. if conn.ConnectionID() == cid {
  1222. c.connections[d] = sliceutil.RemoveAndZero(c.connections[d], i)
  1223. break
  1224. }
  1225. }
  1226. // Clean up if required
  1227. if len(c.connections[d]) == 0 {
  1228. delete(c.connections, d)
  1229. delete(c.wantConnections, d)
  1230. }
  1231. l.Debugf("Removed connection for %s (now %d)", d.Short(), c.connections[d])
  1232. }
  1233. func (c *deviceConnectionTracker) numConnectionsForDevice(d protocol.DeviceID) int {
  1234. c.connectionsMut.Lock()
  1235. defer c.connectionsMut.Unlock()
  1236. return len(c.connections[d])
  1237. }
  1238. func (c *deviceConnectionTracker) wantConnectionsForDevice(d protocol.DeviceID) int {
  1239. c.connectionsMut.Lock()
  1240. defer c.connectionsMut.Unlock()
  1241. return c.wantConnections[d]
  1242. }
  1243. func (c *deviceConnectionTracker) numConnectedDevices() int {
  1244. c.connectionsMut.Lock()
  1245. defer c.connectionsMut.Unlock()
  1246. return len(c.connections)
  1247. }
  1248. func (c *deviceConnectionTracker) worstConnectionPriority(d protocol.DeviceID) int {
  1249. c.connectionsMut.Lock()
  1250. defer c.connectionsMut.Unlock()
  1251. if len(c.connections[d]) == 0 {
  1252. return math.MaxInt // worst possible priority
  1253. }
  1254. worstPriority := c.connections[d][0].Priority()
  1255. for _, conn := range c.connections[d][1:] {
  1256. if p := conn.Priority(); p > worstPriority {
  1257. worstPriority = p
  1258. }
  1259. }
  1260. return worstPriority
  1261. }
  1262. // closeWorsePriorityConnectionsLocked closes all connections to the given
  1263. // device that are worse than the cutoff priority. Must be called with the
  1264. // lock held.
  1265. func (c *deviceConnectionTracker) closeWorsePriorityConnectionsLocked(d protocol.DeviceID, cutoff int) {
  1266. for _, conn := range c.connections[d] {
  1267. if p := conn.Priority(); p > cutoff {
  1268. l.Debugf("Closing connection %s to %s with priority %d (cutoff %d)", conn, d.Short(), p, cutoff)
  1269. go conn.Close(errReplacingConnection)
  1270. }
  1271. }
  1272. }
  1273. // newConnectionID generates a connection ID. The connection ID is designed
  1274. // to be unique for each connection and chronologically sortable. It is
  1275. // based on the sum of two timestamps: when we think the connection was
  1276. // started, and when the other side thinks the connection was started. We
  1277. // then add some random data for good measure. This way, even if the other
  1278. // side does some funny business with the timestamp, we will get no worse
  1279. // than random connection IDs.
  1280. func newConnectionID(t0, t1 int64) string {
  1281. var buf [16]byte // 8 bytes timestamp, 8 bytes random
  1282. binary.BigEndian.PutUint64(buf[:], uint64(t0+t1))
  1283. _, _ = io.ReadFull(rand.Reader, buf[8:])
  1284. enc := base32.HexEncoding.WithPadding(base32.NoPadding)
  1285. // We encode the two parts separately and concatenate the results. The
  1286. // reason for this is that the timestamp (64 bits) doesn't precisely
  1287. // align to the base32 encoding (5 bits per character), so we'd get a
  1288. // character in the middle that is a mix of bits from the timestamp and
  1289. // from the random. We want the timestamp part deterministic.
  1290. return enc.EncodeToString(buf[:8]) + enc.EncodeToString(buf[8:])
  1291. }
  1292. // temporary implementations of min and max, to be removed once we can use
  1293. // Go 1.21 builtins. :)
  1294. func min[T constraints.Ordered](a, b T) T {
  1295. if a < b {
  1296. return a
  1297. }
  1298. return b
  1299. }
  1300. func max[T constraints.Ordered](a, b T) T {
  1301. if a > b {
  1302. return a
  1303. }
  1304. return b
  1305. }