static.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. // Copyright (C) 2015 Audrius Butkevicius and Contributors (see the CONTRIBUTORS file).
  2. package client
  3. import (
  4. "context"
  5. "crypto/tls"
  6. "fmt"
  7. "net"
  8. "net/url"
  9. "time"
  10. "github.com/pkg/errors"
  11. "github.com/syncthing/syncthing/lib/dialer"
  12. syncthingprotocol "github.com/syncthing/syncthing/lib/protocol"
  13. "github.com/syncthing/syncthing/lib/relay/protocol"
  14. )
  15. type staticClient struct {
  16. commonClient
  17. uri *url.URL
  18. config *tls.Config
  19. messageTimeout time.Duration
  20. connectTimeout time.Duration
  21. conn *tls.Conn
  22. connected bool
  23. latency time.Duration
  24. }
  25. func newStaticClient(uri *url.URL, certs []tls.Certificate, invitations chan protocol.SessionInvitation, timeout time.Duration) RelayClient {
  26. c := &staticClient{
  27. uri: uri,
  28. config: configForCerts(certs),
  29. messageTimeout: time.Minute * 2,
  30. connectTimeout: timeout,
  31. }
  32. c.commonClient = newCommonClient(invitations, c.serve, c.String())
  33. return c
  34. }
  35. func (c *staticClient) serve(ctx context.Context) error {
  36. if err := c.connect(ctx); err != nil {
  37. l.Infof("Could not connect to relay %s: %s", c.uri, err)
  38. return err
  39. }
  40. l.Debugln(c, "connected", c.conn.RemoteAddr())
  41. defer c.disconnect()
  42. if err := c.join(); err != nil {
  43. l.Infof("Could not join relay %s: %s", c.uri, err)
  44. return err
  45. }
  46. if err := c.conn.SetDeadline(time.Time{}); err != nil {
  47. l.Infoln("Relay set deadline:", err)
  48. return err
  49. }
  50. l.Infof("Joined relay %s://%s", c.uri.Scheme, c.uri.Host)
  51. defer l.Infof("Disconnected from relay %s://%s", c.uri.Scheme, c.uri.Host)
  52. c.mut.Lock()
  53. c.connected = true
  54. c.mut.Unlock()
  55. messages := make(chan interface{})
  56. errors := make(chan error, 1)
  57. go messageReader(ctx, c.conn, messages, errors)
  58. timeout := time.NewTimer(c.messageTimeout)
  59. for {
  60. select {
  61. case message := <-messages:
  62. timeout.Reset(c.messageTimeout)
  63. l.Debugf("%s received message %T", c, message)
  64. switch msg := message.(type) {
  65. case protocol.Ping:
  66. if err := protocol.WriteMessage(c.conn, protocol.Pong{}); err != nil {
  67. l.Infoln("Relay write:", err)
  68. return err
  69. }
  70. l.Debugln(c, "sent pong")
  71. case protocol.SessionInvitation:
  72. ip := net.IP(msg.Address)
  73. if len(ip) == 0 || ip.IsUnspecified() {
  74. msg.Address = remoteIPBytes(c.conn)
  75. }
  76. c.invitations <- msg
  77. case protocol.RelayFull:
  78. l.Infof("Disconnected from relay %s due to it becoming full.", c.uri)
  79. return fmt.Errorf("relay full")
  80. default:
  81. l.Infoln("Relay: protocol error: unexpected message %v", msg)
  82. return fmt.Errorf("protocol error: unexpected message %v", msg)
  83. }
  84. case <-ctx.Done():
  85. l.Debugln(c, "stopping")
  86. return nil
  87. case err := <-errors:
  88. l.Infof("Disconnecting from relay %s due to error: %s", c.uri, err)
  89. return err
  90. case <-timeout.C:
  91. l.Debugln(c, "timed out")
  92. return fmt.Errorf("timed out")
  93. }
  94. }
  95. }
  96. func (c *staticClient) StatusOK() bool {
  97. c.mut.RLock()
  98. con := c.connected
  99. c.mut.RUnlock()
  100. return con
  101. }
  102. func (c *staticClient) Latency() time.Duration {
  103. c.mut.RLock()
  104. lat := c.latency
  105. c.mut.RUnlock()
  106. return lat
  107. }
  108. func (c *staticClient) String() string {
  109. return fmt.Sprintf("StaticClient:%p@%s", c, c.URI())
  110. }
  111. func (c *staticClient) URI() *url.URL {
  112. return c.uri
  113. }
  114. func (c *staticClient) connect(ctx context.Context) error {
  115. if c.uri.Scheme != "relay" {
  116. return fmt.Errorf("unsupported relay scheme: %v", c.uri.Scheme)
  117. }
  118. t0 := time.Now()
  119. timeoutCtx, cancel := context.WithTimeout(ctx, time.Second)
  120. defer cancel()
  121. tcpConn, err := dialer.DialContext(timeoutCtx, "tcp", c.uri.Host)
  122. if err != nil {
  123. return err
  124. }
  125. c.mut.Lock()
  126. c.latency = time.Since(t0)
  127. c.mut.Unlock()
  128. conn := tls.Client(tcpConn, c.config)
  129. if err := conn.SetDeadline(time.Now().Add(c.connectTimeout)); err != nil {
  130. conn.Close()
  131. return err
  132. }
  133. if err := performHandshakeAndValidation(conn, c.uri); err != nil {
  134. conn.Close()
  135. return err
  136. }
  137. c.conn = conn
  138. return nil
  139. }
  140. func (c *staticClient) disconnect() {
  141. l.Debugln(c, "disconnecting")
  142. c.mut.Lock()
  143. c.connected = false
  144. c.mut.Unlock()
  145. c.conn.Close()
  146. }
  147. func (c *staticClient) join() error {
  148. if err := protocol.WriteMessage(c.conn, protocol.JoinRelayRequest{}); err != nil {
  149. return err
  150. }
  151. message, err := protocol.ReadMessage(c.conn)
  152. if err != nil {
  153. return err
  154. }
  155. switch msg := message.(type) {
  156. case protocol.Response:
  157. if msg.Code != 0 {
  158. return fmt.Errorf("incorrect response code %d: %s", msg.Code, msg.Message)
  159. }
  160. case protocol.RelayFull:
  161. return fmt.Errorf("relay full")
  162. default:
  163. return fmt.Errorf("protocol error: expecting response got %v", msg)
  164. }
  165. return nil
  166. }
  167. func performHandshakeAndValidation(conn *tls.Conn, uri *url.URL) error {
  168. if err := conn.Handshake(); err != nil {
  169. return err
  170. }
  171. cs := conn.ConnectionState()
  172. if !cs.NegotiatedProtocolIsMutual || cs.NegotiatedProtocol != protocol.ProtocolName {
  173. return fmt.Errorf("protocol negotiation error")
  174. }
  175. q := uri.Query()
  176. relayIDs := q.Get("id")
  177. if relayIDs != "" {
  178. relayID, err := syncthingprotocol.DeviceIDFromString(relayIDs)
  179. if err != nil {
  180. return errors.Wrap(err, "relay address contains invalid verification id")
  181. }
  182. certs := cs.PeerCertificates
  183. if cl := len(certs); cl != 1 {
  184. return fmt.Errorf("unexpected certificate count: %d", cl)
  185. }
  186. remoteID := syncthingprotocol.NewDeviceID(certs[0].Raw)
  187. if remoteID != relayID {
  188. return fmt.Errorf("relay id does not match. Expected %v got %v", relayID, remoteID)
  189. }
  190. }
  191. return nil
  192. }
  193. func messageReader(ctx context.Context, conn net.Conn, messages chan<- interface{}, errors chan<- error) {
  194. for {
  195. msg, err := protocol.ReadMessage(conn)
  196. if err != nil {
  197. errors <- err
  198. return
  199. }
  200. select {
  201. case messages <- msg:
  202. case <-ctx.Done():
  203. return
  204. }
  205. }
  206. }