static.go 5.4 KB

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