inbound.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package http
  2. import (
  3. std_bufio "bufio"
  4. "context"
  5. "net"
  6. "os"
  7. "github.com/sagernet/sing-box/adapter"
  8. "github.com/sagernet/sing-box/config"
  9. C "github.com/sagernet/sing-box/constant"
  10. "github.com/sagernet/sing-box/log"
  11. "github.com/sagernet/sing/common"
  12. "github.com/sagernet/sing/common/auth"
  13. "github.com/sagernet/sing/common/buf"
  14. M "github.com/sagernet/sing/common/metadata"
  15. N "github.com/sagernet/sing/common/network"
  16. "github.com/sagernet/sing/protocol/http"
  17. )
  18. var _ adapter.InboundHandler = (*Inbound)(nil)
  19. type Inbound struct {
  20. router adapter.Router
  21. logger log.Logger
  22. authenticator auth.Authenticator
  23. }
  24. func NewInbound(router adapter.Router, logger log.Logger, options *config.SimpleInboundOptions) *Inbound {
  25. return &Inbound{
  26. router: router,
  27. logger: logger,
  28. authenticator: auth.NewAuthenticator(options.Users),
  29. }
  30. }
  31. func (i *Inbound) Type() string {
  32. return C.TypeHTTP
  33. }
  34. func (i *Inbound) Network() []string {
  35. return []string{C.NetworkTCP}
  36. }
  37. func (i *Inbound) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
  38. ctx = &inboundContext{ctx, metadata}
  39. return http.HandleConnection(ctx, conn, std_bufio.NewReader(conn), i.authenticator, (*inboundHandler)(i), M.Metadata{})
  40. }
  41. func (i *Inbound) NewPacket(ctx context.Context, conn N.PacketConn, buffer *buf.Buffer, metadata adapter.InboundContext) error {
  42. return os.ErrInvalid
  43. }
  44. type inboundContext struct {
  45. context.Context
  46. metadata adapter.InboundContext
  47. }
  48. type inboundHandler Inbound
  49. func (h *inboundHandler) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error {
  50. inboundCtx, _ := common.Cast[*inboundContext](ctx)
  51. ctx = inboundCtx.Context
  52. h.logger.WithContext(ctx).Info("inbound connection to ", metadata.Destination)
  53. inboundCtx.metadata.Destination = metadata.Destination
  54. return h.router.RouteConnection(ctx, conn, inboundCtx.metadata)
  55. }