client.go 5.5 KB

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