router_ip.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package route
  2. import (
  3. "context"
  4. "github.com/sagernet/sing-box/adapter"
  5. "github.com/sagernet/sing-tun"
  6. )
  7. func (r *Router) RouteIPConnection(ctx context.Context, conn tun.RouteContext, metadata adapter.InboundContext) tun.RouteAction {
  8. for i, rule := range r.ipRules {
  9. if rule.Match(&metadata) {
  10. if rule.Action() == tun.ActionTypeReject {
  11. r.logger.InfoContext(ctx, "match[", i, "] ", rule.String(), " => reject")
  12. return (*tun.ActionReject)(nil)
  13. }
  14. detour := rule.Outbound()
  15. r.logger.InfoContext(ctx, "match[", i, "] ", rule.String(), " => ", detour)
  16. outbound, loaded := r.Outbound(detour)
  17. if !loaded {
  18. r.logger.ErrorContext(ctx, "outbound not found: ", detour)
  19. break
  20. }
  21. ipOutbound, loaded := outbound.(adapter.IPOutbound)
  22. if !loaded {
  23. r.logger.ErrorContext(ctx, "outbound have no ip connection support: ", detour)
  24. break
  25. }
  26. destination, err := ipOutbound.NewIPConnection(ctx, conn, metadata)
  27. if err != nil {
  28. r.logger.ErrorContext(ctx, err)
  29. break
  30. }
  31. return &tun.ActionDirect{DirectDestination: destination}
  32. }
  33. }
  34. return (*tun.ActionReturn)(nil)
  35. }
  36. func (r *Router) NatRequired(outbound string) bool {
  37. for _, ipRule := range r.ipRules {
  38. if ipRule.Outbound() == outbound {
  39. return true
  40. }
  41. }
  42. return false
  43. }