main.go 9.7 KB

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