Files
Asher b634fa62ee feat: flush logs on unexpected connection end (#32163)
This will flush the debug logs from tailscale which can help debug why
the connection ended unexpectedly.
2026-11-23 02:00:33 -07:00

209 lines
5.8 KiB
Go

package agentssh
import (
"context"
"io"
"net"
"strconv"
"strings"
"sync"
"github.com/gliderlabs/ssh"
"github.com/google/uuid"
"go.uber.org/atomic"
gossh "golang.org/x/crypto/ssh"
"cdr.dev/slog/v3"
"github.com/coder/coder/v2/agent/proto"
"github.com/coder/coder/v2/codersdk"
)
// localForwardChannelData is copied from the ssh package.
type localForwardChannelData struct {
DestAddr string
DestPort uint32
OriginAddr string
OriginPort uint32
}
// JetbrainsChannelWatcher is used to track JetBrains port forwarded (Gateway)
// channels. If the port forward is something other than JetBrains, this struct
// is a noop.
//
// Sessions are counted here, not in sessionHandler: JetBrains opens hundreds
// of ssh sessions but only one persistent forwarded channel.
type JetbrainsChannelWatcher struct {
gossh.NewChannel
startSession startSessionFunc
logger slog.Logger
originAddr string
clientSessionID string
connectionReporter proto.ConnectionReporter
isClosing func() bool
trackChannel func(add bool) bool
}
func NewJetbrainsChannelWatcher(ctx ssh.Context, logger slog.Logger,
connectionReporter proto.ConnectionReporter,
newChannel gossh.NewChannel, startSession startSessionFunc,
isClosing func() bool, trackChannel func(add bool) bool,
clientSessionID string,
) gossh.NewChannel {
logger = logger.With(slog.F("client_session_id", clientSessionID))
d := localForwardChannelData{}
if err := gossh.Unmarshal(newChannel.ExtraData(), &d); err != nil {
// If the data fails to unmarshal, do nothing.
logger.Warn(ctx, "failed to unmarshal port forward data", slog.Error(err))
return newChannel
}
// If we do get a port, we should be able to get the matching PID and from
// there look up the invocation.
cmdline, err := getListeningPortProcessCmdline(d.DestPort)
if err != nil {
logger.Warn(ctx, "failed to inspect port",
slog.F("destination_port", d.DestPort),
slog.Error(err))
return newChannel
}
// If this is not JetBrains, then we do not need to do anything special. We
// attempt to match on something that appears unique to JetBrains software.
if !isJetbrainsProcess(cmdline) {
return newChannel
}
logger.Debug(ctx, "discovered forwarded JetBrains process",
slog.F("destination_port", d.DestPort))
return &JetbrainsChannelWatcher{
NewChannel: newChannel,
startSession: startSession,
logger: logger.With(slog.F("destination_port", d.DestPort)),
originAddr: net.JoinHostPort(d.OriginAddr, strconv.FormatUint(uint64(d.OriginPort), 10)),
connectionReporter: connectionReporter,
clientSessionID: clientSessionID,
isClosing: isClosing,
trackChannel: trackChannel,
}
}
func (w *JetbrainsChannelWatcher) Accept() (gossh.Channel, <-chan *gossh.Request, error) {
connReporter := w.connectionReporter.Connect(proto.ConnectEvent{
ID: uuid.New(),
Method: proto.Connection_METHOD_SSH,
AppName: string(codersdk.AppFamilyJetBrains),
IP: w.originAddr,
ClientSessionID: w.clientSessionID,
})
c, r, err := w.NewChannel.Accept()
if err != nil {
connReporter.Disconnect(proto.DisconnectEvent{
Code: 1,
Reason: err.Error(),
RxBytes: 0,
TxBytes: 0,
})
return c, r, err
}
endSession := w.startSession(string(codersdk.AppFamilyJetBrains))
// The channel handler outlives its connection's tracking, so register the
// channel until its close is reported with the server's shutdown state.
tracked := w.trackChannel(true)
// nolint: gocritic // JetBrains is a proper noun and should be capitalized
w.logger.Debug(context.Background(), "JetBrains watcher accepted channel")
return &ChannelTracker{
Channel: c,
done: func(rxbytes, txbytes int64) {
if tracked {
defer w.trackChannel(false)
}
endSession()
reason := codersdk.DisconnectReasonGraceful
fields := []slog.Field{codersdk.ConnectionDirectionAgentToClient.SlogField()}
if w.isClosing() {
reason = codersdk.DisconnectReasonServerShutdown
fields = append(fields, serverShutdownFields()...)
} else {
fields = append(fields, reason.SlogField(), reason.SlogExpectedField())
}
if !reason.Expected() {
w.logger.Flush(context.Background())
}
//nolint: gocritic // JetBrains is a proper noun and should be capitalized
w.logger.Info(context.Background(), "JetBrains channel closed",
fields...,
)
connReporter.Disconnect(proto.DisconnectEvent{
Code: 0,
Reason: string(reason),
RxBytes: rxbytes,
TxBytes: txbytes,
})
},
}, r, err
}
// ChannelTracker is a wrapper around gossh.Channel that tracks the number of
// bytes transferred and calls done() with the byte counts when when the
// connection is closed.
type ChannelTracker struct {
gossh.Channel
// once ensures close only decrements the counter once.
// Because close can be called multiple times.
once sync.Once
done func(int64, int64)
rxBytes atomic.Int64
txBytes atomic.Int64
}
func (c *ChannelTracker) Close() error {
c.once.Do(func() {
c.done(c.rxBytes.Load(), c.txBytes.Load())
})
return c.Channel.Close()
}
func (c *ChannelTracker) Read(p []byte) (int, error) {
n, err := c.Channel.Read(p)
if n > 0 {
c.rxBytes.Add(int64(n))
}
return n, err
}
func (c *ChannelTracker) Write(p []byte) (int, error) {
n, err := c.Channel.Write(p)
if n > 0 {
c.txBytes.Add(int64(n))
}
return n, err
}
func (c *ChannelTracker) Stderr() io.ReadWriter {
return &readWriterTracker{
ReadWriter: c.Channel.Stderr(),
rxBytes: &c.rxBytes,
txBytes: &c.txBytes,
}
}
func isJetbrainsProcess(cmdline string) bool {
opts := []string{
MagicProcessCmdlineJetBrains,
MagicProcessCmdlineToolbox,
MagicProcessCmdlineGateway,
}
for _, opt := range opts {
if strings.Contains(strings.ToLower(cmdline), strings.ToLower(opt)) {
return true
}
}
return false
}