mixed.go 2.1 KB

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