inbound.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package adapter
  2. import (
  3. "context"
  4. "net"
  5. "net/netip"
  6. "github.com/sagernet/sing-box/common/process"
  7. "github.com/sagernet/sing-box/option"
  8. M "github.com/sagernet/sing/common/metadata"
  9. N "github.com/sagernet/sing/common/network"
  10. )
  11. type Inbound interface {
  12. Service
  13. Type() string
  14. Tag() string
  15. }
  16. type InjectableInbound interface {
  17. Inbound
  18. Network() []string
  19. NewConnection(ctx context.Context, conn net.Conn, metadata InboundContext) error
  20. NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata InboundContext) error
  21. }
  22. type InboundContext struct {
  23. Inbound string
  24. InboundType string
  25. IPVersion int
  26. Network string
  27. Source M.Socksaddr
  28. Destination M.Socksaddr
  29. Domain string
  30. Protocol string
  31. User string
  32. Outbound string
  33. // cache
  34. InboundDetour string
  35. LastInbound string
  36. OriginDestination M.Socksaddr
  37. InboundOptions option.InboundOptions
  38. DestinationAddresses []netip.Addr
  39. SourceGeoIPCode string
  40. GeoIPCode string
  41. ProcessInfo *process.Info
  42. // dns cache
  43. QueryType uint16
  44. }
  45. type inboundContextKey struct{}
  46. func WithContext(ctx context.Context, inboundContext *InboundContext) context.Context {
  47. return context.WithValue(ctx, (*inboundContextKey)(nil), inboundContext)
  48. }
  49. func ContextFrom(ctx context.Context) *InboundContext {
  50. metadata := ctx.Value((*inboundContextKey)(nil))
  51. if metadata == nil {
  52. return nil
  53. }
  54. return metadata.(*InboundContext)
  55. }
  56. func AppendContext(ctx context.Context) (context.Context, *InboundContext) {
  57. metadata := ContextFrom(ctx)
  58. if metadata != nil {
  59. return ctx, metadata
  60. }
  61. metadata = new(InboundContext)
  62. return WithContext(ctx, metadata), metadata
  63. }