fix(direct): guard nil dialer and nil logger in Connect, add doc comments
Add nil checks for connect-options dialer and logger to prevent nil-pointer panics when Connect is called without a DialerConnectOption or LoggerOption. Add package and NewConnector godoc comments. Add 10 unit tests covering construction, Init metadata parsing, Connect success/reject/dial-error paths, nil dialer, nil logger, and the reject conn stub.
This commit is contained in:
@@ -1,7 +1,12 @@
|
||||
// Package direct implements a direct (transparent) connector that establishes
|
||||
// connections to destination addresses using the dialer provided via connect
|
||||
// options. It also supports a "reject" action that returns a dead connection
|
||||
// (reads return io.EOF, writes return io.ErrClosedPipe) without dialing.
|
||||
package direct
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
|
||||
"github.com/go-gost/core/connector"
|
||||
@@ -20,6 +25,7 @@ type directConnector struct {
|
||||
options connector.Options
|
||||
}
|
||||
|
||||
// NewConnector creates a direct connector with the given options.
|
||||
func NewConnector(opts ...connector.Option) connector.Connector {
|
||||
options := connector.Options{}
|
||||
for _, opt := range opts {
|
||||
@@ -45,27 +51,33 @@ func (c *directConnector) Connect(ctx context.Context, _ net.Conn, network, addr
|
||||
return &conn{}, nil
|
||||
}
|
||||
|
||||
if cOpts.Dialer == nil {
|
||||
return nil, errors.New("direct: missing dialer in connect options")
|
||||
}
|
||||
|
||||
conn, err := cOpts.Dialer.Dial(ctx, network, address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var localAddr, remoteAddr string
|
||||
if addr := conn.LocalAddr(); addr != nil {
|
||||
localAddr = addr.String()
|
||||
}
|
||||
if addr := conn.RemoteAddr(); addr != nil {
|
||||
remoteAddr = addr.String()
|
||||
}
|
||||
if c.options.Logger != nil {
|
||||
var localAddr, remoteAddr string
|
||||
if addr := conn.LocalAddr(); addr != nil {
|
||||
localAddr = addr.String()
|
||||
}
|
||||
if addr := conn.RemoteAddr(); addr != nil {
|
||||
remoteAddr = addr.String()
|
||||
}
|
||||
|
||||
log := c.options.Logger.WithFields(map[string]any{
|
||||
"remote": remoteAddr,
|
||||
"local": localAddr,
|
||||
"network": network,
|
||||
"address": address,
|
||||
"sid": string(ctxvalue.SidFromContext(ctx)),
|
||||
})
|
||||
log.Debugf("connect %s/%s", address, network)
|
||||
log := c.options.Logger.WithFields(map[string]any{
|
||||
"remote": remoteAddr,
|
||||
"local": localAddr,
|
||||
"network": network,
|
||||
"address": address,
|
||||
"sid": string(ctxvalue.SidFromContext(ctx)),
|
||||
})
|
||||
log.Debugf("connect %s/%s", address, network)
|
||||
}
|
||||
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user