service.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  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. "encoding/binary"
  10. "errors"
  11. "fmt"
  12. "io"
  13. "net"
  14. "net/url"
  15. "time"
  16. "github.com/juju/ratelimit"
  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/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. )
  29. var (
  30. dialers = make(map[string]dialerFactory, 0)
  31. listeners = make(map[string]listenerFactory, 0)
  32. )
  33. // Service listens and dials all configured unconnected devices, via supported
  34. // dialers. Successful connections are handed to the model.
  35. type Service struct {
  36. *suture.Supervisor
  37. cfg *config.Wrapper
  38. myID protocol.DeviceID
  39. model Model
  40. tlsCfg *tls.Config
  41. discoverer discover.Finder
  42. conns chan IntermediateConnection
  43. bepProtocolName string
  44. tlsDefaultCommonName string
  45. lans []*net.IPNet
  46. writeRateLimit *ratelimit.Bucket
  47. readRateLimit *ratelimit.Bucket
  48. natService *nat.Service
  49. natServiceToken *suture.ServiceToken
  50. listenersMut sync.RWMutex
  51. listeners map[string]genericListener
  52. listenerTokens map[string]suture.ServiceToken
  53. curConMut sync.Mutex
  54. currentConnection map[protocol.DeviceID]Connection
  55. }
  56. func NewService(cfg *config.Wrapper, myID protocol.DeviceID, mdl Model, tlsCfg *tls.Config, discoverer discover.Finder,
  57. bepProtocolName string, tlsDefaultCommonName string, lans []*net.IPNet) *Service {
  58. service := &Service{
  59. Supervisor: suture.NewSimple("connections.Service"),
  60. cfg: cfg,
  61. myID: myID,
  62. model: mdl,
  63. tlsCfg: tlsCfg,
  64. discoverer: discoverer,
  65. conns: make(chan IntermediateConnection),
  66. bepProtocolName: bepProtocolName,
  67. tlsDefaultCommonName: tlsDefaultCommonName,
  68. lans: lans,
  69. natService: nat.NewService(myID, cfg),
  70. listenersMut: sync.NewRWMutex(),
  71. listeners: make(map[string]genericListener),
  72. listenerTokens: make(map[string]suture.ServiceToken),
  73. curConMut: sync.NewMutex(),
  74. currentConnection: make(map[protocol.DeviceID]Connection),
  75. }
  76. cfg.Subscribe(service)
  77. // The rate variables are in KiB/s in the UI (despite the camel casing
  78. // of the name). We multiply by 1024 here to get B/s.
  79. options := service.cfg.Options()
  80. if options.MaxSendKbps > 0 {
  81. service.writeRateLimit = ratelimit.NewBucketWithRate(float64(1024*options.MaxSendKbps), int64(5*1024*options.MaxSendKbps))
  82. }
  83. if options.MaxRecvKbps > 0 {
  84. service.readRateLimit = ratelimit.NewBucketWithRate(float64(1024*options.MaxRecvKbps), int64(5*1024*options.MaxRecvKbps))
  85. }
  86. // There are several moving parts here; one routine per listening address
  87. // (handled in configuration changing) to handle incoming connections,
  88. // one routine to periodically attempt outgoing connections, one routine to
  89. // the the common handling regardless of whether the connection was
  90. // incoming or outgoing.
  91. service.Add(serviceFunc(service.connect))
  92. service.Add(serviceFunc(service.handle))
  93. raw := cfg.Raw()
  94. // Actually starts the listeners and NAT service
  95. service.CommitConfiguration(raw, raw)
  96. return service
  97. }
  98. var (
  99. errDisabled = errors.New("disabled by configuration")
  100. )
  101. func (s *Service) handle() {
  102. next:
  103. for c := range s.conns {
  104. cs := c.ConnectionState()
  105. // We should have negotiated the next level protocol "bep/1.0" as part
  106. // of the TLS handshake. Unfortunately this can't be a hard error,
  107. // because there are implementations out there that don't support
  108. // protocol negotiation (iOS for one...).
  109. if !cs.NegotiatedProtocolIsMutual || cs.NegotiatedProtocol != s.bepProtocolName {
  110. l.Infof("Peer %s did not negotiate bep/1.0", c.RemoteAddr())
  111. }
  112. // We should have received exactly one certificate from the other
  113. // side. If we didn't, they don't have a device ID and we drop the
  114. // connection.
  115. certs := cs.PeerCertificates
  116. if cl := len(certs); cl != 1 {
  117. l.Infof("Got peer certificate list of length %d != 1 from %s; protocol error", cl, c.RemoteAddr())
  118. c.Close()
  119. continue
  120. }
  121. remoteCert := certs[0]
  122. remoteID := protocol.NewDeviceID(remoteCert.Raw)
  123. // The device ID should not be that of ourselves. It can happen
  124. // though, especially in the presence of NAT hairpinning, multiple
  125. // clients between the same NAT gateway, and global discovery.
  126. if remoteID == s.myID {
  127. l.Infof("Connected to myself (%s) - should not happen", remoteID)
  128. c.Close()
  129. continue
  130. }
  131. hello, err := exchangeHello(c, s.model.GetHello(remoteID))
  132. if err != nil {
  133. l.Infof("Failed to exchange Hello messages with %s (%s): %s", remoteID, c.RemoteAddr(), err)
  134. c.Close()
  135. continue
  136. }
  137. s.model.OnHello(remoteID, c.RemoteAddr(), hello)
  138. // If we have a relay connection, and the new incoming connection is
  139. // not a relay connection, we should drop that, and prefer the this one.
  140. s.curConMut.Lock()
  141. ct, ok := s.currentConnection[remoteID]
  142. s.curConMut.Unlock()
  143. // Lower priority is better, just like nice etc.
  144. if ok && ct.Priority > c.Priority {
  145. l.Debugln("Switching connections", remoteID)
  146. s.model.Close(remoteID, protocol.ErrSwitchingConnections)
  147. } else if s.model.ConnectedTo(remoteID) {
  148. // We should not already be connected to the other party. TODO: This
  149. // could use some better handling. If the old connection is dead but
  150. // hasn't timed out yet we may want to drop *that* connection and keep
  151. // this one. But in case we are two devices connecting to each other
  152. // in parallel we don't want to do that or we end up with no
  153. // connections still established...
  154. l.Infof("Connected to already connected device (%s)", remoteID)
  155. c.Close()
  156. continue
  157. } else if s.model.IsPaused(remoteID) {
  158. l.Infof("Connection from paused device (%s)", remoteID)
  159. c.Close()
  160. continue
  161. }
  162. for deviceID, deviceCfg := range s.cfg.Devices() {
  163. if deviceID == remoteID {
  164. // Verify the name on the certificate. By default we set it to
  165. // "syncthing" when generating, but the user may have replaced
  166. // the certificate and used another name.
  167. certName := deviceCfg.CertName
  168. if certName == "" {
  169. certName = s.tlsDefaultCommonName
  170. }
  171. err := remoteCert.VerifyHostname(certName)
  172. if err != nil {
  173. // Incorrect certificate name is something the user most
  174. // likely wants to know about, since it's an advanced
  175. // config. Warn instead of Info.
  176. l.Warnf("Bad certificate from %s (%v): %v", remoteID, c.RemoteAddr(), err)
  177. c.Close()
  178. continue next
  179. }
  180. // If rate limiting is set, and based on the address we should
  181. // limit the connection, then we wrap it in a limiter.
  182. limit := s.shouldLimit(c.RemoteAddr())
  183. wr := io.Writer(c)
  184. if limit && s.writeRateLimit != nil {
  185. wr = NewWriteLimiter(c, s.writeRateLimit)
  186. }
  187. rd := io.Reader(c)
  188. if limit && s.readRateLimit != nil {
  189. rd = NewReadLimiter(c, s.readRateLimit)
  190. }
  191. name := fmt.Sprintf("%s-%s (%s)", c.LocalAddr(), c.RemoteAddr(), c.Type)
  192. protoConn := protocol.NewConnection(remoteID, rd, wr, s.model, name, deviceCfg.Compression)
  193. modelConn := Connection{c, protoConn}
  194. l.Infof("Established secure connection to %s at %s", remoteID, name)
  195. l.Debugf("cipher suite: %04X in lan: %t", c.ConnectionState().CipherSuite, !limit)
  196. s.model.AddConnection(modelConn, hello)
  197. s.curConMut.Lock()
  198. s.currentConnection[remoteID] = modelConn
  199. s.curConMut.Unlock()
  200. continue next
  201. }
  202. }
  203. l.Infof("Connection from %s (%s) with ignored device ID %s", c.RemoteAddr(), c.Type, remoteID)
  204. c.Close()
  205. }
  206. }
  207. func (s *Service) connect() {
  208. nextDial := make(map[string]time.Time)
  209. // Used as delay for the first few connection attempts, increases
  210. // exponentially
  211. initialRampup := time.Second
  212. // Calculated from actual dialers reconnectInterval
  213. var sleep time.Duration
  214. for {
  215. cfg := s.cfg.Raw()
  216. bestDialerPrio := 1<<31 - 1 // worse prio won't build on 32 bit
  217. for _, df := range dialers {
  218. if !df.Enabled(cfg) {
  219. continue
  220. }
  221. if prio := df.Priority(); prio < bestDialerPrio {
  222. bestDialerPrio = prio
  223. }
  224. }
  225. l.Debugln("Reconnect loop")
  226. now := time.Now()
  227. var seen []string
  228. nextDevice:
  229. for _, deviceCfg := range cfg.Devices {
  230. deviceID := deviceCfg.DeviceID
  231. if deviceID == s.myID {
  232. continue
  233. }
  234. paused := s.model.IsPaused(deviceID)
  235. if paused {
  236. continue
  237. }
  238. connected := s.model.ConnectedTo(deviceID)
  239. s.curConMut.Lock()
  240. ct := s.currentConnection[deviceID]
  241. s.curConMut.Unlock()
  242. if connected && ct.Priority == bestDialerPrio {
  243. // Things are already as good as they can get.
  244. continue
  245. }
  246. l.Debugln("Reconnect loop for", deviceID)
  247. var addrs []string
  248. for _, addr := range deviceCfg.Addresses {
  249. if addr == "dynamic" {
  250. if s.discoverer != nil {
  251. if t, err := s.discoverer.Lookup(deviceID); err == nil {
  252. addrs = append(addrs, t...)
  253. }
  254. }
  255. } else {
  256. addrs = append(addrs, addr)
  257. }
  258. }
  259. seen = append(seen, addrs...)
  260. for _, addr := range addrs {
  261. nextDialAt, ok := nextDial[addr]
  262. if ok && initialRampup >= sleep && nextDialAt.After(now) {
  263. l.Debugf("Not dialing %v as sleep is %v, next dial is at %s and current time is %s", addr, sleep, nextDialAt, now)
  264. continue
  265. }
  266. // If we fail at any step before actually getting the dialer
  267. // retry in a minute
  268. nextDial[addr] = now.Add(time.Minute)
  269. uri, err := url.Parse(addr)
  270. if err != nil {
  271. l.Infof("Dialer for %s: %v", addr, err)
  272. continue
  273. }
  274. dialerFactory, err := s.getDialerFactory(cfg, uri)
  275. if err == errDisabled {
  276. l.Debugln("Dialer for", uri, "is disabled")
  277. continue
  278. }
  279. if err != nil {
  280. l.Infof("Dialer for %v: %v", uri, err)
  281. continue
  282. }
  283. if connected && dialerFactory.Priority() >= ct.Priority {
  284. l.Debugf("Not dialing using %s as priorty is less than current connection (%d >= %d)", dialerFactory, dialerFactory.Priority(), ct.Priority)
  285. continue
  286. }
  287. dialer := dialerFactory.New(s.cfg, s.tlsCfg)
  288. l.Debugln("dial", deviceCfg.DeviceID, uri)
  289. nextDial[addr] = now.Add(dialer.RedialFrequency())
  290. conn, err := dialer.Dial(deviceID, uri)
  291. if err != nil {
  292. l.Debugln("dial failed", deviceCfg.DeviceID, uri, err)
  293. continue
  294. }
  295. if connected {
  296. s.model.Close(deviceID, protocol.ErrSwitchingConnections)
  297. }
  298. s.conns <- conn
  299. continue nextDevice
  300. }
  301. }
  302. nextDial, sleep = filterAndFindSleepDuration(nextDial, seen, now)
  303. if initialRampup < sleep {
  304. l.Debugln("initial rampup; sleep", initialRampup, "and update to", initialRampup*2)
  305. time.Sleep(initialRampup)
  306. initialRampup *= 2
  307. } else {
  308. l.Debugln("sleep until next dial", sleep)
  309. time.Sleep(sleep)
  310. }
  311. }
  312. }
  313. func (s *Service) shouldLimit(addr net.Addr) bool {
  314. if s.cfg.Options().LimitBandwidthInLan {
  315. return true
  316. }
  317. tcpaddr, ok := addr.(*net.TCPAddr)
  318. if !ok {
  319. return true
  320. }
  321. for _, lan := range s.lans {
  322. if lan.Contains(tcpaddr.IP) {
  323. return false
  324. }
  325. }
  326. return !tcpaddr.IP.IsLoopback()
  327. }
  328. func (s *Service) createListener(factory listenerFactory, uri *url.URL) bool {
  329. // must be called with listenerMut held
  330. l.Debugln("Starting listener", uri)
  331. listener := factory.New(uri, s.cfg, s.tlsCfg, s.conns, s.natService)
  332. listener.OnAddressesChanged(s.logListenAddressesChangedEvent)
  333. s.listeners[uri.String()] = listener
  334. s.listenerTokens[uri.String()] = s.Add(listener)
  335. return true
  336. }
  337. func (s *Service) logListenAddressesChangedEvent(l genericListener) {
  338. events.Default.Log(events.ListenAddressesChanged, map[string]interface{}{
  339. "address": l.URI(),
  340. "lan": l.LANAddresses(),
  341. "wan": l.WANAddresses(),
  342. })
  343. }
  344. func (s *Service) VerifyConfiguration(from, to config.Configuration) error {
  345. return nil
  346. }
  347. func (s *Service) CommitConfiguration(from, to config.Configuration) bool {
  348. // We require a restart if a device as been removed.
  349. restart := false
  350. newDevices := make(map[protocol.DeviceID]bool, len(to.Devices))
  351. for _, dev := range to.Devices {
  352. newDevices[dev.DeviceID] = true
  353. }
  354. for _, dev := range from.Devices {
  355. if !newDevices[dev.DeviceID] {
  356. restart = true
  357. }
  358. }
  359. s.listenersMut.Lock()
  360. seen := make(map[string]struct{})
  361. for _, addr := range config.Wrap("", to).ListenAddresses() {
  362. if _, ok := s.listeners[addr]; ok {
  363. seen[addr] = struct{}{}
  364. continue
  365. }
  366. uri, err := url.Parse(addr)
  367. if err != nil {
  368. l.Infof("Listener for %s: %v", addr, err)
  369. continue
  370. }
  371. factory, err := s.getListenerFactory(to, uri)
  372. if err == errDisabled {
  373. l.Debugln("Listener for", uri, "is disabled")
  374. continue
  375. }
  376. if err != nil {
  377. l.Infof("Listener for %v: %v", uri, err)
  378. continue
  379. }
  380. s.createListener(factory, uri)
  381. seen[addr] = struct{}{}
  382. }
  383. for addr, listener := range s.listeners {
  384. if _, ok := seen[addr]; !ok || !listener.Factory().Enabled(to) {
  385. l.Debugln("Stopping listener", addr)
  386. s.Remove(s.listenerTokens[addr])
  387. delete(s.listenerTokens, addr)
  388. delete(s.listeners, addr)
  389. }
  390. }
  391. s.listenersMut.Unlock()
  392. if to.Options.NATEnabled && s.natServiceToken == nil {
  393. l.Debugln("Starting NAT service")
  394. token := s.Add(s.natService)
  395. s.natServiceToken = &token
  396. } else if !to.Options.NATEnabled && s.natServiceToken != nil {
  397. l.Debugln("Stopping NAT service")
  398. s.Remove(*s.natServiceToken)
  399. s.natServiceToken = nil
  400. }
  401. return !restart
  402. }
  403. func (s *Service) AllAddresses() []string {
  404. s.listenersMut.RLock()
  405. var addrs []string
  406. for _, listener := range s.listeners {
  407. for _, lanAddr := range listener.LANAddresses() {
  408. addrs = append(addrs, lanAddr.String())
  409. }
  410. for _, wanAddr := range listener.WANAddresses() {
  411. addrs = append(addrs, wanAddr.String())
  412. }
  413. }
  414. s.listenersMut.RUnlock()
  415. return util.UniqueStrings(addrs)
  416. }
  417. func (s *Service) ExternalAddresses() []string {
  418. s.listenersMut.RLock()
  419. var addrs []string
  420. for _, listener := range s.listeners {
  421. for _, wanAddr := range listener.WANAddresses() {
  422. addrs = append(addrs, wanAddr.String())
  423. }
  424. }
  425. s.listenersMut.RUnlock()
  426. return util.UniqueStrings(addrs)
  427. }
  428. func (s *Service) Status() map[string]interface{} {
  429. s.listenersMut.RLock()
  430. result := make(map[string]interface{})
  431. for addr, listener := range s.listeners {
  432. status := make(map[string]interface{})
  433. err := listener.Error()
  434. if err != nil {
  435. status["error"] = err.Error()
  436. }
  437. status["lanAddresses"] = urlsToStrings(listener.LANAddresses())
  438. status["wanAddresses"] = urlsToStrings(listener.WANAddresses())
  439. result[addr] = status
  440. }
  441. s.listenersMut.RUnlock()
  442. return result
  443. }
  444. func (s *Service) getDialerFactory(cfg config.Configuration, uri *url.URL) (dialerFactory, error) {
  445. dialerFactory, ok := dialers[uri.Scheme]
  446. if !ok {
  447. return nil, fmt.Errorf("unknown address scheme %q", uri.Scheme)
  448. }
  449. if !dialerFactory.Enabled(cfg) {
  450. return nil, errDisabled
  451. }
  452. return dialerFactory, nil
  453. }
  454. func (s *Service) getListenerFactory(cfg config.Configuration, uri *url.URL) (listenerFactory, error) {
  455. listenerFactory, ok := listeners[uri.Scheme]
  456. if !ok {
  457. return nil, fmt.Errorf("unknown address scheme %q", uri.Scheme)
  458. }
  459. if !listenerFactory.Enabled(cfg) {
  460. return nil, errDisabled
  461. }
  462. return listenerFactory, nil
  463. }
  464. func exchangeHello(c net.Conn, h protocol.HelloMessage) (protocol.HelloMessage, error) {
  465. if err := c.SetDeadline(time.Now().Add(20 * time.Second)); err != nil {
  466. return protocol.HelloMessage{}, err
  467. }
  468. defer c.SetDeadline(time.Time{})
  469. header := make([]byte, 8)
  470. msg := h.MustMarshalXDR()
  471. binary.BigEndian.PutUint32(header[:4], protocol.HelloMessageMagic)
  472. binary.BigEndian.PutUint32(header[4:], uint32(len(msg)))
  473. if _, err := c.Write(header); err != nil {
  474. return protocol.HelloMessage{}, err
  475. }
  476. if _, err := c.Write(msg); err != nil {
  477. return protocol.HelloMessage{}, err
  478. }
  479. if _, err := io.ReadFull(c, header); err != nil {
  480. return protocol.HelloMessage{}, err
  481. }
  482. if binary.BigEndian.Uint32(header[:4]) != protocol.HelloMessageMagic {
  483. return protocol.HelloMessage{}, fmt.Errorf("incorrect magic")
  484. }
  485. msgSize := binary.BigEndian.Uint32(header[4:])
  486. if msgSize > 1024 {
  487. return protocol.HelloMessage{}, fmt.Errorf("hello message too big")
  488. }
  489. buf := make([]byte, msgSize)
  490. var hello protocol.HelloMessage
  491. if _, err := io.ReadFull(c, buf); err != nil {
  492. return protocol.HelloMessage{}, err
  493. }
  494. if err := hello.UnmarshalXDR(buf); err != nil {
  495. return protocol.HelloMessage{}, err
  496. }
  497. return hello, nil
  498. }
  499. func filterAndFindSleepDuration(nextDial map[string]time.Time, seen []string, now time.Time) (map[string]time.Time, time.Duration) {
  500. newNextDial := make(map[string]time.Time)
  501. for _, addr := range seen {
  502. nextDialAt, ok := nextDial[addr]
  503. if ok {
  504. newNextDial[addr] = nextDialAt
  505. }
  506. }
  507. min := time.Minute
  508. for _, next := range newNextDial {
  509. cur := next.Sub(now)
  510. if cur < min {
  511. min = cur
  512. }
  513. }
  514. return newNextDial, min
  515. }
  516. func urlsToStrings(urls []*url.URL) []string {
  517. strings := make([]string, len(urls))
  518. for i, url := range urls {
  519. strings[i] = url.String()
  520. }
  521. return strings
  522. }