diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 9900007e38..f2dd8037e4 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -172,6 +172,11 @@ android:configChanges="uiMode" android:exported="false" android:label="@string/meta_features" /> + () { + override suspend fun main() { + val store = ServiceStore(this) + val initial = withContext(Dispatchers.IO) { store.landingProxyJson() } + + val design = LandingProxySettingsDesign(this, store) + + setContentDesign(design) + + defer { + val changed = withContext(Dispatchers.IO) { store.landingProxyJson() } != initial + + // reload the running profile; a preview picks the change up on its next load + if (changed && clashRunning) { + sendOverrideChanged() + } + } + + while (isActive) { + select { + events.onReceive { + + } + design.requests.onReceive { + when (it) { + LandingProxySettingsDesign.Request.PickFrontGroup -> { + design.requestFrontGroup(queryGroupNames()) + } + } + } + } + } + } + + private suspend fun queryGroupNames(): List { + return try { + withClash { + if (preparePreview() != null) { + return@withClash emptyList() + } + + try { + queryProxyGroupNames(false).filter { it != "GLOBAL" } + } finally { + releasePreview() + } + } + } catch (e: Exception) { + emptyList() + } + } +} diff --git a/app/src/main/java/com/github/kr328/clash/NetworkSettingsActivity.kt b/app/src/main/java/com/github/kr328/clash/NetworkSettingsActivity.kt index c7cc72451f..726eb58c9d 100644 --- a/app/src/main/java/com/github/kr328/clash/NetworkSettingsActivity.kt +++ b/app/src/main/java/com/github/kr328/clash/NetworkSettingsActivity.kt @@ -1,18 +1,29 @@ package com.github.kr328.clash +import android.content.ActivityNotFoundException +import android.content.Intent +import android.provider.Settings import com.github.kr328.clash.common.util.intent import com.github.kr328.clash.design.NetworkSettingsDesign +import com.github.kr328.clash.remote.StatusClient import com.github.kr328.clash.service.store.ServiceStore +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.isActive import kotlinx.coroutines.selects.select +import kotlinx.coroutines.withContext class NetworkSettingsActivity : BaseActivity() { override suspend fun main() { + val vpnState = withContext(Dispatchers.IO) { + StatusClient(this@NetworkSettingsActivity).vpnState() + } + val design = NetworkSettingsDesign( this, uiStore, ServiceStore(this), clashRunning, + vpnState, ) setContentDesign(design) @@ -30,6 +41,12 @@ class NetworkSettingsActivity : BaseActivity() { when (it) { NetworkSettingsDesign.Request.StartAccessControlList -> startActivity(AccessControlActivity::class.intent) + NetworkSettingsDesign.Request.OpenSystemVpnSettings -> + try { + startActivity(Intent(Settings.ACTION_VPN_SETTINGS)) + } catch (e: ActivityNotFoundException) { + startActivity(Intent(Settings.ACTION_WIRELESS_SETTINGS)) + } } } } diff --git a/app/src/main/java/com/github/kr328/clash/ProxyActivity.kt b/app/src/main/java/com/github/kr328/clash/ProxyActivity.kt index 9136a3000d..fc72adf63c 100644 --- a/app/src/main/java/com/github/kr328/clash/ProxyActivity.kt +++ b/app/src/main/java/com/github/kr328/clash/ProxyActivity.kt @@ -1,5 +1,6 @@ package com.github.kr328.clash +import android.widget.Toast import com.github.kr328.clash.common.util.intent import com.github.kr328.clash.core.Clash import com.github.kr328.clash.core.model.Proxy @@ -14,6 +15,20 @@ import kotlinx.coroutines.sync.withPermit class ProxyActivity : BaseActivity() { override suspend fun main() { + // Load the active profile without starting the service (no-op while running), + // so proxies can be browsed and tested while stopped. + val previewError = withClash { preparePreview() } + + if (previewError != null) { + Toast.makeText(this, previewError, Toast.LENGTH_LONG).show() + + return finish() + } + + defer { + withClash { releasePreview() } + } + val mode = withClash { queryOverride(Clash.OverrideSlot.Session).mode } val names = withClash { queryProxyGroupNames(uiStore.proxyExcludeNotSelectable) } val states = List(names.size) { ProxyState("?") } @@ -46,6 +61,33 @@ class ProxyActivity : BaseActivity() { finish() } } + Event.ClashStop -> { + // the runtime reset the core, load a preview into it again + val error = withClash { reloadPreview() } + + if (error != null) { + Toast.makeText(this@ProxyActivity, error, Toast.LENGTH_LONG).show() + + finish() + } else { + val newNames = withClash { + queryProxyGroupNames(uiStore.proxyExcludeNotSelectable) + } + + if (newNames != names) { + startActivity(ProxyActivity::class.intent) + + finish() + } else { + // the runtime also cleared the session override + design.updateMode( + withClash { queryOverride(Clash.OverrideSlot.Session).mode } + ) + + design.requests.send(ProxyDesign.Request.ReloadAll) + } + } + } else -> Unit } } diff --git a/app/src/main/java/com/github/kr328/clash/SettingsActivity.kt b/app/src/main/java/com/github/kr328/clash/SettingsActivity.kt index 95a0393367..235624142b 100644 --- a/app/src/main/java/com/github/kr328/clash/SettingsActivity.kt +++ b/app/src/main/java/com/github/kr328/clash/SettingsActivity.kt @@ -22,6 +22,8 @@ class SettingsActivity : BaseActivity() { startActivity(AppSettingsActivity::class.intent) SettingsDesign.Request.StartNetwork -> startActivity(NetworkSettingsActivity::class.intent) + SettingsDesign.Request.StartLandingProxy -> + startActivity(LandingProxySettingsActivity::class.intent) SettingsDesign.Request.StartOverride -> startActivity(OverrideSettingsActivity::class.intent) SettingsDesign.Request.StartMetaFeature -> diff --git a/app/src/main/java/com/github/kr328/clash/remote/StatusClient.kt b/app/src/main/java/com/github/kr328/clash/remote/StatusClient.kt index fd3625befc..4b22d9327f 100644 --- a/app/src/main/java/com/github/kr328/clash/remote/StatusClient.kt +++ b/app/src/main/java/com/github/kr328/clash/remote/StatusClient.kt @@ -15,6 +15,27 @@ class StatusClient(private val context: Context) { .build() } + /** Always-on / lockdown state, only known while the VPN service is running (API 29+). */ + fun vpnState(): StatusProvider.VpnState? { + return try { + val result = context.contentResolver.call( + uri, + StatusProvider.METHOD_VPN_STATE, + null, + null + ) ?: return null + + StatusProvider.VpnState( + alwaysOn = result.getBoolean(StatusProvider.KEY_ALWAYS_ON), + lockdown = result.getBoolean(StatusProvider.KEY_LOCKDOWN), + ) + } catch (e: Exception) { + Log.w("Query vpn state: $e", e) + + null + } + } + fun currentProfile(): String? { return try { val result = context.contentResolver.call( diff --git a/core/src/main/cpp/main.c b/core/src/main/cpp/main.c index 61e431c8a1..763edd4972 100644 --- a/core/src/main/cpp/main.c +++ b/core/src/main/cpp/main.c @@ -215,13 +215,35 @@ Java_com_github_kr328_clash_core_bridge_Bridge_nativePatchSelector(JNIEnv *env, JNIEXPORT void JNICALL Java_com_github_kr328_clash_core_bridge_Bridge_nativeLoad(JNIEnv *env, jobject thiz, - jobject completable, jstring path) { + jobject completable, jstring path, + jboolean preview) { TRACE_METHOD(); jobject _completable = new_global(completable); scoped_string _path = get_string(path); - load(_completable, _path); + load(_completable, _path, preview); +} + +JNIEXPORT jstring JNICALL +Java_com_github_kr328_clash_core_bridge_Bridge_nativeSetLandingProxy(JNIEnv *env, jobject thiz, + jstring content) { + TRACE_METHOD(); + + scoped_string response = NULL; + + if (content == NULL) { + response = setLandingProxy(NULL); + } else { + scoped_string _content = get_string(content); + + response = setLandingProxy(_content); + } + + if (response == NULL) + return NULL; + + return new_string(response); } JNIEXPORT void JNICALL diff --git a/core/src/main/golang/native/config.go b/core/src/main/golang/native/config.go index 43e099b683..a3f6d990f0 100644 --- a/core/src/main/golang/native/config.go +++ b/core/src/main/golang/native/config.go @@ -39,14 +39,23 @@ func fetchAndValid(callback unsafe.Pointer, path, url C.c_string, force C.int) { } //export load -func load(completable unsafe.Pointer, path C.c_string) { - go func(path string) { - C.complete(completable, marshalString(config.Load(path))) +func load(completable unsafe.Pointer, path C.c_string, preview C.int) { + go func(path string, preview bool) { + C.complete(completable, marshalString(config.Load(path, preview))) C.release_object(completable) runtime.GC() - }(C.GoString(path)) + }(C.GoString(path), preview != 0) +} + +//export setLandingProxy +func setLandingProxy(content C.c_string) *C.char { + if content == nil { + return marshalString(config.SetLandingProxy("")) + } + + return marshalString(config.SetLandingProxy(C.GoString(content))) } //export readOverride diff --git a/core/src/main/golang/native/config/landing.go b/core/src/main/golang/native/config/landing.go new file mode 100644 index 0000000000..4d6c8426d0 --- /dev/null +++ b/core/src/main/golang/native/config/landing.go @@ -0,0 +1,328 @@ +package config + +import ( + "encoding/json" + "errors" + "fmt" + "sort" + "strings" + "sync" + + "github.com/dlclark/regexp2" + + "github.com/metacubex/mihomo/adapter/outboundgroup" + "github.com/metacubex/mihomo/config" + "github.com/metacubex/mihomo/log" + RC "github.com/metacubex/mihomo/rules/common" + "github.com/metacubex/mihomo/tunnel" +) + +// LandingProxyName is the name of the injected landing (exit) proxy. +const LandingProxyName = "Landing Proxy" + +// LandingProxy describes an explicit landing (exit) proxy chained behind a +// front group of the profile: +// +// device -> front group's selected node -> landing proxy -> target +// +// Every rule, sub-rule and group member that targets the front group is +// redirected to the landing proxy, while the front group itself stays +// selectable and decides which node is used as the relay. +type LandingProxy struct { + Type string `json:"type"` // http, https, socks5 + Server string `json:"server"` + Port int `json:"port"` + Username string `json:"username"` + Password string `json:"password"` + FrontGroup string `json:"frontGroup"` // empty = first `select` group + SkipCertVerify bool `json:"skipCertVerify"` + Sni string `json:"sni"` + Udp bool `json:"udp"` +} + +var ( + landingLock sync.Mutex + landing *LandingProxy +) + +// SetLandingProxy sets (or clears, with an empty string) the landing proxy +// used by subsequent loads. +func SetLandingProxy(content string) error { + landingLock.Lock() + defer landingLock.Unlock() + + if strings.TrimSpace(content) == "" { + landing = nil + + return nil + } + + l := &LandingProxy{} + if err := json.Unmarshal([]byte(content), l); err != nil { + landing = nil + + return err + } + + landing = l + + return nil +} + +func currentLanding() *LandingProxy { + landingLock.Lock() + defer landingLock.Unlock() + + return landing +} + +func (l *LandingProxy) toMapping(front string) (map[string]any, error) { + if l.Server == "" { + return nil, errors.New("landing proxy: server is empty") + } + if l.Port <= 0 || l.Port > 65535 { + return nil, fmt.Errorf("landing proxy: invalid port %d", l.Port) + } + + m := map[string]any{ + "name": LandingProxyName, + "server": l.Server, + "port": l.Port, + "dialer-proxy": front, + } + + if l.Username != "" { + m["username"] = l.Username + m["password"] = l.Password + } + + switch strings.ToLower(l.Type) { + case "http": + m["type"] = "http" + case "https": + m["type"] = "http" + m["tls"] = true + m["skip-cert-verify"] = l.SkipCertVerify + if l.Sni != "" { + m["sni"] = l.Sni + } + case "socks5": + m["type"] = "socks5" + m["udp"] = l.Udp + default: + return nil, fmt.Errorf("landing proxy: unsupported type `%s`", l.Type) + } + + return m, nil +} + +func groupName(group map[string]any) string { + name, _ := group["name"].(string) + + return name +} + +func toStringList(value any) []string { + switch v := value.(type) { + case []string: + return v + case []any: + result := make([]string, 0, len(v)) + for _, item := range v { + if s, ok := item.(string); ok { + result = append(result, s) + } + } + return result + default: + return nil + } +} + +func toBool(value any) bool { + switch v := value.(type) { + case bool: + return v + case string: + return strings.EqualFold(v, "true") + default: + return false + } +} + +func resolveFrontGroup(cfg *config.RawConfig, front string) (string, error) { + if front != "" { + for _, g := range cfg.ProxyGroup { + if groupName(g) == front { + return front, nil + } + } + + return "", fmt.Errorf("landing proxy: front group `%s` not found in profile", front) + } + + for _, g := range cfg.ProxyGroup { + if t, _ := g["type"].(string); t == "select" && groupName(g) != "" && groupName(g) != "GLOBAL" { + return groupName(g), nil + } + } + + return "", errors.New("landing proxy: profile has no `select` group to use as front group") +} + +// expandIncludeAllProxies replaces `include-all`/`include-all-proxies` with an +// explicit proxy list computed from the profile's own proxies, mirroring +// mihomo's ParseProxyGroup. Otherwise the injected landing proxy would be +// pulled into these groups and could form a dial loop through the front group. +func expandIncludeAllProxies(group map[string]any, allProxies []string, hasProviders bool) { + includeAll := toBool(group["include-all"]) + includeAllProxies := toBool(group["include-all-proxies"]) + + if !includeAll && !includeAllProxies { + return + } + + if includeAll { + delete(group, "include-all") + group["include-all-providers"] = true + } + delete(group, "include-all-proxies") + + proxies := toStringList(group["proxies"]) + + if filter, _ := group["filter"].(string); filter != "" { + var regs []*regexp2.Regexp + for _, f := range strings.Split(filter, "`") { + reg, err := regexp2.Compile(f, regexp2.None) + if err != nil { + continue // mihomo will report the invalid filter itself + } + regs = append(regs, reg) + } + for _, p := range allProxies { + for _, reg := range regs { + if ok, _ := reg.MatchString(p); ok { + proxies = append(proxies, p) + break + } + } + } + } else { + proxies = append(proxies, allProxies...) + } + + use := toStringList(group["use"]) + providersIncluded := toBool(group["include-all-providers"]) && hasProviders + if len(proxies) == 0 && len(use) == 0 && !providersIncluded { + fallback, _ := group["empty-fallback"].(string) + if fallback == "" { + fallback = "COMPATIBLE" + } + proxies = []string{fallback} + } + + group["proxies"] = proxies +} + +func retargetRule(line, front string) string { + tp, payload, target, params := RC.ParseRulePayload(line, true) + if target != front || tp == "SUB-RULE" { + return line + } + + switch tp { + case "MATCH": + return tp + "," + LandingProxyName + case "NOT", "OR", "AND", "DOMAIN-REGEX", "PROCESS-NAME-REGEX", "PROCESS-PATH-REGEX": + return tp + "," + payload + "," + LandingProxyName + default: + parts := append([]string{tp, payload, LandingProxyName}, params...) + return strings.Join(parts, ",") + } +} + +func patchLanding(cfg *config.RawConfig, _ string) error { + l := currentLanding() + if l == nil { + return nil + } + + front, err := resolveFrontGroup(cfg, l.FrontGroup) + if err != nil { + return err + } + + mapping, err := l.toMapping(front) + if err != nil { + return err + } + + allProxies := make([]string, 0, len(cfg.Proxy)) + for _, p := range cfg.Proxy { + name, _ := p["name"].(string) + if name == LandingProxyName { + return fmt.Errorf("landing proxy: profile already contains a proxy named `%s`", LandingProxyName) + } + allProxies = append(allProxies, name) + } + sort.Strings(allProxies) // same order mihomo uses for include-all + + for _, g := range cfg.ProxyGroup { + if groupName(g) == LandingProxyName { + return fmt.Errorf("landing proxy: profile already contains a group named `%s`", LandingProxyName) + } + + expandIncludeAllProxies(g, allProxies, len(cfg.ProxyProvider) > 0) + + if groupName(g) == front { + continue + } + + if members := toStringList(g["proxies"]); members != nil { + replaced := make([]string, 0, len(members)) + for _, m := range members { + if m == front { + m = LandingProxyName + } + replaced = append(replaced, m) + } + g["proxies"] = replaced + } + } + + for i, line := range cfg.Rule { + cfg.Rule[i] = retargetRule(line, front) + } + + for name, rules := range cfg.SubRules { + for i, line := range rules { + rules[i] = retargetRule(line, front) + } + cfg.SubRules[name] = rules + } + + cfg.Proxy = append(cfg.Proxy, mapping) + + log.Infoln("[APP] landing proxy %s://%s:%d via `%s`", strings.ToLower(l.Type), l.Server, l.Port, front) + + return nil +} + +// selectLandingInGlobal makes GLOBAL default to the landing proxy, so global +// mode also exits through it. A selection restored afterwards still wins. +func selectLandingInGlobal() { + if currentLanding() == nil { + return + } + + p := tunnel.Proxies()["GLOBAL"] + if p == nil { + return + } + + if s, ok := p.Adapter().(outboundgroup.SelectAble); ok { + if err := s.Set(LandingProxyName); err != nil { + log.Warnln("[APP] select landing proxy in GLOBAL: %s", err.Error()) + } + } +} diff --git a/core/src/main/golang/native/config/load.go b/core/src/main/golang/native/config/load.go index c6d19878c9..a7363f4cc4 100644 --- a/core/src/main/golang/native/config/load.go +++ b/core/src/main/golang/native/config/load.go @@ -10,6 +10,7 @@ import ( "github.com/metacubex/mihomo/common/yaml" "github.com/metacubex/mihomo/config" + "github.com/metacubex/mihomo/constant/provider" "github.com/metacubex/mihomo/hub" "github.com/metacubex/mihomo/log" ) @@ -58,7 +59,58 @@ func Parse(rawConfig *config.RawConfig) (*config.Config, error) { return cfg, nil } -func Load(path string) error { +// stripInbounds disables everything that accepts connections, so a profile can +// be loaded only to browse proxies and run health checks while the service is +// stopped. +func stripInbounds(cfg *config.RawConfig) { + cfg.Port = 0 + cfg.SocksPort = 0 + cfg.RedirPort = 0 + cfg.TProxyPort = 0 + cfg.MixedPort = 0 + cfg.ShadowSocksConfig = "" + cfg.VmessConfig = "" + cfg.Tunnels = nil + cfg.Listeners = nil + cfg.TuicServer.Enable = false + cfg.DNS.Listen = "" + cfg.ExternalController = "" + cfg.ExternalControllerTLS = "" + cfg.ExternalControllerUnix = "" + cfg.ExternalControllerPipe = "" + cfg.GeoAutoUpdate = false +} + +// disableProviderHealthCheck keeps proxy providers from testing latency on +// their own. +func disableProviderHealthCheck(cfg *config.RawConfig) { + for _, mapping := range cfg.ProxyProvider { + if healthCheck, ok := mapping["health-check"].(map[string]any); ok { + healthCheck["enable"] = false + } + } + + // providers without an interval inherit the one of a group using them + for _, group := range cfg.ProxyGroup { + delete(group, "interval") + } +} + +// skipGroupHealthCheck does the same for the proxies listed in groups, which +// the core always tests periodically. Initializing a compatible provider only +// starts that schedule. Groups keep their reference, so testing on request +// still works. +func skipGroupHealthCheck(cfg *config.Config) { + for name, p := range cfg.Providers { + if p.VehicleType() == provider.Compatible { + delete(cfg.Providers, name) + } + } +} + +// Load applies the profile at path to the core. A preview accepts no +// connections and only tests latency on request. +func Load(path string, preview bool) error { rawCfg, err := UnmarshalAndPatch(path) if err != nil { log.Errorln("Load %s: %s", path, err.Error()) @@ -66,6 +118,17 @@ func Load(path string) error { return err } + if err := patchLanding(rawCfg, path); err != nil { + log.Errorln("Load %s: %s", path, err.Error()) + + return err + } + + if preview { + stripInbounds(rawCfg) + disableProviderHealthCheck(rawCfg) + } + logDns(rawCfg) cfg, err := Parse(rawCfg) @@ -75,9 +138,15 @@ func Load(path string) error { return err } + if preview { + skipGroupHealthCheck(cfg) + } + // like hub.Parse() hub.ApplyConfig(cfg) + selectLandingInGlobal() + app.ApplySubtitlePattern(rawCfg.ClashForAndroid.UiSubtitlePattern) runtime.GC() diff --git a/core/src/main/java/com/github/kr328/clash/core/Clash.kt b/core/src/main/java/com/github/kr328/clash/core/Clash.kt index edba62bed0..4769d85cd1 100644 --- a/core/src/main/java/com/github/kr328/clash/core/Clash.kt +++ b/core/src/main/java/com/github/kr328/clash/core/Clash.kt @@ -165,12 +165,27 @@ object Clash { } } - fun load(path: File): CompletableDeferred { + /** + * Load the profile at [path]. + * + * With [preview] set, every inbound (ports, listeners, DNS listener, + * external controller) is stripped, so proxies can be browsed and + * health-checked while the service is stopped. + */ + fun load(path: File, preview: Boolean = false): CompletableDeferred { return CompletableDeferred().apply { - Bridge.nativeLoad(this, path.absolutePath) + Bridge.nativeLoad(this, path.absolutePath, preview) } } + /** + * Set the landing (exit) proxy applied by subsequent [load] calls, + * as JSON, or clear it with null. + */ + fun setLandingProxy(json: String?) { + Bridge.nativeSetLandingProxy(json)?.let { throw ClashException(it) } + } + fun queryProviders(): List { val providers = Json.Default.decodeFromString(JsonArray.serializer(), Bridge.nativeQueryProviders()) diff --git a/core/src/main/java/com/github/kr328/clash/core/bridge/Bridge.kt b/core/src/main/java/com/github/kr328/clash/core/bridge/Bridge.kt index fa3b9247ef..a786f0d4cd 100644 --- a/core/src/main/java/com/github/kr328/clash/core/bridge/Bridge.kt +++ b/core/src/main/java/com/github/kr328/clash/core/bridge/Bridge.kt @@ -35,7 +35,8 @@ object Bridge { force: Boolean ) - external fun nativeLoad(completable: CompletableDeferred, path: String) + external fun nativeLoad(completable: CompletableDeferred, path: String, preview: Boolean) + external fun nativeSetLandingProxy(content: String?): String? external fun nativeQueryProviders(): String external fun nativeUpdateProvider( completable: CompletableDeferred, diff --git a/design/src/main/java/com/github/kr328/clash/design/LandingProxySettingsDesign.kt b/design/src/main/java/com/github/kr328/clash/design/LandingProxySettingsDesign.kt new file mode 100644 index 0000000000..458bec6a0f --- /dev/null +++ b/design/src/main/java/com/github/kr328/clash/design/LandingProxySettingsDesign.kt @@ -0,0 +1,255 @@ +package com.github.kr328.clash.design + +import android.content.Context +import android.view.View +import com.github.kr328.clash.design.databinding.DesignSettingsCommonBinding +import com.github.kr328.clash.design.dialog.requestModelTextInput +import com.github.kr328.clash.design.preference.* +import com.github.kr328.clash.design.ui.ToastDuration +import com.github.kr328.clash.design.util.applyFrom +import com.github.kr328.clash.design.util.bindAppBarElevation +import com.github.kr328.clash.design.util.layoutInflater +import com.github.kr328.clash.design.util.root +import com.github.kr328.clash.service.model.LandingProxyType +import com.github.kr328.clash.service.store.ServiceStore +import com.google.android.material.dialog.MaterialAlertDialogBuilder +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.suspendCancellableCoroutine +import kotlinx.coroutines.withContext +import kotlin.coroutines.resume + +class LandingProxySettingsDesign( + context: Context, + private val srvStore: ServiceStore, +) : Design(context) { + enum class Request { + PickFrontGroup + } + + private val binding = DesignSettingsCommonBinding + .inflate(context.layoutInflater, context.root, false) + + override val root: View + get() = binding.root + + private lateinit var frontGroup: ClickablePreference + + /** + * Let the user pick the front group from [groups] (may be empty when the + * profile could not be loaded), "auto", or a custom name. + */ + suspend fun requestFrontGroup(groups: List) { + val current = withContext(Dispatchers.IO) { srvStore.landingFrontGroup } + + val items = buildList { + add(context.getString(R.string.landing_front_group_auto)) + addAll(groups) + add(context.getString(R.string.landing_front_group_custom)) + } + + val checked = when { + current.isEmpty() -> 0 + current in groups -> groups.indexOf(current) + 1 + else -> items.size - 1 + } + + val index = suspendCancellableCoroutine { ctx -> + val dialog = MaterialAlertDialogBuilder(context) + .setTitle(R.string.landing_front_group) + .setSingleChoiceItems(items.toTypedArray(), checked) { dialog, which -> + ctx.resume(which) + + dialog.dismiss() + } + .setNegativeButton(R.string.cancel) { _, _ -> } + .show() + + dialog.setOnDismissListener { + if (!ctx.isCompleted) + ctx.resume(null) + } + + ctx.invokeOnCancellation { + dialog.dismiss() + } + } ?: return + + val value = when (index) { + 0 -> "" + items.size - 1 -> context.requestModelTextInput( + initial = current, + title = context.getText(R.string.landing_front_group), + reset = null, + hint = context.getText(R.string.landing_front_group), + )?.trim() ?: return + else -> groups[index - 1] + } + + withContext(Dispatchers.IO) { + srvStore.landingFrontGroup = value + } + + updateFrontGroupSummary(value) + } + + private fun updateFrontGroupSummary(value: String) { + frontGroup.summary = value.ifEmpty { + context.getString(R.string.landing_front_group_auto) + } + } + + init { + binding.surface = surface + + binding.activityBarLayout.applyFrom(context) + + binding.scrollRoot.bindAppBarElevation(binding.activityBarLayout) + + val text = object : NullableTextAdapter { + override fun from(value: String): String = value + override fun to(text: String?): String = text?.trim() ?: "" + } + + val port = object : NullableTextAdapter { + override fun from(value: Int): String = if (value > 0) value.toString() else "" + override fun to(text: String?): Int = + text?.trim()?.toIntOrNull()?.takeIf { it in 1..65535 } ?: 0 + } + + val password = object : NullableTextAdapter { + override fun from(value: String): String = if (value.isEmpty()) "" else PASSWORD_MASK + override fun to(text: String?): String = when (text) { + null -> "" + PASSWORD_MASK -> srvStore.landingPassword // unchanged + else -> text + } + } + + val screen = preferenceScreen(context) { + val httpsOnly = mutableListOf() + val socks5Only = mutableListOf() + + fun applyType(type: LandingProxyType) { + httpsOnly.forEach { + it.view.visibility = + if (type == LandingProxyType.Https) View.VISIBLE else View.GONE + } + socks5Only.forEach { + it.view.visibility = + if (type == LandingProxyType.Socks5) View.VISIBLE else View.GONE + } + } + + switch( + value = srvStore::landingEnabled, + icon = R.drawable.ic_baseline_vpn_lock, + title = R.string.landing_proxy_enable, + ) { + listener = OnChangedListener { + launch(Dispatchers.Main) { + val incomplete = withContext(Dispatchers.IO) { + srvStore.landingEnabled && + (srvStore.landingServer.isBlank() || srvStore.landingPort <= 0) + } + + if (incomplete) { + showToast(R.string.landing_proxy_incomplete, ToastDuration.Long) + } + } + } + } + + frontGroup = clickable( + title = R.string.landing_front_group, + ) { + clicked { + requests.trySend(Request.PickFrontGroup) + } + } + + category(R.string.landing_server_category) + + selectableList( + value = srvStore::landingType, + values = LandingProxyType.values(), + valuesText = arrayOf( + R.string.landing_type_http, + R.string.landing_type_https, + R.string.landing_type_socks5, + ), + title = R.string.landing_type, + ) { + listener = OnChangedListener { + launch(Dispatchers.Main) { + applyType(withContext(Dispatchers.IO) { srvStore.landingType }) + } + } + } + + editableText( + value = srvStore::landingServer, + adapter = text, + title = R.string.landing_server, + empty = R.string.landing_not_set, + ) + + editableText( + value = srvStore::landingPort, + adapter = port, + title = R.string.landing_port, + empty = R.string.landing_not_set, + ) + + editableText( + value = srvStore::landingUsername, + adapter = text, + title = R.string.landing_username, + empty = R.string.landing_auth_none, + ) + + editableText( + value = srvStore::landingPassword, + adapter = password, + title = R.string.landing_password, + empty = R.string.landing_auth_none, + ) + + switch( + value = srvStore::landingSkipCertVerify, + title = R.string.landing_skip_cert_verify, + summary = R.string.landing_skip_cert_verify_summary, + configure = httpsOnly::add, + ) + + editableText( + value = srvStore::landingSni, + adapter = text, + title = R.string.landing_sni, + empty = R.string.landing_sni_default, + configure = httpsOnly::add, + ) + + switch( + value = srvStore::landingUdp, + title = R.string.landing_udp, + configure = socks5Only::add, + ) + + launch(Dispatchers.Main) { + val (type, group) = withContext(Dispatchers.IO) { + srvStore.landingType to srvStore.landingFrontGroup + } + + applyType(type) + updateFrontGroupSummary(group) + } + } + + binding.content.addView(screen.root) + } + + companion object { + private const val PASSWORD_MASK = "••••••••" + } +} diff --git a/design/src/main/java/com/github/kr328/clash/design/NetworkSettingsDesign.kt b/design/src/main/java/com/github/kr328/clash/design/NetworkSettingsDesign.kt index 93e1ee3d07..dab35b6cf5 100644 --- a/design/src/main/java/com/github/kr328/clash/design/NetworkSettingsDesign.kt +++ b/design/src/main/java/com/github/kr328/clash/design/NetworkSettingsDesign.kt @@ -11,6 +11,7 @@ import com.github.kr328.clash.design.util.applyFrom import com.github.kr328.clash.design.util.bindAppBarElevation import com.github.kr328.clash.design.util.layoutInflater import com.github.kr328.clash.design.util.root +import com.github.kr328.clash.service.StatusProvider import com.github.kr328.clash.service.model.AccessControlMode import com.github.kr328.clash.service.store.ServiceStore import kotlinx.coroutines.launch @@ -20,9 +21,11 @@ class NetworkSettingsDesign( uiStore: UiStore, srvStore: ServiceStore, running: Boolean, + vpnState: StatusProvider.VpnState?, ) : Design(context) { enum class Request { - StartAccessControlList + StartAccessControlList, + OpenSystemVpnSettings, } private val binding = DesignSettingsCommonBinding @@ -132,6 +135,32 @@ class NetworkSettingsDesign( } } + switch( + value = srvStore::killSwitch, + title = R.string.kill_switch, + summary = R.string.kill_switch_summary, + configure = vpnDependencies::add, + ) + + clickable( + title = R.string.always_on_vpn, + ) { + summary = when { + vpnState == null -> + null + vpnState.alwaysOn && vpnState.lockdown -> + context.getText(R.string.always_on_vpn_summary_lockdown) + vpnState.alwaysOn -> + context.getText(R.string.always_on_vpn_summary_no_lockdown) + else -> + context.getText(R.string.always_on_vpn_summary_off) + } + + clicked { + requests.trySend(Request.OpenSystemVpnSettings) + } + } + if (running) { vpn.enabled = false diff --git a/design/src/main/java/com/github/kr328/clash/design/ProxyDesign.kt b/design/src/main/java/com/github/kr328/clash/design/ProxyDesign.kt index 7dc7f413d7..701e94df16 100644 --- a/design/src/main/java/com/github/kr328/clash/design/ProxyDesign.kt +++ b/design/src/main/java/com/github/kr328/clash/design/ProxyDesign.kt @@ -83,6 +83,12 @@ class ProxyDesign( } } + suspend fun updateMode(mode: TunnelState.Mode?) { + withContext(Dispatchers.Main) { + menu.updateMode(mode) + } + } + suspend fun showModeSwitchTips() { withContext(Dispatchers.Main) { Toast.makeText(context, R.string.mode_switch_tips, Toast.LENGTH_LONG).show() diff --git a/design/src/main/java/com/github/kr328/clash/design/SettingsDesign.kt b/design/src/main/java/com/github/kr328/clash/design/SettingsDesign.kt index 0536a587cd..dbd4238c8a 100644 --- a/design/src/main/java/com/github/kr328/clash/design/SettingsDesign.kt +++ b/design/src/main/java/com/github/kr328/clash/design/SettingsDesign.kt @@ -10,7 +10,7 @@ import com.github.kr328.clash.design.util.root class SettingsDesign(context: Context) : Design(context) { enum class Request { - StartApp, StartNetwork, StartOverride, StartMetaFeature, + StartApp, StartNetwork, StartLandingProxy, StartOverride, StartMetaFeature, } private val binding = DesignSettingsBinding diff --git a/design/src/main/java/com/github/kr328/clash/design/component/ProxyMenu.kt b/design/src/main/java/com/github/kr328/clash/design/component/ProxyMenu.kt index 5d0672adad..fd2183b460 100644 --- a/design/src/main/java/com/github/kr328/clash/design/component/ProxyMenu.kt +++ b/design/src/main/java/com/github/kr328/clash/design/component/ProxyMenu.kt @@ -25,6 +25,18 @@ class ProxyMenu( menu.show() } + fun updateMode(mode: TunnelState.Mode?) { + val id = when (mode) { + null -> R.id.dont_modify + TunnelState.Mode.Direct -> R.id.direct_mode + TunnelState.Mode.Global -> R.id.global_mode + TunnelState.Mode.Rule -> R.id.rule_mode + else -> return + } + + menu.menu.findItem(id).isChecked = true + } + override fun onMenuItemClick(item: MenuItem): Boolean { item.isChecked = !item.isChecked @@ -105,16 +117,10 @@ class ProxyMenu( ProxySort.Title -> findItem(R.id.name).isChecked = true ProxySort.Delay -> findItem(R.id.delay).isChecked = true } - - when (mode) { - null -> findItem(R.id.dont_modify).isChecked = true - TunnelState.Mode.Direct -> findItem(R.id.direct_mode).isChecked = true - TunnelState.Mode.Global -> findItem(R.id.global_mode).isChecked = true - TunnelState.Mode.Rule -> findItem(R.id.rule_mode).isChecked = true - else -> {} - } } + updateMode(mode) + menu.setOnMenuItemClickListener(this) } } diff --git a/design/src/main/java/com/github/kr328/clash/design/view/LargeActionCard.kt b/design/src/main/java/com/github/kr328/clash/design/view/LargeActionCard.kt index 0b75496dc9..2f6c06b2c0 100644 --- a/design/src/main/java/com/github/kr328/clash/design/view/LargeActionCard.kt +++ b/design/src/main/java/com/github/kr328/clash/design/view/LargeActionCard.kt @@ -3,6 +3,7 @@ package com.github.kr328.clash.design.view import android.content.Context import android.graphics.drawable.Drawable import android.util.AttributeSet +import android.view.View import androidx.annotation.AttrRes import com.github.kr328.clash.design.R import com.github.kr328.clash.design.databinding.ComponentLargeActionLabelBinding @@ -27,6 +28,7 @@ class LargeActionCard @JvmOverloads constructor( get() = binding.subtextView.text set(value) { binding.subtextView.text = value + binding.subtextView.visibility = if (value == null) View.GONE else View.VISIBLE } var icon: Drawable? diff --git a/design/src/main/res/layout/design_main.xml b/design/src/main/res/layout/design_main.xml index a562970fa3..283fa53fcf 100644 --- a/design/src/main/res/layout/design_main.xml +++ b/design/src/main/res/layout/design_main.xml @@ -95,9 +95,9 @@ android:layout_height="wrap_content" android:layout_marginVertical="@dimen/main_card_margin_vertical" android:onClick="@{() -> self.request(Request.OpenProxy)}" - android:visibility="@{clashRunning ? View.VISIBLE : View.GONE}" + android:visibility="@{clashRunning || profileName != null ? View.VISIBLE : View.GONE}" app:icon="@drawable/ic_baseline_apps" - app:subtext="@{mode}" + app:subtext="@{clashRunning ? mode : null}" app:text="@string/proxy" /> + + 启动 Clash 服务 停止 Clash 停止 Clash 服务 + + Kill Switch + VPN 意外停止时阻断网络 + 始终开启的 VPN 与锁定模式 + 已开启 · 已屏蔽未使用 VPN 的连接 + 已开启 · 未屏蔽未使用 VPN 的连接 + 未开启 + + 落地代理 + 启用落地代理 + 请填写服务器和端口 + 服务器 + 协议 + HTTP + HTTPS + SOCKS5 + 服务器 + 端口 + 用户名 + 密码 + 未设置 + 无 + 前置组 + 自动 + 自定义… + 跳过证书验证 + 不安全,仅用于自签名证书 + SNI + 默认 + UDP 转发 diff --git a/design/src/main/res/values/strings.xml b/design/src/main/res/values/strings.xml index a2f951e679..734d9ba43c 100644 --- a/design/src/main/res/values/strings.xml +++ b/design/src/main/res/values/strings.xml @@ -373,4 +373,34 @@ Start Clash service Stop Clash Stop Clash service + + Kill Switch + Block network traffic if the VPN stops unexpectedly + Always-on VPN & lockdown + On · Connections without VPN blocked + On · Connections without VPN not blocked + Off + + Landing Proxy + Enable Landing Proxy + Enter the server and port + Server + Protocol + HTTP + HTTPS + SOCKS5 + Server + Port + Username + Password + Not set + None + Front Group + Auto + Custom… + Skip Certificate Verification + Insecure, only for self-signed certificates + SNI + Default + UDP Relay diff --git a/service/src/main/java/com/github/kr328/clash/service/ClashManager.kt b/service/src/main/java/com/github/kr328/clash/service/ClashManager.kt index aa92b4afe4..9868713116 100644 --- a/service/src/main/java/com/github/kr328/clash/service/ClashManager.kt +++ b/service/src/main/java/com/github/kr328/clash/service/ClashManager.kt @@ -4,12 +4,14 @@ import android.content.Context import com.github.kr328.clash.common.log.Log import com.github.kr328.clash.core.Clash import com.github.kr328.clash.core.model.* +import com.github.kr328.clash.service.clash.ClashPreview import com.github.kr328.clash.service.data.Selection import com.github.kr328.clash.service.data.SelectionDao import com.github.kr328.clash.service.remote.IClashManager import com.github.kr328.clash.service.remote.ILogObserver import com.github.kr328.clash.service.store.ServiceStore import com.github.kr328.clash.service.util.sendOverrideChanged +import com.github.kr328.clash.service.util.sendProfileLoaded import kotlinx.coroutines.* import kotlinx.coroutines.channels.ReceiveChannel @@ -62,6 +64,24 @@ class ClashManager(private val context: Context) : IClashManager, Clash.patchOverride(slot, configuration) context.sendOverrideChanged() + + launch { + if (ClashPreview.reloadIfLoaded(context)) { + store.activeProfile?.let(context::sendProfileLoaded) + } + } + } + + override suspend fun preparePreview(): String? { + return ClashPreview.prepare(context) + } + + override suspend fun reloadPreview(): String? { + return ClashPreview.prepare(context, hold = false) + } + + override fun releasePreview() { + ClashPreview.scheduleRelease() } override fun clearOverride(slot: Clash.OverrideSlot) { diff --git a/service/src/main/java/com/github/kr328/clash/service/StatusProvider.kt b/service/src/main/java/com/github/kr328/clash/service/StatusProvider.kt index bd3eb8a9ba..e9c3ab9573 100644 --- a/service/src/main/java/com/github/kr328/clash/service/StatusProvider.kt +++ b/service/src/main/java/com/github/kr328/clash/service/StatusProvider.kt @@ -11,13 +11,23 @@ class StatusProvider : ContentProvider() { override fun call(method: String, arg: String?, extras: Bundle?): Bundle? { return when (method) { METHOD_CURRENT_PROFILE -> { - return if (serviceRunning) + // while the kill switch blocks traffic, clash itself is not running + return if (serviceRunning && !killSwitchActive) Bundle().apply { putString("name", currentProfile) } else null } + METHOD_VPN_STATE -> { + val state = vpnState ?: return null + + return Bundle().apply { + putBoolean(KEY_ALWAYS_ON, state.alwaysOn) + putBoolean(KEY_LOCKDOWN, state.lockdown) + putBoolean(KEY_KILL_SWITCH_ACTIVE, killSwitchActive) + } + } else -> super.call(method, arg, extras) } } @@ -57,8 +67,23 @@ class StatusProvider : ContentProvider() { return true } + data class VpnState(val alwaysOn: Boolean, val lockdown: Boolean) + companion object { const val METHOD_CURRENT_PROFILE = "currentProfile" + const val METHOD_VPN_STATE = "vpnState" + + const val KEY_ALWAYS_ON = "alwaysOn" + const val KEY_LOCKDOWN = "lockdown" + const val KEY_KILL_SWITCH_ACTIVE = "killSwitchActive" + + /** Set while [TunService] holds a blocking interface after an unexpected stop. */ + @Volatile + var killSwitchActive: Boolean = false + + /** Always-on / lockdown state reported by a running [TunService] (API 29+). */ + @Volatile + var vpnState: VpnState? = null private const val CLASH_SERVICE_RUNNING_FILE = "service_running.lock" diff --git a/service/src/main/java/com/github/kr328/clash/service/TunService.kt b/service/src/main/java/com/github/kr328/clash/service/TunService.kt index 8550f8ab81..4e2dc532d2 100644 --- a/service/src/main/java/com/github/kr328/clash/service/TunService.kt +++ b/service/src/main/java/com/github/kr328/clash/service/TunService.kt @@ -2,12 +2,22 @@ package com.github.kr328.clash.service import android.annotation.TargetApi import android.app.PendingIntent +import android.content.BroadcastReceiver +import android.content.Context import android.content.Intent +import android.content.IntentFilter import android.net.ProxyInfo import android.net.VpnService import android.os.Build +import android.os.ParcelFileDescriptor +import androidx.core.app.NotificationCompat +import com.github.kr328.clash.common.compat.getColorCompat import com.github.kr328.clash.common.compat.pendingIntentFlags +import com.github.kr328.clash.common.compat.registerReceiverCompat +import com.github.kr328.clash.common.compat.startForegroundCompat import com.github.kr328.clash.common.constants.Components +import com.github.kr328.clash.common.constants.Intents +import com.github.kr328.clash.common.constants.Permissions import com.github.kr328.clash.common.log.Log import com.github.kr328.clash.service.clash.clashRuntime import com.github.kr328.clash.service.clash.module.* @@ -18,6 +28,7 @@ import com.github.kr328.clash.service.util.parseCIDR import com.github.kr328.clash.service.util.sendClashStarted import com.github.kr328.clash.service.util.sendClashStopped import kotlinx.coroutines.* +import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.selects.select class TunService : VpnService(), CoroutineScope by CoroutineScope(Dispatchers.Default) { @@ -26,6 +37,14 @@ class TunService : VpnService(), CoroutineScope by CoroutineScope(Dispatchers.De private var reason: String? = null + // kill switch state + @Volatile private var userRequestedStop = false + @Volatile private var revoked = false + @Volatile private var destroying = false + private var blockingInterface: ParcelFileDescriptor? = null + private var killSwitchJob: Job? = null + private var killSwitchReceiver: BroadcastReceiver? = null + private val runtime = clashRuntime { val store = ServiceStore(self) @@ -46,9 +65,16 @@ class TunService : VpnService(), CoroutineScope by CoroutineScope(Dispatchers.De try { tun.open() + // the real interface replaced the blocking one (if any) + releaseBlockingInterface() + + reportVpnState() + while (isActive) { val quit = select { close.onEvent { + userRequestedStop = true + true } config.onEvent { @@ -73,13 +99,176 @@ class TunService : VpnService(), CoroutineScope by CoroutineScope(Dispatchers.De reason = e.message } finally { withContext(NonCancellable) { + // Engage before closing the core's interface, so the blocking + // interface replaces it without a gap. + val blocked = shouldEngageKillSwitch() && engageKillSwitch() + tun.close() - stopSelf() + if (!blocked) + stopSelf() + } + } + } + + private fun shouldEngageKillSwitch(): Boolean { + return ServiceStore(self).killSwitch && !userRequestedStop && !revoked && !destroying + } + + /** + * Hold a VPN interface that routes the same traffic as the real one but + * never reads from it, so packets are dropped instead of leaking out of + * the physical network after an unexpected stop. + */ + private fun engageKillSwitch(): Boolean { + val store = ServiceStore(self) + + val fd = try { + with(Builder()) { + addAddress(TUN_GATEWAY, TUN_SUBNET_PREFIX) + addAddress(TUN_GATEWAY6, TUN_SUBNET_PREFIX6) + + // Block IPv6 too, even if not proxied, so it cannot leak. + applyRoutes(store, ipv6 = true) + applyAccessControl(store) + + addDnsServer(TUN_DNS) + setMtu(TUN_MTU) + setBlocking(false) + setSession("Clash") + setConfigureIntent(mainActivityIntent()) + + if (Build.VERSION.SDK_INT >= 29) { + setMetered(false) + } + + establish() + } + } catch (e: Exception) { + Log.w("Kill switch: establish blocking interface: ${e.message}", e) + + null + } ?: return false + + synchronized(this) { + blockingInterface?.close() + blockingInterface = fd + } + + StatusProvider.killSwitchActive = true + + Log.w("Kill switch engaged: ${reason ?: "unknown reason"}") + + notifyKillSwitch() + + killSwitchJob = launch { + val stop = Channel(Channel.CONFLATED) + val receiver = object : BroadcastReceiver() { + override fun onReceive(context: Context?, intent: Intent?) { + stop.trySend(Unit) + } } + + registerReceiverCompat( + receiver, + IntentFilter(Intents.ACTION_CLASH_REQUEST_STOP), + Permissions.RECEIVE_SELF_BROADCASTS, + null + ) + killSwitchReceiver = receiver + + // Wait for the runtime to wind down: a notification module may still + // post once, and the core is reset only after it ends. + delay(1000) + notifyKillSwitch() + + // let the UI show stopped, with the failure reason + sendClashStopped(reason) + + stop.receive() + + Log.i("Kill switch released by user") + + userRequestedStop = true + reason = null // already reported when the kill switch engaged + + stopSelf() + } + + return true + } + + private fun releaseBlockingInterface() { + synchronized(this) { + blockingInterface?.close() + blockingInterface = null + } + + StatusProvider.killSwitchActive = false + } + + private fun cancelKillSwitchJob() { + killSwitchJob?.cancel() + killSwitchJob = null + + killSwitchReceiver?.let { + runCatching { unregisterReceiver(it) } + } + killSwitchReceiver = null + } + + private fun notifyKillSwitch() { + val content = reason?.let { getString(R.string.kill_switch_active_content, it) } + ?: getString(R.string.kill_switch_active_content_unknown) + + val stop = PendingIntent.getBroadcast( + self, + R.id.nf_vpn_status, + Intent(Intents.ACTION_CLASH_REQUEST_STOP).setPackage(packageName), + pendingIntentFlags(PendingIntent.FLAG_UPDATE_CURRENT) + ) + + val notification = NotificationCompat.Builder(self, StaticNotificationModule.CHANNEL_ID) + .setSmallIcon(R.drawable.ic_logo_service) + .setOngoing(true) + .setColor(getColorCompat(R.color.color_clash)) + .setOnlyAlertOnce(true) + .setShowWhen(false) + .setForegroundServiceBehavior(NotificationCompat.FOREGROUND_SERVICE_IMMEDIATE) + .setContentTitle(getText(R.string.kill_switch_active)) + .setContentText(content) + .setStyle(NotificationCompat.BigTextStyle().bigText(content)) + .setContentIntent(mainActivityIntent()) + .addAction(0, getText(R.string.kill_switch_stop), stop) + .build() + + startForegroundCompat(R.id.nf_clash_status, notification) + } + + private fun reportVpnState() { + StatusProvider.vpnState = if (Build.VERSION.SDK_INT >= 29) { + StatusProvider.VpnState(alwaysOn = isAlwaysOn, lockdown = isLockdownEnabled) + } else { + null } } + private fun mainActivityIntent(): PendingIntent { + return PendingIntent.getActivity( + self, + R.id.nf_vpn_status, + Intent().setComponent(Components.MAIN_ACTIVITY), + pendingIntentFlags(PendingIntent.FLAG_UPDATE_CURRENT) + ) + } + + override fun onRevoke() { + // another VPN took over or the user revoked us, never block in that case + revoked = true + + super.onRevoke() + } + override fun onCreate() { super.onCreate() @@ -95,12 +284,34 @@ class TunService : VpnService(), CoroutineScope by CoroutineScope(Dispatchers.De } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + if (killSwitchJob != null) { + // Started again while blocking: retry. The blocking interface stays + // up until the runtime has established the real one. + Log.i("Kill switch: restarting clash runtime") + + cancelKillSwitchJob() + + reason = null + userRequestedStop = false + + StaticNotificationModule.notifyLoadingNotification(this) + + runtime.launch() + } + sendClashStarted() return super.onStartCommand(intent, flags, startId) } override fun onDestroy() { + destroying = true + + cancelKillSwitchJob() + releaseBlockingInterface() + + StatusProvider.vpnState = null + TunModule.requestStop() StatusProvider.serviceRunning = false @@ -131,42 +342,10 @@ class TunService : VpnService(), CoroutineScope by CoroutineScope(Dispatchers.De } // Route - if (store.bypassPrivateNetwork) { - resources.getStringArray(R.array.bypass_private_route).map(::parseCIDR).forEach { - addRoute(it.ip, it.prefix) - } - if (store.allowIpv6) { - resources.getStringArray(R.array.bypass_private_route6).map(::parseCIDR).forEach { - addRoute(it.ip, it.prefix) - } - } - - // Route of virtual DNS - addRoute(TUN_DNS, 32) - if (store.allowIpv6) { - addRoute(TUN_DNS6, 128) - } - } else { - addRoute(NET_ANY, 0) - if (store.allowIpv6) { - addRoute(NET_ANY6, 0) - } - } + applyRoutes(store, ipv6 = store.allowIpv6) // Access Control - when (store.accessControlMode) { - AccessControlMode.AcceptAll -> Unit - AccessControlMode.AcceptSelected -> { - (store.accessControlPackages + packageName).forEach { - runCatching { addAllowedApplication(it) } - } - } - AccessControlMode.DenySelected -> { - (store.accessControlPackages - packageName).forEach { - runCatching { addDisallowedApplication(it) } - } - } - } + applyAccessControl(store) // Blocking setBlocking(false) @@ -184,14 +363,7 @@ class TunService : VpnService(), CoroutineScope by CoroutineScope(Dispatchers.De } // Open MainActivity - setConfigureIntent( - PendingIntent.getActivity( - self, - R.id.nf_vpn_status, - Intent().setComponent(Components.MAIN_ACTIVITY), - pendingIntentFlags(PendingIntent.FLAG_UPDATE_CURRENT) - ) - ) + setConfigureIntent(mainActivityIntent()) // Metered if (Build.VERSION.SDK_INT >= 29) { @@ -228,6 +400,46 @@ class TunService : VpnService(), CoroutineScope by CoroutineScope(Dispatchers.De attach(device) } + private fun Builder.applyRoutes(store: ServiceStore, ipv6: Boolean) { + if (store.bypassPrivateNetwork) { + resources.getStringArray(R.array.bypass_private_route).map(::parseCIDR).forEach { + addRoute(it.ip, it.prefix) + } + if (ipv6) { + resources.getStringArray(R.array.bypass_private_route6).map(::parseCIDR).forEach { + addRoute(it.ip, it.prefix) + } + } + + // Route of virtual DNS + addRoute(TUN_DNS, 32) + if (ipv6) { + addRoute(TUN_DNS6, 128) + } + } else { + addRoute(NET_ANY, 0) + if (ipv6) { + addRoute(NET_ANY6, 0) + } + } + } + + private fun Builder.applyAccessControl(store: ServiceStore) { + when (store.accessControlMode) { + AccessControlMode.AcceptAll -> Unit + AccessControlMode.AcceptSelected -> { + (store.accessControlPackages + packageName).forEach { + runCatching { addAllowedApplication(it) } + } + } + AccessControlMode.DenySelected -> { + (store.accessControlPackages - packageName).forEach { + runCatching { addDisallowedApplication(it) } + } + } + } + } + companion object { private const val TUN_MTU = 9000 private const val TUN_SUBNET_PREFIX = 30 diff --git a/service/src/main/java/com/github/kr328/clash/service/clash/ClashPreview.kt b/service/src/main/java/com/github/kr328/clash/service/clash/ClashPreview.kt new file mode 100644 index 0000000000..ff304710cd --- /dev/null +++ b/service/src/main/java/com/github/kr328/clash/service/clash/ClashPreview.kt @@ -0,0 +1,176 @@ +package com.github.kr328.clash.service.clash + +import android.content.Context +import com.github.kr328.clash.common.log.Log +import com.github.kr328.clash.core.Clash +import com.github.kr328.clash.service.StatusProvider +import com.github.kr328.clash.service.data.ImportedDao +import com.github.kr328.clash.service.data.SelectionDao +import com.github.kr328.clash.service.store.ServiceStore +import com.github.kr328.clash.service.util.importedDir +import kotlinx.coroutines.* + +/** + * Loads the active profile into the core while the service is stopped, so the + * proxy list can be browsed and health-checked without starting the VPN. + * + * Preview loads strip every inbound (see `stripInbounds` in the core), and + * share [globalLock] with [clashRuntime]: while a runtime is active it owns the + * core and preview requests are no-ops. + */ +object ClashPreview { + private const val RELEASE_DELAY = 60_000L + private const val LOCK_TIMEOUT = 5_000L + + private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob()) + + private var loadedKey: String? = null + private var releaseJob: Job? = null + private var holders = 0 + + /** Called by the runtime once it owns the core. Caller holds [globalLock]. */ + internal fun invalidate() { + releaseJob?.cancel() + releaseJob = null + loadedKey = null + holders = 0 + } + + /** + * Ensure the core has the active profile loaded. + * + * Each successful call with [hold] must be balanced by [scheduleRelease]. + * + * @return null on success (or when a runtime already owns the core), + * otherwise the reason the profile could not be loaded. + */ + suspend fun prepare(context: Context, hold: Boolean = true): String? { + val runtimeActive = StatusProvider.serviceRunning && !StatusProvider.killSwitchActive + + if (runtimeActive) { + if (!globalLock.tryLock()) + return null // runtime is active and owns the core + } else { + // A runtime that just stopped may still be resetting the core. + withTimeoutOrNull(LOCK_TIMEOUT) { globalLock.lock() } + ?: return null + } + + try { + if (hold) { + releaseJob?.cancel() + releaseJob = null + } + + val store = ServiceStore(context) + val uuid = store.activeProfile + ?: return "No profile selected" + val active = ImportedDao().queryByUUID(uuid) + ?: return "No profile selected" + val dir = context.importedDir.resolve(active.uuid.toString()) + val landing = store.landingProxyJson() + + val key = listOf( + uuid.toString(), + dir.resolve("config.yaml").lastModified().toString(), + active.ageSecretKey.orEmpty(), + landing.orEmpty(), + Clash.queryOverride(Clash.OverrideSlot.Persist).toString(), + Clash.queryOverride(Clash.OverrideSlot.Session).toString(), + ).joinToString("\u0000") + + if (key == loadedKey) { + if (hold) holders += 1 + + return null + } + + loadedKey = null + + Clash.reset() + Clash.setAgeSecretKey(active.ageSecretKey?.takeIf { it.isNotBlank() }) + Clash.setLandingProxy(landing) + Clash.load(dir, preview = true).await() + + val remove = SelectionDao().querySelections(active.uuid) + .filterNot { Clash.patchSelector(it.proxy, it.selected) } + .map { it.proxy } + + SelectionDao().removeSelections(active.uuid, remove) + + loadedKey = key + + if (hold) holders += 1 + + Log.d("Preview of ${active.name} loaded") + + return null + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + Log.w("Load preview: ${e.message}", e) + + // nothing is loaded anymore, outstanding releases become no-ops + loadedKey = null + holders = 0 + Clash.reset() + + return e.message ?: "Unknown" + } finally { + globalLock.unlock() + } + } + + /** Reload the preview if one is loaded, e.g. after an override change. */ + suspend fun reloadIfLoaded(context: Context): Boolean { + if (loadedKey == null) + return false + + return prepare(context, hold = false) == null && loadedKey != null + } + + /** + * Drop one holder. Once none are left the preview is released after a + * grace period, so reopening the proxy page shortly afterwards keeps the + * loaded profile and its delay results. + */ + fun scheduleRelease() { + scope.launch { + if (!globalLock.tryLock()) + return@launch // runtime owns the core, nothing to release + + try { + if (loadedKey == null) + return@launch + + holders = (holders - 1).coerceAtLeast(0) + + if (holders > 0) + return@launch + + releaseJob?.cancel() + releaseJob = scope.launch { + delay(RELEASE_DELAY) + + if (!globalLock.tryLock()) + return@launch // runtime owns the core now + + try { + if (loadedKey != null && holders == 0) { + loadedKey = null + releaseJob = null + + Clash.reset() + + Log.d("Preview released") + } + } finally { + globalLock.unlock() + } + } + } finally { + globalLock.unlock() + } + } + } +} diff --git a/service/src/main/java/com/github/kr328/clash/service/clash/ClashRuntime.kt b/service/src/main/java/com/github/kr328/clash/service/clash/ClashRuntime.kt index 8c61275de0..c355bbf545 100644 --- a/service/src/main/java/com/github/kr328/clash/service/clash/ClashRuntime.kt +++ b/service/src/main/java/com/github/kr328/clash/service/clash/ClashRuntime.kt @@ -7,7 +7,7 @@ import kotlinx.coroutines.* import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock -private val globalLock = Mutex() +internal val globalLock = Mutex() interface ClashRuntimeScope { fun > install(module: T): T @@ -25,6 +25,9 @@ fun CoroutineScope.clashRuntime(block: suspend ClashRuntimeScope.() -> Unit): Cl globalLock.withLock { Log.d("ClashRuntime: initialize") + // the runtime takes over the core, drop any preview state + ClashPreview.invalidate() + try { val modules = mutableListOf>() diff --git a/service/src/main/java/com/github/kr328/clash/service/clash/module/ConfigurationModule.kt b/service/src/main/java/com/github/kr328/clash/service/clash/module/ConfigurationModule.kt index 7de311aaa9..b8be5cafe9 100644 --- a/service/src/main/java/com/github/kr328/clash/service/clash/module/ConfigurationModule.kt +++ b/service/src/main/java/com/github/kr328/clash/service/clash/module/ConfigurationModule.kt @@ -57,6 +57,8 @@ class ConfigurationModule(service: Service) : Module front group's selected node -> landing proxy -> target. + * + * Serialized as the JSON consumed by the core (`native/config/landing.go`). + */ +@Serializable +data class LandingProxy( + @SerialName("type") val type: String, + @SerialName("server") val server: String, + @SerialName("port") val port: Int, + @SerialName("username") val username: String = "", + @SerialName("password") val password: String = "", + @SerialName("frontGroup") val frontGroup: String = "", + @SerialName("skipCertVerify") val skipCertVerify: Boolean = false, + @SerialName("sni") val sni: String = "", + @SerialName("udp") val udp: Boolean = false, +) diff --git a/service/src/main/java/com/github/kr328/clash/service/remote/IClashManager.kt b/service/src/main/java/com/github/kr328/clash/service/remote/IClashManager.kt index f60c2edb17..77786a01e7 100644 --- a/service/src/main/java/com/github/kr328/clash/service/remote/IClashManager.kt +++ b/service/src/main/java/com/github/kr328/clash/service/remote/IClashManager.kt @@ -23,4 +23,23 @@ interface IClashManager { fun clearOverride(slot: Clash.OverrideSlot) fun setLogObserver(observer: ILogObserver?) + + /** + * Load the active profile without starting the service, so proxies can be + * browsed and tested. No-op while the service is running. + * + * @return null on success, otherwise the failure reason. + */ + suspend fun preparePreview(): String? + + /** + * Load the preview again after the service stopped, for a page already + * showing it. Needs no extra [releasePreview]. + * + * @return null on success, otherwise the failure reason. + */ + suspend fun reloadPreview(): String? + + /** Release the preview loaded by [preparePreview] after a grace period. */ + fun releasePreview() } \ No newline at end of file diff --git a/service/src/main/java/com/github/kr328/clash/service/store/ServiceStore.kt b/service/src/main/java/com/github/kr328/clash/service/store/ServiceStore.kt index 17734d4ce6..f865c4483a 100644 --- a/service/src/main/java/com/github/kr328/clash/service/store/ServiceStore.kt +++ b/service/src/main/java/com/github/kr328/clash/service/store/ServiceStore.kt @@ -5,6 +5,9 @@ import com.github.kr328.clash.common.store.Store import com.github.kr328.clash.common.store.asStoreProvider import com.github.kr328.clash.service.PreferenceProvider import com.github.kr328.clash.service.model.AccessControlMode +import com.github.kr328.clash.service.model.LandingProxy +import com.github.kr328.clash.service.model.LandingProxyType +import kotlinx.serialization.json.Json import java.util.* class ServiceStore(context: Context) { @@ -65,4 +68,84 @@ class ServiceStore(context: Context) { key = "dynamic_notification", defaultValue = true ) + + var killSwitch by store.boolean( + key = "kill_switch", + defaultValue = false + ) + + var landingEnabled by store.boolean( + key = "landing_enabled", + defaultValue = false + ) + + var landingType: LandingProxyType by store.enum( + key = "landing_type", + defaultValue = LandingProxyType.Socks5, + values = LandingProxyType.values() + ) + + var landingServer by store.string( + key = "landing_server", + defaultValue = "" + ) + + var landingPort by store.int( + key = "landing_port", + defaultValue = 0 + ) + + var landingUsername by store.string( + key = "landing_username", + defaultValue = "" + ) + + var landingPassword by store.string( + key = "landing_password", + defaultValue = "" + ) + + var landingFrontGroup by store.string( + key = "landing_front_group", + defaultValue = "" + ) + + var landingSkipCertVerify by store.boolean( + key = "landing_skip_cert_verify", + defaultValue = false + ) + + var landingSni by store.string( + key = "landing_sni", + defaultValue = "" + ) + + var landingUdp by store.boolean( + key = "landing_udp", + defaultValue = true + ) + + /** + * The landing proxy as JSON for [com.github.kr328.clash.core.Clash.setLandingProxy], + * or null when disabled. + */ + fun landingProxyJson(): String? { + if (!landingEnabled) + return null + + return Json.encodeToString( + LandingProxy.serializer(), + LandingProxy( + type = landingType.wireName, + server = landingServer.trim(), + port = landingPort, + username = landingUsername, + password = landingPassword, + frontGroup = landingFrontGroup, + skipCertVerify = landingSkipCertVerify, + sni = landingSni.trim(), + udp = landingUdp, + ) + ) + } } \ No newline at end of file diff --git a/service/src/main/res/values-zh/strings.xml b/service/src/main/res/values-zh/strings.xml index 77b87e9c16..4b41bb47ea 100644 --- a/service/src/main/res/values-zh/strings.xml +++ b/service/src/main/res/values-zh/strings.xml @@ -16,4 +16,8 @@ 配置更新中 配置文件服务状态 配置文件处理结果 + Kill Switch 已生效 + 网络已阻断:%s + 网络已阻断 + 停止 \ No newline at end of file diff --git a/service/src/main/res/values/strings.xml b/service/src/main/res/values/strings.xml index 903b825a84..93d379a815 100644 --- a/service/src/main/res/values/strings.xml +++ b/service/src/main/res/values/strings.xml @@ -18,4 +18,8 @@ Provider Files Profile Updater Profile Updating + Kill switch active + Network blocked: %s + Network blocked + Stop