static.go 6.9 KB

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