Init commit

This commit is contained in:
世界
2022-06-30 21:27:56 +08:00
commit cfa35e5a92
39 changed files with 2202 additions and 0 deletions

94
adapter/direct/inbound.go Normal file
View File

@@ -0,0 +1,94 @@
package direct
import (
"context"
"net"
"net/netip"
"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing-box/common/udpnat"
"github.com/sagernet/sing-box/config"
C "github.com/sagernet/sing-box/constant"
"github.com/sagernet/sing-box/log"
"github.com/sagernet/sing/common/buf"
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
)
var _ adapter.InboundHandler = (*Inbound)(nil)
type Inbound struct {
router adapter.Router
logger log.Logger
network []string
udpNat *udpnat.Service[netip.AddrPort]
overrideOption int
overrideDestination M.Socksaddr
}
func NewInbound(router adapter.Router, logger log.Logger, options *config.DirectInboundOptions) (inbound *Inbound) {
inbound = &Inbound{
router: router,
logger: logger,
network: options.Network.Build(),
}
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)
return
}
func (d *Inbound) Type() string {
return C.TypeDirect
}
func (d *Inbound) Network() []string {
return d.network
}
func (d *Inbound) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
switch d.overrideOption {
case 0:
metadata.Destination = d.overrideDestination
case 1:
destination := d.overrideDestination
destination.Port = metadata.Destination.Port
metadata.Destination = destination
case 2:
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 *Inbound) NewPacket(ctx context.Context, conn N.PacketConn, buffer *buf.Buffer, metadata adapter.InboundContext) error {
switch d.overrideOption {
case 0:
metadata.Destination = d.overrideDestination
case 1:
destination := d.overrideDestination
destination.Port = metadata.Destination.Port
metadata.Destination = destination
case 2:
metadata.Destination.Port = d.overrideDestination.Port
}
d.udpNat.NewPacketDirect(ctx, metadata.Source, conn, buffer, metadata)
return nil
}
func (d *Inbound) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error {
d.logger.WithContext(ctx).Info("inbound packet connection to ", metadata.Destination)
return d.router.RoutePacketConnection(ctx, conn, metadata)
}
func (d *Inbound) NewError(ctx context.Context, err error) {
d.logger.WithContext(ctx).Error(err)
}

View File

@@ -0,0 +1,93 @@
package direct
import (
"context"
"net"
"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing-box/common/dialer"
"github.com/sagernet/sing-box/config"
C "github.com/sagernet/sing-box/constant"
"github.com/sagernet/sing-box/log"
"github.com/sagernet/sing/common/bufio"
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
)
var _ adapter.Outbound = (*Outbound)(nil)
type Outbound struct {
tag string
logger log.Logger
dialer N.Dialer
overrideOption int
overrideDestination M.Socksaddr
}
func NewOutbound(tag string, router adapter.Router, logger log.Logger, options *config.DirectOutboundOptions) (outbound *Outbound) {
outbound = &Outbound{
tag: tag,
logger: logger,
dialer: 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
}
func (d *Outbound) Type() string {
return C.TypeDirect
}
func (d *Outbound) Tag() string {
return d.tag
}
func (d *Outbound) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
switch d.overrideOption {
case 0:
destination = d.overrideDestination
case 1:
newDestination := d.overrideDestination
newDestination.Port = destination.Port
destination = newDestination
case 2:
destination.Port = d.overrideDestination.Port
}
switch network {
case C.NetworkTCP:
d.logger.WithContext(ctx).Debug("outbound connection to ", destination)
case C.NetworkUDP:
d.logger.WithContext(ctx).Debug("outbound packet connection to ", destination)
}
return d.dialer.DialContext(ctx, network, destination)
}
func (d *Outbound) ListenPacket(ctx context.Context) (net.PacketConn, error) {
d.logger.WithContext(ctx).Debug("outbound packet connection")
return d.dialer.ListenPacket(ctx)
}
func (d *Outbound) 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 *Outbound) NewPacketConnection(ctx context.Context, conn N.PacketConn, destination M.Socksaddr) error {
outConn, err := d.ListenPacket(ctx)
if err != nil {
return err
}
return bufio.CopyPacketConn(ctx, conn, bufio.NewPacketConn(outConn))
}

67
adapter/http/inbound.go Normal file
View File

@@ -0,0 +1,67 @@
package http
import (
std_bufio "bufio"
"context"
"net"
"os"
"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing-box/config"
C "github.com/sagernet/sing-box/constant"
"github.com/sagernet/sing-box/log"
"github.com/sagernet/sing/common"
"github.com/sagernet/sing/common/auth"
"github.com/sagernet/sing/common/buf"
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
"github.com/sagernet/sing/protocol/http"
)
var _ adapter.InboundHandler = (*Inbound)(nil)
type Inbound struct {
router adapter.Router
logger log.Logger
authenticator auth.Authenticator
}
func NewInbound(router adapter.Router, logger log.Logger, options *config.SimpleInboundOptions) *Inbound {
return &Inbound{
router: router,
logger: logger,
authenticator: auth.NewAuthenticator(options.Users),
}
}
func (i *Inbound) Type() string {
return C.TypeHTTP
}
func (i *Inbound) Network() []string {
return []string{C.NetworkTCP}
}
func (i *Inbound) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
ctx = &inboundContext{ctx, metadata}
return http.HandleConnection(ctx, conn, std_bufio.NewReader(conn), i.authenticator, (*inboundHandler)(i), M.Metadata{})
}
func (i *Inbound) NewPacket(ctx context.Context, conn N.PacketConn, buffer *buf.Buffer, metadata adapter.InboundContext) error {
return os.ErrInvalid
}
type inboundContext struct {
context.Context
metadata adapter.InboundContext
}
type inboundHandler Inbound
func (h *inboundHandler) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error {
inboundCtx, _ := common.Cast[*inboundContext](ctx)
ctx = inboundCtx.Context
h.logger.WithContext(ctx).Info("inbound connection to ", metadata.Destination)
inboundCtx.metadata.Destination = metadata.Destination
return h.router.RouteConnection(ctx, conn, inboundCtx.metadata)
}

7
adapter/inbound.go Normal file
View File

@@ -0,0 +1,7 @@
package adapter
type Inbound interface {
Service
Type() string
Tag() string
}

View File

@@ -0,0 +1,16 @@
package adapter
import (
"net/netip"
M "github.com/sagernet/sing/common/metadata"
)
type InboundContext struct {
Source netip.AddrPort
Destination M.Socksaddr
Inbound string
Network string
Protocol string
Domain string
}

291
adapter/inbound_default.go Normal file
View File

@@ -0,0 +1,291 @@
package adapter
import (
"context"
"net"
"net/netip"
"os"
"sync"
"time"
"github.com/database64128/tfo-go"
C "github.com/sagernet/sing-box/constant"
"github.com/sagernet/sing-box/log"
"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"
)
type InboundHandler interface {
Type() string
Network() []string
NewConnection(ctx context.Context, conn net.Conn, metadata InboundContext) error
NewPacket(ctx context.Context, conn N.PacketConn, buffer *buf.Buffer, metadata InboundContext) error
}
var _ Inbound = (*DefaultInboundService)(nil)
type DefaultInboundService struct {
ctx context.Context
logger log.Logger
tag string
listen netip.AddrPort
listenerTFO bool
handler InboundHandler
tcpListener *net.TCPListener
udpConn *net.UDPConn
forceAddr6 bool
access sync.RWMutex
closed chan struct{}
outbound chan *defaultInboundUDPServiceOutboundPacket
}
func NewDefaultInboundService(ctx context.Context, tag string, logger log.Logger, listen netip.AddrPort, listenerTFO bool, handler InboundHandler) *DefaultInboundService {
return &DefaultInboundService{
ctx: ctx,
logger: logger,
tag: tag,
listen: listen,
listenerTFO: listenerTFO,
handler: handler,
closed: make(chan struct{}),
outbound: make(chan *defaultInboundUDPServiceOutboundPacket),
}
}
func (s *DefaultInboundService) Type() string {
return s.handler.Type()
}
func (s *DefaultInboundService) Tag() string {
return s.tag
}
func (s *DefaultInboundService) Start() error {
var listenAddr net.Addr
if common.Contains(s.handler.Network(), C.NetworkTCP) {
var tcpListener *net.TCPListener
var err error
if !s.listenerTFO {
tcpListener, err = net.ListenTCP(M.NetworkFromNetAddr("tcp", s.listen.Addr()), M.SocksaddrFromNetIP(s.listen).TCPAddr())
} else {
tcpListener, err = tfo.ListenTCP(M.NetworkFromNetAddr("tcp", s.listen.Addr()), M.SocksaddrFromNetIP(s.listen).TCPAddr())
}
if err != nil {
return err
}
s.tcpListener = tcpListener
go s.loopTCPIn()
listenAddr = tcpListener.Addr()
}
if common.Contains(s.handler.Network(), C.NetworkUDP) {
udpConn, err := net.ListenUDP(M.NetworkFromNetAddr("udp", s.listen.Addr()), M.SocksaddrFromNetIP(s.listen).UDPAddr())
if err != nil {
return err
}
s.udpConn = udpConn
s.forceAddr6 = M.SocksaddrFromNet(udpConn.LocalAddr()).Addr.Is6()
if _, threadUnsafeHandler := common.Cast[N.ThreadUnsafeWriter](s.handler); !threadUnsafeHandler {
go s.loopUDPIn()
} else {
go s.loopUDPInThreadSafe()
}
go s.loopUDPOut()
if listenAddr == nil {
listenAddr = udpConn.LocalAddr()
}
}
s.logger.Info("server started at ", listenAddr)
return nil
}
func (s *DefaultInboundService) Close() error {
return common.Close(
common.PtrOrNil(s.tcpListener),
common.PtrOrNil(s.udpConn),
)
}
func (s *DefaultInboundService) Upstream() any {
return s.handler
}
func (s *DefaultInboundService) loopTCPIn() {
tcpListener := s.tcpListener
for {
conn, err := tcpListener.Accept()
if err != nil {
return
}
var metadata InboundContext
metadata.Inbound = s.tag
metadata.Source = M.AddrPortFromNet(conn.RemoteAddr())
go func() {
metadata.Network = "tcp"
ctx := log.ContextWithID(s.ctx)
s.logger.WithContext(ctx).Info("inbound connection from ", conn.RemoteAddr())
hErr := s.handler.NewConnection(ctx, conn, metadata)
if hErr != nil {
s.newContextError(ctx, E.Cause(hErr, "process connection from ", conn.RemoteAddr()))
}
}()
}
}
func (s *DefaultInboundService) loopUDPIn() {
defer close(s.closed)
_buffer := buf.StackNewPacket()
defer common.KeepAlive(_buffer)
buffer := common.Dup(_buffer)
defer buffer.Release()
buffer.IncRef()
defer buffer.DecRef()
packetService := (*defaultInboundUDPService)(s)
var metadata InboundContext
metadata.Inbound = s.tag
metadata.Network = "udp"
for {
buffer.Reset()
n, addr, err := s.udpConn.ReadFromUDPAddrPort(buffer.FreeBytes())
if err != nil {
return
}
buffer.Truncate(n)
metadata.Source = addr
err = s.handler.NewPacket(s.ctx, packetService, buffer, metadata)
if err != nil {
s.newError(E.Cause(err, "process packet from ", addr))
}
}
}
func (s *DefaultInboundService) loopUDPInThreadSafe() {
defer close(s.closed)
packetService := (*defaultInboundUDPService)(s)
var metadata InboundContext
metadata.Inbound = s.tag
metadata.Network = "udp"
for {
buffer := buf.NewPacket()
n, addr, err := s.udpConn.ReadFromUDPAddrPort(buffer.FreeBytes())
if err != nil {
return
}
buffer.Truncate(n)
metadata.Source = addr
err = s.handler.NewPacket(s.ctx, packetService, buffer, metadata)
if err != nil {
buffer.Release()
s.newError(E.Cause(err, "process packet from ", addr))
}
}
}
func (s *DefaultInboundService) loopUDPOut() {
for {
select {
case packet := <-s.outbound:
err := s.writePacket(packet.buffer, packet.destination)
if err != nil && !E.IsClosed(err) {
s.newError(E.New("write back udp: ", err))
}
continue
case <-s.closed:
}
for {
select {
case packet := <-s.outbound:
packet.buffer.Release()
default:
return
}
}
}
}
func (s *DefaultInboundService) newError(err error) {
s.logger.Warn(err)
}
func (s *DefaultInboundService) newContextError(ctx context.Context, err error) {
common.Close(err)
if E.IsClosed(err) {
s.logger.WithContext(ctx).Debug("connection closed")
return
}
s.logger.Error(err)
}
func (s *DefaultInboundService) writePacket(buffer *buf.Buffer, destination M.Socksaddr) error {
defer buffer.Release()
if destination.Family().IsFqdn() {
udpAddr, err := net.ResolveUDPAddr("udp", destination.String())
if err != nil {
return err
}
return common.Error(s.udpConn.WriteTo(buffer.Bytes(), udpAddr))
}
if s.forceAddr6 && destination.Addr.Is4() {
destination.Addr = netip.AddrFrom16(destination.Addr.As16())
}
return common.Error(s.udpConn.WriteToUDPAddrPort(buffer.Bytes(), destination.AddrPort()))
}
type defaultInboundUDPService DefaultInboundService
func (s *defaultInboundUDPService) 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 *defaultInboundUDPService) WriteIsThreadUnsafe() {
}
type defaultInboundUDPServiceOutboundPacket struct {
buffer *buf.Buffer
destination M.Socksaddr
}
func (s *defaultInboundUDPService) Upstream() any {
return s.udpConn
}
func (s *defaultInboundUDPService) WritePacket(buffer *buf.Buffer, destination M.Socksaddr) error {
s.access.RLock()
defer s.access.RUnlock()
select {
case <-s.closed:
return os.ErrClosed
default:
}
s.outbound <- &defaultInboundUDPServiceOutboundPacket{buffer, destination}
return nil
}
func (s *defaultInboundUDPService) Close() error {
return s.udpConn.Close()
}
func (s *defaultInboundUDPService) LocalAddr() net.Addr {
return s.udpConn.LocalAddr()
}
func (s *defaultInboundUDPService) SetDeadline(t time.Time) error {
return s.udpConn.SetDeadline(t)
}
func (s *defaultInboundUDPService) SetReadDeadline(t time.Time) error {
return s.udpConn.SetReadDeadline(t)
}
func (s *defaultInboundUDPService) SetWriteDeadline(t time.Time) error {
return s.udpConn.SetWriteDeadline(t)
}

89
adapter/mixed/inbound.go Normal file
View File

@@ -0,0 +1,89 @@
package mixed
import (
std_bufio "bufio"
"context"
"net"
"os"
"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing-box/config"
C "github.com/sagernet/sing-box/constant"
"github.com/sagernet/sing-box/log"
"github.com/sagernet/sing/common"
"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"
N "github.com/sagernet/sing/common/network"
"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.InboundHandler = (*Inbound)(nil)
type Inbound struct {
router adapter.Router
logger log.Logger
authenticator auth.Authenticator
}
func NewInbound(router adapter.Router, logger log.Logger, options *config.SimpleInboundOptions) *Inbound {
return &Inbound{
router: router,
logger: logger,
authenticator: auth.NewAuthenticator(options.Users),
}
}
func (i *Inbound) Type() string {
return C.TypeMixed
}
func (i *Inbound) Network() []string {
return []string{C.NetworkTCP}
}
func (i *Inbound) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
headerType, err := rw.ReadByte(conn)
if err != nil {
return err
}
ctx = &inboundContext{ctx, metadata}
switch headerType {
case socks4.Version, socks5.Version:
return socks.HandleConnection0(ctx, conn, headerType, i.authenticator, (*inboundHandler)(i), M.Metadata{})
}
reader := std_bufio.NewReader(bufio.NewCachedReader(conn, buf.As([]byte{headerType})))
return http.HandleConnection(ctx, conn, reader, i.authenticator, (*inboundHandler)(i), M.Metadata{})
}
func (i *Inbound) NewPacket(ctx context.Context, conn N.PacketConn, buffer *buf.Buffer, metadata adapter.InboundContext) error {
return os.ErrInvalid
}
type inboundContext struct {
context.Context
metadata adapter.InboundContext
}
type inboundHandler Inbound
func (h *inboundHandler) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error {
inboundCtx, _ := common.Cast[*inboundContext](ctx)
ctx = inboundCtx.Context
h.logger.WithContext(ctx).Info("inbound connection to ", metadata.Destination)
inboundCtx.metadata.Destination = metadata.Destination
return h.router.RouteConnection(ctx, conn, inboundCtx.metadata)
}
func (h *inboundHandler) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata M.Metadata) error {
inboundCtx, _ := common.Cast[*inboundContext](ctx)
ctx = inboundCtx.Context
h.logger.WithContext(ctx).Info("inbound packet connection to ", metadata.Destination)
inboundCtx.metadata.Destination = metadata.Destination
return h.router.RoutePacketConnection(ctx, conn, inboundCtx.metadata)
}

21
adapter/outbound.go Normal file
View File

@@ -0,0 +1,21 @@
package adapter
import (
"context"
"net"
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
)
type Outbound interface {
Type() string
Tag() string
NewConnection(ctx context.Context, conn net.Conn, destination M.Socksaddr) error
NewPacketConnection(ctx context.Context, conn N.PacketConn, destination M.Socksaddr) error
N.Dialer
}
type OutboundInitializer interface {
Init(outbound Outbound) error
}

15
adapter/router.go Normal file
View File

@@ -0,0 +1,15 @@
package adapter
import (
"context"
"net"
N "github.com/sagernet/sing/common/network"
)
type Router interface {
DefaultOutbound() Outbound
Outbound(tag string) (Outbound, bool)
RouteConnection(ctx context.Context, conn net.Conn, metadata InboundContext) error
RoutePacketConnection(ctx context.Context, conn N.PacketConn, metadata InboundContext) error
}

6
adapter/service.go Normal file
View File

@@ -0,0 +1,6 @@
package adapter
type Service interface {
Start() error
Close() error
}

View File

@@ -0,0 +1,114 @@
package shadowsocks
import (
"context"
"net"
"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing-box/config"
C "github.com/sagernet/sing-box/constant"
"github.com/sagernet/sing-box/log"
"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 ErrUnsupportedMethod = E.New("unsupported method")
var _ adapter.InboundHandler = (*Inbound)(nil)
type Inbound struct {
router adapter.Router
logger log.Logger
network []string
service shadowsocks.Service
}
func (i *Inbound) Network() []string {
return i.network
}
func NewInbound(router adapter.Router, logger log.Logger, options *config.ShadowsocksInboundOptions) (inbound *Inbound, err error) {
inbound = &Inbound{
router: router,
logger: logger,
network: options.Network.Build(),
}
handler := (*inboundHandler)(inbound)
var udpTimeout int64
if options.UDPTimeout != 0 {
udpTimeout = options.UDPTimeout
} else {
udpTimeout = 300
}
switch {
case options.Method == shadowsocks.MethodNone:
inbound.service = shadowsocks.NewNoneService(options.UDPTimeout, handler)
case common.Contains(shadowaead.List, options.Method):
inbound.service, err = shadowaead.NewService(options.Method, nil, options.Password, udpTimeout, handler)
case common.Contains(shadowaead_2022.List, options.Method):
inbound.service, err = shadowaead_2022.NewServiceWithPassword(options.Method, options.Password, udpTimeout, handler)
default:
err = E.Extend(ErrUnsupportedMethod, options.Method)
}
return
}
func (i *Inbound) Type() string {
return C.TypeShadowsocks
}
func (i *Inbound) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
return i.service.NewConnection(&inboundContext{ctx, metadata}, conn, M.Metadata{
Source: M.SocksaddrFromNetIP(metadata.Source),
})
}
func (i *Inbound) NewPacket(ctx context.Context, conn N.PacketConn, buffer *buf.Buffer, metadata adapter.InboundContext) error {
return i.service.NewPacket(&inboundContext{ctx, metadata}, conn, buffer, M.Metadata{
Source: M.SocksaddrFromNetIP(metadata.Source),
})
}
func (i *Inbound) Upstream() any {
return i.service
}
type inboundContext struct {
context.Context
metadata adapter.InboundContext
}
type inboundHandler Inbound
func (h *inboundHandler) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error {
inboundCtx, _ := common.Cast[*inboundContext](ctx)
ctx = inboundCtx.Context
h.logger.WithContext(ctx).Info("inbound connection to ", metadata.Destination)
inboundCtx.metadata.Destination = metadata.Destination
return h.router.RouteConnection(ctx, conn, inboundCtx.metadata)
}
func (h *inboundHandler) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata M.Metadata) error {
inboundCtx, _ := common.Cast[*inboundContext](ctx)
ctx = log.ContextWithID(inboundCtx.Context)
h.logger.WithContext(ctx).Info("inbound packet connection from ", inboundCtx.metadata.Source)
h.logger.WithContext(ctx).Info("inbound packet connection to ", metadata.Destination)
inboundCtx.metadata.Destination = metadata.Destination
return h.router.RoutePacketConnection(ctx, conn, inboundCtx.metadata)
}
func (h *inboundHandler) NewError(ctx context.Context, err error) {
common.Close(err)
if E.IsClosed(err) {
return
}
h.logger.WithContext(ctx).Warn(err)
}

View File

@@ -0,0 +1,104 @@
package shadowsocks
import (
"context"
"net"
"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing-box/common/dialer"
"github.com/sagernet/sing-box/common/tunnel"
"github.com/sagernet/sing-box/config"
C "github.com/sagernet/sing-box/constant"
"github.com/sagernet/sing-box/log"
"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 = (*Outbound)(nil)
type Outbound struct {
tag string
logger log.Logger
dialer N.Dialer
method shadowsocks.Method
serverAddr M.Socksaddr
}
func NewOutbound(tag string, router adapter.Router, logger log.Logger, options *config.ShadowsocksOutboundOptions) (outbound *Outbound, err error) {
outbound = &Outbound{
tag: tag,
logger: logger,
dialer: dialer.NewDialer(router, options.DialerOptions),
}
outbound.method, err = shadowimpl.FetchMethod(options.Method, options.Password)
if err != nil {
return
}
if options.Server == "" {
err = E.New("missing server address")
return
} else if options.ServerPort == 0 {
err = E.New("missing server port")
return
}
outbound.serverAddr = M.ParseSocksaddrHostPort(options.Server, options.ServerPort)
return
}
func (o *Outbound) Type() string {
return C.TypeShadowsocks
}
func (o *Outbound) Tag() string {
return o.tag
}
func (o *Outbound) NewConnection(ctx context.Context, conn net.Conn, destination M.Socksaddr) error {
serverConn, err := o.DialContext(ctx, "tcp", destination)
if err != nil {
return err
}
return tunnel.CopyEarlyConn(ctx, conn, serverConn)
}
func (o *Outbound) NewPacketConnection(ctx context.Context, conn N.PacketConn, destination M.Socksaddr) error {
serverConn, err := o.ListenPacket(ctx)
if err != nil {
return err
}
return bufio.CopyPacketConn(ctx, conn, bufio.NewPacketConn(serverConn))
}
func (o *Outbound) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
switch network {
case C.NetworkTCP:
o.logger.WithContext(ctx).Debug("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).Debug("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 *Outbound) ListenPacket(ctx context.Context) (net.PacketConn, error) {
o.logger.WithContext(ctx).Debug("outbound packet connection to ", o.serverAddr)
outConn, err := o.dialer.ListenPacket(ctx)
if err != nil {
return nil, err
}
return o.method.DialPacketConn(&bufio.BindPacketConn{PacketConn: outConn, Addr: o.serverAddr.UDPAddr()}), nil
}

74
adapter/socks/inbound.go Normal file
View File

@@ -0,0 +1,74 @@
package socks
import (
"context"
"net"
"os"
"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing-box/config"
C "github.com/sagernet/sing-box/constant"
"github.com/sagernet/sing-box/log"
"github.com/sagernet/sing/common"
"github.com/sagernet/sing/common/auth"
"github.com/sagernet/sing/common/buf"
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
"github.com/sagernet/sing/protocol/socks"
)
var _ adapter.InboundHandler = (*Inbound)(nil)
type Inbound struct {
router adapter.Router
logger log.Logger
authenticator auth.Authenticator
}
func NewInbound(router adapter.Router, logger log.Logger, options *config.SimpleInboundOptions) *Inbound {
return &Inbound{
router: router,
logger: logger,
authenticator: auth.NewAuthenticator(options.Users),
}
}
func (i *Inbound) Type() string {
return C.TypeSocks
}
func (i *Inbound) Network() []string {
return []string{C.NetworkTCP}
}
func (i *Inbound) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
ctx = &inboundContext{ctx, metadata}
return socks.HandleConnection(ctx, conn, i.authenticator, (*inboundHandler)(i), M.Metadata{})
}
func (i *Inbound) NewPacket(ctx context.Context, conn N.PacketConn, buffer *buf.Buffer, metadata adapter.InboundContext) error {
return os.ErrInvalid
}
type inboundContext struct {
context.Context
metadata adapter.InboundContext
}
type inboundHandler Inbound
func (h *inboundHandler) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error {
inboundCtx, _ := common.Cast[*inboundContext](ctx)
ctx = inboundCtx.Context
h.logger.WithContext(ctx).Info("inbound connection to ", metadata.Destination)
inboundCtx.metadata.Destination = metadata.Destination
return h.router.RouteConnection(ctx, conn, inboundCtx.metadata)
}
func (h *inboundHandler) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata M.Metadata) error {
inboundCtx, _ := common.Cast[*inboundContext](ctx)
ctx = inboundCtx.Context
h.logger.WithContext(ctx).Info("inbound packet connection to ", metadata.Destination)
inboundCtx.metadata.Destination = metadata.Destination
return h.router.RoutePacketConnection(ctx, conn, inboundCtx.metadata)
}