static.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. // Copyright (C) 2015 Audrius Butkevicius and Contributors (see the CONTRIBUTORS file).
  2. package client
  3. import (
  4. "crypto/tls"
  5. "fmt"
  6. "net"
  7. "net/url"
  8. "time"
  9. "github.com/syncthing/syncthing/lib/dialer"
  10. syncthingprotocol "github.com/syncthing/syncthing/lib/protocol"
  11. "github.com/syncthing/syncthing/lib/relay/protocol"
  12. "github.com/syncthing/syncthing/lib/sync"
  13. )
  14. type staticClient struct {
  15. uri *url.URL
  16. invitations chan protocol.SessionInvitation
  17. closeInvitationsOnFinish bool
  18. config *tls.Config
  19. messageTimeout time.Duration
  20. connectTimeout time.Duration
  21. stop chan struct{}
  22. stopped chan struct{}
  23. stopMut sync.RWMutex
  24. conn *tls.Conn
  25. mut sync.RWMutex
  26. err error
  27. connected bool
  28. latency time.Duration
  29. }
  30. func newStaticClient(uri *url.URL, certs []tls.Certificate, invitations chan protocol.SessionInvitation, timeout time.Duration) RelayClient {
  31. closeInvitationsOnFinish := false
  32. if invitations == nil {
  33. closeInvitationsOnFinish = true
  34. invitations = make(chan protocol.SessionInvitation)
  35. }
  36. stopped := make(chan struct{})
  37. close(stopped) // not yet started, don't block on Stop()
  38. return &staticClient{
  39. uri: uri,
  40. invitations: invitations,
  41. closeInvitationsOnFinish: closeInvitationsOnFinish,
  42. config: configForCerts(certs),
  43. messageTimeout: time.Minute * 2,
  44. connectTimeout: timeout,
  45. stop: make(chan struct{}),
  46. stopped: stopped,
  47. stopMut: sync.NewRWMutex(),
  48. mut: sync.NewRWMutex(),
  49. }
  50. }
  51. func (c *staticClient) Serve() {
  52. defer c.cleanup()
  53. c.stopMut.Lock()
  54. c.stop = make(chan struct{})
  55. c.stopped = make(chan struct{})
  56. c.stopMut.Unlock()
  57. defer close(c.stopped)
  58. if err := c.connect(); err != nil {
  59. l.Infof("Could not connect to relay %s: %s", c.uri, err)
  60. c.setError(err)
  61. return
  62. }
  63. l.Debugln(c, "connected", c.conn.RemoteAddr())
  64. if err := c.join(); err != nil {
  65. c.conn.Close()
  66. l.Infof("Could not join relay %s: %s", c.uri, err)
  67. c.setError(err)
  68. return
  69. }
  70. if err := c.conn.SetDeadline(time.Time{}); err != nil {
  71. c.conn.Close()
  72. l.Infoln("Relay set deadline:", err)
  73. c.setError(err)
  74. return
  75. }
  76. l.Infof("Joined relay %s://%s", c.uri.Scheme, c.uri.Host)
  77. defer l.Infof("Disconnected from relay %s://%s", c.uri.Scheme, c.uri.Host)
  78. c.mut.Lock()
  79. c.connected = true
  80. c.mut.Unlock()
  81. messages := make(chan interface{})
  82. errors := make(chan error, 1)
  83. go messageReader(c.conn, messages, errors)
  84. timeout := time.NewTimer(c.messageTimeout)
  85. c.stopMut.RLock()
  86. defer c.stopMut.RUnlock()
  87. for {
  88. select {
  89. case message := <-messages:
  90. timeout.Reset(c.messageTimeout)
  91. l.Debugf("%s received message %T", c, message)
  92. switch msg := message.(type) {
  93. case protocol.Ping:
  94. if err := protocol.WriteMessage(c.conn, protocol.Pong{}); err != nil {
  95. l.Infoln("Relay write:", err)
  96. c.setError(err)
  97. c.disconnect()
  98. } else {
  99. l.Debugln(c, "sent pong")
  100. }
  101. case protocol.SessionInvitation:
  102. ip := net.IP(msg.Address)
  103. if len(ip) == 0 || ip.IsUnspecified() {
  104. msg.Address = remoteIPBytes(c.conn)
  105. }
  106. c.invitations <- msg
  107. case protocol.RelayFull:
  108. l.Infof("Disconnected from relay %s due to it becoming full.", c.uri)
  109. c.setError(fmt.Errorf("Relay full"))
  110. c.disconnect()
  111. default:
  112. l.Infoln("Relay: protocol error: unexpected message %v", msg)
  113. c.setError(fmt.Errorf("protocol error: unexpected message %v", msg))
  114. c.disconnect()
  115. }
  116. case <-c.stop:
  117. l.Debugln(c, "stopping")
  118. c.setError(nil)
  119. c.disconnect()
  120. // We always exit via this branch of the select, to make sure the
  121. // the reader routine exits.
  122. case err := <-errors:
  123. close(errors)
  124. close(messages)
  125. c.mut.Lock()
  126. if c.connected {
  127. c.conn.Close()
  128. c.connected = false
  129. l.Infof("Disconnecting from relay %s due to error: %s", c.uri, err)
  130. c.err = err
  131. } else {
  132. c.err = nil
  133. }
  134. c.mut.Unlock()
  135. return
  136. case <-timeout.C:
  137. l.Debugln(c, "timed out")
  138. c.disconnect()
  139. c.setError(fmt.Errorf("timed out"))
  140. }
  141. }
  142. }
  143. func (c *staticClient) Stop() {
  144. c.stopMut.RLock()
  145. close(c.stop)
  146. <-c.stopped
  147. c.stopMut.RUnlock()
  148. }
  149. func (c *staticClient) StatusOK() bool {
  150. c.mut.RLock()
  151. con := c.connected
  152. c.mut.RUnlock()
  153. return con
  154. }
  155. func (c *staticClient) Latency() time.Duration {
  156. c.mut.RLock()
  157. lat := c.latency
  158. c.mut.RUnlock()
  159. return lat
  160. }
  161. func (c *staticClient) String() string {
  162. return fmt.Sprintf("StaticClient:%p@%s", c, c.URI())
  163. }
  164. func (c *staticClient) URI() *url.URL {
  165. return c.uri
  166. }
  167. func (c *staticClient) Invitations() chan protocol.SessionInvitation {
  168. c.mut.RLock()
  169. inv := c.invitations
  170. c.mut.RUnlock()
  171. return inv
  172. }
  173. func (c *staticClient) cleanup() {
  174. c.mut.Lock()
  175. if c.closeInvitationsOnFinish {
  176. close(c.invitations)
  177. c.invitations = make(chan protocol.SessionInvitation)
  178. }
  179. c.mut.Unlock()
  180. }
  181. func (c *staticClient) connect() error {
  182. if c.uri.Scheme != "relay" {
  183. return fmt.Errorf("Unsupported relay schema: %v", c.uri.Scheme)
  184. }
  185. t0 := time.Now()
  186. tcpConn, err := dialer.DialTimeout("tcp", c.uri.Host, c.connectTimeout)
  187. if err != nil {
  188. return err
  189. }
  190. c.mut.Lock()
  191. c.latency = time.Since(t0)
  192. c.mut.Unlock()
  193. conn := tls.Client(tcpConn, c.config)
  194. if err := conn.SetDeadline(time.Now().Add(c.connectTimeout)); err != nil {
  195. conn.Close()
  196. return err
  197. }
  198. if err := performHandshakeAndValidation(conn, c.uri); err != nil {
  199. conn.Close()
  200. return err
  201. }
  202. c.conn = conn
  203. return nil
  204. }
  205. func (c *staticClient) disconnect() {
  206. l.Debugln(c, "disconnecting")
  207. c.mut.Lock()
  208. c.connected = false
  209. c.mut.Unlock()
  210. c.conn.Close()
  211. }
  212. func (c *staticClient) setError(err error) {
  213. c.mut.Lock()
  214. c.err = err
  215. c.mut.Unlock()
  216. }
  217. func (c *staticClient) Error() error {
  218. c.mut.RLock()
  219. err := c.err
  220. c.mut.RUnlock()
  221. return err
  222. }
  223. func (c *staticClient) join() error {
  224. if err := protocol.WriteMessage(c.conn, protocol.JoinRelayRequest{}); err != nil {
  225. return err
  226. }
  227. message, err := protocol.ReadMessage(c.conn)
  228. if err != nil {
  229. return err
  230. }
  231. switch msg := message.(type) {
  232. case protocol.Response:
  233. if msg.Code != 0 {
  234. return fmt.Errorf("Incorrect response code %d: %s", msg.Code, msg.Message)
  235. }
  236. case protocol.RelayFull:
  237. return fmt.Errorf("relay full")
  238. default:
  239. return fmt.Errorf("protocol error: expecting response got %v", msg)
  240. }
  241. return nil
  242. }
  243. func performHandshakeAndValidation(conn *tls.Conn, uri *url.URL) error {
  244. if err := conn.Handshake(); err != nil {
  245. return err
  246. }
  247. cs := conn.ConnectionState()
  248. if !cs.NegotiatedProtocolIsMutual || cs.NegotiatedProtocol != protocol.ProtocolName {
  249. return fmt.Errorf("protocol negotiation error")
  250. }
  251. q := uri.Query()
  252. relayIDs := q.Get("id")
  253. if relayIDs != "" {
  254. relayID, err := syncthingprotocol.DeviceIDFromString(relayIDs)
  255. if err != nil {
  256. return fmt.Errorf("relay address contains invalid verification id: %s", err)
  257. }
  258. certs := cs.PeerCertificates
  259. if cl := len(certs); cl != 1 {
  260. return fmt.Errorf("unexpected certificate count: %d", cl)
  261. }
  262. remoteID := syncthingprotocol.NewDeviceID(certs[0].Raw)
  263. if remoteID != relayID {
  264. return fmt.Errorf("relay id does not match. Expected %v got %v", relayID, remoteID)
  265. }
  266. }
  267. return nil
  268. }
  269. func messageReader(conn net.Conn, messages chan<- interface{}, errors chan<- error) {
  270. for {
  271. msg, err := protocol.ReadMessage(conn)
  272. if err != nil {
  273. errors <- err
  274. return
  275. }
  276. messages <- msg
  277. }
  278. }