mixed.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. "github.com/sagernet/sing/common/buf"
  12. "github.com/sagernet/sing/common/bufio"
  13. M "github.com/sagernet/sing/common/metadata"
  14. N "github.com/sagernet/sing/common/network"
  15. "github.com/sagernet/sing/common/rw"
  16. "github.com/sagernet/sing/protocol/http"
  17. "github.com/sagernet/sing/protocol/socks"
  18. "github.com/sagernet/sing/protocol/socks/socks4"
  19. "github.com/sagernet/sing/protocol/socks/socks5"
  20. )
  21. var _ adapter.Inbound = (*Mixed)(nil)
  22. type Mixed struct {
  23. myInboundAdapter
  24. authenticator auth.Authenticator
  25. }
  26. func NewMixed(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.HTTPMixedInboundOptions) *Mixed {
  27. inbound := &Mixed{
  28. myInboundAdapter{
  29. protocol: C.TypeMixed,
  30. network: []string{N.NetworkTCP},
  31. ctx: ctx,
  32. router: router,
  33. logger: logger,
  34. tag: tag,
  35. listenOptions: options.ListenOptions,
  36. setSystemProxy: options.SetSystemProxy,
  37. },
  38. auth.NewAuthenticator(options.Users),
  39. }
  40. inbound.connHandler = inbound
  41. return inbound
  42. }
  43. func (h *Mixed) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
  44. headerType, err := rw.ReadByte(conn)
  45. if err != nil {
  46. return err
  47. }
  48. switch headerType {
  49. case socks4.Version, socks5.Version:
  50. return socks.HandleConnection0(ctx, conn, headerType, h.authenticator, h.upstreamUserHandler(metadata), M.Metadata{})
  51. }
  52. reader := std_bufio.NewReader(bufio.NewCachedReader(conn, buf.As([]byte{headerType})))
  53. return http.HandleConnection(ctx, conn, reader, h.authenticator, h.upstreamUserHandler(metadata), M.Metadata{})
  54. }