inbound.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. package adapter
  2. import (
  3. "context"
  4. "net/netip"
  5. "github.com/sagernet/sing-box/common/process"
  6. "github.com/sagernet/sing-box/option"
  7. M "github.com/sagernet/sing/common/metadata"
  8. )
  9. type Inbound interface {
  10. Service
  11. Type() string
  12. Tag() string
  13. }
  14. type TCPInjectableInbound interface {
  15. Inbound
  16. ConnectionHandlerEx
  17. }
  18. type UDPInjectableInbound interface {
  19. Inbound
  20. PacketConnectionHandlerEx
  21. }
  22. type InboundContext struct {
  23. Inbound string
  24. InboundType string
  25. IPVersion uint8
  26. Network string
  27. Source M.Socksaddr
  28. Destination M.Socksaddr
  29. User string
  30. Outbound string
  31. // sniffer
  32. Protocol string
  33. Domain string
  34. Client string
  35. SniffContext any
  36. // cache
  37. InboundDetour string
  38. LastInbound string
  39. OriginDestination M.Socksaddr
  40. // Deprecated
  41. InboundOptions option.InboundOptions
  42. UDPDisableDomainUnmapping bool
  43. DestinationAddresses []netip.Addr
  44. SourceGeoIPCode string
  45. GeoIPCode string
  46. ProcessInfo *process.Info
  47. QueryType uint16
  48. FakeIP bool
  49. // rule cache
  50. IPCIDRMatchSource bool
  51. IPCIDRAcceptEmpty bool
  52. SourceAddressMatch bool
  53. SourcePortMatch bool
  54. DestinationAddressMatch bool
  55. DestinationPortMatch bool
  56. DidMatch bool
  57. IgnoreDestinationIPCIDRMatch bool
  58. }
  59. func (c *InboundContext) ResetRuleCache() {
  60. c.IPCIDRMatchSource = false
  61. c.IPCIDRAcceptEmpty = false
  62. c.SourceAddressMatch = false
  63. c.SourcePortMatch = false
  64. c.DestinationAddressMatch = false
  65. c.DestinationPortMatch = false
  66. c.DidMatch = false
  67. }
  68. type inboundContextKey struct{}
  69. func WithContext(ctx context.Context, inboundContext *InboundContext) context.Context {
  70. return context.WithValue(ctx, (*inboundContextKey)(nil), inboundContext)
  71. }
  72. func ContextFrom(ctx context.Context) *InboundContext {
  73. metadata := ctx.Value((*inboundContextKey)(nil))
  74. if metadata == nil {
  75. return nil
  76. }
  77. return metadata.(*InboundContext)
  78. }
  79. func ExtendContext(ctx context.Context) (context.Context, *InboundContext) {
  80. var newMetadata InboundContext
  81. if metadata := ContextFrom(ctx); metadata != nil {
  82. newMetadata = *metadata
  83. }
  84. return WithContext(ctx, &newMetadata), &newMetadata
  85. }
  86. func OverrideContext(ctx context.Context) context.Context {
  87. if metadata := ContextFrom(ctx); metadata != nil {
  88. var newMetadata InboundContext
  89. newMetadata = *metadata
  90. return WithContext(ctx, &newMetadata)
  91. }
  92. return ctx
  93. }