2021-03-18 19:40:34 +08:00
|
|
|
// Modified from: https://github.com/Qv2ray/gun-lite
|
|
|
|
// License: MIT
|
|
|
|
|
|
|
|
package gun
|
|
|
|
|
|
|
|
import (
|
2021-04-07 22:57:46 +08:00
|
|
|
"bufio"
|
2022-01-15 19:33:21 +08:00
|
|
|
"context"
|
2021-03-18 19:40:34 +08:00
|
|
|
"crypto/tls"
|
|
|
|
"encoding/binary"
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"net"
|
|
|
|
"net/http"
|
|
|
|
"net/url"
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
|
2023-11-03 21:01:45 +08:00
|
|
|
"github.com/metacubex/mihomo/common/atomic"
|
|
|
|
"github.com/metacubex/mihomo/common/buf"
|
|
|
|
"github.com/metacubex/mihomo/common/pool"
|
|
|
|
tlsC "github.com/metacubex/mihomo/component/tls"
|
2023-03-10 10:01:05 +08:00
|
|
|
|
2021-03-18 19:40:34 +08:00
|
|
|
"golang.org/x/net/http2"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
ErrInvalidLength = errors.New("invalid length")
|
2021-04-07 22:57:46 +08:00
|
|
|
ErrSmallBuffer = errors.New("buffer too small")
|
2021-03-18 19:40:34 +08:00
|
|
|
)
|
|
|
|
|
2021-10-10 23:44:09 +08:00
|
|
|
var defaultHeader = http.Header{
|
|
|
|
"content-type": []string{"application/grpc"},
|
|
|
|
"user-agent": []string{"grpc-go/1.36.0"},
|
|
|
|
}
|
2021-03-18 19:40:34 +08:00
|
|
|
|
|
|
|
type DialFn = func(network, addr string) (net.Conn, error)
|
|
|
|
|
|
|
|
type Conn struct {
|
2021-04-13 23:34:24 +08:00
|
|
|
response *http.Response
|
|
|
|
request *http.Request
|
2022-05-04 16:57:08 +08:00
|
|
|
transport *TransportWrap
|
2021-04-13 23:34:24 +08:00
|
|
|
writer *io.PipeWriter
|
|
|
|
once sync.Once
|
2023-10-10 16:34:33 +08:00
|
|
|
close atomic.Bool
|
2021-04-13 23:34:24 +08:00
|
|
|
err error
|
|
|
|
remain int
|
|
|
|
br *bufio.Reader
|
|
|
|
// deadlines
|
|
|
|
deadline *time.Timer
|
2021-03-18 19:40:34 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
type Config struct {
|
2023-02-01 22:16:06 +08:00
|
|
|
ServiceName string
|
|
|
|
Host string
|
|
|
|
ClientFingerprint string
|
2021-03-18 19:40:34 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func (g *Conn) initRequest() {
|
2021-04-13 23:34:24 +08:00
|
|
|
response, err := g.transport.RoundTrip(g.request)
|
2021-03-18 19:40:34 +08:00
|
|
|
if err != nil {
|
|
|
|
g.err = err
|
|
|
|
g.writer.Close()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if !g.close.Load() {
|
|
|
|
g.response = response
|
2021-04-14 00:16:59 +08:00
|
|
|
g.br = bufio.NewReader(response.Body)
|
2021-03-18 19:40:34 +08:00
|
|
|
} else {
|
|
|
|
response.Body.Close()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (g *Conn) Read(b []byte) (n int, err error) {
|
|
|
|
g.once.Do(g.initRequest)
|
|
|
|
if g.err != nil {
|
|
|
|
return 0, g.err
|
|
|
|
}
|
|
|
|
|
2021-04-14 00:16:59 +08:00
|
|
|
if g.remain > 0 {
|
2021-04-07 22:57:46 +08:00
|
|
|
size := g.remain
|
|
|
|
if len(b) < size {
|
|
|
|
size = len(b)
|
|
|
|
}
|
|
|
|
|
2021-04-14 00:16:59 +08:00
|
|
|
n, err = io.ReadFull(g.br, b[:size])
|
2021-04-07 22:57:46 +08:00
|
|
|
g.remain -= n
|
|
|
|
return
|
2021-03-18 23:19:00 +08:00
|
|
|
} else if g.response == nil {
|
|
|
|
return 0, net.ErrClosed
|
2021-03-18 19:40:34 +08:00
|
|
|
}
|
|
|
|
|
2021-04-07 22:57:46 +08:00
|
|
|
// 0x00 grpclength(uint32) 0x0A uleb128 payload
|
2021-04-14 00:16:59 +08:00
|
|
|
_, err = g.br.Discard(6)
|
2021-03-18 19:40:34 +08:00
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
2021-04-07 22:57:46 +08:00
|
|
|
|
2021-04-14 00:16:59 +08:00
|
|
|
protobufPayloadLen, err := binary.ReadUvarint(g.br)
|
2021-04-07 22:57:46 +08:00
|
|
|
if err != nil {
|
2021-03-18 19:40:34 +08:00
|
|
|
return 0, ErrInvalidLength
|
|
|
|
}
|
|
|
|
|
2021-04-14 00:16:59 +08:00
|
|
|
size := int(protobufPayloadLen)
|
|
|
|
if len(b) < size {
|
|
|
|
size = len(b)
|
2021-03-18 19:40:34 +08:00
|
|
|
}
|
|
|
|
|
2021-04-14 00:16:59 +08:00
|
|
|
n, err = io.ReadFull(g.br, b[:size])
|
2021-04-07 22:57:46 +08:00
|
|
|
if err != nil {
|
2021-03-18 19:40:34 +08:00
|
|
|
return
|
|
|
|
}
|
2021-04-07 22:57:46 +08:00
|
|
|
|
2021-04-14 00:16:59 +08:00
|
|
|
remain := int(protobufPayloadLen) - n
|
2021-04-07 22:57:46 +08:00
|
|
|
if remain > 0 {
|
|
|
|
g.remain = remain
|
|
|
|
}
|
|
|
|
|
2021-04-14 00:16:59 +08:00
|
|
|
return n, nil
|
2021-03-18 19:40:34 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func (g *Conn) Write(b []byte) (n int, err error) {
|
2021-04-14 21:46:05 +08:00
|
|
|
protobufHeader := [binary.MaxVarintLen64 + 1]byte{0x0A}
|
|
|
|
varuintSize := binary.PutUvarint(protobufHeader[1:], uint64(len(b)))
|
2023-01-16 15:54:20 +08:00
|
|
|
var grpcHeader [5]byte
|
2021-04-14 21:46:05 +08:00
|
|
|
grpcPayloadLen := uint32(varuintSize + 1 + len(b))
|
2021-03-18 19:40:34 +08:00
|
|
|
binary.BigEndian.PutUint32(grpcHeader[1:5], grpcPayloadLen)
|
|
|
|
|
2021-09-20 21:02:18 +08:00
|
|
|
buf := pool.GetBuffer()
|
|
|
|
defer pool.PutBuffer(buf)
|
2023-01-16 15:54:20 +08:00
|
|
|
buf.Write(grpcHeader[:])
|
2021-04-14 21:46:05 +08:00
|
|
|
buf.Write(protobufHeader[:varuintSize+1])
|
|
|
|
buf.Write(b)
|
|
|
|
|
|
|
|
_, err = g.writer.Write(buf.Bytes())
|
2021-03-18 19:40:34 +08:00
|
|
|
if err == io.ErrClosedPipe && g.err != nil {
|
|
|
|
err = g.err
|
|
|
|
}
|
|
|
|
|
|
|
|
return len(b), err
|
|
|
|
}
|
|
|
|
|
2023-01-16 15:54:20 +08:00
|
|
|
func (g *Conn) WriteBuffer(buffer *buf.Buffer) error {
|
|
|
|
defer buffer.Release()
|
|
|
|
dataLen := buffer.Len()
|
|
|
|
varLen := UVarintLen(uint64(dataLen))
|
|
|
|
header := buffer.ExtendHeader(6 + varLen)
|
2023-04-05 13:51:50 +08:00
|
|
|
_ = header[6] // bounds check hint to compiler
|
2023-01-16 15:54:20 +08:00
|
|
|
header[0] = 0x00
|
|
|
|
binary.BigEndian.PutUint32(header[1:5], uint32(1+varLen+dataLen))
|
|
|
|
header[5] = 0x0A
|
|
|
|
binary.PutUvarint(header[6:], uint64(dataLen))
|
|
|
|
_, err := g.writer.Write(buffer.Bytes())
|
|
|
|
|
|
|
|
if err == io.ErrClosedPipe && g.err != nil {
|
|
|
|
err = g.err
|
|
|
|
}
|
|
|
|
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
func (g *Conn) FrontHeadroom() int {
|
|
|
|
return 6 + binary.MaxVarintLen64
|
|
|
|
}
|
|
|
|
|
2021-03-18 19:40:34 +08:00
|
|
|
func (g *Conn) Close() error {
|
|
|
|
g.close.Store(true)
|
|
|
|
if r := g.response; r != nil {
|
|
|
|
r.Body.Close()
|
|
|
|
}
|
|
|
|
|
|
|
|
return g.writer.Close()
|
|
|
|
}
|
|
|
|
|
2022-05-04 16:57:08 +08:00
|
|
|
func (g *Conn) LocalAddr() net.Addr { return g.transport.LocalAddr() }
|
|
|
|
func (g *Conn) RemoteAddr() net.Addr { return g.transport.RemoteAddr() }
|
2021-04-13 23:34:24 +08:00
|
|
|
func (g *Conn) SetReadDeadline(t time.Time) error { return g.SetDeadline(t) }
|
|
|
|
func (g *Conn) SetWriteDeadline(t time.Time) error { return g.SetDeadline(t) }
|
|
|
|
|
|
|
|
func (g *Conn) SetDeadline(t time.Time) error {
|
|
|
|
d := time.Until(t)
|
|
|
|
if g.deadline != nil {
|
|
|
|
g.deadline.Reset(d)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
g.deadline = time.AfterFunc(d, func() {
|
|
|
|
g.Close()
|
|
|
|
})
|
|
|
|
return nil
|
|
|
|
}
|
2021-03-18 19:40:34 +08:00
|
|
|
|
2023-03-10 10:01:05 +08:00
|
|
|
func NewHTTP2Client(dialFn DialFn, tlsConfig *tls.Config, Fingerprint string, realityConfig *tlsC.RealityConfig) *TransportWrap {
|
2022-05-04 16:57:08 +08:00
|
|
|
wrap := TransportWrap{}
|
2023-02-01 22:16:06 +08:00
|
|
|
|
2022-08-13 12:35:39 +08:00
|
|
|
dialFunc := func(ctx context.Context, network, addr string, cfg *tls.Config) (net.Conn, error) {
|
2021-03-18 19:40:34 +08:00
|
|
|
pconn, err := dialFn(network, addr)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2022-05-04 16:57:08 +08:00
|
|
|
wrap.remoteAddr = pconn.RemoteAddr()
|
2023-02-01 22:16:06 +08:00
|
|
|
|
2023-05-13 09:38:14 +08:00
|
|
|
if tlsConfig == nil {
|
|
|
|
return pconn, nil
|
|
|
|
}
|
|
|
|
|
2023-02-01 22:16:06 +08:00
|
|
|
if len(Fingerprint) != 0 {
|
2023-03-10 10:01:05 +08:00
|
|
|
if realityConfig == nil {
|
|
|
|
if fingerprint, exists := tlsC.GetFingerprint(Fingerprint); exists {
|
|
|
|
utlsConn := tlsC.UClient(pconn, cfg, fingerprint)
|
2023-11-02 11:22:01 +08:00
|
|
|
if err := utlsConn.HandshakeContext(ctx); err != nil {
|
2023-03-10 10:01:05 +08:00
|
|
|
pconn.Close()
|
|
|
|
return nil, err
|
|
|
|
}
|
2023-11-02 11:22:01 +08:00
|
|
|
state := utlsConn.ConnectionState()
|
2023-03-10 10:01:05 +08:00
|
|
|
if p := state.NegotiatedProtocol; p != http2.NextProtoTLS {
|
|
|
|
utlsConn.Close()
|
|
|
|
return nil, fmt.Errorf("http2: unexpected ALPN protocol %s, want %s", p, http2.NextProtoTLS)
|
|
|
|
}
|
|
|
|
return utlsConn, nil
|
|
|
|
}
|
|
|
|
} else {
|
2023-03-10 20:53:39 +08:00
|
|
|
realityConn, err := tlsC.GetRealityConn(ctx, pconn, Fingerprint, cfg, realityConfig)
|
2023-03-10 10:01:05 +08:00
|
|
|
if err != nil {
|
2023-02-01 22:16:06 +08:00
|
|
|
pconn.Close()
|
|
|
|
return nil, err
|
|
|
|
}
|
2023-03-10 10:01:05 +08:00
|
|
|
//state := realityConn.(*utls.UConn).ConnectionState()
|
|
|
|
//if p := state.NegotiatedProtocol; p != http2.NextProtoTLS {
|
|
|
|
// realityConn.Close()
|
|
|
|
// return nil, fmt.Errorf("http2: unexpected ALPN protocol %s, want %s", p, http2.NextProtoTLS)
|
|
|
|
//}
|
|
|
|
return realityConn, nil
|
2023-02-01 22:16:06 +08:00
|
|
|
}
|
|
|
|
}
|
2023-03-10 10:01:05 +08:00
|
|
|
if realityConfig != nil {
|
|
|
|
return nil, errors.New("REALITY is based on uTLS, please set a client-fingerprint")
|
|
|
|
}
|
2023-02-01 22:16:06 +08:00
|
|
|
|
|
|
|
conn := tls.Client(pconn, cfg)
|
|
|
|
if err := conn.HandshakeContext(ctx); err != nil {
|
2021-03-18 19:40:34 +08:00
|
|
|
pconn.Close()
|
|
|
|
return nil, err
|
|
|
|
}
|
2023-02-01 22:16:06 +08:00
|
|
|
state := conn.ConnectionState()
|
2021-03-18 19:40:34 +08:00
|
|
|
if p := state.NegotiatedProtocol; p != http2.NextProtoTLS {
|
2023-02-01 22:16:06 +08:00
|
|
|
conn.Close()
|
2021-04-05 13:31:10 +08:00
|
|
|
return nil, fmt.Errorf("http2: unexpected ALPN protocol %s, want %s", p, http2.NextProtoTLS)
|
2021-03-18 19:40:34 +08:00
|
|
|
}
|
2023-02-01 22:16:06 +08:00
|
|
|
return conn, nil
|
2021-03-18 19:40:34 +08:00
|
|
|
}
|
|
|
|
|
2022-05-04 16:57:08 +08:00
|
|
|
wrap.Transport = &http2.Transport{
|
2022-08-13 12:35:39 +08:00
|
|
|
DialTLSContext: dialFunc,
|
2021-03-18 19:40:34 +08:00
|
|
|
TLSClientConfig: tlsConfig,
|
|
|
|
AllowHTTP: false,
|
|
|
|
DisableCompression: true,
|
|
|
|
PingTimeout: 0,
|
|
|
|
}
|
2022-05-04 16:57:08 +08:00
|
|
|
|
|
|
|
return &wrap
|
2021-03-18 19:40:34 +08:00
|
|
|
}
|
|
|
|
|
2022-05-04 16:57:08 +08:00
|
|
|
func StreamGunWithTransport(transport *TransportWrap, cfg *Config) (net.Conn, error) {
|
2021-03-18 19:40:34 +08:00
|
|
|
serviceName := "GunService"
|
|
|
|
if cfg.ServiceName != "" {
|
|
|
|
serviceName = cfg.ServiceName
|
|
|
|
}
|
|
|
|
|
|
|
|
reader, writer := io.Pipe()
|
|
|
|
request := &http.Request{
|
|
|
|
Method: http.MethodPost,
|
|
|
|
Body: reader,
|
|
|
|
URL: &url.URL{
|
|
|
|
Scheme: "https",
|
|
|
|
Host: cfg.Host,
|
|
|
|
Path: fmt.Sprintf("/%s/Tun", serviceName),
|
2021-08-19 22:11:56 +08:00
|
|
|
// for unescape path
|
|
|
|
Opaque: fmt.Sprintf("//%s/%s/Tun", cfg.Host, serviceName),
|
2021-03-18 19:40:34 +08:00
|
|
|
},
|
|
|
|
Proto: "HTTP/2",
|
|
|
|
ProtoMajor: 2,
|
|
|
|
ProtoMinor: 0,
|
|
|
|
Header: defaultHeader,
|
|
|
|
}
|
|
|
|
|
|
|
|
conn := &Conn{
|
2021-04-13 23:34:24 +08:00
|
|
|
request: request,
|
|
|
|
transport: transport,
|
|
|
|
writer: writer,
|
|
|
|
close: atomic.NewBool(false),
|
2021-03-18 19:40:34 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
go conn.once.Do(conn.initRequest)
|
|
|
|
return conn, nil
|
|
|
|
}
|
|
|
|
|
2023-03-10 10:01:05 +08:00
|
|
|
func StreamGunWithConn(conn net.Conn, tlsConfig *tls.Config, cfg *Config, realityConfig *tlsC.RealityConfig) (net.Conn, error) {
|
2021-03-18 19:40:34 +08:00
|
|
|
dialFn := func(network, addr string) (net.Conn, error) {
|
|
|
|
return conn, nil
|
|
|
|
}
|
|
|
|
|
2023-03-10 10:01:05 +08:00
|
|
|
transport := NewHTTP2Client(dialFn, tlsConfig, cfg.ClientFingerprint, realityConfig)
|
2021-03-18 19:40:34 +08:00
|
|
|
return StreamGunWithTransport(transport, cfg)
|
|
|
|
}
|