connections.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  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/osutil"
  21. "github.com/syncthing/syncthing/lib/protocol"
  22. "github.com/syncthing/syncthing/lib/relay"
  23. "github.com/syncthing/syncthing/lib/relay/client"
  24. "github.com/thejerf/suture"
  25. )
  26. type DialerFactory func(*url.URL, *tls.Config) (*tls.Conn, error)
  27. type ListenerFactory func(*url.URL, *tls.Config, chan<- model.IntermediateConnection)
  28. var (
  29. dialers = make(map[string]DialerFactory, 0)
  30. listeners = make(map[string]ListenerFactory, 0)
  31. )
  32. type Model interface {
  33. protocol.Model
  34. AddConnection(conn model.Connection)
  35. ConnectedTo(remoteID protocol.DeviceID) bool
  36. IsPaused(remoteID protocol.DeviceID) bool
  37. }
  38. // The connection service listens on TLS and dials configured unconnected
  39. // devices. Successful connections are handed to the model.
  40. type connectionSvc struct {
  41. *suture.Supervisor
  42. cfg *config.Wrapper
  43. myID protocol.DeviceID
  44. model Model
  45. tlsCfg *tls.Config
  46. discoverer discover.Finder
  47. conns chan model.IntermediateConnection
  48. relaySvc *relay.Svc
  49. bepProtocolName string
  50. tlsDefaultCommonName string
  51. lans []*net.IPNet
  52. writeRateLimit *ratelimit.Bucket
  53. readRateLimit *ratelimit.Bucket
  54. lastRelayCheck map[protocol.DeviceID]time.Time
  55. mut sync.RWMutex
  56. connType map[protocol.DeviceID]model.ConnectionType
  57. relaysEnabled bool
  58. }
  59. func NewConnectionSvc(cfg *config.Wrapper, myID protocol.DeviceID, mdl Model, tlsCfg *tls.Config, discoverer discover.Finder, relaySvc *relay.Svc,
  60. bepProtocolName string, tlsDefaultCommonName string, lans []*net.IPNet) suture.Service {
  61. svc := &connectionSvc{
  62. Supervisor: suture.NewSimple("connectionSvc"),
  63. cfg: cfg,
  64. myID: myID,
  65. model: mdl,
  66. tlsCfg: tlsCfg,
  67. discoverer: discoverer,
  68. relaySvc: relaySvc,
  69. conns: make(chan model.IntermediateConnection),
  70. bepProtocolName: bepProtocolName,
  71. tlsDefaultCommonName: tlsDefaultCommonName,
  72. lans: lans,
  73. connType: make(map[protocol.DeviceID]model.ConnectionType),
  74. relaysEnabled: cfg.Options().RelaysEnabled,
  75. lastRelayCheck: make(map[protocol.DeviceID]time.Time),
  76. }
  77. cfg.Subscribe(svc)
  78. if svc.cfg.Options().MaxSendKbps > 0 {
  79. svc.writeRateLimit = ratelimit.NewBucketWithRate(float64(1000*svc.cfg.Options().MaxSendKbps), int64(5*1000*svc.cfg.Options().MaxSendKbps))
  80. }
  81. if svc.cfg.Options().MaxRecvKbps > 0 {
  82. svc.readRateLimit = ratelimit.NewBucketWithRate(float64(1000*svc.cfg.Options().MaxRecvKbps), int64(5*1000*svc.cfg.Options().MaxRecvKbps))
  83. }
  84. // There are several moving parts here; one routine per listening address
  85. // to handle incoming connections, one routine to periodically attempt
  86. // outgoing connections, one routine to the the common handling
  87. // regardless of whether the connection was incoming or outgoing.
  88. // Furthermore, a relay service which handles incoming requests to connect
  89. // via the relays.
  90. //
  91. // TODO: Clean shutdown, and/or handling config changes on the fly. We
  92. // partly do this now - new devices and addresses will be picked up, but
  93. // not new listen addresses and we don't support disconnecting devices
  94. // that are removed and so on...
  95. svc.Add(serviceFunc(svc.connect))
  96. for _, addr := range svc.cfg.Options().ListenAddress {
  97. uri, err := url.Parse(addr)
  98. if err != nil {
  99. l.Infoln("Failed to parse listen address:", addr, err)
  100. continue
  101. }
  102. listener, ok := listeners[uri.Scheme]
  103. if !ok {
  104. l.Infoln("Unknown listen address scheme:", uri.String())
  105. continue
  106. }
  107. if debug {
  108. l.Debugln("listening on", uri.String())
  109. }
  110. svc.Add(serviceFunc(func() {
  111. listener(uri, svc.tlsCfg, svc.conns)
  112. }))
  113. }
  114. svc.Add(serviceFunc(svc.handle))
  115. if svc.relaySvc != nil {
  116. svc.Add(serviceFunc(svc.acceptRelayConns))
  117. }
  118. return svc
  119. }
  120. func (s *connectionSvc) handle() {
  121. next:
  122. for c := range s.conns {
  123. cs := c.Conn.ConnectionState()
  124. // We should have negotiated the next level protocol "bep/1.0" as part
  125. // of the TLS handshake. Unfortunately this can't be a hard error,
  126. // because there are implementations out there that don't support
  127. // protocol negotiation (iOS for one...).
  128. if !cs.NegotiatedProtocolIsMutual || cs.NegotiatedProtocol != s.bepProtocolName {
  129. l.Infof("Peer %s did not negotiate bep/1.0", c.Conn.RemoteAddr())
  130. }
  131. // We should have received exactly one certificate from the other
  132. // side. If we didn't, they don't have a device ID and we drop the
  133. // connection.
  134. certs := cs.PeerCertificates
  135. if cl := len(certs); cl != 1 {
  136. l.Infof("Got peer certificate list of length %d != 1 from %s; protocol error", cl, c.Conn.RemoteAddr())
  137. c.Conn.Close()
  138. continue
  139. }
  140. remoteCert := certs[0]
  141. remoteID := protocol.NewDeviceID(remoteCert.Raw)
  142. // The device ID should not be that of ourselves. It can happen
  143. // though, especially in the presence of NAT hairpinning, multiple
  144. // clients between the same NAT gateway, and global discovery.
  145. if remoteID == s.myID {
  146. l.Infof("Connected to myself (%s) - should not happen", remoteID)
  147. c.Conn.Close()
  148. continue
  149. }
  150. // If we have a relay connection, and the new incoming connection is
  151. // not a relay connection, we should drop that, and prefer the this one.
  152. s.mut.RLock()
  153. ct, ok := s.connType[remoteID]
  154. s.mut.RUnlock()
  155. if ok && !ct.IsDirect() && c.Type.IsDirect() {
  156. if debug {
  157. l.Debugln("Switching connections", remoteID)
  158. }
  159. s.model.Close(remoteID, fmt.Errorf("switching connections"))
  160. } else if s.model.ConnectedTo(remoteID) {
  161. // We should not already be connected to the other party. TODO: This
  162. // could use some better handling. If the old connection is dead but
  163. // hasn't timed out yet we may want to drop *that* connection and keep
  164. // this one. But in case we are two devices connecting to each other
  165. // in parallel we don't want to do that or we end up with no
  166. // connections still established...
  167. l.Infof("Connected to already connected device (%s)", remoteID)
  168. c.Conn.Close()
  169. continue
  170. } else if s.model.IsPaused(remoteID) {
  171. l.Infof("Connection from paused device (%s)", remoteID)
  172. c.Conn.Close()
  173. continue
  174. }
  175. for deviceID, deviceCfg := range s.cfg.Devices() {
  176. if deviceID == remoteID {
  177. // Verify the name on the certificate. By default we set it to
  178. // "syncthing" when generating, but the user may have replaced
  179. // the certificate and used another name.
  180. certName := deviceCfg.CertName
  181. if certName == "" {
  182. certName = s.tlsDefaultCommonName
  183. }
  184. err := remoteCert.VerifyHostname(certName)
  185. if err != nil {
  186. // Incorrect certificate name is something the user most
  187. // likely wants to know about, since it's an advanced
  188. // config. Warn instead of Info.
  189. l.Warnf("Bad certificate from %s (%v): %v", remoteID, c.Conn.RemoteAddr(), err)
  190. c.Conn.Close()
  191. continue next
  192. }
  193. // If rate limiting is set, and based on the address we should
  194. // limit the connection, then we wrap it in a limiter.
  195. limit := s.shouldLimit(c.Conn.RemoteAddr())
  196. wr := io.Writer(c.Conn)
  197. if limit && s.writeRateLimit != nil {
  198. wr = NewWriteLimiter(c.Conn, s.writeRateLimit)
  199. }
  200. rd := io.Reader(c.Conn)
  201. if limit && s.readRateLimit != nil {
  202. rd = NewReadLimiter(c.Conn, s.readRateLimit)
  203. }
  204. name := fmt.Sprintf("%s-%s (%s)", c.Conn.LocalAddr(), c.Conn.RemoteAddr(), c.Type)
  205. protoConn := protocol.NewConnection(remoteID, rd, wr, s.model, name, deviceCfg.Compression)
  206. l.Infof("Established secure connection to %s at %s", remoteID, name)
  207. if debug {
  208. l.Debugf("cipher suite: %04X in lan: %t", c.Conn.ConnectionState().CipherSuite, !limit)
  209. }
  210. s.model.AddConnection(model.Connection{
  211. c.Conn,
  212. protoConn,
  213. c.Type,
  214. })
  215. s.mut.Lock()
  216. s.connType[remoteID] = c.Type
  217. s.mut.Unlock()
  218. continue next
  219. }
  220. }
  221. if !s.cfg.IgnoredDevice(remoteID) {
  222. events.Default.Log(events.DeviceRejected, map[string]string{
  223. "device": remoteID.String(),
  224. "address": c.Conn.RemoteAddr().String(),
  225. })
  226. }
  227. l.Infof("Connection from %s (%s) with ignored device ID %s", c.Conn.RemoteAddr(), c.Type, remoteID)
  228. c.Conn.Close()
  229. }
  230. }
  231. func (s *connectionSvc) connect() {
  232. delay := time.Second
  233. for {
  234. nextDevice:
  235. for deviceID, deviceCfg := range s.cfg.Devices() {
  236. if deviceID == s.myID {
  237. continue
  238. }
  239. if s.model.IsPaused(deviceID) {
  240. continue
  241. }
  242. connected := s.model.ConnectedTo(deviceID)
  243. s.mut.RLock()
  244. ct, ok := s.connType[deviceID]
  245. relaysEnabled := s.relaysEnabled
  246. s.mut.RUnlock()
  247. if connected && ok && ct.IsDirect() {
  248. continue
  249. }
  250. var addrs []string
  251. var relays []discover.Relay
  252. for _, addr := range deviceCfg.Addresses {
  253. if addr == "dynamic" {
  254. if s.discoverer != nil {
  255. if t, r, err := s.discoverer.Lookup(deviceID); err == nil {
  256. addrs = append(addrs, t...)
  257. relays = append(relays, r...)
  258. }
  259. }
  260. } else {
  261. addrs = append(addrs, addr)
  262. }
  263. }
  264. for _, addr := range addrs {
  265. uri, err := url.Parse(addr)
  266. if err != nil {
  267. l.Infoln("Failed to parse connection url:", addr, err)
  268. continue
  269. }
  270. dialer, ok := dialers[uri.Scheme]
  271. if !ok {
  272. l.Infoln("Unknown address schema", uri.String())
  273. continue
  274. }
  275. if debug {
  276. l.Debugln("dial", deviceCfg.DeviceID, uri.String())
  277. }
  278. conn, err := dialer(uri, s.tlsCfg)
  279. if err != nil {
  280. if debug {
  281. l.Debugln("dial failed", deviceCfg.DeviceID, uri.String(), err)
  282. }
  283. continue
  284. }
  285. if connected {
  286. s.model.Close(deviceID, fmt.Errorf("switching connections"))
  287. }
  288. s.conns <- model.IntermediateConnection{
  289. conn, model.ConnectionTypeDirectDial,
  290. }
  291. continue nextDevice
  292. }
  293. // Only connect via relays if not already connected
  294. // Also, do not set lastRelayCheck time if we have no relays,
  295. // as otherwise when we do discover relays, we might have to
  296. // wait up to RelayReconnectIntervalM to connect again.
  297. // Also, do not try relays if we are explicitly told not to.
  298. if connected || len(relays) == 0 || !relaysEnabled {
  299. continue nextDevice
  300. }
  301. reconIntv := time.Duration(s.cfg.Options().RelayReconnectIntervalM) * time.Minute
  302. if last, ok := s.lastRelayCheck[deviceID]; ok && time.Since(last) < reconIntv {
  303. if debug {
  304. l.Debugln("Skipping connecting via relay to", deviceID, "last checked at", last)
  305. }
  306. continue nextDevice
  307. } else if debug {
  308. l.Debugln("Trying relay connections to", deviceID, relays)
  309. }
  310. s.lastRelayCheck[deviceID] = time.Now()
  311. for _, addr := range relays {
  312. uri, err := url.Parse(addr.URL)
  313. if err != nil {
  314. l.Infoln("Failed to parse relay connection url:", addr, err)
  315. continue
  316. }
  317. inv, err := client.GetInvitationFromRelay(uri, deviceID, s.tlsCfg.Certificates)
  318. if err != nil {
  319. if debug {
  320. l.Debugf("Failed to get invitation for %s from %s: %v", deviceID, uri, err)
  321. }
  322. continue
  323. } else if debug {
  324. l.Debugln("Succesfully retrieved relay invitation", inv, "from", uri)
  325. }
  326. conn, err := client.JoinSession(inv)
  327. if err != nil {
  328. if debug {
  329. l.Debugf("Failed to join relay session %s: %v", inv, err)
  330. }
  331. continue
  332. } else if debug {
  333. l.Debugln("Sucessfully joined relay session", inv)
  334. }
  335. err = osutil.SetTCPOptions(conn.(*net.TCPConn))
  336. if err != nil {
  337. l.Infoln(err)
  338. }
  339. var tc *tls.Conn
  340. if inv.ServerSocket {
  341. tc = tls.Server(conn, s.tlsCfg)
  342. } else {
  343. tc = tls.Client(conn, s.tlsCfg)
  344. }
  345. err = tc.Handshake()
  346. if err != nil {
  347. l.Infof("TLS handshake (BEP/relay %s): %v", inv, err)
  348. tc.Close()
  349. continue
  350. }
  351. s.conns <- model.IntermediateConnection{
  352. tc, model.ConnectionTypeRelayDial,
  353. }
  354. continue nextDevice
  355. }
  356. }
  357. time.Sleep(delay)
  358. delay *= 2
  359. if maxD := time.Duration(s.cfg.Options().ReconnectIntervalS) * time.Second; delay > maxD {
  360. delay = maxD
  361. }
  362. }
  363. }
  364. func (s *connectionSvc) acceptRelayConns() {
  365. for {
  366. conn := s.relaySvc.Accept()
  367. s.conns <- model.IntermediateConnection{
  368. Conn: conn,
  369. Type: model.ConnectionTypeRelayAccept,
  370. }
  371. }
  372. }
  373. func (s *connectionSvc) shouldLimit(addr net.Addr) bool {
  374. if s.cfg.Options().LimitBandwidthInLan {
  375. return true
  376. }
  377. tcpaddr, ok := addr.(*net.TCPAddr)
  378. if !ok {
  379. return true
  380. }
  381. for _, lan := range s.lans {
  382. if lan.Contains(tcpaddr.IP) {
  383. return false
  384. }
  385. }
  386. return !tcpaddr.IP.IsLoopback()
  387. }
  388. func (s *connectionSvc) VerifyConfiguration(from, to config.Configuration) error {
  389. return nil
  390. }
  391. func (s *connectionSvc) CommitConfiguration(from, to config.Configuration) bool {
  392. s.mut.Lock()
  393. s.relaysEnabled = to.Options.RelaysEnabled
  394. s.mut.Unlock()
  395. // We require a restart if a device as been removed.
  396. newDevices := make(map[protocol.DeviceID]bool, len(to.Devices))
  397. for _, dev := range to.Devices {
  398. newDevices[dev.DeviceID] = true
  399. }
  400. for _, dev := range from.Devices {
  401. if !newDevices[dev.DeviceID] {
  402. return false
  403. }
  404. }
  405. return true
  406. }
  407. // serviceFunc wraps a function to create a suture.Service without stop
  408. // functionality.
  409. type serviceFunc func()
  410. func (f serviceFunc) Serve() { f() }
  411. func (f serviceFunc) Stop() {}