2016-06-02 12:16:02 +00:00
// Copyright (C) 2015 Audrius Butkevicius and Contributors.
2015-06-24 11:39:46 +00:00
package main
import (
2020-11-17 12:19:04 +00:00
"context"
2015-06-24 11:39:46 +00:00
"crypto/tls"
"flag"
2015-09-07 08:21:23 +00:00
"fmt"
2015-06-24 11:39:46 +00:00
"log"
2015-06-28 00:52:01 +00:00
"net"
2016-11-11 22:51:48 +00:00
"net/http"
2015-09-07 08:21:23 +00:00
"net/url"
2015-11-21 00:31:20 +00:00
"os"
"os/signal"
2015-06-24 11:39:46 +00:00
"path/filepath"
2015-09-07 08:21:23 +00:00
"strings"
2015-11-21 00:08:09 +00:00
"sync/atomic"
2015-11-21 00:31:20 +00:00
"syscall"
2015-06-24 11:39:46 +00:00
"time"
refactor: use modern Protobuf encoder (#9817)
At a high level, this is what I've done and why:
- I'm moving the protobuf generation for the `protocol`, `discovery` and
`db` packages to the modern alternatives, and using `buf` to generate
because it's nice and simple.
- After trying various approaches on how to integrate the new types with
the existing code, I opted for splitting off our own data model types
from the on-the-wire generated types. This means we can have a
`FileInfo` type with nicer ergonomics and lots of methods, while the
protobuf generated type stays clean and close to the wire protocol. It
does mean copying between the two when required, which certainly adds a
small amount of inefficiency. If we want to walk this back in the future
and use the raw generated type throughout, that's possible, this however
makes the refactor smaller (!) as it doesn't change everything about the
type for everyone at the same time.
- I have simply removed in cold blood a significant number of old
database migrations. These depended on previous generations of generated
messages of various kinds and were annoying to support in the new
fashion. The oldest supported database version now is the one from
Syncthing 1.9.0 from Sep 7, 2020.
- I changed config structs to be regular manually defined structs.
For the sake of discussion, some things I tried that turned out not to
work...
### Embedding / wrapping
Embedding the protobuf generated structs in our existing types as a data
container and keeping our methods and stuff:
```
package protocol
type FileInfo struct {
*generated.FileInfo
}
```
This generates a lot of problems because the internal shape of the
generated struct is quite different (different names, different types,
more pointers), because initializing it doesn't work like you'd expect
(i.e., you end up with an embedded nil pointer and a panic), and because
the types of child types don't get wrapped. That is, even if we also
have a similar wrapper around a `Vector`, that's not the type you get
when accessing `someFileInfo.Version`, you get the `*generated.Vector`
that doesn't have methods, etc.
### Aliasing
```
package protocol
type FileInfo = generated.FileInfo
```
Doesn't help because you can't attach methods to it, plus all the above.
### Generating the types into the target package like we do now and
attaching methods
This fails because of the different shape of the generated type (as in
the embedding case above) plus the generated struct already has a bunch
of methods that we can't necessarily override properly (like `String()`
and a bunch of getters).
### Methods to functions
I considered just moving all the methods we attach to functions in a
specific package, so that for example
```
package protocol
func (f FileInfo) Equal(other FileInfo) bool
```
would become
```
package fileinfos
func Equal(a, b *generated.FileInfo) bool
```
and this would mostly work, but becomes quite verbose and cumbersome,
and somewhat limits discoverability (you can't see what methods are
available on the type in auto completions, etc). In the end I did this
in some cases, like in the database layer where a lot of things like
`func (fv *FileVersion) IsEmpty() bool` becomes `func fvIsEmpty(fv
*generated.FileVersion)` because they were anyway just internal methods.
Fixes #8247
2024-12-01 15:50:17 +00:00
"golang.org/x/time/rate"
2024-02-27 12:05:19 +00:00
_ "github.com/syncthing/syncthing/lib/automaxprocs"
2019-10-07 11:30:25 +00:00
"github.com/syncthing/syncthing/lib/build"
2024-02-26 12:23:14 +00:00
"github.com/syncthing/syncthing/lib/config"
2019-08-15 14:29:37 +00:00
"github.com/syncthing/syncthing/lib/events"
2024-02-26 12:23:14 +00:00
"github.com/syncthing/syncthing/lib/nat"
2015-11-21 00:08:09 +00:00
"github.com/syncthing/syncthing/lib/osutil"
2024-02-26 12:23:14 +00:00
_ "github.com/syncthing/syncthing/lib/pmp"
syncthingprotocol "github.com/syncthing/syncthing/lib/protocol"
2015-09-22 17:54:02 +00:00
"github.com/syncthing/syncthing/lib/relay/protocol"
2015-09-11 19:01:33 +00:00
"github.com/syncthing/syncthing/lib/tlsutil"
2016-08-23 06:43:27 +00:00
_ "github.com/syncthing/syncthing/lib/upnp"
2015-06-24 11:39:46 +00:00
)
var (
2015-09-02 20:35:52 +00:00
listen string
2016-06-07 07:31:43 +00:00
debug bool
2015-06-24 11:39:46 +00:00
sessionAddress [ ] byte
sessionPort uint16
2016-06-07 07:31:43 +00:00
networkTimeout = 2 * time . Minute
pingInterval = time . Minute
messageTimeout = time . Minute
2015-07-20 11:25:08 +00:00
2015-11-21 00:08:09 +00:00
limitCheckTimer * time . Timer
2017-08-30 16:52:28 +00:00
sessionLimitBps int
globalLimitBps int
2023-02-07 11:07:34 +00:00
overLimit atomic . Bool
2017-08-30 16:52:28 +00:00
descriptorLimit int64
sessionLimiter * rate . Limiter
globalLimiter * rate . Limiter
networkBufferSize int
2015-08-20 10:59:44 +00:00
2015-09-07 08:21:23 +00:00
statusAddr string
2022-10-01 19:41:02 +00:00
token string
2015-09-07 08:21:23 +00:00
poolAddrs string
2015-10-22 20:40:36 +00:00
pools [ ] string
2015-10-18 15:57:13 +00:00
providedBy string
2016-06-07 07:31:43 +00:00
defaultPoolAddrs = "https://relays.syncthing.net/endpoint"
2016-08-23 06:43:27 +00:00
natEnabled bool
natLease int
natRenewal int
natTimeout int
2017-08-30 14:07:15 +00:00
pprofEnabled bool
2015-06-24 11:39:46 +00:00
)
2018-02-21 14:56:04 +00:00
// httpClient is the HTTP client we use for outbound requests. It has a
// timeout and may get further options set during initialization.
var httpClient = & http . Client {
Timeout : 30 * time . Second ,
}
2015-06-24 11:39:46 +00:00
func main ( ) {
2015-09-11 21:29:50 +00:00
log . SetFlags ( log . Lshortfile | log . LstdFlags )
2016-08-23 06:43:27 +00:00
var dir , extAddress , proto string
2015-06-24 11:39:46 +00:00
2015-09-02 20:35:52 +00:00
flag . StringVar ( & listen , "listen" , ":22067" , "Protocol listen address" )
2015-06-24 11:39:46 +00:00
flag . StringVar ( & dir , "keys" , "." , "Directory where cert.pem and key.pem is stored" )
2015-09-11 19:01:33 +00:00
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." )
flag . DurationVar ( & pingInterval , "ping-interval" , pingInterval , "How often pings are sent" )
flag . DurationVar ( & messageTimeout , "message-timeout" , messageTimeout , "Maximum amount of time we wait for relevant messages to arrive" )
2015-07-20 11:25:08 +00:00
flag . IntVar ( & sessionLimitBps , "per-session-rate" , sessionLimitBps , "Per session rate limit, in bytes/s" )
flag . IntVar ( & globalLimitBps , "global-rate" , globalLimitBps , "Global rate limit, in bytes/s" )
2015-09-11 19:01:33 +00:00
flag . BoolVar ( & debug , "debug" , debug , "Enable debug output" )
2015-08-20 10:59:44 +00:00
flag . StringVar ( & statusAddr , "status-srv" , ":22070" , "Listen address for status service (blank to disable)" )
2022-10-01 19:41:02 +00:00
flag . StringVar ( & token , "token" , "" , "Token to restrict access to the relay (optional). Disables joining any pools." )
2015-09-11 19:01:33 +00:00
flag . StringVar ( & poolAddrs , "pools" , defaultPoolAddrs , "Comma separated list of relay pool addresses to join" )
2015-10-18 15:57:13 +00:00
flag . StringVar ( & providedBy , "provided-by" , "" , "An optional description about who provides the relay" )
2016-07-03 08:44:41 +00:00
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." )
2016-08-23 06:43:27 +00:00
flag . StringVar ( & proto , "protocol" , "tcp" , "Protocol used for listening. 'tcp' for IPv4 and IPv6, 'tcp4' for IPv4, 'tcp6' for IPv6" )
flag . BoolVar ( & natEnabled , "nat" , false , "Use UPnP/NAT-PMP to acquire external port mapping" )
flag . IntVar ( & natLease , "nat-lease" , 60 , "NAT lease length in minutes" )
flag . IntVar ( & natRenewal , "nat-renewal" , 30 , "NAT renewal frequency in minutes" )
flag . IntVar ( & natTimeout , "nat-timeout" , 10 , "NAT discovery timeout in seconds" )
2017-08-30 14:07:15 +00:00
flag . BoolVar ( & pprofEnabled , "pprof" , false , "Enable the built in profiling on the status server" )
2021-03-22 20:47:51 +00:00
flag . IntVar ( & networkBufferSize , "network-buffer" , 65536 , "Network buffer size (two of these per proxied connection)" )
2019-10-07 11:30:25 +00:00
showVersion := flag . Bool ( "version" , false , "Show version" )
2015-07-20 11:25:08 +00:00
flag . Parse ( )
2015-06-24 11:39:46 +00:00
2020-04-16 08:09:33 +00:00
longVer := build . LongVersionFor ( "strelaysrv" )
2019-10-07 11:30:25 +00:00
if * showVersion {
2020-04-16 08:09:33 +00:00
fmt . Println ( longVer )
2019-10-07 11:30:25 +00:00
return
}
2015-06-28 00:52:01 +00:00
if extAddress == "" {
2015-09-02 20:35:52 +00:00
extAddress = listen
2015-06-28 00:52:01 +00:00
}
2016-08-23 06:43:27 +00:00
if len ( providedBy ) > 30 {
log . Fatal ( "Provided-by cannot be longer than 30 characters" )
}
addr , err := net . ResolveTCPAddr ( proto , extAddress )
2015-06-28 00:52:01 +00:00
if err != nil {
log . Fatal ( err )
}
2016-11-11 22:51:48 +00:00
laddr , err := net . ResolveTCPAddr ( proto , listen )
if err != nil {
log . Fatal ( err )
}
2018-02-21 14:56:04 +00:00
2016-11-11 22:51:48 +00:00
if laddr . IP != nil && ! laddr . IP . IsUnspecified ( ) {
2018-02-21 14:56:04 +00:00
// We bind to a specific address. Our outgoing HTTP requests should
// also come from that address.
2016-11-11 22:51:48 +00:00
laddr . Port = 0
2018-02-21 14:56:04 +00:00
boundDialer := & net . Dialer { LocalAddr : laddr }
httpClient . Transport = & http . Transport {
DialContext : boundDialer . DialContext ,
2016-11-11 22:51:48 +00:00
}
}
2020-04-16 08:09:33 +00:00
log . Println ( longVer )
2016-06-02 12:09:36 +00:00
2015-11-21 00:08:09 +00:00
maxDescriptors , err := osutil . MaximizeOpenFileLimit ( )
if maxDescriptors > 0 {
// Assume that 20% of FD's are leaked/unaccounted for.
descriptorLimit = int64 ( maxDescriptors * 80 ) / 100
log . Println ( "Connection limit" , descriptorLimit )
go monitorLimits ( )
2022-07-28 17:36:39 +00:00
} else if err != nil && ! build . IsWindows {
2016-07-03 08:44:41 +00:00
log . Println ( "Assuming no connection limit, due to error retrieving rlimits:" , err )
2015-11-21 00:08:09 +00:00
}
2015-06-28 00:52:01 +00:00
sessionAddress = addr . IP [ : ]
sessionPort = uint16 ( addr . Port )
2015-06-24 11:39:46 +00:00
certFile , keyFile := filepath . Join ( dir , "cert.pem" ) , filepath . Join ( dir , "key.pem" )
cert , err := tls . LoadX509KeyPair ( certFile , keyFile )
if err != nil {
2015-09-11 19:01:33 +00:00
log . Println ( "Failed to load keypair. Generating one, this might take a while..." )
2019-10-16 18:31:46 +00:00
cert , err = tlsutil . NewCertificate ( certFile , keyFile , "strelaysrv" , 20 * 365 )
2015-09-11 19:01:33 +00:00
if err != nil {
log . Fatalln ( "Failed to generate X509 key pair:" , err )
}
2015-06-24 11:39:46 +00:00
}
tlsCfg := & tls . Config {
Certificates : [ ] tls . Certificate { cert } ,
NextProtos : [ ] string { protocol . ProtocolName } ,
ClientAuth : tls . RequestClientCert ,
SessionTicketsDisabled : true ,
InsecureSkipVerify : true ,
MinVersion : tls . VersionTLS12 ,
CipherSuites : [ ] uint16 {
tls . TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 ,
tls . TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 ,
tls . TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA ,
tls . TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA ,
tls . TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA ,
tls . TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA ,
} ,
}
2015-06-28 00:52:01 +00:00
id := syncthingprotocol . NewDeviceID ( cert . Certificate [ 0 ] )
if debug {
log . Println ( "ID:" , id )
}
2015-06-24 11:39:46 +00:00
2020-11-20 13:21:54 +00:00
wrapper := config . Wrap ( "config" , config . New ( id ) , id , events . NoopLogger )
2021-03-11 13:51:00 +00:00
go wrapper . Serve ( context . TODO ( ) )
2021-01-15 14:43:34 +00:00
wrapper . Modify ( func ( cfg * config . Configuration ) {
cfg . Options . NATLeaseM = natLease
cfg . Options . NATRenewalM = natRenewal
cfg . Options . NATTimeoutS = natTimeout
2016-08-23 06:43:27 +00:00
} )
natSvc := nat . NewService ( id , wrapper )
2023-12-11 06:36:18 +00:00
var ipVersion nat . IPVersion
if strings . HasSuffix ( proto , "4" ) {
ipVersion = nat . IPv4Only
} else if strings . HasSuffix ( proto , "6" ) {
ipVersion = nat . IPv6Only
} else {
ipVersion = nat . IPvAny
}
mapping := mapping { natSvc . NewMapping ( nat . TCP , ipVersion , addr . IP , addr . Port ) }
2016-08-23 06:43:27 +00:00
if natEnabled {
2020-11-17 12:19:04 +00:00
ctx , cancel := context . WithCancel ( context . Background ( ) )
go natSvc . Serve ( ctx )
defer cancel ( )
2016-08-23 06:43:27 +00:00
found := make ( chan struct { } )
2021-11-22 07:29:44 +00:00
mapping . OnChanged ( func ( ) {
2016-08-23 06:43:27 +00:00
select {
case found <- struct { } { } :
default :
}
} )
// Need to wait a few extra seconds, since NAT library waits exactly natTimeout seconds on all interfaces.
timeout := time . Duration ( natTimeout + 2 ) * time . Second
log . Printf ( "Waiting %s to acquire NAT mapping" , timeout )
select {
case <- found :
log . Printf ( "Found NAT mapping: %s" , mapping . ExternalAddresses ( ) )
case <- time . After ( timeout ) :
log . Println ( "Timeout out waiting for NAT mapping." )
}
}
2015-07-20 11:25:08 +00:00
if sessionLimitBps > 0 {
2017-01-02 11:29:20 +00:00
sessionLimiter = rate . NewLimiter ( rate . Limit ( sessionLimitBps ) , 2 * sessionLimitBps )
2015-07-20 11:25:08 +00:00
}
if globalLimitBps > 0 {
2017-01-02 11:29:20 +00:00
globalLimiter = rate . NewLimiter ( rate . Limit ( globalLimitBps ) , 2 * globalLimitBps )
2015-07-20 11:25:08 +00:00
}
2015-08-20 10:59:44 +00:00
if statusAddr != "" {
go statusService ( statusAddr )
}
2022-05-02 08:38:49 +00:00
uri , err := url . Parse ( fmt . Sprintf ( "relay://%s/" , mapping . Address ( ) ) )
2015-09-07 08:21:23 +00:00
if err != nil {
log . Fatalln ( "Failed to construct URI" , err )
2021-03-22 20:47:51 +00:00
return
2015-09-07 08:21:23 +00:00
}
2022-05-02 08:38:49 +00:00
// Add properly encoded query string parameters to URL.
query := make ( url . Values )
query . Set ( "id" , id . String ( ) )
query . Set ( "pingInterval" , pingInterval . String ( ) )
query . Set ( "networkTimeout" , networkTimeout . String ( ) )
if sessionLimitBps > 0 {
query . Set ( "sessionLimitBps" , fmt . Sprint ( sessionLimitBps ) )
}
if globalLimitBps > 0 {
query . Set ( "globalLimitBps" , fmt . Sprint ( globalLimitBps ) )
}
if statusAddr != "" {
query . Set ( "statusAddr" , statusAddr )
}
if providedBy != "" {
query . Set ( "providedBy" , providedBy )
}
uri . RawQuery = query . Encode ( )
2015-09-21 21:15:29 +00:00
log . Println ( "URI:" , uri . String ( ) )
2015-09-11 19:01:33 +00:00
2022-10-01 19:41:02 +00:00
if token != "" {
poolAddrs = ""
}
2015-09-07 08:21:23 +00:00
if poolAddrs == defaultPoolAddrs {
log . Println ( "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" )
log . Println ( "!! Joining default relay pools, this relay will be available for public use. !!" )
log . Println ( ` !! Use the -pools="" command line option to make the relay private. !! ` )
log . Println ( "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" )
}
2015-10-22 20:40:36 +00:00
pools = strings . Split ( poolAddrs , "," )
2015-09-07 08:21:23 +00:00
for _ , pool := range pools {
pool = strings . TrimSpace ( pool )
if len ( pool ) > 0 {
2020-12-21 10:55:16 +00:00
go poolHandler ( pool , uri , mapping , cert )
2015-09-07 08:21:23 +00:00
}
}
2022-10-01 19:41:02 +00:00
go listener ( proto , listen , tlsCfg , token )
2015-11-21 00:31:20 +00:00
sigs := make ( chan os . Signal , 1 )
signal . Notify ( sigs , syscall . SIGINT , syscall . SIGTERM )
<- sigs
// Gracefully close all connections, hoping that clients will be faster
// to realize that the relay is now gone.
sessionMut . RLock ( )
for _ , session := range activeSessions {
session . CloseConns ( )
}
for _ , session := range pendingSessions {
session . CloseConns ( )
}
sessionMut . RUnlock ( )
outboxesMut . RLock ( )
for _ , outbox := range outboxes {
close ( outbox )
}
outboxesMut . RUnlock ( )
time . Sleep ( 500 * time . Millisecond )
2015-06-24 11:39:46 +00:00
}
2015-11-21 00:08:09 +00:00
func monitorLimits ( ) {
limitCheckTimer = time . NewTimer ( time . Minute )
2016-08-15 06:37:32 +00:00
for range limitCheckTimer . C {
2023-02-07 11:07:34 +00:00
if numConnections . Load ( ) + numProxies . Load ( ) > descriptorLimit {
overLimit . Store ( true )
2015-11-21 00:08:09 +00:00
log . Println ( "Gone past our connection limits. Starting to refuse new/drop idle connections." )
2023-02-07 11:07:34 +00:00
} else if overLimit . CompareAndSwap ( true , false ) {
2015-11-21 00:08:09 +00:00
log . Println ( "Dropped below our connection limits. Accepting new connections." )
}
limitCheckTimer . Reset ( time . Minute )
}
}
2016-08-23 06:43:27 +00:00
type mapping struct {
* nat . Mapping
}
func ( m * mapping ) Address ( ) nat . Address {
ext := m . ExternalAddresses ( )
if len ( ext ) > 0 {
return ext [ 0 ]
}
return m . Mapping . Address ( )
}