service.go 16 KB

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