dynamic.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. // Copyright (C) 2015 Audrius Butkevicius and Contributors (see the CONTRIBUTORS file).
  2. package client
  3. import (
  4. "crypto/tls"
  5. "encoding/json"
  6. "fmt"
  7. "math/rand"
  8. "net/http"
  9. "net/url"
  10. "sort"
  11. "time"
  12. "github.com/syncthing/syncthing/lib/osutil"
  13. "github.com/syncthing/syncthing/lib/relay/protocol"
  14. "github.com/syncthing/syncthing/lib/sync"
  15. )
  16. type dynamicClient struct {
  17. pooladdr *url.URL
  18. certs []tls.Certificate
  19. invitations chan protocol.SessionInvitation
  20. closeInvitationsOnFinish bool
  21. timeout time.Duration
  22. mut sync.RWMutex
  23. client RelayClient
  24. stop chan struct{}
  25. }
  26. func newDynamicClient(uri *url.URL, certs []tls.Certificate, invitations chan protocol.SessionInvitation, timeout time.Duration) RelayClient {
  27. closeInvitationsOnFinish := false
  28. if invitations == nil {
  29. closeInvitationsOnFinish = true
  30. invitations = make(chan protocol.SessionInvitation)
  31. }
  32. return &dynamicClient{
  33. pooladdr: uri,
  34. certs: certs,
  35. invitations: invitations,
  36. closeInvitationsOnFinish: closeInvitationsOnFinish,
  37. timeout: timeout,
  38. mut: sync.NewRWMutex(),
  39. }
  40. }
  41. func (c *dynamicClient) Serve() {
  42. c.mut.Lock()
  43. c.stop = make(chan struct{})
  44. c.mut.Unlock()
  45. uri := *c.pooladdr
  46. // Trim off the `dynamic+` prefix
  47. uri.Scheme = uri.Scheme[8:]
  48. l.Debugln(c, "looking up dynamic relays")
  49. data, err := http.Get(uri.String())
  50. if err != nil {
  51. l.Debugln(c, "failed to lookup dynamic relays", err)
  52. return
  53. }
  54. var ann dynamicAnnouncement
  55. err = json.NewDecoder(data.Body).Decode(&ann)
  56. data.Body.Close()
  57. if err != nil {
  58. l.Debugln(c, "failed to lookup dynamic relays", err)
  59. return
  60. }
  61. defer c.cleanup()
  62. var addrs []string
  63. for _, relayAnn := range ann.Relays {
  64. ruri, err := url.Parse(relayAnn.URL)
  65. if err != nil {
  66. l.Debugln(c, "failed to parse dynamic relay address", relayAnn.URL, err)
  67. continue
  68. }
  69. l.Debugln(c, "found", ruri)
  70. addrs = append(addrs, ruri.String())
  71. }
  72. for _, addr := range relayAddressesOrder(addrs) {
  73. select {
  74. case <-c.stop:
  75. l.Debugln(c, "stopping")
  76. return
  77. default:
  78. ruri, err := url.Parse(addr)
  79. if err != nil {
  80. l.Debugln(c, "skipping relay", addr, err)
  81. continue
  82. }
  83. client, err := NewClient(ruri, c.certs, c.invitations, c.timeout)
  84. if err != nil {
  85. continue
  86. }
  87. c.mut.Lock()
  88. c.client = client
  89. c.mut.Unlock()
  90. c.client.Serve()
  91. c.mut.Lock()
  92. c.client = nil
  93. c.mut.Unlock()
  94. }
  95. }
  96. l.Debugln(c, "could not find a connectable relay")
  97. }
  98. func (c *dynamicClient) Stop() {
  99. c.mut.RLock()
  100. defer c.mut.RUnlock()
  101. close(c.stop)
  102. if c.client == nil {
  103. return
  104. }
  105. c.client.Stop()
  106. }
  107. func (c *dynamicClient) StatusOK() bool {
  108. c.mut.RLock()
  109. defer c.mut.RUnlock()
  110. if c.client == nil {
  111. return false
  112. }
  113. return c.client.StatusOK()
  114. }
  115. func (c *dynamicClient) Latency() time.Duration {
  116. c.mut.RLock()
  117. defer c.mut.RUnlock()
  118. if c.client == nil {
  119. return time.Hour
  120. }
  121. return c.client.Latency()
  122. }
  123. func (c *dynamicClient) String() string {
  124. return fmt.Sprintf("DynamicClient:%p:%s@%s", c, c.URI(), c.pooladdr)
  125. }
  126. func (c *dynamicClient) URI() *url.URL {
  127. c.mut.RLock()
  128. defer c.mut.RUnlock()
  129. if c.client == nil {
  130. return c.pooladdr
  131. }
  132. return c.client.URI()
  133. }
  134. func (c *dynamicClient) Invitations() chan protocol.SessionInvitation {
  135. c.mut.RLock()
  136. inv := c.invitations
  137. c.mut.RUnlock()
  138. return inv
  139. }
  140. func (c *dynamicClient) cleanup() {
  141. c.mut.Lock()
  142. if c.closeInvitationsOnFinish {
  143. close(c.invitations)
  144. c.invitations = make(chan protocol.SessionInvitation)
  145. }
  146. c.mut.Unlock()
  147. }
  148. // This is the announcement recieved from the relay server;
  149. // {"relays": [{"url": "relay://10.20.30.40:5060"}, ...]}
  150. type dynamicAnnouncement struct {
  151. Relays []struct {
  152. URL string
  153. }
  154. }
  155. // relayAddressesOrder checks the latency to each relay, rounds latency down to
  156. // the closest 50ms, and puts them in buckets of 50ms latency ranges. Then
  157. // shuffles each bucket, and returns all addresses starting with the ones from
  158. // the lowest latency bucket, ending with the highest latency buceket.
  159. func relayAddressesOrder(input []string) []string {
  160. buckets := make(map[int][]string)
  161. for _, relay := range input {
  162. latency, err := osutil.GetLatencyForURL(relay)
  163. if err != nil {
  164. latency = time.Hour
  165. }
  166. id := int(latency/time.Millisecond) / 50
  167. buckets[id] = append(buckets[id], relay)
  168. }
  169. var ids []int
  170. for id, bucket := range buckets {
  171. shuffle(bucket)
  172. ids = append(ids, id)
  173. }
  174. sort.Ints(ids)
  175. addresses := make([]string, len(input))
  176. for _, id := range ids {
  177. addresses = append(addresses, buckets[id]...)
  178. }
  179. return addresses
  180. }
  181. func shuffle(slice []string) {
  182. for i := len(slice) - 1; i > 0; i-- {
  183. j := rand.Intn(i + 1)
  184. slice[i], slice[j] = slice[j], slice[i]
  185. }
  186. }