socks.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package inbound
  2. import (
  3. std_bufio "bufio"
  4. "context"
  5. "net"
  6. "github.com/sagernet/sing-box/adapter"
  7. "github.com/sagernet/sing-box/common/uot"
  8. C "github.com/sagernet/sing-box/constant"
  9. "github.com/sagernet/sing-box/log"
  10. "github.com/sagernet/sing-box/option"
  11. "github.com/sagernet/sing/common/auth"
  12. E "github.com/sagernet/sing/common/exceptions"
  13. N "github.com/sagernet/sing/common/network"
  14. "github.com/sagernet/sing/protocol/socks"
  15. )
  16. var (
  17. _ adapter.Inbound = (*Socks)(nil)
  18. _ adapter.TCPInjectableInbound = (*Socks)(nil)
  19. )
  20. type Socks struct {
  21. myInboundAdapter
  22. authenticator *auth.Authenticator
  23. }
  24. func NewSocks(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.SocksInboundOptions) *Socks {
  25. inbound := &Socks{
  26. myInboundAdapter{
  27. protocol: C.TypeSOCKS,
  28. network: []string{N.NetworkTCP},
  29. ctx: ctx,
  30. router: uot.NewRouter(router, logger),
  31. logger: logger,
  32. tag: tag,
  33. listenOptions: options.ListenOptions,
  34. },
  35. auth.NewAuthenticator(options.Users),
  36. }
  37. inbound.connHandler = inbound
  38. return inbound
  39. }
  40. func (h *Socks) NewConnectionEx(ctx context.Context, conn net.Conn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
  41. err := socks.HandleConnectionEx(ctx, conn, std_bufio.NewReader(conn), h.authenticator, nil, h.upstreamUserHandlerEx(metadata), metadata.Source, metadata.Destination, onClose)
  42. N.CloseOnHandshakeFailure(conn, onClose, err)
  43. if err != nil {
  44. h.logger.ErrorContext(ctx, E.Cause(err, "process connection from ", metadata.Source))
  45. }
  46. }