Compare commits
10 Commits
04642cb2f0
...
145832093e
| Author | SHA1 | Date | |
|---|---|---|---|
| 145832093e | |||
| 875684861e | |||
| 2648fcc44f | |||
| ed8afecf85 | |||
| 6ca55a3d44 | |||
| d02eed3bd8 | |||
| 2b8d34086a | |||
| 09d229a592 | |||
| 206613f092 | |||
| 1d2d9ba63d |
311
.github/workflows/BUILD_GUIDE.md
vendored
Normal file
311
.github/workflows/BUILD_GUIDE.md
vendored
Normal file
@ -0,0 +1,311 @@
|
||||
# 📖 GitHub Actions 构建完全指南
|
||||
|
||||
## 🎯 功能概述
|
||||
|
||||
本 workflow 支持:
|
||||
|
||||
✅ **自动编译 libcore.aar** - sing-box 核心库
|
||||
✅ **Release 构建** - 默认生成正式版 APK
|
||||
✅ **可配置 API 域名** - 支持自定义后端域名
|
||||
✅ **可配置 OSS 地址** - 支持自定义配置文件 CDN
|
||||
✅ **分架构打包** - 生成 arm64-v8a / armeabi-v7a / x86_64 版本
|
||||
✅ **自动创建 Release** - 推送标签自动发布
|
||||
|
||||
---
|
||||
|
||||
## 🚀 使用方法
|
||||
|
||||
### 方法一:手动触发(推荐,支持自定义配置)
|
||||
|
||||
1. **打开 Actions 页面**
|
||||
- 进入 GitHub 仓库
|
||||
- 点击顶部 **Actions** 标签
|
||||
|
||||
2. **选择 Workflow**
|
||||
- 左侧选择 **Build Android APK**
|
||||
- 右侧点击 **Run workflow** 下拉框
|
||||
|
||||
3. **配置参数**
|
||||
|
||||
| 参数 | 说明 | 默认值 |
|
||||
|-----|------|--------|
|
||||
| **构建类型** | debug 或 release | `release` |
|
||||
| **API 域名** | 后端 API 服务器域名 | `api.maodag.top` |
|
||||
| **OSS 地址 1** | 配置文件 CDN 地址(香港) | `https://ppp2.oss-cn-hongkong.aliyuncs.com/bear1.txt` |
|
||||
| **OSS 地址 2** | 配置文件 CDN 地址(东京) | `https://xgp3.oss-ap-northeast-1.aliyuncs.com/bear1.txt` |
|
||||
| **OSS 地址 3** | 配置文件 CDN 地址(首尔) | `https://xpp4.oss-ap-northeast-2.aliyuncs.com/bear1.txt` |
|
||||
| **OSS 地址 4** | 配置文件 CDN 地址(新加坡) | `https://xpp5.oss-ap-southeast-1.aliyuncs.com/bear1.txt` |
|
||||
|
||||
4. **开始构建**
|
||||
- 点击绿色 **Run workflow** 按钮
|
||||
- 等待约 30 分钟完成
|
||||
|
||||
5. **下载 APK**
|
||||
- 构建完成后,在运行记录页面找到 **Artifacts** 区域
|
||||
- 下载对应架构的 APK
|
||||
|
||||
---
|
||||
|
||||
### 方法二:推送代码自动构建(使用默认配置)
|
||||
|
||||
```bash
|
||||
# 提交代码
|
||||
git add .
|
||||
git commit -m "feat: 新功能"
|
||||
|
||||
# 推送到 main 分支
|
||||
git push origin main
|
||||
```
|
||||
|
||||
**注意:** 自动触发的构建使用默认配置(`api.maodag.top` 和默认 OSS 地址)
|
||||
|
||||
---
|
||||
|
||||
### 方法三:创建 Release 版本
|
||||
|
||||
```bash
|
||||
# 1. 打标签(必须以 v 开头)
|
||||
git tag v1.0.0
|
||||
|
||||
# 2. 推送标签
|
||||
git push origin v1.0.0
|
||||
|
||||
# 3. 自动触发构建并创建 Release
|
||||
# 访问 https://github.com/你的用户名/LighthouseApp/releases 查看
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📦 构建产物
|
||||
|
||||
### APK 命名规则
|
||||
|
||||
```
|
||||
BearVPN-{架构}-{类型}-{日期}-{提交哈希}.apk
|
||||
```
|
||||
|
||||
**示例:**
|
||||
```
|
||||
BearVPN-arm64-v8a-release-20251027-abc1234.apk
|
||||
BearVPN-armeabi-v7a-release-20251027-abc1234.apk
|
||||
BearVPN-x86_64-release-20251027-abc1234.apk
|
||||
```
|
||||
|
||||
### 架构说明
|
||||
|
||||
| 架构 | 适用设备 | 推荐度 |
|
||||
|------|---------|-------|
|
||||
| **arm64-v8a** | 2017年后的现代手机 | ⭐⭐⭐⭐⭐ |
|
||||
| **armeabi-v7a** | 2012-2017年的老旧手机 | ⭐⭐ |
|
||||
| **x86_64** | Android 模拟器 | ⭐⭐⭐ |
|
||||
|
||||
**大多数用户应下载 `arm64-v8a` 版本**
|
||||
|
||||
---
|
||||
|
||||
## 🔧 配置示例
|
||||
|
||||
### 示例 1:修改 API 域名
|
||||
|
||||
如果你的后端部署在 `api.example.com`:
|
||||
|
||||
1. 手动触发 workflow
|
||||
2. 将 **API 域名** 改为 `api.example.com`
|
||||
3. OSS 地址保持默认
|
||||
4. 点击 Run workflow
|
||||
|
||||
### 示例 2:使用自己的 CDN
|
||||
|
||||
如果你有自己的配置文件 CDN:
|
||||
|
||||
1. 手动触发 workflow
|
||||
2. API 域名保持默认
|
||||
3. 修改 **OSS 地址 1-4** 为你的 CDN 地址,例如:
|
||||
- OSS 地址 1: `https://cdn1.example.com/config.txt`
|
||||
- OSS 地址 2: `https://cdn2.example.com/config.txt`
|
||||
- OSS 地址 3: `https://cdn3.example.com/config.txt`
|
||||
- OSS 地址 4: `https://cdn4.example.com/config.txt`
|
||||
4. 点击 Run workflow
|
||||
|
||||
### 示例 3:完全自定义配置
|
||||
|
||||
```yaml
|
||||
构建类型: release
|
||||
API 域名: api.mycompany.com
|
||||
OSS 地址 1: https://config.mycdn.com/v1/nodes.txt
|
||||
OSS 地址 2: https://backup1.mycdn.com/v1/nodes.txt
|
||||
OSS 地址 3: https://backup2.mycdn.com/v1/nodes.txt
|
||||
OSS 地址 4: https://backup3.mycdn.com/v1/nodes.txt
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ⏱️ 构建时间
|
||||
|
||||
| 阶段 | 时间 |
|
||||
|-----|------|
|
||||
| 编译 libcore.aar | 10-15 分钟 |
|
||||
| 编译 Flutter APK | 15-20 分钟 |
|
||||
| **总计** | **约 30 分钟** |
|
||||
|
||||
---
|
||||
|
||||
## 🔍 查看构建日志
|
||||
|
||||
1. 打开 Actions 页面
|
||||
2. 点击对应的运行记录
|
||||
3. 点击具体的 job(如 "编译 Android APK")
|
||||
4. 展开步骤查看详细日志
|
||||
|
||||
**关键步骤:**
|
||||
- `⚙️ 配置 API 域名和 OSS 地址` - 查看配置是否正确替换
|
||||
- `🔨 构建 APK` - 查看编译过程
|
||||
- `📦 重命名 APK 文件` - 查看生成的文件名和 MD5
|
||||
|
||||
---
|
||||
|
||||
## 🐛 常见问题
|
||||
|
||||
### Q1: 如何验证配置是否生效?
|
||||
|
||||
**A:** 查看 `⚙️ 配置 API 域名和 OSS 地址` 步骤的日志:
|
||||
|
||||
```
|
||||
🔧 配置构建参数:
|
||||
API 域名: api.example.com
|
||||
OSS 地址 1: https://cdn1.example.com/config.txt
|
||||
...
|
||||
|
||||
✅ 配置替换完成
|
||||
|
||||
📄 查看修改后的配置:
|
||||
static List<String> kr_baseDomains = ["api.example.com","api.example.com"];
|
||||
static String kr_currentDomain = "api.example.com";
|
||||
```
|
||||
|
||||
如果看到你设置的域名,说明配置成功。
|
||||
|
||||
---
|
||||
|
||||
### Q2: Release 构建和 Debug 构建有什么区别?
|
||||
|
||||
| 特性 | Debug | Release |
|
||||
|-----|-------|---------|
|
||||
| **文件大小** | 较大 | 较小(优化后) |
|
||||
| **性能** | 较慢 | 快 |
|
||||
| **调试信息** | 包含 | 移除 |
|
||||
| **代码混淆** | 无 | 有 |
|
||||
| **适用场景** | 开发测试 | 正式发布 |
|
||||
|
||||
**推荐:** 生产环境使用 **release** 构建
|
||||
|
||||
---
|
||||
|
||||
### Q3: 如何使用环境变量配置(不想每次手动输入)?
|
||||
|
||||
在仓库 **Settings → Secrets and variables → Actions → Variables** 添加:
|
||||
|
||||
| 变量名 | 值 |
|
||||
|-------|---|
|
||||
| `DEFAULT_API_DOMAIN` | `api.example.com` |
|
||||
| `DEFAULT_OSS_URL_1` | `https://cdn1.example.com/config.txt` |
|
||||
| `DEFAULT_OSS_URL_2` | `https://cdn2.example.com/config.txt` |
|
||||
| `DEFAULT_OSS_URL_3` | `https://cdn3.example.com/config.txt` |
|
||||
| `DEFAULT_OSS_URL_4` | `https://cdn4.example.com/config.txt` |
|
||||
|
||||
然后修改 workflow 文件,将默认值改为:
|
||||
|
||||
```yaml
|
||||
default: ${{ vars.DEFAULT_API_DOMAIN || 'api.maodag.top' }}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Q4: 构建失败 - "libcore.aar not found"
|
||||
|
||||
**原因:** libcore 编译失败
|
||||
|
||||
**解决:**
|
||||
1. 检查 `build-libcore` job 的日志
|
||||
2. 确认 Go 环境和 gomobile 安装成功
|
||||
3. 确认 libcore 子模块已正确初始化
|
||||
|
||||
---
|
||||
|
||||
### Q5: 如何配置签名(Release 构建必需)?
|
||||
|
||||
详见主文档 `.github/workflows/README.md` 的签名配置章节。
|
||||
|
||||
---
|
||||
|
||||
## 💡 高级技巧
|
||||
|
||||
### 技巧 1:同时构建多个版本
|
||||
|
||||
修改 `build-apk` job:
|
||||
|
||||
```yaml
|
||||
strategy:
|
||||
matrix:
|
||||
build_type: [debug, release]
|
||||
api_domain: ['api.maodag.top', 'api.example.com']
|
||||
```
|
||||
|
||||
这样会生成 4 个 APK(2种类型 × 2个域名)
|
||||
|
||||
---
|
||||
|
||||
### 技巧 2:添加构建完成通知
|
||||
|
||||
在 workflow 最后添加:
|
||||
|
||||
```yaml
|
||||
- name: 📢 发送 Telegram 通知
|
||||
if: success()
|
||||
run: |
|
||||
curl -X POST "https://api.telegram.org/bot${{ secrets.TELEGRAM_BOT_TOKEN }}/sendMessage" \
|
||||
-d chat_id=${{ secrets.TELEGRAM_CHAT_ID }} \
|
||||
-d text="✅ BearVPN 构建成功!下载: https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}"
|
||||
```
|
||||
|
||||
需要先配置 `TELEGRAM_BOT_TOKEN` 和 `TELEGRAM_CHAT_ID` Secrets。
|
||||
|
||||
---
|
||||
|
||||
### 技巧 3:缓存加速构建
|
||||
|
||||
workflow 已配置 Go 和 Flutter 缓存,首次构建约 30 分钟,后续构建可缩短至 15-20 分钟。
|
||||
|
||||
---
|
||||
|
||||
## 📊 构建状态徽章
|
||||
|
||||
在 README.md 中添加:
|
||||
|
||||
```markdown
|
||||

|
||||
```
|
||||
|
||||
效果:
|
||||
|
||||
---
|
||||
|
||||
## 🔗 相关文件
|
||||
|
||||
- **主 Workflow:** `.github/workflows/build-android-apk.yml`
|
||||
- **配置文件:** `lib/app/common/app_config.dart`
|
||||
- **libcore 源码:** `libcore/` 子模块
|
||||
|
||||
---
|
||||
|
||||
## 📞 需要帮助?
|
||||
|
||||
- 查看 [GitHub Actions 文档](https://docs.github.com/actions)
|
||||
- 查看构建日志排查问题
|
||||
- 提交 Issue 到仓库
|
||||
|
||||
---
|
||||
|
||||
**生成时间:** 2025-10-27
|
||||
**作者:** Claude Code
|
||||
**版本:** 1.0.0
|
||||
366
.github/workflows/HOW_TO_BUILD.md
vendored
Normal file
366
.github/workflows/HOW_TO_BUILD.md
vendored
Normal file
@ -0,0 +1,366 @@
|
||||
# 🎯 如何在 GitHub 上构建你的应用
|
||||
|
||||
## 📋 前提条件
|
||||
|
||||
✅ 已将配置推送到 GitHub
|
||||
✅ 有 GitHub 账号访问权限
|
||||
|
||||
---
|
||||
|
||||
## 🚀 方法一:手动触发构建(推荐新手)
|
||||
|
||||
### 步骤 1: 访问 GitHub Actions 页面
|
||||
|
||||
1. 打开浏览器,访问你的仓库:
|
||||
```
|
||||
https://github.com/你的用户名/LighthouseApp
|
||||
```
|
||||
|
||||
2. 点击顶部导航栏的 **Actions** 标签
|
||||
```
|
||||
Code Issues Pull requests Actions Projects Wiki Security Insights
|
||||
↑ 点这里
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 步骤 2: 选择 Workflow
|
||||
|
||||
在左侧栏看到可用的 workflows:
|
||||
|
||||
```
|
||||
All workflows
|
||||
├── Build Android APK ← 仅构建 Android
|
||||
├── Build Multi-Platform ← 构建所有平台 ⭐推荐
|
||||
└── Build Clash Core
|
||||
```
|
||||
|
||||
**选择建议:**
|
||||
- 🟢 **首次测试:** 选择 **Build Android APK**(快速)
|
||||
- 🔵 **正式发布:** 选择 **Build Multi-Platform**(全平台)
|
||||
|
||||
---
|
||||
|
||||
### 步骤 3: 运行 Workflow
|
||||
|
||||
1. 点击选择的 workflow 名称
|
||||
|
||||
2. 右侧出现 **"Run workflow"** 下拉按钮
|
||||
```
|
||||
[Run workflow ▼]
|
||||
```
|
||||
|
||||
3. 点击下拉按钮,展开配置面板
|
||||
|
||||
---
|
||||
|
||||
### 步骤 4: 配置参数
|
||||
|
||||
#### 如果选择 "Build Android APK":
|
||||
|
||||
```yaml
|
||||
┌─────────────────────────────────────────┐
|
||||
│ Run workflow │
|
||||
├─────────────────────────────────────────┤
|
||||
│ Use workflow from │
|
||||
│ Branch: main [▼] │
|
||||
│ │
|
||||
│ 构建类型 │
|
||||
│ ○ debug │
|
||||
│ ● release │
|
||||
│ │
|
||||
│ API 域名 │
|
||||
│ [api.maodag.top________________] │
|
||||
│ │
|
||||
│ OSS 配置地址 1 │
|
||||
│ [https://ppp2.oss-cn-hongkong...] │
|
||||
│ │
|
||||
│ OSS 配置地址 2 │
|
||||
│ [https://xgp3.oss-ap-northeast-1...] │
|
||||
│ │
|
||||
│ OSS 配置地址 3 │
|
||||
│ [https://xpp4.oss-ap-northeast-2...] │
|
||||
│ │
|
||||
│ OSS 配置地址 4 │
|
||||
│ [https://xpp5.oss-ap-southeast-1...] │
|
||||
│ │
|
||||
│ [Cancel] [Run workflow] │
|
||||
└─────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
**配置说明:**
|
||||
- **构建类型:** 选择 `release`(生产环境)
|
||||
- **API 域名:** 填写你的后端域名(默认 `api.maodag.top`)
|
||||
- **OSS 地址:** 保持默认或填写你的 CDN 地址
|
||||
|
||||
#### 如果选择 "Build Multi-Platform":
|
||||
|
||||
额外多一个参数:
|
||||
```yaml
|
||||
│ 构建平台 │
|
||||
│ [android,windows,macos,linux______] │
|
||||
```
|
||||
|
||||
**选项:**
|
||||
- `android` - 仅 Android
|
||||
- `windows` - 仅 Windows
|
||||
- `macos` - 仅 macOS
|
||||
- `linux` - 仅 Linux
|
||||
- `android,windows` - Android + Windows
|
||||
- `android,windows,macos,linux` - 全部平台 ⭐
|
||||
|
||||
---
|
||||
|
||||
### 步骤 5: 开始构建
|
||||
|
||||
1. 检查所有参数是否正确
|
||||
|
||||
2. 点击绿色的 **"Run workflow"** 按钮
|
||||
|
||||
3. 页面刷新,顶部出现黄色进度条:
|
||||
```
|
||||
⚠️ Build Android APK #1
|
||||
Queued - This workflow is in queue waiting to run
|
||||
```
|
||||
|
||||
4. 几秒后变为蓝色(运行中):
|
||||
```
|
||||
🔵 Build Android APK #1
|
||||
In progress - This workflow is currently running
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 步骤 6: 监控构建进度
|
||||
|
||||
1. 点击运行记录(蓝色行)
|
||||
|
||||
2. 看到构建阶段:
|
||||
```
|
||||
编译 libcore.aar 🔵 Running (15分钟)
|
||||
编译 Android APK ⏸️ Pending
|
||||
```
|
||||
|
||||
3. 可以展开查看实时日志:
|
||||
```
|
||||
▼ 编译 libcore.aar
|
||||
▼ 📦 编译 libcore.aar
|
||||
🚀 开始编译 libcore...
|
||||
[gomobile] installing...
|
||||
✅ libcore.aar 生成成功
|
||||
```
|
||||
|
||||
4. 等待所有阶段完成(约 30-85 分钟)
|
||||
|
||||
---
|
||||
|
||||
### 步骤 7: 下载构建产物
|
||||
|
||||
构建成功后:
|
||||
|
||||
1. 向下滚动到 **Artifacts** 区域
|
||||
```
|
||||
📦 Artifacts
|
||||
|
||||
Produced during runtime
|
||||
|
||||
Name Size Expires
|
||||
apk-arm64-v8a-release 42.5 MB in 30 days [Download]
|
||||
apk-armeabi-v7a-release 38.2 MB in 30 days [Download]
|
||||
apk-x86_64-release 45.1 MB in 30 days [Download]
|
||||
```
|
||||
|
||||
2. 点击 **[Download]** 下载对应文件
|
||||
|
||||
3. 下载的是 ZIP 文件,解压后得到 APK:
|
||||
```
|
||||
apk-arm64-v8a-release.zip
|
||||
└── BearVPN-android-arm64-v8a-release-20251027-abc1234.apk
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🏷️ 方法二:推送标签自动构建
|
||||
|
||||
这种方式会自动构建并创建 GitHub Release。
|
||||
|
||||
### 步骤 1: 在本地打标签
|
||||
|
||||
```bash
|
||||
cd /Users/mac/Project/Dart/LighthouseApp
|
||||
|
||||
# 创建标签(版本号必须以 v 开头)
|
||||
git tag v1.0.0
|
||||
|
||||
# 查看标签
|
||||
git tag
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 步骤 2: 推送标签到 GitHub
|
||||
|
||||
```bash
|
||||
git push origin v1.0.0
|
||||
```
|
||||
|
||||
**输出:**
|
||||
```
|
||||
Enumerating objects: 1, done.
|
||||
Counting objects: 100% (1/1), done.
|
||||
Writing objects: 100% (1/1), 160 bytes | 160.00 KiB/s, done.
|
||||
Total 1 (delta 0), reused 0 (delta 0)
|
||||
To github.com:你的用户名/LighthouseApp.git
|
||||
* [new tag] v1.0.0 -> v1.0.0
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 步骤 3: 自动触发构建
|
||||
|
||||
1. 推送标签后,GitHub 自动检测到标签
|
||||
2. 触发 **Build Multi-Platform** workflow
|
||||
3. 使用默认配置构建所有平台
|
||||
|
||||
---
|
||||
|
||||
### 步骤 4: 查看构建进度
|
||||
|
||||
1. 访问 Actions 页面
|
||||
2. 看到自动创建的构建任务:
|
||||
```
|
||||
🔵 Build Multi-Platform
|
||||
v1.0.0
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 步骤 5: 下载 Release
|
||||
|
||||
构建成功后:
|
||||
|
||||
1. 访问 **Releases** 页面:
|
||||
```
|
||||
https://github.com/你的用户名/LighthouseApp/releases
|
||||
```
|
||||
|
||||
2. 看到新创建的 Release:
|
||||
```
|
||||
📦 v1.0.0
|
||||
|
||||
Latest Pre-release
|
||||
|
||||
🎉 BearVPN 多平台版本发布
|
||||
|
||||
Assets (7)
|
||||
├── BearVPN-android-arm64-v8a-release-*.apk 42.5 MB
|
||||
├── BearVPN-android-armeabi-v7a-release-*.apk 38.2 MB
|
||||
├── BearVPN-android-x86_64-release-*.apk 45.1 MB
|
||||
├── BearVPN-windows-x64-release-*.zip 52.3 MB
|
||||
├── BearVPN-macos-release-*.zip 48.7 MB
|
||||
├── BearVPN-linux-x64-release-*.tar.gz 45.9 MB
|
||||
└── Source code (zip)
|
||||
```
|
||||
|
||||
3. 直接下载需要的文件
|
||||
|
||||
---
|
||||
|
||||
## ⏱️ 构建时间参考
|
||||
|
||||
| Workflow | 平台 | 时间 |
|
||||
|---------|------|------|
|
||||
| Build Android APK | Android | 30 分钟 |
|
||||
| Build Multi-Platform | Android | 35 分钟 |
|
||||
| Build Multi-Platform | Windows | 30 分钟 |
|
||||
| Build Multi-Platform | macOS | 35 分钟 |
|
||||
| Build Multi-Platform | Linux | 30 分钟 |
|
||||
| Build Multi-Platform | 全部平台 | **60-85 分钟** |
|
||||
|
||||
**提示:** 平台是并行构建的,不是累加时间。
|
||||
|
||||
---
|
||||
|
||||
## 🎯 推荐流程
|
||||
|
||||
### 首次测试(验证流程)
|
||||
|
||||
```
|
||||
1. 选择 "Build Android APK"
|
||||
2. 使用默认配置
|
||||
3. 运行构建
|
||||
4. 等待 30 分钟
|
||||
5. 下载 arm64-v8a APK
|
||||
6. 安装测试
|
||||
```
|
||||
|
||||
### 正式发布(生产环境)
|
||||
|
||||
```
|
||||
1. 确保代码已测试
|
||||
2. 本地打标签: git tag v1.0.0
|
||||
3. 推送标签: git push origin v1.0.0
|
||||
4. 等待 60-85 分钟
|
||||
5. 在 Releases 页面下载所有平台
|
||||
6. 分发给用户
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🐛 常见问题
|
||||
|
||||
### Q1: 找不到 "Run workflow" 按钮
|
||||
|
||||
**原因:** 可能还在查看历史运行记录
|
||||
|
||||
**解决:**
|
||||
1. 点击左侧的 workflow 名称
|
||||
2. 确保在 workflow 主页面
|
||||
3. 右侧会出现 "Run workflow" 按钮
|
||||
|
||||
---
|
||||
|
||||
### Q2: 构建失败
|
||||
|
||||
**排查步骤:**
|
||||
1. 点击失败的运行记录
|
||||
2. 展开红色的步骤
|
||||
3. 查看错误日志
|
||||
4. 常见错误:
|
||||
- libcore 编译失败 → 检查 Go 环境
|
||||
- APK 构建失败 → 检查 Flutter 依赖
|
||||
|
||||
---
|
||||
|
||||
### Q3: Artifacts 下载后是空的
|
||||
|
||||
**原因:** 构建可能失败
|
||||
|
||||
**解决:**
|
||||
1. 检查构建日志
|
||||
2. 确保所有步骤都是绿色 ✅
|
||||
3. 重新运行构建
|
||||
|
||||
---
|
||||
|
||||
### Q4: 如何修改 API 域名
|
||||
|
||||
**方法 1:** 手动触发时修改参数
|
||||
|
||||
**方法 2:** 修改代码中的默认值
|
||||
```dart
|
||||
// lib/app/common/app_config.dart
|
||||
static String kr_currentDomain = "api.example.com";
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📞 需要帮助?
|
||||
|
||||
- **查看详细文档:** `.github/workflows/INDEX.md`
|
||||
- **快速开始:** `.github/workflows/QUICKSTART.md`
|
||||
- **问题反馈:** GitHub Issues
|
||||
|
||||
---
|
||||
|
||||
**准备好了吗?立即开始构建!** 🚀
|
||||
318
.github/workflows/INDEX.md
vendored
Normal file
318
.github/workflows/INDEX.md
vendored
Normal file
@ -0,0 +1,318 @@
|
||||
# 📚 GitHub Actions 构建系统总览
|
||||
|
||||
## 🎯 快速导航
|
||||
|
||||
| 文档 | 用途 | 适合人群 |
|
||||
|-----|------|---------|
|
||||
| **[QUICKSTART.md](./QUICKSTART.md)** | 3步快速开始 | 新手 |
|
||||
| **[README.md](./README.md)** | 基础说明 | 所有人 |
|
||||
| **[BUILD_GUIDE.md](./BUILD_GUIDE.md)** | Android 详细指南 | Android 开发者 |
|
||||
| **[MULTIPLATFORM_GUIDE.md](./MULTIPLATFORM_GUIDE.md)** | 多平台构建指南 | 全平台开发者 |
|
||||
|
||||
---
|
||||
|
||||
## 📋 可用的 Workflows
|
||||
|
||||
### 1. `build-android-apk.yml` - Android 专用构建
|
||||
|
||||
**功能:**
|
||||
- ✅ 编译 libcore.aar
|
||||
- ✅ 构建 Android APK (arm64/armv7/x86_64)
|
||||
- ✅ 配置 API 域名和 OSS 地址
|
||||
- ✅ Release 构建
|
||||
|
||||
**触发条件:**
|
||||
- 推送到 main/develop 分支
|
||||
- 创建 v* 标签
|
||||
- 手动触发
|
||||
|
||||
**文档:** [BUILD_GUIDE.md](./BUILD_GUIDE.md)
|
||||
|
||||
---
|
||||
|
||||
### 2. `build-multiplatform.yml` - 多平台构建 ⭐推荐
|
||||
|
||||
**功能:**
|
||||
- ✅ Android APK
|
||||
- ✅ Windows 可执行文件
|
||||
- ✅ macOS 应用
|
||||
- ✅ Linux 可执行文件
|
||||
- ✅ 可选择构建平台
|
||||
- ✅ 统一配置管理
|
||||
|
||||
**触发条件:**
|
||||
- 推送到 main/develop 分支
|
||||
- 创建 v* 标签
|
||||
- 手动触发
|
||||
|
||||
**文档:** [MULTIPLATFORM_GUIDE.md](./MULTIPLATFORM_GUIDE.md)
|
||||
|
||||
---
|
||||
|
||||
### 3. `build-clash-core.yml` - Clash 核心编译
|
||||
|
||||
**功能:**
|
||||
- 编译 Clash Meta 核心
|
||||
- 支持多架构 (arm64/armv7/x86_64)
|
||||
|
||||
**触发条件:**
|
||||
- core/ 目录变更
|
||||
- 手动触发
|
||||
|
||||
---
|
||||
|
||||
## 🚀 使用建议
|
||||
|
||||
### 场景 1: 日常开发(仅 Android)
|
||||
|
||||
**使用:** `build-android-apk.yml`
|
||||
```bash
|
||||
# 推送代码自动触发
|
||||
git push origin main
|
||||
```
|
||||
|
||||
**时间:** 约 30 分钟
|
||||
**产物:** 3 个 Android APK
|
||||
|
||||
---
|
||||
|
||||
### 场景 2: 正式发布(所有平台)
|
||||
|
||||
**使用:** `build-multiplatform.yml`
|
||||
```bash
|
||||
# 1. 打标签
|
||||
git tag v1.0.0
|
||||
git push origin v1.0.0
|
||||
|
||||
# 2. 自动构建所有平台并创建 Release
|
||||
```
|
||||
|
||||
**时间:** 约 60-85 分钟(并行)
|
||||
**产物:** Android + Windows + macOS + Linux
|
||||
|
||||
---
|
||||
|
||||
### 场景 3: 测试特定平台
|
||||
|
||||
**使用:** `build-multiplatform.yml` 手动触发
|
||||
```yaml
|
||||
构建平台: android,windows # 只构建这两个
|
||||
```
|
||||
|
||||
**时间:** 约 35 分钟
|
||||
**产物:** 指定平台
|
||||
|
||||
---
|
||||
|
||||
## 📦 构建产物对比
|
||||
|
||||
### Android 专用构建
|
||||
|
||||
```
|
||||
BearVPN-android-arm64-v8a-release-20251027-abc1234.apk
|
||||
BearVPN-android-armeabi-v7a-release-20251027-abc1234.apk
|
||||
BearVPN-android-x86_64-release-20251027-abc1234.apk
|
||||
```
|
||||
|
||||
### 多平台构建
|
||||
|
||||
```
|
||||
# Android
|
||||
BearVPN-android-arm64-v8a-release-20251027-abc1234.apk
|
||||
BearVPN-android-armeabi-v7a-release-20251027-abc1234.apk
|
||||
BearVPN-android-x86_64-release-20251027-abc1234.apk
|
||||
|
||||
# Windows
|
||||
BearVPN-windows-x64-release-20251027-abc1234.zip
|
||||
|
||||
# macOS
|
||||
BearVPN-macos-release-20251027-abc1234.zip
|
||||
|
||||
# Linux
|
||||
BearVPN-linux-x64-release-20251027-abc1234.tar.gz
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ⚙️ 配置参数说明
|
||||
|
||||
### 所有 Workflow 通用参数
|
||||
|
||||
| 参数 | 默认值 | 说明 |
|
||||
|-----|-------|------|
|
||||
| **构建类型** | `release` | debug 或 release |
|
||||
| **API 域名** | `api.maodag.top` | 后端服务器地址 |
|
||||
| **OSS 地址 1** | 香港 CDN | 配置文件源 |
|
||||
| **OSS 地址 2** | 东京 CDN | 备用配置源 |
|
||||
| **OSS 地址 3** | 首尔 CDN | 备用配置源 |
|
||||
| **OSS 地址 4** | 新加坡 CDN | 备用配置源 |
|
||||
|
||||
### 多平台专用参数
|
||||
|
||||
| 参数 | 默认值 | 说明 |
|
||||
|-----|-------|------|
|
||||
| **构建平台** | `android,windows,macos,linux` | 选择构建的平台 |
|
||||
|
||||
---
|
||||
|
||||
## ⏱️ 构建时间对比
|
||||
|
||||
| Workflow | 单平台 | 全平台 |
|
||||
|---------|-------|-------|
|
||||
| **Android 专用** | 30分钟 | - |
|
||||
| **多平台** | 30-40分钟 | 60-85分钟 |
|
||||
|
||||
---
|
||||
|
||||
## 🎯 选择 Workflow 的建议
|
||||
|
||||
### 选择 `build-android-apk.yml` 如果:
|
||||
|
||||
- ✅ 只需要 Android 版本
|
||||
- ✅ 快速迭代开发
|
||||
- ✅ CI/CD 自动触发
|
||||
|
||||
### 选择 `build-multiplatform.yml` 如果:
|
||||
|
||||
- ✅ 需要桌面版本
|
||||
- ✅ 正式版本发布
|
||||
- ✅ 需要灵活选择平台
|
||||
|
||||
---
|
||||
|
||||
## 🔧 环境配置
|
||||
|
||||
### 必需的 Secrets(用于 Release 签名)
|
||||
|
||||
**Android:**
|
||||
```
|
||||
KEYSTORE_BASE64
|
||||
KEYSTORE_PASSWORD
|
||||
KEY_ALIAS
|
||||
KEY_PASSWORD
|
||||
```
|
||||
|
||||
**macOS:**
|
||||
```
|
||||
MACOS_CERTIFICATE_BASE64
|
||||
MACOS_CERTIFICATE_PASSWORD
|
||||
```
|
||||
|
||||
**Windows:**
|
||||
```
|
||||
WINDOWS_CERTIFICATE_BASE64
|
||||
WINDOWS_CERTIFICATE_PASSWORD
|
||||
```
|
||||
|
||||
**说明:** 如果不配置签名,可以使用 debug 构建。
|
||||
|
||||
---
|
||||
|
||||
## 📊 构建流程图
|
||||
|
||||
### Android 专用
|
||||
|
||||
```
|
||||
Checkout 代码
|
||||
↓
|
||||
编译 libcore.aar (15min)
|
||||
↓
|
||||
配置 API/OSS
|
||||
↓
|
||||
构建 APK (20min)
|
||||
↓
|
||||
上传产物
|
||||
```
|
||||
|
||||
### 多平台
|
||||
|
||||
```
|
||||
Checkout 代码
|
||||
↓
|
||||
编译 libcore.aar (15min)
|
||||
↓
|
||||
├─→ Android (20min) ─┐
|
||||
├─→ Windows (15min) ─┤
|
||||
├─→ macOS (20min) ─┼─→ 创建 Release
|
||||
└─→ Linux (15min) ─┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🐛 故障排查
|
||||
|
||||
### 问题 1: libcore 编译失败
|
||||
|
||||
**检查:**
|
||||
1. Go 环境是否正常
|
||||
2. gomobile 是否安装
|
||||
3. 网络连接(下载依赖)
|
||||
|
||||
**日志位置:** `build-libcore` job
|
||||
|
||||
---
|
||||
|
||||
### 问题 2: Android 构建失败
|
||||
|
||||
**常见原因:**
|
||||
- libcore.aar 未生成
|
||||
- Gradle 依赖问题
|
||||
- 签名配置错误
|
||||
|
||||
**解决:** 查看 `build-android` job 日志
|
||||
|
||||
---
|
||||
|
||||
### 问题 3: macOS 构建失败
|
||||
|
||||
**常见原因:**
|
||||
- 签名证书未配置
|
||||
- Xcode 版本不兼容
|
||||
|
||||
**解决:**
|
||||
- 使用 debug 构建
|
||||
- 或配置签名证书
|
||||
|
||||
---
|
||||
|
||||
## 💡 高级用法
|
||||
|
||||
### 1. 定时构建
|
||||
|
||||
添加到 workflow:
|
||||
|
||||
```yaml
|
||||
on:
|
||||
schedule:
|
||||
- cron: '0 2 * * *' # 每天UTC 2:00
|
||||
```
|
||||
|
||||
### 2. PR 自动构建
|
||||
|
||||
已配置:推送 PR 到 main 分支自动触发
|
||||
|
||||
### 3. 构建通知
|
||||
|
||||
可集成 Telegram/Slack/钉钉通知
|
||||
|
||||
---
|
||||
|
||||
## 📞 获取帮助
|
||||
|
||||
- **查看文档:** 本目录下的 Markdown 文件
|
||||
- **查看日志:** GitHub Actions 页面
|
||||
- **提交问题:** Issues 页面
|
||||
|
||||
---
|
||||
|
||||
## 🔗 相关链接
|
||||
|
||||
- [GitHub Actions 文档](https://docs.github.com/actions)
|
||||
- [Flutter CI/CD](https://docs.flutter.dev/deployment/cd)
|
||||
- [sing-box 文档](https://sing-box.sagernet.org/)
|
||||
|
||||
---
|
||||
|
||||
**版本:** 1.0.0
|
||||
**更新:** 2025-10-27
|
||||
**作者:** Claude Code
|
||||
407
.github/workflows/MULTIPLATFORM_GUIDE.md
vendored
Normal file
407
.github/workflows/MULTIPLATFORM_GUIDE.md
vendored
Normal file
@ -0,0 +1,407 @@
|
||||
# 🌐 多平台构建完全指南
|
||||
|
||||
## 📋 支持的平台
|
||||
|
||||
✅ **Android** - arm64-v8a / armeabi-v7a / x86_64
|
||||
✅ **Windows** - x64
|
||||
✅ **macOS** - Universal (Intel + Apple Silicon)
|
||||
✅ **Linux** - x64
|
||||
|
||||
---
|
||||
|
||||
## 🚀 快速开始
|
||||
|
||||
### 方法 1: 构建所有平台(推荐)
|
||||
|
||||
1. 打开 GitHub Actions 页面
|
||||
2. 选择 **Build Multi-Platform**
|
||||
3. 点击 **Run workflow**
|
||||
4. 配置参数:
|
||||
|
||||
```yaml
|
||||
构建类型: release
|
||||
API 域名: api.maodag.top
|
||||
OSS 地址 1-4: 使用默认值
|
||||
构建平台: android,windows,macos,linux # 构建所有平台
|
||||
```
|
||||
|
||||
5. 点击 **Run workflow** 开始
|
||||
|
||||
---
|
||||
|
||||
### 方法 2: 仅构建指定平台
|
||||
|
||||
**场景:** 只需要 Android 和 Windows 版本
|
||||
|
||||
```yaml
|
||||
构建平台: android,windows # 只构建这两个平台
|
||||
```
|
||||
|
||||
**可选值:**
|
||||
- `android` - 仅 Android
|
||||
- `windows` - 仅 Windows
|
||||
- `macos` - 仅 macOS
|
||||
- `linux` - 仅 Linux
|
||||
- `android,windows` - Android + Windows
|
||||
- `android,windows,macos,linux` - 全部平台
|
||||
|
||||
---
|
||||
|
||||
## ⏱️ 构建时间估算
|
||||
|
||||
| 平台 | 时间 | 说明 |
|
||||
|-----|------|-----|
|
||||
| **libcore** | 10-15分钟 | Android 依赖 |
|
||||
| **Android** | 15-20分钟 | 3个架构APK |
|
||||
| **Windows** | 10-15分钟 | x64可执行文件 |
|
||||
| **macOS** | 15-20分钟 | Universal应用 |
|
||||
| **Linux** | 10-15分钟 | x64可执行文件 |
|
||||
| **总计(全平台)** | **60-85分钟** | 并行构建 |
|
||||
|
||||
---
|
||||
|
||||
## 📦 构建产物
|
||||
|
||||
### Android
|
||||
|
||||
```
|
||||
BearVPN-android-arm64-v8a-release-20251027-abc1234.apk (推荐)
|
||||
BearVPN-android-armeabi-v7a-release-20251027-abc1234.apk (老设备)
|
||||
BearVPN-android-x86_64-release-20251027-abc1234.apk (模拟器)
|
||||
```
|
||||
|
||||
**安装:** 直接点击APK安装
|
||||
|
||||
---
|
||||
|
||||
### Windows
|
||||
|
||||
```
|
||||
BearVPN-windows-x64-release-20251027-abc1234.zip
|
||||
```
|
||||
|
||||
**内容结构:**
|
||||
```
|
||||
BearVPN.exe # 主程序
|
||||
flutter_windows.dll # Flutter运行时
|
||||
data/ # 资源文件
|
||||
```
|
||||
|
||||
**运行:**
|
||||
1. 解压 ZIP 文件
|
||||
2. 双击 `BearVPN.exe` 运行
|
||||
3. 如提示缺少依赖,安装 [VC++ Redistributable](https://aka.ms/vs/17/release/vc_redist.x64.exe)
|
||||
|
||||
---
|
||||
|
||||
### macOS
|
||||
|
||||
```
|
||||
BearVPN-macos-release-20251027-abc1234.zip
|
||||
```
|
||||
|
||||
**内容:**
|
||||
```
|
||||
BearVPN.app # 应用程序包(Universal)
|
||||
```
|
||||
|
||||
**安装:**
|
||||
1. 解压 ZIP 文件
|
||||
2. 将 `BearVPN.app` 拖到 **应用程序** 文件夹
|
||||
3. 首次运行右键点击 → 打开(绕过 Gatekeeper)
|
||||
|
||||
**支持架构:**
|
||||
- Intel (x86_64)
|
||||
- Apple Silicon (arm64)
|
||||
|
||||
---
|
||||
|
||||
### Linux
|
||||
|
||||
```
|
||||
BearVPN-linux-x64-release-20251027-abc1234.tar.gz
|
||||
```
|
||||
|
||||
**内容结构:**
|
||||
```
|
||||
bearvpn # 可执行文件
|
||||
lib/ # 共享库
|
||||
data/ # 资源文件
|
||||
```
|
||||
|
||||
**运行:**
|
||||
```bash
|
||||
# 1. 解压
|
||||
tar -xzf BearVPN-linux-x64-release-*.tar.gz
|
||||
cd bundle
|
||||
|
||||
# 2. 添加执行权限
|
||||
chmod +x bearvpn
|
||||
|
||||
# 3. 运行
|
||||
./bearvpn
|
||||
```
|
||||
|
||||
**依赖要求:**
|
||||
- GTK+ 3
|
||||
- libstdc++12
|
||||
|
||||
**安装依赖(Ubuntu/Debian):**
|
||||
```bash
|
||||
sudo apt-get install libgtk-3-0 libstdc++6
|
||||
```
|
||||
|
||||
**安装依赖(Fedora/RHEL):**
|
||||
```bash
|
||||
sudo dnf install gtk3 libstdc++
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔧 配置说明
|
||||
|
||||
### 所有平台通用配置
|
||||
|
||||
| 参数 | 默认值 | 说明 |
|
||||
|-----|-------|------|
|
||||
| **构建类型** | `release` | debug 或 release |
|
||||
| **API 域名** | `api.maodag.top` | 后端服务器 |
|
||||
| **OSS 地址 1** | 香港 CDN | 配置文件源 |
|
||||
| **OSS 地址 2** | 东京 CDN | 备用源 |
|
||||
| **OSS 地址 3** | 首尔 CDN | 备用源 |
|
||||
| **OSS 地址 4** | 新加坡 CDN | 备用源 |
|
||||
| **构建平台** | `android,windows,macos,linux` | 选择平台 |
|
||||
|
||||
---
|
||||
|
||||
## 📥 下载构建产物
|
||||
|
||||
### 从 Actions 页面下载
|
||||
|
||||
1. 打开运行记录
|
||||
2. 滚动到 **Artifacts** 区域
|
||||
3. 下载对应平台:
|
||||
- `android-apk` - Android APK (所有架构)
|
||||
- `windows-x64` - Windows 可执行程序
|
||||
- `macos-app` - macOS 应用
|
||||
- `linux-x64` - Linux 可执行程序
|
||||
|
||||
### 从 Releases 下载(推送标签时)
|
||||
|
||||
1. 访问 Releases 页面
|
||||
2. 选择版本
|
||||
3. 在 Assets 中下载对应平台文件
|
||||
|
||||
---
|
||||
|
||||
## 🎯 使用场景
|
||||
|
||||
### 场景 1: 开发测试(仅 Android)
|
||||
|
||||
```yaml
|
||||
构建类型: debug
|
||||
构建平台: android
|
||||
API 域名: api.test.com
|
||||
```
|
||||
|
||||
**优点:** 快速,约20分钟
|
||||
|
||||
---
|
||||
|
||||
### 场景 2: 正式发布(全平台)
|
||||
|
||||
```yaml
|
||||
构建类型: release
|
||||
构建平台: android,windows,macos,linux
|
||||
API 域名: api.maodag.top
|
||||
```
|
||||
|
||||
**优点:** 一次构建,覆盖所有用户
|
||||
|
||||
---
|
||||
|
||||
### 场景 3: 仅桌面平台
|
||||
|
||||
```yaml
|
||||
构建类型: release
|
||||
构建平台: windows,macos,linux
|
||||
```
|
||||
|
||||
**用途:** 桌面版更新
|
||||
|
||||
---
|
||||
|
||||
## 🐛 常见问题
|
||||
|
||||
### Q1: Windows 构建失败 - "7z command not found"
|
||||
|
||||
**原因:** Windows runner 默认有 7z
|
||||
|
||||
**解决:** 检查构建日志,可能是其他错误
|
||||
|
||||
---
|
||||
|
||||
### Q2: macOS 构建失败 - "Code signing required"
|
||||
|
||||
**原因:** Release 构建需要签名
|
||||
|
||||
**解决方案:**
|
||||
|
||||
**方法 1:** 使用 debug 构建(测试用)
|
||||
|
||||
**方法 2:** 配置签名证书(生产用)
|
||||
```yaml
|
||||
# 在 Secrets 中添加
|
||||
MACOS_CERTIFICATE_BASE64
|
||||
MACOS_CERTIFICATE_PASSWORD
|
||||
MACOS_KEYCHAIN_PASSWORD
|
||||
PROVISIONING_PROFILE_BASE64
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Q3: Linux 运行时提示缺少库
|
||||
|
||||
**错误:**
|
||||
```
|
||||
error while loading shared libraries: libgtk-3.so.0
|
||||
```
|
||||
|
||||
**解决:**
|
||||
```bash
|
||||
sudo apt-get update
|
||||
sudo apt-get install libgtk-3-0
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Q4: 如何只更新某个平台?
|
||||
|
||||
**方法 1:** 手动触发指定平台
|
||||
```yaml
|
||||
构建平台: android # 只构建 Android
|
||||
```
|
||||
|
||||
**方法 2:** 创建平台专用 workflow(推荐)
|
||||
|
||||
---
|
||||
|
||||
### Q5: 构建时间太长怎么办?
|
||||
|
||||
**优化方案:**
|
||||
|
||||
1. **仅构建需要的平台**
|
||||
```yaml
|
||||
构建平台: android # 而不是全部
|
||||
```
|
||||
|
||||
2. **使用缓存**(已配置)
|
||||
- Flutter SDK 缓存
|
||||
- Gradle 缓存
|
||||
- Go modules 缓存
|
||||
|
||||
3. **分批构建**
|
||||
- 白天构建 Android/Windows
|
||||
- 晚上构建 macOS/Linux
|
||||
|
||||
---
|
||||
|
||||
## 💡 高级用法
|
||||
|
||||
### 技巧 1: 矩阵构建多个配置
|
||||
|
||||
修改 workflow:
|
||||
|
||||
```yaml
|
||||
strategy:
|
||||
matrix:
|
||||
api_domain: ['api.prod.com', 'api.test.com']
|
||||
platform: ['android', 'windows', 'macos', 'linux']
|
||||
```
|
||||
|
||||
**效果:** 生成 8 个版本(2域名 × 4平台)
|
||||
|
||||
---
|
||||
|
||||
### 技巧 2: 定时自动构建
|
||||
|
||||
添加到 workflow:
|
||||
|
||||
```yaml
|
||||
on:
|
||||
schedule:
|
||||
- cron: '0 2 * * *' # 每天凌晨2点(UTC)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 技巧 3: 构建完成通知
|
||||
|
||||
添加 Telegram 通知:
|
||||
|
||||
```yaml
|
||||
- name: 📢 通知
|
||||
run: |
|
||||
curl -X POST "https://api.telegram.org/bot${{ secrets.TG_BOT_TOKEN }}/sendMessage" \
|
||||
-d chat_id=${{ secrets.TG_CHAT_ID }} \
|
||||
-d text="✅ 多平台构建完成!"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📊 构建并行示意图
|
||||
|
||||
```
|
||||
libcore (15min)
|
||||
↓
|
||||
├─→ Android (20min) ─┐
|
||||
├─→ Windows (15min) ─┤
|
||||
├─→ macOS (20min) ─┼─→ Release (2min)
|
||||
└─→ Linux (15min) ─┘
|
||||
|
||||
总时间: 约 35-40分钟(并行)
|
||||
如果串行: 约 85分钟
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔐 安全建议
|
||||
|
||||
### Release 版本签名
|
||||
|
||||
**Android:**
|
||||
```yaml
|
||||
# Secrets 配置
|
||||
KEYSTORE_BASE64
|
||||
KEYSTORE_PASSWORD
|
||||
KEY_ALIAS
|
||||
KEY_PASSWORD
|
||||
```
|
||||
|
||||
**macOS:**
|
||||
```yaml
|
||||
# Secrets 配置
|
||||
MACOS_CERTIFICATE_BASE64
|
||||
MACOS_CERTIFICATE_PASSWORD
|
||||
```
|
||||
|
||||
**Windows:**
|
||||
```yaml
|
||||
# Secrets 配置
|
||||
WINDOWS_CERTIFICATE_BASE64
|
||||
WINDOWS_CERTIFICATE_PASSWORD
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📞 需要帮助?
|
||||
|
||||
- 查看 [GitHub Actions 文档](https://docs.github.com/actions)
|
||||
- 查看 [Flutter 桌面支持](https://docs.flutter.dev/desktop)
|
||||
- 提交 Issue
|
||||
|
||||
---
|
||||
|
||||
**版本:** 1.0.0
|
||||
**更新:** 2025-10-27
|
||||
**作者:** Claude Code
|
||||
78
.github/workflows/QUICKSTART.md
vendored
Normal file
78
.github/workflows/QUICKSTART.md
vendored
Normal file
@ -0,0 +1,78 @@
|
||||
# 🚀 GitHub Actions 快速开始
|
||||
|
||||
## 📋 3 步开始使用
|
||||
|
||||
### 步骤 1: 推送配置文件
|
||||
|
||||
```bash
|
||||
cd /Users/mac/Project/Dart/LighthouseApp
|
||||
|
||||
git add .github/workflows/
|
||||
git commit -m "feat: 添加 GitHub Actions 自动构建配置"
|
||||
git push origin main
|
||||
```
|
||||
|
||||
### 步骤 2: 手动触发构建
|
||||
|
||||
1. 打开 GitHub 仓库页面
|
||||
2. 点击 **Actions** 标签
|
||||
3. 左侧选择 **Build Android APK**
|
||||
4. 右侧点击 **Run workflow** 下拉按钮
|
||||
5. 配置参数(可以使用默认值):
|
||||
|
||||
```
|
||||
构建类型: release
|
||||
API 域名: api.maodag.top
|
||||
OSS 地址 1-4: 使用默认值
|
||||
```
|
||||
|
||||
6. 点击绿色 **Run workflow** 按钮
|
||||
|
||||
### 步骤 3: 下载 APK
|
||||
|
||||
- 等待约 30 分钟
|
||||
- 在构建记录页面找到 **Artifacts**
|
||||
- 下载 `apk-arm64-v8a-release`(推荐)
|
||||
|
||||
---
|
||||
|
||||
## 🎯 自定义配置示例
|
||||
|
||||
### 场景 1: 更换 API 域名
|
||||
|
||||
```yaml
|
||||
构建类型: release
|
||||
API 域名: api.example.com ← 修改这里
|
||||
OSS 地址: 保持默认
|
||||
```
|
||||
|
||||
### 场景 2: 使用自己的 CDN
|
||||
|
||||
```yaml
|
||||
构建类型: release
|
||||
API 域名: api.maodag.top
|
||||
OSS 地址 1: https://your-cdn.com/config1.txt ← 修改这里
|
||||
OSS 地址 2: https://your-cdn.com/config2.txt ← 修改这里
|
||||
OSS 地址 3: https://your-cdn.com/config3.txt ← 修改这里
|
||||
OSS 地址 4: https://your-cdn.com/config4.txt ← 修改这里
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📖 详细文档
|
||||
|
||||
- **完整指南:** [BUILD_GUIDE.md](./BUILD_GUIDE.md)
|
||||
- **基础说明:** [README.md](./README.md)
|
||||
|
||||
---
|
||||
|
||||
## ✅ 核心功能
|
||||
|
||||
✅ **Release 构建** - 生产环境优化版本
|
||||
✅ **可配置域名** - 支持自定义 API 和 CDN
|
||||
✅ **分架构打包** - arm64/armv7/x86_64
|
||||
✅ **自动 Release** - 推送标签自动发布
|
||||
|
||||
---
|
||||
|
||||
**需要帮助?** 查看 [BUILD_GUIDE.md](./BUILD_GUIDE.md)
|
||||
90
.github/workflows/README.md
vendored
Normal file
90
.github/workflows/README.md
vendored
Normal file
@ -0,0 +1,90 @@
|
||||
# GitHub Actions 构建说明
|
||||
|
||||
## 📋 工作流概览
|
||||
|
||||
### `build-android-apk.yml` - Android APK 自动构建
|
||||
|
||||
**触发条件:**
|
||||
- ✅ 推送到 `main` 或 `develop` 分支
|
||||
- ✅ 打 `v*` 标签时自动创建 Release
|
||||
- ✅ 手动触发(Actions 页面点击 "Run workflow")
|
||||
|
||||
**构建产物:**
|
||||
- `libcore.aar` - sing-box 核心库
|
||||
- `BearVPN-arm64-v8a-*.apk` - 64位 ARM 版本(推荐)
|
||||
- `BearVPN-armeabi-v7a-*.apk` - 32位 ARM 版本
|
||||
- `BearVPN-x86_64-*.apk` - 模拟器版本
|
||||
|
||||
---
|
||||
|
||||
## 🚀 使用方法
|
||||
|
||||
### 方法一:推送代码自动构建
|
||||
|
||||
```bash
|
||||
git add .
|
||||
git commit -m "feat: 新功能"
|
||||
git push origin main
|
||||
```
|
||||
|
||||
### 方法二:手动触发
|
||||
|
||||
1. 打开仓库 **Actions** 页面
|
||||
2. 点击 **Build Android APK**
|
||||
3. 点击 **Run workflow**
|
||||
|
||||
### 方法三:创建 Release
|
||||
|
||||
```bash
|
||||
git tag v1.0.0
|
||||
git push origin v1.0.0
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📦 下载构建产物
|
||||
|
||||
- **Actions 页面:** 点击运行记录 → Artifacts 区域下载
|
||||
- **Releases 页面:** 选择版本 → Assets 下载
|
||||
|
||||
---
|
||||
|
||||
## 🔧 配置 Release 签名(可选)
|
||||
|
||||
1. 生成密钥:
|
||||
```bash
|
||||
keytool -genkey -v -keystore release.keystore -alias bearvpn -keyalg RSA -keysize 2048 -validity 10000
|
||||
```
|
||||
|
||||
2. 转换为 Base64:
|
||||
```bash
|
||||
base64 release.keystore > keystore.base64.txt
|
||||
```
|
||||
|
||||
3. 在 GitHub 仓库 **Settings → Secrets** 添加:
|
||||
- `KEYSTORE_BASE64`
|
||||
- `KEYSTORE_PASSWORD`
|
||||
- `KEY_ALIAS`
|
||||
- `KEY_PASSWORD`
|
||||
|
||||
---
|
||||
|
||||
## ⏱️ 构建时间
|
||||
|
||||
- libcore.aar: 10-15 分钟
|
||||
- Flutter APK: 15-20 分钟
|
||||
- **总计: 约 30 分钟**
|
||||
|
||||
---
|
||||
|
||||
## 🐛 常见问题
|
||||
|
||||
**Q: 构建失败 "libcore.aar not found"**
|
||||
A: 检查 libcore 子模块是否正确初始化
|
||||
|
||||
**Q: Release 未创建**
|
||||
A: 标签必须以 `v` 开头,如 `v1.0.0`
|
||||
|
||||
---
|
||||
|
||||
生成时间: 2025-10-27
|
||||
319
.github/workflows/build-android-apk.yml
vendored
Normal file
319
.github/workflows/build-android-apk.yml
vendored
Normal file
@ -0,0 +1,319 @@
|
||||
name: Build Android APK
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- develop
|
||||
tags:
|
||||
- 'v*'
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
workflow_dispatch: # 允许手动触发
|
||||
inputs:
|
||||
build_type:
|
||||
description: '构建类型'
|
||||
required: true
|
||||
default: 'release'
|
||||
type: choice
|
||||
options:
|
||||
- debug
|
||||
- release
|
||||
api_domain:
|
||||
description: 'API 域名'
|
||||
required: true
|
||||
default: 'api.maodag.top'
|
||||
type: string
|
||||
oss_url_1:
|
||||
description: 'OSS 配置地址 1'
|
||||
required: true
|
||||
default: 'https://ppp2.oss-cn-hongkong.aliyuncs.com/bear1.txt'
|
||||
type: string
|
||||
oss_url_2:
|
||||
description: 'OSS 配置地址 2'
|
||||
required: true
|
||||
default: 'https://xgp3.oss-ap-northeast-1.aliyuncs.com/bear1.txt'
|
||||
type: string
|
||||
oss_url_3:
|
||||
description: 'OSS 配置地址 3'
|
||||
required: true
|
||||
default: 'https://xpp4.oss-ap-northeast-2.aliyuncs.com/bear1.txt'
|
||||
type: string
|
||||
oss_url_4:
|
||||
description: 'OSS 配置地址 4'
|
||||
required: true
|
||||
default: 'https://xpp5.oss-ap-southeast-1.aliyuncs.com/bear1.txt'
|
||||
type: string
|
||||
|
||||
jobs:
|
||||
build-libcore:
|
||||
name: 编译 libcore.aar
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: 📥 Checkout 代码
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: recursive
|
||||
fetch-depth: 0
|
||||
|
||||
- name: 🔧 设置 Go 环境
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: '1.23'
|
||||
cache: true
|
||||
cache-dependency-path: libcore/go.sum
|
||||
|
||||
- name: 🔧 设置 Node.js 环境
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
|
||||
- name: 🔧 设置 Java 环境
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: 'zulu'
|
||||
java-version: '17'
|
||||
|
||||
- name: 🔧 安装 gomobile
|
||||
run: |
|
||||
go install golang.org/x/mobile/cmd/gomobile@latest
|
||||
gomobile init
|
||||
|
||||
- name: 📦 编译 libcore.aar
|
||||
working-directory: libcore
|
||||
run: |
|
||||
echo "🚀 开始编译 libcore..."
|
||||
make android
|
||||
|
||||
echo "✅ 编译完成,检查产物..."
|
||||
ls -lh bin/
|
||||
|
||||
if [ -f "bin/libcore.aar" ]; then
|
||||
echo "✅ libcore.aar 生成成功"
|
||||
cp bin/libcore.aar ../android/app/libs/
|
||||
else
|
||||
echo "❌ libcore.aar 未找到"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: 📤 上传 libcore.aar
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: libcore-aar
|
||||
path: android/app/libs/libcore.aar
|
||||
retention-days: 7
|
||||
|
||||
build-apk:
|
||||
name: 编译 Android APK
|
||||
needs: build-libcore
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
strategy:
|
||||
matrix:
|
||||
build_type: [release] # 默认 release 构建
|
||||
|
||||
steps:
|
||||
- name: 📥 Checkout 代码
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: recursive
|
||||
fetch-depth: 0
|
||||
|
||||
- name: 🔧 设置 Java 环境
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: 'zulu'
|
||||
java-version: '17'
|
||||
|
||||
- name: 🔧 设置 Flutter 环境
|
||||
uses: subosito/flutter-action@v2
|
||||
with:
|
||||
flutter-version: '3.24.5'
|
||||
channel: 'stable'
|
||||
cache: true
|
||||
|
||||
- name: 📥 下载 libcore.aar
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: libcore-aar
|
||||
path: android/app/libs/
|
||||
|
||||
- name: ⚙️ 配置 API 域名和 OSS 地址
|
||||
run: |
|
||||
CONFIG_FILE="lib/app/common/app_config.dart"
|
||||
|
||||
# 获取参数(手动触发时使用输入值,自动触发时使用默认值)
|
||||
API_DOMAIN="${{ inputs.api_domain || 'api.maodag.top' }}"
|
||||
OSS_URL_1="${{ inputs.oss_url_1 || 'https://ppp2.oss-cn-hongkong.aliyuncs.com/bear1.txt' }}"
|
||||
OSS_URL_2="${{ inputs.oss_url_2 || 'https://xgp3.oss-ap-northeast-1.aliyuncs.com/bear1.txt' }}"
|
||||
OSS_URL_3="${{ inputs.oss_url_3 || 'https://xpp4.oss-ap-northeast-2.aliyuncs.com/bear1.txt' }}"
|
||||
OSS_URL_4="${{ inputs.oss_url_4 || 'https://xpp5.oss-ap-southeast-1.aliyuncs.com/bear1.txt' }}"
|
||||
|
||||
echo "🔧 配置构建参数:"
|
||||
echo " API 域名: $API_DOMAIN"
|
||||
echo " OSS 地址 1: $OSS_URL_1"
|
||||
echo " OSS 地址 2: $OSS_URL_2"
|
||||
echo " OSS 地址 3: $OSS_URL_3"
|
||||
echo " OSS 地址 4: $OSS_URL_4"
|
||||
|
||||
# 替换 API 域名
|
||||
sed -i "s|api\.maodag\.top|$API_DOMAIN|g" "$CONFIG_FILE"
|
||||
|
||||
# 替换 OSS 地址
|
||||
sed -i "s|https://ppp2\.oss-cn-hongkong\.aliyuncs\.com/bear1\.txt|$OSS_URL_1|g" "$CONFIG_FILE"
|
||||
sed -i "s|https://xgp3\.oss-ap-northeast-1\.aliyuncs\.com/bear1\.txt|$OSS_URL_2|g" "$CONFIG_FILE"
|
||||
sed -i "s|https://xpp4\.oss-ap-northeast-2\.aliyuncs\.com/bear1\.txt|$OSS_URL_3|g" "$CONFIG_FILE"
|
||||
sed -i "s|https://xpp5\.oss-ap-southeast-1\.aliyuncs\.com/bear1\.txt|$OSS_URL_4|g" "$CONFIG_FILE"
|
||||
|
||||
echo "✅ 配置替换完成"
|
||||
echo ""
|
||||
echo "📄 查看修改后的配置:"
|
||||
grep -A 15 "kr_baseDomains" "$CONFIG_FILE" || true
|
||||
|
||||
- name: 📦 安装 Flutter 依赖
|
||||
run: |
|
||||
flutter pub get
|
||||
flutter pub run build_runner build --delete-conflicting-outputs
|
||||
|
||||
- name: 🔨 构建 APK (Release)
|
||||
run: |
|
||||
flutter build apk --release --split-per-abi
|
||||
|
||||
- name: 📋 生成构建信息
|
||||
id: build_info
|
||||
run: |
|
||||
BUILD_DATE=$(date '+%Y-%m-%d %H:%M:%S')
|
||||
COMMIT_SHA=${GITHUB_SHA::7}
|
||||
|
||||
echo "build_date=$BUILD_DATE" >> $GITHUB_OUTPUT
|
||||
echo "commit_sha=$COMMIT_SHA" >> $GITHUB_OUTPUT
|
||||
|
||||
echo "📊 构建信息:"
|
||||
echo " - 日期: $BUILD_DATE"
|
||||
echo " - 提交: $COMMIT_SHA"
|
||||
echo " - 分支: ${GITHUB_REF#refs/heads/}"
|
||||
|
||||
- name: 📦 重命名 APK 文件
|
||||
run: |
|
||||
COMMIT_SHA=${{ steps.build_info.outputs.commit_sha }}
|
||||
DATE=$(date '+%Y%m%d')
|
||||
|
||||
cd build/app/outputs/flutter-apk/
|
||||
|
||||
for file in app-*-release.apk; do
|
||||
if [ -f "$file" ]; then
|
||||
# 提取架构名称 (arm64-v8a, armeabi-v7a, x86_64)
|
||||
ARCH=$(echo "$file" | sed "s/app-\(.*\)-release.apk/\1/")
|
||||
NEW_NAME="BearVPN-${ARCH}-release-${DATE}-${COMMIT_SHA}.apk"
|
||||
|
||||
mv "$file" "$NEW_NAME"
|
||||
|
||||
# 计算文件大小和 MD5
|
||||
SIZE=$(ls -lh "$NEW_NAME" | awk '{print $5}')
|
||||
MD5=$(md5sum "$NEW_NAME" | awk '{print $1}')
|
||||
|
||||
echo "✅ $NEW_NAME"
|
||||
echo " 大小: $SIZE"
|
||||
echo " MD5: $MD5"
|
||||
fi
|
||||
done
|
||||
|
||||
ls -lh
|
||||
|
||||
- name: 📤 上传 APK (arm64-v8a)
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: apk-arm64-v8a-release
|
||||
path: build/app/outputs/flutter-apk/*arm64-v8a*.apk
|
||||
retention-days: 30
|
||||
|
||||
- name: 📤 上传 APK (armeabi-v7a)
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: apk-armeabi-v7a-release
|
||||
path: build/app/outputs/flutter-apk/*armeabi-v7a*.apk
|
||||
retention-days: 30
|
||||
|
||||
- name: 📤 上传 APK (x86_64)
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: apk-x86_64-release
|
||||
path: build/app/outputs/flutter-apk/*x86_64*.apk
|
||||
retention-days: 30
|
||||
|
||||
create-release:
|
||||
name: 创建 GitHub Release
|
||||
needs: build-apk
|
||||
runs-on: ubuntu-latest
|
||||
if: startsWith(github.ref, 'refs/tags/v')
|
||||
|
||||
steps:
|
||||
- name: 📥 下载所有 APK
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
path: artifacts
|
||||
pattern: apk-*
|
||||
|
||||
- name: 📋 生成 Release 说明
|
||||
id: release_notes
|
||||
run: |
|
||||
cat > release_notes.md << 'EOF'
|
||||
## 🎉 BearVPN Android 版本发布
|
||||
|
||||
### 📦 安装包说明
|
||||
|
||||
| 架构 | 适用设备 | 文件大小 |
|
||||
|------|----------|----------|
|
||||
| arm64-v8a | 64位 ARM 设备(推荐,现代手机) | ~40MB |
|
||||
| armeabi-v7a | 32位 ARM 设备(老旧手机) | ~35MB |
|
||||
| x86_64 | x86_64 模拟器 | ~45MB |
|
||||
|
||||
### ✨ 主要特性
|
||||
|
||||
- ✅ 支持 Shadowsocks/VLESS/Trojan/Hysteria2 等协议
|
||||
- ✅ 内置 sing-box 核心
|
||||
- ✅ 支持自定义路由规则
|
||||
- ✅ 支持 URL Test 节点延迟测试
|
||||
|
||||
### 📥 下载建议
|
||||
|
||||
**不确定选哪个?** 下载 `arm64-v8a` 版本即可,适用于绝大多数现代 Android 手机。
|
||||
|
||||
### 🔒 文件校验
|
||||
|
||||
下载后请验证 MD5 以确保文件完整性(见下方 Assets 描述)。
|
||||
|
||||
---
|
||||
|
||||
**构建信息:**
|
||||
- 提交: ${GITHUB_SHA::7}
|
||||
- 构建时间: $(date '+%Y-%m-%d %H:%M:%S UTC')
|
||||
- Flutter: 3.24.5
|
||||
- sing-box: latest
|
||||
EOF
|
||||
|
||||
echo "release_notes<<EOF" >> $GITHUB_OUTPUT
|
||||
cat release_notes.md >> $GITHUB_OUTPUT
|
||||
echo "EOF" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: 🚀 创建 GitHub Release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
files: |
|
||||
artifacts/apk-arm64-v8a-*/*.apk
|
||||
artifacts/apk-armeabi-v7a-*/*.apk
|
||||
artifacts/apk-x86_64-*/*.apk
|
||||
body: ${{ steps.release_notes.outputs.release_notes }}
|
||||
draft: false
|
||||
prerelease: false
|
||||
generate_release_notes: true
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: 📢 构建成功通知
|
||||
run: |
|
||||
echo "✅ 构建完成!"
|
||||
echo "📦 Release 已创建: ${{ github.ref }}"
|
||||
echo "🔗 查看: https://github.com/${{ github.repository }}/releases"
|
||||
142
.github/workflows/build-clash-core.yml
vendored
Normal file
142
.github/workflows/build-clash-core.yml
vendored
Normal file
@ -0,0 +1,142 @@
|
||||
name: Build Clash Core
|
||||
|
||||
on:
|
||||
push:
|
||||
paths:
|
||||
- 'core/**'
|
||||
- '.github/workflows/build-clash-core.yml'
|
||||
pull_request:
|
||||
paths:
|
||||
- 'core/**'
|
||||
workflow_dispatch: # 允许手动触发
|
||||
|
||||
jobs:
|
||||
build-android:
|
||||
name: Build Android (${{ matrix.arch }})
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- arch: arm64
|
||||
abi: arm64-v8a
|
||||
cc: aarch64-linux-android29-clang
|
||||
- arch: armv7
|
||||
abi: armeabi-v7a
|
||||
cc: armv7a-linux-androideabi29-clang
|
||||
- arch: x86_64
|
||||
abi: x86_64
|
||||
cc: x86_64-linux-android29-clang
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: recursive
|
||||
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: '1.20'
|
||||
cache: true
|
||||
cache-dependency-path: core/go.sum
|
||||
|
||||
- name: Setup Android NDK
|
||||
uses: nttld/setup-ndk@v1
|
||||
with:
|
||||
ndk-version: r25c
|
||||
add-to-path: true
|
||||
|
||||
- name: Build Core
|
||||
working-directory: core
|
||||
run: make android-${{ matrix.arch }}
|
||||
env:
|
||||
ANDROID_NDK_HOME: ${{ steps.setup-ndk.outputs.ndk-path }}
|
||||
|
||||
- name: Verify Build
|
||||
run: |
|
||||
echo "📦 检查编译产物..."
|
||||
ls -lh android/app/src/main/jniLibs/${{ matrix.abi }}/libclash.so
|
||||
file android/app/src/main/jniLibs/${{ matrix.abi }}/libclash.so
|
||||
|
||||
echo "🔍 验证导出函数..."
|
||||
nm -D android/app/src/main/jniLibs/${{ matrix.abi }}/libclash.so | grep -E "(quickStart|getAndroidVpnOptions|startTUN)"
|
||||
|
||||
- name: Calculate MD5
|
||||
id: md5
|
||||
run: |
|
||||
MD5=$(md5sum android/app/src/main/jniLibs/${{ matrix.abi }}/libclash.so | awk '{print $1}')
|
||||
echo "md5=$MD5" >> $GITHUB_OUTPUT
|
||||
echo "📋 MD5: $MD5"
|
||||
|
||||
- name: Upload Artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: libclash-${{ matrix.abi }}
|
||||
path: android/app/src/main/jniLibs/${{ matrix.abi }}/libclash.so
|
||||
retention-days: 30
|
||||
if-no-files-found: error
|
||||
|
||||
- name: Comment Build Info
|
||||
if: github.event_name == 'pull_request'
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
const fs = require('fs');
|
||||
const stats = fs.statSync('android/app/src/main/jniLibs/${{ matrix.abi }}/libclash.so');
|
||||
const sizeMB = (stats.size / 1024 / 1024).toFixed(2);
|
||||
|
||||
github.rest.issues.createComment({
|
||||
issue_number: context.issue.number,
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
body: `### 🔨 Clash Core 构建完成 (${{ matrix.abi }})
|
||||
|
||||
- **架构:** ${{ matrix.abi }}
|
||||
- **大小:** ${sizeMB} MB
|
||||
- **MD5:** ${{ steps.md5.outputs.md5 }}
|
||||
- **提交:** ${context.sha.substring(0, 7)}
|
||||
|
||||
[下载构建产物](https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId})`
|
||||
});
|
||||
|
||||
create-release:
|
||||
name: Create Release
|
||||
needs: build-android
|
||||
runs-on: ubuntu-latest
|
||||
if: startsWith(github.ref, 'refs/tags/v')
|
||||
|
||||
steps:
|
||||
- name: Download All Artifacts
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
path: artifacts
|
||||
|
||||
- name: Create Release Archive
|
||||
run: |
|
||||
cd artifacts
|
||||
tar -czf clash-core-android-all.tar.gz libclash-*/*.so
|
||||
ls -lh clash-core-android-all.tar.gz
|
||||
|
||||
- name: Create GitHub Release
|
||||
uses: softprops/action-gh-release@v1
|
||||
with:
|
||||
files: artifacts/clash-core-android-all.tar.gz
|
||||
body: |
|
||||
## Clash Meta 核心 Android 构建
|
||||
|
||||
此版本包含所有 Android 架构的预编译二进制文件:
|
||||
- arm64-v8a (ARM64)
|
||||
- armeabi-v7a (ARMv7)
|
||||
- x86_64 (模拟器)
|
||||
|
||||
**使用方法:**
|
||||
```bash
|
||||
tar -xzf clash-core-android-all.tar.gz
|
||||
cp libclash-*/libclash.so android/app/src/main/jniLibs/
|
||||
```
|
||||
draft: false
|
||||
prerelease: false
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
666
.github/workflows/build-multiplatform.yml
vendored
Normal file
666
.github/workflows/build-multiplatform.yml
vendored
Normal file
@ -0,0 +1,666 @@
|
||||
name: Build Multi-Platform
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- develop
|
||||
tags:
|
||||
- 'v*'
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
build_type:
|
||||
description: '构建类型'
|
||||
required: true
|
||||
default: 'release'
|
||||
type: choice
|
||||
options:
|
||||
- debug
|
||||
- release
|
||||
api_domain:
|
||||
description: 'API 域名'
|
||||
required: true
|
||||
default: 'api.maodag.top'
|
||||
type: string
|
||||
oss_url_1:
|
||||
description: 'OSS 配置地址 1'
|
||||
required: true
|
||||
default: 'https://ppp2.oss-cn-hongkong.aliyuncs.com/bear1.txt'
|
||||
type: string
|
||||
oss_url_2:
|
||||
description: 'OSS 配置地址 2'
|
||||
required: true
|
||||
default: 'https://xgp3.oss-ap-northeast-1.aliyuncs.com/bear1.txt'
|
||||
type: string
|
||||
oss_url_3:
|
||||
description: 'OSS 配置地址 3'
|
||||
required: true
|
||||
default: 'https://xpp4.oss-ap-northeast-2.aliyuncs.com/bear1.txt'
|
||||
type: string
|
||||
oss_url_4:
|
||||
description: 'OSS 配置地址 4'
|
||||
required: true
|
||||
default: 'https://xpp5.oss-ap-southeast-1.aliyuncs.com/bear1.txt'
|
||||
type: string
|
||||
platforms:
|
||||
description: '构建平台 (多选: android,windows,macos,linux)'
|
||||
required: true
|
||||
default: 'android,windows,macos,linux'
|
||||
type: string
|
||||
|
||||
jobs:
|
||||
# ==================== 编译 libcore (Android) ====================
|
||||
build-libcore-android:
|
||||
name: 编译 libcore (Android)
|
||||
runs-on: ubuntu-latest
|
||||
if: contains(inputs.platforms || 'android', 'android')
|
||||
|
||||
steps:
|
||||
- name: 📥 Checkout 代码
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: recursive
|
||||
fetch-depth: 0
|
||||
|
||||
- name: 🔧 设置 Go 环境
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: '1.23'
|
||||
cache: true
|
||||
cache-dependency-path: libcore/go.sum
|
||||
|
||||
- name: 🔧 设置 Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
|
||||
- name: 🔧 设置 Java
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: 'zulu'
|
||||
java-version: '17'
|
||||
|
||||
- name: 🔧 安装 gomobile
|
||||
run: |
|
||||
go install golang.org/x/mobile/cmd/gomobile@latest
|
||||
gomobile init
|
||||
|
||||
- name: 📦 编译 libcore.aar
|
||||
working-directory: libcore
|
||||
run: |
|
||||
echo "🚀 开始编译 Android libcore..."
|
||||
make android
|
||||
|
||||
if [ -f "bin/libcore.aar" ]; then
|
||||
echo "✅ libcore.aar 生成成功"
|
||||
ls -lh bin/libcore.aar
|
||||
else
|
||||
echo "❌ libcore.aar 未找到"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: 📤 上传 libcore.aar
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: libcore-android
|
||||
path: libcore/bin/libcore.aar
|
||||
retention-days: 7
|
||||
|
||||
# ==================== 编译 libcore (Windows) ====================
|
||||
build-libcore-windows:
|
||||
name: 编译 libcore (Windows)
|
||||
runs-on: ubuntu-latest
|
||||
if: contains(inputs.platforms || 'windows', 'windows')
|
||||
|
||||
steps:
|
||||
- name: 📥 Checkout 代码
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: recursive
|
||||
fetch-depth: 0
|
||||
|
||||
- name: 🔧 设置 Go 环境
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: '1.23'
|
||||
cache: true
|
||||
cache-dependency-path: libcore/go.sum
|
||||
|
||||
- name: 🔧 设置 Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
|
||||
- name: 🔧 安装 MinGW (交叉编译工具)
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y mingw-w64
|
||||
|
||||
- name: 📦 编译 libcore.dll
|
||||
working-directory: libcore
|
||||
run: |
|
||||
echo "🚀 开始编译 Windows libcore..."
|
||||
make windows-amd64
|
||||
|
||||
if [ -f "bin/libcore.dll" ] && [ -f "bin/HiddifyCli.exe" ]; then
|
||||
echo "✅ Windows libcore 编译成功"
|
||||
ls -lh bin/libcore.dll bin/HiddifyCli.exe
|
||||
else
|
||||
echo "❌ Windows libcore 编译失败"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: 📤 上传 Windows libcore
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: libcore-windows
|
||||
path: |
|
||||
libcore/bin/libcore.dll
|
||||
libcore/bin/HiddifyCli.exe
|
||||
libcore/bin/webui/**
|
||||
retention-days: 7
|
||||
|
||||
# ==================== 编译 libcore (macOS) ====================
|
||||
build-libcore-macos:
|
||||
name: 编译 libcore (macOS)
|
||||
runs-on: macos-latest
|
||||
if: contains(inputs.platforms || 'macos', 'macos')
|
||||
|
||||
steps:
|
||||
- name: 📥 Checkout 代码
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: recursive
|
||||
fetch-depth: 0
|
||||
|
||||
- name: 🔧 设置 Go 环境
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: '1.23'
|
||||
cache: true
|
||||
cache-dependency-path: libcore/go.sum
|
||||
|
||||
- name: 🔧 设置 Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
|
||||
- name: 📦 编译 libcore.dylib
|
||||
working-directory: libcore
|
||||
run: |
|
||||
echo "🚀 开始编译 macOS libcore..."
|
||||
make macos-universal
|
||||
|
||||
if [ -f "bin/libcore.dylib" ] && [ -f "bin/HiddifyCli" ]; then
|
||||
echo "✅ macOS libcore 编译成功"
|
||||
ls -lh bin/libcore.dylib bin/HiddifyCli
|
||||
else
|
||||
echo "❌ macOS libcore 编译失败"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: 📤 上传 macOS libcore
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: libcore-macos
|
||||
path: |
|
||||
libcore/bin/libcore.dylib
|
||||
libcore/bin/HiddifyCli
|
||||
retention-days: 7
|
||||
|
||||
# ==================== 编译 libcore (Linux) ====================
|
||||
build-libcore-linux:
|
||||
name: 编译 libcore (Linux)
|
||||
runs-on: ubuntu-latest
|
||||
if: contains(inputs.platforms || 'linux', 'linux')
|
||||
|
||||
steps:
|
||||
- name: 📥 Checkout 代码
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: recursive
|
||||
fetch-depth: 0
|
||||
|
||||
- name: 🔧 设置 Go 环境
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: '1.23'
|
||||
cache: true
|
||||
cache-dependency-path: libcore/go.sum
|
||||
|
||||
- name: 🔧 设置 Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
|
||||
- name: 📦 编译 libcore.so
|
||||
working-directory: libcore
|
||||
run: |
|
||||
echo "🚀 开始编译 Linux libcore..."
|
||||
make linux-amd64
|
||||
|
||||
if [ -f "bin/lib/libcore.so" ] && [ -f "bin/HiddifyCli" ]; then
|
||||
echo "✅ Linux libcore 编译成功"
|
||||
ls -lh bin/lib/libcore.so bin/HiddifyCli
|
||||
else
|
||||
echo "❌ Linux libcore 编译失败"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: 📤 上传 Linux libcore
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: libcore-linux
|
||||
path: |
|
||||
libcore/bin/lib/libcore.so
|
||||
libcore/bin/HiddifyCli
|
||||
libcore/bin/webui/**
|
||||
retention-days: 7
|
||||
|
||||
# ==================== Android 构建 ====================
|
||||
build-android:
|
||||
name: 构建 Android APK
|
||||
needs: build-libcore-android
|
||||
runs-on: ubuntu-latest
|
||||
if: contains(inputs.platforms || 'android', 'android')
|
||||
|
||||
steps:
|
||||
- name: 📥 Checkout 代码
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: recursive
|
||||
fetch-depth: 0
|
||||
|
||||
- name: 🔧 设置 Java
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: 'zulu'
|
||||
java-version: '17'
|
||||
|
||||
- name: 🔧 设置 Flutter
|
||||
uses: subosito/flutter-action@v2
|
||||
with:
|
||||
flutter-version: '3.24.5'
|
||||
channel: 'stable'
|
||||
cache: true
|
||||
|
||||
- name: 📥 下载 libcore.aar
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: libcore-android
|
||||
path: android/app/libs/
|
||||
|
||||
- name: ⚙️ 配置 API 和 OSS
|
||||
run: |
|
||||
CONFIG_FILE="lib/app/common/app_config.dart"
|
||||
API_DOMAIN="${{ inputs.api_domain || 'api.maodag.top' }}"
|
||||
OSS_URL_1="${{ inputs.oss_url_1 || 'https://ppp2.oss-cn-hongkong.aliyuncs.com/bear1.txt' }}"
|
||||
OSS_URL_2="${{ inputs.oss_url_2 || 'https://xgp3.oss-ap-northeast-1.aliyuncs.com/bear1.txt' }}"
|
||||
OSS_URL_3="${{ inputs.oss_url_3 || 'https://xpp4.oss-ap-northeast-2.aliyuncs.com/bear1.txt' }}"
|
||||
OSS_URL_4="${{ inputs.oss_url_4 || 'https://xpp5.oss-ap-southeast-1.aliyuncs.com/bear1.txt' }}"
|
||||
|
||||
echo "🔧 配置参数:"
|
||||
echo " API: $API_DOMAIN"
|
||||
echo " OSS: $OSS_URL_1"
|
||||
|
||||
sed -i "s|api\.maodag\.top|$API_DOMAIN|g" "$CONFIG_FILE"
|
||||
sed -i "s|https://ppp2\.oss-cn-hongkong\.aliyuncs\.com/bear1\.txt|$OSS_URL_1|g" "$CONFIG_FILE"
|
||||
sed -i "s|https://xgp3\.oss-ap-northeast-1\.aliyuncs\.com/bear1\.txt|$OSS_URL_2|g" "$CONFIG_FILE"
|
||||
sed -i "s|https://xpp4\.oss-ap-northeast-2\.aliyuncs\.com/bear1\.txt|$OSS_URL_3|g" "$CONFIG_FILE"
|
||||
sed -i "s|https://xpp5\.oss-ap-southeast-1\.aliyuncs\.com/bear1\.txt|$OSS_URL_4|g" "$CONFIG_FILE"
|
||||
|
||||
echo "✅ 配置完成"
|
||||
|
||||
- name: 📦 安装 Flutter 依赖
|
||||
run: |
|
||||
flutter pub get
|
||||
flutter pub run build_runner build --delete-conflicting-outputs
|
||||
|
||||
- name: 🔨 构建 APK (Release)
|
||||
run: |
|
||||
flutter build apk --release --split-per-abi
|
||||
|
||||
- name: 📦 重命名 APK
|
||||
run: |
|
||||
COMMIT_SHA=${GITHUB_SHA::7}
|
||||
DATE=$(date '+%Y%m%d')
|
||||
cd build/app/outputs/flutter-apk/
|
||||
|
||||
for file in app-*-release.apk; do
|
||||
if [ -f "$file" ]; then
|
||||
ARCH=$(echo "$file" | sed "s/app-\(.*\)-release.apk/\1/")
|
||||
NEW_NAME="BearVPN-android-${ARCH}-release-${DATE}-${COMMIT_SHA}.apk"
|
||||
mv "$file" "$NEW_NAME"
|
||||
echo "✅ $NEW_NAME"
|
||||
fi
|
||||
done
|
||||
|
||||
- name: 📤 上传 APK
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: android-apk
|
||||
path: build/app/outputs/flutter-apk/*.apk
|
||||
retention-days: 30
|
||||
|
||||
# ==================== Windows 构建 ====================
|
||||
build-windows:
|
||||
name: 构建 Windows
|
||||
needs: build-libcore-windows
|
||||
runs-on: windows-latest
|
||||
if: contains(inputs.platforms || 'windows', 'windows')
|
||||
|
||||
steps:
|
||||
- name: 📥 Checkout 代码
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: recursive
|
||||
fetch-depth: 0
|
||||
|
||||
- name: 🔧 设置 Flutter
|
||||
uses: subosito/flutter-action@v2
|
||||
with:
|
||||
flutter-version: '3.24.5'
|
||||
channel: 'stable'
|
||||
cache: true
|
||||
|
||||
- name: 📥 下载 Windows libcore
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: libcore-windows
|
||||
path: libcore/bin/
|
||||
|
||||
- name: ⚙️ 配置 API 和 OSS
|
||||
shell: bash
|
||||
run: |
|
||||
CONFIG_FILE="lib/app/common/app_config.dart"
|
||||
API_DOMAIN="${{ inputs.api_domain || 'api.maodag.top' }}"
|
||||
OSS_URL_1="${{ inputs.oss_url_1 || 'https://ppp2.oss-cn-hongkong.aliyuncs.com/bear1.txt' }}"
|
||||
OSS_URL_2="${{ inputs.oss_url_2 || 'https://xgp3.oss-ap-northeast-1.aliyuncs.com/bear1.txt' }}"
|
||||
OSS_URL_3="${{ inputs.oss_url_3 || 'https://xpp4.oss-ap-northeast-2.aliyuncs.com/bear1.txt' }}"
|
||||
OSS_URL_4="${{ inputs.oss_url_4 || 'https://xpp5.oss-ap-southeast-1.aliyuncs.com/bear1.txt' }}"
|
||||
|
||||
sed -i "s|api\.maodag\.top|$API_DOMAIN|g" "$CONFIG_FILE"
|
||||
sed -i "s|https://ppp2\.oss-cn-hongkong\.aliyuncs\.com/bear1\.txt|$OSS_URL_1|g" "$CONFIG_FILE"
|
||||
sed -i "s|https://xgp3\.oss-ap-northeast-1\.aliyuncs\.com/bear1\.txt|$OSS_URL_2|g" "$CONFIG_FILE"
|
||||
sed -i "s|https://xpp4\.oss-ap-northeast-2\.aliyuncs\.com/bear1\.txt|$OSS_URL_3|g" "$CONFIG_FILE"
|
||||
sed -i "s|https://xpp5\.oss-ap-southeast-1\.aliyuncs\.com/bear1\.txt|$OSS_URL_4|g" "$CONFIG_FILE"
|
||||
|
||||
- name: 📦 安装 Flutter 依赖
|
||||
run: |
|
||||
flutter pub get
|
||||
|
||||
- name: 🔧 生成代码文件 (build_runner)
|
||||
run: |
|
||||
echo "🔧 开始运行 build_runner..."
|
||||
flutter pub run build_runner build --delete-conflicting-outputs
|
||||
|
||||
echo ""
|
||||
echo "✅ build_runner 完成,检查生成的文件..."
|
||||
|
||||
if (Test-Path "lib\singbox\model\singbox_status.freezed.dart") {
|
||||
echo "✅ singbox_status.freezed.dart 已生成"
|
||||
} else {
|
||||
echo "❌ singbox_status.freezed.dart 未生成"
|
||||
exit 1
|
||||
}
|
||||
|
||||
if (Test-Path "lib\singbox\service\singbox_service_provider.g.dart") {
|
||||
echo "✅ singbox_service_provider.g.dart 已生成"
|
||||
} else {
|
||||
echo "❌ singbox_service_provider.g.dart 未生成"
|
||||
exit 1
|
||||
}
|
||||
shell: pwsh
|
||||
|
||||
- name: 🔨 构建 Windows (Release)
|
||||
run: |
|
||||
flutter build windows --release
|
||||
|
||||
- name: 📦 打包 Windows
|
||||
shell: bash
|
||||
run: |
|
||||
COMMIT_SHA=${GITHUB_SHA::7}
|
||||
DATE=$(date '+%Y%m%d')
|
||||
|
||||
cd build/windows/x64/runner/Release
|
||||
7z a -tzip "../../../../../BearVPN-windows-x64-release-${DATE}-${COMMIT_SHA}.zip" ./*
|
||||
|
||||
- name: 📤 上传 Windows
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: windows-x64
|
||||
path: BearVPN-windows-*.zip
|
||||
retention-days: 30
|
||||
|
||||
# ==================== macOS 构建 ====================
|
||||
build-macos:
|
||||
name: 构建 macOS
|
||||
needs: build-libcore-macos
|
||||
runs-on: macos-latest
|
||||
if: contains(inputs.platforms || 'macos', 'macos')
|
||||
|
||||
steps:
|
||||
- name: 📥 Checkout 代码
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: recursive
|
||||
fetch-depth: 0
|
||||
|
||||
- name: 🔧 设置 Flutter
|
||||
uses: subosito/flutter-action@v2
|
||||
with:
|
||||
flutter-version: '3.24.5'
|
||||
channel: 'stable'
|
||||
cache: true
|
||||
|
||||
- name: 📥 下载 macOS libcore
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: libcore-macos
|
||||
path: libcore/bin/
|
||||
|
||||
- name: 🔧 设置 libcore 执行权限
|
||||
run: |
|
||||
chmod +x libcore/bin/HiddifyCli
|
||||
|
||||
- name: ⚙️ 配置 API 和 OSS
|
||||
run: |
|
||||
CONFIG_FILE="lib/app/common/app_config.dart"
|
||||
API_DOMAIN="${{ inputs.api_domain || 'api.maodag.top' }}"
|
||||
OSS_URL_1="${{ inputs.oss_url_1 || 'https://ppp2.oss-cn-hongkong.aliyuncs.com/bear1.txt' }}"
|
||||
OSS_URL_2="${{ inputs.oss_url_2 || 'https://xgp3.oss-ap-northeast-1.aliyuncs.com/bear1.txt' }}"
|
||||
OSS_URL_3="${{ inputs.oss_url_3 || 'https://xpp4.oss-ap-northeast-2.aliyuncs.com/bear1.txt' }}"
|
||||
OSS_URL_4="${{ inputs.oss_url_4 || 'https://xpp5.oss-ap-southeast-1.aliyuncs.com/bear1.txt' }}"
|
||||
|
||||
sed -i '' "s|api\.maodag\.top|$API_DOMAIN|g" "$CONFIG_FILE"
|
||||
sed -i '' "s|https://ppp2\.oss-cn-hongkong\.aliyuncs\.com/bear1\.txt|$OSS_URL_1|g" "$CONFIG_FILE"
|
||||
sed -i '' "s|https://xgp3\.oss-ap-northeast-1\.aliyuncs\.com/bear1\.txt|$OSS_URL_2|g" "$CONFIG_FILE"
|
||||
sed -i '' "s|https://xpp4\.oss-ap-northeast-2\.aliyuncs\.com/bear1\.txt|$OSS_URL_3|g" "$CONFIG_FILE"
|
||||
sed -i '' "s|https://xpp5\.oss-ap-southeast-1\.aliyuncs\.com/bear1\.txt|$OSS_URL_4|g" "$CONFIG_FILE"
|
||||
|
||||
- name: 📦 安装 Flutter 依赖
|
||||
run: |
|
||||
flutter pub get
|
||||
flutter pub run build_runner build --delete-conflicting-outputs
|
||||
|
||||
- name: 🔨 构建 macOS (Release)
|
||||
run: |
|
||||
flutter build macos --release
|
||||
|
||||
- name: 📦 打包 macOS
|
||||
run: |
|
||||
COMMIT_SHA=${GITHUB_SHA::7}
|
||||
DATE=$(date '+%Y%m%d')
|
||||
|
||||
cd build/macos/Build/Products/Release
|
||||
zip -r -y "../../../../../BearVPN-macos-release-${DATE}-${COMMIT_SHA}.zip" BearVPN.app
|
||||
|
||||
- name: 📤 上传 macOS
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: macos-app
|
||||
path: BearVPN-macos-*.zip
|
||||
retention-days: 30
|
||||
|
||||
# ==================== Linux 构建 ====================
|
||||
build-linux:
|
||||
name: 构建 Linux
|
||||
needs: build-libcore-linux
|
||||
runs-on: ubuntu-latest
|
||||
if: contains(inputs.platforms || 'linux', 'linux')
|
||||
|
||||
steps:
|
||||
- name: 📥 Checkout 代码
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: recursive
|
||||
fetch-depth: 0
|
||||
|
||||
- name: 🔧 安装 Linux 依赖
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y \
|
||||
clang \
|
||||
cmake \
|
||||
ninja-build \
|
||||
pkg-config \
|
||||
libgtk-3-dev \
|
||||
liblzma-dev \
|
||||
libstdc++-12-dev \
|
||||
libayatana-appindicator3-dev
|
||||
|
||||
- name: 🔧 设置 Flutter
|
||||
uses: subosito/flutter-action@v2
|
||||
with:
|
||||
flutter-version: '3.24.5'
|
||||
channel: 'stable'
|
||||
cache: true
|
||||
|
||||
- name: 📥 下载 Linux libcore
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: libcore-linux
|
||||
path: libcore/bin/
|
||||
|
||||
- name: 🔧 设置 libcore 执行权限
|
||||
run: |
|
||||
chmod +x libcore/bin/HiddifyCli
|
||||
|
||||
- name: ⚙️ 配置 API 和 OSS
|
||||
run: |
|
||||
CONFIG_FILE="lib/app/common/app_config.dart"
|
||||
API_DOMAIN="${{ inputs.api_domain || 'api.maodag.top' }}"
|
||||
OSS_URL_1="${{ inputs.oss_url_1 || 'https://ppp2.oss-cn-hongkong.aliyuncs.com/bear1.txt' }}"
|
||||
OSS_URL_2="${{ inputs.oss_url_2 || 'https://xgp3.oss-ap-northeast-1.aliyuncs.com/bear1.txt' }}"
|
||||
OSS_URL_3="${{ inputs.oss_url_3 || 'https://xpp4.oss-ap-northeast-2.aliyuncs.com/bear1.txt' }}"
|
||||
OSS_URL_4="${{ inputs.oss_url_4 || 'https://xpp5.oss-ap-southeast-1.aliyuncs.com/bear1.txt' }}"
|
||||
|
||||
sed -i "s|api\.maodag\.top|$API_DOMAIN|g" "$CONFIG_FILE"
|
||||
sed -i "s|https://ppp2\.oss-cn-hongkong\.aliyuncs\.com/bear1\.txt|$OSS_URL_1|g" "$CONFIG_FILE"
|
||||
sed -i "s|https://xgp3\.oss-ap-northeast-1\.aliyuncs\.com/bear1\.txt|$OSS_URL_2|g" "$CONFIG_FILE"
|
||||
sed -i "s|https://xpp4\.oss-ap-northeast-2\.aliyuncs\.com/bear1\.txt|$OSS_URL_3|g" "$CONFIG_FILE"
|
||||
sed -i "s|https://xpp5\.oss-ap-southeast-1\.aliyuncs\.com/bear1\.txt|$OSS_URL_4|g" "$CONFIG_FILE"
|
||||
|
||||
- name: 📦 安装 Flutter 依赖
|
||||
run: |
|
||||
flutter pub get
|
||||
flutter pub run build_runner build --delete-conflicting-outputs
|
||||
|
||||
- name: 🔨 构建 Linux (Release)
|
||||
run: |
|
||||
flutter build linux --release
|
||||
|
||||
- name: 📦 打包 Linux
|
||||
run: |
|
||||
COMMIT_SHA=${GITHUB_SHA::7}
|
||||
DATE=$(date '+%Y%m%d')
|
||||
|
||||
cd build/linux/x64/release/bundle
|
||||
tar -czf "../../../../../BearVPN-linux-x64-release-${DATE}-${COMMIT_SHA}.tar.gz" ./*
|
||||
|
||||
- name: 📤 上传 Linux
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: linux-x64
|
||||
path: BearVPN-linux-*.tar.gz
|
||||
retention-days: 30
|
||||
|
||||
# ==================== 创建 Release ====================
|
||||
create-release:
|
||||
name: 创建 Release
|
||||
needs: [build-android, build-windows, build-macos, build-linux]
|
||||
runs-on: ubuntu-latest
|
||||
if: startsWith(github.ref, 'refs/tags/v')
|
||||
|
||||
steps:
|
||||
- name: 📥 下载所有构建产物
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
path: artifacts
|
||||
|
||||
- name: 📋 生成 Release 说明
|
||||
id: release_notes
|
||||
run: |
|
||||
cat > release_notes.md << 'EOF'
|
||||
## 🎉 BearVPN 多平台版本发布
|
||||
|
||||
### 📦 平台支持
|
||||
|
||||
| 平台 | 架构 | 文件 |
|
||||
|-----|------|-----|
|
||||
| **Android** | arm64-v8a | BearVPN-android-arm64-v8a-*.apk |
|
||||
| **Android** | armeabi-v7a | BearVPN-android-armeabi-v7a-*.apk |
|
||||
| **Android** | x86_64 | BearVPN-android-x86_64-*.apk |
|
||||
| **Windows** | x64 | BearVPN-windows-x64-*.zip |
|
||||
| **macOS** | Universal | BearVPN-macos-*.zip |
|
||||
| **Linux** | x64 | BearVPN-linux-x64-*.tar.gz |
|
||||
|
||||
### ✨ 主要特性
|
||||
|
||||
- ✅ 支持 Shadowsocks/VLESS/Trojan/Hysteria2
|
||||
- ✅ 内置 sing-box 核心 v3.1.7
|
||||
- ✅ 跨平台支持
|
||||
- ✅ 自定义路由规则
|
||||
|
||||
### 📥 安装指南
|
||||
|
||||
**Android:** 下载 APK 直接安装
|
||||
**Windows:** 解压 ZIP 运行 BearVPN.exe
|
||||
**macOS:** 解压 ZIP 拖拽到应用程序
|
||||
**Linux:** 解压 tar.gz 运行可执行文件
|
||||
|
||||
---
|
||||
|
||||
**构建信息:**
|
||||
- 提交: ${GITHUB_SHA::7}
|
||||
- 时间: $(date '+%Y-%m-%d %H:%M:%S UTC')
|
||||
- Flutter: 3.24.5
|
||||
- sing-box: v3.1.7
|
||||
EOF
|
||||
|
||||
echo "release_notes<<EOF" >> $GITHUB_OUTPUT
|
||||
cat release_notes.md >> $GITHUB_OUTPUT
|
||||
echo "EOF" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: 🚀 创建 Release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
files: |
|
||||
artifacts/android-apk/*.apk
|
||||
artifacts/windows-x64/*.zip
|
||||
artifacts/macos-app/*.zip
|
||||
artifacts/linux-x64/*.tar.gz
|
||||
body: ${{ steps.release_notes.outputs.release_notes }}
|
||||
draft: false
|
||||
prerelease: false
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: 📢 构建完成
|
||||
run: |
|
||||
echo "✅ 所有平台构建完成!"
|
||||
echo "📦 Release: ${{ github.ref }}"
|
||||
echo "🔗 https://github.com/${{ github.repository }}/releases"
|
||||
12
.github/workflows/build-windows.yml
vendored
12
.github/workflows/build-windows.yml
vendored
@ -12,12 +12,12 @@ jobs:
|
||||
runs-on: windows-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Flutter
|
||||
uses: subosito/flutter-action@v2
|
||||
with:
|
||||
flutter-version: '3.24.0'
|
||||
flutter-version: '3.24.5'
|
||||
channel: 'stable'
|
||||
|
||||
- name: Enable Windows desktop
|
||||
@ -33,13 +33,13 @@ jobs:
|
||||
run: flutter build windows --release
|
||||
|
||||
- name: Upload Debug build artifacts
|
||||
uses: actions/upload-artifact@v3
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: windows-debug-build
|
||||
path: build/windows/runner/Debug/
|
||||
|
||||
|
||||
- name: Upload Release build artifacts
|
||||
uses: actions/upload-artifact@v3
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: windows-release-build
|
||||
path: build/windows/runner/Release/
|
||||
|
||||
9
.gitignore
vendored
9
.gitignore
vendored
@ -90,3 +90,12 @@ app.*.map.json
|
||||
# Local configuration
|
||||
local.properties
|
||||
key.properties
|
||||
|
||||
# libcore 编译产物(源码需要提交用于 GitHub Actions 编译)
|
||||
libcore/bin/
|
||||
libcore/node_modules/
|
||||
libcore/*.tar.gz
|
||||
libcore/*.aar
|
||||
|
||||
# Android 编译产物
|
||||
android/app/libs/*.aar
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
org.gradle.jvmargs=-Xmx4048m -Dfile.encoding=UTF-8
|
||||
android.useAndroidX=true
|
||||
android.enableJetifier=true
|
||||
org.gradle.java.home=/Users/mac/Library/Java/JavaVirtualMachines/ms-17.0.16/Contents/Home
|
||||
# org.gradle.java.home=/Users/mac/Library/Java/JavaVirtualMachines/ms-17.0.16/Contents/Home
|
||||
|
||||
255
docs/CLASH_ARCHITECTURE.md
Normal file
255
docs/CLASH_ARCHITECTURE.md
Normal file
@ -0,0 +1,255 @@
|
||||
# Clash Meta 核心架构文档
|
||||
|
||||
## 架构概览
|
||||
|
||||
LighthouseApp 使用 Clash Meta (Mihomo) 作为核心代理引擎,替代原有的 sing-box 实现。
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ Flutter Application │
|
||||
├─────────────────────────────────────────────────────────────┤
|
||||
│ Dart Layer │
|
||||
│ ┌──────────────────────────────────────────────────────┐ │
|
||||
│ │ KRClashImp (lib/app/services/clash_imp/) │ │
|
||||
│ │ • kr_clash_imp.dart - 核心封装 │ │
|
||||
│ │ • clash_ffi.dart - FFI 绑定 │ │
|
||||
│ │ • clash_config_generator - YAML 配置生成 │ │
|
||||
│ │ • clash_service_handler - 服务处理器 │ │
|
||||
│ └──────────────────┬───────────────────────────────────┘ │
|
||||
│ │ dart:ffi │
|
||||
├─────────────────────┼───────────────────────────────────────┤
|
||||
│ Android Native │ │
|
||||
│ ┌──────────────────▼───────────────────────────────────┐ │
|
||||
│ │ ClashService (Kotlin) │ │
|
||||
│ │ • VPNService.kt - VPN 服务入口 │ │
|
||||
│ │ • ClashService.kt - Clash 服务管理 │ │
|
||||
│ │ • Service Isolate - 后台 Dart 运行时 │ │
|
||||
│ └──────────────────┬───────────────────────────────────┘ │
|
||||
│ │ JNI │
|
||||
│ ┌──────────────────▼───────────────────────────────────┐ │
|
||||
│ │ libclash.so (Go + C) │ │
|
||||
│ │ • quickStart() - 启动核心 │ │
|
||||
│ │ • getAndroidVpnOptions() - 获取 VPN 配置 │ │
|
||||
│ │ • startTUN() - 启动 TUN 设备 │ │
|
||||
│ │ • getTraffic() - 流量统计 │ │
|
||||
│ └──────────────────┬───────────────────────────────────┘ │
|
||||
│ │ │
|
||||
├─────────────────────┼───────────────────────────────────────┤
|
||||
│ Go Core │ │
|
||||
│ ┌──────────────────▼───────────────────────────────────┐ │
|
||||
│ │ Clash.Meta (Mihomo) │ │
|
||||
│ │ • TUN 设备管理 │ │
|
||||
│ │ • 路由策略 (bypass-LAN) │ │
|
||||
│ │ • 代理协议支持 (SS/Trojan/VMess/...) │ │
|
||||
│ │ • DNS 解析 │ │
|
||||
│ │ • 流量统计 │ │
|
||||
│ └──────────────────────────────────────────────────────┘ │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
## 核心组件
|
||||
|
||||
### 1. Dart FFI 层 (`kr_clash_imp.dart`)
|
||||
|
||||
**职责:**
|
||||
- 提供与 Go 核心的 FFI 通信接口
|
||||
- 管理核心生命周期 (启动/停止)
|
||||
- 配置文件生成和管理
|
||||
- 并发安全的初始化机制
|
||||
|
||||
**关键方法:**
|
||||
- `start()` - 启动 Clash 核心
|
||||
- `stop()` - 停止核心
|
||||
- `getAndroidVpnOptions()` - 获取 VPN 路由配置 (关键!)
|
||||
- `startTun()` - 启动 TUN 设备
|
||||
|
||||
**并发安全设计:**
|
||||
```dart
|
||||
// 使用 Completer 实现初始化锁
|
||||
Completer<void>? _initLock;
|
||||
|
||||
Future<void> _ensureInitialized() async {
|
||||
if (_initialized) return;
|
||||
if (_initLock != null) {
|
||||
await _initLock!.future; // 等待其他初始化完成
|
||||
return;
|
||||
}
|
||||
// 执行初始化...
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Android Service 层 (`ClashService.kt`)
|
||||
|
||||
**职责:**
|
||||
- 管理 VPN 服务生命周期
|
||||
- 创建 Service Isolate (后台 Dart 运行时)
|
||||
- 处理系统 VPN 权限
|
||||
- 注册底层网络回调 (修复模拟器兼容性)
|
||||
|
||||
**Service Isolate 架构:**
|
||||
```kotlin
|
||||
// 创建独立的 FlutterEngine 用于后台服务
|
||||
serviceEngine = FlutterEngine(Application.application)
|
||||
|
||||
// 执行 Dart Service 入口点
|
||||
val entrypoint = DartExecutor.DartEntrypoint(
|
||||
FlutterInjector.instance().flutterLoader().findAppBundlePath(),
|
||||
"_clashService" // 在 lib/main.dart 中定义
|
||||
)
|
||||
serviceEngine?.dartExecutor?.executeDartEntrypoint(entrypoint)
|
||||
```
|
||||
|
||||
### 3. Go 核心层 (`core/`)
|
||||
|
||||
**目录结构:**
|
||||
```
|
||||
core/
|
||||
├── Clash.Meta/ # Git 子模块,Mihomo 核心
|
||||
├── go.mod # Go 依赖管理
|
||||
├── lib_android.go # Android JNI 桥接
|
||||
├── action.go # 核心操作接口
|
||||
└── hub.go # HTTP API 服务器
|
||||
```
|
||||
|
||||
**关键桥接函数:**
|
||||
```go
|
||||
//export quickStart
|
||||
func quickStart(initParams, params, stateParams *C.char, port C.longlong)
|
||||
|
||||
//export getAndroidVpnOptions
|
||||
func getAndroidVpnOptions() *C.char // 返回详细路由配置!
|
||||
|
||||
//export startTUN
|
||||
func startTUN(fd C.int, callback unsafe.Pointer) C.int
|
||||
```
|
||||
|
||||
## 数据流
|
||||
|
||||
### 启动流程
|
||||
|
||||
```
|
||||
1. Flutter UI (用户点击连接)
|
||||
│
|
||||
├──> KRClashImp.start()
|
||||
│ ├─ 生成 Clash 配置 YAML
|
||||
│ ├─ 调用 FFI: quickStart()
|
||||
│ └─ 等待启动回调
|
||||
│
|
||||
├──> libclash.so: quickStart()
|
||||
│ ├─ 初始化 Clash Meta 核心
|
||||
│ ├─ 解析配置文件
|
||||
│ └─ 启动监听器
|
||||
│
|
||||
├──> ClashService.kt
|
||||
│ ├─ 调用 VpnService.prepare()
|
||||
│ ├─ 获取 VPN 权限
|
||||
│ └─ 建立 TUN 接口
|
||||
│
|
||||
├──> KRClashImp.getAndroidVpnOptions() ⭐ 关键!
|
||||
│ └─ 获取 35+ CIDR 路由列表
|
||||
│
|
||||
└──> VPNService.kt: 配置 VPN Builder
|
||||
├─ addAddress("172.19.0.1/30")
|
||||
├─ addRoute("0.0.0.0/1")
|
||||
├─ addRoute("128.0.0.0/1")
|
||||
├─ addRoute("10.0.0.0/8") # bypass-LAN
|
||||
└─ 启动 TUN 设备
|
||||
```
|
||||
|
||||
### 流量统计流程
|
||||
|
||||
```
|
||||
1. UI 定时器 (每秒)
|
||||
│
|
||||
├──> KRClashImp.getTraffic()
|
||||
│ └─ FFI 调用
|
||||
│
|
||||
├──> libclash.so: getTraffic()
|
||||
│ └─ Clash Meta 内部统计
|
||||
│
|
||||
└──> 返回 JSON
|
||||
{
|
||||
"upload": 1234567,
|
||||
"download": 7654321
|
||||
}
|
||||
```
|
||||
|
||||
## 关键设计决策
|
||||
|
||||
### 为什么使用 Clash Meta 替代 sing-box?
|
||||
|
||||
| 问题 | sing-box | Clash Meta |
|
||||
|------|----------|------------|
|
||||
| **Android VPN 路由** | 简单路由 (3-5条) | 详细路由 (35+条 CIDR) |
|
||||
| **bypass-LAN 支持** | ❌ 不支持 | ✅ 完整支持 |
|
||||
| **PermissionMonitor error 22** | ⚠️ 频繁出现 | ✅ 已解决 |
|
||||
| **模拟器兼容性** | ⚠️ 兼容性问题 | ✅ 完美兼容 |
|
||||
|
||||
### 并发安全保证
|
||||
|
||||
**问题:** Go 运行时初始化不是线程安全的,多个 Dart 方法并发调用 `_ensureInitialized()` 可能导致崩溃。
|
||||
|
||||
**解决方案:** 使用 `Completer` 实现初始化锁:
|
||||
```dart
|
||||
// 场景 1: 第一次调用
|
||||
Thread A: _ensureInitialized() → 创建 _initLock → 执行初始化 → complete()
|
||||
|
||||
// 场景 2: 并发调用
|
||||
Thread B: _ensureInitialized() → 发现 _initLock != null → await _initLock.future ✅
|
||||
|
||||
// 场景 3: 初始化失败重试
|
||||
Thread C: _ensureInitialized() → 异常 → _initLock = null → 允许重试 ✅
|
||||
```
|
||||
|
||||
## 配置文件
|
||||
|
||||
### Clash 配置生成 (`clash_config_generator.dart`)
|
||||
|
||||
```yaml
|
||||
# 生成的 clash_config.yaml 示例
|
||||
mixed-port: 51213
|
||||
allow-lan: false
|
||||
|
||||
tun:
|
||||
enable: true
|
||||
stack: system
|
||||
auto-route: true
|
||||
auto-detect-interface: true
|
||||
dns-hijack:
|
||||
- any:53
|
||||
route-address: # ⭐ 关键! 35+ 详细路由
|
||||
- 0.0.0.0/1
|
||||
- 128.0.0.0/1
|
||||
# ... bypass-LAN CIDRs
|
||||
route-exclude-address:
|
||||
- 10.0.0.0/8 # 绕过局域网
|
||||
- 172.16.0.0/12
|
||||
- 192.168.0.0/16
|
||||
|
||||
proxies:
|
||||
- name: "Server-1"
|
||||
type: ss
|
||||
server: example.com
|
||||
port: 8388
|
||||
# ...
|
||||
|
||||
proxy-groups:
|
||||
- name: "PROXY"
|
||||
type: select
|
||||
proxies:
|
||||
- Server-1
|
||||
```
|
||||
|
||||
## 故障排查
|
||||
|
||||
参考 [CLASH_TROUBLESHOOTING.md](./CLASH_TROUBLESHOOTING.md)
|
||||
|
||||
## 构建指南
|
||||
|
||||
参考 [CLASH_BUILD_GUIDE.md](./CLASH_BUILD_GUIDE.md)
|
||||
|
||||
## 相关资源
|
||||
|
||||
- [Clash Meta 官方文档](https://wiki.metacubex.one/)
|
||||
- [Mihomo GitHub](https://github.com/MetaCubeX/mihomo)
|
||||
- [Xboard-Mihomo 参考实现](https://github.com/chen08209/Xboard-Mihomo)
|
||||
345
docs/CLASH_BUILD_GUIDE.md
Normal file
345
docs/CLASH_BUILD_GUIDE.md
Normal file
@ -0,0 +1,345 @@
|
||||
# Clash Meta 核心编译指南
|
||||
|
||||
## 环境准备
|
||||
|
||||
### 1. 安装必要工具
|
||||
|
||||
```bash
|
||||
# macOS
|
||||
brew install go
|
||||
brew install android-ndk # 或从 Android Studio 安装
|
||||
|
||||
# 验证
|
||||
go version # 需要 go 1.20+
|
||||
```
|
||||
|
||||
### 2. 配置环境变量
|
||||
|
||||
```bash
|
||||
# 添加到 ~/.zshrc 或 ~/.bash_profile
|
||||
export ANDROID_HOME="$HOME/Library/Android/sdk"
|
||||
export ANDROID_NDK_HOME="$ANDROID_HOME/ndk/29.0.14033849" # 根据实际版本调整
|
||||
export PATH="$ANDROID_NDK_HOME/toolchains/llvm/prebuilt/darwin-x86_64/bin:$PATH"
|
||||
|
||||
# 应用配置
|
||||
source ~/.zshrc
|
||||
```
|
||||
|
||||
## 编译步骤
|
||||
|
||||
### 方法 1: 使用项目脚本 (推荐)
|
||||
|
||||
```bash
|
||||
cd /Users/mac/Project/Dart/LighthouseApp/core
|
||||
|
||||
# 编译 ARM64 版本
|
||||
make android-arm64
|
||||
|
||||
# 编译所有架构
|
||||
make android-all # arm64-v8a, armeabi-v7a, x86, x86_64
|
||||
```
|
||||
|
||||
### 方法 2: 手动编译
|
||||
|
||||
#### 编译 ARM64 (arm64-v8a)
|
||||
|
||||
```bash
|
||||
cd /Users/mac/Project/Dart/LighthouseApp/core
|
||||
|
||||
# 1. 初始化 Go 模块
|
||||
go mod download
|
||||
git submodule update --init --recursive
|
||||
|
||||
# 2. 设置交叉编译环境
|
||||
export CGO_ENABLED=1
|
||||
export GOOS=android
|
||||
export GOARCH=arm64
|
||||
export CC="$ANDROID_NDK_HOME/toolchains/llvm/prebuilt/darwin-x86_64/bin/aarch64-linux-android29-clang"
|
||||
|
||||
# 3. 编译为共享库
|
||||
go build -buildmode=c-shared \
|
||||
-ldflags="-s -w" \
|
||||
-trimpath \
|
||||
-o ../android/app/src/main/jniLibs/arm64-v8a/libclash.so \
|
||||
.
|
||||
|
||||
# 4. 验证编译结果
|
||||
ls -lh ../android/app/src/main/jniLibs/arm64-v8a/libclash.so
|
||||
nm -D ../android/app/src/main/jniLibs/arm64-v8a/libclash.so | grep quickStart
|
||||
```
|
||||
|
||||
#### 编译 ARMv7 (armeabi-v7a)
|
||||
|
||||
```bash
|
||||
export GOARCH=arm
|
||||
export CC="$ANDROID_NDK_HOME/toolchains/llvm/prebuilt/darwin-x86_64/bin/armv7a-linux-androideabi29-clang"
|
||||
|
||||
go build -buildmode=c-shared \
|
||||
-ldflags="-s -w" \
|
||||
-trimpath \
|
||||
-o ../android/app/src/main/jniLibs/armeabi-v7a/libclash.so \
|
||||
.
|
||||
```
|
||||
|
||||
#### 编译 x86_64
|
||||
|
||||
```bash
|
||||
export GOARCH=amd64
|
||||
export CC="$ANDROID_NDK_HOME/toolchains/llvm/prebuilt/darwin-x86_64/bin/x86_64-linux-android29-clang"
|
||||
|
||||
go build -buildmode=c-shared \
|
||||
-ldflags="-s -w" \
|
||||
-trimpath \
|
||||
-o ../android/app/src/main/jniLibs/x86_64/libclash.so \
|
||||
.
|
||||
```
|
||||
|
||||
## 编译优化
|
||||
|
||||
### 减小文件体积
|
||||
|
||||
```bash
|
||||
# 使用 -ldflags 优化
|
||||
go build -buildmode=c-shared \
|
||||
-ldflags="-s -w -X 'github.com/metacubex/mihomo/constant.Version=1.0.0'" \
|
||||
-trimpath \
|
||||
-o libclash.so \
|
||||
.
|
||||
|
||||
# -s: 去除符号表
|
||||
# -w: 去除 DWARF 调试信息
|
||||
# -trimpath: 移除文件系统路径
|
||||
```
|
||||
|
||||
### UPX 压缩 (可选)
|
||||
|
||||
```bash
|
||||
# 安装 UPX
|
||||
brew install upx
|
||||
|
||||
# 压缩 SO 文件 (可减少 30-50% 体积)
|
||||
upx --best --lzma libclash.so
|
||||
|
||||
# ⚠️ 注意: UPX 压缩可能导致某些设备加载失败,仅在测试环境使用
|
||||
```
|
||||
|
||||
## 常见问题
|
||||
|
||||
### 问题 1: `undefined reference to 'xxx'`
|
||||
|
||||
**原因:** NDK 版本不匹配或缺少依赖
|
||||
|
||||
**解决:**
|
||||
```bash
|
||||
# 检查 NDK 版本
|
||||
ls $ANDROID_HOME/ndk/
|
||||
|
||||
# 使用推荐版本 (r25c / 25.2.9519653 或更高)
|
||||
export ANDROID_NDK_HOME="$ANDROID_HOME/ndk/25.2.9519653"
|
||||
```
|
||||
|
||||
### 问题 2: `clang: command not found`
|
||||
|
||||
**原因:** CC 环境变量路径错误
|
||||
|
||||
**解决:**
|
||||
```bash
|
||||
# macOS (Apple Silicon)
|
||||
export CC="$ANDROID_NDK_HOME/toolchains/llvm/prebuilt/darwin-aarch64/bin/aarch64-linux-android29-clang"
|
||||
|
||||
# macOS (Intel)
|
||||
export CC="$ANDROID_NDK_HOME/toolchains/llvm/prebuilt/darwin-x86_64/bin/aarch64-linux-android29-clang"
|
||||
```
|
||||
|
||||
### 问题 3: 编译后文件过大 (>50MB)
|
||||
|
||||
**原因:** 未启用优化参数
|
||||
|
||||
**解决:**
|
||||
```bash
|
||||
# 确保使用 -ldflags="-s -w"
|
||||
go build -buildmode=c-shared \
|
||||
-ldflags="-s -w" \
|
||||
-trimpath \
|
||||
-o libclash.so \
|
||||
.
|
||||
|
||||
# 预期大小: 25-30MB (ARM64)
|
||||
```
|
||||
|
||||
### 问题 4: `go: github.com/metacubex/mihomo: module not found`
|
||||
|
||||
**原因:** 子模块未初始化
|
||||
|
||||
**解决:**
|
||||
```bash
|
||||
cd core
|
||||
git submodule update --init --recursive
|
||||
go mod download
|
||||
```
|
||||
|
||||
## 验证编译结果
|
||||
|
||||
### 1. 检查导出函数
|
||||
|
||||
```bash
|
||||
nm -D libclash.so | grep -E "(quickStart|getAndroidVpnOptions|startTUN)"
|
||||
|
||||
# 预期输出:
|
||||
# 0000000000e23960 T getAndroidVpnOptions
|
||||
# 0000000000e237b0 T quickStart
|
||||
# 0000000000e23820 T startTUN
|
||||
```
|
||||
|
||||
### 2. 检查架构
|
||||
|
||||
```bash
|
||||
file libclash.so
|
||||
|
||||
# ARM64 预期输出:
|
||||
# libclash.so: ELF 64-bit LSB shared object, ARM aarch64, version 1 (SYSV), dynamically linked
|
||||
```
|
||||
|
||||
### 3. 测试加载
|
||||
|
||||
```bash
|
||||
# 在 Android 设备上测试
|
||||
adb push libclash.so /data/local/tmp/
|
||||
adb shell "cd /data/local/tmp && LD_LIBRARY_PATH=. /system/bin/true" # 测试加载
|
||||
```
|
||||
|
||||
## 持续集成 (CI/CD)
|
||||
|
||||
### GitHub Actions 示例
|
||||
|
||||
```yaml
|
||||
# .github/workflows/build-clash-core.yml
|
||||
name: Build Clash Core
|
||||
|
||||
on:
|
||||
push:
|
||||
paths:
|
||||
- 'core/**'
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
build-android:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
strategy:
|
||||
matrix:
|
||||
arch: [arm64, arm, amd64]
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
submodules: recursive
|
||||
|
||||
- uses: actions/setup-go@v4
|
||||
with:
|
||||
go-version: '1.20'
|
||||
|
||||
- name: Setup Android NDK
|
||||
uses: nttld/setup-ndk@v1
|
||||
with:
|
||||
ndk-version: r25c
|
||||
|
||||
- name: Build
|
||||
run: |
|
||||
cd core
|
||||
make android-${{ matrix.arch }}
|
||||
|
||||
- name: Upload Artifact
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: libclash-${{ matrix.arch }}
|
||||
path: android/app/src/main/jniLibs/**/libclash.so
|
||||
```
|
||||
|
||||
## 更新核心版本
|
||||
|
||||
### 更新 Clash.Meta 子模块
|
||||
|
||||
```bash
|
||||
cd core/Clash.Meta
|
||||
|
||||
# 更新到最新版本
|
||||
git fetch origin
|
||||
git checkout Alpha # 或其他分支
|
||||
git pull
|
||||
|
||||
cd ..
|
||||
git add Clash.Meta
|
||||
git commit -m "chore: update Clash.Meta to latest"
|
||||
|
||||
# 重新编译
|
||||
make clean
|
||||
make android-arm64
|
||||
```
|
||||
|
||||
### 查看版本信息
|
||||
|
||||
```bash
|
||||
# 查看当前 Clash.Meta 版本
|
||||
cd core/Clash.Meta
|
||||
git log -1 --oneline
|
||||
|
||||
# 查看依赖版本
|
||||
cd ..
|
||||
go list -m github.com/metacubex/mihomo
|
||||
```
|
||||
|
||||
## 调试编译问题
|
||||
|
||||
### 启用详细日志
|
||||
|
||||
```bash
|
||||
# 查看详细编译过程
|
||||
go build -v -x -buildmode=c-shared -o libclash.so .
|
||||
|
||||
# -v: 显示正在编译的包
|
||||
# -x: 显示执行的命令
|
||||
```
|
||||
|
||||
### 检查依赖
|
||||
|
||||
```bash
|
||||
# 列出所有依赖
|
||||
go list -m all
|
||||
|
||||
# 检查特定依赖
|
||||
go mod why github.com/metacubex/mihomo
|
||||
```
|
||||
|
||||
## 性能优化
|
||||
|
||||
### 编译时优化
|
||||
|
||||
```bash
|
||||
# 启用所有优化
|
||||
go build -buildmode=c-shared \
|
||||
-ldflags="-s -w -extldflags=-Wl,-z,now" \
|
||||
-trimpath \
|
||||
-tags="with_gvisor,with_quic" \
|
||||
-o libclash.so \
|
||||
.
|
||||
```
|
||||
|
||||
### Profile 引导优化 (PGO)
|
||||
|
||||
```bash
|
||||
# 1. 生成性能剖析文件
|
||||
go test -cpuprofile=cpu.prof ./...
|
||||
|
||||
# 2. 使用剖析文件编译
|
||||
go build -buildmode=c-shared \
|
||||
-pgo=cpu.prof \
|
||||
-o libclash.so \
|
||||
.
|
||||
```
|
||||
|
||||
## 相关资源
|
||||
|
||||
- [Android NDK 官方文档](https://developer.android.com/ndk)
|
||||
- [Go 交叉编译指南](https://go.dev/doc/install/source#environment)
|
||||
- [Clash Meta 编译指南](https://wiki.metacubex.one/dev/)
|
||||
441
docs/CLASH_TROUBLESHOOTING.md
Normal file
441
docs/CLASH_TROUBLESHOOTING.md
Normal file
@ -0,0 +1,441 @@
|
||||
# Clash Meta 故障排查指南
|
||||
|
||||
## 常见运行时问题
|
||||
|
||||
### 问题 1: VPN 连接失败,日志显示 "PermissionMonitor error 22 (EINVAL)"
|
||||
|
||||
**症状:**
|
||||
```
|
||||
E/VPNService: PermissionMonitor error 22 (EINVAL)
|
||||
E/Clash: TUN 设备启动失败
|
||||
```
|
||||
|
||||
**原因:**
|
||||
- VPN Builder 配置的路由规则无效
|
||||
- 缺少 bypass-LAN 路由配置
|
||||
- 路由 CIDR 格式错误
|
||||
|
||||
**解决方案:**
|
||||
|
||||
1. 检查 `getAndroidVpnOptions()` 返回的路由列表:
|
||||
```dart
|
||||
final options = await KRClashImp().getAndroidVpnOptions();
|
||||
print('路由数量: ${options?['routeAddress']?.length}');
|
||||
print('路由列表: ${options?['routeAddress']}');
|
||||
```
|
||||
|
||||
2. 确认配置包含完整的 bypass-LAN 路由:
|
||||
```yaml
|
||||
# clash_config.yaml
|
||||
tun:
|
||||
route-exclude-address:
|
||||
- 10.0.0.0/8
|
||||
- 100.64.0.0/10
|
||||
- 127.0.0.0/8
|
||||
- 169.254.0.0/16
|
||||
- 172.16.0.0/12
|
||||
- 192.0.0.0/24
|
||||
- 192.0.2.0/24
|
||||
- 192.88.99.0/24
|
||||
- 192.168.0.0/16
|
||||
- 198.18.0.0/15
|
||||
- 198.51.100.0/24
|
||||
- 203.0.113.0/24
|
||||
- 224.0.0.0/3
|
||||
- fc00::/7
|
||||
- fe80::/10
|
||||
- ff00::/8
|
||||
```
|
||||
|
||||
3. 验证 VPN Builder 配置:
|
||||
```kotlin
|
||||
// VPNService.kt
|
||||
builder
|
||||
.addAddress("172.19.0.1/30")
|
||||
.addRoute("0.0.0.0/1") // ✅ 拆分默认路由
|
||||
.addRoute("128.0.0.0/1") // ✅ 避免 0.0.0.0/0
|
||||
.addRoute("10.0.0.0/8") // ✅ bypass-LAN
|
||||
// ...
|
||||
```
|
||||
|
||||
**参考:** `lib/app/services/clash_imp/kr_clash_imp.dart:192`
|
||||
|
||||
---
|
||||
|
||||
### 问题 2: FFI 初始化崩溃 "Go runtime already initialized"
|
||||
|
||||
**症状:**
|
||||
```
|
||||
F/libc: Fatal signal 11 (SIGSEGV), code 1 (SEGV_MAPERR)
|
||||
E/Clash: Go runtime already initialized
|
||||
```
|
||||
|
||||
**原因:**
|
||||
- 多线程并发调用 `_ensureInitialized()`
|
||||
- Go 运行时被重复初始化
|
||||
|
||||
**解决方案:**
|
||||
|
||||
已在 `kr_clash_imp.dart` 中修复,使用 `Completer` 实现并发安全:
|
||||
```dart
|
||||
Future<void> _ensureInitialized() async {
|
||||
if (_initialized) return;
|
||||
if (_initLock != null) {
|
||||
await _initLock!.future; // ✅ 等待其他初始化完成
|
||||
return;
|
||||
}
|
||||
_initLock = Completer<void>();
|
||||
// ... 执行初始化
|
||||
}
|
||||
```
|
||||
|
||||
**验证修复:**
|
||||
```dart
|
||||
// 并发测试
|
||||
await Future.wait([
|
||||
KRClashImp().start(...),
|
||||
KRClashImp().getAndroidVpnOptions(),
|
||||
KRClashImp().getTraffic(),
|
||||
]);
|
||||
// ✅ 应该不会崩溃
|
||||
```
|
||||
|
||||
**参考:** `lib/app/services/clash_imp/kr_clash_imp.dart:43`
|
||||
|
||||
---
|
||||
|
||||
### 问题 3: 模拟器无法联网 "Network unreachable"
|
||||
|
||||
**症状:**
|
||||
```
|
||||
E/Clash: 网络不可达
|
||||
W/VPNService: 底层网络丢失
|
||||
```
|
||||
|
||||
**原因:**
|
||||
- 模拟器需要显式设置底层网络
|
||||
- 缺少 `setUnderlyingNetworks()` 调用
|
||||
|
||||
**解决方案:**
|
||||
|
||||
已在 `VPNService.kt` 中实现:
|
||||
```kotlin
|
||||
// Android P+ 需要设置底层网络
|
||||
private val defaultNetworkCallback by lazy {
|
||||
object : ConnectivityManager.NetworkCallback() {
|
||||
override fun onAvailable(network: Network) {
|
||||
setUnderlyingNetworks(arrayOf(network)) // ✅ 关键!
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 注册回调
|
||||
connectivityManager.registerDefaultNetworkCallback(defaultNetworkCallback)
|
||||
```
|
||||
|
||||
**验证修复:**
|
||||
```bash
|
||||
# 在 MuMu 模拟器测试
|
||||
adb logcat | grep "底层网络"
|
||||
# 应该看到: "底层网络可用: NetworkIdentity{...}"
|
||||
```
|
||||
|
||||
**参考:** `android/.../bg/VPNService.kt:32-66`
|
||||
|
||||
---
|
||||
|
||||
### 问题 4: 配置文件解析失败 "invalid YAML"
|
||||
|
||||
**症状:**
|
||||
```
|
||||
E/Clash: 启动失败: yaml: unmarshal errors:
|
||||
line 10: cannot unmarshal !!str `8388` into int
|
||||
```
|
||||
|
||||
**原因:**
|
||||
- YAML 类型不匹配 (字符串 vs 整数)
|
||||
- 配置格式错误
|
||||
|
||||
**解决方案:**
|
||||
|
||||
检查 `ClashConfigGenerator.generate()`:
|
||||
```dart
|
||||
proxies:
|
||||
- name: "Server-1"
|
||||
type: ss
|
||||
server: "example.com"
|
||||
port: 8388 # ✅ 整数,不要引号
|
||||
password: "password" # ✅ 字符串,使用引号
|
||||
cipher: "aes-256-gcm"
|
||||
```
|
||||
|
||||
**调试方法:**
|
||||
```dart
|
||||
// 打印生成的配置
|
||||
final config = ClashConfigGenerator.generate(...);
|
||||
print('配置预览:\n$config');
|
||||
|
||||
// 保存到文件手动检查
|
||||
File('/tmp/clash_debug.yaml').writeAsStringSync(config);
|
||||
```
|
||||
|
||||
**参考:** `lib/app/services/clash_imp/clash_config_generator.dart`
|
||||
|
||||
---
|
||||
|
||||
### 问题 5: "quickStart timeout" 启动超时
|
||||
|
||||
**症状:**
|
||||
```
|
||||
W/Clash: 启动超时 (10秒)
|
||||
E/Clash: quickStart 未收到回调
|
||||
```
|
||||
|
||||
**原因:**
|
||||
- Go 核心启动耗时过长
|
||||
- ReceivePort 未正确监听
|
||||
- 回调被阻塞
|
||||
|
||||
**解决方案:**
|
||||
|
||||
1. 增加超时时间:
|
||||
```dart
|
||||
_isRunning = await completer.future.timeout(
|
||||
const Duration(seconds: 20), // ✅ 增加到 20 秒
|
||||
onTimeout: () {
|
||||
print('⚠️ 启动超时');
|
||||
return false;
|
||||
},
|
||||
);
|
||||
```
|
||||
|
||||
2. 检查 Go 核心日志:
|
||||
```kotlin
|
||||
// ClashService.kt - 添加日志回调
|
||||
tempMethodChannel.setMethodCallHandler { call, result ->
|
||||
if (call.method == "log") {
|
||||
Log.d(TAG, "Go 核心日志: ${call.arguments}")
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
3. 使用 Service Isolate 避免阻塞:
|
||||
```kotlin
|
||||
// ClashService.kt:102 - 已实现
|
||||
serviceEngine?.dartExecutor?.executeDartEntrypoint(entrypoint)
|
||||
```
|
||||
|
||||
**参考:** `lib/app/services/clash_imp/kr_clash_imp.dart:145`
|
||||
|
||||
---
|
||||
|
||||
### 问题 6: 流量统计不更新
|
||||
|
||||
**症状:**
|
||||
```
|
||||
I/Clash: 流量统计: {"upload": 0, "download": 0} # 始终为 0
|
||||
```
|
||||
|
||||
**原因:**
|
||||
- TUN 设备未正确启动
|
||||
- 流量未通过代理
|
||||
|
||||
**解决方案:**
|
||||
|
||||
1. 确认 TUN 启动成功:
|
||||
```dart
|
||||
final tunStarted = await KRClashImp().startTun(fd, protectCallback);
|
||||
print('TUN 启动状态: $tunStarted'); // 应该为 true
|
||||
```
|
||||
|
||||
2. 检查路由配置:
|
||||
```bash
|
||||
# 在设备上检查路由表
|
||||
adb shell "ip route show table all | grep tun"
|
||||
```
|
||||
|
||||
3. 测试代理连接:
|
||||
```bash
|
||||
# 使用 curl 测试
|
||||
adb shell "curl -v http://www.google.com"
|
||||
# 应该看到代理日志
|
||||
```
|
||||
|
||||
**参考:** `lib/app/services/clash_imp/kr_clash_imp.dart:261`
|
||||
|
||||
---
|
||||
|
||||
## 日志分析
|
||||
|
||||
### 启用详细日志
|
||||
|
||||
```dart
|
||||
// lib/app/services/clash_imp/kr_clash_imp.dart
|
||||
// 添加更详细的日志
|
||||
print('📨 [Clash] 收到消息: ${jsonEncode(message)}');
|
||||
print('📋 [Clash] 配置完整内容:\n$config');
|
||||
```
|
||||
|
||||
### Android Logcat 过滤
|
||||
|
||||
```bash
|
||||
# 只看 Clash 相关日志
|
||||
adb logcat -s "A/Clash" "E/Clash" "W/Clash"
|
||||
|
||||
# 实时监控 FFI 调用
|
||||
adb logcat | grep -E "(ClashFFI|quickStart|getAndroidVpnOptions)"
|
||||
|
||||
# 保存日志到文件
|
||||
adb logcat -d > clash_debug.log
|
||||
```
|
||||
|
||||
### Dart Observatory 调试
|
||||
|
||||
```bash
|
||||
# 启用 Dart Observatory
|
||||
flutter run --observatory-port=8181
|
||||
|
||||
# 在浏览器打开
|
||||
open http://localhost:8181
|
||||
|
||||
# 查看 Isolate 状态
|
||||
# - Main Isolate (UI)
|
||||
# - Service Isolate (Clash 后台)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 性能问题
|
||||
|
||||
### 内存泄漏
|
||||
|
||||
**症状:**
|
||||
- 应用内存持续增长
|
||||
- 最终 OOM 崩溃
|
||||
|
||||
**排查:**
|
||||
```dart
|
||||
// 确保调用 dispose()
|
||||
@override
|
||||
void dispose() {
|
||||
KRClashImp().dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
// 检查 ReceivePort 是否关闭
|
||||
receivePort.listen((message) {
|
||||
// ...
|
||||
receivePort.close(); // ✅ 必须关闭!
|
||||
});
|
||||
```
|
||||
|
||||
### CPU 占用过高
|
||||
|
||||
**症状:**
|
||||
- 设备发热
|
||||
- 电池消耗快
|
||||
|
||||
**排查:**
|
||||
```bash
|
||||
# 查看 CPU 占用
|
||||
adb shell "top -m 10"
|
||||
|
||||
# 使用 Profiler
|
||||
flutter run --profile
|
||||
# DevTools → CPU Profiler
|
||||
```
|
||||
|
||||
**优化:**
|
||||
```dart
|
||||
// 降低流量统计频率
|
||||
Timer.periodic(const Duration(seconds: 2), (timer) { // ✅ 2秒而非1秒
|
||||
final traffic = await KRClashImp().getTraffic();
|
||||
// ...
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 崩溃分析
|
||||
|
||||
### 获取崩溃堆栈
|
||||
|
||||
```bash
|
||||
# Native 崩溃
|
||||
adb logcat -d | grep "backtrace"
|
||||
|
||||
# 使用 ndk-stack 解析
|
||||
adb logcat | ndk-stack -sym android/app/build/intermediates/merged_native_libs/debug/out/lib/arm64-v8a
|
||||
```
|
||||
|
||||
### 常见崩溃模式
|
||||
|
||||
#### SIGSEGV (段错误)
|
||||
|
||||
**原因:** FFI 指针使用错误
|
||||
|
||||
**示例:**
|
||||
```dart
|
||||
// ❌ 错误: 释放后使用
|
||||
final ptr = 'hello'.toNativeUtf8();
|
||||
malloc.free(ptr);
|
||||
_ffi!.someFunction(ptr); // 崩溃!
|
||||
|
||||
// ✅ 正确: 使用后释放
|
||||
final ptr = 'hello'.toNativeUtf8();
|
||||
_ffi!.someFunction(ptr);
|
||||
malloc.free(ptr);
|
||||
```
|
||||
|
||||
#### SIGABRT (异常终止)
|
||||
|
||||
**原因:** Go panic 未恢复
|
||||
|
||||
**解决:** 在 Go 侧添加 recover:
|
||||
```go
|
||||
//export quickStart
|
||||
func quickStart(...) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
log.Println("Panic recovered:", r)
|
||||
}
|
||||
}()
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 获取帮助
|
||||
|
||||
### 收集诊断信息
|
||||
|
||||
创建 Bug 报告时请包含:
|
||||
|
||||
1. **系统信息:**
|
||||
```bash
|
||||
adb shell "getprop ro.build.version.release" # Android 版本
|
||||
adb shell "getprop ro.product.cpu.abi" # CPU 架构
|
||||
```
|
||||
|
||||
2. **应用日志:**
|
||||
```bash
|
||||
adb logcat -d > full_log.txt
|
||||
```
|
||||
|
||||
3. **配置文件:**
|
||||
```dart
|
||||
// 脱敏后的 clash_config.yaml
|
||||
print(config.replaceAll(RegExp(r'password:.*'), 'password: ***'));
|
||||
```
|
||||
|
||||
4. **复现步骤:**
|
||||
- 详细操作流程
|
||||
- 预期结果 vs 实际结果
|
||||
- 复现概率
|
||||
|
||||
### 相关资源
|
||||
|
||||
- [GitHub Issues](https://github.com/your-repo/issues)
|
||||
- [Clash Meta Wiki](https://wiki.metacubex.one/)
|
||||
- [Flutter FFI 文档](https://dart.dev/guides/libraries/c-interop)
|
||||
269
docs/README.md
Normal file
269
docs/README.md
Normal file
@ -0,0 +1,269 @@
|
||||
# LighthouseApp 技术文档
|
||||
|
||||
欢迎查阅 LighthouseApp 技术文档。本目录包含项目的架构设计、开发指南和故障排查信息。
|
||||
|
||||
## 📚 文档导航
|
||||
|
||||
### Clash Meta 核心 (推荐阅读)
|
||||
|
||||
| 文档 | 说明 | 适用人群 |
|
||||
|------|------|----------|
|
||||
| [**架构文档**](./CLASH_ARCHITECTURE.md) | 完整架构设计、数据流、关键决策 | 所有开发者 |
|
||||
| [**编译指南**](./CLASH_BUILD_GUIDE.md) | 本地编译步骤、环境配置、优化方法 | 核心开发者 |
|
||||
| [**故障排查**](./CLASH_TROUBLESHOOTING.md) | 常见问题、日志分析、崩溃调试 | 测试/运维 |
|
||||
|
||||
### CI/CD 工作流
|
||||
|
||||
| 文档 | 说明 |
|
||||
|------|------|
|
||||
| [**GitHub Actions 说明**](../.github/workflows/README.md) | 自动化构建、发布流程 |
|
||||
|
||||
## 🚀 快速开始
|
||||
|
||||
### 新开发者入门
|
||||
|
||||
1. **了解架构** (必读)
|
||||
- 阅读 [CLASH_ARCHITECTURE.md](./CLASH_ARCHITECTURE.md)
|
||||
- 理解 Dart → Android → Go 三层架构
|
||||
- 掌握 FFI 通信机制
|
||||
|
||||
2. **配置开发环境**
|
||||
- 按照 [CLASH_BUILD_GUIDE.md](./CLASH_BUILD_GUIDE.md) 配置环境
|
||||
- 编译第一个 Clash Core
|
||||
- 验证编译结果
|
||||
|
||||
3. **运行项目**
|
||||
```bash
|
||||
# 1. 获取代码
|
||||
git clone <repo-url>
|
||||
cd LighthouseApp
|
||||
|
||||
# 2. 初始化子模块
|
||||
git submodule update --init --recursive
|
||||
|
||||
# 3. 编译核心
|
||||
cd core
|
||||
make android-arm64
|
||||
|
||||
# 4. 运行 Flutter
|
||||
cd ..
|
||||
flutter pub get
|
||||
flutter run
|
||||
```
|
||||
|
||||
### 核心开发者
|
||||
|
||||
如果您需要修改 Clash Meta 核心:
|
||||
|
||||
1. **修改代码**
|
||||
```bash
|
||||
cd core
|
||||
vim lib_android.go # 或其他核心文件
|
||||
```
|
||||
|
||||
2. **本地测试**
|
||||
```bash
|
||||
make android-arm64
|
||||
flutter run
|
||||
```
|
||||
|
||||
3. **提交 PR**
|
||||
- CI/CD 会自动构建所有架构
|
||||
- 检查 Actions 页面的构建结果
|
||||
- 等待代码审查
|
||||
|
||||
## 🏗️ 架构速览
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ LighthouseApp │
|
||||
├─────────────────────────────────────────────────────────────┤
|
||||
│ Flutter/Dart Layer │
|
||||
│ └─ lib/app/services/clash_imp/ │
|
||||
│ ├─ kr_clash_imp.dart (核心封装) │
|
||||
│ ├─ clash_ffi.dart (FFI 绑定) │
|
||||
│ └─ clash_config_generator (配置生成) │
|
||||
├─────────────────────────────────────────────────────────────┤
|
||||
│ Android Native Layer │
|
||||
│ └─ android/app/src/main/kotlin/com/hiddify/hiddify/ │
|
||||
│ ├─ bg/VPNService.kt (VPN 服务) │
|
||||
│ └─ bg/ClashService.kt (Clash 服务) │
|
||||
├─────────────────────────────────────────────────────────────┤
|
||||
│ Go Core Layer │
|
||||
│ └─ core/ │
|
||||
│ ├─ Clash.Meta/ (Git 子模块) │
|
||||
│ ├─ lib_android.go (JNI 桥接) │
|
||||
│ └─ libclash.so (编译产物) │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
详细架构请参考 [CLASH_ARCHITECTURE.md](./CLASH_ARCHITECTURE.md)
|
||||
|
||||
## 🔧 常见任务
|
||||
|
||||
### 编译核心
|
||||
|
||||
```bash
|
||||
cd core
|
||||
|
||||
# 单个架构 (快速)
|
||||
make android-arm64
|
||||
|
||||
# 所有架构 (发布)
|
||||
make android-all
|
||||
|
||||
# 清理
|
||||
make clean
|
||||
|
||||
# 验证
|
||||
make verify
|
||||
```
|
||||
|
||||
### 更新 Clash.Meta
|
||||
|
||||
```bash
|
||||
cd core
|
||||
make update # 更新子模块到最新版本
|
||||
make android-arm64 # 重新编译
|
||||
```
|
||||
|
||||
### 调试问题
|
||||
|
||||
```bash
|
||||
# 查看 Android 日志
|
||||
adb logcat -s "A/Clash" "E/Clash"
|
||||
|
||||
# 查看编译详情
|
||||
cd core
|
||||
go build -v -x -buildmode=c-shared -o test.so .
|
||||
|
||||
# 验证 SO 文件
|
||||
nm -D libclash.so | grep quickStart
|
||||
```
|
||||
|
||||
## 📖 核心概念
|
||||
|
||||
### 1. FFI 并发安全
|
||||
|
||||
**问题:** Go 运行时初始化不是线程安全的
|
||||
|
||||
**解决:** 使用 `Completer` 实现初始化锁
|
||||
|
||||
```dart
|
||||
Future<void> _ensureInitialized() async {
|
||||
if (_initialized) return;
|
||||
if (_initLock != null) {
|
||||
await _initLock!.future; // ✅ 等待其他初始化
|
||||
return;
|
||||
}
|
||||
// ... 执行初始化
|
||||
}
|
||||
```
|
||||
|
||||
详见 [CLASH_ARCHITECTURE.md § 并发安全保证](./CLASH_ARCHITECTURE.md#并发安全保证)
|
||||
|
||||
### 2. Service Isolate 架构
|
||||
|
||||
**为什么需要?**
|
||||
- VPN 服务运行在后台
|
||||
- 主 Isolate 可能被销毁
|
||||
- 需要独立的 Dart 运行时
|
||||
|
||||
**实现:**
|
||||
```kotlin
|
||||
// ClashService.kt
|
||||
serviceEngine = FlutterEngine(Application.application)
|
||||
val entrypoint = DartExecutor.DartEntrypoint(..., "_clashService")
|
||||
serviceEngine?.dartExecutor?.executeDartEntrypoint(entrypoint)
|
||||
```
|
||||
|
||||
详见 [CLASH_ARCHITECTURE.md § Service Isolate 架构](./CLASH_ARCHITECTURE.md#2-android-service-层-clashservicekt)
|
||||
|
||||
### 3. Android VPN 路由配置
|
||||
|
||||
**关键:** `getAndroidVpnOptions()` 返回 35+ 详细 CIDR 路由
|
||||
|
||||
**为什么重要?**
|
||||
- 避免 PermissionMonitor error 22
|
||||
- 支持 bypass-LAN
|
||||
- 兼容模拟器
|
||||
|
||||
详见 [CLASH_TROUBLESHOOTING.md § 问题 1](./CLASH_TROUBLESHOOTING.md#问题-1-vpn-连接失败日志显示-permissionmonitor-error-22-einval)
|
||||
|
||||
## 🐛 遇到问题?
|
||||
|
||||
1. **查看故障排查文档**
|
||||
- [CLASH_TROUBLESHOOTING.md](./CLASH_TROUBLESHOOTING.md) 包含所有常见问题
|
||||
|
||||
2. **收集诊断信息**
|
||||
```bash
|
||||
# 系统信息
|
||||
adb shell "getprop ro.build.version.release"
|
||||
|
||||
# 应用日志
|
||||
adb logcat -d > full_log.txt
|
||||
|
||||
# 核心信息
|
||||
cd core
|
||||
make verify
|
||||
```
|
||||
|
||||
3. **提交 Issue**
|
||||
- 使用诊断信息模板
|
||||
- 包含复现步骤
|
||||
- 附上日志文件
|
||||
|
||||
## 🤝 贡献指南
|
||||
|
||||
### 代码规范
|
||||
|
||||
项目遵循以下原则:
|
||||
- **KISS** (Keep It Simple, Stupid) - 简单至上
|
||||
- **DRY** (Don't Repeat Yourself) - 杜绝重复
|
||||
- **SOLID** - 面向对象设计原则
|
||||
- **YAGNI** (You Aren't Gonna Need It) - 精益求精
|
||||
|
||||
### 提交流程
|
||||
|
||||
1. Fork 项目
|
||||
2. 创建特性分支 (`git checkout -b feature/amazing`)
|
||||
3. 提交更改 (`git commit -m 'feat: add amazing feature'`)
|
||||
4. 推送分支 (`git push origin feature/amazing`)
|
||||
5. 创建 Pull Request
|
||||
|
||||
### Commit 规范
|
||||
|
||||
使用 Conventional Commits:
|
||||
- `feat:` 新功能
|
||||
- `fix:` 修复 Bug
|
||||
- `docs:` 文档更新
|
||||
- `refactor:` 代码重构
|
||||
- `perf:` 性能优化
|
||||
- `test:` 测试相关
|
||||
- `chore:` 构建/工具链
|
||||
|
||||
## 📞 获取帮助
|
||||
|
||||
- **GitHub Issues:** [提交问题](https://github.com/your-repo/issues)
|
||||
- **文档索引:** 您正在阅读!
|
||||
- **外部资源:**
|
||||
- [Clash Meta Wiki](https://wiki.metacubex.one/)
|
||||
- [Flutter FFI 文档](https://dart.dev/guides/libraries/c-interop)
|
||||
- [Android VPN 指南](https://developer.android.com/reference/android/net/VpnService)
|
||||
|
||||
## 📝 更新日志
|
||||
|
||||
| 日期 | 版本 | 更新内容 |
|
||||
|------|------|----------|
|
||||
| 2025-10-25 | 1.0.0 | 完成 Xboard-Mihomo 核心集成 |
|
||||
| 2025-10-25 | 1.0.0 | 修复 FFI 并发安全问题 |
|
||||
| 2025-10-25 | 1.0.0 | 添加完整技术文档 |
|
||||
|
||||
## 📄 许可证
|
||||
|
||||
本项目采用 [LICENSE](../LICENSE) 许可证。
|
||||
|
||||
---
|
||||
|
||||
**最后更新:** 2025-10-25
|
||||
**维护者:** LighthouseApp 开发团队
|
||||
318
docs/go修复.md
Normal file
318
docs/go修复.md
Normal file
@ -0,0 +1,318 @@
|
||||
# Android SELinux chown 权限问题修复方案
|
||||
|
||||
## 问题背景
|
||||
|
||||
在 Android 12+ 系统上,由于 SELinux 严格模式的权限限制,sing-box 核心库在启动时会因为 `chown` 操作被拒绝而失败。具体表现为以下三个错误:
|
||||
|
||||
1. **CommandServer 错误**: `chown: chown command.sock: operation not permitted`
|
||||
2. **Logger 错误**: `start logger: chown box.log: operation not permitted`
|
||||
3. **Clash Cache 错误**: `pre-start cache file: platform chown: chown clash.db: operation not permitted`
|
||||
|
||||
## 问题分析
|
||||
|
||||
### 根本原因
|
||||
|
||||
sing-box (libbox) 在创建文件后会尝试修改文件所有权(`chown`操作),但在 Android 的 SELinux 环境下,应用无法修改外部存储目录中文件的所有权,导致启动失败。
|
||||
|
||||
### 涉及的文件
|
||||
|
||||
1. `command.sock` - CommandServer 的 Unix socket 文件
|
||||
2. `box.log` - sing-box 的日志文件
|
||||
3. `clash.db` - Clash API 的缓存数据库文件
|
||||
|
||||
## 修复方案
|
||||
|
||||
### 方案概述
|
||||
|
||||
**核心思路**: 在配置层面禁用会触发 chown 操作的功能,或者修改底层代码跳过 chown 操作。
|
||||
|
||||
由于修改 sing-box 底层库较为复杂,建议采用配置修改方案。
|
||||
|
||||
---
|
||||
|
||||
## 具体修复步骤
|
||||
|
||||
### 修复 1: 禁用文件日志
|
||||
|
||||
**文件**: `libcore/config/hiddify_option.go`
|
||||
|
||||
**位置**: `DefaultHiddifyOptions()` 函数
|
||||
|
||||
**修改前**:
|
||||
```go
|
||||
LogLevel: "warn",
|
||||
// LogFile: "/dev/null",
|
||||
LogFile: "box.log",
|
||||
```
|
||||
|
||||
**修改后**:
|
||||
```go
|
||||
LogLevel: "warn",
|
||||
LogFile: "", // 禁用文件日志,避免 Android SELinux chown 权限问题
|
||||
// LogFile: "box.log",
|
||||
```
|
||||
|
||||
**说明**:
|
||||
- 将 `LogFile` 设置为空字符串,禁用文件日志输出
|
||||
- 日志将只输出到 stderr,可以通过 logcat 查看
|
||||
- 这不会影响日志功能,只是改变了输出目标
|
||||
|
||||
---
|
||||
|
||||
### 修复 2: 禁用 Clash API 缓存
|
||||
|
||||
**文件**: `libcore/config/config.go`
|
||||
|
||||
**位置**: `setClashAPI()` 函数
|
||||
|
||||
**修改前**:
|
||||
```go
|
||||
func setClashAPI(options *option.Options, opt *HiddifyOptions) {
|
||||
if opt.EnableClashApi {
|
||||
if opt.ClashApiSecret == "" {
|
||||
opt.ClashApiSecret = generateRandomString(16)
|
||||
}
|
||||
options.Experimental = &option.ExperimentalOptions{
|
||||
ClashAPI: &option.ClashAPIOptions{
|
||||
ExternalController: fmt.Sprintf("%s:%d", "127.0.0.1", opt.ClashApiPort),
|
||||
Secret: opt.ClashApiSecret,
|
||||
},
|
||||
|
||||
CacheFile: &option.CacheFileOptions{
|
||||
Enabled: true,
|
||||
Path: "clash.db",
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**修改后**:
|
||||
```go
|
||||
func setClashAPI(options *option.Options, opt *HiddifyOptions) {
|
||||
if opt.EnableClashApi {
|
||||
if opt.ClashApiSecret == "" {
|
||||
opt.ClashApiSecret = generateRandomString(16)
|
||||
}
|
||||
options.Experimental = &option.ExperimentalOptions{
|
||||
ClashAPI: &option.ClashAPIOptions{
|
||||
ExternalController: fmt.Sprintf("%s:%d", "127.0.0.1", opt.ClashApiPort),
|
||||
Secret: opt.ClashApiSecret,
|
||||
},
|
||||
|
||||
CacheFile: &option.CacheFileOptions{
|
||||
Enabled: false, // 禁用缓存以避免 Android SELinux chown 权限问题
|
||||
Path: "", // 清空路径
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**说明**:
|
||||
- 将 `Enabled` 设置为 `false`,禁用 Clash API 缓存功能
|
||||
- 将 `Path` 设置为空字符串
|
||||
- Clash API 功能仍然可用,只是不会持久化节点选择等信息
|
||||
|
||||
---
|
||||
|
||||
### 修复 3: CommandServer 错误处理 (可选)
|
||||
|
||||
**说明**: CommandServer 主要用于命令行控制,对 Android VPN 功能不是必需的。
|
||||
|
||||
#### 方案 A: 在应用层捕获异常 (推荐)
|
||||
|
||||
**文件**: `android/app/src/main/kotlin/com/hiddify/hiddify/bg/BoxService.kt`
|
||||
|
||||
**位置**: `onStartCommand()` 函数
|
||||
|
||||
**修改**:
|
||||
```kotlin
|
||||
GlobalScope.launch(Dispatchers.IO) {
|
||||
Settings.startedByUser = true
|
||||
initialize()
|
||||
try {
|
||||
startCommandServer()
|
||||
} catch (e: Exception) {
|
||||
// CommandServer 启动失败不是致命错误
|
||||
// 在 Android 12+ SELinux 环境下,chown 操作可能被拒绝
|
||||
// 但这不影响 VPN 核心功能,因此记录警告但继续启动服务
|
||||
Log.w(TAG, "CommandServer failed to start (non-fatal): ${e.message}")
|
||||
}
|
||||
startService()
|
||||
}
|
||||
```
|
||||
|
||||
#### 方案 B: 完全禁用 CommandServer
|
||||
|
||||
如果不需要 CommandServer 功能,可以直接注释掉启动代码:
|
||||
```kotlin
|
||||
// startCommandServer() // 在 Android 上禁用
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 验证修复
|
||||
|
||||
### 编译步骤
|
||||
|
||||
1. **使用 Docker 编译** (推荐):
|
||||
```bash
|
||||
cd libcore
|
||||
docker run --rm -v "$PWD:/workspace" -w /workspace golang:1.23 bash -c "bash docker-compile.sh"
|
||||
```
|
||||
|
||||
2. **或者本地编译**:
|
||||
```bash
|
||||
cd libcore
|
||||
make android
|
||||
```
|
||||
|
||||
### 部署编译好的库
|
||||
|
||||
编译完成后,有两种部署方式:
|
||||
|
||||
#### 方式A: 替换完整AAR (推荐生产环境)
|
||||
|
||||
```bash
|
||||
cd libcore
|
||||
# 替换AAR文件
|
||||
cp libcore.aar ../android/app/libs/
|
||||
|
||||
# 删除可能冲突的so文件
|
||||
rm -rf ../android/app/src/main/jniLibs/
|
||||
|
||||
# 重新编译Flutter项目
|
||||
cd ..
|
||||
flutter clean && flutter build apk
|
||||
```
|
||||
|
||||
**优点**: 支持所有架构,适合发布版本
|
||||
|
||||
#### 方式B: 只提取arm64 so文件 (推荐测试环境)
|
||||
|
||||
```bash
|
||||
cd libcore
|
||||
# 从AAR提取arm64的libbox.so
|
||||
unzip -j libcore.aar jni/arm64-v8a/libbox.so -d /tmp/
|
||||
mkdir -p ../android/app/src/main/jniLibs/arm64-v8a/
|
||||
cp /tmp/libbox.so ../android/app/src/main/jniLibs/arm64-v8a/
|
||||
|
||||
# 临时禁用AAR(避免冲突)
|
||||
mv ../android/app/libs/libcore.aar ../android/app/libs/libcore.aar.old
|
||||
|
||||
# 编译测试版本
|
||||
cd ..
|
||||
flutter clean && flutter build apk --debug --split-per-abi
|
||||
```
|
||||
|
||||
**优点**: 编译快速,APK体积小,适合开发调试
|
||||
|
||||
⚠️ **重要**: 两种方式不能同时使用,会产生冲突!请根据需求选择其一。
|
||||
|
||||
### 测试验证
|
||||
|
||||
1. 重新编译 Flutter 应用
|
||||
2. 在 Android 设备上安装并启动
|
||||
3. 查看 logcat 日志,确认没有 chown 相关错误
|
||||
4. 验证 VPN 能正常启动和代理流量
|
||||
|
||||
---
|
||||
|
||||
## 预期结果
|
||||
|
||||
修复后,应用启动日志应该显示:
|
||||
|
||||
```
|
||||
D/A/BoxService: base dir: /data/user/0/app.xxx.com/files
|
||||
D/A/BoxService: working dir: /storage/emulated/0/Android/data/app.xxx.com/files
|
||||
D/A/BoxService: temp dir: /data/user/0/app.xxx.com/cache
|
||||
W/A/BoxService: CommandServer failed to start (non-fatal): chown: chown command.sock: operation not permitted
|
||||
D/A/BoxService: starting service
|
||||
D/A/BoxService: 配置已修改: 禁用文件日志和Clash缓存
|
||||
D/A/EventHandler: new status: Started ✅ 成功启动!
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 影响评估
|
||||
|
||||
### 功能影响
|
||||
|
||||
| 功能 | 修复前 | 修复后 | 影响 |
|
||||
|------|--------|--------|------|
|
||||
| VPN 代理 | ❌ 无法启动 | ✅ 正常工作 | 无影响 |
|
||||
| 日志记录 | 文件输出 | logcat 输出 | 日志仍可用,通过 logcat 查看 |
|
||||
| Clash API | 带缓存 | 无缓存 | 节点选择不持久化,重启后重置 |
|
||||
| CommandServer | ❌ 失败 | 跳过启动 | 命令行控制不可用(非必需) |
|
||||
|
||||
### 性能影响
|
||||
|
||||
- **无性能损失**: 禁用缓存和文件日志对性能无负面影响
|
||||
- **启动速度**: 可能略微加快(减少文件 I/O 操作)
|
||||
|
||||
---
|
||||
|
||||
## 替代方案 (高级)
|
||||
|
||||
如果需要保留完整功能,可以考虑以下方案:
|
||||
|
||||
### 方案 1: 修改 sing-box 源码
|
||||
|
||||
在 sing-box 底层库中跳过 Android 平台的 chown 操作:
|
||||
|
||||
```go
|
||||
// 在文件创建后的 chown 调用处添加平台判断
|
||||
if runtime.GOOS != "android" {
|
||||
if err := os.Chown(path, uid, gid); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**优点**: 保留所有功能
|
||||
**缺点**: 需要修改 sing-box 上游代码,维护成本高
|
||||
|
||||
### 方案 2: 使用内部存储
|
||||
|
||||
将文件创建在 `/data/user/0/` 目录下而不是外部存储:
|
||||
|
||||
**优点**: 避免 SELinux 限制
|
||||
**缺点**: 空间受限,不适合大文件
|
||||
|
||||
---
|
||||
|
||||
## 常见问题
|
||||
|
||||
### Q1: 禁用文件日志后如何查看日志?
|
||||
|
||||
**A**: 使用 adb logcat:
|
||||
```bash
|
||||
adb logcat | grep "A/BoxService\|singbox"
|
||||
```
|
||||
|
||||
### Q2: 禁用 Clash 缓存后有什么影响?
|
||||
|
||||
**A**: 每次启动 VPN 时,节点选择会重置为默认值,但不影响 VPN 的核心代理功能。
|
||||
|
||||
### Q3: 为什么 hiddify-app 可以正常运行?
|
||||
|
||||
**A**: hiddify-app 使用的 libcore 版本已经包含了这些修复,或者使用了不同的配置策略。
|
||||
|
||||
### Q4: 这个修复是否适用于所有 Android 版本?
|
||||
|
||||
**A**: 是的,这个修复对 Android 11 及以下版本也兼容,不会产生负面影响。
|
||||
|
||||
---
|
||||
|
||||
## 参考资料
|
||||
|
||||
- [Android SELinux 权限文档](https://source.android.com/docs/security/features/selinux)
|
||||
- [sing-box 配置文档](https://sing-box.sagernet.org/configuration/)
|
||||
- [Clash API 配置](https://sing-box.sagernet.org/configuration/experimental/clash-api/)
|
||||
|
||||
---
|
||||
|
||||
## 更新日志
|
||||
|
||||
- **2025-10-27**: 初始版本,包含三个核心修复方案
|
||||
@ -214,7 +214,7 @@ class KRHomeConnectionInfoView extends GetView<KRHomeController> {
|
||||
onChanged: (bool value) {
|
||||
controller.kr_toggleSwitch(value);
|
||||
},
|
||||
activeTrackColor: Colors.blue,
|
||||
activeColor: Colors.blue,
|
||||
),
|
||||
],
|
||||
),
|
||||
|
||||
@ -411,7 +411,7 @@ class KRSettingView extends GetView<KRSettingController> {
|
||||
() => CupertinoSwitch(
|
||||
value: value.value,
|
||||
onChanged: onChanged,
|
||||
activeTrackColor: Colors.blue,
|
||||
activeColor: Colors.blue,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
1
libcore
Submodule
1
libcore
Submodule
@ -0,0 +1 @@
|
||||
Subproject commit f993a57755c37e08b02042037cbbf508c66c51f9
|
||||
2
libcore/.gitattributes
vendored
2
libcore/.gitattributes
vendored
@ -1,2 +0,0 @@
|
||||
*.h linguist-detectable=false
|
||||
*.c linguist-detectable=false
|
||||
23
libcore/.github/change_version.sh
vendored
23
libcore/.github/change_version.sh
vendored
@ -1,23 +0,0 @@
|
||||
#! /bin/bash
|
||||
|
||||
SED() { [[ "$OSTYPE" == "darwin"* ]] && sed -i '' "$@" || sed -i "$@"; }
|
||||
|
||||
echo "previous version was $(git describe --tags $(git rev-list --tags --max-count=1))"
|
||||
echo "WARNING: This operation will creates version tag and push to github"
|
||||
read -p "Version? (provide the next x.y.z semver) : " TAG
|
||||
echo $TAG
|
||||
[[ "$TAG" =~ ^[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,2}(\.dev)?$ ]] || { echo "Incorrect tag. e.g., 1.2.3 or 1.2.3.dev"; exit 1; }
|
||||
IFS="." read -r -a VERSION_ARRAY <<< "$TAG"
|
||||
VERSION_STR="${VERSION_ARRAY[0]}.${VERSION_ARRAY[1]}.${VERSION_ARRAY[2]}"
|
||||
BUILD_NUMBER=$(( ${VERSION_ARRAY[0]} * 10000 + ${VERSION_ARRAY[1]} * 100 + ${VERSION_ARRAY[2]} ))
|
||||
echo "version: ${VERSION_STR}+${BUILD_NUMBER}"
|
||||
SED -e "s|<key>CFBundleVersion</key>\s*<string>[^<]*</string>|<key>CFBundleVersion</key><string>${VERSION_STR}</string>|" Info.plist
|
||||
SED -e "s|<key>CFBundleShortVersionString</key>\s*<string>[^<]*</string>|<key>CFBundleShortVersionString</key><string>${VERSION_STR}</string>|" Info.plist
|
||||
SED "s|ENV VERSION=.*|ENV VERSION=v${TAG}|g" docker/Dockerfile
|
||||
git add Info.plist docker/Dockerfile
|
||||
git commit -m "release: version ${TAG}"
|
||||
echo "creating git tag : v${TAG}"
|
||||
git push
|
||||
git tag v${TAG}
|
||||
git push -u origin HEAD --tags
|
||||
echo "Github Actions will detect the new tag and release the new version."
|
||||
303
libcore/.github/workflows/build.yml
vendored
303
libcore/.github/workflows/build.yml
vendored
@ -1,303 +0,0 @@
|
||||
name: Build
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
upload-artifact:
|
||||
type: boolean
|
||||
default: true
|
||||
tag-name:
|
||||
type: string
|
||||
default: "draft"
|
||||
channel:
|
||||
type: string
|
||||
default: "dev"
|
||||
env:
|
||||
REGISTRY_IMAGE: ghcr.io/hiddify/hiddify-core
|
||||
|
||||
|
||||
jobs:
|
||||
update_wrt_hash:
|
||||
permissions: write-all
|
||||
runs-on: ubuntu-latest
|
||||
if: ${{ inputs.channel=='prod' }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- run: |
|
||||
git checkout -b main
|
||||
curl -L -o hiddify-core.tar.gz https://codeload.github.com/hiddify/hiddify-core/tar.gz/${{ inputs.tag-name }}
|
||||
HIDDIFY_CORE_WRT_HASH=$(sha256sum hiddify-core.tar.gz | cut -d' ' -f1)
|
||||
github_ref_name="${{ inputs.tag-name }}"
|
||||
IFS="." read -r -a VERSION_ARRAY <<< "${github_ref_name#v}"
|
||||
VERSION_STR="${VERSION_ARRAY[0]}.${VERSION_ARRAY[1]}.${VERSION_ARRAY[2]}"
|
||||
sed -i "s|PKG_VERSION:=.*|PKG_VERSION:=${VERSION_STR}|g" wrt/Makefile
|
||||
sed -i "s|PKG_HASH:=.*|PKG_HASH:=${HIDDIFY_CORE_WRT_HASH}|g" wrt/Makefile
|
||||
- uses: stefanzweifel/git-auto-commit-action@v5
|
||||
with:
|
||||
commit_message: "Update WRT package HASH."
|
||||
branch: main
|
||||
# push_options: --force
|
||||
build:
|
||||
permissions: write-all
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
job:
|
||||
- { name: 'hiddify-core-android', os: 'ubuntu-latest', target: 'android' }
|
||||
- { name: 'hiddify-core-linux-amd64', os: 'ubuntu-20.04', target: 'linux-amd64' }
|
||||
- { name: "hiddify-core-windows-amd64", os: 'ubuntu-latest', target: 'windows-amd64', aarch: 'x64' }
|
||||
- { name: "hiddify-core-macos-universal", os: 'macos-12', target: 'macos-universal' }
|
||||
- { name: "hiddify-core-ios", os: "macos-12", target: "ios" }
|
||||
# linux custom
|
||||
- {name: hiddify-cli-linux-amd64, goos: linux, goarch: amd64, goamd64: v1, target: 'linux-custom', os: 'ubuntu-20.04'}
|
||||
- {name: hiddify-cli-linux-amd64-v3, goos: linux, goarch: amd64, goamd64: v3, target: 'linux-custom', os: 'ubuntu-20.04'}
|
||||
- {name: hiddify-cli-linux-386, goos: linux, goarch: 386, target: 'linux-custom', os: 'ubuntu-20.04'}
|
||||
- {name: hiddify-cli-linux-arm64, goos: linux, goarch: arm64, target: 'linux-custom', os: 'ubuntu-20.04'}
|
||||
- {name: hiddify-cli-linux-armv5, goos: linux, goarch: arm, goarm: 5, target: 'linux-custom', os: 'ubuntu-20.04'}
|
||||
- {name: hiddify-cli-linux-armv6, goos: linux, goarch: arm, goarm: 6, target: 'linux-custom', os: 'ubuntu-20.04'}
|
||||
- {name: hiddify-cli-linux-armv7, goos: linux, goarch: arm, goarm: 7, target: 'linux-custom', os: 'ubuntu-20.04'}
|
||||
- {name: hiddify-cli-linux-mips-softfloat, goos: linux, goarch: mips, gomips: softfloat, target: 'linux-custom', os: 'ubuntu-20.04'}
|
||||
- {name: hiddify-cli-linux-mips-hardfloat, goos: linux, goarch: mips, gomips: hardfloat, target: 'linux-custom', os: 'ubuntu-20.04'}
|
||||
- {name: hiddify-cli-linux-mipsel-softfloat, goos: linux, goarch: mipsle, gomips: softfloat, target: 'linux-custom', os: 'ubuntu-20.04'}
|
||||
- {name: hiddify-cli-linux-mipsel-hardfloat, goos: linux, goarch: mipsle, gomips: hardfloat, target: 'linux-custom', os: 'ubuntu-20.04'}
|
||||
- {name: hiddify-cli-linux-mips64, goos: linux, goarch: mips64, target: 'linux-custom', os: 'ubuntu-20.04'}
|
||||
- {name: hiddify-cli-linux-mips64el, goos: linux, goarch: mips64le, target: 'linux-custom', os: 'ubuntu-20.04'}
|
||||
- {name: hiddify-cli-linux-s390x, goos: linux, goarch: s390x, target: 'linux-custom', os: 'ubuntu-20.04'}
|
||||
|
||||
runs-on: ${{ matrix.job.os }}
|
||||
env:
|
||||
GOOS: ${{ matrix.job.goos }}
|
||||
GOARCH: ${{ matrix.job.goarch }}
|
||||
GOAMD64: ${{ matrix.job.goamd64 }}
|
||||
GOARM: ${{ matrix.job.goarm }}
|
||||
GOMIPS: ${{ matrix.job.gomips }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
check-latest: false
|
||||
|
||||
- name: Setup Java
|
||||
if: startsWith(matrix.job.target,'android')
|
||||
uses: actions/setup-java@v3
|
||||
with:
|
||||
distribution: 'zulu'
|
||||
java-version: '17'
|
||||
|
||||
- name: Setup NDK
|
||||
if: startsWith(matrix.job.target,'android')
|
||||
uses: nttld/setup-ndk@v1.4.0
|
||||
id: setup-ndk
|
||||
with:
|
||||
ndk-version: r26b
|
||||
add-to-path: true
|
||||
local-cache: false
|
||||
link-to-sdk: true
|
||||
|
||||
- name: Setup MinGW
|
||||
if: startsWith(matrix.job.target,'windows')
|
||||
uses: egor-tensin/setup-mingw@v2
|
||||
with:
|
||||
platform: ${{ matrix.job.aarch }}
|
||||
- name: Setup macos
|
||||
if: startsWith(matrix.job.target,'macos') || startsWith(matrix.job.target,'ios')
|
||||
run: |
|
||||
brew install create-dmg tree coreutils
|
||||
|
||||
- name: Build
|
||||
run: |
|
||||
make -j$(($(nproc) + 1)) ${{ matrix.job.target }}
|
||||
|
||||
- name: zip
|
||||
run: |
|
||||
tree
|
||||
rm -f /*.h */*.h
|
||||
rm ./hiddify-libcore*sources* ||echo "no source"
|
||||
rm ./hiddify-libcore-macos-a*.dylib || echo "no macos arm and amd"
|
||||
files=$(ls | grep -E '^(libcore\.(dll|so|dylib|aar)|webui|Libcore.xcframework|lib|HiddifyCli(\.exe)?)$')
|
||||
echo tar -czvf ${{ matrix.job.name }}.tar.gz $files
|
||||
tar -czvf ${{ matrix.job.name }}.tar.gz $files
|
||||
|
||||
working-directory: bin
|
||||
- uses: actions/upload-artifact@v4
|
||||
if: ${{ success() }}
|
||||
with:
|
||||
name: ${{ matrix.job.name }}
|
||||
path: bin/*.tar.gz
|
||||
retention-days: 1
|
||||
|
||||
|
||||
upload-prerelease:
|
||||
permissions: write-all
|
||||
if: ${{ inputs.upload-artifact }}
|
||||
needs: [build]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
merge-multiple: true
|
||||
pattern: hiddify-*
|
||||
path: bin/
|
||||
|
||||
- name: Display Files Structure
|
||||
run: tree
|
||||
working-directory: bin
|
||||
|
||||
- name: Delete Current Release Assets
|
||||
uses: 8Mi-Tech/delete-release-assets-action@main
|
||||
with:
|
||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
tag: 'draft'
|
||||
deleteOnlyFromDrafts: false
|
||||
|
||||
- name: Create or Update Draft Release
|
||||
uses: softprops/action-gh-release@v1
|
||||
if: ${{ success() }}
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
files: ./bin/*.tar.gz
|
||||
name: 'draft'
|
||||
tag_name: 'draft'
|
||||
prerelease: true
|
||||
|
||||
upload-release:
|
||||
permissions: write-all
|
||||
if: ${{ inputs.channel=='prod' }}
|
||||
needs: [build]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
merge-multiple: true
|
||||
pattern: hiddify-*
|
||||
path: bin/
|
||||
|
||||
- name: Display Files Structure
|
||||
run: ls -R
|
||||
working-directory: bin
|
||||
|
||||
- name: Upload Release
|
||||
uses: softprops/action-gh-release@v1
|
||||
if: ${{ success() }}
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
tag_name: ${{ inputs.tag-name }}
|
||||
|
||||
files: bin/*.tar.gz
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
make-upload-docker:
|
||||
permissions: write-all
|
||||
if: ${{ inputs.channel=='prod' }}
|
||||
needs: [upload-release]
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: true
|
||||
matrix:
|
||||
platform:
|
||||
- linux/amd64
|
||||
# - linux/arm/v5
|
||||
- linux/arm/v6
|
||||
- linux/arm/v7
|
||||
- linux/arm64
|
||||
- linux/386
|
||||
# - linux/ppc64le
|
||||
# - linux/riscv64
|
||||
- linux/s390x
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Prepare
|
||||
run: |
|
||||
platform=${{ matrix.platform }}
|
||||
echo "PLATFORM_PAIR=${platform//\//-}" >> $GITHUB_ENV
|
||||
- name: Setup QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
- name: Setup Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.repository_owner }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
- name: Docker meta
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: ${{ env.REGISTRY_IMAGE }}
|
||||
- name: Build and push by digest
|
||||
id: build
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
platforms: ${{ matrix.platform }}
|
||||
context: ./docker/
|
||||
build-args: |
|
||||
BUILDKIT_CONTEXT_KEEP_GIT_DIR=1
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
outputs: type=image,name=${{ env.REGISTRY_IMAGE }},push-by-digest=true,name-canonical=true,push=true
|
||||
- name: Export digest
|
||||
run: |
|
||||
mkdir -p /tmp/digests
|
||||
digest="${{ steps.build.outputs.digest }}"
|
||||
touch "/tmp/digests/${digest#sha256:}"
|
||||
- name: Upload digest
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: digests-${{ env.PLATFORM_PAIR }}
|
||||
path: /tmp/digests/*
|
||||
if-no-files-found: error
|
||||
retention-days: 1
|
||||
merge:
|
||||
permissions: write-all
|
||||
runs-on: ubuntu-latest
|
||||
needs:
|
||||
- make-upload-docker
|
||||
env:
|
||||
LATEST: ${{ endsWith(inputs.tag-name , 'dev') && 'beta' ||'latest'}}
|
||||
steps:
|
||||
- name: Download digests
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
path: /tmp/digests
|
||||
pattern: digests-*
|
||||
merge-multiple: true
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.repository_owner }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
- name: Create manifest list and push
|
||||
working-directory: /tmp/digests
|
||||
run: |
|
||||
docker buildx imagetools create \
|
||||
-t "${{ env.REGISTRY_IMAGE }}:${{ env.LATEST }}" \
|
||||
-t "${{ env.REGISTRY_IMAGE }}:${{ inputs.tag-name }}" \
|
||||
$(printf '${{ env.REGISTRY_IMAGE }}@sha256:%s ' *)
|
||||
- name: Inspect image
|
||||
|
||||
run: |
|
||||
docker buildx imagetools inspect ${{ env.REGISTRY_IMAGE }}:${{ env.LATEST }}
|
||||
docker buildx imagetools inspect ${{ env.REGISTRY_IMAGE }}:${{ inputs.tag-name }}
|
||||
32
libcore/.github/workflows/ci.yml
vendored
32
libcore/.github/workflows/ci.yml
vendored
@ -1,32 +0,0 @@
|
||||
name: CI
|
||||
on:
|
||||
pull_request:
|
||||
paths-ignore:
|
||||
- '**.md'
|
||||
- 'docs/**'
|
||||
- '.vscode/'
|
||||
- 'appcast.xml'
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- dev
|
||||
- android-fix-action-bug
|
||||
paths-ignore:
|
||||
- '**.md'
|
||||
- 'docs/**'
|
||||
- '.vscode/'
|
||||
- 'appcast.xml'
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
run:
|
||||
uses: ./.github/workflows/build.yml
|
||||
secrets: inherit
|
||||
permissions: write-all
|
||||
if: "${{!contains(github.event.head_commit.message, 'release: version')}}"
|
||||
with:
|
||||
upload-artifact: ${{ github.event_name == 'push' }}
|
||||
|
||||
20
libcore/.github/workflows/release.yml
vendored
20
libcore/.github/workflows/release.yml
vendored
@ -1,20 +0,0 @@
|
||||
name: Release
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v[0-9]+.[0-9]+.[0-9]+'
|
||||
- 'v[0-9]+.[0-9]+.[0-9]+.*'
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
build-release:
|
||||
uses: ./.github/workflows/build.yml
|
||||
secrets: inherit
|
||||
permissions: write-all
|
||||
with:
|
||||
upload-artifact: true
|
||||
tag-name: "${{ github.ref_name }}"
|
||||
channel: "${{ github.ref_type == 'tag' && endsWith(github.ref_name, 'dev') && 'dev' || github.ref_type != 'tag' && 'dev' || 'prod' }}"
|
||||
12
libcore/.gitignore
vendored
12
libcore/.gitignore
vendored
@ -1,12 +0,0 @@
|
||||
/bin/*
|
||||
!/bin/.gitkeep
|
||||
.build
|
||||
.idea
|
||||
cert
|
||||
**/*.log
|
||||
.DS_Store
|
||||
|
||||
**/*.syso
|
||||
node_modules
|
||||
*.db
|
||||
*.json
|
||||
@ -1,10 +0,0 @@
|
||||
{
|
||||
"overrides": [
|
||||
{
|
||||
"files": ".github/**",
|
||||
"options": {
|
||||
"singleQuote": true
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@ -1,9 +0,0 @@
|
||||
.git
|
||||
|
||||
.build
|
||||
.idea
|
||||
|
||||
**/*.log
|
||||
.DS_Store
|
||||
|
||||
**/*.syso
|
||||
@ -1,26 +0,0 @@
|
||||
Hiddify uses [Go](https://go.dev), make sure that you have the correct version installed before starting development. You can use the following commands to check your installed version:
|
||||
|
||||
|
||||
```shell
|
||||
$ go version
|
||||
|
||||
# example response
|
||||
go version go1.21.1 darwin/arm64
|
||||
```
|
||||
|
||||
### Working with the Go Code
|
||||
|
||||
> if you're not interested in building/contributing to the Go code, you can skip this section
|
||||
|
||||
The Go code for Hiddify can be found in the `libcore` folder, as a [git submodule](https://git-scm.com/book/en/v2/Git-Tools-Submodules) and in [core repository](https://github.com/hiddify/hiddify-next-core). The entrypoints for the desktop version are available in the [`libcore/custom`](https://github.com/hiddify/hiddify-next-core/tree/main/custom) folder and for the mobile version they can be found in the [`libcore/mobile`](https://github.com/hiddify/hiddify-next-core/tree/main/mobile) folder.
|
||||
|
||||
For the desktop version, we have to compile the Go code into a C shared library. We are providing a Makefile to generate the C shared libraries for all operating systems. The following Make commands will build libcore and copy the resulting output in [`libcore/bin`](https://github.com/hiddify/hiddify-next-core/tree/main/bin):
|
||||
|
||||
- `make windows-amd64`
|
||||
- `make linux-amd64`
|
||||
- `make macos-universal`
|
||||
|
||||
For the mobile version, we are using the [`gomobile`](https://github.com/golang/go/wiki/Mobile) tools. The following Make commands will build libcore for Android and iOS and copy the resulting output in [`libcore/bin`](https://github.com/hiddify/hiddify-next-core/tree/main/bin):
|
||||
|
||||
- `make android`
|
||||
- `make ios`
|
||||
@ -1,50 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>AvailableLibraries</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>BinaryPath</key>
|
||||
<string>Libcore.framework/Libcore</string>
|
||||
<key>LibraryIdentifier</key>
|
||||
<string>ios-arm64_x86_64-simulator</string>
|
||||
<key>LibraryPath</key>
|
||||
<string>Libcore.framework</string>
|
||||
<key>SupportedArchitectures</key>
|
||||
<array>
|
||||
<string>arm64</string>
|
||||
<string>x86_64</string>
|
||||
</array>
|
||||
<key>SupportedPlatform</key>
|
||||
<string>ios</string>
|
||||
<key>SupportedPlatformVariant</key>
|
||||
<string>simulator</string>
|
||||
</dict>
|
||||
<dict>
|
||||
<key>BinaryPath</key>
|
||||
<string>Libcore.framework/Libcore</string>
|
||||
<key>LibraryIdentifier</key>
|
||||
<string>ios-arm64</string>
|
||||
<key>LibraryPath</key>
|
||||
<string>Libcore.framework</string>
|
||||
<key>SupportedArchitectures</key>
|
||||
<array>
|
||||
<string>arm64</string>
|
||||
</array>
|
||||
<key>SupportedPlatform</key>
|
||||
<string>ios</string>
|
||||
</dict>
|
||||
</array>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>XFWK</string>
|
||||
<key>XCFrameworkFormatVersion</key>
|
||||
<string>1.0</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>ios.libcore.hiddify</string>
|
||||
<key>CFBundleShortVersionString</key><string>3.1.7</string>
|
||||
<key>CFBundleVersion</key><string>3.1.7</string>
|
||||
<key>MinimumOSVersion</key>
|
||||
<string>15.0</string>
|
||||
</dict>
|
||||
</plist>
|
||||
@ -1,699 +0,0 @@
|
||||
|
||||
# GNU GENERAL PUBLIC LICENSE v3
|
||||
|
||||
## Summary:
|
||||
Additional Permissions and Restrictions Under GNU GPL Version 3 Section 7
|
||||
- If you use extends this code, you should directly fork it from github.
|
||||
|
||||
- The forks of the app are not allowed to be listed on F-Droid or other app stores under the original name or original design.
|
||||
|
||||
- Any forks should be published open-source under the same license.
|
||||
|
||||
- Prior consent is required to publish a fork or utilize any part of this repository (github.com/hiddify/hiddify-next and github.com/hiddify/hiddify-next-core) in an application intended for publication on the App Store or for iOS/macOS platforms. (We reserve the right to modify this requirement in the future after completing development for iOS and macOS).
|
||||
- You need prior consent to publish a fork or use any part of this code in an application published in AppStore or publish for iOS or macOS. (We reserve the right to modify this requirement in the future after completing development for iOS and macOS).
|
||||
- You are free to:
|
||||
- Share — copy and redistribute the material in any medium or format with
|
||||
- Adapt — remix, transform, and build upon the material
|
||||
- Under the following terms:
|
||||
- Attribution — You must give appropriate credit, provide a link to the license, and indicate if changes were made. You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you or your use.
|
||||
|
||||
- NonCommercial — You may not use the material for commercial purposes. You can not even include ads in it.
|
||||
|
||||
- ShareAlike — If you remix, transform, or build upon the material, you must distribute your contributions under the same license as the original.
|
||||
|
||||
- Prior consent is required before utilizing any portion of this code for integration into an application intended for the App Store.
|
||||
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
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.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
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 <https://www.gnu.org/licenses/>.
|
||||
|
||||
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:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
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
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
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
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
107
libcore/Makefile
107
libcore/Makefile
@ -1,107 +0,0 @@
|
||||
.ONESHELL:
|
||||
PRODUCT_NAME=libcore
|
||||
BASENAME=$(PRODUCT_NAME)
|
||||
BINDIR=bin
|
||||
LIBNAME=$(PRODUCT_NAME)
|
||||
CLINAME=HiddifyCli
|
||||
|
||||
BRANCH=$(shell git branch --show-current)
|
||||
VERSION=$(shell git describe --tags || echo "unknown version")
|
||||
ifeq ($(OS),Windows_NT)
|
||||
Not available for Windows! use bash in WSL
|
||||
endif
|
||||
|
||||
TAGS=with_gvisor,with_quic,with_wireguard,with_ech,with_utls,with_clash_api,with_grpc
|
||||
IOS_ADD_TAGS=with_dhcp,with_low_memory,with_conntrack
|
||||
GOBUILDLIB=CGO_ENABLED=1 go build -trimpath -tags $(TAGS) -ldflags="-w -s" -buildmode=c-shared
|
||||
GOBUILDSRV=CGO_ENABLED=1 go build -ldflags "-s -w" -trimpath -tags $(TAGS)
|
||||
|
||||
.PHONY: protos
|
||||
protos:
|
||||
protoc --go_out=./ --go-grpc_out=./ --proto_path=hiddifyrpc hiddifyrpc/*.proto
|
||||
protoc --js_out=import_style=commonjs,binary:./extension/html/rpc/ --grpc-web_out=import_style=commonjs,mode=grpcwebtext:./extension/html/rpc/ --proto_path=hiddifyrpc hiddifyrpc/*.proto
|
||||
npx browserify extension/html/rpc/extension.js >extension/html/rpc.js
|
||||
|
||||
|
||||
lib_install:
|
||||
go install -v github.com/sagernet/gomobile/cmd/gomobile@v0.1.1
|
||||
go install -v github.com/sagernet/gomobile/cmd/gobind@v0.1.1
|
||||
npm install
|
||||
|
||||
headers:
|
||||
go build -buildmode=c-archive -o $(BINDIR)/$(LIBNAME).h ./custom
|
||||
|
||||
android: lib_install
|
||||
gomobile bind -v -androidapi=21 -javapkg=io.nekohasekai -libname=box -tags=$(TAGS) -trimpath -target=android -o $(BINDIR)/$(LIBNAME).aar github.com/sagernet/sing-box/experimental/libbox ./mobile
|
||||
|
||||
ios-full: lib_install
|
||||
gomobile bind -v -target ios,iossimulator,tvos,tvossimulator,macos -libname=box -tags=$(TAGS),$(IOS_ADD_TAGS) -trimpath -ldflags="-w -s" -o $(BINDIR)/$(PRODUCT_NAME).xcframework github.com/sagernet/sing-box/experimental/libbox ./mobile
|
||||
mv $(BINDIR)/$(PRODUCT_NAME).xcframework $(BINDIR)/$(LIBNAME).xcframework
|
||||
cp Libcore.podspec $(BINDIR)/$(LIBNAME).xcframework/
|
||||
|
||||
ios: lib_install
|
||||
gomobile bind -v -target ios -libname=box -tags=$(TAGS),$(IOS_ADD_TAGS) -trimpath -ldflags="-w -s" -o $(BINDIR)/Libcore.xcframework github.com/sagernet/sing-box/experimental/libbox ./mobile
|
||||
cp Info.plist $(BINDIR)/Libcore.xcframework/
|
||||
|
||||
|
||||
webui:
|
||||
curl -L -o webui.zip https://github.com/hiddify/Yacd-meta/archive/gh-pages.zip
|
||||
unzip -d ./ -q webui.zip
|
||||
rm webui.zip
|
||||
rm -rf bin/webui
|
||||
mv Yacd-meta-gh-pages bin/webui
|
||||
|
||||
.PHONY: build
|
||||
windows-amd64:
|
||||
curl http://localhost:18020/exit || echo "exited"
|
||||
env GOOS=windows GOARCH=amd64 CC=x86_64-w64-mingw32-gcc $(GOBUILDLIB) -o $(BINDIR)/$(LIBNAME).dll ./custom
|
||||
go install -mod=readonly github.com/akavel/rsrc@latest ||echo "rsrc error in installation"
|
||||
go run ./cli tunnel exit
|
||||
cp $(BINDIR)/$(LIBNAME).dll ./$(LIBNAME).dll
|
||||
$$(go env GOPATH)/bin/rsrc -ico ./assets/hiddify-cli.ico -o ./cli/bydll/cli.syso ||echo "rsrc error in syso"
|
||||
env GOOS=windows GOARCH=amd64 CC=x86_64-w64-mingw32-gcc CGO_LDFLAGS="$(LIBNAME).dll" $(GOBUILDSRV) -o $(BINDIR)/$(CLINAME).exe ./cli/bydll
|
||||
rm ./$(LIBNAME).dll
|
||||
make webui
|
||||
|
||||
|
||||
linux-amd64:
|
||||
mkdir -p $(BINDIR)/lib
|
||||
env GOOS=linux GOARCH=amd64 $(GOBUILDLIB) -o $(BINDIR)/lib/$(LIBNAME).so ./custom
|
||||
mkdir lib
|
||||
cp $(BINDIR)/lib/$(LIBNAME).so ./lib/$(LIBNAME).so
|
||||
env GOOS=linux GOARCH=amd64 CGO_LDFLAGS="./lib/$(LIBNAME).so" $(GOBUILDSRV) -o $(BINDIR)/$(CLINAME) ./cli/bydll
|
||||
rm -rf ./lib
|
||||
chmod +x $(BINDIR)/$(CLINAME)
|
||||
make webui
|
||||
|
||||
|
||||
linux-custom:
|
||||
mkdir -p $(BINDIR)/
|
||||
#env GOARCH=mips $(GOBUILDSRV) -o $(BINDIR)/$(CLINAME) ./cli/
|
||||
go build -ldflags "-s -w" -trimpath -tags $(TAGS) -o $(BINDIR)/$(CLINAME) ./cli/
|
||||
chmod +x $(BINDIR)/$(CLINAME)
|
||||
make webui
|
||||
|
||||
macos-amd64:
|
||||
env GOOS=darwin GOARCH=amd64 CGO_CFLAGS="-mmacosx-version-min=10.11" CGO_LDFLAGS="-mmacosx-version-min=10.11" CGO_ENABLED=1 go build -trimpath -tags $(TAGS),$(IOS_ADD_TAGS) -buildmode=c-shared -o $(BINDIR)/$(LIBNAME)-amd64.dylib ./custom
|
||||
macos-arm64:
|
||||
env GOOS=darwin GOARCH=arm64 CGO_CFLAGS="-mmacosx-version-min=10.11" CGO_LDFLAGS="-mmacosx-version-min=10.11" CGO_ENABLED=1 go build -trimpath -tags $(TAGS),$(IOS_ADD_TAGS) -buildmode=c-shared -o $(BINDIR)/$(LIBNAME)-arm64.dylib ./custom
|
||||
|
||||
macos-universal: macos-amd64 macos-arm64
|
||||
lipo -create $(BINDIR)/$(LIBNAME)-amd64.dylib $(BINDIR)/$(LIBNAME)-arm64.dylib -output $(BINDIR)/$(LIBNAME).dylib
|
||||
cp $(BINDIR)/$(LIBNAME).dylib ./$(LIBNAME).dylib
|
||||
env GOOS=darwin GOARCH=amd64 CGO_CFLAGS="-mmacosx-version-min=10.11" CGO_LDFLAGS="-mmacosx-version-min=10.11" CGO_LDFLAGS="bin/$(LIBNAME).dylib" CGO_ENABLED=1 $(GOBUILDSRV) -o $(BINDIR)/$(CLINAME) ./cli/bydll
|
||||
rm ./$(LIBNAME).dylib
|
||||
chmod +x $(BINDIR)/$(CLINAME)
|
||||
|
||||
clean:
|
||||
rm $(BINDIR)/*
|
||||
|
||||
|
||||
|
||||
|
||||
release: # Create a new tag for release.
|
||||
@bash -c '.github/change_version.sh'
|
||||
|
||||
|
||||
|
||||
@ -1,53 +0,0 @@
|
||||
# hiddify-core
|
||||
|
||||
|
||||
## Docker
|
||||
To Run our docker image see https://github.com/hiddify/hiddify-core/pkgs/container/hiddify-core
|
||||
|
||||
Docker
|
||||
```
|
||||
docker pull ghcr.io/hiddify/hiddify-core:latest
|
||||
```
|
||||
|
||||
Docker Compose
|
||||
```
|
||||
git clone https://github.com/hiddify/hiddify-core
|
||||
cd hiddify-core/docker
|
||||
docker-compose up
|
||||
```
|
||||
|
||||
## WRT
|
||||
...
|
||||
|
||||
## Extension
|
||||
|
||||
An extension is something that can be added to hiddify application by a third party. It will add capability to modify configs, do some extra action, show and receive data from users.
|
||||
|
||||
This extension will be shown in all Hiddify Platforms such as Android/macOS/Linux/Windows/iOS
|
||||
|
||||
[Create an extension](https://github.com/hiddify/hiddify-app-example-extension)
|
||||
|
||||
Features and Road map:
|
||||
|
||||
- [x] Add Third Party Extension capability
|
||||
- [x] Test Extension from Browser without any dependency to android/mac/.... `./cmd.sh extension` the open browser `https://127.0.0.1:12346`
|
||||
- [x] Show Custom UI from Extension `github.com/hiddify/hiddify-core/extension.UpdateUI()`
|
||||
- [x] Show Custom Dialog from Extension `github.com/hiddify/hiddify-core/extension.ShowDialog()`
|
||||
- [x] Show Alert Dialog from Extension `github.com/hiddify/hiddify-core/extension.ShowMessage()`
|
||||
- [x] Get Data from UI `github.com/hiddify/hiddify-core/extension.SubmitData()`
|
||||
- [x] Save Extension Data from `e.Base.Data`
|
||||
- [x] Load Extension Data to `e.Base.Data`
|
||||
- [x] Disable / Enable Extension
|
||||
- [x] Update user proxies before connecting `github.com/hiddify/hiddify-core/extension.BeforeAppConnect()`
|
||||
- [x] Run Tiny Independent Instance `github.com/hiddify/hiddify-core/extension/sdk.RunInstance()`
|
||||
- [x] Parse Any type of configs/url `github.com/hiddify/hiddify-core/extension/sdk.ParseConfig()`
|
||||
- [ ] ToDo: Add Support for MultiLanguage Interface
|
||||
- [ ] ToDo: Custom Extension Outbound
|
||||
- [ ] ToDo: Custom Extension Inbound
|
||||
- [ ] ToDo: Custom Extension ProxyConfig
|
||||
|
||||
Demo Screenshots from HTML:
|
||||
|
||||
<img width="531" alt="image" src="https://github.com/user-attachments/assets/0fbef76f-896f-4c45-a6b8-7a2687c47013">
|
||||
<img width="531" alt="image" src="https://github.com/user-attachments/assets/15bccfa0-d03e-4354-9368-241836d82948">
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 11 KiB |
Binary file not shown.
@ -1,36 +0,0 @@
|
||||
// +build cgo
|
||||
package bridge
|
||||
|
||||
// #include "stdint.h"
|
||||
// #include "include/dart_api_dl.c"
|
||||
//
|
||||
// // Go does not allow calling C function pointers directly. So we are
|
||||
// // forced to provide a trampoline.
|
||||
// bool GoDart_PostCObject(Dart_Port_DL port, Dart_CObject* obj) {
|
||||
// return Dart_PostCObject_DL(port, obj);
|
||||
// }
|
||||
import "C"
|
||||
import (
|
||||
"fmt"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
func InitializeDartApi(api unsafe.Pointer) {
|
||||
if C.Dart_InitializeApiDL(api) != 0 {
|
||||
panic("failed to initialize Dart DL C API: version mismatch. " +
|
||||
"must update include/ to match Dart SDK version")
|
||||
}
|
||||
}
|
||||
|
||||
func SendStringToPort(port int64, msg string) {
|
||||
var obj C.Dart_CObject
|
||||
obj._type = C.Dart_CObject_kString
|
||||
msg_obj := C.CString(msg) // go string -> char*s
|
||||
// union type, we do a force conversion
|
||||
ptr := unsafe.Pointer(&obj.value[0])
|
||||
*(**C.char)(ptr) = msg_obj
|
||||
ret := C.GoDart_PostCObject(C.Dart_Port_DL(port), &obj)
|
||||
if !ret {
|
||||
fmt.Println("ERROR: post to port ", port, " failed", msg)
|
||||
}
|
||||
}
|
||||
@ -1,11 +0,0 @@
|
||||
//go:build !cgo
|
||||
// +build !cgo
|
||||
|
||||
package bridge
|
||||
|
||||
import "unsafe"
|
||||
|
||||
func InitializeDartApi(api unsafe.Pointer) {
|
||||
}
|
||||
func SendStringToPort(port int64, msg string) {
|
||||
}
|
||||
@ -1,23 +0,0 @@
|
||||
# Copyright (c) 2021, the Dart project authors. Please see the AUTHORS file
|
||||
# for details. All rights reserved. Use of this source code is governed by a
|
||||
# BSD-style license that can be found in the LICENSE file.
|
||||
|
||||
import("../../sdk_args.gni")
|
||||
|
||||
# This rule copies header files to include/
|
||||
copy("copy_headers") {
|
||||
visibility = [ "../../sdk:copy_headers" ]
|
||||
|
||||
sources = [
|
||||
"dart_api.h",
|
||||
"dart_api_dl.c",
|
||||
"dart_api_dl.h",
|
||||
"dart_native_api.h",
|
||||
"dart_tools_api.h",
|
||||
"dart_version.h",
|
||||
"internal/dart_api_dl_impl.h",
|
||||
]
|
||||
|
||||
outputs =
|
||||
[ "$root_out_dir/$dart_sdk_output/include/{{source_target_relative}}" ]
|
||||
}
|
||||
@ -1,30 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2021, the Dart project authors. Please see the AUTHORS file
|
||||
* for details. All rights reserved. Use of this source code is governed by a
|
||||
* BSD-style license that can be found in the LICENSE file.
|
||||
*/
|
||||
|
||||
#ifndef RUNTIME_INCLUDE_ANALYZE_SNAPSHOT_API_H_
|
||||
#define RUNTIME_INCLUDE_ANALYZE_SNAPSHOT_API_H_
|
||||
|
||||
#include <stdint.h>
|
||||
#include <optional>
|
||||
|
||||
namespace dart {
|
||||
namespace snapshot_analyzer {
|
||||
typedef struct {
|
||||
const uint8_t* vm_snapshot_data;
|
||||
const uint8_t* vm_snapshot_instructions;
|
||||
const uint8_t* vm_isolate_data;
|
||||
const uint8_t* vm_isolate_instructions;
|
||||
} Dart_SnapshotAnalyzerInformation;
|
||||
|
||||
void Dart_DumpSnapshotInformationAsJson(
|
||||
const Dart_SnapshotAnalyzerInformation& info,
|
||||
char** buffer,
|
||||
intptr_t* buffer_length);
|
||||
|
||||
} // namespace snapshot_analyzer
|
||||
} // namespace dart
|
||||
|
||||
#endif // RUNTIME_INCLUDE_ANALYZE_SNAPSHOT_API_H_
|
||||
@ -1,69 +0,0 @@
|
||||
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
|
||||
// for details. All rights reserved. Use of this source code is governed by a
|
||||
// BSD-style license that can be found in the LICENSE file.
|
||||
|
||||
#ifndef RUNTIME_INCLUDE_BIN_DART_IO_API_H_
|
||||
#define RUNTIME_INCLUDE_BIN_DART_IO_API_H_
|
||||
|
||||
#include "dart_tools_api.h"
|
||||
|
||||
namespace dart {
|
||||
namespace bin {
|
||||
|
||||
// Bootstraps 'dart:io'.
|
||||
void BootstrapDartIo();
|
||||
|
||||
// Cleans up 'dart:io'.
|
||||
void CleanupDartIo();
|
||||
|
||||
// Lets dart:io know where the system temporary directory is located.
|
||||
// Currently only wired up on Android.
|
||||
void SetSystemTempDirectory(const char* system_temp);
|
||||
|
||||
// Tells the system whether to capture Stdout events.
|
||||
void SetCaptureStdout(bool value);
|
||||
|
||||
// Tells the system whether to capture Stderr events.
|
||||
void SetCaptureStderr(bool value);
|
||||
|
||||
// Should Stdout events be captured?
|
||||
bool ShouldCaptureStdout();
|
||||
|
||||
// Should Stderr events be captured?
|
||||
bool ShouldCaptureStderr();
|
||||
|
||||
// Set the executable name used by Platform.executable.
|
||||
void SetExecutableName(const char* executable_name);
|
||||
|
||||
// Set the arguments used by Platform.executableArguments.
|
||||
void SetExecutableArguments(int script_index, char** argv);
|
||||
|
||||
// Set dart:io implementation specific fields of Dart_EmbedderInformation.
|
||||
void GetIOEmbedderInformation(Dart_EmbedderInformation* info);
|
||||
|
||||
// Appropriate to assign to Dart_InitializeParams.file_open/read/write/close.
|
||||
void* OpenFile(const char* name, bool write);
|
||||
void ReadFile(uint8_t** data, intptr_t* file_len, void* stream);
|
||||
void WriteFile(const void* buffer, intptr_t num_bytes, void* stream);
|
||||
void CloseFile(void* stream);
|
||||
|
||||
// Generates 'length' random bytes into 'buffer'. Returns true on success
|
||||
// and false on failure. This is appropriate to assign to
|
||||
// Dart_InitializeParams.entropy_source.
|
||||
bool GetEntropy(uint8_t* buffer, intptr_t length);
|
||||
|
||||
// Performs a lookup of the I/O Dart_NativeFunction with a specified 'name' and
|
||||
// 'argument_count'. Returns NULL if no I/O native function with a matching
|
||||
// name and parameter count is found.
|
||||
Dart_NativeFunction LookupIONative(Dart_Handle name,
|
||||
int argument_count,
|
||||
bool* auto_setup_scope);
|
||||
|
||||
// Returns the symbol for I/O native function 'nf'. Returns NULL if 'nf' is not
|
||||
// a valid I/O native function.
|
||||
const uint8_t* LookupIONativeSymbol(Dart_NativeFunction nf);
|
||||
|
||||
} // namespace bin
|
||||
} // namespace dart
|
||||
|
||||
#endif // RUNTIME_INCLUDE_BIN_DART_IO_API_H_
|
||||
File diff suppressed because it is too large
Load Diff
@ -1,79 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file
|
||||
* for details. All rights reserved. Use of this source code is governed by a
|
||||
* BSD-style license that can be found in the LICENSE file.
|
||||
*/
|
||||
|
||||
#include "dart_api_dl.h" /* NOLINT */
|
||||
#include "dart_version.h" /* NOLINT */
|
||||
#include "internal/dart_api_dl_impl.h" /* NOLINT */
|
||||
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
#define DART_API_DL_DEFINITIONS(name, R, A) name##_Type name##_DL = NULL;
|
||||
|
||||
DART_API_ALL_DL_SYMBOLS(DART_API_DL_DEFINITIONS)
|
||||
DART_API_DEPRECATED_DL_SYMBOLS(DART_API_DL_DEFINITIONS)
|
||||
|
||||
#undef DART_API_DL_DEFINITIONS
|
||||
|
||||
typedef void* DartApiEntry_function;
|
||||
|
||||
DartApiEntry_function FindFunctionPointer(const DartApiEntry* entries,
|
||||
const char* name) {
|
||||
while (entries->name != NULL) {
|
||||
if (strcmp(entries->name, name) == 0) return entries->function;
|
||||
entries++;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
DART_EXPORT void Dart_UpdateExternalSize_Deprecated(
|
||||
Dart_WeakPersistentHandle object, intptr_t external_size) {
|
||||
printf("Dart_UpdateExternalSize is a nop, it has been deprecated\n");
|
||||
}
|
||||
|
||||
DART_EXPORT void Dart_UpdateFinalizableExternalSize_Deprecated(
|
||||
Dart_FinalizableHandle object,
|
||||
Dart_Handle strong_ref_to_object,
|
||||
intptr_t external_allocation_size) {
|
||||
printf("Dart_UpdateFinalizableExternalSize is a nop, "
|
||||
"it has been deprecated\n");
|
||||
}
|
||||
|
||||
intptr_t Dart_InitializeApiDL(void* data) {
|
||||
DartApi* dart_api_data = (DartApi*)data;
|
||||
|
||||
if (dart_api_data->major != DART_API_DL_MAJOR_VERSION) {
|
||||
// If the DartVM we're running on does not have the same version as this
|
||||
// file was compiled against, refuse to initialize. The symbols are not
|
||||
// compatible.
|
||||
return -1;
|
||||
}
|
||||
// Minor versions are allowed to be different.
|
||||
// If the DartVM has a higher minor version, it will provide more symbols
|
||||
// than we initialize here.
|
||||
// If the DartVM has a lower minor version, it will not provide all symbols.
|
||||
// In that case, we leave the missing symbols un-initialized. Those symbols
|
||||
// should not be used by the Dart and native code. The client is responsible
|
||||
// for checking the minor version number himself based on which symbols it
|
||||
// is using.
|
||||
// (If we would error out on this case, recompiling native code against a
|
||||
// newer SDK would break all uses on older SDKs, which is too strict.)
|
||||
|
||||
const DartApiEntry* dart_api_function_pointers = dart_api_data->functions;
|
||||
|
||||
#define DART_API_DL_INIT(name, R, A) \
|
||||
name##_DL = \
|
||||
(name##_Type)(FindFunctionPointer(dart_api_function_pointers, #name));
|
||||
DART_API_ALL_DL_SYMBOLS(DART_API_DL_INIT)
|
||||
#undef DART_API_DL_INIT
|
||||
|
||||
#define DART_API_DEPRECATED_DL_INIT(name, R, A) \
|
||||
name##_DL = name##_Deprecated;
|
||||
DART_API_DEPRECATED_DL_SYMBOLS(DART_API_DEPRECATED_DL_INIT)
|
||||
#undef DART_API_DEPRECATED_DL_INIT
|
||||
|
||||
return 0;
|
||||
}
|
||||
@ -1,162 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file
|
||||
* for details. All rights reserved. Use of this source code is governed by a
|
||||
* BSD-style license that can be found in the LICENSE file.
|
||||
*/
|
||||
|
||||
#ifndef RUNTIME_INCLUDE_DART_API_DL_H_
|
||||
#define RUNTIME_INCLUDE_DART_API_DL_H_
|
||||
|
||||
#include "dart_api.h" /* NOLINT */
|
||||
#include "dart_native_api.h" /* NOLINT */
|
||||
|
||||
/** \mainpage Dynamically Linked Dart API
|
||||
*
|
||||
* This exposes a subset of symbols from dart_api.h and dart_native_api.h
|
||||
* available in every Dart embedder through dynamic linking.
|
||||
*
|
||||
* All symbols are postfixed with _DL to indicate that they are dynamically
|
||||
* linked and to prevent conflicts with the original symbol.
|
||||
*
|
||||
* Link `dart_api_dl.c` file into your library and invoke
|
||||
* `Dart_InitializeApiDL` with `NativeApi.initializeApiDLData`.
|
||||
*/
|
||||
|
||||
DART_EXPORT intptr_t Dart_InitializeApiDL(void* data);
|
||||
|
||||
// ============================================================================
|
||||
// IMPORTANT! Never update these signatures without properly updating
|
||||
// DART_API_DL_MAJOR_VERSION and DART_API_DL_MINOR_VERSION.
|
||||
//
|
||||
// Verbatim copy of `dart_native_api.h` and `dart_api.h` symbol names and types
|
||||
// to trigger compile-time errors if the symbols in those files are updated
|
||||
// without updating these.
|
||||
//
|
||||
// Function return and argument types, and typedefs are carbon copied. Structs
|
||||
// are typechecked nominally in C/C++, so they are not copied, instead a
|
||||
// comment is added to their definition.
|
||||
typedef int64_t Dart_Port_DL;
|
||||
|
||||
typedef void (*Dart_NativeMessageHandler_DL)(Dart_Port_DL dest_port_id,
|
||||
Dart_CObject* message);
|
||||
|
||||
// dart_native_api.h symbols can be called on any thread.
|
||||
#define DART_NATIVE_API_DL_SYMBOLS(F) \
|
||||
/***** dart_native_api.h *****/ \
|
||||
/* Dart_Port */ \
|
||||
F(Dart_PostCObject, bool, (Dart_Port_DL port_id, Dart_CObject * message)) \
|
||||
F(Dart_PostInteger, bool, (Dart_Port_DL port_id, int64_t message)) \
|
||||
F(Dart_NewNativePort, Dart_Port_DL, \
|
||||
(const char* name, Dart_NativeMessageHandler_DL handler, \
|
||||
bool handle_concurrently)) \
|
||||
F(Dart_CloseNativePort, bool, (Dart_Port_DL native_port_id))
|
||||
|
||||
// dart_api.h symbols can only be called on Dart threads.
|
||||
#define DART_API_DL_SYMBOLS(F) \
|
||||
/***** dart_api.h *****/ \
|
||||
/* Errors */ \
|
||||
F(Dart_IsError, bool, (Dart_Handle handle)) \
|
||||
F(Dart_IsApiError, bool, (Dart_Handle handle)) \
|
||||
F(Dart_IsUnhandledExceptionError, bool, (Dart_Handle handle)) \
|
||||
F(Dart_IsCompilationError, bool, (Dart_Handle handle)) \
|
||||
F(Dart_IsFatalError, bool, (Dart_Handle handle)) \
|
||||
F(Dart_GetError, const char*, (Dart_Handle handle)) \
|
||||
F(Dart_ErrorHasException, bool, (Dart_Handle handle)) \
|
||||
F(Dart_ErrorGetException, Dart_Handle, (Dart_Handle handle)) \
|
||||
F(Dart_ErrorGetStackTrace, Dart_Handle, (Dart_Handle handle)) \
|
||||
F(Dart_NewApiError, Dart_Handle, (const char* error)) \
|
||||
F(Dart_NewCompilationError, Dart_Handle, (const char* error)) \
|
||||
F(Dart_NewUnhandledExceptionError, Dart_Handle, (Dart_Handle exception)) \
|
||||
F(Dart_PropagateError, void, (Dart_Handle handle)) \
|
||||
/* Dart_Handle, Dart_PersistentHandle, Dart_WeakPersistentHandle */ \
|
||||
F(Dart_HandleFromPersistent, Dart_Handle, (Dart_PersistentHandle object)) \
|
||||
F(Dart_HandleFromWeakPersistent, Dart_Handle, \
|
||||
(Dart_WeakPersistentHandle object)) \
|
||||
F(Dart_NewPersistentHandle, Dart_PersistentHandle, (Dart_Handle object)) \
|
||||
F(Dart_SetPersistentHandle, void, \
|
||||
(Dart_PersistentHandle obj1, Dart_Handle obj2)) \
|
||||
F(Dart_DeletePersistentHandle, void, (Dart_PersistentHandle object)) \
|
||||
F(Dart_NewWeakPersistentHandle, Dart_WeakPersistentHandle, \
|
||||
(Dart_Handle object, void* peer, intptr_t external_allocation_size, \
|
||||
Dart_HandleFinalizer callback)) \
|
||||
F(Dart_DeleteWeakPersistentHandle, void, (Dart_WeakPersistentHandle object)) \
|
||||
F(Dart_NewFinalizableHandle, Dart_FinalizableHandle, \
|
||||
(Dart_Handle object, void* peer, intptr_t external_allocation_size, \
|
||||
Dart_HandleFinalizer callback)) \
|
||||
F(Dart_DeleteFinalizableHandle, void, \
|
||||
(Dart_FinalizableHandle object, Dart_Handle strong_ref_to_object)) \
|
||||
/* Isolates */ \
|
||||
F(Dart_CurrentIsolate, Dart_Isolate, (void)) \
|
||||
F(Dart_ExitIsolate, void, (void)) \
|
||||
F(Dart_EnterIsolate, void, (Dart_Isolate)) \
|
||||
/* Dart_Port */ \
|
||||
F(Dart_Post, bool, (Dart_Port_DL port_id, Dart_Handle object)) \
|
||||
F(Dart_NewSendPort, Dart_Handle, (Dart_Port_DL port_id)) \
|
||||
F(Dart_SendPortGetId, Dart_Handle, \
|
||||
(Dart_Handle port, Dart_Port_DL * port_id)) \
|
||||
/* Scopes */ \
|
||||
F(Dart_EnterScope, void, (void)) \
|
||||
F(Dart_ExitScope, void, (void)) \
|
||||
/* Objects */ \
|
||||
F(Dart_IsNull, bool, (Dart_Handle))
|
||||
|
||||
// dart_api.h symbols that have been deprecated but are retained here
|
||||
// until we can make a breaking change bumping the major version number
|
||||
// (DART_API_DL_MAJOR_VERSION)
|
||||
#define DART_API_DEPRECATED_DL_SYMBOLS(F) \
|
||||
F(Dart_UpdateExternalSize, void, \
|
||||
(Dart_WeakPersistentHandle object, intptr_t external_allocation_size)) \
|
||||
F(Dart_UpdateFinalizableExternalSize, void, \
|
||||
(Dart_FinalizableHandle object, Dart_Handle strong_ref_to_object, \
|
||||
intptr_t external_allocation_size))
|
||||
|
||||
#define DART_API_ALL_DL_SYMBOLS(F) \
|
||||
DART_NATIVE_API_DL_SYMBOLS(F) \
|
||||
DART_API_DL_SYMBOLS(F)
|
||||
// IMPORTANT! Never update these signatures without properly updating
|
||||
// DART_API_DL_MAJOR_VERSION and DART_API_DL_MINOR_VERSION.
|
||||
//
|
||||
// End of verbatim copy.
|
||||
// ============================================================================
|
||||
|
||||
// Copy of definition of DART_EXPORT without 'used' attribute.
|
||||
//
|
||||
// The 'used' attribute cannot be used with DART_API_ALL_DL_SYMBOLS because
|
||||
// they are not function declarations, but variable declarations with a
|
||||
// function pointer type.
|
||||
//
|
||||
// The function pointer variables are initialized with the addresses of the
|
||||
// functions in the VM. If we were to use function declarations instead, we
|
||||
// would need to forward the call to the VM adding indirection.
|
||||
#if defined(__CYGWIN__)
|
||||
#error Tool chain and platform not supported.
|
||||
#elif defined(_WIN32)
|
||||
#if defined(DART_SHARED_LIB)
|
||||
#define DART_EXPORT_DL DART_EXTERN_C __declspec(dllexport)
|
||||
#else
|
||||
#define DART_EXPORT_DL DART_EXTERN_C
|
||||
#endif
|
||||
#else
|
||||
#if __GNUC__ >= 4
|
||||
#if defined(DART_SHARED_LIB)
|
||||
#define DART_EXPORT_DL DART_EXTERN_C __attribute__((visibility("default")))
|
||||
#else
|
||||
#define DART_EXPORT_DL DART_EXTERN_C
|
||||
#endif
|
||||
#else
|
||||
#error Tool chain not supported.
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#define DART_API_DL_DECLARATIONS(name, R, A) \
|
||||
typedef R(*name##_Type) A; \
|
||||
DART_EXPORT_DL name##_Type name##_DL;
|
||||
|
||||
DART_API_ALL_DL_SYMBOLS(DART_API_DL_DECLARATIONS)
|
||||
DART_API_DEPRECATED_DL_SYMBOLS(DART_API_DL_DECLARATIONS)
|
||||
|
||||
#undef DART_API_DL_DECLARATIONS
|
||||
|
||||
#undef DART_EXPORT_DL
|
||||
|
||||
#endif /* RUNTIME_INCLUDE_DART_API_DL_H_ */ /* NOLINT */
|
||||
@ -1,108 +0,0 @@
|
||||
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
|
||||
// for details. All rights reserved. Use of this source code is governed by a
|
||||
// BSD-style license that can be found in the LICENSE file.
|
||||
|
||||
#ifndef RUNTIME_INCLUDE_DART_EMBEDDER_API_H_
|
||||
#define RUNTIME_INCLUDE_DART_EMBEDDER_API_H_
|
||||
|
||||
#include "include/dart_api.h"
|
||||
#include "include/dart_tools_api.h"
|
||||
|
||||
namespace dart {
|
||||
namespace embedder {
|
||||
|
||||
// Initialize all subsystems of the embedder.
|
||||
//
|
||||
// Must be called before the `Dart_Initialize()` call to initialize the
|
||||
// Dart VM.
|
||||
//
|
||||
// Returns true on success and false otherwise, in which case error would
|
||||
// contain error message.
|
||||
DART_WARN_UNUSED_RESULT bool InitOnce(char** error);
|
||||
|
||||
// Cleans up all subsystems of the embedder.
|
||||
//
|
||||
// Must be called after the `Dart_Cleanup()` call to initialize the
|
||||
// Dart VM.
|
||||
void Cleanup();
|
||||
|
||||
// Common arguments that are passed to isolate creation callback and to
|
||||
// API methods that create isolates.
|
||||
struct IsolateCreationData {
|
||||
// URI for the main script that will be running in the isolate.
|
||||
const char* script_uri;
|
||||
|
||||
// Advisory name of the main method that will be run by isolate.
|
||||
// Only used for error messages.
|
||||
const char* main;
|
||||
|
||||
// Isolate creation flags. Might be absent.
|
||||
Dart_IsolateFlags* flags;
|
||||
|
||||
// Isolate group callback data.
|
||||
void* isolate_group_data;
|
||||
|
||||
// Isolate callback data.
|
||||
void* isolate_data;
|
||||
};
|
||||
|
||||
// Create and initialize kernel-service isolate. This method should be used
|
||||
// when VM invokes isolate creation callback with DART_KERNEL_ISOLATE_NAME as
|
||||
// script_uri.
|
||||
// The isolate is created from the given snapshot (might be kernel data or
|
||||
// app-jit snapshot).
|
||||
DART_WARN_UNUSED_RESULT Dart_Isolate
|
||||
CreateKernelServiceIsolate(const IsolateCreationData& data,
|
||||
const uint8_t* buffer,
|
||||
intptr_t buffer_size,
|
||||
char** error);
|
||||
|
||||
// Service isolate configuration.
|
||||
struct VmServiceConfiguration {
|
||||
enum {
|
||||
kBindHttpServerToAFreePort = 0,
|
||||
kDoNotAutoStartHttpServer = -1
|
||||
};
|
||||
|
||||
// Address to which HTTP server will be bound.
|
||||
const char* ip;
|
||||
|
||||
// Default port. See enum above for special values.
|
||||
int port;
|
||||
|
||||
// If non-null, connection information for the VM service will be output to a
|
||||
// file in JSON format at the location specified.
|
||||
const char* write_service_info_filename;
|
||||
|
||||
// TODO(vegorov) document these ones.
|
||||
bool dev_mode;
|
||||
bool deterministic;
|
||||
bool disable_auth_codes;
|
||||
};
|
||||
|
||||
// Create and initialize vm-service isolate from the given AOT snapshot, which
|
||||
// is expected to contain all necessary 'vm-service' libraries.
|
||||
// This method should be used when VM invokes isolate creation callback with
|
||||
// DART_VM_SERVICE_ISOLATE_NAME as script_uri.
|
||||
DART_WARN_UNUSED_RESULT Dart_Isolate
|
||||
CreateVmServiceIsolate(const IsolateCreationData& data,
|
||||
const VmServiceConfiguration& config,
|
||||
const uint8_t* isolate_data,
|
||||
const uint8_t* isolate_instr,
|
||||
char** error);
|
||||
|
||||
// Create and initialize vm-service isolate from the given kernel binary, which
|
||||
// is expected to contain all necessary 'vm-service' libraries.
|
||||
// This method should be used when VM invokes isolate creation callback with
|
||||
// DART_VM_SERVICE_ISOLATE_NAME as script_uri.
|
||||
DART_WARN_UNUSED_RESULT Dart_Isolate
|
||||
CreateVmServiceIsolateFromKernel(const IsolateCreationData& data,
|
||||
const VmServiceConfiguration& config,
|
||||
const uint8_t* kernel_buffer,
|
||||
intptr_t kernel_buffer_size,
|
||||
char** error);
|
||||
|
||||
} // namespace embedder
|
||||
} // namespace dart
|
||||
|
||||
#endif // RUNTIME_INCLUDE_DART_EMBEDDER_API_H_
|
||||
@ -1,207 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
|
||||
* for details. All rights reserved. Use of this source code is governed by a
|
||||
* BSD-style license that can be found in the LICENSE file.
|
||||
*/
|
||||
|
||||
#ifndef RUNTIME_INCLUDE_DART_NATIVE_API_H_
|
||||
#define RUNTIME_INCLUDE_DART_NATIVE_API_H_
|
||||
|
||||
#include "dart_api.h" /* NOLINT */
|
||||
|
||||
/*
|
||||
* ==========================================
|
||||
* Message sending/receiving from native code
|
||||
* ==========================================
|
||||
*/
|
||||
|
||||
/**
|
||||
* A Dart_CObject is used for representing Dart objects as native C
|
||||
* data outside the Dart heap. These objects are totally detached from
|
||||
* the Dart heap. Only a subset of the Dart objects have a
|
||||
* representation as a Dart_CObject.
|
||||
*
|
||||
* The string encoding in the 'value.as_string' is UTF-8.
|
||||
*
|
||||
* All the different types from dart:typed_data are exposed as type
|
||||
* kTypedData. The specific type from dart:typed_data is in the type
|
||||
* field of the as_typed_data structure. The length in the
|
||||
* as_typed_data structure is always in bytes.
|
||||
*
|
||||
* The data for kTypedData is copied on message send and ownership remains with
|
||||
* the caller. The ownership of data for kExternalTyped is passed to the VM on
|
||||
* message send and returned when the VM invokes the
|
||||
* Dart_HandleFinalizer callback; a non-NULL callback must be provided.
|
||||
*
|
||||
* Note that Dart_CObject_kNativePointer is intended for internal use by
|
||||
* dart:io implementation and has no connection to dart:ffi Pointer class.
|
||||
* It represents a pointer to a native resource of a known type.
|
||||
* The receiving side will only see this pointer as an integer and will not
|
||||
* see the specified finalizer.
|
||||
* The specified finalizer will only be invoked if the message is not delivered.
|
||||
*/
|
||||
typedef enum {
|
||||
Dart_CObject_kNull = 0,
|
||||
Dart_CObject_kBool,
|
||||
Dart_CObject_kInt32,
|
||||
Dart_CObject_kInt64,
|
||||
Dart_CObject_kDouble,
|
||||
Dart_CObject_kString,
|
||||
Dart_CObject_kArray,
|
||||
Dart_CObject_kTypedData,
|
||||
Dart_CObject_kExternalTypedData,
|
||||
Dart_CObject_kSendPort,
|
||||
Dart_CObject_kCapability,
|
||||
Dart_CObject_kNativePointer,
|
||||
Dart_CObject_kUnsupported,
|
||||
Dart_CObject_kUnmodifiableExternalTypedData,
|
||||
Dart_CObject_kNumberOfTypes
|
||||
} Dart_CObject_Type;
|
||||
// This enum is versioned by DART_API_DL_MAJOR_VERSION, only add at the end
|
||||
// and bump the DART_API_DL_MINOR_VERSION.
|
||||
|
||||
typedef struct _Dart_CObject {
|
||||
Dart_CObject_Type type;
|
||||
union {
|
||||
bool as_bool;
|
||||
int32_t as_int32;
|
||||
int64_t as_int64;
|
||||
double as_double;
|
||||
const char* as_string;
|
||||
struct {
|
||||
Dart_Port id;
|
||||
Dart_Port origin_id;
|
||||
} as_send_port;
|
||||
struct {
|
||||
int64_t id;
|
||||
} as_capability;
|
||||
struct {
|
||||
intptr_t length;
|
||||
struct _Dart_CObject** values;
|
||||
} as_array;
|
||||
struct {
|
||||
Dart_TypedData_Type type;
|
||||
intptr_t length; /* in elements, not bytes */
|
||||
const uint8_t* values;
|
||||
} as_typed_data;
|
||||
struct {
|
||||
Dart_TypedData_Type type;
|
||||
intptr_t length; /* in elements, not bytes */
|
||||
uint8_t* data;
|
||||
void* peer;
|
||||
Dart_HandleFinalizer callback;
|
||||
} as_external_typed_data;
|
||||
struct {
|
||||
intptr_t ptr;
|
||||
intptr_t size;
|
||||
Dart_HandleFinalizer callback;
|
||||
} as_native_pointer;
|
||||
} value;
|
||||
} Dart_CObject;
|
||||
// This struct is versioned by DART_API_DL_MAJOR_VERSION, bump the version when
|
||||
// changing this struct.
|
||||
|
||||
/**
|
||||
* Posts a message on some port. The message will contain the Dart_CObject
|
||||
* object graph rooted in 'message'.
|
||||
*
|
||||
* While the message is being sent the state of the graph of Dart_CObject
|
||||
* structures rooted in 'message' should not be accessed, as the message
|
||||
* generation will make temporary modifications to the data. When the message
|
||||
* has been sent the graph will be fully restored.
|
||||
*
|
||||
* If true is returned, the message was enqueued, and finalizers for external
|
||||
* typed data will eventually run, even if the receiving isolate shuts down
|
||||
* before processing the message. If false is returned, the message was not
|
||||
* enqueued and ownership of external typed data in the message remains with the
|
||||
* caller.
|
||||
*
|
||||
* This function may be called on any thread when the VM is running (that is,
|
||||
* after Dart_Initialize has returned and before Dart_Cleanup has been called).
|
||||
*
|
||||
* \param port_id The destination port.
|
||||
* \param message The message to send.
|
||||
*
|
||||
* \return True if the message was posted.
|
||||
*/
|
||||
DART_EXPORT bool Dart_PostCObject(Dart_Port port_id, Dart_CObject* message);
|
||||
|
||||
/**
|
||||
* Posts a message on some port. The message will contain the integer 'message'.
|
||||
*
|
||||
* \param port_id The destination port.
|
||||
* \param message The message to send.
|
||||
*
|
||||
* \return True if the message was posted.
|
||||
*/
|
||||
DART_EXPORT bool Dart_PostInteger(Dart_Port port_id, int64_t message);
|
||||
|
||||
/**
|
||||
* A native message handler.
|
||||
*
|
||||
* This handler is associated with a native port by calling
|
||||
* Dart_NewNativePort.
|
||||
*
|
||||
* The message received is decoded into the message structure. The
|
||||
* lifetime of the message data is controlled by the caller. All the
|
||||
* data references from the message are allocated by the caller and
|
||||
* will be reclaimed when returning to it.
|
||||
*/
|
||||
typedef void (*Dart_NativeMessageHandler)(Dart_Port dest_port_id,
|
||||
Dart_CObject* message);
|
||||
|
||||
/**
|
||||
* Creates a new native port. When messages are received on this
|
||||
* native port, then they will be dispatched to the provided native
|
||||
* message handler.
|
||||
*
|
||||
* \param name The name of this port in debugging messages.
|
||||
* \param handler The C handler to run when messages arrive on the port.
|
||||
* \param handle_concurrently Is it okay to process requests on this
|
||||
* native port concurrently?
|
||||
*
|
||||
* \return If successful, returns the port id for the native port. In
|
||||
* case of error, returns ILLEGAL_PORT.
|
||||
*/
|
||||
DART_EXPORT Dart_Port Dart_NewNativePort(const char* name,
|
||||
Dart_NativeMessageHandler handler,
|
||||
bool handle_concurrently);
|
||||
/* TODO(turnidge): Currently handle_concurrently is ignored. */
|
||||
|
||||
/**
|
||||
* Closes the native port with the given id.
|
||||
*
|
||||
* The port must have been allocated by a call to Dart_NewNativePort.
|
||||
*
|
||||
* \param native_port_id The id of the native port to close.
|
||||
*
|
||||
* \return Returns true if the port was closed successfully.
|
||||
*/
|
||||
DART_EXPORT bool Dart_CloseNativePort(Dart_Port native_port_id);
|
||||
|
||||
/*
|
||||
* ==================
|
||||
* Verification Tools
|
||||
* ==================
|
||||
*/
|
||||
|
||||
/**
|
||||
* Forces all loaded classes and functions to be compiled eagerly in
|
||||
* the current isolate..
|
||||
*
|
||||
* TODO(turnidge): Document.
|
||||
*/
|
||||
DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle Dart_CompileAll(void);
|
||||
|
||||
/**
|
||||
* Finalizes all classes.
|
||||
*/
|
||||
DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle Dart_FinalizeAllClasses(void);
|
||||
|
||||
/* This function is intentionally undocumented.
|
||||
*
|
||||
* It should not be used outside internal tests.
|
||||
*/
|
||||
DART_EXPORT void* Dart_ExecuteInternalCommand(const char* command, void* arg);
|
||||
|
||||
#endif /* INCLUDE_DART_NATIVE_API_H_ */ /* NOLINT */
|
||||
@ -1,658 +0,0 @@
|
||||
// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file
|
||||
// for details. All rights reserved. Use of this source code is governed by a
|
||||
// BSD-style license that can be found in the LICENSE file.
|
||||
|
||||
#ifndef RUNTIME_INCLUDE_DART_TOOLS_API_H_
|
||||
#define RUNTIME_INCLUDE_DART_TOOLS_API_H_
|
||||
|
||||
#include "dart_api.h" /* NOLINT */
|
||||
|
||||
/** \mainpage Dart Tools Embedding API Reference
|
||||
*
|
||||
* This reference describes the Dart embedding API for tools. Tools include
|
||||
* a debugger, service protocol, and timeline.
|
||||
*
|
||||
* NOTE: The APIs described in this file are unstable and subject to change.
|
||||
*
|
||||
* This reference is generated from the header include/dart_tools_api.h.
|
||||
*/
|
||||
|
||||
/*
|
||||
* ========
|
||||
* Debugger
|
||||
* ========
|
||||
*/
|
||||
|
||||
/**
|
||||
* ILLEGAL_ISOLATE_ID is a number guaranteed never to be associated with a
|
||||
* valid isolate.
|
||||
*/
|
||||
#define ILLEGAL_ISOLATE_ID ILLEGAL_PORT
|
||||
|
||||
/**
|
||||
* ILLEGAL_ISOLATE_GROUP_ID is a number guaranteed never to be associated with a
|
||||
* valid isolate group.
|
||||
*/
|
||||
#define ILLEGAL_ISOLATE_GROUP_ID 0
|
||||
|
||||
/*
|
||||
* =======
|
||||
* Service
|
||||
* =======
|
||||
*/
|
||||
|
||||
/**
|
||||
* A service request callback function.
|
||||
*
|
||||
* These callbacks, registered by the embedder, are called when the VM receives
|
||||
* a service request it can't handle and the service request command name
|
||||
* matches one of the embedder registered handlers.
|
||||
*
|
||||
* The return value of the callback indicates whether the response
|
||||
* should be used as a regular result or an error result.
|
||||
* Specifically, if the callback returns true, a regular JSON-RPC
|
||||
* response is built in the following way:
|
||||
*
|
||||
* {
|
||||
* "jsonrpc": "2.0",
|
||||
* "result": <json_object>,
|
||||
* "id": <some sequence id>,
|
||||
* }
|
||||
*
|
||||
* If the callback returns false, a JSON-RPC error is built like this:
|
||||
*
|
||||
* {
|
||||
* "jsonrpc": "2.0",
|
||||
* "error": <json_object>,
|
||||
* "id": <some sequence id>,
|
||||
* }
|
||||
*
|
||||
* \param method The rpc method name.
|
||||
* \param param_keys Service requests can have key-value pair parameters. The
|
||||
* keys and values are flattened and stored in arrays.
|
||||
* \param param_values The values associated with the keys.
|
||||
* \param num_params The length of the param_keys and param_values arrays.
|
||||
* \param user_data The user_data pointer registered with this handler.
|
||||
* \param result A C string containing a valid JSON object. The returned
|
||||
* pointer will be freed by the VM by calling free.
|
||||
*
|
||||
* \return True if the result is a regular JSON-RPC response, false if the
|
||||
* result is a JSON-RPC error.
|
||||
*/
|
||||
typedef bool (*Dart_ServiceRequestCallback)(const char* method,
|
||||
const char** param_keys,
|
||||
const char** param_values,
|
||||
intptr_t num_params,
|
||||
void* user_data,
|
||||
const char** json_object);
|
||||
|
||||
/**
|
||||
* Register a Dart_ServiceRequestCallback to be called to handle
|
||||
* requests for the named rpc on a specific isolate. The callback will
|
||||
* be invoked with the current isolate set to the request target.
|
||||
*
|
||||
* \param method The name of the method that this callback is responsible for.
|
||||
* \param callback The callback to invoke.
|
||||
* \param user_data The user data passed to the callback.
|
||||
*
|
||||
* NOTE: If multiple callbacks with the same name are registered, only
|
||||
* the last callback registered will be remembered.
|
||||
*/
|
||||
DART_EXPORT void Dart_RegisterIsolateServiceRequestCallback(
|
||||
const char* method,
|
||||
Dart_ServiceRequestCallback callback,
|
||||
void* user_data);
|
||||
|
||||
/**
|
||||
* Register a Dart_ServiceRequestCallback to be called to handle
|
||||
* requests for the named rpc. The callback will be invoked without a
|
||||
* current isolate.
|
||||
*
|
||||
* \param method The name of the command that this callback is responsible for.
|
||||
* \param callback The callback to invoke.
|
||||
* \param user_data The user data passed to the callback.
|
||||
*
|
||||
* NOTE: If multiple callbacks with the same name are registered, only
|
||||
* the last callback registered will be remembered.
|
||||
*/
|
||||
DART_EXPORT void Dart_RegisterRootServiceRequestCallback(
|
||||
const char* method,
|
||||
Dart_ServiceRequestCallback callback,
|
||||
void* user_data);
|
||||
|
||||
/**
|
||||
* Embedder information which can be requested by the VM for internal or
|
||||
* reporting purposes.
|
||||
*
|
||||
* The pointers in this structure are not going to be cached or freed by the VM.
|
||||
*/
|
||||
|
||||
#define DART_EMBEDDER_INFORMATION_CURRENT_VERSION (0x00000001)
|
||||
|
||||
typedef struct {
|
||||
int32_t version;
|
||||
const char* name; // [optional] The name of the embedder
|
||||
int64_t current_rss; // [optional] the current RSS of the embedder
|
||||
int64_t max_rss; // [optional] the maximum RSS of the embedder
|
||||
} Dart_EmbedderInformation;
|
||||
|
||||
/**
|
||||
* Callback provided by the embedder that is used by the VM to request
|
||||
* information.
|
||||
*
|
||||
* \return Returns a pointer to a Dart_EmbedderInformation structure.
|
||||
* The embedder keeps the ownership of the structure and any field in it.
|
||||
* The embedder must ensure that the structure will remain valid until the
|
||||
* next invocation of the callback.
|
||||
*/
|
||||
typedef void (*Dart_EmbedderInformationCallback)(
|
||||
Dart_EmbedderInformation* info);
|
||||
|
||||
/**
|
||||
* Register a Dart_ServiceRequestCallback to be called to handle
|
||||
* requests for the named rpc. The callback will be invoked without a
|
||||
* current isolate.
|
||||
*
|
||||
* \param method The name of the command that this callback is responsible for.
|
||||
* \param callback The callback to invoke.
|
||||
* \param user_data The user data passed to the callback.
|
||||
*
|
||||
* NOTE: If multiple callbacks are registered, only the last callback registered
|
||||
* will be remembered.
|
||||
*/
|
||||
DART_EXPORT void Dart_SetEmbedderInformationCallback(
|
||||
Dart_EmbedderInformationCallback callback);
|
||||
|
||||
/**
|
||||
* Invoke a vm-service method and wait for its result.
|
||||
*
|
||||
* \param request_json The utf8-encoded json-rpc request.
|
||||
* \param request_json_length The length of the json-rpc request.
|
||||
*
|
||||
* \param response_json The returned utf8-encoded json response, must be
|
||||
* free()ed by caller.
|
||||
* \param response_json_length The length of the returned json response.
|
||||
* \param error An optional error, must be free()ed by caller.
|
||||
*
|
||||
* \return Whether the call was successfully performed.
|
||||
*
|
||||
* NOTE: This method does not need a current isolate and must not have the
|
||||
* vm-isolate being the current isolate. It must be called after
|
||||
* Dart_Initialize() and before Dart_Cleanup().
|
||||
*/
|
||||
DART_EXPORT bool Dart_InvokeVMServiceMethod(uint8_t* request_json,
|
||||
intptr_t request_json_length,
|
||||
uint8_t** response_json,
|
||||
intptr_t* response_json_length,
|
||||
char** error);
|
||||
|
||||
/*
|
||||
* ========
|
||||
* Event Streams
|
||||
* ========
|
||||
*/
|
||||
|
||||
/**
|
||||
* A callback invoked when the VM service gets a request to listen to
|
||||
* some stream.
|
||||
*
|
||||
* \return Returns true iff the embedder supports the named stream id.
|
||||
*/
|
||||
typedef bool (*Dart_ServiceStreamListenCallback)(const char* stream_id);
|
||||
|
||||
/**
|
||||
* A callback invoked when the VM service gets a request to cancel
|
||||
* some stream.
|
||||
*/
|
||||
typedef void (*Dart_ServiceStreamCancelCallback)(const char* stream_id);
|
||||
|
||||
/**
|
||||
* Adds VM service stream callbacks.
|
||||
*
|
||||
* \param listen_callback A function pointer to a listen callback function.
|
||||
* A listen callback function should not be already set when this function
|
||||
* is called. A NULL value removes the existing listen callback function
|
||||
* if any.
|
||||
*
|
||||
* \param cancel_callback A function pointer to a cancel callback function.
|
||||
* A cancel callback function should not be already set when this function
|
||||
* is called. A NULL value removes the existing cancel callback function
|
||||
* if any.
|
||||
*
|
||||
* \return Success if the callbacks were added. Otherwise, returns an
|
||||
* error handle.
|
||||
*/
|
||||
DART_EXPORT char* Dart_SetServiceStreamCallbacks(
|
||||
Dart_ServiceStreamListenCallback listen_callback,
|
||||
Dart_ServiceStreamCancelCallback cancel_callback);
|
||||
|
||||
/**
|
||||
* Sends a data event to clients of the VM Service.
|
||||
*
|
||||
* A data event is used to pass an array of bytes to subscribed VM
|
||||
* Service clients. For example, in the standalone embedder, this is
|
||||
* function used to provide WriteEvents on the Stdout and Stderr
|
||||
* streams.
|
||||
*
|
||||
* If the embedder passes in a stream id for which no client is
|
||||
* subscribed, then the event is ignored.
|
||||
*
|
||||
* \param stream_id The id of the stream on which to post the event.
|
||||
*
|
||||
* \param event_kind A string identifying what kind of event this is.
|
||||
* For example, 'WriteEvent'.
|
||||
*
|
||||
* \param bytes A pointer to an array of bytes.
|
||||
*
|
||||
* \param bytes_length The length of the byte array.
|
||||
*
|
||||
* \return NULL if the arguments are well formed. Otherwise, returns an
|
||||
* error string. The caller is responsible for freeing the error message.
|
||||
*/
|
||||
DART_EXPORT char* Dart_ServiceSendDataEvent(const char* stream_id,
|
||||
const char* event_kind,
|
||||
const uint8_t* bytes,
|
||||
intptr_t bytes_length);
|
||||
|
||||
/*
|
||||
* ========
|
||||
* Reload support
|
||||
* ========
|
||||
*
|
||||
* These functions are used to implement reloading in the Dart VM.
|
||||
* This is an experimental feature, so embedders should be prepared
|
||||
* for these functions to change.
|
||||
*/
|
||||
|
||||
/**
|
||||
* A callback which determines whether the file at some url has been
|
||||
* modified since some time. If the file cannot be found, true should
|
||||
* be returned.
|
||||
*/
|
||||
typedef bool (*Dart_FileModifiedCallback)(const char* url, int64_t since);
|
||||
|
||||
DART_EXPORT char* Dart_SetFileModifiedCallback(
|
||||
Dart_FileModifiedCallback file_modified_callback);
|
||||
|
||||
/**
|
||||
* Returns true if isolate is currently reloading.
|
||||
*/
|
||||
DART_EXPORT bool Dart_IsReloading();
|
||||
|
||||
/*
|
||||
* ========
|
||||
* Timeline
|
||||
* ========
|
||||
*/
|
||||
|
||||
/**
|
||||
* Enable tracking of specified timeline category. This is operational
|
||||
* only when systrace timeline functionality is turned on.
|
||||
*
|
||||
* \param categories A comma separated list of categories that need to
|
||||
* be enabled, the categories are
|
||||
* "all" : All categories
|
||||
* "API" - Execution of Dart C API functions
|
||||
* "Compiler" - Execution of Dart JIT compiler
|
||||
* "CompilerVerbose" - More detailed Execution of Dart JIT compiler
|
||||
* "Dart" - Execution of Dart code
|
||||
* "Debugger" - Execution of Dart debugger
|
||||
* "Embedder" - Execution of Dart embedder code
|
||||
* "GC" - Execution of Dart Garbage Collector
|
||||
* "Isolate" - Dart Isolate lifecycle execution
|
||||
* "VM" - Execution in Dart VM runtime code
|
||||
* "" - None
|
||||
*
|
||||
* When "all" is specified all the categories are enabled.
|
||||
* When a comma separated list of categories is specified, the categories
|
||||
* that are specified will be enabled and the rest will be disabled.
|
||||
* When "" is specified all the categories are disabled.
|
||||
* The category names are case sensitive.
|
||||
* eg: Dart_EnableTimelineCategory("all");
|
||||
* Dart_EnableTimelineCategory("GC,API,Isolate");
|
||||
* Dart_EnableTimelineCategory("GC,Debugger,Dart");
|
||||
*
|
||||
* \return True if the categories were successfully enabled, False otherwise.
|
||||
*/
|
||||
DART_EXPORT bool Dart_SetEnabledTimelineCategory(const char* categories);
|
||||
|
||||
/**
|
||||
* Returns a timestamp in microseconds. This timestamp is suitable for
|
||||
* passing into the timeline system, and uses the same monotonic clock
|
||||
* as dart:developer's Timeline.now.
|
||||
*
|
||||
* \return A timestamp that can be passed to the timeline system.
|
||||
*/
|
||||
DART_EXPORT int64_t Dart_TimelineGetMicros();
|
||||
|
||||
/**
|
||||
* Returns a raw timestamp in from the monotonic clock.
|
||||
*
|
||||
* \return A raw timestamp from the monotonic clock.
|
||||
*/
|
||||
DART_EXPORT int64_t Dart_TimelineGetTicks();
|
||||
|
||||
/**
|
||||
* Returns the frequency of the monotonic clock.
|
||||
*
|
||||
* \return The frequency of the monotonic clock.
|
||||
*/
|
||||
DART_EXPORT int64_t Dart_TimelineGetTicksFrequency();
|
||||
|
||||
typedef enum {
|
||||
Dart_Timeline_Event_Begin, // Phase = 'B'.
|
||||
Dart_Timeline_Event_End, // Phase = 'E'.
|
||||
Dart_Timeline_Event_Instant, // Phase = 'i'.
|
||||
Dart_Timeline_Event_Duration, // Phase = 'X'.
|
||||
Dart_Timeline_Event_Async_Begin, // Phase = 'b'.
|
||||
Dart_Timeline_Event_Async_End, // Phase = 'e'.
|
||||
Dart_Timeline_Event_Async_Instant, // Phase = 'n'.
|
||||
Dart_Timeline_Event_Counter, // Phase = 'C'.
|
||||
Dart_Timeline_Event_Flow_Begin, // Phase = 's'.
|
||||
Dart_Timeline_Event_Flow_Step, // Phase = 't'.
|
||||
Dart_Timeline_Event_Flow_End, // Phase = 'f'.
|
||||
} Dart_Timeline_Event_Type;
|
||||
|
||||
/**
|
||||
* Add a timeline event to the embedder stream.
|
||||
*
|
||||
* DEPRECATED: this function will be removed in Dart SDK v3.2.
|
||||
*
|
||||
* \param label The name of the event. Its lifetime must extend at least until
|
||||
* Dart_Cleanup.
|
||||
* \param timestamp0 The first timestamp of the event.
|
||||
* \param timestamp1_or_id When reporting an event of type
|
||||
* |Dart_Timeline_Event_Duration|, the second (end) timestamp of the event
|
||||
* should be passed through |timestamp1_or_id|. When reporting an event of
|
||||
* type |Dart_Timeline_Event_Async_Begin|, |Dart_Timeline_Event_Async_End|,
|
||||
* or |Dart_Timeline_Event_Async_Instant|, the async ID associated with the
|
||||
* event should be passed through |timestamp1_or_id|. When reporting an
|
||||
* event of type |Dart_Timeline_Event_Flow_Begin|,
|
||||
* |Dart_Timeline_Event_Flow_Step|, or |Dart_Timeline_Event_Flow_End|, the
|
||||
* flow ID associated with the event should be passed through
|
||||
* |timestamp1_or_id|. When reporting an event of type
|
||||
* |Dart_Timeline_Event_Begin| or |Dart_Timeline_Event_End|, the event ID
|
||||
* associated with the event should be passed through |timestamp1_or_id|.
|
||||
* Note that this event ID will only be used by the MacOS recorder. The
|
||||
* argument to |timestamp1_or_id| will not be used when reporting events of
|
||||
* other types.
|
||||
* \param argument_count The number of argument names and values.
|
||||
* \param argument_names An array of names of the arguments. The lifetime of the
|
||||
* names must extend at least until Dart_Cleanup. The array may be reclaimed
|
||||
* when this call returns.
|
||||
* \param argument_values An array of values of the arguments. The values and
|
||||
* the array may be reclaimed when this call returns.
|
||||
*/
|
||||
DART_EXPORT void Dart_TimelineEvent(const char* label,
|
||||
int64_t timestamp0,
|
||||
int64_t timestamp1_or_id,
|
||||
Dart_Timeline_Event_Type type,
|
||||
intptr_t argument_count,
|
||||
const char** argument_names,
|
||||
const char** argument_values);
|
||||
|
||||
/**
|
||||
* Add a timeline event to the embedder stream.
|
||||
*
|
||||
* Note regarding flow events: events must be associated with flow IDs in two
|
||||
* different ways to allow flow events to be serialized correctly in both
|
||||
* Chrome's JSON trace event format and Perfetto's proto trace format. Events
|
||||
* of type |Dart_Timeline_Event_Flow_Begin|, |Dart_Timeline_Event_Flow_Step|,
|
||||
* and |Dart_Timeline_Event_Flow_End| must be reported to support serialization
|
||||
* in Chrome's trace format. The |flow_ids| argument must be supplied when
|
||||
* reporting events of type |Dart_Timeline_Event_Begin|,
|
||||
* |Dart_Timeline_Event_Duration|, |Dart_Timeline_Event_Instant|,
|
||||
* |Dart_Timeline_Event_Async_Begin|, and |Dart_Timeline_Event_Async_Instant| to
|
||||
* support serialization in Perfetto's proto format.
|
||||
*
|
||||
* \param label The name of the event. Its lifetime must extend at least until
|
||||
* Dart_Cleanup.
|
||||
* \param timestamp0 The first timestamp of the event.
|
||||
* \param timestamp1_or_id When reporting an event of type
|
||||
* |Dart_Timeline_Event_Duration|, the second (end) timestamp of the event
|
||||
* should be passed through |timestamp1_or_id|. When reporting an event of
|
||||
* type |Dart_Timeline_Event_Async_Begin|, |Dart_Timeline_Event_Async_End|,
|
||||
* or |Dart_Timeline_Event_Async_Instant|, the async ID associated with the
|
||||
* event should be passed through |timestamp1_or_id|. When reporting an
|
||||
* event of type |Dart_Timeline_Event_Flow_Begin|,
|
||||
* |Dart_Timeline_Event_Flow_Step|, or |Dart_Timeline_Event_Flow_End|, the
|
||||
* flow ID associated with the event should be passed through
|
||||
* |timestamp1_or_id|. When reporting an event of type
|
||||
* |Dart_Timeline_Event_Begin| or |Dart_Timeline_Event_End|, the event ID
|
||||
* associated with the event should be passed through |timestamp1_or_id|.
|
||||
* Note that this event ID will only be used by the MacOS recorder. The
|
||||
* argument to |timestamp1_or_id| will not be used when reporting events of
|
||||
* other types.
|
||||
* \param flow_id_count The number of flow IDs associated with this event.
|
||||
* \param flow_ids An array of flow IDs associated with this event. The array
|
||||
* may be reclaimed when this call returns.
|
||||
* \param argument_count The number of argument names and values.
|
||||
* \param argument_names An array of names of the arguments. The lifetime of the
|
||||
* names must extend at least until Dart_Cleanup. The array may be reclaimed
|
||||
* when this call returns.
|
||||
* \param argument_values An array of values of the arguments. The values and
|
||||
* the array may be reclaimed when this call returns.
|
||||
*/
|
||||
DART_EXPORT void Dart_RecordTimelineEvent(const char* label,
|
||||
int64_t timestamp0,
|
||||
int64_t timestamp1_or_id,
|
||||
intptr_t flow_id_count,
|
||||
const int64_t* flow_ids,
|
||||
Dart_Timeline_Event_Type type,
|
||||
intptr_t argument_count,
|
||||
const char** argument_names,
|
||||
const char** argument_values);
|
||||
|
||||
/**
|
||||
* Associates a name with the current thread. This name will be used to name
|
||||
* threads in the timeline. Can only be called after a call to Dart_Initialize.
|
||||
*
|
||||
* \param name The name of the thread.
|
||||
*/
|
||||
DART_EXPORT void Dart_SetThreadName(const char* name);
|
||||
|
||||
typedef struct {
|
||||
const char* name;
|
||||
const char* value;
|
||||
} Dart_TimelineRecorderEvent_Argument;
|
||||
|
||||
#define DART_TIMELINE_RECORDER_CURRENT_VERSION (0x00000002)
|
||||
|
||||
typedef struct {
|
||||
/* Set to DART_TIMELINE_RECORDER_CURRENT_VERSION */
|
||||
int32_t version;
|
||||
|
||||
/* The event's type / phase. */
|
||||
Dart_Timeline_Event_Type type;
|
||||
|
||||
/* The event's timestamp according to the same clock as
|
||||
* Dart_TimelineGetMicros. For a duration event, this is the beginning time.
|
||||
*/
|
||||
int64_t timestamp0;
|
||||
|
||||
/**
|
||||
* For a duration event, this is the end time. For an async event, this is the
|
||||
* async ID. For a flow event, this is the flow ID. For a begin or end event,
|
||||
* this is the event ID (which is only referenced by the MacOS recorder).
|
||||
*/
|
||||
int64_t timestamp1_or_id;
|
||||
|
||||
/* The current isolate of the event, as if by Dart_GetMainPortId, or
|
||||
* ILLEGAL_PORT if the event had no current isolate. */
|
||||
Dart_Port isolate;
|
||||
|
||||
/* The current isolate group of the event, as if by
|
||||
* Dart_CurrentIsolateGroupId, or ILLEGAL_PORT if the event had no current
|
||||
* isolate group. */
|
||||
Dart_IsolateGroupId isolate_group;
|
||||
|
||||
/* The callback data associated with the isolate if any. */
|
||||
void* isolate_data;
|
||||
|
||||
/* The callback data associated with the isolate group if any. */
|
||||
void* isolate_group_data;
|
||||
|
||||
/* The name / label of the event. */
|
||||
const char* label;
|
||||
|
||||
/* The stream / category of the event. */
|
||||
const char* stream;
|
||||
|
||||
intptr_t argument_count;
|
||||
Dart_TimelineRecorderEvent_Argument* arguments;
|
||||
} Dart_TimelineRecorderEvent;
|
||||
|
||||
/**
|
||||
* Callback provided by the embedder to handle the completion of timeline
|
||||
* events.
|
||||
*
|
||||
* \param event A timeline event that has just been completed. The VM keeps
|
||||
* ownership of the event and any field in it (i.e., the embedder should copy
|
||||
* any values it needs after the callback returns).
|
||||
*/
|
||||
typedef void (*Dart_TimelineRecorderCallback)(
|
||||
Dart_TimelineRecorderEvent* event);
|
||||
|
||||
/**
|
||||
* Register a `Dart_TimelineRecorderCallback` to be called as timeline events
|
||||
* are completed.
|
||||
*
|
||||
* The callback will be invoked without a current isolate.
|
||||
*
|
||||
* The callback will be invoked on the thread completing the event. Because
|
||||
* `Dart_TimelineEvent` may be called by any thread, the callback may be called
|
||||
* on any thread.
|
||||
*
|
||||
* The callback may be invoked at any time after `Dart_Initialize` is called and
|
||||
* before `Dart_Cleanup` returns.
|
||||
*
|
||||
* If multiple callbacks are registered, only the last callback registered
|
||||
* will be remembered. Providing a NULL callback will clear the registration
|
||||
* (i.e., a NULL callback produced a no-op instead of a crash).
|
||||
*
|
||||
* Setting a callback is insufficient to receive events through the callback. The
|
||||
* VM flag `timeline_recorder` must also be set to `callback`.
|
||||
*/
|
||||
DART_EXPORT void Dart_SetTimelineRecorderCallback(
|
||||
Dart_TimelineRecorderCallback callback);
|
||||
|
||||
/*
|
||||
* =======
|
||||
* Metrics
|
||||
* =======
|
||||
*/
|
||||
|
||||
/**
|
||||
* Return metrics gathered for the VM and individual isolates.
|
||||
*/
|
||||
DART_EXPORT int64_t
|
||||
Dart_IsolateGroupHeapOldUsedMetric(Dart_IsolateGroup group); // Byte
|
||||
DART_EXPORT int64_t
|
||||
Dart_IsolateGroupHeapOldCapacityMetric(Dart_IsolateGroup group); // Byte
|
||||
DART_EXPORT int64_t
|
||||
Dart_IsolateGroupHeapOldExternalMetric(Dart_IsolateGroup group); // Byte
|
||||
DART_EXPORT int64_t
|
||||
Dart_IsolateGroupHeapNewUsedMetric(Dart_IsolateGroup group); // Byte
|
||||
DART_EXPORT int64_t
|
||||
Dart_IsolateGroupHeapNewCapacityMetric(Dart_IsolateGroup group); // Byte
|
||||
DART_EXPORT int64_t
|
||||
Dart_IsolateGroupHeapNewExternalMetric(Dart_IsolateGroup group); // Byte
|
||||
|
||||
/*
|
||||
* ========
|
||||
* UserTags
|
||||
* ========
|
||||
*/
|
||||
|
||||
/*
|
||||
* Gets the current isolate's currently set UserTag instance.
|
||||
*
|
||||
* \return The currently set UserTag instance.
|
||||
*/
|
||||
DART_EXPORT Dart_Handle Dart_GetCurrentUserTag();
|
||||
|
||||
/*
|
||||
* Gets the current isolate's default UserTag instance.
|
||||
*
|
||||
* \return The default UserTag with label 'Default'
|
||||
*/
|
||||
DART_EXPORT Dart_Handle Dart_GetDefaultUserTag();
|
||||
|
||||
/*
|
||||
* Creates a new UserTag instance.
|
||||
*
|
||||
* \param label The name of the new UserTag.
|
||||
*
|
||||
* \return The newly created UserTag instance or an error handle.
|
||||
*/
|
||||
DART_EXPORT Dart_Handle Dart_NewUserTag(const char* label);
|
||||
|
||||
/*
|
||||
* Updates the current isolate's UserTag to a new value.
|
||||
*
|
||||
* \param user_tag The UserTag to be set as the current UserTag.
|
||||
*
|
||||
* \return The previously set UserTag instance or an error handle.
|
||||
*/
|
||||
DART_EXPORT Dart_Handle Dart_SetCurrentUserTag(Dart_Handle user_tag);
|
||||
|
||||
/*
|
||||
* Returns the label of a given UserTag instance.
|
||||
*
|
||||
* \param user_tag The UserTag from which the label will be retrieved.
|
||||
*
|
||||
* \return The UserTag's label. NULL if the user_tag is invalid. The caller is
|
||||
* responsible for freeing the returned label.
|
||||
*/
|
||||
DART_EXPORT DART_WARN_UNUSED_RESULT char* Dart_GetUserTagLabel(
|
||||
Dart_Handle user_tag);
|
||||
|
||||
/*
|
||||
* =======
|
||||
* Heap Snapshot
|
||||
* =======
|
||||
*/
|
||||
|
||||
/**
|
||||
* Callback provided by the caller of `Dart_WriteHeapSnapshot` which is
|
||||
* used to write out chunks of the requested heap snapshot.
|
||||
*
|
||||
* \param context An opaque context which was passed to `Dart_WriteHeapSnapshot`
|
||||
* together with this callback.
|
||||
*
|
||||
* \param buffer Pointer to the buffer containing a chunk of the snapshot.
|
||||
* The callback owns the buffer and needs to `free` it.
|
||||
*
|
||||
* \param size Number of bytes in the `buffer` to be written.
|
||||
*
|
||||
* \param is_last Set to `true` for the last chunk. The callback will not
|
||||
* be invoked again after it was invoked once with `is_last` set to `true`.
|
||||
*/
|
||||
typedef void (*Dart_HeapSnapshotWriteChunkCallback)(void* context,
|
||||
uint8_t* buffer,
|
||||
intptr_t size,
|
||||
bool is_last);
|
||||
|
||||
/**
|
||||
* Generate heap snapshot of the current isolate group and stream it into the
|
||||
* given `callback`. VM would produce snapshot in chunks and send these chunks
|
||||
* one by one back to the embedder by invoking the provided `callback`.
|
||||
*
|
||||
* This API enables embedder to stream snapshot into a file or socket without
|
||||
* allocating a buffer to hold the whole snapshot in memory.
|
||||
*
|
||||
* The isolate group will be paused for the duration of this operation.
|
||||
*
|
||||
* \param write Callback used to write chunks of the heap snapshot.
|
||||
*
|
||||
* \param context Opaque context which would be passed on each invocation of
|
||||
* `write` callback.
|
||||
*
|
||||
* \returns `nullptr` if the operation is successful otherwise error message.
|
||||
* Caller owns error message string and needs to `free` it.
|
||||
*/
|
||||
DART_EXPORT char* Dart_WriteHeapSnapshot(
|
||||
Dart_HeapSnapshotWriteChunkCallback write,
|
||||
void* context);
|
||||
|
||||
#endif // RUNTIME_INCLUDE_DART_TOOLS_API_H_
|
||||
@ -1,16 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file
|
||||
* for details. All rights reserved. Use of this source code is governed by a
|
||||
* BSD-style license that can be found in the LICENSE file.
|
||||
*/
|
||||
|
||||
#ifndef RUNTIME_INCLUDE_DART_VERSION_H_
|
||||
#define RUNTIME_INCLUDE_DART_VERSION_H_
|
||||
|
||||
// On breaking changes the major version is increased.
|
||||
// On backwards compatible changes the minor version is increased.
|
||||
// The versioning covers the symbols exposed in dart_api_dl.h
|
||||
#define DART_API_DL_MAJOR_VERSION 2
|
||||
#define DART_API_DL_MINOR_VERSION 3
|
||||
|
||||
#endif /* RUNTIME_INCLUDE_DART_VERSION_H_ */ /* NOLINT */
|
||||
@ -1,21 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file
|
||||
* for details. All rights reserved. Use of this source code is governed by a
|
||||
* BSD-style license that can be found in the LICENSE file.
|
||||
*/
|
||||
|
||||
#ifndef RUNTIME_INCLUDE_INTERNAL_DART_API_DL_IMPL_H_
|
||||
#define RUNTIME_INCLUDE_INTERNAL_DART_API_DL_IMPL_H_
|
||||
|
||||
typedef struct {
|
||||
const char* name;
|
||||
void (*function)(void);
|
||||
} DartApiEntry;
|
||||
|
||||
typedef struct {
|
||||
const int major;
|
||||
const int minor;
|
||||
const DartApiEntry* const functions;
|
||||
} DartApi;
|
||||
|
||||
#endif /* RUNTIME_INCLUDE_INTERNAL_DART_API_DL_IMPL_H_ */ /* NOLINT */
|
||||
@ -1,18 +0,0 @@
|
||||
@echo off
|
||||
set GOOS=windows
|
||||
set GOARCH=amd64
|
||||
set CC=x86_64-w64-mingw32-gcc
|
||||
set CGO_ENABLED=1
|
||||
go run ./cli tunnel exit
|
||||
del bin\libcore.dll bin\HiddifyCli.exe
|
||||
set CGO_LDFLAGS=
|
||||
go build -trimpath -tags with_gvisor,with_quic,with_wireguard,with_ech,with_utls,with_clash_api,with_grpc -ldflags="-w -s" -buildmode=c-shared -o bin/libcore.dll ./custom
|
||||
go get github.com/akavel/rsrc
|
||||
go install github.com/akavel/rsrc
|
||||
|
||||
rsrc -ico .\assets\hiddify-cli.ico -o cli\bydll\cli.syso
|
||||
|
||||
copy bin\libcore.dll .
|
||||
set CGO_LDFLAGS="libcore.dll"
|
||||
go build -o bin/HiddifyCli.exe ./cli/bydll/
|
||||
del libcore.dll
|
||||
@ -1,35 +0,0 @@
|
||||
package main
|
||||
|
||||
/*
|
||||
#include <stdlib.h>
|
||||
#include <stdint.h>
|
||||
|
||||
// Import the function from the DLL
|
||||
char* parseCli(int argc, char** argv);
|
||||
*/
|
||||
import "C"
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
func main() {
|
||||
args := os.Args
|
||||
|
||||
// Convert []string to []*C.char
|
||||
var cArgs []*C.char
|
||||
for _, arg := range args {
|
||||
cArgs = append(cArgs, C.CString(arg))
|
||||
}
|
||||
defer func() {
|
||||
for _, arg := range cArgs {
|
||||
C.free(unsafe.Pointer(arg))
|
||||
}
|
||||
}()
|
||||
|
||||
// Call the C function
|
||||
result := C.parseCli(C.int(len(cArgs)), (**C.char)(unsafe.Pointer(&cArgs[0])))
|
||||
fmt.Println(C.GoString(result))
|
||||
}
|
||||
@ -1,29 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"github.com/hiddify/hiddify-core/cmd"
|
||||
)
|
||||
|
||||
type UpdateRequest struct {
|
||||
Description string `json:"description,omitempty"`
|
||||
PrivatePods bool `json:"private_pods"`
|
||||
OperatingMode string `json:"operating_mode,omitempty"`
|
||||
ActivationState string `json:"activation_state,omitempty"`
|
||||
}
|
||||
|
||||
func main() {
|
||||
cmd.ParseCli(os.Args[1:])
|
||||
|
||||
// var request UpdateRequest
|
||||
// // jsonTag, err2 := validation.ErrorFieldName(&request, &request.OperatingMode)
|
||||
// jsonTag, err2 := request.ValName(&request.OperatingMode)
|
||||
|
||||
// fmt.Println(jsonTag, err2)
|
||||
// RegisterExtension("com.example.extension", NewExampleExtension())
|
||||
// ex := extensionsMap["com.example.extension"].(*Extension[struct])
|
||||
// fmt.Println(NewExampleExtension().Get())
|
||||
|
||||
// fmt.Println(ex.Get())
|
||||
}
|
||||
@ -1,4 +0,0 @@
|
||||
@echo off
|
||||
set TAGS=with_gvisor,with_quic,with_wireguard,with_ech,with_utls,with_clash_api,with_grpc
|
||||
@REM set TAGS=with_dhcp,with_low_memory,with_conntrack
|
||||
go run --tags %TAGS% ./cli %*
|
||||
@ -1,4 +0,0 @@
|
||||
go mod tidy
|
||||
TAGS=with_gvisor,with_quic,with_wireguard,with_ech,with_utls,with_clash_api,with_grpc
|
||||
# TAGS=with_dhcp,with_low_memory,with_conntrack
|
||||
go run --tags $TAGS ./cli $@
|
||||
@ -1,188 +0,0 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/hiddify/hiddify-core/config"
|
||||
pb "github.com/hiddify/hiddify-core/hiddifyrpc"
|
||||
v2 "github.com/hiddify/hiddify-core/v2"
|
||||
"github.com/sagernet/sing-box/experimental/libbox"
|
||||
"github.com/sagernet/sing-box/log"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var (
|
||||
hiddifySettingPath string
|
||||
configPath string
|
||||
defaultConfigs config.HiddifyOptions = *config.DefaultHiddifyOptions()
|
||||
commandBuildOutputPath string
|
||||
)
|
||||
|
||||
var commandBuild = &cobra.Command{
|
||||
Use: "build",
|
||||
Short: "Build configuration",
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
err := build(configPath, hiddifySettingPath)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
var generateConfig = &cobra.Command{
|
||||
Use: "gen",
|
||||
Short: "gen configuration",
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
conf, err := v2.GenerateConfig(&pb.GenerateConfigRequest{
|
||||
Path: args[0],
|
||||
})
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
log.Debug(string(conf.ConfigContent))
|
||||
},
|
||||
}
|
||||
|
||||
var commandCheck = &cobra.Command{
|
||||
Use: "check",
|
||||
Short: "Check configuration",
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
err := check(configPath)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
commandBuild.Flags().StringVarP(&commandBuildOutputPath, "output", "o", "", "write result to file path instead of stdout")
|
||||
addHConfigFlags(commandBuild)
|
||||
|
||||
mainCommand.AddCommand(commandBuild)
|
||||
mainCommand.AddCommand(generateConfig)
|
||||
}
|
||||
|
||||
func build(path string, optionsPath string) error {
|
||||
if workingDir != "" {
|
||||
path = filepath.Join(workingDir, path)
|
||||
if optionsPath != "" {
|
||||
optionsPath = filepath.Join(workingDir, optionsPath)
|
||||
}
|
||||
os.Chdir(workingDir)
|
||||
}
|
||||
options, err := readConfigAt(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
HiddifyOptions := &defaultConfigs // config.DefaultHiddifyOptions()
|
||||
if optionsPath != "" {
|
||||
HiddifyOptions, err = readHiddifyOptionsAt(optionsPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
config, err := config.BuildConfigJson(*HiddifyOptions, *options)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if commandBuildOutputPath != "" {
|
||||
outputPath, _ := filepath.Abs(filepath.Join(workingDir, commandBuildOutputPath))
|
||||
err = os.WriteFile(outputPath, []byte(config), 0o644)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println("result successfully written to ", outputPath)
|
||||
// libbox.Setup(outputPath, workingDir, workingDir, true)
|
||||
// instance, err := NewService(*patchedOptions)
|
||||
} else {
|
||||
os.Stdout.WriteString(config)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func check(path string) error {
|
||||
content, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return libbox.CheckConfig(string(content))
|
||||
}
|
||||
|
||||
func readConfigAt(path string) (*option.Options, error) {
|
||||
content, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var options option.Options
|
||||
err = options.UnmarshalJSON(content)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &options, nil
|
||||
}
|
||||
|
||||
func readConfigBytes(content []byte) (*option.Options, error) {
|
||||
var options option.Options
|
||||
err := options.UnmarshalJSON(content)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &options, nil
|
||||
}
|
||||
|
||||
func readHiddifyOptionsAt(path string) (*config.HiddifyOptions, error) {
|
||||
content, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var options config.HiddifyOptions
|
||||
err = json.Unmarshal(content, &options)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if options.Warp.WireguardConfigStr != "" {
|
||||
err := json.Unmarshal([]byte(options.Warp.WireguardConfigStr), &options.Warp.WireguardConfig)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if options.Warp2.WireguardConfigStr != "" {
|
||||
err := json.Unmarshal([]byte(options.Warp2.WireguardConfigStr), &options.Warp2.WireguardConfig)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return &options, nil
|
||||
}
|
||||
|
||||
func addHConfigFlags(commandRun *cobra.Command) {
|
||||
commandRun.Flags().StringVarP(&configPath, "config", "c", "", "proxy config path or url")
|
||||
commandRun.MarkFlagRequired("config")
|
||||
commandRun.Flags().StringVarP(&hiddifySettingPath, "hiddify", "d", "", "Hiddify Setting JSON Path")
|
||||
commandRun.Flags().BoolVar(&defaultConfigs.EnableFullConfig, "full-config", false, "allows including tags other than output")
|
||||
commandRun.Flags().StringVar(&defaultConfigs.LogLevel, "log", "warn", "log level")
|
||||
commandRun.Flags().BoolVar(&defaultConfigs.InboundOptions.EnableTun, "tun", false, "Enable Tun")
|
||||
commandRun.Flags().BoolVar(&defaultConfigs.InboundOptions.EnableTunService, "tun-service", false, "Enable Tun Service")
|
||||
commandRun.Flags().BoolVar(&defaultConfigs.InboundOptions.SetSystemProxy, "system-proxy", false, "Enable System Proxy")
|
||||
commandRun.Flags().Uint16Var(&defaultConfigs.InboundOptions.MixedPort, "in-proxy-port", 2334, "Input Mixed Port")
|
||||
commandRun.Flags().BoolVar(&defaultConfigs.TLSTricks.EnableFragment, "fragment", false, "Enable Fragment")
|
||||
commandRun.Flags().StringVar(&defaultConfigs.TLSTricks.FragmentSize, "fragment-size", "2-4", "FragmentSize")
|
||||
commandRun.Flags().StringVar(&defaultConfigs.TLSTricks.FragmentSleep, "fragment-sleep", "2-4", "FragmentSleep")
|
||||
|
||||
commandRun.Flags().BoolVar(&defaultConfigs.TLSTricks.EnablePadding, "padding", false, "Enable Padding")
|
||||
commandRun.Flags().StringVar(&defaultConfigs.TLSTricks.PaddingSize, "padding-size", "1300-1400", "PaddingSize")
|
||||
|
||||
commandRun.Flags().BoolVar(&defaultConfigs.TLSTricks.MixedSNICase, "mixed-sni-case", false, "MixedSNICase")
|
||||
|
||||
commandRun.Flags().StringVar(&defaultConfigs.RemoteDnsAddress, "dns-remote", "1.1.1.1", "RemoteDNS (1.1.1.1, https://1.1.1.1/dns-query)")
|
||||
commandRun.Flags().StringVar(&defaultConfigs.DirectDnsAddress, "dns-direct", "1.1.1.1", "DirectDNS (1.1.1.1, https://1.1.1.1/dns-query)")
|
||||
commandRun.Flags().StringVar(&defaultConfigs.ClashApiSecret, "web-secret", "", "Web Server Secret")
|
||||
commandRun.Flags().Uint16Var(&defaultConfigs.ClashApiPort, "web-port", 6756, "Web Server Port")
|
||||
}
|
||||
@ -1,21 +0,0 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
_ "github.com/hiddify/hiddify-core/extension/repository"
|
||||
"github.com/hiddify/hiddify-core/extension/server"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var commandExtension = &cobra.Command{
|
||||
Use: "extension",
|
||||
Short: "extension configuration",
|
||||
Args: cobra.MaximumNArgs(0),
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
server.StartTestExtensionServer()
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
// commandWarp.Flags().StringVarP(&warpKey, "key", "k", "", "warp key")
|
||||
mainCommand.AddCommand(commandExtension)
|
||||
}
|
||||
@ -1,21 +0,0 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"github.com/hiddify/hiddify-core/utils"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var commandGenerateCertification = &cobra.Command{
|
||||
Use: "gen-cert",
|
||||
Short: "Generate certification for web server",
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
err := os.MkdirAll("cert", 0o644)
|
||||
if err != nil {
|
||||
panic("Error: " + err.Error())
|
||||
}
|
||||
utils.GenerateCertificate("cert/server-cert.pem", "cert/server-key.pem", true, true)
|
||||
utils.GenerateCertificate("cert/client-cert.pem", "cert/client-key.pem", false, true)
|
||||
},
|
||||
}
|
||||
@ -1,59 +0,0 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
|
||||
v2 "github.com/hiddify/hiddify-core/v2"
|
||||
"github.com/sagernet/sing-box/log"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var commandInstance = &cobra.Command{
|
||||
Use: "instance",
|
||||
Short: "instance",
|
||||
Args: cobra.OnlyValidArgs,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
hiddifySetting := defaultConfigs
|
||||
if hiddifySettingPath != "" {
|
||||
hiddifySetting2, err := v2.ReadHiddifyOptionsAt(hiddifySettingPath)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
hiddifySetting = *hiddifySetting2
|
||||
}
|
||||
|
||||
instance, err := v2.RunInstanceString(&hiddifySetting, configPath)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer instance.Close()
|
||||
ping, err := instance.PingAverage("http://cp.cloudflare.com", 4)
|
||||
if err != nil {
|
||||
// log.Fatal(err)
|
||||
}
|
||||
log.Info("Average Ping to Cloudflare : ", ping, "\n")
|
||||
|
||||
for i := 1; i <= 4; i++ {
|
||||
ping, err := instance.PingCloudflare()
|
||||
if err != nil {
|
||||
log.Warn(i, " Error ", err, "\n")
|
||||
} else {
|
||||
log.Info(i, " Ping time: ", ping, " ms\n")
|
||||
}
|
||||
}
|
||||
log.Info("Instance is running on port socks5://127.0.0.1:", instance.ListenPort, "\n")
|
||||
log.Info("Press Ctrl+C to exit\n")
|
||||
sigChan := make(chan os.Signal, 1)
|
||||
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
|
||||
<-sigChan
|
||||
log.Info("CTRL+C recived-->stopping\n")
|
||||
instance.Close()
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
mainCommand.AddCommand(commandInstance)
|
||||
addHConfigFlags(commandInstance)
|
||||
}
|
||||
@ -1,52 +0,0 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/hiddify/hiddify-core/config"
|
||||
"github.com/sagernet/sing-box/log"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var commandParseOutputPath string
|
||||
|
||||
var commandParse = &cobra.Command{
|
||||
Use: "parse",
|
||||
Short: "Parse configuration",
|
||||
Args: cobra.ExactArgs(1),
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
err := parse(args[0])
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
commandParse.Flags().StringVarP(&commandParseOutputPath, "output", "o", "", "write result to file path instead of stdout")
|
||||
|
||||
mainCommand.AddCommand(commandParse)
|
||||
}
|
||||
|
||||
func parse(path string) error {
|
||||
if workingDir != "" {
|
||||
path = filepath.Join(workingDir, path)
|
||||
}
|
||||
config, err := config.ParseConfig(path, true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if commandParseOutputPath != "" {
|
||||
outputPath, _ := filepath.Abs(filepath.Join(workingDir, commandParseOutputPath))
|
||||
err = os.WriteFile(outputPath, config, 0644)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println("result successfully written to ", outputPath)
|
||||
} else {
|
||||
os.Stdout.Write(config)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@ -1,28 +0,0 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
v2 "github.com/hiddify/hiddify-core/v2"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var commandRun = &cobra.Command{
|
||||
Use: "run",
|
||||
Short: "run",
|
||||
Args: cobra.OnlyValidArgs,
|
||||
Run: runCommand,
|
||||
}
|
||||
|
||||
func init() {
|
||||
// commandRun.PersistentFlags().BoolP("help", "", false, "help for this command")
|
||||
// commandRun.Flags().StringVarP(&hiddifySettingPath, "hiddify", "d", "", "Hiddify Setting JSON Path")
|
||||
|
||||
addHConfigFlags(commandRun)
|
||||
|
||||
mainCommand.AddCommand(commandRun)
|
||||
}
|
||||
|
||||
func runCommand(cmd *cobra.Command, args []string) {
|
||||
v2.Setup("./tmp", "./", "./tmp", 0, false)
|
||||
v2.RunStandalone(hiddifySettingPath, configPath, defaultConfigs)
|
||||
}
|
||||
@ -1,141 +0,0 @@
|
||||
package cmd
|
||||
|
||||
// import (
|
||||
// "context"
|
||||
// "fmt"
|
||||
// "io"
|
||||
// "math/rand"
|
||||
// "net/http"
|
||||
// "net/netip"
|
||||
// "time"
|
||||
|
||||
// "github.com/hiddify/hiddify-core/common"
|
||||
// // "github.com/hiddify/hiddify-core/extension_repository/cleanip_scanner"
|
||||
// "github.com/spf13/cobra"
|
||||
// "golang.org/x/net/proxy"
|
||||
// )
|
||||
|
||||
// var commandTemp = &cobra.Command{
|
||||
// Use: "temp",
|
||||
// Short: "temp",
|
||||
// Args: cobra.MaximumNArgs(2),
|
||||
// Run: func(cmd *cobra.Command, args []string) {
|
||||
// // fmt.Printf("Ping time: %d ms\n", Ping())
|
||||
// scanner := cleanip_scanner.NewScannerEngine(&cleanip_scanner.ScannerOptions{
|
||||
// UseIPv4: true,
|
||||
// UseIPv6: common.CanConnectIPv6(),
|
||||
// MaxDesirableRTT: 500 * time.Millisecond,
|
||||
// IPQueueSize: 4,
|
||||
// IPQueueTTL: 10 * time.Second,
|
||||
// ConcurrentPings: 10,
|
||||
// // MaxDesirableIPs: e.count,
|
||||
// CidrList: cleanip_scanner.DefaultCFRanges(),
|
||||
// PingFunc: func(ip netip.Addr) (cleanip_scanner.IPInfo, error) {
|
||||
// fmt.Printf("Ping: %s\n", ip.String())
|
||||
// return cleanip_scanner.IPInfo{
|
||||
// AddrPort: netip.AddrPortFrom(ip, 80),
|
||||
// RTT: time.Duration(rand.Intn(1000)),
|
||||
// CreatedAt: time.Now(),
|
||||
// }, nil
|
||||
// },
|
||||
// },
|
||||
// )
|
||||
|
||||
// ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
// defer cancel()
|
||||
|
||||
// scanner.Run(ctx)
|
||||
|
||||
// t := time.NewTicker(1 * time.Second)
|
||||
// defer t.Stop()
|
||||
|
||||
// for {
|
||||
// ipList := scanner.GetAvailableIPs(false)
|
||||
// if len(ipList) > 1 {
|
||||
// // e.result = ""
|
||||
// for i := 0; i < 2; i++ {
|
||||
// // result = append(result, ipList[i])
|
||||
// // e.result = e.result + ipList[i].AddrPort.String() + "\n"
|
||||
// fmt.Printf("%d %s\n", ipList[i].RTT, ipList[i].AddrPort.String())
|
||||
// }
|
||||
// return
|
||||
// }
|
||||
|
||||
// select {
|
||||
// case <-ctx.Done():
|
||||
// // Context is done
|
||||
// return
|
||||
// case <-t.C:
|
||||
// // Prevent the loop from spinning too fast
|
||||
// continue
|
||||
// }
|
||||
// }
|
||||
// },
|
||||
// }
|
||||
|
||||
// func init() {
|
||||
// mainCommand.AddCommand(commandTemp)
|
||||
// }
|
||||
|
||||
// func GetContent(url string) (string, error) {
|
||||
// return ContentFromURL("GET", url, 10*time.Second)
|
||||
// }
|
||||
|
||||
// func ContentFromURL(method string, url string, timeout time.Duration) (string, error) {
|
||||
// if method == "" {
|
||||
// return "", fmt.Errorf("empty method")
|
||||
// }
|
||||
// if url == "" {
|
||||
// return "", fmt.Errorf("empty url")
|
||||
// }
|
||||
|
||||
// req, err := http.NewRequest(method, url, nil)
|
||||
// if err != nil {
|
||||
// return "", err
|
||||
// }
|
||||
|
||||
// dialer, err := proxy.SOCKS5("tcp", "127.0.0.1:12334", nil, proxy.Direct)
|
||||
// if err != nil {
|
||||
// return "", err
|
||||
// }
|
||||
|
||||
// transport := &http.Transport{
|
||||
// Dial: dialer.Dial,
|
||||
// }
|
||||
|
||||
// client := &http.Client{
|
||||
// Transport: transport,
|
||||
// Timeout: timeout,
|
||||
// }
|
||||
|
||||
// resp, err := client.Do(req)
|
||||
// if err != nil {
|
||||
// return "", err
|
||||
// }
|
||||
// defer resp.Body.Close()
|
||||
|
||||
// if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent {
|
||||
// return "", fmt.Errorf("request failed with status code: %d", resp.StatusCode)
|
||||
// }
|
||||
|
||||
// body, err := io.ReadAll(resp.Body)
|
||||
// if err != nil {
|
||||
// return "", err
|
||||
// }
|
||||
|
||||
// if body == nil {
|
||||
// return "", fmt.Errorf("empty body")
|
||||
// }
|
||||
|
||||
// return string(body), nil
|
||||
// }
|
||||
|
||||
// func Ping() int {
|
||||
// startTime := time.Now()
|
||||
// _, err := ContentFromURL("HEAD", "https://cp.cloudflare.com", 4*time.Second)
|
||||
// if err != nil {
|
||||
// return -1
|
||||
// }
|
||||
// duration := time.Since(startTime)
|
||||
// return int(duration.Milliseconds())
|
||||
// }
|
||||
@ -1,40 +0,0 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/hiddify/hiddify-core/config"
|
||||
v2 "github.com/hiddify/hiddify-core/v2"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var commandService = &cobra.Command{
|
||||
Use: "tunnel run/start/stop/install/uninstall/activate/deactivate/exit",
|
||||
Short: "Tunnel Service run/start/stop/install/uninstall/activate/deactivate/exit",
|
||||
ValidArgs: []string{"run", "start", "stop", "install", "uninstall", "activate", "deactivate", "exit"},
|
||||
Args: cobra.MatchAll(cobra.ExactArgs(1), cobra.OnlyValidArgs),
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
arg := args[0]
|
||||
switch arg {
|
||||
case "activate":
|
||||
config.ActivateTunnelService(config.HiddifyOptions{
|
||||
InboundOptions: config.InboundOptions{
|
||||
EnableTunService: true,
|
||||
MixedPort: 12334,
|
||||
TUNStack: "gvisor",
|
||||
},
|
||||
})
|
||||
<-time.After(1 * time.Second)
|
||||
|
||||
case "deactivate":
|
||||
config.DeactivateTunnelServiceForce()
|
||||
case "exit":
|
||||
config.ExitTunnelService()
|
||||
default:
|
||||
code, out := v2.StartTunnelService(arg)
|
||||
fmt.Printf("exitCode:%d msg=%s", code, out)
|
||||
}
|
||||
},
|
||||
}
|
||||
@ -1,126 +0,0 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/hiddify/hiddify-core/config"
|
||||
T "github.com/sagernet/sing-box/option"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var warpKey string
|
||||
|
||||
var commandWarp = &cobra.Command{
|
||||
Use: "warp",
|
||||
Short: "warp configuration",
|
||||
Args: cobra.ExactArgs(0),
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
out, err := generateWarp()
|
||||
fmt.Printf("out=%v Error! %v", out, err)
|
||||
if err != nil {
|
||||
fmt.Printf("Error! %v", err)
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
// commandWarp.Flags().StringVarP(&warpKey, "key", "k", "", "warp key")
|
||||
mainCommand.AddCommand(commandWarp)
|
||||
}
|
||||
|
||||
type WireGuardConfig struct {
|
||||
Interface InterfaceConfig `json:"Interface"`
|
||||
Peer PeerConfig `json:"Peer"`
|
||||
}
|
||||
|
||||
type InterfaceConfig struct {
|
||||
PrivateKey string `json:"PrivateKey"`
|
||||
DNS string `json:"DNS"`
|
||||
Address []string `json:"Address"`
|
||||
}
|
||||
|
||||
type PeerConfig struct {
|
||||
PublicKey string `json:"PublicKey"`
|
||||
AllowedIPs []string `json:"AllowedIPs"`
|
||||
Endpoint string `json:"Endpoint"`
|
||||
}
|
||||
|
||||
type SingboxConfig struct {
|
||||
Type string `json:"type"`
|
||||
Tag string `json:"tag"`
|
||||
Server string `json:"server"`
|
||||
ServerPort int `json:"server_port"`
|
||||
LocalAddress []string `json:"local_address"`
|
||||
PrivateKey string `json:"private_key"`
|
||||
PeerPublicKey string `json:"peer_public_key"`
|
||||
Reserved []int `json:"reserved"`
|
||||
MTU int `json:"mtu"`
|
||||
}
|
||||
|
||||
func readWireGuardConfig(filePath string) (WireGuardConfig, error) {
|
||||
file, err := os.Open(filePath)
|
||||
if err != nil {
|
||||
return WireGuardConfig{}, err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
scanner := bufio.NewScanner(file)
|
||||
|
||||
var wgConfig WireGuardConfig
|
||||
var currentSection string
|
||||
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
|
||||
if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") {
|
||||
currentSection = strings.TrimSpace(line[1 : len(line)-1])
|
||||
continue
|
||||
}
|
||||
|
||||
if currentSection == "Interface" {
|
||||
parseInterfaceConfig(&wgConfig.Interface, line)
|
||||
} else if currentSection == "Peer" {
|
||||
parsePeerConfig(&wgConfig.Peer, line)
|
||||
}
|
||||
}
|
||||
|
||||
return wgConfig, nil
|
||||
}
|
||||
|
||||
func parseInterfaceConfig(interfaceConfig *InterfaceConfig, line string) {
|
||||
if strings.HasPrefix(line, "PrivateKey") {
|
||||
interfaceConfig.PrivateKey = strings.TrimSpace(strings.SplitN(line, "=", 2)[1])
|
||||
} else if strings.HasPrefix(line, "DNS") {
|
||||
interfaceConfig.DNS = strings.TrimSpace(strings.SplitN(line, "=", 2)[1])
|
||||
} else if strings.HasPrefix(line, "Address") {
|
||||
interfaceConfig.Address = append(interfaceConfig.Address, strings.TrimSpace(strings.SplitN(line, "=", 2)[1]))
|
||||
}
|
||||
}
|
||||
|
||||
func parsePeerConfig(peerConfig *PeerConfig, line string) {
|
||||
if strings.HasPrefix(line, "PublicKey") {
|
||||
peerConfig.PublicKey = strings.TrimSpace(strings.SplitN(line, "=", 2)[1])
|
||||
} else if strings.HasPrefix(line, "AllowedIPs") {
|
||||
peerConfig.AllowedIPs = append(peerConfig.AllowedIPs, strings.TrimSpace(strings.SplitN(line, "=", 2)[1]))
|
||||
} else if strings.HasPrefix(line, "Endpoint") {
|
||||
peerConfig.Endpoint = strings.TrimSpace(strings.SplitN(line, "=", 2)[1])
|
||||
}
|
||||
}
|
||||
func generateWarp() (*T.Outbound, error) {
|
||||
_, _, wg, err := config.GenerateWarpInfo("", "", "")
|
||||
|
||||
// fmt.Printf("%v", wgConfig)
|
||||
singboxConfig, err := config.GenerateWarpSingbox(*wg, "", 0, "", "", "", "")
|
||||
singboxJSON, err := json.MarshalIndent(singboxConfig, "", " ")
|
||||
if err != nil {
|
||||
fmt.Println("Error marshaling Singbox configuration:", err)
|
||||
return nil, err
|
||||
}
|
||||
fmt.Println(string(singboxJSON))
|
||||
return nil, nil
|
||||
}
|
||||
@ -1,55 +0,0 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"context"
|
||||
|
||||
"github.com/sagernet/sing-box/log"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var (
|
||||
workingDir string
|
||||
disableColor bool
|
||||
)
|
||||
|
||||
var mainCommand = &cobra.Command{
|
||||
Use: "HiddifyCli",
|
||||
PersistentPreRun: preRun,
|
||||
}
|
||||
|
||||
func init() {
|
||||
mainCommand.AddCommand(commandService)
|
||||
mainCommand.AddCommand(commandGenerateCertification)
|
||||
|
||||
mainCommand.PersistentFlags().StringVarP(&workingDir, "directory", "D", "", "set working directory")
|
||||
mainCommand.PersistentFlags().BoolVarP(&disableColor, "disable-color", "", false, "disable color output")
|
||||
|
||||
}
|
||||
|
||||
func ParseCli(args []string) error {
|
||||
mainCommand.SetArgs(args)
|
||||
err := mainCommand.Execute()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func preRun(cmd *cobra.Command, args []string) {
|
||||
if disableColor {
|
||||
log.SetStdLogger(log.NewDefaultFactory(context.Background(), log.Formatter{BaseTime: time.Now(), DisableColors: true}, os.Stderr, "", nil, false).Logger())
|
||||
}
|
||||
if workingDir != "" {
|
||||
_, err := os.Stat(workingDir)
|
||||
if err != nil {
|
||||
os.MkdirAll(workingDir, 0o0644)
|
||||
}
|
||||
if err := os.Chdir(workingDir); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,217 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/hiddify/hiddify-core/cmd/internal/build_shared"
|
||||
_ "github.com/sagernet/gomobile"
|
||||
"github.com/sagernet/sing-box/log"
|
||||
"github.com/sagernet/sing/common/rw"
|
||||
)
|
||||
|
||||
var target string
|
||||
|
||||
func init() {
|
||||
flag.StringVar(&target, "target", "android", "target platform")
|
||||
}
|
||||
|
||||
func main() {
|
||||
flag.Parse()
|
||||
|
||||
switch target {
|
||||
case "windows":
|
||||
buildWindows()
|
||||
case "linux":
|
||||
buildLinux()
|
||||
case "macos":
|
||||
buildMacOS()
|
||||
case "android":
|
||||
buildAndroid()
|
||||
case "ios":
|
||||
buildIOS()
|
||||
}
|
||||
}
|
||||
|
||||
var (
|
||||
sharedFlags []string
|
||||
sharedTags []string
|
||||
iosTags []string
|
||||
)
|
||||
|
||||
const libName = "libcore"
|
||||
|
||||
func init() {
|
||||
sharedFlags = append(sharedFlags, "-trimpath")
|
||||
sharedFlags = append(sharedFlags, "-ldflags", "-s -w")
|
||||
sharedTags = append(sharedTags, "with_gvisor", "with_quic", "with_wireguard", "with_ech", "with_utls", "with_clash_api", "with_grpc")
|
||||
iosTags = append(iosTags, "with_dhcp", "with_low_memory", "with_conntrack")
|
||||
}
|
||||
|
||||
func setDesktopEnv() {
|
||||
os.Setenv("CGO_ENABLED", "1")
|
||||
os.Setenv("buildmode", "c-shared")
|
||||
}
|
||||
|
||||
func buildWindows() {
|
||||
setDesktopEnv()
|
||||
os.Setenv("GOOS", "windows")
|
||||
os.Setenv("GOARCH", "amd64")
|
||||
os.Setenv("CC", "x86_64-w64-mingw32-gcc")
|
||||
|
||||
args := []string{"build"}
|
||||
args = append(args, sharedFlags...)
|
||||
args = append(args, "-tags")
|
||||
args = append(args, strings.Join(sharedTags, ","))
|
||||
|
||||
output := filepath.Join("bin", libName+".dll")
|
||||
args = append(args, "-o", output, "./custom")
|
||||
|
||||
command := exec.Command("go", args...)
|
||||
command.Stdout = os.Stdout
|
||||
command.Stderr = os.Stderr
|
||||
log.Debug("command: ", command.String())
|
||||
err := command.Run()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func buildLinux() {
|
||||
setDesktopEnv()
|
||||
os.Setenv("GOOS", "linux")
|
||||
os.Setenv("GOARCH", "amd64")
|
||||
|
||||
args := []string{"build"}
|
||||
args = append(args, sharedFlags...)
|
||||
args = append(args, "-tags")
|
||||
args = append(args, strings.Join(sharedTags, ","))
|
||||
|
||||
output := filepath.Join("bin", libName+".so")
|
||||
args = append(args, "-o", output, "./custom")
|
||||
|
||||
command := exec.Command("go", args...)
|
||||
command.Stdout = os.Stdout
|
||||
command.Stderr = os.Stderr
|
||||
log.Debug("command: ", command.String())
|
||||
err := command.Run()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func buildMacOS() {
|
||||
libPaths := []string{}
|
||||
for _, arch := range []string{"amd64", "arm64"} {
|
||||
out, err := buildMacOSArch(arch)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
return
|
||||
}
|
||||
libPaths = append(libPaths, out)
|
||||
}
|
||||
|
||||
args := []string{"-create"}
|
||||
args = append(args, libPaths...)
|
||||
args = append(args, "-output", filepath.Join("bin", libName+".dylib"))
|
||||
|
||||
command := exec.Command("lipo", args...)
|
||||
command.Stdout = os.Stdout
|
||||
command.Stderr = os.Stderr
|
||||
log.Debug("command: ", command.String())
|
||||
err := command.Run()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func buildMacOSArch(arch string) (string, error) {
|
||||
setDesktopEnv()
|
||||
os.Setenv("GOOS", "darwin")
|
||||
os.Setenv("GOARCH", arch)
|
||||
os.Setenv("CGO_CFLAGS", "-mmacosx-version-min=10.11")
|
||||
os.Setenv("CGO_LDFLAGS", "-mmacosx-version-min=10.11")
|
||||
|
||||
args := []string{"build"}
|
||||
args = append(args, sharedFlags...)
|
||||
tags := append(sharedTags, iosTags...)
|
||||
args = append(args, "-tags")
|
||||
args = append(args, strings.Join(tags, ","))
|
||||
|
||||
filename := libName + "-" + arch + ".dylib"
|
||||
output := filepath.Join("bin", filename)
|
||||
args = append(args, "-o", output, "./custom")
|
||||
|
||||
command := exec.Command("go", args...)
|
||||
command.Stdout = os.Stdout
|
||||
command.Stderr = os.Stderr
|
||||
log.Debug("command: ", command.String())
|
||||
err := command.Run()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return output, nil
|
||||
}
|
||||
|
||||
func buildAndroid() {
|
||||
build_shared.FindMobile()
|
||||
build_shared.FindSDK()
|
||||
|
||||
args := []string{
|
||||
"bind",
|
||||
"-v",
|
||||
"-androidapi", "21",
|
||||
"-javapkg=io.nekohasekai",
|
||||
"-libname=box",
|
||||
"-target=android",
|
||||
}
|
||||
|
||||
args = append(args, sharedFlags...)
|
||||
args = append(args, "-tags")
|
||||
args = append(args, strings.Join(sharedTags, ","))
|
||||
|
||||
output := filepath.Join("bin", libName+".aar")
|
||||
args = append(args, "-o", output, "github.com/sagernet/sing-box/experimental/libbox", "./mobile")
|
||||
|
||||
command := exec.Command(build_shared.GoBinPath+"/gomobile", args...)
|
||||
command.Stdout = os.Stdout
|
||||
command.Stderr = os.Stderr
|
||||
log.Debug("command: ", command.String())
|
||||
err := command.Run()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func buildIOS() {
|
||||
build_shared.FindMobile()
|
||||
|
||||
args := []string{
|
||||
"bind",
|
||||
"-v",
|
||||
"-libname=box",
|
||||
"-target", "ios,iossimulator,tvos,tvossimulator,macos",
|
||||
}
|
||||
|
||||
args = append(args, sharedFlags...)
|
||||
tags := append(sharedTags, iosTags...)
|
||||
args = append(args, "-tags")
|
||||
args = append(args, strings.Join(tags, ","))
|
||||
|
||||
output := filepath.Join("bin", "Libcore.xcframework")
|
||||
args = append(args, "-o", output, "github.com/sagernet/sing-box/experimental/libbox", "./mobile")
|
||||
|
||||
command := exec.Command(build_shared.GoBinPath+"/gomobile", args...)
|
||||
command.Stdout = os.Stdout
|
||||
command.Stderr = os.Stderr
|
||||
log.Debug("command: ", command.String())
|
||||
err := command.Run()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
rw.CopyFile("Info.plist", filepath.Join(output, "Info.plist"))
|
||||
}
|
||||
@ -1,99 +0,0 @@
|
||||
package build_shared
|
||||
|
||||
import (
|
||||
"go/build"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/sagernet/sing-box/log"
|
||||
"github.com/sagernet/sing/common"
|
||||
"github.com/sagernet/sing/common/rw"
|
||||
)
|
||||
|
||||
var (
|
||||
androidSDKPath string
|
||||
androidNDKPath string
|
||||
)
|
||||
|
||||
func FindSDK() {
|
||||
searchPath := []string{
|
||||
"$ANDROID_HOME",
|
||||
"$HOME/Android/Sdk",
|
||||
"$HOME/.local/lib/android/sdk",
|
||||
"$HOME/Library/Android/sdk",
|
||||
}
|
||||
for _, path := range searchPath {
|
||||
path = os.ExpandEnv(path)
|
||||
if rw.FileExists(path + "/licenses/android-sdk-license") {
|
||||
androidSDKPath = path
|
||||
break
|
||||
}
|
||||
}
|
||||
if androidSDKPath == "" {
|
||||
log.Fatal("android SDK not found")
|
||||
}
|
||||
if !findNDK() {
|
||||
log.Fatal("android NDK not found")
|
||||
}
|
||||
|
||||
os.Setenv("ANDROID_HOME", androidSDKPath)
|
||||
os.Setenv("ANDROID_SDK_HOME", androidSDKPath)
|
||||
os.Setenv("ANDROID_NDK_HOME", androidNDKPath)
|
||||
os.Setenv("NDK", androidNDKPath)
|
||||
os.Setenv("PATH", os.Getenv("PATH")+":"+filepath.Join(androidNDKPath, "toolchains", "llvm", "prebuilt", runtime.GOOS+"-x86_64", "bin"))
|
||||
}
|
||||
|
||||
func findNDK() bool {
|
||||
if rw.FileExists(androidSDKPath + "/ndk/26.1.10909125") {
|
||||
androidNDKPath = androidSDKPath + "/ndk/26.1.10909125"
|
||||
return true
|
||||
}
|
||||
ndkVersions, err := os.ReadDir(androidSDKPath + "/ndk")
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
versionNames := common.Map(ndkVersions, os.DirEntry.Name)
|
||||
if len(versionNames) == 0 {
|
||||
return false
|
||||
}
|
||||
sort.Slice(versionNames, func(i, j int) bool {
|
||||
iVersions := strings.Split(versionNames[i], ".")
|
||||
jVersions := strings.Split(versionNames[j], ".")
|
||||
for k := 0; k < len(iVersions) && k < len(jVersions); k++ {
|
||||
iVersion, _ := strconv.Atoi(iVersions[k])
|
||||
jVersion, _ := strconv.Atoi(jVersions[k])
|
||||
if iVersion != jVersion {
|
||||
return iVersion > jVersion
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
for _, versionName := range versionNames {
|
||||
if rw.FileExists(androidSDKPath + "/ndk/" + versionName) {
|
||||
androidNDKPath = androidSDKPath + "/ndk/" + versionName
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
var GoBinPath string
|
||||
|
||||
func FindMobile() {
|
||||
goBin := filepath.Join(build.Default.GOPATH, "bin")
|
||||
|
||||
if runtime.GOOS == "windows" {
|
||||
if !rw.FileExists(goBin + "/" + "gobind.exe") {
|
||||
log.Fatal("missing gomobile.exe installation")
|
||||
}
|
||||
} else {
|
||||
if !rw.FileExists(goBin + "/" + "gobind") {
|
||||
log.Fatal("missing gomobile installation")
|
||||
}
|
||||
}
|
||||
GoBinPath = goBin
|
||||
}
|
||||
@ -1,49 +0,0 @@
|
||||
//go:build !windows
|
||||
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func ExecuteCmd(executablePath string, background bool, args ...string) (string, error) {
|
||||
cwd := filepath.Dir(executablePath)
|
||||
if appimage := os.Getenv("APPIMAGE"); appimage != "" {
|
||||
executablePath = appimage
|
||||
if !background {
|
||||
return "Fail", fmt.Errorf("Appimage cannot have service")
|
||||
}
|
||||
}
|
||||
|
||||
commands := [][]string{
|
||||
{"cocoasudo", "--prompt=Hiddify needs root for tunneling.", executablePath},
|
||||
{"gksu", executablePath},
|
||||
{"pkexec", executablePath},
|
||||
{"xterm", "-e", "sudo", executablePath, strings.Join(args, " ")},
|
||||
{"sudo", executablePath},
|
||||
}
|
||||
|
||||
var err error
|
||||
var cmd *exec.Cmd
|
||||
for _, command := range commands {
|
||||
cmd = exec.Command(command[0], command[1:]...)
|
||||
cmd.Dir = cwd
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
fmt.Printf("Running command: %v\n", command)
|
||||
if background {
|
||||
err = cmd.Start()
|
||||
} else {
|
||||
err = cmd.Run()
|
||||
}
|
||||
if err == nil {
|
||||
return "Ok", nil
|
||||
}
|
||||
}
|
||||
|
||||
return "", fmt.Errorf("Error executing run as root shell command")
|
||||
}
|
||||
@ -1,32 +0,0 @@
|
||||
//go:build windows
|
||||
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
"syscall"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
func ExecuteCmd(exe string, background bool, args ...string) (string, error) {
|
||||
verb := "runas"
|
||||
cwd, err := os.Getwd() // Error handling added
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
verbPtr, _ := syscall.UTF16PtrFromString(verb)
|
||||
exePtr, _ := syscall.UTF16PtrFromString(exe)
|
||||
cwdPtr, _ := syscall.UTF16PtrFromString(cwd)
|
||||
argPtr, _ := syscall.UTF16PtrFromString(strings.Join(args, " "))
|
||||
|
||||
var showCmd int32 = 0 // SW_NORMAL
|
||||
|
||||
err = windows.ShellExecute(0, verbPtr, exePtr, argPtr, cwdPtr, showCmd)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
@ -1,188 +0,0 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
context "context"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"time"
|
||||
|
||||
pb "github.com/hiddify/hiddify-core/hiddifyrpc"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
dns "github.com/sagernet/sing-dns"
|
||||
grpc "google.golang.org/grpc"
|
||||
)
|
||||
|
||||
const (
|
||||
serviceURL = "http://localhost:18020"
|
||||
startEndpoint = "/start"
|
||||
stopEndpoint = "/stop"
|
||||
)
|
||||
|
||||
var tunnelServiceRunning = false
|
||||
|
||||
func isSupportedOS() bool {
|
||||
return runtime.GOOS == "windows" || runtime.GOOS == "linux"
|
||||
}
|
||||
|
||||
func ActivateTunnelService(opt HiddifyOptions) (bool, error) {
|
||||
tunnelServiceRunning = true
|
||||
// if !isSupportedOS() {
|
||||
// return false, E.New("Unsupported OS: " + runtime.GOOS)
|
||||
// }
|
||||
|
||||
go startTunnelRequestWithFailover(opt, true)
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func DeactivateTunnelServiceForce() (bool, error) {
|
||||
return stopTunnelRequest()
|
||||
}
|
||||
|
||||
func DeactivateTunnelService() (bool, error) {
|
||||
// if !isSupportedOS() {
|
||||
// return true, nil
|
||||
// }
|
||||
|
||||
if tunnelServiceRunning {
|
||||
res, err := stopTunnelRequest()
|
||||
if err != nil {
|
||||
tunnelServiceRunning = false
|
||||
}
|
||||
return res, err
|
||||
} else {
|
||||
go stopTunnelRequest()
|
||||
}
|
||||
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func startTunnelRequestWithFailover(opt HiddifyOptions, installService bool) {
|
||||
res, err := startTunnelRequest(opt, installService)
|
||||
fmt.Printf("Start Tunnel Result: %v\n", res)
|
||||
if err != nil {
|
||||
fmt.Printf("Start Tunnel Failed! Stopping core... err=%v\n", err)
|
||||
// StopAndAlert(pb.MessageType.MessageType_UNEXPECTED_ERROR, "Start Tunnel Failed! Stopping...")
|
||||
}
|
||||
}
|
||||
|
||||
func isPortInUse(port string) bool {
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:"+port)
|
||||
if err != nil {
|
||||
return true // Port is in use
|
||||
}
|
||||
defer listener.Close()
|
||||
return false // Port is available
|
||||
}
|
||||
|
||||
func startTunnelRequest(opt HiddifyOptions, installService bool) (bool, error) {
|
||||
if !isPortInUse("18020") {
|
||||
if installService {
|
||||
return runTunnelService(opt)
|
||||
}
|
||||
return false, fmt.Errorf("service is not running")
|
||||
}
|
||||
conn, err := grpc.Dial("127.0.0.1:18020", grpc.WithInsecure())
|
||||
if err != nil {
|
||||
log.Printf("did not connect: %v", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
c := pb.NewTunnelServiceClient(conn)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
|
||||
defer cancel()
|
||||
_, _ = c.Stop(ctx, &pb.Empty{})
|
||||
res, err := c.Start(ctx, &pb.TunnelStartRequest{
|
||||
Ipv6: opt.IPv6Mode == option.DomainStrategy(dns.DomainStrategyUseIPv4),
|
||||
ServerPort: int32(opt.InboundOptions.MixedPort),
|
||||
StrictRoute: opt.InboundOptions.StrictRoute,
|
||||
EndpointIndependentNat: true,
|
||||
Stack: opt.InboundOptions.TUNStack,
|
||||
})
|
||||
if err != nil {
|
||||
log.Printf("could not greet: %+v %+v", res, err)
|
||||
|
||||
if installService {
|
||||
ExitTunnelService()
|
||||
return runTunnelService(opt)
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func stopTunnelRequest() (bool, error) {
|
||||
conn, err := grpc.Dial("127.0.0.1:18020", grpc.WithInsecure())
|
||||
if err != nil {
|
||||
log.Printf("did not connect: %v", err)
|
||||
return false, err
|
||||
}
|
||||
defer conn.Close()
|
||||
c := pb.NewTunnelServiceClient(conn)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second*20)
|
||||
defer cancel()
|
||||
|
||||
res, err := c.Stop(ctx, &pb.Empty{})
|
||||
if err != nil {
|
||||
log.Printf("did not Stopped: %v %v", res, err)
|
||||
_, _ = c.Stop(ctx, &pb.Empty{})
|
||||
return false, err
|
||||
}
|
||||
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func ExitTunnelService() (bool, error) {
|
||||
conn, err := grpc.Dial("127.0.0.1:18020", grpc.WithInsecure())
|
||||
if err != nil {
|
||||
log.Printf("did not connect: %v", err)
|
||||
return false, err
|
||||
}
|
||||
defer conn.Close()
|
||||
c := pb.NewTunnelServiceClient(conn)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second*1)
|
||||
defer cancel()
|
||||
|
||||
res, err := c.Exit(ctx, &pb.Empty{})
|
||||
if res != nil {
|
||||
log.Printf("did not exit: %v %v", res, err)
|
||||
return false, err
|
||||
}
|
||||
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func runTunnelService(opt HiddifyOptions) (bool, error) {
|
||||
executablePath := getTunnelServicePath()
|
||||
fmt.Printf("Executable path is %s", executablePath)
|
||||
out, err := ExecuteCmd(executablePath, false, "tunnel", "install")
|
||||
fmt.Println("Shell command executed:", out, err)
|
||||
if err != nil {
|
||||
out, err = ExecuteCmd(executablePath, true, "tunnel", "run")
|
||||
fmt.Println("Shell command executed without flag:", out, err)
|
||||
}
|
||||
if err == nil {
|
||||
<-time.After(1 * time.Second) // wait until service loaded completely
|
||||
}
|
||||
return startTunnelRequest(opt, false)
|
||||
}
|
||||
|
||||
func getTunnelServicePath() string {
|
||||
var fullPath string
|
||||
exePath, _ := os.Executable()
|
||||
binFolder := filepath.Dir(exePath)
|
||||
switch runtime.GOOS {
|
||||
case "windows":
|
||||
fullPath = "HiddifyCli.exe"
|
||||
case "darwin":
|
||||
fallthrough
|
||||
default:
|
||||
fullPath = "HiddifyCli"
|
||||
}
|
||||
|
||||
abspath, _ := filepath.Abs(filepath.Join(binFolder, fullPath))
|
||||
return abspath
|
||||
}
|
||||
@ -1,869 +0,0 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"net"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
C "github.com/sagernet/sing-box/constant"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
dns "github.com/sagernet/sing-dns"
|
||||
)
|
||||
|
||||
const (
|
||||
DNSRemoteTag = "dns-remote"
|
||||
DNSLocalTag = "dns-local"
|
||||
DNSDirectTag = "dns-direct"
|
||||
DNSBlockTag = "dns-block"
|
||||
DNSFakeTag = "dns-fake"
|
||||
DNSTricksDirectTag = "dns-trick-direct"
|
||||
|
||||
OutboundDirectTag = "direct"
|
||||
OutboundBypassTag = "bypass"
|
||||
OutboundBlockTag = "block"
|
||||
OutboundSelectTag = "select"
|
||||
OutboundURLTestTag = "auto"
|
||||
OutboundDNSTag = "dns-out"
|
||||
OutboundDirectFragmentTag = "direct-fragment"
|
||||
|
||||
InboundTUNTag = "tun-in"
|
||||
InboundMixedTag = "mixed-in"
|
||||
InboundDNSTag = "dns-in"
|
||||
)
|
||||
|
||||
var OutboundMainProxyTag = OutboundSelectTag
|
||||
|
||||
func BuildConfigJson(configOpt HiddifyOptions, input option.Options) (string, error) {
|
||||
options, err := BuildConfig(configOpt, input)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
var buffer bytes.Buffer
|
||||
json.NewEncoder(&buffer)
|
||||
encoder := json.NewEncoder(&buffer)
|
||||
encoder.SetIndent("", " ")
|
||||
err = encoder.Encode(options)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return buffer.String(), nil
|
||||
}
|
||||
|
||||
// TODO include selectors
|
||||
func BuildConfig(opt HiddifyOptions, input option.Options) (*option.Options, error) {
|
||||
fmt.Printf("config options: %++v\n", opt)
|
||||
|
||||
var options option.Options
|
||||
if opt.EnableFullConfig {
|
||||
options.Inbounds = input.Inbounds
|
||||
options.DNS = input.DNS
|
||||
options.Route = input.Route
|
||||
}
|
||||
|
||||
setClashAPI(&options, &opt)
|
||||
setLog(&options, &opt)
|
||||
setInbound(&options, &opt)
|
||||
setDns(&options, &opt)
|
||||
setRoutingOptions(&options, &opt)
|
||||
setFakeDns(&options, &opt)
|
||||
err := setOutbounds(&options, &input, &opt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &options, nil
|
||||
}
|
||||
|
||||
func addForceDirect(options *option.Options, opt *HiddifyOptions, directDNSDomains map[string]bool) {
|
||||
remoteDNSAddress := opt.RemoteDnsAddress
|
||||
if strings.Contains(remoteDNSAddress, "://") {
|
||||
remoteDNSAddress = strings.SplitAfter(remoteDNSAddress, "://")[1]
|
||||
}
|
||||
parsedUrl, err := url.Parse(fmt.Sprintf("https://%s", remoteDNSAddress))
|
||||
if err == nil && net.ParseIP(parsedUrl.Host) == nil {
|
||||
directDNSDomains[parsedUrl.Host] = true
|
||||
}
|
||||
if len(directDNSDomains) > 0 {
|
||||
// trickDnsDomains := []string{}
|
||||
// directDNSDomains = removeDuplicateStr(directDNSDomains)
|
||||
// b, _ := batch.New(context.Background(), batch.WithConcurrencyNum[bool](10))
|
||||
// for _, d := range directDNSDomains {
|
||||
// b.Go(d, func() (bool, error) {
|
||||
// return isBlockedDomain(d), nil
|
||||
// })
|
||||
// }
|
||||
// b.Wait()
|
||||
// for domain, isBlock := range b.Result() {
|
||||
// if isBlock.Value {
|
||||
// trickDnsDomains = append(trickDnsDomains, domain)
|
||||
// }
|
||||
// }
|
||||
|
||||
// trickDomains := strings.Join(trickDnsDomains, ",")
|
||||
// trickRule := Rule{Domains: trickDomains, Outbound: OutboundBypassTag}
|
||||
// trickDnsRule := trickRule.MakeDNSRule()
|
||||
// trickDnsRule.Server = DNSTricksDirectTag
|
||||
// options.DNS.Rules = append([]option.DNSRule{{Type: C.RuleTypeDefault, DefaultOptions: trickDnsRule}}, options.DNS.Rules...)
|
||||
|
||||
directDNSDomainskeys := make([]string, 0, len(directDNSDomains))
|
||||
for key := range directDNSDomains {
|
||||
directDNSDomainskeys = append(directDNSDomainskeys, key)
|
||||
}
|
||||
|
||||
domains := strings.Join(directDNSDomainskeys, ",")
|
||||
directRule := Rule{Domains: domains, Outbound: OutboundBypassTag}
|
||||
dnsRule := directRule.MakeDNSRule()
|
||||
dnsRule.Server = DNSDirectTag
|
||||
options.DNS.Rules = append([]option.DNSRule{{Type: C.RuleTypeDefault, DefaultOptions: dnsRule}}, options.DNS.Rules...)
|
||||
}
|
||||
}
|
||||
|
||||
func setOutbounds(options *option.Options, input *option.Options, opt *HiddifyOptions) error {
|
||||
directDNSDomains := make(map[string]bool)
|
||||
var outbounds []option.Outbound
|
||||
var tags []string
|
||||
OutboundMainProxyTag = OutboundSelectTag
|
||||
// inbound==warp over proxies
|
||||
// outbound==proxies over warp
|
||||
if opt.Warp.EnableWarp {
|
||||
for _, out := range input.Outbounds {
|
||||
if out.Type == C.TypeCustom {
|
||||
if warp, ok := out.CustomOptions["warp"].(map[string]interface{}); ok {
|
||||
key, _ := warp["key"].(string)
|
||||
if key == "p1" {
|
||||
opt.Warp.EnableWarp = false
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if out.Type == C.TypeWireGuard && (out.WireGuardOptions.PrivateKey == opt.Warp.WireguardConfig.PrivateKey || out.WireGuardOptions.PrivateKey == "p1") {
|
||||
opt.Warp.EnableWarp = false
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if opt.Warp.EnableWarp && (opt.Warp.Mode == "warp_over_proxy" || opt.Warp.Mode == "proxy_over_warp") {
|
||||
out, err := GenerateWarpSingbox(opt.Warp.WireguardConfig, opt.Warp.CleanIP, opt.Warp.CleanPort, opt.Warp.FakePackets, opt.Warp.FakePacketSize, opt.Warp.FakePacketDelay, opt.Warp.FakePacketMode)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to generate warp config: %v", err)
|
||||
}
|
||||
out.Tag = "Hiddify Warp ✅"
|
||||
if opt.Warp.Mode == "warp_over_proxy" {
|
||||
out.WireGuardOptions.Detour = OutboundSelectTag
|
||||
OutboundMainProxyTag = out.Tag
|
||||
} else {
|
||||
out.WireGuardOptions.Detour = OutboundDirectTag
|
||||
}
|
||||
patchWarp(out, opt, true, nil)
|
||||
outbounds = append(outbounds, *out)
|
||||
// tags = append(tags, out.Tag)
|
||||
}
|
||||
for _, out := range input.Outbounds {
|
||||
outbound, serverDomain, err := patchOutbound(out, *opt, options.DNS.StaticIPs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if serverDomain != "" {
|
||||
directDNSDomains[serverDomain] = true
|
||||
}
|
||||
out = *outbound
|
||||
|
||||
switch out.Type {
|
||||
case C.TypeDirect, C.TypeBlock, C.TypeDNS:
|
||||
continue
|
||||
case C.TypeSelector, C.TypeURLTest:
|
||||
continue
|
||||
case C.TypeCustom:
|
||||
continue
|
||||
default:
|
||||
if !strings.Contains(out.Tag, "§hide§") {
|
||||
tags = append(tags, out.Tag)
|
||||
}
|
||||
out = patchHiddifyWarpFromConfig(out, *opt)
|
||||
outbounds = append(outbounds, out)
|
||||
}
|
||||
}
|
||||
|
||||
urlTest := option.Outbound{
|
||||
Type: C.TypeURLTest,
|
||||
Tag: OutboundURLTestTag,
|
||||
URLTestOptions: option.URLTestOutboundOptions{
|
||||
Outbounds: tags,
|
||||
URL: opt.ConnectionTestUrl,
|
||||
Interval: option.Duration(opt.URLTestInterval.Duration()),
|
||||
// IdleTimeout: option.Duration(opt.URLTestIdleTimeout.Duration()),
|
||||
Tolerance: 1,
|
||||
IdleTimeout: option.Duration(opt.URLTestInterval.Duration().Nanoseconds() * 3),
|
||||
InterruptExistConnections: true,
|
||||
},
|
||||
}
|
||||
defaultSelect := urlTest.Tag
|
||||
|
||||
for _, tag := range tags {
|
||||
if strings.Contains(tag, "§default§") {
|
||||
defaultSelect = "§default§"
|
||||
}
|
||||
}
|
||||
selector := option.Outbound{
|
||||
Type: C.TypeSelector,
|
||||
Tag: OutboundSelectTag,
|
||||
SelectorOptions: option.SelectorOutboundOptions{
|
||||
Outbounds: append([]string{urlTest.Tag}, tags...),
|
||||
Default: defaultSelect,
|
||||
InterruptExistConnections: true,
|
||||
},
|
||||
}
|
||||
|
||||
outbounds = append([]option.Outbound{selector, urlTest}, outbounds...)
|
||||
|
||||
options.Outbounds = append(
|
||||
outbounds,
|
||||
[]option.Outbound{
|
||||
{
|
||||
Tag: OutboundDNSTag,
|
||||
Type: C.TypeDNS,
|
||||
},
|
||||
{
|
||||
Tag: OutboundDirectTag,
|
||||
Type: C.TypeDirect,
|
||||
},
|
||||
{
|
||||
Tag: OutboundDirectFragmentTag,
|
||||
Type: C.TypeDirect,
|
||||
DirectOptions: option.DirectOutboundOptions{
|
||||
DialerOptions: option.DialerOptions{
|
||||
TCPFastOpen: false,
|
||||
TLSFragment: option.TLSFragmentOptions{
|
||||
Enabled: true,
|
||||
Size: opt.TLSTricks.FragmentSize,
|
||||
Sleep: opt.TLSTricks.FragmentSleep,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Tag: OutboundBypassTag,
|
||||
Type: C.TypeDirect,
|
||||
},
|
||||
{
|
||||
Tag: OutboundBlockTag,
|
||||
Type: C.TypeBlock,
|
||||
},
|
||||
}...,
|
||||
)
|
||||
|
||||
addForceDirect(options, opt, directDNSDomains)
|
||||
return nil
|
||||
}
|
||||
|
||||
func setClashAPI(options *option.Options, opt *HiddifyOptions) {
|
||||
if opt.EnableClashApi {
|
||||
if opt.ClashApiSecret == "" {
|
||||
opt.ClashApiSecret = generateRandomString(16)
|
||||
}
|
||||
options.Experimental = &option.ExperimentalOptions{
|
||||
ClashAPI: &option.ClashAPIOptions{
|
||||
ExternalController: fmt.Sprintf("%s:%d", "127.0.0.1", opt.ClashApiPort),
|
||||
Secret: opt.ClashApiSecret,
|
||||
},
|
||||
|
||||
CacheFile: &option.CacheFileOptions{
|
||||
Enabled: true,
|
||||
Path: "clash.db",
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func setLog(options *option.Options, opt *HiddifyOptions) {
|
||||
options.Log = &option.LogOptions{
|
||||
Level: opt.LogLevel,
|
||||
Output: opt.LogFile,
|
||||
Disabled: false,
|
||||
Timestamp: true,
|
||||
DisableColor: true,
|
||||
}
|
||||
}
|
||||
|
||||
func setInbound(options *option.Options, opt *HiddifyOptions) {
|
||||
var inboundDomainStrategy option.DomainStrategy
|
||||
if !opt.ResolveDestination {
|
||||
inboundDomainStrategy = option.DomainStrategy(dns.DomainStrategyAsIS)
|
||||
} else {
|
||||
inboundDomainStrategy = opt.IPv6Mode
|
||||
}
|
||||
if opt.EnableTunService {
|
||||
ActivateTunnelService(*opt)
|
||||
} else if opt.EnableTun {
|
||||
tunInbound := option.Inbound{
|
||||
Type: C.TypeTun,
|
||||
Tag: InboundTUNTag,
|
||||
|
||||
TunOptions: option.TunInboundOptions{
|
||||
Stack: opt.TUNStack,
|
||||
MTU: opt.MTU,
|
||||
AutoRoute: true,
|
||||
StrictRoute: opt.StrictRoute,
|
||||
EndpointIndependentNat: true,
|
||||
// GSO: runtime.GOOS != "windows",
|
||||
InboundOptions: option.InboundOptions{
|
||||
SniffEnabled: true,
|
||||
SniffOverrideDestination: false,
|
||||
DomainStrategy: inboundDomainStrategy,
|
||||
},
|
||||
},
|
||||
}
|
||||
switch opt.IPv6Mode {
|
||||
case option.DomainStrategy(dns.DomainStrategyUseIPv4):
|
||||
tunInbound.TunOptions.Inet4Address = []netip.Prefix{
|
||||
netip.MustParsePrefix("172.19.0.1/28"),
|
||||
}
|
||||
case option.DomainStrategy(dns.DomainStrategyUseIPv6):
|
||||
tunInbound.TunOptions.Inet6Address = []netip.Prefix{
|
||||
netip.MustParsePrefix("fdfe:dcba:9876::1/126"),
|
||||
}
|
||||
default:
|
||||
tunInbound.TunOptions.Inet4Address = []netip.Prefix{
|
||||
netip.MustParsePrefix("172.19.0.1/28"),
|
||||
}
|
||||
tunInbound.TunOptions.Inet6Address = []netip.Prefix{
|
||||
netip.MustParsePrefix("fdfe:dcba:9876::1/126"),
|
||||
}
|
||||
}
|
||||
options.Inbounds = append(options.Inbounds, tunInbound)
|
||||
|
||||
}
|
||||
|
||||
var bind string
|
||||
if opt.AllowConnectionFromLAN {
|
||||
bind = "0.0.0.0"
|
||||
} else {
|
||||
bind = "127.0.0.1"
|
||||
}
|
||||
|
||||
options.Inbounds = append(
|
||||
options.Inbounds,
|
||||
option.Inbound{
|
||||
Type: C.TypeMixed,
|
||||
Tag: InboundMixedTag,
|
||||
MixedOptions: option.HTTPMixedInboundOptions{
|
||||
ListenOptions: option.ListenOptions{
|
||||
Listen: option.NewListenAddress(netip.MustParseAddr(bind)),
|
||||
ListenPort: opt.MixedPort,
|
||||
InboundOptions: option.InboundOptions{
|
||||
SniffEnabled: true,
|
||||
SniffOverrideDestination: true,
|
||||
DomainStrategy: inboundDomainStrategy,
|
||||
},
|
||||
},
|
||||
SetSystemProxy: opt.SetSystemProxy,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
options.Inbounds = append(
|
||||
options.Inbounds,
|
||||
option.Inbound{
|
||||
Type: C.TypeDirect,
|
||||
Tag: InboundDNSTag,
|
||||
DirectOptions: option.DirectInboundOptions{
|
||||
ListenOptions: option.ListenOptions{
|
||||
Listen: option.NewListenAddress(netip.MustParseAddr(bind)),
|
||||
ListenPort: opt.LocalDnsPort,
|
||||
},
|
||||
// OverrideAddress: "1.1.1.1",
|
||||
// OverridePort: 53,
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
func setDns(options *option.Options, opt *HiddifyOptions) {
|
||||
options.DNS = &option.DNSOptions{
|
||||
StaticIPs: map[string][]string{},
|
||||
DNSClientOptions: option.DNSClientOptions{
|
||||
IndependentCache: opt.IndependentDNSCache,
|
||||
},
|
||||
Final: DNSRemoteTag,
|
||||
Servers: []option.DNSServerOptions{
|
||||
{
|
||||
Tag: DNSRemoteTag,
|
||||
Address: opt.RemoteDnsAddress,
|
||||
AddressResolver: DNSDirectTag,
|
||||
Strategy: opt.RemoteDnsDomainStrategy,
|
||||
},
|
||||
{
|
||||
Tag: DNSTricksDirectTag,
|
||||
Address: "https://sky.rethinkdns.com/",
|
||||
// AddressResolver: "dns-local",
|
||||
Strategy: opt.DirectDnsDomainStrategy,
|
||||
Detour: OutboundDirectFragmentTag,
|
||||
},
|
||||
{
|
||||
Tag: DNSDirectTag,
|
||||
Address: opt.DirectDnsAddress,
|
||||
AddressResolver: DNSLocalTag,
|
||||
Strategy: opt.DirectDnsDomainStrategy,
|
||||
Detour: OutboundDirectTag,
|
||||
},
|
||||
{
|
||||
Tag: DNSLocalTag,
|
||||
Address: "local",
|
||||
Detour: OutboundDirectTag,
|
||||
},
|
||||
{
|
||||
Tag: DNSBlockTag,
|
||||
Address: "rcode://success",
|
||||
},
|
||||
},
|
||||
}
|
||||
sky_rethinkdns := getIPs([]string{"www.speedtest.net", "sky.rethinkdns.com"})
|
||||
if len(sky_rethinkdns) > 0 {
|
||||
options.DNS.StaticIPs["sky.rethinkdns.com"] = sky_rethinkdns
|
||||
}
|
||||
}
|
||||
|
||||
func setFakeDns(options *option.Options, opt *HiddifyOptions) {
|
||||
if opt.EnableFakeDNS {
|
||||
inet4Range := netip.MustParsePrefix("198.18.0.0/15")
|
||||
inet6Range := netip.MustParsePrefix("fc00::/18")
|
||||
options.DNS.FakeIP = &option.DNSFakeIPOptions{
|
||||
Enabled: true,
|
||||
Inet4Range: &inet4Range,
|
||||
Inet6Range: &inet6Range,
|
||||
}
|
||||
options.DNS.Servers = append(
|
||||
options.DNS.Servers,
|
||||
option.DNSServerOptions{
|
||||
Tag: DNSFakeTag,
|
||||
Address: "fakeip",
|
||||
Strategy: option.DomainStrategy(dns.DomainStrategyUseIPv4),
|
||||
},
|
||||
)
|
||||
options.DNS.Rules = append(
|
||||
options.DNS.Rules,
|
||||
option.DNSRule{
|
||||
Type: C.RuleTypeDefault,
|
||||
DefaultOptions: option.DefaultDNSRule{
|
||||
Inbound: []string{InboundTUNTag},
|
||||
Server: DNSFakeTag,
|
||||
DisableCache: true,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
func setRoutingOptions(options *option.Options, opt *HiddifyOptions) {
|
||||
dnsRules := []option.DefaultDNSRule{}
|
||||
routeRules := []option.Rule{}
|
||||
rulesets := []option.RuleSet{}
|
||||
|
||||
if opt.EnableTun && runtime.GOOS == "android" {
|
||||
routeRules = append(
|
||||
routeRules,
|
||||
option.Rule{
|
||||
Type: C.RuleTypeDefault,
|
||||
|
||||
DefaultOptions: option.DefaultRule{
|
||||
Inbound: []string{InboundTUNTag},
|
||||
PackageName: []string{"app.brAccelerator.com"},
|
||||
Outbound: OutboundBypassTag,
|
||||
},
|
||||
},
|
||||
)
|
||||
// routeRules = append(
|
||||
// routeRules,
|
||||
// option.Rule{
|
||||
// Type: C.RuleTypeDefault,
|
||||
// DefaultOptions: option.DefaultRule{
|
||||
// ProcessName: []string{"Hiddify", "Hiddify.exe", "HiddifyCli", "HiddifyCli.exe"},
|
||||
// Outbound: OutboundBypassTag,
|
||||
// },
|
||||
// },
|
||||
// )
|
||||
}
|
||||
routeRules = append(routeRules, option.Rule{
|
||||
Type: C.RuleTypeDefault,
|
||||
DefaultOptions: option.DefaultRule{
|
||||
Inbound: []string{InboundDNSTag},
|
||||
Outbound: OutboundDNSTag,
|
||||
},
|
||||
})
|
||||
routeRules = append(routeRules, option.Rule{
|
||||
Type: C.RuleTypeDefault,
|
||||
DefaultOptions: option.DefaultRule{
|
||||
Port: []uint16{53},
|
||||
Outbound: OutboundDNSTag,
|
||||
},
|
||||
})
|
||||
|
||||
// {
|
||||
// Type: C.RuleTypeDefault,
|
||||
// DefaultOptions: option.DefaultRule{
|
||||
// ClashMode: "Direct",
|
||||
// Outbound: OutboundDirectTag,
|
||||
// },
|
||||
// },
|
||||
// {
|
||||
// Type: C.RuleTypeDefault,
|
||||
// DefaultOptions: option.DefaultRule{
|
||||
// ClashMode: "Global",
|
||||
// Outbound: OutboundMainProxyTag,
|
||||
// },
|
||||
// }, }
|
||||
|
||||
if opt.BypassLAN {
|
||||
routeRules = append(
|
||||
routeRules,
|
||||
option.Rule{
|
||||
Type: C.RuleTypeDefault,
|
||||
DefaultOptions: option.DefaultRule{
|
||||
// GeoIP: []string{"private"},
|
||||
IPIsPrivate: true,
|
||||
Outbound: OutboundBypassTag,
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
for _, rule := range opt.Rules {
|
||||
routeRule := rule.MakeRule()
|
||||
switch rule.Outbound {
|
||||
case "bypass":
|
||||
routeRule.Outbound = OutboundBypassTag
|
||||
case "block":
|
||||
routeRule.Outbound = OutboundBlockTag
|
||||
case "proxy":
|
||||
routeRule.Outbound = OutboundMainProxyTag
|
||||
}
|
||||
|
||||
if routeRule.IsValid() {
|
||||
routeRules = append(
|
||||
routeRules,
|
||||
option.Rule{
|
||||
Type: C.RuleTypeDefault,
|
||||
DefaultOptions: routeRule,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
dnsRule := rule.MakeDNSRule()
|
||||
switch rule.Outbound {
|
||||
case "bypass":
|
||||
dnsRule.Server = DNSDirectTag
|
||||
case "block":
|
||||
dnsRule.Server = DNSBlockTag
|
||||
dnsRule.DisableCache = true
|
||||
case "proxy":
|
||||
if opt.EnableFakeDNS {
|
||||
fakeDnsRule := dnsRule
|
||||
fakeDnsRule.Server = DNSFakeTag
|
||||
fakeDnsRule.Inbound = []string{InboundTUNTag, InboundMixedTag}
|
||||
dnsRules = append(dnsRules, fakeDnsRule)
|
||||
}
|
||||
dnsRule.Server = DNSRemoteTag
|
||||
}
|
||||
dnsRules = append(dnsRules, dnsRule)
|
||||
}
|
||||
|
||||
parsedURL, err := url.Parse(opt.ConnectionTestUrl)
|
||||
if err == nil {
|
||||
var dnsCPttl uint32 = 3000
|
||||
dnsRules = append(dnsRules, option.DefaultDNSRule{
|
||||
Domain: []string{parsedURL.Host},
|
||||
Server: DNSRemoteTag,
|
||||
RewriteTTL: &dnsCPttl,
|
||||
DisableCache: false,
|
||||
})
|
||||
}
|
||||
|
||||
if opt.BlockAds {
|
||||
rulesets = append(rulesets, option.RuleSet{
|
||||
Type: C.RuleSetTypeRemote,
|
||||
Tag: "geosite-ads",
|
||||
Format: C.RuleSetFormatBinary,
|
||||
RemoteOptions: option.RemoteRuleSet{
|
||||
URL: "https://raw.githubusercontent.com/hiddify/hiddify-geo/rule-set/block/geosite-category-ads-all.srs",
|
||||
UpdateInterval: option.Duration(5 * time.Hour * 24),
|
||||
},
|
||||
})
|
||||
rulesets = append(rulesets, option.RuleSet{
|
||||
Type: C.RuleSetTypeRemote,
|
||||
Tag: "geosite-malware",
|
||||
Format: C.RuleSetFormatBinary,
|
||||
RemoteOptions: option.RemoteRuleSet{
|
||||
URL: "https://raw.githubusercontent.com/hiddify/hiddify-geo/rule-set/block/geosite-malware.srs",
|
||||
UpdateInterval: option.Duration(5 * time.Hour * 24),
|
||||
},
|
||||
})
|
||||
rulesets = append(rulesets, option.RuleSet{
|
||||
Type: C.RuleSetTypeRemote,
|
||||
Tag: "geosite-phishing",
|
||||
Format: C.RuleSetFormatBinary,
|
||||
RemoteOptions: option.RemoteRuleSet{
|
||||
URL: "https://raw.githubusercontent.com/hiddify/hiddify-geo/rule-set/block/geosite-phishing.srs",
|
||||
UpdateInterval: option.Duration(5 * time.Hour * 24),
|
||||
},
|
||||
})
|
||||
rulesets = append(rulesets, option.RuleSet{
|
||||
Type: C.RuleSetTypeRemote,
|
||||
Tag: "geosite-cryptominers",
|
||||
Format: C.RuleSetFormatBinary,
|
||||
RemoteOptions: option.RemoteRuleSet{
|
||||
URL: "https://raw.githubusercontent.com/hiddify/hiddify-geo/rule-set/block/geosite-cryptominers.srs",
|
||||
UpdateInterval: option.Duration(5 * time.Hour * 24),
|
||||
},
|
||||
})
|
||||
rulesets = append(rulesets, option.RuleSet{
|
||||
Type: C.RuleSetTypeRemote,
|
||||
Tag: "geoip-phishing",
|
||||
Format: C.RuleSetFormatBinary,
|
||||
RemoteOptions: option.RemoteRuleSet{
|
||||
URL: "https://raw.githubusercontent.com/hiddify/hiddify-geo/rule-set/block/geoip-phishing.srs",
|
||||
UpdateInterval: option.Duration(5 * time.Hour * 24),
|
||||
},
|
||||
})
|
||||
rulesets = append(rulesets, option.RuleSet{
|
||||
Type: C.RuleSetTypeRemote,
|
||||
Tag: "geoip-malware",
|
||||
Format: C.RuleSetFormatBinary,
|
||||
RemoteOptions: option.RemoteRuleSet{
|
||||
URL: "https://raw.githubusercontent.com/hiddify/hiddify-geo/rule-set/block/geoip-malware.srs",
|
||||
UpdateInterval: option.Duration(5 * time.Hour * 24),
|
||||
},
|
||||
})
|
||||
|
||||
routeRules = append(routeRules, option.Rule{
|
||||
Type: C.RuleTypeDefault,
|
||||
DefaultOptions: option.DefaultRule{
|
||||
RuleSet: []string{
|
||||
"geosite-ads",
|
||||
"geosite-malware",
|
||||
"geosite-phishing",
|
||||
"geosite-cryptominers",
|
||||
"geoip-malware",
|
||||
"geoip-phishing",
|
||||
},
|
||||
Outbound: OutboundBlockTag,
|
||||
},
|
||||
})
|
||||
dnsRules = append(dnsRules, option.DefaultDNSRule{
|
||||
RuleSet: []string{
|
||||
"geosite-ads",
|
||||
"geosite-malware",
|
||||
"geosite-phishing",
|
||||
"geosite-cryptominers",
|
||||
"geoip-malware",
|
||||
"geoip-phishing",
|
||||
},
|
||||
Server: DNSBlockTag,
|
||||
// DisableCache: true,
|
||||
})
|
||||
|
||||
}
|
||||
if opt.Region != "other" {
|
||||
dnsRules = append(dnsRules, option.DefaultDNSRule{
|
||||
DomainSuffix: []string{"." + opt.Region},
|
||||
Server: DNSDirectTag,
|
||||
})
|
||||
routeRules = append(routeRules, option.Rule{
|
||||
Type: C.RuleTypeDefault,
|
||||
DefaultOptions: option.DefaultRule{
|
||||
DomainSuffix: []string{"." + opt.Region},
|
||||
Outbound: OutboundDirectTag,
|
||||
},
|
||||
})
|
||||
dnsRules = append(dnsRules, option.DefaultDNSRule{
|
||||
RuleSet: []string{
|
||||
"geoip-" + opt.Region,
|
||||
"geosite-" + opt.Region,
|
||||
},
|
||||
Server: DNSDirectTag,
|
||||
})
|
||||
|
||||
rulesets = append(rulesets, option.RuleSet{
|
||||
Type: C.RuleSetTypeRemote,
|
||||
Tag: "geoip-" + opt.Region,
|
||||
Format: C.RuleSetFormatBinary,
|
||||
RemoteOptions: option.RemoteRuleSet{
|
||||
URL: "https://raw.githubusercontent.com/hiddify/hiddify-geo/rule-set/country/geoip-" + opt.Region + ".srs",
|
||||
UpdateInterval: option.Duration(5 * time.Hour * 24),
|
||||
},
|
||||
})
|
||||
rulesets = append(rulesets, option.RuleSet{
|
||||
Type: C.RuleSetTypeRemote,
|
||||
Tag: "geosite-" + opt.Region,
|
||||
Format: C.RuleSetFormatBinary,
|
||||
RemoteOptions: option.RemoteRuleSet{
|
||||
URL: "https://raw.githubusercontent.com/hiddify/hiddify-geo/rule-set/country/geosite-" + opt.Region + ".srs",
|
||||
UpdateInterval: option.Duration(5 * time.Hour * 24),
|
||||
},
|
||||
})
|
||||
|
||||
routeRules = append(routeRules, option.Rule{
|
||||
Type: C.RuleTypeDefault,
|
||||
DefaultOptions: option.DefaultRule{
|
||||
RuleSet: []string{
|
||||
"geoip-" + opt.Region,
|
||||
"geosite-" + opt.Region,
|
||||
},
|
||||
Outbound: OutboundDirectTag,
|
||||
},
|
||||
})
|
||||
|
||||
}
|
||||
options.Route = &option.RouteOptions{
|
||||
Rules: routeRules,
|
||||
Final: OutboundMainProxyTag,
|
||||
AutoDetectInterface: true,
|
||||
OverrideAndroidVPN: true,
|
||||
RuleSet: rulesets,
|
||||
// GeoIP: &option.GeoIPOptions{
|
||||
// Path: opt.GeoIPPath,
|
||||
// },
|
||||
// Geosite: &option.GeositeOptions{
|
||||
// Path: opt.GeoSitePath,
|
||||
// },
|
||||
}
|
||||
if opt.EnableDNSRouting {
|
||||
for _, dnsRule := range dnsRules {
|
||||
if dnsRule.IsValid() {
|
||||
options.DNS.Rules = append(
|
||||
options.DNS.Rules,
|
||||
option.DNSRule{
|
||||
Type: C.RuleTypeDefault,
|
||||
DefaultOptions: dnsRule,
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func patchHiddifyWarpFromConfig(out option.Outbound, opt HiddifyOptions) option.Outbound {
|
||||
if opt.Warp.EnableWarp && opt.Warp.Mode == "proxy_over_warp" {
|
||||
if out.DirectOptions.Detour == "" {
|
||||
out.DirectOptions.Detour = "Hiddify Warp ✅"
|
||||
}
|
||||
if out.HTTPOptions.Detour == "" {
|
||||
out.HTTPOptions.Detour = "Hiddify Warp ✅"
|
||||
}
|
||||
if out.Hysteria2Options.Detour == "" {
|
||||
out.Hysteria2Options.Detour = "Hiddify Warp ✅"
|
||||
}
|
||||
if out.HysteriaOptions.Detour == "" {
|
||||
out.HysteriaOptions.Detour = "Hiddify Warp ✅"
|
||||
}
|
||||
if out.SSHOptions.Detour == "" {
|
||||
out.SSHOptions.Detour = "Hiddify Warp ✅"
|
||||
}
|
||||
if out.ShadowTLSOptions.Detour == "" {
|
||||
out.ShadowTLSOptions.Detour = "Hiddify Warp ✅"
|
||||
}
|
||||
if out.ShadowsocksOptions.Detour == "" {
|
||||
out.ShadowsocksOptions.Detour = "Hiddify Warp ✅"
|
||||
}
|
||||
if out.ShadowsocksROptions.Detour == "" {
|
||||
out.ShadowsocksROptions.Detour = "Hiddify Warp ✅"
|
||||
}
|
||||
if out.SocksOptions.Detour == "" {
|
||||
out.SocksOptions.Detour = "Hiddify Warp ✅"
|
||||
}
|
||||
if out.TUICOptions.Detour == "" {
|
||||
out.TUICOptions.Detour = "Hiddify Warp ✅"
|
||||
}
|
||||
if out.TorOptions.Detour == "" {
|
||||
out.TorOptions.Detour = "Hiddify Warp ✅"
|
||||
}
|
||||
if out.TrojanOptions.Detour == "" {
|
||||
out.TrojanOptions.Detour = "Hiddify Warp ✅"
|
||||
}
|
||||
if out.VLESSOptions.Detour == "" {
|
||||
out.VLESSOptions.Detour = "Hiddify Warp ✅"
|
||||
}
|
||||
if out.VMessOptions.Detour == "" {
|
||||
out.VMessOptions.Detour = "Hiddify Warp ✅"
|
||||
}
|
||||
if out.WireGuardOptions.Detour == "" {
|
||||
out.WireGuardOptions.Detour = "Hiddify Warp ✅"
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func getIPs(domains []string) []string {
|
||||
res := []string{}
|
||||
for _, d := range domains {
|
||||
ips, err := net.LookupHost(d)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
for _, ip := range ips {
|
||||
if !strings.HasPrefix(ip, "10.") {
|
||||
res = append(res, ip)
|
||||
}
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func isBlockedDomain(domain string) bool {
|
||||
if strings.HasPrefix("full:", domain) {
|
||||
return false
|
||||
}
|
||||
ips, err := net.LookupHost(domain)
|
||||
if err != nil {
|
||||
// fmt.Println(err)
|
||||
return true
|
||||
}
|
||||
|
||||
// Print the IP addresses associated with the domain
|
||||
fmt.Printf("IP addresses for %s:\n", domain)
|
||||
for _, ip := range ips {
|
||||
if strings.HasPrefix(ip, "10.") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func removeDuplicateStr(strSlice []string) []string {
|
||||
allKeys := make(map[string]bool)
|
||||
list := []string{}
|
||||
for _, item := range strSlice {
|
||||
if _, value := allKeys[item]; !value {
|
||||
allKeys[item] = true
|
||||
list = append(list, item)
|
||||
}
|
||||
}
|
||||
return list
|
||||
}
|
||||
|
||||
func generateRandomString(length int) string {
|
||||
// Determine the number of bytes needed
|
||||
bytesNeeded := (length*6 + 7) / 8
|
||||
|
||||
// Generate random bytes
|
||||
randomBytes := make([]byte, bytesNeeded)
|
||||
_, err := rand.Read(randomBytes)
|
||||
if err != nil {
|
||||
return "hiddify"
|
||||
}
|
||||
|
||||
// Encode random bytes to base64
|
||||
randomString := base64.URLEncoding.EncodeToString(randomBytes)
|
||||
|
||||
// Trim padding characters and return the string
|
||||
return randomString[:length]
|
||||
}
|
||||
@ -1,8 +0,0 @@
|
||||
{
|
||||
"log": {},
|
||||
"dns": {},
|
||||
"inbounds": [],
|
||||
"outbounds": [],
|
||||
"route": {},
|
||||
"experimental": {}
|
||||
}
|
||||
@ -1,6 +0,0 @@
|
||||
package config
|
||||
|
||||
const (
|
||||
WarpOverProxy = "warp_over_proxy"
|
||||
ProxyOverWarp = "proxy_over_warp"
|
||||
)
|
||||
@ -1,389 +0,0 @@
|
||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-go v1.33.0
|
||||
// protoc v4.25.3
|
||||
// source: core.proto
|
||||
|
||||
package config
|
||||
|
||||
import (
|
||||
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
|
||||
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
|
||||
reflect "reflect"
|
||||
sync "sync"
|
||||
)
|
||||
|
||||
const (
|
||||
// Verify that this generated code is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
|
||||
// Verify that runtime/protoimpl is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
|
||||
)
|
||||
|
||||
type ParseConfigRequest struct {
|
||||
state protoimpl.MessageState
|
||||
sizeCache protoimpl.SizeCache
|
||||
unknownFields protoimpl.UnknownFields
|
||||
|
||||
TempPath string `protobuf:"bytes,1,opt,name=tempPath,proto3" json:"tempPath,omitempty"`
|
||||
Path string `protobuf:"bytes,2,opt,name=path,proto3" json:"path,omitempty"`
|
||||
Debug bool `protobuf:"varint,3,opt,name=debug,proto3" json:"debug,omitempty"`
|
||||
}
|
||||
|
||||
func (x *ParseConfigRequest) Reset() {
|
||||
*x = ParseConfigRequest{}
|
||||
if protoimpl.UnsafeEnabled {
|
||||
mi := &file_core_proto_msgTypes[0]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
}
|
||||
|
||||
func (x *ParseConfigRequest) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*ParseConfigRequest) ProtoMessage() {}
|
||||
|
||||
func (x *ParseConfigRequest) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_core_proto_msgTypes[0]
|
||||
if protoimpl.UnsafeEnabled && x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use ParseConfigRequest.ProtoReflect.Descriptor instead.
|
||||
func (*ParseConfigRequest) Descriptor() ([]byte, []int) {
|
||||
return file_core_proto_rawDescGZIP(), []int{0}
|
||||
}
|
||||
|
||||
func (x *ParseConfigRequest) GetTempPath() string {
|
||||
if x != nil {
|
||||
return x.TempPath
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *ParseConfigRequest) GetPath() string {
|
||||
if x != nil {
|
||||
return x.Path
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *ParseConfigRequest) GetDebug() bool {
|
||||
if x != nil {
|
||||
return x.Debug
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type ParseConfigResponse struct {
|
||||
state protoimpl.MessageState
|
||||
sizeCache protoimpl.SizeCache
|
||||
unknownFields protoimpl.UnknownFields
|
||||
|
||||
Error *string `protobuf:"bytes,1,opt,name=error,proto3,oneof" json:"error,omitempty"`
|
||||
}
|
||||
|
||||
func (x *ParseConfigResponse) Reset() {
|
||||
*x = ParseConfigResponse{}
|
||||
if protoimpl.UnsafeEnabled {
|
||||
mi := &file_core_proto_msgTypes[1]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
}
|
||||
|
||||
func (x *ParseConfigResponse) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*ParseConfigResponse) ProtoMessage() {}
|
||||
|
||||
func (x *ParseConfigResponse) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_core_proto_msgTypes[1]
|
||||
if protoimpl.UnsafeEnabled && x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use ParseConfigResponse.ProtoReflect.Descriptor instead.
|
||||
func (*ParseConfigResponse) Descriptor() ([]byte, []int) {
|
||||
return file_core_proto_rawDescGZIP(), []int{1}
|
||||
}
|
||||
|
||||
func (x *ParseConfigResponse) GetError() string {
|
||||
if x != nil && x.Error != nil {
|
||||
return *x.Error
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type GenerateConfigRequest struct {
|
||||
state protoimpl.MessageState
|
||||
sizeCache protoimpl.SizeCache
|
||||
unknownFields protoimpl.UnknownFields
|
||||
|
||||
Path string `protobuf:"bytes,1,opt,name=path,proto3" json:"path,omitempty"`
|
||||
Debug bool `protobuf:"varint,2,opt,name=debug,proto3" json:"debug,omitempty"`
|
||||
}
|
||||
|
||||
func (x *GenerateConfigRequest) Reset() {
|
||||
*x = GenerateConfigRequest{}
|
||||
if protoimpl.UnsafeEnabled {
|
||||
mi := &file_core_proto_msgTypes[2]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
}
|
||||
|
||||
func (x *GenerateConfigRequest) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*GenerateConfigRequest) ProtoMessage() {}
|
||||
|
||||
func (x *GenerateConfigRequest) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_core_proto_msgTypes[2]
|
||||
if protoimpl.UnsafeEnabled && x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use GenerateConfigRequest.ProtoReflect.Descriptor instead.
|
||||
func (*GenerateConfigRequest) Descriptor() ([]byte, []int) {
|
||||
return file_core_proto_rawDescGZIP(), []int{2}
|
||||
}
|
||||
|
||||
func (x *GenerateConfigRequest) GetPath() string {
|
||||
if x != nil {
|
||||
return x.Path
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *GenerateConfigRequest) GetDebug() bool {
|
||||
if x != nil {
|
||||
return x.Debug
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type GenerateConfigResponse struct {
|
||||
state protoimpl.MessageState
|
||||
sizeCache protoimpl.SizeCache
|
||||
unknownFields protoimpl.UnknownFields
|
||||
|
||||
Config string `protobuf:"bytes,1,opt,name=config,proto3" json:"config,omitempty"`
|
||||
Error *string `protobuf:"bytes,2,opt,name=error,proto3,oneof" json:"error,omitempty"`
|
||||
}
|
||||
|
||||
func (x *GenerateConfigResponse) Reset() {
|
||||
*x = GenerateConfigResponse{}
|
||||
if protoimpl.UnsafeEnabled {
|
||||
mi := &file_core_proto_msgTypes[3]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
}
|
||||
|
||||
func (x *GenerateConfigResponse) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*GenerateConfigResponse) ProtoMessage() {}
|
||||
|
||||
func (x *GenerateConfigResponse) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_core_proto_msgTypes[3]
|
||||
if protoimpl.UnsafeEnabled && x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use GenerateConfigResponse.ProtoReflect.Descriptor instead.
|
||||
func (*GenerateConfigResponse) Descriptor() ([]byte, []int) {
|
||||
return file_core_proto_rawDescGZIP(), []int{3}
|
||||
}
|
||||
|
||||
func (x *GenerateConfigResponse) GetConfig() string {
|
||||
if x != nil {
|
||||
return x.Config
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *GenerateConfigResponse) GetError() string {
|
||||
if x != nil && x.Error != nil {
|
||||
return *x.Error
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
var File_core_proto protoreflect.FileDescriptor
|
||||
|
||||
var file_core_proto_rawDesc = []byte{
|
||||
0x0a, 0x0a, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0d, 0x43, 0x6f,
|
||||
0x6e, 0x66, 0x69, 0x67, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x22, 0x5a, 0x0a, 0x12, 0x50,
|
||||
0x61, 0x72, 0x73, 0x65, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73,
|
||||
0x74, 0x12, 0x1a, 0x0a, 0x08, 0x74, 0x65, 0x6d, 0x70, 0x50, 0x61, 0x74, 0x68, 0x18, 0x01, 0x20,
|
||||
0x01, 0x28, 0x09, 0x52, 0x08, 0x74, 0x65, 0x6d, 0x70, 0x50, 0x61, 0x74, 0x68, 0x12, 0x12, 0x0a,
|
||||
0x04, 0x70, 0x61, 0x74, 0x68, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x70, 0x61, 0x74,
|
||||
0x68, 0x12, 0x14, 0x0a, 0x05, 0x64, 0x65, 0x62, 0x75, 0x67, 0x18, 0x03, 0x20, 0x01, 0x28, 0x08,
|
||||
0x52, 0x05, 0x64, 0x65, 0x62, 0x75, 0x67, 0x22, 0x3a, 0x0a, 0x13, 0x50, 0x61, 0x72, 0x73, 0x65,
|
||||
0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x19,
|
||||
0x0a, 0x05, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x48, 0x00, 0x52,
|
||||
0x05, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x88, 0x01, 0x01, 0x42, 0x08, 0x0a, 0x06, 0x5f, 0x65, 0x72,
|
||||
0x72, 0x6f, 0x72, 0x22, 0x41, 0x0a, 0x15, 0x47, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x74, 0x65, 0x43,
|
||||
0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x12, 0x0a, 0x04,
|
||||
0x70, 0x61, 0x74, 0x68, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x70, 0x61, 0x74, 0x68,
|
||||
0x12, 0x14, 0x0a, 0x05, 0x64, 0x65, 0x62, 0x75, 0x67, 0x18, 0x02, 0x20, 0x01, 0x28, 0x08, 0x52,
|
||||
0x05, 0x64, 0x65, 0x62, 0x75, 0x67, 0x22, 0x55, 0x0a, 0x16, 0x47, 0x65, 0x6e, 0x65, 0x72, 0x61,
|
||||
0x74, 0x65, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65,
|
||||
0x12, 0x16, 0x0a, 0x06, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09,
|
||||
0x52, 0x06, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x19, 0x0a, 0x05, 0x65, 0x72, 0x72, 0x6f,
|
||||
0x72, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x48, 0x00, 0x52, 0x05, 0x65, 0x72, 0x72, 0x6f, 0x72,
|
||||
0x88, 0x01, 0x01, 0x42, 0x08, 0x0a, 0x06, 0x5f, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x32, 0xc6, 0x01,
|
||||
0x0a, 0x0b, 0x43, 0x6f, 0x72, 0x65, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x54, 0x0a,
|
||||
0x0b, 0x50, 0x61, 0x72, 0x73, 0x65, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x21, 0x2e, 0x43,
|
||||
0x6f, 0x6e, 0x66, 0x69, 0x67, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x50, 0x61, 0x72,
|
||||
0x73, 0x65, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a,
|
||||
0x22, 0x2e, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e,
|
||||
0x50, 0x61, 0x72, 0x73, 0x65, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x65, 0x73, 0x70, 0x6f,
|
||||
0x6e, 0x73, 0x65, 0x12, 0x61, 0x0a, 0x12, 0x47, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x74, 0x65, 0x46,
|
||||
0x75, 0x6c, 0x6c, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x24, 0x2e, 0x43, 0x6f, 0x6e, 0x66,
|
||||
0x69, 0x67, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x47, 0x65, 0x6e, 0x65, 0x72, 0x61,
|
||||
0x74, 0x65, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a,
|
||||
0x25, 0x2e, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e,
|
||||
0x47, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x74, 0x65, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x65,
|
||||
0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x42, 0x0b, 0x5a, 0x09, 0x2e, 0x2e, 0x2f, 0x63, 0x6f, 0x6e,
|
||||
0x66, 0x69, 0x67, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
|
||||
}
|
||||
|
||||
var (
|
||||
file_core_proto_rawDescOnce sync.Once
|
||||
file_core_proto_rawDescData = file_core_proto_rawDesc
|
||||
)
|
||||
|
||||
func file_core_proto_rawDescGZIP() []byte {
|
||||
file_core_proto_rawDescOnce.Do(func() {
|
||||
file_core_proto_rawDescData = protoimpl.X.CompressGZIP(file_core_proto_rawDescData)
|
||||
})
|
||||
return file_core_proto_rawDescData
|
||||
}
|
||||
|
||||
var file_core_proto_msgTypes = make([]protoimpl.MessageInfo, 4)
|
||||
var file_core_proto_goTypes = []interface{}{
|
||||
(*ParseConfigRequest)(nil), // 0: HiddifyOptions.ParseConfigRequest
|
||||
(*ParseConfigResponse)(nil), // 1: HiddifyOptions.ParseConfigResponse
|
||||
(*GenerateConfigRequest)(nil), // 2: HiddifyOptions.GenerateConfigRequest
|
||||
(*GenerateConfigResponse)(nil), // 3: HiddifyOptions.GenerateConfigResponse
|
||||
}
|
||||
var file_core_proto_depIdxs = []int32{
|
||||
0, // 0: HiddifyOptions.CoreService.ParseConfig:input_type -> HiddifyOptions.ParseConfigRequest
|
||||
2, // 1: HiddifyOptions.CoreService.GenerateFullConfig:input_type -> HiddifyOptions.GenerateConfigRequest
|
||||
1, // 2: HiddifyOptions.CoreService.ParseConfig:output_type -> HiddifyOptions.ParseConfigResponse
|
||||
3, // 3: HiddifyOptions.CoreService.GenerateFullConfig:output_type -> HiddifyOptions.GenerateConfigResponse
|
||||
2, // [2:4] is the sub-list for method output_type
|
||||
0, // [0:2] is the sub-list for method input_type
|
||||
0, // [0:0] is the sub-list for extension type_name
|
||||
0, // [0:0] is the sub-list for extension extendee
|
||||
0, // [0:0] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_core_proto_init() }
|
||||
func file_core_proto_init() {
|
||||
if File_core_proto != nil {
|
||||
return
|
||||
}
|
||||
if !protoimpl.UnsafeEnabled {
|
||||
file_core_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
|
||||
switch v := v.(*ParseConfigRequest); i {
|
||||
case 0:
|
||||
return &v.state
|
||||
case 1:
|
||||
return &v.sizeCache
|
||||
case 2:
|
||||
return &v.unknownFields
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
file_core_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
|
||||
switch v := v.(*ParseConfigResponse); i {
|
||||
case 0:
|
||||
return &v.state
|
||||
case 1:
|
||||
return &v.sizeCache
|
||||
case 2:
|
||||
return &v.unknownFields
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
file_core_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} {
|
||||
switch v := v.(*GenerateConfigRequest); i {
|
||||
case 0:
|
||||
return &v.state
|
||||
case 1:
|
||||
return &v.sizeCache
|
||||
case 2:
|
||||
return &v.unknownFields
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
file_core_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} {
|
||||
switch v := v.(*GenerateConfigResponse); i {
|
||||
case 0:
|
||||
return &v.state
|
||||
case 1:
|
||||
return &v.sizeCache
|
||||
case 2:
|
||||
return &v.unknownFields
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
file_core_proto_msgTypes[1].OneofWrappers = []interface{}{}
|
||||
file_core_proto_msgTypes[3].OneofWrappers = []interface{}{}
|
||||
type x struct{}
|
||||
out := protoimpl.TypeBuilder{
|
||||
File: protoimpl.DescBuilder{
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: file_core_proto_rawDesc,
|
||||
NumEnums: 0,
|
||||
NumMessages: 4,
|
||||
NumExtensions: 0,
|
||||
NumServices: 1,
|
||||
},
|
||||
GoTypes: file_core_proto_goTypes,
|
||||
DependencyIndexes: file_core_proto_depIdxs,
|
||||
MessageInfos: file_core_proto_msgTypes,
|
||||
}.Build()
|
||||
File_core_proto = out.File
|
||||
file_core_proto_rawDesc = nil
|
||||
file_core_proto_goTypes = nil
|
||||
file_core_proto_depIdxs = nil
|
||||
}
|
||||
@ -1,146 +0,0 @@
|
||||
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
|
||||
// versions:
|
||||
// - protoc-gen-go-grpc v1.3.0
|
||||
// - protoc v4.25.3
|
||||
// source: core.proto
|
||||
|
||||
package config
|
||||
|
||||
import (
|
||||
context "context"
|
||||
grpc "google.golang.org/grpc"
|
||||
codes "google.golang.org/grpc/codes"
|
||||
status "google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// This is a compile-time assertion to ensure that this generated file
|
||||
// is compatible with the grpc package it is being compiled against.
|
||||
// Requires gRPC-Go v1.32.0 or later.
|
||||
const _ = grpc.SupportPackageIsVersion7
|
||||
|
||||
const (
|
||||
CoreService_ParseConfig_FullMethodName = "/HiddifyOptions.CoreService/ParseConfig"
|
||||
CoreService_GenerateFullConfig_FullMethodName = "/HiddifyOptions.CoreService/GenerateFullConfig"
|
||||
)
|
||||
|
||||
// CoreServiceClient is the client API for CoreService service.
|
||||
//
|
||||
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
|
||||
type CoreServiceClient interface {
|
||||
ParseConfig(ctx context.Context, in *ParseConfigRequest, opts ...grpc.CallOption) (*ParseConfigResponse, error)
|
||||
GenerateFullConfig(ctx context.Context, in *GenerateConfigRequest, opts ...grpc.CallOption) (*GenerateConfigResponse, error)
|
||||
}
|
||||
|
||||
type coreServiceClient struct {
|
||||
cc grpc.ClientConnInterface
|
||||
}
|
||||
|
||||
func NewCoreServiceClient(cc grpc.ClientConnInterface) CoreServiceClient {
|
||||
return &coreServiceClient{cc}
|
||||
}
|
||||
|
||||
func (c *coreServiceClient) ParseConfig(ctx context.Context, in *ParseConfigRequest, opts ...grpc.CallOption) (*ParseConfigResponse, error) {
|
||||
out := new(ParseConfigResponse)
|
||||
err := c.cc.Invoke(ctx, CoreService_ParseConfig_FullMethodName, in, out, opts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *coreServiceClient) GenerateFullConfig(ctx context.Context, in *GenerateConfigRequest, opts ...grpc.CallOption) (*GenerateConfigResponse, error) {
|
||||
out := new(GenerateConfigResponse)
|
||||
err := c.cc.Invoke(ctx, CoreService_GenerateFullConfig_FullMethodName, in, out, opts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// CoreServiceServer is the server API for CoreService service.
|
||||
// All implementations must embed UnimplementedCoreServiceServer
|
||||
// for forward compatibility
|
||||
type CoreServiceServer interface {
|
||||
ParseConfig(context.Context, *ParseConfigRequest) (*ParseConfigResponse, error)
|
||||
GenerateFullConfig(context.Context, *GenerateConfigRequest) (*GenerateConfigResponse, error)
|
||||
mustEmbedUnimplementedCoreServiceServer()
|
||||
}
|
||||
|
||||
// UnimplementedCoreServiceServer must be embedded to have forward compatible implementations.
|
||||
type UnimplementedCoreServiceServer struct {
|
||||
}
|
||||
|
||||
func (UnimplementedCoreServiceServer) ParseConfig(context.Context, *ParseConfigRequest) (*ParseConfigResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method ParseConfig not implemented")
|
||||
}
|
||||
func (UnimplementedCoreServiceServer) GenerateFullConfig(context.Context, *GenerateConfigRequest) (*GenerateConfigResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method GenerateFullConfig not implemented")
|
||||
}
|
||||
func (UnimplementedCoreServiceServer) mustEmbedUnimplementedCoreServiceServer() {}
|
||||
|
||||
// UnsafeCoreServiceServer may be embedded to opt out of forward compatibility for this service.
|
||||
// Use of this interface is not recommended, as added methods to CoreServiceServer will
|
||||
// result in compilation errors.
|
||||
type UnsafeCoreServiceServer interface {
|
||||
mustEmbedUnimplementedCoreServiceServer()
|
||||
}
|
||||
|
||||
func RegisterCoreServiceServer(s grpc.ServiceRegistrar, srv CoreServiceServer) {
|
||||
s.RegisterService(&CoreService_ServiceDesc, srv)
|
||||
}
|
||||
|
||||
func _CoreService_ParseConfig_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(ParseConfigRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(CoreServiceServer).ParseConfig(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: CoreService_ParseConfig_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(CoreServiceServer).ParseConfig(ctx, req.(*ParseConfigRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _CoreService_GenerateFullConfig_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(GenerateConfigRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(CoreServiceServer).GenerateFullConfig(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: CoreService_GenerateFullConfig_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(CoreServiceServer).GenerateFullConfig(ctx, req.(*GenerateConfigRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
// CoreService_ServiceDesc is the grpc.ServiceDesc for CoreService service.
|
||||
// It's only intended for direct use with grpc.RegisterService,
|
||||
// and not to be introspected or modified (even as a copy)
|
||||
var CoreService_ServiceDesc = grpc.ServiceDesc{
|
||||
ServiceName: "HiddifyOptions.CoreService",
|
||||
HandlerType: (*CoreServiceServer)(nil),
|
||||
Methods: []grpc.MethodDesc{
|
||||
{
|
||||
MethodName: "ParseConfig",
|
||||
Handler: _CoreService_ParseConfig_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "GenerateFullConfig",
|
||||
Handler: _CoreService_GenerateFullConfig_Handler,
|
||||
},
|
||||
},
|
||||
Streams: []grpc.StreamDesc{},
|
||||
Metadata: "core.proto",
|
||||
}
|
||||
@ -1,45 +0,0 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime/debug"
|
||||
|
||||
"github.com/sagernet/sing-box/option"
|
||||
)
|
||||
|
||||
func SaveCurrentConfig(path string, options option.Options) error {
|
||||
json, err := ToJson(options)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
p, err := filepath.Abs(path)
|
||||
fmt.Printf("Saving config to %v %+v\n", p, err)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return os.WriteFile(p, []byte(json), 0644)
|
||||
}
|
||||
|
||||
func ToJson(options option.Options) (string, error) {
|
||||
var buffer bytes.Buffer
|
||||
encoder := json.NewEncoder(&buffer)
|
||||
encoder.SetIndent("", " ")
|
||||
// fmt.Printf("%+v\n", options)
|
||||
err := encoder.Encode(options)
|
||||
if err != nil {
|
||||
fmt.Printf("ERROR in coding:%+v\n", err)
|
||||
return "", err
|
||||
}
|
||||
return buffer.String(), nil
|
||||
}
|
||||
|
||||
func DeferPanicToError(name string, err func(error)) {
|
||||
if r := recover(); r != nil {
|
||||
s := fmt.Errorf("%s panic: %s\n%s", name, r, string(debug.Stack()))
|
||||
err(s)
|
||||
}
|
||||
}
|
||||
@ -1,155 +0,0 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"github.com/sagernet/sing-box/option"
|
||||
dns "github.com/sagernet/sing-dns"
|
||||
)
|
||||
|
||||
type HiddifyOptions struct {
|
||||
EnableFullConfig bool `json:"enable-full-config"`
|
||||
LogLevel string `json:"log-level"`
|
||||
LogFile string `json:"log-file"`
|
||||
EnableClashApi bool `json:"enable-clash-api"`
|
||||
ClashApiPort uint16 `json:"clash-api-port"`
|
||||
ClashApiSecret string `json:"web-secret"`
|
||||
Region string `json:"region"`
|
||||
BlockAds bool `json:"block-ads"`
|
||||
UseXrayCoreWhenPossible bool `json:"use-xray-core-when-possible"`
|
||||
// GeoIPPath string `json:"geoip-path"`
|
||||
// GeoSitePath string `json:"geosite-path"`
|
||||
Rules []Rule `json:"rules"`
|
||||
Warp WarpOptions `json:"warp"`
|
||||
Warp2 WarpOptions `json:"warp2"`
|
||||
Mux MuxOptions `json:"mux"`
|
||||
TLSTricks TLSTricks `json:"tls-tricks"`
|
||||
DNSOptions
|
||||
InboundOptions
|
||||
URLTestOptions
|
||||
RouteOptions
|
||||
}
|
||||
|
||||
type DNSOptions struct {
|
||||
RemoteDnsAddress string `json:"remote-dns-address"`
|
||||
RemoteDnsDomainStrategy option.DomainStrategy `json:"remote-dns-domain-strategy"`
|
||||
DirectDnsAddress string `json:"direct-dns-address"`
|
||||
DirectDnsDomainStrategy option.DomainStrategy `json:"direct-dns-domain-strategy"`
|
||||
IndependentDNSCache bool `json:"independent-dns-cache"`
|
||||
EnableFakeDNS bool `json:"enable-fake-dns"`
|
||||
EnableDNSRouting bool `json:"enable-dns-routing"`
|
||||
}
|
||||
|
||||
type InboundOptions struct {
|
||||
EnableTun bool `json:"enable-tun"`
|
||||
EnableTunService bool `json:"enable-tun-service"`
|
||||
SetSystemProxy bool `json:"set-system-proxy"`
|
||||
MixedPort uint16 `json:"mixed-port"`
|
||||
TProxyPort uint16 `json:"tproxy-port"`
|
||||
LocalDnsPort uint16 `json:"local-dns-port"`
|
||||
MTU uint32 `json:"mtu"`
|
||||
StrictRoute bool `json:"strict-route"`
|
||||
TUNStack string `json:"tun-implementation"`
|
||||
}
|
||||
|
||||
type URLTestOptions struct {
|
||||
ConnectionTestUrl string `json:"connection-test-url"`
|
||||
URLTestInterval DurationInSeconds `json:"url-test-interval"`
|
||||
// URLTestIdleTimeout DurationInSeconds `json:"url-test-idle-timeout"`
|
||||
}
|
||||
|
||||
type RouteOptions struct {
|
||||
ResolveDestination bool `json:"resolve-destination"`
|
||||
IPv6Mode option.DomainStrategy `json:"ipv6-mode"`
|
||||
BypassLAN bool `json:"bypass-lan"`
|
||||
AllowConnectionFromLAN bool `json:"allow-connection-from-lan"`
|
||||
}
|
||||
|
||||
type TLSTricks struct {
|
||||
EnableFragment bool `json:"enable-fragment"`
|
||||
FragmentSize string `json:"fragment-size"`
|
||||
FragmentSleep string `json:"fragment-sleep"`
|
||||
MixedSNICase bool `json:"mixed-sni-case"`
|
||||
EnablePadding bool `json:"enable-padding"`
|
||||
PaddingSize string `json:"padding-size"`
|
||||
}
|
||||
|
||||
type MuxOptions struct {
|
||||
Enable bool `json:"enable"`
|
||||
Padding bool `json:"padding"`
|
||||
MaxStreams int `json:"max-streams"`
|
||||
Protocol string `json:"protocol"`
|
||||
}
|
||||
|
||||
type WarpOptions struct {
|
||||
Id string `json:"id"`
|
||||
EnableWarp bool `json:"enable"`
|
||||
Mode string `json:"mode"`
|
||||
WireguardConfigStr string `json:"wireguard-config"`
|
||||
WireguardConfig WarpWireguardConfig `json:"wireguardConfig"` // TODO check
|
||||
FakePackets string `json:"noise"`
|
||||
FakePacketSize string `json:"noise-size"`
|
||||
FakePacketDelay string `json:"noise-delay"`
|
||||
FakePacketMode string `json:"noise-mode"`
|
||||
CleanIP string `json:"clean-ip"`
|
||||
CleanPort uint16 `json:"clean-port"`
|
||||
Account WarpAccount
|
||||
}
|
||||
|
||||
func DefaultHiddifyOptions() *HiddifyOptions {
|
||||
return &HiddifyOptions{
|
||||
DNSOptions: DNSOptions{
|
||||
RemoteDnsAddress: "1.1.1.1",
|
||||
RemoteDnsDomainStrategy: option.DomainStrategy(dns.DomainStrategyAsIS),
|
||||
DirectDnsAddress: "1.1.1.1",
|
||||
DirectDnsDomainStrategy: option.DomainStrategy(dns.DomainStrategyAsIS),
|
||||
IndependentDNSCache: false,
|
||||
EnableFakeDNS: false,
|
||||
EnableDNSRouting: false,
|
||||
},
|
||||
InboundOptions: InboundOptions{
|
||||
EnableTun: false,
|
||||
SetSystemProxy: false,
|
||||
MixedPort: 12334,
|
||||
TProxyPort: 12335,
|
||||
LocalDnsPort: 16450,
|
||||
MTU: 9000,
|
||||
StrictRoute: true,
|
||||
TUNStack: "mixed",
|
||||
},
|
||||
URLTestOptions: URLTestOptions{
|
||||
ConnectionTestUrl: "http://cp.cloudflare.com/",
|
||||
URLTestInterval: DurationInSeconds(600),
|
||||
// URLTestIdleTimeout: DurationInSeconds(6000),
|
||||
},
|
||||
RouteOptions: RouteOptions{
|
||||
ResolveDestination: false,
|
||||
IPv6Mode: option.DomainStrategy(dns.DomainStrategyAsIS),
|
||||
BypassLAN: false,
|
||||
AllowConnectionFromLAN: false,
|
||||
},
|
||||
LogLevel: "warn",
|
||||
// LogFile: "/dev/null",
|
||||
LogFile: "box.log",
|
||||
Region: "other",
|
||||
EnableClashApi: true,
|
||||
ClashApiPort: 16756,
|
||||
ClashApiSecret: "",
|
||||
// GeoIPPath: "geoip.db",
|
||||
// GeoSitePath: "geosite.db",
|
||||
Rules: []Rule{},
|
||||
Mux: MuxOptions{
|
||||
Enable: false,
|
||||
Padding: true,
|
||||
MaxStreams: 8,
|
||||
Protocol: "h2mux",
|
||||
},
|
||||
TLSTricks: TLSTricks{
|
||||
EnableFragment: false,
|
||||
FragmentSize: "10-100",
|
||||
FragmentSleep: "50-200",
|
||||
MixedSNICase: false,
|
||||
EnablePadding: false,
|
||||
PaddingSize: "1200-1500",
|
||||
},
|
||||
UseXrayCoreWhenPossible: false,
|
||||
}
|
||||
}
|
||||
@ -1,185 +0,0 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net"
|
||||
|
||||
C "github.com/sagernet/sing-box/constant"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
)
|
||||
|
||||
type outboundMap map[string]interface{}
|
||||
|
||||
func patchOutboundMux(base option.Outbound, configOpt HiddifyOptions, obj outboundMap) outboundMap {
|
||||
if configOpt.Mux.Enable {
|
||||
multiplex := option.OutboundMultiplexOptions{
|
||||
Enabled: true,
|
||||
Padding: configOpt.Mux.Padding,
|
||||
MaxStreams: configOpt.Mux.MaxStreams,
|
||||
Protocol: configOpt.Mux.Protocol,
|
||||
}
|
||||
obj["multiplex"] = multiplex
|
||||
// } else {
|
||||
// delete(obj, "multiplex")
|
||||
}
|
||||
return obj
|
||||
}
|
||||
|
||||
func patchOutboundTLSTricks(base option.Outbound, configOpt HiddifyOptions, obj outboundMap) outboundMap {
|
||||
if base.Type == C.TypeSelector || base.Type == C.TypeURLTest || base.Type == C.TypeBlock || base.Type == C.TypeDNS {
|
||||
return obj
|
||||
}
|
||||
if isOutboundReality(base) {
|
||||
return obj
|
||||
}
|
||||
|
||||
var tls *option.OutboundTLSOptions
|
||||
var transport *option.V2RayTransportOptions
|
||||
if base.VLESSOptions.OutboundTLSOptionsContainer.TLS != nil {
|
||||
tls = base.VLESSOptions.OutboundTLSOptionsContainer.TLS
|
||||
transport = base.VLESSOptions.Transport
|
||||
} else if base.TrojanOptions.OutboundTLSOptionsContainer.TLS != nil {
|
||||
tls = base.TrojanOptions.OutboundTLSOptionsContainer.TLS
|
||||
transport = base.TrojanOptions.Transport
|
||||
} else if base.VMessOptions.OutboundTLSOptionsContainer.TLS != nil {
|
||||
tls = base.VMessOptions.OutboundTLSOptionsContainer.TLS
|
||||
transport = base.VMessOptions.Transport
|
||||
}
|
||||
if base.Type == C.TypeXray {
|
||||
if configOpt.TLSTricks.EnableFragment {
|
||||
if obj["xray_fragment"] == nil || obj["xray_fragment"].(map[string]any)["packets"] == "" {
|
||||
obj["xray_fragment"] = map[string]any{
|
||||
"packets": "tlshello",
|
||||
"length": configOpt.TLSTricks.FragmentSize,
|
||||
"interval": configOpt.TLSTricks.FragmentSleep,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if base.Type == C.TypeDirect {
|
||||
return patchOutboundFragment(base, configOpt, obj)
|
||||
}
|
||||
|
||||
if tls == nil || !tls.Enabled || transport == nil {
|
||||
return obj
|
||||
}
|
||||
|
||||
if transport.Type != C.V2RayTransportTypeWebsocket && transport.Type != C.V2RayTransportTypeGRPC && transport.Type != C.V2RayTransportTypeHTTPUpgrade {
|
||||
return obj
|
||||
}
|
||||
|
||||
if outtls, ok := obj["tls"].(map[string]interface{}); ok {
|
||||
obj = patchOutboundFragment(base, configOpt, obj)
|
||||
tlsTricks := tls.TLSTricks
|
||||
if tlsTricks == nil {
|
||||
tlsTricks = &option.TLSTricksOptions{}
|
||||
}
|
||||
tlsTricks.MixedCaseSNI = tlsTricks.MixedCaseSNI || configOpt.TLSTricks.MixedSNICase
|
||||
|
||||
if configOpt.TLSTricks.EnablePadding {
|
||||
tlsTricks.PaddingMode = "random"
|
||||
tlsTricks.PaddingSize = configOpt.TLSTricks.PaddingSize
|
||||
// fmt.Printf("--------------------%+v----%+v", tlsTricks.PaddingSize, configOpt)
|
||||
outtls["utls"] = map[string]interface{}{
|
||||
"enabled": true,
|
||||
"fingerprint": "custom",
|
||||
}
|
||||
}
|
||||
|
||||
outtls["tls_tricks"] = tlsTricks
|
||||
// if tlsTricks.MixedCaseSNI || tlsTricks.PaddingMode != "" {
|
||||
// // } else {
|
||||
// // tls["tls_tricks"] = nil
|
||||
// }
|
||||
// fmt.Printf("-------%+v------------- ", tlsTricks)
|
||||
}
|
||||
return obj
|
||||
}
|
||||
|
||||
func patchOutboundFragment(base option.Outbound, configOpt HiddifyOptions, obj outboundMap) outboundMap {
|
||||
if configOpt.TLSTricks.EnableFragment {
|
||||
obj["tcp_fast_open"] = false
|
||||
obj["tls_fragment"] = option.TLSFragmentOptions{
|
||||
Enabled: configOpt.TLSTricks.EnableFragment,
|
||||
Size: configOpt.TLSTricks.FragmentSize,
|
||||
Sleep: configOpt.TLSTricks.FragmentSleep,
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return obj
|
||||
}
|
||||
|
||||
func isOutboundReality(base option.Outbound) bool {
|
||||
// this function checks reality status ONLY FOR VLESS.
|
||||
// Some other protocols can also use reality, but it's discouraged as stated in the reality document
|
||||
if base.Type != C.TypeVLESS {
|
||||
return false
|
||||
}
|
||||
if base.VLESSOptions.OutboundTLSOptionsContainer.TLS == nil {
|
||||
return false
|
||||
}
|
||||
if base.VLESSOptions.OutboundTLSOptionsContainer.TLS.Reality == nil {
|
||||
return false
|
||||
}
|
||||
return base.VLESSOptions.OutboundTLSOptionsContainer.TLS.Reality.Enabled
|
||||
}
|
||||
|
||||
func patchOutbound(base option.Outbound, configOpt HiddifyOptions, staticIpsDns map[string][]string) (*option.Outbound, string, error) {
|
||||
formatErr := func(err error) error {
|
||||
return fmt.Errorf("error patching outbound[%s][%s]: %w", base.Tag, base.Type, err)
|
||||
}
|
||||
err := patchWarp(&base, &configOpt, true, staticIpsDns)
|
||||
if err != nil {
|
||||
return nil, "", formatErr(err)
|
||||
}
|
||||
var outbound option.Outbound
|
||||
|
||||
jsonData, err := base.MarshalJSON()
|
||||
if err != nil {
|
||||
return nil, "", formatErr(err)
|
||||
}
|
||||
|
||||
var obj outboundMap
|
||||
err = json.Unmarshal(jsonData, &obj)
|
||||
if err != nil {
|
||||
return nil, "", formatErr(err)
|
||||
}
|
||||
var serverDomain string
|
||||
if detour, ok := obj["detour"].(string); !ok || detour == "" {
|
||||
if server, ok := obj["server"].(string); ok {
|
||||
if server != "" && net.ParseIP(server) == nil {
|
||||
serverDomain = fmt.Sprintf("full:%s", server)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
obj = patchOutboundTLSTricks(base, configOpt, obj)
|
||||
|
||||
switch base.Type {
|
||||
case C.TypeVMess, C.TypeVLESS, C.TypeTrojan, C.TypeShadowsocks:
|
||||
obj = patchOutboundMux(base, configOpt, obj)
|
||||
}
|
||||
|
||||
modifiedJson, err := json.Marshal(obj)
|
||||
if err != nil {
|
||||
return nil, "", formatErr(err)
|
||||
}
|
||||
|
||||
err = outbound.UnmarshalJSON(modifiedJson)
|
||||
if err != nil {
|
||||
return nil, "", formatErr(err)
|
||||
}
|
||||
|
||||
return &outbound, serverDomain, nil
|
||||
}
|
||||
|
||||
// func (o outboundMap) transportType() string {
|
||||
// if transport, ok := o["transport"].(map[string]interface{}); ok {
|
||||
// if transportType, ok := transport["type"].(string); ok {
|
||||
// return transportType
|
||||
// }
|
||||
// }
|
||||
// return ""
|
||||
// }
|
||||
@ -1,142 +0,0 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
_ "embed"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/hiddify/ray2sing/ray2sing"
|
||||
"github.com/sagernet/sing-box/experimental/libbox"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
"github.com/sagernet/sing/common/batch"
|
||||
SJ "github.com/sagernet/sing/common/json"
|
||||
"github.com/xmdhs/clash2singbox/convert"
|
||||
"github.com/xmdhs/clash2singbox/model/clash"
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
//go:embed config.json.template
|
||||
var configByte []byte
|
||||
|
||||
func ParseConfig(path string, debug bool) ([]byte, error) {
|
||||
content, err := os.ReadFile(path)
|
||||
os.Chdir(filepath.Dir(path))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ParseConfigContent(string(content), debug, nil, false)
|
||||
}
|
||||
|
||||
func ParseConfigContentToOptions(contentstr string, debug bool, configOpt *HiddifyOptions, fullConfig bool) (*option.Options, error) {
|
||||
content, err := ParseConfigContent(contentstr, debug, configOpt, fullConfig)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var options option.Options
|
||||
err = json.Unmarshal(content, &options)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &options, nil
|
||||
}
|
||||
|
||||
func ParseConfigContent(contentstr string, debug bool, configOpt *HiddifyOptions, fullConfig bool) ([]byte, error) {
|
||||
if configOpt == nil {
|
||||
configOpt = DefaultHiddifyOptions()
|
||||
}
|
||||
content := []byte(contentstr)
|
||||
var jsonObj map[string]interface{} = make(map[string]interface{})
|
||||
|
||||
fmt.Printf("Convert using json\n")
|
||||
var tmpJsonResult any
|
||||
jsonDecoder := json.NewDecoder(SJ.NewCommentFilter(bytes.NewReader(content)))
|
||||
if err := jsonDecoder.Decode(&tmpJsonResult); err == nil {
|
||||
if tmpJsonObj, ok := tmpJsonResult.(map[string]interface{}); ok {
|
||||
if tmpJsonObj["outbounds"] == nil {
|
||||
jsonObj["outbounds"] = []interface{}{jsonObj}
|
||||
} else {
|
||||
if fullConfig || (configOpt != nil && configOpt.EnableFullConfig) {
|
||||
jsonObj = tmpJsonObj
|
||||
} else {
|
||||
jsonObj["outbounds"] = tmpJsonObj["outbounds"]
|
||||
}
|
||||
}
|
||||
} else if jsonArray, ok := tmpJsonResult.([]map[string]interface{}); ok {
|
||||
jsonObj["outbounds"] = jsonArray
|
||||
} else {
|
||||
return nil, fmt.Errorf("[SingboxParser] Incorrect Json Format")
|
||||
}
|
||||
|
||||
newContent, _ := json.MarshalIndent(jsonObj, "", " ")
|
||||
|
||||
return patchConfig(newContent, "SingboxParser", configOpt)
|
||||
}
|
||||
|
||||
v2rayStr, err := ray2sing.Ray2Singbox(string(content), configOpt.UseXrayCoreWhenPossible)
|
||||
if err == nil {
|
||||
return patchConfig([]byte(v2rayStr), "V2rayParser", configOpt)
|
||||
}
|
||||
fmt.Printf("Convert using clash\n")
|
||||
clashObj := clash.Clash{}
|
||||
if err := yaml.Unmarshal(content, &clashObj); err == nil && clashObj.Proxies != nil {
|
||||
if len(clashObj.Proxies) == 0 {
|
||||
return nil, fmt.Errorf("[ClashParser] no outbounds found")
|
||||
}
|
||||
converted, err := convert.Clash2sing(clashObj)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("[ClashParser] converting clash to sing-box error: %w", err)
|
||||
}
|
||||
output := configByte
|
||||
output, err = convert.Patch(output, converted, "", "", nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("[ClashParser] patching clash config error: %w", err)
|
||||
}
|
||||
return patchConfig(output, "ClashParser", configOpt)
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("unable to determine config format")
|
||||
}
|
||||
|
||||
func patchConfig(content []byte, name string, configOpt *HiddifyOptions) ([]byte, error) {
|
||||
options := option.Options{}
|
||||
err := json.Unmarshal(content, &options)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("[SingboxParser] unmarshal error: %w", err)
|
||||
}
|
||||
b, _ := batch.New(context.Background(), batch.WithConcurrencyNum[*option.Outbound](2))
|
||||
for _, base := range options.Outbounds {
|
||||
out := base
|
||||
b.Go(base.Tag, func() (*option.Outbound, error) {
|
||||
err := patchWarp(&out, configOpt, false, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("[Warp] patch warp error: %w", err)
|
||||
}
|
||||
// options.Outbounds[i] = base
|
||||
return &out, nil
|
||||
})
|
||||
}
|
||||
if res, err := b.WaitAndGetResult(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
for i, base := range options.Outbounds {
|
||||
options.Outbounds[i] = *res[base.Tag].Value
|
||||
}
|
||||
}
|
||||
|
||||
content, _ = json.MarshalIndent(options, "", " ")
|
||||
|
||||
fmt.Printf("%s\n", content)
|
||||
return validateResult(content, name)
|
||||
}
|
||||
|
||||
func validateResult(content []byte, name string) ([]byte, error) {
|
||||
err := libbox.CheckConfig(string(content))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("[%s] invalid sing-box config: %w", name, err)
|
||||
}
|
||||
return content, nil
|
||||
}
|
||||
@ -1,96 +0,0 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/sagernet/sing-box/option"
|
||||
)
|
||||
|
||||
type Rule struct {
|
||||
RuleSetUrl string `json:"rule-set-url"`
|
||||
Domains string `json:"domains"`
|
||||
IP string `json:"ip"`
|
||||
Port string `json:"port"`
|
||||
Network string `json:"network"`
|
||||
Protocol string `json:"protocol"`
|
||||
Outbound string `json:"outbound"`
|
||||
}
|
||||
|
||||
func (r *Rule) MakeRule() option.DefaultRule {
|
||||
rule := option.DefaultRule{}
|
||||
if len(r.Domains) > 0 {
|
||||
rule = makeDomainRule(rule, strings.Split(r.Domains, ","))
|
||||
}
|
||||
if len(r.IP) > 0 {
|
||||
rule = makeIpRule(rule, strings.Split(r.IP, ","))
|
||||
}
|
||||
if len(r.Port) > 0 {
|
||||
rule = makePortRule(rule, strings.Split(r.Port, ","))
|
||||
}
|
||||
if len(r.Network) > 0 {
|
||||
rule.Network = append(rule.Network, r.Network)
|
||||
}
|
||||
if len(r.Protocol) > 0 {
|
||||
rule.Protocol = append(rule.Protocol, strings.Split(r.Protocol, ",")...)
|
||||
}
|
||||
return rule
|
||||
}
|
||||
|
||||
func (r *Rule) MakeDNSRule() option.DefaultDNSRule {
|
||||
rule := option.DefaultDNSRule{}
|
||||
domains := strings.Split(r.Domains, ",")
|
||||
for _, item := range domains {
|
||||
if strings.HasPrefix(item, "geosite:") {
|
||||
rule.Geosite = append(rule.Geosite, strings.TrimPrefix(item, "geosite:"))
|
||||
} else if strings.HasPrefix(item, "full:") {
|
||||
rule.Domain = append(rule.Domain, strings.ToLower(strings.TrimPrefix(item, "full:")))
|
||||
} else if strings.HasPrefix(item, "domain:") {
|
||||
rule.DomainSuffix = append(rule.DomainSuffix, strings.ToLower(strings.TrimPrefix(item, "domain:")))
|
||||
} else if strings.HasPrefix(item, "regexp:") {
|
||||
rule.DomainRegex = append(rule.DomainRegex, strings.ToLower(strings.TrimPrefix(item, "regexp:")))
|
||||
} else if strings.HasPrefix(item, "keyword:") {
|
||||
rule.DomainKeyword = append(rule.DomainKeyword, strings.ToLower(strings.TrimPrefix(item, "keyword:")))
|
||||
}
|
||||
}
|
||||
return rule
|
||||
}
|
||||
|
||||
func makeDomainRule(options option.DefaultRule, list []string) option.DefaultRule {
|
||||
for _, item := range list {
|
||||
if strings.HasPrefix(item, "geosite:") {
|
||||
options.Geosite = append(options.Geosite, strings.TrimPrefix(item, "geosite:"))
|
||||
} else if strings.HasPrefix(item, "full:") {
|
||||
options.Domain = append(options.Domain, strings.ToLower(strings.TrimPrefix(item, "full:")))
|
||||
} else if strings.HasPrefix(item, "domain:") {
|
||||
options.DomainSuffix = append(options.DomainSuffix, strings.ToLower(strings.TrimPrefix(item, "domain:")))
|
||||
} else if strings.HasPrefix(item, "regexp:") {
|
||||
options.DomainRegex = append(options.DomainRegex, strings.ToLower(strings.TrimPrefix(item, "regexp:")))
|
||||
} else if strings.HasPrefix(item, "keyword:") {
|
||||
options.DomainKeyword = append(options.DomainKeyword, strings.ToLower(strings.TrimPrefix(item, "keyword:")))
|
||||
}
|
||||
}
|
||||
return options
|
||||
}
|
||||
|
||||
func makeIpRule(options option.DefaultRule, list []string) option.DefaultRule {
|
||||
for _, item := range list {
|
||||
if strings.HasPrefix(item, "geoip:") {
|
||||
options.GeoIP = append(options.GeoIP, strings.TrimPrefix(item, "geoip:"))
|
||||
} else {
|
||||
options.IPCIDR = append(options.IPCIDR, item)
|
||||
}
|
||||
}
|
||||
return options
|
||||
}
|
||||
|
||||
func makePortRule(options option.DefaultRule, list []string) option.DefaultRule {
|
||||
for _, item := range list {
|
||||
if strings.Contains(item, ":") {
|
||||
options.PortRange = append(options.PortRange, item)
|
||||
} else if i, err := strconv.Atoi(item); err == nil {
|
||||
options.Port = append(options.Port, uint16(i))
|
||||
}
|
||||
}
|
||||
return options
|
||||
}
|
||||
@ -1,75 +0,0 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
context "context"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/sagernet/sing-box/option"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
type server struct {
|
||||
UnimplementedCoreServiceServer
|
||||
}
|
||||
|
||||
func String(s string) *string {
|
||||
return &s
|
||||
}
|
||||
|
||||
func (s *server) ParseConfig(ctx context.Context, in *ParseConfigRequest) (*ParseConfigResponse, error) {
|
||||
config, err := ParseConfig(in.TempPath, in.Debug)
|
||||
if err != nil {
|
||||
return &ParseConfigResponse{Error: String(err.Error())}, nil
|
||||
}
|
||||
err = os.WriteFile(in.Path, config, 0o644)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &ParseConfigResponse{Error: String("")}, nil
|
||||
}
|
||||
|
||||
func (s *server) GenerateFullConfig(ctx context.Context, in *GenerateConfigRequest) (*GenerateConfigResponse, error) {
|
||||
os.Chdir(filepath.Dir(in.Path))
|
||||
content, err := os.ReadFile(in.Path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var options option.Options
|
||||
err = options.UnmarshalJSON(content)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
config, err := BuildConfigJson(*DefaultHiddifyOptions(), options)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &GenerateConfigResponse{
|
||||
Config: config,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func StartGRPCServer(port uint16) error {
|
||||
lis, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to listen: %v", err)
|
||||
}
|
||||
|
||||
s := grpc.NewServer()
|
||||
RegisterCoreServiceServer(s, &server{})
|
||||
|
||||
log.Println("Server started on :", port)
|
||||
go func() {
|
||||
if err := s.Serve(lis); err != nil {
|
||||
log.Fatalf("Failed to serve: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
return nil
|
||||
}
|
||||
@ -1,25 +0,0 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
type DurationInSeconds int
|
||||
|
||||
func (d DurationInSeconds) MarshalJSON() ([]byte, error) {
|
||||
return json.Marshal(int64(d))
|
||||
}
|
||||
|
||||
func (d *DurationInSeconds) UnmarshalJSON(bytes []byte) error {
|
||||
var v int64
|
||||
if err := json.Unmarshal(bytes, &v); err != nil {
|
||||
return err
|
||||
}
|
||||
*d = DurationInSeconds(v)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d DurationInSeconds) Duration() time.Duration {
|
||||
return time.Duration(d) * time.Second
|
||||
}
|
||||
@ -1,270 +0,0 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/netip"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/bepass-org/warp-plus/warp"
|
||||
"github.com/hiddify/hiddify-core/v2/common"
|
||||
C "github.com/sagernet/sing-box/constant"
|
||||
|
||||
// "github.com/bepass-org/wireguard-go/warp"
|
||||
"github.com/hiddify/hiddify-core/v2/db"
|
||||
|
||||
"github.com/sagernet/sing-box/option"
|
||||
T "github.com/sagernet/sing-box/option"
|
||||
)
|
||||
|
||||
type SingboxConfig struct {
|
||||
Type string `json:"type"`
|
||||
Tag string `json:"tag"`
|
||||
Server string `json:"server"`
|
||||
ServerPort int `json:"server_port"`
|
||||
LocalAddress []string `json:"local_address"`
|
||||
PrivateKey string `json:"private_key"`
|
||||
PeerPublicKey string `json:"peer_public_key"`
|
||||
Reserved []int `json:"reserved"`
|
||||
MTU int `json:"mtu"`
|
||||
}
|
||||
|
||||
func wireGuardToSingbox(wgConfig WarpWireguardConfig, server string, port uint16) (*T.Outbound, error) {
|
||||
clientID, _ := base64.StdEncoding.DecodeString(wgConfig.ClientID)
|
||||
if len(clientID) < 2 {
|
||||
clientID = []byte{0, 0, 0}
|
||||
}
|
||||
out := T.Outbound{
|
||||
Type: "wireguard",
|
||||
Tag: "WARP",
|
||||
WireGuardOptions: T.WireGuardOutboundOptions{
|
||||
ServerOptions: T.ServerOptions{
|
||||
Server: server,
|
||||
ServerPort: port,
|
||||
},
|
||||
|
||||
PrivateKey: wgConfig.PrivateKey,
|
||||
PeerPublicKey: wgConfig.PeerPublicKey,
|
||||
Reserved: []uint8{clientID[0], clientID[1], clientID[2]},
|
||||
// Reserved: []uint8{0, 0, 0},
|
||||
MTU: 1330,
|
||||
},
|
||||
}
|
||||
ips := []string{wgConfig.LocalAddressIPv4 + "/24", wgConfig.LocalAddressIPv6 + "/128"}
|
||||
|
||||
for _, addr := range ips {
|
||||
if addr == "" {
|
||||
continue
|
||||
}
|
||||
prefix, err := netip.ParsePrefix(addr)
|
||||
if err != nil {
|
||||
return nil, err // Handle the error appropriately
|
||||
}
|
||||
out.WireGuardOptions.LocalAddress = append(out.WireGuardOptions.LocalAddress, prefix)
|
||||
}
|
||||
return &out, nil
|
||||
}
|
||||
|
||||
func getRandomIP() string {
|
||||
ipPort, err := warp.RandomWarpEndpoint(true, true)
|
||||
if err == nil {
|
||||
return ipPort.Addr().String()
|
||||
}
|
||||
return "engage.cloudflareclient.com"
|
||||
}
|
||||
|
||||
func generateWarp(license string, host string, port uint16, fakePackets string, fakePacketsSize string, fakePacketsDelay string, fakePacketsMode string) (*T.Outbound, error) {
|
||||
_, _, wgConfig, err := GenerateWarpInfo(license, "", "")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if wgConfig == nil {
|
||||
return nil, fmt.Errorf("invalid warp config")
|
||||
}
|
||||
|
||||
return GenerateWarpSingbox(*wgConfig, host, port, fakePackets, fakePacketsSize, fakePacketsDelay, fakePacketsMode)
|
||||
}
|
||||
|
||||
func GenerateWarpSingbox(wgConfig WarpWireguardConfig, host string, port uint16, fakePackets string, fakePacketsSize string, fakePacketsDelay string, fakePacketMode string) (*T.Outbound, error) {
|
||||
if host == "" {
|
||||
host = "auto4"
|
||||
}
|
||||
|
||||
if (host == "auto" || host == "auto4" || host == "auto6") && fakePackets == "" {
|
||||
fakePackets = "1-3"
|
||||
}
|
||||
if fakePackets != "" && fakePacketsSize == "" {
|
||||
fakePacketsSize = "10-30"
|
||||
}
|
||||
if fakePackets != "" && fakePacketsDelay == "" {
|
||||
fakePacketsDelay = "10-30"
|
||||
}
|
||||
singboxConfig, err := wireGuardToSingbox(wgConfig, host, port)
|
||||
if err != nil {
|
||||
fmt.Printf("%v %v", singboxConfig, err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
singboxConfig.WireGuardOptions.FakePackets = fakePackets
|
||||
singboxConfig.WireGuardOptions.FakePacketsSize = fakePacketsSize
|
||||
singboxConfig.WireGuardOptions.FakePacketsDelay = fakePacketsDelay
|
||||
singboxConfig.WireGuardOptions.FakePacketsMode = fakePacketMode
|
||||
|
||||
return singboxConfig, nil
|
||||
}
|
||||
|
||||
func GenerateWarpInfo(license string, oldAccountId string, oldAccessToken string) (*warp.Identity, string, *WarpWireguardConfig, error) {
|
||||
if oldAccountId != "" && oldAccessToken != "" {
|
||||
err := warp.DeleteDevice(oldAccessToken, oldAccountId)
|
||||
if err != nil {
|
||||
fmt.Printf("Error in removing old device: %v\n", err)
|
||||
} else {
|
||||
fmt.Printf("Old Device Removed")
|
||||
}
|
||||
}
|
||||
l := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo}))
|
||||
identity, err := warp.CreateIdentityOnly(l, license)
|
||||
res := "Error!"
|
||||
var warpcfg WarpWireguardConfig
|
||||
if err == nil {
|
||||
res = "Success"
|
||||
res = fmt.Sprintf("Warp+ enabled: %t\n", identity.Account.WarpPlus)
|
||||
res += fmt.Sprintf("\nAccount type: %s\n", identity.Account.AccountType)
|
||||
warpcfg = WarpWireguardConfig{
|
||||
PrivateKey: identity.PrivateKey,
|
||||
PeerPublicKey: identity.Config.Peers[0].PublicKey,
|
||||
LocalAddressIPv4: identity.Config.Interface.Addresses.V4,
|
||||
LocalAddressIPv6: identity.Config.Interface.Addresses.V6,
|
||||
ClientID: identity.Config.ClientID,
|
||||
}
|
||||
}
|
||||
|
||||
return &identity, res, &warpcfg, err
|
||||
}
|
||||
|
||||
func getOrGenerateWarpLocallyIfNeeded(warpOptions *WarpOptions) WarpWireguardConfig {
|
||||
if warpOptions.WireguardConfig.PrivateKey != "" {
|
||||
return warpOptions.WireguardConfig
|
||||
}
|
||||
table := db.GetTable[WarpOptions]()
|
||||
dbWarpOptions, err := table.Get(warpOptions.Id)
|
||||
if err == nil && dbWarpOptions.WireguardConfig.PrivateKey != "" {
|
||||
return warpOptions.WireguardConfig
|
||||
}
|
||||
license := ""
|
||||
if len(warpOptions.Id) == 26 { // warp key is 26 characters long
|
||||
license = warpOptions.Id
|
||||
} else if len(warpOptions.Id) > 28 && warpOptions.Id[2] == '_' { // warp key is 26 characters long
|
||||
license = warpOptions.Id[3:]
|
||||
}
|
||||
|
||||
accountidentity, _, wireguardConfig, err := GenerateWarpInfo(license, warpOptions.Account.AccountID, warpOptions.Account.AccessToken)
|
||||
if err != nil {
|
||||
return WarpWireguardConfig{}
|
||||
}
|
||||
warpOptions.Account = WarpAccount{
|
||||
AccountID: accountidentity.ID,
|
||||
AccessToken: accountidentity.Token,
|
||||
}
|
||||
warpOptions.WireguardConfig = *wireguardConfig
|
||||
table.UpdateInsert(warpOptions)
|
||||
|
||||
return *wireguardConfig
|
||||
}
|
||||
|
||||
func patchWarp(base *option.Outbound, configOpt *HiddifyOptions, final bool, staticIpsDns map[string][]string) error {
|
||||
if base.Type == C.TypeCustom {
|
||||
if warp, ok := base.CustomOptions["warp"].(map[string]interface{}); ok {
|
||||
key, _ := warp["key"].(string)
|
||||
host, _ := warp["host"].(string)
|
||||
port, _ := warp["port"].(uint16)
|
||||
detour, _ := warp["detour"].(string)
|
||||
fakePackets, _ := warp["fake_packets"].(string)
|
||||
fakePacketsSize, _ := warp["fake_packets_size"].(string)
|
||||
fakePacketsDelay, _ := warp["fake_packets_delay"].(string)
|
||||
fakePacketsMode, _ := warp["fake_packets_mode"].(string)
|
||||
var warpOutbound *T.Outbound
|
||||
var err error
|
||||
|
||||
is_saved_key := len(key) > 1 && key[0] == 'p'
|
||||
|
||||
if (configOpt == nil || !final) && is_saved_key {
|
||||
return nil
|
||||
}
|
||||
var wireguardConfig WarpWireguardConfig
|
||||
if is_saved_key {
|
||||
var warpOpt *WarpOptions
|
||||
if key == "p1" {
|
||||
warpOpt = &configOpt.Warp
|
||||
} else if key == "p2" {
|
||||
warpOpt = &configOpt.Warp2
|
||||
} else {
|
||||
warpOpt = &WarpOptions{
|
||||
Id: key,
|
||||
}
|
||||
}
|
||||
warpOpt.Id = key
|
||||
|
||||
wireguardConfig = getOrGenerateWarpLocallyIfNeeded(warpOpt)
|
||||
} else {
|
||||
_, _, wgConfig, err := GenerateWarpInfo(key, "", "")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
wireguardConfig = *wgConfig
|
||||
}
|
||||
warpOutbound, err = GenerateWarpSingbox(wireguardConfig, host, port, fakePackets, fakePacketsSize, fakePacketsDelay, fakePacketsMode)
|
||||
if err != nil {
|
||||
fmt.Printf("Error generating warp config: %v", err)
|
||||
return err
|
||||
}
|
||||
warpOutbound.WireGuardOptions.Detour = detour
|
||||
base.Type = C.TypeWireGuard
|
||||
base.WireGuardOptions = warpOutbound.WireGuardOptions
|
||||
}
|
||||
}
|
||||
|
||||
if final && base.Type == C.TypeWireGuard {
|
||||
host := base.WireGuardOptions.Server
|
||||
|
||||
if host == "default" || host == "random" || host == "auto" || host == "auto4" || host == "auto6" || isBlockedDomain(host) {
|
||||
// if base.WireGuardOptions.Detour != "" {
|
||||
// base.WireGuardOptions.Server = "162.159.192.1"
|
||||
// } else {
|
||||
rndDomain := strings.ToLower(generateRandomString(20))
|
||||
staticIpsDns[rndDomain] = []string{}
|
||||
if host != "auto4" {
|
||||
if host == "auto6" || common.CanConnectIPv6() {
|
||||
randomIpPort, _ := warp.RandomWarpEndpoint(false, true)
|
||||
staticIpsDns[rndDomain] = append(staticIpsDns[rndDomain], randomIpPort.Addr().String())
|
||||
}
|
||||
}
|
||||
if host != "auto6" {
|
||||
randomIpPort, _ := warp.RandomWarpEndpoint(true, false)
|
||||
staticIpsDns[rndDomain] = append(staticIpsDns[rndDomain], randomIpPort.Addr().String())
|
||||
}
|
||||
base.WireGuardOptions.Server = rndDomain
|
||||
// }
|
||||
}
|
||||
if base.WireGuardOptions.ServerPort == 0 {
|
||||
port := warp.RandomWarpPort()
|
||||
base.WireGuardOptions.ServerPort = port
|
||||
}
|
||||
|
||||
if base.WireGuardOptions.Detour != "" {
|
||||
if base.WireGuardOptions.MTU < 100 {
|
||||
base.WireGuardOptions.MTU = 1280
|
||||
}
|
||||
base.WireGuardOptions.FakePackets = ""
|
||||
base.WireGuardOptions.FakePacketsDelay = ""
|
||||
base.WireGuardOptions.FakePacketsSize = ""
|
||||
}
|
||||
// if base.WireGuardOptions.Detour == "" {
|
||||
// base.WireGuardOptions.GSO = runtime.GOOS != "windows"
|
||||
// }
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@ -1,50 +0,0 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
)
|
||||
|
||||
type WarpAccount struct {
|
||||
AccountID string `json:"account-id"`
|
||||
AccessToken string `json:"access-token"`
|
||||
}
|
||||
|
||||
type WarpWireguardConfig struct {
|
||||
PrivateKey string `json:"private-key"`
|
||||
LocalAddressIPv4 string `json:"local-address-ipv4"`
|
||||
LocalAddressIPv6 string `json:"local-address-ipv6"`
|
||||
PeerPublicKey string `json:"peer-public-key"`
|
||||
ClientID string `json:"client-id"`
|
||||
}
|
||||
|
||||
type WarpGenerationResponse struct {
|
||||
WarpAccount
|
||||
Log string `json:"log"`
|
||||
Config WarpWireguardConfig `json:"config"`
|
||||
}
|
||||
|
||||
func GenerateWarpAccount(licenseKey string, accountId string, accessToken string) (string, error) {
|
||||
identity, log, wg, err := GenerateWarpInfo(licenseKey, accountId, accessToken)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
warpAccount := WarpAccount{
|
||||
AccountID: identity.ID,
|
||||
AccessToken: identity.Token,
|
||||
}
|
||||
warpConfig := WarpWireguardConfig{
|
||||
PrivateKey: wg.PrivateKey,
|
||||
LocalAddressIPv4: wg.LocalAddressIPv4,
|
||||
LocalAddressIPv6: wg.LocalAddressIPv6,
|
||||
PeerPublicKey: wg.PeerPublicKey,
|
||||
ClientID: wg.ClientID,
|
||||
}
|
||||
response := WarpGenerationResponse{warpAccount, log, warpConfig}
|
||||
|
||||
responseJson, err := json.Marshal(response)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(responseJson), nil
|
||||
}
|
||||
@ -1,26 +0,0 @@
|
||||
package main
|
||||
|
||||
/*
|
||||
#include <stdlib.h>
|
||||
*/
|
||||
import "C"
|
||||
import (
|
||||
"unsafe"
|
||||
|
||||
"github.com/hiddify/hiddify-core/cmd"
|
||||
)
|
||||
|
||||
//export parseCli
|
||||
func parseCli(argc C.int, argv **C.char) *C.char {
|
||||
args := make([]string, argc)
|
||||
for i := 0; i < int(argc); i++ {
|
||||
// fmt.Println("parseCli", C.GoString(*argv))
|
||||
args[i] = C.GoString(*argv)
|
||||
argv = (**C.char)(unsafe.Pointer(uintptr(unsafe.Pointer(argv)) + uintptr(unsafe.Sizeof(*argv))))
|
||||
}
|
||||
err := cmd.ParseCli(args[1:])
|
||||
if err != nil {
|
||||
return C.CString(err.Error())
|
||||
}
|
||||
return C.CString("")
|
||||
}
|
||||
@ -1,169 +0,0 @@
|
||||
package main
|
||||
|
||||
/*
|
||||
#include "stdint.h"
|
||||
*/
|
||||
import "C"
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"unsafe"
|
||||
|
||||
"github.com/hiddify/hiddify-core/bridge"
|
||||
"github.com/hiddify/hiddify-core/config"
|
||||
pb "github.com/hiddify/hiddify-core/hiddifyrpc"
|
||||
v2 "github.com/hiddify/hiddify-core/v2"
|
||||
|
||||
"github.com/sagernet/sing-box/log"
|
||||
)
|
||||
|
||||
//export setupOnce
|
||||
func setupOnce(api unsafe.Pointer) {
|
||||
bridge.InitializeDartApi(api)
|
||||
}
|
||||
|
||||
//export setup
|
||||
func setup(baseDir *C.char, workingDir *C.char, tempDir *C.char, statusPort C.longlong, debug bool) (CErr *C.char) {
|
||||
err := v2.Setup(C.GoString(baseDir), C.GoString(workingDir), C.GoString(tempDir), int64(statusPort), debug)
|
||||
return emptyOrErrorC(err)
|
||||
}
|
||||
|
||||
//export parse
|
||||
func parse(path *C.char, tempPath *C.char, debug bool) (CErr *C.char) {
|
||||
res, err := v2.Parse(&pb.ParseRequest{
|
||||
ConfigPath: C.GoString(path),
|
||||
TempPath: C.GoString(tempPath),
|
||||
})
|
||||
if err != nil {
|
||||
log.Error(err.Error())
|
||||
return C.CString(err.Error())
|
||||
}
|
||||
|
||||
err = os.WriteFile(C.GoString(path), []byte(res.Content), 0o644)
|
||||
return emptyOrErrorC(err)
|
||||
}
|
||||
|
||||
//export changeHiddifyOptions
|
||||
func changeHiddifyOptions(HiddifyOptionsJson *C.char) (CErr *C.char) {
|
||||
_, err := v2.ChangeHiddifySettings(&pb.ChangeHiddifySettingsRequest{
|
||||
HiddifySettingsJson: C.GoString(HiddifyOptionsJson),
|
||||
})
|
||||
return emptyOrErrorC(err)
|
||||
}
|
||||
|
||||
//export generateConfig
|
||||
func generateConfig(path *C.char) (res *C.char) {
|
||||
conf, err := v2.GenerateConfig(&pb.GenerateConfigRequest{
|
||||
Path: C.GoString(path),
|
||||
})
|
||||
if err != nil {
|
||||
return emptyOrErrorC(err)
|
||||
}
|
||||
fmt.Printf("Config: %+v\n", conf)
|
||||
fmt.Printf("ConfigContent: %+v\n", conf.ConfigContent)
|
||||
return C.CString(conf.ConfigContent)
|
||||
}
|
||||
|
||||
//export start
|
||||
func start(configPath *C.char, disableMemoryLimit bool) (CErr *C.char) {
|
||||
_, err := v2.Start(&pb.StartRequest{
|
||||
ConfigPath: C.GoString(configPath),
|
||||
EnableOldCommandServer: true,
|
||||
DisableMemoryLimit: disableMemoryLimit,
|
||||
})
|
||||
return emptyOrErrorC(err)
|
||||
}
|
||||
|
||||
//export stop
|
||||
func stop() (CErr *C.char) {
|
||||
_, err := v2.Stop()
|
||||
return emptyOrErrorC(err)
|
||||
}
|
||||
|
||||
//export restart
|
||||
func restart(configPath *C.char, disableMemoryLimit bool) (CErr *C.char) {
|
||||
_, err := v2.Restart(&pb.StartRequest{
|
||||
ConfigPath: C.GoString(configPath),
|
||||
EnableOldCommandServer: true,
|
||||
DisableMemoryLimit: disableMemoryLimit,
|
||||
})
|
||||
return emptyOrErrorC(err)
|
||||
}
|
||||
|
||||
//export startCommandClient
|
||||
func startCommandClient(command C.int, port C.longlong) *C.char {
|
||||
err := v2.StartCommand(int32(command), int64(port))
|
||||
return emptyOrErrorC(err)
|
||||
}
|
||||
|
||||
//export stopCommandClient
|
||||
func stopCommandClient(command C.int) *C.char {
|
||||
err := v2.StopCommand(int32(command))
|
||||
return emptyOrErrorC(err)
|
||||
}
|
||||
|
||||
//export selectOutbound
|
||||
func selectOutbound(groupTag *C.char, outboundTag *C.char) (CErr *C.char) {
|
||||
_, err := v2.SelectOutbound(&pb.SelectOutboundRequest{
|
||||
GroupTag: C.GoString(groupTag),
|
||||
OutboundTag: C.GoString(outboundTag),
|
||||
})
|
||||
|
||||
return emptyOrErrorC(err)
|
||||
}
|
||||
|
||||
//export urlTest
|
||||
func urlTest(groupTag *C.char) (CErr *C.char) {
|
||||
_, err := v2.UrlTest(&pb.UrlTestRequest{
|
||||
GroupTag: C.GoString(groupTag),
|
||||
})
|
||||
|
||||
return emptyOrErrorC(err)
|
||||
}
|
||||
|
||||
func emptyOrErrorC(err error) *C.char {
|
||||
if err == nil {
|
||||
return C.CString("")
|
||||
}
|
||||
log.Error(err.Error())
|
||||
return C.CString(err.Error())
|
||||
}
|
||||
|
||||
//export generateWarpConfig
|
||||
func generateWarpConfig(licenseKey *C.char, accountId *C.char, accessToken *C.char) (CResp *C.char) {
|
||||
res, err := v2.GenerateWarpConfig(&pb.GenerateWarpConfigRequest{
|
||||
LicenseKey: C.GoString(licenseKey),
|
||||
AccountId: C.GoString(accountId),
|
||||
AccessToken: C.GoString(accessToken),
|
||||
})
|
||||
if err != nil {
|
||||
return C.CString(fmt.Sprint("error: ", err.Error()))
|
||||
}
|
||||
warpAccount := config.WarpAccount{
|
||||
AccountID: res.Account.AccountId,
|
||||
AccessToken: res.Account.AccessToken,
|
||||
}
|
||||
warpConfig := config.WarpWireguardConfig{
|
||||
PrivateKey: res.Config.PrivateKey,
|
||||
LocalAddressIPv4: res.Config.LocalAddressIpv4,
|
||||
LocalAddressIPv6: res.Config.LocalAddressIpv6,
|
||||
PeerPublicKey: res.Config.PeerPublicKey,
|
||||
ClientID: res.Config.ClientId,
|
||||
}
|
||||
log := res.Log
|
||||
response := &config.WarpGenerationResponse{
|
||||
WarpAccount: warpAccount,
|
||||
Log: log,
|
||||
Config: warpConfig,
|
||||
}
|
||||
|
||||
responseJson, err := json.Marshal(response)
|
||||
if err != nil {
|
||||
return C.CString("")
|
||||
}
|
||||
return C.CString(string(responseJson))
|
||||
}
|
||||
|
||||
func main() {}
|
||||
@ -1,10 +0,0 @@
|
||||
package main
|
||||
|
||||
import "C"
|
||||
import v2 "github.com/hiddify/hiddify-core/v2"
|
||||
|
||||
//export StartCoreGrpcServer
|
||||
func StartCoreGrpcServer(listenAddress *C.char) (CErr *C.char) {
|
||||
_, err := v2.StartCoreGrpcServer(C.GoString(listenAddress))
|
||||
return emptyOrErrorC(err)
|
||||
}
|
||||
@ -1,72 +0,0 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
echo "安装构建依赖..."
|
||||
apt-get update -qq
|
||||
apt-get install -y -qq wget unzip openjdk-17-jdk build-essential npm
|
||||
|
||||
echo "创建Android SDK目录结构..."
|
||||
mkdir -p /opt/android-sdk/cmdline-tools
|
||||
|
||||
echo "下载Android SDK命令行工具..."
|
||||
cd /tmp
|
||||
wget -q https://dl.google.com/android/repository/commandlinetools-linux-11076708_latest.zip
|
||||
unzip -q commandlinetools-linux-11076708_latest.zip
|
||||
mv cmdline-tools /opt/android-sdk/cmdline-tools/latest
|
||||
|
||||
export ANDROID_HOME=/opt/android-sdk
|
||||
export PATH=$PATH:$ANDROID_HOME/cmdline-tools/latest/bin:$ANDROID_HOME/platform-tools
|
||||
|
||||
echo "接受Android SDK许可..."
|
||||
yes | sdkmanager --licenses > /dev/null 2>&1 || true
|
||||
|
||||
echo "安装Android SDK Platform 21和Build Tools..."
|
||||
sdkmanager "platforms;android-21" "build-tools;30.0.3" "platform-tools"
|
||||
|
||||
echo "安装Android NDK..."
|
||||
cd /tmp
|
||||
wget -q https://dl.google.com/android/repository/android-ndk-r26c-linux.zip
|
||||
unzip -q android-ndk-r26c-linux.zip
|
||||
export ANDROID_NDK_HOME=/tmp/android-ndk-r26c
|
||||
|
||||
echo "安装gomobile..."
|
||||
go install -v github.com/sagernet/gomobile/cmd/gomobile@v0.1.1
|
||||
go install -v github.com/sagernet/gomobile/cmd/gobind@v0.1.1
|
||||
|
||||
export PATH=$PATH:/root/go/bin
|
||||
|
||||
echo "安装npm依赖..."
|
||||
npm install --silent
|
||||
|
||||
echo "初始化gomobile..."
|
||||
gomobile init -ndk $ANDROID_NDK_HOME
|
||||
|
||||
cd /workspace
|
||||
|
||||
echo "开始使用gomobile编译..."
|
||||
gomobile bind -v \
|
||||
-androidapi=21 \
|
||||
-javapkg=io.nekohasekai \
|
||||
-libname=box \
|
||||
-tags="with_gvisor,with_quic,with_wireguard,with_ech,with_utls,with_clash_api,with_grpc" \
|
||||
-trimpath \
|
||||
-target=android/arm64 \
|
||||
-o libcore.aar \
|
||||
github.com/sagernet/sing-box/experimental/libbox ./mobile
|
||||
|
||||
if [ ! -f libcore.aar ]; then
|
||||
echo "❌ 编译失败: libcore.aar未生成"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "提取libbox.so..."
|
||||
unzip -j libcore.aar jni/arm64-v8a/libbox.so -d /tmp/
|
||||
if [ -f /tmp/libbox.so ]; then
|
||||
cp /tmp/libbox.so /workspace/libbox-new.so
|
||||
echo "✅ 编译成功!"
|
||||
ls -lh /workspace/libbox-new.so
|
||||
md5sum /workspace/libbox-new.so
|
||||
else
|
||||
echo "❌ 提取失败: libbox.so未找到"
|
||||
exit 1
|
||||
fi
|
||||
@ -1,30 +0,0 @@
|
||||
FROM alpine:latest
|
||||
ENV CONFIG='https://raw.githubusercontent.com/ircfspace/warpsub/main/export/warp#WARP%20(IRCF)'
|
||||
ENV VERSION=v3.1.7
|
||||
WORKDIR /hiddify
|
||||
RUN apk add curl tar gzip libc6-compat # iptables ip6tables
|
||||
|
||||
RUN echo "architecture: $(apk --print-arch)" && \
|
||||
case "$(apk --print-arch)" in \
|
||||
x86_64) ARCH=amd64 ;; \
|
||||
i386|x86) ARCH=386 ;; \
|
||||
aarch64) ARCH=arm64 ;; \
|
||||
armv7) ARCH=armv7 ;; \
|
||||
armv6|armhf) ARCH=armv6 ;; \
|
||||
armv5) ARCH=armv5 ;; \
|
||||
s390x) ARCH=s390x ;; \
|
||||
*) echo "Unsupported architecture: $(apk --print-arch) $(uname -m)" && exit 1 ;; \
|
||||
esac && \
|
||||
echo "Downloading https://github.com/hiddify/hiddify-core/releases/download/${VERSION}/hiddify-cli-linux-$ARCH.tar.gz" && \
|
||||
curl -L -o hiddify-cli.tar.gz https://github.com/hiddify/hiddify-core/releases/download/${VERSION}/hiddify-cli-linux-$ARCH.tar.gz && \
|
||||
tar -xzf hiddify-cli.tar.gz && rm hiddify-cli.tar.gz
|
||||
COPY hiddify.sh .
|
||||
RUN chmod +x hiddify.sh
|
||||
|
||||
EXPOSE 12334
|
||||
EXPOSE 12335
|
||||
EXPOSE 16756
|
||||
EXPOSE 16450
|
||||
|
||||
|
||||
ENTRYPOINT [ "/hiddify/hiddify.sh" ]
|
||||
@ -1,11 +0,0 @@
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
hiddify:
|
||||
image: ghcr.io/hiddify/hiddify-core:latest
|
||||
network_mode: host
|
||||
environment:
|
||||
CONFIG: "https://github.com/hiddify/hiddify-next/raw/refs/heads/main/test.configs/warp"
|
||||
volumes:
|
||||
- ./hiddify.json:/hiddify/hiddify.json
|
||||
command: ["/opt/hiddify.sh"]
|
||||
@ -1,42 +0,0 @@
|
||||
{
|
||||
"region":"other",
|
||||
"service-mode": "proxy",
|
||||
"log-level": "info",
|
||||
"resolve-destination": true,
|
||||
"ipv6-mode": "prefer_ipv4",
|
||||
"remote-dns-address": "tcp://1.1.1.1",
|
||||
"remote-dns-domain-strategy": "",
|
||||
"direct-dns-address": "1.1.1.1",
|
||||
"direct-dns-domain-strategy": "",
|
||||
"mixed-port": 12334,
|
||||
"local-dns-port": 16450,
|
||||
"tun-implementation": "mixed",
|
||||
"mtu": 9000,
|
||||
"strict-route": false,
|
||||
"connection-test-url": "https://www.gstatic.com/generate_204",
|
||||
"url-test-interval": 600,
|
||||
"enable-clash-api": true,
|
||||
"clash-api-port": 16756,
|
||||
"bypass-lan": false,
|
||||
"allow-connection-from-lan": true,
|
||||
"enable-fake-dns": false,
|
||||
"enable-dns-routing": true,
|
||||
"independent-dns-cache": true,
|
||||
"enable-tls-fragment": false,
|
||||
"tls-fragment-size": "20-70",
|
||||
"tls-fragment-sleep": "10-30",
|
||||
"enable-tls-mixed-sni-case": false,
|
||||
"enable-tls-padding": false,
|
||||
"tls-padding-size": "15-30",
|
||||
"enable-mux": false,
|
||||
"mux-padding": false,
|
||||
"mux-max-streams": 4,
|
||||
"mux-protocol": "h2mux",
|
||||
"enable-warp": false,
|
||||
"warp-detour-mode": "outbound",
|
||||
"warp-license-key": "",
|
||||
"warp-clean-ip": "auto",
|
||||
"warp-port": 0,
|
||||
"warp-noise": "5-10",
|
||||
"warp-noise-delay": "20-200"
|
||||
}
|
||||
@ -1,40 +0,0 @@
|
||||
#!/bin/sh
|
||||
# sysctl -w net.ipv4.ip_forward=1
|
||||
# sysctl -w net.ipv6.ip_forward=1
|
||||
|
||||
# ip rule add fwmark 1 table 100 ;
|
||||
# ip route add local 0.0.0.0/0 dev lo table 100
|
||||
|
||||
# # CREATE TABLE
|
||||
# iptables -t mangle -N hiddify
|
||||
|
||||
# # RETURN LOCAL AND LANS
|
||||
# iptables -t mangle -A OUTPUT -j RETURN
|
||||
# iptables -t nat -A hiddify --dport 2334 -j RETURN
|
||||
|
||||
# iptables -t mangle -A hiddify -d 10.0.0.0/8 -j RETURN
|
||||
# iptables -t mangle -A hiddify -d 127.0.0.0/8 -j RETURN
|
||||
# iptables -t mangle -A hiddify -d 169.254.0.0/16 -j RETURN
|
||||
# iptables -t mangle -A hiddify -d 172.16.0.0/12 -j RETURN
|
||||
# iptables -t mangle -A hiddify -d 192.168.50.0/16 -j RETURN
|
||||
# iptables -t mangle -A hiddify -d 192.168.9.0/16 -j RETURN
|
||||
# iptables -t mangle -A hiddify -d 224.0.0.0/4 -j RETURN
|
||||
# iptables -t mangle -A hiddify -d 240.0.0.0/4 -j RETURN
|
||||
|
||||
# iptables -t mangle -A hiddify -p udp -j TPROXY --on-port 2334 --tproxy-mark 1
|
||||
# iptables -t mangle -A hiddify -p tcp -j TPROXY --on-port 2334 --tproxy-mark 1
|
||||
|
||||
# # HIJACK ICMP (untested)
|
||||
# # iptables -t mangle -A hiddify -p icmp -j DNAT --to-destination 127.0.0.1
|
||||
|
||||
# # REDIRECT
|
||||
# iptables -t mangle -A PREROUTING -j hiddify
|
||||
|
||||
|
||||
if [ -f "/hiddify/hiddify.json" ]; then
|
||||
/hiddify/HiddifyCli run --config "$CONFIG" -d /hiddify/hiddify.json
|
||||
else
|
||||
/hiddify/HiddifyCli run --config "$CONFIG"
|
||||
fi
|
||||
|
||||
|
||||
@ -1,143 +0,0 @@
|
||||
package extension
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/hiddify/hiddify-core/config"
|
||||
"github.com/hiddify/hiddify-core/extension/ui"
|
||||
pb "github.com/hiddify/hiddify-core/hiddifyrpc"
|
||||
"github.com/hiddify/hiddify-core/v2/db"
|
||||
"github.com/jellydator/validation"
|
||||
"github.com/sagernet/sing-box/log"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
)
|
||||
|
||||
type Extension interface {
|
||||
GetUI() ui.Form
|
||||
SubmitData(button string, data map[string]string) error
|
||||
Close() error
|
||||
UpdateUI(form ui.Form) error
|
||||
|
||||
BeforeAppConnect(hiddifySettings *config.HiddifyOptions, singconfig *option.Options) error
|
||||
|
||||
StoreData()
|
||||
|
||||
init(id string)
|
||||
getQueue() chan *pb.ExtensionResponse
|
||||
getId() string
|
||||
}
|
||||
|
||||
type Base[T any] struct {
|
||||
id string
|
||||
// responseStream grpc.ServerStreamingServer[pb.ExtensionResponse]
|
||||
queue chan *pb.ExtensionResponse
|
||||
Data T
|
||||
}
|
||||
|
||||
// func (b *Base) mustEmbdedBaseExtension() {
|
||||
// }
|
||||
|
||||
func (b *Base[T]) BeforeAppConnect(hiddifySettings *config.HiddifyOptions, singconfig *option.Options) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *Base[T]) StoreData() {
|
||||
table := db.GetTable[extensionData]()
|
||||
ed, err := table.Get(b.id)
|
||||
if err != nil {
|
||||
log.Warn("error: ", err)
|
||||
return
|
||||
}
|
||||
res, err := json.Marshal(b.Data)
|
||||
if err != nil {
|
||||
log.Warn("error: ", err)
|
||||
return
|
||||
}
|
||||
ed.JsonData = (res)
|
||||
table.UpdateInsert(ed)
|
||||
}
|
||||
|
||||
func (b *Base[T]) init(id string) {
|
||||
b.id = id
|
||||
b.queue = make(chan *pb.ExtensionResponse, 1)
|
||||
table := db.GetTable[extensionData]()
|
||||
extdata, err := table.Get(b.id)
|
||||
if err != nil {
|
||||
log.Warn("error: ", err)
|
||||
return
|
||||
}
|
||||
if extdata == nil {
|
||||
log.Warn("extension data not found ", id)
|
||||
return
|
||||
}
|
||||
if extdata.JsonData != nil {
|
||||
var t T
|
||||
if err := json.Unmarshal(extdata.JsonData, &t); err != nil {
|
||||
log.Warn("error loading data of ", id, " : ", err)
|
||||
} else {
|
||||
b.Data = t
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (b *Base[T]) getQueue() chan *pb.ExtensionResponse {
|
||||
return b.queue
|
||||
}
|
||||
|
||||
func (b *Base[T]) getId() string {
|
||||
return b.id
|
||||
}
|
||||
|
||||
func (e *Base[T]) ShowMessage(title string, msg string) error {
|
||||
return e.ShowDialog(ui.Form{
|
||||
Title: title,
|
||||
Description: msg,
|
||||
Fields: [][]ui.FormField{
|
||||
{{
|
||||
Type: ui.FieldButton,
|
||||
Key: ui.ButtonDialogOk,
|
||||
Label: "Ok",
|
||||
}},
|
||||
},
|
||||
// Buttons: []string{ui.Button_Ok},
|
||||
})
|
||||
}
|
||||
|
||||
func (p *Base[T]) UpdateUI(form ui.Form) error {
|
||||
p.queue <- &pb.ExtensionResponse{
|
||||
ExtensionId: p.id,
|
||||
Type: pb.ExtensionResponseType_UPDATE_UI,
|
||||
JsonUi: form.ToJSON(),
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Base[T]) ShowDialog(form ui.Form) error {
|
||||
p.queue <- &pb.ExtensionResponse{
|
||||
ExtensionId: p.id,
|
||||
Type: pb.ExtensionResponseType_SHOW_DIALOG,
|
||||
JsonUi: form.ToJSON(),
|
||||
}
|
||||
// log.Printf("Updated UI for extension %s: %s", err, p.id)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (base *Base[T]) ValName(fieldPtr interface{}) string {
|
||||
val, err := validation.ErrorFieldName(&base.Data, fieldPtr)
|
||||
if err != nil {
|
||||
log.Warn(err)
|
||||
return ""
|
||||
}
|
||||
if val == "" {
|
||||
log.Warn("Field not found")
|
||||
return ""
|
||||
}
|
||||
return val
|
||||
}
|
||||
|
||||
type ExtensionFactory struct {
|
||||
Id string
|
||||
Title string
|
||||
Description string
|
||||
Builder func() Extension
|
||||
}
|
||||
@ -1,146 +0,0 @@
|
||||
package extension
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
pb "github.com/hiddify/hiddify-core/hiddifyrpc"
|
||||
"github.com/hiddify/hiddify-core/v2/db"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
type ExtensionHostService struct {
|
||||
pb.UnimplementedExtensionHostServiceServer
|
||||
}
|
||||
|
||||
func (ExtensionHostService) ListExtensions(ctx context.Context, empty *pb.Empty) (*pb.ExtensionList, error) {
|
||||
extensionList := &pb.ExtensionList{
|
||||
Extensions: make([]*pb.Extension, 0),
|
||||
}
|
||||
allext, err := db.GetTable[extensionData]().All()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, dbext := range allext {
|
||||
if ext, ok := allExtensionsMap[dbext.Id]; ok {
|
||||
extensionList.Extensions = append(extensionList.Extensions, &pb.Extension{
|
||||
Id: ext.Id,
|
||||
Title: ext.Title,
|
||||
Description: ext.Description,
|
||||
Enable: dbext.Enable,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return extensionList, nil
|
||||
}
|
||||
|
||||
func getExtension(id string) (*Extension, error) {
|
||||
if !isEnable(id) {
|
||||
return nil, fmt.Errorf("Extension with ID %s is not enabled", id)
|
||||
}
|
||||
if extension, ok := enabledExtensionsMap[id]; ok {
|
||||
return extension, nil
|
||||
}
|
||||
return nil, fmt.Errorf("Extension with ID %s not found", id)
|
||||
}
|
||||
|
||||
func (e ExtensionHostService) Connect(req *pb.ExtensionRequest, stream grpc.ServerStreamingServer[pb.ExtensionResponse]) error {
|
||||
extension, err := getExtension(req.GetExtensionId())
|
||||
if err != nil {
|
||||
log.Printf("Error connecting stream for extension %s: %v", req.GetExtensionId(), err)
|
||||
return err
|
||||
}
|
||||
|
||||
log.Printf("Connecting stream for extension %s", req.GetExtensionId())
|
||||
log.Printf("Extension data: %+v", extension)
|
||||
|
||||
if err := (*extension).UpdateUI((*extension).GetUI()); err != nil {
|
||||
log.Printf("Error updating UI for extension %s: %v", req.GetExtensionId(), err)
|
||||
}
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-stream.Context().Done():
|
||||
return nil
|
||||
case info := <-(*extension).getQueue():
|
||||
stream.Send(info)
|
||||
if info.GetType() == pb.ExtensionResponseType_END {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (e ExtensionHostService) SubmitForm(ctx context.Context, req *pb.SendExtensionDataRequest) (*pb.ExtensionActionResult, error) {
|
||||
extension, err := getExtension(req.GetExtensionId())
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
return &pb.ExtensionActionResult{
|
||||
ExtensionId: req.ExtensionId,
|
||||
Code: pb.ResponseCode_FAILED,
|
||||
Message: err.Error(),
|
||||
}, err
|
||||
}
|
||||
(*extension).SubmitData(req.Button, req.GetData())
|
||||
|
||||
return &pb.ExtensionActionResult{
|
||||
ExtensionId: req.ExtensionId,
|
||||
Code: pb.ResponseCode_OK,
|
||||
Message: "Success",
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (e ExtensionHostService) Close(ctx context.Context, req *pb.ExtensionRequest) (*pb.ExtensionActionResult, error) {
|
||||
extension, err := getExtension(req.GetExtensionId())
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
return &pb.ExtensionActionResult{
|
||||
ExtensionId: req.ExtensionId,
|
||||
Code: pb.ResponseCode_FAILED,
|
||||
Message: err.Error(),
|
||||
}, err
|
||||
}
|
||||
(*extension).Close()
|
||||
(*extension).StoreData()
|
||||
return &pb.ExtensionActionResult{
|
||||
ExtensionId: req.ExtensionId,
|
||||
Code: pb.ResponseCode_OK,
|
||||
Message: "Success",
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (e ExtensionHostService) EditExtension(ctx context.Context, req *pb.EditExtensionRequest) (*pb.ExtensionActionResult, error) {
|
||||
if !req.Enable {
|
||||
extension, _ := getExtension(req.GetExtensionId())
|
||||
if extension != nil {
|
||||
(*extension).Close()
|
||||
(*extension).StoreData()
|
||||
}
|
||||
delete(enabledExtensionsMap, req.GetExtensionId())
|
||||
}
|
||||
table := db.GetTable[extensionData]()
|
||||
data, err := table.Get(req.GetExtensionId())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
data.Enable = req.Enable
|
||||
table.UpdateInsert(data)
|
||||
|
||||
if req.Enable {
|
||||
loadExtension(allExtensionsMap[req.GetExtensionId()])
|
||||
}
|
||||
|
||||
return &pb.ExtensionActionResult{
|
||||
ExtensionId: req.ExtensionId,
|
||||
Code: pb.ResponseCode_OK,
|
||||
Message: "Success",
|
||||
}, nil
|
||||
}
|
||||
|
||||
type extensionData struct {
|
||||
Id string `json:"id"`
|
||||
Enable bool `json:"enable"`
|
||||
JsonData []byte
|
||||
}
|
||||
@ -1,12 +0,0 @@
|
||||
|
||||
import * as a from "./rpc/extension_grpc_web_pb.js";
|
||||
const client = new ExtensionHostServiceClient('http://localhost:8080');
|
||||
const request = new GetHelloRequest();
|
||||
export const getHello = (name) => {
|
||||
request.setName(name)
|
||||
client.getHello(request, {}, (err, response) => {
|
||||
console.log(request.getName());
|
||||
console.log(response.toObject());
|
||||
});
|
||||
}
|
||||
getHello("D")
|
||||
@ -1,82 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Hiddify Extensions</title>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/css/bootstrap.min.css" integrity="sha512-jnSuA4Ss2PkkikSOLtYs8BlYIeeIK1h99ty4YfvRPAlzr377vr3CXDb7sb7eEEBYjDtcYj+AjBH3FLv5uSJuXg==" crossorigin="anonymous" referrerpolicy="no-referrer" />
|
||||
|
||||
|
||||
<style>
|
||||
pre {
|
||||
background-color: black !important; overflow: auto;
|
||||
color: white!important; }
|
||||
</style>
|
||||
|
||||
|
||||
</head>
|
||||
<body>
|
||||
<div class="container mt-5">
|
||||
<div id="connection-page" class="card p-4">
|
||||
<div id="connection-before-connect" class="card-body">
|
||||
<h2 class="card-title mb-4">Connection Settings</h2>
|
||||
|
||||
<div class="mb-3">
|
||||
<label for="config-content" class="form-label">Config String</label>
|
||||
<textarea id="config-content" class="form-control" placeholder="Enter config string here..." rows="3"></textarea>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="hiddify-settings" class="form-label">Hiddify Settings</label>
|
||||
<textarea id="hiddify-settings" class="form-control" placeholder="Enter Hiddify settings here..." rows="3"></textarea>
|
||||
</div>
|
||||
|
||||
<div class="d-flex justify-content-between">
|
||||
<button id="connect-button" class="btn btn-success">Connect</button>
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
<div id="connection-connecting" class="card-body d-none">
|
||||
<h2 id="connection-status" class="card-title mb-4">Connecting...</h2>
|
||||
<button id="disconnect-button" class="btn btn-danger">Disconnect</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="extension-list-container" class="card p-4">
|
||||
<h1 class="mb-4">
|
||||
Extension List
|
||||
</h1>
|
||||
<div id="extension-list" class="list-group">
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<div id="extension-page-container" class="card p-4">
|
||||
|
||||
<div id="extension-page"></div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
<div class="modal fade" id="extension-dialog" style="display: none;" tabindex="-1" aria-labelledby="modalLabel" aria-hidden="true">
|
||||
<div class="modal-dialog">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title" id="modalLabel">Extension List</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<div id="extension-page-containerdialog"></div>
|
||||
</div>
|
||||
<div class="modal-footer" id="modal-footer">
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<script src="https://unpkg.com/ansi_up@5.0.0/ansi_up.js"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/protobufjs@7.X.X/dist/protobuf.min.js"></script>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/js/bootstrap.bundle.min.js" integrity="sha512-7Pi/otdlbbCR+LnW+F7PwFcSDJOuUJB3OxtEHbg4vSMvzvJjde4Po1v4BR9Gdc9aXNUNFVUY+SK51wWT8WF0Gg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js" integrity="sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
|
||||
<script src="rpc.js?1"></script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
File diff suppressed because it is too large
Load Diff
@ -1,460 +0,0 @@
|
||||
// source: base.proto
|
||||
/**
|
||||
* @fileoverview
|
||||
* @enhanceable
|
||||
* @suppress {missingRequire} reports error on implicit type usages.
|
||||
* @suppress {messageConventions} JS Compiler reports an error if a variable or
|
||||
* field starts with 'MSG_' and isn't a translatable message.
|
||||
* @public
|
||||
*/
|
||||
// GENERATED CODE -- DO NOT EDIT!
|
||||
/* eslint-disable */
|
||||
// @ts-nocheck
|
||||
|
||||
var jspb = require('google-protobuf');
|
||||
var goog = jspb;
|
||||
var global =
|
||||
(typeof globalThis !== 'undefined' && globalThis) ||
|
||||
(typeof window !== 'undefined' && window) ||
|
||||
(typeof global !== 'undefined' && global) ||
|
||||
(typeof self !== 'undefined' && self) ||
|
||||
(function () { return this; }).call(null) ||
|
||||
Function('return this')();
|
||||
|
||||
goog.exportSymbol('proto.hiddifyrpc.Empty', null, global);
|
||||
goog.exportSymbol('proto.hiddifyrpc.HelloRequest', null, global);
|
||||
goog.exportSymbol('proto.hiddifyrpc.HelloResponse', null, global);
|
||||
goog.exportSymbol('proto.hiddifyrpc.ResponseCode', null, global);
|
||||
/**
|
||||
* Generated by JsPbCodeGenerator.
|
||||
* @param {Array=} opt_data Optional initial data array, typically from a
|
||||
* server response, or constructed directly in Javascript. The array is used
|
||||
* in place and becomes part of the constructed object. It is not cloned.
|
||||
* If no data is provided, the constructed object will be empty, but still
|
||||
* valid.
|
||||
* @extends {jspb.Message}
|
||||
* @constructor
|
||||
*/
|
||||
proto.hiddifyrpc.HelloRequest = function(opt_data) {
|
||||
jspb.Message.initialize(this, opt_data, 0, -1, null, null);
|
||||
};
|
||||
goog.inherits(proto.hiddifyrpc.HelloRequest, jspb.Message);
|
||||
if (goog.DEBUG && !COMPILED) {
|
||||
/**
|
||||
* @public
|
||||
* @override
|
||||
*/
|
||||
proto.hiddifyrpc.HelloRequest.displayName = 'proto.hiddifyrpc.HelloRequest';
|
||||
}
|
||||
/**
|
||||
* Generated by JsPbCodeGenerator.
|
||||
* @param {Array=} opt_data Optional initial data array, typically from a
|
||||
* server response, or constructed directly in Javascript. The array is used
|
||||
* in place and becomes part of the constructed object. It is not cloned.
|
||||
* If no data is provided, the constructed object will be empty, but still
|
||||
* valid.
|
||||
* @extends {jspb.Message}
|
||||
* @constructor
|
||||
*/
|
||||
proto.hiddifyrpc.HelloResponse = function(opt_data) {
|
||||
jspb.Message.initialize(this, opt_data, 0, -1, null, null);
|
||||
};
|
||||
goog.inherits(proto.hiddifyrpc.HelloResponse, jspb.Message);
|
||||
if (goog.DEBUG && !COMPILED) {
|
||||
/**
|
||||
* @public
|
||||
* @override
|
||||
*/
|
||||
proto.hiddifyrpc.HelloResponse.displayName = 'proto.hiddifyrpc.HelloResponse';
|
||||
}
|
||||
/**
|
||||
* Generated by JsPbCodeGenerator.
|
||||
* @param {Array=} opt_data Optional initial data array, typically from a
|
||||
* server response, or constructed directly in Javascript. The array is used
|
||||
* in place and becomes part of the constructed object. It is not cloned.
|
||||
* If no data is provided, the constructed object will be empty, but still
|
||||
* valid.
|
||||
* @extends {jspb.Message}
|
||||
* @constructor
|
||||
*/
|
||||
proto.hiddifyrpc.Empty = function(opt_data) {
|
||||
jspb.Message.initialize(this, opt_data, 0, -1, null, null);
|
||||
};
|
||||
goog.inherits(proto.hiddifyrpc.Empty, jspb.Message);
|
||||
if (goog.DEBUG && !COMPILED) {
|
||||
/**
|
||||
* @public
|
||||
* @override
|
||||
*/
|
||||
proto.hiddifyrpc.Empty.displayName = 'proto.hiddifyrpc.Empty';
|
||||
}
|
||||
|
||||
|
||||
|
||||
if (jspb.Message.GENERATE_TO_OBJECT) {
|
||||
/**
|
||||
* Creates an object representation of this proto.
|
||||
* Field names that are reserved in JavaScript and will be renamed to pb_name.
|
||||
* Optional fields that are not set will be set to undefined.
|
||||
* To access a reserved field use, foo.pb_<name>, eg, foo.pb_default.
|
||||
* For the list of reserved names please see:
|
||||
* net/proto2/compiler/js/internal/generator.cc#kKeyword.
|
||||
* @param {boolean=} opt_includeInstance Deprecated. whether to include the
|
||||
* JSPB instance for transitional soy proto support:
|
||||
* http://goto/soy-param-migration
|
||||
* @return {!Object}
|
||||
*/
|
||||
proto.hiddifyrpc.HelloRequest.prototype.toObject = function(opt_includeInstance) {
|
||||
return proto.hiddifyrpc.HelloRequest.toObject(opt_includeInstance, this);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Static version of the {@see toObject} method.
|
||||
* @param {boolean|undefined} includeInstance Deprecated. Whether to include
|
||||
* the JSPB instance for transitional soy proto support:
|
||||
* http://goto/soy-param-migration
|
||||
* @param {!proto.hiddifyrpc.HelloRequest} msg The msg instance to transform.
|
||||
* @return {!Object}
|
||||
* @suppress {unusedLocalVariables} f is only used for nested messages
|
||||
*/
|
||||
proto.hiddifyrpc.HelloRequest.toObject = function(includeInstance, msg) {
|
||||
var f, obj = {
|
||||
name: jspb.Message.getFieldWithDefault(msg, 1, "")
|
||||
};
|
||||
|
||||
if (includeInstance) {
|
||||
obj.$jspbMessageInstance = msg;
|
||||
}
|
||||
return obj;
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Deserializes binary data (in protobuf wire format).
|
||||
* @param {jspb.ByteSource} bytes The bytes to deserialize.
|
||||
* @return {!proto.hiddifyrpc.HelloRequest}
|
||||
*/
|
||||
proto.hiddifyrpc.HelloRequest.deserializeBinary = function(bytes) {
|
||||
var reader = new jspb.BinaryReader(bytes);
|
||||
var msg = new proto.hiddifyrpc.HelloRequest;
|
||||
return proto.hiddifyrpc.HelloRequest.deserializeBinaryFromReader(msg, reader);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Deserializes binary data (in protobuf wire format) from the
|
||||
* given reader into the given message object.
|
||||
* @param {!proto.hiddifyrpc.HelloRequest} msg The message object to deserialize into.
|
||||
* @param {!jspb.BinaryReader} reader The BinaryReader to use.
|
||||
* @return {!proto.hiddifyrpc.HelloRequest}
|
||||
*/
|
||||
proto.hiddifyrpc.HelloRequest.deserializeBinaryFromReader = function(msg, reader) {
|
||||
while (reader.nextField()) {
|
||||
if (reader.isEndGroup()) {
|
||||
break;
|
||||
}
|
||||
var field = reader.getFieldNumber();
|
||||
switch (field) {
|
||||
case 1:
|
||||
var value = /** @type {string} */ (reader.readString());
|
||||
msg.setName(value);
|
||||
break;
|
||||
default:
|
||||
reader.skipField();
|
||||
break;
|
||||
}
|
||||
}
|
||||
return msg;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Serializes the message to binary data (in protobuf wire format).
|
||||
* @return {!Uint8Array}
|
||||
*/
|
||||
proto.hiddifyrpc.HelloRequest.prototype.serializeBinary = function() {
|
||||
var writer = new jspb.BinaryWriter();
|
||||
proto.hiddifyrpc.HelloRequest.serializeBinaryToWriter(this, writer);
|
||||
return writer.getResultBuffer();
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Serializes the given message to binary data (in protobuf wire
|
||||
* format), writing to the given BinaryWriter.
|
||||
* @param {!proto.hiddifyrpc.HelloRequest} message
|
||||
* @param {!jspb.BinaryWriter} writer
|
||||
* @suppress {unusedLocalVariables} f is only used for nested messages
|
||||
*/
|
||||
proto.hiddifyrpc.HelloRequest.serializeBinaryToWriter = function(message, writer) {
|
||||
var f = undefined;
|
||||
f = message.getName();
|
||||
if (f.length > 0) {
|
||||
writer.writeString(
|
||||
1,
|
||||
f
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* optional string name = 1;
|
||||
* @return {string}
|
||||
*/
|
||||
proto.hiddifyrpc.HelloRequest.prototype.getName = function() {
|
||||
return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, ""));
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @param {string} value
|
||||
* @return {!proto.hiddifyrpc.HelloRequest} returns this
|
||||
*/
|
||||
proto.hiddifyrpc.HelloRequest.prototype.setName = function(value) {
|
||||
return jspb.Message.setProto3StringField(this, 1, value);
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
if (jspb.Message.GENERATE_TO_OBJECT) {
|
||||
/**
|
||||
* Creates an object representation of this proto.
|
||||
* Field names that are reserved in JavaScript and will be renamed to pb_name.
|
||||
* Optional fields that are not set will be set to undefined.
|
||||
* To access a reserved field use, foo.pb_<name>, eg, foo.pb_default.
|
||||
* For the list of reserved names please see:
|
||||
* net/proto2/compiler/js/internal/generator.cc#kKeyword.
|
||||
* @param {boolean=} opt_includeInstance Deprecated. whether to include the
|
||||
* JSPB instance for transitional soy proto support:
|
||||
* http://goto/soy-param-migration
|
||||
* @return {!Object}
|
||||
*/
|
||||
proto.hiddifyrpc.HelloResponse.prototype.toObject = function(opt_includeInstance) {
|
||||
return proto.hiddifyrpc.HelloResponse.toObject(opt_includeInstance, this);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Static version of the {@see toObject} method.
|
||||
* @param {boolean|undefined} includeInstance Deprecated. Whether to include
|
||||
* the JSPB instance for transitional soy proto support:
|
||||
* http://goto/soy-param-migration
|
||||
* @param {!proto.hiddifyrpc.HelloResponse} msg The msg instance to transform.
|
||||
* @return {!Object}
|
||||
* @suppress {unusedLocalVariables} f is only used for nested messages
|
||||
*/
|
||||
proto.hiddifyrpc.HelloResponse.toObject = function(includeInstance, msg) {
|
||||
var f, obj = {
|
||||
message: jspb.Message.getFieldWithDefault(msg, 1, "")
|
||||
};
|
||||
|
||||
if (includeInstance) {
|
||||
obj.$jspbMessageInstance = msg;
|
||||
}
|
||||
return obj;
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Deserializes binary data (in protobuf wire format).
|
||||
* @param {jspb.ByteSource} bytes The bytes to deserialize.
|
||||
* @return {!proto.hiddifyrpc.HelloResponse}
|
||||
*/
|
||||
proto.hiddifyrpc.HelloResponse.deserializeBinary = function(bytes) {
|
||||
var reader = new jspb.BinaryReader(bytes);
|
||||
var msg = new proto.hiddifyrpc.HelloResponse;
|
||||
return proto.hiddifyrpc.HelloResponse.deserializeBinaryFromReader(msg, reader);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Deserializes binary data (in protobuf wire format) from the
|
||||
* given reader into the given message object.
|
||||
* @param {!proto.hiddifyrpc.HelloResponse} msg The message object to deserialize into.
|
||||
* @param {!jspb.BinaryReader} reader The BinaryReader to use.
|
||||
* @return {!proto.hiddifyrpc.HelloResponse}
|
||||
*/
|
||||
proto.hiddifyrpc.HelloResponse.deserializeBinaryFromReader = function(msg, reader) {
|
||||
while (reader.nextField()) {
|
||||
if (reader.isEndGroup()) {
|
||||
break;
|
||||
}
|
||||
var field = reader.getFieldNumber();
|
||||
switch (field) {
|
||||
case 1:
|
||||
var value = /** @type {string} */ (reader.readString());
|
||||
msg.setMessage(value);
|
||||
break;
|
||||
default:
|
||||
reader.skipField();
|
||||
break;
|
||||
}
|
||||
}
|
||||
return msg;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Serializes the message to binary data (in protobuf wire format).
|
||||
* @return {!Uint8Array}
|
||||
*/
|
||||
proto.hiddifyrpc.HelloResponse.prototype.serializeBinary = function() {
|
||||
var writer = new jspb.BinaryWriter();
|
||||
proto.hiddifyrpc.HelloResponse.serializeBinaryToWriter(this, writer);
|
||||
return writer.getResultBuffer();
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Serializes the given message to binary data (in protobuf wire
|
||||
* format), writing to the given BinaryWriter.
|
||||
* @param {!proto.hiddifyrpc.HelloResponse} message
|
||||
* @param {!jspb.BinaryWriter} writer
|
||||
* @suppress {unusedLocalVariables} f is only used for nested messages
|
||||
*/
|
||||
proto.hiddifyrpc.HelloResponse.serializeBinaryToWriter = function(message, writer) {
|
||||
var f = undefined;
|
||||
f = message.getMessage();
|
||||
if (f.length > 0) {
|
||||
writer.writeString(
|
||||
1,
|
||||
f
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* optional string message = 1;
|
||||
* @return {string}
|
||||
*/
|
||||
proto.hiddifyrpc.HelloResponse.prototype.getMessage = function() {
|
||||
return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, ""));
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @param {string} value
|
||||
* @return {!proto.hiddifyrpc.HelloResponse} returns this
|
||||
*/
|
||||
proto.hiddifyrpc.HelloResponse.prototype.setMessage = function(value) {
|
||||
return jspb.Message.setProto3StringField(this, 1, value);
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
if (jspb.Message.GENERATE_TO_OBJECT) {
|
||||
/**
|
||||
* Creates an object representation of this proto.
|
||||
* Field names that are reserved in JavaScript and will be renamed to pb_name.
|
||||
* Optional fields that are not set will be set to undefined.
|
||||
* To access a reserved field use, foo.pb_<name>, eg, foo.pb_default.
|
||||
* For the list of reserved names please see:
|
||||
* net/proto2/compiler/js/internal/generator.cc#kKeyword.
|
||||
* @param {boolean=} opt_includeInstance Deprecated. whether to include the
|
||||
* JSPB instance for transitional soy proto support:
|
||||
* http://goto/soy-param-migration
|
||||
* @return {!Object}
|
||||
*/
|
||||
proto.hiddifyrpc.Empty.prototype.toObject = function(opt_includeInstance) {
|
||||
return proto.hiddifyrpc.Empty.toObject(opt_includeInstance, this);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Static version of the {@see toObject} method.
|
||||
* @param {boolean|undefined} includeInstance Deprecated. Whether to include
|
||||
* the JSPB instance for transitional soy proto support:
|
||||
* http://goto/soy-param-migration
|
||||
* @param {!proto.hiddifyrpc.Empty} msg The msg instance to transform.
|
||||
* @return {!Object}
|
||||
* @suppress {unusedLocalVariables} f is only used for nested messages
|
||||
*/
|
||||
proto.hiddifyrpc.Empty.toObject = function(includeInstance, msg) {
|
||||
var f, obj = {
|
||||
|
||||
};
|
||||
|
||||
if (includeInstance) {
|
||||
obj.$jspbMessageInstance = msg;
|
||||
}
|
||||
return obj;
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Deserializes binary data (in protobuf wire format).
|
||||
* @param {jspb.ByteSource} bytes The bytes to deserialize.
|
||||
* @return {!proto.hiddifyrpc.Empty}
|
||||
*/
|
||||
proto.hiddifyrpc.Empty.deserializeBinary = function(bytes) {
|
||||
var reader = new jspb.BinaryReader(bytes);
|
||||
var msg = new proto.hiddifyrpc.Empty;
|
||||
return proto.hiddifyrpc.Empty.deserializeBinaryFromReader(msg, reader);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Deserializes binary data (in protobuf wire format) from the
|
||||
* given reader into the given message object.
|
||||
* @param {!proto.hiddifyrpc.Empty} msg The message object to deserialize into.
|
||||
* @param {!jspb.BinaryReader} reader The BinaryReader to use.
|
||||
* @return {!proto.hiddifyrpc.Empty}
|
||||
*/
|
||||
proto.hiddifyrpc.Empty.deserializeBinaryFromReader = function(msg, reader) {
|
||||
while (reader.nextField()) {
|
||||
if (reader.isEndGroup()) {
|
||||
break;
|
||||
}
|
||||
var field = reader.getFieldNumber();
|
||||
switch (field) {
|
||||
default:
|
||||
reader.skipField();
|
||||
break;
|
||||
}
|
||||
}
|
||||
return msg;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Serializes the message to binary data (in protobuf wire format).
|
||||
* @return {!Uint8Array}
|
||||
*/
|
||||
proto.hiddifyrpc.Empty.prototype.serializeBinary = function() {
|
||||
var writer = new jspb.BinaryWriter();
|
||||
proto.hiddifyrpc.Empty.serializeBinaryToWriter(this, writer);
|
||||
return writer.getResultBuffer();
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Serializes the given message to binary data (in protobuf wire
|
||||
* format), writing to the given BinaryWriter.
|
||||
* @param {!proto.hiddifyrpc.Empty} message
|
||||
* @param {!jspb.BinaryWriter} writer
|
||||
* @suppress {unusedLocalVariables} f is only used for nested messages
|
||||
*/
|
||||
proto.hiddifyrpc.Empty.serializeBinaryToWriter = function(message, writer) {
|
||||
var f = undefined;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @enum {number}
|
||||
*/
|
||||
proto.hiddifyrpc.ResponseCode = {
|
||||
OK: 0,
|
||||
FAILED: 1
|
||||
};
|
||||
|
||||
goog.object.extend(exports, proto.hiddifyrpc);
|
||||
@ -1,8 +0,0 @@
|
||||
const hiddify = require("./hiddify_grpc_web_pb.js");
|
||||
const extension = require("./extension_grpc_web_pb.js");
|
||||
|
||||
const grpcServerAddress = '/';
|
||||
const extensionClient = new extension.ExtensionHostServicePromiseClient(grpcServerAddress, null, null);
|
||||
const hiddifyClient = new hiddify.CorePromiseClient(grpcServerAddress, null, null);
|
||||
|
||||
module.exports = { extensionClient ,hiddifyClient};
|
||||
@ -1,109 +0,0 @@
|
||||
const { hiddifyClient } = require('./client.js');
|
||||
const hiddify = require("./hiddify_grpc_web_pb.js");
|
||||
|
||||
function openConnectionPage() {
|
||||
|
||||
$("#extension-list-container").show();
|
||||
$("#extension-page-container").hide();
|
||||
$("#connection-page").show();
|
||||
connect();
|
||||
$("#connect-button").click(async () => {
|
||||
const hsetting_request = new hiddify.ChangeHiddifySettingsRequest();
|
||||
hsetting_request.setHiddifySettingsJson($("#hiddify-settings").val());
|
||||
try{
|
||||
const hres=await hiddifyClient.changeHiddifySettings(hsetting_request, {});
|
||||
}catch(err){
|
||||
$("#hiddify-settings").val("")
|
||||
console.log(err)
|
||||
}
|
||||
|
||||
const parse_request = new hiddify.ParseRequest();
|
||||
parse_request.setContent($("#config-content").val());
|
||||
try{
|
||||
const pres=await hiddifyClient.parse(parse_request, {});
|
||||
if (pres.getResponseCode() !== hiddify.ResponseCode.OK){
|
||||
alert(pres.getMessage());
|
||||
return
|
||||
}
|
||||
$("#config-content").val(pres.getContent());
|
||||
}catch(err){
|
||||
console.log(err)
|
||||
alert(JSON.stringify(err))
|
||||
return
|
||||
}
|
||||
|
||||
const request = new hiddify.StartRequest();
|
||||
|
||||
request.setConfigContent($("#config-content").val());
|
||||
request.setEnableRawConfig(false);
|
||||
try{
|
||||
const res=await hiddifyClient.start(request, {});
|
||||
console.log(res.getCoreState(),res.getMessage())
|
||||
handleCoreStatus(res.getCoreState());
|
||||
}catch(err){
|
||||
console.log(err)
|
||||
alert(JSON.stringify(err))
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
})
|
||||
|
||||
$("#disconnect-button").click(async () => {
|
||||
const request = new hiddify.Empty();
|
||||
try{
|
||||
const res=await hiddifyClient.stop(request, {});
|
||||
console.log(res.getCoreState(),res.getMessage())
|
||||
handleCoreStatus(res.getCoreState());
|
||||
}catch(err){
|
||||
console.log(err)
|
||||
alert(JSON.stringify(err))
|
||||
return
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
function connect(){
|
||||
const request = new hiddify.Empty();
|
||||
const stream = hiddifyClient.coreInfoListener(request, {});
|
||||
stream.on('data', (response) => {
|
||||
console.log('Receving ',response);
|
||||
handleCoreStatus(response);
|
||||
});
|
||||
|
||||
stream.on('error', (err) => {
|
||||
console.error('Error opening extension page:', err);
|
||||
// openExtensionPage(extensionId);
|
||||
});
|
||||
|
||||
stream.on('end', () => {
|
||||
console.log('Stream ended');
|
||||
setTimeout(connect, 1000);
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
function handleCoreStatus(status){
|
||||
if (status == hiddify.CoreState.STOPPED){
|
||||
$("#connection-before-connect").show();
|
||||
$("#connection-connecting").hide();
|
||||
}else{
|
||||
$("#connection-before-connect").hide();
|
||||
$("#connection-connecting").show();
|
||||
if (status == hiddify.CoreState.STARTING){
|
||||
$("#connection-status").text("Starting");
|
||||
$("#connection-status").css("color", "yellow");
|
||||
}else if (status == hiddify.CoreState.STOPPING){
|
||||
$("#connection-status").text("Stopping");
|
||||
$("#connection-status").css("color", "red");
|
||||
}else if (status == hiddify.CoreState.STARTED){
|
||||
$("#connection-status").text("Connected");
|
||||
$("#connection-status").css("color", "green");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
module.exports = { openConnectionPage };
|
||||
@ -1,8 +0,0 @@
|
||||
const { listExtensions } = require('./extensionList.js');
|
||||
const { openConnectionPage } = require('./connectionPage.js');
|
||||
window.onload = () => {
|
||||
listExtensions();
|
||||
openConnectionPage();
|
||||
};
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user