main.go 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. // Copyright (C) 2015 Audrius Butkevicius and Contributors.
  2. package main
  3. import (
  4. "context"
  5. "crypto/tls"
  6. "flag"
  7. "fmt"
  8. "log"
  9. "net"
  10. "net/http"
  11. "net/url"
  12. "os"
  13. "os/signal"
  14. "path/filepath"
  15. "strings"
  16. "sync/atomic"
  17. "syscall"
  18. "time"
  19. "github.com/syncthing/syncthing/lib/build"
  20. "github.com/syncthing/syncthing/lib/events"
  21. "github.com/syncthing/syncthing/lib/osutil"
  22. "github.com/syncthing/syncthing/lib/relay/protocol"
  23. "github.com/syncthing/syncthing/lib/tlsutil"
  24. "golang.org/x/time/rate"
  25. "github.com/syncthing/syncthing/lib/config"
  26. "github.com/syncthing/syncthing/lib/nat"
  27. _ "github.com/syncthing/syncthing/lib/pmp"
  28. _ "github.com/syncthing/syncthing/lib/upnp"
  29. syncthingprotocol "github.com/syncthing/syncthing/lib/protocol"
  30. )
  31. var (
  32. listen string
  33. debug bool
  34. sessionAddress []byte
  35. sessionPort uint16
  36. networkTimeout = 2 * time.Minute
  37. pingInterval = time.Minute
  38. messageTimeout = time.Minute
  39. limitCheckTimer *time.Timer
  40. sessionLimitBps int
  41. globalLimitBps int
  42. overLimit int32
  43. descriptorLimit int64
  44. sessionLimiter *rate.Limiter
  45. globalLimiter *rate.Limiter
  46. networkBufferSize int
  47. statusAddr string
  48. poolAddrs string
  49. pools []string
  50. providedBy string
  51. defaultPoolAddrs = "https://relays.syncthing.net/endpoint"
  52. natEnabled bool
  53. natLease int
  54. natRenewal int
  55. natTimeout int
  56. pprofEnabled bool
  57. )
  58. // httpClient is the HTTP client we use for outbound requests. It has a
  59. // timeout and may get further options set during initialization.
  60. var httpClient = &http.Client{
  61. Timeout: 30 * time.Second,
  62. }
  63. func main() {
  64. log.SetFlags(log.Lshortfile | log.LstdFlags)
  65. var dir, extAddress, proto string
  66. flag.StringVar(&listen, "listen", ":22067", "Protocol listen address")
  67. flag.StringVar(&dir, "keys", ".", "Directory where cert.pem and key.pem is stored")
  68. flag.DurationVar(&networkTimeout, "network-timeout", networkTimeout, "Timeout for network operations between the client and the relay.\n\tIf no data is received between the client and the relay in this period of time, the connection is terminated.\n\tFurthermore, if no data is sent between either clients being relayed within this period of time, the session is also terminated.")
  69. flag.DurationVar(&pingInterval, "ping-interval", pingInterval, "How often pings are sent")
  70. flag.DurationVar(&messageTimeout, "message-timeout", messageTimeout, "Maximum amount of time we wait for relevant messages to arrive")
  71. flag.IntVar(&sessionLimitBps, "per-session-rate", sessionLimitBps, "Per session rate limit, in bytes/s")
  72. flag.IntVar(&globalLimitBps, "global-rate", globalLimitBps, "Global rate limit, in bytes/s")
  73. flag.BoolVar(&debug, "debug", debug, "Enable debug output")
  74. flag.StringVar(&statusAddr, "status-srv", ":22070", "Listen address for status service (blank to disable)")
  75. flag.StringVar(&poolAddrs, "pools", defaultPoolAddrs, "Comma separated list of relay pool addresses to join")
  76. flag.StringVar(&providedBy, "provided-by", "", "An optional description about who provides the relay")
  77. flag.StringVar(&extAddress, "ext-address", "", "An optional address to advertise as being available on.\n\tAllows listening on an unprivileged port with port forwarding from e.g. 443, and be connected to on port 443.")
  78. flag.StringVar(&proto, "protocol", "tcp", "Protocol used for listening. 'tcp' for IPv4 and IPv6, 'tcp4' for IPv4, 'tcp6' for IPv6")
  79. flag.BoolVar(&natEnabled, "nat", false, "Use UPnP/NAT-PMP to acquire external port mapping")
  80. flag.IntVar(&natLease, "nat-lease", 60, "NAT lease length in minutes")
  81. flag.IntVar(&natRenewal, "nat-renewal", 30, "NAT renewal frequency in minutes")
  82. flag.IntVar(&natTimeout, "nat-timeout", 10, "NAT discovery timeout in seconds")
  83. flag.BoolVar(&pprofEnabled, "pprof", false, "Enable the built in profiling on the status server")
  84. flag.IntVar(&networkBufferSize, "network-buffer", 65536, "Network buffer size (two of these per proxied connection)")
  85. showVersion := flag.Bool("version", false, "Show version")
  86. flag.Parse()
  87. longVer := build.LongVersionFor("strelaysrv")
  88. if *showVersion {
  89. fmt.Println(longVer)
  90. return
  91. }
  92. if extAddress == "" {
  93. extAddress = listen
  94. }
  95. if len(providedBy) > 30 {
  96. log.Fatal("Provided-by cannot be longer than 30 characters")
  97. }
  98. addr, err := net.ResolveTCPAddr(proto, extAddress)
  99. if err != nil {
  100. log.Fatal(err)
  101. }
  102. laddr, err := net.ResolveTCPAddr(proto, listen)
  103. if err != nil {
  104. log.Fatal(err)
  105. }
  106. if laddr.IP != nil && !laddr.IP.IsUnspecified() {
  107. // We bind to a specific address. Our outgoing HTTP requests should
  108. // also come from that address.
  109. laddr.Port = 0
  110. boundDialer := &net.Dialer{LocalAddr: laddr}
  111. httpClient.Transport = &http.Transport{
  112. DialContext: boundDialer.DialContext,
  113. }
  114. }
  115. log.Println(longVer)
  116. maxDescriptors, err := osutil.MaximizeOpenFileLimit()
  117. if maxDescriptors > 0 {
  118. // Assume that 20% of FD's are leaked/unaccounted for.
  119. descriptorLimit = int64(maxDescriptors*80) / 100
  120. log.Println("Connection limit", descriptorLimit)
  121. go monitorLimits()
  122. } else if err != nil && !build.IsWindows {
  123. log.Println("Assuming no connection limit, due to error retrieving rlimits:", err)
  124. }
  125. sessionAddress = addr.IP[:]
  126. sessionPort = uint16(addr.Port)
  127. certFile, keyFile := filepath.Join(dir, "cert.pem"), filepath.Join(dir, "key.pem")
  128. cert, err := tls.LoadX509KeyPair(certFile, keyFile)
  129. if err != nil {
  130. log.Println("Failed to load keypair. Generating one, this might take a while...")
  131. cert, err = tlsutil.NewCertificate(certFile, keyFile, "strelaysrv", 20*365)
  132. if err != nil {
  133. log.Fatalln("Failed to generate X509 key pair:", err)
  134. }
  135. }
  136. tlsCfg := &tls.Config{
  137. Certificates: []tls.Certificate{cert},
  138. NextProtos: []string{protocol.ProtocolName},
  139. ClientAuth: tls.RequestClientCert,
  140. SessionTicketsDisabled: true,
  141. InsecureSkipVerify: true,
  142. MinVersion: tls.VersionTLS12,
  143. CipherSuites: []uint16{
  144. tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  145. tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  146. tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
  147. tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
  148. tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
  149. tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
  150. },
  151. }
  152. id := syncthingprotocol.NewDeviceID(cert.Certificate[0])
  153. if debug {
  154. log.Println("ID:", id)
  155. }
  156. wrapper := config.Wrap("config", config.New(id), id, events.NoopLogger)
  157. go wrapper.Serve(context.TODO())
  158. wrapper.Modify(func(cfg *config.Configuration) {
  159. cfg.Options.NATLeaseM = natLease
  160. cfg.Options.NATRenewalM = natRenewal
  161. cfg.Options.NATTimeoutS = natTimeout
  162. })
  163. natSvc := nat.NewService(id, wrapper)
  164. mapping := mapping{natSvc.NewMapping(nat.TCP, addr.IP, addr.Port)}
  165. if natEnabled {
  166. ctx, cancel := context.WithCancel(context.Background())
  167. go natSvc.Serve(ctx)
  168. defer cancel()
  169. found := make(chan struct{})
  170. mapping.OnChanged(func() {
  171. select {
  172. case found <- struct{}{}:
  173. default:
  174. }
  175. })
  176. // Need to wait a few extra seconds, since NAT library waits exactly natTimeout seconds on all interfaces.
  177. timeout := time.Duration(natTimeout+2) * time.Second
  178. log.Printf("Waiting %s to acquire NAT mapping", timeout)
  179. select {
  180. case <-found:
  181. log.Printf("Found NAT mapping: %s", mapping.ExternalAddresses())
  182. case <-time.After(timeout):
  183. log.Println("Timeout out waiting for NAT mapping.")
  184. }
  185. }
  186. if sessionLimitBps > 0 {
  187. sessionLimiter = rate.NewLimiter(rate.Limit(sessionLimitBps), 2*sessionLimitBps)
  188. }
  189. if globalLimitBps > 0 {
  190. globalLimiter = rate.NewLimiter(rate.Limit(globalLimitBps), 2*globalLimitBps)
  191. }
  192. if statusAddr != "" {
  193. go statusService(statusAddr)
  194. }
  195. uri, err := url.Parse(fmt.Sprintf("relay://%s/", mapping.Address()))
  196. if err != nil {
  197. log.Fatalln("Failed to construct URI", err)
  198. return
  199. }
  200. // Add properly encoded query string parameters to URL.
  201. query := make(url.Values)
  202. query.Set("id", id.String())
  203. query.Set("pingInterval", pingInterval.String())
  204. query.Set("networkTimeout", networkTimeout.String())
  205. if sessionLimitBps > 0 {
  206. query.Set("sessionLimitBps", fmt.Sprint(sessionLimitBps))
  207. }
  208. if globalLimitBps > 0 {
  209. query.Set("globalLimitBps", fmt.Sprint(globalLimitBps))
  210. }
  211. if statusAddr != "" {
  212. query.Set("statusAddr", statusAddr)
  213. }
  214. if providedBy != "" {
  215. query.Set("providedBy", providedBy)
  216. }
  217. uri.RawQuery = query.Encode()
  218. log.Println("URI:", uri.String())
  219. if poolAddrs == defaultPoolAddrs {
  220. log.Println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
  221. log.Println("!! Joining default relay pools, this relay will be available for public use. !!")
  222. log.Println(`!! Use the -pools="" command line option to make the relay private. !!`)
  223. log.Println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
  224. }
  225. pools = strings.Split(poolAddrs, ",")
  226. for _, pool := range pools {
  227. pool = strings.TrimSpace(pool)
  228. if len(pool) > 0 {
  229. go poolHandler(pool, uri, mapping, cert)
  230. }
  231. }
  232. go listener(proto, listen, tlsCfg)
  233. sigs := make(chan os.Signal, 1)
  234. signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
  235. <-sigs
  236. // Gracefully close all connections, hoping that clients will be faster
  237. // to realize that the relay is now gone.
  238. sessionMut.RLock()
  239. for _, session := range activeSessions {
  240. session.CloseConns()
  241. }
  242. for _, session := range pendingSessions {
  243. session.CloseConns()
  244. }
  245. sessionMut.RUnlock()
  246. outboxesMut.RLock()
  247. for _, outbox := range outboxes {
  248. close(outbox)
  249. }
  250. outboxesMut.RUnlock()
  251. time.Sleep(500 * time.Millisecond)
  252. }
  253. func monitorLimits() {
  254. limitCheckTimer = time.NewTimer(time.Minute)
  255. for range limitCheckTimer.C {
  256. if atomic.LoadInt64(&numConnections)+atomic.LoadInt64(&numProxies) > descriptorLimit {
  257. atomic.StoreInt32(&overLimit, 1)
  258. log.Println("Gone past our connection limits. Starting to refuse new/drop idle connections.")
  259. } else if atomic.CompareAndSwapInt32(&overLimit, 1, 0) {
  260. log.Println("Dropped below our connection limits. Accepting new connections.")
  261. }
  262. limitCheckTimer.Reset(time.Minute)
  263. }
  264. }
  265. type mapping struct {
  266. *nat.Mapping
  267. }
  268. func (m *mapping) Address() nat.Address {
  269. ext := m.ExternalAddresses()
  270. if len(ext) > 0 {
  271. return ext[0]
  272. }
  273. return m.Mapping.Address()
  274. }