service.go 27 KB

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