service.go 17 KB

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