service.go 22 KB

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