service.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  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. "time"
  16. "github.com/syncthing/syncthing/lib/config"
  17. "github.com/syncthing/syncthing/lib/discover"
  18. "github.com/syncthing/syncthing/lib/events"
  19. "github.com/syncthing/syncthing/lib/nat"
  20. "github.com/syncthing/syncthing/lib/osutil"
  21. "github.com/syncthing/syncthing/lib/protocol"
  22. "github.com/syncthing/syncthing/lib/sync"
  23. "github.com/syncthing/syncthing/lib/util"
  24. // Registers NAT service providers
  25. _ "github.com/syncthing/syncthing/lib/pmp"
  26. _ "github.com/syncthing/syncthing/lib/upnp"
  27. "github.com/thejerf/suture"
  28. "golang.org/x/time/rate"
  29. )
  30. var (
  31. dialers = make(map[string]dialerFactory, 0)
  32. listeners = make(map[string]listenerFactory, 0)
  33. )
  34. const (
  35. perDeviceWarningIntv = 15 * time.Minute
  36. tlsHandshakeTimeout = 10 * time.Second
  37. )
  38. // From go/src/crypto/tls/cipher_suites.go
  39. var tlsCipherSuiteNames = map[uint16]string{
  40. 0x0005: "TLS_RSA_WITH_RC4_128_SHA",
  41. 0x000a: "TLS_RSA_WITH_3DES_EDE_CBC_SHA",
  42. 0x002f: "TLS_RSA_WITH_AES_128_CBC_SHA",
  43. 0x0035: "TLS_RSA_WITH_AES_256_CBC_SHA",
  44. 0x003c: "TLS_RSA_WITH_AES_128_CBC_SHA256",
  45. 0x009c: "TLS_RSA_WITH_AES_128_GCM_SHA256",
  46. 0x009d: "TLS_RSA_WITH_AES_256_GCM_SHA384",
  47. 0xc007: "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA",
  48. 0xc009: "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA",
  49. 0xc00a: "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA",
  50. 0xc011: "TLS_ECDHE_RSA_WITH_RC4_128_SHA",
  51. 0xc012: "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA",
  52. 0xc013: "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",
  53. 0xc014: "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA",
  54. 0xc023: "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256",
  55. 0xc027: "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256",
  56. 0xc02f: "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
  57. 0xc02b: "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
  58. 0xc030: "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
  59. 0xc02c: "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
  60. 0xcca8: "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305",
  61. 0xcca9: "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305",
  62. }
  63. // Service listens and dials all configured unconnected devices, via supported
  64. // dialers. Successful connections are handed to the model.
  65. type Service struct {
  66. *suture.Supervisor
  67. cfg *config.Wrapper
  68. myID protocol.DeviceID
  69. model Model
  70. tlsCfg *tls.Config
  71. discoverer discover.Finder
  72. conns chan internalConn
  73. bepProtocolName string
  74. tlsDefaultCommonName string
  75. limiter *limiter
  76. natService *nat.Service
  77. natServiceToken *suture.ServiceToken
  78. listenersMut sync.RWMutex
  79. listeners map[string]genericListener
  80. listenerTokens map[string]suture.ServiceToken
  81. listenerSupervisor *suture.Supervisor
  82. curConMut sync.Mutex
  83. currentConnection map[protocol.DeviceID]completeConn
  84. }
  85. func NewService(cfg *config.Wrapper, myID protocol.DeviceID, mdl Model, tlsCfg *tls.Config, discoverer discover.Finder,
  86. bepProtocolName string, tlsDefaultCommonName string) *Service {
  87. service := &Service{
  88. Supervisor: suture.New("connections.Service", suture.Spec{
  89. Log: func(line string) {
  90. l.Infoln(line)
  91. },
  92. }),
  93. cfg: cfg,
  94. myID: myID,
  95. model: mdl,
  96. tlsCfg: tlsCfg,
  97. discoverer: discoverer,
  98. conns: make(chan internalConn),
  99. bepProtocolName: bepProtocolName,
  100. tlsDefaultCommonName: tlsDefaultCommonName,
  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. 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. dialTargets := make([]dialTarget, 0)
  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("Parsing dialer address %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(dialerFactory, "for", uri, "is disabled")
  334. continue
  335. }
  336. if err != nil {
  337. l.Infof("%v for %v: %v", dialerFactory, uri, err)
  338. continue
  339. }
  340. prio := dialerFactory.Priority()
  341. if priorityKnown && prio >= ct.internalConn.priority {
  342. l.Debugf("Not dialing using %s as priority is less than current connection (%d >= %d)", dialerFactory, dialerFactory.Priority(), ct.internalConn.priority)
  343. continue
  344. }
  345. dialer := dialerFactory.New(s.cfg, s.tlsCfg)
  346. nextDial[addr] = now.Add(dialer.RedialFrequency())
  347. dialTargets = append(dialTargets, dialTarget{
  348. dialer: dialer,
  349. priority: prio,
  350. deviceID: deviceID,
  351. uri: uri,
  352. })
  353. }
  354. conn, ok := dialParallel(deviceCfg.DeviceID, dialTargets)
  355. if ok {
  356. s.conns <- conn
  357. }
  358. }
  359. nextDial, sleep = filterAndFindSleepDuration(nextDial, seen, now)
  360. if initialRampup < sleep {
  361. l.Debugln("initial rampup; sleep", initialRampup, "and update to", initialRampup*2)
  362. time.Sleep(initialRampup)
  363. initialRampup *= 2
  364. } else {
  365. l.Debugln("sleep until next dial", sleep)
  366. time.Sleep(sleep)
  367. }
  368. }
  369. }
  370. func (s *Service) isLAN(addr net.Addr) bool {
  371. tcpaddr, ok := addr.(*net.TCPAddr)
  372. if !ok {
  373. return false
  374. }
  375. if tcpaddr.IP.IsLoopback() {
  376. return true
  377. }
  378. for _, lan := range s.cfg.Options().AlwaysLocalNets {
  379. _, ipnet, err := net.ParseCIDR(lan)
  380. if err != nil {
  381. l.Debugln("Network", lan, "is malformed:", err)
  382. continue
  383. }
  384. if ipnet.Contains(tcpaddr.IP) {
  385. return true
  386. }
  387. }
  388. lans, _ := osutil.GetLans()
  389. for _, lan := range lans {
  390. if lan.Contains(tcpaddr.IP) {
  391. return true
  392. }
  393. }
  394. return false
  395. }
  396. func (s *Service) createListener(factory listenerFactory, uri *url.URL) bool {
  397. // must be called with listenerMut held
  398. l.Debugln("Starting listener", uri)
  399. listener := factory.New(uri, s.cfg, s.tlsCfg, s.conns, s.natService)
  400. listener.OnAddressesChanged(s.logListenAddressesChangedEvent)
  401. s.listeners[uri.String()] = listener
  402. s.listenerTokens[uri.String()] = s.listenerSupervisor.Add(listener)
  403. return true
  404. }
  405. func (s *Service) logListenAddressesChangedEvent(l genericListener) {
  406. events.Default.Log(events.ListenAddressesChanged, map[string]interface{}{
  407. "address": l.URI(),
  408. "lan": l.LANAddresses(),
  409. "wan": l.WANAddresses(),
  410. })
  411. }
  412. func (s *Service) VerifyConfiguration(from, to config.Configuration) error {
  413. return nil
  414. }
  415. func (s *Service) CommitConfiguration(from, to config.Configuration) bool {
  416. newDevices := make(map[protocol.DeviceID]bool, len(to.Devices))
  417. for _, dev := range to.Devices {
  418. newDevices[dev.DeviceID] = true
  419. }
  420. for _, dev := range from.Devices {
  421. if !newDevices[dev.DeviceID] {
  422. s.curConMut.Lock()
  423. delete(s.currentConnection, dev.DeviceID)
  424. s.curConMut.Unlock()
  425. warningLimitersMut.Lock()
  426. delete(warningLimiters, dev.DeviceID)
  427. warningLimitersMut.Unlock()
  428. }
  429. }
  430. s.listenersMut.Lock()
  431. seen := make(map[string]struct{})
  432. for _, addr := range config.Wrap("", to).ListenAddresses() {
  433. if addr == "" {
  434. // We can get an empty address if there is an empty listener
  435. // element in the config, indicating no listeners should be
  436. // used. This is not an error.
  437. continue
  438. }
  439. if _, ok := s.listeners[addr]; ok {
  440. seen[addr] = struct{}{}
  441. continue
  442. }
  443. uri, err := url.Parse(addr)
  444. if err != nil {
  445. l.Infof("Parsing listener address %s: %v", addr, err)
  446. continue
  447. }
  448. factory, err := s.getListenerFactory(to, uri)
  449. if err == errDisabled {
  450. l.Debugln("Listener for", uri, "is disabled")
  451. continue
  452. }
  453. if err != nil {
  454. l.Infof("Getting listener factory for %v: %v", uri, err)
  455. continue
  456. }
  457. s.createListener(factory, uri)
  458. seen[addr] = struct{}{}
  459. }
  460. for addr, listener := range s.listeners {
  461. if _, ok := seen[addr]; !ok || !listener.Factory().Enabled(to) {
  462. l.Debugln("Stopping listener", addr)
  463. s.listenerSupervisor.Remove(s.listenerTokens[addr])
  464. delete(s.listenerTokens, addr)
  465. delete(s.listeners, addr)
  466. }
  467. }
  468. s.listenersMut.Unlock()
  469. if to.Options.NATEnabled && s.natServiceToken == nil {
  470. l.Debugln("Starting NAT service")
  471. token := s.Add(s.natService)
  472. s.natServiceToken = &token
  473. } else if !to.Options.NATEnabled && s.natServiceToken != nil {
  474. l.Debugln("Stopping NAT service")
  475. s.Remove(*s.natServiceToken)
  476. s.natServiceToken = nil
  477. }
  478. return true
  479. }
  480. func (s *Service) AllAddresses() []string {
  481. s.listenersMut.RLock()
  482. var addrs []string
  483. for _, listener := range s.listeners {
  484. for _, lanAddr := range listener.LANAddresses() {
  485. addrs = append(addrs, lanAddr.String())
  486. }
  487. for _, wanAddr := range listener.WANAddresses() {
  488. addrs = append(addrs, wanAddr.String())
  489. }
  490. }
  491. s.listenersMut.RUnlock()
  492. return util.UniqueStrings(addrs)
  493. }
  494. func (s *Service) ExternalAddresses() []string {
  495. s.listenersMut.RLock()
  496. var addrs []string
  497. for _, listener := range s.listeners {
  498. for _, wanAddr := range listener.WANAddresses() {
  499. addrs = append(addrs, wanAddr.String())
  500. }
  501. }
  502. s.listenersMut.RUnlock()
  503. return util.UniqueStrings(addrs)
  504. }
  505. func (s *Service) Status() map[string]interface{} {
  506. s.listenersMut.RLock()
  507. result := make(map[string]interface{})
  508. for addr, listener := range s.listeners {
  509. status := make(map[string]interface{})
  510. err := listener.Error()
  511. if err != nil {
  512. status["error"] = err.Error()
  513. }
  514. status["lanAddresses"] = urlsToStrings(listener.LANAddresses())
  515. status["wanAddresses"] = urlsToStrings(listener.WANAddresses())
  516. result[addr] = status
  517. }
  518. s.listenersMut.RUnlock()
  519. return result
  520. }
  521. func (s *Service) NATType() string {
  522. s.listenersMut.RLock()
  523. defer s.listenersMut.RUnlock()
  524. for _, listener := range s.listeners {
  525. natType := listener.NATType()
  526. if natType != "unknown" {
  527. return natType
  528. }
  529. }
  530. return "unknown"
  531. }
  532. func (s *Service) getDialerFactory(cfg config.Configuration, uri *url.URL) (dialerFactory, error) {
  533. dialerFactory, ok := dialers[uri.Scheme]
  534. if !ok {
  535. return nil, fmt.Errorf("unknown address scheme %q", uri.Scheme)
  536. }
  537. if !dialerFactory.Enabled(cfg) {
  538. return nil, errDisabled
  539. }
  540. return dialerFactory, nil
  541. }
  542. func (s *Service) getListenerFactory(cfg config.Configuration, uri *url.URL) (listenerFactory, error) {
  543. listenerFactory, ok := listeners[uri.Scheme]
  544. if !ok {
  545. return nil, fmt.Errorf("unknown address scheme %q", uri.Scheme)
  546. }
  547. if !listenerFactory.Enabled(cfg) {
  548. return nil, errDisabled
  549. }
  550. return listenerFactory, nil
  551. }
  552. func filterAndFindSleepDuration(nextDial map[string]time.Time, seen []string, now time.Time) (map[string]time.Time, time.Duration) {
  553. newNextDial := make(map[string]time.Time)
  554. for _, addr := range seen {
  555. nextDialAt, ok := nextDial[addr]
  556. if ok {
  557. newNextDial[addr] = nextDialAt
  558. }
  559. }
  560. min := time.Minute
  561. for _, next := range newNextDial {
  562. cur := next.Sub(now)
  563. if cur < min {
  564. min = cur
  565. }
  566. }
  567. return newNextDial, min
  568. }
  569. func urlsToStrings(urls []*url.URL) []string {
  570. strings := make([]string, len(urls))
  571. for i, url := range urls {
  572. strings[i] = url.String()
  573. }
  574. return strings
  575. }
  576. var warningLimiters = make(map[protocol.DeviceID]*rate.Limiter)
  577. var warningLimitersMut = sync.NewMutex()
  578. func warningFor(dev protocol.DeviceID, msg string) {
  579. warningLimitersMut.Lock()
  580. defer warningLimitersMut.Unlock()
  581. lim, ok := warningLimiters[dev]
  582. if !ok {
  583. lim = rate.NewLimiter(rate.Every(perDeviceWarningIntv), 1)
  584. warningLimiters[dev] = lim
  585. }
  586. if lim.Allow() {
  587. l.Warnln(msg)
  588. }
  589. }
  590. func tlsTimedHandshake(tc *tls.Conn) error {
  591. tc.SetDeadline(time.Now().Add(tlsHandshakeTimeout))
  592. defer tc.SetDeadline(time.Time{})
  593. return tc.Handshake()
  594. }
  595. // IsAllowedNetwork returns true if the given host (IP or resolvable
  596. // hostname) is in the set of allowed networks (CIDR format only).
  597. func IsAllowedNetwork(host string, allowed []string) bool {
  598. if hostNoPort, _, err := net.SplitHostPort(host); err == nil {
  599. host = hostNoPort
  600. }
  601. addr, err := net.ResolveIPAddr("ip", host)
  602. if err != nil {
  603. return false
  604. }
  605. for _, n := range allowed {
  606. result := true
  607. if strings.HasPrefix(n, "!") {
  608. result = false
  609. n = n[1:]
  610. }
  611. _, cidr, err := net.ParseCIDR(n)
  612. if err != nil {
  613. continue
  614. }
  615. if cidr.Contains(addr.IP) {
  616. return result
  617. }
  618. }
  619. return false
  620. }
  621. func dialParallel(deviceID protocol.DeviceID, dialTargets []dialTarget) (internalConn, bool) {
  622. // Group targets into buckets by priority
  623. dialTargetBuckets := make(map[int][]dialTarget, len(dialTargets))
  624. for _, tgt := range dialTargets {
  625. dialTargetBuckets[tgt.priority] = append(dialTargetBuckets[tgt.priority], tgt)
  626. }
  627. // Get all available priorities
  628. priorities := make([]int, 0, len(dialTargetBuckets))
  629. for prio := range dialTargetBuckets {
  630. priorities = append(priorities, prio)
  631. }
  632. // Sort the priorities so that we dial lowest first (which means highest...)
  633. sort.Ints(priorities)
  634. for _, prio := range priorities {
  635. tgts := dialTargetBuckets[prio]
  636. res := make(chan internalConn, len(tgts))
  637. wg := sync.NewWaitGroup()
  638. for _, tgt := range tgts {
  639. wg.Add(1)
  640. go func(tgt dialTarget) {
  641. conn, err := tgt.Dial()
  642. if err == nil {
  643. res <- conn
  644. }
  645. wg.Done()
  646. }(tgt)
  647. }
  648. // Spawn a routine which will unblock main routine in case we fail
  649. // to connect to anyone.
  650. go func() {
  651. wg.Wait()
  652. close(res)
  653. }()
  654. // Wait for the first connection, or for channel closure.
  655. conn, ok := <-res
  656. // Got a connection, means more might come back, hence spawn a
  657. // routine that will do the discarding.
  658. if ok {
  659. l.Debugln("connected to", deviceID, prio, "using", conn, conn.priority)
  660. go func(deviceID protocol.DeviceID, prio int) {
  661. wg.Wait()
  662. l.Debugln("discarding", len(res), "connections while connecting to", deviceID, prio)
  663. for conn := range res {
  664. conn.Close()
  665. }
  666. }(deviceID, prio)
  667. } else {
  668. // Failed to connect, report that fact.
  669. l.Debugln("failed to connect to", deviceID, prio)
  670. }
  671. return conn, ok
  672. }
  673. return internalConn{}, false
  674. }