router.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. GeoIPReader() *geoip.Reader
  21. LoadGeosite(code string) (Rule, error)
  22. Exchange(ctx context.Context, message *mdns.Msg) (*mdns.Msg, error)
  23. Lookup(ctx context.Context, domain string, strategy dns.DomainStrategy) ([]netip.Addr, error)
  24. LookupDefault(ctx context.Context, domain string) ([]netip.Addr, error)
  25. InterfaceFinder() control.InterfaceFinder
  26. DefaultInterface() string
  27. AutoDetectInterface() bool
  28. AutoDetectInterfaceFunc() control.Func
  29. DefaultMark() int
  30. NetworkMonitor() tun.NetworkUpdateMonitor
  31. InterfaceMonitor() tun.DefaultInterfaceMonitor
  32. PackageManager() tun.PackageManager
  33. Rules() []Rule
  34. TimeService
  35. ClashServer() ClashServer
  36. SetClashServer(server ClashServer)
  37. V2RayServer() V2RayServer
  38. SetV2RayServer(server V2RayServer)
  39. }
  40. type routerContextKey struct{}
  41. func ContextWithRouter(ctx context.Context, router Router) context.Context {
  42. return context.WithValue(ctx, (*routerContextKey)(nil), router)
  43. }
  44. func RouterFromContext(ctx context.Context) Router {
  45. metadata := ctx.Value((*routerContextKey)(nil))
  46. if metadata == nil {
  47. return nil
  48. }
  49. return metadata.(Router)
  50. }
  51. type Rule interface {
  52. Service
  53. Type() string
  54. UpdateGeosite() error
  55. Match(metadata *InboundContext) bool
  56. Outbound() string
  57. String() string
  58. }
  59. type DNSRule interface {
  60. Rule
  61. DisableCache() bool
  62. }
  63. type InterfaceUpdateListener interface {
  64. InterfaceUpdated() error
  65. }