http.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package inbound
  2. import (
  3. std_bufio "bufio"
  4. "context"
  5. "net"
  6. "github.com/sagernet/sing-box/adapter"
  7. C "github.com/sagernet/sing-box/constant"
  8. "github.com/sagernet/sing-box/log"
  9. "github.com/sagernet/sing-box/option"
  10. "github.com/sagernet/sing/common/auth"
  11. M "github.com/sagernet/sing/common/metadata"
  12. N "github.com/sagernet/sing/common/network"
  13. "github.com/sagernet/sing/protocol/http"
  14. )
  15. var _ adapter.Inbound = (*HTTP)(nil)
  16. type HTTP struct {
  17. myInboundAdapter
  18. authenticator auth.Authenticator
  19. }
  20. func NewHTTP(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.HTTPMixedInboundOptions) *HTTP {
  21. inbound := &HTTP{
  22. myInboundAdapter{
  23. protocol: C.TypeHTTP,
  24. network: []string{C.NetworkTCP},
  25. ctx: ctx,
  26. router: router,
  27. logger: logger,
  28. tag: tag,
  29. listenOptions: options.ListenOptions,
  30. setSystemProxy: options.SetSystemProxy,
  31. },
  32. auth.NewAuthenticator(options.Users),
  33. }
  34. inbound.connHandler = inbound
  35. return inbound
  36. }
  37. func (h *HTTP) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
  38. return http.HandleConnection(ctx, conn, std_bufio.NewReader(conn), h.authenticator, h.upstreamUserHandler(metadata), M.Metadata{})
  39. }
  40. func (a *myInboundAdapter) upstreamUserHandler(metadata adapter.InboundContext) adapter.UpstreamHandlerAdapter {
  41. return adapter.NewUpstreamHandler(metadata, a.newUserConnection, a.streamUserPacketConnection, a)
  42. }
  43. func (a *myInboundAdapter) newUserConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
  44. user, loaded := auth.UserFromContext[string](ctx)
  45. if !loaded {
  46. a.logger.InfoContext(ctx, "inbound connection to ", metadata.Destination)
  47. return a.router.RouteConnection(ctx, conn, metadata)
  48. }
  49. metadata.User = user
  50. a.logger.InfoContext(ctx, "[", user, "] inbound connection to ", metadata.Destination)
  51. return a.router.RouteConnection(ctx, conn, metadata)
  52. }
  53. func (a *myInboundAdapter) streamUserPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error {
  54. a.logger.InfoContext(ctx, "inbound packet connection to ", metadata.Destination)
  55. return a.router.RoutePacketConnection(ctx, conn, metadata)
  56. }