service.go 16 KB

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