Repository: chen08209/FlClash Branch: main Commit: 672eaccd35dc Files: 437 Total size: 13.4 MB Directory structure: gitextract__scuca8o/ ├── .github/ │ ├── ISSUE_TEMPLATE/ │ │ ├── bug_report.yml │ │ ├── config.yml │ │ └── feature_request.yml │ ├── release_template.md │ └── workflows/ │ └── build.yaml ├── .gitignore ├── .gitmodules ├── .metadata ├── .run/ │ └── main.dart.run.xml ├── CHANGELOG.md ├── LICENSE ├── README.md ├── README_zh_CN.md ├── analysis_options.yaml ├── android/ │ ├── .gitignore │ ├── app/ │ │ ├── build.gradle.kts │ │ ├── google-services.json │ │ ├── proguard-rules.pro │ │ └── src/ │ │ ├── debug/ │ │ │ └── AndroidManifest.xml │ │ ├── main/ │ │ │ ├── AndroidManifest.xml │ │ │ ├── kotlin/ │ │ │ │ └── com/ │ │ │ │ └── follow/ │ │ │ │ └── clash/ │ │ │ │ ├── Application.kt │ │ │ │ ├── BroadcastReceiver.kt │ │ │ │ ├── Ext.kt │ │ │ │ ├── MainActivity.kt │ │ │ │ ├── Service.kt │ │ │ │ ├── State.kt │ │ │ │ ├── TempActivity.kt │ │ │ │ ├── TileService.kt │ │ │ │ ├── models/ │ │ │ │ │ ├── Package.kt │ │ │ │ │ └── State.kt │ │ │ │ └── plugins/ │ │ │ │ ├── AppPlugin.kt │ │ │ │ ├── ServicePlugin.kt │ │ │ │ └── TilePlugin.kt │ │ │ └── res/ │ │ │ ├── drawable/ │ │ │ │ └── ic_launcher_foreground.xml │ │ │ ├── mipmap-anydpi-v26/ │ │ │ │ ├── ic_launcher.xml │ │ │ │ └── ic_launcher_round.xml │ │ │ ├── values/ │ │ │ │ ├── ic_launcher_background.xml │ │ │ │ └── styles.xml │ │ │ ├── values-night/ │ │ │ │ └── styles.xml │ │ │ ├── values-night-v27/ │ │ │ │ └── styles.xml │ │ │ ├── values-v27/ │ │ │ │ └── styles.xml │ │ │ └── xml/ │ │ │ ├── file_paths.xml │ │ │ └── network_security_config.xml │ │ └── profile/ │ │ └── AndroidManifest.xml │ ├── build.gradle.kts │ ├── common/ │ │ ├── .gitignore │ │ ├── build.gradle.kts │ │ └── src/ │ │ └── main/ │ │ ├── AndroidManifest.xml │ │ ├── java/ │ │ │ └── com/ │ │ │ └── follow/ │ │ │ └── clash/ │ │ │ └── common/ │ │ │ ├── Components.kt │ │ │ ├── Enums.kt │ │ │ ├── Ext.kt │ │ │ ├── GlobalState.kt │ │ │ ├── Service.kt │ │ │ └── Utils.kt │ │ └── res/ │ │ └── values/ │ │ └── strings.xml │ ├── core/ │ │ ├── .gitignore │ │ ├── build.gradle.kts │ │ └── src/ │ │ └── main/ │ │ ├── AndroidManifest.xml │ │ ├── cpp/ │ │ │ ├── CMakeLists.txt │ │ │ ├── core.cpp │ │ │ ├── jni_helper.cpp │ │ │ └── jni_helper.h │ │ └── java/ │ │ └── com/ │ │ └── follow/ │ │ └── clash/ │ │ └── core/ │ │ ├── Core.kt │ │ ├── InvokeInterface.kt │ │ └── TunInterface.kt │ ├── gradle/ │ │ ├── libs.versions.toml │ │ └── wrapper/ │ │ └── gradle-wrapper.properties │ ├── gradle.properties │ ├── service/ │ │ ├── .gitignore │ │ ├── build.gradle.kts │ │ └── src/ │ │ └── main/ │ │ ├── AndroidManifest.xml │ │ ├── aidl/ │ │ │ └── com/ │ │ │ └── follow/ │ │ │ └── clash/ │ │ │ └── service/ │ │ │ ├── IAckInterface.aidl │ │ │ ├── ICallbackInterface.aidl │ │ │ ├── IEventInterface.aidl │ │ │ ├── IRemoteInterface.aidl │ │ │ ├── IResultInterface.aidl │ │ │ ├── IVoidInterface.aidl │ │ │ └── models/ │ │ │ ├── AccessControl.aidl │ │ │ ├── NotificationParams.aidl │ │ │ └── VpnOptions.aidl │ │ ├── java/ │ │ │ └── com/ │ │ │ └── follow/ │ │ │ └── clash/ │ │ │ └── service/ │ │ │ ├── CommonService.kt │ │ │ ├── FilesProvider.kt │ │ │ ├── IBaseService.kt │ │ │ ├── RemoteService.kt │ │ │ ├── State.kt │ │ │ ├── VpnService.kt │ │ │ ├── models/ │ │ │ │ ├── NotificationParams.kt │ │ │ │ ├── Traffic.kt │ │ │ │ └── VpnOptions.kt │ │ │ └── modules/ │ │ │ ├── Module.kt │ │ │ ├── ModuleLoader.kt │ │ │ ├── NetworkObserveModule.kt │ │ │ ├── NotificationModule.kt │ │ │ └── SuspendModule.kt │ │ └── res/ │ │ └── drawable/ │ │ ├── ic.xml │ │ └── ic_service.xml │ └── settings.gradle.kts ├── arb/ │ ├── intl_en.arb │ ├── intl_ja.arb │ ├── intl_ru.arb │ └── intl_zh_CN.arb ├── assets/ │ └── data/ │ ├── ASN.mmdb │ └── GEOIP.metadb ├── build.yaml ├── core/ │ ├── action.go │ ├── bride.c │ ├── bride.go │ ├── bride.h │ ├── common.go │ ├── constant.go │ ├── go.mod │ ├── go.sum │ ├── hub.go │ ├── lib.go │ ├── main.go │ ├── main_cgo.go │ ├── platform/ │ │ ├── limit.go │ │ └── procfs.go │ ├── server.go │ └── tun/ │ └── tun.go ├── distribute_options.yaml ├── lib/ │ ├── application.dart │ ├── common/ │ │ ├── app_localizations.dart │ │ ├── archive.dart │ │ ├── cache.dart │ │ ├── color.dart │ │ ├── common.dart │ │ ├── compute.dart │ │ ├── constant.dart │ │ ├── context.dart │ │ ├── converter.dart │ │ ├── datetime.dart │ │ ├── dav_client.dart │ │ ├── file.dart │ │ ├── fixed.dart │ │ ├── function.dart │ │ ├── future.dart │ │ ├── hive.dart │ │ ├── http.dart │ │ ├── icons.dart │ │ ├── indexing.dart │ │ ├── iterable.dart │ │ ├── keyboard.dart │ │ ├── launch.dart │ │ ├── link.dart │ │ ├── lock.dart │ │ ├── measure.dart │ │ ├── migration.dart │ │ ├── mixin.dart │ │ ├── navigation.dart │ │ ├── navigator.dart │ │ ├── network.dart │ │ ├── num.dart │ │ ├── package.dart │ │ ├── path.dart │ │ ├── picker.dart │ │ ├── preferences.dart │ │ ├── print.dart │ │ ├── protocol.dart │ │ ├── proxy.dart │ │ ├── render.dart │ │ ├── request.dart │ │ ├── scroll.dart │ │ ├── snowflake.dart │ │ ├── store.dart │ │ ├── string.dart │ │ ├── system.dart │ │ ├── task.dart │ │ ├── text.dart │ │ ├── theme.dart │ │ ├── tray.dart │ │ ├── utils.dart │ │ ├── window.dart │ │ └── yaml.dart │ ├── controller.dart │ ├── core/ │ │ ├── controller.dart │ │ ├── core.dart │ │ ├── event.dart │ │ ├── interface.dart │ │ ├── lib.dart │ │ └── service.dart │ ├── database/ │ │ ├── database.dart │ │ ├── generated/ │ │ │ └── database.g.dart │ │ ├── links.dart │ │ ├── profiles.dart │ │ ├── rules.dart │ │ └── scripts.dart │ ├── enum/ │ │ └── enum.dart │ ├── features/ │ │ ├── features.dart │ │ └── overwrite/ │ │ ├── overwrite.dart │ │ └── rule.dart │ ├── l10n/ │ │ ├── intl/ │ │ │ ├── messages_all.dart │ │ │ ├── messages_en.dart │ │ │ ├── messages_ja.dart │ │ │ ├── messages_ru.dart │ │ │ └── messages_zh_CN.dart │ │ └── l10n.dart │ ├── main.dart │ ├── manager/ │ │ ├── android_manager.dart │ │ ├── app_manager.dart │ │ ├── connectivity_manager.dart │ │ ├── core_manager.dart │ │ ├── hotkey_manager.dart │ │ ├── manager.dart │ │ ├── proxy_manager.dart │ │ ├── status_manager.dart │ │ ├── theme_manager.dart │ │ ├── tile_manager.dart │ │ ├── tray_manager.dart │ │ ├── vpn_manager.dart │ │ └── window_manager.dart │ ├── models/ │ │ ├── app.dart │ │ ├── clash_config.dart │ │ ├── common.dart │ │ ├── config.dart │ │ ├── core.dart │ │ ├── generated/ │ │ │ ├── app.freezed.dart │ │ │ ├── clash_config.freezed.dart │ │ │ ├── clash_config.g.dart │ │ │ ├── common.freezed.dart │ │ │ ├── common.g.dart │ │ │ ├── config.freezed.dart │ │ │ ├── config.g.dart │ │ │ ├── core.freezed.dart │ │ │ ├── core.g.dart │ │ │ ├── profile.freezed.dart │ │ │ ├── profile.g.dart │ │ │ ├── state.freezed.dart │ │ │ └── state.g.dart │ │ ├── models.dart │ │ ├── profile.dart │ │ └── state.dart │ ├── pages/ │ │ ├── editor.dart │ │ ├── error.dart │ │ ├── home.dart │ │ ├── pages.dart │ │ └── scan.dart │ ├── plugins/ │ │ ├── app.dart │ │ ├── service.dart │ │ └── tile.dart │ ├── providers/ │ │ ├── app.dart │ │ ├── config.dart │ │ ├── database.dart │ │ ├── generated/ │ │ │ ├── app.g.dart │ │ │ ├── config.g.dart │ │ │ ├── database.g.dart │ │ │ └── state.g.dart │ │ ├── providers.dart │ │ └── state.dart │ ├── state.dart │ ├── views/ │ │ ├── about.dart │ │ ├── access.dart │ │ ├── application_setting.dart │ │ ├── backup_and_restore.dart │ │ ├── config/ │ │ │ ├── advanced.dart │ │ │ ├── config.dart │ │ │ ├── dns.dart │ │ │ ├── general.dart │ │ │ ├── network.dart │ │ │ ├── rules.dart │ │ │ └── scripts.dart │ │ ├── connection/ │ │ │ ├── connections.dart │ │ │ ├── item.dart │ │ │ └── requests.dart │ │ ├── dashboard/ │ │ │ ├── dashboard.dart │ │ │ └── widgets/ │ │ │ ├── intranet_ip.dart │ │ │ ├── memory_info.dart │ │ │ ├── network_detection.dart │ │ │ ├── network_speed.dart │ │ │ ├── outbound_mode.dart │ │ │ ├── quick_options.dart │ │ │ ├── start_button.dart │ │ │ ├── traffic_usage.dart │ │ │ └── widgets.dart │ │ ├── developer.dart │ │ ├── hotkey.dart │ │ ├── logs.dart │ │ ├── profiles/ │ │ │ ├── add.dart │ │ │ ├── edit.dart │ │ │ ├── overwrite.dart │ │ │ └── profiles.dart │ │ ├── proxies/ │ │ │ ├── card.dart │ │ │ ├── common.dart │ │ │ ├── list.dart │ │ │ ├── providers.dart │ │ │ ├── proxies.dart │ │ │ ├── setting.dart │ │ │ └── tab.dart │ │ ├── resources.dart │ │ ├── theme.dart │ │ ├── tools.dart │ │ └── views.dart │ └── widgets/ │ ├── activate_box.dart │ ├── animate_grid.dart │ ├── animated_cross_slide.dart │ ├── bar_chart.dart │ ├── builder.dart │ ├── button.dart │ ├── card.dart │ ├── chip.dart │ ├── color_scheme_box.dart │ ├── container.dart │ ├── dialog.dart │ ├── disabled_mask.dart │ ├── donut_chart.dart │ ├── effect.dart │ ├── fade_box.dart │ ├── float_layout.dart │ ├── grid.dart │ ├── icon.dart │ ├── inherited.dart │ ├── input.dart │ ├── keep_scope.dart │ ├── line_chart.dart │ ├── list.dart │ ├── loading.dart │ ├── notification.dart │ ├── null_status.dart │ ├── open_container.dart │ ├── palette.dart │ ├── pop_scope.dart │ ├── popup.dart │ ├── scaffold.dart │ ├── scroll.dart │ ├── setting.dart │ ├── sheet.dart │ ├── side_sheet.dart │ ├── subscription_info_view.dart │ ├── super_grid.dart │ ├── tab.dart │ ├── text.dart │ ├── theme.dart │ ├── view.dart │ ├── wave.dart │ └── widgets.dart ├── linux/ │ ├── .gitignore │ ├── CMakeLists.txt │ ├── flutter/ │ │ ├── CMakeLists.txt │ │ ├── generated_plugin_registrant.cc │ │ ├── generated_plugin_registrant.h │ │ └── generated_plugins.cmake │ ├── packaging/ │ │ ├── appimage/ │ │ │ └── make_config.yaml │ │ ├── deb/ │ │ │ └── make_config.yaml │ │ └── rpm/ │ │ └── make_config.yaml │ └── runner/ │ ├── CMakeLists.txt │ ├── main.cc │ ├── my_application.cc │ └── my_application.h ├── macos/ │ ├── .gitignore │ ├── Flutter/ │ │ ├── Flutter-Debug.xcconfig │ │ ├── Flutter-Release.xcconfig │ │ └── GeneratedPluginRegistrant.swift │ ├── Podfile │ ├── Runner/ │ │ ├── AppDelegate.swift │ │ ├── Assets.xcassets/ │ │ │ ├── AppIcon.appiconset/ │ │ │ │ └── Contents.json │ │ │ └── Contents.json │ │ ├── Base.lproj/ │ │ │ └── MainMenu.xib │ │ ├── Configs/ │ │ │ ├── AppInfo.xcconfig │ │ │ ├── Debug.xcconfig │ │ │ ├── Release.xcconfig │ │ │ └── Warnings.xcconfig │ │ ├── DebugProfile.entitlements │ │ ├── Info.plist │ │ ├── MainFlutterWindow.swift │ │ └── Release.entitlements │ ├── Runner.xcodeproj/ │ │ ├── project.pbxproj │ │ ├── project.xcworkspace/ │ │ │ └── xcshareddata/ │ │ │ └── IDEWorkspaceChecks.plist │ │ └── xcshareddata/ │ │ └── xcschemes/ │ │ └── Runner.xcscheme │ ├── Runner.xcworkspace/ │ │ ├── contents.xcworkspacedata │ │ └── xcshareddata/ │ │ └── IDEWorkspaceChecks.plist │ ├── RunnerTests/ │ │ └── RunnerTests.swift │ └── packaging/ │ └── dmg/ │ └── make_config.yaml ├── plugins/ │ ├── proxy/ │ │ ├── .gitignore │ │ ├── .metadata │ │ ├── CHANGELOG.md │ │ ├── LICENSE │ │ ├── README.md │ │ ├── analysis_options.yaml │ │ ├── lib/ │ │ │ ├── proxy.dart │ │ │ ├── proxy_method_channel.dart │ │ │ └── proxy_platform_interface.dart │ │ ├── pubspec.yaml │ │ └── windows/ │ │ ├── .gitignore │ │ ├── CMakeLists.txt │ │ ├── include/ │ │ │ └── proxy/ │ │ │ └── proxy_plugin_c_api.h │ │ ├── proxy_plugin.cpp │ │ ├── proxy_plugin.h │ │ ├── proxy_plugin_c_api.cpp │ │ └── test/ │ │ └── proxy_plugin_test.cpp │ └── window_ext/ │ ├── .gitignore │ ├── .metadata │ ├── CHANGELOG.md │ ├── LICENSE │ ├── README.md │ ├── analysis_options.yaml │ ├── lib/ │ │ ├── window_ext.dart │ │ ├── window_ext_listener.dart │ │ └── window_ext_manager.dart │ ├── macos/ │ │ ├── Classes/ │ │ │ └── WindowExtPlugin.swift │ │ └── window_ext.podspec │ ├── pubspec.yaml │ └── windows/ │ ├── .gitignore │ ├── CMakeLists.txt │ ├── include/ │ │ └── window_ext/ │ │ └── window_ext_plugin_c_api.h │ ├── test/ │ │ └── window_ext_plugin_test.cpp │ ├── window_ext_plugin.cpp │ ├── window_ext_plugin.h │ └── window_ext_plugin_c_api.cpp ├── pubspec.yaml ├── release_telegram.py ├── services/ │ └── helper/ │ ├── Cargo.toml │ ├── build.rs │ └── src/ │ ├── main.rs │ └── service/ │ ├── hub.rs │ ├── mod.rs │ └── windows.rs ├── setup.dart └── windows/ ├── .gitignore ├── CMakeLists.txt ├── flutter/ │ ├── CMakeLists.txt │ ├── generated_plugin_registrant.cc │ ├── generated_plugin_registrant.h │ └── generated_plugins.cmake ├── packaging/ │ └── exe/ │ ├── ChineseSimplified.isl │ ├── inno_setup.iss │ └── make_config.yaml └── runner/ ├── CMakeLists.txt ├── Runner.rc ├── flutter_window.cpp ├── flutter_window.h ├── main.cpp ├── resource.h ├── runner.exe.manifest ├── utils.cpp ├── utils.h ├── win32_window.cpp └── win32_window.h ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/ISSUE_TEMPLATE/bug_report.yml ================================================ name: 问题反馈 / Bug report title: "[BUG] " description: 反馈你遇到的问题 / Report the issue you are experiencing body: - type: markdown attributes: value: | ## 在提交问题之前,请确认以下事项: 1. 请务必给issue填写一个简洁明了的标题,以便他人快速检索 2. 请确保[已有的问题](https://github.com/chen08209/FlClash/issues?q=is%3Aissue) 中没有人提交过相似issue,否则请在已有的issue下进行讨论 3. 请务必按照模板规范详细描述问题,否则issue将会被直接关闭 ## Before submitting the issue, please make sure of the following checklist: 1. Please be sure to fill in a concise and clear title for the issue so that others can quickly search 2. Please make sure there is no similar issue in the [existing issues](https://github.com/chen08209/FlClash/issues?q=is%3Aissue), otherwise please discuss under the existing issue 3. Please describe the problem in detail according to the template specification, otherwise issue will be closed directly. - type: textarea id: description attributes: label: 问题描述 / Describe the bug description: 详细清晰地描述你遇到的问题,并配合截图 / Describe the problem you encountered in detail and clearly, and provide screenshots validations: required: true - type: textarea attributes: label: 软件版本 / Version description: 请提供FlClash的具体版本 / Please provide the specific version of FlClash. validations: required: true - type: textarea attributes: label: 复现步骤 / To Reproduce description: 请提供复现问题的步骤 / Steps to reproduce the behavior validations: required: true - type: dropdown attributes: label: 操作系统 / OS options: - Android - Windows - MacOS - Linux validations: required: true - type: input attributes: label: 操作系统版本 / OS Version description: 请提供你的操作系统版本,Linux请额外提供桌面环境及窗口系统 / Please provide your OS version, for Linux, please also provide the desktop environment and window system validations: required: true - type: textarea attributes: label: 日志(勿上传日志文件,请粘贴日志内容) / Log (Do not upload the log file, paste the log content directly) description: 请提供完整或相关部分的Debug日志(请在“软件左侧菜单”->“设置”->“日志等级”调整到debug / Please provide a complete or relevant Debug log (please adjust it to debug in the left menu of software-> Settings-> Log Level) validations: required: true ================================================ FILE: .github/ISSUE_TEMPLATE/config.yml ================================================ contact_links: - name: 讨论交流 / Communication url: https://t.me/+G-veVtwBOl4wODc1 about: 在 Telegram 群组中与其他用户讨论交流 / Communicate with other users in the Telegram group ================================================ FILE: .github/ISSUE_TEMPLATE/feature_request.yml ================================================ name: 功能请求 / Feature request title: "[Feature] " description: 提出你的功能请求 / Propose your feature request body: - type: markdown attributes: value: | ## 在提交问题之前,请确认以下事项: 1. 请务必给issue填写一个简洁明了的标题,以便他人快速检索 2. 请确保[已有的问题](https://github.com/chen08209/FlClash/issues?q=is%3Aissue) 中没有人提交过相似issue,否则请在已有的issue下进行讨论 3. 请务必按照模板规范详细描述问题,否则issue将会被直接关闭 ## Before submitting the issue, please make sure of the following checklist: 1. Please be sure to fill in a concise and clear title for the issue so that others can quickly search 2. Please make sure there is no similar issue in the [existing issues](https://github.com/chen08209/FlClash/issues?q=is%3Aissue), otherwise please discuss under the existing issue 3. Please describe the problem in detail according to the template specification, otherwise issue will be closed directly. - type: textarea id: description attributes: label: 功能描述 / Feature description description: 详细清晰地描述你的功能请求 / A clear and concise description of what the feature is validations: required: true - type: textarea attributes: label: 使用场景 / Use case description: 请描述你的功能请求的使用场景 / Please describe the use case of your feature request validations: required: true - type: checkboxes id: os-labels attributes: label: 适用系统 / Target OS description: 请选择该功能适用的操作系统(至少选择一个) / Please select the operating system(s) for this feature request (select at least one) options: - label: Android - label: Windows - label: MacOS - label: Linux validations: required: true ================================================ FILE: .github/release_template.md ================================================
[![Release Downloads](https://img.shields.io/github/downloads/chen08209/FlClash/vVERSION/total?style=flat-square&logo=github)](https://img.shields.io/github/downloads/chen08209/FlClash/vVERSION/)
**Download based on your OS:**
OS Download
Android

Windows
macOS

Linux

**List of all changes:** [ChangeLog](https://github.com/chen08209/FlClash/blob/main/CHANGELOG.md)
================================================ FILE: .github/workflows/build.yaml ================================================ name: build on: push: tags: - 'v*' env: IS_STABLE: ${{ !contains(github.ref, '-') }} jobs: build: runs-on: ${{ matrix.os }} strategy: matrix: include: - platform: android os: ubuntu-latest - platform: windows os: Windows-2022 arch: amd64 - platform: linux os: ubuntu-22.04 arch: amd64 - platform: macos os: macos-15-intel arch: amd64 - platform: macos os: macos-latest arch: arm64 # - platform: windows # os: windows-11-arm # arch: arm64 - platform: linux os: ubuntu-24.04-arm arch: arm64 steps: - name: Setup rust if: startsWith(matrix.os, 'windows-11-arm') run: | Invoke-WebRequest -Uri "https://win.rustup.rs/aarch64" -OutFile rustup-init.exe .\rustup-init.exe -y --default-toolchain stable $cargoPath = "$env:USERPROFILE\.cargo\bin" Add-Content $env:GITHUB_PATH $cargoPath - name: Checkout uses: actions/checkout@v4 with: submodules: recursive - name: Setup Android Signing if: startsWith(matrix.platform,'android') run: | echo "${{ secrets.KEYSTORE }}" | base64 --decode > android/app/keystore.jks echo "${{ secrets.SERVICE_JSON }}" | base64 --decode > android/app/google-services.json echo "keyAlias=${{ secrets.KEY_ALIAS }}" >> android/local.properties echo "storePassword=${{ secrets.STORE_PASSWORD }}" >> android/local.properties echo "keyPassword=${{ secrets.KEY_PASSWORD }}" >> android/local.properties - name: Setup Go uses: actions/setup-go@v5 with: go-version: '1.24.0' cache-dependency-path: | core/go.sum - name: Setup Flutter if: ${{ !(startsWith(matrix.os, 'windows-11-arm') || startsWith(matrix.os, 'ubuntu-24.04-arm')) }} uses: subosito/flutter-action@v2 with: channel: stable flutter-version: 3.35.7 cache: true - name: Setup Flutter With Other if: startsWith(matrix.os, 'windows-11-arm') || startsWith(matrix.os, 'ubuntu-24.04-arm') uses: subosito/flutter-action@v2 with: channel: master flutter-version: 3.35.7 cache: true - name: Get Flutter Dependency run: | flutter --version flutter pub get - name: Setup run: dart setup.dart ${{ matrix.platform }} ${{ matrix.arch && format('--arch {0}', matrix.arch) }} ${{ env.IS_STABLE == 'true' && '--env stable' || '' }} - name: Upload uses: actions/upload-artifact@v4 with: name: artifact-${{ matrix.platform }}${{ matrix.arch && format('-{0}', matrix.arch) }} path: ./dist overwrite: true changelog: runs-on: ubuntu-latest needs: [ build ] steps: - name: Checkout uses: actions/checkout@v4 if: ${{ env.IS_STABLE == 'true' }} with: fetch-depth: 0 ref: refs/heads/main - name: Generate if: ${{ env.IS_STABLE == 'true' }} run: | last_ver=$(grep -m1 '^## ' CHANGELOG.md 2>/dev/null | sed 's/^## //') tags=($(git tag --merged HEAD --sort=-creatordate)) temp="NEW_CHANGELOG.md" > "$temp" for i in "${!tags[@]}"; do curr="${tags[i]}" [[ "$curr" == "$last_ver" ]] && break prev="${tags[i+1]}" range="${prev:+$prev..}$curr" echo -e "## $curr\n" >> "$temp" git log --no-merges --pretty=format:"%B" "$range" | \ awk '!/Update changelog/ && NF {print "- " $0 "\n"}' >> "$temp" done [ -f CHANGELOG.md ] && cat CHANGELOG.md >> "$temp" mv "$temp" CHANGELOG.md - name: Commit if: ${{ env.IS_STABLE == 'true' }} run: | git add CHANGELOG.md if ! git diff --cached --quiet; then echo "Commit pushing" git config --local user.email "chen08209@gmail.com" git config --local user.name "chen08209" git commit -m "Update changelog" git push if [ $? -eq 0 ]; then echo "Push succeeded" else echo "Push failed" exit 1 fi fi env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} upload: permissions: write-all needs: [ build ] runs-on: ubuntu-latest services: telegram-bot-api: image: aiogram/telegram-bot-api:latest env: TELEGRAM_API_ID: ${{ secrets.TELEGRAM_API_ID }} TELEGRAM_API_HASH: ${{ secrets.TELEGRAM_API_HASH }} ports: - 8081:8081 steps: - name: Checkout uses: actions/checkout@v4 with: fetch-depth: 0 - name: Download uses: actions/download-artifact@v4 with: path: ./dist/ pattern: artifact-* merge-multiple: true - name: Generate release.md run: | tags=($(git tag --merged HEAD --sort=-creatordate)) preTag=$(curl -s "https://api.github.com/repos/chen08209/FlClash/releases/latest" | \ sed -nE 's/.*"tag_name": "([^"]+)".*/\1/p') [ -z "$preTag" ] && preTag="" out="release.md" > "$out" for i in "${!tags[@]}"; do curr="${tags[i]}" [[ "$curr" == "$preTag" ]] && break prev="${tags[i+1]}" range="${prev:+$prev..}$curr" git log --no-merges --pretty=format:"%B" "$range" | \ awk '!/Update changelog/ && NF {print "- " $0 "\n"}' >> "$out" done - name: Push to telegram env: TELEGRAM_BOT_TOKEN: ${{ secrets.TELEGRAM_BOT_TOKEN }} TAG: ${{ github.ref_name }} RUN_ID: ${{ github.run_id }} run: | python -m pip install --upgrade pip pip install requests python release_telegram.py - name: Patch release.md run: | version=$(echo "${{ github.ref_name }}" | sed 's/^v//') sed "s|VERSION|$version|g" ./.github/release_template.md >> release.md - name: Generate sha256 if: env.IS_STABLE == 'true' run: | cd ./dist for file in $(find . -type f -not -name "*.sha256"); do sha256sum "$file" > "${file}.sha256" done - name: Release if: ${{ env.IS_STABLE == 'true' }} uses: softprops/action-gh-release@v2 with: files: ./dist/* body_path: './release.md' - name: Create Fdroid Source Dir if: ${{ env.IS_STABLE == 'true' }} run: | mkdir -p ./tmp cp ./dist/*android-arm64-v8a* ./tmp/ || true echo "Files copied successfully" - name: Push to fdroid repo if: ${{ env.IS_STABLE == 'true' }} uses: cpina/github-action-push-to-another-repository@v1.7.2 env: SSH_DEPLOY_KEY: ${{ secrets.SSH_DEPLOY_KEY }} with: source-directory: ./tmp/ destination-github-username: chen08209 destination-repository-name: FlClash-fdroid-repo user-name: 'github-actions[bot]' user-email: 'github-actions[bot]@users.noreply.github.com' target-branch: main commit-message: Update from ${{ github.ref_name }} target-directory: /tmp/ ================================================ FILE: .gitignore ================================================ # Miscellaneous *.class *.log *.pyc *.swp .DS_Store .atom/ .build/ .buildlog/ .history .svn/ .swiftpm/ migrate_working_dir/ # IntelliJ related *.iml *.ipr *.iws .idea/ # The .vscode folder contains launch configuration and tasks you configure in # VS Code which you may wish to be included in version control, so this line # is commented out by default. .vscode/ # Flutter/Dart/Pub related **/doc/api/ **/ios/Flutter/.last_build_id .dart_tool/ .flutter-plugins .flutter-plugins-dependencies .packages .pub-cache/ .pub/ /build/ /dist/ # Symbolication related app.*.symbols # Obfuscation related app.*.map.json #AI generated CLAUDE.md /.claude # Android Studio will place build artifacts here /android/app/debug /android/app/profile /android/app/release /android/**/.cxx /android/**/build /android/common/**/.**/ /android/common/local.* /android/core/**/includes/ /android/core/**/cmake-build-*/ /android/core/**/jniLibs/ #FlClash /libclash/ /android/app/src/main/jniLibs/ /services/helper/target /macos/**/Package.resolved devtools_options.yaml # FVM Version Cache .fvm/ .fvmrc ================================================ FILE: .gitmodules ================================================ [submodule "core/Clash.Meta"] path = core/Clash.Meta url = git@github.com:chen08209/Clash.Meta.git branch = FlClash [submodule "plugins/flutter_distributor"] path = plugins/flutter_distributor url = git@github.com:chen08209/flutter_distributor.git branch = FlClash [submodule "plugins/tray_manager"] path = plugins/tray_manager url = git@github.com:chen08209/tray_manager.git branch = main ================================================ FILE: .metadata ================================================ # This file tracks properties of this Flutter project. # Used by Flutter tool to assess capabilities and perform upgrades etc. # # This file should be version controlled and should not be manually edited. version: revision: "adc901062556672b4138e18a4dc62a4be8f4b3c2" channel: "stable" project_type: app # Tracks metadata for the flutter migrate command migration: platforms: - platform: root create_revision: adc901062556672b4138e18a4dc62a4be8f4b3c2 base_revision: adc901062556672b4138e18a4dc62a4be8f4b3c2 - platform: windows create_revision: adc901062556672b4138e18a4dc62a4be8f4b3c2 base_revision: adc901062556672b4138e18a4dc62a4be8f4b3c2 # User provided section # List of Local paths (relative to this file) that should be # ignored by the migrate tool. # # Files that are not part of the templates will be ignored by default. unmanaged_files: - 'lib/main.dart' - 'ios/Runner.xcodeproj/project.pbxproj' ================================================ FILE: .run/main.dart.run.xml ================================================ ================================================ FILE: CHANGELOG.md ================================================ ## v0.8.92 - Add sqlite store - Optimize android quick action - Optimize backup and restore - Optimize more details ## v0.8.91 - Fix windows some issues - Optimize overwrite handle - Optimize access control page - Optimize some details ## v0.8.90 - Fix android tile service - Support append system DNS - Fix some issues - Update changelog ## v0.8.89 - Fix some issues - Optimize Windows service mode - Update core - Update changelog ## v0.8.88 - Add android separates the core process - Support core status check and force restart - Optimize proxies page and access page - Update flutter and pub dependencies - Update go version - Optimize more details - Update changelog ## v0.8.87 - Optimize desktop view - Optimize logs, requests, connection pages - Optimize windows tray auto hide - Optimize some details - Update core - Update changelog ## v0.8.86 - Fix windows tun issues - Optimize android get system dns - Optimize more details - Update changelog ## v0.8.85 - Support override script - Support proxies search - Support svg display - Optimize config persistence - Add some scenes auto close connections - Update core - Optimize more details ## v0.8.84 - Fix windows service verify issues - Update changelog ## v0.8.83 - Add windows server mode start process verify - Add linux deb dependencies - Add backup recovery strategy select - Support custom text scaling - Optimize the display of different text scale - Optimize windows setup experience - Optimize startTun performance - Optimize android tv experience - Optimize default option - Optimize computed text size - Optimize hyperOS freeform window - Add developer mode - Update core - Optimize more details - Add issues template - Update changelog ## v0.8.82 - Optimize android vpn performance - Add custom primary color and color scheme - Add linux nad windows arm release - Optimize requests and logs page - Fix map input page delete issues - Update changelog ## v0.8.81 - Add rule override - Update core - Optimize more details - Update changelog ## v0.8.80 - Optimize dashboard performance - Fix some issues - Fix unselected proxy group delay issues - Fix asn url issues - Update changelog ## v0.8.79 - Fix tab delay view issues - Fix tray action issues - Fix get profile redirect client ua issues - Fix proxy card delay view issues - Add Russian, Japanese adaptation - Fix some issues - Update changelog ## v0.8.78 - Fix list form input view issues - Fix traffic view issues - Update changelog ## v0.8.77 - Optimize performance - Update core - Optimize core stability - Fix linux tun authority check error - Fix some issues - Fix scroll physics error - Update changelog ## v0.8.75 - Add windows storage corruption detection - Fix core crash caused by windows resource manager restart - Optimize logs, requests, access to pages - Fix macos bypass domain issues - Update changelog ## v0.8.74 - Fix some issues - Update changelog ## v0.8.73 - Update popup menu - Add file editor - Fix android service issues - Optimize desktop background performance - Optimize android main process performance - Optimize delay test - Optimize vpn protect - Update changelog ## v0.8.72 - Update core - Fix some issues - Update changelog ## v0.8.71 - Remake dashboard - Optimize theme - Optimize more details - Update flutter version - Update changelog ## v0.8.70 - Support better window position memory - Add windows arm64 and linux arm64 build script - Optimize some details ## v0.8.69 - Remake desktop - Optimize change proxy - Optimize network check - Fix fallback issues - Optimize lots of details - Update change.yaml - Fix android tile issues - Fix windows tray issues - Support setting bypassDomain - Update flutter version - Fix android service issues - Fix macos dock exit button issues - Add route address setting - Optimize provider view - Update changelog - Update CHANGELOG.md ## v0.8.67 - Add android shortcuts - Fix init params issues - Fix dynamic color issues - Optimize navigator animate - Optimize window init - Optimize fab - Optimize save ## v0.8.66 - Fix the collapse issues - Add fontFamily options ## v0.8.65 - Update core version - Update flutter version - Optimize ip check - Optimize url-test ## v0.8.64 - Update release message - Init auto gen changelog - Fix windows tray issues - Fix urltest issues - Add auto changelog - Fix windows admin auto launch issues - Add android vpn options - Support proxies icon configuration - Optimize android immersion display - Fix some issues - Optimize ip detection - Support android vpn ipv6 inbound switch - Support log export - Optimize more details - Fix android system dns issues - Optimize dns default option - Fix some issues - Update readme ## v0.8.60 - Fix build error2 - Fix build error - Support desktop hotkey - Support android ipv6 inbound - Support android system dns - fix some bugs ## v0.8.59 - Fix delete profile error ## v0.8.58 - Fix submit error 2 - Fix submit error - Optimize DNS strategy - Fix the problem that the tray is not displayed in some cases - Optimize tray - Update core - Fix some error ## v0.8.57 - Fix tun update issues - Add DNS override - Fixed some bugs - Optimize more detail - Add Hosts override ## v0.8.56 - fix android tip error - fix windows auto launch error ## v0.8.55 - Fix windows tray issues - Optimize windows logic - Optimize app logic - Support windows administrator auto launch - Support android close vpn ## v0.8.53 - Change flutter version - Support profiles sort - Support windows country flags display - Optimize proxies page and profiles page columns ## v0.8.52 - Update flutter version - Update version - Update timeout time - Update access control page - Fix bug ## v0.8.51 - Optimize provider page - Optimize delay test - Support local backup and recovery - Fix android tile service issues ## v0.8.49 - Fix linux core build error - Add proxy-only traffic statistics - Update core - Optimize more details - Merge pull request #140 from txyyh/main - 添加自建 F-Droid 仓库相关 workflow - Rename readme fingerprint - Rename workflow deploy repo name - Add download guide to README - Add push release files to fdroid-repo ## v0.8.48 - Optimize proxies page - Fix ua issues - Optimize more details ## v0.8.47 - Fix windows build error ## v0.8.46 - Update app icon - Fix desktop backup error - Optimize request ua - Change android icon - Optimize dashboard ## v0.8.44 - Remove request validate certificate - Sync core ## v0.8.43 - Fix windows error ## v0.8.42 - Fix setup.dart error - Fix android system proxy not effective - Add macos arm64 ## v0.8.41 - Optimize proxies page - Support mouse drag scroll - Adjust desktop ui - Revert "Fix android vpn issues" - This reverts commit 891977408e6938e2acd74e9b9adb959c48c79988. ## v0.8.40 - Fix android vpn issues - Fix android vpn issues - Rollback partial modification ## v0.8.39 - Fix the problem that ui can't be synchronized when android vpn is occupied by an external - Override default socksPort,port ## v0.8.38 - Fix fab issues ## v0.8.37 - Update version - Fix the problem that vpn cannot be started in some cases - Fix the problem that geodata url does not take effect ## v0.8.36 - Update ua - Fix change outbound mode without check ip issues - Separate android ui and vpn - Fix url validate issues 2 - Add android hidden from the recent task - Add geoip file - Support modify geoData URL ## v0.8.35 - Fix url validate issues - Fix check ip performance problem - Optimize resources page ## v0.8.34 - Add ua selector - Support modify test url - Optimize android proxy - Fix the error that async proxy provider could not selected the proxy ## v0.8.33 - Fix android proxy error - Fix submit error - Add windows tun - Optimize android proxy - Optimize change profile - Update application ua - Optimize delay test ## v0.8.32 - Fix android repeated request notification issues ## v0.8.31 - Fix memory overflow issues ## v0.8.30 - Optimize proxies expansion panel 2 - Fix android scan qrcode error ## v0.8.29 - Optimize proxies expansion panel - Fix text error ## v0.8.28 - Optimize proxy - Optimize delayed sorting performance - Add expansion panel proxies page - Support to adjust the proxy card size - Support to adjust proxies columns number - Fix autoRun show issues - Fix Android 10 issues - Optimize ip show ## v0.8.26 - Add intranet IP display - Add connections page - Add search in connections, requests - Add keyword search in connections, requests, logs - Add basic viewing editing capabilities - Optimize update profile ## v0.8.25 - Update version - Fix the problem of excessive memory usage in traffic usage. - Add lightBlue theme color - Fix start unable to update profile issues - Fix flashback caused by process ## v0.8.23 - Add build version - Optimize quick start - Update system default option ## v0.8.22 - Update build.yml - Fix android vpn close issues - Add requests page - Fix checkUpdate dark mode style error - Fix quickStart error open app - Add memory proxies tab index - Support hidden group - Optimize logs - Fix externalController hot load error ## v0.8.21 - Add tcp concurrent switch - Add system proxy switch - Add geodata loader switch - Add external controller switch - Add auto gc on trim memory - Fix android notification error ## v0.8.20 - Fix ipv6 error - Fix android udp direct error - Add ipv6 switch - Add access all selected button - Remove android low version splash ## v0.8.19 - Update version - Add allowBypass - Fix Android only pick .text file issues ## v0.8.18 - Fix search issues ## v0.8.17 - Fix LoadBalance, Relay load error - Fix build.yml4 - Fix build.yml3 - Fix build.yml2 - Fix build.yml - Add search function at access control - Fix the issues with the profile add button to cover the edit button - Adapt LoadBalance and Relay - Add arm - Fix android notification icon error ## v0.8.16 - Add one-click update all profiles - Add expire show ## v0.8.15 - Temp remove tun mode - Remove macos in workflow - Change go version ## v0.8.14 - Update Version - Fix tun unable to open ## v0.8.13 - Optimize delay test2 - Optimize delay test - Add check ip - add check ip request ## v0.8.12 - Fix the problem that the download of remote resources failed after GeodataMode was turned on, which caused the application to flash back. - Fix edit profile error - Fix quickStart change proxy error - Fix core version ## v0.8.10 - Fix core version ## v0.8.9 - Update file_picker - Add resources page - Optimize more detail - Add access selected sorted - Fix notification duplicate creation issue - Fix AccessControl click issue ## v0.8.7 - Fix Workflow - Fix Linux unable to open - Update README.md 3 - Create LICENSE - Update README.md 2 - Update README.md - Optimize workFlow ## v0.8.6 - optimize checkUpdate ## v0.8.5 - Fix submit error ## v0.8.4 - add WebDAV - add Auto check updates - Optimize more details - optimize delayTest ## v0.8.2 - upgrade flutter version ## v0.8.1 - Update kernel - Add import profile via QR code image ## v0.8.0 - Add compatibility mode and adapt clash scheme. ## v0.7.14 - update Version - Reconstruction application proxy logic ## v0.7.13 - Fix Tab destroy error ## v0.7.12 - Optimize repeat healthcheck ## v0.7.11 - Optimize Direct mode ui ## v0.7.10 - Optimize Healthcheck - Remove proxies position animation, improve performance - Add Telegram Link - Update healthcheck policy - New Check URLTest - Fix the problem of invalid auto-selection ## v0.7.8 - New Async UpdateConfig - add changeProfileDebounce - Update Workflow - Fix ChangeProfile block - Fix Release Message Error ## v0.7.7 - Update Selector 2 ## v0.7.6 - Update Version - Fix Proxies Select Error ## v0.7.5 - Fix the problem that the proxy group is empty in global mode. - Fix the problem that the proxy group is empty in global mode. ## v0.7.4 - Add ProxyProvider2 ## v0.7.3 - Add ProxyProvider - Update Version - Update ProxyGroup Sort - Fix Android quickStart VpnService some problems ## v0.7.1 - Update version - Set Android notification low importance - Fix the issue that VpnService can't be closed correctly in special cases - Fix the problem that TileService is not destroyed correctly in some cases - Adjust tab animation defaults - Add Telegram in README_zh_CN.md - Add Telegram ## v0.7.0 - update mobile_scanner - Initial commit ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: README.md ================================================
[**简体中文**](README_zh_CN.md)
## FlClash [![Downloads](https://img.shields.io/github/downloads/chen08209/FlClash/total?style=flat-square&logo=github)](https://github.com/chen08209/FlClash/releases/)[![Last Version](https://img.shields.io/github/release/chen08209/FlClash/all.svg?style=flat-square)](https://github.com/chen08209/FlClash/releases/)[![License](https://img.shields.io/github/license/chen08209/FlClash?style=flat-square)](LICENSE) [![Channel](https://img.shields.io/badge/Telegram-Channel-blue?style=flat-square&logo=telegram)](https://t.me/FlClash) A multi-platform proxy client based on ClashMeta, simple and easy to use, open-source and ad-free. on Desktop:

desktop

on Mobile:

mobile

## Features ✈️ Multi-platform: Android, Windows, macOS and Linux 💻 Adaptive multiple screen sizes, Multiple color themes available 💡 Based on Material You Design, [Surfboard](https://github.com/getsurfboard/surfboard)-like UI ☁️ Supports data sync via WebDAV ✨ Support subscription link, Dark mode ## Use ### Linux ⚠️ Make sure to install the following dependencies before using them ```bash sudo apt-get install libayatana-appindicator3-dev sudo apt-get install libkeybinder-3.0-dev ``` ### Android Support the following actions ```bash com.follow.clash.action.START com.follow.clash.action.STOP com.follow.clash.action.TOGGLE ``` ## Download Get it on F-Droid Get it on GitHub ## Build 1. Update submodules ```bash git submodule update --init --recursive ``` 2. Install `Flutter` and `Golang` environment 3. Build Application - android 1. Install `Android SDK` , `Android NDK` 2. Set `ANDROID_NDK` environment variables 3. Run Build script ```bash dart .\setup.dart android ``` - windows 1. You need a windows client 2. Install `Gcc`,`Inno Setup` 3. Run build script ```bash dart .\setup.dart windows --arch ``` - linux 1. You need a linux client 2. Run build script ```bash dart .\setup.dart linux --arch ``` - macOS 1. You need a macOS client 2. Run build script ```bash dart .\setup.dart macos --arch ``` ## Star The easiest way to support developers is to click on the star (⭐) at the top of the page.

start

================================================ FILE: README_zh_CN.md ================================================
[**English**](README.md)
## FlClash [![Downloads](https://img.shields.io/github/downloads/chen08209/FlClash/total?style=flat-square&logo=github)](https://github.com/chen08209/FlClash/releases/)[![Last Version](https://img.shields.io/github/release/chen08209/FlClash/all.svg?style=flat-square)](https://github.com/chen08209/FlClash/releases/)[![License](https://img.shields.io/github/license/chen08209/FlClash?style=flat-square)](LICENSE) [![Channel](https://img.shields.io/badge/Telegram-Channel-blue?style=flat-square&logo=telegram)](https://t.me/FlClash) 基于ClashMeta的多平台代理客户端,简单易用,开源无广告。 on Desktop:

desktop

on Mobile:

mobile

## Features ✈️ 多平台: Android, Windows, macOS and Linux 💻 自适应多个屏幕尺寸,多种颜色主题可供选择 💡 基本 Material You 设计, 类[Surfboard](https://github.com/getsurfboard/surfboard)用户界面 ☁️ 支持通过WebDAV同步数据 ✨ 支持一键导入订阅, 深色模式 ## Use ### Linux ⚠️ 使用前请确保安装以下依赖 ```bash sudo apt-get install libayatana-appindicator3-dev sudo apt-get install libkeybinder-3.0-dev ``` ### Android 支持下列操作 ```bash com.follow.clash.action.START com.follow.clash.action.STOP com.follow.clash.action.TOGGLE ``` ## Download Get it on F-Droid Get it on GitHub ## Build 1. 更新 submodules ```bash git submodule update --init --recursive ``` 2. 安装 `Flutter` 以及 `Golang` 环境 3. 构建应用 - android 1. 安装 `Android SDK` , `Android NDK` 2. 设置 `ANDROID_NDK` 环境变量 3. 运行构建脚本 ```bash dart .\setup.dart android ``` - windows 1. 你需要一个windows客户端 2. 安装 `Gcc`,`Inno Setup` 3. 运行构建脚本 ```bash dart .\setup.dart windows --arch ``` - linux 1. 你需要一个linux客户端 2. 运行构建脚本 ```bash dart .\setup.dart linux --arch ``` - macOS 1. 你需要一个macOS客户端 2. 运行构建脚本 ```bash dart .\setup.dart macos --arch ``` ## Star History 支持开发者的最简单方式是点击页面顶部的星标(⭐)。

start

================================================ FILE: analysis_options.yaml ================================================ include: package:flutter_lints/flutter.yaml analyzer: exclude: - lib/l10n/intl/** errors: invalid_annotation_target: ignore linter: rules: prefer_single_quotes: true ================================================ FILE: android/.gitignore ================================================ gradle-wrapper.jar /.gradle /captures/ /gradlew /gradlew.bat /local.properties GeneratedPluginRegistrant.java # Remember to never publicly share your keystore. # See https://flutter.dev/docs/deployment/android#reference-the-keystore-from-the-app key.properties **/*.keystore **/*.jks ================================================ FILE: android/app/build.gradle.kts ================================================ import org.jetbrains.kotlin.gradle.dsl.JvmTarget import java.util.Properties plugins { id("com.android.application") id("kotlin-android") id("dev.flutter.flutter-gradle-plugin") id("com.google.gms.google-services") id("com.google.firebase.crashlytics") } val localPropertiesFile = rootProject.file("local.properties") val localProperties = Properties().apply { if (localPropertiesFile.exists()) { localPropertiesFile.inputStream().use { load(it) } } } val mStoreFile: File = file("keystore.jks") val mStorePassword: String? = localProperties.getProperty("storePassword") val mKeyAlias: String? = localProperties.getProperty("keyAlias") val mKeyPassword: String? = localProperties.getProperty("keyPassword") val isRelease = mStoreFile.exists() && mStorePassword != null && mKeyAlias != null && mKeyPassword != null android { namespace = "com.follow.clash" compileSdk = libs.versions.compileSdk.get().toInt() ndkVersion = libs.versions.ndkVersion.get() compileOptions { sourceCompatibility = JavaVersion.VERSION_17 targetCompatibility = JavaVersion.VERSION_17 } defaultConfig { applicationId = "com.follow.clash" minSdk = flutter.minSdkVersion targetSdk = libs.versions.targetSdk.get().toInt() versionCode = flutter.versionCode versionName = flutter.versionName } signingConfigs { if (isRelease) { create("release") { storeFile = mStoreFile storePassword = mStorePassword keyAlias = mKeyAlias keyPassword = mKeyPassword } } } packaging { jniLibs { useLegacyPackaging = true } } buildTypes { debug { isMinifyEnabled = false applicationIdSuffix = ".dev" } release { isMinifyEnabled = true isShrinkResources = true if (isRelease) { signingConfig = signingConfigs.getByName("release") } else { signingConfig = signingConfigs.getByName("debug") applicationIdSuffix = ".dev" } proguardFiles( getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro" ) } } } kotlin { compilerOptions { jvmTarget.set(JvmTarget.JVM_17) } } flutter { source = "../.." } dependencies { implementation(project(":service")) implementation(project(":common")) implementation(libs.core.splashscreen) implementation(libs.gson) implementation(libs.smali.dexlib2) { exclude(group = "com.google.guava", module = "guava") } implementation(platform(libs.firebase.bom)) implementation(libs.firebase.crashlytics.ndk) implementation(libs.firebase.analytics) } ================================================ FILE: android/app/google-services.json ================================================ { "project_info": { "project_number": "000000000000", "project_id": "dev" }, "client": [ { "client_info": { "mobilesdk_app_id": "1:000000000000:android:0000000000000000", "android_client_info": { "package_name": "com.follow.clash" } }, "oauth_client": [], "api_key": [ { "current_key": "0" } ], "services": { "appinvite_service": { "other_platform_oauth_client": [] } } }, { "client_info": { "mobilesdk_app_id": "1:000000000000:android:0000000000000000", "android_client_info": { "package_name": "com.follow.clash.debug" } }, "oauth_client": [], "api_key": [ { "current_key": "0" } ], "services": { "appinvite_service": { "other_platform_oauth_client": [] } } }, { "client_info": { "mobilesdk_app_id": "1:000000000000:android:0000000000000000", "android_client_info": { "package_name": "com.follow.clash.dev" } }, "oauth_client": [], "api_key": [ { "current_key": "0" } ], "services": { "appinvite_service": { "other_platform_oauth_client": [] } } } ] } ================================================ FILE: android/app/proguard-rules.pro ================================================ -keep class com.follow.clash.models.**{ *; } -keep class com.follow.clash.service.models.**{ *; } ================================================ FILE: android/app/src/debug/AndroidManifest.xml ================================================ ================================================ FILE: android/app/src/main/AndroidManifest.xml ================================================ ================================================ FILE: android/app/src/main/kotlin/com/follow/clash/Application.kt ================================================ package com.follow.clash import android.app.Application import android.content.Context import com.follow.clash.common.GlobalState class Application : Application() { override fun attachBaseContext(base: Context?) { super.attachBaseContext(base) GlobalState.init(this) } } ================================================ FILE: android/app/src/main/kotlin/com/follow/clash/BroadcastReceiver.kt ================================================ package com.follow.clash import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import com.follow.clash.common.BroadcastAction import com.follow.clash.common.GlobalState import com.follow.clash.common.action import kotlinx.coroutines.launch class BroadcastReceiver : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { when (intent?.action) { BroadcastAction.SERVICE_CREATED.action -> { GlobalState.log("Receiver service created") GlobalState.launch { State.handleStartServiceAction() } } BroadcastAction.SERVICE_DESTROYED.action -> { GlobalState.log("Receiver service destroyed") GlobalState.launch { State.handleStopServiceAction() } } } } } ================================================ FILE: android/app/src/main/kotlin/com/follow/clash/Ext.kt ================================================ package com.follow.clash import android.app.Application import android.content.Context.MODE_PRIVATE import android.content.pm.PackageManager import android.graphics.Bitmap import android.graphics.drawable.Drawable import android.os.Build import android.os.Handler import android.os.Looper import android.widget.Toast import androidx.core.graphics.drawable.toBitmap import com.follow.clash.common.GlobalState import com.follow.clash.models.SharedState import com.google.gson.Gson import io.flutter.embedding.engine.FlutterEngine import io.flutter.embedding.engine.plugins.FlutterPlugin import io.flutter.plugin.common.MethodChannel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.suspendCancellableCoroutine import kotlinx.coroutines.withContext import java.io.File import java.io.FileOutputStream import java.util.concurrent.TimeUnit import kotlin.coroutines.resume private const val ICON_TTL_DAYS = 1L val Application.sharedState: SharedState get() { try { val sp = getSharedPreferences("FlutterSharedPreferences", MODE_PRIVATE) val res = sp.getString("flutter.sharedState", "") return Gson().fromJson(res, SharedState::class.java) } catch (_: Exception) { return SharedState() } } private var lastToast: Toast? = null fun Application.showToast(text: String?) { Handler(Looper.getMainLooper()).post { lastToast?.cancel() lastToast = Toast.makeText(this, text, Toast.LENGTH_LONG).apply { show() } } } suspend fun PackageManager.getPackageIconPath(packageName: String): String = withContext(Dispatchers.IO) { val cacheDir = GlobalState.application.cacheDir val iconDir = File(cacheDir, "icons").apply { mkdirs() } return@withContext try { val pkgInfo = getPackageInfo(packageName, 0) val lastUpdateTime = pkgInfo.lastUpdateTime val iconFile = File(iconDir, "${packageName}_${lastUpdateTime}.webp") if (iconFile.exists() && !isExpired(iconFile)) { return@withContext iconFile.absolutePath } iconDir.listFiles { f -> f.name.startsWith("${packageName}_") }?.forEach(File::delete) val icon = getApplicationIcon(packageName) saveDrawableToFile(icon, iconFile) iconFile.absolutePath } catch (_: Exception) { val defaultIconFile = File(iconDir, "default_icon.webp") if (!defaultIconFile.exists()) { saveDrawableToFile(defaultActivityIcon, defaultIconFile) } defaultIconFile.absolutePath } } private suspend fun saveDrawableToFile(drawable: Drawable, file: File) { val bitmap = withContext(Dispatchers.Default) { drawable.toBitmap(width = 128, height = 128) } try { val format = when { Build.VERSION.SDK_INT >= Build.VERSION_CODES.R -> { Bitmap.CompressFormat.WEBP_LOSSY } else -> { Bitmap.CompressFormat.WEBP } } FileOutputStream(file).use { fos -> bitmap.compress(format, 90, fos) } } finally { if (!bitmap.isRecycled) bitmap.recycle() } } private fun isExpired(file: File): Boolean { val now = System.currentTimeMillis() val age = now - file.lastModified() return age > TimeUnit.DAYS.toMillis(ICON_TTL_DAYS) } suspend fun MethodChannel.awaitResult( method: String, arguments: Any? = null ): T? = withContext(Dispatchers.Main) { suspendCancellableCoroutine { continuation -> invokeMethod(method, arguments, object : MethodChannel.Result { override fun success(result: Any?) { @Suppress("UNCHECKED_CAST") continuation.resume(result as T?) } override fun error(code: String, message: String?, details: Any?) { continuation.resume(null) } override fun notImplemented() { continuation.resume(null) } }) } } inline fun FlutterEngine.plugin(): T? { return plugins.get(T::class.java) as T? } fun MethodChannel.invokeMethodOnMainThread( method: String, arguments: Any? = null, callback: ((Result) -> Unit)? = null ) { Handler(Looper.getMainLooper()).post { invokeMethod(method, arguments, object : MethodChannel.Result { override fun success(result: Any?) { @Suppress("UNCHECKED_CAST") callback?.invoke(Result.success(result as T)) } override fun error(errorCode: String, errorMessage: String?, errorDetails: Any?) { val exception = Exception("MethodChannel error: $errorCode - $errorMessage") callback?.invoke(Result.failure(exception)) } override fun notImplemented() { val exception = NotImplementedError("Method not implemented: $method") callback?.invoke(Result.failure(exception)) } }) } } ================================================ FILE: android/app/src/main/kotlin/com/follow/clash/MainActivity.kt ================================================ package com.follow.clash import android.os.Bundle import com.follow.clash.common.GlobalState import com.follow.clash.plugins.AppPlugin import com.follow.clash.plugins.ServicePlugin import com.follow.clash.plugins.TilePlugin import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.engine.FlutterEngine import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.launch class MainActivity : FlutterActivity(), CoroutineScope by CoroutineScope(SupervisorJob() + Dispatchers.Default) { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun configureFlutterEngine(flutterEngine: FlutterEngine) { super.configureFlutterEngine(flutterEngine) flutterEngine.plugins.add(AppPlugin()) flutterEngine.plugins.add(ServicePlugin()) flutterEngine.plugins.add(TilePlugin()) State.flutterEngine = flutterEngine } override fun onDestroy() { GlobalState.launch { Service.setEventListener(null) } State.flutterEngine = null super.onDestroy() } } ================================================ FILE: android/app/src/main/kotlin/com/follow/clash/Service.kt ================================================ package com.follow.clash import com.follow.clash.common.GlobalState import com.follow.clash.common.ServiceDelegate import com.follow.clash.common.formatString import com.follow.clash.common.intent import com.follow.clash.service.IAckInterface import com.follow.clash.service.ICallbackInterface import com.follow.clash.service.IEventInterface import com.follow.clash.service.IRemoteInterface import com.follow.clash.service.IResultInterface import com.follow.clash.service.IVoidInterface import com.follow.clash.service.RemoteService import com.follow.clash.service.models.NotificationParams import com.follow.clash.service.models.VpnOptions import kotlinx.coroutines.suspendCancellableCoroutine import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException object Service { private val delegate by lazy { ServiceDelegate( RemoteService::class.intent, ::handleServiceDisconnected ) { IRemoteInterface.Stub.asInterface(it) } } var onServiceDisconnected: ((String) -> Unit)? = null private fun handleServiceDisconnected(message: String) { onServiceDisconnected?.let { it(message) } } fun bind() { delegate.bind() } fun unbind() { delegate.unbind() } suspend fun invokeAction(data: String, cb: ((result: String) -> Unit)?): Result { val res = mutableListOf() return delegate.useService { it.invokeAction( data, object : ICallbackInterface.Stub() { override fun onResult( result: ByteArray?, isSuccess: Boolean, ack: IAckInterface? ) { res.add(result ?: byteArrayOf()) ack?.onAck() if (isSuccess) { cb?.let { cb -> cb(res.formatString()) } } } }) } } suspend fun quickSetup( initParamsString: String, setupParamsString: String, onStarted: (() -> Unit)?, onResult: ((result: String) -> Unit)?, ): Result { val res = mutableListOf() return delegate.useService { it.quickSetup( initParamsString, setupParamsString, object : ICallbackInterface.Stub() { override fun onResult( result: ByteArray?, isSuccess: Boolean, ack: IAckInterface? ) { res.add(result ?: byteArrayOf()) ack?.onAck() if (isSuccess) { onResult?.let { cb -> cb(res.formatString()) } } } }, object : IVoidInterface.Stub() { override fun invoke() { onStarted?.let { onStarted -> onStarted() } } } ) } } suspend fun setEventListener( cb: ((result: String?) -> Unit)? ): Result { val results = HashMap>() return delegate.useService { it.setEventListener( when (cb != null) { true -> object : IEventInterface.Stub() { override fun onEvent( id: String, data: ByteArray?, isSuccess: Boolean, ack: IAckInterface? ) { if (results[id] == null) { results[id] = mutableListOf() } results[id]?.add(data ?: byteArrayOf()) ack?.onAck() if (isSuccess) { cb(results[id]?.formatString()) results.remove(id) } } } false -> null }) } } suspend fun updateNotificationParams( params: NotificationParams ): Result { return delegate.useService { it.updateNotificationParams(params) } } suspend fun setCrashlytics( enable: Boolean ): Result { return delegate.useService { it.setCrashlytics(enable) } } private suspend fun awaitIResultInterface( block: (IResultInterface) -> Unit ): Long = suspendCancellableCoroutine { continuation -> val callback = object : IResultInterface.Stub() { override fun onResult(time: Long) { if (continuation.isActive) { continuation.resume(time) } } } try { block(callback) } catch (e: Exception) { GlobalState.log("awaitIResultInterface $e") if (continuation.isActive) { continuation.resumeWithException(e) } } } suspend fun startService(options: VpnOptions, runTime: Long): Long { return delegate.useService { awaitIResultInterface { callback -> it.startService(options, runTime, callback) } }.getOrNull() ?: 0L } suspend fun stopService(): Long { return delegate.useService { awaitIResultInterface { callback -> it.stopService(callback) } }.getOrNull() ?: 0L } suspend fun getRunTime(): Long { return delegate.useService { it.runTime }.getOrNull() ?: 0L } } ================================================ FILE: android/app/src/main/kotlin/com/follow/clash/State.kt ================================================ package com.follow.clash import android.net.VpnService import com.follow.clash.common.GlobalState import com.follow.clash.models.SharedState import com.follow.clash.plugins.AppPlugin import com.follow.clash.plugins.TilePlugin import com.follow.clash.service.models.NotificationParams import com.google.gson.Gson import io.flutter.embedding.engine.FlutterEngine import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock enum class RunState { START, PENDING, STOP } object State { val runLock = Mutex() var runTime: Long = 0 var sharedState: SharedState = SharedState() val runStateFlow: MutableStateFlow = MutableStateFlow(RunState.STOP) var flutterEngine: FlutterEngine? = null val appPlugin: AppPlugin? get() = flutterEngine?.plugin() val tilePlugin: TilePlugin? get() = flutterEngine?.plugin() suspend fun handleToggleAction() { var action: (suspend () -> Unit)? runLock.withLock { action = when (runStateFlow.value) { RunState.PENDING -> null RunState.START -> ::handleStopServiceAction RunState.STOP -> ::handleStartServiceAction } } action?.invoke() } suspend fun handleSyncState() { runLock.withLock { try { Service.bind() runTime = Service.getRunTime() val runState = when (runTime == 0L) { true -> RunState.STOP false -> RunState.START } runStateFlow.tryEmit(runState) } catch (_: Exception) { runStateFlow.tryEmit(RunState.STOP) } } } suspend fun handleStartServiceAction() { runLock.withLock { if (runStateFlow.value != RunState.STOP) { return } tilePlugin?.handleStart() if (flutterEngine != null) { return } startServiceWithPref() } } suspend fun handleStopServiceAction() { runLock.withLock { if (runStateFlow.value != RunState.START) { return } tilePlugin?.handleStop() if (flutterEngine != null) { return } GlobalState.application.showToast(sharedState.stopTip) handleStopService() } } fun handleStartService() { val appPlugin = flutterEngine?.plugin() if (appPlugin != null) { appPlugin.requestNotificationsPermission { startService() } return } startService() } private fun startServiceWithPref() { GlobalState.launch { runLock.withLock { if (runStateFlow.value != RunState.STOP) { return@launch } sharedState = GlobalState.application.sharedState setupAndStart() } } } suspend fun syncState() { GlobalState.setCrashlytics(sharedState.crashlytics) Service.updateNotificationParams( NotificationParams( title = sharedState.currentProfileName, stopText = sharedState.stopText, onlyStatisticsProxy = sharedState.onlyStatisticsProxy ) ) Service.setCrashlytics(sharedState.crashlytics) } private suspend fun setupAndStart() { Service.bind() syncState() GlobalState.application.showToast(sharedState.startTip) val initParams = mutableMapOf() initParams["home-dir"] = GlobalState.application.filesDir.path initParams["version"] = android.os.Build.VERSION.SDK_INT val initParamsString = Gson().toJson(initParams) val setupParamsString = Gson().toJson(sharedState.setupParams) Service.quickSetup( initParamsString, setupParamsString, onStarted = { startService() }, onResult = { if (it.isNotEmpty()) { GlobalState.application.showToast(it) } }, ) } private fun startService() { GlobalState.launch { runLock.withLock { if (runStateFlow.value != RunState.STOP) { return@launch } try { runStateFlow.tryEmit(RunState.PENDING) val options = sharedState.vpnOptions ?: return@launch appPlugin?.let { it.prepare(options.enable) { runTime = Service.startService(options, runTime) runStateFlow.tryEmit(RunState.START) } } ?: run { val intent = VpnService.prepare(GlobalState.application) if (intent != null) { return@launch } runTime = Service.startService(options, runTime) runStateFlow.tryEmit(RunState.START) } } finally { if (runStateFlow.value == RunState.PENDING) { runStateFlow.tryEmit(RunState.STOP) } } } } } fun handleStopService() { GlobalState.launch { runLock.withLock { if (runStateFlow.value != RunState.START) { return@launch } try { runStateFlow.tryEmit(RunState.PENDING) runTime = Service.stopService() runStateFlow.tryEmit(RunState.STOP) } finally { if (runStateFlow.value == RunState.PENDING) { runStateFlow.tryEmit(RunState.START) } } } } } } ================================================ FILE: android/app/src/main/kotlin/com/follow/clash/TempActivity.kt ================================================ package com.follow.clash import android.app.Activity import android.os.Bundle import com.follow.clash.common.QuickAction import com.follow.clash.common.action import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.launch class TempActivity : Activity(), CoroutineScope by CoroutineScope(SupervisorJob() + Dispatchers.Default) { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) when (intent.action) { QuickAction.START.action -> { launch { State.handleStartServiceAction() } } QuickAction.STOP.action -> { launch { State.handleStopServiceAction() } } QuickAction.TOGGLE.action -> { launch { State.handleToggleAction() } } } finish() } } ================================================ FILE: android/app/src/main/kotlin/com/follow/clash/TileService.kt ================================================ package com.follow.clash import android.annotation.SuppressLint import android.os.Build import android.service.quicksettings.Tile import android.service.quicksettings.TileService import com.follow.clash.common.QuickAction import com.follow.clash.common.quickIntent import com.follow.clash.common.toPendingIntent import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import kotlinx.coroutines.launch class TileService : TileService() { private var scope: CoroutineScope? = null private fun updateTile(runState: RunState) { if (qsTile != null) { qsTile.state = when (runState) { RunState.START -> Tile.STATE_ACTIVE RunState.PENDING -> Tile.STATE_UNAVAILABLE RunState.STOP -> Tile.STATE_INACTIVE } qsTile.updateTile() } } override fun onStartListening() { super.onStartListening() scope?.cancel() scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) scope?.launch { State.handleSyncState() State.runStateFlow.collect { updateTile(it) } } } @SuppressLint("StartActivityAndCollapseDeprecated") private fun handleToggle() { val intent = QuickAction.TOGGLE.quickIntent val pendingIntent = intent.toPendingIntent if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { startActivityAndCollapse(pendingIntent) } else { @Suppress("DEPRECATION") startActivityAndCollapse(intent) } } override fun onClick() { super.onClick() handleToggle() } override fun onStopListening() { scope?.cancel() super.onStopListening() } } ================================================ FILE: android/app/src/main/kotlin/com/follow/clash/models/Package.kt ================================================ package com.follow.clash.models data class Package( val packageName: String, val label: String, val system: Boolean, val internet: Boolean, val lastUpdateTime: Long, ) ================================================ FILE: android/app/src/main/kotlin/com/follow/clash/models/State.kt ================================================ package com.follow.clash.models import com.follow.clash.service.models.VpnOptions import com.google.gson.annotations.SerializedName data class SharedState( val startTip: String = "Starting VPN...", val stopTip: String = "Stopping VPN...", val crashlytics: Boolean = true, val currentProfileName: String = "FlClash", val stopText: String = "Stop", val onlyStatisticsProxy: Boolean = false, val vpnOptions: VpnOptions? = null, val setupParams: SetupParams? = null, ) data class SetupParams( @SerializedName("test-url") val testUrl: String, @SerializedName("selected-map") val selectedMap: Map, ) ================================================ FILE: android/app/src/main/kotlin/com/follow/clash/plugins/AppPlugin.kt ================================================ package com.follow.clash.plugins import android.Manifest import android.app.Activity import android.app.ActivityManager import android.content.Intent import android.content.pm.ApplicationInfo import android.content.pm.ComponentInfo import android.content.pm.PackageManager import android.net.VpnService import android.os.Build import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import androidx.core.content.ContextCompat.getSystemService import androidx.core.content.pm.ShortcutInfoCompat import androidx.core.content.pm.ShortcutManagerCompat import androidx.core.graphics.drawable.IconCompat import com.android.tools.smali.dexlib2.dexbacked.DexBackedDexFile import com.follow.clash.R import com.follow.clash.common.Components import com.follow.clash.common.GlobalState import com.follow.clash.common.QuickAction import com.follow.clash.common.quickIntent import com.follow.clash.getPackageIconPath import com.follow.clash.models.Package import com.follow.clash.showToast import com.google.gson.Gson import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.engine.plugins.FlutterPlugin import io.flutter.embedding.engine.plugins.activity.ActivityAware import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding import io.flutter.plugin.common.MethodCall import io.flutter.plugin.common.MethodChannel import io.flutter.plugin.common.MethodChannel.Result import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.cancel import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.io.File import java.lang.ref.WeakReference import java.util.zip.ZipFile class AppPlugin : FlutterPlugin, MethodChannel.MethodCallHandler, ActivityAware { companion object { const val VPN_PERMISSION_REQUEST_CODE = 1001 const val NOTIFICATION_PERMISSION_REQUEST_CODE = 1002 } private var activityRef: WeakReference? = null private lateinit var channel: MethodChannel private lateinit var scope: CoroutineScope private var vpnPrepareCallback: (suspend () -> Unit)? = null private var requestNotificationCallback: (() -> Unit)? = null private val packages = mutableListOf() private val skipPrefixList = listOf( "com.google", "com.android.chrome", "com.android.vending", "com.microsoft", "com.apple", "com.zhiliaoapp.musically", // Banned by China ) private val chinaAppPrefixList = listOf( "com.tencent", "com.alibaba", "com.umeng", "com.qihoo", "com.ali", "com.alipay", "com.amap", "com.sina", "com.weibo", "com.vivo", "com.xiaomi", "com.huawei", "com.taobao", "com.secneo", "s.h.e.l.l", "com.stub", "com.kiwisec", "com.secshell", "com.wrapper", "cn.securitystack", "com.mogosec", "com.secoen", "com.netease", "com.mx", "com.qq.e", "com.baidu", "com.bytedance", "com.bugly", "com.miui", "com.oppo", "com.coloros", "com.iqoo", "com.meizu", "com.gionee", "cn.nubia", "com.oplus", "andes.oplus", "com.unionpay", "cn.wps" ) private val chinaAppRegex by lazy { ("(" + chinaAppPrefixList.joinToString("|").replace(".", "\\.") + ").*").toRegex() } private var isBlockNotification: Boolean = false override fun onMethodCall(call: MethodCall, result: Result) { when (call.method) { "moveTaskToBack" -> { activityRef?.get()?.moveTaskToBack(true) result.success(true) } "updateExcludeFromRecents" -> { val value = call.argument("value") updateExcludeFromRecents(value) result.success(true) } "initShortcuts" -> { initShortcuts(call.arguments as String) result.success(true) } "getPackages" -> { scope.launch { result.success(getPackagesToJson()) } } "getChinaPackageNames" -> { scope.launch { result.success(getChinaPackageNames()) } } "getPackageIcon" -> { handleGetPackageIcon(call, result) } "tip" -> { val message = call.argument("message") tip(message) result.success(true) } else -> { result.notImplemented() } } } private fun handleGetPackageIcon(call: MethodCall, result: Result) { scope.launch { val packageName = call.argument("packageName") if (packageName == null) { result.success("") return@launch } val path = GlobalState.application.packageManager.getPackageIconPath(packageName) result.success(path) } } private fun initShortcuts(label: String) { val shortcut = with(ShortcutInfoCompat.Builder(GlobalState.application, "toggle")) { setShortLabel(label) setIcon( IconCompat.createWithResource( GlobalState.application, R.mipmap.ic_launcher_round, ) ) setIntent(QuickAction.TOGGLE.quickIntent) build() } ShortcutManagerCompat.setDynamicShortcuts( GlobalState.application, listOf(shortcut) ) } private fun tip(message: String?) { GlobalState.application.showToast(message) } @Suppress("DEPRECATION") private fun updateExcludeFromRecents(value: Boolean?) { val am = getSystemService(GlobalState.application, ActivityManager::class.java) val task = am?.appTasks?.firstOrNull { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { it.taskInfo.taskId == activityRef?.get()?.taskId } else { it.taskInfo.id == activityRef?.get()?.taskId } } when (value) { true -> task?.setExcludeFromRecents(value) false -> task?.setExcludeFromRecents(value) null -> task?.setExcludeFromRecents(false) } } private fun getPackages(): List { val packageManager = GlobalState.application.packageManager if (packages.isNotEmpty()) return packages packageManager?.getInstalledPackages(PackageManager.GET_META_DATA or PackageManager.GET_PERMISSIONS) ?.filter { it.packageName != GlobalState.application.packageName && it.packageName != "android" }?.map { Package( packageName = it.packageName, label = it.applicationInfo?.loadLabel(packageManager).toString(), system = (it.applicationInfo?.flags?.and(ApplicationInfo.FLAG_SYSTEM)) != 0, lastUpdateTime = it.lastUpdateTime, internet = it.requestedPermissions?.contains(Manifest.permission.INTERNET) == true ) }?.let { packages.addAll(it) } return packages } private suspend fun getPackagesToJson(): String { return withContext(Dispatchers.Default) { Gson().toJson(getPackages()) } } private suspend fun getChinaPackageNames(): String { return withContext(Dispatchers.Default) { val packages: List = getPackages().map { it.packageName }.filter { isChinaPackage(it) } Gson().toJson(packages) } } fun requestNotificationsPermission(callBack: () -> Unit) { requestNotificationCallback = callBack if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { val permission = ContextCompat.checkSelfPermission( GlobalState.application, Manifest.permission.POST_NOTIFICATIONS ) if (permission == PackageManager.PERMISSION_GRANTED || isBlockNotification) { invokeRequestNotificationCallback() return } activityRef?.get()?.let { ActivityCompat.requestPermissions( it, arrayOf(Manifest.permission.POST_NOTIFICATIONS), NOTIFICATION_PERMISSION_REQUEST_CODE ) } return } else { invokeRequestNotificationCallback() } } fun invokeRequestNotificationCallback() { requestNotificationCallback?.invoke() requestNotificationCallback = null } fun prepare(needPrepare: Boolean, callBack: (suspend () -> Unit)) { vpnPrepareCallback = callBack if (!needPrepare) { invokeVpnPrepareCallback() return } val intent = VpnService.prepare(GlobalState.application) if (intent != null) { activityRef?.get()?.startActivityForResult(intent, VPN_PERMISSION_REQUEST_CODE) return } invokeVpnPrepareCallback() } fun invokeVpnPrepareCallback() { GlobalState.launch { vpnPrepareCallback?.invoke() vpnPrepareCallback = null } } @Suppress("DEPRECATION") private fun isChinaPackage(packageName: String): Boolean { val packageManager = GlobalState.application.packageManager ?: return false skipPrefixList.forEach { if (packageName == it || packageName.startsWith("$it.")) return false } val packageManagerFlags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { PackageManager.MATCH_UNINSTALLED_PACKAGES or PackageManager.GET_ACTIVITIES or PackageManager.GET_SERVICES or PackageManager.GET_RECEIVERS or PackageManager.GET_PROVIDERS } else { PackageManager.GET_UNINSTALLED_PACKAGES or PackageManager.GET_ACTIVITIES or PackageManager.GET_SERVICES or PackageManager.GET_RECEIVERS or PackageManager.GET_PROVIDERS } if (packageName.matches(chinaAppRegex)) { return true } try { val packageInfo = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { packageManager.getPackageInfo( packageName, PackageManager.PackageInfoFlags.of(packageManagerFlags.toLong()) ) } else { packageManager.getPackageInfo( packageName, packageManagerFlags ) } mutableListOf().apply { packageInfo.services?.let { addAll(it) } packageInfo.activities?.let { addAll(it) } packageInfo.receivers?.let { addAll(it) } packageInfo.providers?.let { addAll(it) } }.forEach { if (it.name.matches(chinaAppRegex)) return true } packageInfo.applicationInfo?.publicSourceDir?.let { ZipFile(File(it)).use { for (packageEntry in it.entries()) { if (packageEntry.name.startsWith("firebase-")) return false } for (packageEntry in it.entries()) { if (!(packageEntry.name.startsWith("classes") && packageEntry.name.endsWith( ".dex" )) ) { continue } if (packageEntry.size > 15000000) { return true } val input = it.getInputStream(packageEntry).buffered() val dexFile = try { DexBackedDexFile.fromInputStream(null, input) } catch (e: Exception) { return false } for (clazz in dexFile.classes) { val clazzName = clazz.type.substring(1, clazz.type.length - 1).replace("/", ".") .replace("$", ".") if (clazzName.matches(chinaAppRegex)) return true } } } } } catch (_: Exception) { return false } return false } override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) { scope = CoroutineScope(Dispatchers.Default) channel = MethodChannel(flutterPluginBinding.binaryMessenger, "${Components.PACKAGE_NAME}/app") channel.setMethodCallHandler(this) } override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) { channel.setMethodCallHandler(null) scope.cancel() } override fun onAttachedToActivity(binding: ActivityPluginBinding) { activityRef = WeakReference(binding.activity) binding.addActivityResultListener(::onActivityResult) binding.addRequestPermissionsResultListener(::onRequestPermissionsResultListener) } override fun onDetachedFromActivityForConfigChanges() { activityRef = null } override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) { activityRef = WeakReference(binding.activity) } override fun onDetachedFromActivity() { channel.invokeMethod("exit", null) activityRef = null } private fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?): Boolean { if (requestCode == VPN_PERMISSION_REQUEST_CODE) { if (resultCode == FlutterActivity.RESULT_OK) { invokeVpnPrepareCallback() } } return true } private fun onRequestPermissionsResultListener( requestCode: Int, permissions: Array, grantResults: IntArray ): Boolean { if (requestCode == NOTIFICATION_PERMISSION_REQUEST_CODE) { isBlockNotification = true } invokeRequestNotificationCallback() return true } } ================================================ FILE: android/app/src/main/kotlin/com/follow/clash/plugins/ServicePlugin.kt ================================================ package com.follow.clash.plugins import com.follow.clash.RunState import com.follow.clash.Service import com.follow.clash.State import com.follow.clash.common.Components import com.follow.clash.invokeMethodOnMainThread import com.follow.clash.models.SharedState import com.google.gson.Gson import io.flutter.embedding.engine.plugins.FlutterPlugin import io.flutter.plugin.common.MethodCall import io.flutter.plugin.common.MethodChannel import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Semaphore import kotlinx.coroutines.sync.withPermit class ServicePlugin : FlutterPlugin, MethodChannel.MethodCallHandler, CoroutineScope by CoroutineScope(SupervisorJob() + Dispatchers.Default) { private lateinit var flutterMethodChannel: MethodChannel override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) { flutterMethodChannel = MethodChannel( flutterPluginBinding.binaryMessenger, "${Components.PACKAGE_NAME}/service" ) flutterMethodChannel.setMethodCallHandler(this) } override fun onDetachedFromEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) { flutterMethodChannel.setMethodCallHandler(null) } override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) = when (call.method) { "init" -> { handleInit(result) } "shutdown" -> { handleShutdown(result) } "invokeAction" -> { handleInvokeAction(call, result) } "getRunTime" -> { handleGetRunTime(result) } "syncState" -> { handleSyncState(call, result) } "start" -> { handleStart(result) } "stop" -> { handleStop(result) } else -> { result.notImplemented() } } private fun handleInvokeAction(call: MethodCall, result: MethodChannel.Result) { launch { val data = call.arguments()!! Service.invokeAction(data) { result.success(it) } } } private fun handleShutdown(result: MethodChannel.Result) { Service.unbind() result.success(true) } private fun handleStart(result: MethodChannel.Result) { State.handleStartService() result.success(true) } private fun handleStop(result: MethodChannel.Result) { State.handleStopService() result.success(true) } val semaphore = Semaphore(10) fun handleSendEvent(value: String?) { launch(Dispatchers.Main) { semaphore.withPermit { flutterMethodChannel.invokeMethod("event", value) } } } private fun onServiceDisconnected(message: String) { State.runStateFlow.tryEmit(RunState.STOP) flutterMethodChannel.invokeMethodOnMainThread("crash", message) } private fun handleSyncState(call: MethodCall, result: MethodChannel.Result) { val data = call.arguments()!! State.sharedState = Gson().fromJson(data, SharedState::class.java) launch { State.syncState() result.success("") } } fun handleInit(result: MethodChannel.Result) { Service.bind() launch { Service.setEventListener { handleSendEvent(it) }.onSuccess { result.success("") }.onFailure { result.success(it.message) } } Service.onServiceDisconnected = ::onServiceDisconnected } private fun handleGetRunTime(result: MethodChannel.Result) { launch { State.handleSyncState() result.success(State.runTime) } } } ================================================ FILE: android/app/src/main/kotlin/com/follow/clash/plugins/TilePlugin.kt ================================================ package com.follow.clash.plugins import com.follow.clash.common.Components import com.follow.clash.invokeMethodOnMainThread import io.flutter.embedding.engine.plugins.FlutterPlugin import io.flutter.plugin.common.MethodCall import io.flutter.plugin.common.MethodChannel class TilePlugin : FlutterPlugin, MethodChannel.MethodCallHandler { private lateinit var channel: MethodChannel override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) { channel = MethodChannel(flutterPluginBinding.binaryMessenger, "${Components.PACKAGE_NAME}/tile") channel.setMethodCallHandler(this) } override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) { channel.setMethodCallHandler(null) } fun handleStart() { channel.invokeMethodOnMainThread("start", null) } fun handleStop() { channel.invokeMethodOnMainThread("stop", null) } override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {} } ================================================ FILE: android/app/src/main/res/drawable/ic_launcher_foreground.xml ================================================ ================================================ FILE: android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml ================================================ ================================================ FILE: android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml ================================================ ================================================ FILE: android/app/src/main/res/values/ic_launcher_background.xml ================================================ #FAFAFA ================================================ FILE: android/app/src/main/res/values/styles.xml ================================================ ================================================ FILE: android/app/src/main/res/values-night/styles.xml ================================================ ================================================ FILE: android/app/src/main/res/values-night-v27/styles.xml ================================================ ================================================ FILE: android/app/src/main/res/values-v27/styles.xml ================================================ ================================================ FILE: android/app/src/main/res/xml/file_paths.xml ================================================ ================================================ FILE: android/app/src/main/res/xml/network_security_config.xml ================================================ localhost 127.0.0.1 ================================================ FILE: android/app/src/profile/AndroidManifest.xml ================================================ ================================================ FILE: android/build.gradle.kts ================================================ allprojects { repositories { google() mavenCentral() } } val newBuildDir: Directory = rootProject.layout.buildDirectory .dir("../../build") .get() rootProject.layout.buildDirectory.value(newBuildDir) subprojects { val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name) project.layout.buildDirectory.value(newSubprojectBuildDir) } subprojects { project.evaluationDependsOn(":app") } tasks.register("clean") { delete(rootProject.layout.buildDirectory) } ================================================ FILE: android/common/.gitignore ================================================ /build ================================================ FILE: android/common/build.gradle.kts ================================================ import org.jetbrains.kotlin.gradle.dsl.JvmTarget plugins { id("com.android.library") id("org.jetbrains.kotlin.android") } android { namespace = "com.follow.clash.common" compileSdk = libs.versions.compileSdk.get().toInt() defaultConfig { minSdk = 21 consumerProguardFiles("consumer-rules.pro") } buildTypes { release { proguardFiles( getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro" ) } } compileOptions { sourceCompatibility = JavaVersion.VERSION_17 targetCompatibility = JavaVersion.VERSION_17 } } kotlin { compilerOptions { jvmTarget.set(JvmTarget.JVM_17) } } dependencies { implementation(libs.androidx.core) implementation(libs.gson) implementation(platform(libs.firebase.bom)) implementation(libs.firebase.crashlytics.ndk) implementation(libs.firebase.analytics) } ================================================ FILE: android/common/src/main/AndroidManifest.xml ================================================ ================================================ FILE: android/common/src/main/java/com/follow/clash/common/Components.kt ================================================ package com.follow.clash.common import android.content.ComponentName object Components { const val PACKAGE_NAME = "com.follow.clash" val MAIN_ACTIVITY = ComponentName(GlobalState.packageName, "${PACKAGE_NAME}.MainActivity") val TEMP_ACTIVITY = ComponentName(GlobalState.packageName, "${PACKAGE_NAME}.TempActivity") val BROADCAST_RECEIVER = ComponentName(GlobalState.packageName, "${PACKAGE_NAME}.BroadcastReceiver") } ================================================ FILE: android/common/src/main/java/com/follow/clash/common/Enums.kt ================================================ package com.follow.clash.common import com.google.gson.annotations.SerializedName enum class QuickAction { STOP, START, TOGGLE, } enum class BroadcastAction { SERVICE_CREATED, SERVICE_DESTROYED, } enum class AccessControlMode { @SerializedName("acceptSelected") ACCEPT_SELECTED, @SerializedName("rejectSelected") REJECT_SELECTED, } ================================================ FILE: android/common/src/main/java/com/follow/clash/common/Ext.kt ================================================ package com.follow.clash.common import android.annotation.SuppressLint import android.app.ActivityManager import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.app.Service import android.content.BroadcastReceiver import android.content.ComponentName import android.content.Context import android.content.Context.RECEIVER_NOT_EXPORTED import android.content.Intent import android.content.IntentFilter import android.content.ServiceConnection import android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE import android.os.Build import android.os.Handler import android.os.IBinder import android.os.Looper import android.os.RemoteException import android.util.Log import androidx.core.content.getSystemService import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.flow.retryWhen import kotlinx.coroutines.withContext import java.nio.charset.Charset import kotlin.reflect.KClass //fun Context.startForegroundServiceCompat(intent: Intent?) { // if (Build.VERSION.SDK_INT >= 26) { // startForegroundService(intent) // } else { // startService(intent) // } //} val KClass<*>.intent: Intent get() = Intent(GlobalState.application, this.java) fun Service.startForegroundCompat(id: Int, notification: Notification) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { startForeground(id, notification, FOREGROUND_SERVICE_TYPE_SPECIAL_USE) } else { startForeground(id, notification) } } val ComponentName.intent: Intent get() = Intent().apply { setComponent(this@intent) setPackage(GlobalState.packageName) } val QuickAction.action: String get() = "${GlobalState.application.packageName}.action.${this.name}" val QuickAction.quickIntent: Intent get() = Components.TEMP_ACTIVITY.intent.apply { action = this@quickIntent.action addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_MULTIPLE_TASK) } val BroadcastAction.action: String get() = "${GlobalState.application.packageName}.intent.action.${this.name}" val Context.processName: String? get() { val pid = android.os.Process.myPid() val activityManager = getSystemService() activityManager?.runningAppProcesses?.find { it.pid == pid }?.let { return it.processName } return null } val BroadcastAction.quickIntent: Intent get() = Components.BROADCAST_RECEIVER.intent.apply { action = this@quickIntent.action } fun BroadcastAction.sendBroadcast() { val intent = Intent().apply { action = this@sendBroadcast.action Log.d("[sendBroadcast]", "$action") setPackage(GlobalState.packageName) } GlobalState.application.sendBroadcast( intent, GlobalState.RECEIVE_BROADCASTS_PERMISSIONS ) } val Intent.toPendingIntent: PendingIntent get() = PendingIntent.getActivity( GlobalState.application, 0, this, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT ) fun Service.startForeground(notification: Notification) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val manager = getSystemService(NotificationManager::class.java) var channel = manager?.getNotificationChannel(GlobalState.NOTIFICATION_CHANNEL) if (channel == null) { channel = NotificationChannel( GlobalState.NOTIFICATION_CHANNEL, "SERVICE_CHANNEL", NotificationManager.IMPORTANCE_LOW ) manager?.createNotificationChannel(channel) } } startForegroundCompat(GlobalState.NOTIFICATION_ID, notification) } @SuppressLint("UnspecifiedRegisterReceiverFlag") fun Context.registerReceiverCompat( receiver: BroadcastReceiver, filter: IntentFilter, ) = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { registerReceiver(receiver, filter, RECEIVER_NOT_EXPORTED) } else { registerReceiver(receiver, filter) } fun Context.receiveBroadcastFlow( configure: IntentFilter.() -> Unit, ): Flow = callbackFlow { val filter = IntentFilter().apply(configure) val receiver = object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { if (context == null || intent == null) return trySend(intent) } } registerReceiverCompat(receiver, filter) awaitClose { unregisterReceiver(receiver) } } inline fun Context.bindServiceFlow( intent: Intent, flags: Int = Context.BIND_AUTO_CREATE, maxRetries: Int = 10, retryDelayMillis: Long = 200L ): Flow> = callbackFlow { val connection = object : ServiceConnection { override fun onServiceConnected(name: ComponentName?, binder: IBinder?) { if (binder != null) { try { @Suppress("UNCHECKED_CAST") val casted = binder as? T if (casted != null) { trySend(Pair(casted, "")) } else { trySend(Pair(null, "Binder is not of type ${T::class.java}")) } } catch (e: RemoteException) { trySend(Pair(null, "Failed to link to death: ${e.message}")) } } else { trySend(Pair(null, "Binder empty")) } } override fun onServiceDisconnected(name: ComponentName?) { trySend(Pair(null, "Service disconnected")) } } val success = withContext(Dispatchers.Main) { bindService(intent, connection, flags) } if (!success) { throw IllegalStateException("bindService() failed, will retry") } awaitClose { Handler(Looper.getMainLooper()).post { unbindService(connection) trySend(Pair(null, "")) } } }.retryWhen { cause, attempt -> if (attempt < maxRetries && cause is Exception) { delay(retryDelayMillis) true } else { false } } val Long.formatBytes: String get() { val units = arrayOf("B", "KB", "MB", "GB", "TB") var size = this.toDouble() var unitIndex = 0 while (size >= 1024 && unitIndex < units.size - 1) { size /= 1024 unitIndex++ } return if (unitIndex == 0) { "${size.toLong()}${units[unitIndex]}" } else { "%.1f${units[unitIndex]}".format(size) } } fun String.chunkedForAidl(charset: Charset = Charsets.UTF_8): List { val allBytes = toByteArray(charset) val total = allBytes.size val maxBytes = when { total <= 100 * 1024 -> total total <= 1024 * 1024 -> 64 * 1024 total <= 10 * 1024 * 1024 -> 128 * 1024 else -> 256 * 1024 } val result = mutableListOf() var index = 0 while (index < total) { val end = minOf(index + maxBytes, total) result.add(allBytes.copyOfRange(index, end)) index = end } return result } fun > T.formatString(charset: Charset = Charsets.UTF_8): String { val totalSize = this.sumOf { it.size } val combined = ByteArray(totalSize) var offset = 0 forEach { byteArray -> byteArray.copyInto(combined, offset) offset += byteArray.size } return String(combined, charset) } ================================================ FILE: android/common/src/main/java/com/follow/clash/common/GlobalState.kt ================================================ package com.follow.clash.common import android.app.Application import android.util.Log import com.google.firebase.FirebaseApp import com.google.firebase.crashlytics.FirebaseCrashlytics import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers object GlobalState : CoroutineScope by CoroutineScope(Dispatchers.Default) { const val NOTIFICATION_CHANNEL = "FlClash" const val NOTIFICATION_ID = 1 val packageName: String get() = application.packageName val RECEIVE_BROADCASTS_PERMISSIONS: String get() = "${packageName}.permission.RECEIVE_BROADCASTS" private var _application: Application? = null val application: Application get() = _application!! fun log(text: String) { Log.d("[FlClash]", text) } fun init(application: Application) { _application = application } fun setCrashlytics(enable: Boolean) { _application?.let { FirebaseApp.initializeApp(it) FirebaseCrashlytics.getInstance().isCrashlyticsCollectionEnabled = enable if (enable) { log("init crashlytics ${it.processName}") } } } } ================================================ FILE: android/common/src/main/java/com/follow/clash/common/Service.kt ================================================ package com.follow.clash.common import android.content.Intent import android.os.IBinder import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeout import java.util.concurrent.atomic.AtomicBoolean class ServiceDelegate( private val intent: Intent, private val onServiceDisconnected: ((String) -> Unit)? = null, private val interfaceCreator: (IBinder) -> T, ) : CoroutineScope by CoroutineScope(SupervisorJob() + Dispatchers.Default) { private val _bindingState = AtomicBoolean(false) private var _serviceState = MutableStateFlow?>(null) val serviceState: StateFlow?> = _serviceState private var job: Job? = null private fun handleBind(data: Pair) { data.first?.let { _serviceState.value = Pair(interfaceCreator(it), data.second) } ?: run { _serviceState.value = Pair(null, data.second) unbind() onServiceDisconnected?.invoke(data.second) _bindingState.set(false) } } fun bind() { if (_bindingState.compareAndSet(false, true)) { job?.cancel() job = null _serviceState.value = null job = launch { runCatching { GlobalState.application.bindServiceFlow(intent) .collect { handleBind(it) } } } } } suspend inline fun useService( timeoutMillis: Long = 5000, crossinline block: suspend (T) -> R ): Result { return runCatching { withTimeout(timeoutMillis) { val state = serviceState.filterNotNull().first() state.first?.let { withContext(Dispatchers.Default) { block(it) } } ?: throw Exception(state.second) } } } fun unbind() { if (_bindingState.compareAndSet(true, false)) { job?.cancel() job = null _serviceState.value = null } } } ================================================ FILE: android/common/src/main/java/com/follow/clash/common/Utils.kt ================================================ package com.follow.clash.common import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow fun tickerFlow(delayMillis: Long, initialDelayMillis: Long = delayMillis): Flow = flow { delay(initialDelayMillis) while (true) { emit(Unit) delay(delayMillis) } } ================================================ FILE: android/common/src/main/res/values/strings.xml ================================================ FlClash ================================================ FILE: android/core/.gitignore ================================================ /build ================================================ FILE: android/core/build.gradle.kts ================================================ import org.jetbrains.kotlin.gradle.dsl.JvmTarget plugins { id("com.android.library") id("org.jetbrains.kotlin.android") } android { namespace = "com.follow.clash.core" compileSdk = libs.versions.compileSdk.get().toInt() ndkVersion = libs.versions.ndkVersion.get() defaultConfig { minSdk = libs.versions.minSdk.get().toInt() } sourceSets { getByName("main") { jniLibs.srcDirs("src/main/jniLibs") } } externalNativeBuild { cmake { path("src/main/cpp/CMakeLists.txt") version = "3.22.1" } } compileOptions { sourceCompatibility = JavaVersion.VERSION_17 targetCompatibility = JavaVersion.VERSION_17 } buildTypes { release { proguardFiles( getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro" ) } } } kotlin { compilerOptions { jvmTarget.set(JvmTarget.JVM_17) } } dependencies { implementation(libs.annotation.jvm) } val copyNativeLibs by tasks.register("copyNativeLibs") { doFirst { delete("src/main/jniLibs") } from("../../libclash/android") into("src/main/jniLibs") doLast { val includesDir = file("src/main/jniLibs/includes") val targetDir = file("src/main/cpp/includes") if (includesDir.exists()) { copy { from(includesDir) into(targetDir) } delete(includesDir) } } } afterEvaluate { tasks.named("preBuild") { dependsOn(copyNativeLibs) } } ================================================ FILE: android/core/src/main/AndroidManifest.xml ================================================ ================================================ FILE: android/core/src/main/cpp/CMakeLists.txt ================================================ cmake_minimum_required(VERSION 3.22.1) project("core") message("CMAKE_SOURCE_DIR ${CMAKE_SOURCE_DIR}") message("CMAKE_BUILD_TYPE ${CMAKE_BUILD_TYPE}") if (NOT "${CMAKE_BUILD_TYPE}" STREQUAL "Debug") set(CMAKE_BUILD_TYPE Release CACHE STRING "Build type" FORCE) add_compile_options(-O3 -flto -g0 -fno-exceptions -fno-rtti) add_link_options(-flto -Wl,--gc-sections,--strip-all) endif () set(LIB_CLASH_PATH "${CMAKE_SOURCE_DIR}/../jniLibs/${ANDROID_ABI}/libclash.so") message("LIB_CLASH_PATH ${LIB_CLASH_PATH}") if (EXISTS ${LIB_CLASH_PATH}) message("Found libclash.so for ABI ${ANDROID_ABI}") add_compile_definitions(LIBCLASH) include_directories(${CMAKE_SOURCE_DIR}/../cpp/includes/${ANDROID_ABI}) link_directories(${CMAKE_SOURCE_DIR}/../jniLibs/${ANDROID_ABI}) add_library(${CMAKE_PROJECT_NAME} SHARED jni_helper.cpp core.cpp) target_link_libraries(${CMAKE_PROJECT_NAME} clash) else () message("Not found libclash.so for ABI ${ANDROID_ABI}") add_library(${CMAKE_PROJECT_NAME} SHARED jni_helper.cpp core.cpp) target_link_libraries(${CMAKE_PROJECT_NAME}) endif () ================================================ FILE: android/core/src/main/cpp/core.cpp ================================================ #include #ifdef LIBCLASH #include "jni_helper.h" #include "libclash.h" #include "bride.h" extern "C" JNIEXPORT void JNICALL Java_com_follow_clash_core_Core_startTun(JNIEnv *env, jobject thiz, jint fd, jobject cb, jstring stack, jstring address, jstring dns) { const auto interface = new_global(cb); startTUN(interface, fd, get_string(stack), get_string(address), get_string(dns)); } extern "C" JNIEXPORT void JNICALL Java_com_follow_clash_core_Core_stopTun(JNIEnv *env, jobject thiz) { stopTun(); } extern "C" JNIEXPORT void JNICALL Java_com_follow_clash_core_Core_forceGC(JNIEnv *env, jobject thiz) { forceGC(); } extern "C" JNIEXPORT void JNICALL Java_com_follow_clash_core_Core_updateDNS(JNIEnv *env, jobject thiz, jstring dns) { updateDns(get_string(dns)); } extern "C" JNIEXPORT void JNICALL Java_com_follow_clash_core_Core_invokeAction(JNIEnv *env, jobject thiz, jstring data, jobject cb) { const auto interface = new_global(cb); invokeAction(interface, get_string(data)); } extern "C" JNIEXPORT void JNICALL Java_com_follow_clash_core_Core_setEventListener(JNIEnv *env, jobject thiz, jobject cb) { if (cb != nullptr) { const auto interface = new_global(cb); setEventListener(interface); } else { setEventListener(nullptr); } } extern "C" JNIEXPORT jstring JNICALL Java_com_follow_clash_core_Core_getTraffic(JNIEnv *env, jobject thiz, const jboolean only_statistics_proxy) { return new_string(getTraffic(only_statistics_proxy)); } extern "C" JNIEXPORT jstring JNICALL Java_com_follow_clash_core_Core_getTotalTraffic(JNIEnv *env, jobject thiz, const jboolean only_statistics_proxy) { return new_string(getTotalTraffic(only_statistics_proxy)); } extern "C" JNIEXPORT void JNICALL Java_com_follow_clash_core_Core_suspended(JNIEnv *env, jobject thiz, jboolean suspended) { suspend(suspended); } extern "C" JNIEXPORT void JNICALL Java_com_follow_clash_core_Core_quickSetup(JNIEnv *env, jobject thiz, jstring init_params_string, jstring setup_params_string, jobject cb) { const auto interface = new_global(cb); quickSetup(interface, get_string(init_params_string), get_string(setup_params_string)); } static jmethodID m_tun_interface_protect; static jmethodID m_tun_interface_resolve_process; static jmethodID m_invoke_interface_result; static void release_jni_object_impl(void *obj) { ATTACH_JNI(); del_global(static_cast(obj)); } static void free_string_impl(char *str) { free(str); } static void call_tun_interface_protect_impl(void *tun_interface, const int fd) { ATTACH_JNI(); env->CallVoidMethod(static_cast(tun_interface), m_tun_interface_protect, fd); } static char * call_tun_interface_resolve_process_impl(void *tun_interface, const int protocol, const char *source, const char *target, const int uid) { ATTACH_JNI(); const auto packageName = reinterpret_cast(env->CallObjectMethod( static_cast(tun_interface), m_tun_interface_resolve_process, protocol, new_string(source), new_string(target), uid)); return get_string(packageName); } static void call_invoke_interface_result_impl(void *invoke_interface, const char *data) { ATTACH_JNI(); env->CallVoidMethod(static_cast(invoke_interface), m_invoke_interface_result, new_string(data)); } extern "C" JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *) { JNIEnv *env = nullptr; if (vm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6) != JNI_OK) { return JNI_ERR; } initialize_jni(vm, env); const auto c_tun_interface = find_class("com/follow/clash/core/TunInterface"); const auto c_invoke_interface = find_class("com/follow/clash/core/InvokeInterface"); m_tun_interface_protect = find_method(c_tun_interface, "protect", "(I)V"); m_tun_interface_resolve_process = find_method(c_tun_interface, "resolverProcess", "(ILjava/lang/String;Ljava/lang/String;I)Ljava/lang/String;"); m_invoke_interface_result = find_method(c_invoke_interface, "onResult", "(Ljava/lang/String;)V"); protect_func = &call_tun_interface_protect_impl; resolve_process_func = &call_tun_interface_resolve_process_impl; result_func = &call_invoke_interface_result_impl; release_object_func = &release_jni_object_impl; free_string_func = &free_string_impl; return JNI_VERSION_1_6; } #else extern "C" JNIEXPORT void JNICALL Java_com_follow_clash_core_Core_startTun(JNIEnv *env, jobject thiz, jint fd, jobject cb, jstring stack, jstring address, jstring dns) { } extern "C" JNIEXPORT void JNICALL Java_com_follow_clash_core_Core_stopTun(JNIEnv *env, jobject thiz) { } extern "C" JNIEXPORT void JNICALL Java_com_follow_clash_core_Core_invokeAction(JNIEnv *env, jobject thiz, jstring data, jobject cb) { } extern "C" JNIEXPORT void JNICALL Java_com_follow_clash_core_Core_forceGC(JNIEnv *env, jobject thiz) { } extern "C" JNIEXPORT void JNICALL Java_com_follow_clash_core_Core_updateDNS(JNIEnv *env, jobject thiz, jstring dns) { } extern "C" JNIEXPORT void JNICALL Java_com_follow_clash_core_Core_setEventListener(JNIEnv *env, jobject thiz, jobject cb) { } extern "C" JNIEXPORT jstring JNICALL Java_com_follow_clash_core_Core_getTraffic(JNIEnv *env, jobject thiz, const jboolean only_statistics_proxy) { } extern "C" JNIEXPORT jstring JNICALL Java_com_follow_clash_core_Core_getTotalTraffic(JNIEnv *env, jobject thiz, const jboolean only_statistics_proxy) { } extern "C" JNIEXPORT void JNICALL Java_com_follow_clash_core_Core_suspended(JNIEnv *env, jobject thiz, jboolean suspended) { } extern "C" JNIEXPORT void JNICALL Java_com_follow_clash_core_Core_quickSetup(JNIEnv *env, jobject thiz, jstring init_params_string, jstring setup_params_string, jobject cb) { } #endif ================================================ FILE: android/core/src/main/cpp/jni_helper.cpp ================================================ #include "jni_helper.h" #include #include #include static JavaVM *global_vm; static jclass c_string; static jmethodID m_new_string; static jmethodID m_get_bytes; void initialize_jni(JavaVM *vm, JNIEnv *env) { global_vm = vm; c_string = reinterpret_cast(new_global(find_class("java/lang/String"))); m_new_string = find_method(c_string, "", "([B)V"); m_get_bytes = find_method(c_string, "getBytes", "()[B"); } JavaVM *global_java_vm() { return global_vm; } char *jni_get_string(JNIEnv *env, jstring str) { const auto array = reinterpret_cast(env->CallObjectMethod(str, m_get_bytes)); const int length = env->GetArrayLength(array); const auto content = static_cast(malloc(length + 1)); env->GetByteArrayRegion(array, 0, length, reinterpret_cast(content)); content[length] = 0; return content; } jstring jni_new_string(JNIEnv *env, const char *str) { const auto length = static_cast(strlen(str)); const auto array = env->NewByteArray(length); env->SetByteArrayRegion(array, 0, length, reinterpret_cast(str)); return reinterpret_cast(env->NewObject(c_string, m_new_string, array)); } int jni_catch_exception(JNIEnv *env) { const int result = env->ExceptionCheck(); if (result) { env->ExceptionDescribe(); env->ExceptionClear(); } return result; } void jni_attach_thread(scoped_jni *jni) { JavaVM *vm = global_java_vm(); if (vm->GetEnv(reinterpret_cast(&jni->env), JNI_VERSION_1_6) == JNI_OK) { jni->require_release = 0; return; } if (vm->AttachCurrentThread(&jni->env, nullptr) != JNI_OK) { abort(); } jni->require_release = 1; } void jni_detach_thread(const scoped_jni *env) { JavaVM *vm = global_java_vm(); if (env->require_release) { vm->DetachCurrentThread(); } } void release_string(char **str) { free(*str); } ================================================ FILE: android/core/src/main/cpp/jni_helper.h ================================================ #pragma once #include struct scoped_jni { JNIEnv *env; int require_release; }; extern void initialize_jni(JavaVM *vm, JNIEnv *env); extern jstring jni_new_string(JNIEnv *env, const char *str); extern char *jni_get_string(JNIEnv *env, jstring str); extern int jni_catch_exception(JNIEnv *env); extern void jni_attach_thread(scoped_jni *jni); extern void jni_detach_thread(const scoped_jni *env); extern void release_string( char **str); #define ATTACH_JNI() __attribute__((unused, cleanup(jni_detach_thread))) \ scoped_jni _jni{}; \ jni_attach_thread(&_jni); \ JNIEnv *env = _jni.env #define scoped_string __attribute__((cleanup(release_string))) char* #define find_class(name) env->FindClass(name) #define find_method(cls, name, signature) env->GetMethodID(cls, name, signature) #define new_global(obj) env->NewGlobalRef(obj) #define del_global(obj) env->DeleteGlobalRef(obj) #define get_string(jstr) jni_get_string(env, jstr) #define new_string(cstr) jni_new_string(env, cstr) ================================================ FILE: android/core/src/main/java/com/follow/clash/core/Core.kt ================================================ package com.follow.clash.core import java.net.InetAddress import java.net.InetSocketAddress import java.net.URL data object Core { private external fun startTun( fd: Int, cb: TunInterface, stack: String, address: String, dns: String, ) external fun forceGC( ) external fun updateDNS( dns: String, ) private fun parseInetSocketAddress(address: String): InetSocketAddress { val url = URL("https://$address") return InetSocketAddress(InetAddress.getByName(url.host), url.port) } fun startTun( fd: Int, protect: (Int) -> Boolean, resolverProcess: (protocol: Int, source: InetSocketAddress, target: InetSocketAddress, uid: Int) -> String, stack: String, address: String, dns: String, ) { startTun( fd, object : TunInterface { override fun protect(fd: Int) { protect(fd) } override fun resolverProcess( protocol: Int, source: String, target: String, uid: Int ): String { return resolverProcess( protocol, parseInetSocketAddress(source), parseInetSocketAddress(target), uid, ) } }, stack, address, dns ) } external fun suspended( suspended: Boolean, ) private external fun invokeAction( data: String, cb: InvokeInterface ) fun invokeAction( data: String, cb: (result: String?) -> Unit ) { invokeAction( data, object : InvokeInterface { override fun onResult(result: String?) { cb(result) } }, ) } private external fun setEventListener(cb: InvokeInterface?) fun callSetEventListener( cb: ((result: String?) -> Unit)? ) { when (cb != null) { true -> setEventListener( object : InvokeInterface { override fun onResult(result: String?) { cb(result) } }, ) false -> setEventListener(null) } } fun quickSetup( initParamsString: String, setupParamsString: String, cb: (result: String?) -> Unit, ) { quickSetup( initParamsString, setupParamsString, object : InvokeInterface { override fun onResult(result: String?) { cb(result) } }, ) } private external fun quickSetup( initParamsString: String, setupParamsString: String, cb: InvokeInterface ) external fun stopTun() external fun getTraffic(onlyStatisticsProxy: Boolean): String external fun getTotalTraffic(onlyStatisticsProxy: Boolean): String init { System.loadLibrary("core") } } ================================================ FILE: android/core/src/main/java/com/follow/clash/core/InvokeInterface.kt ================================================ package com.follow.clash.core import androidx.annotation.Keep @Keep interface InvokeInterface { fun onResult(result: String?) } ================================================ FILE: android/core/src/main/java/com/follow/clash/core/TunInterface.kt ================================================ package com.follow.clash.core import androidx.annotation.Keep @Keep interface TunInterface { fun protect(fd: Int) fun resolverProcess(protocol: Int, source: String, target: String, uid: Int): String } ================================================ FILE: android/gradle/libs.versions.toml ================================================ [versions] #agp = "8.10.1" firebaseBom = "34.2.0" minSdk = "23" targetSdk = "36" compileSdk = "36" ndkVersion = "28.0.13004108" coreKtx = "1.17.0" annotationJvm = "1.9.1" coreSplashscreen = "1.0.1" gson = "2.13.1" kotlin = "2.2.10" smaliDexlib2 = "3.0.9" firebaseCrashlyticsKtx = "20.0.1" firebaseCommonKtx = "22.0.0" [libraries] build-kotlin = { module = "org.jetbrains.kotlin:kotlin-gradle-plugin", version.ref = "kotlin" } androidx-core = { module = "androidx.core:core-ktx", version.ref = "coreKtx" } annotation-jvm = { module = "androidx.annotation:annotation-jvm", version.ref = "annotationJvm" } core-splashscreen = { module = "androidx.core:core-splashscreen", version.ref = "coreSplashscreen" } firebase-analytics = { module = "com.google.firebase:firebase-analytics" } firebase-bom = { module = "com.google.firebase:firebase-bom", version.ref = "firebaseBom" } firebase-crashlytics-ndk = { module = "com.google.firebase:firebase-crashlytics-ndk" } gson = { module = "com.google.code.gson:gson", version.ref = "gson" } smali-dexlib2 = { module = "com.android.tools.smali:smali-dexlib2", version.ref = "smaliDexlib2" } firebase-crashlytics-ktx = { group = "com.google.firebase", name = "firebase-crashlytics-ktx", version.ref = "firebaseCrashlyticsKtx" } firebase-common-ktx = { group = "com.google.firebase", name = "firebase-common-ktx", version.ref = "firebaseCommonKtx" } ================================================ FILE: android/gradle/wrapper/gradle-wrapper.properties ================================================ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-all.zip ================================================ FILE: android/gradle.properties ================================================ org.gradle.jvmargs=-Xmx4G android.useAndroidX=true android.enableJetifier=true ================================================ FILE: android/service/.gitignore ================================================ /build ================================================ FILE: android/service/build.gradle.kts ================================================ import org.jetbrains.kotlin.gradle.dsl.JvmTarget plugins { id("com.android.library") id("org.jetbrains.kotlin.android") id("kotlin-parcelize") } android { namespace = "com.follow.clash.service" compileSdk = 36 defaultConfig { minSdk = libs.versions.minSdk.get().toInt() } buildFeatures { aidl = true } compileOptions { sourceCompatibility = JavaVersion.VERSION_17 targetCompatibility = JavaVersion.VERSION_17 } buildTypes { release { proguardFiles( getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro" ) } } } kotlin { compilerOptions { jvmTarget.set(JvmTarget.JVM_17) } } dependencies { implementation(project(":core")) implementation(project(":common")) implementation(libs.gson) implementation(libs.androidx.core) } ================================================ FILE: android/service/src/main/AndroidManifest.xml ================================================ ================================================ FILE: android/service/src/main/aidl/com/follow/clash/service/IAckInterface.aidl ================================================ // IAckInterface.aidl package com.follow.clash.service; import com.follow.clash.service.IAckInterface; interface IAckInterface { oneway void onAck(); } ================================================ FILE: android/service/src/main/aidl/com/follow/clash/service/ICallbackInterface.aidl ================================================ // ICallbackInterface.aidl package com.follow.clash.service; import com.follow.clash.service.IAckInterface; interface ICallbackInterface { oneway void onResult(in byte[] data,in boolean isSuccess, in IAckInterface ack); } ================================================ FILE: android/service/src/main/aidl/com/follow/clash/service/IEventInterface.aidl ================================================ // IEventInterface.aidl package com.follow.clash.service; import com.follow.clash.service.IAckInterface; interface IEventInterface { oneway void onEvent(in String id, in byte[] data,in boolean isSuccess, in IAckInterface ack); } ================================================ FILE: android/service/src/main/aidl/com/follow/clash/service/IRemoteInterface.aidl ================================================ // IRemoteInterface.aidl package com.follow.clash.service; import com.follow.clash.service.ICallbackInterface; import com.follow.clash.service.IEventInterface; import com.follow.clash.service.IResultInterface; import com.follow.clash.service.IVoidInterface; import com.follow.clash.service.models.VpnOptions; import com.follow.clash.service.models.NotificationParams; interface IRemoteInterface { void invokeAction(in String data, in ICallbackInterface callback); void quickSetup(in String initParamsString, in String setupParamsString, in ICallbackInterface callback, in IVoidInterface onStarted); void updateNotificationParams(in NotificationParams params); void startService(in VpnOptions options, in long runTime, in IResultInterface result); void stopService(in IResultInterface result); void setEventListener(in IEventInterface event); void setCrashlytics(in boolean enable); long getRunTime(); } ================================================ FILE: android/service/src/main/aidl/com/follow/clash/service/IResultInterface.aidl ================================================ // IResultInterface.aidl package com.follow.clash.service; interface IResultInterface { oneway void onResult(in long runTime); } ================================================ FILE: android/service/src/main/aidl/com/follow/clash/service/IVoidInterface.aidl ================================================ // IVoidInterface.aidl package com.follow.clash.service; interface IVoidInterface { oneway void invoke(); } ================================================ FILE: android/service/src/main/aidl/com/follow/clash/service/models/AccessControl.aidl ================================================ //AccessControl.aidl package com.follow.clash.service.models; parcelable AccessControl; ================================================ FILE: android/service/src/main/aidl/com/follow/clash/service/models/NotificationParams.aidl ================================================ //NotificationParams.aidl package com.follow.clash.service.models; parcelable NotificationParams; ================================================ FILE: android/service/src/main/aidl/com/follow/clash/service/models/VpnOptions.aidl ================================================ //VpnOptions.aidl package com.follow.clash.service.models; import com.follow.clash.service.models.AccessControl; parcelable VpnOptions; ================================================ FILE: android/service/src/main/java/com/follow/clash/service/CommonService.kt ================================================ package com.follow.clash.service import android.app.Service import android.content.Intent import android.os.Binder import android.os.IBinder import com.follow.clash.core.Core import com.follow.clash.service.modules.NetworkObserveModule import com.follow.clash.service.modules.NotificationModule import com.follow.clash.service.modules.SuspendModule import com.follow.clash.service.modules.moduleLoader import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers class CommonService : Service(), IBaseService, CoroutineScope by CoroutineScope(Dispatchers.Default) { private val self: CommonService get() = this private val loader = moduleLoader { install(NetworkObserveModule(self)) install(NotificationModule(self)) install(SuspendModule(self)) } override fun onCreate() { super.onCreate() handleCreate() } override fun onDestroy() { handleDestroy() super.onDestroy() } override fun onLowMemory() { Core.forceGC() super.onLowMemory() } private val binder = LocalBinder() inner class LocalBinder : Binder() { fun getService(): CommonService = this@CommonService } override fun onBind(intent: Intent): IBinder { return binder } override fun start() { try { loader.load() } catch (_: Exception) { stop() } } override fun stop() { loader.cancel() stopSelf() } } ================================================ FILE: android/service/src/main/java/com/follow/clash/service/FilesProvider.kt ================================================ package com.follow.clash.service import android.database.Cursor import android.database.MatrixCursor import android.os.CancellationSignal import android.os.ParcelFileDescriptor import android.provider.DocumentsContract import android.provider.DocumentsProvider import java.io.File import java.io.FileNotFoundException class FilesProvider : DocumentsProvider() { companion object { private const val DEFAULT_ROOT_ID = "0" private val DEFAULT_DOCUMENT_COLUMNS = arrayOf( DocumentsContract.Document.COLUMN_DOCUMENT_ID, DocumentsContract.Document.COLUMN_DISPLAY_NAME, DocumentsContract.Document.COLUMN_MIME_TYPE, DocumentsContract.Document.COLUMN_FLAGS, DocumentsContract.Document.COLUMN_SIZE, ) private val DEFAULT_ROOT_COLUMNS = arrayOf( DocumentsContract.Root.COLUMN_ROOT_ID, DocumentsContract.Root.COLUMN_FLAGS, DocumentsContract.Root.COLUMN_ICON, DocumentsContract.Root.COLUMN_TITLE, DocumentsContract.Root.COLUMN_SUMMARY, DocumentsContract.Root.COLUMN_DOCUMENT_ID ) } override fun onCreate(): Boolean { return true } override fun queryRoots(projection: Array?): Cursor { return MatrixCursor(projection ?: DEFAULT_ROOT_COLUMNS).apply { newRow().apply { add(DocumentsContract.Root.COLUMN_ROOT_ID, DEFAULT_ROOT_ID) add(DocumentsContract.Root.COLUMN_FLAGS, DocumentsContract.Root.FLAG_LOCAL_ONLY) add(DocumentsContract.Root.COLUMN_ICON, R.drawable.ic_service) add(DocumentsContract.Root.COLUMN_TITLE, "FlClash") add(DocumentsContract.Root.COLUMN_SUMMARY, "Data") add(DocumentsContract.Root.COLUMN_DOCUMENT_ID, "/") } } } override fun queryChildDocuments( parentDocumentId: String, projection: Array?, sortOrder: String? ): Cursor { val result = MatrixCursor(resolveDocumentProjection(projection)) val parentFile = if (parentDocumentId == "/") { context?.filesDir } else { File(parentDocumentId) } ?: throw FileNotFoundException("Parent directory not found") parentFile.listFiles()?.forEach { file -> includeFile(result, file) } return result } override fun queryDocument(documentId: String, projection: Array?): Cursor { val result = MatrixCursor(resolveDocumentProjection(projection)) val file = File(documentId) includeFile(result, file) return result } override fun openDocument( documentId: String, mode: String, signal: CancellationSignal? ): ParcelFileDescriptor { val file = File(documentId) val accessMode = ParcelFileDescriptor.parseMode(mode) return ParcelFileDescriptor.open(file, accessMode) } private fun includeFile(result: MatrixCursor, file: File) { result.newRow().apply { add(DocumentsContract.Document.COLUMN_DOCUMENT_ID, file.absolutePath) add(DocumentsContract.Document.COLUMN_DISPLAY_NAME, file.name) add(DocumentsContract.Document.COLUMN_SIZE, file.length()) add( DocumentsContract.Document.COLUMN_FLAGS, DocumentsContract.Document.FLAG_SUPPORTS_WRITE or DocumentsContract.Document.FLAG_SUPPORTS_DELETE ) add(DocumentsContract.Document.COLUMN_MIME_TYPE, getDocumentType(file)) } } private fun getDocumentType(file: File): String { return if (file.isDirectory) { DocumentsContract.Document.MIME_TYPE_DIR } else { "application/octet-stream" } } private fun resolveDocumentProjection(projection: Array?): Array { return projection ?: DEFAULT_DOCUMENT_COLUMNS } } ================================================ FILE: android/service/src/main/java/com/follow/clash/service/IBaseService.kt ================================================ package com.follow.clash.service import com.follow.clash.common.BroadcastAction import com.follow.clash.common.GlobalState import com.follow.clash.common.sendBroadcast interface IBaseService { fun handleCreate() { GlobalState.log("Service create") BroadcastAction.SERVICE_CREATED.sendBroadcast() } fun handleDestroy() { GlobalState.log("Service destroy") BroadcastAction.SERVICE_DESTROYED.sendBroadcast() } fun start() fun stop() } ================================================ FILE: android/service/src/main/java/com/follow/clash/service/RemoteService.kt ================================================ package com.follow.clash.service import android.app.Service import android.content.Intent import android.os.IBinder import com.follow.clash.common.GlobalState import com.follow.clash.common.ServiceDelegate import com.follow.clash.common.chunkedForAidl import com.follow.clash.common.intent import com.follow.clash.core.Core import com.follow.clash.service.State.delegate import com.follow.clash.service.State.intent import com.follow.clash.service.State.runLock import com.follow.clash.service.models.NotificationParams import com.follow.clash.service.models.VpnOptions import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.launch import kotlinx.coroutines.suspendCancellableCoroutine import kotlinx.coroutines.sync.withLock import java.util.UUID import kotlin.coroutines.resume class RemoteService : Service(), CoroutineScope by CoroutineScope(SupervisorJob() + Dispatchers.Default) { private fun handleStopService(result: IResultInterface) { launch { runLock.withLock { delegate?.useService { service -> service.stop() delegate?.unbind() } State.runTime = 0 result.onResult(0) } } } private fun handleServiceDisconnected(message: String) { GlobalState.log("Background service disconnected: $message") intent = null delegate = null } private fun handleStartService(runTime: Long, result: IResultInterface) { launch { runLock.withLock { val nextIntent = when (State.options?.enable == true) { true -> VpnService::class.intent false -> CommonService::class.intent } if (intent != nextIntent) { delegate?.unbind() delegate = ServiceDelegate(nextIntent, ::handleServiceDisconnected) { binder -> when (binder) { is VpnService.LocalBinder -> binder.getService() is CommonService.LocalBinder -> binder.getService() else -> throw IllegalArgumentException("Invalid binder type") } } intent = nextIntent delegate?.bind() } delegate?.useService { service -> service.start() } State.runTime = when (runTime != 0L) { true -> runTime false -> System.currentTimeMillis() } result.onResult(State.runTime) } } } private val binder = object : IRemoteInterface.Stub() { override fun invokeAction(data: String, callback: ICallbackInterface) { Core.invokeAction(data) { launch { runCatching { val chunks = it?.chunkedForAidl() ?: listOf() for ((index, chunk) in chunks.withIndex()) { suspendCancellableCoroutine { cont -> callback.onResult( chunk, index == chunks.lastIndex, object : IAckInterface.Stub() { override fun onAck() { cont.resume(Unit) } }, ) } } } } } } override fun quickSetup( initParamsString: String, setupParamsString: String, callback: ICallbackInterface, onStarted: IVoidInterface ) { Core.quickSetup(initParamsString, setupParamsString) { launch { runCatching { val chunks = it?.chunkedForAidl() ?: listOf() for ((index, chunk) in chunks.withIndex()) { suspendCancellableCoroutine { cont -> callback.onResult( chunk, index == chunks.lastIndex, object : IAckInterface.Stub() { override fun onAck() { cont.resume(Unit) } }, ) } } } } } onStarted() } override fun updateNotificationParams(params: NotificationParams?) { State.notificationParamsFlow.tryEmit(params) } override fun startService( options: VpnOptions, runtime: Long, result: IResultInterface, ) { GlobalState.log("remote startService") State.options = options handleStartService(runtime, result) } override fun stopService(result: IResultInterface) { handleStopService(result) } override fun setEventListener(eventListener: IEventInterface?) { GlobalState.log("RemoveEventListener ${eventListener == null}") when (eventListener != null) { true -> Core.callSetEventListener { launch { runCatching { val id = UUID.randomUUID().toString() val chunks = it?.chunkedForAidl() ?: listOf() for ((index, chunk) in chunks.withIndex()) { suspendCancellableCoroutine { cont -> eventListener.onEvent( id, chunk, index == chunks.lastIndex, object : IAckInterface.Stub() { override fun onAck() { cont.resume(Unit) } }, ) } } } } } false -> Core.callSetEventListener(null) } } override fun setCrashlytics(enable: Boolean) { GlobalState.setCrashlytics(enable) } override fun getRunTime(): Long { return State.runTime } } override fun onBind(intent: Intent?): IBinder { return binder } override fun onDestroy() { GlobalState.log("Remote service destroy") super.onDestroy() } } ================================================ FILE: android/service/src/main/java/com/follow/clash/service/State.kt ================================================ package com.follow.clash.service import android.content.Intent import com.follow.clash.common.ServiceDelegate import com.follow.clash.service.models.NotificationParams import com.follow.clash.service.models.VpnOptions import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.sync.Mutex object State { var options: VpnOptions? = null var notificationParamsFlow: MutableStateFlow = MutableStateFlow( NotificationParams() ) val runLock = Mutex() var runTime: Long = 0L var delegate: ServiceDelegate? = null var intent: Intent? = null } ================================================ FILE: android/service/src/main/java/com/follow/clash/service/VpnService.kt ================================================ package com.follow.clash.service import android.content.Intent import android.net.ConnectivityManager import android.net.ProxyInfo import android.os.Binder import android.os.Build import android.os.IBinder import android.os.Parcel import android.os.RemoteException import android.util.Log import androidx.core.content.getSystemService import com.follow.clash.common.AccessControlMode import com.follow.clash.common.GlobalState import com.follow.clash.core.Core import com.follow.clash.service.models.VpnOptions import com.follow.clash.service.models.getIpv4RouteAddress import com.follow.clash.service.models.getIpv6RouteAddress import com.follow.clash.service.models.toCIDR import com.follow.clash.service.modules.NetworkObserveModule import com.follow.clash.service.modules.NotificationModule import com.follow.clash.service.modules.SuspendModule import com.follow.clash.service.modules.moduleLoader import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import java.net.InetSocketAddress import android.net.VpnService as SystemVpnService class VpnService : SystemVpnService(), IBaseService, CoroutineScope by CoroutineScope(Dispatchers.Default) { private val self: VpnService get() = this private val loader = moduleLoader { install(NetworkObserveModule(self)) install(NotificationModule(self)) install(SuspendModule(self)) } override fun onCreate() { super.onCreate() handleCreate() } override fun onDestroy() { handleDestroy() super.onDestroy() } private val connectivity by lazy { getSystemService() } private val uidPageNameMap = mutableMapOf() private fun resolverProcess( protocol: Int, source: InetSocketAddress, target: InetSocketAddress, uid: Int, ): String { val nextUid = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { connectivity?.getConnectionOwnerUid(protocol, source, target) ?: -1 } else { uid } if (nextUid == -1) { return "" } if (!uidPageNameMap.containsKey(nextUid)) { uidPageNameMap[nextUid] = this.packageManager?.getPackagesForUid(nextUid)?.first() ?: "" } return uidPageNameMap[nextUid] ?: "" } val VpnOptions.address get(): String = buildString { append(IPV4_ADDRESS) if (ipv6) { append(",") append(IPV6_ADDRESS) } } val VpnOptions.dns get(): String { if (dnsHijacking) { return NET_ANY } return buildString { append(DNS) if (ipv6) { append(",") append(DNS6) } } } override fun onLowMemory() { Core.forceGC() super.onLowMemory() } private val binder = LocalBinder() inner class LocalBinder : Binder() { fun getService(): VpnService = this@VpnService override fun onTransact(code: Int, data: Parcel, reply: Parcel?, flags: Int): Boolean { try { val isSuccess = super.onTransact(code, data, reply, flags) if (!isSuccess) { GlobalState.log("VpnService disconnected") handleDestroy() } return isSuccess } catch (e: RemoteException) { GlobalState.log("VpnService onTransact $e") return false } } } override fun onBind(intent: Intent): IBinder { return binder } private fun handleStart(options: VpnOptions) { val fd = with(Builder()) { val cidr = IPV4_ADDRESS.toCIDR() addAddress(cidr.address, cidr.prefixLength) Log.d( "addAddress", "address: ${cidr.address} prefixLength:${cidr.prefixLength}" ) val routeAddress = options.getIpv4RouteAddress() if (routeAddress.isNotEmpty()) { try { routeAddress.forEach { i -> Log.d( "addRoute4", "address: ${i.address} prefixLength:${i.prefixLength}" ) addRoute(i.address, i.prefixLength) } } catch (_: Exception) { addRoute(NET_ANY, 0) } } else { addRoute(NET_ANY, 0) } if (options.ipv6) { try { val cidr = IPV6_ADDRESS.toCIDR() Log.d( "addAddress6", "address: ${cidr.address} prefixLength:${cidr.prefixLength}" ) addAddress(cidr.address, cidr.prefixLength) } catch (_: Exception) { Log.d( "addAddress6", "IPv6 is not supported." ) } try { val routeAddress = options.getIpv6RouteAddress() if (routeAddress.isNotEmpty()) { try { routeAddress.forEach { i -> Log.d( "addRoute6", "address: ${i.address} prefixLength:${i.prefixLength}" ) addRoute(i.address, i.prefixLength) } } catch (_: Exception) { addRoute("::", 0) } } else { addRoute(NET_ANY6, 0) } } catch (_: Exception) { addRoute(NET_ANY6, 0) } } addDnsServer(DNS) if (options.ipv6) { addDnsServer(DNS6) } setMtu(9000) options.accessControlProps.let { accessControl -> if (accessControl.enable) { when (accessControl.mode) { AccessControlMode.ACCEPT_SELECTED -> { (accessControl.acceptList + packageName).forEach { addAllowedApplication(it) } } AccessControlMode.REJECT_SELECTED -> { (accessControl.rejectList - packageName).forEach { addDisallowedApplication(it) } } } } } setSession("FlClash") setBlocking(false) if (Build.VERSION.SDK_INT >= 29) { setMetered(false) } if (options.allowBypass) { allowBypass() } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && options.systemProxy) { GlobalState.log("Open http proxy") setHttpProxy( ProxyInfo.buildDirectProxy( "127.0.0.1", options.port, options.bypassDomain ) ) } establish()?.detachFd() ?: throw NullPointerException("Establish VPN rejected by system") } Core.startTun( fd, protect = this::protect, resolverProcess = this::resolverProcess, options.stack, options.address, options.dns ) } override fun start() { try { loader.load() State.options?.let { handleStart(it) } } catch (_: Exception) { stop() } } override fun stop() { loader.cancel() Core.stopTun() stopSelf() } companion object { private const val IPV4_ADDRESS = "172.19.0.1/30" private const val IPV6_ADDRESS = "fdfe:dcba:9876::1/126" private const val DNS = "172.19.0.2" private const val DNS6 = "fdfe:dcba:9876::2" private const val NET_ANY = "0.0.0.0" private const val NET_ANY6 = "::" } } ================================================ FILE: android/service/src/main/java/com/follow/clash/service/models/NotificationParams.kt ================================================ package com.follow.clash.service.models import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize data class NotificationParams( val title: String = "FlClash", val stopText: String = "STOP", val onlyStatisticsProxy: Boolean = false, ) : Parcelable ================================================ FILE: android/service/src/main/java/com/follow/clash/service/models/Traffic.kt ================================================ package com.follow.clash.service.models import com.follow.clash.common.GlobalState import com.follow.clash.common.formatBytes import com.follow.clash.core.Core import com.google.gson.Gson data class Traffic( val up: Long, val down: Long, ) val Traffic.speedText: String get() = "${up.formatBytes}/s↑ ${down.formatBytes}/s↓" fun Core.getSpeedTrafficText(onlyStatisticsProxy: Boolean): String { try { val res = getTraffic(onlyStatisticsProxy) val traffic = Gson().fromJson(res, Traffic::class.java) return traffic.speedText } catch (e: Exception) { GlobalState.log(e.message + "") return "" } } ================================================ FILE: android/service/src/main/java/com/follow/clash/service/models/VpnOptions.kt ================================================ package com.follow.clash.service.models import android.os.Parcelable import com.follow.clash.common.AccessControlMode import kotlinx.parcelize.Parcelize import java.net.InetAddress @Parcelize data class AccessControlProps( val enable: Boolean, val mode: AccessControlMode, val acceptList: List, val rejectList: List, ) : Parcelable @Parcelize data class VpnOptions( val enable: Boolean, val port: Int, val ipv6: Boolean, val dnsHijacking: Boolean, val accessControlProps: AccessControlProps, val allowBypass: Boolean, val systemProxy: Boolean, val bypassDomain: List, val stack: String, val routeAddress: List, ) : Parcelable data class CIDR(val address: InetAddress, val prefixLength: Int) fun VpnOptions.getIpv4RouteAddress(): List { return routeAddress.filter { it.isIpv4() }.map { it.toCIDR() } } fun VpnOptions.getIpv6RouteAddress(): List { return routeAddress.filter { it.isIpv6() }.map { it.toCIDR() } } fun String.isIpv4(): Boolean { val parts = split("/") if (parts.size != 2) { throw IllegalArgumentException("Invalid CIDR format") } val address = InetAddress.getByName(parts[0]) return address.address.size == 4 } fun String.isIpv6(): Boolean { val parts = split("/") if (parts.size != 2) { throw IllegalArgumentException("Invalid CIDR format") } val address = InetAddress.getByName(parts[0]) return address.address.size == 16 } fun String.toCIDR(): CIDR { val parts = split("/") if (parts.size != 2) { throw IllegalArgumentException("Invalid CIDR format") } val ipAddress = parts[0] val prefixLength = parts[1].toIntOrNull() ?: throw IllegalArgumentException("Invalid prefix length") val address = InetAddress.getByName(ipAddress) val maxPrefix = if (address.address.size == 4) 32 else 128 if (prefixLength < 0 || prefixLength > maxPrefix) { throw IllegalArgumentException("Invalid prefix length for IP version") } return CIDR(address, prefixLength) } ================================================ FILE: android/service/src/main/java/com/follow/clash/service/modules/Module.kt ================================================ package com.follow.clash.service.modules abstract class Module { private var isInstall: Boolean = false protected abstract fun onInstall() protected abstract fun onUninstall() fun install() { isInstall = true onInstall() } fun uninstall() { onUninstall() isInstall = false } } ================================================ FILE: android/service/src/main/java/com/follow/clash/service/modules/ModuleLoader.kt ================================================ package com.follow.clash.service.modules import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock interface ModuleLoaderScope { fun install(module: T): T } interface ModuleLoader { fun load() fun cancel() } private val mutex = Mutex() fun CoroutineScope.moduleLoader(block: suspend ModuleLoaderScope.() -> Unit): ModuleLoader { val modules = mutableListOf() var job: Job? = null return object : ModuleLoader { override fun load() { job = launch(Dispatchers.IO) { mutex.withLock { val scope = object : ModuleLoaderScope { override fun install(module: T): T { modules.add(module) module.install() return module } } scope.block() } } } override fun cancel() { launch(Dispatchers.IO) { job?.cancel() mutex.withLock { modules.asReversed().forEach { it.uninstall() } modules.clear() } } } } } ================================================ FILE: android/service/src/main/java/com/follow/clash/service/modules/NetworkObserveModule.kt ================================================ package com.follow.clash.service.modules import android.app.Service import android.net.ConnectivityManager import android.net.LinkProperties import android.net.Network import android.net.NetworkCapabilities import android.net.NetworkCapabilities.TRANSPORT_SATELLITE import android.net.NetworkCapabilities.TRANSPORT_USB import android.net.NetworkRequest import android.os.Build import androidx.core.content.getSystemService import com.follow.clash.core.Core import java.net.Inet4Address import java.net.Inet6Address import java.net.InetAddress import java.util.concurrent.ConcurrentHashMap private data class NetworkInfo( @Volatile var losingMs: Long = 0, @Volatile var dnsList: List = emptyList() ) { fun isAvailable(): Boolean = losingMs < System.currentTimeMillis() } class NetworkObserveModule(private val service: Service) : Module() { private val networkInfos = ConcurrentHashMap() private val connectivity by lazy { service.getSystemService() } private var preDnsList = listOf() private val request = NetworkRequest.Builder().apply { addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN) addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { addCapability(NetworkCapabilities.NET_CAPABILITY_FOREGROUND) } addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED) }.build() private val callback = object : ConnectivityManager.NetworkCallback() { override fun onAvailable(network: Network) { networkInfos[network] = NetworkInfo() onUpdateNetwork() super.onAvailable(network) } override fun onLosing(network: Network, maxMsToLive: Int) { networkInfos[network]?.losingMs = System.currentTimeMillis() + maxMsToLive onUpdateNetwork() setUnderlyingNetworks(network) super.onLosing(network, maxMsToLive) } override fun onLost(network: Network) { networkInfos.remove(network) onUpdateNetwork() setUnderlyingNetworks(network) super.onLost(network) } override fun onLinkPropertiesChanged(network: Network, linkProperties: LinkProperties) { networkInfos[network]?.dnsList = linkProperties.dnsServers onUpdateNetwork() setUnderlyingNetworks(network) super.onLinkPropertiesChanged(network, linkProperties) } } override fun onInstall() { onUpdateNetwork() connectivity?.registerNetworkCallback(request, callback) } private fun networkToInt(entry: Map.Entry): Int { val capabilities = connectivity?.getNetworkCapabilities(entry.key) return when { capabilities == null -> 100 capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN) -> 90 capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> 0 capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> 1 Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && capabilities.hasTransport( TRANSPORT_USB ) -> 2 capabilities.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH) -> 3 capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> 4 Build.VERSION.SDK_INT >= Build.VERSION_CODES.VANILLA_ICE_CREAM && capabilities.hasTransport( TRANSPORT_SATELLITE ) -> 5 else -> 20 } + (if (entry.value.isAvailable()) 0 else 10) } fun onUpdateNetwork() { val dnsList = (networkInfos.asSequence().minByOrNull { networkToInt(it) }?.value?.dnsList ?: emptyList()).map { x -> x.asSocketAddressText(53) } if (dnsList == preDnsList) { return } preDnsList = dnsList Core.updateDNS(dnsList.toSet().joinToString(",")) } fun setUnderlyingNetworks(network: Network) { // if (service is VpnService && Build.VERSION.SDK_INT in 22..28) { // service.setUnderlyingNetworks(arrayOf(network)) // } } override fun onUninstall() { connectivity?.unregisterNetworkCallback(callback) networkInfos.clear() onUpdateNetwork() } } fun InetAddress.asSocketAddressText(port: Int): String { return when (this) { is Inet6Address -> "[${numericToTextFormat(this)}]:$port" is Inet4Address -> "${this.hostAddress}:$port" else -> throw IllegalArgumentException("Unsupported Inet type ${this.javaClass}") } } private fun numericToTextFormat(address: Inet6Address): String { val src = address.address val sb = StringBuilder(39) for (i in 0 until 8) { sb.append( Integer.toHexString( src[i shl 1].toInt() shl 8 and 0xff00 or (src[(i shl 1) + 1].toInt() and 0xff) ) ) if (i < 7) { sb.append(":") } } if (address.scopeId > 0) { sb.append("%") sb.append(address.scopeId) } return sb.toString() } ================================================ FILE: android/service/src/main/java/com/follow/clash/service/modules/NotificationModule.kt ================================================ package com.follow.clash.service.modules import android.app.Notification.FOREGROUND_SERVICE_IMMEDIATE import android.app.Service import android.app.Service.STOP_FOREGROUND_REMOVE import android.content.Intent import android.os.Build import android.os.PowerManager import androidx.core.app.NotificationCompat import androidx.core.content.getSystemService import com.follow.clash.common.Components import com.follow.clash.common.GlobalState import com.follow.clash.common.QuickAction import com.follow.clash.common.quickIntent import com.follow.clash.common.receiveBroadcastFlow import com.follow.clash.common.startForeground import com.follow.clash.common.tickerFlow import com.follow.clash.common.toPendingIntent import com.follow.clash.core.Core import com.follow.clash.service.R import com.follow.clash.service.State import com.follow.clash.service.models.NotificationParams import com.follow.clash.service.models.getSpeedTrafficText import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.cancel import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onStart import kotlinx.coroutines.launch data class ExtendedNotificationParams( val title: String, val stopText: String, val onlyStatisticsProxy: Boolean, val contentText: String, ) val NotificationParams.extended: ExtendedNotificationParams get() = ExtendedNotificationParams( title, stopText, onlyStatisticsProxy, Core.getSpeedTrafficText(onlyStatisticsProxy) ) class NotificationModule(private val service: Service) : Module() { private val scope = CoroutineScope(Dispatchers.Default) override fun onInstall() { scope.launch { val screenFlow = service.receiveBroadcastFlow { addAction(Intent.ACTION_SCREEN_ON) addAction(Intent.ACTION_SCREEN_OFF) }.map { intent -> intent.action == Intent.ACTION_SCREEN_ON }.onStart { emit(isScreenOn()) } combine( tickerFlow(1000, 0), State.notificationParamsFlow, screenFlow ) { _, params, screenOn -> params?.extended to screenOn }.filter { (params, screenOn) -> params != null && screenOn } .distinctUntilChanged { old, new -> old.first == new.first && old.second == new.second } .collect { (params, _) -> update(params!!) } State.notificationParamsFlow.value?.let { update(it.extended) } ?: run { update(NotificationParams().extended) } } } private fun isScreenOn(): Boolean { val pm = service.getSystemService() return when (pm != null) { true -> pm.isInteractive false -> true } } private val notificationBuilder: NotificationCompat.Builder by lazy { val intent = Intent().setComponent(Components.MAIN_ACTIVITY) with( NotificationCompat.Builder( service, GlobalState.NOTIFICATION_CHANNEL ) ) { setSmallIcon(R.drawable.ic) setContentTitle("FlClash") setContentIntent(intent.toPendingIntent) setPriority(NotificationCompat.PRIORITY_HIGH) setCategory(NotificationCompat.CATEGORY_SERVICE) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { foregroundServiceBehavior = FOREGROUND_SERVICE_IMMEDIATE } setOngoing(true) setShowWhen(true) setOnlyAlertOnce(true) } } private fun update(params: ExtendedNotificationParams) { service.startForeground( with(notificationBuilder) { setContentTitle(params.title) setContentText(params.contentText) clearActions() addAction( 0, params.stopText, QuickAction.STOP.quickIntent.toPendingIntent ).build() }) } override fun onUninstall() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { service.stopForeground(STOP_FOREGROUND_REMOVE) } else { service.stopForeground(true) } scope.cancel() } } ================================================ FILE: android/service/src/main/java/com/follow/clash/service/modules/SuspendModule.kt ================================================ package com.follow.clash.service.modules import android.app.Service import android.content.Intent import android.os.PowerManager import androidx.core.content.getSystemService import com.follow.clash.common.receiveBroadcastFlow import com.follow.clash.core.Core import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.cancel import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onStart import kotlinx.coroutines.launch class SuspendModule(private val service: Service) : Module() { private val scope = CoroutineScope(Dispatchers.Default) private fun isScreenOn(): Boolean { val pm = service.getSystemService() return when (pm != null) { true -> pm.isInteractive false -> true } } val isDeviceIdleMode: Boolean get() { return service.getSystemService()?.isDeviceIdleMode ?: true } private fun onUpdate(isScreenOn: Boolean) { if (isScreenOn) { Core.suspended(false) return } Core.suspended(isDeviceIdleMode) } override fun onInstall() { scope.launch { val screenFlow = service.receiveBroadcastFlow { addAction(Intent.ACTION_SCREEN_ON) addAction(Intent.ACTION_SCREEN_OFF) }.map { intent -> intent.action == Intent.ACTION_SCREEN_ON }.onStart { emit(isScreenOn()) } screenFlow.collect { onUpdate(it) } } } override fun onUninstall() { scope.cancel() } } ================================================ FILE: android/service/src/main/res/drawable/ic.xml ================================================ ================================================ FILE: android/service/src/main/res/drawable/ic_service.xml ================================================ ================================================ FILE: android/settings.gradle.kts ================================================ pluginManagement { val flutterSdkPath = run { val properties = java.util.Properties() file("local.properties").inputStream().use { properties.load(it) } val flutterSdkPath = properties.getProperty("flutter.sdk") require(flutterSdkPath != null) { "flutter.sdk not set in local.properties" } flutterSdkPath } includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") repositories { google() mavenCentral() gradlePluginPortal() } } plugins { id("dev.flutter.flutter-plugin-loader") version "1.0.0" id("com.android.application") version "8.12.2" apply false id("org.jetbrains.kotlin.android") version "2.2.10" apply false id("com.google.gms.google-services") version ("4.3.15") apply false id("com.google.firebase.crashlytics") version ("2.8.1") apply false } include(":app") include(":core") include(":service") include(":common") ================================================ FILE: arb/intl_en.arb ================================================ { "rule": "Rule", "global": "Global", "direct": "Direct", "dashboard": "Dashboard", "proxies": "Proxies", "profile": "Profile", "profiles": "Profiles", "tools": "Tools", "logs": "Logs", "logsDesc": "Log capture records", "resources": "Resources", "resourcesDesc": "External resource related info", "trafficUsage": "Traffic usage", "coreInfo": "Core info", "networkSpeed": "Network speed", "outboundMode": "Outbound mode", "networkDetection": "Network detection", "upload": "Upload", "download": "Download", "noProxy": "No proxy", "noProxyDesc": "Please create a profile or add a valid profile", "nullProfileDesc": "No profile, Please add a profile", "settings": "Settings", "language": "Language", "defaultText": "Default", "more": "More", "other": "Other", "about": "About", "en": "English", "ja": "Japanese", "ru": "Russian", "zh_CN": "Simplified Chinese", "theme": "Theme", "themeDesc": "Set dark mode,adjust the color", "override": "Override", "overrideDesc": "Override Proxy related config", "allowLan": "AllowLan", "allowLanDesc": "Allow access proxy through the LAN", "tun": "TUN", "tunDesc": "only effective in administrator mode", "minimizeOnExit": "Minimize on exit", "minimizeOnExitDesc": "Modify the default system exit event", "autoLaunch": "Auto launch", "autoLaunchDesc": "Follow the system self startup", "silentLaunch": "SilentLaunch", "silentLaunchDesc": "Start in the background", "autoRun": "AutoRun", "autoRunDesc": "Auto run when the application is opened", "logcat": "Logcat", "logcatDesc": "Disabling will hide the log entry", "autoCheckUpdate": "Auto check updates", "autoCheckUpdateDesc": "Auto check for updates when the app starts", "accessControl": "AccessControl", "accessControlDesc": "Configure application access proxy", "application": "Application", "applicationDesc": "Modify application related settings", "edit": "Edit", "confirm": "Confirm", "update": "Update", "add": "Add", "save": "Save", "delete": "Delete", "years": "Years", "months": "Months", "hours": "Hours", "days": "Days", "minutes": "Minutes", "seconds": "Seconds", "ago": " Ago", "just": "Just", "qrcode": "QR code", "qrcodeDesc": "Scan QR code to obtain profile", "url": "URL", "urlDesc": "Obtain profile through URL", "file": "File", "fileDesc": "Directly upload profile", "name": "Name", "profileNameNullValidationDesc": "Please input the profile name", "profileUrlNullValidationDesc": "Please input the profile URL", "profileUrlInvalidValidationDesc": "Please input a valid profile URL", "autoUpdate": "Auto update", "autoUpdateInterval": "Auto update interval (minutes)", "profileAutoUpdateIntervalNullValidationDesc": "Please enter the auto update interval time", "profileAutoUpdateIntervalInvalidValidationDesc": "Please input a valid interval time format", "themeMode": "Theme mode", "themeColor": "Theme color", "preview": "Preview", "auto": "Auto", "light": "Light", "dark": "Dark", "importFromURL": "Import from URL", "submit": "Submit", "doYouWantToPass": "Do you want to pass", "create": "Create", "defaultSort": "Sort by default", "delaySort": "Sort by delay", "nameSort": "Sort by name", "pleaseUploadFile": "Please upload file", "pleaseUploadValidQrcode": "Please upload a valid QR code", "blacklistMode": "Blacklist mode", "whitelistMode": "Whitelist mode", "filterSystemApp": "Filter system app", "cancelFilterSystemApp": "Cancel filter system app", "selectAll": "Select all", "cancelSelectAll": "Cancel select all", "appAccessControl": "App access control", "accessControlAllowDesc": "Only allow selected app to enter VPN", "accessControlNotAllowDesc": "The selected application will be excluded from VPN", "selected": "Selected", "unableToUpdateCurrentProfileDesc": "unable to update current profile", "noMoreInfoDesc": "No more info", "profileParseErrorDesc": "profile parse error", "proxyPort": "ProxyPort", "proxyPortDesc": "Set the Clash listening port", "port": "Port", "logLevel": "LogLevel", "show": "Show", "exit": "Exit", "systemProxy": "System proxy", "project": "Project", "core": "Core", "tabAnimation": "Tab animation", "desc": "A multi-platform proxy client based on ClashMeta, simple and easy to use, open-source and ad-free.", "startVpn": "Starting VPN...", "stopVpn": "Stopping VPN...", "discovery": "Discovery a new version", "compatible": "Compatibility mode", "compatibleDesc": "Opening it will lose part of its application ability and gain the support of full amount of Clash.", "notSelectedTip": "The current proxy group cannot be selected.", "tip": "tip", "account": "Account", "backup": "Backup", "backupSuccess": "Backup success", "noInfo": "No info", "pleaseBindWebDAV": "Please bind WebDAV", "bind": "Bind", "connectivity": "Connectivity:", "webDAVConfiguration": "WebDAV configuration", "address": "Address", "addressHelp": "WebDAV server address", "addressTip": "Please enter a valid WebDAV address", "password": "Password", "checkUpdate": "Check for updates", "discoverNewVersion": "Discover the new version", "checkUpdateError": "The current application is already the latest version", "goDownload": "Go to download", "unknown": "Unknown", "geoData": "GeoData", "externalResources": "External resources", "checking": "Checking...", "country": "Country", "checkError": "Check error", "search": "Search", "allowBypass": "Allow applications to bypass VPN", "allowBypassDesc": "Some apps can bypass VPN when turned on", "externalController": "ExternalController", "externalControllerDesc": "Once enabled, the Clash kernel can be controlled on port 9090", "ipv6Desc": "When turned on it will be able to receive IPv6 traffic", "app": "App", "general": "General", "vpnSystemProxyDesc": "Attach HTTP proxy to VpnService", "systemProxyDesc": "Attach HTTP proxy to VpnService", "unifiedDelay": "Unified delay", "unifiedDelayDesc": "Remove extra delays such as handshaking", "tcpConcurrent": "TCP concurrent", "tcpConcurrentDesc": "Enabling it will allow TCP concurrency", "geodataLoader": "Geo Low Memory Mode", "geodataLoaderDesc": "Enabling will use the Geo low memory loader", "requests": "Requests", "requestsDesc": "View recently request records", "findProcessMode": "Find process", "init": "Init", "infiniteTime": "Long term effective", "expirationTime": "Expiration time", "connections": "Connections", "connectionsDesc": "View current connections data", "intranetIP": "Intranet IP", "view": "View", "cut": "Cut", "copy": "Copy", "paste": "Paste", "testUrl": "Test url", "sync": "Sync", "exclude": "Hidden from recent tasks", "excludeDesc": "When the app is in the background, the app is hidden from the recent task", "oneColumn": "One column", "twoColumns": "Two columns", "threeColumns": "Three columns", "fourColumns": "Four columns", "expand": "Standard", "shrink": "Shrink", "min": "Min", "tab": "Tab", "list": "List", "delay": "Delay", "style": "Style", "size": "Size", "sort": "Sort", "columns": "Columns", "proxiesSetting": "Proxies setting", "proxyGroup": "Proxy group", "go": "Go", "externalLink": "External link", "otherContributors": "Other contributors", "autoCloseConnections": "Auto close connections", "autoCloseConnectionsDesc": "Auto close connections after change node", "onlyStatisticsProxy": "Only statistics proxy", "onlyStatisticsProxyDesc": "When turned on, only statistics proxy traffic", "pureBlackMode": "Pure black mode", "keepAliveIntervalDesc": "Tcp keep alive interval", "entries": " entries", "local": "Local", "remote": "Remote", "remoteBackupDesc": "Backup local data to WebDAV", "localBackupDesc": "Backup local data to local", "mode": "Mode", "time": "Time", "source": "Source", "allApps": "All apps", "onlyOtherApps": "Only third-party apps", "action": "Action", "intelligentSelected": "Intelligent selection", "clipboardImport": "Clipboard import", "clipboardExport": "Export clipboard", "layout": "Layout", "tight": "Tight", "standard": "Standard", "loose": "Loose", "profilesSort": "Profiles sort", "start": "Start", "stop": "Stop", "appDesc": "Processing app related settings", "vpnDesc": "Modify VPN related settings", "dnsDesc": "Update DNS related settings", "key": "Key", "value": "Value", "hostsDesc": "Add Hosts", "vpnTip": "Changes take effect after restarting the VPN", "vpnEnableDesc": "Auto routes all system traffic through VpnService", "options": "Options", "loopback": "Loopback unlock tool", "loopbackDesc": "Used for UWP loopback unlocking", "providers": "Providers", "proxyProviders": "Proxy providers", "ruleProviders": "Rule providers", "overrideDns": "Override Dns", "overrideDnsDesc": "Turning it on will override the DNS options in the profile", "status": "Status", "statusDesc": "System DNS will be used when turned off", "preferH3Desc": "Prioritize the use of DOH's http/3", "respectRules": "Respect rules", "respectRulesDesc": "DNS connection following rules, need to configure proxy-server-nameserver", "dnsMode": "DNS mode", "fakeipRange": "Fakeip range", "fakeipFilter": "Fakeip filter", "defaultNameserver": "Default nameserver", "defaultNameserverDesc": "For resolving DNS server", "nameserver": "Nameserver", "nameserverDesc": "For resolving domain", "useHosts": "Use hosts", "useSystemHosts": "Use system hosts", "nameserverPolicy": "Nameserver policy", "nameserverPolicyDesc": "Specify the corresponding nameserver policy", "proxyNameserver": "Proxy nameserver", "proxyNameserverDesc": "Domain for resolving proxy nodes", "fallback": "Fallback", "fallbackDesc": "Generally use offshore DNS", "fallbackFilter": "Fallback filter", "geoipCode": "Geoip code", "ipcidr": "Ipcidr", "domain": "Domain", "reset": "Reset", "action_view": "Show/Hide", "action_start": "Start/Stop", "action_mode": "Switch mode", "action_proxy": "System proxy", "action_tun": "TUN", "disclaimer": "Disclaimer", "disclaimerDesc": "This software is only used for non-commercial purposes such as learning exchanges and scientific research. It is strictly prohibited to use this software for commercial purposes. Any commercial activity, if any, has nothing to do with this software.", "agree": "Agree", "hotkeyManagement": "Hotkey Management", "hotkeyManagementDesc": "Use keyboard to control applications", "pressKeyboard": "Please press the keyboard.", "inputCorrectHotkey": "Please enter the correct hotkey", "hotkeyConflict": "Hotkey conflict", "remove": "Remove", "noHotKey": "No HotKey", "noNetwork": "No network", "ipv6InboundDesc": "Allow IPv6 inbound", "exportLogs": "Export logs", "exportSuccess": "Export Success", "iconStyle": "Icon style", "onlyIcon": "Icon", "noIcon": "None", "stackMode": "Stack mode", "network": "Network", "networkDesc": "Modify network-related settings", "bypassDomain": "Bypass domain", "bypassDomainDesc": "Only takes effect when the system proxy is enabled", "resetTip": "Make sure to reset", "regExp": "RegExp", "icon": "Icon", "iconConfiguration": "Icon configuration", "noData": "No data", "adminAutoLaunch": "Admin auto launch", "adminAutoLaunchDesc": "Boot up by using admin mode", "fontFamily": "FontFamily", "systemFont": "System font", "toggle": "Toggle", "system": "System", "routeMode": "Route mode", "routeMode_bypassPrivate": "Bypass private route address", "routeMode_config": "Use config", "routeAddress": "Route address", "routeAddressDesc": "Config listen route address", "pleaseInputAdminPassword": "Please enter the admin password", "copyEnvVar": "Copying environment variables", "memoryInfo": "Memory info", "cancel": "Cancel", "fileIsUpdate": "The file has been modified. Do you want to save the changes?", "profileHasUpdate": "The profile has been modified. Do you want to disable auto update?", "hasCacheChange": "Do you want to cache the changes?", "copySuccess": "Copy success", "copyLink": "Copy link", "exportFile": "Export file", "cacheCorrupt": "The cache is corrupt. Do you want to clear it?", "detectionTip": "Relying on third-party api is for reference only", "listen": "Listen", "undo": "undo", "redo": "redo", "none": "none", "basicConfig": "Basic configuration", "basicConfigDesc": "Modify the basic configuration globally", "advancedConfig": "Advanced configuration", "advancedConfigDesc": "Provide diverse configuration options", "selectedCountTitle": "{count} items have been selected", "addRule": "Add rule", "ruleName": "Rule name", "content": "Content", "subRule": "Sub rule", "ruleTarget": "Rule target", "sourceIp": "Source IP", "noResolve": "No resolve IP", "getOriginRules": "Get original rules", "overrideOriginRules": "Override the original rule", "addedOriginRules": "Attach on the original rules", "enableOverride": "Enable override", "saveChanges": "Do you want to save the changes?", "generalDesc": "Modify general settings", "findProcessModeDesc": "There is a certain performance loss after opening", "tabAnimationDesc": "Effective only in mobile view", "saveTip": "Are you sure you want to save?", "colorSchemes": "Color schemes", "palette": "Palette", "tonalSpotScheme": "TonalSpot", "fidelityScheme": "Fidelity", "monochromeScheme": "Monochrome", "neutralScheme": "Neutral", "vibrantScheme": "Vibrant", "expressiveScheme": "Expressive", "contentScheme": "Content", "rainbowScheme": "Rainbow", "fruitSaladScheme": "FruitSalad", "developerMode": "Developer mode", "developerModeEnableTip": "Developer mode is enabled.", "messageTest": "Message test", "messageTestTip": "This is a message.", "crashTest": "Crash test", "clearData": "Clear Data", "textScale": "Text Scaling", "internet": "Internet", "systemApp": "System APP", "noNetworkApp": "No network APP", "contactMe": "Contact me", "restoreStrategy": "Restore strategy", "restoreStrategy_override": "Override", "restoreStrategy_compatible": "Compatible", "logsTest": "Logs test", "emptyTip": "{label} cannot be empty", "urlTip": "{label} must be a url", "numberTip": "{label} must be a number", "interval": "Interval", "existsTip": "Current {label} already exists", "deleteTip": "Are you sure you want to delete the current {label}?", "deleteMultipTip": "Are you sure you want to delete the selected {label}?", "nullTip": "No {label} yet", "script": "Script", "color": "Color", "rename": "Rename", "unnamed": "Unnamed", "pleaseEnterScriptName": "Please enter a script name", "overrideInvalidTip": "Does not take effect in script mode", "mixedPort": "Mixed Port", "socksPort": "Socks Port", "redirPort": "Redir Port", "tproxyPort": "Tproxy Port", "portTip": "{label} must be between 1024 and 49151", "portConflictTip": "Please enter a different port", "import": "Import", "importFile": "Import from file", "importUrl": "Import from URL", "autoSetSystemDns": "Auto set system DNS", "details": "{label} details", "creationTime": "Creation time", "process": "Process", "host": "Host", "destination": "Destination", "destinationGeoIP": "Destination GeoIP", "destinationIPASN": "Destination IPASN", "specialProxy": "Special proxy", "specialRules": "special rules", "remoteDestination": "Remote destination", "networkType": "Network type", "proxyChains": "Proxy chains", "log": "Log", "connection": "Connection", "request": "Request", "connected": "Connected", "disconnected": "Disconnected", "connecting": "Connecting...", "restartCoreTip": "Are you sure you want to restart the core?", "forceRestartCoreTip": "Are you sure you want to force restart the core?", "dnsHijacking": "DNS hijacking", "coreStatus": "Core status", "dataCollectionTip": "Data Collection Notice", "dataCollectionContent": "This app uses Firebase Crashlytics to collect crash information to improve app stability.\nThe collected data includes device information and crash details, but does not contain personal sensitive data.\nYou can disable this feature in settings.", "crashlytics": "Crash Analysis", "crashlyticsTip": "When enabled, automatically uploads crash logs without sensitive information when the app crashes", "appendSystemDns": "Append System DNS", "appendSystemDnsTip": "Forcefully append system DNS to the configuration", "editRule": "Edit rule", "overrideMode": "Override mode", "standardModeDesc": "Standard mode, override basic configuration, provide simple rule addition capability", "scriptModeDesc": "Script mode, use external extension scripts, provide one-click override configuration capability", "addedRules": "Added rules", "controlGlobalAddedRules": "Control global added rules", "overrideScript": "Override script", "goToConfigureScript": "Go to configure script", "editGlobalRules": "Edit global rules", "externalFetch": "External fetch", "confirmForceCrashCore": "Are you sure you want to force crash the core?", "confirmClearAllData": "Are you sure you want to clear all data?", "loading": "Loading...", "loadTest": "Load test", "yearsAgo": "{count, plural, =1{1 year ago} other{{count} years ago}}", "monthsAgo": "{count, plural, =1{1 month ago} other{{count} months ago}}", "daysAgo": "{count, plural, =1{1 day ago} other{{count} days ago}}", "hoursAgo": "{count, plural, =1{1 hour ago} other{{count} hours ago}}", "minutesAgo": "{count, plural, =1{1 minute ago} other{{count} minutes ago}}", "justNow": "Just now", "noLongerRemind": "Don't remind again", "accessControlSettings": "Access Control Settings", "turnOn": "Turn On", "turnOff": "Turn Off", "coreConfigChangeDetected": "Core configuration change detected", "reload": "Reload", "vpnConfigChangeDetected": "VPN configuration change detected", "restart": "Restart", "speedStatistics": "Speed statistics", "resetPageChangesTip": "The current page has changes. Are you sure you want to reset?", "overwriteTypeCustom": "Custom", "overwriteTypeCustomDesc": "Custom mode, fully customize proxy groups and rules", "unknownNetworkError": "Unknown network error", "networkRequestException": "Network request exception, please try again later.", "restoreException": "Recovery exception", "networkException": "Network exception, please check your connection and try again", "invalidBackupFile": "Invalid backup file", "pruneCache": "Prune cache", "backupAndRestore": "Backup and Restore", "backupAndRestoreDesc": "Sync data via WebDAV or files", "restore": "Restore", "restoreSuccess": "Restore success", "restoreFromWebDAVDesc": "Restore data via WebDAV", "restoreFromFileDesc": "Restore data via file", "restoreOnlyConfig": "Restore configuration files only", "restoreAllData": "Restore all data", "addProfile": "Add Profile", "delayTest": "Delay Test" } ================================================ FILE: arb/intl_ja.arb ================================================ { "rule": "ルール", "global": "グローバル", "direct": "ダイレクト", "dashboard": "ダッシュボード", "proxies": "プロキシ", "profile": "プロファイル", "profiles": "プロファイル一覧", "tools": "ツール", "logs": "ログ", "logsDesc": "ログキャプチャ記録", "resources": "リソース", "resourcesDesc": "外部リソース関連情報", "trafficUsage": "トラフィック使用量", "coreInfo": "コア情報", "networkSpeed": "ネットワーク速度", "outboundMode": "アウトバウンドモード", "networkDetection": "ネットワーク検出", "upload": "アップロード", "download": "ダウンロード", "noProxy": "プロキシなし", "noProxyDesc": "プロファイルを作成するか、有効なプロファイルを追加してください", "nullProfileDesc": "プロファイルがありません。追加してください", "settings": "設定", "language": "言語", "defaultText": "デフォルト", "more": "詳細", "other": "その他", "about": "について", "en": "英語", "ja": "日本語", "ru": "ロシア語", "zh_CN": "簡体字中国語", "theme": "テーマ", "themeDesc": "ダークモードの設定、色の調整", "override": "上書き", "overrideDesc": "プロキシ関連設定を上書き", "allowLan": "LANを許可", "allowLanDesc": "LAN経由でのプロキシアクセスを許可", "tun": "TUN", "tunDesc": "管理者モードでのみ有効", "minimizeOnExit": "終了時に最小化", "minimizeOnExitDesc": "システムの終了イベントを変更", "autoLaunch": "自動起動", "autoLaunchDesc": "システムの自動起動に従う", "silentLaunch": "バックグラウンド起動", "silentLaunchDesc": "バックグラウンドで起動", "autoRun": "自動実行", "autoRunDesc": "アプリ起動時に自動実行", "logcat": "ログキャット", "logcatDesc": "無効化するとログエントリを非表示", "autoCheckUpdate": "自動更新チェック", "autoCheckUpdateDesc": "起動時に更新を自動チェック", "accessControl": "アクセス制御", "accessControlDesc": "アプリケーションのプロキシアクセスを設定", "application": "アプリケーション", "applicationDesc": "アプリ関連設定を変更", "edit": "編集", "confirm": "確認", "update": "更新", "add": "追加", "save": "保存", "delete": "削除", "years": "年", "months": "月", "hours": "時間", "days": "日", "minutes": "分", "seconds": "秒", "ago": "前", "just": "たった今", "qrcode": "QRコード", "qrcodeDesc": "QRコードをスキャンしてプロファイルを取得", "url": "URL", "urlDesc": "URL経由でプロファイルを取得", "file": "ファイル", "fileDesc": "プロファイルを直接アップロード", "name": "名前", "profileNameNullValidationDesc": "プロファイル名を入力してください", "profileUrlNullValidationDesc": "プロファイルURLを入力してください", "profileUrlInvalidValidationDesc": "有効なプロファイルURLを入力してください", "autoUpdate": "自動更新", "autoUpdateInterval": "自動更新間隔(分)", "profileAutoUpdateIntervalNullValidationDesc": "自動更新間隔を入力してください", "profileAutoUpdateIntervalInvalidValidationDesc": "有効な間隔形式を入力してください", "themeMode": "テーマモード", "themeColor": "テーマカラー", "preview": "プレビュー", "auto": "自動", "light": "ライト", "dark": "ダーク", "importFromURL": "URLからインポート", "submit": "送信", "doYouWantToPass": "通過させますか?", "create": "作成", "defaultSort": "デフォルト順", "delaySort": "遅延順", "nameSort": "名前順", "pleaseUploadFile": "ファイルをアップロードしてください", "pleaseUploadValidQrcode": "有効なQRコードをアップロードしてください", "blacklistMode": "ブラックリストモード", "whitelistMode": "ホワイトリストモード", "filterSystemApp": "システムアプリを除外", "cancelFilterSystemApp": "システムアプリの除外を解除", "selectAll": "すべて選択", "cancelSelectAll": "全選択解除", "appAccessControl": "アプリアクセス制御", "accessControlAllowDesc": "選択したアプリのみVPNを許可", "accessControlNotAllowDesc": "選択したアプリをVPNから除外", "selected": "選択済み", "unableToUpdateCurrentProfileDesc": "現在のプロファイルを更新できません", "noMoreInfoDesc": "追加情報なし", "profileParseErrorDesc": "プロファイル解析エラー", "proxyPort": "プロキシポート", "proxyPortDesc": "Clashのリスニングポートを設定", "port": "ポート", "logLevel": "ログレベル", "show": "表示", "exit": "終了", "systemProxy": "システムプロキシ", "project": "プロジェクト", "core": "コア", "tabAnimation": "タブアニメーション", "desc": "ClashMetaベースのマルチプラットフォームプロキシクライアント。シンプルで使いやすく、オープンソースで広告なし。", "startVpn": "VPNを開始中...", "stopVpn": "VPNを停止中...", "discovery": "新しいバージョンを発見", "compatible": "互換モード", "compatibleDesc": "有効化すると一部機能を失いますが、Clashの完全サポートを獲得", "notSelectedTip": "現在のプロキシグループは選択できません", "tip": "ヒント", "account": "アカウント", "backup": "バックアップ", "backupSuccess": "バックアップ成功", "noInfo": "情報なし", "pleaseBindWebDAV": "WebDAVをバインドしてください", "bind": "バインド", "connectivity": "接続性:", "webDAVConfiguration": "WebDAV設定", "address": "アドレス", "addressHelp": "WebDAVサーバーアドレス", "addressTip": "有効なWebDAVアドレスを入力", "password": "パスワード", "checkUpdate": "更新を確認", "discoverNewVersion": "新バージョンを発見", "checkUpdateError": "アプリは最新版です", "goDownload": "ダウンロードへ", "unknown": "不明", "geoData": "地域データ", "externalResources": "外部リソース", "checking": "確認中...", "country": "国", "checkError": "確認エラー", "search": "検索", "allowBypass": "アプリがVPNをバイパスすることを許可", "allowBypassDesc": "有効化すると一部アプリがVPNをバイパス", "externalController": "外部コントローラー", "externalControllerDesc": "有効化するとClashコアをポート9090で制御可能", "ipv6Desc": "有効化するとIPv6トラフィックを受信可能", "app": "アプリ", "general": "一般", "vpnSystemProxyDesc": "HTTPプロキシをVpnServiceに接続", "systemProxyDesc": "HTTPプロキシをVpnServiceに接続", "unifiedDelay": "統一遅延", "unifiedDelayDesc": "ハンドシェイクなどの余分な遅延を削除", "tcpConcurrent": "TCP並列処理", "tcpConcurrentDesc": "TCP並列処理を許可", "geodataLoader": "Geo低メモリモード", "geodataLoaderDesc": "有効化するとGeo低メモリローダーを使用", "requests": "リクエスト", "requestsDesc": "最近のリクエスト記録を表示", "findProcessMode": "プロセス検出", "init": "初期化", "infiniteTime": "長期有効", "expirationTime": "有効期限", "connections": "接続", "connectionsDesc": "現在の接続データを表示", "intranetIP": "イントラネットIP", "view": "表示", "cut": "切り取り", "copy": "コピー", "paste": "貼り付け", "testUrl": "URLテスト", "sync": "同期", "exclude": "最近のタスクから非表示", "excludeDesc": "アプリがバックグラウンド時に最近のタスクから非表示", "oneColumn": "1列", "twoColumns": "2列", "threeColumns": "3列", "fourColumns": "4列", "expand": "標準", "shrink": "縮小", "min": "最小化", "tab": "タブ", "list": "リスト", "delay": "遅延", "style": "スタイル", "size": "サイズ", "sort": "並び替え", "columns": "列", "proxiesSetting": "プロキシ設定", "proxyGroup": "プロキシグループ", "go": "移動", "externalLink": "外部リンク", "otherContributors": "その他の貢献者", "autoCloseConnections": "接続を自動閉じる", "autoCloseConnectionsDesc": "ノード変更後に接続を自動閉じる", "onlyStatisticsProxy": "プロキシのみ統計", "onlyStatisticsProxyDesc": "有効化するとプロキシトラフィックのみ統計", "pureBlackMode": "純黒モード", "keepAliveIntervalDesc": "TCPキープアライブ間隔", "entries": " エントリ", "local": "ローカル", "remote": "リモート", "remoteBackupDesc": "WebDAVにデータをバックアップ", "localBackupDesc": "ローカルにデータをバックアップ", "mode": "モード", "time": "時間", "source": "ソース", "allApps": "全アプリ", "onlyOtherApps": "サードパーティアプリのみ", "action": "アクション", "intelligentSelected": "インテリジェント選択", "clipboardImport": "クリップボードからインポート", "clipboardExport": "クリップボードにエクスポート", "layout": "レイアウト", "tight": "密", "standard": "標準", "loose": "疎", "profilesSort": "プロファイルの並び替え", "start": "開始", "stop": "停止", "appDesc": "アプリ関連設定の処理", "vpnDesc": "VPN関連設定の変更", "dnsDesc": "DNS関連設定の更新", "key": "キー", "value": "値", "hostsDesc": "ホストを追加", "vpnTip": "変更はVPN再起動後に有効", "vpnEnableDesc": "VpnService経由で全システムトラフィックをルーティング", "options": "オプション", "loopback": "ループバック解除ツール", "loopbackDesc": "UWPループバック解除用", "providers": "プロバイダー", "proxyProviders": "プロキシプロバイダー", "ruleProviders": "ルールプロバイダー", "overrideDns": "DNS上書き", "overrideDnsDesc": "有効化するとプロファイルのDNS設定を上書き", "status": "ステータス", "statusDesc": "無効時はシステムDNSを使用", "preferH3Desc": "DOHのHTTP/3を優先使用", "respectRules": "ルール尊重", "respectRulesDesc": "DNS接続がルールに従う(proxy-server-nameserverの設定が必要)", "dnsMode": "DNSモード", "fakeipRange": "Fakeip範囲", "fakeipFilter": "Fakeipフィルター", "defaultNameserver": "デフォルトネームサーバー", "defaultNameserverDesc": "DNSサーバーの解決用", "nameserver": "ネームサーバー", "nameserverDesc": "ドメイン解決用", "useHosts": "ホストを使用", "useSystemHosts": "システムホストを使用", "nameserverPolicy": "ネームサーバーポリシー", "nameserverPolicyDesc": "対応するネームサーバーポリシーを指定", "proxyNameserver": "プロキシネームサーバー", "proxyNameserverDesc": "プロキシノード解決用ドメイン", "fallback": "フォールバック", "fallbackDesc": "通常はオフショアDNSを使用", "fallbackFilter": "フォールバックフィルター", "geoipCode": "GeoIPコード", "ipcidr": "IPCIDR", "domain": "ドメイン", "reset": "リセット", "action_view": "表示/非表示", "action_start": "開始/停止", "action_mode": "モード切替", "action_proxy": "システムプロキシ", "action_tun": "TUN", "disclaimer": "免責事項", "disclaimerDesc": "本ソフトウェアは学習交流や科学研究などの非営利目的でのみ使用されます。商用利用は厳禁です。いかなる商用活動も本ソフトウェアとは無関係です。", "agree": "同意", "hotkeyManagement": "ホットキー管理", "hotkeyManagementDesc": "キーボードでアプリを制御", "pressKeyboard": "キーボードを押してください", "inputCorrectHotkey": "正しいホットキーを入力", "hotkeyConflict": "ホットキー競合", "remove": "削除", "noHotKey": "ホットキーなし", "noNetwork": "ネットワークなし", "ipv6InboundDesc": "IPv6インバウンドを許可", "exportLogs": "ログをエクスポート", "exportSuccess": "エクスポート成功", "iconStyle": "アイコンスタイル", "onlyIcon": "アイコンのみ", "noIcon": "なし", "stackMode": "スタックモード", "network": "ネットワーク", "networkDesc": "ネットワーク関連設定の変更", "bypassDomain": "バイパスドメイン", "bypassDomainDesc": "システムプロキシ有効時のみ適用", "resetTip": "リセットを確定", "regExp": "正規表現", "icon": "アイコン", "iconConfiguration": "アイコン設定", "noData": "データなし", "adminAutoLaunch": "管理者自動起動", "adminAutoLaunchDesc": "管理者モードで起動", "fontFamily": "フォントファミリー", "systemFont": "システムフォント", "toggle": "トグル", "system": "システム", "routeMode": "ルートモード", "routeMode_bypassPrivate": "プライベートルートをバイパス", "routeMode_config": "設定を使用", "routeAddress": "ルートアドレス", "routeAddressDesc": "ルートアドレスを設定", "pleaseInputAdminPassword": "管理者パスワードを入力", "copyEnvVar": "環境変数をコピー", "memoryInfo": "メモリ情報", "cancel": "キャンセル", "fileIsUpdate": "ファイルが変更されました。保存しますか?", "profileHasUpdate": "プロファイルが変更されました。自動更新を無効化しますか?", "hasCacheChange": "変更をキャッシュしますか?", "copySuccess": "コピー成功", "copyLink": "リンクをコピー", "exportFile": "ファイルをエクスポート", "cacheCorrupt": "キャッシュが破損しています。クリアしますか?", "detectionTip": "サードパーティAPIに依存(参考値)", "listen": "リスン", "undo": "元に戻す", "redo": "やり直す", "none": "なし", "basicConfig": "基本設定", "basicConfigDesc": "基本設定をグローバルに変更", "advancedConfig": "高度な設定", "advancedConfigDesc": "多様な設定を提供", "selectedCountTitle": "{count} 項目が選択されています", "addRule": "ルールを追加", "ruleName": "ルール名", "content": "内容", "subRule": "サブルール", "ruleTarget": "ルール対象", "sourceIp": "送信元IP", "noResolve": "IPを解決しない", "getOriginRules": "元のルールを取得", "overrideOriginRules": "元のルールを上書き", "addedOriginRules": "元のルールに追加", "enableOverride": "上書きを有効化", "saveChanges": "変更を保存しますか?", "generalDesc": "一般設定を変更", "findProcessModeDesc": "有効化するとパフォーマンスが若干低下します", "tabAnimationDesc": "モバイル表示でのみ有効", "saveTip": "保存してもよろしいですか?", "colorSchemes": "カラースキーム", "palette": "パレット", "tonalSpotScheme": "トーンスポット", "fidelityScheme": "ハイファイデリティー", "monochromeScheme": "モノクローム", "neutralScheme": "ニュートラル", "vibrantScheme": "ビブラント", "expressiveScheme": "エクスプレッシブ", "contentScheme": "コンテンツテーマ", "rainbowScheme": "レインボー", "fruitSaladScheme": "フルーツサラダ", "developerMode": "デベロッパーモード", "developerModeEnableTip": "デベロッパーモードが有効になりました。", "messageTest": "メッセージテスト", "messageTestTip": "これはメッセージです。", "crashTest": "クラッシュテスト", "clearData": "データを消去", "zoom": "ズーム", "textScale": "テキストスケーリング", "internet": "インターネット", "systemApp": "システムアプリ", "noNetworkApp": "ネットワークなしアプリ", "contactMe": "連絡する", "restoreStrategy": "復元ストラテジー", "restoreStrategy_override": "上書き", "restoreStrategy_compatible": "互換", "logsTest": "ログテスト", "emptyTip": "{label}は空欄にできません", "urlTip": "{label}はURLである必要があります", "numberTip": "{label}は数字でなければなりません", "interval": "インターバル", "existsTip": "現在の{label}は既に存在しています", "deleteTip": "現在の{label}を削除してもよろしいですか?", "deleteMultipTip": "選択された{label}を削除してもよろしいですか?", "nullTip": "まだ{label}はありません", "script": "スクリプト", "color": "カラー", "rename": "リネーム", "unnamed": "無題", "pleaseEnterScriptName": "スクリプト名を入力してください", "overrideInvalidTip": "スクリプトモードでは有効になりません", "mixedPort": "混合ポート", "socksPort": "Socksポート", "redirPort": "Redirポート", "tproxyPort": "Tproxyポート", "portTip": "{label} は 1024 から 49151 の間でなければなりません", "portConflictTip": "別のポートを入力してください", "import": "インポート", "importFile": "ファイルからインポート", "importUrl": "URLからインポート", "autoSetSystemDns": "オートセットシステムDNS", "details": "{label}詳細", "creationTime": "作成時間", "process": "プロセス", "host": "ホスト", "destination": "宛先", "destinationGeoIP": "宛先地理情報", "destinationIPASN": "宛先IP ASN", "specialProxy": "特殊プロキシ", "specialRules": "特殊ルール", "remoteDestination": "リモート宛先", "networkType": "ネットワーク種別", "proxyChains": "プロキシチェーン", "log": "ログ", "connection": "接続", "request": "リクエスト", "connected": "接続済み", "disconnected": "切断済み", "connecting": "接続中...", "restartCoreTip": "コアを再起動してもよろしいですか?", "forceRestartCoreTip": "コアを強制再起動してもよろしいですか?", "dnsHijacking": "DNSハイジャッキング", "coreStatus": "コアステータス", "dataCollectionTip": "データ収集説明", "dataCollectionContent": "本アプリはFirebase Crashlyticsを使用してクラッシュ情報を収集し、アプリの安定性を向上させます。\n収集されるデータにはデバイス情報とクラッシュ詳細が含まれますが、個人の機密データは含まれません。\n設定でこの機能を無効にすることができます。", "crashlytics": "クラッシュ分析", "crashlyticsTip": "有効にすると、アプリがクラッシュした際に機密情報を含まないクラッシュログを自動的にアップロードします", "appendSystemDns": "システムDNSを追加", "appendSystemDnsTip": "設定にシステムDNSを強制的に追加します", "editRule": "ルールを編集", "overrideMode": "上書きモード", "standardModeDesc": "標準モード、基本設定を上書きし、シンプルなルール追加機能を提供", "scriptModeDesc": "スクリプトモード、外部拡張スクリプトを使用し、ワンクリックで設定を上書きする機能を提供", "addedRules": "追加ルール", "controlGlobalAddedRules": "グローバル追加ルールを制御", "overrideScript": "上書きスクリプト", "goToConfigureScript": "スクリプト設定に移動", "editGlobalRules": "グローバルルールを編集", "externalFetch": "外部取得", "confirmForceCrashCore": "コアを強制的にクラッシュさせてもよろしいですか?", "confirmClearAllData": "すべてのデータをクリアしてもよろしいですか?", "loading": "読み込み中...", "loadTest": "読み込みテスト", "yearsAgo": "{count}年前", "monthsAgo": "{count}ヶ月前", "daysAgo": "{count}日前", "hoursAgo": "{count}時間前", "minutesAgo": "{count}分前", "justNow": "たった今", "noLongerRemind": "今後表示しない", "accessControlSettings": "アクセス制御設定", "turnOn": "オン", "turnOff": "オフ", "coreConfigChangeDetected": "コア設定の変更が検出されました", "reload": "リロード", "vpnConfigChangeDetected": "VPN設定の変更が検出されました", "restart": "再起動", "speedStatistics": "速度統計", "resetPageChangesTip": "現在のページに変更があります。リセットしてもよろしいですか?", "overwriteTypeCustom": "カスタム", "overwriteTypeCustomDesc": "カスタムモード、プロキシグループとルールを完全にカスタマイズ可能", "unknownNetworkError": "不明なネットワークエラー", "networkRequestException": "ネットワーク要求例外、後でもう一度試してください。", "restoreException": "復元例外", "networkException": "ネットワーク例外、接続を確認してもう一度お試しください", "invalidBackupFile": "無効なバックアップファイル", "pruneCache": "キャッシュの削除", "backupAndRestore": "バックアップと復元", "backupAndRestoreDesc": "WebDAVまたはファイルを介してデータを同期する", "restore": "復元", "restoreSuccess": "復元に成功しました", "restoreFromWebDAVDesc": "WebDAVを介してデータを復元する", "restoreFromFileDesc": "ファイルを介してデータを復元する", "restoreOnlyConfig": "設定ファイルのみを復元する", "restoreAllData": "すべてのデータを復元する", "addProfile": "プロファイルを追加", "delayTest": "遅延テスト" } ================================================ FILE: arb/intl_ru.arb ================================================ { "rule": "Правило", "global": "Глобальный", "direct": "Прямой", "dashboard": "Панель управления", "proxies": "Прокси", "profile": "Профиль", "profiles": "Профили", "tools": "Инструменты", "logs": "Логи", "logsDesc": "Записи захвата логов", "resources": "Ресурсы", "resourcesDesc": "Информация, связанная с внешними ресурсами", "trafficUsage": "Использование трафика", "coreInfo": "Информация о ядре", "networkSpeed": "Скорость сети", "outboundMode": "Режим исходящего трафика", "networkDetection": "Обнаружение сети", "upload": "Загрузка", "download": "Скачивание", "noProxy": "Нет прокси", "noProxyDesc": "Пожалуйста, создайте профиль или добавьте действительный профиль", "nullProfileDesc": "Нет профиля, пожалуйста, добавьте профиль", "settings": "Настройки", "language": "Язык", "defaultText": "По умолчанию", "more": "Еще", "other": "Другое", "about": "О программе", "en": "Английский", "ja": "Японский", "ru": "Русский", "zh_CN": "Упрощенный китайский", "theme": "Тема", "themeDesc": "Установить темный режим, настроить цвет", "override": "Переопределить", "overrideDesc": "Переопределить конфигурацию, связанную с прокси", "allowLan": "Разрешить LAN", "allowLanDesc": "Разрешить доступ к прокси через локальную сеть", "tun": "TUN", "tunDesc": "действительно только в режиме администратора", "minimizeOnExit": "Свернуть при выходе", "minimizeOnExitDesc": "Изменить стандартное событие выхода из системы", "autoLaunch": "Автозапуск", "autoLaunchDesc": "Следовать автозапуску системы", "silentLaunch": "Тихий запуск", "silentLaunchDesc": "Запуск в фоновом режиме", "autoRun": "Автозапуск", "autoRunDesc": "Автоматический запуск при открытии приложения", "logcat": "Logcat", "logcatDesc": "Отключение скроет запись логов", "autoCheckUpdate": "Автопроверка обновлений", "autoCheckUpdateDesc": "Автоматически проверять обновления при запуске приложения", "accessControl": "Контроль доступа", "accessControlDesc": "Настройка доступа приложений к прокси", "application": "Приложение", "applicationDesc": "Изменение настроек, связанных с приложением", "edit": "Редактировать", "confirm": "Подтвердить", "update": "Обновить", "add": "Добавить", "save": "Сохранить", "delete": "Удалить", "years": "Лет", "months": "Месяцев", "hours": "Часов", "days": "Дней", "minutes": "Минут", "seconds": "Секунд", "ago": " назад", "just": "Только что", "qrcode": "QR-код", "qrcodeDesc": "Сканируйте QR-код для получения профиля", "url": "URL", "urlDesc": "Получить профиль через URL", "file": "Файл", "fileDesc": "Прямая загрузка профиля", "name": "Имя", "profileNameNullValidationDesc": "Пожалуйста, введите имя профиля", "profileUrlNullValidationDesc": "Пожалуйста, введите URL профиля", "profileUrlInvalidValidationDesc": "Пожалуйста, введите действительный URL профиля", "autoUpdate": "Автообновление", "autoUpdateInterval": "Интервал автообновления (минуты)", "profileAutoUpdateIntervalNullValidationDesc": "Пожалуйста, введите интервал времени для автообновления", "profileAutoUpdateIntervalInvalidValidationDesc": "Пожалуйста, введите действительный формат интервала времени", "themeMode": "Режим темы", "themeColor": "Цвет темы", "preview": "Предпросмотр", "auto": "Авто", "light": "Светлый", "dark": "Темный", "importFromURL": "Импорт из URL", "submit": "Отправить", "doYouWantToPass": "Вы хотите пропустить", "create": "Создать", "defaultSort": "Сортировка по умолчанию", "delaySort": "Сортировка по задержке", "nameSort": "Сортировка по имени", "pleaseUploadFile": "Пожалуйста, загрузите файл", "pleaseUploadValidQrcode": "Пожалуйста, загрузите действительный QR-код", "blacklistMode": "Режим черного списка", "whitelistMode": "Режим белого списка", "filterSystemApp": "Фильтровать системные приложения", "cancelFilterSystemApp": "Отменить фильтрацию системных приложений", "selectAll": "Выбрать все", "cancelSelectAll": "Отменить выбор всего", "appAccessControl": "Контроль доступа приложений", "accessControlAllowDesc": "Разрешить только выбранным приложениям доступ к VPN", "accessControlNotAllowDesc": "Выбранные приложения будут исключены из VPN", "selected": "Выбрано", "unableToUpdateCurrentProfileDesc": "невозможно обновить текущий профиль", "noMoreInfoDesc": "Нет дополнительной информации", "profileParseErrorDesc": "ошибка разбора профиля", "proxyPort": "Порт прокси", "proxyPortDesc": "Установить порт прослушивания Clash", "port": "Порт", "logLevel": "Уровень логов", "show": "Показать", "exit": "Выход", "systemProxy": "Системный прокси", "project": "Проект", "core": "Ядро", "tabAnimation": "Анимация вкладок", "desc": "Многоплатформенный прокси-клиент на основе ClashMeta, простой и удобный в использовании, с открытым исходным кодом и без рекламы.", "startVpn": "Запуск VPN...", "stopVpn": "Остановка VPN...", "discovery": "Обнаружена новая версия", "compatible": "Режим совместимости", "compatibleDesc": "Включение приведет к потере части функциональности приложения, но обеспечит полную поддержку Clash.", "notSelectedTip": "Текущая группа прокси не может быть выбрана.", "tip": "подсказка", "backupAndRecovery": "Резервное копирование и восстановление", "backupAndRecoveryDesc": "Синхронизация данных через WebDAV или файл", "account": "Аккаунт", "backup": "Резервное копирование", "recovery": "Восстановление", "recoveryProfiles": "Только восстановление профилей", "recoveryAll": "Восстановить все данные", "recoverySuccess": "Восстановление успешно", "backupSuccess": "Резервное копирование успешно", "noInfo": "Нет информации", "pleaseBindWebDAV": "Пожалуйста, привяжите WebDAV", "bind": "Привязать", "connectivity": "Связь:", "webDAVConfiguration": "Конфигурация WebDAV", "address": "Адрес", "addressHelp": "Адрес сервера WebDAV", "addressTip": "Пожалуйста, введите действительный адрес WebDAV", "password": "Пароль", "checkUpdate": "Проверить обновления", "discoverNewVersion": "Обнаружена новая версия", "checkUpdateError": "Текущее приложение уже является последней версией", "goDownload": "Перейти к загрузке", "unknown": "Неизвестно", "geoData": "Геоданные", "externalResources": "Внешние ресурсы", "checking": "Проверка...", "country": "Страна", "checkError": "Ошибка проверки", "search": "Поиск", "allowBypass": "Разрешить приложениям обходить VPN", "allowBypassDesc": "Некоторые приложения могут обходить VPN при включении", "externalController": "Внешний контроллер", "externalControllerDesc": "При включении ядро Clash можно контролировать на порту 9090", "ipv6Desc": "При включении будет возможно получать IPv6 трафик", "app": "Приложение", "general": "Общие", "vpnSystemProxyDesc": "Прикрепить HTTP-прокси к VpnService", "systemProxyDesc": "Прикрепить HTTP-прокси к VpnService", "unifiedDelay": "Унифицированная задержка", "unifiedDelayDesc": "Убрать дополнительные задержки, такие как рукопожатие", "tcpConcurrent": "TCP параллелизм", "tcpConcurrentDesc": "Включение позволит использовать параллелизм TCP", "geodataLoader": "Режим низкого потребления памяти для геоданных", "geodataLoaderDesc": "Включение будет использовать загрузчик геоданных с низким потреблением памяти", "requests": "Запросы", "requestsDesc": "Просмотр последних записей запросов", "findProcessMode": "Режим поиска процесса", "init": "Инициализация", "infiniteTime": "Долгосрочное действие", "expirationTime": "Время истечения", "connections": "Соединения", "connectionsDesc": "Просмотр текущих данных о соединениях", "intranetIP": "Внутренний IP", "view": "Просмотр", "cut": "Вырезать", "copy": "Копировать", "paste": "Вставить", "testUrl": "Тест URL", "sync": "Синхронизация", "exclude": "Скрыть из последних задач", "excludeDesc": "Когда приложение находится в фоновом режиме, оно скрыто из последних задач", "oneColumn": "Один столбец", "twoColumns": "Два столбца", "threeColumns": "Три столбца", "fourColumns": "Четыре столбца", "expand": "Стандартный", "shrink": "Сжать", "min": "Мин", "tab": "Вкладка", "list": "Список", "delay": "Задержка", "style": "Стиль", "size": "Размер", "sort": "Сортировка", "columns": "Столбцы", "proxiesSetting": "Настройка прокси", "proxyGroup": "Группа прокси", "go": "Перейти", "externalLink": "Внешняя ссылка", "otherContributors": "Другие участники", "autoCloseConnections": "Автоматическое закрытие соединений", "autoCloseConnectionsDesc": "Автоматически закрывать соединения после смены узла", "onlyStatisticsProxy": "Только статистика прокси", "onlyStatisticsProxyDesc": "При включении будет учитываться только трафик прокси", "pureBlackMode": "Чисто черный режим", "keepAliveIntervalDesc": "Интервал поддержания TCP-соединения", "entries": " записей", "local": "Локальный", "remote": "Удаленный", "remoteBackupDesc": "Резервное копирование локальных данных на WebDAV", "remoteRecoveryDesc": "Восстановление данных с WebDAV", "localBackupDesc": "Резервное копирование локальных данных на локальный диск", "localRecoveryDesc": "Восстановление данных из файла", "mode": "Режим", "time": "Время", "source": "Источник", "allApps": "Все приложения", "onlyOtherApps": "Только сторонние приложения", "action": "Действие", "intelligentSelected": "Интеллектуальный выбор", "clipboardImport": "Импорт из буфера обмена", "clipboardExport": "Экспорт в буфер обмена", "layout": "Макет", "tight": "Плотный", "standard": "Стандартный", "loose": "Свободный", "profilesSort": "Сортировка профилей", "start": "Старт", "stop": "Стоп", "appDesc": "Обработка настроек, связанных с приложением", "vpnDesc": "Изменение настроек, связанных с VPN", "dnsDesc": "Обновление настроек, связанных с DNS", "key": "Ключ", "value": "Значение", "hostsDesc": "Добавить Hosts", "vpnTip": "Изменения вступят в силу после перезапуска VPN", "vpnEnableDesc": "Автоматически направляет весь системный трафик через VpnService", "options": "Опции", "loopback": "Инструмент разблокировки Loopback", "loopbackDesc": "Используется для разблокировки Loopback UWP", "providers": "Провайдеры", "proxyProviders": "Провайдеры прокси", "ruleProviders": "Провайдеры правил", "overrideDns": "Переопределить DNS", "overrideDnsDesc": "Включение переопределит настройки DNS в профиле", "status": "Статус", "statusDesc": "Системный DNS будет использоваться при выключении", "preferH3Desc": "Приоритетное использование HTTP/3 для DOH", "respectRules": "Соблюдение правил", "respectRulesDesc": "DNS-соединение следует правилам, необходимо настроить proxy-server-nameserver", "dnsMode": "Режим DNS", "fakeipRange": "Диапазон Fakeip", "fakeipFilter": "Фильтр Fakeip", "defaultNameserver": "Сервер имен по умолчанию", "defaultNameserverDesc": "Для разрешения DNS-сервера", "nameserver": "Сервер имен", "nameserverDesc": "Для разрешения домена", "useHosts": "Использовать hosts", "useSystemHosts": "Использовать системные hosts", "nameserverPolicy": "Политика сервера имен", "nameserverPolicyDesc": "Указать соответствующую политику сервера имен", "proxyNameserver": "Прокси-сервер имен", "proxyNameserverDesc": "Домен для разрешения прокси-узлов", "fallback": "Резервный", "fallbackDesc": "Обычно используется оффшорный DNS", "fallbackFilter": "Фильтр резервного DNS", "geoipCode": "Код Geoip", "ipcidr": "IPCIDR", "domain": "Домен", "reset": "Сброс", "action_view": "Показать/Скрыть", "action_start": "Старт/Стоп", "action_mode": "Переключить режим", "action_proxy": "Системный прокси", "action_tun": "TUN", "disclaimer": "Отказ от ответственности", "disclaimerDesc": "Это программное обеспечение используется только в некоммерческих целях, таких как учебные обмены и научные исследования. Запрещено использовать это программное обеспечение в коммерческих целях. Любая коммерческая деятельность, если таковая имеется, не имеет отношения к этому программному обеспечению.", "agree": "Согласен", "hotkeyManagement": "Управление горячими клавишами", "hotkeyManagementDesc": "Использование клавиатуры для управления приложением", "pressKeyboard": "Пожалуйста, нажмите клавишу.", "inputCorrectHotkey": "Пожалуйста, введите правильную горячую клавишу", "hotkeyConflict": "Конфликт горячих клавиш", "remove": "Удалить", "noHotKey": "Нет горячей клавиши", "noNetwork": "Нет сети", "ipv6InboundDesc": "Разрешить входящий IPv6", "exportLogs": "Экспорт логов", "exportSuccess": "Экспорт успешен", "iconStyle": "Стиль иконки", "onlyIcon": "Только иконка", "noIcon": "Нет иконки", "stackMode": "Режим стека", "network": "Сеть", "networkDesc": "Изменение настроек, связанных с сетью", "bypassDomain": "Обход домена", "bypassDomainDesc": "Действует только при включенном системном прокси", "resetTip": "Убедитесь, что хотите сбросить", "regExp": "Регулярное выражение", "icon": "Иконка", "iconConfiguration": "Конфигурация иконки", "noData": "Нет данных", "adminAutoLaunch": "Автозапуск с правами администратора", "adminAutoLaunchDesc": "Запуск с правами администратора при загрузке системы", "fontFamily": "Семейство шрифтов", "systemFont": "Системный шрифт", "toggle": "Переключить", "system": "Система", "routeMode": "Режим маршрутизации", "routeMode_bypassPrivate": "Обход частных адресов маршрутизации", "routeMode_config": "Использовать конфигурацию", "routeAddress": "Адрес маршрутизации", "routeAddressDesc": "Настройка адреса прослушивания маршрутизации", "pleaseInputAdminPassword": "Пожалуйста, введите пароль администратора", "copyEnvVar": "Копирование переменных окружения", "memoryInfo": "Информация о памяти", "cancel": "Отмена", "fileIsUpdate": "Файл был изменен. Хотите сохранить изменения?", "profileHasUpdate": "Профиль был изменен. Хотите отключить автообновление?", "hasCacheChange": "Хотите сохранить изменения в кэше?", "copySuccess": "Копирование успешно", "copyLink": "Копировать ссылку", "exportFile": "Экспорт файла", "cacheCorrupt": "Кэш поврежден. Хотите очистить его?", "detectionTip": "Опирается на сторонний API, только для справки", "listen": "Слушать", "undo": "Отменить", "redo": "Повторить", "none": "Нет", "basicConfig": "Базовая конфигурация", "basicConfigDesc": "Глобальное изменение базовых настроек", "advancedConfig": "Расширенная конфигурация", "advancedConfigDesc": "Предоставляет разнообразные варианты конфигурации", "selectedCountTitle": "Выбрано {count} элементов", "addRule": "Добавить правило", "ruleName": "Название правила", "content": "Содержание", "subRule": "Подправило", "ruleTarget": "Цель правила", "sourceIp": "Исходный IP", "noResolve": "Не разрешать IP", "getOriginRules": "Получить оригинальные правила", "overrideOriginRules": "Переопределить оригинальное правило", "addedOriginRules": "Добавить к оригинальным правилам", "enableOverride": "Включить переопределение", "saveChanges": "Сохранить изменения?", "generalDesc": "Изменение общих настроек", "findProcessModeDesc": "При включении возможны небольшие потери производительности", "tabAnimationDesc": "Действительно только в мобильном виде", "saveTip": "Вы уверены, что хотите сохранить?", "colorSchemes": "Цветовые схемы", "palette": "Палитра", "tonalSpotScheme": "Тональный акцент", "fidelityScheme": "Точная передача", "monochromeScheme": "Монохром", "neutralScheme": "Нейтральные", "vibrantScheme": "Яркие", "expressiveScheme": "Экспрессивные", "contentScheme": "Контентная тема", "rainbowScheme": "Радужные", "fruitSaladScheme": "Фруктовый микс", "developerMode": "Режим разработчика", "developerModeEnableTip": "Режим разработчика активирован.", "messageTest": "Тестирование сообщения", "messageTestTip": "Это сообщение.", "crashTest": "Тест на сбои", "clearData": "Очистить данные", "zoom": "Масштаб", "textScale": "Масштабирование текста", "internet": "Интернет", "systemApp": "Системное приложение", "noNetworkApp": "Приложение без сети", "contactMe": "Свяжитесь со мной", "restoreStrategy": "Стратегия восстановления", "restoreStrategy_override": "Перезаписать", "restoreStrategy_compatible": "Совместимый", "logsTest": "Тест журналов", "emptyTip": "{label} не может быть пустым", "urlTip": "{label} должен быть URL", "numberTip": "{label} должно быть числом", "interval": "Интервал", "existsTip": "Текущий {label} уже существует", "deleteTip": "Вы уверены, что хотите удалить текущий {label}?", "deleteMultipTip": "Вы уверены, что хотите удалить выбранные {label}?", "nullTip": "{label} пока отсутствуют", "script": "Скрипт", "color": "Цвет", "rename": "Переименовать", "unnamed": "Без имени", "pleaseEnterScriptName": "Пожалуйста, введите название скрипта", "overrideInvalidTip": "В скриптовом режиме не действует", "mixedPort": "Смешанный порт", "socksPort": "Socks-порт", "redirPort": "Redir-порт", "tproxyPort": "Tproxy-порт", "portTip": "{label} должен быть числом от 1024 до 49151", "portConflictTip": "Введите другой порт", "import": "Импорт", "importFile": "Импорт из файла", "importUrl": "Импорт по URL", "autoSetSystemDns": "Автоматическая настройка системного DNS", "details": "Детали {}", "creationTime": "Время создания", "process": "процесс", "host": "Хост", "destination": "Назначение", "destinationGeoIP": "Геолокация назначения", "destinationIPASN": "ASN назначения", "specialProxy": "Специальный прокси", "specialRules": "Специальные правила", "remoteDestination": "Удалённое назначение", "networkType": "Тип сети", "proxyChains": "Цепочки прокси", "log": "Журнал", "connection": "Соединение", "request": "Запрос", "connected": "Подключено", "disconnected": "Отключено", "connecting": "Подключение...", "restartCoreTip": "Вы уверены, что хотите перезапустить ядро?", "forceRestartCoreTip": "Вы уверены, что хотите принудительно перезапустить ядро?", "dnsHijacking": "DNS-перехват", "coreStatus": "Основной статус", "dataCollectionTip": "Уведомление о сборе данных", "dataCollectionContent": "Это приложение использует Firebase Crashlytics для сбора информации о сбоях nhằm улучшения стабильности приложения.\nСобираемые данные включают информацию об устройстве и подробности о сбоях, но не содержат персональных конфиденциальных данных.\nВы можете отключить эту функцию в настройках.", "crashlytics": "Анализ сбоев", "crashlyticsTip": "При включении автоматически загружает журналы сбоев без конфиденциальной информации, когда приложение выходит из строя", "appendSystemDns": "Добавить системный DNS", "appendSystemDnsTip": "Принудительно добавить системный DNS к конфигурации", "editRule": "Редактировать правило", "overrideMode": "Режим переопределения", "standardModeDesc": "Стандартный режим, переопределение базовой конфигурации, предоставление возможности простого добавления правил", "scriptModeDesc": "Режим скрипта, использование внешних расширяющих скриптов, предоставление возможности переопределения конфигурации одним кликом", "addedRules": "Добавленные правила", "controlGlobalAddedRules": "Управление глобальными добавленными правилами", "overrideScript": "Скрипт переопределения", "goToConfigureScript": "Перейти к настройке скрипта", "editGlobalRules": "Редактировать глобальные правила", "externalFetch": "Внешнее получение", "confirmForceCrashCore": "Вы уверены, что хотите принудительно аварийно завершить работу ядра?", "confirmClearAllData": "Вы уверены, что хотите очистить все данные?", "loading": "Загрузка...", "loadTest": "Тест загрузки", "yearsAgo": "{count, plural, one{{count} год назад} few{{count} года назад} many{{count} лет назад} other{{count} года назад}}", "monthsAgo": "{count, plural, one{{count} месяц назад} few{{count} месяца назад} many{{count} месяцев назад} other{{count} месяца назад}}", "daysAgo": "{count, plural, one{{count} день назад} few{{count} дня назад} many{{count} дней назад} other{{count} дня назад}}", "hoursAgo": "{count, plural, one{{count} час назад} few{{count} часа назад} many{{count} часов назад} other{{count} часа назад}}", "minutesAgo": "{count, plural, one{{count} минута назад} few{{count} минуты назад} many{{count} минут назад} other{{count} минуты назад}}", "justNow": "Только что", "noLongerRemind": "Больше не напоминать", "accessControlSettings": "Настройки контроля доступа", "turnOn": "Включить", "turnOff": "Выключить", "coreConfigChangeDetected": "Обнаружено изменение конфигурации ядра", "reload": "Перезагрузить", "vpnConfigChangeDetected": "Обнаружено изменение конфигурации VPN", "restart": "Перезапустить", "speedStatistics": "Статистика скорости", "resetPageChangesTip": "На текущей странице есть изменения. Вы уверены, что хотите сбросить?", "overwriteTypeCustom": "Пользовательский", "overwriteTypeCustomDesc": "Пользовательский режим, полная настройка групп прокси и правил", "unknownNetworkError": "Неизвестная сетевая ошибка", "networkRequestException": "Исключение сетевого запроса, пожалуйста, попробуйте позже.", "restoreException": "Ошибка восстановления", "networkException": "Ошибка сети, проверьте соединение и попробуйте еще раз", "invalidBackupFile": "Неверный файл резервной копии", "pruneCache": "Очистить кэш", "backupAndRestore": "Резервное копирование и восстановление", "backupAndRestoreDesc": "Синхронизация данных через WebDAV или файлы", "restore": "Восстановить", "restoreSuccess": "Восстановление успешно", "restoreFromWebDAVDesc": "Восстановить данные через WebDAV", "restoreFromFileDesc": "Восстановить данные из файла", "restoreOnlyConfig": "Восстановить только файлы конфигурации", "restoreAllData": "Восстановить все данные", "addProfile": "Добавить профиль", "delayTest": "Тест задержки" } ================================================ FILE: arb/intl_zh_CN.arb ================================================ { "rule": "规则", "global": "全局", "direct": "直连", "dashboard": "仪表盘", "proxies": "代理", "profile": "配置", "profiles": "配置", "tools": "工具", "logs": "日志", "logsDesc": "日志捕获记录", "resources": "资源", "resourcesDesc": "外部资源相关信息", "trafficUsage": "流量统计", "coreInfo": "内核信息", "networkSpeed": "网络速度", "outboundMode": "出站模式", "networkDetection": "网络检测", "upload": "上传", "download": "下载", "noProxy": "暂无代理", "noProxyDesc": "请创建配置文件或者添加有效配置文件", "nullProfileDesc": "没有配置文件,请先添加配置文件", "settings": "设置", "language": "语言", "defaultText": "默认", "more": "更多", "other": "其他", "about": "关于", "en": "英语", "ja": "日语", "ru": "俄语", "zh_CN": "中文简体", "theme": "主题", "themeDesc": "设置深色模式,调整色彩", "override": "覆写", "overrideDesc": "覆写代理相关配置", "allowLan": "局域网代理", "allowLanDesc": "允许通过局域网访问代理", "tun": "虚拟网卡", "tunDesc": "仅在管理员模式生效", "minimizeOnExit": "退出时最小化", "minimizeOnExitDesc": "修改系统默认退出事件", "autoLaunch": "自启动", "autoLaunchDesc": "跟随系统自启动", "silentLaunch": "静默启动", "silentLaunchDesc": "后台启动", "autoRun": "自动运行", "autoRunDesc": "应用打开时自动运行", "logcat": "日志捕获", "logcatDesc": "禁用将会隐藏日志入口", "autoCheckUpdate": "自动检查更新", "autoCheckUpdateDesc": "应用启动时自动检查更新", "accessControl": "访问控制", "accessControlDesc": "配置应用访问代理", "application": "应用程序", "applicationDesc": "修改应用程序相关设置", "edit": "编辑", "confirm": "确定", "update": "更新", "add": "添加", "save": "保存", "delete": "删除", "years": "年", "months": "月", "hours": "小时", "days": "天", "minutes": "分钟", "seconds": "秒", "ago": "前", "just": "刚刚", "qrcode": "二维码", "qrcodeDesc": "扫描二维码获取配置文件", "url": "URL", "urlDesc": "通过URL获取配置文件", "file": "文件", "fileDesc": "直接上传配置文件", "name": "名称", "profileNameNullValidationDesc": "请输入配置名称", "profileUrlNullValidationDesc": "请输入配置URL", "profileUrlInvalidValidationDesc": "请输入有效配置URL", "autoUpdate": "自动更新", "autoUpdateInterval": "自动更新间隔(分钟)", "profileAutoUpdateIntervalNullValidationDesc": "请输入自动更新间隔时间", "profileAutoUpdateIntervalInvalidValidationDesc": "请输入有效间隔时间格式", "themeMode": "主题模式", "themeColor": "主题色彩", "preview": "预览", "auto": "自动", "light": "浅色", "dark": "深色", "importFromURL": "从URL导入", "submit": "提交", "doYouWantToPass": "是否要通过", "create": "创建", "defaultSort": "按默认排序", "delaySort": "按延迟排序", "nameSort": "按名称排序", "pleaseUploadFile": "请上传文件", "pleaseUploadValidQrcode": "请上传有效的二维码", "blacklistMode": "黑名单模式", "whitelistMode": "白名单模式", "filterSystemApp": "过滤系统应用", "cancelFilterSystemApp": "取消过滤系统应用", "selectAll": "全选", "cancelSelectAll": "取消全选", "appAccessControl": "应用访问控制", "accessControlAllowDesc": "只允许选中应用进入VPN", "accessControlNotAllowDesc": "选中应用将会被排除在VPN之外", "selected": "已选择", "unableToUpdateCurrentProfileDesc": "无法更新当前配置文件", "noMoreInfoDesc": "暂无更多信息", "profileParseErrorDesc": "配置文件解析错误", "proxyPort": "代理端口", "proxyPortDesc": "设置Clash监听端口", "port": "端口", "logLevel": "日志等级", "show": "显示", "exit": "退出", "systemProxy": "系统代理", "project": "项目", "core": "内核", "tabAnimation": "选项卡动画", "desc": "基于ClashMeta的多平台代理客户端,简单易用,开源无广告。", "startVpn": "正在启动VPN...", "stopVpn": "正在停止VPN...", "discovery": "发现新版本", "compatible": "兼容模式", "compatibleDesc": "开启将失去部分应用能力,获得全量的Clash的支持", "notSelectedTip": "当前代理组无法选中", "tip": "提示", "account": "账号", "backup": "备份", "backupSuccess": "备份成功", "noInfo": "暂无信息", "pleaseBindWebDAV": "请绑定WebDAV", "bind": "绑定", "connectivity": "连通性:", "webDAVConfiguration": "WebDAV配置", "address": "地址", "addressHelp": "WebDAV服务器地址", "addressTip": "请输入有效的WebDAV地址", "password": "密码", "checkUpdate": "检查更新", "discoverNewVersion": "发现新版本", "checkUpdateError": "当前应用已经是最新版了", "goDownload": "前往下载", "unknown": "未知", "geoData": "地理数据", "externalResources": "外部资源", "checking": "检测中...", "country": "区域", "checkError": "检测失败", "search": "搜索", "allowBypass": "允许应用绕过VPN", "allowBypassDesc": "开启后部分应用可绕过VPN", "externalController": "外部控制器", "externalControllerDesc": "开启后将可以通过9090端口控制Clash内核", "ipv6Desc": "开启后将可以接收IPv6流量", "app": "应用", "general": "常规", "vpnSystemProxyDesc": "为VpnService附加HTTP代理", "systemProxyDesc": "设置系统代理", "unifiedDelay": "统一延迟", "unifiedDelayDesc": "去除握手等额外延迟", "tcpConcurrent": "TCP并发", "tcpConcurrentDesc": "开启后允许TCP并发", "geodataLoader": "Geo低内存模式", "geodataLoaderDesc": "开启将使用Geo低内存加载器", "requests": "请求", "requestsDesc": "查看最近请求记录", "findProcessMode": "查找进程", "init": "初始化", "infiniteTime": "长期有效", "expirationTime": "到期时间", "connections": "连接", "connectionsDesc": "查看当前连接数据", "intranetIP": "内网 IP", "view": "查看", "cut": "剪切", "copy": "复制", "paste": "粘贴", "testUrl": "测速链接", "sync": "同步", "exclude": "从最近任务中隐藏", "excludeDesc": "应用在后台时,从最近任务中隐藏应用", "oneColumn": "一列", "twoColumns": "两列", "threeColumns": "三列", "fourColumns": "四列", "expand": "标准", "shrink": "紧凑", "min": "最小", "tab": "标签页", "list": "列表", "delay": "延迟", "style": "风格", "size": "尺寸", "sort": "排序", "columns": "列数", "proxiesSetting": "代理设置", "proxyGroup": "代理组", "go": "前往", "externalLink": "外部链接", "otherContributors": "其他贡献者", "autoCloseConnections": "自动关闭连接", "autoCloseConnectionsDesc": "切换节点后自动关闭连接", "onlyStatisticsProxy": "仅统计代理", "onlyStatisticsProxyDesc": "开启后,将只统计代理流量", "pureBlackMode": "纯黑模式", "keepAliveIntervalDesc": "TCP保持活动间隔", "entries": "个条目", "local": "本地", "remote": "远程", "remoteBackupDesc": "备份数据到WebDAV", "localBackupDesc": "备份数据到本地", "mode": "模式", "time": "时间", "source": "来源", "allApps": "所有应用", "onlyOtherApps": "仅第三方应用", "action": "操作", "intelligentSelected": "智能选择", "clipboardImport": "剪贴板导入", "clipboardExport": "导出剪贴板", "layout": "布局", "tight": "紧凑", "standard": "标准", "loose": "宽松", "profilesSort": "配置排序", "start": "启动", "stop": "暂停", "appDesc": "处理应用相关设置", "vpnDesc": "修改VPN相关设置", "dnsDesc": "更新DNS相关设置", "key": "键", "value": "值", "hostsDesc": "追加Hosts", "vpnTip": "重启VPN后改变生效", "vpnEnableDesc": "通过VpnService自动路由系统所有流量", "options": "选项", "loopback": "回环解锁工具", "loopbackDesc": "用于UWP回环解锁", "providers": "提供者", "proxyProviders": "代理提供者", "ruleProviders": "规则提供者", "overrideDns": "覆写DNS", "overrideDnsDesc": "开启后将覆盖配置中的DNS选项", "status": "状态", "statusDesc": "关闭后将使用系统DNS", "preferH3Desc": "优先使用DOH的http/3", "respectRules": "遵守规则", "respectRulesDesc": "DNS连接跟随rules,需配置proxy-server-nameserver", "dnsMode": "DNS模式", "fakeipRange": "Fakeip范围", "fakeipFilter": "Fakeip过滤", "defaultNameserver": "默认域名服务器", "defaultNameserverDesc": "用于解析DNS服务器", "nameserver": "域名服务器", "nameserverDesc": "用于解析域名", "useHosts": "使用Hosts", "useSystemHosts": "使用系统Hosts", "nameserverPolicy": "域名服务器策略", "nameserverPolicyDesc": "指定对应域名服务器策略", "proxyNameserver": "代理域名服务器", "proxyNameserverDesc": "用于解析代理节点的域名", "fallback": "Fallback", "fallbackDesc": "一般情况下使用境外DNS", "fallbackFilter": "Fallback过滤", "geoipCode": "Geoip代码", "ipcidr": "IP/掩码", "domain": "域名", "reset": "重置", "action_view": "显示/隐藏", "action_start": "启动/停止", "action_mode": "切换模式", "action_proxy": "系统代理", "action_tun": "虚拟网卡", "disclaimer": "免责声明", "disclaimerDesc": "本软件仅供学习交流、科研等非商业性质的用途,严禁将本软件用于商业目的。如有任何商业行为,均与本软件无关。", "agree": "同意", "hotkeyManagement": "快捷键管理", "hotkeyManagementDesc": "使用键盘控制应用程序", "pressKeyboard": "请按下按键", "inputCorrectHotkey": "请输入正确的快捷键", "hotkeyConflict": "快捷键冲突", "remove": "移除", "noHotKey": "暂无快捷键", "noNetwork": "无网络", "ipv6InboundDesc": "允许IPv6入站", "exportLogs": "导出日志", "exportSuccess": "导出成功", "iconStyle": "图标样式", "onlyIcon": "仅图标", "noIcon": "无图标", "stackMode": "栈模式", "network": "网络", "networkDesc": "修改网络相关设置", "bypassDomain": "排除域名", "bypassDomainDesc": "仅在系统代理启用时生效", "resetTip": "确定要重置吗?", "regExp": "正则", "icon": "图片", "iconConfiguration": "图片配置", "noData": "暂无数据", "adminAutoLaunch": "管理员自启动", "adminAutoLaunchDesc": "使用管理员模式开机自启动", "fontFamily": "字体", "systemFont": "系统字体", "toggle": "切换", "system": "系统", "routeMode": "路由模式", "routeMode_bypassPrivate": "绕过私有路由地址", "routeMode_config": "使用配置", "routeAddress": "路由地址", "routeAddressDesc": "配置监听路由地址", "pleaseInputAdminPassword": "请输入管理员密码", "copyEnvVar": "复制环境变量", "memoryInfo": "内存信息", "cancel": "取消", "fileIsUpdate": "文件有修改,是否保存修改", "profileHasUpdate": "配置文件已经修改,是否关闭自动更新 ", "hasCacheChange": "是否缓存修改", "copySuccess": "复制成功", "copyLink": "复制链接", "exportFile": "导出文件", "cacheCorrupt": "缓存已损坏,是否清空?", "detectionTip": "依赖第三方api,仅供参考", "listen": "监听", "undo": "撤销", "redo": "重做", "none": "无", "basicConfig": "基本配置", "basicConfigDesc": "全局修改基本配置", "advancedConfig": "进阶配置", "advancedConfigDesc": "提供多样化配置", "selectedCountTitle": "已选择 {count} 项", "addRule": "添加规则", "ruleName": "规则名称", "content": "内容", "subRule": "子规则", "ruleTarget": "规则目标", "sourceIp": "源IP", "noResolve": "不解析IP", "getOriginRules": "获取原始规则", "overrideOriginRules": "覆盖原始规则", "addedOriginRules": "附加到原始规则", "enableOverride": "启用覆写", "saveChanges": "是否保存更改?", "generalDesc": "修改通用设置", "findProcessModeDesc": "开启后会有一定性能损耗", "tabAnimationDesc": "仅在移动视图中有效", "saveTip": "确定要保存吗?", "colorSchemes": "配色方案", "palette": "调色板", "tonalSpotScheme": "调性点缀", "fidelityScheme": "高保真", "monochromeScheme": "单色", "neutralScheme": "中性", "vibrantScheme": "活力", "expressiveScheme": "表现力", "contentScheme": "内容主题", "rainbowScheme": "彩虹", "fruitSaladScheme": "果缤纷", "developerMode": "开发者模式", "developerModeEnableTip": "开发者模式已启用。", "messageTest": "消息测试", "messageTestTip": "这是一条消息。", "crashTest": "崩溃测试", "clearData": "清除数据", "zoom": "缩放", "textScale": "文本缩放", "internet": "互联网", "systemApp": "系统应用", "noNetworkApp": "无网络应用", "contactMe": "联系我", "restoreStrategy": "恢复策略", "restoreStrategy_override": "覆盖", "restoreStrategy_compatible": "兼容", "logsTest": "日志测试", "emptyTip": "{label}不能为空", "urlTip": "{label}必须为URL", "numberTip": "{label}必须为数字", "interval": "间隔", "existsTip": "{label}当前已存在", "deleteTip": "确定删除当前{label}吗?", "deleteMultipTip": "确定删除选中的{label}吗?", "nullTip": "暂无{label}", "script": "脚本", "color": "颜色", "rename": "重命名", "unnamed": "未命名", "pleaseEnterScriptName": "请输入脚本名称", "overrideInvalidTip": "在脚本模式下不生效", "mixedPort": "混合端口", "socksPort": "Socks端口", "redirPort": "Redir端口", "tproxyPort": "Tproxy端口", "portTip": "{label} 必须在 1024 到 49151 之间", "portConflictTip": "请输入不同的端口", "import": "导入", "importFile": "通过文件导入", "importUrl": "通过URL导入", "autoSetSystemDns": "自动设置系统DNS", "details": "{label}详情", "creationTime": "创建时间", "process": "进程", "host": "主机", "destination": "目标地址", "destinationGeoIP": "目标地理定位", "destinationIPASN": "目标IP ASN", "specialProxy": "特殊代理", "specialRules": "特殊规则", "remoteDestination": "远程目标", "networkType": "网络类型", "proxyChains": "代理链", "log": "日志", "connection": "连接", "request": "请求", "connected": "已连接", "disconnected": "已断开", "connecting": "连接中...", "restartCoreTip": "您确定要重启核心吗?", "forceRestartCoreTip": "您确定要强制重启核心吗?", "dnsHijacking": "DNS劫持", "coreStatus": "核心状态", "dataCollectionTip": "数据收集说明", "dataCollectionContent": "本应用使用 Firebase Crashlytics 收集崩溃信息以改进应用稳定性。\n收集的数据包括设备信息和崩溃详情,不包含个人敏感数据。\n您可以在设置中关闭此功能。", "crashlytics": "崩溃分析", "crashlyticsTip": "开启后,应用崩溃时自动上传不包含敏感信息的崩溃日志", "appendSystemDns": "追加系统DNS", "appendSystemDnsTip": "强制为配置附加系统DNS", "editRule": "编辑规则", "overrideMode": "覆写模式", "standardModeDesc": "标准模式,覆写基本配置,提供简单追加规则能力", "scriptModeDesc": "脚本模式,使用外部扩展脚本,提供一键覆写配置的能力", "addedRules": "附加规则", "controlGlobalAddedRules": "控制全局附加规则", "overrideScript": "覆写脚本", "goToConfigureScript": "前往配置脚本", "editGlobalRules": "编辑全局规则", "externalFetch": "外部获取", "confirmForceCrashCore": "确定要强制崩溃核心?", "confirmClearAllData": "确定要清除所有数据?", "loading": "加载中...", "loadTest": "加载测试", "yearsAgo": "{count} 年前", "monthsAgo": "{count} 个月前", "daysAgo": "{count} 天前", "hoursAgo": "{count} 小时前", "minutesAgo": "{count} 分钟前", "justNow": "刚刚", "noLongerRemind": "不再提示", "accessControlSettings": "访问控制设置", "turnOn": "开启", "turnOff": "关闭", "coreConfigChangeDetected": "检测到核心配置更改", "reload": "重载", "vpnConfigChangeDetected": "检测到VPN相关配置改动", "restart": "重启", "speedStatistics": "网速统计", "resetPageChangesTip": "当前页面存在更改,确定重置吗?", "overwriteTypeCustom": "自定义", "overwriteTypeCustomDesc": "自定义模式,支持完全自定义修改代理组以及规则", "unknownNetworkError": "未知网络错误", "networkRequestException": "网络请求异常,请稍后再试。", "restoreException": "恢复异常", "networkException": "网络异常,请检查连接后重试", "invalidBackupFile": "无效备份文件", "pruneCache": "修剪缓存", "backupAndRestore": "备份与恢复", "backupAndRestoreDesc": "通过WebDAV或者文件同步数据", "restore": "恢复", "restoreSuccess": "恢复成功", "restoreFromWebDAVDesc": "通过WebDAV恢复数据", "restoreFromFileDesc": "通过文件恢复数据", "restoreOnlyConfig": "仅恢复配置文件", "restoreAllData": "恢复所有数据", "addProfile": "添加配置", "delayTest": "延迟测试" } ================================================ FILE: assets/data/ASN.mmdb ================================================ [File too large to display: 10.3 MB] ================================================ FILE: build.yaml ================================================ targets: $default: builders: source_gen:combining_builder: options: build_extensions: '^lib/models/{{}}.dart': 'lib/models/generated/{{}}.g.dart' '^lib/providers/{{}}.dart': 'lib/providers/generated/{{}}.g.dart' '^lib/database/{{}}.dart': 'lib/database/generated/{{}}.g.dart' freezed: options: build_extensions: '^lib/models/{{}}.dart': 'lib/models/generated/{{}}.freezed.dart' ================================================ FILE: core/action.go ================================================ package main import ( "encoding/json" "unsafe" ) type Action struct { Id string `json:"id"` Method Method `json:"method"` Data interface{} `json:"data"` } type ActionResult struct { Id string `json:"id"` Method Method `json:"method"` Data interface{} `json:"data"` Code int `json:"code"` callback unsafe.Pointer } func (result ActionResult) Json() ([]byte, error) { data, err := json.Marshal(result) return data, err } func (result ActionResult) success(data interface{}) { result.Code = 0 result.Data = data result.send() } func (result ActionResult) error(data interface{}) { result.Code = -1 result.Data = data result.send() } func handleAction(action *Action, result ActionResult) { switch action.Method { case initClashMethod: paramsString := action.Data.(string) result.success(handleInitClash(paramsString)) return case getIsInitMethod: result.success(handleGetIsInit()) return case forceGcMethod: handleForceGC() result.success(true) return case shutdownMethod: result.success(handleShutdown()) return case validateConfigMethod: path := action.Data.(string) result.success(handleValidateConfig(path)) return case updateConfigMethod: data := []byte(action.Data.(string)) result.success(handleUpdateConfig(data)) return case setupConfigMethod: data := []byte(action.Data.(string)) result.success(handleSetupConfig(data)) return case getProxiesMethod: result.success(handleGetProxies()) return case changeProxyMethod: data := action.Data.(string) handleChangeProxy(data, func(value string) { result.success(value) }) return case getTrafficMethod: data := action.Data.(bool) result.success(handleGetTraffic(data)) return case getTotalTrafficMethod: data := action.Data.(bool) result.success(handleGetTotalTraffic(data)) return case resetTrafficMethod: handleResetTraffic() result.success(true) return case asyncTestDelayMethod: data := action.Data.(string) handleAsyncTestDelay(data, func(value string) { result.success(value) }) return case getConnectionsMethod: result.success(handleGetConnections()) return case closeConnectionsMethod: result.success(handleCloseConnections()) return case resetConnectionsMethod: result.success(handleResetConnections()) return case getConfigMethod: path := action.Data.(string) config, err := handleGetConfig(path) if err != nil { result.error(err) return } result.success(config) return case closeConnectionMethod: id := action.Data.(string) result.success(handleCloseConnection(id)) return case getExternalProvidersMethod: result.success(handleGetExternalProviders()) return case getExternalProviderMethod: externalProviderName := action.Data.(string) result.success(handleGetExternalProvider(externalProviderName)) case updateGeoDataMethod: paramsString := action.Data.(string) var params = map[string]string{} err := json.Unmarshal([]byte(paramsString), ¶ms) if err != nil { result.success(err.Error()) return } geoType := params["geo-type"] geoName := params["geo-name"] handleUpdateGeoData(geoType, geoName, func(value string) { result.success(value) }) return case updateExternalProviderMethod: providerName := action.Data.(string) handleUpdateExternalProvider(providerName, func(value string) { result.success(value) }) return case sideLoadExternalProviderMethod: paramsString := action.Data.(string) var params = map[string]string{} err := json.Unmarshal([]byte(paramsString), ¶ms) if err != nil { result.success(err.Error()) return } providerName := params["providerName"] data := params["data"] handleSideLoadExternalProvider(providerName, []byte(data), func(value string) { result.success(value) }) return case startLogMethod: handleStartLog() result.success(true) return case stopLogMethod: handleStopLog() result.success(true) return case startListenerMethod: result.success(handleStartListener()) return case stopListenerMethod: result.success(handleStopListener()) return case getCountryCodeMethod: ip := action.Data.(string) handleGetCountryCode(ip, func(value string) { result.success(value) }) return case getMemoryMethod: handleGetMemory(func(value string) { result.success(value) }) return case crashMethod: result.success(true) handleCrash() case deleteFile: path := action.Data.(string) handleDelFile(path, result) return default: nextHandle(action, result) } } ================================================ FILE: core/bride.c ================================================ #include "bride.h" void (*release_object_func)(void *obj); void (*free_string_func)(char *data); void (*protect_func)(void *tun_interface, int fd); char* (*resolve_process_func)(void *tun_interface,int protocol, const char *source, const char *target, int uid); void (*result_func)(void *invoke_Interface, const char *data); void protect(void *tun_interface, int fd) { protect_func(tun_interface, fd); } char* resolve_process(void *tun_interface, int protocol, const char *source, const char *target, int uid) { return resolve_process_func(tun_interface, protocol, source, target, uid); } void release_object(void *obj) { release_object_func(obj); } void free_string(char *data) { free_string_func(data); } void result(void *invoke_Interface, const char *data) { return result_func(invoke_Interface, data); } ================================================ FILE: core/bride.go ================================================ //go:build android && cgo package main //#include "bride.h" import "C" import "unsafe" func protect(callback unsafe.Pointer, fd int) { C.protect(callback, C.int(fd)) } func resolveProcess(callback unsafe.Pointer, protocol int, source, target string, uid int) string { s := C.CString(source) defer C.free(unsafe.Pointer(s)) t := C.CString(target) defer C.free(unsafe.Pointer(t)) res := C.resolve_process(callback, C.int(protocol), s, t, C.int(uid)) return takeCString(res) } func invokeResult(callback unsafe.Pointer, data string) { s := C.CString(data) defer C.free(unsafe.Pointer(s)) C.result(callback, s) } func releaseObject(callback unsafe.Pointer) { C.release_object(callback) } func takeCString(s *C.char) string { defer C.free_string(s) return C.GoString(s) } ================================================ FILE: core/bride.h ================================================ #pragma once #include extern void (*release_object_func)(void *obj); extern void (*free_string_func)(char *data); extern void (*protect_func)(void *tun_interface, int fd); extern char* (*resolve_process_func)(void *tun_interface, int protocol, const char *source, const char *target, int uid); extern void (*result_func)(void *invoke_Interface, const char *data); extern void protect(void *tun_interface, int fd); extern char* resolve_process(void *tun_interface, int protocol, const char *source, const char *target, int uid); extern void release_object(void *obj); extern void free_string(char *data); extern void result(void *invoke_Interface, const char *data); ================================================ FILE: core/common.go ================================================ package main import ( b "bytes" "context" "encoding/json" "errors" "github.com/metacubex/mihomo/adapter" "github.com/metacubex/mihomo/adapter/inbound" "github.com/metacubex/mihomo/adapter/outboundgroup" "github.com/metacubex/mihomo/adapter/provider" "github.com/metacubex/mihomo/common/batch" "github.com/metacubex/mihomo/component/dialer" "github.com/metacubex/mihomo/component/resolver" "github.com/metacubex/mihomo/config" "github.com/metacubex/mihomo/constant" "github.com/metacubex/mihomo/constant/features" cp "github.com/metacubex/mihomo/constant/provider" "github.com/metacubex/mihomo/hub" "github.com/metacubex/mihomo/hub/executor" "github.com/metacubex/mihomo/hub/route" "github.com/metacubex/mihomo/listener" "github.com/metacubex/mihomo/log" rp "github.com/metacubex/mihomo/rules/provider" "github.com/metacubex/mihomo/tunnel" "os" "path/filepath" "runtime" "sync" ) var ( currentConfig *config.Config version = 0 isRunning = false runLock sync.Mutex mBatch, _ = batch.New[bool](context.Background(), batch.WithConcurrencyNum[bool](50)) ) func getExternalProvidersRaw() map[string]cp.Provider { eps := make(map[string]cp.Provider) for n, p := range tunnel.Providers() { if p.VehicleType() != cp.Compatible { eps[n] = p } } for n, p := range tunnel.RuleProviders() { if p.VehicleType() != cp.Compatible { eps[n] = p } } return eps } func toExternalProvider(p cp.Provider) (*ExternalProvider, error) { switch p.(type) { case *provider.ProxySetProvider: psp := p.(*provider.ProxySetProvider) return &ExternalProvider{ Name: psp.Name(), Type: psp.Type().String(), VehicleType: psp.VehicleType().String(), Count: psp.Count(), UpdateAt: psp.UpdatedAt(), Path: psp.Vehicle().Path(), SubscriptionInfo: psp.GetSubscriptionInfo(), }, nil case *rp.RuleSetProvider: rsp := p.(*rp.RuleSetProvider) return &ExternalProvider{ Name: rsp.Name(), Type: rsp.Type().String(), VehicleType: rsp.VehicleType().String(), Count: rsp.Count(), UpdateAt: rsp.UpdatedAt(), Path: rsp.Vehicle().Path(), }, nil default: return nil, errors.New("not external provider") } } func sideUpdateExternalProvider(p cp.Provider, bytes []byte) error { switch p.(type) { case *provider.ProxySetProvider: psp := p.(*provider.ProxySetProvider) _, _, err := psp.SideUpdate(bytes) if err == nil { return err } return nil case rp.RuleSetProvider: rsp := p.(*rp.RuleSetProvider) _, _, err := rsp.SideUpdate(bytes) if err == nil { return err } return nil default: return errors.New("not external provider") } } func updateListeners() { if !isRunning { return } if currentConfig == nil { return } listeners := currentConfig.Listeners general := currentConfig.General listener.PatchInboundListeners(listeners, tunnel.Tunnel, true) allowLan := general.AllowLan listener.SetAllowLan(allowLan) inbound.SetSkipAuthPrefixes(general.SkipAuthPrefixes) inbound.SetAllowedIPs(general.LanAllowedIPs) inbound.SetDisAllowedIPs(general.LanDisAllowedIPs) bindAddress := general.BindAddress listener.SetBindAddress(bindAddress) listener.ReCreateHTTP(general.Port, tunnel.Tunnel) listener.ReCreateSocks(general.SocksPort, tunnel.Tunnel) listener.ReCreateRedir(general.RedirPort, tunnel.Tunnel) listener.ReCreateTProxy(general.TProxyPort, tunnel.Tunnel) listener.ReCreateMixed(general.MixedPort, tunnel.Tunnel) listener.ReCreateShadowSocks(general.ShadowSocksConfig, tunnel.Tunnel) listener.ReCreateVmess(general.VmessConfig, tunnel.Tunnel) listener.ReCreateTuic(general.TuicServer, tunnel.Tunnel) if !features.Android { listener.ReCreateTun(general.Tun, tunnel.Tunnel) } } func stopListeners() { listener.StopListener() } func patchSelectGroup(mapping map[string]string) { for name, proxy := range tunnel.ProxiesWithProviders() { outbound, ok := proxy.(*adapter.Proxy) if !ok { continue } selector, ok := outbound.ProxyAdapter.(outboundgroup.SelectAble) if !ok { continue } selected, exist := mapping[name] if !exist { continue } selector.ForceSet(selected) } } func defaultSetupParams() *SetupParams { return &SetupParams{ TestURL: "https://www.gstatic.com/generate_204", SelectedMap: map[string]string{}, } } func readFile(path string) ([]byte, error) { if _, err := os.Stat(path); os.IsNotExist(err) { return nil, err } data, err := os.ReadFile(path) if err != nil { return nil, err } return data, err } func updateConfig(params *UpdateParams) { runLock.Lock() defer runLock.Unlock() general := currentConfig.General if params.MixedPort != nil { general.MixedPort = *params.MixedPort } if params.Sniffing != nil { general.Sniffing = *params.Sniffing tunnel.SetSniffing(general.Sniffing) } if params.FindProcessMode != nil { general.FindProcessMode = *params.FindProcessMode tunnel.SetFindProcessMode(general.FindProcessMode) } if params.TCPConcurrent != nil { general.TCPConcurrent = *params.TCPConcurrent dialer.SetTcpConcurrent(general.TCPConcurrent) } if params.Interface != nil { general.Interface = *params.Interface dialer.DefaultInterface.Store(general.Interface) } if params.UnifiedDelay != nil { general.UnifiedDelay = *params.UnifiedDelay adapter.UnifiedDelay.Store(general.UnifiedDelay) } if params.Mode != nil { general.Mode = *params.Mode tunnel.SetMode(general.Mode) } if params.LogLevel != nil { general.LogLevel = *params.LogLevel log.SetLevel(general.LogLevel) } if params.IPv6 != nil { general.IPv6 = *params.IPv6 resolver.DisableIPv6 = !general.IPv6 } if params.ExternalController != nil { currentConfig.Controller.ExternalController = *params.ExternalController route.ReCreateServer(&route.Config{ Addr: currentConfig.Controller.ExternalController, }) } if params.Tun != nil { general.Tun.Enable = params.Tun.Enable general.Tun.AutoRoute = *params.Tun.AutoRoute general.Tun.Device = *params.Tun.Device general.Tun.RouteAddress = *params.Tun.RouteAddress general.Tun.DNSHijack = *params.Tun.DNSHijack general.Tun.Stack = *params.Tun.Stack } updateListeners() } func applyConfig(params *SetupParams) error { runtime.GC() runLock.Lock() defer runLock.Unlock() var err error constant.DefaultTestURL = params.TestURL currentConfig, err = executor.ParseWithPath(filepath.Join(constant.Path.HomeDir(), "config.yaml")) if err != nil { currentConfig, _ = config.ParseRawConfig(config.DefaultRawConfig()) } hub.ApplyConfig(currentConfig) patchSelectGroup(params.SelectedMap) updateListeners() return err } func UnmarshalJson(data []byte, v any) error { decoder := json.NewDecoder(b.NewReader(data)) decoder.UseNumber() err := decoder.Decode(v) return err } ================================================ FILE: core/constant.go ================================================ package main import ( "encoding/json" "github.com/metacubex/mihomo/adapter/provider" P "github.com/metacubex/mihomo/component/process" "github.com/metacubex/mihomo/constant" "github.com/metacubex/mihomo/log" "github.com/metacubex/mihomo/tunnel" "net/netip" "time" ) type InitParams struct { HomeDir string `json:"home-dir"` Version int `json:"version"` } type SetupParams struct { SelectedMap map[string]string `json:"selected-map"` TestURL string `json:"test-url"` } type UpdateParams struct { Tun *tunSchema `json:"tun"` AllowLan *bool `json:"allow-lan"` MixedPort *int `json:"mixed-port"` FindProcessMode *P.FindProcessMode `json:"find-process-mode"` Mode *tunnel.TunnelMode `json:"mode"` LogLevel *log.LogLevel `json:"log-level"` IPv6 *bool `json:"ipv6"` Sniffing *bool `json:"sniffing"` TCPConcurrent *bool `json:"tcp-concurrent"` ExternalController *string `json:"external-controller"` Interface *string `json:"interface-name"` UnifiedDelay *bool `json:"unified-delay"` } type tunSchema struct { Enable bool `yaml:"enable" json:"enable"` Device *string `yaml:"device" json:"device"` Stack *constant.TUNStack `yaml:"stack" json:"stack"` DNSHijack *[]string `yaml:"dns-hijack" json:"dns-hijack"` AutoRoute *bool `yaml:"auto-route" json:"auto-route"` RouteAddress *[]netip.Prefix `yaml:"route-address" json:"route-address,omitempty"` } type ChangeProxyParams struct { GroupName *string `json:"group-name"` ProxyName *string `json:"proxy-name"` } type TestDelayParams struct { ProxyName string `json:"proxy-name"` TestUrl string `json:"test-url"` Timeout int64 `json:"timeout"` } type ExternalProvider struct { Name string `json:"name"` Type string `json:"type"` VehicleType string `json:"vehicle-type"` Count int `json:"count"` Path string `json:"path"` UpdateAt time.Time `json:"update-at"` SubscriptionInfo *provider.SubscriptionInfo `json:"subscription-info"` } type ProxiesData struct { Proxies map[string]constant.Proxy `json:"proxies"` All []string `json:"all"` } const ( messageMethod Method = "message" initClashMethod Method = "initClash" getIsInitMethod Method = "getIsInit" forceGcMethod Method = "forceGc" shutdownMethod Method = "shutdown" validateConfigMethod Method = "validateConfig" updateConfigMethod Method = "updateConfig" getProxiesMethod Method = "getProxies" changeProxyMethod Method = "changeProxy" getTrafficMethod Method = "getTraffic" getTotalTrafficMethod Method = "getTotalTraffic" resetTrafficMethod Method = "resetTraffic" asyncTestDelayMethod Method = "asyncTestDelay" getConnectionsMethod Method = "getConnections" closeConnectionsMethod Method = "closeConnections" resetConnectionsMethod Method = "resetConnectionsMethod" closeConnectionMethod Method = "closeConnection" getExternalProvidersMethod Method = "getExternalProviders" getExternalProviderMethod Method = "getExternalProvider" getCountryCodeMethod Method = "getCountryCode" getMemoryMethod Method = "getMemory" updateGeoDataMethod Method = "updateGeoData" updateExternalProviderMethod Method = "updateExternalProvider" sideLoadExternalProviderMethod Method = "sideLoadExternalProvider" startLogMethod Method = "startLog" stopLogMethod Method = "stopLog" startListenerMethod Method = "startListener" stopListenerMethod Method = "stopListener" updateDnsMethod Method = "updateDns" crashMethod Method = "crash" setupConfigMethod Method = "setupConfig" getConfigMethod Method = "getConfig" deleteFile Method = "deleteFile" ) type Method string type MessageType string type Delay struct { Url string `json:"url"` Name string `json:"name"` Value int32 `json:"value"` } type Message struct { Type MessageType `json:"type"` Data interface{} `json:"data"` } const ( LogMessage MessageType = "log" DelayMessage MessageType = "delay" RequestMessage MessageType = "request" LoadedMessage MessageType = "loaded" ) func (message *Message) Json() (string, error) { data, err := json.Marshal(message) return string(data), err } ================================================ FILE: core/go.mod ================================================ module core go 1.20 replace github.com/metacubex/mihomo => ./Clash.Meta require ( github.com/metacubex/mihomo v0.0.0-00010101000000-000000000000 golang.org/x/sync v0.11.0 ) require ( filippo.io/edwards25519 v1.1.0 // indirect github.com/RyuaNerin/go-krypto v1.3.0 // indirect github.com/Yawning/aez v0.0.0-20211027044916-e49e68abd344 // indirect github.com/ajg/form v1.5.1 // indirect github.com/andybalholm/brotli v1.0.6 // indirect github.com/bahlo/generic-list-go v0.2.0 // indirect github.com/buger/jsonparser v1.1.1 // indirect github.com/coreos/go-iptables v0.8.0 // indirect github.com/dlclark/regexp2 v1.11.5 // indirect github.com/enfein/mieru/v3 v3.26.2 // indirect github.com/ericlagergren/aegis v0.0.0-20250325060835-cd0defd64358 // indirect github.com/ericlagergren/polyval v0.0.0-20220411101811-e25bc10ba391 // indirect github.com/ericlagergren/siv v0.0.0-20220507050439-0b757b3aa5f1 // indirect github.com/ericlagergren/subtle v0.0.0-20220507045147-890d697da010 // indirect github.com/fsnotify/fsnotify v1.9.0 // indirect github.com/gaukas/godicttls v0.0.4 // indirect github.com/go-ole/go-ole v1.3.0 // indirect github.com/gobwas/httphead v0.1.0 // indirect github.com/gobwas/pool v0.2.1 // indirect github.com/gobwas/ws v1.4.0 // indirect github.com/gofrs/uuid/v5 v5.4.0 // indirect github.com/golang/snappy v1.0.0 // indirect github.com/google/btree v1.1.3 // indirect github.com/google/go-cmp v0.6.0 // indirect github.com/google/pprof v0.0.0-20240727154555-813a5fbdbec8 // indirect github.com/insomniacslk/dhcp v0.0.0-20250109001534-8abf58130905 // indirect github.com/josharian/native v1.1.0 // indirect github.com/klauspost/compress v1.17.9 // indirect github.com/klauspost/cpuid/v2 v2.2.6 // indirect github.com/klauspost/reedsolomon v1.12.3 // indirect github.com/mailru/easyjson v0.7.7 // indirect github.com/mdlayher/netlink v1.7.2 // indirect github.com/mdlayher/socket v0.4.1 // indirect github.com/metacubex/amneziawg-go v0.0.0-20251104174305-5a0e9f7e361d // indirect github.com/metacubex/ascon v0.1.0 // indirect github.com/metacubex/bart v0.26.0 // indirect github.com/metacubex/bbolt v0.0.0-20250725135710-010dbbbb7a5b // indirect github.com/metacubex/blake3 v0.1.0 // indirect github.com/metacubex/chacha v0.1.5 // indirect github.com/metacubex/chi v0.1.0 // indirect github.com/metacubex/cpu v0.1.0 // indirect github.com/metacubex/fswatch v0.1.1 // indirect github.com/metacubex/gopacket v1.1.20-0.20230608035415-7e2f98a3e759 // indirect github.com/metacubex/gvisor v0.0.0-20251227095601-261ec1326fe8 // indirect github.com/metacubex/hkdf v0.1.0 // indirect github.com/metacubex/hpke v0.1.0 // indirect github.com/metacubex/http v0.1.0 // indirect github.com/metacubex/kcp-go v0.0.0-20260105040817-550693377604 // indirect github.com/metacubex/mlkem v0.1.0 // indirect github.com/metacubex/nftables v0.0.0-20250503052935-30a69ab87793 // indirect github.com/metacubex/qpack v0.6.0 // indirect github.com/metacubex/quic-go v0.59.1-0.20260112033758-aa29579f2001 // indirect github.com/metacubex/randv2 v0.2.0 // indirect github.com/metacubex/restls-client-go v0.1.7 // indirect github.com/metacubex/sing v0.5.6 // indirect github.com/metacubex/sing-mux v0.3.4 // indirect github.com/metacubex/sing-quic v0.0.0-20260112044712-65d17608159e // indirect github.com/metacubex/sing-shadowsocks v0.2.12 // indirect github.com/metacubex/sing-shadowsocks2 v0.2.7 // indirect github.com/metacubex/sing-shadowtls v0.0.0-20250503063515-5d9f966d17a2 // indirect github.com/metacubex/sing-tun v0.4.11 // indirect github.com/metacubex/sing-vmess v0.2.4 // indirect github.com/metacubex/sing-wireguard v0.0.0-20250503063753-2dc62acc626f // indirect github.com/metacubex/smux v0.0.0-20260105030934-d0c8756d3141 // indirect github.com/metacubex/tfo-go v0.0.0-20251130171125-413e892ac443 // indirect github.com/metacubex/tls v0.1.1 // indirect github.com/metacubex/utls v1.8.4 // indirect github.com/metacubex/wireguard-go v0.0.0-20250820062549-a6cecdd7f57f // indirect github.com/metacubex/yamux v0.0.0-20250918083631-dd5f17c0be49 // indirect github.com/miekg/dns v1.1.63 // indirect github.com/mroth/weightedrand/v2 v2.1.0 // indirect github.com/oasisprotocol/deoxysii v0.0.0-20220228165953-2091330c22b7 // indirect github.com/openacid/low v0.1.21 // indirect github.com/oschwald/maxminddb-golang v1.12.0 // indirect github.com/pierrec/lz4/v4 v4.1.14 // indirect github.com/sagernet/netlink v0.0.0-20240612041022-b9a21c07ac6a // indirect github.com/samber/lo v1.52.0 // indirect github.com/sina-ghaderi/poly1305 v0.0.0-20220724002748-c5926b03988b // indirect github.com/sina-ghaderi/rabaead v0.0.0-20220730151906-ab6e06b96e8c // indirect github.com/sina-ghaderi/rabbitio v0.0.0-20220730151941-9ce26f4f872e // indirect github.com/sirupsen/logrus v1.9.3 // indirect github.com/u-root/uio v0.0.0-20230220225925-ffce2a382923 // indirect github.com/vishvananda/netns v0.0.4 // indirect github.com/vmihailenco/msgpack/v5 v5.4.1 // indirect github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect github.com/wk8/go-ordered-map/v2 v2.1.8 // indirect gitlab.com/go-extension/aes-ccm v0.0.0-20230221065045-e58665ef23c7 // indirect gitlab.com/yawning/bsaes.git v0.0.0-20190805113838-0a714cd429ec // indirect go4.org/netipx v0.0.0-20231129151722-fdeea329fbba // indirect golang.org/x/crypto v0.33.0 // indirect golang.org/x/exp v0.0.0-20240904232852-e7e105dedf7e // indirect golang.org/x/mod v0.20.0 // indirect golang.org/x/net v0.35.0 // indirect golang.org/x/sys v0.30.0 // indirect golang.org/x/text v0.22.0 // indirect golang.org/x/time v0.10.0 // indirect golang.org/x/tools v0.24.0 // indirect google.golang.org/protobuf v1.34.2 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) ================================================ FILE: core/go.sum ================================================ filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= github.com/RyuaNerin/go-krypto v1.3.0 h1:smavTzSMAx8iuVlGb4pEwl9MD2qicqMzuXR2QWp2/Pg= github.com/RyuaNerin/go-krypto v1.3.0/go.mod h1:9R9TU936laAIqAmjcHo/LsaXYOZlymudOAxjaBf62UM= github.com/RyuaNerin/testingutil v0.1.0 h1:IYT6JL57RV3U2ml3dLHZsVtPOP6yNK7WUVdzzlpNrss= github.com/Yawning/aez v0.0.0-20211027044916-e49e68abd344 h1:cDVUiFo+npB0ZASqnw4q90ylaVAbnYyx0JYqK4YcGok= github.com/Yawning/aez v0.0.0-20211027044916-e49e68abd344/go.mod h1:9pIqrY6SXNL8vjRQE5Hd/OL5GyK/9MrGUWs87z/eFfk= github.com/ajg/form v1.5.1 h1:t9c7v8JUKu/XxOGBU0yjNpaMloxGEJhUkqFRq0ibGeU= github.com/ajg/form v1.5.1/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY= github.com/andybalholm/brotli v1.0.6 h1:Yf9fFpf49Zrxb9NlQaluyE92/+X7UVHlhMNJN2sxfOI= github.com/andybalholm/brotli v1.0.6/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig= github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk= github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg= github.com/blang/semver v3.5.1+incompatible/go.mod h1:kRBLl5iJ+tD4TcOOxsy/0fnwebNt5EWlYSAyrTnjyyk= github.com/buger/jsonparser v1.1.1 h1:2PnMjfWD7wBILjqQbt530v576A/cAbQvEW9gGIpYMUs= github.com/buger/jsonparser v1.1.1/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0= github.com/coreos/go-iptables v0.8.0 h1:MPc2P89IhuVpLI7ETL/2tx3XZ61VeICZjYqDEgNsPRc= github.com/coreos/go-iptables v0.8.0/go.mod h1:Qe8Bv2Xik5FyTXwgIbLAnv2sWSBmvWdFETJConOQ//Q= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dlclark/regexp2 v1.11.5 h1:Q/sSnsKerHeCkc/jSTNq1oCm7KiVgUMZRDUoRu0JQZQ= github.com/dlclark/regexp2 v1.11.5/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= github.com/enfein/mieru/v3 v3.26.2 h1:U/2XJc+3vrJD9r815FoFdwToQFEcqSOzzzWIPPhjfEU= github.com/enfein/mieru/v3 v3.26.2/go.mod h1:zJBUCsi5rxyvHM8fjFf+GLaEl4OEjjBXr1s5F6Qd3hM= github.com/ericlagergren/aegis v0.0.0-20250325060835-cd0defd64358 h1:kXYqH/sL8dS/FdoFjr12ePjnLPorPo2FsnrHNuXSDyo= github.com/ericlagergren/aegis v0.0.0-20250325060835-cd0defd64358/go.mod h1:hkIFzoiIPZYxdFOOLyDho59b7SrDfo+w3h+yWdlg45I= github.com/ericlagergren/polyval v0.0.0-20220411101811-e25bc10ba391 h1:8j2RH289RJplhA6WfdaPqzg1MjH2K8wX5e0uhAxrw2g= github.com/ericlagergren/polyval v0.0.0-20220411101811-e25bc10ba391/go.mod h1:K2R7GhgxrlJzHw2qiPWsCZXf/kXEJN9PLnQK73Ll0po= github.com/ericlagergren/saferand v0.0.0-20220206064634-960a4dd2bc5c h1:RUzBDdZ+e/HEe2Nh8lYsduiPAZygUfVXJn0Ncj5sHMg= github.com/ericlagergren/siv v0.0.0-20220507050439-0b757b3aa5f1 h1:tlDMEdcPRQKBEz5nGDMvswiajqh7k8ogWRlhRwKy5mY= github.com/ericlagergren/siv v0.0.0-20220507050439-0b757b3aa5f1/go.mod h1:4RfsapbGx2j/vU5xC/5/9qB3kn9Awp1YDiEnN43QrJ4= github.com/ericlagergren/subtle v0.0.0-20220507045147-890d697da010 h1:fuGucgPk5dN6wzfnxl3D0D3rVLw4v2SbBT9jb4VnxzA= github.com/ericlagergren/subtle v0.0.0-20220507045147-890d697da010/go.mod h1:JtBcj7sBuTTRupn7c2bFspMDIObMJsVK8TeUvpShPok= github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= github.com/gaukas/godicttls v0.0.4 h1:NlRaXb3J6hAnTmWdsEKb9bcSBD6BvcIjdGdeb0zfXbk= github.com/gaukas/godicttls v0.0.4/go.mod h1:l6EenT4TLWgTdwslVb4sEMOCf7Bv0JAK67deKr9/NCI= github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE= github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78= github.com/gobwas/httphead v0.1.0 h1:exrUm0f4YX0L7EBwZHuCF4GDp8aJfVeBrlLQrs6NqWU= github.com/gobwas/httphead v0.1.0/go.mod h1:O/RXo79gxV8G+RqlR/otEwx4Q36zl9rqC5u12GKvMCM= github.com/gobwas/pool v0.2.1 h1:xfeeEhW7pwmX8nuLVlqbzVc7udMDrwetjEv+TZIz1og= github.com/gobwas/pool v0.2.1/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw= github.com/gobwas/ws v1.4.0 h1:CTaoG1tojrh4ucGPcoJFiAQUAsEWekEWvLy7GsVNqGs= github.com/gobwas/ws v1.4.0/go.mod h1:G3gNqMNtPppf5XUz7O4shetPpcZ1VJ7zt18dlUeakrc= github.com/gofrs/uuid/v5 v5.4.0 h1:EfbpCTjqMuGyq5ZJwxqzn3Cbr2d0rUZU7v5ycAk/e/0= github.com/gofrs/uuid/v5 v5.4.0/go.mod h1:CDOjlDMVAtN56jqyRUZh58JT31Tiw7/oQyEXZV+9bD8= github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/snappy v1.0.0 h1:Oy607GVXHs7RtbggtPBnr2RmDArIsAefDwvrdWvRhGs= github.com/golang/snappy v1.0.0/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/google/btree v1.1.3 h1:CVpQJjYgC4VbzxeGVHfvZrv1ctoYCAI8vbl07Fcxlyg= github.com/google/btree v1.1.3/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4= github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/pprof v0.0.0-20240727154555-813a5fbdbec8 h1:FKHo8hFI3A+7w0aUQuYXQ+6EN5stWmeY/AZqtM8xk9k= github.com/google/pprof v0.0.0-20240727154555-813a5fbdbec8/go.mod h1:K1liHPHnj73Fdn/EKuT8nrFqBihUSKXoLYU0BuatOYo= github.com/google/tink/go v1.6.1 h1:t7JHqO8Ath2w2ig5vjwQYJzhGEZymedQc90lQXUBa4I= github.com/insomniacslk/dhcp v0.0.0-20250109001534-8abf58130905 h1:q3OEI9RaN/wwcx+qgGo6ZaoJkCiDYe/gjDLfq7lQQF4= github.com/insomniacslk/dhcp v0.0.0-20250109001534-8abf58130905/go.mod h1:VvGYjkZoJyKqlmT1yzakUs4mfKMNB0XdODP0+rdml6k= github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= github.com/josharian/native v1.0.1-0.20221213033349-c1e37c09b531/go.mod h1:7X/raswPFr05uY3HiLlYeyQntB6OO7E/d2Cu7qoaN2w= github.com/josharian/native v1.1.0 h1:uuaP0hAbW7Y4l0ZRQ6C9zfb7Mg1mbFKry/xzDAfmtLA= github.com/josharian/native v1.1.0/go.mod h1:7X/raswPFr05uY3HiLlYeyQntB6OO7E/d2Cu7qoaN2w= github.com/klauspost/compress v1.17.9 h1:6KIumPrER1LHsvBVuDa0r5xaG0Es51mhhB9BQB2qeMA= github.com/klauspost/compress v1.17.9/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw= github.com/klauspost/cpuid/v2 v2.2.6 h1:ndNyv040zDGIDh8thGkXYjnFtiN02M1PVVF+JE/48xc= github.com/klauspost/cpuid/v2 v2.2.6/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws= github.com/klauspost/reedsolomon v1.12.3 h1:tzUznbfc3OFwJaTebv/QdhnFf2Xvb7gZ24XaHLBPmdc= github.com/klauspost/reedsolomon v1.12.3/go.mod h1:3K5rXwABAvzGeR01r6pWZieUALXO/Tq7bFKGIb4m4WI= github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= github.com/mdlayher/netlink v1.7.2 h1:/UtM3ofJap7Vl4QWCPDGXY8d3GIY2UGSDbK+QWmY8/g= github.com/mdlayher/netlink v1.7.2/go.mod h1:xraEF7uJbxLhc5fpHL4cPe221LI2bdttWlU+ZGLfQSw= github.com/mdlayher/socket v0.4.1 h1:eM9y2/jlbs1M615oshPQOHZzj6R6wMT7bX5NPiQvn2U= github.com/mdlayher/socket v0.4.1/go.mod h1:cAqeGjoufqdxWkD7DkpyS+wcefOtmu5OQ8KuoJGIReA= github.com/metacubex/amneziawg-go v0.0.0-20251104174305-5a0e9f7e361d h1:vAJ0ZT4aO803F1uw2roIA9yH7Sxzox34tVVyye1bz6c= github.com/metacubex/amneziawg-go v0.0.0-20251104174305-5a0e9f7e361d/go.mod h1:MsM/5czONyXMJ3PRr5DbQ4O/BxzAnJWOIcJdLzW6qHY= github.com/metacubex/ascon v0.1.0 h1:6ZWxmXYszT1XXtwkf6nxfFhc/OTtQ9R3Vyj1jN32lGM= github.com/metacubex/ascon v0.1.0/go.mod h1:eV5oim4cVPPdEL8/EYaTZ0iIKARH9pnhAK/fcT5Kacc= github.com/metacubex/bart v0.26.0 h1:d/bBTvVatfVWGfQbiDpYKI1bXUJgjaabB2KpK1Tnk6w= github.com/metacubex/bart v0.26.0/go.mod h1:DCcyfP4MC+Zy7sLK7XeGuMw+P5K9mIRsYOBgiE8icsI= github.com/metacubex/bbolt v0.0.0-20250725135710-010dbbbb7a5b h1:j7dadXD8I2KTmMt8jg1JcaP1ANL3JEObJPdANKcSYPY= github.com/metacubex/bbolt v0.0.0-20250725135710-010dbbbb7a5b/go.mod h1:+WmP0VJZDkDszvpa83HzfUp6QzARl/IKkMorH4+nODw= github.com/metacubex/blake3 v0.1.0 h1:KGnjh/56REO7U+cgZA8dnBhxdP7jByrG7hTP+bu6cqY= github.com/metacubex/blake3 v0.1.0/go.mod h1:CCkLdzFrqf7xmxCdhQFvJsRRV2mwOLDoSPg6vUTB9Uk= github.com/metacubex/chacha v0.1.5 h1:fKWMb/5c7ZrY8Uoqi79PPFxl+qwR7X/q0OrsAubyX2M= github.com/metacubex/chacha v0.1.5/go.mod h1:Djn9bPZxLTXbJFSeyo0/qzEzQI+gUSSzttuzZM75GH8= github.com/metacubex/chi v0.1.0 h1:rjNDyDj50nRpicG43CNkIw4ssiCbmDL8d7wJXKlUCsg= github.com/metacubex/chi v0.1.0/go.mod h1:zM5u5oMQt8b2DjvDHvzadKrP6B2ztmasL1YHRMbVV+g= github.com/metacubex/cpu v0.1.0 h1:8PeTdV9j6UKbN1K5Jvtbi/Jock7dknvzyYuLb8Conmk= github.com/metacubex/cpu v0.1.0/go.mod h1:09VEt4dSRLR+bOA8l4w4NDuzGZ8n5dkMv7e8axgEeTU= github.com/metacubex/fswatch v0.1.1 h1:jqU7C/v+g0qc2RUFgmAOPoVvfl2BXXUXEumn6oQuxhU= github.com/metacubex/fswatch v0.1.1/go.mod h1:czrTT7Zlbz7vWft8RQu9Qqh+JoX+Nnb+UabuyN1YsgI= github.com/metacubex/gopacket v1.1.20-0.20230608035415-7e2f98a3e759 h1:cjd4biTvOzK9ubNCCkQ+ldc4YSH/rILn53l/xGBFHHI= github.com/metacubex/gopacket v1.1.20-0.20230608035415-7e2f98a3e759/go.mod h1:UHOv2xu+RIgLwpXca7TLrXleEd4oR3sPatW6IF8wU88= github.com/metacubex/gvisor v0.0.0-20251227095601-261ec1326fe8 h1:hUL81H0Ic/XIDkvtn9M1pmfDdfid7JzYQToY4Ps1TvQ= github.com/metacubex/gvisor v0.0.0-20251227095601-261ec1326fe8/go.mod h1:8LpS0IJW1VmWzUm3ylb0e2SK5QDm5lO/2qwWLZgRpBU= github.com/metacubex/hkdf v0.1.0 h1:fPA6VzXK8cU1foc/TOmGCDmSa7pZbxlnqhl3RNsthaA= github.com/metacubex/hkdf v0.1.0/go.mod h1:3seEfds3smgTAXqUGn+tgEJH3uXdsUjOiduG/2EtvZ4= github.com/metacubex/hpke v0.1.0 h1:gu2jUNhraehWi0P/z5HX2md3d7L1FhPQE6/Q0E9r9xQ= github.com/metacubex/hpke v0.1.0/go.mod h1:vfDm6gfgrwlXUxKDkWbcE44hXtmc1uxLDm2BcR11b3U= github.com/metacubex/http v0.1.0 h1:Jcy0I9zKjYijSUaksZU34XEe2xNdoFkgUTB7z7K5q0o= github.com/metacubex/http v0.1.0/go.mod h1:Nxx0zZAo2AhRfanyL+fmmK6ACMtVsfpwIl1aFAik2Eg= github.com/metacubex/kcp-go v0.0.0-20260105040817-550693377604 h1:hJwCVlE3ojViC35MGHB+FBr8TuIf3BUFn2EQ1VIamsI= github.com/metacubex/kcp-go v0.0.0-20260105040817-550693377604/go.mod h1:lpmN3m269b3V5jFCWtffqBLS4U3QQoIid9ugtO+OhVc= github.com/metacubex/mlkem v0.1.0 h1:wFClitonSFcmipzzQvax75beLQU+D7JuC+VK1RzSL8I= github.com/metacubex/mlkem v0.1.0/go.mod h1:amhaXZVeYNShuy9BILcR7P0gbeo/QLZsnqCdL8U2PDQ= github.com/metacubex/nftables v0.0.0-20250503052935-30a69ab87793 h1:1Qpuy+sU3DmyX9HwI+CrBT/oLNJngvBorR2RbajJcqo= github.com/metacubex/nftables v0.0.0-20250503052935-30a69ab87793/go.mod h1:RjRNb4G52yAgfR+Oe/kp9G4PJJ97Fnj89eY1BFO3YyA= github.com/metacubex/qpack v0.6.0 h1:YqClGIMOpiRYLjV1qOs483Od08MdPgRnHjt90FuaAKw= github.com/metacubex/qpack v0.6.0/go.mod h1:lKGSi7Xk94IMvHGOmxS9eIei3bvIqpOAImEBsaOwTkA= github.com/metacubex/quic-go v0.59.1-0.20260112033758-aa29579f2001 h1:RlT3bFCIDM/NR9GWaDbFCrweOwpHRfgaT9c0zuRlPhY= github.com/metacubex/quic-go v0.59.1-0.20260112033758-aa29579f2001/go.mod h1:oNzMrmylS897M3zSMuapIdwSwfq6F2qW01Z3NhVRJhk= github.com/metacubex/randv2 v0.2.0 h1:uP38uBvV2SxYfLj53kuvAjbND4RUDfFJjwr4UigMiLs= github.com/metacubex/randv2 v0.2.0/go.mod h1:kFi2SzrQ5WuneuoLLCMkABtiBu6VRrMrWFqSPyj2cxY= github.com/metacubex/restls-client-go v0.1.7 h1:eCwiXCTQb5WJu9IlgYvDBA1OgrINv58dEe7hcN5H15k= github.com/metacubex/restls-client-go v0.1.7/go.mod h1:BN/U52vPw7j8VTSh2vleD/MnmVKCov84mS5VcjVHH4g= github.com/metacubex/sing v0.5.6 h1:mEPDCadsCj3DB8gn+t/EtposlYuALEkExa/LUguw6/c= github.com/metacubex/sing v0.5.6/go.mod h1:ypf0mjwlZm0sKdQSY+yQvmsbWa0hNPtkeqyRMGgoN+w= github.com/metacubex/sing-mux v0.3.4 h1:tf4r27CIkzaxq9kBlAXQkgMXq2HPp5Mta60Kb4RCZF0= github.com/metacubex/sing-mux v0.3.4/go.mod h1:SEJfAuykNj/ozbPqngEYqyggwSr81+L7Nu09NRD5mh4= github.com/metacubex/sing-quic v0.0.0-20260112044712-65d17608159e h1:MLxp42z9Jd6LtY2suyawnl24oNzIsFxWc15bNeDIGxA= github.com/metacubex/sing-quic v0.0.0-20260112044712-65d17608159e/go.mod h1:+lgKTd52xAarGtqugALISShyw4KxnoEpYe2u0zJh26w= github.com/metacubex/sing-shadowsocks v0.2.12 h1:Wqzo8bYXrK5aWqxu/TjlTnYZzAKtKsaFQBdr6IHFaBE= github.com/metacubex/sing-shadowsocks v0.2.12/go.mod h1:2e5EIaw0rxKrm1YTRmiMnDulwbGxH9hAFlrwQLQMQkU= github.com/metacubex/sing-shadowsocks2 v0.2.7 h1:hSuuc0YpsfiqYqt1o+fP4m34BQz4e6wVj3PPBVhor3A= github.com/metacubex/sing-shadowsocks2 v0.2.7/go.mod h1:vOEbfKC60txi0ca+yUlqEwOGc3Obl6cnSgx9Gf45KjE= github.com/metacubex/sing-shadowtls v0.0.0-20250503063515-5d9f966d17a2 h1:gXU+MYPm7Wme3/OAY2FFzVq9d9GxPHOqu5AQfg/ddhI= github.com/metacubex/sing-shadowtls v0.0.0-20250503063515-5d9f966d17a2/go.mod h1:mbfboaXauKJNIHJYxQRa+NJs4JU9NZfkA+I33dS2+9E= github.com/metacubex/sing-tun v0.4.11 h1:NG5zpvYPbBXf+9GSUmDaGCDwl3hZXV677tbRAw0QtCM= github.com/metacubex/sing-tun v0.4.11/go.mod h1:L/TjQY5JEGy8nvsuYmy/XgMFMCPiF0+AWSFCYfS6r9w= github.com/metacubex/sing-vmess v0.2.4 h1:Tx6AGgCiEf400E/xyDuYyafsel6sGbR8oF7RkAaus6I= github.com/metacubex/sing-vmess v0.2.4/go.mod h1:21R5R1u90uUvBQF0owoooEu96/SAYYD56nDrwm6nFaM= github.com/metacubex/sing-wireguard v0.0.0-20250503063753-2dc62acc626f h1:Sr/DYKYofKHKc4GF3qkRGNuj6XA6c0eqPgEDN+VAsYU= github.com/metacubex/sing-wireguard v0.0.0-20250503063753-2dc62acc626f/go.mod h1:jpAkVLPnCpGSfNyVmj6Cq4YbuZsFepm/Dc+9BAOcR80= github.com/metacubex/smux v0.0.0-20260105030934-d0c8756d3141 h1:DK2l6m2Fc85H2BhiAPgbJygiWhesPlfGmF+9Vw6ARdk= github.com/metacubex/smux v0.0.0-20260105030934-d0c8756d3141/go.mod h1:/yI4OiGOSn0SURhZdJF3CbtPg3nwK700bG8TZLMBvAg= github.com/metacubex/tfo-go v0.0.0-20251130171125-413e892ac443 h1:H6TnfM12tOoTizYE/qBHH3nEuibIelmHI+BVSxVJr8o= github.com/metacubex/tfo-go v0.0.0-20251130171125-413e892ac443/go.mod h1:l9oLnLoEXyGZ5RVLsh7QCC5XsouTUyKk4F2nLm2DHLw= github.com/metacubex/tls v0.1.1 h1:BEcZrsPTTfNf4sKZ02EbZodv4UIj7fgHWa1Eqo12Bc0= github.com/metacubex/tls v0.1.1/go.mod h1:0XeVdL0cBw+8i5Hqy3lVeP9IyD/LFTq02ExvHM6rzEM= github.com/metacubex/utls v1.8.4 h1:HmL9nUApDdWSkgUyodfwF6hSjtiwCGGdyhaSpEejKpg= github.com/metacubex/utls v1.8.4/go.mod h1:kncGGVhFaoGn5M3pFe3SXhZCzsbCJayNOH4UEqTKTko= github.com/metacubex/wireguard-go v0.0.0-20250820062549-a6cecdd7f57f h1:FGBPRb1zUabhPhDrlKEjQ9lgIwQ6cHL4x8M9lrERhbk= github.com/metacubex/wireguard-go v0.0.0-20250820062549-a6cecdd7f57f/go.mod h1:oPGcV994OGJedmmxrcK9+ni7jUEMGhR+uVQAdaduIP4= github.com/metacubex/yamux v0.0.0-20250918083631-dd5f17c0be49 h1:lhlqpYHopuTLx9xQt22kSA9HtnyTDmk5XjjQVCGHe2E= github.com/metacubex/yamux v0.0.0-20250918083631-dd5f17c0be49/go.mod h1:MBeEa9IVBphH7vc3LNtW6ZujVXFizotPo3OEiHQ+TNU= github.com/miekg/dns v1.1.63 h1:8M5aAw6OMZfFXTT7K5V0Eu5YiiL8l7nUAkyN6C9YwaY= github.com/miekg/dns v1.1.63/go.mod h1:6NGHfjhpmr5lt3XPLuyfDJi5AXbNIPM9PY6H6sF1Nfs= github.com/mroth/weightedrand/v2 v2.1.0 h1:o1ascnB1CIVzsqlfArQQjeMy1U0NcIbBO5rfd5E/OeU= github.com/mroth/weightedrand/v2 v2.1.0/go.mod h1:f2faGsfOGOwc1p94wzHKKZyTpcJUW7OJ/9U4yfiNAOU= github.com/oasisprotocol/deoxysii v0.0.0-20220228165953-2091330c22b7 h1:1102pQc2SEPp5+xrS26wEaeb26sZy6k9/ZXlZN+eXE4= github.com/oasisprotocol/deoxysii v0.0.0-20220228165953-2091330c22b7/go.mod h1:UqoUn6cHESlliMhOnKLWr+CBH+e3bazUPvFj1XZwAjs= github.com/openacid/errors v0.8.1/go.mod h1:GUQEJJOJE3W9skHm8E8Y4phdl2LLEN8iD7c5gcGgdx0= github.com/openacid/low v0.1.21 h1:Tr2GNu4N/+rGRYdOsEHOE89cxUIaDViZbVmKz29uKGo= github.com/openacid/low v0.1.21/go.mod h1:q+MsKI6Pz2xsCkzV4BLj7NR5M4EX0sGz5AqotpZDVh0= github.com/openacid/must v0.1.3/go.mod h1:luPiXCuJlEo3UUFQngVQokV0MPGryeYvtCbQPs3U1+I= github.com/openacid/testkeys v0.1.6/go.mod h1:MfA7cACzBpbiwekivj8StqX0WIRmqlMsci1c37CA3Do= github.com/oschwald/maxminddb-golang v1.12.0 h1:9FnTOD0YOhP7DGxGsq4glzpGy5+w7pq50AS6wALUMYs= github.com/oschwald/maxminddb-golang v1.12.0/go.mod h1:q0Nob5lTCqyQ8WT6FYgS1L7PXKVVbgiymefNwIjPzgY= github.com/pierrec/lz4/v4 v4.1.14 h1:+fL8AQEZtz/ijeNnpduH0bROTu0O3NZAlPjQxGn8LwE= github.com/pierrec/lz4/v4 v4.1.14/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/sagernet/netlink v0.0.0-20240612041022-b9a21c07ac6a h1:ObwtHN2VpqE0ZNjr6sGeT00J8uU7JF4cNUdb44/Duis= github.com/sagernet/netlink v0.0.0-20240612041022-b9a21c07ac6a/go.mod h1:xLnfdiJbSp8rNqYEdIW/6eDO4mVoogml14Bh2hSiFpM= github.com/samber/lo v1.52.0 h1:Rvi+3BFHES3A8meP33VPAxiBZX/Aws5RxrschYGjomw= github.com/samber/lo v1.52.0/go.mod h1:4+MXEGsJzbKGaUEQFKBq2xtfuznW9oz/WrgyzMzRoM0= github.com/sina-ghaderi/poly1305 v0.0.0-20220724002748-c5926b03988b h1:rXHg9GrUEtWZhEkrykicdND3VPjlVbYiLdX9J7gimS8= github.com/sina-ghaderi/poly1305 v0.0.0-20220724002748-c5926b03988b/go.mod h1:X7qrxNQViEaAN9LNZOPl9PfvQtp3V3c7LTo0dvGi0fM= github.com/sina-ghaderi/rabaead v0.0.0-20220730151906-ab6e06b96e8c h1:DjKMC30y6yjG3IxDaeAj3PCoRr+IsO+bzyT+Se2m2Hk= github.com/sina-ghaderi/rabaead v0.0.0-20220730151906-ab6e06b96e8c/go.mod h1:NV/a66PhhWYVmUMaotlXJ8fIEFB98u+c8l/CQIEFLrU= github.com/sina-ghaderi/rabbitio v0.0.0-20220730151941-9ce26f4f872e h1:ur8uMsPIFG3i4Gi093BQITvwH9znsz2VUZmnmwHvpIo= github.com/sina-ghaderi/rabbitio v0.0.0-20220730151941-9ce26f4f872e/go.mod h1:+e5fBW3bpPyo+3uLo513gIUblc03egGjMM0+5GKbzK8= github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/u-root/uio v0.0.0-20230220225925-ffce2a382923 h1:tHNk7XK9GkmKUR6Gh8gVBKXc2MVSZ4G/NnWLtzw4gNA= github.com/u-root/uio v0.0.0-20230220225925-ffce2a382923/go.mod h1:eLL9Nub3yfAho7qB0MzZizFhTU2QkLeoVsWdHtDW264= github.com/vishvananda/netlink v1.1.0/go.mod h1:cTgwzPIzzgDAYoQrMm0EdrjRUBkTqKYppBueQtXaqoE= github.com/vishvananda/netns v0.0.0-20191106174202-0a2b9b5464df/go.mod h1:JP3t17pCcGlemwknint6hfoeCVQrEMVwxRLRjXpq+BU= github.com/vishvananda/netns v0.0.0-20210104183010-2eb08e3e575f/go.mod h1:DD4vA1DwXk04H54A1oHXtwZmA0grkVMdPxx/VGLCah0= github.com/vishvananda/netns v0.0.4 h1:Oeaw1EM2JMxD51g9uhtC0D7erkIjgmj8+JZc26m1YX8= github.com/vishvananda/netns v0.0.4/go.mod h1:SpkAiCQRtJ6TvvxPnOSyH3BMl6unz3xZlaprSwhNNJM= github.com/vmihailenco/msgpack/v5 v5.4.1 h1:cQriyiUvjTwOHg8QZaPihLWeRAAVoCpE00IUPn0Bjt8= github.com/vmihailenco/msgpack/v5 v5.4.1/go.mod h1:GaZTsDaehaPpQVyxrf5mtQlH+pc21PIudVV/E3rRQok= github.com/vmihailenco/tagparser/v2 v2.0.0 h1:y09buUbR+b5aycVFQs/g70pqKVZNBmxwAhO7/IwNM9g= github.com/vmihailenco/tagparser/v2 v2.0.0/go.mod h1:Wri+At7QHww0WTrCBeu4J6bNtoV6mEfg5OIWRZA9qds= github.com/wk8/go-ordered-map/v2 v2.1.8 h1:5h/BUHu93oj4gIdvHHHGsScSTMijfx5PeYkE/fJgbpc= github.com/wk8/go-ordered-map/v2 v2.1.8/go.mod h1:5nJHM5DyteebpVlHnWMV0rPz6Zp7+xBAnxjb1X5vnTw= github.com/xtaci/lossyconn v0.0.0-20190602105132-8df528c0c9ae h1:J0GxkO96kL4WF+AIT3M4mfUVinOCPgf2uUWYFUzN0sM= gitlab.com/go-extension/aes-ccm v0.0.0-20230221065045-e58665ef23c7 h1:UNrDfkQqiEYzdMlNsVvBYOAJWZjdktqFE9tQh5BT2+4= gitlab.com/go-extension/aes-ccm v0.0.0-20230221065045-e58665ef23c7/go.mod h1:E+rxHvJG9H6PUdzq9NRG6csuLN3XUx98BfGOVWNYnXs= gitlab.com/yawning/bsaes.git v0.0.0-20190805113838-0a714cd429ec h1:FpfFs4EhNehiVfzQttTuxanPIT43FtkkCFypIod8LHo= gitlab.com/yawning/bsaes.git v0.0.0-20190805113838-0a714cd429ec/go.mod h1:BZ1RAoRPbCxum9Grlv5aeksu2H8BiKehBYooU2LFiOQ= go.uber.org/mock v0.4.0 h1:VcM4ZOtdbR4f6VXfiOpwpVJDL6lCReaZ6mw31wqh7KU= go4.org/netipx v0.0.0-20231129151722-fdeea329fbba h1:0b9z3AuHCjxk0x/opv64kcgZLBseWJUpBw5I82+2U4M= go4.org/netipx v0.0.0-20231129151722-fdeea329fbba/go.mod h1:PLyyIXexvUFg3Owu6p/WfdlivPbZJsZdgWZlrGope/Y= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.33.0 h1:IOBPskki6Lysi0lo9qQvbxiQ+FvsCC/YWOecCHAixus= golang.org/x/crypto v0.33.0/go.mod h1:bVdXmD7IV/4GdElGPozy6U7lWdRXA4qyRVGJV57uQ5M= golang.org/x/exp v0.0.0-20240904232852-e7e105dedf7e h1:I88y4caeGeuDQxgdoFPUq097j7kNfw6uvuiNxUBfcBk= golang.org/x/exp v0.0.0-20240904232852-e7e105dedf7e/go.mod h1:akd2r19cwCdwSwWeIdzYQGa/EZZyqcOdwWiwj5L5eKQ= golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= golang.org/x/mod v0.20.0 h1:utOm6MM3R3dnawAiJgn0y+xvuYRsm1RKM/4giyfDgV0= golang.org/x/mod v0.20.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.35.0 h1:T5GQRQb2y08kTAByq9L4/bz8cipCdA8FbRTXewonqY8= golang.org/x/net v0.35.0/go.mod h1:EglIi67kWsHKlRzzVMUD93VMSWGFOMSZgxFjparz1Qk= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.11.0 h1:GGz8+XQP4FvTTrjZPzNKTMFtSXH80RAzG+5ghFPgK9w= golang.org/x/sync v0.11.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190606203320-7fc4e5ec1444/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190804053845-51ab0e2deafa/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200217220822-9197077df867/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20220622161953-175b2fd9d664/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc= golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/term v0.29.0 h1:L6pJp37ocefwRRtYPKSWOWzOtWSxVajvz2ldH/xi3iU= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM= golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY= golang.org/x/time v0.10.0 h1:3usCWA8tQn0L8+hFJQNgzpWbd89begxN66o1Ojdn5L4= golang.org/x/time v0.10.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.24.0 h1:J1shsA93PJUEVaUSaay7UXAyE8aimq3GW0pjlolpa24= golang.org/x/tools v0.24.0/go.mod h1:YhNqVBIfWHdzvTLs0d8LCuMhkKUgSUKldakyV7W/WDQ= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg= google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= ================================================ FILE: core/hub.go ================================================ package main import ( "cmp" "context" "encoding/json" "github.com/metacubex/mihomo/adapter" "github.com/metacubex/mihomo/adapter/outboundgroup" "github.com/metacubex/mihomo/common/observable" "github.com/metacubex/mihomo/common/utils" "github.com/metacubex/mihomo/component/mmdb" "github.com/metacubex/mihomo/component/resolver" "github.com/metacubex/mihomo/component/updater" "github.com/metacubex/mihomo/config" "github.com/metacubex/mihomo/constant" "github.com/metacubex/mihomo/constant/features" cp "github.com/metacubex/mihomo/constant/provider" "github.com/metacubex/mihomo/hub/executor" "github.com/metacubex/mihomo/listener" "github.com/metacubex/mihomo/log" "github.com/metacubex/mihomo/tunnel" "github.com/metacubex/mihomo/tunnel/statistic" "golang.org/x/exp/slices" "net" "os" "runtime" "runtime/debug" "strconv" "time" ) var ( isInit = false externalProviders = map[string]cp.Provider{} logSubscriber observable.Subscription[log.Event] ) func handleInitClash(paramsString string) bool { runLock.Lock() defer runLock.Unlock() var params = InitParams{} err := json.Unmarshal([]byte(paramsString), ¶ms) if err != nil { return false } version = params.Version constant.SetHomeDir(params.HomeDir) isInit = true return isInit } func handleStartListener() bool { runLock.Lock() defer runLock.Unlock() isRunning = true updateListeners() resolver.ResetConnection() return true } func handleStopListener() bool { runLock.Lock() defer runLock.Unlock() isRunning = false listener.StopListener() resolver.ResetConnection() return true } func handleGetIsInit() bool { return isInit } func handleForceGC() { log.Infoln("[APP] request force GC") runtime.GC() if features.Android { debug.FreeOSMemory() } } func handleShutdown() bool { stopListeners() executor.Shutdown() handleForceGC() isInit = false return true } func handleValidateConfig(path string) string { buf, err := readFile(path) _, err = config.UnmarshalRawConfig(buf) if err != nil { return err.Error() } return "" } func handleGetProxies() ProxiesData { runLock.Lock() defer runLock.Unlock() nameList := config.GetProxyNameList() proxies := make(map[string]constant.Proxy) for name, proxy := range tunnel.Proxies() { proxies[name] = proxy } for _, p := range tunnel.Providers() { for _, proxy := range p.Proxies() { proxies[proxy.Name()] = proxy } } hasGlobal := false allNames := make([]string, 0, len(nameList)+1) for _, name := range nameList { if name == "GLOBAL" { hasGlobal = true } p, ok := proxies[name] if !ok || p == nil { continue } switch p.Type() { case constant.Selector, constant.URLTest, constant.Fallback, constant.Relay, constant.LoadBalance: allNames = append(allNames, name) default: } } if !hasGlobal { if p, ok := proxies["GLOBAL"]; ok && p != nil { allNames = append([]string{"GLOBAL"}, allNames...) } } return ProxiesData{ All: allNames, Proxies: proxies, } } func handleChangeProxy(data string, fn func(string string)) { runLock.Lock() go func() { defer runLock.Unlock() var params = &ChangeProxyParams{} err := json.Unmarshal([]byte(data), params) if err != nil { fn(err.Error()) return } groupName := *params.GroupName proxyName := *params.ProxyName proxies := tunnel.ProxiesWithProviders() group, ok := proxies[groupName] if !ok { fn("Not found group") return } adapterProxy := group.(*adapter.Proxy) selector, ok := adapterProxy.ProxyAdapter.(outboundgroup.SelectAble) if !ok { fn("Group is not selectable") return } if proxyName == "" { selector.ForceSet(proxyName) } else { err = selector.Set(proxyName) } if err != nil { fn(err.Error()) return } fn("") return }() } func handleGetTraffic(onlyStatisticsProxy bool) string { up, down := statistic.DefaultManager.NowTraffic(onlyStatisticsProxy) traffic := map[string]int64{ "up": up, "down": down, } data, err := json.Marshal(traffic) if err != nil { log.Errorln("Error: %s", err) return "" } return string(data) } func handleGetTotalTraffic(onlyStatisticsProxy bool) string { up, down := statistic.DefaultManager.TotalTraffic(onlyStatisticsProxy) traffic := map[string]int64{ "up": up, "down": down, } data, err := json.Marshal(traffic) if err != nil { log.Errorln("Error: %s", err) return "" } return string(data) } func handleResetTraffic() { statistic.DefaultManager.ResetStatistic() } func handleAsyncTestDelay(paramsString string, fn func(string)) { mBatch.Go(paramsString, func() (bool, error) { var params = &TestDelayParams{} err := json.Unmarshal([]byte(paramsString), params) if err != nil { fn("") return false, nil } expectedStatus, err := utils.NewUnsignedRanges[uint16]("") if err != nil { fn("") return false, nil } ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*time.Duration(params.Timeout)) defer cancel() proxies := tunnel.ProxiesWithProviders() proxy := proxies[params.ProxyName] delayData := &Delay{ Name: params.ProxyName, } if proxy == nil { delayData.Value = -1 data, _ := json.Marshal(delayData) fn(string(data)) return false, nil } testUrl := constant.DefaultTestURL if params.TestUrl != "" { testUrl = params.TestUrl } delayData.Url = testUrl delay, err := proxy.URLTest(ctx, testUrl, expectedStatus) if err != nil || delay == 0 { delayData.Value = -1 data, _ := json.Marshal(delayData) fn(string(data)) return false, nil } delayData.Value = int32(delay) data, _ := json.Marshal(delayData) fn(string(data)) return false, nil }) } func handleGetConnections() string { runLock.Lock() defer runLock.Unlock() snapshot := statistic.DefaultManager.Snapshot() data, err := json.Marshal(snapshot) if err != nil { log.Errorln("Error: %s", err) return "" } return string(data) } func handleCloseConnections() bool { runLock.Lock() defer runLock.Unlock() closeConnections() return true } func closeConnections() { statistic.DefaultManager.Range(func(c statistic.Tracker) bool { err := c.Close() if err != nil { return false } return true }) } func handleResetConnections() bool { runLock.Lock() defer runLock.Unlock() resolver.ResetConnection() return true } func handleCloseConnection(connectionId string) bool { runLock.Lock() defer runLock.Unlock() c := statistic.DefaultManager.Get(connectionId) if c == nil { return false } _ = c.Close() return true } func handleGetExternalProviders() string { runLock.Lock() defer runLock.Unlock() externalProviders = getExternalProvidersRaw() eps := make([]ExternalProvider, 0) for _, p := range externalProviders { externalProvider, err := toExternalProvider(p) if err != nil { continue } eps = append(eps, *externalProvider) } slices.SortFunc(eps, func(a, b ExternalProvider) int { return cmp.Compare(a.Name, b.Name) }) data, err := json.Marshal(eps) if err != nil { return "" } return string(data) } func handleGetExternalProvider(externalProviderName string) string { runLock.Lock() defer runLock.Unlock() externalProvider, exist := externalProviders[externalProviderName] if !exist { return "" } e, err := toExternalProvider(externalProvider) if err != nil { return "" } data, err := json.Marshal(e) if err != nil { return "" } return string(data) } func handleUpdateGeoData(geoType string, geoName string, fn func(value string)) { go func() { path := constant.Path.Resolve(geoName) switch geoType { case "MMDB": err := updater.UpdateMMDBWithPath(path) if err != nil { fn(err.Error()) return } case "ASN": err := updater.UpdateASNWithPath(path) if err != nil { fn(err.Error()) return } case "GEOIP": err := updater.UpdateGeoIpWithPath(path) if err != nil { fn(err.Error()) return } case "GEOSITE": err := updater.UpdateGeoSiteWithPath(path) if err != nil { fn(err.Error()) return } } fn("") }() } func handleUpdateExternalProvider(providerName string, fn func(value string)) { go func() { externalProvider, exist := externalProviders[providerName] if !exist { fn("external provider is not exist") return } err := externalProvider.Update() if err != nil { fn(err.Error()) return } fn("") }() } func handleSideLoadExternalProvider(providerName string, data []byte, fn func(value string)) { go func() { runLock.Lock() defer runLock.Unlock() externalProvider, exist := externalProviders[providerName] if !exist { fn("external provider is not exist") return } err := sideUpdateExternalProvider(externalProvider, data) if err != nil { fn(err.Error()) return } fn("") }() } func handleSuspend(suspended bool) bool { if suspended { tunnel.OnSuspend() } else { tunnel.OnRunning() } return true } func handleStartLog() { if logSubscriber != nil { log.UnSubscribe(logSubscriber) logSubscriber = nil } logSubscriber = log.Subscribe() go func() { for logData := range logSubscriber { if logData.LogLevel < log.Level() { continue } message := &Message{ Type: LogMessage, Data: logData, } sendMessage(*message) } }() } func handleStopLog() { if logSubscriber != nil { log.UnSubscribe(logSubscriber) logSubscriber = nil } } func handleGetCountryCode(ip string, fn func(value string)) { go func() { runLock.Lock() defer runLock.Unlock() codes := mmdb.IPInstance().LookupCode(net.ParseIP(ip)) if len(codes) == 0 { fn("") return } fn(codes[0]) }() } func handleGetMemory(fn func(value string)) { go func() { fn(strconv.FormatUint(statistic.DefaultManager.Memory(), 10)) }() } func handleGetConfig(path string) (*config.RawConfig, error) { bytes, err := readFile(path) if err != nil { return nil, err } prof, err := config.UnmarshalRawConfig(bytes) if err != nil { return nil, err } return prof, nil } func handleCrash() { panic("handle invoke crash") } func handleUpdateConfig(bytes []byte) string { var params = &UpdateParams{} err := json.Unmarshal(bytes, params) if err != nil { return err.Error() } updateConfig(params) return "" } func handleDelFile(path string, result ActionResult) { go func() { fileInfo, err := os.Stat(path) if err != nil { if !os.IsNotExist(err) { result.success(err.Error()) } result.success("") return } if fileInfo.IsDir() { err = os.RemoveAll(path) if err != nil { result.success(err.Error()) return } } else { err = os.Remove(path) if err != nil { result.success(err.Error()) return } } result.success("") }() } func handleSetupConfig(bytes []byte) string { if !isInit { return "not initialized" } var params = defaultSetupParams() err := UnmarshalJson(bytes, params) if err != nil { log.Errorln("unmarshalRawConfig error %v", err) _ = applyConfig(defaultSetupParams()) return err.Error() } err = applyConfig(params) if err != nil { return err.Error() } return "" } func init() { adapter.UrlTestHook = func(url string, name string, delay uint16) { delayData := &Delay{ Url: url, Name: name, } if delay == 0 { delayData.Value = -1 } else { delayData.Value = int32(delay) } sendMessage(Message{ Type: DelayMessage, Data: delayData, }) } statistic.DefaultRequestNotify = func(c statistic.Tracker) { sendMessage(Message{ Type: RequestMessage, Data: c, }) } executor.DefaultProviderLoadedHook = func(providerName string) { sendMessage(Message{ Type: LoadedMessage, Data: providerName, }) } } ================================================ FILE: core/lib.go ================================================ //go:build cgo package main /* #include */ import "C" import ( "context" "core/platform" t "core/tun" "encoding/json" "errors" "github.com/metacubex/mihomo/component/dialer" "github.com/metacubex/mihomo/component/process" "github.com/metacubex/mihomo/constant" "github.com/metacubex/mihomo/dns" "github.com/metacubex/mihomo/listener/sing_tun" "github.com/metacubex/mihomo/log" "golang.org/x/sync/semaphore" "net" "strings" "sync" "syscall" "unsafe" ) var eventListener unsafe.Pointer type TunHandler struct { listener *sing_tun.Listener callback unsafe.Pointer limit *semaphore.Weighted } func (th *TunHandler) start(fd int, stack, address, dns string) { runLock.Lock() defer runLock.Unlock() _ = th.limit.Acquire(context.TODO(), 4) defer th.limit.Release(4) th.initHook() tunListener := t.Start(fd, stack, address, dns) if tunListener != nil { log.Infoln("TUN address: %v", tunListener.Address()) th.listener = tunListener return } th.clear() } func (th *TunHandler) close() { _ = th.limit.Acquire(context.TODO(), 4) defer th.limit.Release(4) th.clear() } func (th *TunHandler) clear() { th.removeHook() if th.listener != nil { _ = th.listener.Close() } if th.callback != nil { releaseObject(th.callback) } th.callback = nil th.listener = nil } func (th *TunHandler) handleProtect(fd int) { _ = th.limit.Acquire(context.Background(), 1) defer th.limit.Release(1) if th.listener == nil { return } protect(th.callback, fd) } func (th *TunHandler) handleResolveProcess(source, target net.Addr) string { _ = th.limit.Acquire(context.Background(), 1) defer th.limit.Release(1) if th.listener == nil { return "" } var protocol int uid := -1 switch source.Network() { case "udp", "udp4", "udp6": protocol = syscall.IPPROTO_UDP case "tcp", "tcp4", "tcp6": protocol = syscall.IPPROTO_TCP } if version < 29 { uid = platform.QuerySocketUidFromProcFs(source, target) } return resolveProcess(th.callback, protocol, source.String(), target.String(), uid) } func (th *TunHandler) initHook() { dialer.DefaultSocketHook = func(network, address string, conn syscall.RawConn) error { if platform.ShouldBlockConnection() { return errBlocked } return conn.Control(func(fd uintptr) { tunHandler.handleProtect(int(fd)) }) } process.DefaultPackageNameResolver = func(metadata *constant.Metadata) (string, error) { src, dst := metadata.RawSrcAddr, metadata.RawDstAddr if src == nil || dst == nil { return "", process.ErrInvalidNetwork } return tunHandler.handleResolveProcess(src, dst), nil } } func (th *TunHandler) removeHook() { dialer.DefaultSocketHook = nil process.DefaultPackageNameResolver = nil } var ( tunLock sync.Mutex errBlocked = errors.New("blocked") tunHandler *TunHandler ) func handleStopTun() { tunLock.Lock() defer tunLock.Unlock() if tunHandler != nil { tunHandler.close() } } func handleStartTun(callback unsafe.Pointer, fd int, stack, address, dns string) { handleStopTun() tunLock.Lock() defer tunLock.Unlock() if fd != 0 { tunHandler = &TunHandler{ callback: callback, limit: semaphore.NewWeighted(4), } tunHandler.start(fd, stack, address, dns) } } func handleUpdateDns(value string) { go func() { log.Infoln("[DNS] updateDns %s", value) dns.UpdateSystemDNS(strings.Split(value, ",")) dns.FlushCacheWithDefaultResolver() }() } func (result ActionResult) send() { data, err := result.Json() if err != nil { return } invokeResult(result.callback, string(data)) if result.Method != messageMethod { releaseObject(result.callback) } } func nextHandle(action *Action, result ActionResult) bool { switch action.Method { case updateDnsMethod: data := action.Data.(string) handleUpdateDns(data) result.success(true) return true } return false } //export invokeAction func invokeAction(callback unsafe.Pointer, paramsChar *C.char) { params := takeCString(paramsChar) var action = &Action{} err := json.Unmarshal([]byte(params), action) if err != nil { invokeResult(callback, err.Error()) return } result := ActionResult{ Id: action.Id, Method: action.Method, callback: callback, } go handleAction(action, result) } //export startTUN func startTUN(callback unsafe.Pointer, fd C.int, stackChar, addressChar, dnsChar *C.char) bool { handleStartTun(callback, int(fd), takeCString(stackChar), takeCString(addressChar), takeCString(dnsChar)) if !isRunning { handleStartListener() } else { handleResetConnections() } return true } //export quickSetup func quickSetup(callback unsafe.Pointer, initParamsChar *C.char, setupParamsChar *C.char) { go func() { initParamsString := takeCString(initParamsChar) setupParamsString := takeCString(setupParamsChar) if !handleInitClash(initParamsString) { invokeResult(callback, "init failed") return } isRunning = true message := handleSetupConfig([]byte(setupParamsString)) invokeResult(callback, message) }() } //export setEventListener func setEventListener(listener unsafe.Pointer) { if eventListener != nil || listener == nil { releaseObject(eventListener) } eventListener = listener } //export getTotalTraffic func getTotalTraffic(onlyStatisticsProxy bool) *C.char { data := C.CString(handleGetTotalTraffic(onlyStatisticsProxy)) defer C.free(unsafe.Pointer(data)) return data } //export getTraffic func getTraffic(onlyStatisticsProxy bool) *C.char { data := C.CString(handleGetTraffic(onlyStatisticsProxy)) defer C.free(unsafe.Pointer(data)) return data } func sendMessage(message Message) { if eventListener == nil { return } result := ActionResult{ Method: messageMethod, callback: eventListener, Data: message, } result.send() } //export stopTun func stopTun() { handleStopTun() if isRunning { handleStopListener() } } //export suspend func suspend(suspended bool) { handleSuspend(suspended) } //export forceGC func forceGC() { handleForceGC() } //export updateDns func updateDns(s *C.char) { handleUpdateDns(takeCString(s)) } ================================================ FILE: core/main.go ================================================ //go:build !cgo package main import ( "fmt" "os" ) func main() { args := os.Args if len(args) <= 1 { fmt.Println("Arguments error") os.Exit(1) } startServer(args[1]) } ================================================ FILE: core/main_cgo.go ================================================ //go:build cgo package main import "C" func main() { } ================================================ FILE: core/platform/limit.go ================================================ //go:build android && cgo package platform import "syscall" var nullFd int var maxFdCount int func init() { fd, err := syscall.Open("/dev/null", syscall.O_WRONLY, 0644) if err != nil { panic(err.Error()) } nullFd = fd var limit syscall.Rlimit if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &limit); err != nil { maxFdCount = 1024 } else { maxFdCount = int(limit.Cur) } maxFdCount = maxFdCount / 4 * 3 } func ShouldBlockConnection() bool { fd, err := syscall.Dup(nullFd) if err != nil { return true } _ = syscall.Close(fd) if fd > maxFdCount { return true } return false } ================================================ FILE: core/platform/procfs.go ================================================ //go:build linux package platform import ( "bufio" "encoding/binary" "encoding/hex" "fmt" "net" "os" "strconv" "strings" "unsafe" ) var netIndexOfLocal = -1 var netIndexOfUid = -1 var nativeEndian binary.ByteOrder func QuerySocketUidFromProcFs(source, _ net.Addr) int { if netIndexOfLocal < 0 || netIndexOfUid < 0 { return -1 } network := source.Network() if strings.HasSuffix(network, "4") || strings.HasSuffix(network, "6") { network = network[:len(network)-1] } path := "/proc/net/" + network var sIP net.IP var sPort int switch s := source.(type) { case *net.TCPAddr: sIP = s.IP sPort = s.Port case *net.UDPAddr: sIP = s.IP sPort = s.Port default: return -1 } sIP = sIP.To16() if sIP == nil { return -1 } uid := doQuery(path+"6", sIP, sPort) if uid == -1 { sIP = sIP.To4() if sIP == nil { return -1 } uid = doQuery(path, sIP, sPort) } return uid } func doQuery(path string, sIP net.IP, sPort int) int { file, err := os.Open(path) if err != nil { return -1 } defer func(file *os.File) { _ = file.Close() }(file) reader := bufio.NewReader(file) var bytes [2]byte binary.BigEndian.PutUint16(bytes[:], uint16(sPort)) local := fmt.Sprintf("%s:%s", hex.EncodeToString(nativeEndianIP(sIP)), hex.EncodeToString(bytes[:])) for { row, _, err := reader.ReadLine() if err != nil { return -1 } fields := strings.Fields(string(row)) if len(fields) <= netIndexOfLocal || len(fields) <= netIndexOfUid { continue } if strings.EqualFold(local, fields[netIndexOfLocal]) { uid, err := strconv.Atoi(fields[netIndexOfUid]) if err != nil { return -1 } return uid } } } func nativeEndianIP(ip net.IP) []byte { result := make([]byte, len(ip)) for i := 0; i < len(ip); i += 4 { value := binary.BigEndian.Uint32(ip[i:]) nativeEndian.PutUint32(result[i:], value) } return result } func init() { file, err := os.Open("/proc/net/tcp") if err != nil { return } defer func(file *os.File) { _ = file.Close() }(file) reader := bufio.NewReader(file) header, _, err := reader.ReadLine() if err != nil { return } columns := strings.Fields(string(header)) var txQueue, rxQueue, tr, tmWhen bool for idx, col := range columns { offset := 0 if txQueue && rxQueue { offset-- } if tr && tmWhen { offset-- } switch col { case "tx_queue": txQueue = true case "rx_queue": rxQueue = true case "tr": tr = true case "tm->when": tmWhen = true case "local_address": netIndexOfLocal = idx + offset case "uid": netIndexOfUid = idx + offset } } } func init() { var x uint32 = 0x01020304 if *(*byte)(unsafe.Pointer(&x)) == 0x01 { nativeEndian = binary.BigEndian } else { nativeEndian = binary.LittleEndian } } ================================================ FILE: core/server.go ================================================ //go:build !cgo package main import ( "bufio" "encoding/json" "fmt" "net" "strconv" ) var conn net.Conn func (result ActionResult) send() { data, err := result.Json() if err != nil { return } send(data) } func sendMessage(message Message) { result := ActionResult{ Method: messageMethod, Data: message, } result.send() } func send(data []byte) { if conn == nil { return } _, _ = conn.Write(append(data, []byte("\n")...)) } func startServer(arg string) { _, err := strconv.Atoi(arg) if err != nil { conn, err = net.Dial("unix", arg) } else { conn, err = net.Dial("tcp", fmt.Sprintf("127.0.0.1:%s", arg)) } if err != nil { panic(err.Error()) } defer func(conn net.Conn) { _ = conn.Close() }(conn) reader := bufio.NewReader(conn) for { data, err := reader.ReadString('\n') if err != nil { return } var action = &Action{} err = json.Unmarshal([]byte(data), action) if err != nil { return } result := ActionResult{ Id: action.Id, Method: action.Method, } go handleAction(action, result) } } func nextHandle(action *Action, result ActionResult) bool { return false } ================================================ FILE: core/tun/tun.go ================================================ //go:build android && cgo package tun import "C" import ( "github.com/metacubex/mihomo/constant" LC "github.com/metacubex/mihomo/listener/config" "github.com/metacubex/mihomo/listener/sing_tun" "github.com/metacubex/mihomo/log" "github.com/metacubex/mihomo/tunnel" "net" "net/netip" "strings" ) func Start(fd int, stack string, address, dns string) *sing_tun.Listener { var prefix4 []netip.Prefix var prefix6 []netip.Prefix tunStack, ok := constant.StackTypeMapping[strings.ToLower(stack)] if !ok { tunStack = constant.TunSystem } for _, a := range strings.Split(address, ",") { a = strings.TrimSpace(a) if len(a) == 0 { continue } prefix, err := netip.ParsePrefix(a) if err != nil { log.Errorln("TUN:", err) return nil } if prefix.Addr().Is4() { prefix4 = append(prefix4, prefix) } else { prefix6 = append(prefix6, prefix) } } var dnsHijack []string for _, d := range strings.Split(dns, ",") { d = strings.TrimSpace(d) if len(d) == 0 { continue } dnsHijack = append(dnsHijack, net.JoinHostPort(d, "53")) } options := LC.Tun{ Enable: true, Device: "FlClash", Stack: tunStack, DNSHijack: dnsHijack, AutoRoute: false, AutoDetectInterface: false, Inet4Address: prefix4, Inet6Address: prefix6, MTU: 9000, FileDescriptor: fd, } listener, err := sing_tun.New(options, tunnel.Tunnel) if err != nil { log.Errorln("TUN:", err) return nil } return listener } ================================================ FILE: distribute_options.yaml ================================================ app_name: 'FlClash' output: 'dist/' ================================================ FILE: lib/application.dart ================================================ import 'dart:async'; import 'dart:io'; import 'package:connectivity_plus/connectivity_plus.dart'; import 'package:fl_clash/common/common.dart'; import 'package:fl_clash/core/core.dart'; import 'package:fl_clash/l10n/l10n.dart'; import 'package:fl_clash/manager/hotkey_manager.dart'; import 'package:fl_clash/manager/manager.dart'; import 'package:fl_clash/plugins/app.dart'; import 'package:fl_clash/providers/providers.dart'; import 'package:fl_clash/state.dart'; import 'package:flutter/material.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'controller.dart'; import 'pages/pages.dart'; class Application extends ConsumerStatefulWidget { const Application({super.key}); @override ConsumerState createState() => ApplicationState(); } class ApplicationState extends ConsumerState { Timer? _autoUpdateProfilesTaskTimer; bool _preHasVpn = false; final _pageTransitionsTheme = const PageTransitionsTheme( builders: { TargetPlatform.android: commonSharedXPageTransitions, TargetPlatform.windows: commonSharedXPageTransitions, TargetPlatform.linux: commonSharedXPageTransitions, TargetPlatform.macOS: commonSharedXPageTransitions, }, ); ColorScheme _getAppColorScheme({ required Brightness brightness, int? primaryColor, }) { return ref.read(genColorSchemeProvider(brightness)); } @override void initState() { super.initState(); WidgetsBinding.instance.addPostFrameCallback((timeStamp) async { final currentContext = globalState.navigatorKey.currentContext; if (currentContext != null) { await appController.attach(currentContext, ref); } else { exit(0); } _autoUpdateProfilesTask(); appController.initLink(); app?.initShortcuts(); }); } void _autoUpdateProfilesTask() { _autoUpdateProfilesTaskTimer = Timer(const Duration(minutes: 20), () async { await appController.autoUpdateProfiles(); _autoUpdateProfilesTask(); }); } Widget _buildPlatformState({required Widget child}) { if (system.isDesktop) { return WindowManager( child: TrayManager( child: HotKeyManager(child: ProxyManager(child: child)), ), ); } return AndroidManager(child: TileManager(child: child)); } Widget _buildState({required Widget child}) { return AppStateManager( child: CoreManager( child: ConnectivityManager( onConnectivityChanged: (results) async { commonPrint.log('connectivityChanged ${results.toString()}'); appController.updateLocalIp(); final hasVpn = results.contains(ConnectivityResult.vpn); if (_preHasVpn == hasVpn) { appController.addCheckIp(); } _preHasVpn = hasVpn; }, child: child, ), ), ); } Widget _buildPlatformApp({required Widget child}) { if (system.isDesktop) { return WindowHeaderContainer(child: child); } return VpnManager(child: child); } Widget _buildApp({required Widget child}) { return StatusManager(child: ThemeManager(child: child)); } @override Widget build(context) { return Consumer( builder: (_, ref, child) { final locale = ref.watch( appSettingProvider.select((state) => state.locale), ); final themeProps = ref.watch(themeSettingProvider); return MaterialApp( debugShowCheckedModeBanner: false, navigatorKey: globalState.navigatorKey, localizationsDelegates: const [ AppLocalizations.delegate, GlobalMaterialLocalizations.delegate, GlobalCupertinoLocalizations.delegate, GlobalWidgetsLocalizations.delegate, ], builder: (_, child) { return AppEnvManager( child: _buildApp( child: _buildPlatformState( child: _buildState(child: _buildPlatformApp(child: child!)), ), ), ); }, scrollBehavior: BaseScrollBehavior(), title: appName, locale: utils.getLocaleForString(locale), supportedLocales: AppLocalizations.delegate.supportedLocales, themeMode: themeProps.themeMode, theme: ThemeData( useMaterial3: true, pageTransitionsTheme: _pageTransitionsTheme, colorScheme: _getAppColorScheme( brightness: Brightness.light, primaryColor: themeProps.primaryColor, ), ), darkTheme: ThemeData( useMaterial3: true, pageTransitionsTheme: _pageTransitionsTheme, colorScheme: _getAppColorScheme( brightness: Brightness.dark, primaryColor: themeProps.primaryColor, ).toPureBlack(themeProps.pureBlack), ), home: child!, ); }, child: const HomePage(), ); } @override Future dispose() async { linkManager.destroy(); _autoUpdateProfilesTaskTimer?.cancel(); await coreController.destroy(); await appController.handleExit(); super.dispose(); } } ================================================ FILE: lib/common/app_localizations.dart ================================================ import 'package:fl_clash/l10n/l10n.dart'; final appLocalizations = AppLocalizations.current; ================================================ FILE: lib/common/archive.dart ================================================ import 'dart:io'; import 'package:archive/archive_io.dart'; import 'package:path/path.dart'; extension ArchiveExt on Archive { void addDirectoryToArchive(String dirPath, String parentPath) { final dir = Directory(dirPath); if (!dir.existsSync()) { return; } final entities = dir.listSync(recursive: false); for (final entity in entities) { final relativePath = relative(entity.path, from: parentPath); if (entity is File) { final data = entity.readAsBytesSync(); final archiveFile = ArchiveFile(relativePath, data.length, data); addFile(archiveFile); } } } // void addTextFile(String name, T raw) { // final data = json.encode(raw); // addFile(ArchiveFile.string(name, data)); // } } ================================================ FILE: lib/common/cache.dart ================================================ import 'dart:io'; import 'package:dio/dio.dart'; import 'package:fl_clash/common/common.dart'; import 'package:flutter_cache_manager/flutter_cache_manager.dart'; class LocalImageCacheManager extends CacheManager { static const key = 'ImageCaches'; static final LocalImageCacheManager _instance = LocalImageCacheManager._(); factory LocalImageCacheManager() { return _instance; } LocalImageCacheManager._() : super(Config(key, fileService: _LocalImageCacheFileService())); } class _LocalImageCacheFileService extends FileService { _LocalImageCacheFileService(); @override Future get( String url, { Map? headers, }) async { final response = await request.dio.get( url, options: Options(headers: headers, responseType: ResponseType.stream), ); return _LocalImageResponse(response); } } class _LocalImageResponse implements FileServiceResponse { _LocalImageResponse(this._response); final DateTime _receivedTime = DateTime.now(); final Response _response; String? _header(String name) { return _response.headers.value(name); } @override int get statusCode => _response.statusCode ?? 0; @override Stream> get content => _response.data!.stream.transform(uint8ListToListIntConverter); @override int? get contentLength => _response.data?.contentLength; @override DateTime get validTill { var ageDuration = const Duration(days: 7); final controlHeader = _header(HttpHeaders.cacheControlHeader); if (controlHeader != null) { final controlSettings = controlHeader.split(','); for (final setting in controlSettings) { final sanitizedSetting = setting.trim().toLowerCase(); if (sanitizedSetting == 'no-cache') { ageDuration = Duration.zero; } if (sanitizedSetting.startsWith('max-age=')) { final validSeconds = int.tryParse(sanitizedSetting.split('=')[1]) ?? 0; if (validSeconds > 0) { ageDuration = Duration(seconds: validSeconds); } } } } if (ageDuration > const Duration(days: 7)) { return _receivedTime.add(ageDuration); } return _receivedTime.add(const Duration(days: 7)); } @override String? get eTag => _header(HttpHeaders.etagHeader); @override String get fileExtension { var fileExtension = ''; final contentTypeHeader = _header(HttpHeaders.contentTypeHeader); if (contentTypeHeader != null) { final contentType = ContentType.parse(contentTypeHeader); fileExtension = contentType.fileExtension; } return fileExtension; } } extension ContentTypeConverter on ContentType { String get fileExtension => mimeTypes[mimeType] ?? '.$subType'; } const mimeTypes = { 'application/vnd.android.package-archive': '.apk', 'application/epub+zip': '.epub', 'application/gzip': '.gz', 'application/java-archive': '.jar', 'application/json': '.json', 'application/ld+json': '.jsonld', 'application/msword': '.doc', 'application/octet-stream': '.bin', 'application/ogg': '.ogx', 'application/pdf': '.pdf', 'application/php': '.php', 'application/rtf': '.rtf', 'application/vnd.amazon.ebook': '.azw', 'application/vnd.apple.installer+xml': '.mpkg', 'application/vnd.mozilla.xul+xml': '.xul', 'application/vnd.ms-excel': '.xls', 'application/vnd.ms-fontobject': '.eot', 'application/vnd.ms-powerpoint': '.ppt', 'application/vnd.oasis.opendocument.presentation': '.odp', 'application/vnd.oasis.opendocument.spreadsheet': '.ods', 'application/vnd.oasis.opendocument.text': '.odt', 'application/vnd.openxmlformats-officedocument.presentationml.presentation': '.pptx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': '.xlsx', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': '.docx', 'application/vnd.rar': '.rar', 'application/vnd.visio': '.vsd', 'application/x-7z-compressed': '.7z', 'application/x-abiword': '.abw', 'application/x-bzip': '.bz', 'application/x-bzip2': '.bz2', 'application/x-csh': '.csh', 'application/x-freearc': '.arc', 'application/x-sh': '.sh', 'application/x-shockwave-flash': '.swf', 'application/x-tar': '.tar', 'application/xhtml+xml': '.xhtml', 'application/xml': '.xml', 'application/zip': '.zip', 'audio/3gpp': '.3gp', 'audio/3gpp2': '.3g2', 'audio/aac': '.aac', 'audio/x-aac': '.aac', 'audio/midi': '.midi', 'audio/x-midi': '.midi', 'audio/x-m4a': '.m4a', 'audio/m4a': '.m4a', 'audio/mpeg': '.mp3', 'audio/ogg': '.oga', 'audio/opus': '.opus', 'audio/wav': '.wav', 'audio/x-wav': '.wav', 'audio/webm': '.weba', 'font/otf': '.otf', 'font/ttf': '.ttf', 'font/woff': '.woff', 'font/woff2': '.woff2', 'image/bmp': '.bmp', 'image/gif': '.gif', 'image/jpeg': '.jpg', 'image/png': '.png', 'image/svg+xml': '.svg', 'image/tiff': '.tiff', 'image/vnd.microsoft.icon': '.ico', 'image/webp': '.webp', 'text/calendar': '.ics', 'text/css': '.css', 'text/csv': '.csv', 'text/html': '.html', 'text/javascript': '.js', 'text/plain': '.txt', 'text/xml': '.xml', 'video/3gpp': '.3gp', 'video/3gpp2': '.3g2', 'video/mp2t': '.ts', 'video/mpeg': '.mpeg', 'video/ogg': '.ogv', 'video/webm': '.webm', 'video/x-msvideo': '.avi', 'video/quicktime': '.mov', }; ================================================ FILE: lib/common/color.dart ================================================ import 'dart:math'; import 'package:flutter/material.dart'; extension ColorExtension on Color { Color get opacity80 { return withAlpha(204); } Color get opacity60 { return withAlpha(153); } Color get opacity50 { return withAlpha(128); } Color get opacity38 { return withAlpha(97); } Color get opacity30 { return withAlpha(77); } Color get opacity12 { return withAlpha(31); } Color get opacity15 { return withAlpha(38); } Color get opacity10 { return withAlpha(15); } Color get opacity3 { return withAlpha(76); } Color get opacity0 { return withAlpha(0); } int get value32bit { return _floatToInt8(a) << 24 | _floatToInt8(r) << 16 | _floatToInt8(g) << 8 | _floatToInt8(b) << 0; } int get alpha8bit => (0xff000000 & value32bit) >> 24; int get red8bit => (0x00ff0000 & value32bit) >> 16; int get green8bit => (0x0000ff00 & value32bit) >> 8; int get blue8bit => (0x000000ff & value32bit) >> 0; int _floatToInt8(double x) { return (x * 255.0).round() & 0xff; } Color lighten([double amount = 10]) { if (amount <= 0) return this; if (amount > 100) return Colors.white; final HSLColor hsl = this == const Color(0xFF000000) ? HSLColor.fromColor(this).withSaturation(0) : HSLColor.fromColor(this); return hsl .withLightness(min(1, max(0, hsl.lightness + amount / 100))) .toColor(); } String get hex { final value = toARGB32(); final red = (value >> 16) & 0xFF; final green = (value >> 8) & 0xFF; final blue = value & 0xFF; return '#${red.toRadixString(16).padLeft(2, '0')}' '${green.toRadixString(16).padLeft(2, '0')}' '${blue.toRadixString(16).padLeft(2, '0')}' .toUpperCase(); } Color darken([final int amount = 10]) { if (amount <= 0) return this; if (amount > 100) return Colors.black; final HSLColor hsl = HSLColor.fromColor(this); return hsl .withLightness(min(1, max(0, hsl.lightness - amount / 100))) .toColor(); } Color blendDarken( BuildContext context, { double factor = 0.1, }) { final brightness = Theme.of(context).brightness; return Color.lerp( this, brightness == Brightness.dark ? Colors.white : Colors.black, factor, )!; } Color blendLighten( BuildContext context, { double factor = 0.1, }) { final brightness = Theme.of(context).brightness; return Color.lerp( this, brightness == Brightness.dark ? Colors.black : Colors.white, factor, )!; } } extension ColorSchemeExtension on ColorScheme { ColorScheme toPureBlack(bool isPrueBlack) => isPrueBlack ? copyWith( surface: Colors.black, surfaceContainer: surfaceContainer.darken( 5, ), ) : this; } ================================================ FILE: lib/common/common.dart ================================================ export 'app_localizations.dart'; export 'cache.dart'; export 'color.dart'; export 'compute.dart'; export 'constant.dart'; export 'context.dart'; export 'converter.dart'; export 'datetime.dart'; export 'file.dart'; export 'fixed.dart'; export 'function.dart'; export 'future.dart'; export 'hive.dart'; export 'http.dart'; export 'icons.dart'; export 'indexing.dart'; export 'iterable.dart'; export 'keyboard.dart'; export 'launch.dart'; export 'link.dart'; export 'lock.dart'; export 'measure.dart'; export 'migration.dart'; export 'mixin.dart'; export 'navigation.dart'; export 'navigator.dart'; export 'network.dart'; export 'num.dart'; export 'package.dart'; export 'path.dart'; export 'picker.dart'; export 'preferences.dart'; export 'print.dart'; export 'protocol.dart'; export 'proxy.dart'; export 'render.dart'; export 'request.dart'; export 'scroll.dart'; export 'snowflake.dart'; export 'string.dart'; export 'system.dart'; export 'task.dart'; export 'text.dart'; export 'tray.dart'; export 'utils.dart'; export 'window.dart'; export 'yaml.dart'; ================================================ FILE: lib/common/compute.dart ================================================ import 'package:fl_clash/common/common.dart'; import 'package:fl_clash/enum/enum.dart'; import 'package:fl_clash/models/models.dart'; List computeSort({ required List groups, required ProxiesSortType sortType, required DelayMap delayMap, required Map selectedMap, required String defaultTestUrl, }) { List sortOfDelay({ required List groups, required List proxies, required DelayMap delayMap, required Map selectedMap, required String testUrl, }) { return List.from(proxies)..sort((a, b) { final aDelayState = computeProxyDelayState( proxyName: a.name, testUrl: testUrl, groups: groups, selectedMap: selectedMap, delayMap: delayMap, ); final bDelayState = computeProxyDelayState( proxyName: b.name, testUrl: testUrl, groups: groups, selectedMap: selectedMap, delayMap: delayMap, ); return aDelayState.compareTo(bDelayState); }); } List sortOfName(List proxies) { return List.of(proxies)..sort((a, b) => a.name.compareTo(b.name)); } return groups.map((group) { final proxies = group.all; final newProxies = switch (sortType) { ProxiesSortType.none => proxies, ProxiesSortType.delay => sortOfDelay( groups: groups, proxies: proxies, delayMap: delayMap, selectedMap: selectedMap, testUrl: group.testUrl.takeFirstValid([defaultTestUrl]), ), ProxiesSortType.name => sortOfName(proxies), }; return group.copyWith(all: newProxies); }).toList(); } SelectedProxyState getRealSelectedProxyState( SelectedProxyState state, { required List groups, required Map selectedMap, }) { if (state.proxyName.isEmpty) return state; final index = groups.indexWhere((element) => element.name == state.proxyName); final newState = state.copyWith(group: true); if (index == -1) return newState; final group = groups[index]; final currentSelectedName = group.getCurrentSelectedName( selectedMap[newState.proxyName] ?? '', ); if (currentSelectedName.isEmpty) { return newState; } return getRealSelectedProxyState( newState.copyWith(proxyName: currentSelectedName, testUrl: group.testUrl), groups: groups, selectedMap: selectedMap, ); } SelectedProxyState computeRealSelectedProxyState( String proxyName, { required List groups, required Map selectedMap, }) { return getRealSelectedProxyState( SelectedProxyState(proxyName: proxyName), groups: groups, selectedMap: selectedMap, ); } DelayState computeProxyDelayState({ required String proxyName, required String testUrl, required List groups, required Map selectedMap, required DelayMap delayMap, }) { final state = computeRealSelectedProxyState( proxyName, groups: groups, selectedMap: selectedMap, ); final currentDelayMap = delayMap[state.testUrl.takeFirstValid([testUrl])] ?? {}; final delay = currentDelayMap[state.proxyName]; return DelayState(delay: delay ?? 0, group: state.group); } ================================================ FILE: lib/common/constant.dart ================================================ // ignore_for_file: constant_identifier_names import 'dart:math'; import 'dart:ui'; import 'package:collection/collection.dart'; import 'package:fl_clash/common/common.dart'; import 'package:fl_clash/enum/enum.dart'; import 'package:fl_clash/models/models.dart'; import 'package:flutter/material.dart'; const appName = 'FlClash'; const appHelperService = 'FlClashHelperService'; const coreName = 'clash.meta'; const browserUa = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'; const packageName = 'com.follow.clash'; final unixSocketPath = '/tmp/FlClashSocket_${Random().nextInt(10000)}.sock'; const helperPort = 47890; const maxTextScale = 1.4; const minTextScale = 0.8; final baseInfoEdgeInsets = EdgeInsets.symmetric( vertical: 16.mAp, horizontal: 16.mAp, ); final listHeaderPadding = EdgeInsets.only( left: 16.mAp, right: 8.mAp, top: 24.mAp, bottom: 8.mAp, ); const watchExecution = true; final defaultTextScaleFactor = WidgetsBinding.instance.platformDispatcher.textScaleFactor; const httpTimeoutDuration = Duration(milliseconds: 5000); const moreDuration = Duration(milliseconds: 100); const animateDuration = Duration(milliseconds: 100); const midDuration = Duration(milliseconds: 200); const commonDuration = Duration(milliseconds: 300); const defaultUpdateDuration = Duration(days: 1); const MMDB = 'GEOIP.metadb'; const ASN = 'ASN.mmdb'; const GEOIP = 'GEOIP.dat'; const GEOSITE = 'GEOSITE.dat'; final double kHeaderHeight = system.isDesktop ? !system.isMacOS ? 40 : 28 : 0; const profilesDirectoryName = 'profiles'; const localhost = '127.0.0.1'; const clashConfigKey = 'clash_config'; const configKey = 'config'; const double dialogCommonWidth = 300; const repository = 'chen08209/FlClash'; const defaultExternalController = '127.0.0.1:9090'; const maxMobileWidth = 600; const maxLaptopWidth = 840; const defaultTestUrl = 'https://www.gstatic.com/generate_204'; final commonFilter = ImageFilter.blur( sigmaX: 5, sigmaY: 5, tileMode: TileMode.mirror, ); const listEquality = ListEquality(); const navigationItemListEquality = ListEquality(); const trackerInfoListEquality = ListEquality(); const stringListEquality = ListEquality(); const intListEquality = ListEquality(); const logListEquality = ListEquality(); const groupListEquality = ListEquality(); const ruleListEquality = ListEquality(); const scriptListEquality = ListEquality