main.go 9.7 KB

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