2016-05-04 19:38:12 +00:00
|
|
|
// Copyright (C) 2015 The Syncthing Authors.
|
|
|
|
//
|
|
|
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
|
|
|
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
|
2017-02-09 06:52:18 +00:00
|
|
|
// You can obtain one at https://mozilla.org/MPL/2.0/.
|
2016-05-04 19:38:12 +00:00
|
|
|
|
|
|
|
package connections
|
|
|
|
|
|
|
|
import (
|
2019-11-21 07:41:15 +00:00
|
|
|
"context"
|
2016-05-04 19:38:12 +00:00
|
|
|
"crypto/tls"
|
|
|
|
"fmt"
|
|
|
|
"net"
|
|
|
|
"net/url"
|
2017-11-15 09:36:33 +00:00
|
|
|
"sort"
|
2017-04-13 17:43:29 +00:00
|
|
|
"strings"
|
2017-12-07 07:08:24 +00:00
|
|
|
stdsync "sync"
|
2016-05-04 19:38:12 +00:00
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/syncthing/syncthing/lib/config"
|
|
|
|
"github.com/syncthing/syncthing/lib/discover"
|
|
|
|
"github.com/syncthing/syncthing/lib/events"
|
|
|
|
"github.com/syncthing/syncthing/lib/nat"
|
2017-11-06 14:05:29 +00:00
|
|
|
"github.com/syncthing/syncthing/lib/osutil"
|
2016-05-04 19:38:12 +00:00
|
|
|
"github.com/syncthing/syncthing/lib/protocol"
|
|
|
|
"github.com/syncthing/syncthing/lib/sync"
|
|
|
|
"github.com/syncthing/syncthing/lib/util"
|
|
|
|
|
|
|
|
// Registers NAT service providers
|
|
|
|
_ "github.com/syncthing/syncthing/lib/pmp"
|
|
|
|
_ "github.com/syncthing/syncthing/lib/upnp"
|
|
|
|
|
2019-11-26 07:39:51 +00:00
|
|
|
"github.com/pkg/errors"
|
2018-09-08 09:56:56 +00:00
|
|
|
"github.com/thejerf/suture"
|
2017-01-02 11:29:20 +00:00
|
|
|
"golang.org/x/time/rate"
|
2016-05-04 19:38:12 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
2019-02-02 11:09:07 +00:00
|
|
|
dialers = make(map[string]dialerFactory)
|
|
|
|
listeners = make(map[string]listenerFactory)
|
2016-05-04 19:38:12 +00:00
|
|
|
)
|
|
|
|
|
2018-02-09 10:40:57 +00:00
|
|
|
var (
|
|
|
|
errDisabled = errors.New("disabled by configuration")
|
|
|
|
errDeprecated = errors.New("deprecated protocol")
|
|
|
|
)
|
|
|
|
|
2016-07-02 20:33:31 +00:00
|
|
|
const (
|
2020-04-20 06:23:38 +00:00
|
|
|
perDeviceWarningIntv = 15 * time.Minute
|
|
|
|
tlsHandshakeTimeout = 10 * time.Second
|
|
|
|
minConnectionReplaceAge = 10 * time.Second
|
2016-07-02 20:33:31 +00:00
|
|
|
)
|
2016-06-09 12:30:35 +00:00
|
|
|
|
2016-12-18 21:07:44 +00:00
|
|
|
// From go/src/crypto/tls/cipher_suites.go
|
|
|
|
var tlsCipherSuiteNames = map[uint16]string{
|
2019-02-26 10:49:02 +00:00
|
|
|
// TLS 1.2
|
2016-12-18 21:07:44 +00:00
|
|
|
0x0005: "TLS_RSA_WITH_RC4_128_SHA",
|
|
|
|
0x000a: "TLS_RSA_WITH_3DES_EDE_CBC_SHA",
|
|
|
|
0x002f: "TLS_RSA_WITH_AES_128_CBC_SHA",
|
|
|
|
0x0035: "TLS_RSA_WITH_AES_256_CBC_SHA",
|
|
|
|
0x003c: "TLS_RSA_WITH_AES_128_CBC_SHA256",
|
|
|
|
0x009c: "TLS_RSA_WITH_AES_128_GCM_SHA256",
|
|
|
|
0x009d: "TLS_RSA_WITH_AES_256_GCM_SHA384",
|
|
|
|
0xc007: "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA",
|
|
|
|
0xc009: "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA",
|
|
|
|
0xc00a: "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA",
|
|
|
|
0xc011: "TLS_ECDHE_RSA_WITH_RC4_128_SHA",
|
|
|
|
0xc012: "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA",
|
|
|
|
0xc013: "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",
|
|
|
|
0xc014: "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA",
|
|
|
|
0xc023: "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256",
|
|
|
|
0xc027: "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256",
|
|
|
|
0xc02f: "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
|
|
|
|
0xc02b: "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
|
|
|
|
0xc030: "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
|
|
|
|
0xc02c: "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
|
|
|
|
0xcca8: "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305",
|
|
|
|
0xcca9: "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305",
|
2019-02-26 10:49:02 +00:00
|
|
|
|
|
|
|
// TLS 1.3
|
|
|
|
0x1301: "TLS_AES_128_GCM_SHA256",
|
|
|
|
0x1302: "TLS_AES_256_GCM_SHA384",
|
|
|
|
0x1303: "TLS_CHACHA20_POLY1305_SHA256",
|
|
|
|
}
|
|
|
|
|
|
|
|
var tlsVersionNames = map[uint16]string{
|
|
|
|
tls.VersionTLS12: "TLS1.2",
|
2019-11-10 08:47:17 +00:00
|
|
|
tls.VersionTLS13: "TLS1.3",
|
2016-12-18 21:07:44 +00:00
|
|
|
}
|
|
|
|
|
2016-05-04 19:38:12 +00:00
|
|
|
// Service listens and dials all configured unconnected devices, via supported
|
|
|
|
// dialers. Successful connections are handed to the model.
|
2019-02-26 08:09:25 +00:00
|
|
|
type Service interface {
|
|
|
|
suture.Service
|
2019-08-13 07:33:33 +00:00
|
|
|
discover.AddressLister
|
2019-05-16 21:11:46 +00:00
|
|
|
ListenerStatus() map[string]ListenerStatusEntry
|
|
|
|
ConnectionStatus() map[string]ConnectionStatusEntry
|
2019-02-26 08:09:25 +00:00
|
|
|
NATType() string
|
|
|
|
}
|
|
|
|
|
2019-05-16 21:11:46 +00:00
|
|
|
type ListenerStatusEntry struct {
|
|
|
|
Error *string `json:"error"`
|
|
|
|
LANAddresses []string `json:"lanAddresses"`
|
|
|
|
WANAddresses []string `json:"wanAddresses"`
|
|
|
|
}
|
|
|
|
|
|
|
|
type ConnectionStatusEntry struct {
|
|
|
|
When time.Time `json:"when"`
|
|
|
|
Error *string `json:"error"`
|
|
|
|
}
|
|
|
|
|
2019-02-26 08:09:25 +00:00
|
|
|
type service struct {
|
2016-05-04 19:38:12 +00:00
|
|
|
*suture.Supervisor
|
2020-02-25 20:18:31 +00:00
|
|
|
connectionStatusHandler
|
|
|
|
|
2019-02-26 08:09:25 +00:00
|
|
|
cfg config.Wrapper
|
2016-05-04 19:38:12 +00:00
|
|
|
myID protocol.DeviceID
|
|
|
|
model Model
|
|
|
|
tlsCfg *tls.Config
|
|
|
|
discoverer discover.Finder
|
2016-11-30 07:54:20 +00:00
|
|
|
conns chan internalConn
|
2016-05-04 19:38:12 +00:00
|
|
|
bepProtocolName string
|
|
|
|
tlsDefaultCommonName string
|
2017-01-02 11:29:20 +00:00
|
|
|
limiter *limiter
|
2016-05-04 19:38:12 +00:00
|
|
|
natService *nat.Service
|
|
|
|
natServiceToken *suture.ServiceToken
|
2019-08-15 14:29:37 +00:00
|
|
|
evLogger events.Logger
|
2016-05-04 19:38:12 +00:00
|
|
|
|
2016-11-19 12:37:14 +00:00
|
|
|
listenersMut sync.RWMutex
|
|
|
|
listeners map[string]genericListener
|
|
|
|
listenerTokens map[string]suture.ServiceToken
|
|
|
|
listenerSupervisor *suture.Supervisor
|
2016-05-04 19:38:12 +00:00
|
|
|
}
|
|
|
|
|
2019-08-15 14:29:37 +00:00
|
|
|
func NewService(cfg config.Wrapper, myID protocol.DeviceID, mdl Model, tlsCfg *tls.Config, discoverer discover.Finder, bepProtocolName string, tlsDefaultCommonName string, evLogger events.Logger) Service {
|
2019-02-26 08:09:25 +00:00
|
|
|
service := &service{
|
2016-11-19 12:37:14 +00:00
|
|
|
Supervisor: suture.New("connections.Service", suture.Spec{
|
|
|
|
Log: func(line string) {
|
|
|
|
l.Infoln(line)
|
|
|
|
},
|
2018-09-08 09:56:56 +00:00
|
|
|
PassThroughPanics: true,
|
2016-11-19 12:37:14 +00:00
|
|
|
}),
|
2020-02-25 20:18:31 +00:00
|
|
|
connectionStatusHandler: newConnectionStatusHandler(),
|
|
|
|
|
2016-05-04 19:38:12 +00:00
|
|
|
cfg: cfg,
|
|
|
|
myID: myID,
|
|
|
|
model: mdl,
|
|
|
|
tlsCfg: tlsCfg,
|
|
|
|
discoverer: discoverer,
|
2016-11-30 07:54:20 +00:00
|
|
|
conns: make(chan internalConn),
|
2016-05-04 19:38:12 +00:00
|
|
|
bepProtocolName: bepProtocolName,
|
|
|
|
tlsDefaultCommonName: tlsDefaultCommonName,
|
2017-01-02 11:29:20 +00:00
|
|
|
limiter: newLimiter(cfg),
|
2016-05-04 19:38:12 +00:00
|
|
|
natService: nat.NewService(myID, cfg),
|
2019-08-15 14:29:37 +00:00
|
|
|
evLogger: evLogger,
|
2016-05-04 19:38:12 +00:00
|
|
|
|
2016-05-09 15:03:12 +00:00
|
|
|
listenersMut: sync.NewRWMutex(),
|
|
|
|
listeners: make(map[string]genericListener),
|
|
|
|
listenerTokens: make(map[string]suture.ServiceToken),
|
|
|
|
|
2016-11-19 12:37:14 +00:00
|
|
|
// A listener can fail twice, rapidly. Any more than that and it
|
|
|
|
// will be put on suspension for ten minutes. Restarts and changes
|
|
|
|
// due to config are done by removing and adding services, so are
|
|
|
|
// not subject to these limitations.
|
|
|
|
listenerSupervisor: suture.New("c.S.listenerSupervisor", suture.Spec{
|
|
|
|
Log: func(line string) {
|
|
|
|
l.Infoln(line)
|
|
|
|
},
|
2018-09-08 09:56:56 +00:00
|
|
|
FailureThreshold: 2,
|
|
|
|
FailureBackoff: 600 * time.Second,
|
|
|
|
PassThroughPanics: true,
|
2016-11-19 12:37:14 +00:00
|
|
|
}),
|
2016-05-04 19:38:12 +00:00
|
|
|
}
|
|
|
|
cfg.Subscribe(service)
|
|
|
|
|
2017-10-22 12:36:36 +00:00
|
|
|
raw := cfg.RawCopy()
|
|
|
|
// Actually starts the listeners and NAT service
|
|
|
|
// Need to start this before service.connect so that any dials that
|
|
|
|
// try punch through already have a listener to cling on.
|
|
|
|
service.CommitConfiguration(raw, raw)
|
|
|
|
|
2016-05-04 19:38:12 +00:00
|
|
|
// There are several moving parts here; one routine per listening address
|
|
|
|
// (handled in configuration changing) to handle incoming connections,
|
|
|
|
// one routine to periodically attempt outgoing connections, one routine to
|
2017-02-25 08:12:13 +00:00
|
|
|
// the common handling regardless of whether the connection was
|
2016-05-04 19:38:12 +00:00
|
|
|
// incoming or outgoing.
|
|
|
|
|
2019-11-21 07:41:15 +00:00
|
|
|
service.Add(util.AsService(service.connect, fmt.Sprintf("%s/connect", service)))
|
|
|
|
service.Add(util.AsService(service.handle, fmt.Sprintf("%s/handle", service)))
|
2016-11-19 12:37:14 +00:00
|
|
|
service.Add(service.listenerSupervisor)
|
2016-05-04 19:38:12 +00:00
|
|
|
|
|
|
|
return service
|
|
|
|
}
|
|
|
|
|
2019-12-04 06:15:00 +00:00
|
|
|
func (s *service) Stop() {
|
|
|
|
s.cfg.Unsubscribe(s.limiter)
|
|
|
|
s.cfg.Unsubscribe(s)
|
|
|
|
s.Supervisor.Stop()
|
|
|
|
}
|
|
|
|
|
2019-11-21 07:41:15 +00:00
|
|
|
func (s *service) handle(ctx context.Context) {
|
2019-07-09 09:40:30 +00:00
|
|
|
var c internalConn
|
|
|
|
for {
|
|
|
|
select {
|
2019-11-21 07:41:15 +00:00
|
|
|
case <-ctx.Done():
|
2019-07-09 09:40:30 +00:00
|
|
|
return
|
|
|
|
case c = <-s.conns:
|
|
|
|
}
|
|
|
|
|
2016-05-04 19:38:12 +00:00
|
|
|
cs := c.ConnectionState()
|
|
|
|
|
|
|
|
// We should have negotiated the next level protocol "bep/1.0" as part
|
|
|
|
// of the TLS handshake. Unfortunately this can't be a hard error,
|
|
|
|
// because there are implementations out there that don't support
|
|
|
|
// protocol negotiation (iOS for one...).
|
|
|
|
if !cs.NegotiatedProtocolIsMutual || cs.NegotiatedProtocol != s.bepProtocolName {
|
2018-01-12 11:27:55 +00:00
|
|
|
l.Infof("Peer at %s did not negotiate bep/1.0", c)
|
2016-05-04 19:38:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// We should have received exactly one certificate from the other
|
|
|
|
// side. If we didn't, they don't have a device ID and we drop the
|
|
|
|
// connection.
|
|
|
|
certs := cs.PeerCertificates
|
|
|
|
if cl := len(certs); cl != 1 {
|
2018-01-12 11:27:55 +00:00
|
|
|
l.Infof("Got peer certificate list of length %d != 1 from peer at %s; protocol error", cl, c)
|
2016-05-04 19:38:12 +00:00
|
|
|
c.Close()
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
remoteCert := certs[0]
|
|
|
|
remoteID := protocol.NewDeviceID(remoteCert.Raw)
|
|
|
|
|
|
|
|
// The device ID should not be that of ourselves. It can happen
|
|
|
|
// though, especially in the presence of NAT hairpinning, multiple
|
|
|
|
// clients between the same NAT gateway, and global discovery.
|
|
|
|
if remoteID == s.myID {
|
2018-01-12 11:27:55 +00:00
|
|
|
l.Infof("Connected to myself (%s) at %s - should not happen", remoteID, c)
|
2016-05-04 19:38:12 +00:00
|
|
|
c.Close()
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2019-08-09 11:31:42 +00:00
|
|
|
_ = c.SetDeadline(time.Now().Add(20 * time.Second))
|
2016-06-09 10:50:14 +00:00
|
|
|
hello, err := protocol.ExchangeHello(c, s.model.GetHello(remoteID))
|
2016-05-04 19:38:12 +00:00
|
|
|
if err != nil {
|
2016-06-09 10:50:14 +00:00
|
|
|
if protocol.IsVersionMismatch(err) {
|
|
|
|
// The error will be a relatively user friendly description
|
2016-07-04 10:40:29 +00:00
|
|
|
// of what's wrong with the version compatibility. By
|
|
|
|
// default identify the other side by device ID and IP.
|
|
|
|
remote := fmt.Sprintf("%v (%v)", remoteID, c.RemoteAddr())
|
|
|
|
if hello.DeviceName != "" {
|
|
|
|
// If the name was set in the hello return, use that to
|
|
|
|
// give the user more info about which device is the
|
|
|
|
// affected one. It probably says more than the remote
|
|
|
|
// IP.
|
|
|
|
remote = fmt.Sprintf("%q (%s %s, %v)", hello.DeviceName, hello.ClientName, hello.ClientVersion, remoteID)
|
|
|
|
}
|
|
|
|
msg := fmt.Sprintf("Connecting to %s: %s", remote, err)
|
2016-06-09 12:30:35 +00:00
|
|
|
warningFor(remoteID, msg)
|
2016-06-09 10:50:14 +00:00
|
|
|
} else {
|
|
|
|
// It's something else - connection reset or whatever
|
2018-01-12 11:27:55 +00:00
|
|
|
l.Infof("Failed to exchange Hello messages with %s at %s: %s", remoteID, c, err)
|
2016-06-09 10:50:14 +00:00
|
|
|
}
|
2016-05-04 19:38:12 +00:00
|
|
|
c.Close()
|
|
|
|
continue
|
|
|
|
}
|
2019-08-09 11:31:42 +00:00
|
|
|
_ = c.SetDeadline(time.Time{})
|
2016-05-04 19:38:12 +00:00
|
|
|
|
2016-08-05 09:29:49 +00:00
|
|
|
// The Model will return an error for devices that we don't want to
|
|
|
|
// have a connection with for whatever reason, for example unknown devices.
|
|
|
|
if err := s.model.OnHello(remoteID, c.RemoteAddr(), hello); err != nil {
|
2016-12-02 11:56:14 +00:00
|
|
|
l.Infof("Connection from %s at %s (%s) rejected: %v", remoteID, c.RemoteAddr(), c.Type(), err)
|
2016-08-05 09:29:49 +00:00
|
|
|
c.Close()
|
|
|
|
continue
|
|
|
|
}
|
2016-05-04 19:38:12 +00:00
|
|
|
|
|
|
|
// If we have a relay connection, and the new incoming connection is
|
2017-11-04 07:20:11 +00:00
|
|
|
// not a relay connection, we should drop that, and prefer this one.
|
2017-11-21 07:25:38 +00:00
|
|
|
ct, connected := s.model.Connection(remoteID)
|
2016-05-04 19:38:12 +00:00
|
|
|
|
|
|
|
// Lower priority is better, just like nice etc.
|
2020-04-20 06:23:38 +00:00
|
|
|
if connected && (ct.Priority() > c.priority || time.Since(ct.Statistics().StartedAt) > minConnectionReplaceAge) {
|
2017-11-21 07:25:38 +00:00
|
|
|
l.Debugf("Switching connections %s (existing: %s new: %s)", remoteID, ct, c)
|
2016-08-07 12:20:37 +00:00
|
|
|
} else if connected {
|
2016-05-04 19:38:12 +00:00
|
|
|
// We should not already be connected to the other party. TODO: This
|
|
|
|
// could use some better handling. If the old connection is dead but
|
|
|
|
// hasn't timed out yet we may want to drop *that* connection and keep
|
|
|
|
// this one. But in case we are two devices connecting to each other
|
|
|
|
// in parallel we don't want to do that or we end up with no
|
|
|
|
// connections still established...
|
2017-11-21 07:25:38 +00:00
|
|
|
l.Infof("Connected to already connected device %s (existing: %s new: %s)", remoteID, ct, c)
|
2016-05-04 19:38:12 +00:00
|
|
|
c.Close()
|
2016-05-09 15:03:12 +00:00
|
|
|
continue
|
2016-05-04 19:38:12 +00:00
|
|
|
}
|
|
|
|
|
2016-08-05 09:29:49 +00:00
|
|
|
deviceCfg, ok := s.cfg.Device(remoteID)
|
|
|
|
if !ok {
|
2018-10-30 09:34:19 +00:00
|
|
|
l.Infof("Device %s removed from config during connection attempt at %s", remoteID, c)
|
|
|
|
c.Close()
|
|
|
|
continue
|
2016-08-05 09:29:49 +00:00
|
|
|
}
|
2016-05-04 19:38:12 +00:00
|
|
|
|
2016-08-05 09:29:49 +00:00
|
|
|
// Verify the name on the certificate. By default we set it to
|
|
|
|
// "syncthing" when generating, but the user may have replaced
|
|
|
|
// the certificate and used another name.
|
|
|
|
certName := deviceCfg.CertName
|
|
|
|
if certName == "" {
|
|
|
|
certName = s.tlsDefaultCommonName
|
|
|
|
}
|
|
|
|
if err := remoteCert.VerifyHostname(certName); err != nil {
|
|
|
|
// Incorrect certificate name is something the user most
|
|
|
|
// likely wants to know about, since it's an advanced
|
|
|
|
// config. Warn instead of Info.
|
2018-01-12 11:27:55 +00:00
|
|
|
l.Warnf("Bad certificate from %s at %s: %v", remoteID, c, err)
|
2016-08-05 09:29:49 +00:00
|
|
|
c.Close()
|
2019-07-09 09:40:30 +00:00
|
|
|
continue
|
2016-08-05 09:29:49 +00:00
|
|
|
}
|
2016-05-04 19:38:12 +00:00
|
|
|
|
2017-01-02 11:29:20 +00:00
|
|
|
// Wrap the connection in rate limiters. The limiter itself will
|
|
|
|
// keep up with config changes to the rate and whether or not LAN
|
|
|
|
// connections are limited.
|
|
|
|
isLAN := s.isLAN(c.RemoteAddr())
|
2018-03-26 10:01:59 +00:00
|
|
|
rd, wr := s.limiter.getLimiters(remoteID, c, isLAN)
|
2016-05-04 19:38:12 +00:00
|
|
|
|
2018-01-12 11:27:55 +00:00
|
|
|
protoConn := protocol.NewConnection(remoteID, rd, wr, s.model, c.String(), deviceCfg.Compression)
|
2016-11-30 07:54:20 +00:00
|
|
|
modelConn := completeConn{c, protoConn}
|
2016-05-04 19:38:12 +00:00
|
|
|
|
2019-02-26 10:49:02 +00:00
|
|
|
l.Infof("Established secure connection to %s at %s", remoteID, c)
|
2016-05-04 19:38:12 +00:00
|
|
|
|
2016-08-05 09:29:49 +00:00
|
|
|
s.model.AddConnection(modelConn, hello)
|
2019-07-09 09:40:30 +00:00
|
|
|
continue
|
2016-05-04 19:38:12 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-11-21 07:41:15 +00:00
|
|
|
func (s *service) connect(ctx context.Context) {
|
2016-05-04 19:38:12 +00:00
|
|
|
nextDial := make(map[string]time.Time)
|
2016-05-09 15:03:12 +00:00
|
|
|
|
2016-05-17 00:05:38 +00:00
|
|
|
// Used as delay for the first few connection attempts, increases
|
|
|
|
// exponentially
|
|
|
|
initialRampup := time.Second
|
|
|
|
|
|
|
|
// Calculated from actual dialers reconnectInterval
|
|
|
|
var sleep time.Duration
|
2016-05-09 15:33:25 +00:00
|
|
|
|
2016-05-04 19:38:12 +00:00
|
|
|
for {
|
2016-11-12 09:34:18 +00:00
|
|
|
cfg := s.cfg.RawCopy()
|
2016-05-17 00:05:38 +00:00
|
|
|
|
|
|
|
bestDialerPrio := 1<<31 - 1 // worse prio won't build on 32 bit
|
|
|
|
for _, df := range dialers {
|
2018-02-09 10:40:57 +00:00
|
|
|
if df.Valid(cfg) != nil {
|
2016-05-17 00:05:38 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
if prio := df.Priority(); prio < bestDialerPrio {
|
|
|
|
bestDialerPrio = prio
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-05-04 19:38:12 +00:00
|
|
|
l.Debugln("Reconnect loop")
|
|
|
|
|
|
|
|
now := time.Now()
|
|
|
|
var seen []string
|
|
|
|
|
2016-05-17 00:05:38 +00:00
|
|
|
for _, deviceCfg := range cfg.Devices {
|
2020-02-13 13:43:00 +00:00
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
return
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
|
2016-05-17 00:05:38 +00:00
|
|
|
deviceID := deviceCfg.DeviceID
|
2016-05-04 19:38:12 +00:00
|
|
|
if deviceID == s.myID {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2016-12-21 18:41:25 +00:00
|
|
|
if deviceCfg.Paused {
|
2016-05-04 19:38:12 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2017-11-21 07:25:38 +00:00
|
|
|
ct, connected := s.model.Connection(deviceID)
|
2016-05-09 15:03:12 +00:00
|
|
|
|
2017-11-21 07:25:38 +00:00
|
|
|
if connected && ct.Priority() == bestDialerPrio {
|
2016-05-09 15:33:25 +00:00
|
|
|
// Things are already as good as they can get.
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2016-05-04 19:38:12 +00:00
|
|
|
var addrs []string
|
|
|
|
for _, addr := range deviceCfg.Addresses {
|
|
|
|
if addr == "dynamic" {
|
|
|
|
if s.discoverer != nil {
|
2020-02-13 13:43:00 +00:00
|
|
|
if t, err := s.discoverer.Lookup(ctx, deviceID); err == nil {
|
2016-05-04 19:38:12 +00:00
|
|
|
addrs = append(addrs, t...)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
addrs = append(addrs, addr)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-05-29 07:56:40 +00:00
|
|
|
addrs = util.UniqueTrimmedStrings(addrs)
|
2017-11-22 07:05:49 +00:00
|
|
|
|
2017-11-21 07:25:38 +00:00
|
|
|
l.Debugln("Reconnect loop for", deviceID, addrs)
|
|
|
|
|
2017-11-15 09:36:33 +00:00
|
|
|
dialTargets := make([]dialTarget, 0)
|
|
|
|
|
2016-05-04 19:38:12 +00:00
|
|
|
for _, addr := range addrs {
|
2018-02-25 15:12:46 +00:00
|
|
|
// Use a special key that is more than just the address, as you might have two devices connected to the same relay
|
|
|
|
nextDialKey := deviceID.String() + "/" + addr
|
|
|
|
seen = append(seen, nextDialKey)
|
|
|
|
nextDialAt, ok := nextDial[nextDialKey]
|
2016-05-17 00:05:38 +00:00
|
|
|
if ok && initialRampup >= sleep && nextDialAt.After(now) {
|
2018-02-25 15:12:46 +00:00
|
|
|
l.Debugf("Not dialing %s via %v as sleep is %v, next dial is at %s and current time is %s", deviceID, addr, sleep, nextDialAt, now)
|
2016-05-17 00:05:38 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
// If we fail at any step before actually getting the dialer
|
|
|
|
// retry in a minute
|
2018-02-25 15:12:46 +00:00
|
|
|
nextDial[nextDialKey] = now.Add(time.Minute)
|
2016-05-17 00:05:38 +00:00
|
|
|
|
2016-05-04 19:38:12 +00:00
|
|
|
uri, err := url.Parse(addr)
|
|
|
|
if err != nil {
|
2019-05-16 21:11:46 +00:00
|
|
|
s.setConnectionStatus(addr, err)
|
2017-11-14 21:49:36 +00:00
|
|
|
l.Infof("Parsing dialer address %s: %v", addr, err)
|
2016-05-04 19:38:12 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2017-04-01 09:52:31 +00:00
|
|
|
if len(deviceCfg.AllowedNetworks) > 0 {
|
|
|
|
if !IsAllowedNetwork(uri.Host, deviceCfg.AllowedNetworks) {
|
2019-05-16 21:11:46 +00:00
|
|
|
s.setConnectionStatus(addr, errors.New("network disallowed"))
|
2017-04-01 09:52:31 +00:00
|
|
|
l.Debugln("Network for", uri, "is disallowed")
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-02-09 10:40:57 +00:00
|
|
|
dialerFactory, err := getDialerFactory(cfg, uri)
|
2019-05-16 21:11:46 +00:00
|
|
|
if err != nil {
|
|
|
|
s.setConnectionStatus(addr, err)
|
|
|
|
}
|
2018-02-09 10:40:57 +00:00
|
|
|
switch err {
|
|
|
|
case nil:
|
|
|
|
// all good
|
|
|
|
case errDisabled:
|
|
|
|
l.Debugln("Dialer for", uri, "is disabled")
|
2016-05-04 19:38:12 +00:00
|
|
|
continue
|
2018-02-09 10:40:57 +00:00
|
|
|
case errDeprecated:
|
|
|
|
l.Debugln("Dialer for", uri, "is deprecated")
|
|
|
|
continue
|
|
|
|
default:
|
|
|
|
l.Infof("Dialer for %v: %v", uri, err)
|
2016-05-04 19:38:12 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2017-11-22 07:05:49 +00:00
|
|
|
priority := dialerFactory.Priority()
|
2017-11-15 09:36:33 +00:00
|
|
|
|
2017-11-22 07:05:49 +00:00
|
|
|
if connected && priority >= ct.Priority() {
|
2017-11-21 07:25:38 +00:00
|
|
|
l.Debugf("Not dialing using %s as priority is less than current connection (%d >= %d)", dialerFactory, dialerFactory.Priority(), ct.Priority())
|
2016-05-04 19:38:12 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2019-11-26 07:36:58 +00:00
|
|
|
dialer := dialerFactory.New(s.cfg.Options(), s.tlsCfg)
|
2018-02-25 15:12:46 +00:00
|
|
|
nextDial[nextDialKey] = now.Add(dialer.RedialFrequency())
|
2016-05-17 00:05:38 +00:00
|
|
|
|
2017-11-22 07:05:49 +00:00
|
|
|
// For LAN addresses, increase the priority so that we
|
|
|
|
// try these first.
|
|
|
|
switch {
|
|
|
|
case dialerFactory.AlwaysWAN():
|
|
|
|
// Do nothing.
|
|
|
|
case s.isLANHost(uri.Host):
|
|
|
|
priority -= 1
|
|
|
|
}
|
|
|
|
|
2017-11-15 09:36:33 +00:00
|
|
|
dialTargets = append(dialTargets, dialTarget{
|
2019-05-16 21:11:46 +00:00
|
|
|
addr: addr,
|
2017-11-15 09:36:33 +00:00
|
|
|
dialer: dialer,
|
2017-11-22 07:05:49 +00:00
|
|
|
priority: priority,
|
2017-11-15 09:36:33 +00:00
|
|
|
deviceID: deviceID,
|
|
|
|
uri: uri,
|
|
|
|
})
|
|
|
|
}
|
2016-05-04 19:38:12 +00:00
|
|
|
|
2019-11-26 07:39:51 +00:00
|
|
|
conn, ok := s.dialParallel(ctx, deviceCfg.DeviceID, dialTargets)
|
2017-11-15 09:36:33 +00:00
|
|
|
if ok {
|
2016-05-04 19:38:12 +00:00
|
|
|
s.conns <- conn
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
nextDial, sleep = filterAndFindSleepDuration(nextDial, seen, now)
|
|
|
|
|
2016-05-17 00:05:38 +00:00
|
|
|
if initialRampup < sleep {
|
|
|
|
l.Debugln("initial rampup; sleep", initialRampup, "and update to", initialRampup*2)
|
2019-07-09 09:40:30 +00:00
|
|
|
sleep = initialRampup
|
2016-05-17 00:05:38 +00:00
|
|
|
initialRampup *= 2
|
2016-05-04 19:38:12 +00:00
|
|
|
} else {
|
2016-05-17 00:05:38 +00:00
|
|
|
l.Debugln("sleep until next dial", sleep)
|
2019-07-09 09:40:30 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
select {
|
|
|
|
case <-time.After(sleep):
|
2019-11-21 07:41:15 +00:00
|
|
|
case <-ctx.Done():
|
2019-07-09 09:40:30 +00:00
|
|
|
return
|
2016-05-04 19:38:12 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-02-26 08:09:25 +00:00
|
|
|
func (s *service) isLANHost(host string) bool {
|
2017-11-22 08:00:07 +00:00
|
|
|
// Probably we are called with an ip:port combo which we can resolve as
|
|
|
|
// a TCP address.
|
|
|
|
if addr, err := net.ResolveTCPAddr("tcp", host); err == nil {
|
|
|
|
return s.isLAN(addr)
|
2017-11-22 07:05:49 +00:00
|
|
|
}
|
2017-11-22 08:00:07 +00:00
|
|
|
// ... but this function looks general enough that someone might try
|
|
|
|
// with just an IP as well in the future so lets allow that.
|
|
|
|
if addr, err := net.ResolveIPAddr("ip", host); err == nil {
|
|
|
|
return s.isLAN(addr)
|
2017-11-22 07:05:49 +00:00
|
|
|
}
|
2017-11-22 08:00:07 +00:00
|
|
|
return false
|
2017-11-22 07:05:49 +00:00
|
|
|
}
|
|
|
|
|
2019-02-26 08:09:25 +00:00
|
|
|
func (s *service) isLAN(addr net.Addr) bool {
|
2017-11-22 08:00:07 +00:00
|
|
|
var ip net.IP
|
|
|
|
|
|
|
|
switch addr := addr.(type) {
|
|
|
|
case *net.IPAddr:
|
|
|
|
ip = addr.IP
|
|
|
|
case *net.TCPAddr:
|
|
|
|
ip = addr.IP
|
|
|
|
case *net.UDPAddr:
|
|
|
|
ip = addr.IP
|
|
|
|
default:
|
|
|
|
// From the standard library, just Unix sockets.
|
|
|
|
// If you invent your own, handle it.
|
2017-01-02 11:29:20 +00:00
|
|
|
return false
|
2016-05-04 19:38:12 +00:00
|
|
|
}
|
2017-11-06 14:05:29 +00:00
|
|
|
|
2017-11-22 08:00:07 +00:00
|
|
|
if ip.IsLoopback() {
|
2017-11-06 14:05:29 +00:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, lan := range s.cfg.Options().AlwaysLocalNets {
|
|
|
|
_, ipnet, err := net.ParseCIDR(lan)
|
|
|
|
if err != nil {
|
|
|
|
l.Debugln("Network", lan, "is malformed:", err)
|
|
|
|
continue
|
|
|
|
}
|
2017-11-22 08:00:07 +00:00
|
|
|
if ipnet.Contains(ip) {
|
2017-11-06 14:05:29 +00:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
lans, _ := osutil.GetLans()
|
|
|
|
for _, lan := range lans {
|
2017-11-22 08:00:07 +00:00
|
|
|
if lan.Contains(ip) {
|
2017-01-02 11:29:20 +00:00
|
|
|
return true
|
2016-05-04 19:38:12 +00:00
|
|
|
}
|
|
|
|
}
|
2017-11-06 14:05:29 +00:00
|
|
|
|
|
|
|
return false
|
2016-05-04 19:38:12 +00:00
|
|
|
}
|
|
|
|
|
2019-02-26 08:09:25 +00:00
|
|
|
func (s *service) createListener(factory listenerFactory, uri *url.URL) bool {
|
2016-05-09 15:03:12 +00:00
|
|
|
// must be called with listenerMut held
|
2016-05-04 19:38:12 +00:00
|
|
|
|
2016-05-17 00:05:38 +00:00
|
|
|
l.Debugln("Starting listener", uri)
|
2016-05-04 19:38:12 +00:00
|
|
|
|
2016-05-17 00:05:38 +00:00
|
|
|
listener := factory.New(uri, s.cfg, s.tlsCfg, s.conns, s.natService)
|
2016-05-04 19:38:12 +00:00
|
|
|
listener.OnAddressesChanged(s.logListenAddressesChangedEvent)
|
2016-05-17 00:05:38 +00:00
|
|
|
s.listeners[uri.String()] = listener
|
2016-11-19 12:37:14 +00:00
|
|
|
s.listenerTokens[uri.String()] = s.listenerSupervisor.Add(listener)
|
2016-05-17 00:05:38 +00:00
|
|
|
return true
|
2016-05-04 19:38:12 +00:00
|
|
|
}
|
|
|
|
|
2019-02-26 08:09:25 +00:00
|
|
|
func (s *service) logListenAddressesChangedEvent(l genericListener) {
|
2019-08-15 14:29:37 +00:00
|
|
|
s.evLogger.Log(events.ListenAddressesChanged, map[string]interface{}{
|
2016-05-04 19:38:12 +00:00
|
|
|
"address": l.URI(),
|
|
|
|
"lan": l.LANAddresses(),
|
|
|
|
"wan": l.WANAddresses(),
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2019-02-26 08:09:25 +00:00
|
|
|
func (s *service) VerifyConfiguration(from, to config.Configuration) error {
|
2016-05-04 19:38:12 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-02-26 08:09:25 +00:00
|
|
|
func (s *service) CommitConfiguration(from, to config.Configuration) bool {
|
2016-05-04 19:38:12 +00:00
|
|
|
newDevices := make(map[protocol.DeviceID]bool, len(to.Devices))
|
|
|
|
for _, dev := range to.Devices {
|
|
|
|
newDevices[dev.DeviceID] = true
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, dev := range from.Devices {
|
|
|
|
if !newDevices[dev.DeviceID] {
|
2016-08-07 16:21:59 +00:00
|
|
|
warningLimitersMut.Lock()
|
|
|
|
delete(warningLimiters, dev.DeviceID)
|
|
|
|
warningLimitersMut.Unlock()
|
2016-05-04 19:38:12 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-05-09 15:03:12 +00:00
|
|
|
s.listenersMut.Lock()
|
2016-05-04 19:38:12 +00:00
|
|
|
seen := make(map[string]struct{})
|
2019-11-26 16:07:25 +00:00
|
|
|
for _, addr := range to.Options.ListenAddresses() {
|
2017-11-17 09:12:35 +00:00
|
|
|
if addr == "" {
|
|
|
|
// We can get an empty address if there is an empty listener
|
|
|
|
// element in the config, indicating no listeners should be
|
|
|
|
// used. This is not an error.
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2016-05-17 00:05:38 +00:00
|
|
|
if _, ok := s.listeners[addr]; ok {
|
|
|
|
seen[addr] = struct{}{}
|
|
|
|
continue
|
2016-05-04 19:38:12 +00:00
|
|
|
}
|
2016-05-17 00:05:38 +00:00
|
|
|
|
|
|
|
uri, err := url.Parse(addr)
|
|
|
|
if err != nil {
|
2017-11-14 21:49:36 +00:00
|
|
|
l.Infof("Parsing listener address %s: %v", addr, err)
|
2016-05-17 00:05:38 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2018-02-09 10:40:57 +00:00
|
|
|
factory, err := getListenerFactory(to, uri)
|
|
|
|
switch err {
|
|
|
|
case nil:
|
|
|
|
// all good
|
|
|
|
case errDisabled:
|
2016-05-17 00:05:38 +00:00
|
|
|
l.Debugln("Listener for", uri, "is disabled")
|
|
|
|
continue
|
2018-02-09 10:40:57 +00:00
|
|
|
case errDeprecated:
|
|
|
|
l.Debugln("Listener for", uri, "is deprecated")
|
|
|
|
continue
|
|
|
|
default:
|
|
|
|
l.Infof("Listener for %v: %v", uri, err)
|
2016-05-17 00:05:38 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
s.createListener(factory, uri)
|
2016-05-04 19:38:12 +00:00
|
|
|
seen[addr] = struct{}{}
|
|
|
|
}
|
|
|
|
|
2016-05-17 00:05:38 +00:00
|
|
|
for addr, listener := range s.listeners {
|
2018-02-09 10:40:57 +00:00
|
|
|
if _, ok := seen[addr]; !ok || listener.Factory().Valid(to) != nil {
|
2016-05-04 19:38:12 +00:00
|
|
|
l.Debugln("Stopping listener", addr)
|
2019-02-02 11:16:27 +00:00
|
|
|
s.listenerSupervisor.Remove(s.listenerTokens[addr])
|
2016-05-04 19:38:12 +00:00
|
|
|
delete(s.listenerTokens, addr)
|
|
|
|
delete(s.listeners, addr)
|
|
|
|
}
|
|
|
|
}
|
2016-05-09 15:03:12 +00:00
|
|
|
s.listenersMut.Unlock()
|
2016-05-04 19:38:12 +00:00
|
|
|
|
|
|
|
if to.Options.NATEnabled && s.natServiceToken == nil {
|
|
|
|
l.Debugln("Starting NAT service")
|
|
|
|
token := s.Add(s.natService)
|
|
|
|
s.natServiceToken = &token
|
|
|
|
} else if !to.Options.NATEnabled && s.natServiceToken != nil {
|
|
|
|
l.Debugln("Stopping NAT service")
|
2019-02-02 11:16:27 +00:00
|
|
|
s.Remove(*s.natServiceToken)
|
2016-05-04 19:38:12 +00:00
|
|
|
s.natServiceToken = nil
|
|
|
|
}
|
|
|
|
|
2016-08-07 16:21:59 +00:00
|
|
|
return true
|
2016-05-04 19:38:12 +00:00
|
|
|
}
|
|
|
|
|
2019-02-26 08:09:25 +00:00
|
|
|
func (s *service) AllAddresses() []string {
|
2016-05-09 15:03:12 +00:00
|
|
|
s.listenersMut.RLock()
|
2016-05-04 19:38:12 +00:00
|
|
|
var addrs []string
|
|
|
|
for _, listener := range s.listeners {
|
|
|
|
for _, lanAddr := range listener.LANAddresses() {
|
|
|
|
addrs = append(addrs, lanAddr.String())
|
|
|
|
}
|
|
|
|
for _, wanAddr := range listener.WANAddresses() {
|
|
|
|
addrs = append(addrs, wanAddr.String())
|
|
|
|
}
|
|
|
|
}
|
2016-05-09 15:03:12 +00:00
|
|
|
s.listenersMut.RUnlock()
|
2019-05-29 07:56:40 +00:00
|
|
|
return util.UniqueTrimmedStrings(addrs)
|
2016-05-04 19:38:12 +00:00
|
|
|
}
|
|
|
|
|
2019-02-26 08:09:25 +00:00
|
|
|
func (s *service) ExternalAddresses() []string {
|
2016-05-09 15:03:12 +00:00
|
|
|
s.listenersMut.RLock()
|
2016-05-04 19:38:12 +00:00
|
|
|
var addrs []string
|
|
|
|
for _, listener := range s.listeners {
|
|
|
|
for _, wanAddr := range listener.WANAddresses() {
|
|
|
|
addrs = append(addrs, wanAddr.String())
|
|
|
|
}
|
|
|
|
}
|
2016-05-09 15:03:12 +00:00
|
|
|
s.listenersMut.RUnlock()
|
2019-05-29 07:56:40 +00:00
|
|
|
return util.UniqueTrimmedStrings(addrs)
|
2016-05-04 19:38:12 +00:00
|
|
|
}
|
|
|
|
|
2019-05-16 21:11:46 +00:00
|
|
|
func (s *service) ListenerStatus() map[string]ListenerStatusEntry {
|
|
|
|
result := make(map[string]ListenerStatusEntry)
|
2016-05-09 15:03:12 +00:00
|
|
|
s.listenersMut.RLock()
|
2016-05-04 19:38:12 +00:00
|
|
|
for addr, listener := range s.listeners {
|
2019-05-16 21:11:46 +00:00
|
|
|
var status ListenerStatusEntry
|
2016-05-04 19:38:12 +00:00
|
|
|
|
2019-05-16 21:11:46 +00:00
|
|
|
if err := listener.Error(); err != nil {
|
|
|
|
errStr := err.Error()
|
|
|
|
status.Error = &errStr
|
2016-05-04 19:38:12 +00:00
|
|
|
}
|
|
|
|
|
2019-05-16 21:11:46 +00:00
|
|
|
status.LANAddresses = urlsToStrings(listener.LANAddresses())
|
|
|
|
status.WANAddresses = urlsToStrings(listener.WANAddresses())
|
2016-05-04 19:38:12 +00:00
|
|
|
|
|
|
|
result[addr] = status
|
|
|
|
}
|
2016-05-09 15:03:12 +00:00
|
|
|
s.listenersMut.RUnlock()
|
2016-05-04 19:38:12 +00:00
|
|
|
return result
|
|
|
|
}
|
|
|
|
|
2020-02-25 20:18:31 +00:00
|
|
|
type connectionStatusHandler struct {
|
|
|
|
connectionStatusMut sync.RWMutex
|
|
|
|
connectionStatus map[string]ConnectionStatusEntry // address -> latest error/status
|
|
|
|
}
|
|
|
|
|
|
|
|
func newConnectionStatusHandler() connectionStatusHandler {
|
|
|
|
return connectionStatusHandler{
|
|
|
|
connectionStatusMut: sync.NewRWMutex(),
|
|
|
|
connectionStatus: make(map[string]ConnectionStatusEntry),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *connectionStatusHandler) ConnectionStatus() map[string]ConnectionStatusEntry {
|
2019-05-16 21:11:46 +00:00
|
|
|
result := make(map[string]ConnectionStatusEntry)
|
|
|
|
s.connectionStatusMut.RLock()
|
|
|
|
for k, v := range s.connectionStatus {
|
|
|
|
result[k] = v
|
|
|
|
}
|
|
|
|
s.connectionStatusMut.RUnlock()
|
|
|
|
return result
|
|
|
|
}
|
|
|
|
|
2020-02-25 20:18:31 +00:00
|
|
|
func (s *connectionStatusHandler) setConnectionStatus(address string, err error) {
|
2020-02-25 15:56:24 +00:00
|
|
|
if errors.Cause(err) == context.Canceled {
|
2019-11-26 07:39:51 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-05-16 21:11:46 +00:00
|
|
|
status := ConnectionStatusEntry{When: time.Now().UTC().Truncate(time.Second)}
|
|
|
|
if err != nil {
|
|
|
|
errStr := err.Error()
|
|
|
|
status.Error = &errStr
|
|
|
|
}
|
|
|
|
|
|
|
|
s.connectionStatusMut.Lock()
|
|
|
|
s.connectionStatus[address] = status
|
|
|
|
s.connectionStatusMut.Unlock()
|
|
|
|
}
|
|
|
|
|
2019-02-26 08:09:25 +00:00
|
|
|
func (s *service) NATType() string {
|
2017-10-12 06:16:46 +00:00
|
|
|
s.listenersMut.RLock()
|
|
|
|
defer s.listenersMut.RUnlock()
|
|
|
|
for _, listener := range s.listeners {
|
|
|
|
natType := listener.NATType()
|
|
|
|
if natType != "unknown" {
|
|
|
|
return natType
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return "unknown"
|
|
|
|
}
|
|
|
|
|
2018-02-09 10:40:57 +00:00
|
|
|
func getDialerFactory(cfg config.Configuration, uri *url.URL) (dialerFactory, error) {
|
2016-05-17 00:05:38 +00:00
|
|
|
dialerFactory, ok := dialers[uri.Scheme]
|
|
|
|
if !ok {
|
|
|
|
return nil, fmt.Errorf("unknown address scheme %q", uri.Scheme)
|
|
|
|
}
|
2018-02-09 10:40:57 +00:00
|
|
|
if err := dialerFactory.Valid(cfg); err != nil {
|
|
|
|
return nil, err
|
2016-05-17 00:05:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return dialerFactory, nil
|
|
|
|
}
|
|
|
|
|
2018-02-09 10:40:57 +00:00
|
|
|
func getListenerFactory(cfg config.Configuration, uri *url.URL) (listenerFactory, error) {
|
2016-05-17 00:05:38 +00:00
|
|
|
listenerFactory, ok := listeners[uri.Scheme]
|
|
|
|
if !ok {
|
|
|
|
return nil, fmt.Errorf("unknown address scheme %q", uri.Scheme)
|
|
|
|
}
|
2018-02-09 10:40:57 +00:00
|
|
|
if err := listenerFactory.Valid(cfg); err != nil {
|
|
|
|
return nil, err
|
2016-05-17 00:05:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return listenerFactory, nil
|
|
|
|
}
|
|
|
|
|
2016-05-04 19:38:12 +00:00
|
|
|
func filterAndFindSleepDuration(nextDial map[string]time.Time, seen []string, now time.Time) (map[string]time.Time, time.Duration) {
|
|
|
|
newNextDial := make(map[string]time.Time)
|
|
|
|
|
|
|
|
for _, addr := range seen {
|
|
|
|
nextDialAt, ok := nextDial[addr]
|
|
|
|
if ok {
|
|
|
|
newNextDial[addr] = nextDialAt
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
min := time.Minute
|
|
|
|
for _, next := range newNextDial {
|
|
|
|
cur := next.Sub(now)
|
|
|
|
if cur < min {
|
|
|
|
min = cur
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return newNextDial, min
|
|
|
|
}
|
|
|
|
|
|
|
|
func urlsToStrings(urls []*url.URL) []string {
|
|
|
|
strings := make([]string, len(urls))
|
|
|
|
for i, url := range urls {
|
|
|
|
strings[i] = url.String()
|
|
|
|
}
|
|
|
|
return strings
|
|
|
|
}
|
2016-06-09 12:30:35 +00:00
|
|
|
|
2017-01-02 11:29:20 +00:00
|
|
|
var warningLimiters = make(map[protocol.DeviceID]*rate.Limiter)
|
2016-06-09 12:30:35 +00:00
|
|
|
var warningLimitersMut = sync.NewMutex()
|
|
|
|
|
|
|
|
func warningFor(dev protocol.DeviceID, msg string) {
|
|
|
|
warningLimitersMut.Lock()
|
|
|
|
defer warningLimitersMut.Unlock()
|
|
|
|
lim, ok := warningLimiters[dev]
|
|
|
|
if !ok {
|
2017-01-02 11:29:20 +00:00
|
|
|
lim = rate.NewLimiter(rate.Every(perDeviceWarningIntv), 1)
|
2016-06-09 12:30:35 +00:00
|
|
|
warningLimiters[dev] = lim
|
|
|
|
}
|
2017-01-02 11:29:20 +00:00
|
|
|
if lim.Allow() {
|
2016-06-09 12:30:35 +00:00
|
|
|
l.Warnln(msg)
|
|
|
|
}
|
|
|
|
}
|
2016-07-02 20:33:31 +00:00
|
|
|
|
|
|
|
func tlsTimedHandshake(tc *tls.Conn) error {
|
2019-02-02 11:16:27 +00:00
|
|
|
tc.SetDeadline(time.Now().Add(tlsHandshakeTimeout))
|
|
|
|
defer tc.SetDeadline(time.Time{})
|
2016-07-02 20:33:31 +00:00
|
|
|
return tc.Handshake()
|
|
|
|
}
|
2017-04-01 09:52:31 +00:00
|
|
|
|
|
|
|
// IsAllowedNetwork returns true if the given host (IP or resolvable
|
|
|
|
// hostname) is in the set of allowed networks (CIDR format only).
|
|
|
|
func IsAllowedNetwork(host string, allowed []string) bool {
|
|
|
|
if hostNoPort, _, err := net.SplitHostPort(host); err == nil {
|
|
|
|
host = hostNoPort
|
|
|
|
}
|
|
|
|
|
|
|
|
addr, err := net.ResolveIPAddr("ip", host)
|
|
|
|
if err != nil {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, n := range allowed {
|
2017-04-13 17:43:29 +00:00
|
|
|
result := true
|
|
|
|
if strings.HasPrefix(n, "!") {
|
|
|
|
result = false
|
|
|
|
n = n[1:]
|
|
|
|
}
|
2017-04-01 09:52:31 +00:00
|
|
|
_, cidr, err := net.ParseCIDR(n)
|
|
|
|
if err != nil {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
if cidr.Contains(addr.IP) {
|
2017-04-13 17:43:29 +00:00
|
|
|
return result
|
2017-04-01 09:52:31 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return false
|
|
|
|
}
|
2017-11-15 09:36:33 +00:00
|
|
|
|
2019-11-26 07:39:51 +00:00
|
|
|
func (s *service) dialParallel(ctx context.Context, deviceID protocol.DeviceID, dialTargets []dialTarget) (internalConn, bool) {
|
2017-11-15 09:36:33 +00:00
|
|
|
// Group targets into buckets by priority
|
|
|
|
dialTargetBuckets := make(map[int][]dialTarget, len(dialTargets))
|
|
|
|
for _, tgt := range dialTargets {
|
|
|
|
dialTargetBuckets[tgt.priority] = append(dialTargetBuckets[tgt.priority], tgt)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get all available priorities
|
|
|
|
priorities := make([]int, 0, len(dialTargetBuckets))
|
|
|
|
for prio := range dialTargetBuckets {
|
|
|
|
priorities = append(priorities, prio)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Sort the priorities so that we dial lowest first (which means highest...)
|
|
|
|
sort.Ints(priorities)
|
|
|
|
|
|
|
|
for _, prio := range priorities {
|
|
|
|
tgts := dialTargetBuckets[prio]
|
|
|
|
res := make(chan internalConn, len(tgts))
|
2017-12-07 07:08:24 +00:00
|
|
|
wg := stdsync.WaitGroup{}
|
2017-11-15 09:36:33 +00:00
|
|
|
for _, tgt := range tgts {
|
|
|
|
wg.Add(1)
|
2017-11-19 17:38:13 +00:00
|
|
|
go func(tgt dialTarget) {
|
2019-11-26 07:39:51 +00:00
|
|
|
conn, err := tgt.Dial(ctx)
|
2017-11-15 09:36:33 +00:00
|
|
|
if err == nil {
|
2019-08-09 11:31:42 +00:00
|
|
|
// Closes the connection on error
|
|
|
|
err = s.validateIdentity(conn, deviceID)
|
|
|
|
}
|
|
|
|
s.setConnectionStatus(tgt.addr, err)
|
|
|
|
if err != nil {
|
|
|
|
l.Debugln("dialing", deviceID, tgt.uri, "error:", err)
|
|
|
|
} else {
|
|
|
|
l.Debugln("dialing", deviceID, tgt.uri, "success:", conn)
|
2017-11-15 09:36:33 +00:00
|
|
|
res <- conn
|
|
|
|
}
|
|
|
|
wg.Done()
|
2017-11-19 17:38:13 +00:00
|
|
|
}(tgt)
|
2017-11-15 09:36:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Spawn a routine which will unblock main routine in case we fail
|
|
|
|
// to connect to anyone.
|
|
|
|
go func() {
|
|
|
|
wg.Wait()
|
|
|
|
close(res)
|
|
|
|
}()
|
|
|
|
|
|
|
|
// Wait for the first connection, or for channel closure.
|
2018-01-12 11:27:55 +00:00
|
|
|
if conn, ok := <-res; ok {
|
|
|
|
// Got a connection, means more might come back, hence spawn a
|
|
|
|
// routine that will do the discarding.
|
2017-11-15 09:36:33 +00:00
|
|
|
l.Debugln("connected to", deviceID, prio, "using", conn, conn.priority)
|
|
|
|
go func(deviceID protocol.DeviceID, prio int) {
|
|
|
|
wg.Wait()
|
|
|
|
l.Debugln("discarding", len(res), "connections while connecting to", deviceID, prio)
|
|
|
|
for conn := range res {
|
|
|
|
conn.Close()
|
|
|
|
}
|
|
|
|
}(deviceID, prio)
|
2017-11-21 14:58:18 +00:00
|
|
|
return conn, ok
|
2017-11-15 09:36:33 +00:00
|
|
|
}
|
2018-01-12 11:27:55 +00:00
|
|
|
// Failed to connect, report that fact.
|
|
|
|
l.Debugln("failed to connect to", deviceID, prio)
|
2017-11-15 09:36:33 +00:00
|
|
|
}
|
|
|
|
return internalConn{}, false
|
|
|
|
}
|
2019-08-09 11:31:42 +00:00
|
|
|
|
|
|
|
func (s *service) validateIdentity(c internalConn, expectedID protocol.DeviceID) error {
|
|
|
|
cs := c.ConnectionState()
|
|
|
|
|
|
|
|
// We should have received exactly one certificate from the other
|
|
|
|
// side. If we didn't, they don't have a device ID and we drop the
|
|
|
|
// connection.
|
|
|
|
certs := cs.PeerCertificates
|
|
|
|
if cl := len(certs); cl != 1 {
|
|
|
|
l.Infof("Got peer certificate list of length %d != 1 from peer at %s; protocol error", cl, c)
|
|
|
|
c.Close()
|
|
|
|
return fmt.Errorf("expected 1 certificate, got %d", cl)
|
|
|
|
}
|
|
|
|
remoteCert := certs[0]
|
|
|
|
remoteID := protocol.NewDeviceID(remoteCert.Raw)
|
|
|
|
|
|
|
|
// The device ID should not be that of ourselves. It can happen
|
|
|
|
// though, especially in the presence of NAT hairpinning, multiple
|
|
|
|
// clients between the same NAT gateway, and global discovery.
|
|
|
|
if remoteID == s.myID {
|
|
|
|
l.Infof("Connected to myself (%s) at %s - should not happen", remoteID, c)
|
|
|
|
c.Close()
|
2020-03-03 21:40:00 +00:00
|
|
|
return errors.New("connected to self")
|
2019-08-09 11:31:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// We should see the expected device ID
|
|
|
|
if !remoteID.Equals(expectedID) {
|
|
|
|
c.Close()
|
|
|
|
return fmt.Errorf("unexpected device id, expected %s got %s", expectedID, remoteID)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|