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 (
"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"
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-11-21 00:08:09 +00:00
"runtime"
2016-06-02 12:09:36 +00:00
"strconv"
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"
2015-07-20 11:25:08 +00:00
"github.com/juju/ratelimit"
2015-11-21 00:08:09 +00:00
"github.com/syncthing/syncthing/lib/osutil"
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"
2015-06-28 00:52:01 +00:00
2015-09-22 17:54:02 +00:00
syncthingprotocol "github.com/syncthing/syncthing/lib/protocol"
2015-06-24 11:39:46 +00:00
)
2016-06-02 12:09:36 +00:00
var (
Version string
BuildStamp string
BuildUser string
BuildHost string
BuildDate time . Time
LongVersion string
)
func init ( ) {
stamp , _ := strconv . Atoi ( BuildStamp )
BuildDate = time . Unix ( int64 ( stamp ) , 0 )
date := BuildDate . UTC ( ) . Format ( "2006-01-02 15:04:05 MST" )
2016-07-04 10:51:22 +00:00
LongVersion = fmt . Sprintf ( ` strelaysrv %s (%s %s-%s) %s@%s %s ` , Version , runtime . Version ( ) , runtime . GOOS , runtime . GOARCH , BuildUser , BuildHost , date )
2016-06-02 12:09:36 +00:00
}
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
2015-07-20 11:25:08 +00:00
sessionLimitBps int
globalLimitBps int
2015-11-21 00:08:09 +00:00
overLimit int32
descriptorLimit int64
2015-07-20 11:25:08 +00:00
sessionLimiter * ratelimit . Bucket
globalLimiter * ratelimit . Bucket
2015-08-20 10:59:44 +00:00
2015-09-07 08:21:23 +00:00
statusAddr string
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"
2015-06-24 11:39:46 +00:00
)
func main ( ) {
2015-09-11 21:29:50 +00:00
log . SetFlags ( log . Lshortfile | log . LstdFlags )
2015-06-24 11:39:46 +00:00
var dir , extAddress string
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)" )
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." )
2015-07-20 11:25:08 +00:00
flag . Parse ( )
2015-06-24 11:39:46 +00:00
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
}
addr , err := net . ResolveTCPAddr ( "tcp" , extAddress )
if err != nil {
log . Fatal ( err )
}
2016-06-02 12:09:36 +00:00
log . Println ( LongVersion )
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 ( )
} else if err != nil && runtime . GOOS != "windows" {
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..." )
2016-07-04 10:51:22 +00:00
cert , err = tlsutil . NewCertificate ( certFile , keyFile , "strelaysrv" , 3072 )
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
2015-07-20 11:25:08 +00:00
if sessionLimitBps > 0 {
sessionLimiter = ratelimit . NewBucketWithRate ( float64 ( sessionLimitBps ) , int64 ( 2 * sessionLimitBps ) )
}
if globalLimitBps > 0 {
globalLimiter = ratelimit . NewBucketWithRate ( float64 ( globalLimitBps ) , int64 ( 2 * globalLimitBps ) )
}
2015-08-20 10:59:44 +00:00
if statusAddr != "" {
go statusService ( statusAddr )
}
2015-10-23 21:24:53 +00:00
uri , err := url . Parse ( fmt . Sprintf ( "relay://%s/?id=%s&pingInterval=%s&networkTimeout=%s&sessionLimitBps=%d&globalLimitBps=%d&statusAddr=%s&providedBy=%s" , extAddress , id , pingInterval , networkTimeout , sessionLimitBps , globalLimitBps , statusAddr , providedBy ) )
2015-09-07 08:21:23 +00:00
if err != nil {
log . Fatalln ( "Failed to construct URI" , err )
}
2015-09-21 21:15:29 +00:00
log . Println ( "URI:" , uri . String ( ) )
2015-09-11 19:01:33 +00:00
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 {
go poolHandler ( pool , uri )
}
}
2015-11-21 00:31:20 +00:00
go listener ( listen , tlsCfg )
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-06-02 12:48:25 +00:00
for _ = range limitCheckTimer . C {
2015-11-21 00:08:09 +00:00
if atomic . LoadInt64 ( & numConnections ) + atomic . LoadInt64 ( & numProxies ) > descriptorLimit {
atomic . StoreInt32 ( & overLimit , 1 )
log . Println ( "Gone past our connection limits. Starting to refuse new/drop idle connections." )
} else if atomic . CompareAndSwapInt32 ( & overLimit , 1 , 0 ) {
log . Println ( "Dropped below our connection limits. Accepting new connections." )
}
limitCheckTimer . Reset ( time . Minute )
}
}