socks.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package outbound
  2. import (
  3. "context"
  4. "net"
  5. M "github.com/sagernet/sing/common/metadata"
  6. N "github.com/sagernet/sing/common/network"
  7. "github.com/sagernet/sing/protocol/socks"
  8. "github.com/sagernet/sing-box/adapter"
  9. "github.com/sagernet/sing-box/common/dialer"
  10. C "github.com/sagernet/sing-box/constant"
  11. "github.com/sagernet/sing-box/log"
  12. "github.com/sagernet/sing-box/option"
  13. )
  14. var _ adapter.Outbound = (*Socks)(nil)
  15. type Socks struct {
  16. myOutboundAdapter
  17. client *socks.Client
  18. }
  19. func NewSocks(router adapter.Router, logger log.Logger, tag string, options option.SocksOutboundOptions) (*Socks, error) {
  20. detour := dialer.NewOutbound(router, options.OutboundDialerOptions)
  21. var version socks.Version
  22. var err error
  23. if options.Version != "" {
  24. version, err = socks.ParseVersion(options.Version)
  25. } else {
  26. version = socks.Version5
  27. }
  28. if err != nil {
  29. return nil, err
  30. }
  31. return &Socks{
  32. myOutboundAdapter{
  33. protocol: C.TypeSocks,
  34. logger: logger,
  35. tag: tag,
  36. network: options.Network.Build(),
  37. },
  38. socks.NewClient(detour, options.ServerOptions.Build(), version, options.Username, options.Password),
  39. }, nil
  40. }
  41. func (h *Socks) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
  42. ctx, metadata := adapter.AppendContext(ctx)
  43. metadata.Outbound = h.tag
  44. metadata.Destination = destination
  45. switch network {
  46. case C.NetworkTCP:
  47. h.logger.WithContext(ctx).Info("outbound connection to ", destination)
  48. case C.NetworkUDP:
  49. h.logger.WithContext(ctx).Info("outbound packet connection to ", destination)
  50. default:
  51. panic("unknown network " + network)
  52. }
  53. return h.client.DialContext(ctx, network, destination)
  54. }
  55. func (h *Socks) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
  56. ctx, metadata := adapter.AppendContext(ctx)
  57. metadata.Outbound = h.tag
  58. metadata.Destination = destination
  59. h.logger.WithContext(ctx).Info("outbound packet connection to ", destination)
  60. return h.client.ListenPacket(ctx, destination)
  61. }
  62. func (h *Socks) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
  63. return NewConnection(ctx, h, conn, metadata)
  64. }
  65. func (h *Socks) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error {
  66. return NewPacketConnection(ctx, h, conn, metadata)
  67. }