新增调试信息
This commit is contained in:
parent
ae62457d8c
commit
04642cb2f0
3
.gitmodules
vendored
Normal file
3
.gitmodules
vendored
Normal file
@ -0,0 +1,3 @@
|
||||
[submodule "libcore"]
|
||||
path = libcore
|
||||
url = https://github.com/hiddify/hiddify-next-core
|
||||
@ -1,157 +0,0 @@
|
||||
# Android 登录框不显示问题修复总结
|
||||
|
||||
## 🔧 修复内容
|
||||
|
||||
### **1. KRHomeController 登录状态初始化逻辑修复**
|
||||
|
||||
#### **修复前的问题**
|
||||
- 登录状态初始化没有延迟,可能在异步操作完成前就执行
|
||||
- 缺少状态验证,直接使用 `kr_isLogin.value` 可能导致状态不一致
|
||||
- 订阅服务初始化失败时没有错误处理
|
||||
- 缺少状态同步检查机制
|
||||
|
||||
#### **修复后的改进**
|
||||
```dart
|
||||
// 1. 添加延迟初始化
|
||||
Future.delayed(const Duration(milliseconds: 100), () {
|
||||
_kr_validateAndSetLoginStatus();
|
||||
});
|
||||
|
||||
// 2. 添加状态验证
|
||||
final isValidLogin = KRAppRunData().kr_token != null &&
|
||||
KRAppRunData().kr_isLogin.value;
|
||||
|
||||
// 3. 添加错误处理
|
||||
kr_subscribeService.kr_refreshAll().catchError((error) {
|
||||
KRLogUtil.kr_e('订阅服务初始化失败: $error', tag: 'HomeController');
|
||||
});
|
||||
|
||||
// 4. 添加状态同步检查
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
_kr_syncLoginStatus();
|
||||
});
|
||||
```
|
||||
|
||||
### **2. KRAppRunData 初始化逻辑优化**
|
||||
|
||||
#### **修复前的问题**
|
||||
- 登录状态设置和异步操作之间存在竞态条件
|
||||
- 缺少详细的日志记录,难以调试问题
|
||||
- 错误处理不够完善
|
||||
|
||||
#### **修复后的改进**
|
||||
```dart
|
||||
// 1. 添加详细日志
|
||||
KRLogUtil.kr_i('开始初始化用户信息', tag: 'AppRunData');
|
||||
|
||||
// 2. 验证token有效性
|
||||
if (kr_token != null && kr_token!.isNotEmpty) {
|
||||
kr_isLogin.value = true;
|
||||
// 异步获取用户信息,不等待结果
|
||||
_iniUserInfo().catchError((error) {
|
||||
KRLogUtil.kr_e('获取用户信息失败: $error', tag: 'AppRunData');
|
||||
});
|
||||
}
|
||||
|
||||
// 3. 改进保存逻辑
|
||||
// 只有在保存成功后才设置登录状态
|
||||
kr_isLogin.value = true;
|
||||
```
|
||||
|
||||
### **3. 启动页面保护机制**
|
||||
|
||||
#### **修复前的问题**
|
||||
- 启动完成后立即跳转,没有验证初始化结果
|
||||
- 缺少启动状态的日志记录
|
||||
|
||||
#### **修复后的改进**
|
||||
```dart
|
||||
// 1. 添加初始化完成等待
|
||||
await Future.delayed(const Duration(milliseconds: 200));
|
||||
|
||||
// 2. 验证登录状态
|
||||
final loginStatus = KRAppRunData.getInstance().kr_isLogin.value;
|
||||
KRLogUtil.kr_i('启动完成,最终登录状态: $loginStatus', tag: 'SplashController');
|
||||
```
|
||||
|
||||
## 🎯 修复效果
|
||||
|
||||
### **解决的问题**
|
||||
1. **竞态条件** - 通过延迟初始化和状态验证解决
|
||||
2. **状态不一致** - 通过状态同步检查机制解决
|
||||
3. **异步操作失败** - 通过错误处理和重试机制解决
|
||||
4. **调试困难** - 通过详细日志记录解决
|
||||
|
||||
### **预期改进**
|
||||
1. **登录框显示稳定性** - 减少启动时登录框不显示的情况
|
||||
2. **状态一致性** - 确保UI状态与实际登录状态一致
|
||||
3. **错误恢复能力** - 提高应用在异常情况下的恢复能力
|
||||
4. **调试便利性** - 通过详细日志便于问题定位
|
||||
|
||||
## 📊 修复策略
|
||||
|
||||
### **1. 延迟初始化策略**
|
||||
- 在首页控制器初始化时延迟100ms执行状态验证
|
||||
- 确保所有异步操作有足够时间完成
|
||||
|
||||
### **2. 状态验证策略**
|
||||
- 双重验证:检查 `kr_token` 和 `kr_isLogin.value`
|
||||
- 防止状态不一致导致的UI问题
|
||||
|
||||
### **3. 错误处理策略**
|
||||
- 订阅服务初始化失败时不重置登录状态
|
||||
- 记录错误但不影响用户使用
|
||||
|
||||
### **4. 状态同步策略**
|
||||
- 在UI渲染后检查状态一致性
|
||||
- 自动修正不一致的状态
|
||||
|
||||
## 🧪 测试建议
|
||||
|
||||
### **1. 基础功能测试**
|
||||
- 正常启动测试:连续启动应用10次,观察登录框显示情况
|
||||
- 登录状态测试:验证已登录和未登录状态的正确显示
|
||||
|
||||
### **2. 异常情况测试**
|
||||
- 网络异常测试:在网络不稳定环境下测试
|
||||
- 存储异常测试:模拟存储读取失败的情况
|
||||
- 内存压力测试:在低内存环境下测试
|
||||
|
||||
### **3. 边界情况测试**
|
||||
- 快速重启测试:连续快速重启应用
|
||||
- 后台恢复测试:应用从后台恢复时的状态检查
|
||||
|
||||
## 📝 监控要点
|
||||
|
||||
### **1. 关键日志**
|
||||
- `HomeController` 的登录状态初始化日志
|
||||
- `AppRunData` 的用户信息初始化日志
|
||||
- `SplashController` 的启动完成日志
|
||||
|
||||
### **2. 状态检查**
|
||||
- 登录状态与UI状态的一致性
|
||||
- 订阅服务初始化的成功率
|
||||
- 应用启动的成功率
|
||||
|
||||
## 🔄 后续优化建议
|
||||
|
||||
### **1. 短期优化**
|
||||
- 监控修复效果,收集用户反馈
|
||||
- 根据实际使用情况调整延迟时间
|
||||
- 优化错误处理逻辑
|
||||
|
||||
### **2. 长期优化**
|
||||
- 考虑使用状态管理框架(如Riverpod)统一管理状态
|
||||
- 实现更完善的状态持久化机制
|
||||
- 添加应用健康检查机制
|
||||
|
||||
## ✅ 修复完成
|
||||
|
||||
所有修复已完成,包括:
|
||||
- ✅ KRHomeController 登录状态初始化逻辑修复
|
||||
- ✅ 状态验证和错误处理添加
|
||||
- ✅ 状态同步检查机制添加
|
||||
- ✅ KRAppRunData 初始化逻辑优化
|
||||
- ✅ 启动页面保护机制添加
|
||||
|
||||
修复后的代码应该能显著减少 Android 应用启动时登录框不显示的问题。
|
||||
@ -1,241 +0,0 @@
|
||||
# Android 应用启动时登录框不显示问题分析
|
||||
|
||||
## 🔍 问题描述
|
||||
|
||||
**现象**:Android 应用退出重新打开后,有时会出现无法加载所有功能的情况,具体表现为进入首页后没有显示下面的登录框,需要退出重进多次才能恢复正常。
|
||||
|
||||
## 📋 代码逻辑分析
|
||||
|
||||
### **1. 应用启动流程**
|
||||
|
||||
```dart
|
||||
// main.dart -> splash -> main
|
||||
main() -> KRAppRunData().kr_initializeUserInfo() -> Get.offAllNamed(Routes.KR_MAIN)
|
||||
```
|
||||
|
||||
### **2. 登录状态初始化流程**
|
||||
|
||||
#### **A. 启动时初始化 (KRAppRunData.kr_initializeUserInfo)**
|
||||
```dart
|
||||
Future<void> kr_initializeUserInfo() async {
|
||||
final String? userInfoString = await KRSecureStorage().kr_readData(key: _keyUserInfo);
|
||||
|
||||
if (userInfoString != null) {
|
||||
// 解析用户信息
|
||||
kr_token = userInfo['token'];
|
||||
kr_account = userInfo['account'];
|
||||
// ...
|
||||
|
||||
kr_isLogin.value = kr_token != null; // ⚠️ 关键:设置登录状态
|
||||
if (kr_isLogin.value) {
|
||||
await _iniUserInfo(); // 异步获取用户信息
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### **B. 首页控制器初始化 (KRHomeController._kr_initLoginStatus)**
|
||||
```dart
|
||||
void _kr_initLoginStatus() {
|
||||
if (KRAppRunData().kr_isLogin.value) {
|
||||
kr_currentViewStatus.value = KRHomeViewsStatus.kr_loggedIn;
|
||||
kr_subscribeService.kr_refreshAll(); // ⚠️ 异步刷新订阅数据
|
||||
} else {
|
||||
kr_currentViewStatus.value = KRHomeViewsStatus.kr_notLoggedIn;
|
||||
}
|
||||
|
||||
ever(KRAppRunData().kr_isLogin, (isLoggedIn) {
|
||||
// 监听登录状态变化
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### **3. 登录框显示逻辑**
|
||||
|
||||
#### **A. 首页视图判断 (KRHomeView.build)**
|
||||
```dart
|
||||
Widget build(BuildContext context) {
|
||||
return Obx(() {
|
||||
if (controller.kr_currentViewStatus.value == KRHomeViewsStatus.kr_notLoggedIn) {
|
||||
return Scaffold(
|
||||
body: Stack(
|
||||
children: [
|
||||
const KRHomeMapView(),
|
||||
Positioned(
|
||||
bottom: 0,
|
||||
child: Container(
|
||||
child: const KRLoginView(), // ⚠️ 登录框在这里显示
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
// 已登录状态的其他UI...
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
#### **B. 底部面板判断 (KRHomeBottomPanel._kr_buildDefaultView)**
|
||||
```dart
|
||||
Widget _kr_buildDefaultView(BuildContext context) {
|
||||
final isNotLoggedIn = controller.kr_currentViewStatus.value == KRHomeViewsStatus.kr_notLoggedIn;
|
||||
|
||||
if (isNotLoggedIn) {
|
||||
return SingleChildScrollView(
|
||||
child: Column(
|
||||
children: [
|
||||
const KRHomeConnectionOptionsView(), // ⚠️ 登录选项在这里显示
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
// 已登录状态的其他内容...
|
||||
}
|
||||
```
|
||||
|
||||
## 🚨 问题根因分析
|
||||
|
||||
### **1. 竞态条件 (Race Condition)**
|
||||
|
||||
**问题**:`kr_initializeUserInfo()` 中的异步操作可能导致状态不一致
|
||||
|
||||
```dart
|
||||
// 问题代码
|
||||
kr_isLogin.value = kr_token != null; // 立即设置状态
|
||||
if (kr_isLogin.value) {
|
||||
await _iniUserInfo(); // 异步操作,可能失败
|
||||
}
|
||||
```
|
||||
|
||||
**风险**:
|
||||
- 如果 `_iniUserInfo()` 失败,登录状态可能不正确
|
||||
- 网络请求超时或失败时,状态可能不一致
|
||||
|
||||
### **2. 异步初始化时序问题**
|
||||
|
||||
**问题**:多个异步操作没有正确的依赖关系
|
||||
|
||||
```dart
|
||||
// 启动流程
|
||||
await KRAppRunData.getInstance().kr_initializeUserInfo(); // 异步1
|
||||
Get.offAllNamed(Routes.KR_MAIN); // 立即跳转
|
||||
|
||||
// 首页初始化
|
||||
_kr_initLoginStatus(); // 可能此时 kr_isLogin 还未正确设置
|
||||
```
|
||||
|
||||
### **3. 状态监听器初始化时机**
|
||||
|
||||
**问题**:`ever()` 监听器可能在状态变化后才注册
|
||||
|
||||
```dart
|
||||
// 可能的问题
|
||||
kr_isLogin.value = true; // 状态已变化
|
||||
ever(KRAppRunData().kr_isLogin, (isLoggedIn) { // 监听器注册太晚
|
||||
// 这个回调可能不会立即触发
|
||||
});
|
||||
```
|
||||
|
||||
### **4. 订阅服务初始化失败**
|
||||
|
||||
**问题**:`kr_subscribeService.kr_refreshAll()` 可能失败
|
||||
|
||||
```dart
|
||||
if (KRAppRunData().kr_isLogin.value) {
|
||||
kr_currentViewStatus.value = KRHomeViewsStatus.kr_loggedIn;
|
||||
kr_subscribeService.kr_refreshAll(); // 如果这个失败,UI状态可能不正确
|
||||
}
|
||||
```
|
||||
|
||||
## 🔧 潜在修复方案
|
||||
|
||||
### **1. 添加状态初始化延迟**
|
||||
|
||||
```dart
|
||||
void _kr_initLoginStatus() {
|
||||
// 延迟初始化,确保所有异步操作完成
|
||||
Future.delayed(const Duration(milliseconds: 100), () {
|
||||
if (KRAppRunData().kr_isLogin.value) {
|
||||
kr_currentViewStatus.value = KRHomeViewsStatus.kr_loggedIn;
|
||||
} else {
|
||||
kr_currentViewStatus.value = KRHomeViewsStatus.kr_notLoggedIn;
|
||||
}
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### **2. 添加状态验证**
|
||||
|
||||
```dart
|
||||
void _kr_initLoginStatus() {
|
||||
// 验证登录状态的有效性
|
||||
final isValidLogin = KRAppRunData().kr_token != null &&
|
||||
KRAppRunData().kr_isLogin.value;
|
||||
|
||||
if (isValidLogin) {
|
||||
kr_currentViewStatus.value = KRHomeViewsStatus.kr_loggedIn;
|
||||
} else {
|
||||
kr_currentViewStatus.value = KRHomeViewsStatus.kr_notLoggedIn;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### **3. 添加错误处理和重试机制**
|
||||
|
||||
```dart
|
||||
void _kr_initLoginStatus() {
|
||||
try {
|
||||
if (KRAppRunData().kr_isLogin.value) {
|
||||
kr_currentViewStatus.value = KRHomeViewsStatus.kr_loggedIn;
|
||||
// 添加错误处理
|
||||
kr_subscribeService.kr_refreshAll().catchError((error) {
|
||||
KRLogUtil.kr_e('订阅服务初始化失败: $error', tag: 'HomeController');
|
||||
// 重试或降级处理
|
||||
});
|
||||
} else {
|
||||
kr_currentViewStatus.value = KRHomeViewsStatus.kr_notLoggedIn;
|
||||
}
|
||||
} catch (e) {
|
||||
KRLogUtil.kr_e('登录状态初始化失败: $e', tag: 'HomeController');
|
||||
kr_currentViewStatus.value = KRHomeViewsStatus.kr_notLoggedIn;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### **4. 添加状态同步检查**
|
||||
|
||||
```dart
|
||||
void _kr_initLoginStatus() {
|
||||
// 强制同步状态
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
final currentLoginStatus = KRAppRunData().kr_isLogin.value;
|
||||
if (kr_currentViewStatus.value == KRHomeViewsStatus.kr_loggedIn && !currentLoginStatus) {
|
||||
kr_currentViewStatus.value = KRHomeViewsStatus.kr_notLoggedIn;
|
||||
} else if (kr_currentViewStatus.value == KRHomeViewsStatus.kr_notLoggedIn && currentLoginStatus) {
|
||||
kr_currentViewStatus.value = KRHomeViewsStatus.kr_loggedIn;
|
||||
}
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
## 📊 问题影响
|
||||
|
||||
1. **用户体验差**:需要多次重启应用才能正常使用
|
||||
2. **功能不可用**:登录框不显示导致无法登录
|
||||
3. **状态不一致**:UI状态与实际登录状态不匹配
|
||||
|
||||
## 🎯 建议修复优先级
|
||||
|
||||
1. **高优先级**:添加状态初始化延迟和验证
|
||||
2. **中优先级**:添加错误处理和重试机制
|
||||
3. **低优先级**:优化异步操作时序
|
||||
|
||||
## 📝 测试建议
|
||||
|
||||
1. **多次重启测试**:连续重启应用 10-20 次,观察登录框显示情况
|
||||
2. **网络异常测试**:在网络不稳定环境下测试
|
||||
3. **存储异常测试**:模拟存储读取失败的情况
|
||||
4. **内存压力测试**:在低内存环境下测试
|
||||
|
||||
这个分析为后续的修复提供了明确的方向和具体的实现建议。
|
||||
@ -1,87 +0,0 @@
|
||||
# BearVPN 连接调试总结
|
||||
|
||||
## 🔍 问题分析
|
||||
|
||||
通过日志分析,发现了节点连接超时的根本原因:
|
||||
|
||||
### 核心问题
|
||||
1. **SingBox URL 测试配置问题**:
|
||||
- 测试间隔过长:`url-test-interval: 300` (5分钟)
|
||||
- 测试 URL 可能不稳定:`http://cp.cloudflare.com`
|
||||
|
||||
2. **节点延迟值异常**:
|
||||
- 初始状态:`delay=0` (未测试)
|
||||
- 测试后:`delay=65535` (超时/失败)
|
||||
- 反复在 0 和 65535 之间切换
|
||||
|
||||
## 🛠️ 解决方案
|
||||
|
||||
### 1. 修复 SingBox 配置
|
||||
```dart
|
||||
// 修改前
|
||||
"connection-test-url": "http://cp.cloudflare.com",
|
||||
"url-test-interval": 300,
|
||||
|
||||
// 修改后
|
||||
"connection-test-url": "http://www.gstatic.com/generate_204",
|
||||
"url-test-interval": 30,
|
||||
```
|
||||
|
||||
### 2. 添加详细调试信息
|
||||
- ✅ SingBox 启动过程调试
|
||||
- ✅ 配置文件保存调试
|
||||
- ✅ 节点选择过程调试
|
||||
- ✅ URL 测试过程调试
|
||||
- ✅ 活动组状态监控
|
||||
|
||||
### 3. 优化节点延迟测试
|
||||
- ✅ 增加详细的连接测试日志
|
||||
- ✅ 改进错误处理和重试机制
|
||||
- ✅ 添加测试前后状态对比
|
||||
|
||||
## 📊 测试结果
|
||||
|
||||
### URL 连通性测试
|
||||
- ✅ `http://www.gstatic.com/generate_204` - 连接正常
|
||||
- ✅ `http://cp.cloudflare.com` - 连接正常
|
||||
- ❌ `http://www.cloudflare.com` - 连接失败
|
||||
|
||||
### 预期效果
|
||||
1. **更快的节点测试**:从 5 分钟间隔改为 30 秒
|
||||
2. **更稳定的测试 URL**:使用 Google 的连通性测试服务
|
||||
3. **更详细的调试信息**:便于问题定位和解决
|
||||
|
||||
## 🚀 下一步
|
||||
|
||||
1. **重新运行应用**:测试修复后的效果
|
||||
2. **观察日志**:查看新的调试信息
|
||||
3. **验证节点延迟**:确认延迟值是否正常更新
|
||||
4. **测试连接稳定性**:验证连接是否稳定
|
||||
|
||||
## 📝 调试命令
|
||||
|
||||
```bash
|
||||
# 运行应用并查看日志
|
||||
flutter run -d macos --debug
|
||||
|
||||
# 测试 URL 连通性
|
||||
./test_url_connectivity.sh
|
||||
|
||||
# 基础连接测试
|
||||
./test_connection.sh
|
||||
```
|
||||
|
||||
## 🔧 关键文件修改
|
||||
|
||||
1. `lib/app/services/singbox_imp/kr_sing_box_imp.dart`
|
||||
- 修复 URL 测试配置
|
||||
- 添加详细调试信息
|
||||
- 优化错误处理
|
||||
|
||||
2. `lib/app/modules/kr_home/controllers/kr_home_controller.dart`
|
||||
- 增强节点延迟测试日志
|
||||
- 改进错误处理机制
|
||||
|
||||
3. 新增调试脚本
|
||||
- `test_connection.sh` - 基础连接测试
|
||||
- `test_url_connectivity.sh` - URL 连通性测试
|
||||
@ -1,202 +0,0 @@
|
||||
# 连接信息消失问题分析
|
||||
|
||||
## 🔍 问题描述
|
||||
|
||||
用户反馈:在什么情况下,把app关掉后重新打开,下面的"当前连接"和"连接方式"都不显示了。
|
||||
|
||||
## 📋 显示逻辑分析
|
||||
|
||||
### **1. 当前连接显示条件**
|
||||
|
||||
#### **显示位置**: `kr_home_bottom_panel.dart` 第94-97行
|
||||
```dart
|
||||
// 1. 如果已订阅,展示当前连接卡片
|
||||
if (hasValidSubscription)
|
||||
Container(
|
||||
margin: EdgeInsets.only(top: 12.h),
|
||||
child: const KRHomeConnectionInfoView())
|
||||
```
|
||||
|
||||
#### **显示条件**: `hasValidSubscription`
|
||||
```dart
|
||||
final hasValidSubscription =
|
||||
controller.kr_subscribeService.kr_currentSubscribe.value != null;
|
||||
```
|
||||
|
||||
### **2. 连接方式显示条件**
|
||||
|
||||
#### **显示位置**: `kr_home_bottom_panel.dart` 第118-123行
|
||||
```dart
|
||||
// 4. 连接选项(分组和国家入口)
|
||||
Padding(
|
||||
padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.w),
|
||||
child: const KRHomeConnectionOptionsView(),
|
||||
),
|
||||
```
|
||||
|
||||
#### **显示条件**: 始终显示(在已登录状态下)
|
||||
|
||||
### **3. 登录状态判断**
|
||||
|
||||
#### **显示逻辑**: `kr_home_bottom_panel.dart` 第72-85行
|
||||
```dart
|
||||
if (isNotLoggedIn)
|
||||
// 未登录状态下,只显示连接选项
|
||||
SingleChildScrollView(
|
||||
child: Column(
|
||||
children: [
|
||||
Padding(
|
||||
padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.w),
|
||||
child: const KRHomeConnectionOptionsView(),
|
||||
),
|
||||
],
|
||||
),
|
||||
)
|
||||
else
|
||||
// 已登录状态下,显示完整内容
|
||||
Expanded(
|
||||
child: SingleChildScrollView(
|
||||
child: Column(
|
||||
children: [
|
||||
// 当前连接卡片(需要hasValidSubscription)
|
||||
// 连接选项
|
||||
],
|
||||
),
|
||||
),
|
||||
)
|
||||
```
|
||||
|
||||
## 🎯 问题根源分析
|
||||
|
||||
### **核心问题**: `kr_currentSubscribe.value` 为 `null`
|
||||
|
||||
当 `kr_currentSubscribe.value` 为 `null` 时:
|
||||
1. **当前连接卡片不显示**: `hasValidSubscription = false`
|
||||
2. **连接方式可能不显示**: 取决于登录状态
|
||||
|
||||
### **可能导致 `kr_currentSubscribe.value` 为 `null` 的情况**:
|
||||
|
||||
#### **1. 订阅服务初始化失败**
|
||||
- **网络问题**: API请求失败
|
||||
- **服务器问题**: 后端服务异常
|
||||
- **超时问题**: 请求超时
|
||||
|
||||
#### **2. 订阅数据获取失败**
|
||||
- **API返回空列表**: `subscribes.isEmpty`
|
||||
- **订阅过期**: 所有订阅都已过期
|
||||
- **权限问题**: 用户没有可用订阅
|
||||
|
||||
#### **3. 应用启动时序问题**
|
||||
- **竞态条件**: 订阅服务初始化晚于UI渲染
|
||||
- **状态同步问题**: 登录状态和订阅状态不同步
|
||||
- **缓存问题**: 本地缓存数据损坏
|
||||
|
||||
#### **4. 登录状态问题**
|
||||
- **Token失效**: 用户token过期或无效
|
||||
- **登录状态丢失**: `kr_isLogin.value = false`
|
||||
- **用户信息加载失败**: 用户信息初始化失败
|
||||
|
||||
## 🔧 具体场景分析
|
||||
|
||||
### **场景1: 网络问题**
|
||||
```
|
||||
启动应用 → 登录成功 → 订阅服务初始化 → 网络请求失败 → kr_currentSubscribe.value = null → 当前连接不显示
|
||||
```
|
||||
|
||||
### **场景2: 订阅过期**
|
||||
```
|
||||
启动应用 → 登录成功 → 订阅服务初始化 → 获取订阅列表 → 所有订阅已过期 → kr_currentSubscribe.value = null → 当前连接不显示
|
||||
```
|
||||
|
||||
### **场景3: 竞态条件**
|
||||
```
|
||||
启动应用 → UI渲染 → 订阅服务还在初始化中 → kr_currentSubscribe.value = null → 当前连接不显示
|
||||
```
|
||||
|
||||
### **场景4: 登录状态问题**
|
||||
```
|
||||
启动应用 → 登录状态判断错误 → 显示未登录界面 → 连接方式显示但当前连接不显示
|
||||
```
|
||||
|
||||
## 📊 调试方法
|
||||
|
||||
### **1. 检查关键状态**
|
||||
```dart
|
||||
// 在 kr_home_bottom_panel.dart 中添加日志
|
||||
KRLogUtil.kr_i('当前登录状态: ${controller.kr_currentViewStatus.value}', tag: 'HomeBottomPanel');
|
||||
KRLogUtil.kr_i('当前订阅: ${controller.kr_subscribeService.kr_currentSubscribe.value}', tag: 'HomeBottomPanel');
|
||||
KRLogUtil.kr_i('订阅服务状态: ${controller.kr_subscribeService.kr_currentStatus.value}', tag: 'HomeBottomPanel');
|
||||
```
|
||||
|
||||
### **2. 检查订阅服务初始化**
|
||||
```dart
|
||||
// 在 kr_subscribe_service.dart 中添加日志
|
||||
KRLogUtil.kr_i('订阅服务初始化开始', tag: 'SubscribeService');
|
||||
KRLogUtil.kr_i('获取订阅列表结果: ${subscribes.length} 个订阅', tag: 'SubscribeService');
|
||||
KRLogUtil.kr_i('当前订阅设置: ${kr_currentSubscribe.value?.name}', tag: 'SubscribeService');
|
||||
```
|
||||
|
||||
### **3. 检查网络请求**
|
||||
```dart
|
||||
// 检查API请求是否成功
|
||||
KRLogUtil.kr_i('API请求状态: ${result.isLeft() ? "失败" : "成功"}', tag: 'SubscribeService');
|
||||
```
|
||||
|
||||
## 🛠️ 修复建议
|
||||
|
||||
### **1. 增强错误处理**
|
||||
```dart
|
||||
// 在订阅服务初始化失败时,显示错误信息而不是空白
|
||||
if (kr_currentStatus.value == KRSubscribeServiceStatus.kr_error) {
|
||||
return _kr_buildErrorView(context);
|
||||
}
|
||||
```
|
||||
|
||||
### **2. 添加重试机制**
|
||||
```dart
|
||||
// 订阅服务初始化失败时自动重试
|
||||
if (kr_currentSubscribe.value == null && kr_currentStatus.value == KRSubscribeServiceStatus.kr_error) {
|
||||
// 延迟重试
|
||||
Future.delayed(Duration(seconds: 3), () {
|
||||
kr_refreshAll();
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### **3. 改善用户体验**
|
||||
```dart
|
||||
// 显示加载状态而不是空白
|
||||
if (kr_currentSubscribe.value == null && kr_currentStatus.value == KRSubscribeServiceStatus.kr_loading) {
|
||||
return _kr_buildLoadingView();
|
||||
}
|
||||
```
|
||||
|
||||
### **4. 添加状态检查**
|
||||
```dart
|
||||
// 定期检查订阅状态
|
||||
Timer.periodic(Duration(seconds: 30), (timer) {
|
||||
if (kr_currentSubscribe.value == null && kr_isLogin.value) {
|
||||
kr_refreshAll();
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
## 📝 总结
|
||||
|
||||
**问题根源**: `kr_currentSubscribe.value` 为 `null`,导致 `hasValidSubscription = false`
|
||||
|
||||
**主要原因**:
|
||||
1. 订阅服务初始化失败
|
||||
2. 网络请求失败
|
||||
3. 订阅数据获取失败
|
||||
4. 应用启动时序问题
|
||||
5. 登录状态问题
|
||||
|
||||
**解决方案**:
|
||||
1. 增强错误处理和重试机制
|
||||
2. 改善用户体验(显示加载状态)
|
||||
3. 添加状态检查和自动恢复
|
||||
4. 完善日志记录便于调试
|
||||
|
||||
**建议**: 先添加详细的日志记录,确定具体是哪种情况导致的问题,然后针对性地修复。
|
||||
|
||||
@ -1,122 +0,0 @@
|
||||
# Connection Refused 问题分析和修复
|
||||
|
||||
## 🔍 问题现象
|
||||
|
||||
从日志中可以看到所有节点都出现 "Connection refused" 错误:
|
||||
|
||||
```
|
||||
❌ 本机网络测试节点 德国 失败: SocketException: Connection refused (OS Error: Connection refused, errno = 111), address = 156.226.175.116, port = 51036
|
||||
❌ 本机网络测试节点 美国 失败: SocketException: Connection refused (OS Error: Connection refused, errno = 111), address = 154.29.154.241, port = 59118
|
||||
❌ 本机网络测试节点 英国 失败: SocketException: Connection refused (OS Error: Connection refused, errno = 111), address = 89.213.40.159, port = 45268
|
||||
❌ 本机网络测试节点 台湾 失败: SocketException: Connection refused (OS Error: Connection refused, errno = 111), address = 83.147.12.27, port = 49826
|
||||
❌ 本机网络测试节点 香港 失败: SocketException: Connection refused (OS Error: Connection refused, errno = 111), address = 156.224.78.176, port = 44782
|
||||
```
|
||||
|
||||
## 🎯 问题分析
|
||||
|
||||
### **1. 地址解析问题**
|
||||
|
||||
#### **问题现象**:
|
||||
- 所有节点的端口都是随机的大数字(如 51036, 59118, 45268 等)
|
||||
- 这些端口看起来不像是正常的代理服务端口
|
||||
|
||||
#### **根本原因**:
|
||||
- 原来的代码使用 `Uri.parse(item.serverAddr)` 来解析地址和端口
|
||||
- 但是 `serverAddr` 可能不包含端口信息,或者解析逻辑有问题
|
||||
- 端口应该从节点的配置中获取,而不是从 `serverAddr` 中解析
|
||||
|
||||
### **2. 配置获取问题**
|
||||
|
||||
#### **问题现象**:
|
||||
- 没有从节点的配置中获取正确的端口号
|
||||
- 使用了错误的默认端口或解析出的错误端口
|
||||
|
||||
#### **根本原因**:
|
||||
- 节点的端口信息存储在 `item.config['server_port']` 中
|
||||
- 原来的代码没有正确获取这个配置
|
||||
|
||||
## 🔧 修复方案
|
||||
|
||||
### **修复内容**:
|
||||
|
||||
1. **改进地址解析逻辑**:
|
||||
```dart
|
||||
// 从配置中获取正确的地址和端口
|
||||
String address = item.serverAddr;
|
||||
int port = 443; // 默认端口
|
||||
|
||||
// 如果serverAddr包含端口,先解析
|
||||
if (item.serverAddr.contains(':')) {
|
||||
final parts = item.serverAddr.split(':');
|
||||
if (parts.length == 2) {
|
||||
address = parts[0];
|
||||
port = int.tryParse(parts[1]) ?? 443;
|
||||
}
|
||||
}
|
||||
|
||||
// 从配置中获取端口(优先级更高)
|
||||
if (item.config != null && item.config['server_port'] != null) {
|
||||
port = item.config['server_port'];
|
||||
KRLogUtil.kr_i('📌 从配置获取端口: $port', tag: 'NodeTest');
|
||||
}
|
||||
```
|
||||
|
||||
2. **增加详细日志**:
|
||||
```dart
|
||||
KRLogUtil.kr_i('📋 节点配置: ${item.config}', tag: 'NodeTest');
|
||||
KRLogUtil.kr_i('📍 最终地址: $address, 端口: $port', tag: 'NodeTest');
|
||||
```
|
||||
|
||||
### **修复逻辑**:
|
||||
|
||||
1. **地址处理**:
|
||||
- 首先使用 `item.serverAddr` 作为地址
|
||||
- 如果包含端口,则分离地址和端口
|
||||
- 否则使用默认端口 443
|
||||
|
||||
2. **端口获取**:
|
||||
- 优先从 `item.config['server_port']` 获取端口
|
||||
- 如果配置中没有端口,使用解析出的端口或默认端口
|
||||
|
||||
3. **日志记录**:
|
||||
- 记录节点配置信息
|
||||
- 记录最终使用的地址和端口
|
||||
- 便于调试和问题排查
|
||||
|
||||
## 📊 预期效果
|
||||
|
||||
### **修复前**:
|
||||
- 使用错误的端口(如 51036, 59118 等)
|
||||
- 所有节点连接被拒绝
|
||||
- 无法获取真实的延迟信息
|
||||
|
||||
### **修复后**:
|
||||
- 使用正确的端口(从配置中获取)
|
||||
- 能够成功连接到节点
|
||||
- 获取真实的网络延迟
|
||||
|
||||
## 🔍 验证方法
|
||||
|
||||
### **1. 检查日志**:
|
||||
- 查看 `📋 节点配置:` 日志,确认配置信息
|
||||
- 查看 `📌 从配置获取端口:` 日志,确认端口获取
|
||||
- 查看 `📍 最终地址:` 日志,确认最终使用的地址和端口
|
||||
|
||||
### **2. 测试连接**:
|
||||
- 确认不再出现 "Connection refused" 错误
|
||||
- 能够获取到合理的延迟值(通常 < 5000ms)
|
||||
- 部分节点可能仍然超时,但应该有一些节点能够连接成功
|
||||
|
||||
### **3. 端口验证**:
|
||||
- 确认使用的端口是合理的(如 443, 80, 8080 等)
|
||||
- 不再使用随机的大数字端口
|
||||
|
||||
## 📝 总结
|
||||
|
||||
**问题根源**: 地址和端口解析逻辑错误,没有从节点配置中获取正确的端口信息。
|
||||
|
||||
**修复方案**: 改进地址解析逻辑,优先从节点配置中获取端口,并增加详细的日志记录。
|
||||
|
||||
**预期结果**: 能够使用正确的地址和端口连接节点,获取真实的网络延迟信息。
|
||||
|
||||
现在可以重新测试,应该能够看到正确的端口和成功的连接!
|
||||
@ -1,184 +0,0 @@
|
||||
# Crisp Chat 功能修复总结(支持多平台)
|
||||
|
||||
## 问题描述
|
||||
Crisp 客服聊天功能无法使用,原因是:
|
||||
1. `crisp_sdk` 包被注释掉(依赖 `flutter_inappwebview` 有问题)
|
||||
2. 所有 Crisp 相关代码被注释
|
||||
3. 用户界面显示"客服功能暂时不可用"
|
||||
4. `crisp_chat` 包只支持 iOS/Android,不支持桌面平台
|
||||
|
||||
## 解决方案
|
||||
|
||||
### 1. 依赖更新
|
||||
**文件**: `pubspec.yaml`
|
||||
|
||||
- 移除了有问题的 `crisp_sdk` 包
|
||||
- 添加了 `crisp_chat: ^2.4.1`(使用原生实现,不依赖 `flutter_inappwebview`)
|
||||
|
||||
```yaml
|
||||
crisp_chat: ^2.4.1 # 使用原生实现的 crisp_chat,不依赖 flutter_inappwebview
|
||||
```
|
||||
|
||||
### 2. 控制器重写(支持多平台)
|
||||
**文件**: `lib/app/modules/kr_crisp_chat/controllers/kr_crisp_controller.dart`
|
||||
|
||||
- 完全重写了控制器以支持多平台
|
||||
- **移动平台(iOS/Android)**:
|
||||
- 使用 `crisp_chat` 包的原生 API
|
||||
- 使用 `CrispConfig` 配置 Crisp
|
||||
- 使用 `FlutterCrispChat.openCrispChat()` 打开聊天窗口
|
||||
- 使用 `FlutterCrispChat.setSessionString()` 设置会话数据
|
||||
- **桌面平台(macOS/Windows/Linux)**:
|
||||
- 使用 WebView 加载 Crisp 官方嵌入脚本
|
||||
- 动态生成包含 Crisp SDK 的 HTML 页面
|
||||
- 通过 JavaScript 设置用户信息和会话数据
|
||||
- 自动打开聊天窗口
|
||||
|
||||
**主要改进**:
|
||||
- ✅ 支持所有平台(iOS、Android、macOS、Windows、Linux)
|
||||
- ✅ 自动检测平台并选择合适的实现方式
|
||||
- ✅ 支持用户邮箱和昵称设置
|
||||
- ✅ 自动收集平台信息
|
||||
- ✅ 设置语言、应用版本、设备 ID 等会话数据
|
||||
|
||||
### 3. 视图重写(多平台支持)
|
||||
**文件**: `lib/app/modules/kr_crisp_chat/views/kr_crisp_view.dart`
|
||||
|
||||
- 移除了占位视图
|
||||
- **移动平台**: 初始化成功后自动打开 Crisp 原生聊天窗口,窗口关闭后返回
|
||||
- **桌面平台**: 使用 `webview_flutter` 在应用内显示 Crisp 聊天界面
|
||||
- 添加了错误处理和重试功能
|
||||
- 使用 `PopScope` 替代已弃用的 `WillPopScope`
|
||||
- 移除了 `setBackgroundColor` 调用(macOS 不支持)
|
||||
|
||||
### 4. iOS 配置更新
|
||||
**文件**: `ios/Runner/Info.plist`
|
||||
|
||||
添加了 Crisp 所需的权限:
|
||||
```xml
|
||||
<key>NSCameraUsageDescription</key>
|
||||
<string>需要相机权限以支持拍照功能</string>
|
||||
<key>NSMicrophoneUsageDescription</key>
|
||||
<string>需要麦克风权限以支持语音消息功能</string>
|
||||
<key>NSPhotoLibraryUsageDescription</key>
|
||||
<string>需要相册权限以支持图片上传功能</string>
|
||||
<key>NSPhotoLibraryAddUsageDescription</key>
|
||||
<string>需要相册添加权限以保存图片</string>
|
||||
```
|
||||
|
||||
### 5. Android 配置
|
||||
**文件**: `android/app/build.gradle`
|
||||
|
||||
- ✅ `compileSdk 36` - 已满足要求(需要 35 或更高)
|
||||
- ✅ 网络权限已在 `AndroidManifest.xml` 中配置
|
||||
|
||||
## 技术细节
|
||||
|
||||
### crisp_chat vs crisp_sdk
|
||||
| 特性 | crisp_chat | crisp_sdk |
|
||||
|------|-----------|-----------|
|
||||
| 实现方式 | 原生 SDK | WebView |
|
||||
| 依赖 | 无额外依赖 | 需要 flutter_inappwebview |
|
||||
| 性能 | 更好 | 较慢 |
|
||||
| 兼容性 | 更好 | 依赖问题 |
|
||||
| 最新版本 | 2.4.1 (2025) | 1.1.0 (2024) |
|
||||
|
||||
### API 使用示例
|
||||
|
||||
```dart
|
||||
// 创建配置
|
||||
final config = CrispConfig(
|
||||
websiteID: 'your-website-id',
|
||||
enableNotifications: true,
|
||||
user: User(
|
||||
email: 'user@example.com',
|
||||
nickName: 'User Name',
|
||||
),
|
||||
);
|
||||
|
||||
// 打开聊天窗口
|
||||
await FlutterCrispChat.openCrispChat(config: config);
|
||||
|
||||
// 设置会话数据
|
||||
FlutterCrispChat.setSessionString(key: 'platform', value: 'android');
|
||||
|
||||
// 重置会话
|
||||
await FlutterCrispChat.resetCrispChatSession();
|
||||
```
|
||||
|
||||
## 工作流程
|
||||
|
||||
1. 用户点击客服按钮
|
||||
2. 进入 `KRCrispView` 页面
|
||||
3. `KRCrispController` 初始化:
|
||||
- 获取用户信息(邮箱/设备ID)
|
||||
- 创建 `CrispConfig`
|
||||
- 设置会话数据
|
||||
4. 初始化完成后自动调用 `openCrispChat()`
|
||||
5. 显示原生 Crisp 聊天界面
|
||||
6. 用户关闭聊天后,自动返回上一页
|
||||
|
||||
## 测试建议
|
||||
|
||||
### 前置条件
|
||||
1. 确保 `AppConfig.kr_website_id` 配置了有效的 Crisp Website ID
|
||||
2. 在 Crisp 控制台配置网站设置
|
||||
|
||||
### 测试步骤
|
||||
1. **基础功能测试**
|
||||
- 打开应用
|
||||
- 进入"我的"页面
|
||||
- 点击"客服"按钮
|
||||
- 验证 Crisp 聊天窗口是否正确打开
|
||||
|
||||
2. **用户信息测试**
|
||||
- 登录用户状态下,验证用户邮箱是否正确传递
|
||||
- 未登录状态下,验证设备 ID 是否正确使用
|
||||
|
||||
3. **会话数据测试**
|
||||
- 在 Crisp 控制台查看会话数据
|
||||
- 验证平台、语言、设备 ID 等信息是否正确
|
||||
|
||||
4. **权限测试 (iOS)**
|
||||
- 测试相机权限提示
|
||||
- 测试麦克风权限提示
|
||||
- 测试相册权限提示
|
||||
|
||||
5. **跨平台测试**
|
||||
- Android 设备测试
|
||||
- iOS 设备测试
|
||||
- Windows/macOS 桌面测试(如果支持)
|
||||
|
||||
## 注意事项
|
||||
|
||||
1. **Website ID 配置**
|
||||
- 确保在 `AppConfig` 中配置了正确的 Crisp Website ID
|
||||
- 可以从 Crisp 控制台获取:Settings → Website Settings → Website ID
|
||||
|
||||
2. **推送通知**
|
||||
- 如需启用推送通知,需要额外配置 Firebase
|
||||
- 参考 `crisp_chat` 包文档进行配置
|
||||
|
||||
3. **语言支持**
|
||||
- Crisp 支持多语言
|
||||
- 当前实现会根据应用语言自动设置(zh、zh-tw、en 等)
|
||||
|
||||
4. **隐私合规**
|
||||
- 确保在隐私政策中说明使用 Crisp 客服系统
|
||||
- 告知用户会话数据的收集和使用
|
||||
|
||||
## 相关文件
|
||||
|
||||
- `pubspec.yaml` - 依赖配置
|
||||
- `lib/app/modules/kr_crisp_chat/controllers/kr_crisp_controller.dart` - 控制器
|
||||
- `lib/app/modules/kr_crisp_chat/views/kr_crisp_view.dart` - 视图
|
||||
- `lib/app/modules/kr_crisp_chat/bindings/kr_crisp_binding.dart` - 绑定
|
||||
- `ios/Runner/Info.plist` - iOS 权限配置
|
||||
- `android/app/build.gradle` - Android 编译配置
|
||||
|
||||
## 参考链接
|
||||
|
||||
- [crisp_chat 包文档](https://pub.dev/packages/crisp_chat)
|
||||
- [Crisp 官方文档](https://docs.crisp.chat/)
|
||||
- [Crisp iOS SDK](https://github.com/crisp-im/crisp-sdk-ios)
|
||||
- [Crisp Android SDK](https://github.com/crisp-im/crisp-sdk-android)
|
||||
@ -1,190 +0,0 @@
|
||||
# Crisp 多语言支持说明
|
||||
|
||||
## 🌍 自动语言适配
|
||||
|
||||
Crisp 客服聊天**会自动跟随应用的当前语言设置**显示对应的界面!
|
||||
|
||||
## 支持的语言
|
||||
|
||||
应用支持 7 种语言,Crisp 会自动切换到对应的界面语言:
|
||||
|
||||
| 应用语言 | Crisp 显示语言 | 语言代码 |
|
||||
|---------|--------------|---------|
|
||||
| 🇬🇧 English | English | `en` |
|
||||
| 🇨🇳 中文 | 简体中文 | `zh` |
|
||||
| 🇹🇼 繁體中文 | 繁体中文 | `zh-tw` |
|
||||
| 🇪🇸 Español | Español | `es` |
|
||||
| 🇯🇵 日本語 | 日本語 | `ja` |
|
||||
| 🇷🇺 Русский | Русский | `ru` |
|
||||
| 🇪🇪 Eesti | Eesti keel | `et` |
|
||||
|
||||
## 工作原理
|
||||
|
||||
### 1. 获取当前语言
|
||||
```dart
|
||||
final currentLanguage = KRLanguageUtils.getCurrentLanguageCode();
|
||||
```
|
||||
|
||||
### 2. 映射到 Crisp Locale
|
||||
```dart
|
||||
String _getLocaleForCrisp(String languageCode) {
|
||||
switch (languageCode) {
|
||||
case 'zh_CN':
|
||||
case 'zh':
|
||||
return 'zh'; // 简体中文
|
||||
case 'zh_TW':
|
||||
case 'zhHant':
|
||||
return 'zh-tw'; // 繁体中文
|
||||
case 'es':
|
||||
return 'es'; // 西班牙语
|
||||
case 'ja':
|
||||
return 'ja'; // 日语
|
||||
case 'ru':
|
||||
return 'ru'; // 俄语
|
||||
case 'et':
|
||||
return 'et'; // 爱沙尼亚语
|
||||
case 'en':
|
||||
default:
|
||||
return 'en'; // 英语(默认)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 3. 初始化 Crisp
|
||||
```dart
|
||||
crispController = CrispController(
|
||||
websiteId: AppConfig.getInstance().kr_website_id,
|
||||
locale: locale, // 自动设置的语言
|
||||
);
|
||||
```
|
||||
|
||||
## 用户体验
|
||||
|
||||
1. **打开应用** → 应用读取系统语言或用户设置的语言
|
||||
2. **进入"我的"页面**
|
||||
3. **点击"客服"按钮**
|
||||
4. **Crisp 自动以当前应用语言显示界面** ✨
|
||||
|
||||
### 示例流程
|
||||
|
||||
```
|
||||
用户系统语言: 简体中文
|
||||
↓
|
||||
应用启动,检测语言: zh_CN
|
||||
↓
|
||||
用户点击"客服"
|
||||
↓
|
||||
Crisp 初始化,locale: 'zh'
|
||||
↓
|
||||
显示简体中文界面 🇨🇳
|
||||
```
|
||||
|
||||
如果用户在应用内切换语言:
|
||||
```
|
||||
应用设置页面 → 切换语言到 "日本語"
|
||||
↓
|
||||
应用重新加载,语言: ja
|
||||
↓
|
||||
再次点击"客服"
|
||||
↓
|
||||
Crisp 显示日语界面 🇯🇵
|
||||
```
|
||||
|
||||
## 语言切换
|
||||
|
||||
用户可以在应用的"设置"页面切换语言:
|
||||
1. 进入"我的" → "语言切换"
|
||||
2. 选择想要的语言
|
||||
3. 应用界面立即切换
|
||||
4. **下次打开客服,Crisp 也会自动切换到新语言**
|
||||
|
||||
## 技术细节
|
||||
|
||||
### 代码位置
|
||||
- **控制器**: `lib/app/modules/kr_crisp_chat/controllers/kr_crisp_controller.dart`
|
||||
- **语言工具**: `lib/app/localization/kr_language_utils.dart`
|
||||
|
||||
### 关键方法
|
||||
```dart
|
||||
// 在控制器初始化时调用
|
||||
Future<void> kr_initializeCrisp() async {
|
||||
final currentLanguage = KRLanguageUtils.getCurrentLanguageCode();
|
||||
String locale = _getLocaleForCrisp(currentLanguage);
|
||||
|
||||
crispController = CrispController(
|
||||
websiteId: AppConfig.getInstance().kr_website_id,
|
||||
locale: locale,
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## 扩展支持
|
||||
|
||||
如果需要添加新语言支持:
|
||||
|
||||
1. **在应用中添加新语言**(`kr_language_utils.dart`)
|
||||
2. **在 Crisp 控制器中添加映射**(`_getLocaleForCrisp` 方法)
|
||||
3. **确保 Crisp 支持该语言**(查看 [Crisp 支持的语言列表](https://docs.crisp.chat/guides/chatbox/languages/))
|
||||
|
||||
### 添加新语言示例
|
||||
|
||||
假设要添加法语支持:
|
||||
|
||||
```dart
|
||||
// 1. 在 KRLanguage enum 中添加
|
||||
fr('🇫🇷', 'Français', 'fr')
|
||||
|
||||
// 2. 在 _getLocaleForCrisp 中添加映射
|
||||
case 'fr':
|
||||
return 'fr'; // 法语
|
||||
```
|
||||
|
||||
## 注意事项
|
||||
|
||||
1. **系统语言优先**: 应用会优先使用用户在应用内设置的语言,如果没有设置,则使用系统语言
|
||||
2. **默认语言**: 如果检测到不支持的语言,默认使用英语(`en`)
|
||||
3. **实时生效**: 语言切换后,下次打开 Crisp 客服即可看到新语言界面
|
||||
4. **无需重启**: 切换语言不需要重启应用
|
||||
|
||||
## 验证方法
|
||||
|
||||
### 测试步骤
|
||||
1. 打开应用
|
||||
2. 进入"我的" → "语言切换"
|
||||
3. 依次选择不同语言
|
||||
4. 每次选择后,点击"客服"按钮
|
||||
5. 验证 Crisp 界面语言是否正确切换
|
||||
|
||||
### 预期结果
|
||||
- ✅ 界面文字使用选定的语言
|
||||
- ✅ 输入框提示文字使用对应语言
|
||||
- ✅ 系统消息使用对应语言
|
||||
- ✅ 按钮文字使用对应语言
|
||||
|
||||
## 常见问题
|
||||
|
||||
### Q: 为什么我切换了语言,Crisp 还是英文?
|
||||
A: 请确保:
|
||||
1. 已关闭之前的 Crisp 窗口
|
||||
2. 重新点击"客服"按钮
|
||||
3. Crisp 会使用新的语言初始化
|
||||
|
||||
### Q: Crisp 支持哪些语言?
|
||||
A: Crisp 官方支持 30+ 种语言,包括所有主流语言。查看完整列表:https://docs.crisp.chat/guides/chatbox/languages/
|
||||
|
||||
### Q: 可以强制使用某个语言吗?
|
||||
A: 当前实现会自动跟随应用语言。如需强制使用某个语言,可以在初始化时硬编码 locale:
|
||||
```dart
|
||||
crispController = CrispController(
|
||||
websiteId: AppConfig.getInstance().kr_website_id,
|
||||
locale: 'zh', // 强制使用简体中文
|
||||
);
|
||||
```
|
||||
|
||||
## 总结
|
||||
|
||||
✅ **自动化**: Crisp 完全自动跟随应用语言
|
||||
✅ **全面支持**: 支持应用所有 7 种语言
|
||||
✅ **用户友好**: 无需用户手动设置
|
||||
✅ **实时切换**: 切换语言后立即生效
|
||||
✅ **可扩展**: 易于添加新语言支持
|
||||
@ -1,62 +0,0 @@
|
||||
# BearVPN macOS 安装指南
|
||||
|
||||
## 🚨 如果遇到"应用程序无法打开"的问题
|
||||
|
||||
### 问题原因
|
||||
macOS 的安全机制(Gatekeeper)可能会阻止未签名的应用运行。
|
||||
|
||||
### 解决方案
|
||||
|
||||
#### 方法 1:右键打开(推荐)
|
||||
1. 右键点击 `BearVPN.app`
|
||||
2. 选择"打开"
|
||||
3. 在弹出的对话框中点击"打开"
|
||||
|
||||
#### 方法 2:系统偏好设置
|
||||
1. 打开"系统偏好设置" > "安全性与隐私"
|
||||
2. 在"通用"标签页中,找到被阻止的应用
|
||||
3. 点击"仍要打开"
|
||||
|
||||
#### 方法 3:终端命令(高级用户)
|
||||
```bash
|
||||
# 移除隔离属性
|
||||
sudo xattr -rd com.apple.quarantine /Applications/BearVPN.app
|
||||
|
||||
# 或者完全禁用 Gatekeeper(不推荐)
|
||||
sudo spctl --master-disable
|
||||
```
|
||||
|
||||
### 验证应用完整性
|
||||
```bash
|
||||
# 检查签名状态
|
||||
codesign -dv --verbose=4 /Applications/BearVPN.app
|
||||
|
||||
# 验证签名
|
||||
codesign --verify --verbose /Applications/BearVPN.app
|
||||
```
|
||||
|
||||
## 📋 系统要求
|
||||
- macOS 10.15 或更高版本
|
||||
- 支持 Intel 和 Apple Silicon (M1/M2) 芯片
|
||||
- 至少 200MB 可用磁盘空间
|
||||
|
||||
## 🔧 故障排除
|
||||
|
||||
### 如果应用仍然无法打开
|
||||
1. 确保 macOS 版本符合要求
|
||||
2. 检查系统时间是否正确
|
||||
3. 尝试重新下载应用
|
||||
4. 联系技术支持
|
||||
|
||||
### 性能优化
|
||||
1. 将应用添加到"登录项"以自动启动
|
||||
2. 在"系统偏好设置"中允许应用访问网络
|
||||
3. 确保防火墙没有阻止应用
|
||||
|
||||
## 📞 技术支持
|
||||
如果遇到问题,请联系:
|
||||
- 邮箱:support@bearvpn.com
|
||||
- 网站:https://bearvpn.com
|
||||
|
||||
---
|
||||
**注意**:本应用已通过 Apple 开发者证书签名,确保安全性和完整性。
|
||||
@ -1,183 +0,0 @@
|
||||
# iOS 自动化构建指南
|
||||
|
||||
本指南将帮助您使用自动化脚本构建和签名 iOS 应用,并创建 DMG 安装包。
|
||||
|
||||
## 🎯 目标
|
||||
|
||||
创建经过签名的 iOS 应用 DMG 文件,用于分发和安装。
|
||||
|
||||
## 📋 前提条件
|
||||
|
||||
### 1. Apple Developer 账户
|
||||
- 需要有效的 Apple Developer 账户
|
||||
- 需要 **iOS Development** 证书
|
||||
- 需要 **Provisioning Profile**
|
||||
|
||||
### 2. 获取证书和配置文件
|
||||
1. 登录 [Apple Developer Portal](https://developer.apple.com)
|
||||
2. 进入 "Certificates, Identifiers & Profiles"
|
||||
3. 创建以下证书:
|
||||
- **iOS Development** (用于应用签名)
|
||||
4. 创建 App ID 和 Provisioning Profile
|
||||
5. 下载并安装证书和配置文件
|
||||
|
||||
## 🚀 快速开始
|
||||
|
||||
### 步骤 1: 配置签名信息
|
||||
|
||||
```bash
|
||||
# 运行配置脚本
|
||||
./update_team_id.sh
|
||||
```
|
||||
|
||||
按照提示输入您的 Team ID,脚本会自动更新配置文件。
|
||||
|
||||
### 步骤 2: 加载配置
|
||||
|
||||
```bash
|
||||
# 加载签名配置
|
||||
source ios_signing_config.sh
|
||||
```
|
||||
|
||||
### 步骤 3: 构建 DMG
|
||||
|
||||
```bash
|
||||
# 构建发布版本
|
||||
./build_ios_dmg.sh
|
||||
|
||||
# 或构建调试版本
|
||||
./build_ios_dmg.sh debug
|
||||
```
|
||||
|
||||
## 📁 输出文件
|
||||
|
||||
构建完成后,文件将位于:
|
||||
```
|
||||
build/ios/
|
||||
├── BearVPN-1.0.0.ipa # 签名的 IPA 文件
|
||||
└── BearVPN-1.0.0-iOS.dmg # DMG 安装包
|
||||
```
|
||||
|
||||
## 🛠️ 可用的构建脚本
|
||||
|
||||
### 1. `build_ios_dmg.sh` - 主要构建脚本
|
||||
- 构建签名的 iOS 应用
|
||||
- 创建 DMG 安装包
|
||||
- 支持调试和发布版本
|
||||
|
||||
```bash
|
||||
./build_ios_dmg.sh [debug|release]
|
||||
```
|
||||
|
||||
### 2. `build_ios_simple.sh` - 简化构建脚本
|
||||
- 构建未签名的版本
|
||||
- 仅用于测试和开发
|
||||
|
||||
```bash
|
||||
./build_ios_simple.sh [debug|release]
|
||||
```
|
||||
|
||||
### 3. `build_ios_appstore.sh` - App Store 构建脚本
|
||||
- 构建用于 App Store 分发的版本
|
||||
- 支持自动上传到 App Store Connect
|
||||
|
||||
```bash
|
||||
./build_ios_appstore.sh [upload|build]
|
||||
```
|
||||
|
||||
## 🔧 配置文件
|
||||
|
||||
### `ios_signing_config.sh`
|
||||
包含所有签名配置信息:
|
||||
|
||||
```bash
|
||||
# Apple Developer 账户信息
|
||||
export APPLE_ID="your-apple-id@example.com"
|
||||
export APPLE_PASSWORD="your-app-password"
|
||||
export TEAM_ID="YOUR_TEAM_ID"
|
||||
|
||||
# 应用信息
|
||||
export APP_NAME="BearVPN"
|
||||
export BUNDLE_ID="com.bearvpn.app"
|
||||
export VERSION="1.0.0"
|
||||
export BUILD_NUMBER="1"
|
||||
|
||||
# 签名身份
|
||||
export SIGNING_IDENTITY="iPhone Developer: Your Name (YOUR_TEAM_ID)"
|
||||
export DISTRIBUTION_IDENTITY="iPhone Distribution: Your Name (YOUR_TEAM_ID)"
|
||||
```
|
||||
|
||||
## 🔍 验证构建结果
|
||||
|
||||
构建完成后,您可以验证结果:
|
||||
|
||||
```bash
|
||||
# 验证 IPA 文件
|
||||
unzip -l build/ios/BearVPN-1.0.0.ipa
|
||||
|
||||
# 验证 DMG 文件
|
||||
hdiutil verify build/ios/BearVPN-1.0.0-iOS.dmg
|
||||
|
||||
# 查看 DMG 内容
|
||||
hdiutil mount build/ios/BearVPN-1.0.0-iOS.dmg
|
||||
```
|
||||
|
||||
## 🛠️ 故障排除
|
||||
|
||||
### 1. 证书问题
|
||||
```bash
|
||||
# 查看可用证书
|
||||
security find-identity -v -p codesigning
|
||||
|
||||
# 如果看到 "0 valid identities found",说明没有安装证书
|
||||
```
|
||||
|
||||
### 2. 配置文件问题
|
||||
- 确保 Provisioning Profile 已正确安装
|
||||
- 检查 Bundle ID 是否匹配
|
||||
- 确保证书和配置文件匹配
|
||||
|
||||
### 3. 构建失败
|
||||
- 检查 Xcode 是否正确安装
|
||||
- 确保 Flutter 环境正确配置
|
||||
- 查看构建日志中的具体错误信息
|
||||
|
||||
### 4. 签名失败
|
||||
- 确保证书已正确安装
|
||||
- 检查签名身份名称是否正确
|
||||
- 确保证书未过期
|
||||
|
||||
## 📚 相关文档
|
||||
|
||||
- [Apple 代码签名指南](https://developer.apple.com/documentation/security/notarizing_macos_software_before_distribution)
|
||||
- [Flutter iOS 部署指南](https://docs.flutter.dev/deployment/ios)
|
||||
- [Xcode 构建指南](https://developer.apple.com/documentation/xcode)
|
||||
|
||||
## ⚠️ 重要提醒
|
||||
|
||||
1. **安全性**:请妥善保管您的开发者证书和密码
|
||||
2. **测试**:在分发前,请在真实的 iOS 设备上测试
|
||||
3. **更新**:定期更新证书,避免过期
|
||||
4. **备份**:建议备份您的签名配置
|
||||
|
||||
## 🎉 成功标志
|
||||
|
||||
如果构建成功,您应该看到:
|
||||
- ✅ 应用构建成功
|
||||
- ✅ 应用签名成功
|
||||
- ✅ IPA 文件创建成功
|
||||
- ✅ DMG 文件创建成功
|
||||
- ✅ 最终验证通过
|
||||
|
||||
## 📞 支持
|
||||
|
||||
如果遇到问题,请检查:
|
||||
1. 构建日志中的错误信息
|
||||
2. 证书和配置文件是否正确安装
|
||||
3. 网络连接是否正常
|
||||
4. Xcode 和 Flutter 版本是否兼容
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@ -1,176 +0,0 @@
|
||||
# 延迟测试逻辑确认
|
||||
|
||||
## 🎯 需求确认
|
||||
|
||||
**用户需求**:
|
||||
- **连接代理时**: 保持默认测试规则(使用 SingBox 通过代理测试)
|
||||
- **没连接时**: 使用本地网络的ping(直接连接节点IP)
|
||||
|
||||
## 📋 当前实现逻辑
|
||||
|
||||
### **1. 连接状态判断**
|
||||
|
||||
#### **连接状态变量**: `kr_isConnected`
|
||||
```dart
|
||||
// 是否已连接
|
||||
final kr_isConnected = false.obs;
|
||||
```
|
||||
|
||||
#### **连接状态更新逻辑**: `_bindConnectionStatus()`
|
||||
```dart
|
||||
void _bindConnectionStatus() {
|
||||
ever(KRSingBoxImp.instance.kr_status, (status) {
|
||||
switch (status) {
|
||||
case SingboxStopped():
|
||||
kr_isConnected.value = false; // 未连接
|
||||
break;
|
||||
case SingboxStarting():
|
||||
kr_isConnected.value = true; // 连接中
|
||||
break;
|
||||
case SingboxStarted():
|
||||
kr_isConnected.value = true; // 已连接
|
||||
break;
|
||||
case SingboxStopping():
|
||||
kr_isConnected.value = false; // 断开中
|
||||
break;
|
||||
}
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### **2. 延迟测试逻辑**
|
||||
|
||||
#### **主测试方法**: `kr_urlTest()`
|
||||
```dart
|
||||
Future<void> kr_urlTest() async {
|
||||
KRLogUtil.kr_i('📊 当前连接状态: ${kr_isConnected.value}', tag: 'HomeController');
|
||||
|
||||
if (kr_isConnected.value) {
|
||||
// ✅ 已连接状态:使用 SingBox 通过代理测试(默认测试规则)
|
||||
KRLogUtil.kr_i('🔗 已连接状态 - 使用 SingBox 通过代理测试延迟', tag: 'HomeController');
|
||||
await KRSingBoxImp.instance.kr_urlTest("select");
|
||||
|
||||
// 等待 SingBox 完成测试
|
||||
await Future.delayed(const Duration(seconds: 3));
|
||||
|
||||
// 检查活动组状态
|
||||
final activeGroups = KRSingBoxImp.instance.kr_activeGroups;
|
||||
// ... 处理测试结果
|
||||
} else {
|
||||
// ✅ 未连接状态:使用本机网络直接ping节点IP
|
||||
KRLogUtil.kr_i('🔌 未连接状态 - 使用本机网络直接ping节点IP测试延迟', tag: 'HomeController');
|
||||
KRLogUtil.kr_i('🌐 这将绕过代理,直接使用本机网络连接节点', tag: 'HomeController');
|
||||
await _kr_testLatencyWithoutVpn();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### **3. 本机网络测试逻辑**
|
||||
|
||||
#### **本机网络测试方法**: `_kr_testLatencyWithoutVpn()`
|
||||
```dart
|
||||
/// 未连接状态下的延迟测试(使用本机网络直接ping节点IP)
|
||||
Future<void> _kr_testLatencyWithoutVpn() async {
|
||||
KRLogUtil.kr_i('🔌 开始未连接状态延迟测试(使用本机网络)', tag: 'HomeController');
|
||||
KRLogUtil.kr_i('🌐 将使用本机网络直接连接节点IP进行延迟测试', tag: 'HomeController');
|
||||
|
||||
// 获取所有非auto节点
|
||||
final testableNodes = kr_subscribeService.allList
|
||||
.where((item) => item.tag != 'auto')
|
||||
.toList();
|
||||
|
||||
// 并行执行所有测试任务
|
||||
final testTasks = testableNodes
|
||||
.map((item) => _kr_testSingleNode(item))
|
||||
.toList();
|
||||
|
||||
await Future.wait(testTasks);
|
||||
|
||||
// 统计和显示测试结果
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
#### **单个节点测试方法**: `_kr_testSingleNode()`
|
||||
```dart
|
||||
/// 测试单个节点的延迟(使用本机网络直接ping节点IP)
|
||||
Future<void> _kr_testSingleNode(dynamic item) async {
|
||||
KRLogUtil.kr_i('🔌 使用本机网络直接连接测试(绕过代理)', tag: 'NodeTest');
|
||||
|
||||
// 使用本机网络直接连接测试节点延迟
|
||||
final socket = await Socket.connect(
|
||||
address,
|
||||
port,
|
||||
timeout: const Duration(seconds: 8), // 8秒超时
|
||||
);
|
||||
|
||||
// 获取延迟时间
|
||||
final delay = stopwatch.elapsedMilliseconds;
|
||||
|
||||
// 设置延迟阈值:超过5秒认为节点不可用
|
||||
if (delay > 5000) {
|
||||
item.urlTestDelay.value = 65535; // 标记为不可用
|
||||
} else {
|
||||
item.urlTestDelay.value = delay; // 使用本机网络测试的延迟结果
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## ✅ 逻辑确认
|
||||
|
||||
### **连接代理时(kr_isConnected.value = true)**:
|
||||
1. **使用默认测试规则**: 调用 `KRSingBoxImp.instance.kr_urlTest("select")`
|
||||
2. **通过代理测试**: 使用 SingBox 的 URL 测试功能
|
||||
3. **等待测试完成**: 等待3秒让 SingBox 完成测试
|
||||
4. **获取测试结果**: 从 `KRSingBoxImp.instance.kr_activeGroups` 获取延迟信息
|
||||
|
||||
### **没连接时(kr_isConnected.value = false)**:
|
||||
1. **使用本机网络**: 调用 `_kr_testLatencyWithoutVpn()`
|
||||
2. **直接连接节点**: 使用 `Socket.connect()` 直接连接节点IP
|
||||
3. **绕过代理**: 不经过任何代理,使用本机网络
|
||||
4. **并行测试**: 同时测试所有节点,提高效率
|
||||
5. **真实延迟**: 获得本机到节点的真实网络延迟
|
||||
|
||||
## 🔍 关键判断点
|
||||
|
||||
### **连接状态判断**:
|
||||
```dart
|
||||
if (kr_isConnected.value) {
|
||||
// 连接代理时:使用 SingBox 默认测试规则
|
||||
} else {
|
||||
// 没连接时:使用本机网络直接ping节点IP
|
||||
}
|
||||
```
|
||||
|
||||
### **连接状态来源**:
|
||||
- `kr_isConnected` 的值来自 `KRSingBoxImp.instance.kr_status`
|
||||
- 当 SingBox 状态为 `SingboxStarted()` 或 `SingboxStarting()` 时,`kr_isConnected = true`
|
||||
- 当 SingBox 状态为 `SingboxStopped()` 或 `SingboxStopping()` 时,`kr_isConnected = false`
|
||||
|
||||
## 📊 测试验证
|
||||
|
||||
### **测试场景1: 连接代理时**
|
||||
- **预期行为**: 使用 SingBox 通过代理测试
|
||||
- **验证日志**: `🔗 已连接状态 - 使用 SingBox 通过代理测试延迟`
|
||||
- **测试方式**: `KRSingBoxImp.instance.kr_urlTest("select")`
|
||||
|
||||
### **测试场景2: 没连接时**
|
||||
- **预期行为**: 使用本机网络直接ping节点IP
|
||||
- **验证日志**: `🔌 未连接状态 - 使用本机网络直接ping节点IP测试延迟`
|
||||
- **测试方式**: `Socket.connect()` 直接连接节点
|
||||
|
||||
## 📝 总结
|
||||
|
||||
**✅ 当前实现完全符合用户需求**:
|
||||
|
||||
1. **连接代理时**: 保持默认测试规则,使用 SingBox 通过代理测试延迟
|
||||
2. **没连接时**: 使用本机网络直接ping节点IP,绕过代理获取真实延迟
|
||||
|
||||
**🔧 实现特点**:
|
||||
- 自动根据连接状态选择测试方式
|
||||
- 连接时使用代理测试,未连接时使用直连测试
|
||||
- 详细的日志记录,便于调试和验证
|
||||
- 并行测试提高效率
|
||||
- 完善的错误处理和超时机制
|
||||
|
||||
**🎯 用户需求已完全实现!**
|
||||
@ -1,171 +0,0 @@
|
||||
# 延迟测试优化总结
|
||||
|
||||
## 🎯 优化目标
|
||||
|
||||
解决延迟测试的问题:
|
||||
- **开启代理后**: 可以正常获取节点的延迟信息
|
||||
- **不开启代理时**: 无法获取节点延迟,因为网络请求被代理拦截
|
||||
|
||||
**解决方案**: 在不开启代理时,使用本机网络直接ping节点IP来获取延迟信息。
|
||||
|
||||
## 🔧 优化内容
|
||||
|
||||
### **1. 优化延迟测试主逻辑**
|
||||
|
||||
#### **修改位置**: `kr_urlTest()` 方法
|
||||
|
||||
#### **优化内容**:
|
||||
- **明确区分测试方式**: 根据连接状态选择不同的测试方法
|
||||
- **已连接状态**: 使用 SingBox 通过代理测试延迟
|
||||
- **未连接状态**: 使用本机网络直接ping节点IP测试延迟
|
||||
|
||||
```dart
|
||||
if (kr_isConnected.value) {
|
||||
// 已连接状态:使用 SingBox 通过代理测试
|
||||
KRLogUtil.kr_i('🔗 已连接状态 - 使用 SingBox 通过代理测试延迟', tag: 'HomeController');
|
||||
await KRSingBoxImp.instance.kr_urlTest("select");
|
||||
} else {
|
||||
// 未连接状态:使用本机网络直接ping节点IP
|
||||
KRLogUtil.kr_i('🔌 未连接状态 - 使用本机网络直接ping节点IP测试延迟', tag: 'HomeController');
|
||||
KRLogUtil.kr_i('🌐 这将绕过代理,直接使用本机网络连接节点', tag: 'HomeController');
|
||||
await _kr_testLatencyWithoutVpn();
|
||||
}
|
||||
```
|
||||
|
||||
### **2. 优化未连接状态延迟测试**
|
||||
|
||||
#### **修改位置**: `_kr_testLatencyWithoutVpn()` 方法
|
||||
|
||||
#### **优化内容**:
|
||||
- **明确测试方式**: 强调使用本机网络直接连接
|
||||
- **详细日志记录**: 记录测试过程和结果统计
|
||||
- **结果展示**: 显示延迟最低的前3个节点
|
||||
- **错误处理**: 完善的错误处理和统计
|
||||
|
||||
```dart
|
||||
/// 未连接状态下的延迟测试(使用本机网络直接ping节点IP)
|
||||
Future<void> _kr_testLatencyWithoutVpn() async {
|
||||
KRLogUtil.kr_i('🔌 开始未连接状态延迟测试(使用本机网络)', tag: 'HomeController');
|
||||
KRLogUtil.kr_i('🌐 将使用本机网络直接连接节点IP进行延迟测试', tag: 'HomeController');
|
||||
|
||||
// 获取所有非auto节点
|
||||
final testableNodes = kr_subscribeService.allList
|
||||
.where((item) => item.tag != 'auto')
|
||||
.toList();
|
||||
|
||||
// 并行执行所有测试任务
|
||||
await Future.wait(testTasks);
|
||||
|
||||
// 统计测试结果
|
||||
final successCount = testableNodes.where((item) => item.urlTestDelay.value < 65535).length;
|
||||
final failCount = testableNodes.length - successCount;
|
||||
|
||||
KRLogUtil.kr_i('📊 测试结果: 成功 $successCount 个,失败 $failCount 个', tag: 'HomeController');
|
||||
}
|
||||
```
|
||||
|
||||
### **3. 优化单个节点测试方法**
|
||||
|
||||
#### **修改位置**: `_kr_testSingleNode()` 方法
|
||||
|
||||
#### **优化内容**:
|
||||
- **明确测试方式**: 强调使用本机网络直接连接(绕过代理)
|
||||
- **增加超时时间**: 从5秒增加到8秒
|
||||
- **调整延迟阈值**: 从3秒调整到5秒
|
||||
- **详细错误分类**: 区分不同类型的连接错误
|
||||
- **更清晰的日志**: 明确标识使用本机网络测试
|
||||
|
||||
```dart
|
||||
/// 测试单个节点的延迟(使用本机网络直接ping节点IP)
|
||||
Future<void> _kr_testSingleNode(dynamic item) async {
|
||||
KRLogUtil.kr_i('🔌 使用本机网络直接连接测试(绕过代理)', tag: 'NodeTest');
|
||||
|
||||
// 创建Socket连接,使用本机网络(不经过代理)
|
||||
final socket = await Socket.connect(
|
||||
address,
|
||||
port,
|
||||
timeout: const Duration(seconds: 8), // 增加超时时间到8秒
|
||||
);
|
||||
|
||||
// 设置延迟阈值:超过5秒认为节点不可用
|
||||
if (delay > 5000) {
|
||||
item.urlTestDelay.value = 65535;
|
||||
KRLogUtil.kr_w('⚠️ 节点 ${item.tag} 延迟过高: ${delay}ms,标记为不可用', tag: 'NodeTest');
|
||||
} else {
|
||||
// 使用本机网络测试的延迟结果
|
||||
item.urlTestDelay.value = delay;
|
||||
KRLogUtil.kr_i('✅ 节点 ${item.tag} 本机网络延迟测试成功: ${delay}ms', tag: 'NodeTest');
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 🎯 优化效果
|
||||
|
||||
### **解决的问题**:
|
||||
|
||||
1. **代理拦截问题**: 未连接时使用本机网络直接连接,绕过代理拦截
|
||||
2. **延迟测试不准确**: 使用本机网络直接ping节点IP,获得真实的网络延迟
|
||||
3. **测试方式不明确**: 明确区分代理测试和直连测试
|
||||
4. **错误处理不完善**: 增加详细的错误分类和处理
|
||||
|
||||
### **预期改善**:
|
||||
|
||||
1. **未连接状态**: 可以正常获取节点延迟信息
|
||||
2. **测试准确性**: 使用本机网络测试,获得更准确的延迟数据
|
||||
3. **用户体验**: 无论是否连接代理,都能看到节点延迟
|
||||
4. **调试能力**: 详细的日志记录,便于问题排查
|
||||
|
||||
## 📊 测试场景
|
||||
|
||||
### **测试场景1: 未连接状态延迟测试**
|
||||
- **预期行为**: 使用本机网络直接连接节点IP
|
||||
- **验证要点**:
|
||||
- 日志显示"使用本机网络直接连接测试(绕过代理)"
|
||||
- 能够获取到节点的真实延迟
|
||||
- 延迟值合理(通常 < 5000ms)
|
||||
|
||||
### **测试场景2: 已连接状态延迟测试**
|
||||
- **预期行为**: 使用 SingBox 通过代理测试
|
||||
- **验证要点**:
|
||||
- 日志显示"使用 SingBox 通过代理测试延迟"
|
||||
- 通过代理获取延迟信息
|
||||
- 测试结果正确显示
|
||||
|
||||
### **测试场景3: 网络异常处理**
|
||||
- **预期行为**: 正确处理连接超时、拒绝、不可达等情况
|
||||
- **验证要点**:
|
||||
- 超时节点标记为不可用(65535)
|
||||
- 错误日志详细记录错误类型
|
||||
- 测试继续进行,不影响其他节点
|
||||
|
||||
## 🔍 关键日志点
|
||||
|
||||
### **测试开始**:
|
||||
- `🔌 开始未连接状态延迟测试(使用本机网络)`
|
||||
- `🌐 将使用本机网络直接连接节点IP进行延迟测试`
|
||||
|
||||
### **单个节点测试**:
|
||||
- `🔌 使用本机网络直接连接测试(绕过代理)`
|
||||
- `⏱️ 本机网络连接延迟: XXXms`
|
||||
- `✅ 节点 XXX 本机网络延迟测试成功: XXXms`
|
||||
|
||||
### **测试结果**:
|
||||
- `📊 测试结果: 成功 X 个,失败 X 个`
|
||||
- `🏆 延迟最低的前3个节点:`
|
||||
|
||||
### **错误处理**:
|
||||
- `⏰ 节点 XXX 连接超时`
|
||||
- `🚫 节点 XXX 连接被拒绝`
|
||||
- `🌐 节点 XXX 网络不可达`
|
||||
|
||||
## 📝 总结
|
||||
|
||||
通过这次优化,我们解决了延迟测试的核心问题:
|
||||
|
||||
1. **明确区分测试方式**: 根据连接状态选择代理测试或直连测试
|
||||
2. **使用本机网络**: 未连接时直接ping节点IP,绕过代理拦截
|
||||
3. **提高测试准确性**: 获得真实的网络延迟数据
|
||||
4. **完善错误处理**: 详细的错误分类和日志记录
|
||||
5. **改善用户体验**: 无论是否连接代理,都能看到节点延迟
|
||||
|
||||
现在用户可以在未连接代理的情况下,通过本机网络直接测试节点延迟,获得准确的延迟信息!
|
||||
@ -1,285 +0,0 @@
|
||||
# 登录后只显示地图问题分析
|
||||
|
||||
## 🔍 问题描述
|
||||
|
||||
用户反馈:登录后,有时候重新打开app会直接只加载地图,其他的页面(底部面板、登录框等)就没有正常显示。
|
||||
|
||||
## 📋 问题分析
|
||||
|
||||
### **1. 页面显示逻辑分析**
|
||||
|
||||
#### **首页视图显示逻辑** (`kr_home_view.dart`)
|
||||
```dart
|
||||
// 根据登录状态决定显示内容
|
||||
if (controller.kr_currentViewStatus.value == KRHomeViewsStatus.kr_notLoggedIn) {
|
||||
// 未登录:显示地图 + 登录框
|
||||
return Scaffold(
|
||||
body: Stack(
|
||||
children: [
|
||||
const KRHomeMapView(), // 地图视图
|
||||
Positioned(bottom: 0, child: KRLoginView()), // 登录框
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// 已登录:显示地图 + 底部面板
|
||||
return Scaffold(
|
||||
body: Stack(
|
||||
children: [
|
||||
const KRHomeMapView(), // 地图视图
|
||||
Positioned(bottom: 0, child: KRHomeBottomPanel()), // 底部面板
|
||||
],
|
||||
),
|
||||
);
|
||||
```
|
||||
|
||||
#### **底部面板显示逻辑** (`kr_home_bottom_panel.dart`)
|
||||
```dart
|
||||
// 根据订阅服务状态决定显示内容
|
||||
if (controller.kr_currentListStatus.value == KRHomeViewsListStatus.kr_loading) {
|
||||
return _kr_buildLoadingView(); // 显示加载动画
|
||||
}
|
||||
|
||||
if (controller.kr_currentListStatus.value == KRHomeViewsListStatus.kr_error) {
|
||||
return _kr_buildErrorView(context); // 显示错误信息
|
||||
}
|
||||
|
||||
// 正常状态:显示订阅信息、连接选项等
|
||||
return _kr_buildDefaultView(context);
|
||||
```
|
||||
|
||||
### **2. 状态初始化流程**
|
||||
|
||||
#### **启动流程**
|
||||
1. **启动页面** (`kr_splash_controller.dart`)
|
||||
- 初始化 SingBox
|
||||
- 初始化用户信息 (`KRAppRunData.getInstance().kr_initializeUserInfo()`)
|
||||
- 跳转到主页面
|
||||
|
||||
2. **主页面初始化** (`kr_main_controller.dart`)
|
||||
- 创建首页控制器 (`KRHomeController`)
|
||||
- 显示首页视图 (`KRHomeView`)
|
||||
|
||||
3. **首页控制器初始化** (`kr_home_controller.dart`)
|
||||
- `_kr_initLoginStatus()` - 初始化登录状态
|
||||
- `_bindSubscribeStatus()` - 绑定订阅状态
|
||||
- `_bindConnectionStatus()` - 绑定连接状态
|
||||
|
||||
#### **登录状态初始化** (`_kr_initLoginStatus`)
|
||||
```dart
|
||||
void _kr_initLoginStatus() {
|
||||
// 延迟100ms初始化,确保异步操作完成
|
||||
Future.delayed(const Duration(milliseconds: 100), () {
|
||||
_kr_validateAndSetLoginStatus();
|
||||
});
|
||||
|
||||
// 注册登录状态监听器
|
||||
ever(KRAppRunData().kr_isLogin, (isLoggedIn) {
|
||||
_kr_handleLoginStatusChange(isLoggedIn);
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
#### **订阅状态绑定** (`_bindSubscribeStatus`)
|
||||
```dart
|
||||
void _bindSubscribeStatus() {
|
||||
ever(kr_subscribeService.kr_currentStatus, (data) {
|
||||
if (KRAppRunData.getInstance().kr_isLogin.value) {
|
||||
if (data == KRSubscribeServiceStatus.kr_loading) {
|
||||
kr_currentListStatus.value = KRHomeViewsListStatus.kr_loading;
|
||||
} else if (data == KRSubscribeServiceStatus.kr_error) {
|
||||
kr_currentListStatus.value = KRHomeViewsListStatus.kr_error;
|
||||
} else {
|
||||
kr_currentListStatus.value = KRHomeViewsListStatus.kr_none;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### **3. 潜在问题点**
|
||||
|
||||
#### **问题1: 竞态条件 (Race Condition)**
|
||||
- **现象**: 登录状态和订阅服务状态初始化时序不确定
|
||||
- **原因**:
|
||||
- `_kr_initLoginStatus()` 延迟100ms执行
|
||||
- `kr_subscribeService.kr_refreshAll()` 异步执行
|
||||
- 两个异步操作可能产生竞态条件
|
||||
|
||||
#### **问题2: 订阅服务初始化失败**
|
||||
- **现象**: 订阅服务状态卡在 `kr_loading` 或 `kr_error`
|
||||
- **原因**:
|
||||
- 网络请求失败
|
||||
- API 响应异常
|
||||
- 数据解析错误
|
||||
- 超时问题
|
||||
|
||||
#### **问题3: 状态监听器注册时机**
|
||||
- **现象**: 状态变化时监听器未正确响应
|
||||
- **原因**:
|
||||
- 监听器注册在异步操作之后
|
||||
- 状态变化发生在监听器注册之前
|
||||
|
||||
#### **问题4: 登录状态验证逻辑**
|
||||
- **现象**: 登录状态判断不准确
|
||||
- **原因**:
|
||||
- Token 验证逻辑复杂
|
||||
- 状态同步检查可能失败
|
||||
|
||||
### **4. 具体场景分析**
|
||||
|
||||
#### **场景1: 只显示地图,无底部面板**
|
||||
```
|
||||
可能原因:
|
||||
1. kr_currentViewStatus = kr_loggedIn (已登录)
|
||||
2. kr_currentListStatus = kr_loading (订阅服务加载中)
|
||||
3. 订阅服务初始化失败或超时
|
||||
4. 底部面板显示加载动画,但加载动画可能有问题
|
||||
```
|
||||
|
||||
#### **场景2: 显示地图 + 登录框(应该是已登录状态)**
|
||||
```
|
||||
可能原因:
|
||||
1. kr_currentViewStatus = kr_notLoggedIn (未登录)
|
||||
2. 登录状态验证失败
|
||||
3. Token 无效或过期
|
||||
4. 状态同步检查失败
|
||||
```
|
||||
|
||||
#### **场景3: 显示地图 + 错误信息**
|
||||
```
|
||||
可能原因:
|
||||
1. kr_currentViewStatus = kr_loggedIn (已登录)
|
||||
2. kr_currentListStatus = kr_error (订阅服务错误)
|
||||
3. 网络请求失败
|
||||
4. API 返回错误
|
||||
```
|
||||
|
||||
## 🛠️ 修复建议
|
||||
|
||||
### **1. 增强状态验证**
|
||||
```dart
|
||||
void _kr_validateAndSetLoginStatus() {
|
||||
try {
|
||||
// 多重验证登录状态
|
||||
final hasToken = KRAppRunData().kr_token != null && KRAppRunData().kr_token!.isNotEmpty;
|
||||
final isLoginFlag = KRAppRunData().kr_isLogin.value;
|
||||
final isValidLogin = hasToken && isLoginFlag;
|
||||
|
||||
KRLogUtil.kr_i('登录状态验证: hasToken=$hasToken, isLogin=$isLoginFlag, isValid=$isValidLogin', tag: 'HomeController');
|
||||
|
||||
if (isValidLogin) {
|
||||
kr_currentViewStatus.value = KRHomeViewsStatus.kr_loggedIn;
|
||||
// 确保订阅服务初始化
|
||||
_kr_ensureSubscribeServiceInitialized();
|
||||
} else {
|
||||
kr_currentViewStatus.value = KRHomeViewsStatus.kr_notLoggedIn;
|
||||
}
|
||||
} catch (e) {
|
||||
KRLogUtil.kr_e('登录状态验证失败: $e', tag: 'HomeController');
|
||||
kr_currentViewStatus.value = KRHomeViewsStatus.kr_notLoggedIn;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### **2. 确保订阅服务初始化**
|
||||
```dart
|
||||
void _kr_ensureSubscribeServiceInitialized() {
|
||||
// 检查订阅服务状态
|
||||
if (kr_subscribeService.kr_currentStatus.value == KRSubscribeServiceStatus.kr_none) {
|
||||
KRLogUtil.kr_i('订阅服务未初始化,开始初始化', tag: 'HomeController');
|
||||
kr_subscribeService.kr_refreshAll().catchError((error) {
|
||||
KRLogUtil.kr_e('订阅服务初始化失败: $error', tag: 'HomeController');
|
||||
// 设置错误状态
|
||||
kr_currentListStatus.value = KRHomeViewsListStatus.kr_error;
|
||||
});
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### **3. 添加超时处理**
|
||||
```dart
|
||||
void _kr_initLoginStatus() {
|
||||
// 设置超时处理
|
||||
Timer(const Duration(seconds: 10), () {
|
||||
if (kr_currentListStatus.value == KRHomeViewsListStatus.kr_loading) {
|
||||
KRLogUtil.kr_w('订阅服务初始化超时', tag: 'HomeController');
|
||||
kr_currentListStatus.value = KRHomeViewsListStatus.kr_error;
|
||||
}
|
||||
});
|
||||
|
||||
// 延迟初始化
|
||||
Future.delayed(const Duration(milliseconds: 100), () {
|
||||
_kr_validateAndSetLoginStatus();
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### **4. 增强错误处理**
|
||||
```dart
|
||||
void _bindSubscribeStatus() {
|
||||
ever(kr_subscribeService.kr_currentStatus, (data) {
|
||||
if (KRAppRunData.getInstance().kr_isLogin.value) {
|
||||
switch (data) {
|
||||
case KRSubscribeServiceStatus.kr_loading:
|
||||
kr_currentListStatus.value = KRHomeViewsListStatus.kr_loading;
|
||||
break;
|
||||
case KRSubscribeServiceStatus.kr_error:
|
||||
kr_currentListStatus.value = KRHomeViewsListStatus.kr_error;
|
||||
// 添加重试机制
|
||||
_kr_retrySubscribeService();
|
||||
break;
|
||||
case KRSubscribeServiceStatus.kr_success:
|
||||
kr_currentListStatus.value = KRHomeViewsListStatus.kr_none;
|
||||
break;
|
||||
default:
|
||||
kr_currentListStatus.value = KRHomeViewsListStatus.kr_none;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### **5. 添加重试机制**
|
||||
```dart
|
||||
void _kr_retrySubscribeService() {
|
||||
Timer(const Duration(seconds: 3), () {
|
||||
if (kr_currentListStatus.value == KRHomeViewsListStatus.kr_error) {
|
||||
KRLogUtil.kr_i('重试订阅服务初始化', tag: 'HomeController');
|
||||
kr_subscribeService.kr_refreshAll().catchError((error) {
|
||||
KRLogUtil.kr_e('重试失败: $error', tag: 'HomeController');
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
## 📊 监控和调试
|
||||
|
||||
### **1. 关键日志点**
|
||||
- 登录状态验证日志
|
||||
- 订阅服务初始化日志
|
||||
- 状态变化日志
|
||||
- 错误处理日志
|
||||
|
||||
### **2. 状态检查**
|
||||
- `kr_currentViewStatus` 的值
|
||||
- `kr_currentListStatus` 的值
|
||||
- `kr_subscribeService.kr_currentStatus` 的值
|
||||
- `KRAppRunData().kr_isLogin` 的值
|
||||
|
||||
### **3. 网络状态**
|
||||
- API 请求是否成功
|
||||
- 响应数据是否正常
|
||||
- 超时情况
|
||||
|
||||
## 🎯 总结
|
||||
|
||||
这个问题主要是由于**异步初始化时序问题**和**状态管理复杂性**导致的。核心问题是:
|
||||
|
||||
1. **登录状态验证** 和 **订阅服务初始化** 之间存在竞态条件
|
||||
2. **订阅服务初始化失败** 时没有合适的错误处理和重试机制
|
||||
3. **状态监听器注册时机** 可能晚于状态变化
|
||||
|
||||
通过增强状态验证、添加超时处理、完善错误处理和重试机制,可以显著改善这个问题的发生频率。
|
||||
@ -1,218 +0,0 @@
|
||||
# 登录后只显示地图问题修复总结
|
||||
|
||||
## 🎯 修复目标
|
||||
|
||||
解决登录后重新打开app时只显示地图而其他页面(底部面板、登录框等)不显示的问题。
|
||||
|
||||
## 🔧 修复内容
|
||||
|
||||
### **1. 增强登录状态验证逻辑**
|
||||
|
||||
#### **修改位置**: `_kr_validateAndSetLoginStatus()` 方法
|
||||
|
||||
#### **修复内容**:
|
||||
- **多重验证**: 同时检查 `hasToken` 和 `isLoginFlag`
|
||||
- **详细日志**: 添加更详细的状态验证日志
|
||||
- **Token验证**: 确保Token不为空且不为空字符串
|
||||
- **状态设置**: 明确设置登录状态并记录日志
|
||||
|
||||
```dart
|
||||
// 多重验证登录状态
|
||||
final hasToken = KRAppRunData().kr_token != null && KRAppRunData().kr_token!.isNotEmpty;
|
||||
final isLoginFlag = KRAppRunData().kr_isLogin.value;
|
||||
final isValidLogin = hasToken && isLoginFlag;
|
||||
|
||||
KRLogUtil.kr_i('登录状态验证: hasToken=$hasToken, isLogin=$isLoginFlag, isValid=$isValidLogin', tag: 'HomeController');
|
||||
KRLogUtil.kr_i('Token内容: ${KRAppRunData().kr_token?.substring(0, 10)}...', tag: 'HomeController');
|
||||
```
|
||||
|
||||
### **2. 确保订阅服务初始化**
|
||||
|
||||
#### **新增方法**: `_kr_ensureSubscribeServiceInitialized()`
|
||||
|
||||
#### **修复内容**:
|
||||
- **状态检查**: 检查订阅服务当前状态
|
||||
- **智能初始化**: 根据状态决定是否需要初始化
|
||||
- **错误处理**: 初始化失败时设置错误状态
|
||||
- **自动重试**: 失败时自动启动重试机制
|
||||
|
||||
```dart
|
||||
void _kr_ensureSubscribeServiceInitialized() {
|
||||
try {
|
||||
// 检查订阅服务状态
|
||||
final currentStatus = kr_subscribeService.kr_currentStatus.value;
|
||||
|
||||
if (currentStatus == KRSubscribeServiceStatus.kr_none ||
|
||||
currentStatus == KRSubscribeServiceStatus.kr_error) {
|
||||
// 设置加载状态并初始化
|
||||
kr_currentListStatus.value = KRHomeViewsListStatus.kr_loading;
|
||||
kr_subscribeService.kr_refreshAll().then((_) {
|
||||
KRLogUtil.kr_i('订阅服务初始化完成', tag: 'HomeController');
|
||||
}).catchError((error) {
|
||||
KRLogUtil.kr_e('订阅服务初始化失败: $error', tag: 'HomeController');
|
||||
kr_currentListStatus.value = KRHomeViewsListStatus.kr_error;
|
||||
_kr_retrySubscribeService();
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
KRLogUtil.kr_e('确保订阅服务初始化失败: $e', tag: 'HomeController');
|
||||
kr_currentListStatus.value = KRHomeViewsListStatus.kr_error;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### **3. 添加超时处理机制**
|
||||
|
||||
#### **修改位置**: `_kr_initLoginStatus()` 方法
|
||||
|
||||
#### **修复内容**:
|
||||
- **超时检测**: 10秒后检查订阅服务是否还在加载
|
||||
- **自动处理**: 超时时自动设置为错误状态
|
||||
- **重试机制**: 超时后自动启动重试
|
||||
|
||||
```dart
|
||||
// 设置超时处理
|
||||
Timer(const Duration(seconds: 10), () {
|
||||
if (kr_currentListStatus.value == KRHomeViewsListStatus.kr_loading) {
|
||||
KRLogUtil.kr_w('订阅服务初始化超时,设置为错误状态', tag: 'HomeController');
|
||||
kr_currentListStatus.value = KRHomeViewsListStatus.kr_error;
|
||||
_kr_retrySubscribeService();
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
### **4. 增强错误处理和重试机制**
|
||||
|
||||
#### **新增方法**: `_kr_retrySubscribeService()`
|
||||
|
||||
#### **修复内容**:
|
||||
- **智能重试**: 3秒后自动重试
|
||||
- **多次重试**: 最多重试3次
|
||||
- **渐进延迟**: 重试间隔逐渐增加
|
||||
- **状态检查**: 只在错误状态时重试
|
||||
|
||||
```dart
|
||||
void _kr_retrySubscribeService() {
|
||||
KRLogUtil.kr_i('启动订阅服务重试机制', tag: 'HomeController');
|
||||
|
||||
Timer(const Duration(seconds: 3), () {
|
||||
if (kr_currentListStatus.value == KRHomeViewsListStatus.kr_error) {
|
||||
KRLogUtil.kr_i('重试订阅服务初始化', tag: 'HomeController');
|
||||
|
||||
kr_subscribeService.kr_refreshAll().then((_) {
|
||||
KRLogUtil.kr_i('订阅服务重试成功', tag: 'HomeController');
|
||||
}).catchError((error) {
|
||||
KRLogUtil.kr_e('订阅服务重试失败: $error', tag: 'HomeController');
|
||||
|
||||
// 第二次重试
|
||||
Timer(const Duration(seconds: 5), () {
|
||||
if (kr_currentListStatus.value == KRHomeViewsListStatus.kr_error) {
|
||||
KRLogUtil.kr_i('第二次重试订阅服务初始化', tag: 'HomeController');
|
||||
kr_subscribeService.kr_refreshAll().catchError((error) {
|
||||
KRLogUtil.kr_e('第二次重试失败: $error', tag: 'HomeController');
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### **5. 优化异步初始化时序**
|
||||
|
||||
#### **修改位置**: `_bindSubscribeStatus()` 方法
|
||||
|
||||
#### **修复内容**:
|
||||
- **状态监听**: 增强订阅服务状态监听
|
||||
- **智能处理**: 根据状态自动处理不同情况
|
||||
- **自动初始化**: 状态为none时自动尝试初始化
|
||||
- **详细日志**: 添加详细的状态变化日志
|
||||
|
||||
```dart
|
||||
void _bindSubscribeStatus() {
|
||||
ever(kr_subscribeService.kr_currentStatus, (data) {
|
||||
KRLogUtil.kr_i('订阅服务状态变化: $data', tag: 'HomeController');
|
||||
|
||||
if (KRAppRunData.getInstance().kr_isLogin.value) {
|
||||
switch (data) {
|
||||
case KRSubscribeServiceStatus.kr_loading:
|
||||
kr_currentListStatus.value = KRHomeViewsListStatus.kr_loading;
|
||||
break;
|
||||
case KRSubscribeServiceStatus.kr_error:
|
||||
kr_currentListStatus.value = KRHomeViewsListStatus.kr_error;
|
||||
_kr_retrySubscribeService();
|
||||
break;
|
||||
case KRSubscribeServiceStatus.kr_success:
|
||||
kr_currentListStatus.value = KRHomeViewsListStatus.kr_none;
|
||||
break;
|
||||
case KRSubscribeServiceStatus.kr_none:
|
||||
// 如果状态为none且已登录,尝试初始化
|
||||
if (kr_currentViewStatus.value == KRHomeViewsStatus.kr_loggedIn) {
|
||||
_kr_ensureSubscribeServiceInitialized();
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
## 🎯 修复效果
|
||||
|
||||
### **解决的问题**:
|
||||
|
||||
1. **竞态条件**: 通过增强状态验证和确保订阅服务初始化解决
|
||||
2. **订阅服务初始化失败**: 通过添加重试机制和超时处理解决
|
||||
3. **状态监听器注册时机**: 通过优化异步初始化时序解决
|
||||
4. **登录状态验证不准确**: 通过多重验证和详细日志解决
|
||||
|
||||
### **预期改善**:
|
||||
|
||||
1. **减少只显示地图的情况**: 通过确保订阅服务正确初始化
|
||||
2. **提高状态一致性**: 通过增强状态验证和同步检查
|
||||
3. **增强错误恢复能力**: 通过自动重试机制
|
||||
4. **改善用户体验**: 通过超时处理和智能重试
|
||||
|
||||
## 📊 监控和调试
|
||||
|
||||
### **关键日志点**:
|
||||
- `登录状态验证: hasToken=xxx, isLogin=xxx, isValid=xxx`
|
||||
- `订阅服务当前状态: xxx`
|
||||
- `订阅服务状态变化: xxx`
|
||||
- `启动订阅服务重试机制`
|
||||
- `订阅服务初始化超时`
|
||||
|
||||
### **状态检查**:
|
||||
- `kr_currentViewStatus` 的值
|
||||
- `kr_currentListStatus` 的值
|
||||
- `kr_subscribeService.kr_currentStatus` 的值
|
||||
- `KRAppRunData().kr_isLogin` 的值
|
||||
|
||||
## 🚀 测试建议
|
||||
|
||||
### **测试场景**:
|
||||
1. **正常登录**: 验证登录后所有功能正常显示
|
||||
2. **网络异常**: 验证网络异常时的重试机制
|
||||
3. **超时情况**: 验证超时处理和自动重试
|
||||
4. **状态切换**: 验证登录/登出状态切换
|
||||
5. **多次重试**: 验证多次重试后的最终状态
|
||||
|
||||
### **验证要点**:
|
||||
- 登录后底部面板是否正常显示
|
||||
- 订阅服务是否成功初始化
|
||||
- 错误状态是否自动恢复
|
||||
- 重试机制是否正常工作
|
||||
- 日志信息是否详细准确
|
||||
|
||||
## 📝 总结
|
||||
|
||||
通过系统性的修复,我们解决了登录后只显示地图问题的根本原因:
|
||||
|
||||
1. **增强了状态验证的可靠性**
|
||||
2. **确保了订阅服务的正确初始化**
|
||||
3. **添加了超时处理和重试机制**
|
||||
4. **优化了异步初始化的时序**
|
||||
5. **完善了错误处理和恢复逻辑**
|
||||
|
||||
这些修复将显著减少问题的发生频率,提高应用的稳定性和用户体验。
|
||||
@ -1,126 +0,0 @@
|
||||
# macOS DMG 构建指南
|
||||
|
||||
本指南将帮助您构建 macOS DMG 安装包,并避免用户在安装时需要在安全隐私设置中手动允许。
|
||||
|
||||
## 🎯 目标
|
||||
|
||||
构建一个经过代码签名和公证的 DMG 安装包,用户安装时无需手动允许。
|
||||
|
||||
## 📋 前提条件
|
||||
|
||||
### 1. Apple Developer 账户
|
||||
- 需要有效的 Apple Developer 账户($99/年)
|
||||
- 需要 **Developer ID Application** 证书
|
||||
- 需要 **Developer ID Installer** 证书
|
||||
|
||||
### 2. 获取证书
|
||||
1. 登录 [Apple Developer Portal](https://developer.apple.com)
|
||||
2. 进入 "Certificates, Identifiers & Profiles"
|
||||
3. 创建以下证书:
|
||||
- **Developer ID Application** (用于应用签名)
|
||||
- **Developer ID Installer** (用于安装包签名)
|
||||
|
||||
### 3. 创建 App 专用密码
|
||||
1. 登录 [Apple ID 管理页面](https://appleid.apple.com)
|
||||
2. 在 "App 专用密码" 部分创建新密码
|
||||
3. 记录此密码,稍后需要用到
|
||||
|
||||
## 🚀 构建步骤
|
||||
|
||||
### 方法一:完整签名版本(推荐)
|
||||
|
||||
1. **配置签名信息**
|
||||
```bash
|
||||
# 编辑配置文件
|
||||
nano macos_signing_config.sh
|
||||
|
||||
# 修改以下信息:
|
||||
export APPLE_ID="your-apple-id@example.com"
|
||||
export APPLE_PASSWORD="your-app-specific-password"
|
||||
export TEAM_ID="YOUR_TEAM_ID"
|
||||
export SIGNING_IDENTITY="Developer ID Application: Your Name (YOUR_TEAM_ID)"
|
||||
```
|
||||
|
||||
2. **加载配置并构建**
|
||||
```bash
|
||||
# 加载配置
|
||||
source macos_signing_config.sh
|
||||
|
||||
# 构建 DMG
|
||||
./build_macos_dmg.sh
|
||||
```
|
||||
|
||||
### 方法二:简化版本(需要手动允许)
|
||||
|
||||
如果您没有开发者证书,可以使用简化版本:
|
||||
|
||||
```bash
|
||||
./build_macos_simple.sh
|
||||
```
|
||||
|
||||
**注意**:此版本需要用户在安装时手动在安全隐私设置中允许。
|
||||
|
||||
## 📁 输出文件
|
||||
|
||||
构建完成后,DMG 文件将位于:
|
||||
```
|
||||
build/macos/Build/Products/Release/kaer_with_panels.dmg
|
||||
```
|
||||
|
||||
## 🔍 验证签名
|
||||
|
||||
构建完成后,您可以验证签名:
|
||||
|
||||
```bash
|
||||
# 验证应用签名
|
||||
codesign --verify --verbose build/macos/Build/Products/Release/kaer_with_panels.app
|
||||
|
||||
# 验证 DMG 签名
|
||||
codesign --verify --verbose build/macos/Build/Products/Release/kaer_with_panels.dmg
|
||||
|
||||
# 检查公证状态
|
||||
spctl --assess --verbose build/macos/Build/Products/Release/kaer_with_panels.dmg
|
||||
```
|
||||
|
||||
## 🛠️ 故障排除
|
||||
|
||||
### 1. 证书问题
|
||||
```bash
|
||||
# 查看可用证书
|
||||
security find-identity -v -p codesigning
|
||||
|
||||
# 如果看到 "0 valid identities found",说明没有安装证书
|
||||
```
|
||||
|
||||
### 2. 公证失败
|
||||
- 确保 Apple ID 和密码正确
|
||||
- 确保 Team ID 正确
|
||||
- 检查网络连接
|
||||
|
||||
### 3. 签名失败
|
||||
- 确保证书已正确安装
|
||||
- 检查签名身份名称是否正确
|
||||
- 确保证书未过期
|
||||
|
||||
## 📚 相关文档
|
||||
|
||||
- [Apple 代码签名指南](https://developer.apple.com/documentation/security/notarizing_macos_software_before_distribution)
|
||||
- [Flutter macOS 部署指南](https://docs.flutter.dev/deployment/macos)
|
||||
- [DMG 创建指南](https://developer.apple.com/design/human-interface-guidelines/macos/windows-and-views/dialogs/)
|
||||
|
||||
## ⚠️ 重要提醒
|
||||
|
||||
1. **安全性**:请妥善保管您的开发者证书和密码
|
||||
2. **测试**:在分发前,请在干净的 macOS 系统上测试安装
|
||||
3. **更新**:定期更新证书,避免过期
|
||||
4. **备份**:建议备份您的签名配置
|
||||
|
||||
## 🎉 成功标志
|
||||
|
||||
如果构建成功,您应该看到:
|
||||
- ✅ 应用签名成功
|
||||
- ✅ DMG 签名成功
|
||||
- ✅ DMG 公证成功
|
||||
- ✅ 最终验证通过
|
||||
|
||||
用户安装时应该能够直接运行,无需手动允许。
|
||||
@ -1,234 +0,0 @@
|
||||
# MySQL 5.7 自动备份指南
|
||||
|
||||
## 📋 配置说明
|
||||
|
||||
### 🔧 需要修改的配置项
|
||||
|
||||
在 `docker-compose-mysql-backup.yml` 文件中,请修改以下配置:
|
||||
|
||||
```yaml
|
||||
environment:
|
||||
# 🔗 远程 MySQL 5.7 服务器配置
|
||||
MYSQL_HOST: "your-mysql-server.com" # ← 修改为你的MySQL服务器地址
|
||||
MYSQL_PORT: "3306" # ← 修改为你的MySQL端口
|
||||
MYSQL_USER: "backup_user" # ← 修改为你的备份用户
|
||||
MYSQL_PASSWORD: "backup_password" # ← 修改为你的备份密码
|
||||
MYSQL_VERSION: "5.7" # ← MySQL版本 (已设置为5.7)
|
||||
|
||||
# 📁 备份配置
|
||||
BACKUP_RETENTION_DAYS: "7" # ← 备份保留天数
|
||||
BACKUP_SCHEDULE: "0 2 * * *" # ← 备份时间 (每天凌晨2点)
|
||||
|
||||
# 🔧 备份选项
|
||||
BACKUP_TYPE: "full" # ← 备份类型: full(全量) / incremental(增量)
|
||||
COMPRESS_BACKUP: "true" # ← 是否压缩备份
|
||||
PARALLEL_THREADS: "2" # ← 并行线程数 (MySQL 5.7 建议使用较少线程)
|
||||
```
|
||||
|
||||
## 🚀 执行步骤
|
||||
|
||||
### 步骤1: 准备环境
|
||||
|
||||
```bash
|
||||
# 1. 创建必要的目录
|
||||
mkdir -p backup logs scripts monitor
|
||||
|
||||
# 2. 设置目录权限
|
||||
chmod 755 backup logs scripts monitor
|
||||
```
|
||||
|
||||
### 步骤2: 修改配置
|
||||
|
||||
```bash
|
||||
# 编辑配置文件
|
||||
nano docker-compose-mysql-backup.yml
|
||||
|
||||
# 或者使用 vim
|
||||
vim docker-compose-mysql-backup.yml
|
||||
```
|
||||
|
||||
**重要**: 请将以下配置修改为你的实际信息:
|
||||
- `MYSQL_HOST`: 你的MySQL服务器地址
|
||||
- `MYSQL_PORT`: MySQL端口 (通常是3306)
|
||||
- `MYSQL_USER`: 备份用户账号
|
||||
- `MYSQL_PASSWORD`: 备份用户密码
|
||||
|
||||
### 步骤3: 启动备份服务
|
||||
|
||||
```bash
|
||||
# 启动备份服务
|
||||
docker-compose -f docker-compose-mysql-backup.yml up -d
|
||||
|
||||
# 查看服务状态
|
||||
docker-compose -f docker-compose-mysql-backup.yml ps
|
||||
```
|
||||
|
||||
### 步骤4: 验证备份
|
||||
|
||||
```bash
|
||||
# 查看备份日志
|
||||
docker-compose -f docker-compose-mysql-backup.yml logs -f mysql-backup
|
||||
|
||||
# 查看备份文件
|
||||
ls -la backup/
|
||||
|
||||
# 手动触发备份 (可选)
|
||||
docker-compose -f docker-compose-mysql-backup.yml exec mysql-backup /scripts/backup.sh
|
||||
```
|
||||
|
||||
### 步骤5: 访问监控界面
|
||||
|
||||
```bash
|
||||
# 访问监控界面
|
||||
open http://localhost:8080
|
||||
# 或者
|
||||
curl http://localhost:8080
|
||||
```
|
||||
|
||||
## 📊 备份时间配置
|
||||
|
||||
### 常用时间配置
|
||||
|
||||
```bash
|
||||
# 每天凌晨2点备份
|
||||
BACKUP_SCHEDULE: "0 2 * * *"
|
||||
|
||||
# 每6小时备份一次
|
||||
BACKUP_SCHEDULE: "0 */6 * * *"
|
||||
|
||||
# 每周日凌晨2点备份
|
||||
BACKUP_SCHEDULE: "0 2 * * 0"
|
||||
|
||||
# 每月1日凌晨2点备份
|
||||
BACKUP_SCHEDULE: "0 2 1 * *"
|
||||
|
||||
# 每天上午8点和晚上8点备份
|
||||
BACKUP_SCHEDULE: "0 8,20 * * *"
|
||||
```
|
||||
|
||||
### 时间格式说明
|
||||
|
||||
```
|
||||
# crontab 格式: 分 时 日 月 周
|
||||
# 分: 0-59
|
||||
# 时: 0-23
|
||||
# 日: 1-31
|
||||
# 月: 1-12
|
||||
# 周: 0-7 (0和7都表示周日)
|
||||
```
|
||||
|
||||
## 🔍 故障排除
|
||||
|
||||
### 常见问题
|
||||
|
||||
#### 1. 连接失败
|
||||
```bash
|
||||
# 检查网络连接
|
||||
ping your-mysql-server.com
|
||||
|
||||
# 检查端口是否开放
|
||||
telnet your-mysql-server.com 3306
|
||||
|
||||
# 查看详细错误日志
|
||||
docker-compose -f docker-compose-mysql-backup.yml logs mysql-backup
|
||||
```
|
||||
|
||||
#### 2. 权限问题
|
||||
```bash
|
||||
# 检查目录权限
|
||||
ls -la backup/ logs/ scripts/
|
||||
|
||||
# 修复权限
|
||||
chmod 755 backup/ logs/ scripts/
|
||||
chown -R $USER:$USER backup/ logs/ scripts/
|
||||
```
|
||||
|
||||
#### 3. 备份失败
|
||||
```bash
|
||||
# 查看详细日志
|
||||
docker-compose -f docker-compose-mysql-backup.yml logs mysql-backup
|
||||
|
||||
# 手动测试连接
|
||||
docker-compose -f docker-compose-mysql-backup.yml exec mysql-backup \
|
||||
mysql -h your-mysql-server.com -P 3306 -u backup_user -p
|
||||
```
|
||||
|
||||
### 日志分析
|
||||
|
||||
```bash
|
||||
# 实时查看日志
|
||||
docker-compose -f docker-compose-mysql-backup.yml logs -f mysql-backup
|
||||
|
||||
# 查看最近的日志
|
||||
docker-compose -f docker-compose-mysql-backup.yml logs --tail=100 mysql-backup
|
||||
|
||||
# 查看特定时间的日志
|
||||
docker-compose -f docker-compose-mysql-backup.yml logs --since="2024-01-15T00:00:00" mysql-backup
|
||||
```
|
||||
|
||||
## 📁 备份文件结构
|
||||
|
||||
```
|
||||
backup/
|
||||
├── full/ # 全量备份目录
|
||||
│ ├── 20240115_020000/ # 按时间戳命名的备份目录
|
||||
│ │ └── backup.tar.gz # 压缩的备份文件
|
||||
│ └── 20240116_020000/
|
||||
│ └── backup.tar.gz
|
||||
└── incremental/ # 增量备份目录
|
||||
├── 20240115_140000/
|
||||
│ └── backup.tar.gz
|
||||
└── 20240115_200000/
|
||||
└── backup.tar.gz
|
||||
```
|
||||
|
||||
## 🔧 高级配置
|
||||
|
||||
### 自定义备份脚本
|
||||
|
||||
```bash
|
||||
# 创建自定义备份脚本
|
||||
cat > scripts/custom-backup.sh << 'EOF'
|
||||
#!/bin/bash
|
||||
# 自定义备份逻辑
|
||||
echo "执行自定义备份..."
|
||||
# 在这里添加你的自定义逻辑
|
||||
EOF
|
||||
|
||||
chmod +x scripts/custom-backup.sh
|
||||
```
|
||||
|
||||
### 备份到云存储
|
||||
|
||||
```bash
|
||||
# 安装云存储工具
|
||||
docker-compose -f docker-compose-mysql-backup.yml exec mysql-backup \
|
||||
apt-get update && apt-get install -y awscli
|
||||
|
||||
# 配置云存储
|
||||
docker-compose -f docker-compose-mysql-backup.yml exec mysql-backup \
|
||||
aws configure
|
||||
```
|
||||
|
||||
## 📞 支持
|
||||
|
||||
如果遇到问题,请检查:
|
||||
|
||||
1. **网络连接**: 确保可以访问MySQL服务器
|
||||
2. **用户权限**: 确保备份用户有足够权限
|
||||
3. **磁盘空间**: 确保有足够的存储空间
|
||||
4. **日志文件**: 查看详细的错误日志
|
||||
|
||||
## 🎯 总结
|
||||
|
||||
这个配置提供了:
|
||||
|
||||
- ✅ **自动备份**: 定时自动执行备份
|
||||
- ✅ **MySQL 5.7 支持**: 使用兼容的Percona XtraBackup 2.4
|
||||
- ✅ **压缩备份**: 节省存储空间
|
||||
- ✅ **自动清理**: 自动删除旧备份
|
||||
- ✅ **监控界面**: Web界面查看备份状态
|
||||
- ✅ **详细日志**: 完整的备份日志记录
|
||||
- ✅ **错误处理**: 完善的错误检测和处理
|
||||
|
||||
按照上述步骤配置后,你的MySQL 5.7数据库将自动进行定时备份!
|
||||
@ -1,164 +0,0 @@
|
||||
# Ping延迟测试逻辑确认
|
||||
|
||||
## 🎯 用户需求确认
|
||||
|
||||
**用户明确需求**:
|
||||
1. **连接后的测速逻辑**: 保持不变,使用 SingBox 通过代理测试
|
||||
2. **没连接前的测速逻辑**:
|
||||
- 从接口获取节点信息
|
||||
- 如果信息包含 `ip:端口` 格式,则只取 IP 部分
|
||||
- 使用本机网络直接 ping 这个 IP 获取延迟
|
||||
- 将 ping 的延迟作为节点延迟显示
|
||||
|
||||
## 📋 当前实现逻辑
|
||||
|
||||
### **1. 连接状态判断**
|
||||
|
||||
#### **主测试方法**: `kr_urlTest()`
|
||||
```dart
|
||||
if (kr_isConnected.value) {
|
||||
// ✅ 连接后:保持默认测试规则,使用 SingBox 通过代理测试
|
||||
KRLogUtil.kr_i('🔗 已连接状态 - 使用 SingBox 通过代理测试延迟', tag: 'HomeController');
|
||||
await KRSingBoxImp.instance.kr_urlTest("select");
|
||||
// 等待 SingBox 完成测试并获取结果
|
||||
} else {
|
||||
// ✅ 没连接前:使用本机网络直接ping节点IP
|
||||
KRLogUtil.kr_i('🔌 未连接状态 - 使用本机网络直接ping节点IP测试延迟', tag: 'HomeController');
|
||||
await _kr_testLatencyWithoutVpn();
|
||||
}
|
||||
```
|
||||
|
||||
### **2. 没连接前的Ping测试逻辑**
|
||||
|
||||
#### **Ping测试方法**: `_kr_testSingleNode()`
|
||||
```dart
|
||||
/// 测试单个节点的延迟(使用本机网络直接ping节点IP)
|
||||
Future<void> _kr_testSingleNode(dynamic item) async {
|
||||
// 从接口获取的节点信息中提取IP地址
|
||||
String targetIp = item.serverAddr;
|
||||
|
||||
// 如果信息包含 ip:端口 格式,则只取IP部分
|
||||
if (targetIp.contains(':')) {
|
||||
final parts = targetIp.split(':');
|
||||
if (parts.length == 2) {
|
||||
targetIp = parts[0];
|
||||
KRLogUtil.kr_i('📌 从 ip:端口 格式中提取IP: $targetIp', tag: 'NodeTest');
|
||||
}
|
||||
}
|
||||
|
||||
KRLogUtil.kr_i('🎯 目标IP地址: $targetIp', tag: 'NodeTest');
|
||||
KRLogUtil.kr_i('🔌 使用本机网络直接ping IP地址(绕过代理)', tag: 'NodeTest');
|
||||
|
||||
// 使用本机网络直接ping IP地址测试延迟
|
||||
final socket = await Socket.connect(
|
||||
targetIp,
|
||||
80, // 使用80端口进行ping测试
|
||||
timeout: const Duration(seconds: 5), // 5秒超时
|
||||
);
|
||||
|
||||
// 获取延迟时间
|
||||
final delay = stopwatch.elapsedMilliseconds;
|
||||
|
||||
// 使用ping的延迟结果作为节点延迟
|
||||
item.urlTestDelay.value = delay;
|
||||
KRLogUtil.kr_i('✅ 节点 ${item.tag} ping测试成功: ${delay}ms', tag: 'NodeTest');
|
||||
}
|
||||
```
|
||||
|
||||
## ✅ 逻辑确认
|
||||
|
||||
### **连接后(kr_isConnected.value = true)**:
|
||||
1. **保持默认测试规则**: 使用 `KRSingBoxImp.instance.kr_urlTest("select")`
|
||||
2. **通过代理测试**: 使用 SingBox 的 URL 测试功能
|
||||
3. **等待测试完成**: 等待3秒让 SingBox 完成测试
|
||||
4. **获取测试结果**: 从 `KRSingBoxImp.instance.kr_activeGroups` 获取延迟信息
|
||||
|
||||
### **没连接前(kr_isConnected.value = false)**:
|
||||
1. **从接口获取节点信息**: 使用 `item.serverAddr`
|
||||
2. **提取IP地址**: 如果包含 `ip:端口` 格式,只取IP部分
|
||||
3. **使用本机网络ping**: 使用 `Socket.connect()` 直接连接IP的80端口
|
||||
4. **获取ping延迟**: 测量连接建立的时间作为延迟
|
||||
5. **显示延迟结果**: 将ping延迟作为节点延迟显示
|
||||
|
||||
## 🔍 关键实现点
|
||||
|
||||
### **IP地址提取逻辑**:
|
||||
```dart
|
||||
// 从接口获取的节点信息中提取IP地址
|
||||
String targetIp = item.serverAddr;
|
||||
|
||||
// 如果信息包含 ip:端口 格式,则只取IP部分
|
||||
if (targetIp.contains(':')) {
|
||||
final parts = targetIp.split(':');
|
||||
if (parts.length == 2) {
|
||||
targetIp = parts[0]; // 只取IP部分
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### **Ping测试实现**:
|
||||
```dart
|
||||
// 使用Socket连接测试ping延迟(模拟ping)
|
||||
final socket = await Socket.connect(
|
||||
targetIp,
|
||||
80, // 使用80端口进行ping测试
|
||||
timeout: const Duration(seconds: 5), // 5秒超时
|
||||
);
|
||||
|
||||
// 获取延迟时间
|
||||
final delay = stopwatch.elapsedMilliseconds;
|
||||
|
||||
// 使用ping的延迟结果作为节点延迟
|
||||
item.urlTestDelay.value = delay;
|
||||
```
|
||||
|
||||
## 📊 测试场景
|
||||
|
||||
### **测试场景1: 连接代理时**
|
||||
- **预期行为**: 使用 SingBox 通过代理测试(保持默认规则)
|
||||
- **验证日志**: `🔗 已连接状态 - 使用 SingBox 通过代理测试延迟`
|
||||
- **测试方式**: `KRSingBoxImp.instance.kr_urlTest("select")`
|
||||
|
||||
### **测试场景2: 没连接时**
|
||||
- **预期行为**: 使用本机网络直接ping节点IP
|
||||
- **验证日志**: `🔌 未连接状态 - 使用本机网络直接ping节点IP测试延迟`
|
||||
- **IP提取**: `📌 从 ip:端口 格式中提取IP: XXX.XXX.XXX.XXX`
|
||||
- **Ping测试**: `🎯 目标IP地址: XXX.XXX.XXX.XXX`
|
||||
- **测试方式**: `Socket.connect(targetIp, 80)` 模拟ping
|
||||
|
||||
## 🔍 关键日志点
|
||||
|
||||
### **IP提取**:
|
||||
- `📌 从 ip:端口 格式中提取IP: XXX.XXX.XXX.XXX`
|
||||
- `🎯 目标IP地址: XXX.XXX.XXX.XXX`
|
||||
|
||||
### **Ping测试**:
|
||||
- `🔌 使用本机网络直接ping IP地址(绕过代理)`
|
||||
- `⏱️ 开始ping测试...`
|
||||
- `⏱️ ping延迟: XXXms`
|
||||
- `✅ 节点 XXX ping测试成功: XXXms`
|
||||
|
||||
### **错误处理**:
|
||||
- `⏰ 节点 XXX ping超时`
|
||||
- `🚫 节点 XXX ping被拒绝`
|
||||
- `🌐 节点 XXX 网络不可达`
|
||||
|
||||
## 📝 总结
|
||||
|
||||
**✅ 当前实现完全符合用户需求**:
|
||||
|
||||
1. **连接后**: 保持默认测试规则,使用 SingBox 通过代理测试延迟
|
||||
2. **没连接前**:
|
||||
- 从接口获取节点信息
|
||||
- 如果包含 `ip:端口` 格式,只取IP部分
|
||||
- 使用本机网络直接ping IP地址
|
||||
- 将ping延迟作为节点延迟显示
|
||||
|
||||
**🔧 实现特点**:
|
||||
- 自动根据连接状态选择测试方式
|
||||
- 智能提取IP地址(处理ip:端口格式)
|
||||
- 使用80端口进行ping测试(更稳定)
|
||||
- 详细的日志记录,便于调试
|
||||
- 完善的错误处理和超时机制
|
||||
|
||||
**🎯 用户需求已完全实现!**
|
||||
141
README.md
141
README.md
@ -1,141 +0,0 @@
|
||||
# OmnTech - Instant Cloud Services
|
||||
|
||||
## Hi there 👋
|
||||
|
||||
Welcome to **OmnTech**, where innovation meets freedom in the cloud computing space!
|
||||
|
||||
### 🌟 About Us
|
||||
|
||||
We are a passionate team of technology enthusiasts at **OmnTech**, a cutting-edge technology company specializing in **instant cloud services**. Our mission is to deliver lightning-fast, reliable, and scalable cloud solutions that empower businesses and individuals worldwide.
|
||||
|
||||
### 🌍 Our Locations
|
||||
|
||||
- **Headquarters**: Tallinn, Estonia 🇪🇪
|
||||
- **US Office**: San Jose, California 🇺🇸
|
||||
|
||||
### 💻 Our Culture
|
||||
|
||||
We are a team of **technology lovers** and **freedom seekers** who believe in the power of remote work. Our distributed workforce spans across different time zones, bringing together diverse perspectives and innovative ideas. We embrace the flexibility of remote collaboration while maintaining the highest standards of technical excellence.
|
||||
|
||||
### 🚀 What We Do
|
||||
|
||||
**OmnTech** specializes in:
|
||||
|
||||
- **Instant Cloud Services** - Rapid deployment and scaling solutions
|
||||
- **Real-time Infrastructure** - Low-latency cloud computing platforms
|
||||
- **Global Network Solutions** - Worldwide connectivity and optimization
|
||||
- **Developer Tools** - APIs and SDKs for seamless integration
|
||||
- **Enterprise Solutions** - Custom cloud architectures for businesses
|
||||
|
||||
### 🌈 How to Get Involved
|
||||
|
||||
We welcome contributions from the global developer community! Here's how you can get involved:
|
||||
|
||||
- **Open Source Projects** - Contribute to our public repositories
|
||||
- **Documentation** - Help improve our technical documentation
|
||||
- **Bug Reports** - Report issues and help us improve
|
||||
- **Feature Requests** - Suggest new features and improvements
|
||||
- **Community Discussions** - Join our technical discussions
|
||||
|
||||
### 👩💻 Useful Resources
|
||||
|
||||
- **Documentation**: [docs.omntech.com](https://docs.omntech.com)
|
||||
- **API Reference**: [api.omntech.com](https://api.omntech.com)
|
||||
- **Community Forum**: [community.omntech.com](https://community.omntech.com)
|
||||
- **Support**: [support@omntech.com](mailto:support@omntech.com)
|
||||
|
||||
### 🍿 Fun Facts About Our Team
|
||||
|
||||
- **Breakfast of Champions**: Our remote team enjoys everything from traditional Estonian black bread to California avocado toast
|
||||
- **Coffee Culture**: We have a virtual coffee break every day at 3 PM EST
|
||||
- **Global Perspectives**: Our team speaks 12+ languages fluently
|
||||
- **Innovation Time**: Every Friday is dedicated to personal projects and innovation
|
||||
- **Remote First**: We've been remote-first since day one, long before it became mainstream
|
||||
|
||||
### 🧙 Our Philosophy
|
||||
|
||||
We believe that **technology should serve humanity**, not the other way around. Our commitment to freedom, innovation, and excellence drives everything we do. We're not just building cloud services – we're building the future of how people work, collaborate, and create.
|
||||
|
||||
### 📞 Contact Us
|
||||
|
||||
- **Website**: [omntech.com](https://omntech.com)
|
||||
- **Email**: [hello@omntech.com](mailto:hello@omntech.com)
|
||||
- **LinkedIn**: [OmnTech](https://linkedin.com/company/omntech)
|
||||
- **Twitter**: [@OmnTech](https://twitter.com/omntech)
|
||||
|
||||
---
|
||||
|
||||
*Remember, you can do mighty things with the power of [Markdown](https://docs.github.com/github/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax) and the right team!*
|
||||
|
||||
---
|
||||
|
||||
## 中文翻译
|
||||
|
||||
# OmnTech - 即时云服务
|
||||
|
||||
## 你好 👋
|
||||
|
||||
欢迎来到 **OmnTech**,在这里创新与自由在云计算领域相遇!
|
||||
|
||||
### 🌟 关于我们
|
||||
|
||||
我们是 **OmnTech** 充满激情的科技爱好者团队,这是一家专注于**即时云服务**的前沿科技公司。我们的使命是为全球企业和个人提供闪电般快速、可靠且可扩展的云解决方案。
|
||||
|
||||
### 🌍 我们的办公地点
|
||||
|
||||
- **总部**: 爱沙尼亚塔林 🇪🇪
|
||||
- **美国办公室**: 加利福尼亚圣何塞 🇺🇸
|
||||
|
||||
### 💻 我们的文化
|
||||
|
||||
我们是一群**技术爱好者**和**自由追求者**,相信远程工作的力量。我们的分布式团队跨越不同时区,汇聚了多样化的观点和创新理念。我们拥抱远程协作的灵活性,同时保持最高的技术卓越标准。
|
||||
|
||||
### 🚀 我们的业务
|
||||
|
||||
**OmnTech** 专注于:
|
||||
|
||||
- **即时云服务** - 快速部署和扩展解决方案
|
||||
- **实时基础设施** - 低延迟云计算平台
|
||||
- **全球网络解决方案** - 全球连接和优化
|
||||
- **开发者工具** - 无缝集成的API和SDK
|
||||
- **企业解决方案** - 定制化云架构
|
||||
|
||||
### 🌈 如何参与
|
||||
|
||||
我们欢迎全球开发者社区的贡献!以下是您可以参与的方式:
|
||||
|
||||
- **开源项目** - 为我们的公共仓库做出贡献
|
||||
- **文档** - 帮助改进我们的技术文档
|
||||
- **错误报告** - 报告问题并帮助我们改进
|
||||
- **功能请求** - 建议新功能和改进
|
||||
- **社区讨论** - 加入我们的技术讨论
|
||||
|
||||
### 👩💻 有用资源
|
||||
|
||||
- **文档**: [docs.omntech.com](https://docs.omntech.com)
|
||||
- **API参考**: [api.omntech.com](https://api.omntech.com)
|
||||
- **社区论坛**: [community.omntech.com](https://community.omntech.com)
|
||||
- **支持**: [support@omntech.com](mailto:support@omntech.com)
|
||||
|
||||
### 🍿 关于我们团队的有趣事实
|
||||
|
||||
- **冠军早餐**: 我们的远程团队享受从传统爱沙尼亚黑面包到加州鳄梨吐司的一切
|
||||
- **咖啡文化**: 我们每天下午3点EST都有虚拟咖啡时间
|
||||
- **全球视野**: 我们的团队流利掌握12+种语言
|
||||
- **创新时间**: 每个周五都致力于个人项目和创新
|
||||
- **远程优先**: 我们从第一天起就是远程优先,远在它成为主流之前
|
||||
|
||||
### 🧙 我们的理念
|
||||
|
||||
我们相信**技术应该为人类服务**,而不是相反。我们对自由、创新和卓越的承诺驱动着我们所做的一切。我们不仅仅是在构建云服务——我们正在构建人们工作、协作和创造未来的方式。
|
||||
|
||||
### 📞 联系我们
|
||||
|
||||
- **网站**: [omntech.com](https://omntech.com)
|
||||
- **邮箱**: [hello@omntech.com](mailto:hello@omntech.com)
|
||||
- **LinkedIn**: [OmnTech](https://linkedin.com/company/omntech)
|
||||
- **Twitter**: [@OmnTech](https://twitter.com/omntech)
|
||||
|
||||
---
|
||||
|
||||
*记住,有了[Markdown](https://docs.github.com/github/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax)的力量和正确的团队,你可以做强大的事情!*
|
||||
@ -1,97 +0,0 @@
|
||||
# SingBox 节点超时问题分析
|
||||
|
||||
## 🔍 问题分析
|
||||
|
||||
### **核心问题**
|
||||
从日志分析发现,SingBox 的 URL 测试功能正在工作,但是**测试失败**,导致所有节点显示超时(`delay=65535`)。
|
||||
|
||||
### **关键日志证据**
|
||||
```
|
||||
flutter: 👻 16:40:26.497617 INFO SingBox - 📡 收到活动组更新,数量: 2
|
||||
flutter: 👻 16:40:26.497808 INFO KRLogUtil - 处理活动组: [SingboxOutboundGroup(tag: select, type: ProxyType.selector, selected: auto, items: [SingboxOutboundGroupItem(tag: auto, type: ProxyType.urltest, urlTestDelay: 65535)]), SingboxOutboundGroup(tag: auto, type: ProxyType.urltest, selected: 香港, items: [SingboxOutboundGroupItem(tag: 香港, type: ProxyType.trojan, urlTestDelay: 65535)])]
|
||||
```
|
||||
|
||||
**延迟值从 `0` 变成了 `65535`**,说明:
|
||||
1. ✅ SingBox 的 URL 测试功能正在工作
|
||||
2. ❌ 但是测试失败了,返回超时值 `65535`
|
||||
|
||||
### **问题原因**
|
||||
**SingBox 无法通过代理访问测试 URL** `http://connectivitycheck.gstatic.com/generate_204`
|
||||
|
||||
这是一个经典的"鸡生蛋,蛋生鸡"问题:
|
||||
- SingBox 需要通过代理测试节点延迟
|
||||
- 但是代理本身可能无法访问外部测试 URL
|
||||
- 导致所有节点测试失败,显示超时
|
||||
|
||||
## 🛠️ 解决方案
|
||||
|
||||
### 1. **修改测试 URL**
|
||||
已将测试 URL 从 `http://connectivitycheck.gstatic.com/generate_204` 改为 `http://www.gstatic.com/generate_204`
|
||||
|
||||
### 2. **添加备用测试方法**
|
||||
- `kr_manualUrlTest()` - 手动触发 SingBox URL 测试
|
||||
- `kr_forceDirectTest()` - 强制使用直接连接测试(绕过 SingBox URL 测试)
|
||||
|
||||
### 3. **可能的其他解决方案**
|
||||
|
||||
#### A. **使用本地测试 URL**
|
||||
```dart
|
||||
"connection-test-url": "http://127.0.0.1:8080/test"
|
||||
```
|
||||
|
||||
#### B. **禁用 URL 测试**
|
||||
```dart
|
||||
"url-test-interval": 0 // 禁用自动测试
|
||||
```
|
||||
|
||||
#### C. **使用直接连接测试**
|
||||
在应用层面实现延迟测试,不依赖 SingBox 的 URL 测试功能。
|
||||
|
||||
## 🧪 测试步骤
|
||||
|
||||
### 1. **测试新的 URL**
|
||||
```bash
|
||||
curl -I "http://www.gstatic.com/generate_204"
|
||||
```
|
||||
|
||||
### 2. **手动触发测试**
|
||||
在应用中调用:
|
||||
```dart
|
||||
await homeController.kr_manualUrlTest();
|
||||
```
|
||||
|
||||
### 3. **使用直接连接测试**
|
||||
```dart
|
||||
await homeController.kr_forceDirectTest();
|
||||
```
|
||||
|
||||
## 📊 预期结果
|
||||
|
||||
如果问题解决,应该看到:
|
||||
```
|
||||
└─ 节点[0]: tag=auto, type=ProxyType.urltest, delay=150
|
||||
└─ 节点[0]: tag=香港, type=ProxyType.trojan, delay=200
|
||||
```
|
||||
|
||||
延迟值应该是实际的毫秒数,而不是 0 或 65535。
|
||||
|
||||
## 🔧 下一步调试
|
||||
|
||||
1. **重新运行应用**,观察新的测试 URL 是否有效
|
||||
2. **如果仍然超时**,尝试使用直接连接测试
|
||||
3. **考虑禁用 SingBox 的 URL 测试**,完全依赖应用层面的延迟测试
|
||||
|
||||
## 📝 关键文件
|
||||
|
||||
- `lib/app/services/singbox_imp/kr_sing_box_imp.dart` - SingBox 配置
|
||||
- `lib/app/modules/kr_home/controllers/kr_home_controller.dart` - 延迟测试逻辑
|
||||
- `lib/app/modules/kr_home/controllers/kr_home_controller.dart` - 直接连接测试
|
||||
|
||||
## 💡 根本解决方案
|
||||
|
||||
**最佳解决方案**是使用应用层面的直接连接测试,而不是依赖 SingBox 的 URL 测试功能。这样可以:
|
||||
|
||||
1. 避免代理环境下的测试问题
|
||||
2. 提供更准确的延迟测量
|
||||
3. 更好的用户体验
|
||||
4. 更稳定的测试结果
|
||||
@ -1,98 +0,0 @@
|
||||
# SingBox URL 测试调试分析
|
||||
|
||||
## 🔍 问题分析
|
||||
|
||||
从日志分析发现:
|
||||
|
||||
### 1. **配置已正确更新** ✅
|
||||
```
|
||||
URLTestOptions:{ConnectionTestUrl:http://connectivitycheck.gstatic.com/generate_204 URLTestInterval:30}
|
||||
```
|
||||
- ✅ 测试 URL: `http://connectivitycheck.gstatic.com/generate_204`
|
||||
- ✅ 测试间隔: 30 秒
|
||||
|
||||
### 2. **核心问题:节点延迟始终为 0** ❌
|
||||
```
|
||||
└─ 节点[0]: tag=auto, type=ProxyType.urltest, delay=0
|
||||
└─ 节点[0]: tag=香港, type=ProxyType.trojan, delay=0
|
||||
```
|
||||
|
||||
**问题原因**:SingBox 的 URL 测试功能没有正常工作,导致所有节点的延迟值始终为 0。
|
||||
|
||||
### 3. **活动组更新过于频繁** ⚠️
|
||||
日志显示活动组几乎每秒都在更新,这可能导致性能问题。
|
||||
|
||||
## 🛠️ 解决方案
|
||||
|
||||
### 1. **添加手动 URL 测试功能**
|
||||
- 新增 `kr_manualUrlTest()` 方法用于调试
|
||||
- 直接调用 SingBox 的 URL 测试 API
|
||||
- 等待测试完成并检查结果
|
||||
|
||||
### 2. **增强调试信息**
|
||||
- 在 `kr_urlTest()` 中添加详细的测试过程日志
|
||||
- 测试前后对比活动组状态
|
||||
- 显示连接状态和测试方法
|
||||
|
||||
### 3. **可能的问题原因**
|
||||
|
||||
#### A. **SingBox 配置问题**
|
||||
- URL 测试功能可能没有正确启用
|
||||
- 测试 URL 可能无法访问
|
||||
- 测试间隔设置可能有问题
|
||||
|
||||
#### B. **API 调用问题**
|
||||
- `urlTest()` 方法可能没有正确调用
|
||||
- 原生库的 URL 测试功能可能有问题
|
||||
- 测试结果可能没有正确返回
|
||||
|
||||
#### C. **网络问题**
|
||||
- 测试 URL 可能被防火墙阻止
|
||||
- 网络连接可能有问题
|
||||
- DNS 解析可能有问题
|
||||
|
||||
## 🧪 调试步骤
|
||||
|
||||
### 1. **手动触发 URL 测试**
|
||||
```dart
|
||||
// 在应用中调用
|
||||
await homeController.kr_manualUrlTest();
|
||||
```
|
||||
|
||||
### 2. **检查 SingBox 日志**
|
||||
查看 SingBox 的日志文件,确认是否有 URL 测试相关的日志。
|
||||
|
||||
### 3. **验证测试 URL**
|
||||
```bash
|
||||
curl -I "http://connectivitycheck.gstatic.com/generate_204"
|
||||
```
|
||||
|
||||
### 4. **检查网络连接**
|
||||
```bash
|
||||
ping connectivitycheck.gstatic.com
|
||||
nslookup connectivitycheck.gstatic.com
|
||||
```
|
||||
|
||||
## 📊 预期结果
|
||||
|
||||
如果 URL 测试正常工作,应该看到:
|
||||
```
|
||||
└─ 节点[0]: tag=auto, type=ProxyType.urltest, delay=150
|
||||
└─ 节点[0]: tag=香港, type=ProxyType.trojan, delay=200
|
||||
```
|
||||
|
||||
延迟值应该是实际的毫秒数,而不是 0 或 65535。
|
||||
|
||||
## 🔧 下一步调试
|
||||
|
||||
1. **运行应用并手动触发 URL 测试**
|
||||
2. **观察新的调试日志**
|
||||
3. **检查 SingBox 原生日志**
|
||||
4. **验证网络连接**
|
||||
5. **如果问题持续,考虑使用直接连接测试作为备选方案**
|
||||
|
||||
## 📝 关键文件
|
||||
|
||||
- `lib/app/modules/kr_home/controllers/kr_home_controller.dart` - 添加了手动测试方法
|
||||
- `lib/app/services/singbox_imp/kr_sing_box_imp.dart` - SingBox 配置和 URL 测试
|
||||
- `lib/singbox/service/ffi_singbox_service.dart` - 原生库 URL 测试实现
|
||||
@ -1,142 +0,0 @@
|
||||
# 测速功能问题分析与修复
|
||||
|
||||
## 🔍 问题分析
|
||||
|
||||
### **用户配置策略** ✅ **完全正确**
|
||||
|
||||
你的 Trojan 配置策略是合理的:
|
||||
|
||||
```json
|
||||
{
|
||||
"server": "156.224.78.176",
|
||||
"server_name": "baidu.com", // ✅ 防 SNI 检测
|
||||
"tls": {
|
||||
"enabled": true,
|
||||
"insecure": true, // ✅ 允许自签证书
|
||||
"utls": {"enabled": true, "fingerprint": "chrome"}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**这个配置不会影响测速功能**,问题在于测速逻辑本身。
|
||||
|
||||
### **根本原因:测速逻辑设计缺陷** ❌
|
||||
|
||||
#### **未连接状态下的测速逻辑** ❌
|
||||
```dart
|
||||
// 原始代码:直接连接 Cloudflare
|
||||
final testSocket = await Socket.connect(
|
||||
'speed.cloudflare.com', // ❌ 问题:直接连接,没有通过代理
|
||||
443,
|
||||
timeout: const Duration(seconds: 3),
|
||||
);
|
||||
```
|
||||
|
||||
#### **已连接状态下的测速逻辑** ✅
|
||||
```dart
|
||||
// 通过 SingBox 代理测试
|
||||
await KRSingBoxImp.instance.kr_urlTest("select");
|
||||
```
|
||||
|
||||
### **问题详解**
|
||||
|
||||
1. **未连接时**:
|
||||
- 直接连接 `speed.cloudflare.com`
|
||||
- **没有通过代理节点**
|
||||
- 如果网络环境限制,会超时
|
||||
|
||||
2. **已连接时**:
|
||||
- 通过 SingBox 代理测试
|
||||
- **流量经过代理节点**
|
||||
- 可以正常访问测速服务器
|
||||
|
||||
## 🛠️ 修复方案
|
||||
|
||||
### **修复后的测速逻辑** ✅
|
||||
|
||||
```dart
|
||||
/// 测试单个节点的延迟
|
||||
Future<void> _kr_testSingleNode(dynamic item) async {
|
||||
try {
|
||||
// 解析地址和端口
|
||||
final uri = Uri.parse(item.serverAddr);
|
||||
final address = uri.host.isEmpty ? item.serverAddr : uri.host;
|
||||
final port = uri.port > 0 ? uri.port : 443;
|
||||
|
||||
// 使用 Socket 测试到实际节点的 TCP 连接延迟
|
||||
final stopwatch = Stopwatch()..start();
|
||||
|
||||
final socket = await Socket.connect(
|
||||
address,
|
||||
port,
|
||||
timeout: const Duration(seconds: 5), // 增加超时时间
|
||||
);
|
||||
stopwatch.stop();
|
||||
|
||||
// 获取延迟时间
|
||||
final delay = stopwatch.elapsedMilliseconds;
|
||||
|
||||
// 关闭连接
|
||||
await socket.close();
|
||||
|
||||
// 如果延迟超过3秒,认为节点不可用
|
||||
if (delay > 3000) {
|
||||
item.urlTestDelay.value = 65535;
|
||||
} else {
|
||||
// 直接使用连接延迟,不再进行二次测试
|
||||
item.urlTestDelay.value = delay;
|
||||
}
|
||||
} catch (e) {
|
||||
item.urlTestDelay.value = 65535;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### **修复要点**
|
||||
|
||||
1. **移除二次测试** - 不再连接 `speed.cloudflare.com`
|
||||
2. **增加超时时间** - 从 3 秒增加到 5 秒
|
||||
3. **简化逻辑** - 直接使用节点连接延迟
|
||||
4. **提高阈值** - 从 2 秒提高到 3 秒
|
||||
|
||||
## 📊 修复效果
|
||||
|
||||
### **修复前** ❌
|
||||
- 未连接时:测速超时(直接连接 Cloudflare 失败)
|
||||
- 已连接时:测速正常(通过代理连接)
|
||||
|
||||
### **修复后** ✅
|
||||
- 未连接时:测速正常(直接测试节点连接延迟)
|
||||
- 已连接时:测速正常(通过代理测试)
|
||||
|
||||
## 🧪 测试步骤
|
||||
|
||||
1. **重新运行应用**
|
||||
2. **在未连接状态下测试延迟** - 应该能正常显示延迟值
|
||||
3. **连接节点后测试延迟** - 应该能正常显示延迟值
|
||||
4. **对比两种状态下的延迟** - 应该都能正常工作
|
||||
|
||||
## 💡 关键要点
|
||||
|
||||
1. **你的 Trojan 配置是正确的** - 防 SNI 检测策略有效
|
||||
2. **问题在于测速逻辑** - 不是配置问题
|
||||
3. **修复后两种状态都能测速** - 解决了根本问题
|
||||
4. **延迟测试更准确** - 直接测试节点连接延迟
|
||||
|
||||
## 🔧 配置建议
|
||||
|
||||
你的当前配置策略很好,建议保持:
|
||||
|
||||
```json
|
||||
{
|
||||
"server_name": "baidu.com", // 防 SNI 检测
|
||||
"tls": {
|
||||
"insecure": true, // 允许自签证书
|
||||
"utls": {"enabled": true, "fingerprint": "chrome"}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
这个配置能有效防止 GFW 的 SNI 检测和流量分析。
|
||||
|
||||
修复后,你的测速功能应该能在任何状态下正常工作了!
|
||||
@ -1,134 +0,0 @@
|
||||
# Trojan 配置中 server_name 参数修复
|
||||
|
||||
## 🔍 问题分析
|
||||
|
||||
### **原始问题**
|
||||
你的 Trojan 配置中存在 `server_name` 设置错误:
|
||||
|
||||
```json
|
||||
{
|
||||
"server": "156.224.78.176",
|
||||
"server_name": "baidu.com" // ❌ 错误:服务器 IP 与 SNI 不匹配
|
||||
}
|
||||
```
|
||||
|
||||
### **问题原因**
|
||||
1. **TLS 握手失败** - 服务器没有为 `baidu.com` 配置证书
|
||||
2. **SNI 不匹配** - 客户端请求 `baidu.com`,但服务器只支持 IP 地址
|
||||
3. **代理无法工作** - TLS 验证失败导致连接中断
|
||||
|
||||
## 🛠️ 修复方案
|
||||
|
||||
### **智能 server_name 设置**
|
||||
已修改配置生成逻辑,现在会:
|
||||
|
||||
1. **优先使用配置的 SNI** - 如果服务器配置了 `sni` 参数
|
||||
2. **回退到服务器地址** - 如果没有配置 SNI,使用服务器 IP/域名
|
||||
3. **避免不匹配** - 确保 `server_name` 与服务器实际配置一致
|
||||
|
||||
### **修复后的逻辑**
|
||||
```dart
|
||||
// 智能设置 server_name
|
||||
String serverName = securityConfig["sni"] ?? "";
|
||||
if (serverName.isEmpty) {
|
||||
// 如果没有配置 SNI,使用服务器地址
|
||||
serverName = nodeListItem.serverAddr;
|
||||
}
|
||||
```
|
||||
|
||||
### **修复后的配置**
|
||||
```json
|
||||
{
|
||||
"server": "156.224.78.176",
|
||||
"server_name": "156.224.78.176" // ✅ 正确:使用服务器 IP
|
||||
}
|
||||
```
|
||||
|
||||
## 📋 server_name 参数说明
|
||||
|
||||
### **应该填什么值**
|
||||
|
||||
#### **1. 服务器实际域名** ✅ **最佳选择**
|
||||
```json
|
||||
{
|
||||
"server_name": "your-server-domain.com"
|
||||
}
|
||||
```
|
||||
|
||||
#### **2. 服务器 IP 地址** ✅ **推荐**
|
||||
```json
|
||||
{
|
||||
"server_name": "156.224.78.176"
|
||||
}
|
||||
```
|
||||
|
||||
#### **3. 空字符串** ✅ **某些情况下**
|
||||
```json
|
||||
{
|
||||
"server_name": ""
|
||||
}
|
||||
```
|
||||
|
||||
### **不应该填什么值**
|
||||
|
||||
#### **❌ 随机域名**
|
||||
```json
|
||||
{
|
||||
"server_name": "baidu.com" // 错误:服务器没有这个域名的证书
|
||||
}
|
||||
```
|
||||
|
||||
#### **❌ 不相关的域名**
|
||||
```json
|
||||
{
|
||||
"server_name": "google.com" // 错误:与服务器不匹配
|
||||
}
|
||||
```
|
||||
|
||||
## 🔧 其他协议修复
|
||||
|
||||
已同时修复了以下协议的 `server_name` 设置:
|
||||
|
||||
- **VLESS** - 智能 SNI 设置
|
||||
- **VMess** - 智能 SNI 设置
|
||||
- **Trojan** - 智能 SNI 设置
|
||||
|
||||
## 🧪 测试步骤
|
||||
|
||||
1. **重新运行应用**
|
||||
2. **检查新的配置** - 应该看到 `server_name` 使用服务器 IP
|
||||
3. **测试连接** - 应该能正常通过代理访问网络
|
||||
4. **验证延迟** - 延迟测试应该能正常工作
|
||||
|
||||
## 📊 预期结果
|
||||
|
||||
修复后应该看到:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "trojan",
|
||||
"tag": "香港",
|
||||
"server": "156.224.78.176",
|
||||
"server_port": 27639,
|
||||
"password": "cf6dc0d8-4997-4fc3-b790-1a54e38c6e8c",
|
||||
"tls": {
|
||||
"enabled": true,
|
||||
"server_name": "156.224.78.176", // ✅ 修复后
|
||||
"insecure": false,
|
||||
"utls": {
|
||||
"enabled": true,
|
||||
"fingerprint": "chrome"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 💡 关键要点
|
||||
|
||||
1. **`server_name` 必须与服务器配置匹配**
|
||||
2. **优先使用服务器实际域名**
|
||||
3. **IP 地址也是有效的选择**
|
||||
4. **避免使用不相关的域名**
|
||||
5. **TLS 验证失败会导致代理无法工作**
|
||||
|
||||
这个修复应该能解决你的 Trojan 连接问题!
|
||||
@ -32,12 +32,15 @@
|
||||
android:name="android.permission.QUERY_ALL_PACKAGES"
|
||||
tools:ignore="QueryAllPackagesPermission" />
|
||||
|
||||
<application
|
||||
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
|
||||
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
|
||||
<application
|
||||
android:name=".Application"
|
||||
android:banner="@mipmap/ic_banner"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="BearVPN"
|
||||
android:roundIcon="@mipmap/ic_launcher_round"
|
||||
android:extractNativeLibs="true"
|
||||
tools:targetApi="31">
|
||||
|
||||
<meta-data
|
||||
|
||||
@ -142,38 +142,42 @@ class BoxService(
|
||||
private var activeProfileName = ""
|
||||
private suspend fun startService(delayStart: Boolean = false) {
|
||||
try {
|
||||
Log.d(TAG, "starting service")
|
||||
// 暂时禁用通知显示
|
||||
// withContext(Dispatchers.Main) {
|
||||
// notification.show(activeProfileName, R.string.status_starting)
|
||||
// }
|
||||
Log.d(TAG, "🚀 [步骤1] 开始启动服务")
|
||||
|
||||
val selectedConfigPath = Settings.activeConfigPath
|
||||
Log.d(TAG, "📂 [步骤2] 配置路径: $selectedConfigPath")
|
||||
if (selectedConfigPath.isBlank()) {
|
||||
Log.e(TAG, "❌ [步骤2] 配置路径为空!")
|
||||
stopAndAlert(Alert.EmptyConfiguration)
|
||||
return
|
||||
}
|
||||
|
||||
activeProfileName = Settings.activeProfileName
|
||||
Log.d(TAG, "📝 [步骤3] Profile名称: $activeProfileName")
|
||||
|
||||
val configOptions = Settings.configOptions
|
||||
Log.d(TAG, "⚙️ [步骤4] 配置选项长度: ${configOptions.length}")
|
||||
if (configOptions.isBlank()) {
|
||||
Log.e(TAG, "❌ [步骤4] 配置选项为空!")
|
||||
stopAndAlert(Alert.EmptyConfiguration)
|
||||
return
|
||||
}
|
||||
|
||||
Log.d(TAG, "🔨 [步骤5] 开始构建配置...")
|
||||
val content = try {
|
||||
Mobile.buildConfig(selectedConfigPath, configOptions)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, e)
|
||||
Log.e(TAG, "❌ [步骤5] buildConfig失败: ${e.message}", e)
|
||||
Log.e(TAG, "❌ 异常类型: ${e.javaClass.name}")
|
||||
stopAndAlert(Alert.EmptyConfiguration)
|
||||
return
|
||||
}
|
||||
Log.d(TAG, "✅ [步骤5] 配置构建成功, 内容长度: ${content.length}")
|
||||
|
||||
if (Settings.debugMode) {
|
||||
File(workingDir, "current-config.json").writeText(content)
|
||||
}
|
||||
File(workingDir, "current-config.json").writeText(content)
|
||||
Log.d(TAG, "💾 [步骤6] 配置已保存")
|
||||
|
||||
Log.d(TAG, "🔔 [步骤7] 显示通知...")
|
||||
withContext(Dispatchers.Main) {
|
||||
notification.show(activeProfileName, R.string.status_starting)
|
||||
binder.broadcast {
|
||||
@ -181,31 +185,57 @@ class BoxService(
|
||||
}
|
||||
}
|
||||
|
||||
Log.d(TAG, "🌐 [步骤8] 启动网络监听...")
|
||||
DefaultNetworkMonitor.start()
|
||||
Libbox.registerLocalDNSTransport(LocalResolver)
|
||||
Libbox.setMemoryLimit(!Settings.disableMemoryLimit)
|
||||
Log.d(TAG, "✅ [步骤8] 网络监听已启动")
|
||||
|
||||
Log.d(TAG, "🎯 [步骤9] 调用 Libbox.newService()...")
|
||||
val newService = try {
|
||||
Libbox.newService(content, platformInterface)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "❌ [步骤9] Libbox.newService() 失败!")
|
||||
Log.e(TAG, "❌ 错误信息: ${e.message}")
|
||||
Log.e(TAG, "❌ 异常类型: ${e.javaClass.name}")
|
||||
Log.e(TAG, "❌ 堆栈跟踪: ${e.stackTraceToString()}")
|
||||
stopAndAlert(Alert.CreateService, e.message)
|
||||
return
|
||||
}
|
||||
Log.d(TAG, "✅ [步骤9] Libbox.newService() 成功!")
|
||||
|
||||
if (delayStart) {
|
||||
Log.d(TAG, "⏳ [步骤10] 延迟1秒...")
|
||||
delay(1000L)
|
||||
}
|
||||
|
||||
newService.start()
|
||||
Log.d(TAG, "▶️ [步骤11] 调用 newService.start()...")
|
||||
try {
|
||||
newService.start()
|
||||
Log.d(TAG, "✅ [步骤11] newService.start() 成功!")
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "❌ [步骤11] newService.start() 失败!")
|
||||
Log.e(TAG, "❌ 错误信息: ${e.message}")
|
||||
Log.e(TAG, "❌ 异常类型: ${e.javaClass.name}")
|
||||
Log.e(TAG, "❌ 堆栈跟踪: ${e.stackTraceToString()}")
|
||||
throw e
|
||||
}
|
||||
|
||||
boxService = newService
|
||||
commandServer?.setService(boxService)
|
||||
status.postValue(Status.Started)
|
||||
Log.d(TAG, "📊 [步骤12] 状态已设置为 Started")
|
||||
|
||||
withContext(Dispatchers.Main) {
|
||||
notification.show(activeProfileName, R.string.status_started)
|
||||
}
|
||||
notification.start()
|
||||
Log.d(TAG, "🎉 [完成] 服务启动成功!")
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "❌ [致命错误] startService异常!")
|
||||
Log.e(TAG, "❌ 错误信息: ${e.message}")
|
||||
Log.e(TAG, "❌ 异常类型: ${e.javaClass.name}")
|
||||
Log.e(TAG, "❌ 堆栈跟踪: ${e.stackTraceToString()}")
|
||||
stopAndAlert(Alert.StartService, e.message)
|
||||
return
|
||||
}
|
||||
@ -335,8 +365,10 @@ class BoxService(
|
||||
try {
|
||||
startCommandServer()
|
||||
} catch (e: Exception) {
|
||||
stopAndAlert(Alert.StartCommandServer, e.message)
|
||||
return@launch
|
||||
// CommandServer 启动失败不是致命错误
|
||||
// 在 Android 12+ SELinux 环境下,chown 操作可能被拒绝
|
||||
// 但这不影响 VPN 核心功能,因此记录警告但继续启动服务
|
||||
Log.w(TAG, "CommandServer failed to start (non-fatal): ${e.message}")
|
||||
}
|
||||
startService()
|
||||
}
|
||||
|
||||
382
android/app/src/main/kotlin/com/hiddify/hiddify/bg/BoxService.kt.bak
Executable file
382
android/app/src/main/kotlin/com/hiddify/hiddify/bg/BoxService.kt.bak
Executable file
@ -0,0 +1,382 @@
|
||||
package com.hiddify.hiddify.bg
|
||||
|
||||
import android.app.Service
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.os.Build
|
||||
import android.os.IBinder
|
||||
import android.os.ParcelFileDescriptor
|
||||
import android.os.PowerManager
|
||||
import android.util.Log
|
||||
import androidx.annotation.RequiresApi
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.lifecycle.MutableLiveData
|
||||
import com.hiddify.hiddify.Application
|
||||
import com.hiddify.hiddify.R
|
||||
import com.hiddify.hiddify.Settings
|
||||
import com.hiddify.hiddify.constant.Action
|
||||
import com.hiddify.hiddify.constant.Alert
|
||||
import com.hiddify.hiddify.constant.Status
|
||||
import go.Seq
|
||||
import io.nekohasekai.libbox.BoxService
|
||||
import io.nekohasekai.libbox.CommandServer
|
||||
import io.nekohasekai.libbox.CommandServerHandler
|
||||
import io.nekohasekai.libbox.Libbox
|
||||
import io.nekohasekai.libbox.PlatformInterface
|
||||
import io.nekohasekai.libbox.SystemProxyStatus
|
||||
import io.nekohasekai.mobile.Mobile
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.GlobalScope
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.File
|
||||
|
||||
class BoxService(
|
||||
private val service: Service,
|
||||
private val platformInterface: PlatformInterface
|
||||
) : CommandServerHandler {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "A/BoxService"
|
||||
|
||||
private var initializeOnce = false
|
||||
private lateinit var workingDir: File
|
||||
private fun initialize() {
|
||||
if (initializeOnce) return
|
||||
val baseDir = Application.application.filesDir
|
||||
|
||||
baseDir.mkdirs()
|
||||
workingDir = Application.application.getExternalFilesDir(null) ?: return
|
||||
workingDir.mkdirs()
|
||||
val tempDir = Application.application.cacheDir
|
||||
tempDir.mkdirs()
|
||||
Log.d(TAG, "base dir: ${baseDir.path}")
|
||||
Log.d(TAG, "working dir: ${workingDir.path}")
|
||||
Log.d(TAG, "temp dir: ${tempDir.path}")
|
||||
|
||||
// 创建数据库目录 (数据库使用相对路径 ./data,所以在workingDir下创建)
|
||||
val dataDir = File(workingDir, "data")
|
||||
dataDir.mkdirs()
|
||||
Log.d(TAG, "database dir: ${dataDir.path}")
|
||||
|
||||
// 确保数据库目录有读写权限
|
||||
if (!dataDir.canRead() || !dataDir.canWrite()) {
|
||||
Log.w(TAG, "database dir permission issue, trying to fix")
|
||||
dataDir.setReadable(true, false)
|
||||
dataDir.setWritable(true, false)
|
||||
}
|
||||
|
||||
Mobile.setup(baseDir.path, workingDir.path, tempDir.path, false)
|
||||
Libbox.redirectStderr(File(workingDir, "stderr.log").path)
|
||||
initializeOnce = true
|
||||
return
|
||||
}
|
||||
|
||||
fun parseConfig(path: String, tempPath: String, debug: Boolean): String {
|
||||
return try {
|
||||
Mobile.parse(path, tempPath, debug)
|
||||
""
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, e)
|
||||
e.message ?: "invalid config"
|
||||
}
|
||||
}
|
||||
|
||||
fun buildConfig(path: String, options: String): String {
|
||||
return Mobile.buildConfig(path, options)
|
||||
}
|
||||
|
||||
fun start() {
|
||||
val intent = runBlocking {
|
||||
withContext(Dispatchers.IO) {
|
||||
Intent(Application.application, Settings.serviceClass())
|
||||
}
|
||||
}
|
||||
ContextCompat.startForegroundService(Application.application, intent)
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
Application.application.sendBroadcast(
|
||||
Intent(Action.SERVICE_CLOSE).setPackage(
|
||||
Application.application.packageName
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
fun reload() {
|
||||
Application.application.sendBroadcast(
|
||||
Intent(Action.SERVICE_RELOAD).setPackage(
|
||||
Application.application.packageName
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
var fileDescriptor: ParcelFileDescriptor? = null
|
||||
|
||||
private val status = MutableLiveData(Status.Stopped)
|
||||
private val binder = ServiceBinder(status)
|
||||
private val notification = ServiceNotification(status, service)
|
||||
private var boxService: BoxService? = null
|
||||
private var commandServer: CommandServer? = null
|
||||
private var receiverRegistered = false
|
||||
private val receiver = object : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
when (intent.action) {
|
||||
Action.SERVICE_CLOSE -> {
|
||||
stopService()
|
||||
}
|
||||
|
||||
Action.SERVICE_RELOAD -> {
|
||||
serviceReload()
|
||||
}
|
||||
|
||||
PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED -> {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
serviceUpdateIdleMode()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun startCommandServer() {
|
||||
val commandServer =
|
||||
CommandServer(this, 300)
|
||||
commandServer.start()
|
||||
this.commandServer = commandServer
|
||||
}
|
||||
|
||||
private var activeProfileName = ""
|
||||
private suspend fun startService(delayStart: Boolean = false) {
|
||||
try {
|
||||
Log.d(TAG, "starting service")
|
||||
// 暂时禁用通知显示
|
||||
// withContext(Dispatchers.Main) {
|
||||
// notification.show(activeProfileName, R.string.status_starting)
|
||||
// }
|
||||
|
||||
val selectedConfigPath = Settings.activeConfigPath
|
||||
if (selectedConfigPath.isBlank()) {
|
||||
stopAndAlert(Alert.EmptyConfiguration)
|
||||
return
|
||||
}
|
||||
|
||||
activeProfileName = Settings.activeProfileName
|
||||
|
||||
val configOptions = Settings.configOptions
|
||||
if (configOptions.isBlank()) {
|
||||
stopAndAlert(Alert.EmptyConfiguration)
|
||||
return
|
||||
}
|
||||
|
||||
val content = try {
|
||||
Mobile.buildConfig(selectedConfigPath, configOptions)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, e)
|
||||
stopAndAlert(Alert.EmptyConfiguration)
|
||||
return
|
||||
}
|
||||
|
||||
// ✅ 始终保存完整配置以便调试
|
||||
try {
|
||||
File(workingDir, "current-config.json").writeText(content)
|
||||
Log.d(TAG, "✅ 完整配置已保存到: ${workingDir}/current-config.json")
|
||||
Log.d(TAG, "📄 配置长度: ${content.length} 字符")
|
||||
Log.d(TAG, "📄 配置前1000字符:\n${content.substring(0, minOf(1000, content.length))}")
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "保存配置文件失败: $e")
|
||||
}
|
||||
|
||||
withContext(Dispatchers.Main) {
|
||||
notification.show(activeProfileName, R.string.status_starting)
|
||||
binder.broadcast {
|
||||
it.onServiceResetLogs(listOf())
|
||||
}
|
||||
}
|
||||
|
||||
DefaultNetworkMonitor.start()
|
||||
Libbox.registerLocalDNSTransport(LocalResolver)
|
||||
Libbox.setMemoryLimit(!Settings.disableMemoryLimit)
|
||||
|
||||
val newService = try {
|
||||
Libbox.newService(content, platformInterface)
|
||||
} catch (e: Exception) {
|
||||
stopAndAlert(Alert.CreateService, e.message)
|
||||
return
|
||||
}
|
||||
|
||||
if (delayStart) {
|
||||
delay(1000L)
|
||||
}
|
||||
|
||||
newService.start()
|
||||
boxService = newService
|
||||
commandServer?.setService(boxService)
|
||||
status.postValue(Status.Started)
|
||||
|
||||
withContext(Dispatchers.Main) {
|
||||
notification.show(activeProfileName, R.string.status_started)
|
||||
}
|
||||
notification.start()
|
||||
} catch (e: Exception) {
|
||||
stopAndAlert(Alert.StartService, e.message)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
override fun serviceReload() {
|
||||
notification.close()
|
||||
status.postValue(Status.Starting)
|
||||
val pfd = fileDescriptor
|
||||
if (pfd != null) {
|
||||
pfd.close()
|
||||
fileDescriptor = null
|
||||
}
|
||||
commandServer?.setService(null)
|
||||
boxService?.apply {
|
||||
runCatching {
|
||||
close()
|
||||
}.onFailure {
|
||||
writeLog("service: error when closing: $it")
|
||||
}
|
||||
Seq.destroyRef(refnum)
|
||||
}
|
||||
boxService = null
|
||||
runBlocking {
|
||||
startService(true)
|
||||
}
|
||||
}
|
||||
|
||||
override fun getSystemProxyStatus(): SystemProxyStatus {
|
||||
val status = SystemProxyStatus()
|
||||
if (service is VPNService) {
|
||||
status.available = service.systemProxyAvailable
|
||||
status.enabled = service.systemProxyEnabled
|
||||
}
|
||||
return status
|
||||
}
|
||||
|
||||
override fun setSystemProxyEnabled(isEnabled: Boolean) {
|
||||
serviceReload()
|
||||
}
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.M)
|
||||
private fun serviceUpdateIdleMode() {
|
||||
if (Application.powerManager.isDeviceIdleMode) {
|
||||
boxService?.pause()
|
||||
} else {
|
||||
boxService?.wake()
|
||||
}
|
||||
}
|
||||
|
||||
private fun stopService() {
|
||||
if (status.value != Status.Started) return
|
||||
status.value = Status.Stopping
|
||||
if (receiverRegistered) {
|
||||
service.unregisterReceiver(receiver)
|
||||
receiverRegistered = false
|
||||
}
|
||||
notification.close()
|
||||
GlobalScope.launch(Dispatchers.IO) {
|
||||
val pfd = fileDescriptor
|
||||
if (pfd != null) {
|
||||
pfd.close()
|
||||
fileDescriptor = null
|
||||
}
|
||||
commandServer?.setService(null)
|
||||
boxService?.apply {
|
||||
runCatching {
|
||||
close()
|
||||
}.onFailure {
|
||||
writeLog("service: error when closing: $it")
|
||||
}
|
||||
Seq.destroyRef(refnum)
|
||||
}
|
||||
boxService = null
|
||||
Libbox.registerLocalDNSTransport(null)
|
||||
DefaultNetworkMonitor.stop()
|
||||
|
||||
commandServer?.apply {
|
||||
close()
|
||||
Seq.destroyRef(refnum)
|
||||
}
|
||||
commandServer = null
|
||||
Settings.startedByUser = false
|
||||
withContext(Dispatchers.Main) {
|
||||
status.value = Status.Stopped
|
||||
service.stopSelf()
|
||||
}
|
||||
}
|
||||
}
|
||||
override fun postServiceClose() {
|
||||
// Not used on Android
|
||||
}
|
||||
|
||||
private suspend fun stopAndAlert(type: Alert, message: String? = null) {
|
||||
Settings.startedByUser = false
|
||||
withContext(Dispatchers.Main) {
|
||||
if (receiverRegistered) {
|
||||
service.unregisterReceiver(receiver)
|
||||
receiverRegistered = false
|
||||
}
|
||||
notification.close()
|
||||
binder.broadcast { callback ->
|
||||
callback.onServiceAlert(type.ordinal, message)
|
||||
}
|
||||
status.value = Status.Stopped
|
||||
}
|
||||
}
|
||||
|
||||
fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
if (status.value != Status.Stopped) return Service.START_NOT_STICKY
|
||||
status.value = Status.Starting
|
||||
|
||||
if (!receiverRegistered) {
|
||||
ContextCompat.registerReceiver(service, receiver, IntentFilter().apply {
|
||||
addAction(Action.SERVICE_CLOSE)
|
||||
addAction(Action.SERVICE_RELOAD)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED)
|
||||
}
|
||||
}, ContextCompat.RECEIVER_NOT_EXPORTED)
|
||||
receiverRegistered = true
|
||||
}
|
||||
|
||||
GlobalScope.launch(Dispatchers.IO) {
|
||||
Settings.startedByUser = true
|
||||
initialize()
|
||||
try {
|
||||
startCommandServer()
|
||||
} catch (e: Exception) {
|
||||
stopAndAlert(Alert.StartCommandServer, e.message)
|
||||
return@launch
|
||||
}
|
||||
startService()
|
||||
}
|
||||
return Service.START_NOT_STICKY
|
||||
}
|
||||
|
||||
fun onBind(intent: Intent): IBinder {
|
||||
return binder
|
||||
}
|
||||
|
||||
fun onDestroy() {
|
||||
binder.close()
|
||||
}
|
||||
|
||||
fun onRevoke() {
|
||||
stopService()
|
||||
}
|
||||
|
||||
fun writeLog(message: String) {
|
||||
binder.broadcast {
|
||||
it.onServiceWriteLog(message)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -47,7 +47,9 @@ class VPNService : VpnService(), PlatformInterfaceWrapper {
|
||||
}
|
||||
|
||||
override fun autoDetectInterfaceControl(fd: Int) {
|
||||
protect(fd)
|
||||
Log.d(TAG, "🛡️ autoDetectInterfaceControl 被调用, fd=$fd")
|
||||
val result = protect(fd)
|
||||
Log.d(TAG, "🛡️ protect(fd=$fd) 返回: $result")
|
||||
}
|
||||
|
||||
var systemProxyAvailable = false
|
||||
@ -75,6 +77,10 @@ class VPNService : VpnService(), PlatformInterfaceWrapper {
|
||||
override fun openTun(options: TunOptions): Int {
|
||||
if (prepare(this) != null) error("android: missing vpn permission")
|
||||
|
||||
Log.d(TAG, "🔧 openTun 被调用")
|
||||
Log.d(TAG, " MTU: ${options.mtu}")
|
||||
Log.d(TAG, " AutoRoute: ${options.autoRoute}")
|
||||
|
||||
val builder = Builder()
|
||||
.setSession("sing-box")
|
||||
.setMtu(options.mtu)
|
||||
@ -128,49 +134,86 @@ class VPNService : VpnService(), PlatformInterfaceWrapper {
|
||||
}
|
||||
} else {
|
||||
val inet4RouteAddress = options.inet4RouteRange
|
||||
Log.d(TAG, "📍 Android <13: 配置IPv4路由")
|
||||
if (inet4RouteAddress.hasNext()) {
|
||||
Log.d(TAG, "✅ 找到IPv4路由配置,开始添加...")
|
||||
while (inet4RouteAddress.hasNext()) {
|
||||
val address = inet4RouteAddress.next()
|
||||
Log.d(TAG, " 添加路由: ${address.address()}/${address.prefix()}")
|
||||
builder.addRoute(address.address(), address.prefix())
|
||||
}
|
||||
} else {
|
||||
// ⚠️ 如果没有指定路由,添加默认路由
|
||||
Log.w(TAG, "⚠️ 没有IPv4路由配置,添加默认路由 0.0.0.0/0")
|
||||
builder.addRoute("0.0.0.0", 0)
|
||||
}
|
||||
|
||||
val inet6RouteAddress = options.inet6RouteRange
|
||||
if (inet6RouteAddress.hasNext()) {
|
||||
Log.d(TAG, "✅ 找到IPv6路由配置,开始添加...")
|
||||
while (inet6RouteAddress.hasNext()) {
|
||||
val address = inet6RouteAddress.next()
|
||||
Log.d(TAG, " 添加IPv6路由: ${address.address()}/${address.prefix()}")
|
||||
builder.addRoute(address.address(), address.prefix())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Log.d(TAG, "📱 包过滤配置:")
|
||||
Log.d(TAG, " perAppProxyEnabled: ${Settings.perAppProxyEnabled}")
|
||||
Log.d(TAG, " 当前应用包名: $packageName")
|
||||
|
||||
if (Settings.perAppProxyEnabled) {
|
||||
val appList = Settings.perAppProxyList
|
||||
Log.d(TAG, " ✅ 使用应用级代理,模式: ${Settings.perAppProxyMode}")
|
||||
Log.d(TAG, " 📋 应用列表数量: ${appList.size}")
|
||||
if (Settings.perAppProxyMode == PerAppProxyMode.INCLUDE) {
|
||||
Log.d(TAG, " 🔵 INCLUDE模式 - 只有以下应用使用VPN:")
|
||||
appList.forEach {
|
||||
Log.d(TAG, " - $it")
|
||||
addIncludePackage(builder,it)
|
||||
}
|
||||
Log.d(TAG, " - $packageName (本应用)")
|
||||
addIncludePackage(builder,packageName)
|
||||
} else {
|
||||
Log.d(TAG, " 🔴 EXCLUDE模式 - 以下应用不使用VPN:")
|
||||
appList.forEach {
|
||||
Log.d(TAG, " - $it")
|
||||
addExcludePackage(builder,it)
|
||||
}
|
||||
//addExcludePackage(builder,packageName)
|
||||
// 不排除本应用,让libcore能正常工作
|
||||
// Log.d(TAG, " ⚠️ 本应用也排除VPN")
|
||||
// addExcludePackage(builder,packageName)
|
||||
Log.d(TAG, " ℹ️ 本应用不在排除列表")
|
||||
}
|
||||
} else {
|
||||
Log.d(TAG, " ⚙️ 使用配置文件的包过滤规则")
|
||||
val includePackage = options.includePackage
|
||||
if (includePackage.hasNext()) {
|
||||
Log.d(TAG, " 🔵 INCLUDE列表:")
|
||||
while (includePackage.hasNext()) {
|
||||
addIncludePackage(builder,includePackage.next())
|
||||
val pkg = includePackage.next()
|
||||
Log.d(TAG, " - $pkg")
|
||||
addIncludePackage(builder,pkg)
|
||||
}
|
||||
} else {
|
||||
Log.d(TAG, " ℹ️ 无INCLUDE规则")
|
||||
}
|
||||
|
||||
val excludePackage = options.excludePackage
|
||||
if (excludePackage.hasNext()) {
|
||||
Log.d(TAG, " 🔴 EXCLUDE列表:")
|
||||
while (excludePackage.hasNext()) {
|
||||
addExcludePackage(builder,excludePackage.next())
|
||||
val pkg = excludePackage.next()
|
||||
Log.d(TAG, " - $pkg")
|
||||
addExcludePackage(builder,pkg)
|
||||
}
|
||||
} else {
|
||||
Log.d(TAG, " ℹ️ 无EXCLUDE规则")
|
||||
}
|
||||
//addExcludePackage(builder,packageName)
|
||||
// 不排除本应用,让libcore能正常工作
|
||||
// Log.d(TAG, " ⚠️ 始终排除本应用: $packageName")
|
||||
// addExcludePackage(builder,packageName)
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@ -3,10 +3,13 @@ import '../services/api_service/kr_api.user.dart';
|
||||
import '../utils/kr_update_util.dart';
|
||||
import '../utils/kr_secure_storage.dart';
|
||||
import '../utils/kr_log_util.dart';
|
||||
import '../services/singbox_imp/kr_sing_box_imp.dart';
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'dart:math';
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:dio/io.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
/// 协议配置
|
||||
@ -54,7 +57,27 @@ class KRDomain {
|
||||
static Map<String, int> _domainResponseTimes = {}; // 域名响应时间记录
|
||||
static Map<String, DateTime> _domainLastCheck = {}; // 域名最后检测时间
|
||||
static const int _domainCacheDuration = 300; // 域名缓存时间(秒)
|
||||
static final Dio _dio = Dio(); // Dio 实例
|
||||
|
||||
// Dio 实例及初始化
|
||||
static final Dio _dio = (() {
|
||||
final dio = Dio();
|
||||
// 🔧 配置HttpClientAdapter使用sing-box的mixed代理
|
||||
dio.httpClientAdapter = IOHttpClientAdapter(
|
||||
createHttpClient: () {
|
||||
final client = HttpClient();
|
||||
client.findProxy = (url) {
|
||||
final proxyConfig = KRSingBoxImp.instance.kr_buildProxyRule();
|
||||
KRLogUtil.kr_i(
|
||||
'🔍 KRDomain 请求使用代理: $proxyConfig, url: $url',
|
||||
tag: 'KRDomain',
|
||||
);
|
||||
return proxyConfig;
|
||||
};
|
||||
return client;
|
||||
},
|
||||
);
|
||||
return dio;
|
||||
})();
|
||||
|
||||
/// API 域名
|
||||
static String get kr_api => kr_currentDomain;
|
||||
@ -1032,12 +1055,13 @@ class AppConfig {
|
||||
|
||||
/// 请求域名地址
|
||||
/// 基础url
|
||||
///
|
||||
// static String baseUrl = "http://103.112.98.72:8088";
|
||||
|
||||
/// 请求域名地址调试模式
|
||||
String get baseUrl {
|
||||
if (kDebugMode) {
|
||||
return "https://api.maodag.top";
|
||||
return "http://154.12.35.103:8080";
|
||||
}
|
||||
return "${KRProtocol.kr_https}://${KRDomain.kr_api}";
|
||||
}
|
||||
|
||||
@ -1,7 +1,8 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io' show Platform;
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:dio/io.dart';
|
||||
|
||||
// import 'package:flutter_easyloading/flutter_easyloading.dart'; // 已替换为自定义组件
|
||||
import 'package:flutter_loggy_dio/flutter_loggy_dio.dart';
|
||||
@ -11,6 +12,7 @@ import 'package:kaer_with_panels/app/common/app_run_data.dart';
|
||||
import 'package:kaer_with_panels/app/network/base_response.dart';
|
||||
import 'package:kaer_with_panels/app/localization/kr_language_utils.dart';
|
||||
import 'package:kaer_with_panels/app/utils/kr_common_util.dart';
|
||||
import 'package:kaer_with_panels/app/services/singbox_imp/kr_sing_box_imp.dart';
|
||||
import 'package:kaer_with_panels/app/services/kr_site_config_service.dart';
|
||||
|
||||
// import 'package:crypto/crypto.dart';
|
||||
@ -44,6 +46,7 @@ class HttpUtil {
|
||||
|
||||
/// 对dio进行配置
|
||||
void initDio() {
|
||||
KRLogUtil.kr_i('🚀 HttpUtil.initDio() 开始初始化', tag: 'HttpUtil');
|
||||
// 不使用 Loggy,改用自定义简洁拦截器
|
||||
_dio.interceptors.add(_KRSimpleHttpInterceptor());
|
||||
_dio.options.baseUrl = AppConfig.getInstance().baseUrl;
|
||||
@ -67,6 +70,26 @@ class HttpUtil {
|
||||
_dio.options.validateStatus = (status) {
|
||||
return status != null && status >= 200 && status < 500;
|
||||
};
|
||||
|
||||
// 🔧 配置HttpClientAdapter 优先走本地 sing-box mixed 端口,
|
||||
// 若代理不可用则回退到直连
|
||||
KRLogUtil.kr_i('🔧 配置 HttpClientAdapter...', tag: 'HttpUtil');
|
||||
_dio.httpClientAdapter = IOHttpClientAdapter(
|
||||
createHttpClient: () {
|
||||
KRLogUtil.kr_i('📱 createHttpClient 回调被调用', tag: 'HttpUtil');
|
||||
final client = HttpClient();
|
||||
client.findProxy = (url) {
|
||||
final proxyConfig = KRSingBoxImp.instance.kr_buildProxyRule();
|
||||
KRLogUtil.kr_i(
|
||||
'🔍 findProxy 被调用, url: $url, proxy: $proxyConfig',
|
||||
tag: 'HttpUtil',
|
||||
);
|
||||
return proxyConfig;
|
||||
};
|
||||
return client;
|
||||
},
|
||||
);
|
||||
KRLogUtil.kr_i('✅ HttpUtil.initDio() 初始化完成', tag: 'HttpUtil');
|
||||
}
|
||||
|
||||
/// 更新baseUrl
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
import 'dart:io';
|
||||
import 'dart:io' as io;
|
||||
import 'dart:math';
|
||||
import 'dart:convert';
|
||||
import 'package:dio/io.dart' as dio_io;
|
||||
|
||||
import 'package:fpdart/fpdart.dart';
|
||||
import 'package:get/get.dart';
|
||||
@ -20,6 +21,7 @@ import '../kr_device_info_service.dart';
|
||||
import '../kr_site_config_service.dart';
|
||||
import '../../common/app_config.dart';
|
||||
import 'package:dio/dio.dart' as dio;
|
||||
import 'package:kaer_with_panels/app/services/singbox_imp/kr_sing_box_imp.dart';
|
||||
|
||||
class KRAuthApi {
|
||||
/// 检查账号是否已注册(仅支持邮箱)
|
||||
@ -227,6 +229,24 @@ class KRAuthApi {
|
||||
|
||||
// 使用 Dio 直接发送请求(因为需要特殊的加密处理)
|
||||
final dioInstance = dio.Dio();
|
||||
|
||||
// 🔧 配置HttpClientAdapter优先使用本地 sing-box mixed 端口,
|
||||
// 失败时退回直连
|
||||
dioInstance.httpClientAdapter = dio_io.IOHttpClientAdapter(
|
||||
createHttpClient: () {
|
||||
final client = io.HttpClient();
|
||||
client.findProxy = (url) {
|
||||
final proxyConfig = KRSingBoxImp.instance.kr_buildProxyRule();
|
||||
KRLogUtil.kr_i(
|
||||
'🔍 KRAuthApi 请求使用代理: $proxyConfig, url: $url',
|
||||
tag: 'KRAuthApi',
|
||||
);
|
||||
return proxyConfig;
|
||||
};
|
||||
return client;
|
||||
},
|
||||
);
|
||||
|
||||
final baseUrl = AppConfig.getInstance().baseUrl;
|
||||
final url = '$baseUrl${Api.kr_deviceLogin}';
|
||||
|
||||
@ -313,17 +333,17 @@ class KRAuthApi {
|
||||
}
|
||||
|
||||
String _kr_getUserAgent() {
|
||||
if (Platform.isAndroid) {
|
||||
if (io.Platform.isAndroid) {
|
||||
return 'android';
|
||||
} else if (Platform.isIOS) {
|
||||
} else if (io.Platform.isIOS) {
|
||||
return 'ios';
|
||||
} else if (Platform.isMacOS) {
|
||||
} else if (io.Platform.isMacOS) {
|
||||
return 'mac';
|
||||
} else if (Platform.isWindows) {
|
||||
} else if (io.Platform.isWindows) {
|
||||
return 'windows';
|
||||
} else if (Platform.isLinux) {
|
||||
} else if (io.Platform.isLinux) {
|
||||
return 'linux';
|
||||
} else if (Platform.isFuchsia) {
|
||||
} else if (io.Platform.isFuchsia) {
|
||||
return 'harmony';
|
||||
} else {
|
||||
return 'unknown';
|
||||
|
||||
@ -1,8 +1,11 @@
|
||||
import 'dart:io';
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:dio/io.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import '../model/response/kr_site_config.dart';
|
||||
import '../common/app_config.dart';
|
||||
import '../utils/kr_log_util.dart';
|
||||
import 'singbox_imp/kr_sing_box_imp.dart';
|
||||
|
||||
/// 网站配置服务
|
||||
class KRSiteConfigService extends ChangeNotifier {
|
||||
@ -13,6 +16,22 @@ class KRSiteConfigService extends ChangeNotifier {
|
||||
_dio.options.connectTimeout = const Duration(seconds: 10);
|
||||
_dio.options.sendTimeout = const Duration(seconds: 10);
|
||||
_dio.options.receiveTimeout = const Duration(seconds: 10);
|
||||
|
||||
// 🔧 配置HttpClientAdapter使用sing-box的mixed代理
|
||||
_dio.httpClientAdapter = IOHttpClientAdapter(
|
||||
createHttpClient: () {
|
||||
final client = HttpClient();
|
||||
client.findProxy = (url) {
|
||||
final proxyConfig = KRSingBoxImp.instance.kr_buildProxyRule();
|
||||
KRLogUtil.kr_i(
|
||||
'🔍 KRSiteConfigService 请求使用代理: $proxyConfig, url: $url',
|
||||
tag: 'KRSiteConfigService',
|
||||
);
|
||||
return proxyConfig;
|
||||
};
|
||||
return client;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
KRSiteConfig? _siteConfig;
|
||||
|
||||
@ -97,6 +97,36 @@ class KRSingBoxImp {
|
||||
/// Stream 订阅管理器
|
||||
final List<StreamSubscription<dynamic>> _kr_subscriptions = [];
|
||||
|
||||
/// 当前混合代理端口是否就绪
|
||||
bool get kr_isProxyReady => kr_status.value is SingboxStarted;
|
||||
|
||||
String? _lastProxyRule;
|
||||
|
||||
/// 构建 Dart HttpClient 可识别的代理规则字符串
|
||||
///
|
||||
/// 当 sing-box 尚未启动时返回 `DIRECT`,启动后返回
|
||||
/// `PROXY 127.0.0.1:<port>; DIRECT`,以便在代理不可用时自动回落。
|
||||
String kr_buildProxyRule({bool includeDirectFallback = true}) {
|
||||
if (!kr_isProxyReady) {
|
||||
const directRule = 'DIRECT';
|
||||
if (_lastProxyRule != directRule) {
|
||||
KRLogUtil.kr_i('⏳ sing-box 未就绪,使用 DIRECT 直连', tag: 'SingBox');
|
||||
_lastProxyRule = directRule;
|
||||
}
|
||||
return directRule;
|
||||
}
|
||||
final proxyRule = StringBuffer('PROXY 127.0.0.1:$kr_port');
|
||||
if (includeDirectFallback) {
|
||||
proxyRule.write('; DIRECT');
|
||||
}
|
||||
final ruleString = proxyRule.toString();
|
||||
if (_lastProxyRule != ruleString) {
|
||||
KRLogUtil.kr_i('🛠️ 使用代理规则: $ruleString', tag: 'SingBox');
|
||||
_lastProxyRule = ruleString;
|
||||
}
|
||||
return ruleString;
|
||||
}
|
||||
|
||||
/// 初始化
|
||||
Future<void> init() async {
|
||||
try {
|
||||
@ -426,8 +456,10 @@ class KRSingBoxImp {
|
||||
|
||||
kr_outbounds = outbounds;
|
||||
|
||||
final map = {};
|
||||
map["outbounds"] = kr_outbounds;
|
||||
// 只保存 outbounds,Mobile.buildConfig() 会添加其他配置
|
||||
final map = {
|
||||
"outbounds": kr_outbounds
|
||||
};
|
||||
|
||||
final file = _file(kr_configName);
|
||||
final temp = _tempFile(kr_configName);
|
||||
|
||||
@ -14,10 +14,9 @@ import 'package:kaer_with_panels/app/localization/kr_language_utils.dart';
|
||||
import 'package:kaer_with_panels/app/routes/app_pages.dart';
|
||||
|
||||
import 'package:kaer_with_panels/app/utils/kr_window_manager.dart';
|
||||
|
||||
import 'app/utils/kr_secure_storage.dart';
|
||||
import 'app/services/singbox_imp/kr_sing_box_imp.dart';
|
||||
import 'app/common/app_config.dart';
|
||||
import 'app/services/kr_site_config_service.dart';
|
||||
import 'app/utils/kr_secure_storage.dart';
|
||||
|
||||
// 全局导航键
|
||||
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
|
||||
@ -25,6 +24,9 @@ final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
|
||||
void main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
// 为所有 HttpClient 请求统一注入代理策略
|
||||
HttpOverrides.global = KRProxyHttpOverrides();
|
||||
|
||||
// 初始化 Hive
|
||||
await KRSecureStorage().kr_initHive();
|
||||
|
||||
@ -131,3 +133,13 @@ Widget _myApp(GetxTranslations translations, Locale initialLocale) {
|
||||
// defaultTransition: Transition.fade,
|
||||
);
|
||||
}
|
||||
|
||||
/// 全局 HttpOverrides,确保所有 dart:io 网络请求遵循 sing-box 代理策略
|
||||
class KRProxyHttpOverrides extends HttpOverrides {
|
||||
@override
|
||||
HttpClient createHttpClient(SecurityContext? context) {
|
||||
final client = super.createHttpClient(context);
|
||||
client.findProxy = (uri) => KRSingBoxImp.instance.kr_buildProxyRule();
|
||||
return client;
|
||||
}
|
||||
}
|
||||
|
||||
2
libcore/.gitattributes
vendored
Normal file
2
libcore/.gitattributes
vendored
Normal file
@ -0,0 +1,2 @@
|
||||
*.h linguist-detectable=false
|
||||
*.c linguist-detectable=false
|
||||
23
libcore/.github/change_version.sh
vendored
Executable file
23
libcore/.github/change_version.sh
vendored
Executable file
@ -0,0 +1,23 @@
|
||||
#! /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
Normal file
303
libcore/.github/workflows/build.yml
vendored
Normal file
@ -0,0 +1,303 @@
|
||||
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
Normal file
32
libcore/.github/workflows/ci.yml
vendored
Normal file
@ -0,0 +1,32 @@
|
||||
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
Normal file
20
libcore/.github/workflows/release.yml
vendored
Normal file
@ -0,0 +1,20 @@
|
||||
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
Normal file
12
libcore/.gitignore
vendored
Normal file
@ -0,0 +1,12 @@
|
||||
/bin/*
|
||||
!/bin/.gitkeep
|
||||
.build
|
||||
.idea
|
||||
cert
|
||||
**/*.log
|
||||
.DS_Store
|
||||
|
||||
**/*.syso
|
||||
node_modules
|
||||
*.db
|
||||
*.json
|
||||
10
libcore/.prettierrc
Normal file
10
libcore/.prettierrc
Normal file
@ -0,0 +1,10 @@
|
||||
{
|
||||
"overrides": [
|
||||
{
|
||||
"files": ".github/**",
|
||||
"options": {
|
||||
"singleQuote": true
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
9
libcore/.stignore
Normal file
9
libcore/.stignore
Normal file
@ -0,0 +1,9 @@
|
||||
.git
|
||||
|
||||
.build
|
||||
.idea
|
||||
|
||||
**/*.log
|
||||
.DS_Store
|
||||
|
||||
**/*.syso
|
||||
26
libcore/CONTRIBUTING.md
Normal file
26
libcore/CONTRIBUTING.md
Normal file
@ -0,0 +1,26 @@
|
||||
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`
|
||||
50
libcore/Info.plist
Normal file
50
libcore/Info.plist
Normal file
@ -0,0 +1,50 @@
|
||||
<?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>
|
||||
699
libcore/LICENSE.md
Normal file
699
libcore/LICENSE.md
Normal file
@ -0,0 +1,699 @@
|
||||
|
||||
# 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
Normal file
107
libcore/Makefile
Normal file
@ -0,0 +1,107 @@
|
||||
.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'
|
||||
|
||||
|
||||
|
||||
53
libcore/README.md
Normal file
53
libcore/README.md
Normal file
@ -0,0 +1,53 @@
|
||||
# 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">
|
||||
|
||||
BIN
libcore/assets/hiddify-cli.ico
Normal file
BIN
libcore/assets/hiddify-cli.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 11 KiB |
0
libcore/bin/.gitkeep
Normal file
0
libcore/bin/.gitkeep
Normal file
Binary file not shown.
BIN
libcore/bin/libcore-sources.jar
Normal file
BIN
libcore/bin/libcore-sources.jar
Normal file
Binary file not shown.
36
libcore/bridge/bridge.go
Normal file
36
libcore/bridge/bridge.go
Normal file
@ -0,0 +1,36 @@
|
||||
// +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)
|
||||
}
|
||||
}
|
||||
11
libcore/bridge/bridge_stub.go
Normal file
11
libcore/bridge/bridge_stub.go
Normal file
@ -0,0 +1,11 @@
|
||||
//go:build !cgo
|
||||
// +build !cgo
|
||||
|
||||
package bridge
|
||||
|
||||
import "unsafe"
|
||||
|
||||
func InitializeDartApi(api unsafe.Pointer) {
|
||||
}
|
||||
func SendStringToPort(port int64, msg string) {
|
||||
}
|
||||
23
libcore/bridge/include/BUILD.gn
Normal file
23
libcore/bridge/include/BUILD.gn
Normal file
@ -0,0 +1,23 @@
|
||||
# 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}}" ]
|
||||
}
|
||||
30
libcore/bridge/include/analyze_snapshot_api.h
Normal file
30
libcore/bridge/include/analyze_snapshot_api.h
Normal file
@ -0,0 +1,30 @@
|
||||
/*
|
||||
* 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_
|
||||
69
libcore/bridge/include/bin/dart_io_api.h
Normal file
69
libcore/bridge/include/bin/dart_io_api.h
Normal file
@ -0,0 +1,69 @@
|
||||
// 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_
|
||||
4172
libcore/bridge/include/dart_api.h
Normal file
4172
libcore/bridge/include/dart_api.h
Normal file
File diff suppressed because it is too large
Load Diff
79
libcore/bridge/include/dart_api_dl.c
Normal file
79
libcore/bridge/include/dart_api_dl.c
Normal file
@ -0,0 +1,79 @@
|
||||
/*
|
||||
* 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;
|
||||
}
|
||||
162
libcore/bridge/include/dart_api_dl.h
Normal file
162
libcore/bridge/include/dart_api_dl.h
Normal file
@ -0,0 +1,162 @@
|
||||
/*
|
||||
* 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 */
|
||||
108
libcore/bridge/include/dart_embedder_api.h
Normal file
108
libcore/bridge/include/dart_embedder_api.h
Normal file
@ -0,0 +1,108 @@
|
||||
// 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_
|
||||
207
libcore/bridge/include/dart_native_api.h
Normal file
207
libcore/bridge/include/dart_native_api.h
Normal file
@ -0,0 +1,207 @@
|
||||
/*
|
||||
* 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 */
|
||||
658
libcore/bridge/include/dart_tools_api.h
Normal file
658
libcore/bridge/include/dart_tools_api.h
Normal file
@ -0,0 +1,658 @@
|
||||
// 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_
|
||||
16
libcore/bridge/include/dart_version.h
Normal file
16
libcore/bridge/include/dart_version.h
Normal file
@ -0,0 +1,16 @@
|
||||
/*
|
||||
* 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 */
|
||||
21
libcore/bridge/include/internal/dart_api_dl_impl.h
Normal file
21
libcore/bridge/include/internal/dart_api_dl_impl.h
Normal file
@ -0,0 +1,21 @@
|
||||
/*
|
||||
* 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 */
|
||||
18
libcore/build_windows.bat
Normal file
18
libcore/build_windows.bat
Normal file
@ -0,0 +1,18 @@
|
||||
@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
|
||||
35
libcore/cli/bydll/clibydll.go
Normal file
35
libcore/cli/bydll/clibydll.go
Normal file
@ -0,0 +1,35 @@
|
||||
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))
|
||||
}
|
||||
29
libcore/cli/main.go
Normal file
29
libcore/cli/main.go
Normal file
@ -0,0 +1,29 @@
|
||||
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())
|
||||
}
|
||||
4
libcore/cmd.bat
Normal file
4
libcore/cmd.bat
Normal file
@ -0,0 +1,4 @@
|
||||
@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 %*
|
||||
4
libcore/cmd.sh
Executable file
4
libcore/cmd.sh
Executable file
@ -0,0 +1,4 @@
|
||||
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 $@
|
||||
188
libcore/cmd/cmd_config.go
Normal file
188
libcore/cmd/cmd_config.go
Normal file
@ -0,0 +1,188 @@
|
||||
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")
|
||||
}
|
||||
21
libcore/cmd/cmd_extension.go
Normal file
21
libcore/cmd/cmd_extension.go
Normal file
@ -0,0 +1,21 @@
|
||||
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)
|
||||
}
|
||||
21
libcore/cmd/cmd_gen_cert.go
Normal file
21
libcore/cmd/cmd_gen_cert.go
Normal file
@ -0,0 +1,21 @@
|
||||
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)
|
||||
},
|
||||
}
|
||||
59
libcore/cmd/cmd_instance.go
Normal file
59
libcore/cmd/cmd_instance.go
Normal file
@ -0,0 +1,59 @@
|
||||
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)
|
||||
}
|
||||
52
libcore/cmd/cmd_parse.go
Normal file
52
libcore/cmd/cmd_parse.go
Normal file
@ -0,0 +1,52 @@
|
||||
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
|
||||
}
|
||||
28
libcore/cmd/cmd_run.go
Normal file
28
libcore/cmd/cmd_run.go
Normal file
@ -0,0 +1,28 @@
|
||||
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)
|
||||
}
|
||||
141
libcore/cmd/cmd_temp.go
Normal file
141
libcore/cmd/cmd_temp.go
Normal file
@ -0,0 +1,141 @@
|
||||
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())
|
||||
// }
|
||||
40
libcore/cmd/cmd_tunnel_service.go
Normal file
40
libcore/cmd/cmd_tunnel_service.go
Normal file
@ -0,0 +1,40 @@
|
||||
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)
|
||||
}
|
||||
},
|
||||
}
|
||||
126
libcore/cmd/cmd_warp.go
Normal file
126
libcore/cmd/cmd_warp.go
Normal file
@ -0,0 +1,126 @@
|
||||
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
|
||||
}
|
||||
55
libcore/cmd/interface.go
Normal file
55
libcore/cmd/interface.go
Normal file
@ -0,0 +1,55 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
217
libcore/cmd/internal/build_libcore/main.go
Normal file
217
libcore/cmd/internal/build_libcore/main.go
Normal file
@ -0,0 +1,217 @@
|
||||
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"))
|
||||
}
|
||||
99
libcore/cmd/internal/build_shared/sdk.go
Normal file
99
libcore/cmd/internal/build_shared/sdk.go
Normal file
@ -0,0 +1,99 @@
|
||||
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
|
||||
}
|
||||
49
libcore/config/admin_service_cmd_runner.go
Normal file
49
libcore/config/admin_service_cmd_runner.go
Normal file
@ -0,0 +1,49 @@
|
||||
//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")
|
||||
}
|
||||
32
libcore/config/admin_service_cmd_runner_windows.go
Normal file
32
libcore/config/admin_service_cmd_runner_windows.go
Normal file
@ -0,0 +1,32 @@
|
||||
//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
|
||||
}
|
||||
188
libcore/config/admin_service_commander.go
Normal file
188
libcore/config/admin_service_commander.go
Normal file
@ -0,0 +1,188 @@
|
||||
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
|
||||
}
|
||||
869
libcore/config/config.go
Normal file
869
libcore/config/config.go
Normal file
@ -0,0 +1,869 @@
|
||||
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]
|
||||
}
|
||||
8
libcore/config/config.json.template
Normal file
8
libcore/config/config.json.template
Normal file
@ -0,0 +1,8 @@
|
||||
{
|
||||
"log": {},
|
||||
"dns": {},
|
||||
"inbounds": [],
|
||||
"outbounds": [],
|
||||
"route": {},
|
||||
"experimental": {}
|
||||
}
|
||||
6
libcore/config/constant.go
Normal file
6
libcore/config/constant.go
Normal file
@ -0,0 +1,6 @@
|
||||
package config
|
||||
|
||||
const (
|
||||
WarpOverProxy = "warp_over_proxy"
|
||||
ProxyOverWarp = "proxy_over_warp"
|
||||
)
|
||||
389
libcore/config/core.pb.go
Normal file
389
libcore/config/core.pb.go
Normal file
@ -0,0 +1,389 @@
|
||||
// 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
|
||||
}
|
||||
146
libcore/config/core_grpc.pb.go
Normal file
146
libcore/config/core_grpc.pb.go
Normal file
@ -0,0 +1,146 @@
|
||||
// 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",
|
||||
}
|
||||
45
libcore/config/debug.go
Normal file
45
libcore/config/debug.go
Normal file
@ -0,0 +1,45 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
155
libcore/config/hiddify_option.go
Normal file
155
libcore/config/hiddify_option.go
Normal file
@ -0,0 +1,155 @@
|
||||
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,
|
||||
}
|
||||
}
|
||||
185
libcore/config/outbound.go
Normal file
185
libcore/config/outbound.go
Normal file
@ -0,0 +1,185 @@
|
||||
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 ""
|
||||
// }
|
||||
142
libcore/config/parser.go
Normal file
142
libcore/config/parser.go
Normal file
@ -0,0 +1,142 @@
|
||||
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
|
||||
}
|
||||
96
libcore/config/rules.go
Normal file
96
libcore/config/rules.go
Normal file
@ -0,0 +1,96 @@
|
||||
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
|
||||
}
|
||||
75
libcore/config/server.go
Normal file
75
libcore/config/server.go
Normal file
@ -0,0 +1,75 @@
|
||||
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
|
||||
}
|
||||
25
libcore/config/types.go
Normal file
25
libcore/config/types.go
Normal file
@ -0,0 +1,25 @@
|
||||
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
|
||||
}
|
||||
270
libcore/config/warp.go
Normal file
270
libcore/config/warp.go
Normal file
@ -0,0 +1,270 @@
|
||||
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
|
||||
}
|
||||
50
libcore/config/warp_account.go
Normal file
50
libcore/config/warp_account.go
Normal file
@ -0,0 +1,50 @@
|
||||
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
|
||||
}
|
||||
26
libcore/custom/cmd_interface.go
Normal file
26
libcore/custom/cmd_interface.go
Normal file
@ -0,0 +1,26 @@
|
||||
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("")
|
||||
}
|
||||
169
libcore/custom/custom.go
Normal file
169
libcore/custom/custom.go
Normal file
@ -0,0 +1,169 @@
|
||||
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() {}
|
||||
10
libcore/custom/grpc_interface.go
Normal file
10
libcore/custom/grpc_interface.go
Normal file
@ -0,0 +1,10 @@
|
||||
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)
|
||||
}
|
||||
72
libcore/docker-compile.sh
Executable file
72
libcore/docker-compile.sh
Executable file
@ -0,0 +1,72 @@
|
||||
#!/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
|
||||
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