service.go 20 KB

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