clash_service.dart 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. import 'dart:convert';
  2. import 'dart:io';
  3. import 'dart:async';
  4. import 'package:get/get.dart';
  5. import 'package:yaml_edit/yaml_edit.dart';
  6. import 'package:path/path.dart' as path;
  7. import '../../common/constants.dart';
  8. import '../../const/const.dart';
  9. import '../../controller/controllers.dart';
  10. import '../../data/model/NodeMode.dart';
  11. import '../../utils/shell.dart';
  12. import '../../utils/utils.dart';
  13. import '../mode/clash_config.dart';
  14. class ClashService extends GetxController {
  15. Process? clashCoreProcess;
  16. final coreStatus = RunningState.stoped.obs;
  17. final serviceMode = false.obs;
  18. bool get clashServiceIsRuning => coreStatus.value == RunningState.running;
  19. Future<void> updatePorts() async {
  20. // 检查端口占用
  21. int newPort = await findAvailablePort(controllers.config.mixedPort.value+1);
  22. controllers.config.mixedPort.value = newPort;
  23. controllers.global.updateMsg("混合端口已更新为: $newPort");
  24. // 检查API端口占用
  25. int newApiPort = await findAvailablePort(controllers.config.apiAddressPort.value);
  26. controllers.config.apiAddressPort.value = newApiPort;
  27. controllers.global.updateMsg("API端口已更新为: $newApiPort");
  28. int newDnsPort = await findAvailablePort(int.parse(controllers.config.dnsPort.value.split(':').last));
  29. controllers.config.dnsPort.value = '${controllers.config.dnsPort.value.split(':').first}:$newDnsPort';
  30. await controllers.config.saveConfig();
  31. //await controllers.config.readClashCoreApi();
  32. }
  33. Future<void> makeInitConfig() async {
  34. //await updatePorts();
  35. //await controllers.config.readClashCoreApi();
  36. var mode = controllers.global.modesSelect.value;
  37. var clashConfig = ClashConfig(
  38. mixedPort: controllers.config.mixedPort.value,
  39. allowLan: true,
  40. bindAddress: '*',
  41. mode: mode,
  42. logLevel: 'debug',
  43. externalController: '127.0.0.1:${controllers.config.apiAddressPort.value}',
  44. unifiedDelay: false,
  45. geodataMode: true,
  46. tcpConcurrent: false,
  47. findProcessMode: 'strict',
  48. globalClientFingerprint: 'chrome',
  49. dns: DNS(
  50. enable: false,
  51. listen: controllers.config.dnsPort.value,
  52. ipv6: false,
  53. enhancedMode: kRedirHostMode,
  54. fakeIpFilter: null,
  55. nameserver: kDomesticDNS,
  56. proxyServerNameserver: kDomesticDNS,
  57. nameserverPolicy: {
  58. 'geosite:cn,private': kDomesticDNS,
  59. 'geosite:geolocation-!cn': kForeignDNS,
  60. },
  61. ),
  62. tun: Tun(
  63. enable: false,
  64. stack: 'system',
  65. autoRoute: true,
  66. autoRedirect: true,
  67. autoDetectInterface: true,
  68. dnsHijack: ['any:53'],
  69. ),
  70. proxies: [],
  71. rules: [
  72. 'GEOIP,CN,DIRECT',
  73. 'MATCH,DIRECT'
  74. ]
  75. );
  76. try {
  77. final file = File(path.join(Paths.config.path, Files.makeInitProxyConfig.path ));
  78. await file.writeAsString(clashConfig.toYaml());
  79. print('配置文件已成功保存到: ${file.path}');
  80. } catch (e) {
  81. print('保存配置文件时发生错误: $e');
  82. throw Exception('无法保存配置文件');
  83. }
  84. }
  85. // 启动普通模式的核心进程
  86. Future<bool> startNormalCore() async {
  87. try {
  88. // 先停止所有现有进程
  89. // await controllers.global.stopAllCore();
  90. coreStatus.value = RunningState.starting;
  91. controllers.global.updateMsg("启动普通模式内核...");
  92. clashCoreProcess = await Process.start(
  93. Files.assetsCCore.path,
  94. ['-d', Paths.config.path, '-f', path.join(Paths.config.path, controllers.config.config.value.selected)],
  95. mode: ProcessStartMode.inheritStdio
  96. );
  97. // 等待进程启动并检查API可用性
  98. if (!await _waitForCoreReady()) {
  99. return false;
  100. }
  101. coreStatus.value = RunningState.running;
  102. controllers.global.updateMsg("普通模式内核启动成功");
  103. return true;
  104. } catch (e) {
  105. controllers.global.updateMsg("启动内核错误: $e");
  106. coreStatus.value = RunningState.error;
  107. return false;
  108. }
  109. }
  110. // 启动TUN模式的核心进程
  111. Future<bool> startTunCore(String password) async {
  112. Process? process;
  113. try {
  114. // 先停止所有现有进程
  115. await controllers.global.stopAllCore();
  116. coreStatus.value = RunningState.starting;
  117. controllers.global.updateMsg("启动TUN模式内核...");
  118. final corePath = path.join(Paths.assetsBin.path, path.basename(Files.assetsCCore.path));
  119. final configPath = path.join(Paths.config.path, controllers.config.config.value.selected);
  120. process = await Process.start('bash', [
  121. '-c',
  122. 'echo "$password" | sudo -S $corePath -d ${Paths.config.path} -f $configPath'
  123. ], mode: ProcessStartMode.inheritStdio);
  124. clashCoreProcess = process;
  125. // 等待root进程启动
  126. if (!await _waitForRootProcess()) {
  127. throw Exception("TUN模式进程启动失败");
  128. }
  129. // 等待API可用
  130. if (!await _waitForCoreReady()) {
  131. throw Exception("TUN模式API初始化失败");
  132. }
  133. coreStatus.value = RunningState.running;
  134. controllers.global.updateMsg("TUN模式内核启动成功");
  135. return true;
  136. } catch (e) {
  137. process?.kill();
  138. controllers.global.updateMsg("启动TUN模式失败: $e");
  139. coreStatus.value = RunningState.error;
  140. return false;
  141. }
  142. }
  143. // 等待进程API就绪
  144. Future<bool> _waitForCoreReady() async {
  145. final timeout = const Duration(seconds: 30);
  146. final checkInterval = const Duration(milliseconds: 200);
  147. final startTime = DateTime.now();
  148. controllers.core.setApi(
  149. controllers.config.clashCoreApiAddress.value,
  150. controllers.config.clashCoreApiSecret.value
  151. );
  152. while (DateTime.now().difference(startTime) < timeout) {
  153. try {
  154. controllers.global.updateMsg("等待内核启动..");
  155. await controllers.core.fetchHello();
  156. return true;
  157. } catch (_) {
  158. await Future.delayed(checkInterval);
  159. }
  160. }
  161. return false;
  162. }
  163. // 等待root进程启动
  164. Future<bool> _waitForRootProcess() async {
  165. int retryCount = 0;
  166. while (retryCount < 10) {
  167. final checkResult = await Process.run('bash', [
  168. '-c',
  169. 'ps -ef | grep core-darwin | grep root | grep -v grep'
  170. ]);
  171. if (checkResult.exitCode == 0 && checkResult.stdout.toString().isNotEmpty) {
  172. return true;
  173. }
  174. await Future.delayed(const Duration(milliseconds: 500));
  175. retryCount++;
  176. }
  177. return false;
  178. }
  179. Future<void> stopClashCore() async {
  180. coreStatus.value = RunningState.stopping;
  181. await controllers.global.closeProxy();
  182. clashCoreProcess?.kill();
  183. killProcess(ClashName.name);
  184. coreStatus.value = RunningState.stoped;
  185. }
  186. Future<bool> initClashCoreConfig() async {
  187. controllers.config.config.value.selected = Files.makeInitProxyConfig.path;
  188. await makeInitConfig();
  189. await controllers.global.checkAllCoresStopped();
  190. if (coreStatus.value == RunningState.error) {
  191. controllers.global.updateMsg("启动内核失败...");
  192. return false;
  193. } else {
  194. await controllers.core.updateVersion();
  195. controllers.global.updateMsg("启动内核成功...");
  196. return true;
  197. }
  198. }
  199. Future<void> stopClash() async {
  200. controllers.config.config.value.selected = Files.makeInitProxyConfig.path;
  201. if (coreStatus.value == RunningState.running) {
  202. await controllers.config.readClashCoreApi();
  203. controllers.core.setApi(controllers.config.clashCoreApiAddress.value, controllers.config.clashCoreApiSecret.value);
  204. await controllers.core.changeConfig(path.join(Paths.config.path, controllers.config.config.value.selected));
  205. }
  206. }
  207. Future<void> reloadClashCore() async {
  208. try {
  209. // if(coreStatus.value == RunningState.stoped){
  210. // await updatePorts();
  211. // }
  212. controllers.config.config.value.selected = Files.makeProxyConfig.path;
  213. if (coreStatus.value == RunningState.running) {
  214. controllers.global.updateMsg("切换配置...");
  215. await controllers.config.readClashCoreApi();
  216. controllers.core.setApi(controllers.config.clashCoreApiAddress.value, controllers.config.clashCoreApiSecret.value);
  217. await controllers.core.changeConfig(path.join(Paths.config.path, controllers.config.config.value.selected));
  218. controllers.global.updateMsg("fetchReloadConfig${controllers.config.clashCoreApiAddress.value}...");
  219. }
  220. } catch (e) {
  221. // if(coreStatus.value == RunningState.stoped){
  222. // await updatePorts();
  223. // }
  224. controllers.global.updateMsg("重新配置...");
  225. await controllers.config.readClashCoreApi();
  226. controllers.core.setApi(controllers.config.clashCoreApiAddress.value, controllers.config.clashCoreApiSecret.value);
  227. await controllers.core.changeConfig(path.join(Paths.config.path, controllers.config.config.value.selected));
  228. }
  229. }
  230. Future<String> generateYamlConfig(List<NodeMode> nodes) async {
  231. // await updatePorts();
  232. final config = ClashConfig(
  233. mixedPort: controllers.config.mixedPort.value,
  234. allowLan: true,
  235. bindAddress: '*',
  236. mode: controllers.global.modesSelect.value == "global" ? "global" : "rule",
  237. logLevel: 'info',
  238. externalController: '127.0.0.1:${controllers.config.apiAddressPort.value}',
  239. unifiedDelay: false,
  240. geodataMode: true,
  241. tcpConcurrent: false,
  242. findProcessMode: 'strict',
  243. globalClientFingerprint: 'chrome',
  244. profile: {
  245. 'store-selected': true,
  246. 'store-fake-ip': true,
  247. },
  248. sniffer: Sniffer(
  249. enable: true,
  250. sniff: {
  251. 'HTTP': {
  252. 'ports': [80, '8080-8880'],
  253. 'override-destination': true,
  254. },
  255. 'TLS': {
  256. 'ports': [443, 8443],
  257. },
  258. // 'QUIC': {
  259. // 'ports': [443, 8443],
  260. // },
  261. },
  262. skipDomain: ['www.baidu.com'],
  263. ),
  264. dns: DNS(
  265. enable: true,
  266. listen: kDnsListenPort,
  267. ipv6: false,
  268. enhancedMode: kRedirHostMode,
  269. fakeIpFilter: null,
  270. nameserver: kDomesticDNS,
  271. proxyServerNameserver: kDomesticDNS,
  272. nameserverPolicy: {
  273. 'geosite:cn,private': kDomesticDNS,
  274. 'geosite:geolocation-!cn': kForeignDNS,
  275. },
  276. ),
  277. tun: Tun(
  278. enable: controllers.global.routeModesSelect.value == "tun" ? true:false,
  279. stack: 'gvisor',
  280. autoRoute: true,
  281. autoRedirect: false,
  282. autoDetectInterface: true,
  283. dnsHijack: ['any:53'],
  284. ),
  285. proxies: [],
  286. proxyGroups: [
  287. ProxyGroup(
  288. name: 'proxy',
  289. type: 'select',
  290. proxies: [],
  291. ),
  292. ],
  293. rules: [
  294. 'GEOIP,CN,DIRECT',
  295. 'MATCH,proxy',
  296. ],
  297. );
  298. for (final node in nodes) {
  299. BaseProxy proxy;
  300. switch (node.type) {
  301. case 'trojan':
  302. proxy = TrojanProxy(
  303. name: node.name ?? '',
  304. server: node.host ?? '',
  305. port: node.port ?? 0,
  306. password: node.passwd ?? '',
  307. udp: node.udp == 1,
  308. sni: node.sni,
  309. );
  310. break;
  311. case 'shadowsocks':
  312. proxy = SSProxy(
  313. name: node.name ?? '',
  314. type: 'ss',
  315. server: node.host ?? '',
  316. port: node.port ?? 0,
  317. password: node.passwd ?? '',
  318. cipher: node.method ?? '',
  319. udp: node.udp == 1,
  320. );
  321. break;
  322. case 'v2ray':
  323. final type = (node.vless == 1) ? 'vless' : 'vmess';
  324. if (type == 'vless') {
  325. proxy = VlessProxy(
  326. name: node.name ?? '',
  327. uuid: node.uuid ?? '',
  328. server: node.host ?? '',
  329. port: node.port ?? 0,
  330. udp: node.udp == 1,
  331. flow: 'xtls-rprx-vision',
  332. tls: true,
  333. servername: node.v2Sni,
  334. realityOpts: {'public-key': node.vlessPulkey},
  335. network: 'tcp',
  336. );
  337. } else {
  338. proxy = VmessProxy(
  339. name: node.name ?? '',
  340. uuid: node.uuid ?? '',
  341. server: node.host ?? '',
  342. port: node.port ?? 0,
  343. alterId: node.v2AlterId,
  344. cipher: node.method,
  345. udp: node.udp == 1,
  346. );
  347. }
  348. break;
  349. default:
  350. continue;
  351. }
  352. config.proxies?.add(proxy.toJson());
  353. config.proxyGroups?[0].proxies.add(node.name ?? '');
  354. }
  355. return config.toYaml();
  356. }
  357. Future<void> saveConfigToFile(String filePath, List<NodeMode> nodes) async {
  358. try {
  359. final configYaml = await generateYamlConfig(nodes);
  360. final file = File(filePath);
  361. await file.writeAsString(configYaml);
  362. print('配置文件已成功保存到: $filePath');
  363. } catch (e) {
  364. print('保存配置文件时发生错误: $e');
  365. throw Exception('无法保存配置文件');
  366. }
  367. }
  368. }
  369. extension ConfigToYaml on ClashConfig {
  370. String toYaml() {
  371. final yamlMap = toJson();
  372. final yamlEditor = YamlEditor('');
  373. yamlEditor.update([], yamlMap);
  374. return yamlEditor.toString();
  375. }
  376. }