static.go 6.1 KB

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