service.go 20 KB

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