static.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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(); 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() error {
  115. if c.uri.Scheme != "relay" {
  116. return fmt.Errorf("unsupported relay scheme: %v", c.uri.Scheme)
  117. }
  118. t0 := time.Now()
  119. tcpConn, err := dialer.DialTimeout("tcp", c.uri.Host, c.connectTimeout)
  120. if err != nil {
  121. return err
  122. }
  123. c.mut.Lock()
  124. c.latency = time.Since(t0)
  125. c.mut.Unlock()
  126. conn := tls.Client(tcpConn, c.config)
  127. if err := conn.SetDeadline(time.Now().Add(c.connectTimeout)); err != nil {
  128. conn.Close()
  129. return err
  130. }
  131. if err := performHandshakeAndValidation(conn, c.uri); err != nil {
  132. conn.Close()
  133. return err
  134. }
  135. c.conn = conn
  136. return nil
  137. }
  138. func (c *staticClient) disconnect() {
  139. l.Debugln(c, "disconnecting")
  140. c.mut.Lock()
  141. c.connected = false
  142. c.mut.Unlock()
  143. c.conn.Close()
  144. }
  145. func (c *staticClient) join() error {
  146. if err := protocol.WriteMessage(c.conn, protocol.JoinRelayRequest{}); err != nil {
  147. return err
  148. }
  149. message, err := protocol.ReadMessage(c.conn)
  150. if err != nil {
  151. return err
  152. }
  153. switch msg := message.(type) {
  154. case protocol.Response:
  155. if msg.Code != 0 {
  156. return fmt.Errorf("incorrect response code %d: %s", msg.Code, msg.Message)
  157. }
  158. case protocol.RelayFull:
  159. return fmt.Errorf("relay full")
  160. default:
  161. return fmt.Errorf("protocol error: expecting response got %v", msg)
  162. }
  163. return nil
  164. }
  165. func performHandshakeAndValidation(conn *tls.Conn, uri *url.URL) error {
  166. if err := conn.Handshake(); err != nil {
  167. return err
  168. }
  169. cs := conn.ConnectionState()
  170. if !cs.NegotiatedProtocolIsMutual || cs.NegotiatedProtocol != protocol.ProtocolName {
  171. return fmt.Errorf("protocol negotiation error")
  172. }
  173. q := uri.Query()
  174. relayIDs := q.Get("id")
  175. if relayIDs != "" {
  176. relayID, err := syncthingprotocol.DeviceIDFromString(relayIDs)
  177. if err != nil {
  178. return errors.Wrap(err, "relay address contains invalid verification id")
  179. }
  180. certs := cs.PeerCertificates
  181. if cl := len(certs); cl != 1 {
  182. return fmt.Errorf("unexpected certificate count: %d", cl)
  183. }
  184. remoteID := syncthingprotocol.NewDeviceID(certs[0].Raw)
  185. if remoteID != relayID {
  186. return fmt.Errorf("relay id does not match. Expected %v got %v", relayID, remoteID)
  187. }
  188. }
  189. return nil
  190. }
  191. func messageReader(ctx context.Context, conn net.Conn, messages chan<- interface{}, errors chan<- error) {
  192. for {
  193. msg, err := protocol.ReadMessage(conn)
  194. if err != nil {
  195. errors <- err
  196. return
  197. }
  198. select {
  199. case messages <- msg:
  200. case <-ctx.Done():
  201. return
  202. }
  203. }
  204. }