service.go 26 KB

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