service.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798
  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 at %s did not negotiate bep/1.0", c)
  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 peer at %s; protocol error", cl, c)
  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) at %s - should not happen", remoteID, c)
  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 at %s: %s", remoteID, c, 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 at %s: %v", remoteID, c, 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. protoConn := protocol.NewConnection(remoteID, rd, wr, s.model, c.String(), deviceCfg.Compression)
  241. modelConn := completeConn{c, protoConn}
  242. l.Infof("Established secure connection to %s at %s (%s)", remoteID, c, tlsCipherSuiteNames[c.ConnectionState().CipherSuite])
  243. s.model.AddConnection(modelConn, hello)
  244. continue next
  245. }
  246. }
  247. func (s *Service) connect() {
  248. nextDial := make(map[string]time.Time)
  249. // Used as delay for the first few connection attempts, increases
  250. // exponentially
  251. initialRampup := time.Second
  252. // Calculated from actual dialers reconnectInterval
  253. var sleep time.Duration
  254. for {
  255. cfg := s.cfg.RawCopy()
  256. bestDialerPrio := 1<<31 - 1 // worse prio won't build on 32 bit
  257. for _, df := range dialers {
  258. if !df.Enabled(cfg) {
  259. continue
  260. }
  261. if prio := df.Priority(); prio < bestDialerPrio {
  262. bestDialerPrio = prio
  263. }
  264. }
  265. l.Debugln("Reconnect loop")
  266. now := time.Now()
  267. var seen []string
  268. for _, deviceCfg := range cfg.Devices {
  269. deviceID := deviceCfg.DeviceID
  270. if deviceID == s.myID {
  271. continue
  272. }
  273. if deviceCfg.Paused {
  274. continue
  275. }
  276. ct, connected := s.model.Connection(deviceID)
  277. if connected && ct.Priority() == bestDialerPrio {
  278. // Things are already as good as they can get.
  279. continue
  280. }
  281. var addrs []string
  282. for _, addr := range deviceCfg.Addresses {
  283. if addr == "dynamic" {
  284. if s.discoverer != nil {
  285. if t, err := s.discoverer.Lookup(deviceID); err == nil {
  286. addrs = append(addrs, t...)
  287. }
  288. }
  289. } else {
  290. addrs = append(addrs, addr)
  291. }
  292. }
  293. addrs = util.UniqueStrings(addrs)
  294. l.Debugln("Reconnect loop for", deviceID, addrs)
  295. seen = append(seen, addrs...)
  296. dialTargets := make([]dialTarget, 0)
  297. for _, addr := range addrs {
  298. nextDialAt, ok := nextDial[addr]
  299. if ok && initialRampup >= sleep && nextDialAt.After(now) {
  300. l.Debugf("Not dialing %v as sleep is %v, next dial is at %s and current time is %s", addr, sleep, nextDialAt, now)
  301. continue
  302. }
  303. // If we fail at any step before actually getting the dialer
  304. // retry in a minute
  305. nextDial[addr] = now.Add(time.Minute)
  306. uri, err := url.Parse(addr)
  307. if err != nil {
  308. l.Infof("Parsing dialer address %s: %v", addr, err)
  309. continue
  310. }
  311. if len(deviceCfg.AllowedNetworks) > 0 {
  312. if !IsAllowedNetwork(uri.Host, deviceCfg.AllowedNetworks) {
  313. l.Debugln("Network for", uri, "is disallowed")
  314. continue
  315. }
  316. }
  317. dialerFactory, err := s.getDialerFactory(cfg, uri)
  318. if err == errDisabled {
  319. l.Debugln(dialerFactory, "for", uri, "is disabled")
  320. continue
  321. }
  322. if err != nil {
  323. l.Infof("%v for %v: %v", dialerFactory, uri, err)
  324. continue
  325. }
  326. priority := dialerFactory.Priority()
  327. if connected && priority >= ct.Priority() {
  328. l.Debugf("Not dialing using %s as priority is less than current connection (%d >= %d)", dialerFactory, dialerFactory.Priority(), ct.Priority())
  329. continue
  330. }
  331. dialer := dialerFactory.New(s.cfg, s.tlsCfg)
  332. nextDial[addr] = now.Add(dialer.RedialFrequency())
  333. // For LAN addresses, increase the priority so that we
  334. // try these first.
  335. switch {
  336. case dialerFactory.AlwaysWAN():
  337. // Do nothing.
  338. case s.isLANHost(uri.Host):
  339. priority -= 1
  340. }
  341. dialTargets = append(dialTargets, dialTarget{
  342. dialer: dialer,
  343. priority: priority,
  344. deviceID: deviceID,
  345. uri: uri,
  346. })
  347. }
  348. conn, ok := dialParallel(deviceCfg.DeviceID, dialTargets)
  349. if ok {
  350. s.conns <- conn
  351. }
  352. }
  353. nextDial, sleep = filterAndFindSleepDuration(nextDial, seen, now)
  354. if initialRampup < sleep {
  355. l.Debugln("initial rampup; sleep", initialRampup, "and update to", initialRampup*2)
  356. time.Sleep(initialRampup)
  357. initialRampup *= 2
  358. } else {
  359. l.Debugln("sleep until next dial", sleep)
  360. time.Sleep(sleep)
  361. }
  362. }
  363. }
  364. func (s *Service) isLANHost(host string) bool {
  365. // Probably we are called with an ip:port combo which we can resolve as
  366. // a TCP address.
  367. if addr, err := net.ResolveTCPAddr("tcp", host); err == nil {
  368. return s.isLAN(addr)
  369. }
  370. // ... but this function looks general enough that someone might try
  371. // with just an IP as well in the future so lets allow that.
  372. if addr, err := net.ResolveIPAddr("ip", host); err == nil {
  373. return s.isLAN(addr)
  374. }
  375. return false
  376. }
  377. func (s *Service) isLAN(addr net.Addr) bool {
  378. var ip net.IP
  379. switch addr := addr.(type) {
  380. case *net.IPAddr:
  381. ip = addr.IP
  382. case *net.TCPAddr:
  383. ip = addr.IP
  384. case *net.UDPAddr:
  385. ip = addr.IP
  386. default:
  387. // From the standard library, just Unix sockets.
  388. // If you invent your own, handle it.
  389. return false
  390. }
  391. if ip.IsLoopback() {
  392. return true
  393. }
  394. for _, lan := range s.cfg.Options().AlwaysLocalNets {
  395. _, ipnet, err := net.ParseCIDR(lan)
  396. if err != nil {
  397. l.Debugln("Network", lan, "is malformed:", err)
  398. continue
  399. }
  400. if ipnet.Contains(ip) {
  401. return true
  402. }
  403. }
  404. lans, _ := osutil.GetLans()
  405. for _, lan := range lans {
  406. if lan.Contains(ip) {
  407. return true
  408. }
  409. }
  410. return false
  411. }
  412. func (s *Service) createListener(factory listenerFactory, uri *url.URL) bool {
  413. // must be called with listenerMut held
  414. l.Debugln("Starting listener", uri)
  415. listener := factory.New(uri, s.cfg, s.tlsCfg, s.conns, s.natService)
  416. listener.OnAddressesChanged(s.logListenAddressesChangedEvent)
  417. s.listeners[uri.String()] = listener
  418. s.listenerTokens[uri.String()] = s.listenerSupervisor.Add(listener)
  419. return true
  420. }
  421. func (s *Service) logListenAddressesChangedEvent(l genericListener) {
  422. events.Default.Log(events.ListenAddressesChanged, map[string]interface{}{
  423. "address": l.URI(),
  424. "lan": l.LANAddresses(),
  425. "wan": l.WANAddresses(),
  426. })
  427. }
  428. func (s *Service) VerifyConfiguration(from, to config.Configuration) error {
  429. return nil
  430. }
  431. func (s *Service) CommitConfiguration(from, to config.Configuration) bool {
  432. newDevices := make(map[protocol.DeviceID]bool, len(to.Devices))
  433. for _, dev := range to.Devices {
  434. newDevices[dev.DeviceID] = true
  435. }
  436. for _, dev := range from.Devices {
  437. if !newDevices[dev.DeviceID] {
  438. warningLimitersMut.Lock()
  439. delete(warningLimiters, dev.DeviceID)
  440. warningLimitersMut.Unlock()
  441. }
  442. }
  443. s.listenersMut.Lock()
  444. seen := make(map[string]struct{})
  445. for _, addr := range config.Wrap("", to).ListenAddresses() {
  446. if addr == "" {
  447. // We can get an empty address if there is an empty listener
  448. // element in the config, indicating no listeners should be
  449. // used. This is not an error.
  450. continue
  451. }
  452. if _, ok := s.listeners[addr]; ok {
  453. seen[addr] = struct{}{}
  454. continue
  455. }
  456. uri, err := url.Parse(addr)
  457. if err != nil {
  458. l.Infof("Parsing listener address %s: %v", addr, err)
  459. continue
  460. }
  461. factory, err := s.getListenerFactory(to, uri)
  462. if err == errDisabled {
  463. l.Debugln("Listener for", uri, "is disabled")
  464. continue
  465. }
  466. if err != nil {
  467. l.Infof("Getting listener factory for %v: %v", uri, err)
  468. continue
  469. }
  470. s.createListener(factory, uri)
  471. seen[addr] = struct{}{}
  472. }
  473. for addr, listener := range s.listeners {
  474. if _, ok := seen[addr]; !ok || !listener.Factory().Enabled(to) {
  475. l.Debugln("Stopping listener", addr)
  476. s.listenerSupervisor.Remove(s.listenerTokens[addr])
  477. delete(s.listenerTokens, addr)
  478. delete(s.listeners, addr)
  479. }
  480. }
  481. s.listenersMut.Unlock()
  482. if to.Options.NATEnabled && s.natServiceToken == nil {
  483. l.Debugln("Starting NAT service")
  484. token := s.Add(s.natService)
  485. s.natServiceToken = &token
  486. } else if !to.Options.NATEnabled && s.natServiceToken != nil {
  487. l.Debugln("Stopping NAT service")
  488. s.Remove(*s.natServiceToken)
  489. s.natServiceToken = nil
  490. }
  491. return true
  492. }
  493. func (s *Service) AllAddresses() []string {
  494. s.listenersMut.RLock()
  495. var addrs []string
  496. for _, listener := range s.listeners {
  497. for _, lanAddr := range listener.LANAddresses() {
  498. addrs = append(addrs, lanAddr.String())
  499. }
  500. for _, wanAddr := range listener.WANAddresses() {
  501. addrs = append(addrs, wanAddr.String())
  502. }
  503. }
  504. s.listenersMut.RUnlock()
  505. return util.UniqueStrings(addrs)
  506. }
  507. func (s *Service) ExternalAddresses() []string {
  508. s.listenersMut.RLock()
  509. var addrs []string
  510. for _, listener := range s.listeners {
  511. for _, wanAddr := range listener.WANAddresses() {
  512. addrs = append(addrs, wanAddr.String())
  513. }
  514. }
  515. s.listenersMut.RUnlock()
  516. return util.UniqueStrings(addrs)
  517. }
  518. func (s *Service) Status() map[string]interface{} {
  519. s.listenersMut.RLock()
  520. result := make(map[string]interface{})
  521. for addr, listener := range s.listeners {
  522. status := make(map[string]interface{})
  523. err := listener.Error()
  524. if err != nil {
  525. status["error"] = err.Error()
  526. }
  527. status["lanAddresses"] = urlsToStrings(listener.LANAddresses())
  528. status["wanAddresses"] = urlsToStrings(listener.WANAddresses())
  529. result[addr] = status
  530. }
  531. s.listenersMut.RUnlock()
  532. return result
  533. }
  534. func (s *Service) NATType() string {
  535. s.listenersMut.RLock()
  536. defer s.listenersMut.RUnlock()
  537. for _, listener := range s.listeners {
  538. natType := listener.NATType()
  539. if natType != "unknown" {
  540. return natType
  541. }
  542. }
  543. return "unknown"
  544. }
  545. func (s *Service) getDialerFactory(cfg config.Configuration, uri *url.URL) (dialerFactory, error) {
  546. dialerFactory, ok := dialers[uri.Scheme]
  547. if !ok {
  548. return nil, fmt.Errorf("unknown address scheme %q", uri.Scheme)
  549. }
  550. if !dialerFactory.Enabled(cfg) {
  551. return nil, errDisabled
  552. }
  553. return dialerFactory, nil
  554. }
  555. func (s *Service) getListenerFactory(cfg config.Configuration, uri *url.URL) (listenerFactory, error) {
  556. listenerFactory, ok := listeners[uri.Scheme]
  557. if !ok {
  558. return nil, fmt.Errorf("unknown address scheme %q", uri.Scheme)
  559. }
  560. if !listenerFactory.Enabled(cfg) {
  561. return nil, errDisabled
  562. }
  563. return listenerFactory, nil
  564. }
  565. func filterAndFindSleepDuration(nextDial map[string]time.Time, seen []string, now time.Time) (map[string]time.Time, time.Duration) {
  566. newNextDial := make(map[string]time.Time)
  567. for _, addr := range seen {
  568. nextDialAt, ok := nextDial[addr]
  569. if ok {
  570. newNextDial[addr] = nextDialAt
  571. }
  572. }
  573. min := time.Minute
  574. for _, next := range newNextDial {
  575. cur := next.Sub(now)
  576. if cur < min {
  577. min = cur
  578. }
  579. }
  580. return newNextDial, min
  581. }
  582. func urlsToStrings(urls []*url.URL) []string {
  583. strings := make([]string, len(urls))
  584. for i, url := range urls {
  585. strings[i] = url.String()
  586. }
  587. return strings
  588. }
  589. var warningLimiters = make(map[protocol.DeviceID]*rate.Limiter)
  590. var warningLimitersMut = sync.NewMutex()
  591. func warningFor(dev protocol.DeviceID, msg string) {
  592. warningLimitersMut.Lock()
  593. defer warningLimitersMut.Unlock()
  594. lim, ok := warningLimiters[dev]
  595. if !ok {
  596. lim = rate.NewLimiter(rate.Every(perDeviceWarningIntv), 1)
  597. warningLimiters[dev] = lim
  598. }
  599. if lim.Allow() {
  600. l.Warnln(msg)
  601. }
  602. }
  603. func tlsTimedHandshake(tc *tls.Conn) error {
  604. tc.SetDeadline(time.Now().Add(tlsHandshakeTimeout))
  605. defer tc.SetDeadline(time.Time{})
  606. return tc.Handshake()
  607. }
  608. // IsAllowedNetwork returns true if the given host (IP or resolvable
  609. // hostname) is in the set of allowed networks (CIDR format only).
  610. func IsAllowedNetwork(host string, allowed []string) bool {
  611. if hostNoPort, _, err := net.SplitHostPort(host); err == nil {
  612. host = hostNoPort
  613. }
  614. addr, err := net.ResolveIPAddr("ip", host)
  615. if err != nil {
  616. return false
  617. }
  618. for _, n := range allowed {
  619. result := true
  620. if strings.HasPrefix(n, "!") {
  621. result = false
  622. n = n[1:]
  623. }
  624. _, cidr, err := net.ParseCIDR(n)
  625. if err != nil {
  626. continue
  627. }
  628. if cidr.Contains(addr.IP) {
  629. return result
  630. }
  631. }
  632. return false
  633. }
  634. func dialParallel(deviceID protocol.DeviceID, dialTargets []dialTarget) (internalConn, bool) {
  635. // Group targets into buckets by priority
  636. dialTargetBuckets := make(map[int][]dialTarget, len(dialTargets))
  637. for _, tgt := range dialTargets {
  638. dialTargetBuckets[tgt.priority] = append(dialTargetBuckets[tgt.priority], tgt)
  639. }
  640. // Get all available priorities
  641. priorities := make([]int, 0, len(dialTargetBuckets))
  642. for prio := range dialTargetBuckets {
  643. priorities = append(priorities, prio)
  644. }
  645. // Sort the priorities so that we dial lowest first (which means highest...)
  646. sort.Ints(priorities)
  647. for _, prio := range priorities {
  648. tgts := dialTargetBuckets[prio]
  649. res := make(chan internalConn, len(tgts))
  650. wg := stdsync.WaitGroup{}
  651. for _, tgt := range tgts {
  652. wg.Add(1)
  653. go func(tgt dialTarget) {
  654. conn, err := tgt.Dial()
  655. if err == nil {
  656. res <- conn
  657. }
  658. wg.Done()
  659. }(tgt)
  660. }
  661. // Spawn a routine which will unblock main routine in case we fail
  662. // to connect to anyone.
  663. go func() {
  664. wg.Wait()
  665. close(res)
  666. }()
  667. // Wait for the first connection, or for channel closure.
  668. if conn, ok := <-res; ok {
  669. // Got a connection, means more might come back, hence spawn a
  670. // routine that will do the discarding.
  671. l.Debugln("connected to", deviceID, prio, "using", conn, conn.priority)
  672. go func(deviceID protocol.DeviceID, prio int) {
  673. wg.Wait()
  674. l.Debugln("discarding", len(res), "connections while connecting to", deviceID, prio)
  675. for conn := range res {
  676. conn.Close()
  677. }
  678. }(deviceID, prio)
  679. return conn, ok
  680. }
  681. // Failed to connect, report that fact.
  682. l.Debugln("failed to connect to", deviceID, prio)
  683. }
  684. return internalConn{}, false
  685. }