connections.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  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 http://mozilla.org/MPL/2.0/.
  6. package connections
  7. import (
  8. "crypto/tls"
  9. "fmt"
  10. "io"
  11. "net"
  12. "net/url"
  13. "sync"
  14. "time"
  15. "github.com/juju/ratelimit"
  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/model"
  20. "github.com/syncthing/syncthing/lib/protocol"
  21. "github.com/syncthing/syncthing/lib/relay"
  22. "github.com/syncthing/syncthing/lib/relay/client"
  23. "github.com/syncthing/syncthing/lib/upnp"
  24. "github.com/syncthing/syncthing/lib/util"
  25. "github.com/thejerf/suture"
  26. )
  27. type DialerFactory func(*url.URL, *tls.Config) (*tls.Conn, error)
  28. type ListenerFactory func(*url.URL, *tls.Config, chan<- model.IntermediateConnection)
  29. var (
  30. dialers = make(map[string]DialerFactory, 0)
  31. listeners = make(map[string]ListenerFactory, 0)
  32. )
  33. type Model interface {
  34. protocol.Model
  35. AddConnection(conn model.Connection)
  36. ConnectedTo(remoteID protocol.DeviceID) bool
  37. IsPaused(remoteID protocol.DeviceID) bool
  38. }
  39. // Service listens on TLS and dials configured unconnected devices. Successful
  40. // connections are handed to the model.
  41. type Service struct {
  42. *suture.Supervisor
  43. cfg *config.Wrapper
  44. myID protocol.DeviceID
  45. model Model
  46. tlsCfg *tls.Config
  47. discoverer discover.Finder
  48. conns chan model.IntermediateConnection
  49. upnpService *upnp.Service
  50. relayService relay.Service
  51. bepProtocolName string
  52. tlsDefaultCommonName string
  53. lans []*net.IPNet
  54. writeRateLimit *ratelimit.Bucket
  55. readRateLimit *ratelimit.Bucket
  56. lastRelayCheck map[protocol.DeviceID]time.Time
  57. mut sync.RWMutex
  58. connType map[protocol.DeviceID]model.ConnectionType
  59. relaysEnabled bool
  60. }
  61. func NewConnectionService(cfg *config.Wrapper, myID protocol.DeviceID, mdl Model, tlsCfg *tls.Config, discoverer discover.Finder, upnpService *upnp.Service,
  62. relayService relay.Service, bepProtocolName string, tlsDefaultCommonName string, lans []*net.IPNet) *Service {
  63. service := &Service{
  64. Supervisor: suture.NewSimple("connections.Service"),
  65. cfg: cfg,
  66. myID: myID,
  67. model: mdl,
  68. tlsCfg: tlsCfg,
  69. discoverer: discoverer,
  70. upnpService: upnpService,
  71. relayService: relayService,
  72. conns: make(chan model.IntermediateConnection),
  73. bepProtocolName: bepProtocolName,
  74. tlsDefaultCommonName: tlsDefaultCommonName,
  75. lans: lans,
  76. connType: make(map[protocol.DeviceID]model.ConnectionType),
  77. relaysEnabled: cfg.Options().RelaysEnabled,
  78. lastRelayCheck: make(map[protocol.DeviceID]time.Time),
  79. }
  80. cfg.Subscribe(service)
  81. // The rate variables are in KiB/s in the UI (despite the camel casing
  82. // of the name). We multiply by 1024 here to get B/s.
  83. if service.cfg.Options().MaxSendKbps > 0 {
  84. service.writeRateLimit = ratelimit.NewBucketWithRate(float64(1024*service.cfg.Options().MaxSendKbps), int64(5*1024*service.cfg.Options().MaxSendKbps))
  85. }
  86. if service.cfg.Options().MaxRecvKbps > 0 {
  87. service.readRateLimit = ratelimit.NewBucketWithRate(float64(1024*service.cfg.Options().MaxRecvKbps), int64(5*1024*service.cfg.Options().MaxRecvKbps))
  88. }
  89. // There are several moving parts here; one routine per listening address
  90. // to handle incoming connections, one routine to periodically attempt
  91. // outgoing connections, one routine to the the common handling
  92. // regardless of whether the connection was incoming or outgoing.
  93. // Furthermore, a relay service which handles incoming requests to connect
  94. // via the relays.
  95. //
  96. // TODO: Clean shutdown, and/or handling config changes on the fly. We
  97. // partly do this now - new devices and addresses will be picked up, but
  98. // not new listen addresses and we don't support disconnecting devices
  99. // that are removed and so on...
  100. service.Add(serviceFunc(service.connect))
  101. for _, addr := range service.cfg.Options().ListenAddress {
  102. uri, err := url.Parse(addr)
  103. if err != nil {
  104. l.Infoln("Failed to parse listen address:", addr, err)
  105. continue
  106. }
  107. listener, ok := listeners[uri.Scheme]
  108. if !ok {
  109. l.Infoln("Unknown listen address scheme:", uri.String())
  110. continue
  111. }
  112. l.Debugln("listening on", uri)
  113. service.Add(serviceFunc(func() {
  114. listener(uri, service.tlsCfg, service.conns)
  115. }))
  116. }
  117. service.Add(serviceFunc(service.handle))
  118. if service.relayService != nil {
  119. service.Add(serviceFunc(service.acceptRelayConns))
  120. }
  121. return service
  122. }
  123. func (s *Service) handle() {
  124. next:
  125. for c := range s.conns {
  126. cs := c.Conn.ConnectionState()
  127. // We should have negotiated the next level protocol "bep/1.0" as part
  128. // of the TLS handshake. Unfortunately this can't be a hard error,
  129. // because there are implementations out there that don't support
  130. // protocol negotiation (iOS for one...).
  131. if !cs.NegotiatedProtocolIsMutual || cs.NegotiatedProtocol != s.bepProtocolName {
  132. l.Infof("Peer %s did not negotiate bep/1.0", c.Conn.RemoteAddr())
  133. }
  134. // We should have received exactly one certificate from the other
  135. // side. If we didn't, they don't have a device ID and we drop the
  136. // connection.
  137. certs := cs.PeerCertificates
  138. if cl := len(certs); cl != 1 {
  139. l.Infof("Got peer certificate list of length %d != 1 from %s; protocol error", cl, c.Conn.RemoteAddr())
  140. c.Conn.Close()
  141. continue
  142. }
  143. remoteCert := certs[0]
  144. remoteID := protocol.NewDeviceID(remoteCert.Raw)
  145. // The device ID should not be that of ourselves. It can happen
  146. // though, especially in the presence of NAT hairpinning, multiple
  147. // clients between the same NAT gateway, and global discovery.
  148. if remoteID == s.myID {
  149. l.Infof("Connected to myself (%s) - should not happen", remoteID)
  150. c.Conn.Close()
  151. continue
  152. }
  153. // If we have a relay connection, and the new incoming connection is
  154. // not a relay connection, we should drop that, and prefer the this one.
  155. s.mut.RLock()
  156. ct, ok := s.connType[remoteID]
  157. s.mut.RUnlock()
  158. if ok && !ct.IsDirect() && c.Type.IsDirect() {
  159. l.Debugln("Switching connections", remoteID)
  160. s.model.Close(remoteID, fmt.Errorf("switching connections"))
  161. } else if s.model.ConnectedTo(remoteID) {
  162. // We should not already be connected to the other party. TODO: This
  163. // could use some better handling. If the old connection is dead but
  164. // hasn't timed out yet we may want to drop *that* connection and keep
  165. // this one. But in case we are two devices connecting to each other
  166. // in parallel we don't want to do that or we end up with no
  167. // connections still established...
  168. l.Infof("Connected to already connected device (%s)", remoteID)
  169. c.Conn.Close()
  170. continue
  171. } else if s.model.IsPaused(remoteID) {
  172. l.Infof("Connection from paused device (%s)", remoteID)
  173. c.Conn.Close()
  174. continue
  175. }
  176. for deviceID, deviceCfg := range s.cfg.Devices() {
  177. if deviceID == remoteID {
  178. // Verify the name on the certificate. By default we set it to
  179. // "syncthing" when generating, but the user may have replaced
  180. // the certificate and used another name.
  181. certName := deviceCfg.CertName
  182. if certName == "" {
  183. certName = s.tlsDefaultCommonName
  184. }
  185. err := remoteCert.VerifyHostname(certName)
  186. if err != nil {
  187. // Incorrect certificate name is something the user most
  188. // likely wants to know about, since it's an advanced
  189. // config. Warn instead of Info.
  190. l.Warnf("Bad certificate from %s (%v): %v", remoteID, c.Conn.RemoteAddr(), err)
  191. c.Conn.Close()
  192. continue next
  193. }
  194. // If rate limiting is set, and based on the address we should
  195. // limit the connection, then we wrap it in a limiter.
  196. limit := s.shouldLimit(c.Conn.RemoteAddr())
  197. wr := io.Writer(c.Conn)
  198. if limit && s.writeRateLimit != nil {
  199. wr = NewWriteLimiter(c.Conn, s.writeRateLimit)
  200. }
  201. rd := io.Reader(c.Conn)
  202. if limit && s.readRateLimit != nil {
  203. rd = NewReadLimiter(c.Conn, s.readRateLimit)
  204. }
  205. name := fmt.Sprintf("%s-%s (%s)", c.Conn.LocalAddr(), c.Conn.RemoteAddr(), c.Type)
  206. protoConn := protocol.NewConnection(remoteID, rd, wr, s.model, name, deviceCfg.Compression)
  207. l.Infof("Established secure connection to %s at %s", remoteID, name)
  208. l.Debugf("cipher suite: %04X in lan: %t", c.Conn.ConnectionState().CipherSuite, !limit)
  209. s.model.AddConnection(model.Connection{
  210. c.Conn,
  211. protoConn,
  212. c.Type,
  213. })
  214. s.mut.Lock()
  215. s.connType[remoteID] = c.Type
  216. s.mut.Unlock()
  217. continue next
  218. }
  219. }
  220. if !s.cfg.IgnoredDevice(remoteID) {
  221. events.Default.Log(events.DeviceRejected, map[string]string{
  222. "device": remoteID.String(),
  223. "address": c.Conn.RemoteAddr().String(),
  224. })
  225. }
  226. l.Infof("Connection from %s (%s) with ignored device ID %s", c.Conn.RemoteAddr(), c.Type, remoteID)
  227. c.Conn.Close()
  228. }
  229. }
  230. func (s *Service) connect() {
  231. delay := time.Second
  232. for {
  233. l.Debugln("Reconnect loop")
  234. nextDevice:
  235. for deviceID, deviceCfg := range s.cfg.Devices() {
  236. if deviceID == s.myID {
  237. continue
  238. }
  239. l.Debugln("Reconnect loop for", deviceID)
  240. if s.model.IsPaused(deviceID) {
  241. continue
  242. }
  243. connected := s.model.ConnectedTo(deviceID)
  244. s.mut.RLock()
  245. ct, ok := s.connType[deviceID]
  246. relaysEnabled := s.relaysEnabled
  247. s.mut.RUnlock()
  248. if connected && ok && ct.IsDirect() {
  249. l.Debugln("Already connected to", deviceID, "via", ct.String())
  250. continue
  251. }
  252. addrs, relays := s.resolveAddresses(deviceID, deviceCfg.Addresses)
  253. for _, addr := range addrs {
  254. if conn := s.connectDirect(deviceID, addr); conn != nil {
  255. l.Debugln("Connecting to", deviceID, "via", addr, "succeeded")
  256. if connected {
  257. s.model.Close(deviceID, fmt.Errorf("switching connections"))
  258. }
  259. s.conns <- model.IntermediateConnection{
  260. conn, model.ConnectionTypeDirectDial,
  261. }
  262. continue nextDevice
  263. }
  264. l.Debugln("Connecting to", deviceID, "via", addr, "failed")
  265. }
  266. // Only connect via relays if not already connected
  267. // Also, do not set lastRelayCheck time if we have no relays,
  268. // as otherwise when we do discover relays, we might have to
  269. // wait up to RelayReconnectIntervalM to connect again.
  270. // Also, do not try relays if we are explicitly told not to.
  271. if connected || len(relays) == 0 || !relaysEnabled {
  272. l.Debugln("Not connecting via relay", connected, len(relays) == 0, !relaysEnabled)
  273. continue nextDevice
  274. }
  275. reconIntv := time.Duration(s.cfg.Options().RelayReconnectIntervalM) * time.Minute
  276. if last, ok := s.lastRelayCheck[deviceID]; ok && time.Since(last) < reconIntv {
  277. l.Debugln("Skipping connecting via relay to", deviceID, "last checked at", last)
  278. continue nextDevice
  279. }
  280. l.Debugln("Trying relay connections to", deviceID, relays)
  281. s.lastRelayCheck[deviceID] = time.Now()
  282. for _, addr := range relays {
  283. if conn := s.connectViaRelay(deviceID, addr); conn != nil {
  284. l.Debugln("Connecting to", deviceID, "via", addr, "succeeded")
  285. s.conns <- model.IntermediateConnection{
  286. conn, model.ConnectionTypeRelayDial,
  287. }
  288. continue nextDevice
  289. }
  290. l.Debugln("Connecting to", deviceID, "via", addr, "failed")
  291. }
  292. }
  293. time.Sleep(delay)
  294. delay *= 2
  295. if maxD := time.Duration(s.cfg.Options().ReconnectIntervalS) * time.Second; delay > maxD {
  296. delay = maxD
  297. }
  298. }
  299. }
  300. func (s *Service) resolveAddresses(deviceID protocol.DeviceID, inAddrs []string) (addrs []string, relays []discover.Relay) {
  301. for _, addr := range inAddrs {
  302. if addr == "dynamic" {
  303. if s.discoverer != nil {
  304. if t, r, err := s.discoverer.Lookup(deviceID); err == nil {
  305. addrs = append(addrs, t...)
  306. relays = append(relays, r...)
  307. }
  308. }
  309. } else {
  310. addrs = append(addrs, addr)
  311. }
  312. }
  313. return
  314. }
  315. func (s *Service) connectDirect(deviceID protocol.DeviceID, addr string) *tls.Conn {
  316. uri, err := url.Parse(addr)
  317. if err != nil {
  318. l.Infoln("Failed to parse connection url:", addr, err)
  319. return nil
  320. }
  321. dialer, ok := dialers[uri.Scheme]
  322. if !ok {
  323. l.Infoln("Unknown address schema", uri)
  324. return nil
  325. }
  326. l.Debugln("dial", deviceID, uri)
  327. conn, err := dialer(uri, s.tlsCfg)
  328. if err != nil {
  329. l.Debugln("dial failed", deviceID, uri, err)
  330. return nil
  331. }
  332. return conn
  333. }
  334. func (s *Service) connectViaRelay(deviceID protocol.DeviceID, addr discover.Relay) *tls.Conn {
  335. uri, err := url.Parse(addr.URL)
  336. if err != nil {
  337. l.Infoln("Failed to parse relay connection url:", addr, err)
  338. return nil
  339. }
  340. inv, err := client.GetInvitationFromRelay(uri, deviceID, s.tlsCfg.Certificates, 10*time.Second)
  341. if err != nil {
  342. l.Debugf("Failed to get invitation for %s from %s: %v", deviceID, uri, err)
  343. return nil
  344. }
  345. l.Debugln("Succesfully retrieved relay invitation", inv, "from", uri)
  346. conn, err := client.JoinSession(inv)
  347. if err != nil {
  348. l.Debugf("Failed to join relay session %s: %v", inv, err)
  349. return nil
  350. }
  351. l.Debugln("Successfully joined relay session", inv)
  352. var tc *tls.Conn
  353. if inv.ServerSocket {
  354. tc = tls.Server(conn, s.tlsCfg)
  355. } else {
  356. tc = tls.Client(conn, s.tlsCfg)
  357. }
  358. err = tc.Handshake()
  359. if err != nil {
  360. l.Infof("TLS handshake (BEP/relay %s): %v", inv, err)
  361. tc.Close()
  362. return nil
  363. }
  364. return tc
  365. }
  366. func (s *Service) acceptRelayConns() {
  367. for {
  368. conn := s.relayService.Accept()
  369. s.conns <- model.IntermediateConnection{
  370. Conn: conn,
  371. Type: model.ConnectionTypeRelayAccept,
  372. }
  373. }
  374. }
  375. func (s *Service) shouldLimit(addr net.Addr) bool {
  376. if s.cfg.Options().LimitBandwidthInLan {
  377. return true
  378. }
  379. tcpaddr, ok := addr.(*net.TCPAddr)
  380. if !ok {
  381. return true
  382. }
  383. for _, lan := range s.lans {
  384. if lan.Contains(tcpaddr.IP) {
  385. return false
  386. }
  387. }
  388. return !tcpaddr.IP.IsLoopback()
  389. }
  390. func (s *Service) VerifyConfiguration(from, to config.Configuration) error {
  391. return nil
  392. }
  393. func (s *Service) CommitConfiguration(from, to config.Configuration) bool {
  394. s.mut.Lock()
  395. s.relaysEnabled = to.Options.RelaysEnabled
  396. s.mut.Unlock()
  397. // We require a restart if a device as been removed.
  398. newDevices := make(map[protocol.DeviceID]bool, len(to.Devices))
  399. for _, dev := range to.Devices {
  400. newDevices[dev.DeviceID] = true
  401. }
  402. for _, dev := range from.Devices {
  403. if !newDevices[dev.DeviceID] {
  404. return false
  405. }
  406. }
  407. return true
  408. }
  409. // ExternalAddresses returns a list of addresses that are our best guess for
  410. // where we are reachable from the outside. As a special case, we may return
  411. // one or more addresses with an empty IP address (0.0.0.0 or ::) and just
  412. // port number - this means that the outside address of a NAT gateway should
  413. // be substituted.
  414. func (s *Service) ExternalAddresses() []string {
  415. return s.addresses(false)
  416. }
  417. // AllAddresses returns a list of addresses that are our best guess for where
  418. // we are reachable from the local network. Same conditions as
  419. // ExternalAddresses, but private IPv4 addresses are included.
  420. func (s *Service) AllAddresses() []string {
  421. return s.addresses(true)
  422. }
  423. func (s *Service) addresses(includePrivateIPV4 bool) []string {
  424. var addrs []string
  425. // Grab our listen addresses from the config. Unspecified ones are passed
  426. // on verbatim (to be interpreted by a global discovery server or local
  427. // discovery peer). Public addresses are passed on verbatim. Private
  428. // addresses are filtered.
  429. for _, addrStr := range s.cfg.Options().ListenAddress {
  430. addrURL, err := url.Parse(addrStr)
  431. if err != nil {
  432. l.Infoln("Listen address", addrStr, "is invalid:", err)
  433. continue
  434. }
  435. addr, err := net.ResolveTCPAddr(addrURL.Scheme, addrURL.Host)
  436. if err != nil {
  437. l.Infoln("Listen address", addrStr, "is invalid:", err)
  438. continue
  439. }
  440. if addr.IP == nil || addr.IP.IsUnspecified() {
  441. // Address like 0.0.0.0:22000 or [::]:22000 or :22000; include as is.
  442. addrs = append(addrs, util.Address(addrURL.Scheme, addr.String()))
  443. } else if isPublicIPv4(addr.IP) || isPublicIPv6(addr.IP) {
  444. // A public address; include as is.
  445. addrs = append(addrs, util.Address(addrURL.Scheme, addr.String()))
  446. } else if includePrivateIPV4 && addr.IP.To4().IsGlobalUnicast() {
  447. // A private IPv4 address.
  448. addrs = append(addrs, util.Address(addrURL.Scheme, addr.String()))
  449. }
  450. }
  451. // Get an external port mapping from the upnpService, if it has one. If so,
  452. // add it as another unspecified address.
  453. if s.upnpService != nil {
  454. if port := s.upnpService.ExternalPort(); port != 0 {
  455. addrs = append(addrs, fmt.Sprintf("tcp://:%d", port))
  456. }
  457. }
  458. return addrs
  459. }
  460. func isPublicIPv4(ip net.IP) bool {
  461. ip = ip.To4()
  462. if ip == nil {
  463. // Not an IPv4 address (IPv6)
  464. return false
  465. }
  466. // IsGlobalUnicast below only checks that it's not link local or
  467. // multicast, and we want to exclude private (NAT:ed) addresses as well.
  468. rfc1918 := []net.IPNet{
  469. {IP: net.IP{10, 0, 0, 0}, Mask: net.IPMask{255, 0, 0, 0}},
  470. {IP: net.IP{172, 16, 0, 0}, Mask: net.IPMask{255, 240, 0, 0}},
  471. {IP: net.IP{192, 168, 0, 0}, Mask: net.IPMask{255, 255, 0, 0}},
  472. }
  473. for _, n := range rfc1918 {
  474. if n.Contains(ip) {
  475. return false
  476. }
  477. }
  478. return ip.IsGlobalUnicast()
  479. }
  480. func isPublicIPv6(ip net.IP) bool {
  481. if ip.To4() != nil {
  482. // Not an IPv6 address (IPv4)
  483. // (To16() returns a v6 mapped v4 address so can't be used to check
  484. // that it's an actual v6 address)
  485. return false
  486. }
  487. return ip.IsGlobalUnicast()
  488. }
  489. // serviceFunc wraps a function to create a suture.Service without stop
  490. // functionality.
  491. type serviceFunc func()
  492. func (f serviceFunc) Serve() { f() }
  493. func (f serviceFunc) Stop() {}