service.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959
  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. package connections
  7. import (
  8. "context"
  9. "crypto/tls"
  10. "fmt"
  11. "net"
  12. "net/url"
  13. "sort"
  14. "strings"
  15. stdsync "sync"
  16. "time"
  17. "github.com/syncthing/syncthing/lib/config"
  18. "github.com/syncthing/syncthing/lib/discover"
  19. "github.com/syncthing/syncthing/lib/events"
  20. "github.com/syncthing/syncthing/lib/nat"
  21. "github.com/syncthing/syncthing/lib/osutil"
  22. "github.com/syncthing/syncthing/lib/protocol"
  23. "github.com/syncthing/syncthing/lib/sync"
  24. "github.com/syncthing/syncthing/lib/util"
  25. // Registers NAT service providers
  26. _ "github.com/syncthing/syncthing/lib/pmp"
  27. _ "github.com/syncthing/syncthing/lib/upnp"
  28. "github.com/pkg/errors"
  29. "github.com/thejerf/suture/v4"
  30. "golang.org/x/time/rate"
  31. )
  32. var (
  33. dialers = make(map[string]dialerFactory)
  34. listeners = make(map[string]listenerFactory)
  35. )
  36. var (
  37. // Dialers and listeners return errUnsupported (or a wrapped variant)
  38. // when they are intentionally out of service due to configuration,
  39. // build, etc. This is not logged loudly.
  40. errUnsupported = errors.New("unsupported protocol")
  41. // These are specific explanations for errUnsupported.
  42. errDisabled = fmt.Errorf("%w: disabled by configuration", errUnsupported)
  43. errDeprecated = fmt.Errorf("%w: deprecated", errUnsupported)
  44. errNotInBuild = fmt.Errorf("%w: disabled at build time", errUnsupported)
  45. )
  46. const (
  47. perDeviceWarningIntv = 15 * time.Minute
  48. tlsHandshakeTimeout = 10 * time.Second
  49. minConnectionReplaceAge = 10 * time.Second
  50. )
  51. // From go/src/crypto/tls/cipher_suites.go
  52. var tlsCipherSuiteNames = map[uint16]string{
  53. // TLS 1.2
  54. 0x0005: "TLS_RSA_WITH_RC4_128_SHA",
  55. 0x000a: "TLS_RSA_WITH_3DES_EDE_CBC_SHA",
  56. 0x002f: "TLS_RSA_WITH_AES_128_CBC_SHA",
  57. 0x0035: "TLS_RSA_WITH_AES_256_CBC_SHA",
  58. 0x003c: "TLS_RSA_WITH_AES_128_CBC_SHA256",
  59. 0x009c: "TLS_RSA_WITH_AES_128_GCM_SHA256",
  60. 0x009d: "TLS_RSA_WITH_AES_256_GCM_SHA384",
  61. 0xc007: "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA",
  62. 0xc009: "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA",
  63. 0xc00a: "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA",
  64. 0xc011: "TLS_ECDHE_RSA_WITH_RC4_128_SHA",
  65. 0xc012: "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA",
  66. 0xc013: "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",
  67. 0xc014: "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA",
  68. 0xc023: "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256",
  69. 0xc027: "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256",
  70. 0xc02f: "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
  71. 0xc02b: "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
  72. 0xc030: "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
  73. 0xc02c: "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
  74. 0xcca8: "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305",
  75. 0xcca9: "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305",
  76. // TLS 1.3
  77. 0x1301: "TLS_AES_128_GCM_SHA256",
  78. 0x1302: "TLS_AES_256_GCM_SHA384",
  79. 0x1303: "TLS_CHACHA20_POLY1305_SHA256",
  80. }
  81. var tlsVersionNames = map[uint16]string{
  82. tls.VersionTLS12: "TLS1.2",
  83. tls.VersionTLS13: "TLS1.3",
  84. }
  85. // Service listens and dials all configured unconnected devices, via supported
  86. // dialers. Successful connections are handed to the model.
  87. type Service interface {
  88. suture.Service
  89. discover.AddressLister
  90. ListenerStatus() map[string]ListenerStatusEntry
  91. ConnectionStatus() map[string]ConnectionStatusEntry
  92. NATType() string
  93. }
  94. type ListenerStatusEntry struct {
  95. Error *string `json:"error"`
  96. LANAddresses []string `json:"lanAddresses"`
  97. WANAddresses []string `json:"wanAddresses"`
  98. }
  99. type ConnectionStatusEntry struct {
  100. When time.Time `json:"when"`
  101. Error *string `json:"error"`
  102. }
  103. type service struct {
  104. *suture.Supervisor
  105. connectionStatusHandler
  106. cfg config.Wrapper
  107. myID protocol.DeviceID
  108. model Model
  109. tlsCfg *tls.Config
  110. discoverer discover.Finder
  111. conns chan internalConn
  112. bepProtocolName string
  113. tlsDefaultCommonName string
  114. limiter *limiter
  115. natService *nat.Service
  116. evLogger events.Logger
  117. listenersMut sync.RWMutex
  118. listeners map[string]genericListener
  119. listenerTokens map[string]suture.ServiceToken
  120. listenerSupervisor *suture.Supervisor
  121. }
  122. func NewService(cfg config.Wrapper, myID protocol.DeviceID, mdl Model, tlsCfg *tls.Config, discoverer discover.Finder, bepProtocolName string, tlsDefaultCommonName string, evLogger events.Logger) Service {
  123. spec := util.SpecWithInfoLogger(l)
  124. service := &service{
  125. Supervisor: suture.New("connections.Service", spec),
  126. connectionStatusHandler: newConnectionStatusHandler(),
  127. cfg: cfg,
  128. myID: myID,
  129. model: mdl,
  130. tlsCfg: tlsCfg,
  131. discoverer: discoverer,
  132. conns: make(chan internalConn),
  133. bepProtocolName: bepProtocolName,
  134. tlsDefaultCommonName: tlsDefaultCommonName,
  135. limiter: newLimiter(myID, cfg),
  136. natService: nat.NewService(myID, cfg),
  137. evLogger: evLogger,
  138. listenersMut: sync.NewRWMutex(),
  139. listeners: make(map[string]genericListener),
  140. listenerTokens: make(map[string]suture.ServiceToken),
  141. // A listener can fail twice, rapidly. Any more than that and it
  142. // will be put on suspension for ten minutes. Restarts and changes
  143. // due to config are done by removing and adding services, so are
  144. // not subject to these limitations.
  145. listenerSupervisor: suture.New("c.S.listenerSupervisor", suture.Spec{
  146. EventHook: func(e suture.Event) {
  147. l.Infoln(e)
  148. },
  149. FailureThreshold: 2,
  150. FailureBackoff: 600 * time.Second,
  151. PassThroughPanics: true,
  152. }),
  153. }
  154. cfg.Subscribe(service)
  155. raw := cfg.RawCopy()
  156. // Actually starts the listeners and NAT service
  157. // Need to start this before service.connect so that any dials that
  158. // try punch through already have a listener to cling on.
  159. service.CommitConfiguration(raw, raw)
  160. // There are several moving parts here; one routine per listening address
  161. // (handled in configuration changing) to handle incoming connections,
  162. // one routine to periodically attempt outgoing connections, one routine to
  163. // the common handling regardless of whether the connection was
  164. // incoming or outgoing.
  165. service.Add(util.AsService(service.connect, fmt.Sprintf("%s/connect", service)))
  166. service.Add(util.AsService(service.handle, fmt.Sprintf("%s/handle", service)))
  167. service.Add(service.listenerSupervisor)
  168. service.Add(service.natService)
  169. util.OnSupervisorDone(service.Supervisor, func() {
  170. service.cfg.Unsubscribe(service.limiter)
  171. service.cfg.Unsubscribe(service)
  172. })
  173. return service
  174. }
  175. func (s *service) handle(ctx context.Context) error {
  176. var c internalConn
  177. for {
  178. select {
  179. case <-ctx.Done():
  180. return ctx.Err()
  181. case c = <-s.conns:
  182. }
  183. cs := c.ConnectionState()
  184. // We should have negotiated the next level protocol "bep/1.0" as part
  185. // of the TLS handshake. Unfortunately this can't be a hard error,
  186. // because there are implementations out there that don't support
  187. // protocol negotiation (iOS for one...).
  188. if !cs.NegotiatedProtocolIsMutual || cs.NegotiatedProtocol != s.bepProtocolName {
  189. l.Infof("Peer at %s did not negotiate bep/1.0", c)
  190. }
  191. // We should have received exactly one certificate from the other
  192. // side. If we didn't, they don't have a device ID and we drop the
  193. // connection.
  194. certs := cs.PeerCertificates
  195. if cl := len(certs); cl != 1 {
  196. l.Infof("Got peer certificate list of length %d != 1 from peer at %s; protocol error", cl, c)
  197. c.Close()
  198. continue
  199. }
  200. remoteCert := certs[0]
  201. remoteID := protocol.NewDeviceID(remoteCert.Raw)
  202. // The device ID should not be that of ourselves. It can happen
  203. // though, especially in the presence of NAT hairpinning, multiple
  204. // clients between the same NAT gateway, and global discovery.
  205. if remoteID == s.myID {
  206. l.Infof("Connected to myself (%s) at %s - should not happen", remoteID, c)
  207. c.Close()
  208. continue
  209. }
  210. _ = c.SetDeadline(time.Now().Add(20 * time.Second))
  211. hello, err := protocol.ExchangeHello(c, s.model.GetHello(remoteID))
  212. if err != nil {
  213. if protocol.IsVersionMismatch(err) {
  214. // The error will be a relatively user friendly description
  215. // of what's wrong with the version compatibility. By
  216. // default identify the other side by device ID and IP.
  217. remote := fmt.Sprintf("%v (%v)", remoteID, c.RemoteAddr())
  218. if hello.DeviceName != "" {
  219. // If the name was set in the hello return, use that to
  220. // give the user more info about which device is the
  221. // affected one. It probably says more than the remote
  222. // IP.
  223. remote = fmt.Sprintf("%q (%s %s, %v)", hello.DeviceName, hello.ClientName, hello.ClientVersion, remoteID)
  224. }
  225. msg := fmt.Sprintf("Connecting to %s: %s", remote, err)
  226. warningFor(remoteID, msg)
  227. } else {
  228. // It's something else - connection reset or whatever
  229. l.Infof("Failed to exchange Hello messages with %s at %s: %s", remoteID, c, err)
  230. }
  231. c.Close()
  232. continue
  233. }
  234. _ = c.SetDeadline(time.Time{})
  235. // The Model will return an error for devices that we don't want to
  236. // have a connection with for whatever reason, for example unknown devices.
  237. if err := s.model.OnHello(remoteID, c.RemoteAddr(), hello); err != nil {
  238. l.Infof("Connection from %s at %s (%s) rejected: %v", remoteID, c.RemoteAddr(), c.Type(), err)
  239. c.Close()
  240. continue
  241. }
  242. // If we have a relay connection, and the new incoming connection is
  243. // not a relay connection, we should drop that, and prefer this one.
  244. ct, connected := s.model.Connection(remoteID)
  245. // Lower priority is better, just like nice etc.
  246. if connected && (ct.Priority() > c.priority || time.Since(ct.Statistics().StartedAt) > minConnectionReplaceAge) {
  247. l.Debugf("Switching connections %s (existing: %s new: %s)", remoteID, ct, c)
  248. } else if connected {
  249. // We should not already be connected to the other party. TODO: This
  250. // could use some better handling. If the old connection is dead but
  251. // hasn't timed out yet we may want to drop *that* connection and keep
  252. // this one. But in case we are two devices connecting to each other
  253. // in parallel we don't want to do that or we end up with no
  254. // connections still established...
  255. l.Infof("Connected to already connected device %s (existing: %s new: %s)", remoteID, ct, c)
  256. c.Close()
  257. continue
  258. }
  259. deviceCfg, ok := s.cfg.Device(remoteID)
  260. if !ok {
  261. l.Infof("Device %s removed from config during connection attempt at %s", remoteID, c)
  262. c.Close()
  263. continue
  264. }
  265. // Verify the name on the certificate. By default we set it to
  266. // "syncthing" when generating, but the user may have replaced
  267. // the certificate and used another name.
  268. certName := deviceCfg.CertName
  269. if certName == "" {
  270. certName = s.tlsDefaultCommonName
  271. }
  272. if remoteCert.Subject.CommonName == certName {
  273. // All good. We do this check because our old style certificates
  274. // have "syncthing" in the CommonName field and no SANs, which
  275. // is not accepted by VerifyHostname() any more as of Go 1.15.
  276. } else if err := remoteCert.VerifyHostname(certName); err != nil {
  277. // Incorrect certificate name is something the user most
  278. // likely wants to know about, since it's an advanced
  279. // config. Warn instead of Info.
  280. l.Warnf("Bad certificate from %s at %s: %v", remoteID, c, err)
  281. c.Close()
  282. continue
  283. }
  284. // Wrap the connection in rate limiters. The limiter itself will
  285. // keep up with config changes to the rate and whether or not LAN
  286. // connections are limited.
  287. isLAN := s.isLAN(c.RemoteAddr())
  288. rd, wr := s.limiter.getLimiters(remoteID, c, isLAN)
  289. var protoConn protocol.Connection
  290. passwords := s.cfg.FolderPasswords(remoteID)
  291. if len(passwords) > 0 {
  292. protoConn = protocol.NewEncryptedConnection(passwords, remoteID, rd, wr, s.model, c.String(), deviceCfg.Compression)
  293. } else {
  294. protoConn = protocol.NewConnection(remoteID, rd, wr, s.model, c.String(), deviceCfg.Compression)
  295. }
  296. modelConn := completeConn{c, protoConn}
  297. l.Infof("Established secure connection to %s at %s", remoteID, c)
  298. s.model.AddConnection(modelConn, hello)
  299. continue
  300. }
  301. }
  302. func (s *service) connect(ctx context.Context) error {
  303. nextDial := make(map[string]time.Time)
  304. // Used as delay for the first few connection attempts, increases
  305. // exponentially
  306. initialRampup := time.Second
  307. // Calculated from actual dialers reconnectInterval
  308. var sleep time.Duration
  309. for {
  310. cfg := s.cfg.RawCopy()
  311. bestDialerPrio := 1<<31 - 1 // worse prio won't build on 32 bit
  312. for _, df := range dialers {
  313. if df.Valid(cfg) != nil {
  314. continue
  315. }
  316. if prio := df.Priority(); prio < bestDialerPrio {
  317. bestDialerPrio = prio
  318. }
  319. }
  320. l.Debugln("Reconnect loop")
  321. now := time.Now()
  322. var seen []string
  323. for _, deviceCfg := range cfg.Devices {
  324. select {
  325. case <-ctx.Done():
  326. return ctx.Err()
  327. default:
  328. }
  329. deviceID := deviceCfg.DeviceID
  330. if deviceID == s.myID {
  331. continue
  332. }
  333. if deviceCfg.Paused {
  334. continue
  335. }
  336. ct, connected := s.model.Connection(deviceID)
  337. if connected && ct.Priority() == bestDialerPrio {
  338. // Things are already as good as they can get.
  339. continue
  340. }
  341. var addrs []string
  342. for _, addr := range deviceCfg.Addresses {
  343. if addr == "dynamic" {
  344. if s.discoverer != nil {
  345. if t, err := s.discoverer.Lookup(ctx, deviceID); err == nil {
  346. addrs = append(addrs, t...)
  347. }
  348. }
  349. } else {
  350. addrs = append(addrs, addr)
  351. }
  352. }
  353. addrs = util.UniqueTrimmedStrings(addrs)
  354. l.Debugln("Reconnect loop for", deviceID, addrs)
  355. dialTargets := make([]dialTarget, 0)
  356. for _, addr := range addrs {
  357. // Use a special key that is more than just the address, as you might have two devices connected to the same relay
  358. nextDialKey := deviceID.String() + "/" + addr
  359. seen = append(seen, nextDialKey)
  360. nextDialAt, ok := nextDial[nextDialKey]
  361. if ok && initialRampup >= sleep && nextDialAt.After(now) {
  362. l.Debugf("Not dialing %s via %v as sleep is %v, next dial is at %s and current time is %s", deviceID, addr, sleep, nextDialAt, now)
  363. continue
  364. }
  365. // If we fail at any step before actually getting the dialer
  366. // retry in a minute
  367. nextDial[nextDialKey] = now.Add(time.Minute)
  368. uri, err := url.Parse(addr)
  369. if err != nil {
  370. s.setConnectionStatus(addr, err)
  371. l.Infof("Parsing dialer address %s: %v", addr, err)
  372. continue
  373. }
  374. if len(deviceCfg.AllowedNetworks) > 0 {
  375. if !IsAllowedNetwork(uri.Host, deviceCfg.AllowedNetworks) {
  376. s.setConnectionStatus(addr, errors.New("network disallowed"))
  377. l.Debugln("Network for", uri, "is disallowed")
  378. continue
  379. }
  380. }
  381. dialerFactory, err := getDialerFactory(cfg, uri)
  382. if err != nil {
  383. s.setConnectionStatus(addr, err)
  384. }
  385. if errors.Is(err, errUnsupported) {
  386. l.Debugf("Dialer for %v: %v", uri, err)
  387. continue
  388. } else if err != nil {
  389. l.Infof("Dialer for %v: %v", uri, err)
  390. continue
  391. }
  392. priority := dialerFactory.Priority()
  393. if connected && priority >= ct.Priority() {
  394. l.Debugf("Not dialing using %s as priority is less than current connection (%d >= %d)", dialerFactory, dialerFactory.Priority(), ct.Priority())
  395. continue
  396. }
  397. dialer := dialerFactory.New(s.cfg.Options(), s.tlsCfg)
  398. nextDial[nextDialKey] = now.Add(dialer.RedialFrequency())
  399. // For LAN addresses, increase the priority so that we
  400. // try these first.
  401. switch {
  402. case dialerFactory.AlwaysWAN():
  403. // Do nothing.
  404. case s.isLANHost(uri.Host):
  405. priority -= 1
  406. }
  407. dialTargets = append(dialTargets, dialTarget{
  408. addr: addr,
  409. dialer: dialer,
  410. priority: priority,
  411. deviceID: deviceID,
  412. uri: uri,
  413. })
  414. }
  415. conn, ok := s.dialParallel(ctx, deviceCfg.DeviceID, dialTargets)
  416. if ok {
  417. s.conns <- conn
  418. }
  419. }
  420. nextDial, sleep = filterAndFindSleepDuration(nextDial, seen, now)
  421. if initialRampup < sleep {
  422. l.Debugln("initial rampup; sleep", initialRampup, "and update to", initialRampup*2)
  423. sleep = initialRampup
  424. initialRampup *= 2
  425. } else {
  426. l.Debugln("sleep until next dial", sleep)
  427. }
  428. select {
  429. case <-time.After(sleep):
  430. case <-ctx.Done():
  431. return ctx.Err()
  432. }
  433. }
  434. }
  435. func (s *service) isLANHost(host string) bool {
  436. // Probably we are called with an ip:port combo which we can resolve as
  437. // a TCP address.
  438. if addr, err := net.ResolveTCPAddr("tcp", host); err == nil {
  439. return s.isLAN(addr)
  440. }
  441. // ... but this function looks general enough that someone might try
  442. // with just an IP as well in the future so lets allow that.
  443. if addr, err := net.ResolveIPAddr("ip", host); err == nil {
  444. return s.isLAN(addr)
  445. }
  446. return false
  447. }
  448. func (s *service) isLAN(addr net.Addr) bool {
  449. var ip net.IP
  450. switch addr := addr.(type) {
  451. case *net.IPAddr:
  452. ip = addr.IP
  453. case *net.TCPAddr:
  454. ip = addr.IP
  455. case *net.UDPAddr:
  456. ip = addr.IP
  457. default:
  458. // From the standard library, just Unix sockets.
  459. // If you invent your own, handle it.
  460. return false
  461. }
  462. if ip.IsLoopback() {
  463. return true
  464. }
  465. for _, lan := range s.cfg.Options().AlwaysLocalNets {
  466. _, ipnet, err := net.ParseCIDR(lan)
  467. if err != nil {
  468. l.Debugln("Network", lan, "is malformed:", err)
  469. continue
  470. }
  471. if ipnet.Contains(ip) {
  472. return true
  473. }
  474. }
  475. lans, _ := osutil.GetLans()
  476. for _, lan := range lans {
  477. if lan.Contains(ip) {
  478. return true
  479. }
  480. }
  481. return false
  482. }
  483. func (s *service) createListener(factory listenerFactory, uri *url.URL) bool {
  484. // must be called with listenerMut held
  485. l.Debugln("Starting listener", uri)
  486. listener := factory.New(uri, s.cfg, s.tlsCfg, s.conns, s.natService)
  487. listener.OnAddressesChanged(s.logListenAddressesChangedEvent)
  488. s.listeners[uri.String()] = listener
  489. s.listenerTokens[uri.String()] = s.listenerSupervisor.Add(listener)
  490. return true
  491. }
  492. func (s *service) logListenAddressesChangedEvent(l ListenerAddresses) {
  493. s.evLogger.Log(events.ListenAddressesChanged, map[string]interface{}{
  494. "address": l.URI,
  495. "lan": l.LANAddresses,
  496. "wan": l.WANAddresses,
  497. })
  498. }
  499. func (s *service) VerifyConfiguration(from, to config.Configuration) error {
  500. return nil
  501. }
  502. func (s *service) CommitConfiguration(from, to config.Configuration) bool {
  503. newDevices := make(map[protocol.DeviceID]bool, len(to.Devices))
  504. for _, dev := range to.Devices {
  505. newDevices[dev.DeviceID] = true
  506. }
  507. for _, dev := range from.Devices {
  508. if !newDevices[dev.DeviceID] {
  509. warningLimitersMut.Lock()
  510. delete(warningLimiters, dev.DeviceID)
  511. warningLimitersMut.Unlock()
  512. }
  513. }
  514. s.listenersMut.Lock()
  515. seen := make(map[string]struct{})
  516. for _, addr := range to.Options.ListenAddresses() {
  517. if addr == "" {
  518. // We can get an empty address if there is an empty listener
  519. // element in the config, indicating no listeners should be
  520. // used. This is not an error.
  521. continue
  522. }
  523. uri, err := url.Parse(addr)
  524. if err != nil {
  525. l.Warnf("Skipping malformed listener URL %q: %v", addr, err)
  526. continue
  527. }
  528. // Make sure we always have the canonical representation of the URL.
  529. // This is for consistency as we use it as a map key, but also to
  530. // avoid misunderstandings. We do not just use the canonicalized
  531. // version, because an URL that looks very similar to a human might
  532. // mean something entirely different to the computer (e.g.,
  533. // tcp:/127.0.0.1:22000 in fact being equivalent to tcp://:22000).
  534. if canonical := uri.String(); canonical != addr {
  535. l.Warnf("Skipping malformed listener URL %q (not canonical)", addr)
  536. continue
  537. }
  538. if _, ok := s.listeners[addr]; ok {
  539. seen[addr] = struct{}{}
  540. continue
  541. }
  542. factory, err := getListenerFactory(to, uri)
  543. if errors.Is(err, errUnsupported) {
  544. l.Debugf("Listener for %v: %v", uri, err)
  545. continue
  546. } else if err != nil {
  547. l.Infof("Listener for %v: %v", uri, err)
  548. continue
  549. }
  550. s.createListener(factory, uri)
  551. seen[addr] = struct{}{}
  552. }
  553. for addr, listener := range s.listeners {
  554. if _, ok := seen[addr]; !ok || listener.Factory().Valid(to) != nil {
  555. l.Debugln("Stopping listener", addr)
  556. s.listenerSupervisor.Remove(s.listenerTokens[addr])
  557. delete(s.listenerTokens, addr)
  558. delete(s.listeners, addr)
  559. }
  560. }
  561. s.listenersMut.Unlock()
  562. return true
  563. }
  564. func (s *service) AllAddresses() []string {
  565. s.listenersMut.RLock()
  566. var addrs []string
  567. for _, listener := range s.listeners {
  568. for _, lanAddr := range listener.LANAddresses() {
  569. addrs = append(addrs, lanAddr.String())
  570. }
  571. for _, wanAddr := range listener.WANAddresses() {
  572. addrs = append(addrs, wanAddr.String())
  573. }
  574. }
  575. s.listenersMut.RUnlock()
  576. return util.UniqueTrimmedStrings(addrs)
  577. }
  578. func (s *service) ExternalAddresses() []string {
  579. if s.cfg.Options().AnnounceLANAddresses {
  580. return s.AllAddresses()
  581. }
  582. s.listenersMut.RLock()
  583. var addrs []string
  584. for _, listener := range s.listeners {
  585. for _, wanAddr := range listener.WANAddresses() {
  586. addrs = append(addrs, wanAddr.String())
  587. }
  588. }
  589. s.listenersMut.RUnlock()
  590. return util.UniqueTrimmedStrings(addrs)
  591. }
  592. func (s *service) ListenerStatus() map[string]ListenerStatusEntry {
  593. result := make(map[string]ListenerStatusEntry)
  594. s.listenersMut.RLock()
  595. for addr, listener := range s.listeners {
  596. var status ListenerStatusEntry
  597. if err := listener.Error(); err != nil {
  598. errStr := err.Error()
  599. status.Error = &errStr
  600. }
  601. status.LANAddresses = urlsToStrings(listener.LANAddresses())
  602. status.WANAddresses = urlsToStrings(listener.WANAddresses())
  603. result[addr] = status
  604. }
  605. s.listenersMut.RUnlock()
  606. return result
  607. }
  608. type connectionStatusHandler struct {
  609. connectionStatusMut sync.RWMutex
  610. connectionStatus map[string]ConnectionStatusEntry // address -> latest error/status
  611. }
  612. func newConnectionStatusHandler() connectionStatusHandler {
  613. return connectionStatusHandler{
  614. connectionStatusMut: sync.NewRWMutex(),
  615. connectionStatus: make(map[string]ConnectionStatusEntry),
  616. }
  617. }
  618. func (s *connectionStatusHandler) ConnectionStatus() map[string]ConnectionStatusEntry {
  619. result := make(map[string]ConnectionStatusEntry)
  620. s.connectionStatusMut.RLock()
  621. for k, v := range s.connectionStatus {
  622. result[k] = v
  623. }
  624. s.connectionStatusMut.RUnlock()
  625. return result
  626. }
  627. func (s *connectionStatusHandler) setConnectionStatus(address string, err error) {
  628. if errors.Cause(err) == context.Canceled {
  629. return
  630. }
  631. status := ConnectionStatusEntry{When: time.Now().UTC().Truncate(time.Second)}
  632. if err != nil {
  633. errStr := err.Error()
  634. status.Error = &errStr
  635. }
  636. s.connectionStatusMut.Lock()
  637. s.connectionStatus[address] = status
  638. s.connectionStatusMut.Unlock()
  639. }
  640. func (s *service) NATType() string {
  641. s.listenersMut.RLock()
  642. defer s.listenersMut.RUnlock()
  643. for _, listener := range s.listeners {
  644. natType := listener.NATType()
  645. if natType != "unknown" {
  646. return natType
  647. }
  648. }
  649. return "unknown"
  650. }
  651. func getDialerFactory(cfg config.Configuration, uri *url.URL) (dialerFactory, error) {
  652. dialerFactory, ok := dialers[uri.Scheme]
  653. if !ok {
  654. return nil, fmt.Errorf("unknown address scheme %q", uri.Scheme)
  655. }
  656. if err := dialerFactory.Valid(cfg); err != nil {
  657. return nil, err
  658. }
  659. return dialerFactory, nil
  660. }
  661. func getListenerFactory(cfg config.Configuration, uri *url.URL) (listenerFactory, error) {
  662. listenerFactory, ok := listeners[uri.Scheme]
  663. if !ok {
  664. return nil, fmt.Errorf("unknown address scheme %q", uri.Scheme)
  665. }
  666. if err := listenerFactory.Valid(cfg); err != nil {
  667. return nil, err
  668. }
  669. return listenerFactory, nil
  670. }
  671. func filterAndFindSleepDuration(nextDial map[string]time.Time, seen []string, now time.Time) (map[string]time.Time, time.Duration) {
  672. newNextDial := make(map[string]time.Time)
  673. for _, addr := range seen {
  674. nextDialAt, ok := nextDial[addr]
  675. if ok {
  676. newNextDial[addr] = nextDialAt
  677. }
  678. }
  679. min := time.Minute
  680. for _, next := range newNextDial {
  681. cur := next.Sub(now)
  682. if cur < min {
  683. min = cur
  684. }
  685. }
  686. return newNextDial, min
  687. }
  688. func urlsToStrings(urls []*url.URL) []string {
  689. strings := make([]string, len(urls))
  690. for i, url := range urls {
  691. strings[i] = url.String()
  692. }
  693. return strings
  694. }
  695. var warningLimiters = make(map[protocol.DeviceID]*rate.Limiter)
  696. var warningLimitersMut = sync.NewMutex()
  697. func warningFor(dev protocol.DeviceID, msg string) {
  698. warningLimitersMut.Lock()
  699. defer warningLimitersMut.Unlock()
  700. lim, ok := warningLimiters[dev]
  701. if !ok {
  702. lim = rate.NewLimiter(rate.Every(perDeviceWarningIntv), 1)
  703. warningLimiters[dev] = lim
  704. }
  705. if lim.Allow() {
  706. l.Warnln(msg)
  707. }
  708. }
  709. func tlsTimedHandshake(tc *tls.Conn) error {
  710. tc.SetDeadline(time.Now().Add(tlsHandshakeTimeout))
  711. defer tc.SetDeadline(time.Time{})
  712. return tc.Handshake()
  713. }
  714. // IsAllowedNetwork returns true if the given host (IP or resolvable
  715. // hostname) is in the set of allowed networks (CIDR format only).
  716. func IsAllowedNetwork(host string, allowed []string) bool {
  717. if hostNoPort, _, err := net.SplitHostPort(host); err == nil {
  718. host = hostNoPort
  719. }
  720. addr, err := net.ResolveIPAddr("ip", host)
  721. if err != nil {
  722. return false
  723. }
  724. for _, n := range allowed {
  725. result := true
  726. if strings.HasPrefix(n, "!") {
  727. result = false
  728. n = n[1:]
  729. }
  730. _, cidr, err := net.ParseCIDR(n)
  731. if err != nil {
  732. continue
  733. }
  734. if cidr.Contains(addr.IP) {
  735. return result
  736. }
  737. }
  738. return false
  739. }
  740. func (s *service) dialParallel(ctx context.Context, deviceID protocol.DeviceID, dialTargets []dialTarget) (internalConn, bool) {
  741. // Group targets into buckets by priority
  742. dialTargetBuckets := make(map[int][]dialTarget, len(dialTargets))
  743. for _, tgt := range dialTargets {
  744. dialTargetBuckets[tgt.priority] = append(dialTargetBuckets[tgt.priority], tgt)
  745. }
  746. // Get all available priorities
  747. priorities := make([]int, 0, len(dialTargetBuckets))
  748. for prio := range dialTargetBuckets {
  749. priorities = append(priorities, prio)
  750. }
  751. // Sort the priorities so that we dial lowest first (which means highest...)
  752. sort.Ints(priorities)
  753. for _, prio := range priorities {
  754. tgts := dialTargetBuckets[prio]
  755. res := make(chan internalConn, len(tgts))
  756. wg := stdsync.WaitGroup{}
  757. for _, tgt := range tgts {
  758. wg.Add(1)
  759. go func(tgt dialTarget) {
  760. conn, err := tgt.Dial(ctx)
  761. if err == nil {
  762. // Closes the connection on error
  763. err = s.validateIdentity(conn, deviceID)
  764. }
  765. s.setConnectionStatus(tgt.addr, err)
  766. if err != nil {
  767. l.Debugln("dialing", deviceID, tgt.uri, "error:", err)
  768. } else {
  769. l.Debugln("dialing", deviceID, tgt.uri, "success:", conn)
  770. res <- conn
  771. }
  772. wg.Done()
  773. }(tgt)
  774. }
  775. // Spawn a routine which will unblock main routine in case we fail
  776. // to connect to anyone.
  777. go func() {
  778. wg.Wait()
  779. close(res)
  780. }()
  781. // Wait for the first connection, or for channel closure.
  782. if conn, ok := <-res; ok {
  783. // Got a connection, means more might come back, hence spawn a
  784. // routine that will do the discarding.
  785. l.Debugln("connected to", deviceID, prio, "using", conn, conn.priority)
  786. go func(deviceID protocol.DeviceID, prio int) {
  787. wg.Wait()
  788. l.Debugln("discarding", len(res), "connections while connecting to", deviceID, prio)
  789. for conn := range res {
  790. conn.Close()
  791. }
  792. }(deviceID, prio)
  793. return conn, ok
  794. }
  795. // Failed to connect, report that fact.
  796. l.Debugln("failed to connect to", deviceID, prio)
  797. }
  798. return internalConn{}, false
  799. }
  800. func (s *service) validateIdentity(c internalConn, expectedID protocol.DeviceID) error {
  801. cs := c.ConnectionState()
  802. // We should have received exactly one certificate from the other
  803. // side. If we didn't, they don't have a device ID and we drop the
  804. // connection.
  805. certs := cs.PeerCertificates
  806. if cl := len(certs); cl != 1 {
  807. l.Infof("Got peer certificate list of length %d != 1 from peer at %s; protocol error", cl, c)
  808. c.Close()
  809. return fmt.Errorf("expected 1 certificate, got %d", cl)
  810. }
  811. remoteCert := certs[0]
  812. remoteID := protocol.NewDeviceID(remoteCert.Raw)
  813. // The device ID should not be that of ourselves. It can happen
  814. // though, especially in the presence of NAT hairpinning, multiple
  815. // clients between the same NAT gateway, and global discovery.
  816. if remoteID == s.myID {
  817. l.Infof("Connected to myself (%s) at %s - should not happen", remoteID, c)
  818. c.Close()
  819. return errors.New("connected to self")
  820. }
  821. // We should see the expected device ID
  822. if !remoteID.Equals(expectedID) {
  823. c.Close()
  824. return fmt.Errorf("unexpected device id, expected %s got %s", expectedID, remoteID)
  825. }
  826. return nil
  827. }