service.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  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. "time"
  14. "github.com/syncthing/syncthing/lib/config"
  15. "github.com/syncthing/syncthing/lib/discover"
  16. "github.com/syncthing/syncthing/lib/events"
  17. "github.com/syncthing/syncthing/lib/nat"
  18. "github.com/syncthing/syncthing/lib/protocol"
  19. "github.com/syncthing/syncthing/lib/sync"
  20. "github.com/syncthing/syncthing/lib/util"
  21. // Registers NAT service providers
  22. _ "github.com/syncthing/syncthing/lib/pmp"
  23. _ "github.com/syncthing/syncthing/lib/upnp"
  24. "github.com/thejerf/suture"
  25. "golang.org/x/time/rate"
  26. )
  27. var (
  28. dialers = make(map[string]dialerFactory, 0)
  29. listeners = make(map[string]listenerFactory, 0)
  30. )
  31. const (
  32. perDeviceWarningIntv = 15 * time.Minute
  33. tlsHandshakeTimeout = 10 * time.Second
  34. )
  35. // From go/src/crypto/tls/cipher_suites.go
  36. var tlsCipherSuiteNames = map[uint16]string{
  37. 0x0005: "TLS_RSA_WITH_RC4_128_SHA",
  38. 0x000a: "TLS_RSA_WITH_3DES_EDE_CBC_SHA",
  39. 0x002f: "TLS_RSA_WITH_AES_128_CBC_SHA",
  40. 0x0035: "TLS_RSA_WITH_AES_256_CBC_SHA",
  41. 0x003c: "TLS_RSA_WITH_AES_128_CBC_SHA256",
  42. 0x009c: "TLS_RSA_WITH_AES_128_GCM_SHA256",
  43. 0x009d: "TLS_RSA_WITH_AES_256_GCM_SHA384",
  44. 0xc007: "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA",
  45. 0xc009: "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA",
  46. 0xc00a: "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA",
  47. 0xc011: "TLS_ECDHE_RSA_WITH_RC4_128_SHA",
  48. 0xc012: "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA",
  49. 0xc013: "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",
  50. 0xc014: "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA",
  51. 0xc023: "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256",
  52. 0xc027: "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256",
  53. 0xc02f: "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
  54. 0xc02b: "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
  55. 0xc030: "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
  56. 0xc02c: "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
  57. 0xcca8: "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305",
  58. 0xcca9: "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305",
  59. }
  60. // Service listens and dials all configured unconnected devices, via supported
  61. // dialers. Successful connections are handed to the model.
  62. type Service struct {
  63. *suture.Supervisor
  64. cfg *config.Wrapper
  65. myID protocol.DeviceID
  66. model Model
  67. tlsCfg *tls.Config
  68. discoverer discover.Finder
  69. conns chan internalConn
  70. bepProtocolName string
  71. tlsDefaultCommonName string
  72. lans []*net.IPNet
  73. limiter *limiter
  74. natService *nat.Service
  75. natServiceToken *suture.ServiceToken
  76. listenersMut sync.RWMutex
  77. listeners map[string]genericListener
  78. listenerTokens map[string]suture.ServiceToken
  79. listenerSupervisor *suture.Supervisor
  80. curConMut sync.Mutex
  81. currentConnection map[protocol.DeviceID]completeConn
  82. }
  83. func NewService(cfg *config.Wrapper, myID protocol.DeviceID, mdl Model, tlsCfg *tls.Config, discoverer discover.Finder,
  84. bepProtocolName string, tlsDefaultCommonName string, lans []*net.IPNet) *Service {
  85. service := &Service{
  86. Supervisor: suture.New("connections.Service", suture.Spec{
  87. Log: func(line string) {
  88. l.Infoln(line)
  89. },
  90. }),
  91. cfg: cfg,
  92. myID: myID,
  93. model: mdl,
  94. tlsCfg: tlsCfg,
  95. discoverer: discoverer,
  96. conns: make(chan internalConn),
  97. bepProtocolName: bepProtocolName,
  98. tlsDefaultCommonName: tlsDefaultCommonName,
  99. lans: lans,
  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. // There are several moving parts here; one routine per listening address
  121. // (handled in configuration changing) to handle incoming connections,
  122. // one routine to periodically attempt outgoing connections, one routine to
  123. // the common handling regardless of whether the connection was
  124. // incoming or outgoing.
  125. service.Add(serviceFunc(service.connect))
  126. service.Add(serviceFunc(service.handle))
  127. service.Add(service.listenerSupervisor)
  128. raw := cfg.RawCopy()
  129. // Actually starts the listeners and NAT service
  130. service.CommitConfiguration(raw, raw)
  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 the this one.
  200. connected := s.model.ConnectedTo(remoteID)
  201. s.curConMut.Lock()
  202. ct, ok := s.currentConnection[remoteID]
  203. s.curConMut.Unlock()
  204. priorityKnown := ok && connected
  205. // Lower priority is better, just like nice etc.
  206. if priorityKnown && ct.internalConn.priority > c.priority {
  207. l.Debugln("Switching connections", remoteID)
  208. } else if connected {
  209. // We should not already be connected to the other party. TODO: This
  210. // could use some better handling. If the old connection is dead but
  211. // hasn't timed out yet we may want to drop *that* connection and keep
  212. // this one. But in case we are two devices connecting to each other
  213. // in parallel we don't want to do that or we end up with no
  214. // connections still established...
  215. l.Infof("Connected to already connected device (%s)", remoteID)
  216. c.Close()
  217. continue
  218. }
  219. deviceCfg, ok := s.cfg.Device(remoteID)
  220. if !ok {
  221. panic("bug: unknown device should already have been rejected")
  222. }
  223. // Verify the name on the certificate. By default we set it to
  224. // "syncthing" when generating, but the user may have replaced
  225. // the certificate and used another name.
  226. certName := deviceCfg.CertName
  227. if certName == "" {
  228. certName = s.tlsDefaultCommonName
  229. }
  230. if err := remoteCert.VerifyHostname(certName); err != nil {
  231. // Incorrect certificate name is something the user most
  232. // likely wants to know about, since it's an advanced
  233. // config. Warn instead of Info.
  234. l.Warnf("Bad certificate from %s (%v): %v", remoteID, c.RemoteAddr(), err)
  235. c.Close()
  236. continue next
  237. }
  238. // Wrap the connection in rate limiters. The limiter itself will
  239. // keep up with config changes to the rate and whether or not LAN
  240. // connections are limited.
  241. isLAN := s.isLAN(c.RemoteAddr())
  242. wr := s.limiter.newWriteLimiter(c, isLAN)
  243. rd := s.limiter.newReadLimiter(c, isLAN)
  244. name := fmt.Sprintf("%s-%s (%s)", c.LocalAddr(), c.RemoteAddr(), c.Type())
  245. protoConn := protocol.NewConnection(remoteID, rd, wr, s.model, name, deviceCfg.Compression)
  246. modelConn := completeConn{c, protoConn}
  247. l.Infof("Established secure connection to %s at %s (%s)", remoteID, name, tlsCipherSuiteNames[c.ConnectionState().CipherSuite])
  248. s.model.AddConnection(modelConn, hello)
  249. s.curConMut.Lock()
  250. s.currentConnection[remoteID] = modelConn
  251. s.curConMut.Unlock()
  252. continue next
  253. }
  254. }
  255. func (s *Service) connect() {
  256. nextDial := make(map[string]time.Time)
  257. // Used as delay for the first few connection attempts, increases
  258. // exponentially
  259. initialRampup := time.Second
  260. // Calculated from actual dialers reconnectInterval
  261. var sleep time.Duration
  262. for {
  263. cfg := s.cfg.RawCopy()
  264. bestDialerPrio := 1<<31 - 1 // worse prio won't build on 32 bit
  265. for _, df := range dialers {
  266. if !df.Enabled(cfg) {
  267. continue
  268. }
  269. if prio := df.Priority(); prio < bestDialerPrio {
  270. bestDialerPrio = prio
  271. }
  272. }
  273. l.Debugln("Reconnect loop")
  274. now := time.Now()
  275. var seen []string
  276. nextDevice:
  277. for _, deviceCfg := range cfg.Devices {
  278. deviceID := deviceCfg.DeviceID
  279. if deviceID == s.myID {
  280. continue
  281. }
  282. if deviceCfg.Paused {
  283. continue
  284. }
  285. connected := s.model.ConnectedTo(deviceID)
  286. s.curConMut.Lock()
  287. ct, ok := s.currentConnection[deviceID]
  288. s.curConMut.Unlock()
  289. priorityKnown := ok && connected
  290. if priorityKnown && ct.internalConn.priority == bestDialerPrio {
  291. // Things are already as good as they can get.
  292. continue
  293. }
  294. l.Debugln("Reconnect loop for", deviceID)
  295. var addrs []string
  296. for _, addr := range deviceCfg.Addresses {
  297. if addr == "dynamic" {
  298. if s.discoverer != nil {
  299. if t, err := s.discoverer.Lookup(deviceID); err == nil {
  300. addrs = append(addrs, t...)
  301. }
  302. }
  303. } else {
  304. addrs = append(addrs, addr)
  305. }
  306. }
  307. seen = append(seen, addrs...)
  308. for _, addr := range addrs {
  309. nextDialAt, ok := nextDial[addr]
  310. if ok && initialRampup >= sleep && nextDialAt.After(now) {
  311. l.Debugf("Not dialing %v as sleep is %v, next dial is at %s and current time is %s", addr, sleep, nextDialAt, now)
  312. continue
  313. }
  314. // If we fail at any step before actually getting the dialer
  315. // retry in a minute
  316. nextDial[addr] = now.Add(time.Minute)
  317. uri, err := url.Parse(addr)
  318. if err != nil {
  319. l.Infof("Dialer for %s: %v", addr, err)
  320. continue
  321. }
  322. dialerFactory, err := s.getDialerFactory(cfg, uri)
  323. if err == errDisabled {
  324. l.Debugln("Dialer for", uri, "is disabled")
  325. continue
  326. }
  327. if err != nil {
  328. l.Infof("Dialer for %v: %v", uri, err)
  329. continue
  330. }
  331. if priorityKnown && dialerFactory.Priority() >= ct.internalConn.priority {
  332. l.Debugf("Not dialing using %s as priority is less than current connection (%d >= %d)", dialerFactory, dialerFactory.Priority(), ct.internalConn.priority)
  333. continue
  334. }
  335. dialer := dialerFactory.New(s.cfg, s.tlsCfg)
  336. l.Debugln("dial", deviceCfg.DeviceID, uri)
  337. nextDial[addr] = now.Add(dialer.RedialFrequency())
  338. conn, err := dialer.Dial(deviceID, uri)
  339. if err != nil {
  340. l.Debugln("dial failed", deviceCfg.DeviceID, uri, err)
  341. continue
  342. }
  343. s.conns <- conn
  344. continue nextDevice
  345. }
  346. }
  347. nextDial, sleep = filterAndFindSleepDuration(nextDial, seen, now)
  348. if initialRampup < sleep {
  349. l.Debugln("initial rampup; sleep", initialRampup, "and update to", initialRampup*2)
  350. time.Sleep(initialRampup)
  351. initialRampup *= 2
  352. } else {
  353. l.Debugln("sleep until next dial", sleep)
  354. time.Sleep(sleep)
  355. }
  356. }
  357. }
  358. func (s *Service) isLAN(addr net.Addr) bool {
  359. tcpaddr, ok := addr.(*net.TCPAddr)
  360. if !ok {
  361. return false
  362. }
  363. for _, lan := range s.lans {
  364. if lan.Contains(tcpaddr.IP) {
  365. return true
  366. }
  367. }
  368. return tcpaddr.IP.IsLoopback()
  369. }
  370. func (s *Service) createListener(factory listenerFactory, uri *url.URL) bool {
  371. // must be called with listenerMut held
  372. l.Debugln("Starting listener", uri)
  373. listener := factory.New(uri, s.cfg, s.tlsCfg, s.conns, s.natService)
  374. listener.OnAddressesChanged(s.logListenAddressesChangedEvent)
  375. s.listeners[uri.String()] = listener
  376. s.listenerTokens[uri.String()] = s.listenerSupervisor.Add(listener)
  377. return true
  378. }
  379. func (s *Service) logListenAddressesChangedEvent(l genericListener) {
  380. events.Default.Log(events.ListenAddressesChanged, map[string]interface{}{
  381. "address": l.URI(),
  382. "lan": l.LANAddresses(),
  383. "wan": l.WANAddresses(),
  384. })
  385. }
  386. func (s *Service) VerifyConfiguration(from, to config.Configuration) error {
  387. return nil
  388. }
  389. func (s *Service) CommitConfiguration(from, to config.Configuration) bool {
  390. newDevices := make(map[protocol.DeviceID]bool, len(to.Devices))
  391. for _, dev := range to.Devices {
  392. newDevices[dev.DeviceID] = true
  393. }
  394. for _, dev := range from.Devices {
  395. if !newDevices[dev.DeviceID] {
  396. s.curConMut.Lock()
  397. delete(s.currentConnection, dev.DeviceID)
  398. s.curConMut.Unlock()
  399. warningLimitersMut.Lock()
  400. delete(warningLimiters, dev.DeviceID)
  401. warningLimitersMut.Unlock()
  402. }
  403. }
  404. s.listenersMut.Lock()
  405. seen := make(map[string]struct{})
  406. for _, addr := range config.Wrap("", to).ListenAddresses() {
  407. if _, ok := s.listeners[addr]; ok {
  408. seen[addr] = struct{}{}
  409. continue
  410. }
  411. uri, err := url.Parse(addr)
  412. if err != nil {
  413. l.Infof("Listener for %s: %v", addr, err)
  414. continue
  415. }
  416. factory, err := s.getListenerFactory(to, uri)
  417. if err == errDisabled {
  418. l.Debugln("Listener for", uri, "is disabled")
  419. continue
  420. }
  421. if err != nil {
  422. l.Infof("Listener for %v: %v", uri, err)
  423. continue
  424. }
  425. s.createListener(factory, uri)
  426. seen[addr] = struct{}{}
  427. }
  428. for addr, listener := range s.listeners {
  429. if _, ok := seen[addr]; !ok || !listener.Factory().Enabled(to) {
  430. l.Debugln("Stopping listener", addr)
  431. s.listenerSupervisor.Remove(s.listenerTokens[addr])
  432. delete(s.listenerTokens, addr)
  433. delete(s.listeners, addr)
  434. }
  435. }
  436. s.listenersMut.Unlock()
  437. if to.Options.NATEnabled && s.natServiceToken == nil {
  438. l.Debugln("Starting NAT service")
  439. token := s.Add(s.natService)
  440. s.natServiceToken = &token
  441. } else if !to.Options.NATEnabled && s.natServiceToken != nil {
  442. l.Debugln("Stopping NAT service")
  443. s.Remove(*s.natServiceToken)
  444. s.natServiceToken = nil
  445. }
  446. return true
  447. }
  448. func (s *Service) AllAddresses() []string {
  449. s.listenersMut.RLock()
  450. var addrs []string
  451. for _, listener := range s.listeners {
  452. for _, lanAddr := range listener.LANAddresses() {
  453. addrs = append(addrs, lanAddr.String())
  454. }
  455. for _, wanAddr := range listener.WANAddresses() {
  456. addrs = append(addrs, wanAddr.String())
  457. }
  458. }
  459. s.listenersMut.RUnlock()
  460. return util.UniqueStrings(addrs)
  461. }
  462. func (s *Service) ExternalAddresses() []string {
  463. s.listenersMut.RLock()
  464. var addrs []string
  465. for _, listener := range s.listeners {
  466. for _, wanAddr := range listener.WANAddresses() {
  467. addrs = append(addrs, wanAddr.String())
  468. }
  469. }
  470. s.listenersMut.RUnlock()
  471. return util.UniqueStrings(addrs)
  472. }
  473. func (s *Service) Status() map[string]interface{} {
  474. s.listenersMut.RLock()
  475. result := make(map[string]interface{})
  476. for addr, listener := range s.listeners {
  477. status := make(map[string]interface{})
  478. err := listener.Error()
  479. if err != nil {
  480. status["error"] = err.Error()
  481. }
  482. status["lanAddresses"] = urlsToStrings(listener.LANAddresses())
  483. status["wanAddresses"] = urlsToStrings(listener.WANAddresses())
  484. result[addr] = status
  485. }
  486. s.listenersMut.RUnlock()
  487. return result
  488. }
  489. func (s *Service) getDialerFactory(cfg config.Configuration, uri *url.URL) (dialerFactory, error) {
  490. dialerFactory, ok := dialers[uri.Scheme]
  491. if !ok {
  492. return nil, fmt.Errorf("unknown address scheme %q", uri.Scheme)
  493. }
  494. if !dialerFactory.Enabled(cfg) {
  495. return nil, errDisabled
  496. }
  497. return dialerFactory, nil
  498. }
  499. func (s *Service) getListenerFactory(cfg config.Configuration, uri *url.URL) (listenerFactory, error) {
  500. listenerFactory, ok := listeners[uri.Scheme]
  501. if !ok {
  502. return nil, fmt.Errorf("unknown address scheme %q", uri.Scheme)
  503. }
  504. if !listenerFactory.Enabled(cfg) {
  505. return nil, errDisabled
  506. }
  507. return listenerFactory, nil
  508. }
  509. func filterAndFindSleepDuration(nextDial map[string]time.Time, seen []string, now time.Time) (map[string]time.Time, time.Duration) {
  510. newNextDial := make(map[string]time.Time)
  511. for _, addr := range seen {
  512. nextDialAt, ok := nextDial[addr]
  513. if ok {
  514. newNextDial[addr] = nextDialAt
  515. }
  516. }
  517. min := time.Minute
  518. for _, next := range newNextDial {
  519. cur := next.Sub(now)
  520. if cur < min {
  521. min = cur
  522. }
  523. }
  524. return newNextDial, min
  525. }
  526. func urlsToStrings(urls []*url.URL) []string {
  527. strings := make([]string, len(urls))
  528. for i, url := range urls {
  529. strings[i] = url.String()
  530. }
  531. return strings
  532. }
  533. var warningLimiters = make(map[protocol.DeviceID]*rate.Limiter)
  534. var warningLimitersMut = sync.NewMutex()
  535. func warningFor(dev protocol.DeviceID, msg string) {
  536. warningLimitersMut.Lock()
  537. defer warningLimitersMut.Unlock()
  538. lim, ok := warningLimiters[dev]
  539. if !ok {
  540. lim = rate.NewLimiter(rate.Every(perDeviceWarningIntv), 1)
  541. warningLimiters[dev] = lim
  542. }
  543. if lim.Allow() {
  544. l.Warnln(msg)
  545. }
  546. }
  547. func tlsTimedHandshake(tc *tls.Conn) error {
  548. tc.SetDeadline(time.Now().Add(tlsHandshakeTimeout))
  549. defer tc.SetDeadline(time.Time{})
  550. return tc.Handshake()
  551. }