service.go 27 KB

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