Refactor struct & Add override dialer options
This commit is contained in:
@@ -22,5 +22,5 @@ type InboundContext struct {
|
||||
|
||||
SourceGeoIPCode string
|
||||
GeoIPCode string
|
||||
ProcessPath string
|
||||
// ProcessPath string
|
||||
}
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
package inbound
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
C "github.com/sagernet/sing-box/constant"
|
||||
"github.com/sagernet/sing-box/log"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
"github.com/sagernet/sing/common"
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
F "github.com/sagernet/sing/common/format"
|
||||
)
|
||||
|
||||
func New(ctx context.Context, router adapter.Router, logger log.Logger, index int, options option.Inbound) (adapter.Inbound, error) {
|
||||
if common.IsEmptyByEquals(options) {
|
||||
return nil, E.New("empty inbound config")
|
||||
}
|
||||
var tag string
|
||||
if options.Tag != "" {
|
||||
tag = options.Tag
|
||||
} else {
|
||||
tag = F.ToString(index)
|
||||
}
|
||||
inboundLogger := logger.WithPrefix(F.ToString("inbound/", options.Type, "[", tag, "]: "))
|
||||
switch options.Type {
|
||||
case C.TypeDirect:
|
||||
return NewDirect(ctx, router, inboundLogger, options.Tag, options.DirectOptions), nil
|
||||
case C.TypeSocks:
|
||||
return NewSocks(ctx, router, inboundLogger, options.Tag, options.SocksOptions), nil
|
||||
case C.TypeHTTP:
|
||||
return NewHTTP(ctx, router, inboundLogger, options.Tag, options.HTTPOptions), nil
|
||||
case C.TypeMixed:
|
||||
return NewMixed(ctx, router, inboundLogger, options.Tag, options.MixedOptions), nil
|
||||
case C.TypeShadowsocks:
|
||||
return NewShadowsocks(ctx, router, inboundLogger, options.Tag, options.ShadowsocksOptions)
|
||||
default:
|
||||
return nil, E.New("unknown inbound type: ", options.Type)
|
||||
}
|
||||
}
|
||||
@@ -1,305 +0,0 @@
|
||||
package inbound
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"net/netip"
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/database64128/tfo-go"
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
C "github.com/sagernet/sing-box/constant"
|
||||
"github.com/sagernet/sing-box/log"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
"github.com/sagernet/sing/common"
|
||||
"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"
|
||||
)
|
||||
|
||||
var _ adapter.Inbound = (*myInboundAdapter)(nil)
|
||||
|
||||
type myInboundAdapter struct {
|
||||
protocol string
|
||||
network []string
|
||||
ctx context.Context
|
||||
router adapter.Router
|
||||
logger log.Logger
|
||||
tag string
|
||||
listenOptions option.ListenOptions
|
||||
connHandler adapter.ConnectionHandler
|
||||
packetHandler adapter.PacketHandler
|
||||
packetUpstream any
|
||||
|
||||
// internal
|
||||
|
||||
tcpListener *net.TCPListener
|
||||
udpConn *net.UDPConn
|
||||
packetForce6 bool
|
||||
packetAccess sync.RWMutex
|
||||
packetOutboundClosed chan struct{}
|
||||
packetOutbound chan *myInboundPacket
|
||||
}
|
||||
|
||||
func (a *myInboundAdapter) Type() string {
|
||||
return a.protocol
|
||||
}
|
||||
|
||||
func (a *myInboundAdapter) Tag() string {
|
||||
return a.tag
|
||||
}
|
||||
|
||||
func (a *myInboundAdapter) Start() error {
|
||||
bindAddr := M.SocksaddrFromAddrPort(netip.Addr(a.listenOptions.Listen), a.listenOptions.Port)
|
||||
var listenAddr net.Addr
|
||||
if common.Contains(a.network, C.NetworkTCP) {
|
||||
var tcpListener *net.TCPListener
|
||||
var err error
|
||||
if !a.listenOptions.TCPFastOpen {
|
||||
tcpListener, err = net.ListenTCP(M.NetworkFromNetAddr("tcp", bindAddr.Addr), bindAddr.TCPAddr())
|
||||
} else {
|
||||
tcpListener, err = tfo.ListenTCP(M.NetworkFromNetAddr("tcp", bindAddr.Addr), bindAddr.TCPAddr())
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
a.tcpListener = tcpListener
|
||||
go a.loopTCPIn()
|
||||
listenAddr = tcpListener.Addr()
|
||||
}
|
||||
if common.Contains(a.network, C.NetworkUDP) {
|
||||
udpConn, err := net.ListenUDP(M.NetworkFromNetAddr("udp", bindAddr.Addr), bindAddr.UDPAddr())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
a.udpConn = udpConn
|
||||
a.packetForce6 = M.SocksaddrFromNet(udpConn.LocalAddr()).Addr.Is6()
|
||||
a.packetOutboundClosed = make(chan struct{})
|
||||
a.packetOutbound = make(chan *myInboundPacket)
|
||||
if _, threadUnsafeHandler := common.Cast[N.ThreadUnsafeWriter](a.packetUpstream); !threadUnsafeHandler {
|
||||
go a.loopUDPIn()
|
||||
} else {
|
||||
go a.loopUDPInThreadSafe()
|
||||
}
|
||||
go a.loopUDPOut()
|
||||
if listenAddr == nil {
|
||||
listenAddr = udpConn.LocalAddr()
|
||||
}
|
||||
}
|
||||
a.logger.Info("server started at ", listenAddr)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *myInboundAdapter) Close() error {
|
||||
return common.Close(
|
||||
common.PtrOrNil(a.tcpListener),
|
||||
common.PtrOrNil(a.udpConn),
|
||||
)
|
||||
}
|
||||
|
||||
func (a *myInboundAdapter) upstreamHandler(metadata adapter.InboundContext) adapter.UpstreamHandlerAdapter {
|
||||
return adapter.NewUpstreamHandler(metadata, a.newConnection, a.streamPacketConnection, a)
|
||||
}
|
||||
|
||||
func (a *myInboundAdapter) upstreamContextHandler() adapter.UpstreamHandlerAdapter {
|
||||
return adapter.NewUpstreamContextHandler(a.newConnection, a.newPacketConnection, a)
|
||||
}
|
||||
|
||||
func (a *myInboundAdapter) newConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
|
||||
a.logger.WithContext(ctx).Info("inbound connection to ", metadata.Destination)
|
||||
return a.router.RouteConnection(ctx, conn, metadata)
|
||||
}
|
||||
|
||||
func (a *myInboundAdapter) streamPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error {
|
||||
a.logger.WithContext(ctx).Info("inbound packet connection to ", metadata.Destination)
|
||||
return a.router.RoutePacketConnection(ctx, conn, metadata)
|
||||
}
|
||||
|
||||
func (a *myInboundAdapter) newPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error {
|
||||
ctx = log.ContextWithID(ctx)
|
||||
a.logger.WithContext(ctx).Info("inbound packet connection from ", metadata.Source)
|
||||
a.logger.WithContext(ctx).Info("inbound packet connection to ", metadata.Destination)
|
||||
return a.router.RoutePacketConnection(ctx, conn, metadata)
|
||||
}
|
||||
|
||||
func (a *myInboundAdapter) loopTCPIn() {
|
||||
tcpListener := a.tcpListener
|
||||
for {
|
||||
conn, err := tcpListener.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
ctx := log.ContextWithID(a.ctx)
|
||||
var metadata adapter.InboundContext
|
||||
metadata.Inbound = a.tag
|
||||
metadata.Network = "tcp"
|
||||
metadata.Source = M.SocksaddrFromNet(conn.RemoteAddr())
|
||||
a.logger.WithContext(ctx).Info("inbound connection from ", metadata.Source)
|
||||
hErr := a.connHandler.NewConnection(ctx, conn, metadata)
|
||||
if hErr != nil {
|
||||
a.NewError(ctx, E.Cause(hErr, "process connection from ", metadata.Source))
|
||||
}
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
func (a *myInboundAdapter) loopUDPIn() {
|
||||
defer close(a.packetOutboundClosed)
|
||||
_buffer := buf.StackNewPacket()
|
||||
defer common.KeepAlive(_buffer)
|
||||
buffer := common.Dup(_buffer)
|
||||
defer buffer.Release()
|
||||
buffer.IncRef()
|
||||
defer buffer.DecRef()
|
||||
packetService := (*myInboundPacketAdapter)(a)
|
||||
for {
|
||||
buffer.Reset()
|
||||
n, addr, err := a.udpConn.ReadFromUDPAddrPort(buffer.FreeBytes())
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
buffer.Truncate(n)
|
||||
var metadata adapter.InboundContext
|
||||
metadata.Inbound = a.tag
|
||||
metadata.Network = "udp"
|
||||
metadata.Source = M.SocksaddrFromNetIP(addr)
|
||||
err = a.packetHandler.NewPacket(a.ctx, packetService, buffer, metadata)
|
||||
if err != nil {
|
||||
a.newError(E.Cause(err, "process packet from ", metadata.Source))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (a *myInboundAdapter) loopUDPInThreadSafe() {
|
||||
defer close(a.packetOutboundClosed)
|
||||
packetService := (*myInboundPacketAdapter)(a)
|
||||
for {
|
||||
buffer := buf.NewPacket()
|
||||
n, addr, err := a.udpConn.ReadFromUDPAddrPort(buffer.FreeBytes())
|
||||
if err != nil {
|
||||
buffer.Release()
|
||||
return
|
||||
}
|
||||
buffer.Truncate(n)
|
||||
var metadata adapter.InboundContext
|
||||
metadata.Inbound = a.tag
|
||||
metadata.Network = "udp"
|
||||
metadata.Source = M.SocksaddrFromNetIP(addr)
|
||||
err = a.packetHandler.NewPacket(a.ctx, packetService, buffer, metadata)
|
||||
if err != nil {
|
||||
buffer.Release()
|
||||
a.newError(E.Cause(err, "process packet from ", metadata.Source))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (a *myInboundAdapter) loopUDPOut() {
|
||||
for {
|
||||
select {
|
||||
case packet := <-a.packetOutbound:
|
||||
err := a.writePacket(packet.buffer, packet.destination)
|
||||
if err != nil && !E.IsClosed(err) {
|
||||
a.newError(E.New("write back udp: ", err))
|
||||
}
|
||||
continue
|
||||
case <-a.packetOutboundClosed:
|
||||
}
|
||||
for {
|
||||
select {
|
||||
case packet := <-a.packetOutbound:
|
||||
packet.buffer.Release()
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (a *myInboundAdapter) newError(err error) {
|
||||
a.logger.Error(err)
|
||||
}
|
||||
|
||||
func (a *myInboundAdapter) NewError(ctx context.Context, err error) {
|
||||
common.Close(err)
|
||||
if E.IsClosed(err) {
|
||||
a.logger.WithContext(ctx).Debug("connection closed")
|
||||
return
|
||||
}
|
||||
a.logger.Error(err)
|
||||
}
|
||||
|
||||
func (a *myInboundAdapter) writePacket(buffer *buf.Buffer, destination M.Socksaddr) error {
|
||||
defer buffer.Release()
|
||||
if destination.IsFqdn() {
|
||||
udpAddr, err := net.ResolveUDPAddr("udp", destination.String())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return common.Error(a.udpConn.WriteTo(buffer.Bytes(), udpAddr))
|
||||
}
|
||||
if a.packetForce6 && destination.Addr.Is4() {
|
||||
destination.Addr = netip.AddrFrom16(destination.Addr.As16())
|
||||
}
|
||||
return common.Error(a.udpConn.WriteToUDPAddrPort(buffer.Bytes(), destination.AddrPort()))
|
||||
}
|
||||
|
||||
type myInboundPacketAdapter myInboundAdapter
|
||||
|
||||
func (s *myInboundPacketAdapter) ReadPacket(buffer *buf.Buffer) (M.Socksaddr, error) {
|
||||
n, addr, err := s.udpConn.ReadFromUDPAddrPort(buffer.FreeBytes())
|
||||
if err != nil {
|
||||
return M.Socksaddr{}, err
|
||||
}
|
||||
buffer.Truncate(n)
|
||||
return M.SocksaddrFromNetIP(addr), nil
|
||||
}
|
||||
|
||||
func (s *myInboundPacketAdapter) WriteIsThreadUnsafe() {
|
||||
}
|
||||
|
||||
type myInboundPacket struct {
|
||||
buffer *buf.Buffer
|
||||
destination M.Socksaddr
|
||||
}
|
||||
|
||||
func (s *myInboundPacketAdapter) Upstream() any {
|
||||
return s.udpConn
|
||||
}
|
||||
|
||||
func (s *myInboundPacketAdapter) WritePacket(buffer *buf.Buffer, destination M.Socksaddr) error {
|
||||
s.packetAccess.RLock()
|
||||
defer s.packetAccess.RUnlock()
|
||||
|
||||
select {
|
||||
case <-s.packetOutboundClosed:
|
||||
return os.ErrClosed
|
||||
default:
|
||||
}
|
||||
|
||||
s.packetOutbound <- &myInboundPacket{buffer, destination}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *myInboundPacketAdapter) Close() error {
|
||||
return s.udpConn.Close()
|
||||
}
|
||||
|
||||
func (s *myInboundPacketAdapter) LocalAddr() net.Addr {
|
||||
return s.udpConn.LocalAddr()
|
||||
}
|
||||
|
||||
func (s *myInboundPacketAdapter) SetDeadline(t time.Time) error {
|
||||
return s.udpConn.SetDeadline(t)
|
||||
}
|
||||
|
||||
func (s *myInboundPacketAdapter) SetReadDeadline(t time.Time) error {
|
||||
return s.udpConn.SetReadDeadline(t)
|
||||
}
|
||||
|
||||
func (s *myInboundPacketAdapter) SetWriteDeadline(t time.Time) error {
|
||||
return s.udpConn.SetWriteDeadline(t)
|
||||
}
|
||||
@@ -1,86 +0,0 @@
|
||||
package inbound
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"net/netip"
|
||||
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
C "github.com/sagernet/sing-box/constant"
|
||||
"github.com/sagernet/sing-box/log"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
"github.com/sagernet/sing/common/buf"
|
||||
M "github.com/sagernet/sing/common/metadata"
|
||||
N "github.com/sagernet/sing/common/network"
|
||||
"github.com/sagernet/sing/common/udpnat"
|
||||
)
|
||||
|
||||
var _ adapter.Inbound = (*Direct)(nil)
|
||||
|
||||
type Direct struct {
|
||||
myInboundAdapter
|
||||
udpNat *udpnat.Service[netip.AddrPort]
|
||||
overrideOption int
|
||||
overrideDestination M.Socksaddr
|
||||
}
|
||||
|
||||
func NewDirect(ctx context.Context, router adapter.Router, logger log.Logger, tag string, options option.DirectInboundOptions) *Direct {
|
||||
inbound := &Direct{
|
||||
myInboundAdapter: myInboundAdapter{
|
||||
protocol: C.TypeDirect,
|
||||
network: options.Network.Build(),
|
||||
ctx: ctx,
|
||||
router: router,
|
||||
logger: logger,
|
||||
tag: tag,
|
||||
listenOptions: options.ListenOptions,
|
||||
},
|
||||
}
|
||||
if options.OverrideAddress != "" && options.OverridePort != 0 {
|
||||
inbound.overrideOption = 1
|
||||
inbound.overrideDestination = M.ParseSocksaddrHostPort(options.OverrideAddress, options.OverridePort)
|
||||
} else if options.OverrideAddress != "" {
|
||||
inbound.overrideOption = 2
|
||||
inbound.overrideDestination = M.ParseSocksaddrHostPort(options.OverrideAddress, options.OverridePort)
|
||||
} else if options.OverridePort != 0 {
|
||||
inbound.overrideOption = 3
|
||||
inbound.overrideDestination = M.Socksaddr{Port: options.OverridePort}
|
||||
}
|
||||
inbound.udpNat = udpnat.New[netip.AddrPort](options.UDPTimeout, inbound.upstreamContextHandler())
|
||||
inbound.connHandler = inbound
|
||||
inbound.packetHandler = inbound
|
||||
return inbound
|
||||
}
|
||||
|
||||
func (d *Direct) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
|
||||
switch d.overrideOption {
|
||||
case 1:
|
||||
metadata.Destination = d.overrideDestination
|
||||
case 2:
|
||||
destination := d.overrideDestination
|
||||
destination.Port = metadata.Destination.Port
|
||||
metadata.Destination = destination
|
||||
case 3:
|
||||
metadata.Destination.Port = d.overrideDestination.Port
|
||||
}
|
||||
d.logger.WithContext(ctx).Info("inbound connection to ", metadata.Destination)
|
||||
return d.router.RouteConnection(ctx, conn, metadata)
|
||||
}
|
||||
|
||||
func (d *Direct) NewPacket(ctx context.Context, conn N.PacketConn, buffer *buf.Buffer, metadata adapter.InboundContext) error {
|
||||
switch d.overrideOption {
|
||||
case 1:
|
||||
metadata.Destination = d.overrideDestination
|
||||
case 2:
|
||||
destination := d.overrideDestination
|
||||
destination.Port = metadata.Destination.Port
|
||||
metadata.Destination = destination
|
||||
case 3:
|
||||
metadata.Destination.Port = d.overrideDestination.Port
|
||||
}
|
||||
var upstreamMetadata M.Metadata
|
||||
upstreamMetadata.Source = metadata.Source
|
||||
upstreamMetadata.Destination = metadata.Destination
|
||||
d.udpNat.NewPacketDirect(&adapter.MetadataContext{Context: log.ContextWithID(ctx), Metadata: metadata}, metadata.Source.AddrPort(), conn, buffer, upstreamMetadata)
|
||||
return nil
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
package inbound
|
||||
|
||||
import (
|
||||
std_bufio "bufio"
|
||||
"context"
|
||||
"net"
|
||||
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
C "github.com/sagernet/sing-box/constant"
|
||||
"github.com/sagernet/sing-box/log"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
"github.com/sagernet/sing/common/auth"
|
||||
M "github.com/sagernet/sing/common/metadata"
|
||||
"github.com/sagernet/sing/protocol/http"
|
||||
)
|
||||
|
||||
var _ adapter.Inbound = (*HTTP)(nil)
|
||||
|
||||
type HTTP struct {
|
||||
myInboundAdapter
|
||||
authenticator auth.Authenticator
|
||||
}
|
||||
|
||||
func NewHTTP(ctx context.Context, router adapter.Router, logger log.Logger, tag string, options option.SimpleInboundOptions) *HTTP {
|
||||
inbound := &HTTP{
|
||||
myInboundAdapter{
|
||||
protocol: C.TypeHTTP,
|
||||
network: []string{C.NetworkTCP},
|
||||
ctx: ctx,
|
||||
router: router,
|
||||
logger: logger,
|
||||
tag: tag,
|
||||
listenOptions: options.ListenOptions,
|
||||
},
|
||||
auth.NewAuthenticator(options.Users),
|
||||
}
|
||||
inbound.connHandler = inbound
|
||||
return inbound
|
||||
}
|
||||
|
||||
func (h *HTTP) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
|
||||
return http.HandleConnection(ctx, conn, std_bufio.NewReader(conn), h.authenticator, h.upstreamHandler(metadata), M.Metadata{})
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
package inbound
|
||||
|
||||
import (
|
||||
std_bufio "bufio"
|
||||
"context"
|
||||
"net"
|
||||
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
C "github.com/sagernet/sing-box/constant"
|
||||
"github.com/sagernet/sing-box/log"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
"github.com/sagernet/sing/common/auth"
|
||||
"github.com/sagernet/sing/common/buf"
|
||||
"github.com/sagernet/sing/common/bufio"
|
||||
M "github.com/sagernet/sing/common/metadata"
|
||||
"github.com/sagernet/sing/common/rw"
|
||||
"github.com/sagernet/sing/protocol/http"
|
||||
"github.com/sagernet/sing/protocol/socks"
|
||||
"github.com/sagernet/sing/protocol/socks/socks4"
|
||||
"github.com/sagernet/sing/protocol/socks/socks5"
|
||||
)
|
||||
|
||||
var _ adapter.Inbound = (*Mixed)(nil)
|
||||
|
||||
type Mixed struct {
|
||||
myInboundAdapter
|
||||
authenticator auth.Authenticator
|
||||
}
|
||||
|
||||
func NewMixed(ctx context.Context, router adapter.Router, logger log.Logger, tag string, options option.SimpleInboundOptions) *Mixed {
|
||||
inbound := &Mixed{
|
||||
myInboundAdapter{
|
||||
protocol: C.TypeMixed,
|
||||
network: []string{C.NetworkTCP},
|
||||
ctx: ctx,
|
||||
router: router,
|
||||
logger: logger,
|
||||
tag: tag,
|
||||
listenOptions: options.ListenOptions,
|
||||
},
|
||||
auth.NewAuthenticator(options.Users),
|
||||
}
|
||||
inbound.connHandler = inbound
|
||||
return inbound
|
||||
}
|
||||
|
||||
func (h *Mixed) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
|
||||
headerType, err := rw.ReadByte(conn)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch headerType {
|
||||
case socks4.Version, socks5.Version:
|
||||
return socks.HandleConnection0(ctx, conn, headerType, h.authenticator, h.upstreamHandler(metadata), M.Metadata{})
|
||||
}
|
||||
reader := std_bufio.NewReader(bufio.NewCachedReader(conn, buf.As([]byte{headerType})))
|
||||
return http.HandleConnection(ctx, conn, reader, h.authenticator, h.upstreamHandler(metadata), M.Metadata{})
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
package inbound
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
C "github.com/sagernet/sing-box/constant"
|
||||
"github.com/sagernet/sing-box/log"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
"github.com/sagernet/sing-shadowsocks"
|
||||
"github.com/sagernet/sing-shadowsocks/shadowaead"
|
||||
"github.com/sagernet/sing-shadowsocks/shadowaead_2022"
|
||||
"github.com/sagernet/sing/common"
|
||||
"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"
|
||||
)
|
||||
|
||||
var _ adapter.Inbound = (*Shadowsocks)(nil)
|
||||
|
||||
type Shadowsocks struct {
|
||||
myInboundAdapter
|
||||
service shadowsocks.Service
|
||||
}
|
||||
|
||||
func NewShadowsocks(ctx context.Context, router adapter.Router, logger log.Logger, tag string, options option.ShadowsocksInboundOptions) (*Shadowsocks, error) {
|
||||
inbound := &Shadowsocks{
|
||||
myInboundAdapter: myInboundAdapter{
|
||||
protocol: C.TypeShadowsocks,
|
||||
network: options.Network.Build(),
|
||||
ctx: ctx,
|
||||
router: router,
|
||||
logger: logger,
|
||||
tag: tag,
|
||||
listenOptions: options.ListenOptions,
|
||||
},
|
||||
}
|
||||
inbound.connHandler = inbound
|
||||
inbound.packetHandler = inbound
|
||||
var udpTimeout int64
|
||||
if options.UDPTimeout != 0 {
|
||||
udpTimeout = options.UDPTimeout
|
||||
} else {
|
||||
udpTimeout = 300
|
||||
}
|
||||
var err error
|
||||
switch {
|
||||
case options.Method == shadowsocks.MethodNone:
|
||||
inbound.service = shadowsocks.NewNoneService(options.UDPTimeout, inbound.upstreamContextHandler())
|
||||
case common.Contains(shadowaead.List, options.Method):
|
||||
inbound.service, err = shadowaead.NewService(options.Method, nil, options.Password, udpTimeout, inbound.upstreamContextHandler())
|
||||
case common.Contains(shadowaead_2022.List, options.Method):
|
||||
inbound.service, err = shadowaead_2022.NewServiceWithPassword(options.Method, options.Password, udpTimeout, inbound.upstreamContextHandler())
|
||||
default:
|
||||
err = E.New("shadowsocks: unsupported method: ", options.Method)
|
||||
}
|
||||
inbound.packetUpstream = inbound.service
|
||||
return inbound, err
|
||||
}
|
||||
|
||||
func (h *Shadowsocks) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
|
||||
return h.service.NewConnection(&adapter.MetadataContext{Context: ctx, Metadata: metadata}, conn, M.Metadata{
|
||||
Source: metadata.Source,
|
||||
})
|
||||
}
|
||||
|
||||
func (h *Shadowsocks) NewPacket(ctx context.Context, conn N.PacketConn, buffer *buf.Buffer, metadata adapter.InboundContext) error {
|
||||
h.logger.Trace("inbound packet from ", metadata.Source)
|
||||
return h.service.NewPacket(&adapter.MetadataContext{Context: ctx, Metadata: metadata}, conn, buffer, M.Metadata{
|
||||
Source: metadata.Source,
|
||||
})
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
package inbound
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
C "github.com/sagernet/sing-box/constant"
|
||||
"github.com/sagernet/sing-box/log"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
"github.com/sagernet/sing/common/auth"
|
||||
M "github.com/sagernet/sing/common/metadata"
|
||||
"github.com/sagernet/sing/protocol/socks"
|
||||
)
|
||||
|
||||
var _ adapter.Inbound = (*Socks)(nil)
|
||||
|
||||
type Socks struct {
|
||||
myInboundAdapter
|
||||
authenticator auth.Authenticator
|
||||
}
|
||||
|
||||
func NewSocks(ctx context.Context, router adapter.Router, logger log.Logger, tag string, options option.SimpleInboundOptions) *Socks {
|
||||
inbound := &Socks{
|
||||
myInboundAdapter{
|
||||
protocol: C.TypeSocks,
|
||||
network: []string{C.NetworkTCP},
|
||||
ctx: ctx,
|
||||
router: router,
|
||||
logger: logger,
|
||||
tag: tag,
|
||||
listenOptions: options.ListenOptions,
|
||||
},
|
||||
auth.NewAuthenticator(options.Users),
|
||||
}
|
||||
inbound.connHandler = inbound
|
||||
return inbound
|
||||
}
|
||||
|
||||
func (h *Socks) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
|
||||
return socks.HandleConnection(ctx, conn, h.authenticator, h.upstreamHandler(metadata), M.Metadata{})
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
package outbound
|
||||
|
||||
import (
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
C "github.com/sagernet/sing-box/constant"
|
||||
"github.com/sagernet/sing-box/log"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
"github.com/sagernet/sing/common"
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
F "github.com/sagernet/sing/common/format"
|
||||
)
|
||||
|
||||
func New(router adapter.Router, logger log.Logger, index int, options option.Outbound) (adapter.Outbound, error) {
|
||||
if common.IsEmpty(options) {
|
||||
return nil, E.New("empty outbound config")
|
||||
}
|
||||
var tag string
|
||||
if options.Tag != "" {
|
||||
tag = options.Tag
|
||||
} else {
|
||||
tag = F.ToString(index)
|
||||
}
|
||||
outboundLogger := logger.WithPrefix(F.ToString("outbound/", options.Type, "[", tag, "]: "))
|
||||
switch options.Type {
|
||||
case C.TypeDirect:
|
||||
return NewDirect(router, outboundLogger, options.Tag, options.DirectOptions), nil
|
||||
case C.TypeSocks:
|
||||
return NewSocks(router, outboundLogger, options.Tag, options.SocksOptions)
|
||||
case C.TypeShadowsocks:
|
||||
return NewShadowsocks(router, outboundLogger, options.Tag, options.ShadowsocksOptions)
|
||||
default:
|
||||
return nil, E.New("unknown outbound type: ", options.Type)
|
||||
}
|
||||
}
|
||||
@@ -1,138 +0,0 @@
|
||||
package outbound
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"runtime"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/database64128/tfo-go"
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
"github.com/sagernet/sing-box/log"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
"github.com/sagernet/sing/common"
|
||||
"github.com/sagernet/sing/common/buf"
|
||||
"github.com/sagernet/sing/common/bufio"
|
||||
"github.com/sagernet/sing/common/control"
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
M "github.com/sagernet/sing/common/metadata"
|
||||
N "github.com/sagernet/sing/common/network"
|
||||
)
|
||||
|
||||
type myOutboundAdapter struct {
|
||||
protocol string
|
||||
logger log.Logger
|
||||
tag string
|
||||
dialer N.Dialer
|
||||
}
|
||||
|
||||
func (a *myOutboundAdapter) Type() string {
|
||||
return a.protocol
|
||||
}
|
||||
|
||||
func (a *myOutboundAdapter) Tag() string {
|
||||
return a.tag
|
||||
}
|
||||
|
||||
type defaultDialer struct {
|
||||
tfo.Dialer
|
||||
net.ListenConfig
|
||||
}
|
||||
|
||||
func (d *defaultDialer) DialContext(ctx context.Context, network string, address M.Socksaddr) (net.Conn, error) {
|
||||
return d.Dialer.DialContext(ctx, network, address.String())
|
||||
}
|
||||
|
||||
func (d *defaultDialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
|
||||
return d.ListenConfig.ListenPacket(ctx, "udp", "")
|
||||
}
|
||||
|
||||
func newDialer(options option.DialerOptions) N.Dialer {
|
||||
var dialer net.Dialer
|
||||
var listener net.ListenConfig
|
||||
if options.BindInterface != "" {
|
||||
dialer.Control = control.Append(dialer.Control, control.BindToInterface(options.BindInterface))
|
||||
listener.Control = control.Append(listener.Control, control.BindToInterface(options.BindInterface))
|
||||
}
|
||||
if options.RoutingMark != 0 {
|
||||
dialer.Control = control.Append(dialer.Control, control.RoutingMark(options.RoutingMark))
|
||||
listener.Control = control.Append(listener.Control, control.RoutingMark(options.RoutingMark))
|
||||
}
|
||||
if options.ReuseAddr {
|
||||
listener.Control = control.Append(listener.Control, control.ReuseAddr())
|
||||
}
|
||||
if options.ConnectTimeout != 0 {
|
||||
dialer.Timeout = time.Duration(options.ConnectTimeout) * time.Second
|
||||
}
|
||||
return &defaultDialer{tfo.Dialer{Dialer: dialer, DisableTFO: !options.TCPFastOpen}, listener}
|
||||
}
|
||||
|
||||
type lazyDialer struct {
|
||||
router adapter.Router
|
||||
options option.DialerOptions
|
||||
dialer N.Dialer
|
||||
initOnce sync.Once
|
||||
initErr error
|
||||
}
|
||||
|
||||
func NewDialer(router adapter.Router, options option.DialerOptions) N.Dialer {
|
||||
if options.Detour == "" {
|
||||
return newDialer(options)
|
||||
}
|
||||
return &lazyDialer{
|
||||
router: router,
|
||||
options: options,
|
||||
}
|
||||
}
|
||||
|
||||
func (d *lazyDialer) Dialer() (N.Dialer, error) {
|
||||
d.initOnce.Do(func() {
|
||||
var loaded bool
|
||||
d.dialer, loaded = d.router.Outbound(d.options.Detour)
|
||||
if !loaded {
|
||||
d.initErr = E.New("outbound detour not found: ", d.options.Detour)
|
||||
}
|
||||
})
|
||||
return d.dialer, d.initErr
|
||||
}
|
||||
|
||||
func (d *lazyDialer) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
|
||||
dialer, err := d.Dialer()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return dialer.DialContext(ctx, network, destination)
|
||||
}
|
||||
|
||||
func (d *lazyDialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
|
||||
dialer, err := d.Dialer()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return dialer.ListenPacket(ctx, destination)
|
||||
}
|
||||
|
||||
func CopyEarlyConn(ctx context.Context, conn net.Conn, serverConn net.Conn) error {
|
||||
_payload := buf.StackNew()
|
||||
payload := common.Dup(_payload)
|
||||
err := conn.SetReadDeadline(time.Now().Add(100 * time.Millisecond))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = payload.ReadFrom(conn)
|
||||
if err != nil && !E.IsTimeout(err) {
|
||||
return E.Cause(err, "read payload")
|
||||
}
|
||||
err = conn.SetReadDeadline(time.Time{})
|
||||
if err != nil {
|
||||
payload.Release()
|
||||
return err
|
||||
}
|
||||
_, err = serverConn.Write(payload.Bytes())
|
||||
if err != nil {
|
||||
return E.Cause(err, "client handshake")
|
||||
}
|
||||
runtime.KeepAlive(_payload)
|
||||
return bufio.CopyConn(ctx, conn, serverConn)
|
||||
}
|
||||
@@ -1,85 +0,0 @@
|
||||
package outbound
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
C "github.com/sagernet/sing-box/constant"
|
||||
"github.com/sagernet/sing-box/log"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
"github.com/sagernet/sing/common/bufio"
|
||||
M "github.com/sagernet/sing/common/metadata"
|
||||
N "github.com/sagernet/sing/common/network"
|
||||
)
|
||||
|
||||
var _ adapter.Outbound = (*Direct)(nil)
|
||||
|
||||
type Direct struct {
|
||||
myOutboundAdapter
|
||||
overrideOption int
|
||||
overrideDestination M.Socksaddr
|
||||
}
|
||||
|
||||
func NewDirect(router adapter.Router, logger log.Logger, tag string, options option.DirectOutboundOptions) *Direct {
|
||||
outbound := &Direct{
|
||||
myOutboundAdapter: myOutboundAdapter{
|
||||
protocol: C.TypeDirect,
|
||||
logger: logger,
|
||||
tag: tag,
|
||||
dialer: NewDialer(router, options.DialerOptions),
|
||||
},
|
||||
}
|
||||
if options.OverrideAddress != "" && options.OverridePort != 0 {
|
||||
outbound.overrideOption = 1
|
||||
outbound.overrideDestination = M.ParseSocksaddrHostPort(options.OverrideAddress, options.OverridePort)
|
||||
} else if options.OverrideAddress != "" {
|
||||
outbound.overrideOption = 2
|
||||
outbound.overrideDestination = M.ParseSocksaddrHostPort(options.OverrideAddress, options.OverridePort)
|
||||
} else if options.OverridePort != 0 {
|
||||
outbound.overrideOption = 3
|
||||
outbound.overrideDestination = M.Socksaddr{Port: options.OverridePort}
|
||||
}
|
||||
return outbound
|
||||
}
|
||||
|
||||
func (d *Direct) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
|
||||
switch d.overrideOption {
|
||||
case 1:
|
||||
destination = d.overrideDestination
|
||||
case 2:
|
||||
newDestination := d.overrideDestination
|
||||
newDestination.Port = destination.Port
|
||||
destination = newDestination
|
||||
case 3:
|
||||
destination.Port = d.overrideDestination.Port
|
||||
}
|
||||
switch network {
|
||||
case C.NetworkTCP:
|
||||
d.logger.WithContext(ctx).Info("outbound connection to ", destination)
|
||||
case C.NetworkUDP:
|
||||
d.logger.WithContext(ctx).Info("outbound packet connection to ", destination)
|
||||
}
|
||||
return d.dialer.DialContext(ctx, network, destination)
|
||||
}
|
||||
|
||||
func (d *Direct) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
|
||||
d.logger.WithContext(ctx).Info("outbound packet connection")
|
||||
return d.dialer.ListenPacket(ctx, destination)
|
||||
}
|
||||
|
||||
func (d *Direct) NewConnection(ctx context.Context, conn net.Conn, destination M.Socksaddr) error {
|
||||
outConn, err := d.DialContext(ctx, "tcp", destination)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return bufio.CopyConn(ctx, conn, outConn)
|
||||
}
|
||||
|
||||
func (d *Direct) NewPacketConnection(ctx context.Context, conn N.PacketConn, destination M.Socksaddr) error {
|
||||
outConn, err := d.ListenPacket(ctx, destination)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return bufio.CopyPacketConn(ctx, conn, bufio.NewPacketConn(outConn))
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
package outbound
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
C "github.com/sagernet/sing-box/constant"
|
||||
"github.com/sagernet/sing-box/log"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
"github.com/sagernet/sing-shadowsocks"
|
||||
"github.com/sagernet/sing-shadowsocks/shadowimpl"
|
||||
"github.com/sagernet/sing/common/bufio"
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
M "github.com/sagernet/sing/common/metadata"
|
||||
N "github.com/sagernet/sing/common/network"
|
||||
)
|
||||
|
||||
var _ adapter.Outbound = (*Shadowsocks)(nil)
|
||||
|
||||
type Shadowsocks struct {
|
||||
myOutboundAdapter
|
||||
method shadowsocks.Method
|
||||
serverAddr M.Socksaddr
|
||||
}
|
||||
|
||||
func NewShadowsocks(router adapter.Router, logger log.Logger, tag string, options option.ShadowsocksOutboundOptions) (*Shadowsocks, error) {
|
||||
outbound := &Shadowsocks{
|
||||
myOutboundAdapter: myOutboundAdapter{
|
||||
protocol: C.TypeDirect,
|
||||
logger: logger,
|
||||
tag: tag,
|
||||
dialer: NewDialer(router, options.DialerOptions),
|
||||
},
|
||||
}
|
||||
var err error
|
||||
outbound.method, err = shadowimpl.FetchMethod(options.Method, options.Password)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if options.Server == "" {
|
||||
return nil, E.New("missing server address")
|
||||
} else if options.ServerPort == 0 {
|
||||
return nil, E.New("missing server port")
|
||||
}
|
||||
outbound.serverAddr = M.ParseSocksaddrHostPort(options.Server, options.ServerPort)
|
||||
return outbound, nil
|
||||
}
|
||||
|
||||
func (o *Shadowsocks) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
|
||||
switch network {
|
||||
case C.NetworkTCP:
|
||||
o.logger.WithContext(ctx).Info("outbound connection to ", destination)
|
||||
outConn, err := o.dialer.DialContext(ctx, "tcp", o.serverAddr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return o.method.DialEarlyConn(outConn, destination), nil
|
||||
case C.NetworkUDP:
|
||||
o.logger.WithContext(ctx).Info("outbound packet connection to ", destination)
|
||||
outConn, err := o.dialer.DialContext(ctx, "udp", o.serverAddr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &bufio.BindPacketConn{PacketConn: o.method.DialPacketConn(outConn), Addr: destination}, nil
|
||||
default:
|
||||
panic("unknown network " + network)
|
||||
}
|
||||
}
|
||||
|
||||
func (o *Shadowsocks) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
|
||||
o.logger.WithContext(ctx).Info("outbound packet connection to ", o.serverAddr)
|
||||
outConn, err := o.dialer.ListenPacket(ctx, destination)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return o.method.DialPacketConn(&bufio.BindPacketConn{PacketConn: outConn, Addr: o.serverAddr.UDPAddr()}), nil
|
||||
}
|
||||
|
||||
func (o *Shadowsocks) NewConnection(ctx context.Context, conn net.Conn, destination M.Socksaddr) error {
|
||||
serverConn, err := o.DialContext(ctx, "tcp", destination)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return CopyEarlyConn(ctx, conn, serverConn)
|
||||
}
|
||||
|
||||
func (o *Shadowsocks) NewPacketConnection(ctx context.Context, conn N.PacketConn, destination M.Socksaddr) error {
|
||||
serverConn, err := o.ListenPacket(ctx, destination)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return bufio.CopyPacketConn(ctx, conn, bufio.NewPacketConn(serverConn))
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
package outbound
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
C "github.com/sagernet/sing-box/constant"
|
||||
"github.com/sagernet/sing-box/log"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
"github.com/sagernet/sing/common/bufio"
|
||||
M "github.com/sagernet/sing/common/metadata"
|
||||
N "github.com/sagernet/sing/common/network"
|
||||
"github.com/sagernet/sing/protocol/socks"
|
||||
)
|
||||
|
||||
var _ adapter.Outbound = (*Socks)(nil)
|
||||
|
||||
type Socks struct {
|
||||
myOutboundAdapter
|
||||
client *socks.Client
|
||||
}
|
||||
|
||||
func NewSocks(router adapter.Router, logger log.Logger, tag string, options option.SocksOutboundOptions) (*Socks, error) {
|
||||
dialer := NewDialer(router, options.DialerOptions)
|
||||
var version socks.Version
|
||||
var err error
|
||||
if options.Version != "" {
|
||||
version, err = socks.ParseVersion(options.Version)
|
||||
} else {
|
||||
version = socks.Version5
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Socks{
|
||||
myOutboundAdapter{
|
||||
protocol: C.TypeSocks,
|
||||
logger: logger,
|
||||
tag: tag,
|
||||
dialer: dialer,
|
||||
},
|
||||
socks.NewClient(dialer, M.ParseSocksaddrHostPort(options.Server, options.ServerPort), version, options.Username, options.Password),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *Socks) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
|
||||
switch network {
|
||||
case C.NetworkTCP:
|
||||
h.logger.WithContext(ctx).Info("outbound connection to ", destination)
|
||||
case C.NetworkUDP:
|
||||
h.logger.WithContext(ctx).Info("outbound packet connection to ", destination)
|
||||
default:
|
||||
panic("unknown network " + network)
|
||||
}
|
||||
return h.client.DialContext(ctx, network, destination)
|
||||
}
|
||||
|
||||
func (h *Socks) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
|
||||
h.logger.WithContext(ctx).Info("outbound packet connection to ", destination)
|
||||
return h.client.ListenPacket(ctx, destination)
|
||||
}
|
||||
|
||||
func (h *Socks) NewConnection(ctx context.Context, conn net.Conn, destination M.Socksaddr) error {
|
||||
outConn, err := h.DialContext(ctx, "tcp", destination)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return bufio.CopyConn(ctx, conn, outConn)
|
||||
}
|
||||
|
||||
func (h *Socks) NewPacketConnection(ctx context.Context, conn N.PacketConn, destination M.Socksaddr) error {
|
||||
outConn, err := h.ListenPacket(ctx, destination)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return bufio.CopyPacketConn(ctx, conn, bufio.NewPacketConn(outConn))
|
||||
}
|
||||
@@ -1,226 +0,0 @@
|
||||
package route
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/oschwald/geoip2-golang"
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
C "github.com/sagernet/sing-box/constant"
|
||||
"github.com/sagernet/sing-box/log"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
"github.com/sagernet/sing/common"
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
M "github.com/sagernet/sing/common/metadata"
|
||||
N "github.com/sagernet/sing/common/network"
|
||||
)
|
||||
|
||||
var _ adapter.Router = (*Router)(nil)
|
||||
|
||||
type Router struct {
|
||||
ctx context.Context
|
||||
logger log.Logger
|
||||
defaultOutbound adapter.Outbound
|
||||
outboundByTag map[string]adapter.Outbound
|
||||
rules []adapter.Rule
|
||||
|
||||
needGeoDatabase bool
|
||||
geoOptions option.GeoIPOptions
|
||||
geoReader *geoip2.Reader
|
||||
}
|
||||
|
||||
func NewRouter(ctx context.Context, logger log.Logger, options option.RouteOptions) (*Router, error) {
|
||||
router := &Router{
|
||||
ctx: ctx,
|
||||
logger: logger.WithPrefix("router: "),
|
||||
outboundByTag: make(map[string]adapter.Outbound),
|
||||
rules: make([]adapter.Rule, 0, len(options.Rules)),
|
||||
needGeoDatabase: hasGeoRule(options.Rules),
|
||||
geoOptions: common.PtrValueOrDefault(options.GeoIP),
|
||||
}
|
||||
for i, ruleOptions := range options.Rules {
|
||||
rule, err := NewRule(router, logger, ruleOptions)
|
||||
if err != nil {
|
||||
return nil, E.Cause(err, "parse rule[", i, "]")
|
||||
}
|
||||
router.rules = append(router.rules, rule)
|
||||
}
|
||||
return router, nil
|
||||
}
|
||||
|
||||
func hasGeoRule(rules []option.Rule) bool {
|
||||
for _, rule := range rules {
|
||||
if rule.DefaultOptions != nil {
|
||||
if isGeoRule(common.PtrValueOrDefault(rule.DefaultOptions)) {
|
||||
return true
|
||||
}
|
||||
} else if rule.LogicalOptions != nil {
|
||||
for _, subRule := range rule.LogicalOptions.Rules {
|
||||
if isGeoRule(subRule) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func isGeoRule(rule option.DefaultRule) bool {
|
||||
return len(rule.SourceGeoIP) > 0 && common.Any(rule.SourceGeoIP, notPrivateNode) || len(rule.GeoIP) > 0 && common.Any(rule.GeoIP, notPrivateNode)
|
||||
}
|
||||
|
||||
func notPrivateNode(code string) bool {
|
||||
return code == "private"
|
||||
}
|
||||
|
||||
func (r *Router) UpdateOutbounds(outbounds []adapter.Outbound) {
|
||||
var defaultOutbound adapter.Outbound
|
||||
outboundByTag := make(map[string]adapter.Outbound)
|
||||
if len(outbounds) > 0 {
|
||||
defaultOutbound = outbounds[0]
|
||||
}
|
||||
for _, outbound := range outbounds {
|
||||
outboundByTag[outbound.Tag()] = outbound
|
||||
}
|
||||
r.defaultOutbound = defaultOutbound
|
||||
r.outboundByTag = outboundByTag
|
||||
}
|
||||
|
||||
func (r *Router) Start() error {
|
||||
if r.needGeoDatabase {
|
||||
go r.prepareGeoIPDatabase()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Router) Close() error {
|
||||
return common.Close(
|
||||
common.PtrOrNil(r.geoReader),
|
||||
)
|
||||
}
|
||||
|
||||
func (r *Router) GeoIPReader() *geoip2.Reader {
|
||||
return r.geoReader
|
||||
}
|
||||
|
||||
func (r *Router) prepareGeoIPDatabase() {
|
||||
var geoPath string
|
||||
if r.geoOptions.Path != "" {
|
||||
geoPath = r.geoOptions.Path
|
||||
} else {
|
||||
geoPath = "Country.mmdb"
|
||||
}
|
||||
geoPath, loaded := C.Find(geoPath)
|
||||
if !loaded {
|
||||
r.logger.Warn("geoip database not exists: ", geoPath)
|
||||
var err error
|
||||
for attempts := 0; attempts < 3; attempts++ {
|
||||
err = r.downloadGeoIPDatabase(geoPath)
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
r.logger.Error("download geoip database: ", err)
|
||||
os.Remove(geoPath)
|
||||
time.Sleep(10 * time.Second)
|
||||
}
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
geoReader, err := geoip2.Open(geoPath)
|
||||
if err == nil {
|
||||
r.logger.Info("loaded geoip database")
|
||||
r.geoReader = geoReader
|
||||
} else {
|
||||
r.logger.Error("open geoip database: ", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Router) downloadGeoIPDatabase(savePath string) error {
|
||||
var downloadURL string
|
||||
if r.geoOptions.DownloadURL != "" {
|
||||
downloadURL = r.geoOptions.DownloadURL
|
||||
} else {
|
||||
downloadURL = "https://cdn.jsdelivr.net/gh/Dreamacro/maxmind-geoip@release/Country.mmdb"
|
||||
}
|
||||
r.logger.Info("downloading geoip database")
|
||||
var detour adapter.Outbound
|
||||
if r.geoOptions.DownloadDetour != "" {
|
||||
outbound, loaded := r.Outbound(r.geoOptions.DownloadDetour)
|
||||
if !loaded {
|
||||
return E.New("detour outbound not found: ", r.geoOptions.DownloadDetour)
|
||||
}
|
||||
detour = outbound
|
||||
} else {
|
||||
detour = r.defaultOutbound
|
||||
}
|
||||
|
||||
if parentDir := filepath.Dir(savePath); parentDir != "" {
|
||||
os.MkdirAll(parentDir, 0o755)
|
||||
}
|
||||
|
||||
saveFile, err := os.OpenFile(savePath, os.O_CREATE|os.O_WRONLY, 0o644)
|
||||
if err != nil {
|
||||
return E.Cause(err, "open output file: ", downloadURL)
|
||||
}
|
||||
defer saveFile.Close()
|
||||
|
||||
httpClient := &http.Client{
|
||||
Timeout: 5 * time.Second,
|
||||
Transport: &http.Transport{
|
||||
ForceAttemptHTTP2: true,
|
||||
TLSHandshakeTimeout: 5 * time.Second,
|
||||
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
return detour.DialContext(ctx, network, M.ParseSocksaddr(addr))
|
||||
},
|
||||
},
|
||||
}
|
||||
response, err := httpClient.Get(downloadURL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
_, err = io.Copy(saveFile, response.Body)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *Router) DefaultOutbound() adapter.Outbound {
|
||||
if r.defaultOutbound == nil {
|
||||
panic("missing default outbound")
|
||||
}
|
||||
return r.defaultOutbound
|
||||
}
|
||||
|
||||
func (r *Router) Outbound(tag string) (adapter.Outbound, bool) {
|
||||
outbound, loaded := r.outboundByTag[tag]
|
||||
return outbound, loaded
|
||||
}
|
||||
|
||||
func (r *Router) RouteConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
|
||||
return r.match(ctx, metadata).NewConnection(ctx, conn, metadata.Destination)
|
||||
}
|
||||
|
||||
func (r *Router) RoutePacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error {
|
||||
return r.match(ctx, metadata).NewPacketConnection(ctx, conn, metadata.Destination)
|
||||
}
|
||||
|
||||
func (r *Router) match(ctx context.Context, metadata adapter.InboundContext) adapter.Outbound {
|
||||
for i, rule := range r.rules {
|
||||
if rule.Match(&metadata) {
|
||||
detour := rule.Outbound()
|
||||
r.logger.WithContext(ctx).Info("match [", i, "]", rule.String(), " => ", detour)
|
||||
if outbound, loaded := r.Outbound(detour); loaded {
|
||||
return outbound
|
||||
}
|
||||
r.logger.WithContext(ctx).Error("outbound not found: ", detour)
|
||||
}
|
||||
}
|
||||
r.logger.WithContext(ctx).Info("no match")
|
||||
return r.defaultOutbound
|
||||
}
|
||||
@@ -1,130 +0,0 @@
|
||||
package route
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
C "github.com/sagernet/sing-box/constant"
|
||||
"github.com/sagernet/sing-box/log"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
"github.com/sagernet/sing/common"
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
F "github.com/sagernet/sing/common/format"
|
||||
)
|
||||
|
||||
func NewRule(router adapter.Router, logger log.Logger, options option.Rule) (adapter.Rule, error) {
|
||||
if common.IsEmptyByEquals(options) {
|
||||
return nil, E.New("empty rule config")
|
||||
}
|
||||
switch options.Type {
|
||||
case "", C.RuleTypeDefault:
|
||||
if !options.DefaultOptions.IsValid() {
|
||||
return nil, E.New("missing conditions")
|
||||
}
|
||||
if options.DefaultOptions.Outbound == "" {
|
||||
return nil, E.New("missing outbound field")
|
||||
}
|
||||
return NewDefaultRule(router, logger, common.PtrValueOrDefault(options.DefaultOptions))
|
||||
case C.RuleTypeLogical:
|
||||
if !options.LogicalOptions.IsValid() {
|
||||
return nil, E.New("missing conditions")
|
||||
}
|
||||
if options.LogicalOptions.Outbound == "" {
|
||||
return nil, E.New("missing outbound field")
|
||||
}
|
||||
return NewLogicalRule(router, logger, common.PtrValueOrDefault(options.LogicalOptions))
|
||||
default:
|
||||
return nil, E.New("unknown rule type: ", options.Type)
|
||||
}
|
||||
}
|
||||
|
||||
var _ adapter.Rule = (*DefaultRule)(nil)
|
||||
|
||||
type DefaultRule struct {
|
||||
index int
|
||||
outbound string
|
||||
items []RuleItem
|
||||
}
|
||||
|
||||
type RuleItem interface {
|
||||
Match(metadata *adapter.InboundContext) bool
|
||||
String() string
|
||||
}
|
||||
|
||||
func NewDefaultRule(router adapter.Router, logger log.Logger, options option.DefaultRule) (*DefaultRule, error) {
|
||||
rule := &DefaultRule{
|
||||
outbound: options.Outbound,
|
||||
}
|
||||
if len(options.Inbound) > 0 {
|
||||
rule.items = append(rule.items, NewInboundRule(options.Inbound))
|
||||
}
|
||||
if options.IPVersion > 0 {
|
||||
switch options.IPVersion {
|
||||
case 4, 6:
|
||||
rule.items = append(rule.items, NewIPVersionItem(options.IPVersion == 6))
|
||||
default:
|
||||
return nil, E.New("invalid ip version: ", options.IPVersion)
|
||||
}
|
||||
}
|
||||
if options.Network != "" {
|
||||
switch options.Network {
|
||||
case C.NetworkTCP, C.NetworkUDP:
|
||||
rule.items = append(rule.items, NewNetworkItem(options.Network))
|
||||
default:
|
||||
return nil, E.New("invalid network: ", options.Network)
|
||||
}
|
||||
}
|
||||
if len(options.Protocol) > 0 {
|
||||
rule.items = append(rule.items, NewProtocolItem(options.Protocol))
|
||||
}
|
||||
if len(options.Domain) > 0 || len(options.DomainSuffix) > 0 {
|
||||
rule.items = append(rule.items, NewDomainItem(options.Domain, options.DomainSuffix))
|
||||
}
|
||||
if len(options.DomainKeyword) > 0 {
|
||||
rule.items = append(rule.items, NewDomainKeywordItem(options.DomainKeyword))
|
||||
}
|
||||
if len(options.SourceGeoIP) > 0 {
|
||||
rule.items = append(rule.items, NewGeoIPItem(router, logger, true, options.SourceGeoIP))
|
||||
}
|
||||
if len(options.GeoIP) > 0 {
|
||||
rule.items = append(rule.items, NewGeoIPItem(router, logger, false, options.GeoIP))
|
||||
}
|
||||
if len(options.SourceIPCIDR) > 0 {
|
||||
item, err := NewIPCIDRItem(true, options.SourceIPCIDR)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rule.items = append(rule.items, item)
|
||||
}
|
||||
if len(options.IPCIDR) > 0 {
|
||||
item, err := NewIPCIDRItem(false, options.IPCIDR)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rule.items = append(rule.items, item)
|
||||
}
|
||||
if len(options.SourcePort) > 0 {
|
||||
rule.items = append(rule.items, NewPortItem(true, options.SourcePort))
|
||||
}
|
||||
if len(options.Port) > 0 {
|
||||
rule.items = append(rule.items, NewPortItem(false, options.Port))
|
||||
}
|
||||
return rule, nil
|
||||
}
|
||||
|
||||
func (r *DefaultRule) Match(metadata *adapter.InboundContext) bool {
|
||||
for _, item := range r.items {
|
||||
if item.Match(metadata) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (r *DefaultRule) Outbound() string {
|
||||
return r.outbound
|
||||
}
|
||||
|
||||
func (r *DefaultRule) String() string {
|
||||
return strings.Join(common.Map(r.items, F.ToString0[RuleItem]), " ")
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
package route
|
||||
|
||||
import (
|
||||
"net/netip"
|
||||
"strings"
|
||||
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
"github.com/sagernet/sing/common"
|
||||
F "github.com/sagernet/sing/common/format"
|
||||
)
|
||||
|
||||
var _ RuleItem = (*IPCIDRItem)(nil)
|
||||
|
||||
type IPCIDRItem struct {
|
||||
prefixes []netip.Prefix
|
||||
isSource bool
|
||||
}
|
||||
|
||||
func NewIPCIDRItem(isSource bool, prefixStrings []string) (*IPCIDRItem, error) {
|
||||
prefixes := make([]netip.Prefix, 0, len(prefixStrings))
|
||||
for _, prefixString := range prefixStrings {
|
||||
prefix, err := netip.ParsePrefix(prefixString)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
prefixes = append(prefixes, prefix)
|
||||
}
|
||||
return &IPCIDRItem{
|
||||
prefixes: prefixes,
|
||||
isSource: isSource,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *IPCIDRItem) Match(metadata *adapter.InboundContext) bool {
|
||||
if r.isSource {
|
||||
for _, prefix := range r.prefixes {
|
||||
if prefix.Contains(metadata.Source.Addr) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if metadata.Destination.IsFqdn() {
|
||||
return false
|
||||
}
|
||||
for _, prefix := range r.prefixes {
|
||||
if prefix.Contains(metadata.Destination.Addr) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (r *IPCIDRItem) String() string {
|
||||
var description string
|
||||
if r.isSource {
|
||||
description = "source_ipcidr="
|
||||
} else {
|
||||
description = "ipcidr="
|
||||
}
|
||||
pLen := len(r.prefixes)
|
||||
if pLen == 1 {
|
||||
description += r.prefixes[0].String()
|
||||
} else {
|
||||
description += "[" + strings.Join(common.Map(r.prefixes, F.ToString0[netip.Prefix]), " ") + "]"
|
||||
}
|
||||
return description
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
package route
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
"github.com/sagernet/sing-box/common/domain"
|
||||
"github.com/sagernet/sing/common"
|
||||
)
|
||||
|
||||
var _ RuleItem = (*DomainItem)(nil)
|
||||
|
||||
type DomainItem struct {
|
||||
description string
|
||||
matcher *domain.Matcher
|
||||
}
|
||||
|
||||
func NewDomainItem(domains []string, domainSuffixes []string) *DomainItem {
|
||||
domains = common.Uniq(domains)
|
||||
domainSuffixes = common.Uniq(domainSuffixes)
|
||||
var description string
|
||||
if dLen := len(domains); dLen > 0 {
|
||||
if dLen == 1 {
|
||||
description = "domain=" + domains[0]
|
||||
} else if dLen > 3 {
|
||||
description = "domain=[" + strings.Join(domains[:3], " ") + "...]"
|
||||
} else {
|
||||
description = "domain=[" + strings.Join(domains, " ") + "]"
|
||||
}
|
||||
}
|
||||
if dsLen := len(domainSuffixes); dsLen > 0 {
|
||||
if len(description) > 0 {
|
||||
description += " "
|
||||
}
|
||||
if dsLen == 1 {
|
||||
description += "domainSuffix=" + domainSuffixes[0]
|
||||
} else if dsLen > 3 {
|
||||
description += "domainSuffix=[" + strings.Join(domainSuffixes[:3], " ") + "...]"
|
||||
} else {
|
||||
description += "domainSuffix=[" + strings.Join(domainSuffixes, " ") + "]"
|
||||
}
|
||||
}
|
||||
return &DomainItem{
|
||||
description,
|
||||
domain.NewMatcher(domains, domainSuffixes),
|
||||
}
|
||||
}
|
||||
|
||||
func (r *DomainItem) Match(metadata *adapter.InboundContext) bool {
|
||||
var domainHost string
|
||||
if metadata.Domain != "" {
|
||||
domainHost = metadata.Domain
|
||||
} else {
|
||||
domainHost = metadata.Destination.Fqdn
|
||||
}
|
||||
if domainHost == "" {
|
||||
return false
|
||||
}
|
||||
return r.matcher.Match(domainHost)
|
||||
}
|
||||
|
||||
func (r *DomainItem) String() string {
|
||||
return r.description
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
package route
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
)
|
||||
|
||||
var _ RuleItem = (*DomainKeywordItem)(nil)
|
||||
|
||||
type DomainKeywordItem struct {
|
||||
keywords []string
|
||||
}
|
||||
|
||||
func NewDomainKeywordItem(keywords []string) *DomainKeywordItem {
|
||||
return &DomainKeywordItem{keywords}
|
||||
}
|
||||
|
||||
func (r *DomainKeywordItem) Match(metadata *adapter.InboundContext) bool {
|
||||
var domainHost string
|
||||
if metadata.Domain != "" {
|
||||
domainHost = metadata.Domain
|
||||
} else {
|
||||
domainHost = metadata.Destination.Fqdn
|
||||
}
|
||||
if domainHost == "" {
|
||||
return false
|
||||
}
|
||||
for _, keyword := range r.keywords {
|
||||
if strings.Contains(domainHost, keyword) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (r *DomainKeywordItem) String() string {
|
||||
kLen := len(r.keywords)
|
||||
if kLen == 1 {
|
||||
return "domain_keyword=" + r.keywords[0]
|
||||
} else if kLen > 3 {
|
||||
return "domain_keyword=[" + strings.Join(r.keywords[:3], " ") + "...]"
|
||||
} else {
|
||||
return "domain_keyword=[" + strings.Join(r.keywords, " ") + "]"
|
||||
}
|
||||
}
|
||||
@@ -1,102 +0,0 @@
|
||||
package route
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
"github.com/sagernet/sing-box/log"
|
||||
N "github.com/sagernet/sing/common/network"
|
||||
)
|
||||
|
||||
var _ RuleItem = (*GeoIPItem)(nil)
|
||||
|
||||
type GeoIPItem struct {
|
||||
router adapter.Router
|
||||
logger log.Logger
|
||||
isSource bool
|
||||
codes []string
|
||||
codeMap map[string]bool
|
||||
}
|
||||
|
||||
func NewGeoIPItem(router adapter.Router, logger log.Logger, isSource bool, codes []string) *GeoIPItem {
|
||||
codeMap := make(map[string]bool)
|
||||
for _, code := range codes {
|
||||
codeMap[code] = true
|
||||
}
|
||||
return &GeoIPItem{
|
||||
router: router,
|
||||
logger: logger,
|
||||
codes: codes,
|
||||
isSource: isSource,
|
||||
codeMap: codeMap,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *GeoIPItem) Match(metadata *adapter.InboundContext) bool {
|
||||
geoReader := r.router.GeoIPReader()
|
||||
if geoReader == nil {
|
||||
return r.match(metadata)
|
||||
}
|
||||
if r.isSource {
|
||||
if metadata.SourceGeoIPCode == "" {
|
||||
country, err := geoReader.Country(metadata.Source.Addr.AsSlice())
|
||||
if err != nil {
|
||||
r.logger.Error("query geoip for ", metadata.Source.Addr, ": ", err)
|
||||
return false
|
||||
}
|
||||
metadata.SourceGeoIPCode = strings.ToLower(country.Country.IsoCode)
|
||||
}
|
||||
} else {
|
||||
if metadata.Destination.IsFqdn() {
|
||||
return false
|
||||
}
|
||||
if metadata.GeoIPCode == "" {
|
||||
country, err := geoReader.Country(metadata.Destination.Addr.AsSlice())
|
||||
if err != nil {
|
||||
r.logger.Error("query geoip for ", metadata.Destination.Addr, ": ", err)
|
||||
return false
|
||||
}
|
||||
metadata.GeoIPCode = strings.ToLower(country.Country.IsoCode)
|
||||
}
|
||||
}
|
||||
return r.match(metadata)
|
||||
}
|
||||
|
||||
func (r *GeoIPItem) match(metadata *adapter.InboundContext) bool {
|
||||
if r.isSource {
|
||||
if metadata.SourceGeoIPCode == "" {
|
||||
if !N.IsPublicAddr(metadata.Source.Addr) {
|
||||
metadata.SourceGeoIPCode = "private"
|
||||
}
|
||||
}
|
||||
return r.codeMap[metadata.SourceGeoIPCode]
|
||||
} else {
|
||||
if metadata.Destination.IsFqdn() {
|
||||
return false
|
||||
}
|
||||
if metadata.GeoIPCode == "" {
|
||||
if !N.IsPublicAddr(metadata.Destination.Addr) {
|
||||
metadata.GeoIPCode = "private"
|
||||
}
|
||||
}
|
||||
return r.codeMap[metadata.GeoIPCode]
|
||||
}
|
||||
}
|
||||
|
||||
func (r *GeoIPItem) String() string {
|
||||
var description string
|
||||
if r.isSource {
|
||||
description = "source_geoip="
|
||||
} else {
|
||||
description = "geoip="
|
||||
}
|
||||
cLen := len(r.codes)
|
||||
if cLen == 1 {
|
||||
description += r.codes[0]
|
||||
} else if cLen > 3 {
|
||||
description += "[" + strings.Join(r.codes[:3], " ") + "...]"
|
||||
} else {
|
||||
description += "[" + strings.Join(r.codes, " ") + "]"
|
||||
}
|
||||
return description
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
package route
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
F "github.com/sagernet/sing/common/format"
|
||||
)
|
||||
|
||||
var _ RuleItem = (*InboundItem)(nil)
|
||||
|
||||
type InboundItem struct {
|
||||
inbounds []string
|
||||
inboundMap map[string]bool
|
||||
}
|
||||
|
||||
func NewInboundRule(inbounds []string) *InboundItem {
|
||||
rule := &InboundItem{inbounds, make(map[string]bool)}
|
||||
for _, inbound := range inbounds {
|
||||
rule.inboundMap[inbound] = true
|
||||
}
|
||||
return rule
|
||||
}
|
||||
|
||||
func (r *InboundItem) Match(metadata *adapter.InboundContext) bool {
|
||||
return r.inboundMap[metadata.Inbound]
|
||||
}
|
||||
|
||||
func (r *InboundItem) String() string {
|
||||
if len(r.inbounds) == 1 {
|
||||
return F.ToString("inbound=", r.inbounds[0])
|
||||
} else {
|
||||
return F.ToString("inbound=[", strings.Join(r.inbounds, " "), "]")
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
package route
|
||||
|
||||
import (
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
)
|
||||
|
||||
var _ RuleItem = (*IPVersionItem)(nil)
|
||||
|
||||
type IPVersionItem struct {
|
||||
isIPv6 bool
|
||||
}
|
||||
|
||||
func NewIPVersionItem(isIPv6 bool) *IPVersionItem {
|
||||
return &IPVersionItem{isIPv6}
|
||||
}
|
||||
|
||||
func (r *IPVersionItem) Match(metadata *adapter.InboundContext) bool {
|
||||
return metadata.Destination.IsIP() && metadata.Destination.Family().IsIPv6() == r.isIPv6
|
||||
}
|
||||
|
||||
func (r *IPVersionItem) String() string {
|
||||
var versionStr string
|
||||
if r.isIPv6 {
|
||||
versionStr = "6"
|
||||
} else {
|
||||
versionStr = "4"
|
||||
}
|
||||
return "ip_version=" + versionStr
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
package route
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
C "github.com/sagernet/sing-box/constant"
|
||||
"github.com/sagernet/sing-box/log"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
"github.com/sagernet/sing/common"
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
F "github.com/sagernet/sing/common/format"
|
||||
)
|
||||
|
||||
var _ adapter.Rule = (*LogicalRule)(nil)
|
||||
|
||||
type LogicalRule struct {
|
||||
mode string
|
||||
rules []*DefaultRule
|
||||
outbound string
|
||||
}
|
||||
|
||||
func NewLogicalRule(router adapter.Router, logger log.Logger, options option.LogicalRule) (*LogicalRule, error) {
|
||||
r := &LogicalRule{
|
||||
rules: make([]*DefaultRule, len(options.Rules)),
|
||||
outbound: options.Outbound,
|
||||
}
|
||||
switch options.Mode {
|
||||
case C.LogicalTypeAnd:
|
||||
r.mode = C.LogicalTypeAnd
|
||||
case C.LogicalTypeOr:
|
||||
r.mode = C.LogicalTypeOr
|
||||
default:
|
||||
return nil, E.New("unknown logical mode: ", options.Mode)
|
||||
}
|
||||
for i, subRule := range options.Rules {
|
||||
rule, err := NewDefaultRule(router, logger, subRule)
|
||||
if err != nil {
|
||||
return nil, E.Cause(err, "sub rule[", i, "]")
|
||||
}
|
||||
r.rules[i] = rule
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
|
||||
func (r *LogicalRule) Match(metadata *adapter.InboundContext) bool {
|
||||
if r.mode == C.LogicalTypeAnd {
|
||||
return common.All(r.rules, func(it *DefaultRule) bool {
|
||||
return it.Match(metadata)
|
||||
})
|
||||
} else {
|
||||
return common.Any(r.rules, func(it *DefaultRule) bool {
|
||||
return it.Match(metadata)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func (r *LogicalRule) Outbound() string {
|
||||
return r.outbound
|
||||
}
|
||||
|
||||
func (r *LogicalRule) String() string {
|
||||
var op string
|
||||
switch r.mode {
|
||||
case C.LogicalTypeAnd:
|
||||
op = "&&"
|
||||
case C.LogicalTypeOr:
|
||||
op = "||"
|
||||
}
|
||||
return "logical(" + strings.Join(common.Map(r.rules, F.ToString0[*DefaultRule]), " "+op+" ") + ")"
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
package route
|
||||
|
||||
import (
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
)
|
||||
|
||||
var _ RuleItem = (*NetworkItem)(nil)
|
||||
|
||||
type NetworkItem struct {
|
||||
network string
|
||||
}
|
||||
|
||||
func NewNetworkItem(network string) *NetworkItem {
|
||||
return &NetworkItem{network}
|
||||
}
|
||||
|
||||
func (r *NetworkItem) Match(metadata *adapter.InboundContext) bool {
|
||||
return r.network == metadata.Network
|
||||
}
|
||||
|
||||
func (r *NetworkItem) String() string {
|
||||
return "network=" + r.network
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
package route
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
"github.com/sagernet/sing/common"
|
||||
F "github.com/sagernet/sing/common/format"
|
||||
)
|
||||
|
||||
var _ RuleItem = (*PortItem)(nil)
|
||||
|
||||
type PortItem struct {
|
||||
ports []uint16
|
||||
portMap map[uint16]bool
|
||||
isSource bool
|
||||
}
|
||||
|
||||
func NewPortItem(isSource bool, ports []uint16) *PortItem {
|
||||
portMap := make(map[uint16]bool)
|
||||
for _, port := range ports {
|
||||
portMap[port] = true
|
||||
}
|
||||
return &PortItem{
|
||||
ports: ports,
|
||||
portMap: portMap,
|
||||
isSource: isSource,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *PortItem) Match(metadata *adapter.InboundContext) bool {
|
||||
if r.isSource {
|
||||
return r.portMap[metadata.Source.Port]
|
||||
} else {
|
||||
return r.portMap[metadata.Destination.Port]
|
||||
}
|
||||
}
|
||||
|
||||
func (r *PortItem) String() string {
|
||||
var description string
|
||||
if r.isSource {
|
||||
description = "source_port="
|
||||
} else {
|
||||
description = "port="
|
||||
}
|
||||
pLen := len(r.ports)
|
||||
if pLen == 1 {
|
||||
description += F.ToString(r.ports[0])
|
||||
} else {
|
||||
description += "[" + strings.Join(common.Map(r.ports, F.ToString0[uint16]), " ") + "]"
|
||||
}
|
||||
return description
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
package route
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
F "github.com/sagernet/sing/common/format"
|
||||
)
|
||||
|
||||
var _ RuleItem = (*ProtocolItem)(nil)
|
||||
|
||||
type ProtocolItem struct {
|
||||
protocols []string
|
||||
protocolMap map[string]bool
|
||||
}
|
||||
|
||||
func NewProtocolItem(protocols []string) *ProtocolItem {
|
||||
protocolMap := make(map[string]bool)
|
||||
for _, protocol := range protocols {
|
||||
protocolMap[protocol] = true
|
||||
}
|
||||
return &ProtocolItem{
|
||||
protocols: protocols,
|
||||
protocolMap: protocolMap,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *ProtocolItem) Match(metadata *adapter.InboundContext) bool {
|
||||
return r.protocolMap[metadata.Protocol]
|
||||
}
|
||||
|
||||
func (r *ProtocolItem) String() string {
|
||||
if len(r.protocols) == 1 {
|
||||
return F.ToString("protocol=", r.protocols[0])
|
||||
}
|
||||
return F.ToString("protocol=[", strings.Join(r.protocols, " "), "]")
|
||||
}
|
||||
Reference in New Issue
Block a user