Files
syncthing/lib/relay/client/static.go
Jakob Borg 836045ee87 feat: switch logging framework (#10220)
This updates our logging framework from legacy freetext strings using
the `log` package to structured log entries using `log/slog`. I have
updated all INFO or higher level entries, but not yet DEBUG (😓)... So,
at a high level:

There is a slight change in log levels, effectively adding a new warning
level:

- DEBUG is still debug (ideally not for users but developers, though
this is something we need to work on)
- INFO is still info, though I've added more data here, effectively
making Syncthing more verbose by default (more on this below)
- WARNING is a new log level that is different from the _old_ WARNING
(more below)
- ERROR is what was WARNING before -- problems that must be dealt with,
and also bubbled as a popup in the GUI.

A new feature is that the logging level can be set per package to
something other than just debug or info, and hence I feel that we can
add a bit more things into INFO while moving some (in fact, most)
current INFO level warnings into WARNING. For example, I think it's
justified to get a log of synced files in INFO and sync failures in
WARNING. These are things that have historically been tricky to debug
properly, and having more information by default will be useful to many,
while still making it possible get close to told level of inscrutability
by setting the log level to WARNING. I'd like to get to a stage where
DEBUG is never necessary to just figure out what's going on, as opposed
to trying to narrow down a likely bug.

Code wise:

- Our logging object, generally known as `l` in each package, is now a
new adapter object that provides the old API on top of the newer one.
(This should go away once all old log entries are migrated.) This is
only for `l.Debugln` and `l.Debugf`.
- There is a new level tracker that keeps the log level for each
package.
- There is a nested setup of handlers, since the structure mandated by
`log/slog` is slightly convoluted (imho). We do this because we need to
do formatting at a "medium" level internally so we can buffer log lines
in text format but with separate timestamp and log level for the API/GUI
to consume.
- The `debug` API call becomes a `loglevels` API call, which can set the
log level to `DEBUG`, `INFO`, `WARNING` or `ERROR` per package. The GUI
is updated to handle this.
- Our custom `sync` package provided some debugging of mutexes quite
strongly integrated into the old logging framework, only turned on when
`STTRACE` was set to certain values at startup, etc. It's been a long
time since this has been useful; I removed it.
- The `STTRACE` env var remains and can be used the same way as before,
while additionally permitting specific log levels to be specified,
`STTRACE=model:WARN,scanner:DEBUG`.
- There is a new command line option `--log-level=INFO` to set the
default log level.
- The command line options `--log-flags` and `--verbose` go away, but
are currently retained as hidden & ignored options since we set them by
default in some of our startup examples and Syncthing would otherwise
fail to start.

Sample format messages:

```
2009-02-13 23:31:30 INF A basic info line (attr1="val with spaces" attr2=2 attr3="val\"quote" a=a log.pkg=slogutil)
2009-02-13 23:31:30 INF An info line with grouped values (attr1=val1 foo.attr2=2 foo.bar.attr3=3 a=a log.pkg=slogutil)
2009-02-13 23:31:30 INF An info line with grouped values via logger (foo.attr1=val1 foo.attr2=2 a=a log.pkg=slogutil)
2009-02-13 23:31:30 INF An info line with nested grouped values via logger (bar.foo.attr1=val1 bar.foo.attr2=2 a=a log.pkg=slogutil)
2009-02-13 23:31:30 WRN A warning entry (a=a log.pkg=slogutil)
2009-02-13 23:31:30 ERR An error (a=a log.pkg=slogutil)
```

---------

Co-authored-by: Ross Smith II <ross@smithii.com>
2025-08-07 11:19:36 +02:00

252 lines
5.7 KiB
Go

// Copyright (C) 2015 Audrius Butkevicius and Contributors (see the CONTRIBUTORS file).
package client
import (
"context"
"crypto/tls"
"errors"
"fmt"
"log/slog"
"net"
"net/url"
"time"
"github.com/syncthing/syncthing/internal/slogutil"
"github.com/syncthing/syncthing/lib/dialer"
"github.com/syncthing/syncthing/lib/osutil"
syncthingprotocol "github.com/syncthing/syncthing/lib/protocol"
"github.com/syncthing/syncthing/lib/relay/protocol"
)
type staticClient struct {
commonClient
uri *url.URL
config *tls.Config
messageTimeout time.Duration
connectTimeout time.Duration
conn *tls.Conn
token string
}
func newStaticClient(uri *url.URL, certs []tls.Certificate, invitations chan protocol.SessionInvitation, timeout time.Duration) *staticClient {
c := &staticClient{
uri: uri,
config: configForCerts(certs),
messageTimeout: time.Minute * 2,
connectTimeout: timeout,
token: uri.Query().Get("token"),
}
c.commonClient = newCommonClient(invitations, c.serve, c.String())
return c
}
func (c *staticClient) serve(ctx context.Context) error {
if err := c.connect(ctx); err != nil {
l.Debugf("Could not connect to relay %s: %s", c.uri, err)
return err
}
l.Debugln(c, "connected", c.conn.RemoteAddr())
defer c.disconnect()
if err := c.join(); err != nil {
l.Debugf("Could not join relay %s: %s", c.uri, err)
return err
}
if err := c.conn.SetDeadline(time.Time{}); err != nil {
l.Debugln("Relay set deadline:", err)
return err
}
slog.InfoContext(ctx, "Joined relay", slogutil.URI(fmt.Sprintf("%s://%s", c.uri.Scheme, c.uri.Host)))
messages := make(chan interface{})
errorsc := make(chan error, 1)
go messageReader(ctx, c.conn, messages, errorsc)
timeout := time.NewTimer(c.messageTimeout)
for {
select {
case message := <-messages:
timeout.Reset(c.messageTimeout)
l.Debugf("%s received message %T", c, message)
switch msg := message.(type) {
case protocol.Ping:
if err := protocol.WriteMessage(c.conn, protocol.Pong{}); err != nil {
l.Debugln("Relay write:", err)
return err
}
l.Debugln(c, "sent pong")
case protocol.SessionInvitation:
ip := net.IP(msg.Address)
if len(ip) == 0 || ip.IsUnspecified() {
msg.Address, _ = osutil.IPFromAddr(c.conn.RemoteAddr())
}
select {
case c.invitations <- msg:
case <-ctx.Done():
l.Debugln(c, "stopping")
return ctx.Err()
}
case protocol.RelayFull:
l.Debugf("Disconnected from relay %s due to it becoming full.", c.uri)
return errors.New("relay full")
default:
l.Debugf("Relay: protocol error: unexpected message %v", msg)
return fmt.Errorf("protocol error: unexpected message %v", msg)
}
case <-ctx.Done():
l.Debugln(c, "stopping")
return ctx.Err()
case err := <-errorsc:
l.Debugf("Disconnecting from relay %s due to error: %s", c.uri, err)
return err
case <-timeout.C:
l.Debugln(c, "timed out")
return errors.New("timed out")
}
}
}
func (c *staticClient) String() string {
return fmt.Sprintf("StaticClient:%p@%s", c, c.URI())
}
func (c *staticClient) URI() *url.URL {
return c.uri
}
func (c *staticClient) connect(ctx context.Context) error {
if c.uri.Scheme != "relay" {
return fmt.Errorf("unsupported relay scheme: %v", c.uri.Scheme)
}
timeoutCtx, cancel := context.WithTimeout(ctx, c.connectTimeout)
defer cancel()
tcpConn, err := dialer.DialContext(timeoutCtx, "tcp", c.uri.Host)
if err != nil {
return err
}
// Copy the TLS config and set the server name we're connecting to. In
// many cases this will be an IP address, in which case it's a no-op. In
// other cases it will be a hostname, which will cause the TLS stack to
// send SNI.
cfg := c.config
if host, _, err := net.SplitHostPort(c.uri.Host); err == nil {
cfg = cfg.Clone()
cfg.ServerName = host
}
conn := tls.Client(tcpConn, cfg)
if err := conn.SetDeadline(time.Now().Add(c.connectTimeout)); err != nil {
conn.Close()
return err
}
if err := performHandshakeAndValidation(conn, c.uri); err != nil {
conn.Close()
return err
}
c.conn = conn
return nil
}
func (c *staticClient) disconnect() {
l.Debugln(c, "disconnecting")
c.conn.Close()
}
func (c *staticClient) join() error {
if err := protocol.WriteMessage(c.conn, protocol.JoinRelayRequest{Token: c.token}); err != nil {
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 &incorrectResponseCodeErr{msg.Code, msg.Message}
}
case protocol.RelayFull:
return errors.New("relay full")
default:
return fmt.Errorf("protocol error: expecting response got %v", msg)
}
return nil
}
func performHandshakeAndValidation(conn *tls.Conn, uri *url.URL) error {
if err := conn.Handshake(); err != nil {
return err
}
cs := conn.ConnectionState()
if cs.NegotiatedProtocol != protocol.ProtocolName {
return errors.New("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: %w", 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
}
func messageReader(ctx context.Context, conn net.Conn, messages chan<- interface{}, errors chan<- error) {
for {
msg, err := protocol.ReadMessage(conn)
if err != nil {
errors <- err
return
}
select {
case messages <- msg:
case <-ctx.Done():
return
}
}
}