connections.go 13 KB

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