mirror of
https://github.com/shtorm-7/sing-box-extended.git
synced 2026-07-08 17:23:20 +03:00
Compare commits
9 Commits
v1.0.6
...
v1.1-beta1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8d044232af | ||
|
|
aa7e85caa7 | ||
|
|
46a8f24400 | ||
|
|
87bc292296 | ||
|
|
ac539ace70 | ||
|
|
a15b13978f | ||
|
|
0c975db0a6 | ||
|
|
cb4fea0240 | ||
|
|
8e7957d440 |
2
.github/workflows/debug.yml
vendored
2
.github/workflows/debug.yml
vendored
@@ -3,7 +3,6 @@ name: Debug build
|
|||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches:
|
branches:
|
||||||
- main
|
|
||||||
- dev
|
- dev
|
||||||
- dev-next
|
- dev-next
|
||||||
paths-ignore:
|
paths-ignore:
|
||||||
@@ -12,7 +11,6 @@ on:
|
|||||||
- '!.github/workflows/debug.yml'
|
- '!.github/workflows/debug.yml'
|
||||||
pull_request:
|
pull_request:
|
||||||
branches:
|
branches:
|
||||||
- main
|
|
||||||
- dev
|
- dev
|
||||||
- dev-next
|
- dev-next
|
||||||
|
|
||||||
|
|||||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -4,5 +4,4 @@
|
|||||||
/*.db
|
/*.db
|
||||||
/site/
|
/site/
|
||||||
/bin/
|
/bin/
|
||||||
/dist/
|
/dist/
|
||||||
/sing-box
|
|
||||||
@@ -38,25 +38,13 @@ type myUpstreamHandlerWrapper struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (w *myUpstreamHandlerWrapper) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error {
|
func (w *myUpstreamHandlerWrapper) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error {
|
||||||
myMetadata := w.metadata
|
w.metadata.Destination = metadata.Destination
|
||||||
if metadata.Source.IsValid() {
|
return w.connectionHandler(ctx, conn, w.metadata)
|
||||||
myMetadata.Source = metadata.Source
|
|
||||||
}
|
|
||||||
if metadata.Destination.IsValid() {
|
|
||||||
myMetadata.Destination = metadata.Destination
|
|
||||||
}
|
|
||||||
return w.connectionHandler(ctx, conn, myMetadata)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (w *myUpstreamHandlerWrapper) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata M.Metadata) error {
|
func (w *myUpstreamHandlerWrapper) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata M.Metadata) error {
|
||||||
myMetadata := w.metadata
|
w.metadata.Destination = metadata.Destination
|
||||||
if metadata.Source.IsValid() {
|
return w.packetHandler(ctx, conn, w.metadata)
|
||||||
myMetadata.Source = metadata.Source
|
|
||||||
}
|
|
||||||
if metadata.Destination.IsValid() {
|
|
||||||
myMetadata.Destination = metadata.Destination
|
|
||||||
}
|
|
||||||
return w.packetHandler(ctx, conn, myMetadata)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (w *myUpstreamHandlerWrapper) NewError(ctx context.Context, err error) {
|
func (w *myUpstreamHandlerWrapper) NewError(ctx context.Context, err error) {
|
||||||
@@ -90,23 +78,13 @@ func NewUpstreamContextHandler(
|
|||||||
|
|
||||||
func (w *myUpstreamContextHandlerWrapper) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error {
|
func (w *myUpstreamContextHandlerWrapper) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error {
|
||||||
myMetadata := ContextFrom(ctx)
|
myMetadata := ContextFrom(ctx)
|
||||||
if metadata.Source.IsValid() {
|
myMetadata.Destination = metadata.Destination
|
||||||
myMetadata.Source = metadata.Source
|
|
||||||
}
|
|
||||||
if metadata.Destination.IsValid() {
|
|
||||||
myMetadata.Destination = metadata.Destination
|
|
||||||
}
|
|
||||||
return w.connectionHandler(ctx, conn, *myMetadata)
|
return w.connectionHandler(ctx, conn, *myMetadata)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (w *myUpstreamContextHandlerWrapper) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata M.Metadata) error {
|
func (w *myUpstreamContextHandlerWrapper) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata M.Metadata) error {
|
||||||
myMetadata := ContextFrom(ctx)
|
myMetadata := ContextFrom(ctx)
|
||||||
if metadata.Source.IsValid() {
|
myMetadata.Destination = metadata.Destination
|
||||||
myMetadata.Source = metadata.Source
|
|
||||||
}
|
|
||||||
if metadata.Destination.IsValid() {
|
|
||||||
myMetadata.Destination = metadata.Destination
|
|
||||||
}
|
|
||||||
return w.packetHandler(ctx, conn, *myMetadata)
|
return w.packetHandler(ctx, conn, *myMetadata)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -112,6 +112,10 @@ func NewDefault(router adapter.Router, options option.DialerOptions) *DefaultDia
|
|||||||
if options.TCPFastOpen {
|
if options.TCPFastOpen {
|
||||||
warnTFOOnUnsupportedPlatform.Check()
|
warnTFOOnUnsupportedPlatform.Check()
|
||||||
}
|
}
|
||||||
|
if !options.UDPFragment {
|
||||||
|
dialer.Control = control.Append(dialer.Control, control.DisableUDPFragment())
|
||||||
|
listener.Control = control.Append(listener.Control, control.DisableUDPFragment())
|
||||||
|
}
|
||||||
var bindUDPAddr string
|
var bindUDPAddr string
|
||||||
udpDialer := dialer
|
udpDialer := dialer
|
||||||
var bindAddress netip.Addr
|
var bindAddress netip.Addr
|
||||||
|
|||||||
128
common/json/comment.go
Normal file
128
common/json/comment.go
Normal file
@@ -0,0 +1,128 @@
|
|||||||
|
package json
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"io"
|
||||||
|
)
|
||||||
|
|
||||||
|
// kanged from v2ray
|
||||||
|
|
||||||
|
type commentFilterState = byte
|
||||||
|
|
||||||
|
const (
|
||||||
|
commentFilterStateContent commentFilterState = iota
|
||||||
|
commentFilterStateEscape
|
||||||
|
commentFilterStateDoubleQuote
|
||||||
|
commentFilterStateDoubleQuoteEscape
|
||||||
|
commentFilterStateSingleQuote
|
||||||
|
commentFilterStateSingleQuoteEscape
|
||||||
|
commentFilterStateComment
|
||||||
|
commentFilterStateSlash
|
||||||
|
commentFilterStateMultilineComment
|
||||||
|
commentFilterStateMultilineCommentStar
|
||||||
|
)
|
||||||
|
|
||||||
|
type CommentFilter struct {
|
||||||
|
br *bufio.Reader
|
||||||
|
state commentFilterState
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewCommentFilter(reader io.Reader) io.Reader {
|
||||||
|
return &CommentFilter{br: bufio.NewReader(reader)}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v *CommentFilter) Read(b []byte) (int, error) {
|
||||||
|
p := b[:0]
|
||||||
|
for len(p) < len(b)-2 {
|
||||||
|
x, err := v.br.ReadByte()
|
||||||
|
if err != nil {
|
||||||
|
if len(p) == 0 {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return len(p), nil
|
||||||
|
}
|
||||||
|
switch v.state {
|
||||||
|
case commentFilterStateContent:
|
||||||
|
switch x {
|
||||||
|
case '"':
|
||||||
|
v.state = commentFilterStateDoubleQuote
|
||||||
|
p = append(p, x)
|
||||||
|
case '\'':
|
||||||
|
v.state = commentFilterStateSingleQuote
|
||||||
|
p = append(p, x)
|
||||||
|
case '\\':
|
||||||
|
v.state = commentFilterStateEscape
|
||||||
|
case '#':
|
||||||
|
v.state = commentFilterStateComment
|
||||||
|
case '/':
|
||||||
|
v.state = commentFilterStateSlash
|
||||||
|
default:
|
||||||
|
p = append(p, x)
|
||||||
|
}
|
||||||
|
case commentFilterStateEscape:
|
||||||
|
p = append(p, '\\', x)
|
||||||
|
v.state = commentFilterStateContent
|
||||||
|
case commentFilterStateDoubleQuote:
|
||||||
|
switch x {
|
||||||
|
case '"':
|
||||||
|
v.state = commentFilterStateContent
|
||||||
|
p = append(p, x)
|
||||||
|
case '\\':
|
||||||
|
v.state = commentFilterStateDoubleQuoteEscape
|
||||||
|
default:
|
||||||
|
p = append(p, x)
|
||||||
|
}
|
||||||
|
case commentFilterStateDoubleQuoteEscape:
|
||||||
|
p = append(p, '\\', x)
|
||||||
|
v.state = commentFilterStateDoubleQuote
|
||||||
|
case commentFilterStateSingleQuote:
|
||||||
|
switch x {
|
||||||
|
case '\'':
|
||||||
|
v.state = commentFilterStateContent
|
||||||
|
p = append(p, x)
|
||||||
|
case '\\':
|
||||||
|
v.state = commentFilterStateSingleQuoteEscape
|
||||||
|
default:
|
||||||
|
p = append(p, x)
|
||||||
|
}
|
||||||
|
case commentFilterStateSingleQuoteEscape:
|
||||||
|
p = append(p, '\\', x)
|
||||||
|
v.state = commentFilterStateSingleQuote
|
||||||
|
case commentFilterStateComment:
|
||||||
|
if x == '\n' {
|
||||||
|
v.state = commentFilterStateContent
|
||||||
|
p = append(p, '\n')
|
||||||
|
}
|
||||||
|
case commentFilterStateSlash:
|
||||||
|
switch x {
|
||||||
|
case '/':
|
||||||
|
v.state = commentFilterStateComment
|
||||||
|
case '*':
|
||||||
|
v.state = commentFilterStateMultilineComment
|
||||||
|
default:
|
||||||
|
p = append(p, '/', x)
|
||||||
|
}
|
||||||
|
case commentFilterStateMultilineComment:
|
||||||
|
switch x {
|
||||||
|
case '*':
|
||||||
|
v.state = commentFilterStateMultilineCommentStar
|
||||||
|
case '\n':
|
||||||
|
p = append(p, '\n')
|
||||||
|
}
|
||||||
|
case commentFilterStateMultilineCommentStar:
|
||||||
|
switch x {
|
||||||
|
case '/':
|
||||||
|
v.state = commentFilterStateContent
|
||||||
|
case '*':
|
||||||
|
// Stay
|
||||||
|
case '\n':
|
||||||
|
p = append(p, '\n')
|
||||||
|
default:
|
||||||
|
v.state = commentFilterStateMultilineComment
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
panic("Unknown state.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return len(p), nil
|
||||||
|
}
|
||||||
@@ -13,6 +13,7 @@ import (
|
|||||||
|
|
||||||
type Listener struct {
|
type Listener struct {
|
||||||
net.Listener
|
net.Listener
|
||||||
|
AcceptNoHeader bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *Listener) Accept() (net.Conn, error) {
|
func (l *Listener) Accept() (net.Conn, error) {
|
||||||
@@ -22,7 +23,7 @@ func (l *Listener) Accept() (net.Conn, error) {
|
|||||||
}
|
}
|
||||||
bufReader := std_bufio.NewReader(conn)
|
bufReader := std_bufio.NewReader(conn)
|
||||||
header, err := proxyproto.Read(bufReader)
|
header, err := proxyproto.Read(bufReader)
|
||||||
if err != nil {
|
if err != nil && !(l.AcceptNoHeader && err == proxyproto.ErrNoProxyProtocol) {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if bufReader.Buffered() > 0 {
|
if bufReader.Buffered() > 0 {
|
||||||
@@ -33,8 +34,11 @@ func (l *Listener) Accept() (net.Conn, error) {
|
|||||||
}
|
}
|
||||||
conn = bufio.NewCachedConn(conn, cache)
|
conn = bufio.NewCachedConn(conn, cache)
|
||||||
}
|
}
|
||||||
return &bufio.AddrConn{Conn: conn, Metadata: M.Metadata{
|
if header != nil {
|
||||||
Source: M.SocksaddrFromNet(header.SourceAddr),
|
return &bufio.AddrConn{Conn: conn, Metadata: M.Metadata{
|
||||||
Destination: M.SocksaddrFromNet(header.DestinationAddr),
|
Source: M.SocksaddrFromNet(header.SourceAddr),
|
||||||
}}, nil
|
Destination: M.SocksaddrFromNet(header.DestinationAddr),
|
||||||
|
}}, nil
|
||||||
|
}
|
||||||
|
return conn, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ type systemProxy struct {
|
|||||||
isMixed bool
|
isMixed bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *systemProxy) update() error {
|
func (p *systemProxy) update(event int) error {
|
||||||
newInterfaceName := p.monitor.DefaultInterfaceName(netip.IPv4Unspecified())
|
newInterfaceName := p.monitor.DefaultInterfaceName(netip.IPv4Unspecified())
|
||||||
if p.interfaceName == newInterfaceName {
|
if p.interfaceName == newInterfaceName {
|
||||||
return nil
|
return nil
|
||||||
@@ -88,7 +88,7 @@ func SetSystemProxy(router adapter.Router, port uint16, isMixed bool) (func() er
|
|||||||
port: port,
|
port: port,
|
||||||
isMixed: isMixed,
|
isMixed: isMixed,
|
||||||
}
|
}
|
||||||
err := proxy.update()
|
err := proxy.update(tun.EventInterfaceUpdate)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,7 +24,8 @@ func QUICClientHello(ctx context.Context, packet []byte) (*adapter.InboundContex
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if typeByte&0x40 == 0 {
|
|
||||||
|
if typeByte&0x80 == 0 || typeByte&0x40 == 0 {
|
||||||
return nil, E.New("bad type byte")
|
return nil, E.New("bad type byte")
|
||||||
}
|
}
|
||||||
var versionNumber uint32
|
var versionNumber uint32
|
||||||
@@ -144,6 +145,9 @@ func QUICClientHello(ctx context.Context, packet []byte) (*adapter.InboundContex
|
|||||||
default:
|
default:
|
||||||
return nil, E.New("bad packet number length")
|
return nil, E.New("bad packet number length")
|
||||||
}
|
}
|
||||||
|
if packetNumber != 0 {
|
||||||
|
return nil, E.New("bad packet number: ", packetNumber)
|
||||||
|
}
|
||||||
extHdrLen := hdrLen + int(packetNumberLength)
|
extHdrLen := hdrLen + int(packetNumberLength)
|
||||||
copy(newPacket[extHdrLen:hdrLen+4], packet[extHdrLen:])
|
copy(newPacket[extHdrLen:hdrLen+4], packet[extHdrLen:])
|
||||||
data := newPacket[extHdrLen : int(packetLen)+hdrLen]
|
data := newPacket[extHdrLen : int(packetLen)+hdrLen]
|
||||||
@@ -168,76 +172,37 @@ func QUICClientHello(ctx context.Context, packet []byte) (*adapter.InboundContex
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
var frameType byte
|
|
||||||
var frameLen uint64
|
|
||||||
var fragments []struct {
|
|
||||||
offset uint64
|
|
||||||
length uint64
|
|
||||||
payload []byte
|
|
||||||
}
|
|
||||||
decryptedReader := bytes.NewReader(decrypted)
|
decryptedReader := bytes.NewReader(decrypted)
|
||||||
for {
|
frameType, err := decryptedReader.ReadByte()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
for frameType == 0x0 {
|
||||||
|
// skip padding
|
||||||
frameType, err = decryptedReader.ReadByte()
|
frameType, err = decryptedReader.ReadByte()
|
||||||
if err == io.EOF {
|
if err != nil {
|
||||||
break
|
return nil, err
|
||||||
}
|
|
||||||
switch frameType {
|
|
||||||
case 0x0:
|
|
||||||
continue
|
|
||||||
case 0x1:
|
|
||||||
continue
|
|
||||||
case 0x6:
|
|
||||||
var offset uint64
|
|
||||||
offset, err = qtls.ReadUvarint(decryptedReader)
|
|
||||||
if err != nil {
|
|
||||||
return &adapter.InboundContext{Protocol: C.ProtocolQUIC}, err
|
|
||||||
}
|
|
||||||
var length uint64
|
|
||||||
length, err = qtls.ReadUvarint(decryptedReader)
|
|
||||||
if err != nil {
|
|
||||||
return &adapter.InboundContext{Protocol: C.ProtocolQUIC}, err
|
|
||||||
}
|
|
||||||
index := len(decrypted) - decryptedReader.Len()
|
|
||||||
fragments = append(fragments, struct {
|
|
||||||
offset uint64
|
|
||||||
length uint64
|
|
||||||
payload []byte
|
|
||||||
}{offset, length, decrypted[index : index+int(length)]})
|
|
||||||
frameLen += length
|
|
||||||
_, err = decryptedReader.Seek(int64(length), io.SeekCurrent)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
// ignore unknown frame type
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if frameType != 0x6 {
|
||||||
|
// not crypto frame
|
||||||
|
return &adapter.InboundContext{Protocol: C.ProtocolQUIC}, nil
|
||||||
|
}
|
||||||
|
_, err = qtls.ReadUvarint(decryptedReader)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
_, err = qtls.ReadUvarint(decryptedReader)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
tlsHdr := make([]byte, 5)
|
tlsHdr := make([]byte, 5)
|
||||||
tlsHdr[0] = 0x16
|
tlsHdr[0] = 0x16
|
||||||
binary.BigEndian.PutUint16(tlsHdr[1:], uint16(0x0303))
|
binary.BigEndian.PutUint16(tlsHdr[1:], uint16(0x0303))
|
||||||
binary.BigEndian.PutUint16(tlsHdr[3:], uint16(frameLen))
|
binary.BigEndian.PutUint16(tlsHdr[3:], uint16(decryptedReader.Len()))
|
||||||
var index uint64
|
metadata, err := TLSClientHello(ctx, io.MultiReader(bytes.NewReader(tlsHdr), decryptedReader))
|
||||||
var length int
|
|
||||||
var readers []io.Reader
|
|
||||||
readers = append(readers, bytes.NewReader(tlsHdr))
|
|
||||||
find:
|
|
||||||
for {
|
|
||||||
for _, fragment := range fragments {
|
|
||||||
if fragment.offset == index {
|
|
||||||
readers = append(readers, bytes.NewReader(fragment.payload))
|
|
||||||
index = fragment.offset + fragment.length
|
|
||||||
length++
|
|
||||||
continue find
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if length == len(fragments) {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
return &adapter.InboundContext{Protocol: C.ProtocolQUIC}, E.New("bad fragments")
|
|
||||||
}
|
|
||||||
metadata, err := TLSClientHello(ctx, io.MultiReader(readers...))
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return &adapter.InboundContext{Protocol: C.ProtocolQUIC}, err
|
return nil, err
|
||||||
}
|
}
|
||||||
metadata.Protocol = C.ProtocolQUIC
|
metadata.Protocol = C.ProtocolQUIC
|
||||||
return metadata, nil
|
return metadata, nil
|
||||||
|
|||||||
@@ -19,15 +19,6 @@ func TestSniffQUICv1(t *testing.T) {
|
|||||||
require.Equal(t, metadata.Domain, "cloudflare-quic.com")
|
require.Equal(t, metadata.Domain, "cloudflare-quic.com")
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSniffQUICFragment(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
pkt, err := hex.DecodeString("cc00000001082e3d5d1b64040c55000044d0ccea69e773f6631c1d18b04ae9ee75fcfc34ef74fa62533c93534338a86f101a05d70e0697fb483063fa85db1c59ccfbda5c35234931d8524d8aac37eaaad649470a67794cd754b23c98695238b8363452333bc8c4858376b4166e001da2006e35cf98a91e11a56419b2786775284942d0f7163982f7c248867d12dd374957481dbc564013ff785e1916195eef671f725908f761099d992d69231336ba81d9e25fe2fa3a6eff4318a6ccf10176fc841a1b315f7b35c5b292266fc869d76ca533e7d14e86d82db2e22eacd350977e47d2e012d8a5891c5aaf2a0f4c2b2dae897c161e5b68cbb4dee952472bdc1e21504b8f02534ec4366ce3f8bf86efc78e0232778fbd554457567112abdcafcf6d4d8fcf35083c25d9495679614aba21696e338c62b585046cc55ba8c09c844361d889a47c3ea703b4e23545a9ab2c0bb369693a9ddfb5daffa85cf80fdd6ad66738664e5b0a551729b4955cff7255afcb04dee88c2f072c9de7400947a1bd9327ac5d012a33000ada021d4c03d249fb017d6ac9200b2f9436beab8183ddfbe2d8aee31ffb7df9e1cc181c1af80c39a89965d18ed12da8e3ebe2ae1fbe4b348f83ba19e3e3d1c9b22bcf03ab6ad9b30fe180623faa291ebad83bcd71d7b57f2f5e2f3b8e81d24fb70b2f2159239e8f21ffafef2747aba47d97ab4081e603c018b10678cf99cab1fb42156a14486fa435153979d7279fd22cd40af7088bfc7eff41af2f4b3c0c8864d0040d74dff427f7bffdb8c278474ea00311326cf4925471a8cf596cb92119f19e0f789490ba9cb77b98015a987d93e0324cf1a38b55109f00c3e6ddc5180fb107bf468323afec9bb49fd6a86418569789d66cafe3b8253c2aebb3af3782c1c54dd560487d031d28e6a6e23e159581bb1d47efc4da3fe1d169f9ffb0ca9ba61af0a38a92fde5bc5e6ec026e8378a6315a7b95abf1d2da790a391306ce74d0baf8e2ce648ca74c487f2c0a76a28a80cdf5bd34316eb607684fe7e6d9e83824a00e07660d0b90e3cddd61ebf10748263474afa88c300549e64ce2e90560bb1a12dee7e9484f729a8a4ee7c5651adb5194b3b3ae38e501567c7dbf36e7bb37a2c20b74655f47f2d9af18e52e9d4c9c9eee8e63745779b8f0b06f3a09d846ba62eb978ad77c85de1ee2fee3fbb4c2d283c73e1ccba56a4658e48a2665d200f7f9342f8e84c2ba490094a4f94feec89e42d2f654f564c2beb2997bafa1fc2c68ad8e160b63587d49abc31b834878d52acfb05fb73d0e059b206162e3c90b40c4bc08407ffcb3c08431895b691a3fea923f1f3b48db75d3e6b91fd319ffe4d486e0e14bd5c6affc838dee63d9e0b80f169b5e6c02c7321dcb20deb2b8e707b60e345a308d505bbf26a93d8f18b39d62632e9a77cbe48b3b32eb8819d6311a49820d40f5acbf0273c91c36b2269a03e72ee64df3dfb10ddefe73c64ef60870b2b77bd99dea655f5fe791b538a929a14d99f6d69685d72431ea5f0f4b27a044f2f575ab474fcc3857895934de1ca2581798eaef2c17fe5aaf2e6add97fa32997c7026f15c1b1ad0e6043ae506027a7c0242546fdc851cca39a204e56879f2cef838be8ec66e0f2292f8c862e06f810eb9b80c7a467ce6e90155206352c7f82b1173ba3b98d35bb72c259a60db20dd1a43fe6d7aef0265e6eaa5caafd9b64b448ff745a2046acbdb65cf2a5007809808a4828dc99097feedc734c236260c584")
|
|
||||||
require.NoError(t, err)
|
|
||||||
metadata, err := sniff.QUICClientHello(context.Background(), pkt)
|
|
||||||
require.NoError(t, err)
|
|
||||||
require.Equal(t, metadata.Domain, "cloudflare-quic.com")
|
|
||||||
}
|
|
||||||
|
|
||||||
func FuzzSniffQUIC(f *testing.F) {
|
func FuzzSniffQUIC(f *testing.F) {
|
||||||
f.Fuzz(func(t *testing.T, data []byte) {
|
f.Fuzz(func(t *testing.T, data []byte) {
|
||||||
sniff.QUICClientHello(context.Background(), data)
|
sniff.QUICClientHello(context.Background(), data)
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
|
"os"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/sagernet/sing-box/adapter"
|
"github.com/sagernet/sing-box/adapter"
|
||||||
@@ -29,25 +30,23 @@ func PeekStream(ctx context.Context, conn net.Conn, buffer *buf.Buffer, sniffers
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
var metadata *adapter.InboundContext
|
var metadata *adapter.InboundContext
|
||||||
var errors []error
|
|
||||||
for _, sniffer := range sniffers {
|
for _, sniffer := range sniffers {
|
||||||
metadata, err = sniffer(ctx, bytes.NewReader(buffer.Bytes()))
|
metadata, err = sniffer(ctx, bytes.NewReader(buffer.Bytes()))
|
||||||
if metadata != nil {
|
if err != nil {
|
||||||
return metadata, nil
|
continue
|
||||||
}
|
}
|
||||||
errors = append(errors, err)
|
return metadata, nil
|
||||||
}
|
}
|
||||||
return nil, E.Errors(errors...)
|
return nil, os.ErrInvalid
|
||||||
}
|
}
|
||||||
|
|
||||||
func PeekPacket(ctx context.Context, packet []byte, sniffers ...PacketSniffer) (*adapter.InboundContext, error) {
|
func PeekPacket(ctx context.Context, packet []byte, sniffers ...PacketSniffer) (*adapter.InboundContext, error) {
|
||||||
var errors []error
|
|
||||||
for _, sniffer := range sniffers {
|
for _, sniffer := range sniffers {
|
||||||
metadata, err := sniffer(ctx, packet)
|
sniffMetadata, err := sniffer(ctx, packet)
|
||||||
if metadata != nil {
|
if err != nil {
|
||||||
return metadata, nil
|
continue
|
||||||
}
|
}
|
||||||
errors = append(errors, err)
|
return sniffMetadata, nil
|
||||||
}
|
}
|
||||||
return nil, E.Errors(errors...)
|
return nil, os.ErrInvalid
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
package constant
|
package constant
|
||||||
|
|
||||||
var (
|
var (
|
||||||
Version = "1.0.6"
|
Version = "1.1-beta1"
|
||||||
Commit = ""
|
Commit = ""
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,3 +1,46 @@
|
|||||||
|
#### 1.1-beta1
|
||||||
|
|
||||||
|
* Add support for use with android VPNService **1**
|
||||||
|
* Add tun support for WireGuard outbound **2**
|
||||||
|
* Add system tun stack **3**
|
||||||
|
* Add comment filter for config **4**
|
||||||
|
* Add option for allow optional proxy protocol header
|
||||||
|
* Add half close for smux
|
||||||
|
* Set UDP DF by default **5**
|
||||||
|
* Set default tun mtu to 9000
|
||||||
|
* Update gVisor to 20220905.0
|
||||||
|
|
||||||
|
*1*:
|
||||||
|
|
||||||
|
In previous versions, Android VPN would not work with tun enabled.
|
||||||
|
|
||||||
|
The usage of tun over VPN and VPN over tun is now supported, see [Tun Inbound](/configuration/inbound/tun#auto_route).
|
||||||
|
|
||||||
|
*2*:
|
||||||
|
|
||||||
|
In previous releases, WireGuard outbound support was backed by the lower performance gVisor virtual interface.
|
||||||
|
|
||||||
|
It achieves the same performance as wireguard-go by providing automatic system interface support.
|
||||||
|
|
||||||
|
*3*:
|
||||||
|
|
||||||
|
It does not depend on gVisor and has better performance in some cases.
|
||||||
|
|
||||||
|
It is less compatible and may not be available in some environments.
|
||||||
|
|
||||||
|
*4*:
|
||||||
|
|
||||||
|
Annotated json configuration files are now supported.
|
||||||
|
|
||||||
|
*5*:
|
||||||
|
|
||||||
|
UDP fragmentation is now blocked by default.
|
||||||
|
|
||||||
|
Including shadowsocks-libev, shadowsocks-rust and quic-go all disable segmentation by default.
|
||||||
|
|
||||||
|
See [Dial Fields](/configuration/shared/dial#udp_fragment)
|
||||||
|
and [Listen Fields](/configuration/shared/listen#udp_fragment).
|
||||||
|
|
||||||
#### 1.0.1
|
#### 1.0.1
|
||||||
|
|
||||||
* Fix match 4in6 address in ip_cidr
|
* Fix match 4in6 address in ip_cidr
|
||||||
|
|||||||
@@ -12,7 +12,7 @@
|
|||||||
"interface_name": "tun0",
|
"interface_name": "tun0",
|
||||||
"inet4_address": "172.19.0.1/30",
|
"inet4_address": "172.19.0.1/30",
|
||||||
"inet6_address": "fdfe:dcba:9876::1/128",
|
"inet6_address": "fdfe:dcba:9876::1/128",
|
||||||
"mtu": 1500,
|
"mtu": 9000,
|
||||||
"auto_route": true,
|
"auto_route": true,
|
||||||
"strict_route": true,
|
"strict_route": true,
|
||||||
"endpoint_independent_nat": false,
|
"endpoint_independent_nat": false,
|
||||||
@@ -80,6 +80,10 @@ Set the default route to the Tun.
|
|||||||
|
|
||||||
To avoid traffic loopback, set `route.auto_detect_interface` or `route.default_interface` or `outbound.bind_interface`
|
To avoid traffic loopback, set `route.auto_detect_interface` or `route.default_interface` or `outbound.bind_interface`
|
||||||
|
|
||||||
|
!!! note "Use with Android VPN"
|
||||||
|
|
||||||
|
By default, VPN takes precedence over tun. To make tun go through VPN, enable `route.override_android_vpn`.
|
||||||
|
|
||||||
#### strict_route
|
#### strict_route
|
||||||
|
|
||||||
Enforce strict routing rules in Linux when `auto_route` is enabled:
|
Enforce strict routing rules in Linux when `auto_route` is enabled:
|
||||||
@@ -92,6 +96,10 @@ not be accessible by others.
|
|||||||
|
|
||||||
#### endpoint_independent_nat
|
#### endpoint_independent_nat
|
||||||
|
|
||||||
|
!!! info ""
|
||||||
|
|
||||||
|
This item is only available on the gvisor stack, other stacks are endpoint-independent NAT by default.
|
||||||
|
|
||||||
Enable endpoint-independent NAT.
|
Enable endpoint-independent NAT.
|
||||||
|
|
||||||
Performance may degrade slightly, so it is not recommended to enable on when it is not needed.
|
Performance may degrade slightly, so it is not recommended to enable on when it is not needed.
|
||||||
@@ -104,10 +112,11 @@ UDP NAT expiration time in seconds, default is 300 (5 minutes).
|
|||||||
|
|
||||||
TCP/IP stack.
|
TCP/IP stack.
|
||||||
|
|
||||||
| Stack | Upstream | Status |
|
| Stack | Description | Status |
|
||||||
|------------------|-----------------------------------------------------------------------|-------------------|
|
|------------------|--------------------------------------------------------------------------------|-------------------|
|
||||||
| gVisor (default) | [google/gvisor](https://github.com/google/gvisor) | recommended |
|
| gVisor (default) | Based on [google/gvisor](https://github.com/google/gvisor) | recommended |
|
||||||
| LWIP | [eycorsican/go-tun2socks](https://github.com/eycorsican/go-tun2socks) | upstream archived |
|
| system | Less compatibility and sometimes better performance. | recommended |
|
||||||
|
| LWIP | Based on [eycorsican/go-tun2socks](https://github.com/eycorsican/go-tun2socks) | upstream archived |
|
||||||
|
|
||||||
!!! warning ""
|
!!! warning ""
|
||||||
|
|
||||||
|
|||||||
@@ -12,7 +12,7 @@
|
|||||||
"interface_name": "tun0",
|
"interface_name": "tun0",
|
||||||
"inet4_address": "172.19.0.1/30",
|
"inet4_address": "172.19.0.1/30",
|
||||||
"inet6_address": "fdfe:dcba:9876::1/128",
|
"inet6_address": "fdfe:dcba:9876::1/128",
|
||||||
"mtu": 1500,
|
"mtu": 9000,
|
||||||
"auto_route": true,
|
"auto_route": true,
|
||||||
"strict_route": true,
|
"strict_route": true,
|
||||||
"endpoint_independent_nat": false,
|
"endpoint_independent_nat": false,
|
||||||
@@ -80,6 +80,10 @@ tun 接口的 IPv6 前缀。
|
|||||||
|
|
||||||
为避免流量环回,请设置 `route.auto_detect_interface` 或 `route.default_interface` 或 `outbound.bind_interface`。
|
为避免流量环回,请设置 `route.auto_detect_interface` 或 `route.default_interface` 或 `outbound.bind_interface`。
|
||||||
|
|
||||||
|
!!! note "与 Android VPN 一起使用"
|
||||||
|
|
||||||
|
VPN 默认优先于 tun。要使 tun 经过 VPN,启用 `route.override_android_vpn`。
|
||||||
|
|
||||||
#### strict_route
|
#### strict_route
|
||||||
|
|
||||||
在 Linux 中启用 `auto_route` 时执行严格的路由规则。
|
在 Linux 中启用 `auto_route` 时执行严格的路由规则。
|
||||||
@@ -103,10 +107,11 @@ UDP NAT 过期时间,以秒为单位,默认为 300(5 分钟)。
|
|||||||
|
|
||||||
TCP/IP 栈。
|
TCP/IP 栈。
|
||||||
|
|
||||||
| 栈 | 上游 | 状态 |
|
| 栈 | 描述 | 状态 |
|
||||||
|------------------|-----------------------------------------------------------------------|-------|
|
|------------------|--------------------------------------------------------------------------|-------|
|
||||||
| gVisor (default) | [google/gvisor](https://github.com/google/gvisor) | 推荐 |
|
| gVisor (default) | 基于 [google/gvisor](https://github.com/google/gvisor) | 推荐 |
|
||||||
| LWIP | [eycorsican/go-tun2socks](https://github.com/eycorsican/go-tun2socks) | 上游已存档 |
|
| system | 兼容性较差,有时性能更好。 | 推荐 |
|
||||||
|
| LWIP | 基于 [eycorsican/go-tun2socks](https://github.com/eycorsican/go-tun2socks) | 上游已存档 |
|
||||||
|
|
||||||
!!! warning ""
|
!!! warning ""
|
||||||
|
|
||||||
|
|||||||
@@ -7,8 +7,9 @@
|
|||||||
|
|
||||||
"server": "127.0.0.1",
|
"server": "127.0.0.1",
|
||||||
"server_port": 1080,
|
"server_port": 1080,
|
||||||
|
"system_interface": false,
|
||||||
|
"interface_name": "wg0",
|
||||||
"local_address": [
|
"local_address": [
|
||||||
"10.0.0.1",
|
|
||||||
"10.0.0.2/32"
|
"10.0.0.2/32"
|
||||||
],
|
],
|
||||||
"private_key": "YNXtAzepDqRv9H52osJVDQnznT5AM11eCK3ESpwSt04=",
|
"private_key": "YNXtAzepDqRv9H52osJVDQnznT5AM11eCK3ESpwSt04=",
|
||||||
@@ -39,11 +40,21 @@ The server address.
|
|||||||
|
|
||||||
The server port.
|
The server port.
|
||||||
|
|
||||||
|
#### system_interface
|
||||||
|
|
||||||
|
Use system tun support.
|
||||||
|
|
||||||
|
Requires privileges and cannot conflict with system interfaces.
|
||||||
|
|
||||||
|
#### interface_name
|
||||||
|
|
||||||
|
Custom device name when `system_interface` enabled.
|
||||||
|
|
||||||
#### local_address
|
#### local_address
|
||||||
|
|
||||||
==Required==
|
==Required==
|
||||||
|
|
||||||
List of IP (v4 or v6) addresses (optionally with CIDR masks) to be assigned to the interface.
|
List of IP (v4 or v6) address prefixes to be assigned to the interface.
|
||||||
|
|
||||||
#### private_key
|
#### private_key
|
||||||
|
|
||||||
|
|||||||
@@ -7,8 +7,9 @@
|
|||||||
|
|
||||||
"server": "127.0.0.1",
|
"server": "127.0.0.1",
|
||||||
"server_port": 1080,
|
"server_port": 1080,
|
||||||
|
"system_interface": false,
|
||||||
|
"interface_name": "wg0",
|
||||||
"local_address": [
|
"local_address": [
|
||||||
"10.0.0.1",
|
|
||||||
"10.0.0.2/32"
|
"10.0.0.2/32"
|
||||||
],
|
],
|
||||||
"private_key": "YNXtAzepDqRv9H52osJVDQnznT5AM11eCK3ESpwSt04=",
|
"private_key": "YNXtAzepDqRv9H52osJVDQnznT5AM11eCK3ESpwSt04=",
|
||||||
@@ -39,13 +40,23 @@
|
|||||||
|
|
||||||
服务器端口。
|
服务器端口。
|
||||||
|
|
||||||
|
#### system_interface
|
||||||
|
|
||||||
|
使用系统 tun 支持。
|
||||||
|
|
||||||
|
需要特权且不能与系统接口冲突。
|
||||||
|
|
||||||
|
#### interface_name
|
||||||
|
|
||||||
|
启用 `system_interface` 时的自定义设备名称。
|
||||||
|
|
||||||
#### local_address
|
#### local_address
|
||||||
|
|
||||||
==必填==
|
==必填==
|
||||||
|
|
||||||
接口的 IPv4/IPv6 地址或地址段的列表您。
|
接口的 IPv4/IPv6 地址或地址段的列表您。
|
||||||
|
|
||||||
要分配给接口的 IP(v4 或 v6)地址列表(可以选择带有 CIDR 掩码)。
|
要分配给接口的 IP(v4 或 v6)地址段列表。
|
||||||
|
|
||||||
#### private_key
|
#### private_key
|
||||||
|
|
||||||
|
|||||||
@@ -10,6 +10,7 @@
|
|||||||
"rules": [],
|
"rules": [],
|
||||||
"final": "",
|
"final": "",
|
||||||
"auto_detect_interface": false,
|
"auto_detect_interface": false,
|
||||||
|
"override_android_vpn": false,
|
||||||
"default_interface": "en0",
|
"default_interface": "en0",
|
||||||
"default_mark": 233
|
"default_mark": 233
|
||||||
}
|
}
|
||||||
@@ -34,17 +35,25 @@ Default outbound tag. the first outbound will be used if empty.
|
|||||||
|
|
||||||
Only supported on Linux, Windows and macOS.
|
Only supported on Linux, Windows and macOS.
|
||||||
|
|
||||||
Bind outbound connections to the default NIC by default to prevent routing loops under Tun.
|
Bind outbound connections to the default NIC by default to prevent routing loops under tun.
|
||||||
|
|
||||||
Takes no effect if `outbound.bind_interface` is set.
|
Takes no effect if `outbound.bind_interface` is set.
|
||||||
|
|
||||||
|
#### override_android_vpn
|
||||||
|
|
||||||
|
!!! error ""
|
||||||
|
|
||||||
|
Only supported on Android.
|
||||||
|
|
||||||
|
Accept Android VPN as upstream NIC when `auto_detect_interface` enabled.
|
||||||
|
|
||||||
#### default_interface
|
#### default_interface
|
||||||
|
|
||||||
!!! error ""
|
!!! error ""
|
||||||
|
|
||||||
Only supported on Linux, Windows and macOS.
|
Only supported on Linux, Windows and macOS.
|
||||||
|
|
||||||
Bind outbound connections to the specified NIC by default to prevent routing loops under Tun.
|
Bind outbound connections to the specified NIC by default to prevent routing loops under tun.
|
||||||
|
|
||||||
Takes no effect if `auto_detect_interface` is set.
|
Takes no effect if `auto_detect_interface` is set.
|
||||||
|
|
||||||
|
|||||||
@@ -10,6 +10,7 @@
|
|||||||
"rules": [],
|
"rules": [],
|
||||||
"final": "",
|
"final": "",
|
||||||
"auto_detect_interface": false,
|
"auto_detect_interface": false,
|
||||||
|
"override_android_vpn": false,
|
||||||
"default_interface": "en0",
|
"default_interface": "en0",
|
||||||
"default_mark": 233
|
"default_mark": 233
|
||||||
}
|
}
|
||||||
@@ -34,17 +35,25 @@
|
|||||||
|
|
||||||
仅支持 Linux、Windows 和 macOS。
|
仅支持 Linux、Windows 和 macOS。
|
||||||
|
|
||||||
默认将出站连接绑定到默认网卡,以防止在 Tun 下出现路由环路。
|
默认将出站连接绑定到默认网卡,以防止在 tun 下出现路由环路。
|
||||||
|
|
||||||
如果设置了 `outbound.bind_interface` 设置,则不生效。
|
如果设置了 `outbound.bind_interface` 设置,则不生效。
|
||||||
|
|
||||||
|
#### override_android_vpn
|
||||||
|
|
||||||
|
!!! error ""
|
||||||
|
|
||||||
|
仅支持 Android。
|
||||||
|
|
||||||
|
启用 `auto_detect_interface` 时接受 Android VPN 作为上游网卡。
|
||||||
|
|
||||||
#### default_interface
|
#### default_interface
|
||||||
|
|
||||||
!!! error ""
|
!!! error ""
|
||||||
|
|
||||||
仅支持 Linux、Windows 和 macOS。
|
仅支持 Linux、Windows 和 macOS。
|
||||||
|
|
||||||
默认将出站连接绑定到指定网卡,以防止在 Tun 下出现路由环路。
|
默认将出站连接绑定到指定网卡,以防止在 tun 下出现路由环路。
|
||||||
|
|
||||||
如果设置了 `auto_detect_interface` 设置,则不生效。
|
如果设置了 `auto_detect_interface` 设置,则不生效。
|
||||||
|
|
||||||
|
|||||||
@@ -9,6 +9,7 @@
|
|||||||
"reuse_addr": false,
|
"reuse_addr": false,
|
||||||
"connect_timeout": "5s",
|
"connect_timeout": "5s",
|
||||||
"tcp_fast_open": false,
|
"tcp_fast_open": false,
|
||||||
|
"udp_fragment": false,
|
||||||
"domain_strategy": "prefer_ipv6",
|
"domain_strategy": "prefer_ipv6",
|
||||||
"fallback_delay": "300ms"
|
"fallback_delay": "300ms"
|
||||||
}
|
}
|
||||||
@@ -16,9 +17,9 @@
|
|||||||
|
|
||||||
### Fields
|
### Fields
|
||||||
|
|
||||||
| Field | Available Context |
|
| Field | Available Context |
|
||||||
|-----------------------------------------------------------------------------------|-------------------|
|
|---------------------------------------------------------------------------------------------------------------------|-------------------|
|
||||||
| `bind_interface` /`bind_address` /`routing_mark` /`reuse_addr` /`connect_timeout` | `detour` not set |
|
| `bind_interface` /`bind_address` /`routing_mark` /`reuse_addr` / `tcp_fast_open`/ `udp_fragment` /`connect_timeout` | `detour` not set |
|
||||||
|
|
||||||
#### detour
|
#### detour
|
||||||
|
|
||||||
@@ -44,6 +45,14 @@ Set netfilter routing mark.
|
|||||||
|
|
||||||
Reuse listener address.
|
Reuse listener address.
|
||||||
|
|
||||||
|
#### tcp_fast_open
|
||||||
|
|
||||||
|
Enable TCP Fast Open.
|
||||||
|
|
||||||
|
#### udp_fragment
|
||||||
|
|
||||||
|
Enable UDP fragmentation.
|
||||||
|
|
||||||
#### connect_timeout
|
#### connect_timeout
|
||||||
|
|
||||||
Connect timeout, in golang's Duration format.
|
Connect timeout, in golang's Duration format.
|
||||||
|
|||||||
@@ -9,6 +9,7 @@
|
|||||||
"reuse_addr": false,
|
"reuse_addr": false,
|
||||||
"connect_timeout": "5s",
|
"connect_timeout": "5s",
|
||||||
"tcp_fast_open": false,
|
"tcp_fast_open": false,
|
||||||
|
"udp_fragment": false,
|
||||||
"domain_strategy": "prefer_ipv6",
|
"domain_strategy": "prefer_ipv6",
|
||||||
"fallback_delay": "300ms"
|
"fallback_delay": "300ms"
|
||||||
}
|
}
|
||||||
@@ -16,6 +17,11 @@
|
|||||||
|
|
||||||
### 字段
|
### 字段
|
||||||
|
|
||||||
|
| 字段 | 可用上下文 |
|
||||||
|
|---------------------------------------------------------------------------------------------------------------------|--------------|
|
||||||
|
| `bind_interface` /`bind_address` /`routing_mark` /`reuse_addr` / `tcp_fast_open`/ `udp_fragment` /`connect_timeout` | `detour` 未设置 |
|
||||||
|
|
||||||
|
|
||||||
#### detour
|
#### detour
|
||||||
|
|
||||||
上游出站的标签。
|
上游出站的标签。
|
||||||
@@ -42,6 +48,14 @@
|
|||||||
|
|
||||||
重用监听地址。
|
重用监听地址。
|
||||||
|
|
||||||
|
#### tcp_fast_open
|
||||||
|
|
||||||
|
启用 TCP Fast Open。
|
||||||
|
|
||||||
|
#### udp_fragment
|
||||||
|
|
||||||
|
启用 UDP 分段。
|
||||||
|
|
||||||
#### connect_timeout
|
#### connect_timeout
|
||||||
|
|
||||||
连接超时,采用 golang 的 Duration 格式。
|
连接超时,采用 golang 的 Duration 格式。
|
||||||
|
|||||||
@@ -5,24 +5,27 @@
|
|||||||
"listen": "::",
|
"listen": "::",
|
||||||
"listen_port": 5353,
|
"listen_port": 5353,
|
||||||
"tcp_fast_open": false,
|
"tcp_fast_open": false,
|
||||||
|
"udp_fragment": false,
|
||||||
"sniff": false,
|
"sniff": false,
|
||||||
"sniff_override_destination": false,
|
"sniff_override_destination": false,
|
||||||
"domain_strategy": "prefer_ipv6",
|
"domain_strategy": "prefer_ipv6",
|
||||||
"udp_timeout": 300,
|
"udp_timeout": 300,
|
||||||
"proxy_protocol": false,
|
"proxy_protocol": false,
|
||||||
|
"proxy_protocol_accept_no_header": false,
|
||||||
"detour": "another-in"
|
"detour": "another-in"
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### Fields
|
### Fields
|
||||||
|
|
||||||
| Field | Available Context |
|
| Field | Available Context |
|
||||||
|------------------|-------------------------------------------------------------------|
|
|-----------------------------------|-------------------------------------------------------------------|
|
||||||
| `listen` | Needs to listen on TCP or UDP. |
|
| `listen` | Needs to listen on TCP or UDP. |
|
||||||
| `listen_port` | Needs to listen on TCP or UDP. |
|
| `listen_port` | Needs to listen on TCP or UDP. |
|
||||||
| `tcp_fast_open` | Needs to listen on TCP. |
|
| `tcp_fast_open` | Needs to listen on TCP. |
|
||||||
| `udp_timeout` | Needs to assemble UDP connections, currently Tun and Shadowsocks. |
|
| `udp_timeout` | Needs to assemble UDP connections, currently Tun and Shadowsocks. |
|
||||||
| `proxy_protocol` | Needs to listen on TCP. |
|
| `proxy_protocol` | Needs to listen on TCP. |
|
||||||
|
| `proxy_protocol_accept_no_header` | When `proxy_protocol` enabled |
|
||||||
|
|
||||||
#### listen
|
#### listen
|
||||||
|
|
||||||
@@ -36,7 +39,11 @@ Listen port.
|
|||||||
|
|
||||||
#### tcp_fast_open
|
#### tcp_fast_open
|
||||||
|
|
||||||
Enable tcp fast open for listener.
|
Enable TCP Fast Open.
|
||||||
|
|
||||||
|
#### udp_fragment
|
||||||
|
|
||||||
|
Enable UDP fragmentation.
|
||||||
|
|
||||||
#### sniff
|
#### sniff
|
||||||
|
|
||||||
@@ -66,6 +73,10 @@ UDP NAT expiration time in seconds, default is 300 (5 minutes).
|
|||||||
|
|
||||||
Parse [Proxy Protocol](https://www.haproxy.org/download/1.8/doc/proxy-protocol.txt) in the connection header.
|
Parse [Proxy Protocol](https://www.haproxy.org/download/1.8/doc/proxy-protocol.txt) in the connection header.
|
||||||
|
|
||||||
|
#### proxy_protocol_accept_no_header
|
||||||
|
|
||||||
|
Accept connections without Proxy Protocol header.
|
||||||
|
|
||||||
#### detour
|
#### detour
|
||||||
|
|
||||||
If set, connections will be forwarded to the specified inbound.
|
If set, connections will be forwarded to the specified inbound.
|
||||||
|
|||||||
@@ -5,21 +5,26 @@
|
|||||||
"listen": "::",
|
"listen": "::",
|
||||||
"listen_port": 5353,
|
"listen_port": 5353,
|
||||||
"tcp_fast_open": false,
|
"tcp_fast_open": false,
|
||||||
|
"udp_fragment": false,
|
||||||
"sniff": false,
|
"sniff": false,
|
||||||
"sniff_override_destination": false,
|
"sniff_override_destination": false,
|
||||||
"domain_strategy": "prefer_ipv6",
|
"domain_strategy": "prefer_ipv6",
|
||||||
"udp_timeout": 300,
|
"udp_timeout": 300,
|
||||||
|
"proxy_protocol": false,
|
||||||
|
"proxy_protocol_accept_no_header": false,
|
||||||
"detour": "another-in"
|
"detour": "another-in"
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
| 字段 | 可用上下文 |
|
|
||||||
|------------------|-------------------------------------|
|
| 字段 | 可用上下文 |
|
||||||
| `listen` | 需要监听 TCP 或 UDP。 |
|
|-----------------------------------|-------------------------------------|
|
||||||
| `listen_port` | 需要监听 TCP 或 UDP。 |
|
| `listen` | 需要监听 TCP 或 UDP。 |
|
||||||
| `tcp_fast_open` | 需要监听 TCP。 |
|
| `listen_port` | 需要监听 TCP 或 UDP。 |
|
||||||
| `udp_timeout` | 需要组装 UDP 连接, 当前为 Tun 和 Shadowsocks。 |
|
| `tcp_fast_open` | 需要监听 TCP。 |
|
||||||
| `proxy_protocol` | 需要监听 TCP。 |
|
| `udp_timeout` | 需要组装 UDP 连接, 当前为 Tun 和 Shadowsocks。 |
|
||||||
|
| `proxy_protocol` | 需要监听 TCP。 |
|
||||||
|
| `proxy_protocol_accept_no_header` | `proxy_protocol` 启用时 |
|
||||||
|
|
||||||
### 字段
|
### 字段
|
||||||
|
|
||||||
@@ -35,7 +40,11 @@
|
|||||||
|
|
||||||
#### tcp_fast_open
|
#### tcp_fast_open
|
||||||
|
|
||||||
为监听器启用 TCP 快速打开。
|
启用 TCP Fast Open。
|
||||||
|
|
||||||
|
#### udp_fragment
|
||||||
|
|
||||||
|
启用 UDP 分段。
|
||||||
|
|
||||||
#### sniff
|
#### sniff
|
||||||
|
|
||||||
@@ -65,6 +74,10 @@ UDP NAT 过期时间,以秒为单位,默认为 300(5 分钟)。
|
|||||||
|
|
||||||
解析连接头中的 [代理协议](https://www.haproxy.org/download/1.8/doc/proxy-protocol.txt)。
|
解析连接头中的 [代理协议](https://www.haproxy.org/download/1.8/doc/proxy-protocol.txt)。
|
||||||
|
|
||||||
|
#### proxy_protocol_accept_no_header
|
||||||
|
|
||||||
|
接受没有代理协议标头的连接。
|
||||||
|
|
||||||
#### detour
|
#### detour
|
||||||
|
|
||||||
如果设置,连接将被转发到指定的入站。
|
如果设置,连接将被转发到指定的入站。
|
||||||
|
|||||||
@@ -8,10 +8,10 @@ import (
|
|||||||
|
|
||||||
"github.com/sagernet/sing-box/common/json"
|
"github.com/sagernet/sing-box/common/json"
|
||||||
"github.com/sagernet/sing-box/experimental/clashapi/trafficontrol"
|
"github.com/sagernet/sing-box/experimental/clashapi/trafficontrol"
|
||||||
"github.com/sagernet/websocket"
|
|
||||||
|
|
||||||
"github.com/go-chi/chi/v5"
|
"github.com/go-chi/chi/v5"
|
||||||
"github.com/go-chi/render"
|
"github.com/go-chi/render"
|
||||||
|
"github.com/gorilla/websocket"
|
||||||
)
|
)
|
||||||
|
|
||||||
func connectionRouter(trafficManager *trafficontrol.Manager) http.Handler {
|
func connectionRouter(trafficManager *trafficontrol.Manager) http.Handler {
|
||||||
|
|||||||
@@ -70,26 +70,18 @@ func proxyInfo(server *Server, detour adapter.Outbound) *badjson.JSONObject {
|
|||||||
case C.TypeSocks:
|
case C.TypeSocks:
|
||||||
clashType = "Socks"
|
clashType = "Socks"
|
||||||
case C.TypeHTTP:
|
case C.TypeHTTP:
|
||||||
clashType = "HTTP"
|
clashType = "Http"
|
||||||
case C.TypeShadowsocks:
|
case C.TypeShadowsocks:
|
||||||
clashType = "Shadowsocks"
|
clashType = "Shadowsocks"
|
||||||
case C.TypeVMess:
|
case C.TypeVMess:
|
||||||
clashType = "VMess"
|
clashType = "Vmess"
|
||||||
case C.TypeTrojan:
|
case C.TypeTrojan:
|
||||||
clashType = "Trojan"
|
clashType = "Trojan"
|
||||||
case C.TypeHysteria:
|
|
||||||
clashType = "Hysteria"
|
|
||||||
case C.TypeWireGuard:
|
|
||||||
clashType = "WireGuard"
|
|
||||||
case C.TypeTor:
|
|
||||||
clashType = "Tor"
|
|
||||||
case C.TypeSSH:
|
|
||||||
clashType = "SSH"
|
|
||||||
case C.TypeSelector:
|
case C.TypeSelector:
|
||||||
clashType = "Selector"
|
clashType = "Selector"
|
||||||
isGroup = true
|
isGroup = true
|
||||||
default:
|
default:
|
||||||
clashType = "Direct"
|
clashType = "Socks"
|
||||||
}
|
}
|
||||||
info.Put("type", clashType)
|
info.Put("type", clashType)
|
||||||
info.Put("name", detour.Tag())
|
info.Put("name", detour.Tag())
|
||||||
|
|||||||
@@ -21,11 +21,11 @@ import (
|
|||||||
E "github.com/sagernet/sing/common/exceptions"
|
E "github.com/sagernet/sing/common/exceptions"
|
||||||
F "github.com/sagernet/sing/common/format"
|
F "github.com/sagernet/sing/common/format"
|
||||||
N "github.com/sagernet/sing/common/network"
|
N "github.com/sagernet/sing/common/network"
|
||||||
"github.com/sagernet/websocket"
|
|
||||||
|
|
||||||
"github.com/go-chi/chi/v5"
|
"github.com/go-chi/chi/v5"
|
||||||
"github.com/go-chi/cors"
|
"github.com/go-chi/cors"
|
||||||
"github.com/go-chi/render"
|
"github.com/go-chi/render"
|
||||||
|
"github.com/gorilla/websocket"
|
||||||
)
|
)
|
||||||
|
|
||||||
var _ adapter.ClashServer = (*Server)(nil)
|
var _ adapter.ClashServer = (*Server)(nil)
|
||||||
|
|||||||
20
go.mod
20
go.mod
@@ -12,6 +12,7 @@ require (
|
|||||||
github.com/go-chi/cors v1.2.1
|
github.com/go-chi/cors v1.2.1
|
||||||
github.com/go-chi/render v1.0.2
|
github.com/go-chi/render v1.0.2
|
||||||
github.com/gofrs/uuid v4.2.0+incompatible
|
github.com/gofrs/uuid v4.2.0+incompatible
|
||||||
|
github.com/gorilla/websocket v1.5.0
|
||||||
github.com/hashicorp/yamux v0.1.1
|
github.com/hashicorp/yamux v0.1.1
|
||||||
github.com/logrusorgru/aurora v2.0.3+incompatible
|
github.com/logrusorgru/aurora v2.0.3+incompatible
|
||||||
github.com/mholt/acmez v1.0.4
|
github.com/mholt/acmez v1.0.4
|
||||||
@@ -19,24 +20,23 @@ require (
|
|||||||
github.com/pires/go-proxyproto v0.6.2
|
github.com/pires/go-proxyproto v0.6.2
|
||||||
github.com/sagernet/certmagic v0.0.0-20220819042630-4a57f8b6853a
|
github.com/sagernet/certmagic v0.0.0-20220819042630-4a57f8b6853a
|
||||||
github.com/sagernet/quic-go v0.0.0-20220818150011-de611ab3e2bb
|
github.com/sagernet/quic-go v0.0.0-20220818150011-de611ab3e2bb
|
||||||
github.com/sagernet/sing v0.0.0-20220913004915-27ddefbb8921
|
github.com/sagernet/sing v0.0.0-20220905164441-f3d346256d4a
|
||||||
github.com/sagernet/sing-dns v0.0.0-20220822023312-3e086b06d666
|
github.com/sagernet/sing-dns v0.0.0-20220822023312-3e086b06d666
|
||||||
github.com/sagernet/sing-shadowsocks v0.0.0-20220819002358-7461bb09a8f6
|
github.com/sagernet/sing-shadowsocks v0.0.0-20220819002358-7461bb09a8f6
|
||||||
github.com/sagernet/sing-tun v0.0.0-20220828031750-185b6c880a83
|
github.com/sagernet/sing-tun v0.0.0-20220909054347-575ac2941790
|
||||||
github.com/sagernet/sing-vmess v0.0.0-20220913015714-c4ab86d40e12
|
github.com/sagernet/sing-vmess v0.0.0-20220907073918-72d7fdf6825f
|
||||||
github.com/sagernet/smux v0.0.0-20220831015742-e0f1988e3195
|
github.com/sagernet/smux v0.0.0-20220907034654-1acb8471c15a
|
||||||
github.com/sagernet/websocket v0.0.0-20220913015213-615516348b4e
|
|
||||||
github.com/spf13/cobra v1.5.0
|
github.com/spf13/cobra v1.5.0
|
||||||
github.com/stretchr/testify v1.8.0
|
github.com/stretchr/testify v1.8.0
|
||||||
go.uber.org/atomic v1.10.0
|
go.uber.org/atomic v1.10.0
|
||||||
go4.org/netipx v0.0.0-20220812043211-3cc044ffd68d
|
go4.org/netipx v0.0.0-20220812043211-3cc044ffd68d
|
||||||
golang.org/x/crypto v0.0.0-20220829220503-c86fa9a7ed90
|
golang.org/x/crypto v0.0.0-20220829220503-c86fa9a7ed90
|
||||||
golang.org/x/net v0.0.0-20220826154423-83b083e8dc8b
|
golang.org/x/net v0.0.0-20220907135653-1e95f45603a7
|
||||||
golang.org/x/sys v0.0.0-20220829200755-d48e67d00261
|
golang.org/x/sys v0.0.0-20220908164124-27713097b956
|
||||||
golang.zx2c4.com/wireguard v0.0.0-20220829161405-d1d08426b27b
|
golang.zx2c4.com/wireguard v0.0.0-20220904105730-b51010ba13f0
|
||||||
google.golang.org/grpc v1.49.0
|
google.golang.org/grpc v1.49.0
|
||||||
google.golang.org/protobuf v1.28.1
|
google.golang.org/protobuf v1.28.1
|
||||||
gvisor.dev/gvisor v0.0.0-20220819163037-ba6e795b139a
|
gvisor.dev/gvisor v0.0.0-20220901235040-6ca97ef2ce1c
|
||||||
)
|
)
|
||||||
|
|
||||||
//replace github.com/sagernet/sing => ../sing
|
//replace github.com/sagernet/sing => ../sing
|
||||||
@@ -59,7 +59,7 @@ require (
|
|||||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||||
github.com/sagernet/abx-go v0.0.0-20220819185957-dba1257d738e // indirect
|
github.com/sagernet/abx-go v0.0.0-20220819185957-dba1257d738e // indirect
|
||||||
github.com/sagernet/go-tun2socks v1.16.12-0.20220818015926-16cb67876a61 // indirect
|
github.com/sagernet/go-tun2socks v1.16.12-0.20220818015926-16cb67876a61 // indirect
|
||||||
github.com/sagernet/netlink v0.0.0-20220826133217-3fb4ff92ea17 // indirect
|
github.com/sagernet/netlink v0.0.0-20220905062125-8043b4a9aa97 // indirect
|
||||||
github.com/spf13/pflag v1.0.5 // indirect
|
github.com/spf13/pflag v1.0.5 // indirect
|
||||||
github.com/vishvananda/netns v0.0.0-20211101163701-50045581ed74 // indirect
|
github.com/vishvananda/netns v0.0.0-20211101163701-50045581ed74 // indirect
|
||||||
go.uber.org/multierr v1.6.0 // indirect
|
go.uber.org/multierr v1.6.0 // indirect
|
||||||
|
|||||||
40
go.sum
40
go.sum
@@ -73,6 +73,8 @@ github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/
|
|||||||
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||||
github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg=
|
github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg=
|
||||||
github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
|
github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc=
|
||||||
|
github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||||
github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw=
|
github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw=
|
||||||
github.com/hashicorp/yamux v0.1.1 h1:yrQxtgseBDrq9Y652vSRDvsKCJKOUD+GzTS4Y0Y8pvE=
|
github.com/hashicorp/yamux v0.1.1 h1:yrQxtgseBDrq9Y652vSRDvsKCJKOUD+GzTS4Y0Y8pvE=
|
||||||
github.com/hashicorp/yamux v0.1.1/go.mod h1:CtWFDAQgb7dxtzFs4tWbplKIe2jSi3+5vKbgIO0SLnQ=
|
github.com/hashicorp/yamux v0.1.1/go.mod h1:CtWFDAQgb7dxtzFs4tWbplKIe2jSi3+5vKbgIO0SLnQ=
|
||||||
@@ -127,26 +129,24 @@ github.com/sagernet/certmagic v0.0.0-20220819042630-4a57f8b6853a h1:SE3Xn4GOQ+kx
|
|||||||
github.com/sagernet/certmagic v0.0.0-20220819042630-4a57f8b6853a/go.mod h1:Q+ZXyesnkjV5B70B1ixk65ecKrlJ2jz0atv3fPKsVVo=
|
github.com/sagernet/certmagic v0.0.0-20220819042630-4a57f8b6853a/go.mod h1:Q+ZXyesnkjV5B70B1ixk65ecKrlJ2jz0atv3fPKsVVo=
|
||||||
github.com/sagernet/go-tun2socks v1.16.12-0.20220818015926-16cb67876a61 h1:5+m7c6AkmAylhauulqN/c5dnh8/KssrE9c93TQrXldA=
|
github.com/sagernet/go-tun2socks v1.16.12-0.20220818015926-16cb67876a61 h1:5+m7c6AkmAylhauulqN/c5dnh8/KssrE9c93TQrXldA=
|
||||||
github.com/sagernet/go-tun2socks v1.16.12-0.20220818015926-16cb67876a61/go.mod h1:QUQ4RRHD6hGGHdFMEtR8T2P6GS6R3D/CXKdaYHKKXms=
|
github.com/sagernet/go-tun2socks v1.16.12-0.20220818015926-16cb67876a61/go.mod h1:QUQ4RRHD6hGGHdFMEtR8T2P6GS6R3D/CXKdaYHKKXms=
|
||||||
github.com/sagernet/netlink v0.0.0-20220826133217-3fb4ff92ea17 h1:zvm6IrIgo4rLizJCHkH+SWUBhm+jyjjozX031QdAlj8=
|
github.com/sagernet/netlink v0.0.0-20220905062125-8043b4a9aa97 h1:iL5gZI3uFp0X6EslacyapiRz7LLSJyr4RajF/BhMVyE=
|
||||||
github.com/sagernet/netlink v0.0.0-20220826133217-3fb4ff92ea17/go.mod h1:xLnfdiJbSp8rNqYEdIW/6eDO4mVoogml14Bh2hSiFpM=
|
github.com/sagernet/netlink v0.0.0-20220905062125-8043b4a9aa97/go.mod h1:xLnfdiJbSp8rNqYEdIW/6eDO4mVoogml14Bh2hSiFpM=
|
||||||
github.com/sagernet/quic-go v0.0.0-20220818150011-de611ab3e2bb h1:wc0yQ+SBn4TaTYRwpwvEm3nc4eRdxk6vtRbouLVZAzk=
|
github.com/sagernet/quic-go v0.0.0-20220818150011-de611ab3e2bb h1:wc0yQ+SBn4TaTYRwpwvEm3nc4eRdxk6vtRbouLVZAzk=
|
||||||
github.com/sagernet/quic-go v0.0.0-20220818150011-de611ab3e2bb/go.mod h1:MIccjRKnPTjWwAOpl+AUGWOkzyTd9tERytudxu+1ra4=
|
github.com/sagernet/quic-go v0.0.0-20220818150011-de611ab3e2bb/go.mod h1:MIccjRKnPTjWwAOpl+AUGWOkzyTd9tERytudxu+1ra4=
|
||||||
github.com/sagernet/sing v0.0.0-20220812082120-05f9836bff8f/go.mod h1:QVsS5L/ZA2Q5UhQwLrn0Trw+msNd/NPGEhBKR/ioWiY=
|
github.com/sagernet/sing v0.0.0-20220812082120-05f9836bff8f/go.mod h1:QVsS5L/ZA2Q5UhQwLrn0Trw+msNd/NPGEhBKR/ioWiY=
|
||||||
github.com/sagernet/sing v0.0.0-20220817130738-ce854cda8522/go.mod h1:QVsS5L/ZA2Q5UhQwLrn0Trw+msNd/NPGEhBKR/ioWiY=
|
github.com/sagernet/sing v0.0.0-20220817130738-ce854cda8522/go.mod h1:QVsS5L/ZA2Q5UhQwLrn0Trw+msNd/NPGEhBKR/ioWiY=
|
||||||
github.com/sagernet/sing v0.0.0-20220913004915-27ddefbb8921 h1:xUHzlIbdlPV/fkToIO9futp9lmKIY+72ezk/whQ8XsI=
|
github.com/sagernet/sing v0.0.0-20220905164441-f3d346256d4a h1:Bqt+eYP7vJocAgAVAXC0B0ZN0uMr6g6exAoF3Ado2pg=
|
||||||
github.com/sagernet/sing v0.0.0-20220913004915-27ddefbb8921/go.mod h1:kZvzh1VDa/Dg/Bt5WaYKU0jl5ept8KKDpl3Ay4gRtRQ=
|
github.com/sagernet/sing v0.0.0-20220905164441-f3d346256d4a/go.mod h1:kZvzh1VDa/Dg/Bt5WaYKU0jl5ept8KKDpl3Ay4gRtRQ=
|
||||||
github.com/sagernet/sing-dns v0.0.0-20220822023312-3e086b06d666 h1:XUTocA/Ek0dFxUX+xJCWMPPFZCn2GC/uLrBjTSr1vHY=
|
github.com/sagernet/sing-dns v0.0.0-20220822023312-3e086b06d666 h1:XUTocA/Ek0dFxUX+xJCWMPPFZCn2GC/uLrBjTSr1vHY=
|
||||||
github.com/sagernet/sing-dns v0.0.0-20220822023312-3e086b06d666/go.mod h1:eDyH7AJmqBGjZQdQmpZIzlbTREudZuWDExMuGKgjRVM=
|
github.com/sagernet/sing-dns v0.0.0-20220822023312-3e086b06d666/go.mod h1:eDyH7AJmqBGjZQdQmpZIzlbTREudZuWDExMuGKgjRVM=
|
||||||
github.com/sagernet/sing-shadowsocks v0.0.0-20220819002358-7461bb09a8f6 h1:JJfDeYYhWunvtxsU/mOVNTmFQmnzGx9dY034qG6G3g4=
|
github.com/sagernet/sing-shadowsocks v0.0.0-20220819002358-7461bb09a8f6 h1:JJfDeYYhWunvtxsU/mOVNTmFQmnzGx9dY034qG6G3g4=
|
||||||
github.com/sagernet/sing-shadowsocks v0.0.0-20220819002358-7461bb09a8f6/go.mod h1:EX3RbZvrwAkPI2nuGa78T2iQXmrkT+/VQtskjou42xM=
|
github.com/sagernet/sing-shadowsocks v0.0.0-20220819002358-7461bb09a8f6/go.mod h1:EX3RbZvrwAkPI2nuGa78T2iQXmrkT+/VQtskjou42xM=
|
||||||
github.com/sagernet/sing-tun v0.0.0-20220828031750-185b6c880a83 h1:SoWiHYuOCVedqA7T/CJSZUUrcPGKQb2wFKEq8DphiAI=
|
github.com/sagernet/sing-tun v0.0.0-20220909054347-575ac2941790 h1:SnIhaHWVk3tTTx/zFEor9zRItcbzTYMoC8F22FAZ/Iw=
|
||||||
github.com/sagernet/sing-tun v0.0.0-20220828031750-185b6c880a83/go.mod h1:76r07HS1WRcEI4mE9pFsohfTBUt1j/G9Avz6DaOP3VU=
|
github.com/sagernet/sing-tun v0.0.0-20220909054347-575ac2941790/go.mod h1:5AhPUv9jWDQ3pv3Mj78SL/1TSjhoaj6WNASxRKLqXqM=
|
||||||
github.com/sagernet/sing-vmess v0.0.0-20220913015714-c4ab86d40e12 h1:4HYGbTDDemgBVTmaspXbkgjJlXc3hYVjNxSddJndq8Y=
|
github.com/sagernet/sing-vmess v0.0.0-20220907073918-72d7fdf6825f h1:6l9aXZqAl1JqXJWi89KHpWnM/moQUPGG+XiwMc+yD0A=
|
||||||
github.com/sagernet/sing-vmess v0.0.0-20220913015714-c4ab86d40e12/go.mod h1:u66Vv7NHXJWfeAmhh7JuJp/cwxmuQlM56QoZ7B7Mmd0=
|
github.com/sagernet/sing-vmess v0.0.0-20220907073918-72d7fdf6825f/go.mod h1:u66Vv7NHXJWfeAmhh7JuJp/cwxmuQlM56QoZ7B7Mmd0=
|
||||||
github.com/sagernet/smux v0.0.0-20220831015742-e0f1988e3195 h1:5VBIbVw9q7aKbrFdT83mjkyvQ+VaRsQ6yflTepfln38=
|
github.com/sagernet/smux v0.0.0-20220907034654-1acb8471c15a h1:GCNwsN8MEckpjGJjK3qjQBQ9qHsoXB9B/KHUWBvE1V4=
|
||||||
github.com/sagernet/smux v0.0.0-20220831015742-e0f1988e3195/go.mod h1:yedWtra8nyGJ+SyI+ziwuaGMzBatbB10P1IOOZbbSK8=
|
github.com/sagernet/smux v0.0.0-20220907034654-1acb8471c15a/go.mod h1:yedWtra8nyGJ+SyI+ziwuaGMzBatbB10P1IOOZbbSK8=
|
||||||
github.com/sagernet/websocket v0.0.0-20220913015213-615516348b4e h1:7uw2njHFGE+VpWamge6o56j2RWk4omF6uLKKxMmcWvs=
|
|
||||||
github.com/sagernet/websocket v0.0.0-20220913015213-615516348b4e/go.mod h1:45TUl8+gH4SIKr4ykREbxKWTxkDlSzFENzctB1dVRRY=
|
|
||||||
github.com/spf13/cobra v1.5.0 h1:X+jTBEBqF0bHN+9cSMgmfuvv2VHJ9ezmFNf9Y/XstYU=
|
github.com/spf13/cobra v1.5.0 h1:X+jTBEBqF0bHN+9cSMgmfuvv2VHJ9ezmFNf9Y/XstYU=
|
||||||
github.com/spf13/cobra v1.5.0/go.mod h1:dWXEIy2H428czQCjInthrTRUg7yKbok+2Qi/yBIJoUM=
|
github.com/spf13/cobra v1.5.0/go.mod h1:dWXEIy2H428czQCjInthrTRUg7yKbok+2Qi/yBIJoUM=
|
||||||
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
|
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
|
||||||
@@ -212,8 +212,8 @@ golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v
|
|||||||
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
|
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
|
||||||
golang.org/x/net v0.0.0-20210525063256-abc453219eb5/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
golang.org/x/net v0.0.0-20210525063256-abc453219eb5/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||||
golang.org/x/net v0.0.0-20220630215102-69896b714898/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
golang.org/x/net v0.0.0-20220630215102-69896b714898/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||||
golang.org/x/net v0.0.0-20220826154423-83b083e8dc8b h1:ZmngSVLe/wycRns9MKikG9OWIEjGcGAkacif7oYQaUY=
|
golang.org/x/net v0.0.0-20220907135653-1e95f45603a7 h1:1WGATo9HAhkWMbfyuVU0tEFP88OIkUvwaHFveQPvzCQ=
|
||||||
golang.org/x/net v0.0.0-20220826154423-83b083e8dc8b/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk=
|
golang.org/x/net v0.0.0-20220907135653-1e95f45603a7/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk=
|
||||||
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||||
golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||||
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
@@ -244,8 +244,8 @@ golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBc
|
|||||||
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.0.0-20220731174439-a90be440212d/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.0.0-20220731174439-a90be440212d/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.0.0-20220829200755-d48e67d00261 h1:v6hYoSR9T5oet+pMXwUWkbiVqx/63mlHjefrHmxwfeY=
|
golang.org/x/sys v0.0.0-20220908164124-27713097b956 h1:XeJjHH1KiLpKGb6lvMiksZ9l0fVUh+AmGcm0nOMEBOY=
|
||||||
golang.org/x/sys v0.0.0-20220829200755-d48e67d00261/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211 h1:JGgROgKl9N8DuW20oFS5gxc+lE67/N3FcwmBPMe7ArY=
|
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211 h1:JGgROgKl9N8DuW20oFS5gxc+lE67/N3FcwmBPMe7ArY=
|
||||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||||
@@ -276,8 +276,8 @@ golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8T
|
|||||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
golang.zx2c4.com/wintun v0.0.0-20211104114900-415007cec224 h1:Ug9qvr1myri/zFN6xL17LSCBGFDnphBBhzmILHsM5TY=
|
golang.zx2c4.com/wintun v0.0.0-20211104114900-415007cec224 h1:Ug9qvr1myri/zFN6xL17LSCBGFDnphBBhzmILHsM5TY=
|
||||||
golang.zx2c4.com/wintun v0.0.0-20211104114900-415007cec224/go.mod h1:deeaetjYA+DHMHg+sMSMI58GrEteJUUzzw7en6TJQcI=
|
golang.zx2c4.com/wintun v0.0.0-20211104114900-415007cec224/go.mod h1:deeaetjYA+DHMHg+sMSMI58GrEteJUUzzw7en6TJQcI=
|
||||||
golang.zx2c4.com/wireguard v0.0.0-20220829161405-d1d08426b27b h1:qgrKnOfe1zyURRNdmDlGbN32i38Zjmw0B1+TMdHcOvg=
|
golang.zx2c4.com/wireguard v0.0.0-20220904105730-b51010ba13f0 h1:5ZkdpbduT/g+9OtbSDvbF3KvfQG45CtH/ppO8FUmvCQ=
|
||||||
golang.zx2c4.com/wireguard v0.0.0-20220829161405-d1d08426b27b/go.mod h1:6y4CqPAy54NwiN4nC8K+R1eMpQDB1P2d25qmunh2RSA=
|
golang.zx2c4.com/wireguard v0.0.0-20220904105730-b51010ba13f0/go.mod h1:enML0deDxY1ux+B6ANGiwtg0yAJi1rctkTpcHNAVPyg=
|
||||||
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
|
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
|
||||||
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
|
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
|
||||||
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
|
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
|
||||||
@@ -326,8 +326,8 @@ gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C
|
|||||||
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
gvisor.dev/gvisor v0.0.0-20220819163037-ba6e795b139a h1:W1h3JsEzYWg7eD4908iHv49p7AOx7JPKsoh/fsxgylM=
|
gvisor.dev/gvisor v0.0.0-20220901235040-6ca97ef2ce1c h1:m5lcgWnL3OElQNVyp3qcncItJ2c0sQlSGjYK2+nJTA4=
|
||||||
gvisor.dev/gvisor v0.0.0-20220819163037-ba6e795b139a/go.mod h1:TIvkJD0sxe8pIob3p6T8IzxXunlp6yfgktvTNp+DGNM=
|
gvisor.dev/gvisor v0.0.0-20220901235040-6ca97ef2ce1c/go.mod h1:TIvkJD0sxe8pIob3p6T8IzxXunlp6yfgktvTNp+DGNM=
|
||||||
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||||
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||||
lukechampine.com/blake3 v1.1.7 h1:GgRMhmdsuK8+ii6UZFDL8Nb+VyMwadAgcJyfYHxG6n0=
|
lukechampine.com/blake3 v1.1.7 h1:GgRMhmdsuK8+ii6UZFDL8Nb+VyMwadAgcJyfYHxG6n0=
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package inbound
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"net"
|
"net"
|
||||||
|
"sync"
|
||||||
|
|
||||||
"github.com/sagernet/sing-box/adapter"
|
"github.com/sagernet/sing-box/adapter"
|
||||||
"github.com/sagernet/sing-box/common/settings"
|
"github.com/sagernet/sing-box/common/settings"
|
||||||
@@ -41,6 +42,7 @@ type myInboundAdapter struct {
|
|||||||
tcpListener net.Listener
|
tcpListener net.Listener
|
||||||
udpConn *net.UDPConn
|
udpConn *net.UDPConn
|
||||||
udpAddr M.Socksaddr
|
udpAddr M.Socksaddr
|
||||||
|
packetAccess sync.RWMutex
|
||||||
packetOutboundClosed chan struct{}
|
packetOutboundClosed chan struct{}
|
||||||
packetOutbound chan *myInboundPacket
|
packetOutbound chan *myInboundPacket
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ func (a *myInboundAdapter) ListenTCP() (net.Listener, error) {
|
|||||||
}
|
}
|
||||||
if a.listenOptions.ProxyProtocol {
|
if a.listenOptions.ProxyProtocol {
|
||||||
a.logger.Debug("proxy protocol enabled")
|
a.logger.Debug("proxy protocol enabled")
|
||||||
tcpListener = &proxyproto.Listener{Listener: tcpListener}
|
tcpListener = &proxyproto.Listener{Listener: tcpListener, AcceptNoHeader: a.listenOptions.ProxyProtocolAcceptNoHeader}
|
||||||
}
|
}
|
||||||
a.tcpListener = tcpListener
|
a.tcpListener = tcpListener
|
||||||
return tcpListener, err
|
return tcpListener, err
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import (
|
|||||||
"github.com/sagernet/sing-dns"
|
"github.com/sagernet/sing-dns"
|
||||||
"github.com/sagernet/sing/common"
|
"github.com/sagernet/sing/common"
|
||||||
"github.com/sagernet/sing/common/buf"
|
"github.com/sagernet/sing/common/buf"
|
||||||
|
"github.com/sagernet/sing/common/control"
|
||||||
E "github.com/sagernet/sing/common/exceptions"
|
E "github.com/sagernet/sing/common/exceptions"
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
N "github.com/sagernet/sing/common/network"
|
N "github.com/sagernet/sing/common/network"
|
||||||
@@ -17,11 +18,15 @@ import (
|
|||||||
|
|
||||||
func (a *myInboundAdapter) ListenUDP() (net.PacketConn, error) {
|
func (a *myInboundAdapter) ListenUDP() (net.PacketConn, error) {
|
||||||
bindAddr := M.SocksaddrFrom(netip.Addr(a.listenOptions.Listen), a.listenOptions.ListenPort)
|
bindAddr := M.SocksaddrFrom(netip.Addr(a.listenOptions.Listen), a.listenOptions.ListenPort)
|
||||||
udpConn, err := net.ListenUDP(M.NetworkFromNetAddr(N.NetworkUDP, bindAddr.Addr), bindAddr.UDPAddr())
|
var lc net.ListenConfig
|
||||||
|
if !a.listenOptions.UDPFragment {
|
||||||
|
lc.Control = control.Append(lc.Control, control.DisableUDPFragment())
|
||||||
|
}
|
||||||
|
udpConn, err := lc.ListenPacket(a.ctx, M.NetworkFromNetAddr(N.NetworkUDP, bindAddr.Addr), bindAddr.String())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
a.udpConn = udpConn
|
a.udpConn = udpConn.(*net.UDPConn)
|
||||||
a.udpAddr = bindAddr
|
a.udpAddr = bindAddr
|
||||||
a.logger.Info("udp server started at ", udpConn.LocalAddr())
|
a.logger.Info("udp server started at ", udpConn.LocalAddr())
|
||||||
return udpConn, err
|
return udpConn, err
|
||||||
@@ -203,12 +208,17 @@ func (s *myInboundPacketAdapter) Upstream() any {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *myInboundPacketAdapter) WritePacket(buffer *buf.Buffer, destination M.Socksaddr) error {
|
func (s *myInboundPacketAdapter) WritePacket(buffer *buf.Buffer, destination M.Socksaddr) error {
|
||||||
|
s.packetAccess.RLock()
|
||||||
|
defer s.packetAccess.RUnlock()
|
||||||
|
|
||||||
select {
|
select {
|
||||||
case s.packetOutbound <- &myInboundPacket{buffer, destination}:
|
|
||||||
return nil
|
|
||||||
case <-s.packetOutboundClosed:
|
case <-s.packetOutboundClosed:
|
||||||
return os.ErrClosed
|
return os.ErrClosed
|
||||||
|
default:
|
||||||
}
|
}
|
||||||
|
|
||||||
|
s.packetOutbound <- &myInboundPacket{buffer, destination}
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *myInboundPacketAdapter) Close() error {
|
func (s *myInboundPacketAdapter) Close() error {
|
||||||
|
|||||||
@@ -250,6 +250,12 @@ func (h *Hysteria) acceptStream(ctx context.Context, conn quic.Connection, strea
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
err = hysteria.WriteServerResponse(stream, hysteria.ServerResponse{
|
||||||
|
OK: true,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
var metadata adapter.InboundContext
|
var metadata adapter.InboundContext
|
||||||
metadata.Inbound = h.tag
|
metadata.Inbound = h.tag
|
||||||
metadata.InboundType = C.TypeHysteria
|
metadata.InboundType = C.TypeHysteria
|
||||||
@@ -259,14 +265,7 @@ func (h *Hysteria) acceptStream(ctx context.Context, conn quic.Connection, strea
|
|||||||
metadata.Source = M.SocksaddrFromNet(conn.RemoteAddr())
|
metadata.Source = M.SocksaddrFromNet(conn.RemoteAddr())
|
||||||
metadata.OriginDestination = M.SocksaddrFromNet(conn.LocalAddr())
|
metadata.OriginDestination = M.SocksaddrFromNet(conn.LocalAddr())
|
||||||
metadata.Destination = M.ParseSocksaddrHostPort(request.Host, request.Port)
|
metadata.Destination = M.ParseSocksaddrHostPort(request.Host, request.Port)
|
||||||
|
|
||||||
if !request.UDP {
|
if !request.UDP {
|
||||||
err = hysteria.WriteServerResponse(stream, hysteria.ServerResponse{
|
|
||||||
OK: true,
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
h.logger.InfoContext(ctx, "inbound connection to ", metadata.Destination)
|
h.logger.InfoContext(ctx, "inbound connection to ", metadata.Destination)
|
||||||
return h.router.RouteConnection(ctx, hysteria.NewConn(stream, metadata.Destination), metadata)
|
return h.router.RouteConnection(ctx, hysteria.NewConn(stream, metadata.Destination), metadata)
|
||||||
} else {
|
} else {
|
||||||
@@ -278,13 +277,6 @@ func (h *Hysteria) acceptStream(ctx context.Context, conn quic.Connection, strea
|
|||||||
h.udpSessions[id] = nCh
|
h.udpSessions[id] = nCh
|
||||||
h.udpSessionId += 1
|
h.udpSessionId += 1
|
||||||
h.udpAccess.Unlock()
|
h.udpAccess.Unlock()
|
||||||
err = hysteria.WriteServerResponse(stream, hysteria.ServerResponse{
|
|
||||||
OK: true,
|
|
||||||
UDPSessionID: id,
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
packetConn := hysteria.NewPacketConn(conn, stream, id, metadata.Destination, nCh, common.Closer(func() error {
|
packetConn := hysteria.NewPacketConn(conn, stream, id, metadata.Destination, nCh, common.Closer(func() error {
|
||||||
h.udpAccess.Lock()
|
h.udpAccess.Lock()
|
||||||
if ch, ok := h.udpSessions[id]; ok {
|
if ch, ok := h.udpSessions[id]; ok {
|
||||||
|
|||||||
@@ -248,14 +248,7 @@ func (c *naiveH1Conn) read(p []byte) (n int, err error) {
|
|||||||
c.paddingRemaining = 0
|
c.paddingRemaining = 0
|
||||||
}
|
}
|
||||||
if c.readPadding < kFirstPaddings {
|
if c.readPadding < kFirstPaddings {
|
||||||
var paddingHdr []byte
|
paddingHdr := p[:3]
|
||||||
if len(p) >= 3 {
|
|
||||||
paddingHdr = p[:3]
|
|
||||||
} else {
|
|
||||||
_paddingHdr := make([]byte, 3)
|
|
||||||
defer common.KeepAlive(_paddingHdr)
|
|
||||||
paddingHdr = common.Dup(_paddingHdr)
|
|
||||||
}
|
|
||||||
_, err = io.ReadFull(c.Conn, paddingHdr)
|
_, err = io.ReadFull(c.Conn, paddingHdr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
@@ -427,14 +420,7 @@ func (c *naiveH2Conn) read(p []byte) (n int, err error) {
|
|||||||
c.paddingRemaining = 0
|
c.paddingRemaining = 0
|
||||||
}
|
}
|
||||||
if c.readPadding < kFirstPaddings {
|
if c.readPadding < kFirstPaddings {
|
||||||
var paddingHdr []byte
|
paddingHdr := p[:3]
|
||||||
if len(p) >= 3 {
|
|
||||||
paddingHdr = p[:3]
|
|
||||||
} else {
|
|
||||||
_paddingHdr := make([]byte, 3)
|
|
||||||
defer common.KeepAlive(_paddingHdr)
|
|
||||||
paddingHdr = common.Dup(_paddingHdr)
|
|
||||||
}
|
|
||||||
_, err = io.ReadFull(c.reader, paddingHdr)
|
_, err = io.ReadFull(c.reader, paddingHdr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -40,11 +40,11 @@ type Tun struct {
|
|||||||
func NewTun(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.TunInboundOptions) (*Tun, error) {
|
func NewTun(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.TunInboundOptions) (*Tun, error) {
|
||||||
tunName := options.InterfaceName
|
tunName := options.InterfaceName
|
||||||
if tunName == "" {
|
if tunName == "" {
|
||||||
tunName = tun.DefaultInterfaceName()
|
tunName = tun.CalculateInterfaceName("")
|
||||||
}
|
}
|
||||||
tunMTU := options.MTU
|
tunMTU := options.MTU
|
||||||
if tunMTU == 0 {
|
if tunMTU == 0 {
|
||||||
tunMTU = 1500
|
tunMTU = 9000
|
||||||
}
|
}
|
||||||
var udpTimeout int64
|
var udpTimeout int64
|
||||||
if options.UDPTimeout != 0 {
|
if options.UDPTimeout != 0 {
|
||||||
@@ -77,8 +77,8 @@ func NewTun(ctx context.Context, router adapter.Router, logger log.ContextLogger
|
|||||||
tunOptions: tun.Options{
|
tunOptions: tun.Options{
|
||||||
Name: tunName,
|
Name: tunName,
|
||||||
MTU: tunMTU,
|
MTU: tunMTU,
|
||||||
Inet4Address: options.Inet4Address.Build(),
|
Inet4Address: common.Map(options.Inet4Address, option.ListenPrefix.Build),
|
||||||
Inet6Address: options.Inet6Address.Build(),
|
Inet6Address: common.Map(options.Inet6Address, option.ListenPrefix.Build),
|
||||||
AutoRoute: options.AutoRoute,
|
AutoRoute: options.AutoRoute,
|
||||||
StrictRoute: options.StrictRoute,
|
StrictRoute: options.StrictRoute,
|
||||||
IncludeUID: includeUID,
|
IncludeUID: includeUID,
|
||||||
@@ -86,6 +86,8 @@ func NewTun(ctx context.Context, router adapter.Router, logger log.ContextLogger
|
|||||||
IncludeAndroidUser: options.IncludeAndroidUser,
|
IncludeAndroidUser: options.IncludeAndroidUser,
|
||||||
IncludePackage: options.IncludePackage,
|
IncludePackage: options.IncludePackage,
|
||||||
ExcludePackage: options.ExcludePackage,
|
ExcludePackage: options.ExcludePackage,
|
||||||
|
InterfaceMonitor: router.InterfaceMonitor(),
|
||||||
|
TableIndex: 2022,
|
||||||
},
|
},
|
||||||
endpointIndependentNat: options.EndpointIndependentNat,
|
endpointIndependentNat: options.EndpointIndependentNat,
|
||||||
udpTimeout: udpTimeout,
|
udpTimeout: udpTimeout,
|
||||||
@@ -142,7 +144,18 @@ func (t *Tun) Start() error {
|
|||||||
return E.Cause(err, "configure tun interface")
|
return E.Cause(err, "configure tun interface")
|
||||||
}
|
}
|
||||||
t.tunIf = tunIf
|
t.tunIf = tunIf
|
||||||
t.tunStack, err = tun.NewStack(t.ctx, t.stack, tunIf, t.tunOptions.MTU, t.endpointIndependentNat, t.udpTimeout, t)
|
t.tunStack, err = tun.NewStack(t.stack, tun.StackOptions{
|
||||||
|
Context: t.ctx,
|
||||||
|
Tun: tunIf,
|
||||||
|
MTU: t.tunOptions.MTU,
|
||||||
|
Name: t.tunOptions.Name,
|
||||||
|
Inet4Address: t.tunOptions.Inet4Address,
|
||||||
|
Inet6Address: t.tunOptions.Inet6Address,
|
||||||
|
EndpointIndependentNat: t.endpointIndependentNat,
|
||||||
|
UDPTimeout: t.udpTimeout,
|
||||||
|
Handler: t,
|
||||||
|
Logger: t.logger,
|
||||||
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ type _Options struct {
|
|||||||
type Options _Options
|
type Options _Options
|
||||||
|
|
||||||
func (o *Options) UnmarshalJSON(content []byte) error {
|
func (o *Options) UnmarshalJSON(content []byte) error {
|
||||||
decoder := json.NewDecoder(bytes.NewReader(content))
|
decoder := json.NewDecoder(json.NewCommentFilter(bytes.NewReader(content)))
|
||||||
decoder.DisallowUnknownFields()
|
decoder.DisallowUnknownFields()
|
||||||
err := decoder.Decode((*_Options)(o))
|
err := decoder.Decode((*_Options)(o))
|
||||||
if err == nil {
|
if err == nil {
|
||||||
|
|||||||
@@ -111,11 +111,13 @@ type InboundOptions struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type ListenOptions struct {
|
type ListenOptions struct {
|
||||||
Listen ListenAddress `json:"listen"`
|
Listen ListenAddress `json:"listen"`
|
||||||
ListenPort uint16 `json:"listen_port,omitempty"`
|
ListenPort uint16 `json:"listen_port,omitempty"`
|
||||||
TCPFastOpen bool `json:"tcp_fast_open,omitempty"`
|
TCPFastOpen bool `json:"tcp_fast_open,omitempty"`
|
||||||
UDPTimeout int64 `json:"udp_timeout,omitempty"`
|
UDPFragment bool `json:"udp_fragment,omitempty"`
|
||||||
ProxyProtocol bool `json:"proxy_protocol,omitempty"`
|
UDPTimeout int64 `json:"udp_timeout,omitempty"`
|
||||||
Detour string `json:"detour,omitempty"`
|
ProxyProtocol bool `json:"proxy_protocol,omitempty"`
|
||||||
|
ProxyProtocolAcceptNoHeader bool `json:"proxy_protocol_accept_no_header,omitempty"`
|
||||||
|
Detour string `json:"detour,omitempty"`
|
||||||
InboundOptions
|
InboundOptions
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -113,6 +113,7 @@ type DialerOptions struct {
|
|||||||
ReuseAddr bool `json:"reuse_addr,omitempty"`
|
ReuseAddr bool `json:"reuse_addr,omitempty"`
|
||||||
ConnectTimeout Duration `json:"connect_timeout,omitempty"`
|
ConnectTimeout Duration `json:"connect_timeout,omitempty"`
|
||||||
TCPFastOpen bool `json:"tcp_fast_open,omitempty"`
|
TCPFastOpen bool `json:"tcp_fast_open,omitempty"`
|
||||||
|
UDPFragment bool `json:"udp_fragment,omitempty"`
|
||||||
DomainStrategy DomainStrategy `json:"domain_strategy,omitempty"`
|
DomainStrategy DomainStrategy `json:"domain_strategy,omitempty"`
|
||||||
FallbackDelay Duration `json:"fallback_delay,omitempty"`
|
FallbackDelay Duration `json:"fallback_delay,omitempty"`
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ type RouteOptions struct {
|
|||||||
Final string `json:"final,omitempty"`
|
Final string `json:"final,omitempty"`
|
||||||
FindProcess bool `json:"find_process,omitempty"`
|
FindProcess bool `json:"find_process,omitempty"`
|
||||||
AutoDetectInterface bool `json:"auto_detect_interface,omitempty"`
|
AutoDetectInterface bool `json:"auto_detect_interface,omitempty"`
|
||||||
|
OverrideAndroidVPN bool `json:"override_android_vpn,omitempty"`
|
||||||
DefaultInterface string `json:"default_interface,omitempty"`
|
DefaultInterface string `json:"default_interface,omitempty"`
|
||||||
DefaultMark int `json:"default_mark,omitempty"`
|
DefaultMark int `json:"default_mark,omitempty"`
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,21 +1,21 @@
|
|||||||
package option
|
package option
|
||||||
|
|
||||||
type TunInboundOptions struct {
|
type TunInboundOptions struct {
|
||||||
InterfaceName string `json:"interface_name,omitempty"`
|
InterfaceName string `json:"interface_name,omitempty"`
|
||||||
MTU uint32 `json:"mtu,omitempty"`
|
MTU uint32 `json:"mtu,omitempty"`
|
||||||
Inet4Address *ListenPrefix `json:"inet4_address,omitempty"`
|
Inet4Address Listable[ListenPrefix] `json:"inet4_address,omitempty"`
|
||||||
Inet6Address *ListenPrefix `json:"inet6_address,omitempty"`
|
Inet6Address Listable[ListenPrefix] `json:"inet6_address,omitempty"`
|
||||||
AutoRoute bool `json:"auto_route,omitempty"`
|
AutoRoute bool `json:"auto_route,omitempty"`
|
||||||
StrictRoute bool `json:"strict_route,omitempty"`
|
StrictRoute bool `json:"strict_route,omitempty"`
|
||||||
IncludeUID Listable[uint32] `json:"include_uid,omitempty"`
|
IncludeUID Listable[uint32] `json:"include_uid,omitempty"`
|
||||||
IncludeUIDRange Listable[string] `json:"include_uid_range,omitempty"`
|
IncludeUIDRange Listable[string] `json:"include_uid_range,omitempty"`
|
||||||
ExcludeUID Listable[uint32] `json:"exclude_uid,omitempty"`
|
ExcludeUID Listable[uint32] `json:"exclude_uid,omitempty"`
|
||||||
ExcludeUIDRange Listable[string] `json:"exclude_uid_range,omitempty"`
|
ExcludeUIDRange Listable[string] `json:"exclude_uid_range,omitempty"`
|
||||||
IncludeAndroidUser Listable[int] `json:"include_android_user,omitempty"`
|
IncludeAndroidUser Listable[int] `json:"include_android_user,omitempty"`
|
||||||
IncludePackage Listable[string] `json:"include_package,omitempty"`
|
IncludePackage Listable[string] `json:"include_package,omitempty"`
|
||||||
ExcludePackage Listable[string] `json:"exclude_package,omitempty"`
|
ExcludePackage Listable[string] `json:"exclude_package,omitempty"`
|
||||||
EndpointIndependentNat bool `json:"endpoint_independent_nat,omitempty"`
|
EndpointIndependentNat bool `json:"endpoint_independent_nat,omitempty"`
|
||||||
UDPTimeout int64 `json:"udp_timeout,omitempty"`
|
UDPTimeout int64 `json:"udp_timeout,omitempty"`
|
||||||
Stack string `json:"stack,omitempty"`
|
Stack string `json:"stack,omitempty"`
|
||||||
InboundOptions
|
InboundOptions
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -184,9 +184,6 @@ func (p *ListenPrefix) UnmarshalJSON(bytes []byte) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *ListenPrefix) Build() netip.Prefix {
|
func (p ListenPrefix) Build() netip.Prefix {
|
||||||
if p == nil {
|
return netip.Prefix(p)
|
||||||
return netip.Prefix{}
|
|
||||||
}
|
|
||||||
return netip.Prefix(*p)
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,10 +3,12 @@ package option
|
|||||||
type WireGuardOutboundOptions struct {
|
type WireGuardOutboundOptions struct {
|
||||||
DialerOptions
|
DialerOptions
|
||||||
ServerOptions
|
ServerOptions
|
||||||
LocalAddress Listable[string] `json:"local_address"`
|
SystemInterface bool `json:"system_interface,omitempty"`
|
||||||
PrivateKey string `json:"private_key"`
|
InterfaceName string `json:"interface_name,omitempty"`
|
||||||
PeerPublicKey string `json:"peer_public_key"`
|
LocalAddress Listable[ListenPrefix] `json:"local_address"`
|
||||||
PreSharedKey string `json:"pre_shared_key,omitempty"`
|
PrivateKey string `json:"private_key"`
|
||||||
MTU uint32 `json:"mtu,omitempty"`
|
PeerPublicKey string `json:"peer_public_key"`
|
||||||
Network NetworkList `json:"network,omitempty"`
|
PreSharedKey string `json:"pre_shared_key,omitempty"`
|
||||||
|
MTU uint32 `json:"mtu,omitempty"`
|
||||||
|
Network NetworkList `json:"network,omitempty"`
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -79,9 +79,7 @@ func NewEarlyConnection(ctx context.Context, this N.Dialer, conn net.Conn, metad
|
|||||||
func NewPacketConnection(ctx context.Context, this N.Dialer, conn N.PacketConn, metadata adapter.InboundContext) error {
|
func NewPacketConnection(ctx context.Context, this N.Dialer, conn N.PacketConn, metadata adapter.InboundContext) error {
|
||||||
switch metadata.Protocol {
|
switch metadata.Protocol {
|
||||||
case C.ProtocolQUIC, C.ProtocolDNS:
|
case C.ProtocolQUIC, C.ProtocolDNS:
|
||||||
if !metadata.Destination.Addr.IsUnspecified() {
|
return connectPacketConnection(ctx, this, conn, metadata)
|
||||||
return connectPacketConnection(ctx, this, conn, metadata)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
ctx = adapter.WithContext(ctx, &metadata)
|
ctx = adapter.WithContext(ctx, &metadata)
|
||||||
var outConn net.PacketConn
|
var outConn net.PacketConn
|
||||||
|
|||||||
@@ -20,9 +20,8 @@ var _ adapter.Outbound = (*Socks)(nil)
|
|||||||
|
|
||||||
type Socks struct {
|
type Socks struct {
|
||||||
myOutboundAdapter
|
myOutboundAdapter
|
||||||
client *socks.Client
|
client *socks.Client
|
||||||
resolve bool
|
uot bool
|
||||||
uot bool
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewSocks(router adapter.Router, logger log.ContextLogger, tag string, options option.SocksOutboundOptions) (*Socks, error) {
|
func NewSocks(router adapter.Router, logger log.ContextLogger, tag string, options option.SocksOutboundOptions) (*Socks, error) {
|
||||||
@@ -46,7 +45,6 @@ func NewSocks(router adapter.Router, logger log.ContextLogger, tag string, optio
|
|||||||
tag: tag,
|
tag: tag,
|
||||||
},
|
},
|
||||||
socks.NewClient(detour, options.ServerOptions.Build(), version, options.Username, options.Password),
|
socks.NewClient(detour, options.ServerOptions.Build(), version, options.Username, options.Password),
|
||||||
version == socks.Version4,
|
|
||||||
options.UoT,
|
options.UoT,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
@@ -74,13 +72,6 @@ func (h *Socks) DialContext(ctx context.Context, network string, destination M.S
|
|||||||
default:
|
default:
|
||||||
return nil, E.Extend(N.ErrUnknownNetwork, network)
|
return nil, E.Extend(N.ErrUnknownNetwork, network)
|
||||||
}
|
}
|
||||||
if h.resolve && destination.IsFqdn() {
|
|
||||||
addrs, err := h.router.LookupDefault(ctx, destination.Fqdn)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return N.DialSerial(ctx, h.client, network, destination, addrs)
|
|
||||||
}
|
|
||||||
return h.client.DialContext(ctx, network, destination)
|
return h.client.DialContext(ctx, network, destination)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -122,9 +122,6 @@ func (s *SSH) connect() (*ssh.Client, error) {
|
|||||||
Auth: s.authMethod,
|
Auth: s.authMethod,
|
||||||
ClientVersion: s.clientVersion,
|
ClientVersion: s.clientVersion,
|
||||||
HostKeyAlgorithms: s.hostKeyAlgorithms,
|
HostKeyAlgorithms: s.hostKeyAlgorithms,
|
||||||
HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
|
|
||||||
return nil
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
clientConn, chans, reqs, err := ssh.NewClientConn(conn, s.serverAddr.Addr.String(), config)
|
clientConn, chans, reqs, err := ssh.NewClientConn(conn, s.serverAddr.Addr.String(), config)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -8,49 +8,30 @@ import (
|
|||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
|
||||||
"os"
|
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
|
||||||
|
|
||||||
"github.com/sagernet/sing-box/adapter"
|
"github.com/sagernet/sing-box/adapter"
|
||||||
"github.com/sagernet/sing-box/common/dialer"
|
"github.com/sagernet/sing-box/common/dialer"
|
||||||
C "github.com/sagernet/sing-box/constant"
|
C "github.com/sagernet/sing-box/constant"
|
||||||
"github.com/sagernet/sing-box/log"
|
"github.com/sagernet/sing-box/log"
|
||||||
"github.com/sagernet/sing-box/option"
|
"github.com/sagernet/sing-box/option"
|
||||||
|
"github.com/sagernet/sing-box/transport/wireguard"
|
||||||
"github.com/sagernet/sing/common"
|
"github.com/sagernet/sing/common"
|
||||||
"github.com/sagernet/sing/common/debug"
|
"github.com/sagernet/sing/common/debug"
|
||||||
E "github.com/sagernet/sing/common/exceptions"
|
E "github.com/sagernet/sing/common/exceptions"
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
N "github.com/sagernet/sing/common/network"
|
N "github.com/sagernet/sing/common/network"
|
||||||
|
|
||||||
"golang.zx2c4.com/wireguard/conn"
|
|
||||||
"golang.zx2c4.com/wireguard/device"
|
"golang.zx2c4.com/wireguard/device"
|
||||||
"golang.zx2c4.com/wireguard/tun"
|
|
||||||
"gvisor.dev/gvisor/pkg/bufferv2"
|
|
||||||
"gvisor.dev/gvisor/pkg/tcpip"
|
|
||||||
"gvisor.dev/gvisor/pkg/tcpip/adapters/gonet"
|
|
||||||
"gvisor.dev/gvisor/pkg/tcpip/header"
|
|
||||||
"gvisor.dev/gvisor/pkg/tcpip/network/ipv4"
|
|
||||||
"gvisor.dev/gvisor/pkg/tcpip/network/ipv6"
|
|
||||||
"gvisor.dev/gvisor/pkg/tcpip/stack"
|
|
||||||
"gvisor.dev/gvisor/pkg/tcpip/transport/icmp"
|
|
||||||
"gvisor.dev/gvisor/pkg/tcpip/transport/tcp"
|
|
||||||
"gvisor.dev/gvisor/pkg/tcpip/transport/udp"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var _ adapter.Outbound = (*WireGuard)(nil)
|
var _ adapter.Outbound = (*WireGuard)(nil)
|
||||||
|
|
||||||
type WireGuard struct {
|
type WireGuard struct {
|
||||||
myOutboundAdapter
|
myOutboundAdapter
|
||||||
ctx context.Context
|
bind *wireguard.ClientBind
|
||||||
serverAddr M.Socksaddr
|
device *device.Device
|
||||||
dialer N.Dialer
|
tunDevice wireguard.Device
|
||||||
endpoint conn.Endpoint
|
|
||||||
device *device.Device
|
|
||||||
tunDevice *wireTunDevice
|
|
||||||
connAccess sync.Mutex
|
|
||||||
conn *wireConn
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewWireGuard(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.WireGuardOutboundOptions) (*WireGuard, error) {
|
func NewWireGuard(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.WireGuardOutboundOptions) (*WireGuard, error) {
|
||||||
@@ -62,39 +43,13 @@ func NewWireGuard(ctx context.Context, router adapter.Router, logger log.Context
|
|||||||
logger: logger,
|
logger: logger,
|
||||||
tag: tag,
|
tag: tag,
|
||||||
},
|
},
|
||||||
ctx: ctx,
|
|
||||||
serverAddr: options.ServerOptions.Build(),
|
|
||||||
dialer: dialer.New(router, options.DialerOptions),
|
|
||||||
}
|
}
|
||||||
var endpointIp netip.Addr
|
peerAddr := options.ServerOptions.Build()
|
||||||
if !outbound.serverAddr.IsFqdn() {
|
outbound.bind = wireguard.NewClientBind(ctx, dialer.New(router, options.DialerOptions), peerAddr)
|
||||||
endpointIp = outbound.serverAddr.Addr
|
localPrefixes := common.Map(options.LocalAddress, option.ListenPrefix.Build)
|
||||||
} else {
|
if len(localPrefixes) == 0 {
|
||||||
endpointIp = netip.AddrFrom4([4]byte{127, 0, 0, 1})
|
|
||||||
}
|
|
||||||
outbound.endpoint = conn.StdNetEndpoint(netip.AddrPortFrom(endpointIp, outbound.serverAddr.Port))
|
|
||||||
localAddress := make([]tcpip.AddressWithPrefix, len(options.LocalAddress))
|
|
||||||
if len(localAddress) == 0 {
|
|
||||||
return nil, E.New("missing local address")
|
return nil, E.New("missing local address")
|
||||||
}
|
}
|
||||||
for index, address := range options.LocalAddress {
|
|
||||||
if strings.Contains(address, "/") {
|
|
||||||
prefix, err := netip.ParsePrefix(address)
|
|
||||||
if err != nil {
|
|
||||||
return nil, E.Cause(err, "parse local address prefix ", address)
|
|
||||||
}
|
|
||||||
localAddress[index] = tcpip.AddressWithPrefix{
|
|
||||||
Address: tcpip.Address(prefix.Addr().AsSlice()),
|
|
||||||
PrefixLen: prefix.Bits(),
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
addr, err := netip.ParseAddr(address)
|
|
||||||
if err != nil {
|
|
||||||
return nil, E.Cause(err, "parse local address ", address)
|
|
||||||
}
|
|
||||||
localAddress[index] = tcpip.Address(addr.AsSlice()).WithPrefix()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
var privateKey, peerPublicKey, preSharedKey string
|
var privateKey, peerPublicKey, preSharedKey string
|
||||||
{
|
{
|
||||||
bytes, err := base64.StdEncoding.DecodeString(options.PrivateKey)
|
bytes, err := base64.StdEncoding.DecodeString(options.PrivateKey)
|
||||||
@@ -119,13 +74,13 @@ func NewWireGuard(ctx context.Context, router adapter.Router, logger log.Context
|
|||||||
}
|
}
|
||||||
ipcConf := "private_key=" + privateKey
|
ipcConf := "private_key=" + privateKey
|
||||||
ipcConf += "\npublic_key=" + peerPublicKey
|
ipcConf += "\npublic_key=" + peerPublicKey
|
||||||
ipcConf += "\nendpoint=" + outbound.endpoint.DstToString()
|
ipcConf += "\nendpoint=" + peerAddr.String()
|
||||||
if preSharedKey != "" {
|
if preSharedKey != "" {
|
||||||
ipcConf += "\npreshared_key=" + preSharedKey
|
ipcConf += "\npreshared_key=" + preSharedKey
|
||||||
}
|
}
|
||||||
var has4, has6 bool
|
var has4, has6 bool
|
||||||
for _, address := range localAddress {
|
for _, address := range localPrefixes {
|
||||||
if address.Address.To4() != "" {
|
if address.Addr().Is4() {
|
||||||
has4 = true
|
has4 = true
|
||||||
} else {
|
} else {
|
||||||
has6 = true
|
has6 = true
|
||||||
@@ -141,11 +96,17 @@ func NewWireGuard(ctx context.Context, router adapter.Router, logger log.Context
|
|||||||
if mtu == 0 {
|
if mtu == 0 {
|
||||||
mtu = 1408
|
mtu = 1408
|
||||||
}
|
}
|
||||||
wireDevice, err := newWireDevice(localAddress, mtu)
|
var wireTunDevice wireguard.Device
|
||||||
if err != nil {
|
var err error
|
||||||
return nil, err
|
if !options.SystemInterface {
|
||||||
|
wireTunDevice, err = wireguard.NewStackDevice(localPrefixes, mtu)
|
||||||
|
} else {
|
||||||
|
wireTunDevice, err = wireguard.NewSystemDevice(router, options.InterfaceName, localPrefixes, mtu)
|
||||||
}
|
}
|
||||||
wgDevice := device.NewDevice(wireDevice, (*wireClientBind)(outbound), &device.Logger{
|
if err != nil {
|
||||||
|
return nil, E.Cause(err, "create WireGuard device")
|
||||||
|
}
|
||||||
|
wgDevice := device.NewDevice(wireTunDevice, outbound.bind, &device.Logger{
|
||||||
Verbosef: func(format string, args ...interface{}) {
|
Verbosef: func(format string, args ...interface{}) {
|
||||||
logger.Debug(fmt.Sprintf(strings.ToLower(format), args...))
|
logger.Debug(fmt.Sprintf(strings.ToLower(format), args...))
|
||||||
},
|
},
|
||||||
@@ -161,7 +122,7 @@ func NewWireGuard(ctx context.Context, router adapter.Router, logger log.Context
|
|||||||
return nil, E.Cause(err, "setup wireguard")
|
return nil, E.Cause(err, "setup wireguard")
|
||||||
}
|
}
|
||||||
outbound.device = wgDevice
|
outbound.device = wgDevice
|
||||||
outbound.tunDevice = wireDevice
|
outbound.tunDevice = wireTunDevice
|
||||||
return outbound, nil
|
return outbound, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -172,54 +133,19 @@ func (w *WireGuard) DialContext(ctx context.Context, network string, destination
|
|||||||
case N.NetworkUDP:
|
case N.NetworkUDP:
|
||||||
w.logger.InfoContext(ctx, "outbound packet connection to ", destination)
|
w.logger.InfoContext(ctx, "outbound packet connection to ", destination)
|
||||||
}
|
}
|
||||||
addr := tcpip.FullAddress{
|
|
||||||
NIC: defaultNIC,
|
|
||||||
Port: destination.Port,
|
|
||||||
}
|
|
||||||
if destination.IsFqdn() {
|
if destination.IsFqdn() {
|
||||||
addrs, err := w.router.LookupDefault(ctx, destination.Fqdn)
|
addrs, err := w.router.LookupDefault(ctx, destination.Fqdn)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
addr.Addr = tcpip.Address(addrs[0].AsSlice())
|
return N.DialSerial(ctx, w.tunDevice, network, destination, addrs)
|
||||||
} else {
|
|
||||||
addr.Addr = tcpip.Address(destination.Addr.AsSlice())
|
|
||||||
}
|
|
||||||
bind := tcpip.FullAddress{
|
|
||||||
NIC: defaultNIC,
|
|
||||||
}
|
|
||||||
var networkProtocol tcpip.NetworkProtocolNumber
|
|
||||||
if destination.IsIPv4() {
|
|
||||||
networkProtocol = header.IPv4ProtocolNumber
|
|
||||||
bind.Addr = w.tunDevice.addr4
|
|
||||||
} else {
|
|
||||||
networkProtocol = header.IPv6ProtocolNumber
|
|
||||||
bind.Addr = w.tunDevice.addr6
|
|
||||||
}
|
|
||||||
switch N.NetworkName(network) {
|
|
||||||
case N.NetworkTCP:
|
|
||||||
return gonet.DialTCPWithBind(ctx, w.tunDevice.stack, bind, addr, networkProtocol)
|
|
||||||
case N.NetworkUDP:
|
|
||||||
return gonet.DialUDP(w.tunDevice.stack, &bind, &addr, networkProtocol)
|
|
||||||
default:
|
|
||||||
return nil, E.Extend(N.ErrUnknownNetwork, network)
|
|
||||||
}
|
}
|
||||||
|
return w.tunDevice.DialContext(ctx, network, destination)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (w *WireGuard) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
|
func (w *WireGuard) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
|
||||||
w.logger.InfoContext(ctx, "outbound packet connection to ", destination)
|
w.logger.InfoContext(ctx, "outbound packet connection to ", destination)
|
||||||
bind := tcpip.FullAddress{
|
return w.tunDevice.ListenPacket(ctx, destination)
|
||||||
NIC: defaultNIC,
|
|
||||||
}
|
|
||||||
var networkProtocol tcpip.NetworkProtocolNumber
|
|
||||||
if destination.IsIPv4() || w.tunDevice.addr6 == "" {
|
|
||||||
networkProtocol = header.IPv4ProtocolNumber
|
|
||||||
bind.Addr = w.tunDevice.addr4
|
|
||||||
} else {
|
|
||||||
networkProtocol = header.IPv6ProtocolNumber
|
|
||||||
bind.Addr = w.tunDevice.addr6
|
|
||||||
}
|
|
||||||
return gonet.DialUDP(w.tunDevice.stack, &bind, nil, networkProtocol)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (w *WireGuard) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
|
func (w *WireGuard) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
|
||||||
@@ -231,300 +157,13 @@ func (w *WireGuard) NewPacketConnection(ctx context.Context, conn N.PacketConn,
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (w *WireGuard) Start() error {
|
func (w *WireGuard) Start() error {
|
||||||
w.tunDevice.events <- tun.EventUp
|
return w.tunDevice.Start()
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (w *WireGuard) Close() error {
|
func (w *WireGuard) Close() error {
|
||||||
return common.Close(
|
return common.Close(
|
||||||
common.PtrOrNil(w.tunDevice),
|
w.tunDevice,
|
||||||
common.PtrOrNil(w.device),
|
common.PtrOrNil(w.device),
|
||||||
common.PtrOrNil(w.conn),
|
common.PtrOrNil(w.bind),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
var _ conn.Bind = (*wireClientBind)(nil)
|
|
||||||
|
|
||||||
type wireClientBind WireGuard
|
|
||||||
|
|
||||||
func (c *wireClientBind) connect() (*wireConn, error) {
|
|
||||||
c.connAccess.Lock()
|
|
||||||
defer c.connAccess.Unlock()
|
|
||||||
if c.conn != nil {
|
|
||||||
select {
|
|
||||||
case <-c.conn.done:
|
|
||||||
default:
|
|
||||||
return c.conn, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
udpConn, err := c.dialer.DialContext(c.ctx, "udp", c.serverAddr)
|
|
||||||
if err != nil {
|
|
||||||
return nil, &wireError{err}
|
|
||||||
}
|
|
||||||
c.conn = &wireConn{
|
|
||||||
Conn: udpConn,
|
|
||||||
done: make(chan struct{}),
|
|
||||||
}
|
|
||||||
return c.conn, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *wireClientBind) Open(port uint16) (fns []conn.ReceiveFunc, actualPort uint16, err error) {
|
|
||||||
return []conn.ReceiveFunc{c.receive}, 0, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *wireClientBind) receive(b []byte) (n int, ep conn.Endpoint, err error) {
|
|
||||||
udpConn, err := c.connect()
|
|
||||||
if err != nil {
|
|
||||||
err = &wireError{err}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
n, err = udpConn.Read(b)
|
|
||||||
if err != nil {
|
|
||||||
udpConn.Close()
|
|
||||||
err = &wireError{err}
|
|
||||||
}
|
|
||||||
ep = c.endpoint
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *wireClientBind) Close() error {
|
|
||||||
c.connAccess.Lock()
|
|
||||||
defer c.connAccess.Unlock()
|
|
||||||
common.Close(common.PtrOrNil(c.conn))
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *wireClientBind) SetMark(mark uint32) error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *wireClientBind) Send(b []byte, ep conn.Endpoint) error {
|
|
||||||
udpConn, err := c.connect()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
_, err = udpConn.Write(b)
|
|
||||||
if err != nil {
|
|
||||||
udpConn.Close()
|
|
||||||
}
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *wireClientBind) ParseEndpoint(s string) (conn.Endpoint, error) {
|
|
||||||
return c.endpoint, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
type wireError struct {
|
|
||||||
cause error
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *wireError) Error() string {
|
|
||||||
return w.cause.Error()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *wireError) Timeout() bool {
|
|
||||||
if cause, causeNet := w.cause.(net.Error); causeNet {
|
|
||||||
return cause.Timeout()
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *wireError) Temporary() bool {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
type wireConn struct {
|
|
||||||
net.Conn
|
|
||||||
access sync.Mutex
|
|
||||||
done chan struct{}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *wireConn) Close() error {
|
|
||||||
w.access.Lock()
|
|
||||||
defer w.access.Unlock()
|
|
||||||
select {
|
|
||||||
case <-w.done:
|
|
||||||
return net.ErrClosed
|
|
||||||
default:
|
|
||||||
}
|
|
||||||
w.Conn.Close()
|
|
||||||
close(w.done)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var _ tun.Device = (*wireTunDevice)(nil)
|
|
||||||
|
|
||||||
const defaultNIC tcpip.NICID = 1
|
|
||||||
|
|
||||||
type wireTunDevice struct {
|
|
||||||
stack *stack.Stack
|
|
||||||
mtu uint32
|
|
||||||
events chan tun.Event
|
|
||||||
outbound chan *stack.PacketBuffer
|
|
||||||
dispatcher stack.NetworkDispatcher
|
|
||||||
done chan struct{}
|
|
||||||
addr4 tcpip.Address
|
|
||||||
addr6 tcpip.Address
|
|
||||||
}
|
|
||||||
|
|
||||||
func newWireDevice(localAddresses []tcpip.AddressWithPrefix, mtu uint32) (*wireTunDevice, error) {
|
|
||||||
ipStack := stack.New(stack.Options{
|
|
||||||
NetworkProtocols: []stack.NetworkProtocolFactory{ipv4.NewProtocol, ipv6.NewProtocol},
|
|
||||||
TransportProtocols: []stack.TransportProtocolFactory{tcp.NewProtocol, udp.NewProtocol, icmp.NewProtocol4, icmp.NewProtocol6},
|
|
||||||
HandleLocal: true,
|
|
||||||
})
|
|
||||||
tunDevice := &wireTunDevice{
|
|
||||||
stack: ipStack,
|
|
||||||
mtu: mtu,
|
|
||||||
events: make(chan tun.Event, 4),
|
|
||||||
outbound: make(chan *stack.PacketBuffer, 256),
|
|
||||||
done: make(chan struct{}),
|
|
||||||
}
|
|
||||||
err := ipStack.CreateNIC(defaultNIC, (*wireEndpoint)(tunDevice))
|
|
||||||
if err != nil {
|
|
||||||
return nil, E.New(err.String())
|
|
||||||
}
|
|
||||||
for _, addr := range localAddresses {
|
|
||||||
var protoAddr tcpip.ProtocolAddress
|
|
||||||
if len(addr.Address) == net.IPv4len {
|
|
||||||
tunDevice.addr4 = addr.Address
|
|
||||||
protoAddr = tcpip.ProtocolAddress{
|
|
||||||
Protocol: ipv4.ProtocolNumber,
|
|
||||||
AddressWithPrefix: addr,
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
tunDevice.addr6 = addr.Address
|
|
||||||
protoAddr = tcpip.ProtocolAddress{
|
|
||||||
Protocol: ipv6.ProtocolNumber,
|
|
||||||
AddressWithPrefix: addr,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
err = ipStack.AddProtocolAddress(defaultNIC, protoAddr, stack.AddressProperties{})
|
|
||||||
if err != nil {
|
|
||||||
return nil, E.New("parse local address ", protoAddr.AddressWithPrefix, ": ", err.String())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
sOpt := tcpip.TCPSACKEnabled(true)
|
|
||||||
ipStack.SetTransportProtocolOption(tcp.ProtocolNumber, &sOpt)
|
|
||||||
cOpt := tcpip.CongestionControlOption("cubic")
|
|
||||||
ipStack.SetTransportProtocolOption(tcp.ProtocolNumber, &cOpt)
|
|
||||||
ipStack.AddRoute(tcpip.Route{Destination: header.IPv4EmptySubnet, NIC: defaultNIC})
|
|
||||||
ipStack.AddRoute(tcpip.Route{Destination: header.IPv6EmptySubnet, NIC: defaultNIC})
|
|
||||||
return tunDevice, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *wireTunDevice) File() *os.File {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *wireTunDevice) Read(p []byte, offset int) (n int, err error) {
|
|
||||||
packetBuffer, ok := <-w.outbound
|
|
||||||
if !ok {
|
|
||||||
return 0, os.ErrClosed
|
|
||||||
}
|
|
||||||
defer packetBuffer.DecRef()
|
|
||||||
p = p[offset:]
|
|
||||||
for _, slice := range packetBuffer.AsSlices() {
|
|
||||||
n += copy(p[n:], slice)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *wireTunDevice) Write(p []byte, offset int) (n int, err error) {
|
|
||||||
p = p[offset:]
|
|
||||||
if len(p) == 0 {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
var networkProtocol tcpip.NetworkProtocolNumber
|
|
||||||
switch header.IPVersion(p) {
|
|
||||||
case header.IPv4Version:
|
|
||||||
networkProtocol = header.IPv4ProtocolNumber
|
|
||||||
case header.IPv6Version:
|
|
||||||
networkProtocol = header.IPv6ProtocolNumber
|
|
||||||
}
|
|
||||||
packetBuffer := stack.NewPacketBuffer(stack.PacketBufferOptions{
|
|
||||||
Payload: bufferv2.MakeWithData(p),
|
|
||||||
})
|
|
||||||
defer packetBuffer.DecRef()
|
|
||||||
w.dispatcher.DeliverNetworkPacket(networkProtocol, packetBuffer)
|
|
||||||
n = len(p)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *wireTunDevice) Flush() error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *wireTunDevice) MTU() (int, error) {
|
|
||||||
return int(w.mtu), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *wireTunDevice) Name() (string, error) {
|
|
||||||
return "sing-box", nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *wireTunDevice) Events() chan tun.Event {
|
|
||||||
return w.events
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *wireTunDevice) Close() error {
|
|
||||||
select {
|
|
||||||
case <-w.done:
|
|
||||||
return os.ErrClosed
|
|
||||||
default:
|
|
||||||
}
|
|
||||||
close(w.done)
|
|
||||||
w.stack.Close()
|
|
||||||
for _, endpoint := range w.stack.CleanupEndpoints() {
|
|
||||||
endpoint.Abort()
|
|
||||||
}
|
|
||||||
w.stack.Wait()
|
|
||||||
close(w.outbound)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var _ stack.LinkEndpoint = (*wireEndpoint)(nil)
|
|
||||||
|
|
||||||
type wireEndpoint wireTunDevice
|
|
||||||
|
|
||||||
func (ep *wireEndpoint) MTU() uint32 {
|
|
||||||
return ep.mtu
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ep *wireEndpoint) MaxHeaderLength() uint16 {
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ep *wireEndpoint) LinkAddress() tcpip.LinkAddress {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ep *wireEndpoint) Capabilities() stack.LinkEndpointCapabilities {
|
|
||||||
return stack.CapabilityNone
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ep *wireEndpoint) Attach(dispatcher stack.NetworkDispatcher) {
|
|
||||||
ep.dispatcher = dispatcher
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ep *wireEndpoint) IsAttached() bool {
|
|
||||||
return ep.dispatcher != nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ep *wireEndpoint) Wait() {
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ep *wireEndpoint) ARPHardwareType() header.ARPHardwareType {
|
|
||||||
return header.ARPHardwareNone
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ep *wireEndpoint) AddHeader(buffer *stack.PacketBuffer) {
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ep *wireEndpoint) WritePackets(list stack.PacketBufferList) (int, tcpip.Error) {
|
|
||||||
for _, packetBuffer := range list.AsSlice() {
|
|
||||||
packetBuffer.IncRef()
|
|
||||||
ep.outbound <- packetBuffer
|
|
||||||
}
|
|
||||||
return list.Len(), nil
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -244,7 +244,7 @@ func NewRouter(ctx context.Context, logger log.ContextLogger, dnsLogger log.Cont
|
|||||||
|
|
||||||
needInterfaceMonitor := options.AutoDetectInterface ||
|
needInterfaceMonitor := options.AutoDetectInterface ||
|
||||||
C.IsDarwin && common.Any(inbounds, func(inbound option.Inbound) bool {
|
C.IsDarwin && common.Any(inbounds, func(inbound option.Inbound) bool {
|
||||||
return inbound.HTTPOptions.SetSystemProxy || inbound.MixedOptions.SetSystemProxy
|
return inbound.HTTPOptions.SetSystemProxy || inbound.MixedOptions.SetSystemProxy || C.IsAndroid && inbound.TunOptions.AutoRoute
|
||||||
})
|
})
|
||||||
|
|
||||||
if router.interfaceBindManager != nil || needInterfaceMonitor {
|
if router.interfaceBindManager != nil || needInterfaceMonitor {
|
||||||
@@ -258,12 +258,24 @@ func NewRouter(ctx context.Context, logger log.ContextLogger, dnsLogger log.Cont
|
|||||||
}
|
}
|
||||||
|
|
||||||
if router.networkMonitor != nil && needInterfaceMonitor {
|
if router.networkMonitor != nil && needInterfaceMonitor {
|
||||||
interfaceMonitor, err := tun.NewDefaultInterfaceMonitor(router.networkMonitor)
|
interfaceMonitor, err := tun.NewDefaultInterfaceMonitor(router.networkMonitor, tun.DefaultInterfaceMonitorOptions{
|
||||||
|
OverrideAndroidVPN: options.OverrideAndroidVPN,
|
||||||
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, E.New("auto_detect_interface unsupported on current platform")
|
return nil, E.New("auto_detect_interface unsupported on current platform")
|
||||||
}
|
}
|
||||||
interfaceMonitor.RegisterCallback(func() error {
|
interfaceMonitor.RegisterCallback(func(event int) error {
|
||||||
router.logger.Info("updated default interface ", router.interfaceMonitor.DefaultInterfaceName(netip.IPv4Unspecified()), ", index ", router.interfaceMonitor.DefaultInterfaceIndex(netip.IPv4Unspecified()))
|
if C.IsAndroid {
|
||||||
|
var vpnStatus string
|
||||||
|
if router.interfaceMonitor.AndroidVPNEnabled() {
|
||||||
|
vpnStatus = "enabled"
|
||||||
|
} else {
|
||||||
|
vpnStatus = "disabled"
|
||||||
|
}
|
||||||
|
router.logger.Info("updated default interface ", router.interfaceMonitor.DefaultInterfaceName(netip.IPv4Unspecified()), ", index ", router.interfaceMonitor.DefaultInterfaceIndex(netip.IPv4Unspecified()), ", vpn ", vpnStatus)
|
||||||
|
} else {
|
||||||
|
router.logger.Info("updated default interface ", router.interfaceMonitor.DefaultInterfaceName(netip.IPv4Unspecified()), ", index ", router.interfaceMonitor.DefaultInterfaceIndex(netip.IPv4Unspecified()))
|
||||||
|
}
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
router.interfaceMonitor = interfaceMonitor
|
router.interfaceMonitor = interfaceMonitor
|
||||||
@@ -541,8 +553,8 @@ func (r *Router) RouteConnection(ctx context.Context, conn net.Conn, metadata ad
|
|||||||
if metadata.SniffEnabled {
|
if metadata.SniffEnabled {
|
||||||
buffer := buf.NewPacket()
|
buffer := buf.NewPacket()
|
||||||
buffer.FullReset()
|
buffer.FullReset()
|
||||||
sniffMetadata, _ := sniff.PeekStream(ctx, conn, buffer, sniff.StreamDomainNameQuery, sniff.TLSClientHello, sniff.HTTPHost)
|
sniffMetadata, err := sniff.PeekStream(ctx, conn, buffer, sniff.StreamDomainNameQuery, sniff.TLSClientHello, sniff.HTTPHost)
|
||||||
if sniffMetadata != nil {
|
if err == nil {
|
||||||
metadata.Protocol = sniffMetadata.Protocol
|
metadata.Protocol = sniffMetadata.Protocol
|
||||||
metadata.Domain = sniffMetadata.Domain
|
metadata.Domain = sniffMetadata.Domain
|
||||||
if metadata.SniffOverrideDestination && sniff.IsDomainName(metadata.Domain) {
|
if metadata.SniffOverrideDestination && sniff.IsDomainName(metadata.Domain) {
|
||||||
@@ -618,8 +630,8 @@ func (r *Router) RoutePacketConnection(ctx context.Context, conn N.PacketConn, m
|
|||||||
buffer.Release()
|
buffer.Release()
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
sniffMetadata, _ := sniff.PeekPacket(ctx, buffer.Bytes(), sniff.DomainNameQuery, sniff.QUICClientHello, sniff.STUNMessage)
|
sniffMetadata, err := sniff.PeekPacket(ctx, buffer.Bytes(), sniff.DomainNameQuery, sniff.QUICClientHello, sniff.STUNMessage)
|
||||||
if sniffMetadata != nil {
|
if err == nil {
|
||||||
metadata.Protocol = sniffMetadata.Protocol
|
metadata.Protocol = sniffMetadata.Protocol
|
||||||
metadata.Domain = sniffMetadata.Domain
|
metadata.Domain = sniffMetadata.Domain
|
||||||
if metadata.SniffOverrideDestination && sniff.IsDomainName(metadata.Domain) {
|
if metadata.SniffOverrideDestination && sniff.IsDomainName(metadata.Domain) {
|
||||||
@@ -667,12 +679,12 @@ func (r *Router) match(ctx context.Context, metadata *adapter.InboundContext, de
|
|||||||
}
|
}
|
||||||
processInfo, err := process.FindProcessInfo(r.processSearcher, ctx, metadata.Network, metadata.Source.AddrPort(), originDestination)
|
processInfo, err := process.FindProcessInfo(r.processSearcher, ctx, metadata.Network, metadata.Source.AddrPort(), originDestination)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
r.logger.DebugContext(ctx, "failed to search process: ", err)
|
r.logger.InfoContext(ctx, "failed to search process: ", err)
|
||||||
} else {
|
} else {
|
||||||
if processInfo.ProcessPath != "" {
|
if processInfo.ProcessPath != "" {
|
||||||
r.logger.DebugContext(ctx, "found process path: ", processInfo.ProcessPath)
|
r.logger.InfoContext(ctx, "found process path: ", processInfo.ProcessPath)
|
||||||
} else if processInfo.PackageName != "" {
|
} else if processInfo.PackageName != "" {
|
||||||
r.logger.DebugContext(ctx, "found package name: ", processInfo.PackageName)
|
r.logger.InfoContext(ctx, "found package name: ", processInfo.PackageName)
|
||||||
} else if processInfo.UserId != -1 {
|
} else if processInfo.UserId != -1 {
|
||||||
if /*needUserName &&*/ true {
|
if /*needUserName &&*/ true {
|
||||||
osUser, _ := user.LookupId(F.ToString(processInfo.UserId))
|
osUser, _ := user.LookupId(F.ToString(processInfo.UserId))
|
||||||
@@ -681,9 +693,9 @@ func (r *Router) match(ctx context.Context, metadata *adapter.InboundContext, de
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if processInfo.User != "" {
|
if processInfo.User != "" {
|
||||||
r.logger.DebugContext(ctx, "found user: ", processInfo.User)
|
r.logger.InfoContext(ctx, "found user: ", processInfo.User)
|
||||||
} else {
|
} else {
|
||||||
r.logger.DebugContext(ctx, "found user id: ", processInfo.UserId)
|
r.logger.InfoContext(ctx, "found user id: ", processInfo.UserId)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
metadata.ProcessInfo = processInfo
|
metadata.ProcessInfo = processInfo
|
||||||
|
|||||||
@@ -82,9 +82,6 @@ func (r *Router) Lookup(ctx context.Context, domain string, strategy dns.DomainS
|
|||||||
r.dnsLogger.InfoContext(ctx, "lookup succeed for ", domain, ": ", strings.Join(F.MapToString(addrs), " "))
|
r.dnsLogger.InfoContext(ctx, "lookup succeed for ", domain, ": ", strings.Join(F.MapToString(addrs), " "))
|
||||||
} else {
|
} else {
|
||||||
r.dnsLogger.ErrorContext(ctx, E.Cause(err, "lookup failed for ", domain))
|
r.dnsLogger.ErrorContext(ctx, E.Cause(err, "lookup failed for ", domain))
|
||||||
if err == nil {
|
|
||||||
err = dns.RCodeNameError
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return addrs, err
|
return addrs, err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -41,9 +41,7 @@ var _ adapter.Rule = (*DefaultRule)(nil)
|
|||||||
type DefaultRule struct {
|
type DefaultRule struct {
|
||||||
items []RuleItem
|
items []RuleItem
|
||||||
sourceAddressItems []RuleItem
|
sourceAddressItems []RuleItem
|
||||||
sourcePortItems []RuleItem
|
|
||||||
destinationAddressItems []RuleItem
|
destinationAddressItems []RuleItem
|
||||||
destinationPortItems []RuleItem
|
|
||||||
allItems []RuleItem
|
allItems []RuleItem
|
||||||
invert bool
|
invert bool
|
||||||
outbound string
|
outbound string
|
||||||
@@ -145,7 +143,7 @@ func NewDefaultRule(router adapter.Router, logger log.ContextLogger, options opt
|
|||||||
}
|
}
|
||||||
if len(options.SourcePort) > 0 {
|
if len(options.SourcePort) > 0 {
|
||||||
item := NewPortItem(true, options.SourcePort)
|
item := NewPortItem(true, options.SourcePort)
|
||||||
rule.sourcePortItems = append(rule.sourcePortItems, item)
|
rule.items = append(rule.items, item)
|
||||||
rule.allItems = append(rule.allItems, item)
|
rule.allItems = append(rule.allItems, item)
|
||||||
}
|
}
|
||||||
if len(options.SourcePortRange) > 0 {
|
if len(options.SourcePortRange) > 0 {
|
||||||
@@ -153,12 +151,12 @@ func NewDefaultRule(router adapter.Router, logger log.ContextLogger, options opt
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, E.Cause(err, "source_port_range")
|
return nil, E.Cause(err, "source_port_range")
|
||||||
}
|
}
|
||||||
rule.sourcePortItems = append(rule.sourcePortItems, item)
|
rule.items = append(rule.items, item)
|
||||||
rule.allItems = append(rule.allItems, item)
|
rule.allItems = append(rule.allItems, item)
|
||||||
}
|
}
|
||||||
if len(options.Port) > 0 {
|
if len(options.Port) > 0 {
|
||||||
item := NewPortItem(false, options.Port)
|
item := NewPortItem(false, options.Port)
|
||||||
rule.destinationPortItems = append(rule.destinationPortItems, item)
|
rule.items = append(rule.items, item)
|
||||||
rule.allItems = append(rule.allItems, item)
|
rule.allItems = append(rule.allItems, item)
|
||||||
}
|
}
|
||||||
if len(options.PortRange) > 0 {
|
if len(options.PortRange) > 0 {
|
||||||
@@ -166,7 +164,7 @@ func NewDefaultRule(router adapter.Router, logger log.ContextLogger, options opt
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, E.Cause(err, "port_range")
|
return nil, E.Cause(err, "port_range")
|
||||||
}
|
}
|
||||||
rule.destinationPortItems = append(rule.destinationPortItems, item)
|
rule.items = append(rule.items, item)
|
||||||
rule.allItems = append(rule.allItems, item)
|
rule.allItems = append(rule.allItems, item)
|
||||||
}
|
}
|
||||||
if len(options.ProcessName) > 0 {
|
if len(options.ProcessName) > 0 {
|
||||||
@@ -253,19 +251,6 @@ func (r *DefaultRule) Match(metadata *adapter.InboundContext) bool {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(r.sourcePortItems) > 0 {
|
|
||||||
var sourcePortMatch bool
|
|
||||||
for _, item := range r.sourcePortItems {
|
|
||||||
if item.Match(metadata) {
|
|
||||||
sourcePortMatch = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !sourcePortMatch {
|
|
||||||
return r.invert
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(r.destinationAddressItems) > 0 {
|
if len(r.destinationAddressItems) > 0 {
|
||||||
var destinationAddressMatch bool
|
var destinationAddressMatch bool
|
||||||
for _, item := range r.destinationAddressItems {
|
for _, item := range r.destinationAddressItems {
|
||||||
@@ -279,19 +264,6 @@ func (r *DefaultRule) Match(metadata *adapter.InboundContext) bool {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(r.destinationPortItems) > 0 {
|
|
||||||
var destinationPortMatch bool
|
|
||||||
for _, item := range r.destinationPortItems {
|
|
||||||
if item.Match(metadata) {
|
|
||||||
destinationPortMatch = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !destinationPortMatch {
|
|
||||||
return r.invert
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return !r.invert
|
return !r.invert
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -39,15 +39,12 @@ func NewDNSRule(router adapter.Router, logger log.ContextLogger, options option.
|
|||||||
var _ adapter.DNSRule = (*DefaultDNSRule)(nil)
|
var _ adapter.DNSRule = (*DefaultDNSRule)(nil)
|
||||||
|
|
||||||
type DefaultDNSRule struct {
|
type DefaultDNSRule struct {
|
||||||
items []RuleItem
|
items []RuleItem
|
||||||
sourceAddressItems []RuleItem
|
addressItems []RuleItem
|
||||||
sourcePortItems []RuleItem
|
allItems []RuleItem
|
||||||
destinationAddressItems []RuleItem
|
invert bool
|
||||||
destinationPortItems []RuleItem
|
outbound string
|
||||||
allItems []RuleItem
|
disableCache bool
|
||||||
invert bool
|
|
||||||
outbound string
|
|
||||||
disableCache bool
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewDefaultDNSRule(router adapter.Router, logger log.ContextLogger, options option.DefaultDNSRule) (*DefaultDNSRule, error) {
|
func NewDefaultDNSRule(router adapter.Router, logger log.ContextLogger, options option.DefaultDNSRule) (*DefaultDNSRule, error) {
|
||||||
@@ -93,12 +90,12 @@ func NewDefaultDNSRule(router adapter.Router, logger log.ContextLogger, options
|
|||||||
}
|
}
|
||||||
if len(options.Domain) > 0 || len(options.DomainSuffix) > 0 {
|
if len(options.Domain) > 0 || len(options.DomainSuffix) > 0 {
|
||||||
item := NewDomainItem(options.Domain, options.DomainSuffix)
|
item := NewDomainItem(options.Domain, options.DomainSuffix)
|
||||||
rule.destinationAddressItems = append(rule.destinationAddressItems, item)
|
rule.addressItems = append(rule.addressItems, item)
|
||||||
rule.allItems = append(rule.allItems, item)
|
rule.allItems = append(rule.allItems, item)
|
||||||
}
|
}
|
||||||
if len(options.DomainKeyword) > 0 {
|
if len(options.DomainKeyword) > 0 {
|
||||||
item := NewDomainKeywordItem(options.DomainKeyword)
|
item := NewDomainKeywordItem(options.DomainKeyword)
|
||||||
rule.destinationAddressItems = append(rule.destinationAddressItems, item)
|
rule.addressItems = append(rule.addressItems, item)
|
||||||
rule.allItems = append(rule.allItems, item)
|
rule.allItems = append(rule.allItems, item)
|
||||||
}
|
}
|
||||||
if len(options.DomainRegex) > 0 {
|
if len(options.DomainRegex) > 0 {
|
||||||
@@ -106,17 +103,17 @@ func NewDefaultDNSRule(router adapter.Router, logger log.ContextLogger, options
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, E.Cause(err, "domain_regex")
|
return nil, E.Cause(err, "domain_regex")
|
||||||
}
|
}
|
||||||
rule.destinationAddressItems = append(rule.destinationAddressItems, item)
|
rule.addressItems = append(rule.addressItems, item)
|
||||||
rule.allItems = append(rule.allItems, item)
|
rule.allItems = append(rule.allItems, item)
|
||||||
}
|
}
|
||||||
if len(options.Geosite) > 0 {
|
if len(options.Geosite) > 0 {
|
||||||
item := NewGeositeItem(router, logger, options.Geosite)
|
item := NewGeositeItem(router, logger, options.Geosite)
|
||||||
rule.destinationAddressItems = append(rule.destinationAddressItems, item)
|
rule.addressItems = append(rule.addressItems, item)
|
||||||
rule.allItems = append(rule.allItems, item)
|
rule.allItems = append(rule.allItems, item)
|
||||||
}
|
}
|
||||||
if len(options.SourceGeoIP) > 0 {
|
if len(options.SourceGeoIP) > 0 {
|
||||||
item := NewGeoIPItem(router, logger, true, options.SourceGeoIP)
|
item := NewGeoIPItem(router, logger, true, options.SourceGeoIP)
|
||||||
rule.sourceAddressItems = append(rule.sourceAddressItems, item)
|
rule.items = append(rule.items, item)
|
||||||
rule.allItems = append(rule.allItems, item)
|
rule.allItems = append(rule.allItems, item)
|
||||||
}
|
}
|
||||||
if len(options.SourceIPCIDR) > 0 {
|
if len(options.SourceIPCIDR) > 0 {
|
||||||
@@ -124,12 +121,12 @@ func NewDefaultDNSRule(router adapter.Router, logger log.ContextLogger, options
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, E.Cause(err, "source_ipcidr")
|
return nil, E.Cause(err, "source_ipcidr")
|
||||||
}
|
}
|
||||||
rule.sourceAddressItems = append(rule.sourceAddressItems, item)
|
rule.items = append(rule.items, item)
|
||||||
rule.allItems = append(rule.allItems, item)
|
rule.allItems = append(rule.allItems, item)
|
||||||
}
|
}
|
||||||
if len(options.SourcePort) > 0 {
|
if len(options.SourcePort) > 0 {
|
||||||
item := NewPortItem(true, options.SourcePort)
|
item := NewPortItem(true, options.SourcePort)
|
||||||
rule.sourcePortItems = append(rule.sourcePortItems, item)
|
rule.items = append(rule.items, item)
|
||||||
rule.allItems = append(rule.allItems, item)
|
rule.allItems = append(rule.allItems, item)
|
||||||
}
|
}
|
||||||
if len(options.SourcePortRange) > 0 {
|
if len(options.SourcePortRange) > 0 {
|
||||||
@@ -137,12 +134,12 @@ func NewDefaultDNSRule(router adapter.Router, logger log.ContextLogger, options
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, E.Cause(err, "source_port_range")
|
return nil, E.Cause(err, "source_port_range")
|
||||||
}
|
}
|
||||||
rule.sourcePortItems = append(rule.sourcePortItems, item)
|
rule.items = append(rule.items, item)
|
||||||
rule.allItems = append(rule.allItems, item)
|
rule.allItems = append(rule.allItems, item)
|
||||||
}
|
}
|
||||||
if len(options.Port) > 0 {
|
if len(options.Port) > 0 {
|
||||||
item := NewPortItem(false, options.Port)
|
item := NewPortItem(false, options.Port)
|
||||||
rule.destinationPortItems = append(rule.destinationPortItems, item)
|
rule.items = append(rule.items, item)
|
||||||
rule.allItems = append(rule.allItems, item)
|
rule.allItems = append(rule.allItems, item)
|
||||||
}
|
}
|
||||||
if len(options.PortRange) > 0 {
|
if len(options.PortRange) > 0 {
|
||||||
@@ -150,7 +147,7 @@ func NewDefaultDNSRule(router adapter.Router, logger log.ContextLogger, options
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, E.Cause(err, "port_range")
|
return nil, E.Cause(err, "port_range")
|
||||||
}
|
}
|
||||||
rule.destinationPortItems = append(rule.destinationPortItems, item)
|
rule.items = append(rule.items, item)
|
||||||
rule.allItems = append(rule.allItems, item)
|
rule.allItems = append(rule.allItems, item)
|
||||||
}
|
}
|
||||||
if len(options.ProcessName) > 0 {
|
if len(options.ProcessName) > 0 {
|
||||||
@@ -228,59 +225,18 @@ func (r *DefaultDNSRule) Match(metadata *adapter.InboundContext) bool {
|
|||||||
return r.invert
|
return r.invert
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if len(r.addressItems) > 0 {
|
||||||
if len(r.sourceAddressItems) > 0 {
|
var addressMatch bool
|
||||||
var sourceAddressMatch bool
|
for _, item := range r.addressItems {
|
||||||
for _, item := range r.sourceAddressItems {
|
|
||||||
if item.Match(metadata) {
|
if item.Match(metadata) {
|
||||||
sourceAddressMatch = true
|
addressMatch = true
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if !sourceAddressMatch {
|
if !addressMatch {
|
||||||
return r.invert
|
return r.invert
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(r.sourcePortItems) > 0 {
|
|
||||||
var sourcePortMatch bool
|
|
||||||
for _, item := range r.sourcePortItems {
|
|
||||||
if item.Match(metadata) {
|
|
||||||
sourcePortMatch = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !sourcePortMatch {
|
|
||||||
return r.invert
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(r.destinationAddressItems) > 0 {
|
|
||||||
var destinationAddressMatch bool
|
|
||||||
for _, item := range r.destinationAddressItems {
|
|
||||||
if item.Match(metadata) {
|
|
||||||
destinationAddressMatch = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !destinationAddressMatch {
|
|
||||||
return r.invert
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(r.destinationPortItems) > 0 {
|
|
||||||
var destinationPortMatch bool
|
|
||||||
for _, item := range r.destinationPortItems {
|
|
||||||
if item.Match(metadata) {
|
|
||||||
destinationPortMatch = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !destinationPortMatch {
|
|
||||||
return r.invert
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return !r.invert
|
return !r.invert
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -82,20 +82,6 @@ func testSuitSimple(t *testing.T, clientPort uint16, testPort uint16) {
|
|||||||
require.NoError(t, testPingPongWithPacketConn(t, testPort, dialUDP))
|
require.NoError(t, testPingPongWithPacketConn(t, testPort, dialUDP))
|
||||||
}
|
}
|
||||||
|
|
||||||
func testSuitSimple1(t *testing.T, clientPort uint16, testPort uint16) {
|
|
||||||
dialer := socks.NewClient(N.SystemDialer, M.ParseSocksaddrHostPort("127.0.0.1", clientPort), socks.Version5, "", "")
|
|
||||||
dialTCP := func() (net.Conn, error) {
|
|
||||||
return dialer.DialContext(context.Background(), "tcp", M.ParseSocksaddrHostPort("127.0.0.1", testPort))
|
|
||||||
}
|
|
||||||
dialUDP := func() (net.PacketConn, error) {
|
|
||||||
return dialer.ListenPacket(context.Background(), M.ParseSocksaddrHostPort("127.0.0.1", testPort))
|
|
||||||
}
|
|
||||||
require.NoError(t, testPingPongWithConn(t, testPort, dialTCP))
|
|
||||||
require.NoError(t, testPingPongWithPacketConn(t, testPort, dialUDP))
|
|
||||||
require.NoError(t, testPingPongWithConn(t, testPort, dialTCP))
|
|
||||||
require.NoError(t, testLargeDataWithPacketConn(t, testPort, dialUDP))
|
|
||||||
}
|
|
||||||
|
|
||||||
func testSuitWg(t *testing.T, clientPort uint16, testPort uint16) {
|
func testSuitWg(t *testing.T, clientPort uint16, testPort uint16) {
|
||||||
dialer := socks.NewClient(N.SystemDialer, M.ParseSocksaddrHostPort("127.0.0.1", clientPort), socks.Version5, "", "")
|
dialer := socks.NewClient(N.SystemDialer, M.ParseSocksaddrHostPort("127.0.0.1", clientPort), socks.Version5, "", "")
|
||||||
dialTCP := func() (net.Conn, error) {
|
dialTCP := func() (net.Conn, error) {
|
||||||
@@ -108,8 +94,8 @@ func testSuitWg(t *testing.T, clientPort uint16, testPort uint16) {
|
|||||||
}
|
}
|
||||||
return bufio.NewUnbindPacketConn(conn), nil
|
return bufio.NewUnbindPacketConn(conn), nil
|
||||||
}
|
}
|
||||||
require.NoError(t, testPingPongWithConn(t, testPort, dialTCP))
|
|
||||||
require.NoError(t, testPingPongWithPacketConn(t, testPort, dialUDP))
|
|
||||||
require.NoError(t, testLargeDataWithConn(t, testPort, dialTCP))
|
require.NoError(t, testLargeDataWithConn(t, testPort, dialTCP))
|
||||||
require.NoError(t, testLargeDataWithPacketConn(t, testPort, dialUDP))
|
require.NoError(t, testLargeDataWithPacketConn(t, testPort, dialUDP))
|
||||||
|
// require.NoError(t, testPingPongWithConn(t, testPort, dialTCP))
|
||||||
|
// require.NoError(t, testPingPongWithPacketConn(t, testPort, dialUDP))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -385,24 +385,21 @@ func testLargeDataWithPacketConn(t *testing.T, port uint16, pcc func() (net.Pack
|
|||||||
hashMap := map[int][]byte{}
|
hashMap := map[int][]byte{}
|
||||||
mux := sync.Mutex{}
|
mux := sync.Mutex{}
|
||||||
for i := 0; i < times; i++ {
|
for i := 0; i < times; i++ {
|
||||||
go func(idx int) {
|
buf := make([]byte, chunkSize)
|
||||||
buf := make([]byte, chunkSize)
|
if _, err = rand.Read(buf[1:]); err != nil {
|
||||||
if _, err := rand.Read(buf[1:]); err != nil {
|
t.Log(err.Error())
|
||||||
t.Log(err.Error())
|
continue
|
||||||
return
|
}
|
||||||
}
|
buf[0] = byte(i)
|
||||||
buf[0] = byte(idx)
|
|
||||||
|
|
||||||
hash := md5.Sum(buf)
|
hash := md5.Sum(buf)
|
||||||
mux.Lock()
|
mux.Lock()
|
||||||
hashMap[idx] = hash[:]
|
hashMap[i] = hash[:]
|
||||||
mux.Unlock()
|
mux.Unlock()
|
||||||
|
if _, err = pc.WriteTo(buf, addr); err != nil {
|
||||||
if _, err := pc.WriteTo(buf, addr); err != nil {
|
t.Log(err)
|
||||||
t.Log(err.Error())
|
continue
|
||||||
return
|
}
|
||||||
}
|
|
||||||
}(i)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return hashMap, nil
|
return hashMap, nil
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[Interface]
|
[Interface]
|
||||||
PrivateKey = gHWUGzTh5YCEV6k8dneVP537XhVtoQJPIlFNs2zsxlE=
|
PrivateKey = gHWUGzTh5YCEV6k8dneVP537XhVtoQJPIlFNs2zsxlE=
|
||||||
Address = 10.0.0.1/24
|
Address = 10.0.0.1/32
|
||||||
ListenPort = 10000
|
ListenPort = 10000
|
||||||
|
|
||||||
[Peer]
|
[Peer]
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ require (
|
|||||||
github.com/docker/docker v20.10.17+incompatible
|
github.com/docker/docker v20.10.17+incompatible
|
||||||
github.com/docker/go-connections v0.4.0
|
github.com/docker/go-connections v0.4.0
|
||||||
github.com/gofrs/uuid v4.2.0+incompatible
|
github.com/gofrs/uuid v4.2.0+incompatible
|
||||||
github.com/sagernet/sing v0.0.0-20220913004915-27ddefbb8921
|
github.com/sagernet/sing v0.0.0-20220903085538-02b9ca1cc133
|
||||||
github.com/sagernet/sing-shadowsocks v0.0.0-20220819002358-7461bb09a8f6
|
github.com/sagernet/sing-shadowsocks v0.0.0-20220819002358-7461bb09a8f6
|
||||||
github.com/spyzhov/ajson v0.7.1
|
github.com/spyzhov/ajson v0.7.1
|
||||||
github.com/stretchr/testify v1.8.0
|
github.com/stretchr/testify v1.8.0
|
||||||
@@ -37,6 +37,7 @@ require (
|
|||||||
github.com/golang/mock v1.6.0 // indirect
|
github.com/golang/mock v1.6.0 // indirect
|
||||||
github.com/golang/protobuf v1.5.2 // indirect
|
github.com/golang/protobuf v1.5.2 // indirect
|
||||||
github.com/google/btree v1.0.1 // indirect
|
github.com/google/btree v1.0.1 // indirect
|
||||||
|
github.com/gorilla/websocket v1.5.0 // indirect
|
||||||
github.com/hashicorp/yamux v0.1.1 // indirect
|
github.com/hashicorp/yamux v0.1.1 // indirect
|
||||||
github.com/klauspost/cpuid/v2 v2.1.0 // indirect
|
github.com/klauspost/cpuid/v2 v2.1.0 // indirect
|
||||||
github.com/libdns/libdns v0.2.1 // indirect
|
github.com/libdns/libdns v0.2.1 // indirect
|
||||||
@@ -62,9 +63,8 @@ require (
|
|||||||
github.com/sagernet/quic-go v0.0.0-20220818150011-de611ab3e2bb // indirect
|
github.com/sagernet/quic-go v0.0.0-20220818150011-de611ab3e2bb // indirect
|
||||||
github.com/sagernet/sing-dns v0.0.0-20220903082137-b1102b8fc961 // indirect
|
github.com/sagernet/sing-dns v0.0.0-20220903082137-b1102b8fc961 // indirect
|
||||||
github.com/sagernet/sing-tun v0.0.0-20220828031750-185b6c880a83 // indirect
|
github.com/sagernet/sing-tun v0.0.0-20220828031750-185b6c880a83 // indirect
|
||||||
github.com/sagernet/sing-vmess v0.0.0-20220913015714-c4ab86d40e12 // indirect
|
github.com/sagernet/sing-vmess v0.0.0-20220907073918-72d7fdf6825f // indirect
|
||||||
github.com/sagernet/smux v0.0.0-20220831015742-e0f1988e3195 // indirect
|
github.com/sagernet/smux v0.0.0-20220831015742-e0f1988e3195 // indirect
|
||||||
github.com/sagernet/websocket v0.0.0-20220913015213-615516348b4e // indirect
|
|
||||||
github.com/sirupsen/logrus v1.8.1 // indirect
|
github.com/sirupsen/logrus v1.8.1 // indirect
|
||||||
github.com/vishvananda/netns v0.0.0-20211101163701-50045581ed74 // indirect
|
github.com/vishvananda/netns v0.0.0-20211101163701-50045581ed74 // indirect
|
||||||
go.uber.org/atomic v1.10.0 // indirect
|
go.uber.org/atomic v1.10.0 // indirect
|
||||||
|
|||||||
12
test/go.sum
12
test/go.sum
@@ -85,6 +85,8 @@ github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/
|
|||||||
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||||
github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg=
|
github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg=
|
||||||
github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
|
github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc=
|
||||||
|
github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||||
github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw=
|
github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw=
|
||||||
github.com/hashicorp/yamux v0.1.1 h1:yrQxtgseBDrq9Y652vSRDvsKCJKOUD+GzTS4Y0Y8pvE=
|
github.com/hashicorp/yamux v0.1.1 h1:yrQxtgseBDrq9Y652vSRDvsKCJKOUD+GzTS4Y0Y8pvE=
|
||||||
github.com/hashicorp/yamux v0.1.1/go.mod h1:CtWFDAQgb7dxtzFs4tWbplKIe2jSi3+5vKbgIO0SLnQ=
|
github.com/hashicorp/yamux v0.1.1/go.mod h1:CtWFDAQgb7dxtzFs4tWbplKIe2jSi3+5vKbgIO0SLnQ=
|
||||||
@@ -153,20 +155,18 @@ github.com/sagernet/quic-go v0.0.0-20220818150011-de611ab3e2bb h1:wc0yQ+SBn4TaTY
|
|||||||
github.com/sagernet/quic-go v0.0.0-20220818150011-de611ab3e2bb/go.mod h1:MIccjRKnPTjWwAOpl+AUGWOkzyTd9tERytudxu+1ra4=
|
github.com/sagernet/quic-go v0.0.0-20220818150011-de611ab3e2bb/go.mod h1:MIccjRKnPTjWwAOpl+AUGWOkzyTd9tERytudxu+1ra4=
|
||||||
github.com/sagernet/sing v0.0.0-20220812082120-05f9836bff8f/go.mod h1:QVsS5L/ZA2Q5UhQwLrn0Trw+msNd/NPGEhBKR/ioWiY=
|
github.com/sagernet/sing v0.0.0-20220812082120-05f9836bff8f/go.mod h1:QVsS5L/ZA2Q5UhQwLrn0Trw+msNd/NPGEhBKR/ioWiY=
|
||||||
github.com/sagernet/sing v0.0.0-20220817130738-ce854cda8522/go.mod h1:QVsS5L/ZA2Q5UhQwLrn0Trw+msNd/NPGEhBKR/ioWiY=
|
github.com/sagernet/sing v0.0.0-20220817130738-ce854cda8522/go.mod h1:QVsS5L/ZA2Q5UhQwLrn0Trw+msNd/NPGEhBKR/ioWiY=
|
||||||
github.com/sagernet/sing v0.0.0-20220913004915-27ddefbb8921 h1:xUHzlIbdlPV/fkToIO9futp9lmKIY+72ezk/whQ8XsI=
|
github.com/sagernet/sing v0.0.0-20220903085538-02b9ca1cc133 h1:krnb8wKEFIdXhmJYlhJMbEcPsJFISy2fz90uHVz7hMU=
|
||||||
github.com/sagernet/sing v0.0.0-20220913004915-27ddefbb8921/go.mod h1:kZvzh1VDa/Dg/Bt5WaYKU0jl5ept8KKDpl3Ay4gRtRQ=
|
github.com/sagernet/sing v0.0.0-20220903085538-02b9ca1cc133/go.mod h1:kZvzh1VDa/Dg/Bt5WaYKU0jl5ept8KKDpl3Ay4gRtRQ=
|
||||||
github.com/sagernet/sing-dns v0.0.0-20220903082137-b1102b8fc961 h1:5JeqhvCGV6AQQiAO0V67Loh2eyO3JNjIQnvRF8NnTE0=
|
github.com/sagernet/sing-dns v0.0.0-20220903082137-b1102b8fc961 h1:5JeqhvCGV6AQQiAO0V67Loh2eyO3JNjIQnvRF8NnTE0=
|
||||||
github.com/sagernet/sing-dns v0.0.0-20220903082137-b1102b8fc961/go.mod h1:vKBBy4mNJRaFuJ8H6kYIOPofsZ1JT5mgdwIlebtvnZ4=
|
github.com/sagernet/sing-dns v0.0.0-20220903082137-b1102b8fc961/go.mod h1:vKBBy4mNJRaFuJ8H6kYIOPofsZ1JT5mgdwIlebtvnZ4=
|
||||||
github.com/sagernet/sing-shadowsocks v0.0.0-20220819002358-7461bb09a8f6 h1:JJfDeYYhWunvtxsU/mOVNTmFQmnzGx9dY034qG6G3g4=
|
github.com/sagernet/sing-shadowsocks v0.0.0-20220819002358-7461bb09a8f6 h1:JJfDeYYhWunvtxsU/mOVNTmFQmnzGx9dY034qG6G3g4=
|
||||||
github.com/sagernet/sing-shadowsocks v0.0.0-20220819002358-7461bb09a8f6/go.mod h1:EX3RbZvrwAkPI2nuGa78T2iQXmrkT+/VQtskjou42xM=
|
github.com/sagernet/sing-shadowsocks v0.0.0-20220819002358-7461bb09a8f6/go.mod h1:EX3RbZvrwAkPI2nuGa78T2iQXmrkT+/VQtskjou42xM=
|
||||||
github.com/sagernet/sing-tun v0.0.0-20220828031750-185b6c880a83 h1:SoWiHYuOCVedqA7T/CJSZUUrcPGKQb2wFKEq8DphiAI=
|
github.com/sagernet/sing-tun v0.0.0-20220828031750-185b6c880a83 h1:SoWiHYuOCVedqA7T/CJSZUUrcPGKQb2wFKEq8DphiAI=
|
||||||
github.com/sagernet/sing-tun v0.0.0-20220828031750-185b6c880a83/go.mod h1:76r07HS1WRcEI4mE9pFsohfTBUt1j/G9Avz6DaOP3VU=
|
github.com/sagernet/sing-tun v0.0.0-20220828031750-185b6c880a83/go.mod h1:76r07HS1WRcEI4mE9pFsohfTBUt1j/G9Avz6DaOP3VU=
|
||||||
github.com/sagernet/sing-vmess v0.0.0-20220913015714-c4ab86d40e12 h1:4HYGbTDDemgBVTmaspXbkgjJlXc3hYVjNxSddJndq8Y=
|
github.com/sagernet/sing-vmess v0.0.0-20220907073918-72d7fdf6825f h1:6l9aXZqAl1JqXJWi89KHpWnM/moQUPGG+XiwMc+yD0A=
|
||||||
github.com/sagernet/sing-vmess v0.0.0-20220913015714-c4ab86d40e12/go.mod h1:u66Vv7NHXJWfeAmhh7JuJp/cwxmuQlM56QoZ7B7Mmd0=
|
github.com/sagernet/sing-vmess v0.0.0-20220907073918-72d7fdf6825f/go.mod h1:u66Vv7NHXJWfeAmhh7JuJp/cwxmuQlM56QoZ7B7Mmd0=
|
||||||
github.com/sagernet/smux v0.0.0-20220831015742-e0f1988e3195 h1:5VBIbVw9q7aKbrFdT83mjkyvQ+VaRsQ6yflTepfln38=
|
github.com/sagernet/smux v0.0.0-20220831015742-e0f1988e3195 h1:5VBIbVw9q7aKbrFdT83mjkyvQ+VaRsQ6yflTepfln38=
|
||||||
github.com/sagernet/smux v0.0.0-20220831015742-e0f1988e3195/go.mod h1:yedWtra8nyGJ+SyI+ziwuaGMzBatbB10P1IOOZbbSK8=
|
github.com/sagernet/smux v0.0.0-20220831015742-e0f1988e3195/go.mod h1:yedWtra8nyGJ+SyI+ziwuaGMzBatbB10P1IOOZbbSK8=
|
||||||
github.com/sagernet/websocket v0.0.0-20220913015213-615516348b4e h1:7uw2njHFGE+VpWamge6o56j2RWk4omF6uLKKxMmcWvs=
|
|
||||||
github.com/sagernet/websocket v0.0.0-20220913015213-615516348b4e/go.mod h1:45TUl8+gH4SIKr4ykREbxKWTxkDlSzFENzctB1dVRRY=
|
|
||||||
github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
|
github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
|
||||||
github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE=
|
github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE=
|
||||||
github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
|
github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
|
||||||
|
|||||||
@@ -80,7 +80,7 @@ func TestHysteriaSelf(t *testing.T) {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
testSuitSimple1(t, clientPort, testPort)
|
testSuitSimple(t, clientPort, testPort)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestHysteriaInbound(t *testing.T) {
|
func TestHysteriaInbound(t *testing.T) {
|
||||||
@@ -171,5 +171,5 @@ func TestHysteriaOutbound(t *testing.T) {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
testSuit(t, clientPort, testPort)
|
testSuitSimple(t, clientPort, testPort)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -122,62 +122,3 @@ func TestTrojanSelf(t *testing.T) {
|
|||||||
})
|
})
|
||||||
testSuit(t, clientPort, testPort)
|
testSuit(t, clientPort, testPort)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestTrojanPlainSelf(t *testing.T) {
|
|
||||||
startInstance(t, option.Options{
|
|
||||||
Inbounds: []option.Inbound{
|
|
||||||
{
|
|
||||||
Type: C.TypeMixed,
|
|
||||||
Tag: "mixed-in",
|
|
||||||
MixedOptions: option.HTTPMixedInboundOptions{
|
|
||||||
ListenOptions: option.ListenOptions{
|
|
||||||
Listen: option.ListenAddress(netip.IPv4Unspecified()),
|
|
||||||
ListenPort: clientPort,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Type: C.TypeTrojan,
|
|
||||||
TrojanOptions: option.TrojanInboundOptions{
|
|
||||||
ListenOptions: option.ListenOptions{
|
|
||||||
Listen: option.ListenAddress(netip.IPv4Unspecified()),
|
|
||||||
ListenPort: serverPort,
|
|
||||||
},
|
|
||||||
Users: []option.TrojanUser{
|
|
||||||
{
|
|
||||||
Name: "sekai",
|
|
||||||
Password: "password",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
Outbounds: []option.Outbound{
|
|
||||||
{
|
|
||||||
Type: C.TypeDirect,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Type: C.TypeTrojan,
|
|
||||||
Tag: "trojan-out",
|
|
||||||
TrojanOptions: option.TrojanOutboundOptions{
|
|
||||||
ServerOptions: option.ServerOptions{
|
|
||||||
Server: "127.0.0.1",
|
|
||||||
ServerPort: serverPort,
|
|
||||||
},
|
|
||||||
Password: "password",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
Route: &option.RouteOptions{
|
|
||||||
Rules: []option.Rule{
|
|
||||||
{
|
|
||||||
DefaultOptions: option.DefaultRule{
|
|
||||||
Inbound: []string{"mixed-in"},
|
|
||||||
Outbound: "trojan-out",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
})
|
|
||||||
testSuit(t, clientPort, testPort)
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -161,7 +161,7 @@ func testV2RayGRPCOutbound(t *testing.T, forceLite bool) {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
testSuit(t, clientPort, testPort)
|
testSuitSimple(t, clientPort, testPort)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestV2RayGRPCLite(t *testing.T) {
|
func TestV2RayGRPCLite(t *testing.T) {
|
||||||
|
|||||||
@@ -266,7 +266,7 @@ func TestVMessQUICSelf(t *testing.T) {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
testSuit(t, clientPort, testPort)
|
testSuitSimple(t, clientPort, testPort)
|
||||||
}
|
}
|
||||||
|
|
||||||
func testV2RayTransportNOTLSSelf(t *testing.T, transport *option.V2RayTransportOptions) {
|
func testV2RayTransportNOTLSSelf(t *testing.T, transport *option.V2RayTransportOptions) {
|
||||||
@@ -330,5 +330,5 @@ func testV2RayTransportNOTLSSelf(t *testing.T, transport *option.V2RayTransportO
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
testSuit(t, clientPort, testPort)
|
testSuitSimple(t, clientPort, testPort)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -193,5 +193,5 @@ func testV2RayWebsocketOutbound(t *testing.T, maxEarlyData uint32, earlyDataHead
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
testSuit(t, clientPort, testPort)
|
testSuitSimple(t, clientPort, testPort)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -256,7 +256,7 @@ func testVMessOutboundWithV2Ray(t *testing.T, security string, uuid uuid.UUID, g
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
testSuit(t, clientPort, testPort)
|
testSuitSimple(t, clientPort, testPort)
|
||||||
}
|
}
|
||||||
|
|
||||||
func testVMessSelf(t *testing.T, security string, uuid uuid.UUID, alterId int, globalPadding bool, authenticatedLength bool, packetAddr bool) {
|
func testVMessSelf(t *testing.T, security string, uuid uuid.UUID, alterId int, globalPadding bool, authenticatedLength bool, packetAddr bool) {
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net/netip"
|
"net/netip"
|
||||||
|
"os"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -40,7 +41,7 @@ func TestWireGuard(t *testing.T) {
|
|||||||
Server: "127.0.0.1",
|
Server: "127.0.0.1",
|
||||||
ServerPort: serverPort,
|
ServerPort: serverPort,
|
||||||
},
|
},
|
||||||
LocalAddress: []string{"10.0.0.2/32"},
|
LocalAddress: []option.ListenPrefix{option.ListenPrefix(netip.MustParsePrefix("10.0.0.2/32"))},
|
||||||
PrivateKey: "qGnwlkZljMxeECW8fbwAWdvgntnbK7B8UmMFl3zM0mk=",
|
PrivateKey: "qGnwlkZljMxeECW8fbwAWdvgntnbK7B8UmMFl3zM0mk=",
|
||||||
PeerPublicKey: "QsdcBm+oJw2oNv0cIFXLIq1E850lgTBonup4qnKEQBg=",
|
PeerPublicKey: "QsdcBm+oJw2oNv0cIFXLIq1E850lgTBonup4qnKEQBg=",
|
||||||
},
|
},
|
||||||
@@ -49,3 +50,49 @@ func TestWireGuard(t *testing.T) {
|
|||||||
})
|
})
|
||||||
testSuitWg(t, clientPort, testPort)
|
testSuitWg(t, clientPort, testPort)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestWireGuardSystem(t *testing.T) {
|
||||||
|
if os.Getuid() != 0 {
|
||||||
|
t.Skip("requires root")
|
||||||
|
}
|
||||||
|
startDockerContainer(t, DockerOptions{
|
||||||
|
Image: ImageBoringTun,
|
||||||
|
Cap: []string{"MKNOD", "NET_ADMIN", "NET_RAW"},
|
||||||
|
Ports: []uint16{serverPort, testPort},
|
||||||
|
Bind: map[string]string{
|
||||||
|
"wireguard.conf": "/etc/wireguard/wg0.conf",
|
||||||
|
},
|
||||||
|
Cmd: []string{"wg0"},
|
||||||
|
})
|
||||||
|
time.Sleep(5 * time.Second)
|
||||||
|
startInstance(t, option.Options{
|
||||||
|
Inbounds: []option.Inbound{
|
||||||
|
{
|
||||||
|
Type: C.TypeMixed,
|
||||||
|
MixedOptions: option.HTTPMixedInboundOptions{
|
||||||
|
ListenOptions: option.ListenOptions{
|
||||||
|
Listen: option.ListenAddress(netip.IPv4Unspecified()),
|
||||||
|
ListenPort: clientPort,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
Outbounds: []option.Outbound{
|
||||||
|
{
|
||||||
|
Type: C.TypeWireGuard,
|
||||||
|
WireGuardOptions: option.WireGuardOutboundOptions{
|
||||||
|
InterfaceName: "wg",
|
||||||
|
ServerOptions: option.ServerOptions{
|
||||||
|
Server: "127.0.0.1",
|
||||||
|
ServerPort: serverPort,
|
||||||
|
},
|
||||||
|
LocalAddress: []option.ListenPrefix{option.ListenPrefix(netip.MustParsePrefix("10.0.0.2/32"))},
|
||||||
|
PrivateKey: "qGnwlkZljMxeECW8fbwAWdvgntnbK7B8UmMFl3zM0mk=",
|
||||||
|
PeerPublicKey: "QsdcBm+oJw2oNv0cIFXLIq1E850lgTBonup4qnKEQBg=",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
time.Sleep(10 * time.Second)
|
||||||
|
testSuitWg(t, clientPort, testPort)
|
||||||
|
}
|
||||||
|
|||||||
@@ -62,9 +62,7 @@ func NewClient(ctx context.Context, dialer N.Dialer, serverAddr M.Socksaddr, opt
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) Close() error {
|
func (c *Client) Close() error {
|
||||||
return common.Close(
|
return common.Close(c.conn)
|
||||||
common.PtrOrNil(c.conn),
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) connect() (*grpc.ClientConn, error) {
|
func (c *Client) connect() (*grpc.ClientConn, error) {
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ import (
|
|||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"net"
|
"net"
|
||||||
"os"
|
"os"
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/sagernet/sing-box/adapter"
|
"github.com/sagernet/sing-box/adapter"
|
||||||
"github.com/sagernet/sing-box/option"
|
"github.com/sagernet/sing-box/option"
|
||||||
@@ -14,8 +13,6 @@ import (
|
|||||||
|
|
||||||
"google.golang.org/grpc"
|
"google.golang.org/grpc"
|
||||||
"google.golang.org/grpc/credentials"
|
"google.golang.org/grpc/credentials"
|
||||||
gM "google.golang.org/grpc/metadata"
|
|
||||||
"google.golang.org/grpc/peer"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var _ adapter.V2RayServerTransport = (*Server)(nil)
|
var _ adapter.V2RayServerTransport = (*Server)(nil)
|
||||||
@@ -40,22 +37,7 @@ func NewServer(ctx context.Context, options option.V2RayGRPCOptions, tlsConfig *
|
|||||||
func (s *Server) Tun(server GunService_TunServer) error {
|
func (s *Server) Tun(server GunService_TunServer) error {
|
||||||
ctx, cancel := context.WithCancel(s.ctx)
|
ctx, cancel := context.WithCancel(s.ctx)
|
||||||
conn := NewGRPCConn(server, cancel)
|
conn := NewGRPCConn(server, cancel)
|
||||||
var metadata M.Metadata
|
go s.handler.NewConnection(ctx, conn, M.Metadata{})
|
||||||
if remotePeer, loaded := peer.FromContext(server.Context()); loaded {
|
|
||||||
metadata.Source = M.SocksaddrFromNet(remotePeer.Addr)
|
|
||||||
}
|
|
||||||
if grpcMetadata, loaded := gM.FromIncomingContext(server.Context()); loaded {
|
|
||||||
forwardFrom := strings.Join(grpcMetadata.Get("X-Forwarded-For"), ",")
|
|
||||||
if forwardFrom != "" {
|
|
||||||
for _, from := range strings.Split(forwardFrom, ",") {
|
|
||||||
originAddr := M.ParseSocksaddr(from)
|
|
||||||
if originAddr.IsValid() {
|
|
||||||
metadata.Source = originAddr.Unwrap()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
go s.handler.NewConnection(ctx, conn, metadata)
|
|
||||||
<-ctx.Done()
|
<-ctx.Done()
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"sync"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/sagernet/sing-box/common/baderror"
|
"github.com/sagernet/sing-box/common/baderror"
|
||||||
@@ -29,7 +28,6 @@ type GunConn struct {
|
|||||||
create chan struct{}
|
create chan struct{}
|
||||||
err error
|
err error
|
||||||
readRemaining int
|
readRemaining int
|
||||||
writeAccess sync.Mutex
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func newGunConn(reader io.Reader, writer io.Writer, flusher http.Flusher) *GunConn {
|
func newGunConn(reader io.Reader, writer io.Writer, flusher http.Flusher) *GunConn {
|
||||||
@@ -102,9 +100,7 @@ func (c *GunConn) Write(b []byte) (n int, err error) {
|
|||||||
grpcHeader := buf.Get(5)
|
grpcHeader := buf.Get(5)
|
||||||
grpcPayloadLen := uint32(1 + varuintLen + len(b))
|
grpcPayloadLen := uint32(1 + varuintLen + len(b))
|
||||||
binary.BigEndian.PutUint32(grpcHeader[1:5], grpcPayloadLen)
|
binary.BigEndian.PutUint32(grpcHeader[1:5], grpcPayloadLen)
|
||||||
c.writeAccess.Lock()
|
|
||||||
_, err = bufio.Copy(c.writer, io.MultiReader(bytes.NewReader(grpcHeader), bytes.NewReader(protobufHeader[:varuintLen+1]), bytes.NewReader(b)))
|
_, err = bufio.Copy(c.writer, io.MultiReader(bytes.NewReader(grpcHeader), bytes.NewReader(protobufHeader[:varuintLen+1]), bytes.NewReader(b)))
|
||||||
c.writeAccess.Unlock()
|
|
||||||
buf.Put(grpcHeader)
|
buf.Put(grpcHeader)
|
||||||
if c.flusher != nil {
|
if c.flusher != nil {
|
||||||
c.flusher.Flush()
|
c.flusher.Flush()
|
||||||
|
|||||||
@@ -14,7 +14,8 @@ import (
|
|||||||
E "github.com/sagernet/sing/common/exceptions"
|
E "github.com/sagernet/sing/common/exceptions"
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
N "github.com/sagernet/sing/common/network"
|
N "github.com/sagernet/sing/common/network"
|
||||||
"github.com/sagernet/websocket"
|
|
||||||
|
"github.com/gorilla/websocket"
|
||||||
)
|
)
|
||||||
|
|
||||||
var _ adapter.V2RayClientTransport = (*Client)(nil)
|
var _ adapter.V2RayClientTransport = (*Client)(nil)
|
||||||
|
|||||||
@@ -11,7 +11,8 @@ import (
|
|||||||
|
|
||||||
C "github.com/sagernet/sing-box/constant"
|
C "github.com/sagernet/sing-box/constant"
|
||||||
E "github.com/sagernet/sing/common/exceptions"
|
E "github.com/sagernet/sing/common/exceptions"
|
||||||
"github.com/sagernet/websocket"
|
|
||||||
|
"github.com/gorilla/websocket"
|
||||||
)
|
)
|
||||||
|
|
||||||
type WebsocketConn struct {
|
type WebsocketConn struct {
|
||||||
|
|||||||
@@ -19,7 +19,8 @@ import (
|
|||||||
M "github.com/sagernet/sing/common/metadata"
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
N "github.com/sagernet/sing/common/network"
|
N "github.com/sagernet/sing/common/network"
|
||||||
sHttp "github.com/sagernet/sing/protocol/http"
|
sHttp "github.com/sagernet/sing/protocol/http"
|
||||||
"github.com/sagernet/websocket"
|
|
||||||
|
"github.com/gorilla/websocket"
|
||||||
)
|
)
|
||||||
|
|
||||||
var _ adapter.V2RayServerTransport = (*Server)(nil)
|
var _ adapter.V2RayServerTransport = (*Server)(nil)
|
||||||
|
|||||||
132
transport/wireguard/client_bind.go
Normal file
132
transport/wireguard/client_bind.go
Normal file
@@ -0,0 +1,132 @@
|
|||||||
|
package wireguard
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"github.com/sagernet/sing/common"
|
||||||
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
|
N "github.com/sagernet/sing/common/network"
|
||||||
|
|
||||||
|
"golang.zx2c4.com/wireguard/conn"
|
||||||
|
)
|
||||||
|
|
||||||
|
var _ conn.Bind = (*ClientBind)(nil)
|
||||||
|
|
||||||
|
type ClientBind struct {
|
||||||
|
ctx context.Context
|
||||||
|
dialer N.Dialer
|
||||||
|
peerAddr M.Socksaddr
|
||||||
|
connAccess sync.Mutex
|
||||||
|
conn *wireConn
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewClientBind(ctx context.Context, dialer N.Dialer, peerAddr M.Socksaddr) *ClientBind {
|
||||||
|
return &ClientBind{
|
||||||
|
ctx: ctx,
|
||||||
|
dialer: dialer,
|
||||||
|
peerAddr: peerAddr,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *ClientBind) connect() (*wireConn, error) {
|
||||||
|
serverConn := c.conn
|
||||||
|
if serverConn != nil {
|
||||||
|
select {
|
||||||
|
case <-serverConn.done:
|
||||||
|
serverConn = nil
|
||||||
|
default:
|
||||||
|
return serverConn, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c.connAccess.Lock()
|
||||||
|
defer c.connAccess.Unlock()
|
||||||
|
serverConn = c.conn
|
||||||
|
if serverConn != nil {
|
||||||
|
select {
|
||||||
|
case <-serverConn.done:
|
||||||
|
serverConn = nil
|
||||||
|
default:
|
||||||
|
return serverConn, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
udpConn, err := c.dialer.DialContext(c.ctx, "udp", c.peerAddr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, &wireError{err}
|
||||||
|
}
|
||||||
|
c.conn = &wireConn{
|
||||||
|
Conn: udpConn,
|
||||||
|
done: make(chan struct{}),
|
||||||
|
}
|
||||||
|
return c.conn, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *ClientBind) Open(port uint16) (fns []conn.ReceiveFunc, actualPort uint16, err error) {
|
||||||
|
return []conn.ReceiveFunc{c.receive}, 0, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *ClientBind) receive(b []byte) (n int, ep conn.Endpoint, err error) {
|
||||||
|
udpConn, err := c.connect()
|
||||||
|
if err != nil {
|
||||||
|
err = &wireError{err}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
n, err = udpConn.Read(b)
|
||||||
|
if err != nil {
|
||||||
|
udpConn.Close()
|
||||||
|
err = &wireError{err}
|
||||||
|
}
|
||||||
|
ep = Endpoint(c.peerAddr)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *ClientBind) Close() error {
|
||||||
|
c.connAccess.Lock()
|
||||||
|
defer c.connAccess.Unlock()
|
||||||
|
common.Close(common.PtrOrNil(c.conn))
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *ClientBind) SetMark(mark uint32) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *ClientBind) Send(b []byte, ep conn.Endpoint) error {
|
||||||
|
udpConn, err := c.connect()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, err = udpConn.Write(b)
|
||||||
|
if err != nil {
|
||||||
|
udpConn.Close()
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *ClientBind) ParseEndpoint(s string) (conn.Endpoint, error) {
|
||||||
|
return Endpoint(c.peerAddr), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *ClientBind) Endpoint() conn.Endpoint {
|
||||||
|
return Endpoint(c.peerAddr)
|
||||||
|
}
|
||||||
|
|
||||||
|
type wireConn struct {
|
||||||
|
net.Conn
|
||||||
|
access sync.Mutex
|
||||||
|
done chan struct{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *wireConn) Close() error {
|
||||||
|
w.access.Lock()
|
||||||
|
defer w.access.Unlock()
|
||||||
|
select {
|
||||||
|
case <-w.done:
|
||||||
|
return net.ErrClosed
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
w.Conn.Close()
|
||||||
|
close(w.done)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
14
transport/wireguard/device.go
Normal file
14
transport/wireguard/device.go
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
package wireguard
|
||||||
|
|
||||||
|
import (
|
||||||
|
N "github.com/sagernet/sing/common/network"
|
||||||
|
|
||||||
|
"golang.zx2c4.com/wireguard/tun"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Device interface {
|
||||||
|
tun.Device
|
||||||
|
N.Dialer
|
||||||
|
Start() error
|
||||||
|
// NewEndpoint() (stack.LinkEndpoint, error)
|
||||||
|
}
|
||||||
254
transport/wireguard/device_stack.go
Normal file
254
transport/wireguard/device_stack.go
Normal file
@@ -0,0 +1,254 @@
|
|||||||
|
//go:build !no_gvisor
|
||||||
|
|
||||||
|
package wireguard
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net"
|
||||||
|
"net/netip"
|
||||||
|
"os"
|
||||||
|
|
||||||
|
E "github.com/sagernet/sing/common/exceptions"
|
||||||
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
|
N "github.com/sagernet/sing/common/network"
|
||||||
|
|
||||||
|
"golang.zx2c4.com/wireguard/tun"
|
||||||
|
"gvisor.dev/gvisor/pkg/bufferv2"
|
||||||
|
"gvisor.dev/gvisor/pkg/tcpip"
|
||||||
|
"gvisor.dev/gvisor/pkg/tcpip/adapters/gonet"
|
||||||
|
"gvisor.dev/gvisor/pkg/tcpip/header"
|
||||||
|
"gvisor.dev/gvisor/pkg/tcpip/network/ipv4"
|
||||||
|
"gvisor.dev/gvisor/pkg/tcpip/network/ipv6"
|
||||||
|
"gvisor.dev/gvisor/pkg/tcpip/stack"
|
||||||
|
"gvisor.dev/gvisor/pkg/tcpip/transport/icmp"
|
||||||
|
"gvisor.dev/gvisor/pkg/tcpip/transport/tcp"
|
||||||
|
"gvisor.dev/gvisor/pkg/tcpip/transport/udp"
|
||||||
|
)
|
||||||
|
|
||||||
|
var _ Device = (*StackDevice)(nil)
|
||||||
|
|
||||||
|
const defaultNIC tcpip.NICID = 1
|
||||||
|
|
||||||
|
type StackDevice struct {
|
||||||
|
stack *stack.Stack
|
||||||
|
mtu uint32
|
||||||
|
events chan tun.Event
|
||||||
|
outbound chan *stack.PacketBuffer
|
||||||
|
dispatcher stack.NetworkDispatcher
|
||||||
|
done chan struct{}
|
||||||
|
addr4 tcpip.Address
|
||||||
|
addr6 tcpip.Address
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewStackDevice(localAddresses []netip.Prefix, mtu uint32) (*StackDevice, error) {
|
||||||
|
ipStack := stack.New(stack.Options{
|
||||||
|
NetworkProtocols: []stack.NetworkProtocolFactory{ipv4.NewProtocol, ipv6.NewProtocol},
|
||||||
|
TransportProtocols: []stack.TransportProtocolFactory{tcp.NewProtocol, udp.NewProtocol, icmp.NewProtocol4, icmp.NewProtocol6},
|
||||||
|
HandleLocal: true,
|
||||||
|
})
|
||||||
|
tunDevice := &StackDevice{
|
||||||
|
stack: ipStack,
|
||||||
|
mtu: mtu,
|
||||||
|
events: make(chan tun.Event, 1),
|
||||||
|
outbound: make(chan *stack.PacketBuffer, 256),
|
||||||
|
done: make(chan struct{}),
|
||||||
|
}
|
||||||
|
err := ipStack.CreateNIC(defaultNIC, (*wireEndpoint)(tunDevice))
|
||||||
|
if err != nil {
|
||||||
|
return nil, E.New(err.String())
|
||||||
|
}
|
||||||
|
for _, prefix := range localAddresses {
|
||||||
|
addr := tcpip.Address(prefix.Addr().AsSlice())
|
||||||
|
protoAddr := tcpip.ProtocolAddress{
|
||||||
|
AddressWithPrefix: tcpip.AddressWithPrefix{
|
||||||
|
Address: addr,
|
||||||
|
PrefixLen: prefix.Bits(),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
if prefix.Addr().Is4() {
|
||||||
|
tunDevice.addr4 = addr
|
||||||
|
protoAddr.Protocol = ipv4.ProtocolNumber
|
||||||
|
} else {
|
||||||
|
tunDevice.addr6 = addr
|
||||||
|
protoAddr.Protocol = ipv6.ProtocolNumber
|
||||||
|
}
|
||||||
|
err = ipStack.AddProtocolAddress(defaultNIC, protoAddr, stack.AddressProperties{})
|
||||||
|
if err != nil {
|
||||||
|
return nil, E.New("parse local address ", protoAddr.AddressWithPrefix, ": ", err.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sOpt := tcpip.TCPSACKEnabled(true)
|
||||||
|
ipStack.SetTransportProtocolOption(tcp.ProtocolNumber, &sOpt)
|
||||||
|
cOpt := tcpip.CongestionControlOption("cubic")
|
||||||
|
ipStack.SetTransportProtocolOption(tcp.ProtocolNumber, &cOpt)
|
||||||
|
ipStack.AddRoute(tcpip.Route{Destination: header.IPv4EmptySubnet, NIC: defaultNIC})
|
||||||
|
ipStack.AddRoute(tcpip.Route{Destination: header.IPv6EmptySubnet, NIC: defaultNIC})
|
||||||
|
return tunDevice, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *StackDevice) NewEndpoint() (stack.LinkEndpoint, error) {
|
||||||
|
return (*wireEndpoint)(w), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *StackDevice) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
|
||||||
|
addr := tcpip.FullAddress{
|
||||||
|
NIC: defaultNIC,
|
||||||
|
Port: destination.Port,
|
||||||
|
Addr: tcpip.Address(destination.Addr.AsSlice()),
|
||||||
|
}
|
||||||
|
bind := tcpip.FullAddress{
|
||||||
|
NIC: defaultNIC,
|
||||||
|
}
|
||||||
|
var networkProtocol tcpip.NetworkProtocolNumber
|
||||||
|
if destination.IsIPv4() {
|
||||||
|
networkProtocol = header.IPv4ProtocolNumber
|
||||||
|
bind.Addr = w.addr4
|
||||||
|
} else {
|
||||||
|
networkProtocol = header.IPv6ProtocolNumber
|
||||||
|
bind.Addr = w.addr6
|
||||||
|
}
|
||||||
|
switch N.NetworkName(network) {
|
||||||
|
case N.NetworkTCP:
|
||||||
|
return gonet.DialTCPWithBind(ctx, w.stack, bind, addr, networkProtocol)
|
||||||
|
case N.NetworkUDP:
|
||||||
|
return gonet.DialUDP(w.stack, &bind, &addr, networkProtocol)
|
||||||
|
default:
|
||||||
|
return nil, E.Extend(N.ErrUnknownNetwork, network)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *StackDevice) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
|
||||||
|
bind := tcpip.FullAddress{
|
||||||
|
NIC: defaultNIC,
|
||||||
|
}
|
||||||
|
var networkProtocol tcpip.NetworkProtocolNumber
|
||||||
|
if destination.IsIPv4() || w.addr6 == "" {
|
||||||
|
networkProtocol = header.IPv4ProtocolNumber
|
||||||
|
bind.Addr = w.addr4
|
||||||
|
} else {
|
||||||
|
networkProtocol = header.IPv6ProtocolNumber
|
||||||
|
bind.Addr = w.addr6
|
||||||
|
}
|
||||||
|
return gonet.DialUDP(w.stack, &bind, nil, networkProtocol)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *StackDevice) Start() error {
|
||||||
|
w.events <- tun.EventUp
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *StackDevice) File() *os.File {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *StackDevice) Read(p []byte, offset int) (n int, err error) {
|
||||||
|
packetBuffer, ok := <-w.outbound
|
||||||
|
if !ok {
|
||||||
|
return 0, os.ErrClosed
|
||||||
|
}
|
||||||
|
defer packetBuffer.DecRef()
|
||||||
|
p = p[offset:]
|
||||||
|
for _, slice := range packetBuffer.AsSlices() {
|
||||||
|
n += copy(p[n:], slice)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *StackDevice) Write(p []byte, offset int) (n int, err error) {
|
||||||
|
p = p[offset:]
|
||||||
|
if len(p) == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var networkProtocol tcpip.NetworkProtocolNumber
|
||||||
|
switch header.IPVersion(p) {
|
||||||
|
case header.IPv4Version:
|
||||||
|
networkProtocol = header.IPv4ProtocolNumber
|
||||||
|
case header.IPv6Version:
|
||||||
|
networkProtocol = header.IPv6ProtocolNumber
|
||||||
|
}
|
||||||
|
packetBuffer := stack.NewPacketBuffer(stack.PacketBufferOptions{
|
||||||
|
Payload: bufferv2.MakeWithData(p),
|
||||||
|
})
|
||||||
|
defer packetBuffer.DecRef()
|
||||||
|
w.dispatcher.DeliverNetworkPacket(networkProtocol, packetBuffer)
|
||||||
|
n = len(p)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *StackDevice) Flush() error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *StackDevice) MTU() (int, error) {
|
||||||
|
return int(w.mtu), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *StackDevice) Name() (string, error) {
|
||||||
|
return "sing-box", nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *StackDevice) Events() chan tun.Event {
|
||||||
|
return w.events
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *StackDevice) Close() error {
|
||||||
|
select {
|
||||||
|
case <-w.done:
|
||||||
|
return os.ErrClosed
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
close(w.done)
|
||||||
|
w.stack.Close()
|
||||||
|
for _, endpoint := range w.stack.CleanupEndpoints() {
|
||||||
|
endpoint.Abort()
|
||||||
|
}
|
||||||
|
w.stack.Wait()
|
||||||
|
close(w.outbound)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ stack.LinkEndpoint = (*wireEndpoint)(nil)
|
||||||
|
|
||||||
|
type wireEndpoint StackDevice
|
||||||
|
|
||||||
|
func (ep *wireEndpoint) MTU() uint32 {
|
||||||
|
return ep.mtu
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ep *wireEndpoint) MaxHeaderLength() uint16 {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ep *wireEndpoint) LinkAddress() tcpip.LinkAddress {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ep *wireEndpoint) Capabilities() stack.LinkEndpointCapabilities {
|
||||||
|
return stack.CapabilityNone
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ep *wireEndpoint) Attach(dispatcher stack.NetworkDispatcher) {
|
||||||
|
ep.dispatcher = dispatcher
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ep *wireEndpoint) IsAttached() bool {
|
||||||
|
return ep.dispatcher != nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ep *wireEndpoint) Wait() {
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ep *wireEndpoint) ARPHardwareType() header.ARPHardwareType {
|
||||||
|
return header.ARPHardwareNone
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ep *wireEndpoint) AddHeader(buffer *stack.PacketBuffer) {
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ep *wireEndpoint) WritePackets(list stack.PacketBufferList) (int, tcpip.Error) {
|
||||||
|
for _, packetBuffer := range list.AsSlice() {
|
||||||
|
packetBuffer.IncRef()
|
||||||
|
ep.outbound <- packetBuffer
|
||||||
|
}
|
||||||
|
return list.Len(), nil
|
||||||
|
}
|
||||||
9
transport/wireguard/device_stack_stub.go
Normal file
9
transport/wireguard/device_stack_stub.go
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
//go:build no_gvisor
|
||||||
|
|
||||||
|
package wireguard
|
||||||
|
|
||||||
|
import "github.com/sagernet/sing-tun"
|
||||||
|
|
||||||
|
func NewStackDevice(localAddresses []netip.Prefix, mtu uint32) (Device, error) {
|
||||||
|
return nil, tun.ErrGVisorNotIncluded
|
||||||
|
}
|
||||||
110
transport/wireguard/device_system.go
Normal file
110
transport/wireguard/device_system.go
Normal file
@@ -0,0 +1,110 @@
|
|||||||
|
package wireguard
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net"
|
||||||
|
"net/netip"
|
||||||
|
"os"
|
||||||
|
|
||||||
|
"github.com/sagernet/sing-box/adapter"
|
||||||
|
"github.com/sagernet/sing-box/common/dialer"
|
||||||
|
"github.com/sagernet/sing-box/option"
|
||||||
|
"github.com/sagernet/sing-tun"
|
||||||
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
|
N "github.com/sagernet/sing/common/network"
|
||||||
|
|
||||||
|
wgTun "golang.zx2c4.com/wireguard/tun"
|
||||||
|
)
|
||||||
|
|
||||||
|
var _ Device = (*SystemDevice)(nil)
|
||||||
|
|
||||||
|
type SystemDevice struct {
|
||||||
|
dialer N.Dialer
|
||||||
|
device tun.Tun
|
||||||
|
name string
|
||||||
|
mtu int
|
||||||
|
events chan wgTun.Event
|
||||||
|
}
|
||||||
|
|
||||||
|
/*func (w *SystemDevice) NewEndpoint() (stack.LinkEndpoint, error) {
|
||||||
|
gTun, isGTun := w.device.(tun.GVisorTun)
|
||||||
|
if !isGTun {
|
||||||
|
return nil, tun.ErrGVisorUnsupported
|
||||||
|
}
|
||||||
|
return gTun.NewEndpoint()
|
||||||
|
}*/
|
||||||
|
|
||||||
|
func NewSystemDevice(router adapter.Router, interfaceName string, localPrefixes []netip.Prefix, mtu uint32) (*SystemDevice, error) {
|
||||||
|
var inet4Addresses []netip.Prefix
|
||||||
|
var inet6Addresses []netip.Prefix
|
||||||
|
for _, prefixes := range localPrefixes {
|
||||||
|
if prefixes.Addr().Is4() {
|
||||||
|
inet4Addresses = append(inet4Addresses, prefixes)
|
||||||
|
} else {
|
||||||
|
inet6Addresses = append(inet6Addresses, prefixes)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if interfaceName == "" {
|
||||||
|
interfaceName = tun.CalculateInterfaceName("wg")
|
||||||
|
}
|
||||||
|
tunInterface, err := tun.Open(tun.Options{
|
||||||
|
Name: interfaceName,
|
||||||
|
Inet4Address: inet4Addresses,
|
||||||
|
Inet6Address: inet6Addresses,
|
||||||
|
MTU: mtu,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &SystemDevice{
|
||||||
|
dialer.NewDefault(router, option.DialerOptions{
|
||||||
|
BindInterface: interfaceName,
|
||||||
|
}),
|
||||||
|
tunInterface, interfaceName, int(mtu), make(chan wgTun.Event),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *SystemDevice) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
|
||||||
|
return w.dialer.DialContext(ctx, network, destination)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *SystemDevice) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
|
||||||
|
return w.dialer.ListenPacket(ctx, destination)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *SystemDevice) Start() error {
|
||||||
|
w.events <- wgTun.EventUp
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *SystemDevice) File() *os.File {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *SystemDevice) Read(bytes []byte, index int) (int, error) {
|
||||||
|
return w.device.Read(bytes[index-tunPacketOffset:])
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *SystemDevice) Write(bytes []byte, index int) (int, error) {
|
||||||
|
return w.device.Write(bytes[index:])
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *SystemDevice) Flush() error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *SystemDevice) MTU() (int, error) {
|
||||||
|
return w.mtu, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *SystemDevice) Name() (string, error) {
|
||||||
|
return w.name, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *SystemDevice) Events() chan wgTun.Event {
|
||||||
|
return w.events
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *SystemDevice) Close() error {
|
||||||
|
return w.device.Close()
|
||||||
|
}
|
||||||
37
transport/wireguard/endpoint.go
Normal file
37
transport/wireguard/endpoint.go
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
package wireguard
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/netip"
|
||||||
|
|
||||||
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
|
|
||||||
|
"golang.zx2c4.com/wireguard/conn"
|
||||||
|
)
|
||||||
|
|
||||||
|
var _ conn.Endpoint = (*Endpoint)(nil)
|
||||||
|
|
||||||
|
type Endpoint M.Socksaddr
|
||||||
|
|
||||||
|
func (e Endpoint) ClearSrc() {
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e Endpoint) SrcToString() string {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e Endpoint) DstToString() string {
|
||||||
|
return (M.Socksaddr)(e).String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e Endpoint) DstToBytes() []byte {
|
||||||
|
b, _ := (M.Socksaddr)(e).AddrPort().MarshalBinary()
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e Endpoint) DstIP() netip.Addr {
|
||||||
|
return (M.Socksaddr)(e).Addr
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e Endpoint) SrcIP() netip.Addr {
|
||||||
|
return netip.Addr{}
|
||||||
|
}
|
||||||
22
transport/wireguard/error.go
Normal file
22
transport/wireguard/error.go
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
package wireguard
|
||||||
|
|
||||||
|
import "net"
|
||||||
|
|
||||||
|
type wireError struct {
|
||||||
|
cause error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *wireError) Error() string {
|
||||||
|
return w.cause.Error()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *wireError) Timeout() bool {
|
||||||
|
if cause, causeNet := w.cause.(net.Error); causeNet {
|
||||||
|
return cause.Timeout()
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *wireError) Temporary() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
96
transport/wireguard/server_bind.go
Normal file
96
transport/wireguard/server_bind.go
Normal file
@@ -0,0 +1,96 @@
|
|||||||
|
package wireguard
|
||||||
|
|
||||||
|
import (
|
||||||
|
"io"
|
||||||
|
|
||||||
|
"github.com/sagernet/sing/common/buf"
|
||||||
|
E "github.com/sagernet/sing/common/exceptions"
|
||||||
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
|
N "github.com/sagernet/sing/common/network"
|
||||||
|
|
||||||
|
"golang.zx2c4.com/wireguard/conn"
|
||||||
|
)
|
||||||
|
|
||||||
|
var _ conn.Bind = (*ServerBind)(nil)
|
||||||
|
|
||||||
|
type ServerBind struct {
|
||||||
|
inbound chan serverPacket
|
||||||
|
done chan struct{}
|
||||||
|
writeBack N.PacketWriter
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewServerBind(writeBack N.PacketWriter) *ServerBind {
|
||||||
|
return &ServerBind{
|
||||||
|
inbound: make(chan serverPacket, 256),
|
||||||
|
done: make(chan struct{}),
|
||||||
|
writeBack: writeBack,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ServerBind) Abort() error {
|
||||||
|
select {
|
||||||
|
case <-s.done:
|
||||||
|
return io.ErrClosedPipe
|
||||||
|
default:
|
||||||
|
close(s.done)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type serverPacket struct {
|
||||||
|
buffer *buf.Buffer
|
||||||
|
source M.Socksaddr
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ServerBind) Open(port uint16) (fns []conn.ReceiveFunc, actualPort uint16, err error) {
|
||||||
|
fns = []conn.ReceiveFunc{s.receive}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ServerBind) receive(b []byte) (n int, ep conn.Endpoint, err error) {
|
||||||
|
select {
|
||||||
|
case packet := <-s.inbound:
|
||||||
|
defer packet.buffer.Release()
|
||||||
|
n = copy(b, packet.buffer.Bytes())
|
||||||
|
ep = Endpoint(packet.source)
|
||||||
|
return
|
||||||
|
case <-s.done:
|
||||||
|
err = io.ErrClosedPipe
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ServerBind) WriteIsThreadUnsafe() {
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ServerBind) WritePacket(buffer *buf.Buffer, destination M.Socksaddr) error {
|
||||||
|
select {
|
||||||
|
case s.inbound <- serverPacket{
|
||||||
|
buffer: buffer,
|
||||||
|
source: destination,
|
||||||
|
}:
|
||||||
|
return nil
|
||||||
|
case <-s.done:
|
||||||
|
return io.ErrClosedPipe
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ServerBind) Close() error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ServerBind) SetMark(mark uint32) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ServerBind) Send(b []byte, ep conn.Endpoint) error {
|
||||||
|
return s.writeBack.WritePacket(buf.As(b), M.Socksaddr(ep.(Endpoint)))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ServerBind) ParseEndpoint(addr string) (conn.Endpoint, error) {
|
||||||
|
destination := M.ParseSocksaddr(addr)
|
||||||
|
if !destination.IsValid() || destination.Port == 0 {
|
||||||
|
return nil, E.New("invalid endpoint: ", addr)
|
||||||
|
}
|
||||||
|
return Endpoint(destination), nil
|
||||||
|
}
|
||||||
3
transport/wireguard/tun_darwin.go
Normal file
3
transport/wireguard/tun_darwin.go
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
package wireguard
|
||||||
|
|
||||||
|
const tunPacketOffset = 4
|
||||||
5
transport/wireguard/tun_nondarwin.go
Normal file
5
transport/wireguard/tun_nondarwin.go
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
//go:build !darwin
|
||||||
|
|
||||||
|
package wireguard
|
||||||
|
|
||||||
|
const tunPacketOffset = 0
|
||||||
Reference in New Issue
Block a user