mixed.go 1.8 KB

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