syncthing/lib/relay/client/client.go

284 lines
5.6 KiB
Go
Raw Normal View History

2015-06-27 17:52:01 -07:00
// Copyright (C) 2015 Audrius Butkevicius and Contributors (see the CONTRIBUTORS file).
package client
import (
"crypto/tls"
"fmt"
"net"
"net/url"
"time"
2015-10-12 11:30:14 -07:00
"github.com/syncthing/syncthing/lib/dialer"
2015-09-22 10:38:46 -07:00
syncthingprotocol "github.com/syncthing/syncthing/lib/protocol"
"github.com/syncthing/syncthing/lib/relay/protocol"
2015-08-19 12:49:34 -07:00
"github.com/syncthing/syncthing/lib/sync"
2015-06-27 17:52:01 -07:00
)
type ProtocolClient struct {
URI *url.URL
Invitations chan protocol.SessionInvitation
closeInvitationsOnFinish bool
config *tls.Config
timeout time.Duration
stop chan struct{}
stopped chan struct{}
conn *tls.Conn
2015-07-22 14:34:05 -07:00
mut sync.RWMutex
connected bool
latency time.Duration
2015-06-27 17:52:01 -07:00
}
2015-07-20 02:56:10 -07:00
func NewProtocolClient(uri *url.URL, certs []tls.Certificate, invitations chan protocol.SessionInvitation) *ProtocolClient {
closeInvitationsOnFinish := false
if invitations == nil {
closeInvitationsOnFinish = true
invitations = make(chan protocol.SessionInvitation)
2015-06-28 12:34:28 -07:00
}
2015-07-20 02:56:10 -07:00
return &ProtocolClient{
URI: uri,
Invitations: invitations,
2015-06-27 17:52:01 -07:00
2015-07-20 02:56:10 -07:00
closeInvitationsOnFinish: closeInvitationsOnFinish,
2015-06-27 17:52:01 -07:00
2015-07-20 02:56:10 -07:00
config: configForCerts(certs),
2015-06-27 17:52:01 -07:00
2015-07-20 02:56:10 -07:00
timeout: time.Minute * 2,
stop: make(chan struct{}),
stopped: make(chan struct{}),
2015-07-22 14:34:05 -07:00
mut: sync.NewRWMutex(),
connected: false,
2015-07-20 02:56:10 -07:00
}
2015-06-27 17:52:01 -07:00
}
func (c *ProtocolClient) Serve() {
2015-07-20 02:56:10 -07:00
c.stop = make(chan struct{})
c.stopped = make(chan struct{})
defer close(c.stopped)
2015-06-27 17:52:01 -07:00
if err := c.connect(); err != nil {
Implement facility based logger, debugging via REST API This implements a new debug/trace infrastructure based on a slightly hacked up logger. Instead of the traditional "if debug { ... }" I've rewritten the logger to have no-op Debugln and Debugf, unless debugging has been enabled for a given "facility". The "facility" is just a string, typically a package name. This will be slightly slower than before; but not that much as it's mostly a function call that returns immediately. For the cases where it matters (the Debugln takes a hex.Dump() of something for example, and it's not in a very occasional "if err != nil" branch) there is an l.ShouldDebug(facility) that is fast enough to be used like the old "if debug". The point of all this is that we can now toggle debugging for the various packages on and off at runtime. There's a new method /rest/system/debug that can be POSTed a set of facilities to enable and disable debug for, or GET from to get a list of facilities with descriptions and their current debug status. Similarly a /rest/system/log?since=... can grab the latest log entries, up to 250 of them (hardcoded constant in main.go) plus the initial few. Not implemented in this commit (but planned) is a simple debug GUI available on /debug that shows the current log in an easily pasteable format and has checkboxes to enable the various debug facilities. The debug instructions to a user then becomes "visit this URL, check these boxes, reproduce your problem, copy and paste the log". The actual log viewer on the hypothetical /debug URL can poll regularly for new log entries and this bypass the 250 line limit. The existing STTRACE=foo variable is still obeyed and just sets the start state of the system.
2015-10-03 08:25:21 -07:00
l.Debugln("Relay connect:", err)
2015-07-20 02:56:10 -07:00
return
2015-06-27 17:52:01 -07:00
}
Implement facility based logger, debugging via REST API This implements a new debug/trace infrastructure based on a slightly hacked up logger. Instead of the traditional "if debug { ... }" I've rewritten the logger to have no-op Debugln and Debugf, unless debugging has been enabled for a given "facility". The "facility" is just a string, typically a package name. This will be slightly slower than before; but not that much as it's mostly a function call that returns immediately. For the cases where it matters (the Debugln takes a hex.Dump() of something for example, and it's not in a very occasional "if err != nil" branch) there is an l.ShouldDebug(facility) that is fast enough to be used like the old "if debug". The point of all this is that we can now toggle debugging for the various packages on and off at runtime. There's a new method /rest/system/debug that can be POSTed a set of facilities to enable and disable debug for, or GET from to get a list of facilities with descriptions and their current debug status. Similarly a /rest/system/log?since=... can grab the latest log entries, up to 250 of them (hardcoded constant in main.go) plus the initial few. Not implemented in this commit (but planned) is a simple debug GUI available on /debug that shows the current log in an easily pasteable format and has checkboxes to enable the various debug facilities. The debug instructions to a user then becomes "visit this URL, check these boxes, reproduce your problem, copy and paste the log". The actual log viewer on the hypothetical /debug URL can poll regularly for new log entries and this bypass the 250 line limit. The existing STTRACE=foo variable is still obeyed and just sets the start state of the system.
2015-10-03 08:25:21 -07:00
l.Debugln(c, "connected", c.conn.RemoteAddr())
2015-06-27 17:52:01 -07:00
if err := c.join(); err != nil {
c.conn.Close()
2015-07-20 02:56:10 -07:00
l.Infoln("Relay join:", err)
return
2015-06-27 17:52:01 -07:00
}
2015-07-20 02:56:10 -07:00
if err := c.conn.SetDeadline(time.Time{}); err != nil {
2015-10-12 09:10:59 -07:00
c.conn.Close()
2015-07-20 02:56:10 -07:00
l.Infoln("Relay set deadline:", err)
return
}
2015-06-27 17:52:01 -07:00
Implement facility based logger, debugging via REST API This implements a new debug/trace infrastructure based on a slightly hacked up logger. Instead of the traditional "if debug { ... }" I've rewritten the logger to have no-op Debugln and Debugf, unless debugging has been enabled for a given "facility". The "facility" is just a string, typically a package name. This will be slightly slower than before; but not that much as it's mostly a function call that returns immediately. For the cases where it matters (the Debugln takes a hex.Dump() of something for example, and it's not in a very occasional "if err != nil" branch) there is an l.ShouldDebug(facility) that is fast enough to be used like the old "if debug". The point of all this is that we can now toggle debugging for the various packages on and off at runtime. There's a new method /rest/system/debug that can be POSTed a set of facilities to enable and disable debug for, or GET from to get a list of facilities with descriptions and their current debug status. Similarly a /rest/system/log?since=... can grab the latest log entries, up to 250 of them (hardcoded constant in main.go) plus the initial few. Not implemented in this commit (but planned) is a simple debug GUI available on /debug that shows the current log in an easily pasteable format and has checkboxes to enable the various debug facilities. The debug instructions to a user then becomes "visit this URL, check these boxes, reproduce your problem, copy and paste the log". The actual log viewer on the hypothetical /debug URL can poll regularly for new log entries and this bypass the 250 line limit. The existing STTRACE=foo variable is still obeyed and just sets the start state of the system.
2015-10-03 08:25:21 -07:00
l.Debugln(c, "joined", c.conn.RemoteAddr(), "via", c.conn.LocalAddr())
2015-06-27 17:52:01 -07:00
defer c.cleanup()
2015-07-22 14:34:05 -07:00
c.mut.Lock()
c.connected = true
c.mut.Unlock()
2015-06-27 17:52:01 -07:00
messages := make(chan interface{})
errors := make(chan error, 1)
2015-07-20 02:56:10 -07:00
go messageReader(c.conn, messages, errors)
2015-06-27 17:52:01 -07:00
timeout := time.NewTimer(c.timeout)
2015-07-20 02:56:10 -07:00
2015-06-27 17:52:01 -07:00
for {
select {
case message := <-messages:
timeout.Reset(c.timeout)
2015-10-11 18:11:58 -07:00
l.Debugf("%s received message %T", c, message)
2015-07-20 02:56:10 -07:00
2015-06-27 17:52:01 -07:00
switch msg := message.(type) {
case protocol.Ping:
if err := protocol.WriteMessage(c.conn, protocol.Pong{}); err != nil {
2015-07-20 02:56:10 -07:00
l.Infoln("Relay write:", err)
return
2015-06-27 17:52:01 -07:00
}
Implement facility based logger, debugging via REST API This implements a new debug/trace infrastructure based on a slightly hacked up logger. Instead of the traditional "if debug { ... }" I've rewritten the logger to have no-op Debugln and Debugf, unless debugging has been enabled for a given "facility". The "facility" is just a string, typically a package name. This will be slightly slower than before; but not that much as it's mostly a function call that returns immediately. For the cases where it matters (the Debugln takes a hex.Dump() of something for example, and it's not in a very occasional "if err != nil" branch) there is an l.ShouldDebug(facility) that is fast enough to be used like the old "if debug". The point of all this is that we can now toggle debugging for the various packages on and off at runtime. There's a new method /rest/system/debug that can be POSTed a set of facilities to enable and disable debug for, or GET from to get a list of facilities with descriptions and their current debug status. Similarly a /rest/system/log?since=... can grab the latest log entries, up to 250 of them (hardcoded constant in main.go) plus the initial few. Not implemented in this commit (but planned) is a simple debug GUI available on /debug that shows the current log in an easily pasteable format and has checkboxes to enable the various debug facilities. The debug instructions to a user then becomes "visit this URL, check these boxes, reproduce your problem, copy and paste the log". The actual log viewer on the hypothetical /debug URL can poll regularly for new log entries and this bypass the 250 line limit. The existing STTRACE=foo variable is still obeyed and just sets the start state of the system.
2015-10-03 08:25:21 -07:00
l.Debugln(c, "sent pong")
2015-07-20 02:56:10 -07:00
2015-06-27 17:52:01 -07:00
case protocol.SessionInvitation:
ip := net.IP(msg.Address)
if len(ip) == 0 || ip.IsUnspecified() {
msg.Address = c.conn.RemoteAddr().(*net.TCPAddr).IP[:]
}
c.Invitations <- msg
2015-07-20 02:56:10 -07:00
2015-06-27 17:52:01 -07:00
default:
2015-07-20 02:56:10 -07:00
l.Infoln("Relay: protocol error: unexpected message %v", msg)
return
2015-06-27 17:52:01 -07:00
}
2015-07-20 02:56:10 -07:00
2015-06-27 17:52:01 -07:00
case <-c.stop:
Implement facility based logger, debugging via REST API This implements a new debug/trace infrastructure based on a slightly hacked up logger. Instead of the traditional "if debug { ... }" I've rewritten the logger to have no-op Debugln and Debugf, unless debugging has been enabled for a given "facility". The "facility" is just a string, typically a package name. This will be slightly slower than before; but not that much as it's mostly a function call that returns immediately. For the cases where it matters (the Debugln takes a hex.Dump() of something for example, and it's not in a very occasional "if err != nil" branch) there is an l.ShouldDebug(facility) that is fast enough to be used like the old "if debug". The point of all this is that we can now toggle debugging for the various packages on and off at runtime. There's a new method /rest/system/debug that can be POSTed a set of facilities to enable and disable debug for, or GET from to get a list of facilities with descriptions and their current debug status. Similarly a /rest/system/log?since=... can grab the latest log entries, up to 250 of them (hardcoded constant in main.go) plus the initial few. Not implemented in this commit (but planned) is a simple debug GUI available on /debug that shows the current log in an easily pasteable format and has checkboxes to enable the various debug facilities. The debug instructions to a user then becomes "visit this URL, check these boxes, reproduce your problem, copy and paste the log". The actual log viewer on the hypothetical /debug URL can poll regularly for new log entries and this bypass the 250 line limit. The existing STTRACE=foo variable is still obeyed and just sets the start state of the system.
2015-10-03 08:25:21 -07:00
l.Debugln(c, "stopping")
2015-07-20 02:56:10 -07:00
return
2015-06-27 17:52:01 -07:00
case err := <-errors:
2015-07-20 02:56:10 -07:00
l.Infoln("Relay received:", err)
return
2015-06-27 17:52:01 -07:00
case <-timeout.C:
Implement facility based logger, debugging via REST API This implements a new debug/trace infrastructure based on a slightly hacked up logger. Instead of the traditional "if debug { ... }" I've rewritten the logger to have no-op Debugln and Debugf, unless debugging has been enabled for a given "facility". The "facility" is just a string, typically a package name. This will be slightly slower than before; but not that much as it's mostly a function call that returns immediately. For the cases where it matters (the Debugln takes a hex.Dump() of something for example, and it's not in a very occasional "if err != nil" branch) there is an l.ShouldDebug(facility) that is fast enough to be used like the old "if debug". The point of all this is that we can now toggle debugging for the various packages on and off at runtime. There's a new method /rest/system/debug that can be POSTed a set of facilities to enable and disable debug for, or GET from to get a list of facilities with descriptions and their current debug status. Similarly a /rest/system/log?since=... can grab the latest log entries, up to 250 of them (hardcoded constant in main.go) plus the initial few. Not implemented in this commit (but planned) is a simple debug GUI available on /debug that shows the current log in an easily pasteable format and has checkboxes to enable the various debug facilities. The debug instructions to a user then becomes "visit this URL, check these boxes, reproduce your problem, copy and paste the log". The actual log viewer on the hypothetical /debug URL can poll regularly for new log entries and this bypass the 250 line limit. The existing STTRACE=foo variable is still obeyed and just sets the start state of the system.
2015-10-03 08:25:21 -07:00
l.Debugln(c, "timed out")
2015-06-27 17:52:01 -07:00
return
}
}
}
func (c *ProtocolClient) Stop() {
if c.stop == nil {
return
}
2015-07-20 02:56:10 -07:00
close(c.stop)
2015-06-27 17:52:01 -07:00
<-c.stopped
}
2015-07-22 14:34:05 -07:00
func (c *ProtocolClient) StatusOK() bool {
c.mut.RLock()
con := c.connected
c.mut.RUnlock()
return con
}
func (c *ProtocolClient) Latency() time.Duration {
c.mut.RLock()
lat := c.latency
c.mut.RUnlock()
return lat
}
2015-06-27 17:52:01 -07:00
func (c *ProtocolClient) String() string {
return fmt.Sprintf("ProtocolClient@%p", c)
}
2015-07-20 02:56:10 -07:00
func (c *ProtocolClient) connect() error {
if c.URI.Scheme != "relay" {
2015-09-22 11:34:24 -07:00
return fmt.Errorf("Unsupported relay schema: %v", c.URI.Scheme)
2015-07-20 02:56:10 -07:00
}
t0 := time.Now()
2015-10-12 11:30:14 -07:00
tcpConn, err := dialer.Dial("tcp", c.URI.Host)
2015-07-20 02:56:10 -07:00
if err != nil {
return err
}
c.mut.Lock()
c.latency = time.Since(t0)
c.mut.Unlock()
conn := tls.Client(tcpConn, c.config)
if err = conn.Handshake(); err != nil {
return err
}
2015-07-20 02:56:10 -07:00
if err := conn.SetDeadline(time.Now().Add(10 * time.Second)); err != nil {
conn.Close()
return err
}
if err := performHandshakeAndValidation(conn, c.URI); err != nil {
conn.Close()
return err
}
c.conn = conn
return nil
}
2015-06-27 17:52:01 -07:00
func (c *ProtocolClient) cleanup() {
if c.closeInvitationsOnFinish {
close(c.Invitations)
c.Invitations = make(chan protocol.SessionInvitation)
}
Implement facility based logger, debugging via REST API This implements a new debug/trace infrastructure based on a slightly hacked up logger. Instead of the traditional "if debug { ... }" I've rewritten the logger to have no-op Debugln and Debugf, unless debugging has been enabled for a given "facility". The "facility" is just a string, typically a package name. This will be slightly slower than before; but not that much as it's mostly a function call that returns immediately. For the cases where it matters (the Debugln takes a hex.Dump() of something for example, and it's not in a very occasional "if err != nil" branch) there is an l.ShouldDebug(facility) that is fast enough to be used like the old "if debug". The point of all this is that we can now toggle debugging for the various packages on and off at runtime. There's a new method /rest/system/debug that can be POSTed a set of facilities to enable and disable debug for, or GET from to get a list of facilities with descriptions and their current debug status. Similarly a /rest/system/log?since=... can grab the latest log entries, up to 250 of them (hardcoded constant in main.go) plus the initial few. Not implemented in this commit (but planned) is a simple debug GUI available on /debug that shows the current log in an easily pasteable format and has checkboxes to enable the various debug facilities. The debug instructions to a user then becomes "visit this URL, check these boxes, reproduce your problem, copy and paste the log". The actual log viewer on the hypothetical /debug URL can poll regularly for new log entries and this bypass the 250 line limit. The existing STTRACE=foo variable is still obeyed and just sets the start state of the system.
2015-10-03 08:25:21 -07:00
l.Debugln(c, "cleaning up")
2015-06-27 17:52:01 -07:00
2015-07-22 14:34:05 -07:00
c.mut.Lock()
c.connected = false
c.mut.Unlock()
2015-07-20 02:56:10 -07:00
c.conn.Close()
2015-06-27 17:52:01 -07:00
}
func (c *ProtocolClient) join() error {
2015-07-20 02:56:10 -07:00
if err := protocol.WriteMessage(c.conn, protocol.JoinRelayRequest{}); err != nil {
2015-06-27 17:52:01 -07:00
return err
}
message, err := protocol.ReadMessage(c.conn)
if err != nil {
return err
}
switch msg := message.(type) {
case protocol.Response:
if msg.Code != 0 {
return fmt.Errorf("Incorrect response code %d: %s", msg.Code, msg.Message)
}
2015-07-20 02:56:10 -07:00
2015-06-27 17:52:01 -07:00
default:
return fmt.Errorf("protocol error: expecting response got %v", msg)
}
return nil
}
func performHandshakeAndValidation(conn *tls.Conn, uri *url.URL) error {
2015-07-20 02:56:10 -07:00
if err := conn.Handshake(); err != nil {
2015-06-27 17:52:01 -07:00
return err
}
cs := conn.ConnectionState()
if !cs.NegotiatedProtocolIsMutual || cs.NegotiatedProtocol != protocol.ProtocolName {
return fmt.Errorf("protocol negotiation error")
}
q := uri.Query()
relayIDs := q.Get("id")
if relayIDs != "" {
relayID, err := syncthingprotocol.DeviceIDFromString(relayIDs)
if err != nil {
return fmt.Errorf("relay address contains invalid verification id: %s", err)
}
certs := cs.PeerCertificates
if cl := len(certs); cl != 1 {
return fmt.Errorf("unexpected certificate count: %d", cl)
}
remoteID := syncthingprotocol.NewDeviceID(certs[0].Raw)
if remoteID != relayID {
return fmt.Errorf("relay id does not match. Expected %v got %v", relayID, remoteID)
}
}
return nil
}
2015-07-20 02:56:10 -07:00
func messageReader(conn net.Conn, messages chan<- interface{}, errors chan<- error) {
for {
msg, err := protocol.ReadMessage(conn)
if err != nil {
errors <- err
return
}
messages <- msg
}
}