sing-box/protocol/trojan/inbound.go

258 lines
8.7 KiB
Go
Raw Normal View History

2024-11-02 00:39:02 +08:00
package trojan
2022-08-08 08:56:04 +08:00
import (
"context"
"net"
"os"
"github.com/sagernet/sing-box/adapter"
2024-11-02 00:39:02 +08:00
"github.com/sagernet/sing-box/adapter/inbound"
"github.com/sagernet/sing-box/common/listener"
"github.com/sagernet/sing-box/common/mux"
2022-09-09 18:45:10 +08:00
"github.com/sagernet/sing-box/common/tls"
2022-08-08 08:56:04 +08:00
C "github.com/sagernet/sing-box/constant"
"github.com/sagernet/sing-box/log"
"github.com/sagernet/sing-box/option"
"github.com/sagernet/sing-box/transport/trojan"
2022-08-23 12:11:56 +08:00
"github.com/sagernet/sing-box/transport/v2ray"
2022-08-08 08:56:04 +08:00
"github.com/sagernet/sing/common"
"github.com/sagernet/sing/common/auth"
E "github.com/sagernet/sing/common/exceptions"
F "github.com/sagernet/sing/common/format"
2022-08-20 20:54:20 +08:00
M "github.com/sagernet/sing/common/metadata"
2022-08-08 08:56:04 +08:00
N "github.com/sagernet/sing/common/network"
)
2024-11-02 00:39:02 +08:00
func RegisterInbound(registry *inbound.Registry) {
inbound.Register[option.TrojanInboundOptions](registry, C.TypeTrojan, NewInbound)
}
var _ adapter.TCPInjectableInbound = (*Inbound)(nil)
2022-08-08 08:56:04 +08:00
2024-11-02 00:39:02 +08:00
type Inbound struct {
inbound.Adapter
router adapter.ConnectionRouterEx
logger log.ContextLogger
listener *listener.Listener
2022-08-25 13:35:48 +08:00
service *trojan.Service[int]
users []option.TrojanUser
2022-09-09 18:45:10 +08:00
tlsConfig tls.ServerConfig
2022-08-25 13:35:48 +08:00
fallbackAddr M.Socksaddr
fallbackAddrTLSNextProto map[string]M.Socksaddr
transport adapter.V2RayServerTransport
2022-08-08 08:56:04 +08:00
}
2024-11-02 00:39:02 +08:00
func NewInbound(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.TrojanInboundOptions) (adapter.Inbound, error) {
inbound := &Inbound{
Adapter: inbound.NewAdapter(C.TypeTrojan, tag),
router: router,
logger: logger,
users: options.Users,
2022-08-08 08:56:04 +08:00
}
2022-08-25 13:35:48 +08:00
if options.TLS != nil {
2023-08-29 13:43:42 +08:00
tlsConfig, err := tls.NewServer(ctx, logger, common.PtrValueOrDefault(options.TLS))
2022-08-25 13:35:48 +08:00
if err != nil {
return nil, err
}
inbound.tlsConfig = tlsConfig
}
2024-11-23 22:34:02 +08:00
var fallbackHandler N.TCPConnectionHandlerEx
2022-08-25 13:35:48 +08:00
if options.Fallback != nil && options.Fallback.Server != "" || len(options.FallbackForALPN) > 0 {
if options.Fallback != nil && options.Fallback.Server != "" {
inbound.fallbackAddr = options.Fallback.Build()
if !inbound.fallbackAddr.IsValid() {
return nil, E.New("invalid fallback address: ", inbound.fallbackAddr)
}
}
if len(options.FallbackForALPN) > 0 {
if inbound.tlsConfig == nil {
return nil, E.New("fallback for ALPN is not supported without TLS")
}
fallbackAddrNextProto := make(map[string]M.Socksaddr)
for nextProto, destination := range options.FallbackForALPN {
fallbackAddr := destination.Build()
if !fallbackAddr.IsValid() {
return nil, E.New("invalid fallback address for ALPN ", nextProto, ": ", fallbackAddr)
}
fallbackAddrNextProto[nextProto] = fallbackAddr
}
inbound.fallbackAddrTLSNextProto = fallbackAddrNextProto
}
2024-11-23 22:34:02 +08:00
fallbackHandler = adapter.NewUpstreamContextHandlerEx(inbound.fallbackConnection, nil)
2022-08-20 20:54:20 +08:00
}
2024-11-23 22:34:02 +08:00
service := trojan.NewService[int](adapter.NewUpstreamContextHandlerEx(inbound.newConnection, inbound.newPacketConnection), fallbackHandler, logger)
2022-08-08 08:56:04 +08:00
err := service.UpdateUsers(common.MapIndexed(options.Users, func(index int, it option.TrojanUser) int {
return index
}), common.Map(options.Users, func(it option.TrojanUser) string {
return it.Password
}))
if err != nil {
return nil, err
}
2022-08-23 12:11:56 +08:00
if options.Transport != nil {
2024-11-02 00:39:02 +08:00
inbound.transport, err = v2ray.NewServerTransport(ctx, logger, common.PtrValueOrDefault(options.Transport), inbound.tlsConfig, (*inboundTransportHandler)(inbound))
2022-08-23 12:11:56 +08:00
if err != nil {
return nil, E.Cause(err, "create server transport: ", options.Transport.Type)
}
}
inbound.router, err = mux.NewRouterWithOptions(inbound.router, logger, common.PtrValueOrDefault(options.Multiplex))
if err != nil {
return nil, err
}
2022-08-08 08:56:04 +08:00
inbound.service = service
2024-11-02 00:39:02 +08:00
inbound.listener = listener.New(listener.Options{
Context: ctx,
Logger: logger,
Network: []string{N.NetworkTCP},
Listen: options.ListenOptions,
ConnectionHandler: inbound,
})
2022-08-08 08:56:04 +08:00
return inbound, nil
}
2024-11-21 18:10:41 +08:00
func (h *Inbound) Start(stage adapter.StartStage) error {
if stage != adapter.StartStateStart {
return nil
}
2022-08-08 08:56:04 +08:00
if h.tlsConfig != nil {
err := h.tlsConfig.Start()
if err != nil {
return E.Cause(err, "create TLS config")
}
}
2022-08-23 12:11:56 +08:00
if h.transport == nil {
2024-11-02 00:39:02 +08:00
return h.listener.Start()
2022-08-23 12:11:56 +08:00
}
if common.Contains(h.transport.Network(), N.NetworkTCP) {
2024-11-02 00:39:02 +08:00
tcpListener, err := h.listener.ListenTCP()
2022-08-23 12:11:56 +08:00
if err != nil {
return err
}
go func() {
sErr := h.transport.Serve(tcpListener)
if sErr != nil && !E.IsClosed(sErr) {
h.logger.Error("transport serve error: ", sErr)
}
}()
}
if common.Contains(h.transport.Network(), N.NetworkUDP) {
2024-11-02 00:39:02 +08:00
udpConn, err := h.listener.ListenUDP()
2022-08-23 12:11:56 +08:00
if err != nil {
return err
}
go func() {
sErr := h.transport.ServePacket(udpConn)
if sErr != nil && !E.IsClosed(sErr) {
h.logger.Error("transport serve error: ", sErr)
}
}()
}
return nil
2022-08-08 08:56:04 +08:00
}
2024-11-02 00:39:02 +08:00
func (h *Inbound) Close() error {
2022-08-08 08:56:04 +08:00
return common.Close(
h.listener,
2022-09-09 18:45:10 +08:00
h.tlsConfig,
2022-08-23 12:11:56 +08:00
h.transport,
2022-08-08 08:56:04 +08:00
)
}
2024-11-23 22:34:02 +08:00
func (h *Inbound) NewConnectionEx(ctx context.Context, conn net.Conn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
2022-08-29 10:10:41 +08:00
if h.tlsConfig != nil && h.transport == nil {
2024-11-23 22:34:02 +08:00
tlsConn, err := tls.ServerHandshake(ctx, conn, h.tlsConfig)
2022-09-30 11:27:18 +08:00
if err != nil {
2024-11-23 22:34:02 +08:00
N.CloseOnHandshakeFailure(conn, onClose, err)
h.logger.ErrorContext(ctx, E.Cause(err, "process connection from ", metadata.Source, ": TLS handshake"))
return
2022-09-30 11:27:18 +08:00
}
2024-11-23 22:34:02 +08:00
conn = tlsConn
2022-08-08 08:56:04 +08:00
}
2024-11-23 22:34:02 +08:00
err := h.service.NewConnection(adapter.WithContext(ctx, &metadata), conn, metadata.Source, onClose)
2024-10-21 23:38:34 +08:00
if err != nil {
2024-11-23 22:34:02 +08:00
N.CloseOnHandshakeFailure(conn, onClose, err)
h.logger.ErrorContext(ctx, E.Cause(err, "process connection from ", metadata.Source))
2024-10-21 23:38:34 +08:00
}
2022-08-29 19:43:13 +08:00
}
2024-11-23 22:34:02 +08:00
func (h *Inbound) newConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
metadata.Inbound = h.Tag()
metadata.InboundType = h.Type()
2022-08-08 08:56:04 +08:00
userIndex, loaded := auth.UserFromContext[int](ctx)
if !loaded {
2024-11-23 22:34:02 +08:00
N.CloseOnHandshakeFailure(conn, onClose, os.ErrInvalid)
return
2022-08-08 08:56:04 +08:00
}
user := h.users[userIndex].Name
if user == "" {
user = F.ToString(userIndex)
} else {
metadata.User = user
}
h.logger.InfoContext(ctx, "[", user, "] inbound connection to ", metadata.Destination)
2024-11-23 22:34:02 +08:00
h.router.RouteConnectionEx(ctx, conn, metadata, onClose)
}
func (h *Inbound) newPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
metadata.Inbound = h.Tag()
metadata.InboundType = h.Type()
userIndex, loaded := auth.UserFromContext[int](ctx)
if !loaded {
N.CloseOnHandshakeFailure(conn, onClose, os.ErrInvalid)
return
}
user := h.users[userIndex].Name
if user == "" {
user = F.ToString(userIndex)
} else {
metadata.User = user
}
h.logger.InfoContext(ctx, "[", user, "] inbound packet connection to ", metadata.Destination)
h.router.RoutePacketConnectionEx(ctx, conn, metadata, onClose)
2022-08-08 08:56:04 +08:00
}
2024-11-23 22:34:02 +08:00
func (h *Inbound) fallbackConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
2022-08-25 13:35:48 +08:00
var fallbackAddr M.Socksaddr
if len(h.fallbackAddrTLSNextProto) > 0 {
2022-10-01 11:41:15 +08:00
if tlsConn, loaded := common.Cast[tls.Conn](conn); loaded {
2022-08-25 13:35:48 +08:00
connectionState := tlsConn.ConnectionState()
if connectionState.NegotiatedProtocol != "" {
if fallbackAddr, loaded = h.fallbackAddrTLSNextProto[connectionState.NegotiatedProtocol]; !loaded {
2024-11-23 22:34:02 +08:00
h.logger.DebugContext(ctx, "process connection from ", metadata.Source, ": fallback disabled for ALPN: ", connectionState.NegotiatedProtocol)
N.CloseOnHandshakeFailure(conn, onClose, os.ErrInvalid)
return
2022-08-25 13:35:48 +08:00
}
}
}
}
if !fallbackAddr.IsValid() {
2022-10-01 11:41:15 +08:00
if !h.fallbackAddr.IsValid() {
2024-11-23 22:34:02 +08:00
h.logger.DebugContext(ctx, "process connection from ", metadata.Source, ": fallback disabled by default")
N.CloseOnHandshakeFailure(conn, onClose, os.ErrInvalid)
return
2022-10-01 11:41:15 +08:00
}
2022-08-25 13:35:48 +08:00
fallbackAddr = h.fallbackAddr
}
metadata.Inbound = h.Tag()
metadata.InboundType = h.Type()
2022-08-25 13:35:48 +08:00
metadata.Destination = fallbackAddr
2024-11-23 22:34:02 +08:00
h.logger.InfoContext(ctx, "fallback connection to ", fallbackAddr)
h.router.RouteConnectionEx(ctx, conn, metadata, onClose)
2022-08-08 08:56:04 +08:00
}
2024-11-02 00:39:02 +08:00
var _ adapter.V2RayServerTransportHandler = (*inboundTransportHandler)(nil)
2024-11-02 00:39:02 +08:00
type inboundTransportHandler Inbound
2024-11-02 00:39:02 +08:00
func (h *inboundTransportHandler) NewConnectionEx(ctx context.Context, conn net.Conn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
var metadata adapter.InboundContext
metadata.Source = source
metadata.Destination = destination
2024-11-23 22:34:02 +08:00
//nolint:staticcheck
metadata.InboundDetour = h.listener.ListenOptions().Detour
//nolint:staticcheck
metadata.InboundOptions = h.listener.ListenOptions().InboundOptions
2024-11-02 00:39:02 +08:00
h.logger.InfoContext(ctx, "inbound connection from ", metadata.Source)
(*Inbound)(h).NewConnectionEx(ctx, conn, metadata, onClose)
}