connections.go 13 KB

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