service.go 23 KB

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