1 Star 0 Fork 0

朽木木/gost-x

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
connector.go 2.60 KB
一键复制 编辑 原始数据 按行查看 历史
hao_shen 提交于 2025-03-25 16:26 +08:00 . 2
package tunnel
import (
"context"
"fmt"
"net"
"time"
"gitee.com/hao_shen/gost-core/connector"
md "gitee.com/hao_shen/gost-core/metadata"
ctxvalue "gitee.com/hao_shen/gost-x/ctx"
"gitee.com/hao_shen/gost-x/registry"
"github.com/go-gost/relay"
)
func init() {
registry.ConnectorRegistry().Register("router", NewConnector)
}
type routerConnector struct {
md metadata
options connector.Options
}
func NewConnector(opts ...connector.Option) connector.Connector {
options := connector.Options{}
for _, opt := range opts {
opt(&options)
}
return &routerConnector{
options: options,
}
}
func (c *routerConnector) Init(md md.Metadata) (err error) {
return c.parseMetadata(md)
}
func (c *routerConnector) Connect(ctx context.Context, conn net.Conn, network, address string, opts ...connector.ConnectOption) (net.Conn, error) {
log := c.options.Logger.WithFields(map[string]any{
"remote": conn.RemoteAddr().String(),
"local": conn.LocalAddr().String(),
"network": network,
"address": address,
"sid": string(ctxvalue.SidFromContext(ctx)),
})
log.Debugf("connect %s/%s", address, network)
if c.md.connectTimeout > 0 {
conn.SetDeadline(time.Now().Add(c.md.connectTimeout))
defer conn.SetDeadline(time.Time{})
}
req := relay.Request{
Version: relay.Version1,
Cmd: relay.CmdAssociate,
}
if c.options.Auth != nil {
pwd, _ := c.options.Auth.Password()
req.Features = append(req.Features, &relay.UserAuthFeature{
Username: c.options.Auth.Username(),
Password: pwd,
})
}
switch network {
case "udp":
req.Features = append(req.Features, &relay.NetworkFeature{
Network: relay.NetworkUDP,
})
case "ip":
req.Features = append(req.Features, &relay.NetworkFeature{
Network: relay.NetworkIP,
})
}
srcAddr := conn.LocalAddr().String()
if v := ctxvalue.ClientAddrFromContext(ctx); v != "" {
srcAddr = string(v)
}
af := &relay.AddrFeature{}
af.ParseFrom(srcAddr)
req.Features = append(req.Features, af) // src address
af = &relay.AddrFeature{}
af.ParseFrom(address)
req.Features = append(req.Features, af) // dst address
if !c.md.routerID.IsZero() {
req.Features = append(req.Features, &relay.TunnelFeature{
ID: c.md.routerID,
})
}
if _, err := req.WriteTo(conn); err != nil {
return nil, err
}
// drain the response
if err := readResponse(conn); err != nil {
return nil, err
}
switch network {
case "udp", "ip":
conn = &packetConn{
Conn: conn,
}
default:
err := fmt.Errorf("network %s is unsupported", network)
log.Error(err)
return nil, err
}
log.Debugf("connect to router %s@%s OK", address, c.md.routerID)
return conn, nil
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/hao_shen/gost-x.git
git@gitee.com:hao_shen/gost-x.git
hao_shen
gost-x
gost-x
v1.1.1

搜索帮助