diff --git a/route/router.go b/route/router.go index dac2f09e61..0b74c7204a 100644 --- a/route/router.go +++ b/route/router.go @@ -132,7 +132,7 @@ func NewRouter( pauseManager: service.FromContext[pause.Manager](ctx), platformInterface: platformInterface, needWIFIState: hasRule(options.Rules, isWIFIRule) || hasDNSRule(dnsOptions.Rules, isWIFIDNSRule), - needPackageManager: C.IsAndroid && platformInterface == nil && common.Any(inbounds, func(inbound option.Inbound) bool { + needPackageManager: common.Any(inbounds, func(inbound option.Inbound) bool { return len(inbound.TunOptions.IncludePackage) > 0 || len(inbound.TunOptions.ExcludePackage) > 0 }), } @@ -532,7 +532,7 @@ func (r *Router) Start() error { r.dnsClient.Start() monitor.Finish() - if r.needPackageManager && r.platformInterface == nil { + if C.IsAndroid && r.platformInterface == nil { monitor.Start("initialize package manager") packageManager, err := tun.NewPackageManager(tun.PackageManagerOptions{ Callback: r, @@ -542,13 +542,15 @@ func (r *Router) Start() error { if err != nil { return E.Cause(err, "create package manager") } - monitor.Start("start package manager") - err = packageManager.Start() - monitor.Finish() - if err != nil { - return E.Cause(err, "start package manager") + if r.needPackageManager { + monitor.Start("start package manager") + err = packageManager.Start() + monitor.Finish() + if err != nil { + return E.Cause(err, "start package manager") + } + r.packageManager = packageManager } - r.packageManager = packageManager } for i, rule := range r.dnsRules { @@ -679,20 +681,30 @@ func (r *Router) PostStart() error { } ruleSetStartContext.Close() } - var ( - needProcessFromRuleSet bool - needWIFIStateFromRuleSet bool - ) + needFindProcess := r.needFindProcess + needWIFIState := r.needWIFIState for _, ruleSet := range r.ruleSets { metadata := ruleSet.Metadata() if metadata.ContainsProcessRule { - needProcessFromRuleSet = true + needFindProcess = true } if metadata.ContainsWIFIRule { - needWIFIStateFromRuleSet = true + needWIFIState = true + } + } + if C.IsAndroid && r.platformInterface == nil && !r.needPackageManager { + if needFindProcess { + monitor.Start("start package manager") + err := r.packageManager.Start() + monitor.Finish() + if err != nil { + return E.Cause(err, "start package manager") + } + } else { + r.packageManager = nil } } - if needProcessFromRuleSet || r.needFindProcess { + if needFindProcess { if r.platformInterface != nil { r.processSearcher = r.platformInterface } else { @@ -711,7 +723,7 @@ func (r *Router) PostStart() error { } } } - if (needWIFIStateFromRuleSet || r.needWIFIState) && r.platformInterface != nil { + if needWIFIState && r.platformInterface != nil { monitor.Start("initialize WIFI state") r.needWIFIState = true r.interfaceMonitor.RegisterCallback(func(_ int) {