package tuic import ( "context" "net" "strings" "time" "github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing-box/adapter/inbound" "github.com/sagernet/sing-box/common/listener" "github.com/sagernet/sing-box/common/tls" "github.com/sagernet/sing-box/common/uot" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing-box/option" qtls "github.com/sagernet/sing-quic" "github.com/sagernet/sing-quic/tuic" "github.com/sagernet/sing/common" "github.com/sagernet/sing/common/auth" E "github.com/sagernet/sing/common/exceptions" M "github.com/sagernet/sing/common/metadata" N "github.com/sagernet/sing/common/network" sService "github.com/sagernet/sing/service" "github.com/gofrs/uuid/v5" ) func RegisterInbound(registry *inbound.Registry) { inbound.Register[option.TUICInboundOptions](registry, C.TypeTUIC, NewInbound) } type Inbound struct { inbound.Adapter router adapter.ConnectionRouterEx logger log.ContextLogger listener *listener.Listener tlsConfig tls.ServerConfig server *tuic.Service[int] userNameList []string userManager adapter.UserManager } func NewInbound(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.TUICInboundOptions) (adapter.Inbound, error) { options.UDPFragmentDefault = true if options.TLS == nil || !options.TLS.Enabled { return nil, C.ErrTLSRequired } tlsConfig, err := tls.NewServer(ctx, logger, common.PtrValueOrDefault(options.TLS)) if err != nil { return nil, err } inbound := &Inbound{ Adapter: inbound.NewAdapter(C.TypeTUIC, tag), router: uot.NewRouter(router, logger), logger: logger, listener: listener.New(listener.Options{ Context: ctx, Logger: logger, Listen: options.ListenOptions, }), tlsConfig: tlsConfig, } var udpTimeout time.Duration if options.UDPTimeout != 0 { udpTimeout = time.Duration(options.UDPTimeout) } else { udpTimeout = C.UDPTimeout } service, err := tuic.NewService[int](tuic.ServiceOptions{ Context: ctx, Logger: logger, TLSConfig: tlsConfig, QUICOptions: qtls.QUICOptions{ IdleTimeout: options.IdleTimeout.Build(), KeepAlivePeriod: options.KeepAlivePeriod.Build(), StreamReceiveWindow: options.StreamReceiveWindow.Value(), ConnectionReceiveWindow: options.ConnectionReceiveWindow.Value(), MaxConcurrentStreams: options.MaxConcurrentStreams, InitialPacketSize: options.InitialPacketSize, DisablePathMTUDiscovery: options.DisablePathMTUDiscovery, }, CongestionControl: options.CongestionControl, AuthTimeout: time.Duration(options.AuthTimeout), ZeroRTTHandshake: options.ZeroRTTHandshake, Heartbeat: time.Duration(options.Heartbeat), UDPTimeout: udpTimeout, Handler: inbound, }) if err != nil { return nil, err } userManager := sService.FromContext[adapter.UserManager](ctx) if userManager != nil { creds, err := userManager.GetCredentials(C.TypeTUIC) if err == nil && len(creds) > 0 { userList := make([]int, 0, len(creds)) userNameList := make([]string, 0, len(creds)) userUUIDList := make([][16]byte, 0, len(creds)) userPasswordList := make([]string, 0, len(creds)) for i, c := range creds { parts := strings.SplitN(c.Credential, ":", 2) if len(parts) < 1 || parts[0] == "" { continue } userUUID, pErr := uuid.FromString(parts[0]) if pErr != nil { continue } password := "" if len(parts) == 2 { password = parts[1] } userList = append(userList, i) userNameList = append(userNameList, c.Username) userUUIDList = append(userUUIDList, userUUID) userPasswordList = append(userPasswordList, password) } if len(userList) > 0 { service.UpdateUsers(userList, userUUIDList, userPasswordList) inbound.userNameList = userNameList } } inbound.userManager = userManager } else { userList := make([]int, 0, len(options.Users)) userNameList := make([]string, 0, len(options.Users)) userUUIDList := make([][16]byte, 0, len(options.Users)) userPasswordList := make([]string, 0, len(options.Users)) for index, user := range options.Users { if user.UUID == "" { return nil, E.New("missing uuid for user ", index) } userUUID, err := uuid.FromString(user.UUID) if err != nil { return nil, E.Cause(err, "invalid uuid for user ", index) } userList = append(userList, index) userNameList = append(userNameList, user.Name) userUUIDList = append(userUUIDList, userUUID) userPasswordList = append(userPasswordList, user.Password) } service.UpdateUsers(userList, userUUIDList, userPasswordList) inbound.userNameList = userNameList } inbound.server = service return inbound, nil } func (h *Inbound) NewConnectionEx(ctx context.Context, conn net.Conn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) { ctx = log.ContextWithNewID(ctx) var metadata adapter.InboundContext metadata.Inbound = h.Tag() metadata.InboundType = h.Type() //nolint:staticcheck metadata.InboundDetour = h.listener.ListenOptions().Detour //nolint:staticcheck metadata.OriginDestination = h.listener.UDPAddr() metadata.Source = source metadata.Destination = destination h.logger.InfoContext(ctx, "inbound connection from ", metadata.Source) userID, _ := auth.UserFromContext[int](ctx) if userName := h.userNameList[userID]; userName != "" { metadata.User = userName h.logger.InfoContext(ctx, "[", userName, "] inbound connection to ", metadata.Destination) } else { h.logger.InfoContext(ctx, "inbound connection to ", metadata.Destination) } h.router.RouteConnectionEx(ctx, conn, metadata, onClose) } func (h *Inbound) NewPacketConnectionEx(ctx context.Context, conn N.PacketConn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) { ctx = log.ContextWithNewID(ctx) var metadata adapter.InboundContext metadata.Inbound = h.Tag() metadata.InboundType = h.Type() //nolint:staticcheck metadata.InboundDetour = h.listener.ListenOptions().Detour //nolint:staticcheck metadata.OriginDestination = h.listener.UDPAddr() metadata.Source = source metadata.Destination = destination h.logger.InfoContext(ctx, "inbound packet connection from ", metadata.Source) userID, _ := auth.UserFromContext[int](ctx) if userName := h.userNameList[userID]; userName != "" { metadata.User = userName h.logger.InfoContext(ctx, "[", userName, "] inbound packet connection to ", metadata.Destination) } else { h.logger.InfoContext(ctx, "inbound packet connection to ", metadata.Destination) } h.router.RoutePacketConnectionEx(ctx, conn, metadata, onClose) } func (h *Inbound) Start(stage adapter.StartStage) error { if stage != adapter.StartStateStart { return nil } if h.tlsConfig != nil { err := h.tlsConfig.Start() if err != nil { return err } } if h.userManager != nil { go h.credentialLoop() } packetConn, err := h.listener.ListenUDP() if err != nil { return err } return h.server.Start(packetConn) } func (h *Inbound) syncCredentials() { creds, err := h.userManager.GetCredentials(C.TypeTUIC) if err != nil || len(creds) == 0 { return } userList := make([]int, 0, len(creds)) userNameList := make([]string, 0, len(creds)) userUUIDList := make([][16]byte, 0, len(creds)) userPasswordList := make([]string, 0, len(creds)) for i, c := range creds { parts := strings.SplitN(c.Credential, ":", 2) if len(parts) < 1 || parts[0] == "" { continue } userUUID, pErr := uuid.FromString(parts[0]) if pErr != nil { continue } password := "" if len(parts) == 2 { password = parts[1] } userList = append(userList, i) userNameList = append(userNameList, c.Username) userUUIDList = append(userUUIDList, userUUID) userPasswordList = append(userPasswordList, password) } if len(userList) > 0 { h.server.UpdateUsers(userList, userUUIDList, userPasswordList) h.userNameList = userNameList } } func (h *Inbound) credentialLoop() { h.syncCredentials() ticker := time.NewTicker(30 * time.Second) defer ticker.Stop() for range ticker.C { h.syncCredentials() } } func (h *Inbound) Close() error { return common.Close( h.listener, h.tlsConfig, common.PtrOrNil(h.server), ) }