redirect.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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. M "github.com/sagernet/sing/common/metadata"
  11. N "github.com/sagernet/sing/common/network"
  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{N.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) NewConnectionEx(ctx context.Context, conn net.Conn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
  32. destination, err := redir.GetOriginalDestination(conn)
  33. if err != nil {
  34. conn.Close()
  35. r.logger.ErrorContext(ctx, "process connection from ", conn.RemoteAddr(), ": get redirect destination: ", err)
  36. return
  37. }
  38. metadata.Destination = M.SocksaddrFromNetIP(destination)
  39. r.newConnectionEx(ctx, conn, metadata, onClose)
  40. }