redirect.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package inbound
  2. import (
  3. "context"
  4. "net"
  5. "github.com/sagernet/sing-box/adapter"
  6. "github.com/sagernet/sing-box/common/redir"
  7. C "github.com/sagernet/sing-box/constant"
  8. "github.com/sagernet/sing-box/log"
  9. "github.com/sagernet/sing-box/option"
  10. E "github.com/sagernet/sing/common/exceptions"
  11. M "github.com/sagernet/sing/common/metadata"
  12. )
  13. type Redirect struct {
  14. myInboundAdapter
  15. }
  16. func NewRedirect(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.RedirectInboundOptions) *Redirect {
  17. redirect := &Redirect{
  18. myInboundAdapter{
  19. protocol: C.TypeRedirect,
  20. network: []string{C.NetworkTCP},
  21. ctx: ctx,
  22. router: router,
  23. logger: logger,
  24. tag: tag,
  25. listenOptions: options.ListenOptions,
  26. },
  27. }
  28. redirect.connHandler = redirect
  29. return redirect
  30. }
  31. func (r *Redirect) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
  32. destination, err := redir.GetOriginalDestination(conn)
  33. if err != nil {
  34. return E.Cause(err, "get redirect destination")
  35. }
  36. metadata.Destination = M.SocksaddrFromNetIP(destination)
  37. return r.newConnection(ctx, conn, metadata)
  38. }