router.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package adapter
  2. import (
  3. "context"
  4. "net"
  5. "net/netip"
  6. "github.com/sagernet/sing-box/common/geoip"
  7. "github.com/sagernet/sing-dns"
  8. "github.com/sagernet/sing-tun"
  9. "github.com/sagernet/sing/common/control"
  10. N "github.com/sagernet/sing/common/network"
  11. mdns "github.com/miekg/dns"
  12. )
  13. type Router interface {
  14. Service
  15. Outbounds() []Outbound
  16. Outbound(tag string) (Outbound, bool)
  17. DefaultOutbound(network string) Outbound
  18. RouteConnection(ctx context.Context, conn net.Conn, metadata InboundContext) error
  19. RoutePacketConnection(ctx context.Context, conn N.PacketConn, metadata InboundContext) error
  20. RouteIPConnection(ctx context.Context, conn tun.RouteContext, metadata InboundContext) tun.RouteAction
  21. NatRequired(outbound string) bool
  22. GeoIPReader() *geoip.Reader
  23. LoadGeosite(code string) (Rule, error)
  24. Exchange(ctx context.Context, message *mdns.Msg) (*mdns.Msg, error)
  25. Lookup(ctx context.Context, domain string, strategy dns.DomainStrategy) ([]netip.Addr, error)
  26. LookupDefault(ctx context.Context, domain string) ([]netip.Addr, error)
  27. InterfaceFinder() control.InterfaceFinder
  28. DefaultInterface() string
  29. AutoDetectInterface() bool
  30. AutoDetectInterfaceFunc() control.Func
  31. DefaultMark() int
  32. NetworkMonitor() tun.NetworkUpdateMonitor
  33. InterfaceMonitor() tun.DefaultInterfaceMonitor
  34. PackageManager() tun.PackageManager
  35. Rules() []Rule
  36. IPRules() []IPRule
  37. TimeService
  38. ClashServer() ClashServer
  39. SetClashServer(server ClashServer)
  40. V2RayServer() V2RayServer
  41. SetV2RayServer(server V2RayServer)
  42. }
  43. type routerContextKey struct{}
  44. func ContextWithRouter(ctx context.Context, router Router) context.Context {
  45. return context.WithValue(ctx, (*routerContextKey)(nil), router)
  46. }
  47. func RouterFromContext(ctx context.Context) Router {
  48. metadata := ctx.Value((*routerContextKey)(nil))
  49. if metadata == nil {
  50. return nil
  51. }
  52. return metadata.(Router)
  53. }
  54. type Rule interface {
  55. Service
  56. Type() string
  57. UpdateGeosite() error
  58. Match(metadata *InboundContext) bool
  59. Outbound() string
  60. String() string
  61. }
  62. type DNSRule interface {
  63. Rule
  64. DisableCache() bool
  65. }
  66. type IPRule interface {
  67. Rule
  68. Action() tun.ActionType
  69. }
  70. type InterfaceUpdateListener interface {
  71. InterfaceUpdated() error
  72. }