service.go 23 KB

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