sing-box/inbound/trojan.go

237 lines
7.4 KiB
Go
Raw Permalink Normal View History

2022-08-08 08:56:04 +08:00
package inbound
import (
"context"
"net"
"os"
"github.com/sagernet/sing-box/adapter"
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"
)
2022-08-29 19:43:13 +08:00
var (
_ adapter.Inbound = (*Trojan)(nil)
_ adapter.InjectableInbound = (*Trojan)(nil)
)
2022-08-08 08:56:04 +08:00
type Trojan struct {
myInboundAdapter
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
}
func NewTrojan(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.TrojanInboundOptions) (*Trojan, error) {
inbound := &Trojan{
myInboundAdapter: myInboundAdapter{
protocol: C.TypeTrojan,
network: []string{N.NetworkTCP},
ctx: ctx,
router: router,
logger: logger,
tag: tag,
listenOptions: options.ListenOptions,
},
users: options.Users,
}
2022-08-25 13:35:48 +08:00
if options.TLS != nil {
2023-02-21 14:53:00 +08:00
tlsConfig, err := tls.NewServer(ctx, router, logger, common.PtrValueOrDefault(options.TLS))
2022-08-25 13:35:48 +08:00
if err != nil {
return nil, err
}
inbound.tlsConfig = tlsConfig
}
2022-08-20 20:54:20 +08:00
var fallbackHandler N.TCPConnectionHandler
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
}
2022-08-20 20:54:20 +08:00
fallbackHandler = adapter.NewUpstreamContextHandler(inbound.fallbackConnection, nil, nil)
}
service := trojan.NewService[int](adapter.NewUpstreamContextHandler(inbound.newConnection, inbound.newPacketConnection, inbound), fallbackHandler)
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 {
inbound.transport, err = v2ray.NewServerTransport(ctx, common.PtrValueOrDefault(options.Transport), inbound.tlsConfig, (*trojanTransportHandler)(inbound))
2022-08-23 12:11:56 +08:00
if err != nil {
return nil, E.Cause(err, "create server transport: ", options.Transport.Type)
}
}
2022-08-08 08:56:04 +08:00
inbound.service = service
inbound.connHandler = inbound
return inbound, nil
}
func (h *Trojan) Start() error {
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 {
return h.myInboundAdapter.Start()
}
if common.Contains(h.transport.Network(), N.NetworkTCP) {
tcpListener, err := h.myInboundAdapter.ListenTCP()
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) {
udpConn, err := h.myInboundAdapter.ListenUDP()
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
}
func (h *Trojan) Close() error {
return common.Close(
&h.myInboundAdapter,
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
)
}
2022-08-29 10:10:41 +08:00
func (h *Trojan) newTransportConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
2022-08-29 19:02:14 +08:00
h.injectTCP(conn, metadata)
2022-08-29 10:10:41 +08:00
return nil
}
2022-08-08 08:56:04 +08:00
func (h *Trojan) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
2022-09-30 11:27:18 +08:00
var err error
2022-08-29 10:10:41 +08:00
if h.tlsConfig != nil && h.transport == nil {
2022-09-30 11:27:18 +08:00
conn, err = tls.ServerHandshake(ctx, conn, h.tlsConfig)
if err != nil {
return err
}
2022-08-08 08:56:04 +08:00
}
return h.service.NewConnection(adapter.WithContext(ctx, &metadata), conn, adapter.UpstreamMetadata(metadata))
2022-08-08 08:56:04 +08:00
}
2022-08-29 19:43:13 +08:00
func (h *Trojan) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error {
return os.ErrInvalid
}
2022-08-08 08:56:04 +08:00
func (h *Trojan) newConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
userIndex, loaded := auth.UserFromContext[int](ctx)
if !loaded {
return os.ErrInvalid
}
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)
return h.router.RouteConnection(ctx, conn, metadata)
}
2022-08-20 20:54:20 +08:00
func (h *Trojan) fallbackConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
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 {
return E.New("fallback disabled for ALPN: ", connectionState.NegotiatedProtocol)
}
}
}
}
if !fallbackAddr.IsValid() {
2022-10-01 11:41:15 +08:00
if !h.fallbackAddr.IsValid() {
return E.New("fallback disabled by default")
}
2022-08-25 13:35:48 +08:00
fallbackAddr = h.fallbackAddr
}
h.logger.InfoContext(ctx, "fallback connection to ", fallbackAddr)
metadata.Destination = fallbackAddr
2022-08-20 20:54:20 +08:00
return h.router.RouteConnection(ctx, conn, metadata)
}
2022-08-08 08:56:04 +08:00
func (h *Trojan) newPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error {
userIndex, loaded := auth.UserFromContext[int](ctx)
if !loaded {
return os.ErrInvalid
}
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)
return h.router.RoutePacketConnection(ctx, conn, metadata)
}
var _ adapter.V2RayServerTransportHandler = (*trojanTransportHandler)(nil)
type trojanTransportHandler Trojan
func (t *trojanTransportHandler) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error {
return (*Trojan)(t).newTransportConnection(ctx, conn, adapter.InboundContext{
Source: metadata.Source,
Destination: metadata.Destination,
})
}
func (t *trojanTransportHandler) FallbackConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error {
return (*Trojan)(t).fallbackConnection(ctx, conn, adapter.InboundContext{
Source: metadata.Source,
Destination: metadata.Destination,
})
}