static.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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.Debugf("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.Debugf("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.Debugln("Relay set deadline:", err)
  48. return err
  49. }
  50. l.Infof("Joined relay %s://%s", c.uri.Scheme, c.uri.Host)
  51. c.mut.Lock()
  52. c.connected = true
  53. c.mut.Unlock()
  54. messages := make(chan interface{})
  55. errorsc := make(chan error, 1)
  56. go messageReader(ctx, c.conn, messages, errorsc)
  57. timeout := time.NewTimer(c.messageTimeout)
  58. for {
  59. select {
  60. case message := <-messages:
  61. timeout.Reset(c.messageTimeout)
  62. l.Debugf("%s received message %T", c, message)
  63. switch msg := message.(type) {
  64. case protocol.Ping:
  65. if err := protocol.WriteMessage(c.conn, protocol.Pong{}); err != nil {
  66. l.Debugln("Relay write:", err)
  67. return err
  68. }
  69. l.Debugln(c, "sent pong")
  70. case protocol.SessionInvitation:
  71. ip := net.IP(msg.Address)
  72. if len(ip) == 0 || ip.IsUnspecified() {
  73. msg.Address = remoteIPBytes(c.conn)
  74. }
  75. select {
  76. case c.invitations <- msg:
  77. case <-ctx.Done():
  78. l.Debugln(c, "stopping")
  79. return ctx.Err()
  80. }
  81. case protocol.RelayFull:
  82. l.Debugf("Disconnected from relay %s due to it becoming full.", c.uri)
  83. return errors.New("relay full")
  84. default:
  85. l.Debugln("Relay: protocol error: unexpected message %v", msg)
  86. return fmt.Errorf("protocol error: unexpected message %v", msg)
  87. }
  88. case <-ctx.Done():
  89. l.Debugln(c, "stopping")
  90. return ctx.Err()
  91. case err := <-errorsc:
  92. l.Debugf("Disconnecting from relay %s due to error: %s", c.uri, err)
  93. return err
  94. case <-timeout.C:
  95. l.Debugln(c, "timed out")
  96. return errors.New("timed out")
  97. }
  98. }
  99. }
  100. func (c *staticClient) StatusOK() bool {
  101. c.mut.RLock()
  102. con := c.connected
  103. c.mut.RUnlock()
  104. return con
  105. }
  106. func (c *staticClient) Latency() time.Duration {
  107. c.mut.RLock()
  108. lat := c.latency
  109. c.mut.RUnlock()
  110. return lat
  111. }
  112. func (c *staticClient) String() string {
  113. return fmt.Sprintf("StaticClient:%p@%s", c, c.URI())
  114. }
  115. func (c *staticClient) URI() *url.URL {
  116. return c.uri
  117. }
  118. func (c *staticClient) connect(ctx context.Context) error {
  119. if c.uri.Scheme != "relay" {
  120. return fmt.Errorf("unsupported relay scheme: %v", c.uri.Scheme)
  121. }
  122. t0 := time.Now()
  123. timeoutCtx, cancel := context.WithTimeout(ctx, c.connectTimeout)
  124. defer cancel()
  125. tcpConn, err := dialer.DialContext(timeoutCtx, "tcp", c.uri.Host)
  126. if err != nil {
  127. return err
  128. }
  129. c.mut.Lock()
  130. c.latency = time.Since(t0)
  131. c.mut.Unlock()
  132. conn := tls.Client(tcpConn, c.config)
  133. if err := conn.SetDeadline(time.Now().Add(c.connectTimeout)); err != nil {
  134. conn.Close()
  135. return err
  136. }
  137. if err := performHandshakeAndValidation(conn, c.uri); err != nil {
  138. conn.Close()
  139. return err
  140. }
  141. c.conn = conn
  142. return nil
  143. }
  144. func (c *staticClient) disconnect() {
  145. l.Debugln(c, "disconnecting")
  146. c.mut.Lock()
  147. c.connected = false
  148. c.mut.Unlock()
  149. c.conn.Close()
  150. }
  151. func (c *staticClient) join() error {
  152. if err := protocol.WriteMessage(c.conn, protocol.JoinRelayRequest{}); err != nil {
  153. return err
  154. }
  155. message, err := protocol.ReadMessage(c.conn)
  156. if err != nil {
  157. return err
  158. }
  159. switch msg := message.(type) {
  160. case protocol.Response:
  161. if msg.Code != 0 {
  162. return &incorrectResponseCodeErr{msg.Code, msg.Message}
  163. }
  164. case protocol.RelayFull:
  165. return errors.New("relay full")
  166. default:
  167. return fmt.Errorf("protocol error: expecting response got %v", msg)
  168. }
  169. return nil
  170. }
  171. func performHandshakeAndValidation(conn *tls.Conn, uri *url.URL) error {
  172. if err := conn.Handshake(); err != nil {
  173. return err
  174. }
  175. cs := conn.ConnectionState()
  176. if !cs.NegotiatedProtocolIsMutual || cs.NegotiatedProtocol != protocol.ProtocolName {
  177. return errors.New("protocol negotiation error")
  178. }
  179. q := uri.Query()
  180. relayIDs := q.Get("id")
  181. if relayIDs != "" {
  182. relayID, err := syncthingprotocol.DeviceIDFromString(relayIDs)
  183. if err != nil {
  184. return errors.Wrap(err, "relay address contains invalid verification id")
  185. }
  186. certs := cs.PeerCertificates
  187. if cl := len(certs); cl != 1 {
  188. return fmt.Errorf("unexpected certificate count: %d", cl)
  189. }
  190. remoteID := syncthingprotocol.NewDeviceID(certs[0].Raw)
  191. if remoteID != relayID {
  192. return fmt.Errorf("relay id does not match. Expected %v got %v", relayID, remoteID)
  193. }
  194. }
  195. return nil
  196. }
  197. func messageReader(ctx context.Context, conn net.Conn, messages chan<- interface{}, errors chan<- error) {
  198. for {
  199. msg, err := protocol.ReadMessage(conn)
  200. if err != nil {
  201. errors <- err
  202. return
  203. }
  204. select {
  205. case messages <- msg:
  206. case <-ctx.Done():
  207. return
  208. }
  209. }
  210. }