Compare commits
23 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 490e6b40f5 | |||
| bc0d6953bc | |||
| 22e522e933 | |||
| 5e8a8a4b4d | |||
| fa16373d66 | |||
| 1a776dc759 | |||
| 12ef82e41f | |||
| 3656ba9315 | |||
| f73960ad36 | |||
| c0a80400d2 | |||
| 3c1985e980 | |||
| 423dd1e35d | |||
| 63ad7f2354 | |||
| 5cc2c3de82 | |||
| bb1a9908d4 | |||
| 4e1a70ec6d | |||
| 590a6ae6ff | |||
| 116c7b51fe | |||
| 42a4ccb24c | |||
| 34b9e3b16e | |||
| 3038eb66d8 | |||
| 52aa2027d0 | |||
| 6108000cce |
+1
-1
@@ -78,7 +78,7 @@ func (*defaultRoute) Bind(ctx context.Context, network, address string, opts ...
|
||||
ReadQueueSize: options.UDPDataQueueSize,
|
||||
ReadBufferSize: options.UDPDataBufferSize,
|
||||
TTL: options.UDPConnTTL,
|
||||
KeepAlive: true,
|
||||
Keepalive: true,
|
||||
Logger: logger,
|
||||
})
|
||||
return ln, err
|
||||
|
||||
+14
-12
@@ -42,12 +42,6 @@ func (r *Router) Options() *chain.RouterOptions {
|
||||
}
|
||||
|
||||
func (r *Router) Dial(ctx context.Context, network, address string) (conn net.Conn, err error) {
|
||||
if r.options.Timeout > 0 {
|
||||
var cancel context.CancelFunc
|
||||
ctx, cancel = context.WithTimeout(ctx, r.options.Timeout)
|
||||
defer cancel()
|
||||
}
|
||||
|
||||
host := address
|
||||
if h, _, _ := net.SplitHostPort(address); h != "" {
|
||||
host = h
|
||||
@@ -93,6 +87,13 @@ func (r *Router) dial(ctx context.Context, network, address string) (conn net.Co
|
||||
r.options.Logger.Debugf("dial %s/%s", address, network)
|
||||
|
||||
for i := 0; i < count; i++ {
|
||||
ctx := ctx
|
||||
if r.options.Timeout > 0 {
|
||||
var cancel context.CancelFunc
|
||||
ctx, cancel = context.WithTimeout(ctx, r.options.Timeout)
|
||||
defer cancel()
|
||||
}
|
||||
|
||||
var ipAddr string
|
||||
ipAddr, err = xnet.Resolve(ctx, "ip", address, r.options.Resolver, r.options.HostMapper, r.options.Logger)
|
||||
if err != nil {
|
||||
@@ -133,12 +134,6 @@ func (r *Router) dial(ctx context.Context, network, address string) (conn net.Co
|
||||
}
|
||||
|
||||
func (r *Router) Bind(ctx context.Context, network, address string, opts ...chain.BindOption) (ln net.Listener, err error) {
|
||||
if r.options.Timeout > 0 {
|
||||
var cancel context.CancelFunc
|
||||
ctx, cancel = context.WithTimeout(ctx, r.options.Timeout)
|
||||
defer cancel()
|
||||
}
|
||||
|
||||
count := r.options.Retries + 1
|
||||
if count <= 0 {
|
||||
count = 1
|
||||
@@ -146,6 +141,13 @@ func (r *Router) Bind(ctx context.Context, network, address string, opts ...chai
|
||||
r.options.Logger.Debugf("bind on %s/%s", address, network)
|
||||
|
||||
for i := 0; i < count; i++ {
|
||||
ctx := ctx
|
||||
if r.options.Timeout > 0 {
|
||||
var cancel context.CancelFunc
|
||||
ctx, cancel = context.WithTimeout(ctx, r.options.Timeout)
|
||||
defer cancel()
|
||||
}
|
||||
|
||||
var route chain.Route
|
||||
if r.options.Chain != nil {
|
||||
route = r.options.Chain.Route(ctx, network, address)
|
||||
|
||||
@@ -376,6 +376,13 @@ type HTTPURLRewriteConfig struct {
|
||||
Replacement string
|
||||
}
|
||||
|
||||
type HTTPBodyRewriteConfig struct {
|
||||
// filter by MIME types
|
||||
Type string
|
||||
Match string
|
||||
Replacement string
|
||||
}
|
||||
|
||||
type NodeFilterConfig struct {
|
||||
Host string `yaml:",omitempty" json:"host,omitempty"`
|
||||
Protocol string `yaml:",omitempty" json:"protocol,omitempty"`
|
||||
@@ -383,9 +390,15 @@ type NodeFilterConfig struct {
|
||||
}
|
||||
|
||||
type HTTPNodeConfig struct {
|
||||
// rewrite host header
|
||||
Host string `yaml:",omitempty" json:"host,omitempty"`
|
||||
// additional request header
|
||||
Header map[string]string `yaml:",omitempty" json:"header,omitempty"`
|
||||
// rewrite URL
|
||||
Rewrite []HTTPURLRewriteConfig `yaml:",omitempty" json:"rewrite,omitempty"`
|
||||
// rewrite response body
|
||||
RewriteBody []HTTPBodyRewriteConfig `yaml:"rewriteBody,omitempty" json:"rewriteBody,omitempty"`
|
||||
// HTTP basic auth
|
||||
Auth *AuthConfig `yaml:",omitempty" json:"auth,omitempty"`
|
||||
}
|
||||
|
||||
|
||||
@@ -193,12 +193,21 @@ func ParseNode(hop string, cfg *config.NodeConfig, log logger.Logger) (*chain.No
|
||||
}
|
||||
for _, v := range cfg.HTTP.Rewrite {
|
||||
if pattern, _ := regexp.Compile(v.Match); pattern != nil {
|
||||
settings.Rewrite = append(settings.Rewrite, chain.HTTPURLRewriteSetting{
|
||||
settings.RewriteURL = append(settings.RewriteURL, chain.HTTPURLRewriteSetting{
|
||||
Pattern: pattern,
|
||||
Replacement: v.Replacement,
|
||||
})
|
||||
}
|
||||
}
|
||||
for _, v := range cfg.HTTP.RewriteBody {
|
||||
if pattern, _ := regexp.Compile(v.Match); pattern != nil {
|
||||
settings.RewriteBody = append(settings.RewriteBody, chain.HTTPBodyRewriteSettings{
|
||||
Type: v.Type,
|
||||
Pattern: pattern,
|
||||
Replacement: []byte(v.Replacement),
|
||||
})
|
||||
}
|
||||
}
|
||||
opts = append(opts, chain.HTTPNodeOption(settings))
|
||||
}
|
||||
|
||||
|
||||
@@ -73,7 +73,7 @@ func (c *relayConnector) bindUDP(ctx context.Context, conn net.Conn, network, ad
|
||||
ReadQueueSize: opts.UDPDataQueueSize,
|
||||
ReadBufferSize: opts.UDPDataBufferSize,
|
||||
TTL: opts.UDPConnTTL,
|
||||
KeepAlive: true,
|
||||
Keepalive: true,
|
||||
Logger: log,
|
||||
})
|
||||
|
||||
|
||||
@@ -87,7 +87,7 @@ func (c *socks5Connector) bindUDP(ctx context.Context, conn net.Conn, network, a
|
||||
ReadQueueSize: opts.UDPDataQueueSize,
|
||||
ReadBufferSize: opts.UDPDataBufferSize,
|
||||
TTL: opts.UDPConnTTL,
|
||||
KeepAlive: true,
|
||||
Keepalive: true,
|
||||
Logger: log,
|
||||
})
|
||||
|
||||
|
||||
+20
-1
@@ -19,9 +19,11 @@ import (
|
||||
|
||||
func init() {
|
||||
registry.DialerRegistry().Register("icmp", NewDialer)
|
||||
registry.DialerRegistry().Register("icmp6", NewDialer6)
|
||||
}
|
||||
|
||||
type icmpDialer struct {
|
||||
ip6 bool
|
||||
sessions map[string]*quicSession
|
||||
sessionMutex sync.Mutex
|
||||
logger logger.Logger
|
||||
@@ -42,6 +44,19 @@ func NewDialer(opts ...dialer.Option) dialer.Dialer {
|
||||
}
|
||||
}
|
||||
|
||||
func NewDialer6(opts ...dialer.Option) dialer.Dialer {
|
||||
options := dialer.Options{}
|
||||
for _, opt := range opts {
|
||||
opt(&options)
|
||||
}
|
||||
|
||||
return &icmpDialer{
|
||||
ip6: true,
|
||||
sessions: make(map[string]*quicSession),
|
||||
logger: options.Logger,
|
||||
options: options,
|
||||
}
|
||||
}
|
||||
func (d *icmpDialer) Init(md md.Metadata) (err error) {
|
||||
if err = d.parseMetadata(md); err != nil {
|
||||
return
|
||||
@@ -71,7 +86,11 @@ func (d *icmpDialer) Dial(ctx context.Context, addr string, opts ...dialer.DialO
|
||||
}
|
||||
|
||||
var pc net.PacketConn
|
||||
if d.ip6 {
|
||||
pc, err = icmp.ListenPacket("ip6:ipv6-icmp", "")
|
||||
} else {
|
||||
pc, err = icmp.ListenPacket("ip4:icmp", "")
|
||||
}
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
@@ -81,7 +100,7 @@ func (d *icmpDialer) Dial(ctx context.Context, addr string, opts ...dialer.DialO
|
||||
id = rand.New(rand.NewSource(time.Now().UnixNano())).Intn(math.MaxUint16) + 1
|
||||
raddr.Port = id
|
||||
}
|
||||
pc = icmp_pkg.ClientConn(pc, id)
|
||||
pc = icmp_pkg.ClientConn(d.ip6, pc, id)
|
||||
|
||||
session, err = d.initSession(ctx, raddr, pc)
|
||||
if err != nil {
|
||||
|
||||
+4
-11
@@ -14,21 +14,14 @@ type metadata struct {
|
||||
}
|
||||
|
||||
func (d *icmpDialer) parseMetadata(md mdata.Metadata) (err error) {
|
||||
const (
|
||||
keepAlive = "keepAlive"
|
||||
keepAlivePeriod = "ttl"
|
||||
handshakeTimeout = "handshakeTimeout"
|
||||
maxIdleTimeout = "maxIdleTimeout"
|
||||
)
|
||||
|
||||
if mdutil.GetBool(md, keepAlive) {
|
||||
d.md.keepAlivePeriod = mdutil.GetDuration(md, keepAlivePeriod)
|
||||
if mdutil.GetBool(md, "keepalive") {
|
||||
d.md.keepAlivePeriod = mdutil.GetDuration(md, "ttl")
|
||||
if d.md.keepAlivePeriod <= 0 {
|
||||
d.md.keepAlivePeriod = 10 * time.Second
|
||||
}
|
||||
}
|
||||
d.md.handshakeTimeout = mdutil.GetDuration(md, handshakeTimeout)
|
||||
d.md.maxIdleTimeout = mdutil.GetDuration(md, maxIdleTimeout)
|
||||
d.md.handshakeTimeout = mdutil.GetDuration(md, "handshakeTimeout")
|
||||
d.md.maxIdleTimeout = mdutil.GetDuration(md, "maxIdleTimeout")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
+15
-2
@@ -2,8 +2,8 @@ package mtls
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
tls "github.com/refraction-networking/utls"
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -123,7 +123,20 @@ func (d *mtlsDialer) Handshake(ctx context.Context, conn net.Conn, options ...di
|
||||
}
|
||||
|
||||
func (d *mtlsDialer) initSession(ctx context.Context, conn net.Conn) (*muxSession, error) {
|
||||
tlsConn := tls.Client(conn, d.options.TLSConfig)
|
||||
tlsConfig := d.options.TLSConfig
|
||||
var utlsConf = &tls.Config{InsecureSkipVerify: tlsConfig.InsecureSkipVerify, ServerName: tlsConfig.ServerName, ClientAuth: tls.ClientAuthType(tlsConfig.ClientAuth), ClientCAs: tlsConfig.ClientCAs, RootCAs: tlsConfig.RootCAs}
|
||||
if len(tlsConfig.Certificates) > 0 {
|
||||
for _, certificate := range tlsConfig.Certificates {
|
||||
utlsConf.Certificates = append(utlsConf.Certificates, tls.Certificate{
|
||||
Certificate: certificate.Certificate,
|
||||
PrivateKey: certificate.PrivateKey,
|
||||
OCSPStaple: certificate.OCSPStaple,
|
||||
SignedCertificateTimestamps: certificate.SignedCertificateTimestamps,
|
||||
Leaf: certificate.Leaf,
|
||||
})
|
||||
}
|
||||
}
|
||||
tlsConn := tls.UClient(conn, utlsConf, tls.HelloChrome_Auto)
|
||||
if err := tlsConn.HandshakeContext(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -3,6 +3,8 @@ package mws
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/go-gost/x/util"
|
||||
tls "github.com/refraction-networking/utls"
|
||||
"net"
|
||||
"net/url"
|
||||
"sync"
|
||||
@@ -158,6 +160,33 @@ func (d *mwsDialer) initSession(ctx context.Context, host string, conn net.Conn,
|
||||
if d.tlsEnabled {
|
||||
url.Scheme = "wss"
|
||||
dialer.TLSClientConfig = d.options.TLSConfig
|
||||
tlsConfig := d.options.TLSConfig
|
||||
dialer.NetDialTLSContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
utlsConf := &tls.Config{InsecureSkipVerify: tlsConfig.InsecureSkipVerify, ServerName: tlsConfig.ServerName, ClientAuth: tls.ClientAuthType(tlsConfig.ClientAuth), ClientCAs: tlsConfig.ClientCAs, RootCAs: tlsConfig.RootCAs}
|
||||
if len(tlsConfig.Certificates) > 0 {
|
||||
for _, certificate := range tlsConfig.Certificates {
|
||||
utlsConf.Certificates = append(utlsConf.Certificates, tls.Certificate{
|
||||
Certificate: certificate.Certificate,
|
||||
PrivateKey: certificate.PrivateKey,
|
||||
OCSPStaple: certificate.OCSPStaple,
|
||||
SignedCertificateTimestamps: certificate.SignedCertificateTimestamps,
|
||||
Leaf: certificate.Leaf,
|
||||
})
|
||||
}
|
||||
}
|
||||
var client *tls.UConn
|
||||
if d.md.useH2 {
|
||||
client = tls.UClient(conn, utlsConf, tls.HelloChrome_Auto)
|
||||
} else {
|
||||
client = tls.UClient(conn, utlsConf, tls.HelloCustom)
|
||||
client.ApplyPreset(util.NewWsSpec())
|
||||
}
|
||||
err := client.Handshake()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return client, nil
|
||||
}
|
||||
}
|
||||
|
||||
if d.md.handshakeTimeout > 0 {
|
||||
|
||||
@@ -27,6 +27,9 @@ type metadata struct {
|
||||
header http.Header
|
||||
keepaliveInterval time.Duration
|
||||
muxCfg *mux.Config
|
||||
|
||||
//Evan Enhanced
|
||||
useH2 bool
|
||||
}
|
||||
|
||||
func (d *mwsDialer) parseMetadata(md mdata.Metadata) (err error) {
|
||||
@@ -67,5 +70,6 @@ func (d *mwsDialer) parseMetadata(md mdata.Metadata) (err error) {
|
||||
}
|
||||
}
|
||||
|
||||
d.md.useH2 = mdutil.GetBool(md, "h2")
|
||||
return
|
||||
}
|
||||
|
||||
+15
-3
@@ -2,7 +2,7 @@ package tls
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
tls "github.com/refraction-networking/utls"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
@@ -57,8 +57,20 @@ func (d *tlsDialer) Handshake(ctx context.Context, conn net.Conn, options ...dia
|
||||
conn.SetDeadline(time.Now().Add(d.md.handshakeTimeout))
|
||||
defer conn.SetDeadline(time.Time{})
|
||||
}
|
||||
|
||||
tlsConn := tls.Client(conn, d.options.TLSConfig)
|
||||
tlsConfig := d.options.TLSConfig
|
||||
utlsConf := &tls.Config{InsecureSkipVerify: tlsConfig.InsecureSkipVerify, ServerName: tlsConfig.ServerName, ClientAuth: tls.ClientAuthType(tlsConfig.ClientAuth), ClientCAs: tlsConfig.ClientCAs, RootCAs: tlsConfig.RootCAs}
|
||||
if len(tlsConfig.Certificates) > 0 {
|
||||
for _, certificate := range tlsConfig.Certificates {
|
||||
utlsConf.Certificates = append(utlsConf.Certificates, tls.Certificate{
|
||||
Certificate: certificate.Certificate,
|
||||
PrivateKey: certificate.PrivateKey,
|
||||
OCSPStaple: certificate.OCSPStaple,
|
||||
SignedCertificateTimestamps: certificate.SignedCertificateTimestamps,
|
||||
Leaf: certificate.Leaf,
|
||||
})
|
||||
}
|
||||
}
|
||||
tlsConn := tls.UClient(conn, utlsConf, tls.HelloChrome_Auto)
|
||||
if err := tlsConn.HandshakeContext(ctx); err != nil {
|
||||
conn.Close()
|
||||
return nil, err
|
||||
|
||||
+36
-4
@@ -2,6 +2,8 @@ package ws
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/go-gost/x/util"
|
||||
tls "github.com/refraction-networking/utls"
|
||||
"net"
|
||||
"net/url"
|
||||
"time"
|
||||
@@ -91,13 +93,43 @@ func (d *wsDialer) Handshake(ctx context.Context, conn net.Conn, options ...dial
|
||||
},
|
||||
}
|
||||
|
||||
url := url.URL{Scheme: "ws", Host: host, Path: d.md.path}
|
||||
urlObj := url.URL{Scheme: "ws", Host: host, Path: d.md.path}
|
||||
if d.tlsEnabled {
|
||||
url.Scheme = "wss"
|
||||
urlObj.Scheme = "wss"
|
||||
dialer.TLSClientConfig = d.options.TLSConfig
|
||||
tlsConfig := d.options.TLSConfig
|
||||
dialer.NetDialTLSContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
utlsConf := &tls.Config{InsecureSkipVerify: tlsConfig.InsecureSkipVerify, ServerName: tlsConfig.ServerName, ClientAuth: tls.ClientAuthType(tlsConfig.ClientAuth), ClientCAs: tlsConfig.ClientCAs, RootCAs: tlsConfig.RootCAs}
|
||||
if len(tlsConfig.Certificates) > 0 {
|
||||
for _, certificate := range tlsConfig.Certificates {
|
||||
utlsConf.Certificates = append(utlsConf.Certificates, tls.Certificate{
|
||||
Certificate: certificate.Certificate,
|
||||
PrivateKey: certificate.PrivateKey,
|
||||
OCSPStaple: certificate.OCSPStaple,
|
||||
SignedCertificateTimestamps: certificate.SignedCertificateTimestamps,
|
||||
Leaf: certificate.Leaf,
|
||||
})
|
||||
}
|
||||
|
||||
c, resp, err := dialer.DialContext(ctx, url.String(), d.md.header)
|
||||
}
|
||||
var client *tls.UConn
|
||||
if d.md.useH2 {
|
||||
client = tls.UClient(conn, utlsConf, tls.HelloChrome_Auto)
|
||||
} else {
|
||||
client = tls.UClient(conn, utlsConf, tls.HelloCustom)
|
||||
client.ApplyPreset(util.NewWsSpec())
|
||||
}
|
||||
err := client.Handshake()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return client, nil
|
||||
}
|
||||
}
|
||||
urlStr, errUnescape := url.QueryUnescape(urlObj.String())
|
||||
if errUnescape != nil {
|
||||
d.options.Logger.Debugf("[ws] URL QueryUnescape Error URL.String() -> %s", urlObj.String())
|
||||
}
|
||||
c, resp, err := dialer.DialContext(ctx, urlStr, d.md.header)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -25,6 +25,9 @@ type metadata struct {
|
||||
|
||||
header http.Header
|
||||
keepaliveInterval time.Duration
|
||||
|
||||
//Evan Enhance
|
||||
useH2 bool
|
||||
}
|
||||
|
||||
func (d *wsDialer) parseMetadata(md mdata.Metadata) (err error) {
|
||||
@@ -56,5 +59,6 @@ func (d *wsDialer) parseMetadata(md mdata.Metadata) (err error) {
|
||||
}
|
||||
}
|
||||
|
||||
d.md.useH2 = mdutil.GetBool(md, "h2")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ require (
|
||||
github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d
|
||||
github.com/gin-contrib/cors v1.6.0
|
||||
github.com/gin-gonic/gin v1.9.1
|
||||
github.com/go-gost/core v0.1.0
|
||||
github.com/go-gost/core v0.1.1
|
||||
github.com/go-gost/gosocks4 v0.0.1
|
||||
github.com/go-gost/gosocks5 v0.4.2
|
||||
github.com/go-gost/plugin v0.0.0-20240103125338-9c84e29cb81a
|
||||
|
||||
@@ -53,8 +53,8 @@ github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE
|
||||
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
|
||||
github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg=
|
||||
github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU=
|
||||
github.com/go-gost/core v0.1.0 h1:LJJc8PIlRflE8ZIpxls+wYX1e8OGB0nUKJYh8HevM4U=
|
||||
github.com/go-gost/core v0.1.0/go.mod h1:WGI43jOka7FAsSAwi/fSMaqxdR+E339ycb4NBGlFr6A=
|
||||
github.com/go-gost/core v0.1.1 h1:8joR9KJYBvpurNu3i0zqN9orQthVzOjhtT4STumwNF0=
|
||||
github.com/go-gost/core v0.1.1/go.mod h1:WGI43jOka7FAsSAwi/fSMaqxdR+E339ycb4NBGlFr6A=
|
||||
github.com/go-gost/gosocks4 v0.0.1 h1:+k1sec8HlELuQV7rWftIkmy8UijzUt2I6t+iMPlGB2s=
|
||||
github.com/go-gost/gosocks4 v0.0.1/go.mod h1:3B6L47HbU/qugDg4JnoFPHgJXE43Inz8Bah1QaN9qCc=
|
||||
github.com/go-gost/gosocks5 v0.4.2 h1:IianxHTkACPqCwiOAT3MHoMdSUl+SEPSRu1ikawC1Pc=
|
||||
|
||||
@@ -2,6 +2,7 @@ package local
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
@@ -105,7 +106,7 @@ func (h *forwardHandler) Handle(ctx context.Context, conn net.Conn, opts ...hand
|
||||
}
|
||||
|
||||
if protocol == forward.ProtoHTTP {
|
||||
h.handleHTTP(ctx, rw, conn.RemoteAddr(), log)
|
||||
h.handleHTTP(ctx, xio.NewReadWriteCloser(rw, rw, conn), conn.RemoteAddr(), log)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -176,11 +177,12 @@ func (h *forwardHandler) Handle(ctx context.Context, conn net.Conn, opts ...hand
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *forwardHandler) handleHTTP(ctx context.Context, rw io.ReadWriter, remoteAddr net.Addr, log logger.Logger) (err error) {
|
||||
func (h *forwardHandler) handleHTTP(ctx context.Context, rw io.ReadWriteCloser, remoteAddr net.Addr, log logger.Logger) (err error) {
|
||||
br := bufio.NewReader(rw)
|
||||
|
||||
var cc net.Conn
|
||||
for {
|
||||
var cc net.Conn
|
||||
|
||||
resp := &http.Response{
|
||||
ProtoMajor: 1,
|
||||
ProtoMinor: 1,
|
||||
@@ -241,6 +243,7 @@ func (h *forwardHandler) handleHTTP(ctx context.Context, rw io.ReadWriter, remot
|
||||
})
|
||||
log.Debugf("find node for host %s -> %s(%s)", req.Host, target.Name, target.Addr)
|
||||
|
||||
var bodyRewrites []chain.HTTPBodyRewriteSettings
|
||||
if httpSettings := target.Options().HTTP; httpSettings != nil {
|
||||
if auther := httpSettings.Auther; auther != nil {
|
||||
username, password, _ := req.BasicAuth()
|
||||
@@ -261,7 +264,7 @@ func (h *forwardHandler) handleHTTP(ctx context.Context, rw io.ReadWriter, remot
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
|
||||
for _, re := range httpSettings.Rewrite {
|
||||
for _, re := range httpSettings.RewriteURL {
|
||||
if re.Pattern.MatchString(req.URL.Path) {
|
||||
if s := re.Pattern.ReplaceAllString(req.URL.Path, re.Replacement); s != "" {
|
||||
req.URL.Path = s
|
||||
@@ -269,6 +272,8 @@ func (h *forwardHandler) handleHTTP(ctx context.Context, rw io.ReadWriter, remot
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bodyRewrites = httpSettings.RewriteBody
|
||||
}
|
||||
|
||||
cc, err = h.options.Router.Dial(ctx, "tcp", target.Addr)
|
||||
@@ -329,7 +334,18 @@ func (h *forwardHandler) handleHTTP(ctx context.Context, rw io.ReadWriter, remot
|
||||
log.Trace(string(dump))
|
||||
}
|
||||
|
||||
if res.Close {
|
||||
defer rw.Close()
|
||||
}
|
||||
|
||||
if err := h.rewriteBody(res, bodyRewrites...); err != nil {
|
||||
rw.Close()
|
||||
log.Errorf("rewrite body: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
if err = res.Write(rw); err != nil {
|
||||
rw.Close()
|
||||
log.Errorf("write response from node %s(%s): %v", target.Name, target.Addr, err)
|
||||
}
|
||||
}()
|
||||
@@ -348,6 +364,54 @@ func (h *forwardHandler) handleHTTP(ctx context.Context, rw io.ReadWriter, remot
|
||||
return
|
||||
}
|
||||
|
||||
func (h *forwardHandler) rewriteBody(resp *http.Response, rewrites ...chain.HTTPBodyRewriteSettings) error {
|
||||
if resp == nil || len(rewrites) == 0 || resp.ContentLength <= 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
if encoding := resp.Header.Get("Content-Encoding"); encoding != "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
body, err := drainBody(resp.Body)
|
||||
if err != nil || body == nil {
|
||||
return err
|
||||
}
|
||||
|
||||
contentType, _, _ := strings.Cut(resp.Header.Get("Content-Type"), ";")
|
||||
for _, rewrite := range rewrites {
|
||||
rewriteType := rewrite.Type
|
||||
if rewriteType == "" {
|
||||
rewriteType = "text/html"
|
||||
}
|
||||
if rewriteType != "*" && !strings.Contains(rewriteType, contentType) {
|
||||
continue
|
||||
}
|
||||
|
||||
body = rewrite.Pattern.ReplaceAll(body, rewrite.Replacement)
|
||||
}
|
||||
|
||||
resp.Body = io.NopCloser(bytes.NewReader(body))
|
||||
resp.ContentLength = int64(len(body))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func drainBody(b io.ReadCloser) (body []byte, err error) {
|
||||
if b == nil || b == http.NoBody {
|
||||
// No copying needed. Preserve the magic sentinel meaning of NoBody.
|
||||
return nil, nil
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
if _, err = buf.ReadFrom(b); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = b.Close(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
func (h *forwardHandler) checkRateLimit(addr net.Addr) bool {
|
||||
if h.options.RateLimiter == nil {
|
||||
return true
|
||||
|
||||
@@ -2,6 +2,7 @@ package remote
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
@@ -107,7 +108,7 @@ func (h *forwardHandler) Handle(ctx context.Context, conn net.Conn, opts ...hand
|
||||
}
|
||||
}
|
||||
if protocol == forward.ProtoHTTP {
|
||||
h.handleHTTP(ctx, rw, conn.RemoteAddr(), localAddr, log)
|
||||
h.handleHTTP(ctx, xio.NewReadWriteCloser(rw, rw, conn), conn.RemoteAddr(), localAddr, log)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -177,11 +178,11 @@ func (h *forwardHandler) Handle(ctx context.Context, conn net.Conn, opts ...hand
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *forwardHandler) handleHTTP(ctx context.Context, rw io.ReadWriter, remoteAddr net.Addr, localAddr net.Addr, log logger.Logger) (err error) {
|
||||
func (h *forwardHandler) handleHTTP(ctx context.Context, rw io.ReadWriteCloser, remoteAddr net.Addr, localAddr net.Addr, log logger.Logger) (err error) {
|
||||
br := bufio.NewReader(rw)
|
||||
var cc net.Conn
|
||||
|
||||
for {
|
||||
var cc net.Conn
|
||||
resp := &http.Response{
|
||||
ProtoMajor: 1,
|
||||
ProtoMinor: 1,
|
||||
@@ -242,6 +243,7 @@ func (h *forwardHandler) handleHTTP(ctx context.Context, rw io.ReadWriter, remot
|
||||
})
|
||||
log.Debugf("find node for host %s -> %s(%s)", req.Host, target.Name, target.Addr)
|
||||
|
||||
var bodyRewrites []chain.HTTPBodyRewriteSettings
|
||||
if httpSettings := target.Options().HTTP; httpSettings != nil {
|
||||
if auther := httpSettings.Auther; auther != nil {
|
||||
username, password, _ := req.BasicAuth()
|
||||
@@ -261,7 +263,7 @@ func (h *forwardHandler) handleHTTP(ctx context.Context, rw io.ReadWriter, remot
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
|
||||
for _, re := range httpSettings.Rewrite {
|
||||
for _, re := range httpSettings.RewriteURL {
|
||||
if re.Pattern.MatchString(req.URL.Path) {
|
||||
if s := re.Pattern.ReplaceAllString(req.URL.Path, re.Replacement); s != "" {
|
||||
req.URL.Path = s
|
||||
@@ -269,6 +271,8 @@ func (h *forwardHandler) handleHTTP(ctx context.Context, rw io.ReadWriter, remot
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bodyRewrites = httpSettings.RewriteBody
|
||||
}
|
||||
|
||||
cc, err = h.options.Router.Dial(ctx, "tcp", target.Addr)
|
||||
@@ -331,7 +335,18 @@ func (h *forwardHandler) handleHTTP(ctx context.Context, rw io.ReadWriter, remot
|
||||
log.Trace(string(dump))
|
||||
}
|
||||
|
||||
if res.Close {
|
||||
defer rw.Close()
|
||||
}
|
||||
|
||||
if err := h.rewriteBody(res, bodyRewrites...); err != nil {
|
||||
rw.Close()
|
||||
log.Errorf("rewrite body: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
if err = res.Write(rw); err != nil {
|
||||
rw.Close()
|
||||
log.Errorf("write response from node %s(%s): %v", target.Name, target.Addr, err)
|
||||
}
|
||||
}()
|
||||
@@ -350,6 +365,50 @@ func (h *forwardHandler) handleHTTP(ctx context.Context, rw io.ReadWriter, remot
|
||||
return
|
||||
}
|
||||
|
||||
func (h *forwardHandler) rewriteBody(resp *http.Response, rewrites ...chain.HTTPBodyRewriteSettings) error {
|
||||
if resp == nil || len(rewrites) == 0 || resp.ContentLength <= 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
body, err := drainBody(resp.Body)
|
||||
if err != nil || body == nil {
|
||||
return err
|
||||
}
|
||||
|
||||
contentType, _, _ := strings.Cut(resp.Header.Get("Content-Type"), ";")
|
||||
for _, rewrite := range rewrites {
|
||||
rewriteType := rewrite.Type
|
||||
if rewriteType == "" {
|
||||
rewriteType = "text/html"
|
||||
}
|
||||
if rewriteType != "*" && !strings.Contains(rewriteType, contentType) {
|
||||
continue
|
||||
}
|
||||
|
||||
body = rewrite.Pattern.ReplaceAll(body, rewrite.Replacement)
|
||||
}
|
||||
|
||||
resp.Body = io.NopCloser(bytes.NewReader(body))
|
||||
resp.ContentLength = int64(len(body))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func drainBody(b io.ReadCloser) (body []byte, err error) {
|
||||
if b == nil || b == http.NoBody {
|
||||
// No copying needed. Preserve the magic sentinel meaning of NoBody.
|
||||
return nil, nil
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
if _, err = buf.ReadFrom(b); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = b.Close(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
func (h *forwardHandler) checkRateLimit(addr net.Addr) bool {
|
||||
if h.options.RateLimiter == nil {
|
||||
return true
|
||||
|
||||
+65
-19
@@ -24,6 +24,7 @@ import (
|
||||
md "github.com/go-gost/core/metadata"
|
||||
"github.com/go-gost/core/observer/stats"
|
||||
ctxvalue "github.com/go-gost/x/ctx"
|
||||
xio "github.com/go-gost/x/internal/io"
|
||||
netpkg "github.com/go-gost/x/internal/net"
|
||||
stats_util "github.com/go-gost/x/internal/util/stats"
|
||||
traffic_wrapper "github.com/go-gost/x/limiter/traffic/wrapper"
|
||||
@@ -236,7 +237,7 @@ func (h *httpHandler) handleRequest(ctx context.Context, conn net.Conn, req *htt
|
||||
}
|
||||
|
||||
if req.Method != http.MethodConnect {
|
||||
return h.handleProxy(rw, cc, req, log)
|
||||
return h.handleProxy(xio.NewReadWriteCloser(rw, rw, conn), cc, req, log)
|
||||
}
|
||||
|
||||
resp.StatusCode = http.StatusOK
|
||||
@@ -261,24 +262,80 @@ func (h *httpHandler) handleRequest(ctx context.Context, conn net.Conn, req *htt
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *httpHandler) handleProxy(rw, cc io.ReadWriter, req *http.Request, log logger.Logger) (err error) {
|
||||
func (h *httpHandler) handleProxy(rw io.ReadWriteCloser, cc io.ReadWriter, req *http.Request, log logger.Logger) (err error) {
|
||||
roundTrip := func(req *http.Request) error {
|
||||
if req == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
resp := &http.Response{
|
||||
ProtoMajor: req.ProtoMajor,
|
||||
ProtoMinor: req.ProtoMinor,
|
||||
Header: http.Header{},
|
||||
StatusCode: http.StatusServiceUnavailable,
|
||||
}
|
||||
|
||||
// HTTP/1.0
|
||||
if req.ProtoMajor == 1 && req.ProtoMinor == 0 {
|
||||
if strings.ToLower(req.Header.Get("Connection")) == "keep-alive" {
|
||||
req.Header.Del("Connection")
|
||||
} else {
|
||||
req.Header.Set("Connection", "close")
|
||||
}
|
||||
}
|
||||
|
||||
req.Header.Del("Proxy-Connection")
|
||||
|
||||
if err = req.Write(cc); err != nil {
|
||||
log.Error(err)
|
||||
resp.Write(rw)
|
||||
return err
|
||||
}
|
||||
|
||||
ch := make(chan error, 1)
|
||||
|
||||
go func() {
|
||||
ch <- netpkg.CopyBuffer(rw, cc, 32*1024)
|
||||
res, err := http.ReadResponse(bufio.NewReader(cc), req)
|
||||
if err != nil {
|
||||
h.options.Logger.Errorf("read response: %v", err)
|
||||
resp.Write(rw)
|
||||
return
|
||||
}
|
||||
|
||||
if log.IsLevelEnabled(logger.TraceLevel) {
|
||||
dump, _ := httputil.DumpResponse(res, false)
|
||||
log.Trace(string(dump))
|
||||
}
|
||||
|
||||
if res.Close {
|
||||
defer rw.Close()
|
||||
}
|
||||
|
||||
// HTTP/1.0
|
||||
if req.ProtoMajor == 1 && req.ProtoMinor == 0 {
|
||||
if !res.Close {
|
||||
res.Header.Set("Connection", "keep-alive")
|
||||
}
|
||||
res.ProtoMajor = req.ProtoMajor
|
||||
res.ProtoMinor = req.ProtoMinor
|
||||
}
|
||||
|
||||
if err = res.Write(rw); err != nil {
|
||||
rw.Close()
|
||||
log.Errorf("write response: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
if err = roundTrip(req); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for {
|
||||
err := func() error {
|
||||
req, err := http.ReadRequest(bufio.NewReader(rw))
|
||||
if err != nil {
|
||||
if errors.Is(err, io.EOF) || errors.Is(err, net.ErrClosed) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -287,21 +344,10 @@ func (h *httpHandler) handleProxy(rw, cc io.ReadWriter, req *http.Request, log l
|
||||
log.Trace(string(dump))
|
||||
}
|
||||
|
||||
req.Header.Del("Proxy-Connection")
|
||||
|
||||
if err = req.Write(cc); err != nil {
|
||||
if err = roundTrip(req); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}()
|
||||
ch <- err
|
||||
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return <-ch
|
||||
}
|
||||
|
||||
func (h *httpHandler) decodeServerName(s string) (string, error) {
|
||||
|
||||
@@ -14,12 +14,8 @@ type metadata struct {
|
||||
}
|
||||
|
||||
func (h *redirectHandler) parseMetadata(md mdata.Metadata) (err error) {
|
||||
const (
|
||||
tproxy = "tproxy"
|
||||
sniffing = "sniffing"
|
||||
)
|
||||
h.md.tproxy = mdutil.GetBool(md, tproxy)
|
||||
h.md.sniffing = mdutil.GetBool(md, sniffing)
|
||||
h.md.tproxy = mdutil.GetBool(md, "tproxy")
|
||||
h.md.sniffing = mdutil.GetBool(md, "sniffing")
|
||||
h.md.sniffingTimeout = mdutil.GetDuration(md, "sniffing.timeout")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -101,6 +101,7 @@ func (h *socks5Handler) Handle(ctx context.Context, conn net.Conn, opts ...handl
|
||||
|
||||
if clientID := sc.ID(); clientID != "" {
|
||||
ctx = ctxvalue.ContextWithClientID(ctx, ctxvalue.ClientID(clientID))
|
||||
log = log.WithFields(map[string]any{"user": clientID})
|
||||
}
|
||||
|
||||
conn = sc
|
||||
|
||||
@@ -83,6 +83,9 @@ func (ep *entrypoint) handle(ctx context.Context, conn net.Conn) error {
|
||||
log.Trace(string(dump))
|
||||
}
|
||||
|
||||
resp.ProtoMajor = req.ProtoMajor
|
||||
resp.ProtoMinor = req.ProtoMinor
|
||||
|
||||
var tunnelID relay.TunnelID
|
||||
if ep.ingress != nil {
|
||||
if rule := ep.ingress.GetRule(ctx, req.Host); rule != nil {
|
||||
@@ -123,13 +126,15 @@ func (ep *entrypoint) handle(ctx context.Context, conn net.Conn) error {
|
||||
timeout: 15 * time.Second,
|
||||
log: log,
|
||||
}
|
||||
cc, node, cid, err := d.Dial(ctx, "tcp", tunnelID.String())
|
||||
c, node, cid, err := d.Dial(ctx, "tcp", tunnelID.String())
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
return resp.Write(conn)
|
||||
}
|
||||
log.Debugf("new connection to tunnel: %s, connector: %s", tunnelID, cid)
|
||||
|
||||
cc = c
|
||||
|
||||
host := req.Host
|
||||
if h, _, _ := net.SplitHostPort(host); h == "" {
|
||||
host = net.JoinHostPort(strings.Trim(host, "[]"), "80")
|
||||
@@ -149,17 +154,26 @@ func (ep *entrypoint) handle(ctx context.Context, conn net.Conn) error {
|
||||
Version: relay.Version1,
|
||||
Status: relay.StatusOK,
|
||||
Features: features,
|
||||
}).WriteTo(cc)
|
||||
}).WriteTo(c)
|
||||
}
|
||||
|
||||
if err := req.Write(cc); err != nil {
|
||||
cc.Close()
|
||||
// HTTP/1.0
|
||||
if req.ProtoMajor == 1 && req.ProtoMinor == 0 {
|
||||
if strings.ToLower(req.Header.Get("Connection")) == "keep-alive" {
|
||||
req.Header.Del("Connection")
|
||||
} else {
|
||||
req.Header.Set("Connection", "close")
|
||||
}
|
||||
}
|
||||
|
||||
if err := req.Write(c); err != nil {
|
||||
c.Close()
|
||||
log.Errorf("send request: %v", err)
|
||||
return resp.Write(conn)
|
||||
}
|
||||
|
||||
if req.Header.Get("Upgrade") == "websocket" {
|
||||
err := xnet.Transport(cc, xio.NewReadWriter(br, conn))
|
||||
err := xnet.Transport(c, xio.NewReadWriter(br, conn))
|
||||
if err == nil {
|
||||
err = io.EOF
|
||||
}
|
||||
@@ -167,7 +181,7 @@ func (ep *entrypoint) handle(ctx context.Context, conn net.Conn) error {
|
||||
}
|
||||
|
||||
go func() {
|
||||
defer cc.Close()
|
||||
defer c.Close()
|
||||
|
||||
t := time.Now()
|
||||
log.Debugf("%s <-> %s", remoteAddr, host)
|
||||
@@ -178,7 +192,7 @@ func (ep *entrypoint) handle(ctx context.Context, conn net.Conn) error {
|
||||
}).Debugf("%s >-< %s", remoteAddr, host)
|
||||
}()
|
||||
|
||||
res, err := http.ReadResponse(bufio.NewReader(cc), req)
|
||||
res, err := http.ReadResponse(bufio.NewReader(c), req)
|
||||
if err != nil {
|
||||
log.Errorf("read response: %v", err)
|
||||
resp.Write(conn)
|
||||
@@ -190,7 +204,21 @@ func (ep *entrypoint) handle(ctx context.Context, conn net.Conn) error {
|
||||
log.Trace(string(dump))
|
||||
}
|
||||
|
||||
if res.Close {
|
||||
defer conn.Close()
|
||||
}
|
||||
|
||||
// HTTP/1.0
|
||||
if req.ProtoMajor == 1 && req.ProtoMinor == 0 {
|
||||
if !res.Close {
|
||||
res.Header.Set("Connection", "keep-alive")
|
||||
}
|
||||
res.ProtoMajor = req.ProtoMajor
|
||||
res.ProtoMinor = req.ProtoMinor
|
||||
}
|
||||
|
||||
if err = res.Write(conn); err != nil {
|
||||
conn.Close()
|
||||
log.Errorf("write response: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
@@ -264,6 +264,10 @@ func (h *tunnelHandler) Handle(ctx context.Context, conn net.Conn, opts ...handl
|
||||
|
||||
// Close implements io.Closer interface.
|
||||
func (h *tunnelHandler) Close() error {
|
||||
if h.epSvc != nil {
|
||||
h.epSvc.Close()
|
||||
}
|
||||
h.pool.Close()
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -66,6 +66,14 @@ func (c *Connector) Session() *mux.Session {
|
||||
return c.s
|
||||
}
|
||||
|
||||
func (c *Connector) Close() error {
|
||||
if c == nil || c.s == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return c.s.Close()
|
||||
}
|
||||
|
||||
type Tunnel struct {
|
||||
node string
|
||||
id relay.TunnelID
|
||||
@@ -75,7 +83,7 @@ type Tunnel struct {
|
||||
mu sync.RWMutex
|
||||
sd sd.SD
|
||||
ttl time.Duration
|
||||
rw *selector.RandomWeighted[*Connector]
|
||||
// rw *selector.RandomWeighted[*Connector]
|
||||
}
|
||||
|
||||
func NewTunnel(node string, tid relay.TunnelID, ttl time.Duration) *Tunnel {
|
||||
@@ -85,7 +93,7 @@ func NewTunnel(node string, tid relay.TunnelID, ttl time.Duration) *Tunnel {
|
||||
t: time.Now(),
|
||||
close: make(chan struct{}),
|
||||
ttl: ttl,
|
||||
rw: selector.NewRandomWeighted[*Connector](),
|
||||
// rw: selector.NewRandomWeighted[*Connector](),
|
||||
}
|
||||
if t.ttl <= 0 {
|
||||
t.ttl = defaultTTL
|
||||
@@ -117,8 +125,14 @@ func (t *Tunnel) GetConnector(network string) *Connector {
|
||||
t.mu.RLock()
|
||||
defer t.mu.RUnlock()
|
||||
|
||||
rw := t.rw
|
||||
rw.Reset()
|
||||
// rw := t.rw
|
||||
// rw.Reset()
|
||||
|
||||
if len(t.connectors) == 1 {
|
||||
return t.connectors[0]
|
||||
}
|
||||
|
||||
rw := selector.NewRandomWeighted[*Connector]()
|
||||
|
||||
found := false
|
||||
for _, c := range t.connectors {
|
||||
@@ -147,6 +161,22 @@ func (t *Tunnel) GetConnector(network string) *Connector {
|
||||
return rw.Next()
|
||||
}
|
||||
|
||||
func (t *Tunnel) Close() error {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
|
||||
select {
|
||||
case <-t.close:
|
||||
default:
|
||||
for _, c := range t.connectors {
|
||||
c.Close()
|
||||
}
|
||||
close(t.close)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *Tunnel) CloseOnIdle() bool {
|
||||
t.mu.RLock()
|
||||
defer t.mu.RUnlock()
|
||||
@@ -256,6 +286,22 @@ func (p *ConnectorPool) Get(network string, tid string) *Connector {
|
||||
return t.GetConnector(network)
|
||||
}
|
||||
|
||||
func (p *ConnectorPool) Close() error {
|
||||
if p == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
|
||||
for k, v := range p.tunnels {
|
||||
v.Close()
|
||||
delete(p.tunnels, k)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *ConnectorPool) closeIdles() {
|
||||
ticker := time.NewTicker(1 * time.Hour)
|
||||
defer ticker.Stop()
|
||||
|
||||
+1
-1
@@ -245,7 +245,7 @@ func (ing *localIngress) GetRule(ctx context.Context, host string, opts ...ingre
|
||||
}
|
||||
|
||||
if ep != nil {
|
||||
ing.options.logger.Debugf("ingress: %s -> %s", host, ep)
|
||||
ing.options.logger.Debugf("ingress: %s -> %s:%s", host, ep.Hostname, ep.Endpoint)
|
||||
}
|
||||
|
||||
return ep
|
||||
|
||||
@@ -13,3 +13,17 @@ func NewReadWriter(r io.Reader, w io.Writer) io.ReadWriter {
|
||||
Writer: w,
|
||||
}
|
||||
}
|
||||
|
||||
type readWriteCloser struct {
|
||||
io.Reader
|
||||
io.Writer
|
||||
io.Closer
|
||||
}
|
||||
|
||||
func NewReadWriteCloser(r io.Reader, w io.Writer, c io.Closer) io.ReadWriteCloser {
|
||||
return &readWriteCloser{
|
||||
Reader: r,
|
||||
Writer: w,
|
||||
Closer: c,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,14 +17,13 @@ type ListenConfig struct {
|
||||
ReadQueueSize int
|
||||
ReadBufferSize int
|
||||
TTL time.Duration
|
||||
KeepAlive bool
|
||||
Keepalive bool
|
||||
Logger logger.Logger
|
||||
}
|
||||
type listener struct {
|
||||
conn net.PacketConn
|
||||
cqueue chan net.Conn
|
||||
connPool *connPool
|
||||
// mux sync.Mutex
|
||||
closed chan struct{}
|
||||
errChan chan error
|
||||
config *ListenConfig
|
||||
@@ -42,9 +41,7 @@ func NewListener(conn net.PacketConn, cfg *ListenConfig) net.Listener {
|
||||
errChan: make(chan error, 1),
|
||||
config: cfg,
|
||||
}
|
||||
if cfg.KeepAlive {
|
||||
ln.connPool = newConnPool(cfg.TTL).WithLogger(cfg.Logger)
|
||||
}
|
||||
go ln.listenLoop()
|
||||
|
||||
return ln
|
||||
@@ -113,15 +110,12 @@ func (ln *listener) Close() error {
|
||||
}
|
||||
|
||||
func (ln *listener) getConn(raddr net.Addr) *conn {
|
||||
// ln.mux.Lock()
|
||||
// defer ln.mux.Unlock()
|
||||
|
||||
c, ok := ln.connPool.Get(raddr.String())
|
||||
if ok {
|
||||
if ok && !c.isClosed() {
|
||||
return c
|
||||
}
|
||||
|
||||
c = newConn(ln.conn, ln.Addr(), raddr, ln.config.ReadQueueSize, ln.config.KeepAlive)
|
||||
c = newConn(ln.conn, ln.Addr(), raddr, ln.config.ReadQueueSize, ln.config.Keepalive)
|
||||
select {
|
||||
case ln.cqueue <- c:
|
||||
ln.connPool.Set(raddr.String(), c)
|
||||
@@ -142,17 +136,17 @@ type conn struct {
|
||||
idle int32 // indicate the connection is idle
|
||||
closed chan struct{}
|
||||
closeMutex sync.Mutex
|
||||
keepAlive bool
|
||||
keepalive bool
|
||||
}
|
||||
|
||||
func newConn(c net.PacketConn, laddr, remoteAddr net.Addr, queueSize int, keepAlive bool) *conn {
|
||||
func newConn(c net.PacketConn, laddr, remoteAddr net.Addr, queueSize int, keepalive bool) *conn {
|
||||
return &conn{
|
||||
PacketConn: c,
|
||||
localAddr: laddr,
|
||||
remoteAddr: remoteAddr,
|
||||
rc: make(chan []byte, queueSize),
|
||||
closed: make(chan struct{}),
|
||||
keepAlive: keepAlive,
|
||||
keepalive: keepalive,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -178,12 +172,15 @@ func (c *conn) Read(b []byte) (n int, err error) {
|
||||
return
|
||||
}
|
||||
|
||||
func (c *conn) Write(b []byte) (n int, err error) {
|
||||
n, err = c.WriteTo(b, c.remoteAddr)
|
||||
if !c.keepAlive {
|
||||
c.Close()
|
||||
func (c *conn) WriteTo(b []byte, addr net.Addr) (n int, err error) {
|
||||
if !c.keepalive {
|
||||
defer c.Close()
|
||||
}
|
||||
return
|
||||
return c.PacketConn.WriteTo(b, addr)
|
||||
}
|
||||
|
||||
func (c *conn) Write(b []byte) (n int, err error) {
|
||||
return c.WriteTo(b, c.remoteAddr)
|
||||
}
|
||||
|
||||
func (c *conn) Close() error {
|
||||
@@ -198,6 +195,15 @@ func (c *conn) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *conn) isClosed() bool {
|
||||
select {
|
||||
case <-c.closed:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (c *conn) LocalAddr() net.Addr {
|
||||
return c.localAddr
|
||||
}
|
||||
|
||||
@@ -12,6 +12,12 @@ import (
|
||||
"github.com/go-gost/core/logger"
|
||||
"golang.org/x/net/icmp"
|
||||
"golang.org/x/net/ipv4"
|
||||
"golang.org/x/net/ipv6"
|
||||
)
|
||||
|
||||
const (
|
||||
ICMPv4 = 1
|
||||
ICMPv6 = 58
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -79,13 +85,15 @@ func (m *message) Decode(b []byte) (n int, err error) {
|
||||
}
|
||||
|
||||
type clientConn struct {
|
||||
ip6 bool
|
||||
net.PacketConn
|
||||
id int
|
||||
seq uint32
|
||||
}
|
||||
|
||||
func ClientConn(conn net.PacketConn, id int) net.PacketConn {
|
||||
func ClientConn(ip6 bool, conn net.PacketConn, id int) net.PacketConn {
|
||||
return &clientConn{
|
||||
ip6: ip6,
|
||||
PacketConn: conn,
|
||||
id: id,
|
||||
}
|
||||
@@ -101,13 +109,17 @@ func (c *clientConn) ReadFrom(b []byte) (n int, addr net.Addr, err error) {
|
||||
return
|
||||
}
|
||||
|
||||
m, err := icmp.ParseMessage(1, buf[:n])
|
||||
proto := ICMPv4
|
||||
if c.ip6 {
|
||||
proto = ICMPv6
|
||||
}
|
||||
m, err := icmp.ParseMessage(proto, buf[:n])
|
||||
if err != nil {
|
||||
// logger.Default().Error("icmp: parse message %v", err)
|
||||
return 0, addr, err
|
||||
}
|
||||
echo, ok := m.Body.(*icmp.Echo)
|
||||
if !ok || m.Type != ipv4.ICMPTypeEchoReply {
|
||||
if !ok || m.Type != ipv4.ICMPTypeEchoReply && m.Type != ipv6.ICMPTypeEchoReply {
|
||||
// logger.Default().Warnf("icmp: invalid type %s (discarded)", m.Type)
|
||||
continue // discard
|
||||
}
|
||||
@@ -135,6 +147,7 @@ func (c *clientConn) ReadFrom(b []byte) (n int, addr net.Addr, err error) {
|
||||
addr = &net.UDPAddr{
|
||||
IP: v.IP,
|
||||
Port: c.id,
|
||||
Zone: v.Zone,
|
||||
}
|
||||
}
|
||||
// logger.Default().Infof("icmp: read from: %v %d", addr, n)
|
||||
@@ -146,7 +159,7 @@ func (c *clientConn) WriteTo(b []byte, addr net.Addr) (n int, err error) {
|
||||
// logger.Default().Infof("icmp: write to: %v %d", addr, len(b))
|
||||
switch v := addr.(type) {
|
||||
case *net.UDPAddr:
|
||||
addr = &net.IPAddr{IP: v.IP}
|
||||
addr = &net.IPAddr{IP: v.IP, Zone: v.Zone}
|
||||
}
|
||||
|
||||
buf := bufpool.Get(writeBufferSize)
|
||||
@@ -170,6 +183,10 @@ func (c *clientConn) WriteTo(b []byte, addr net.Addr) (n int, err error) {
|
||||
Code: 0,
|
||||
Body: &echo,
|
||||
}
|
||||
if c.ip6 {
|
||||
m.Type = ipv6.ICMPTypeEchoRequest
|
||||
}
|
||||
|
||||
wb, err := m.Marshal(nil)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
@@ -180,12 +197,14 @@ func (c *clientConn) WriteTo(b []byte, addr net.Addr) (n int, err error) {
|
||||
}
|
||||
|
||||
type serverConn struct {
|
||||
ip6 bool
|
||||
net.PacketConn
|
||||
seqs [65535]uint32
|
||||
}
|
||||
|
||||
func ServerConn(conn net.PacketConn) net.PacketConn {
|
||||
func ServerConn(ip6 bool, conn net.PacketConn) net.PacketConn {
|
||||
return &serverConn{
|
||||
ip6: ip6,
|
||||
PacketConn: conn,
|
||||
}
|
||||
}
|
||||
@@ -200,14 +219,18 @@ func (c *serverConn) ReadFrom(b []byte) (n int, addr net.Addr, err error) {
|
||||
return
|
||||
}
|
||||
|
||||
m, err := icmp.ParseMessage(1, buf[:n])
|
||||
proto := ICMPv4
|
||||
if c.ip6 {
|
||||
proto = ICMPv6
|
||||
}
|
||||
m, err := icmp.ParseMessage(proto, buf[:n])
|
||||
if err != nil {
|
||||
// logger.Default().Error("icmp: parse message %v", err)
|
||||
return 0, addr, err
|
||||
}
|
||||
|
||||
echo, ok := m.Body.(*icmp.Echo)
|
||||
if !ok || m.Type != ipv4.ICMPTypeEcho || echo.ID <= 0 {
|
||||
if !ok || echo.ID <= 0 || m.Type != ipv4.ICMPTypeEcho && m.Type != ipv6.ICMPTypeEchoRequest {
|
||||
// logger.Default().Warnf("icmp: invalid type %s (discarded)", m.Type)
|
||||
continue
|
||||
}
|
||||
@@ -229,6 +252,7 @@ func (c *serverConn) ReadFrom(b []byte) (n int, addr net.Addr, err error) {
|
||||
addr = &net.UDPAddr{
|
||||
IP: v.IP,
|
||||
Port: echo.ID,
|
||||
Zone: v.Zone,
|
||||
}
|
||||
}
|
||||
break
|
||||
@@ -244,7 +268,7 @@ func (c *serverConn) WriteTo(b []byte, addr net.Addr) (n int, err error) {
|
||||
var id int
|
||||
switch v := addr.(type) {
|
||||
case *net.UDPAddr:
|
||||
addr = &net.IPAddr{IP: v.IP}
|
||||
addr = &net.IPAddr{IP: v.IP, Zone: v.Zone}
|
||||
id = v.Port
|
||||
}
|
||||
|
||||
@@ -275,6 +299,10 @@ func (c *serverConn) WriteTo(b []byte, addr net.Addr) (n int, err error) {
|
||||
Code: 0,
|
||||
Body: &echo,
|
||||
}
|
||||
if c.ip6 {
|
||||
m.Type = ipv6.ICMPTypeEchoReply
|
||||
}
|
||||
|
||||
wb, err := m.Marshal(nil)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
|
||||
@@ -64,7 +64,7 @@ func (l *ftcpListener) Init(md md.Metadata) (err error) {
|
||||
ReadQueueSize: l.md.readQueueSize,
|
||||
ReadBufferSize: l.md.readBufferSize,
|
||||
TTL: l.md.ttl,
|
||||
KeepAlive: true,
|
||||
Keepalive: true,
|
||||
Logger: l.logger,
|
||||
})
|
||||
return
|
||||
|
||||
@@ -19,9 +19,11 @@ import (
|
||||
|
||||
func init() {
|
||||
registry.ListenerRegistry().Register("icmp", NewListener)
|
||||
registry.ListenerRegistry().Register("icmp6", NewListener6)
|
||||
}
|
||||
|
||||
type icmpListener struct {
|
||||
ip6 bool
|
||||
ln quic.EarlyListener
|
||||
cqueue chan net.Conn
|
||||
errChan chan error
|
||||
@@ -41,6 +43,18 @@ func NewListener(opts ...listener.Option) listener.Listener {
|
||||
}
|
||||
}
|
||||
|
||||
func NewListener6(opts ...listener.Option) listener.Listener {
|
||||
options := listener.Options{}
|
||||
for _, opt := range opts {
|
||||
opt(&options)
|
||||
}
|
||||
return &icmpListener{
|
||||
ip6: true,
|
||||
logger: options.Logger,
|
||||
options: options,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *icmpListener) Init(md md.Metadata) (err error) {
|
||||
if err = l.parseMetadata(md); err != nil {
|
||||
return
|
||||
@@ -52,11 +66,15 @@ func (l *icmpListener) Init(md md.Metadata) (err error) {
|
||||
}
|
||||
|
||||
var conn net.PacketConn
|
||||
if l.ip6 {
|
||||
conn, err = icmp.ListenPacket("ip6:ipv6-icmp", addr)
|
||||
} else {
|
||||
conn, err = icmp.ListenPacket("ip4:icmp", addr)
|
||||
}
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
conn = icmp_pkg.ServerConn(conn)
|
||||
conn = icmp_pkg.ServerConn(l.ip6, conn)
|
||||
conn = metrics.WrapPacketConn(l.options.Service, conn)
|
||||
conn = stats.WrapPacketConn(conn, l.options.Stats)
|
||||
conn = admission.WrapPacketConn(l.options.Admission, conn)
|
||||
|
||||
@@ -20,28 +20,19 @@ type metadata struct {
|
||||
}
|
||||
|
||||
func (l *icmpListener) parseMetadata(md mdata.Metadata) (err error) {
|
||||
const (
|
||||
keepAlive = "keepAlive"
|
||||
keepAlivePeriod = "ttl"
|
||||
handshakeTimeout = "handshakeTimeout"
|
||||
maxIdleTimeout = "maxIdleTimeout"
|
||||
|
||||
backlog = "backlog"
|
||||
)
|
||||
|
||||
l.md.backlog = mdutil.GetInt(md, backlog)
|
||||
l.md.backlog = mdutil.GetInt(md, "backlog")
|
||||
if l.md.backlog <= 0 {
|
||||
l.md.backlog = defaultBacklog
|
||||
}
|
||||
|
||||
if mdutil.GetBool(md, keepAlive) {
|
||||
l.md.keepAlivePeriod = mdutil.GetDuration(md, keepAlivePeriod)
|
||||
if mdutil.GetBool(md, "keepalive") {
|
||||
l.md.keepAlivePeriod = mdutil.GetDuration(md, "ttl")
|
||||
if l.md.keepAlivePeriod <= 0 {
|
||||
l.md.keepAlivePeriod = 10 * time.Second
|
||||
}
|
||||
}
|
||||
l.md.handshakeTimeout = mdutil.GetDuration(md, handshakeTimeout)
|
||||
l.md.maxIdleTimeout = mdutil.GetDuration(md, maxIdleTimeout)
|
||||
l.md.handshakeTimeout = mdutil.GetDuration(md, "handshakeTimeout")
|
||||
l.md.maxIdleTimeout = mdutil.GetDuration(md, "maxIdleTimeout")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
@@ -11,10 +11,7 @@ type metadata struct {
|
||||
}
|
||||
|
||||
func (l *redirectListener) parseMetadata(md mdata.Metadata) (err error) {
|
||||
const (
|
||||
tproxy = "tproxy"
|
||||
)
|
||||
l.md.tproxy = mdutil.GetBool(md, tproxy)
|
||||
l.md.tproxy = mdutil.GetBool(md, "tproxy")
|
||||
l.md.mptcp = mdutil.GetBool(md, "mptcp")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
|
||||
const (
|
||||
defaultTTL = 5 * time.Second
|
||||
defaultReadBufferSize = 1024
|
||||
defaultReadBufferSize = 8192
|
||||
defaultReadQueueSize = 1024
|
||||
defaultBacklog = 128
|
||||
)
|
||||
|
||||
@@ -65,7 +65,7 @@ func (l *udpListener) Init(md md.Metadata) (err error) {
|
||||
Backlog: l.md.backlog,
|
||||
ReadQueueSize: l.md.readQueueSize,
|
||||
ReadBufferSize: l.md.readBufferSize,
|
||||
KeepAlive: l.md.keepalive,
|
||||
Keepalive: l.md.keepalive,
|
||||
TTL: l.md.ttl,
|
||||
Logger: l.logger,
|
||||
})
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
|
||||
const (
|
||||
defaultTTL = 5 * time.Second
|
||||
defaultReadBufferSize = 1024
|
||||
defaultReadBufferSize = 8192
|
||||
defaultReadQueueSize = 128
|
||||
defaultBacklog = 128
|
||||
)
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
package util
|
||||
|
||||
import tls "github.com/refraction-networking/utls"
|
||||
|
||||
func NewWsSpec() *tls.ClientHelloSpec {
|
||||
return &tls.ClientHelloSpec{
|
||||
CipherSuites: []uint16{
|
||||
tls.GREASE_PLACEHOLDER,
|
||||
tls.TLS_AES_128_GCM_SHA256,
|
||||
tls.TLS_AES_256_GCM_SHA384,
|
||||
tls.TLS_CHACHA20_POLY1305_SHA256,
|
||||
tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
|
||||
tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
|
||||
tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
|
||||
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
|
||||
tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
|
||||
tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
|
||||
tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
|
||||
tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
|
||||
tls.TLS_RSA_WITH_AES_128_GCM_SHA256,
|
||||
tls.TLS_RSA_WITH_AES_256_GCM_SHA384,
|
||||
tls.TLS_RSA_WITH_AES_128_CBC_SHA,
|
||||
tls.TLS_RSA_WITH_AES_256_CBC_SHA,
|
||||
},
|
||||
CompressionMethods: []byte{
|
||||
0x00, // compressionNone
|
||||
},
|
||||
Extensions: []tls.TLSExtension{
|
||||
&tls.UtlsGREASEExtension{},
|
||||
&tls.SNIExtension{},
|
||||
&tls.ExtendedMasterSecretExtension{},
|
||||
&tls.RenegotiationInfoExtension{Renegotiation: tls.RenegotiateOnceAsClient},
|
||||
&tls.SupportedCurvesExtension{[]tls.CurveID{
|
||||
tls.GREASE_PLACEHOLDER,
|
||||
tls.X25519,
|
||||
tls.CurveP256,
|
||||
tls.CurveP384,
|
||||
}},
|
||||
&tls.SupportedPointsExtension{SupportedPoints: []byte{
|
||||
0x00, // pointFormatUncompressed
|
||||
}},
|
||||
&tls.SessionTicketExtension{},
|
||||
&tls.ALPNExtension{AlpnProtocols: []string{"http/1.1"}},
|
||||
&tls.StatusRequestExtension{},
|
||||
&tls.SignatureAlgorithmsExtension{SupportedSignatureAlgorithms: []tls.SignatureScheme{
|
||||
tls.ECDSAWithP256AndSHA256,
|
||||
tls.PSSWithSHA256,
|
||||
tls.PKCS1WithSHA256,
|
||||
tls.ECDSAWithP384AndSHA384,
|
||||
tls.PSSWithSHA384,
|
||||
tls.PKCS1WithSHA384,
|
||||
tls.PSSWithSHA512,
|
||||
tls.PKCS1WithSHA512,
|
||||
}},
|
||||
&tls.SCTExtension{},
|
||||
&tls.KeyShareExtension{[]tls.KeyShare{
|
||||
{Group: tls.CurveID(tls.GREASE_PLACEHOLDER), Data: []byte{0}},
|
||||
{Group: tls.X25519},
|
||||
}},
|
||||
&tls.PSKKeyExchangeModesExtension{[]uint8{
|
||||
tls.PskModeDHE,
|
||||
}},
|
||||
&tls.SupportedVersionsExtension{[]uint16{
|
||||
tls.GREASE_PLACEHOLDER,
|
||||
tls.VersionTLS13,
|
||||
tls.VersionTLS12,
|
||||
}},
|
||||
&tls.UtlsCompressCertExtension{[]tls.CertCompressionAlgo{
|
||||
tls.CertCompressionBrotli,
|
||||
}},
|
||||
&tls.ApplicationSettingsExtension{SupportedProtocols: []string{"h2"}},
|
||||
&tls.UtlsGREASEExtension{},
|
||||
&tls.UtlsPaddingExtension{GetPaddingLen: tls.BoringPaddingStyle},
|
||||
},
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user