inbound.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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 uint8
  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. QueryType uint16
  43. FakeIP bool
  44. // rule cache
  45. IPCIDRMatchSource bool
  46. SourceAddressMatch bool
  47. SourcePortMatch bool
  48. DestinationAddressMatch bool
  49. DestinationPortMatch bool
  50. }
  51. func (c *InboundContext) ResetRuleCache() {
  52. c.IPCIDRMatchSource = false
  53. c.SourceAddressMatch = false
  54. c.SourcePortMatch = false
  55. c.DestinationAddressMatch = false
  56. c.DestinationPortMatch = false
  57. }
  58. type inboundContextKey struct{}
  59. func WithContext(ctx context.Context, inboundContext *InboundContext) context.Context {
  60. return context.WithValue(ctx, (*inboundContextKey)(nil), inboundContext)
  61. }
  62. func ContextFrom(ctx context.Context) *InboundContext {
  63. metadata := ctx.Value((*inboundContextKey)(nil))
  64. if metadata == nil {
  65. return nil
  66. }
  67. return metadata.(*InboundContext)
  68. }
  69. func AppendContext(ctx context.Context) (context.Context, *InboundContext) {
  70. metadata := ContextFrom(ctx)
  71. if metadata != nil {
  72. return ctx, metadata
  73. }
  74. metadata = new(InboundContext)
  75. return WithContext(ctx, metadata), metadata
  76. }
  77. func ExtendContext(ctx context.Context) (context.Context, *InboundContext) {
  78. var newMetadata InboundContext
  79. if metadata := ContextFrom(ctx); metadata != nil {
  80. newMetadata = *metadata
  81. }
  82. return WithContext(ctx, &newMetadata), &newMetadata
  83. }