clash_service.dart 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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. Future<bool> startClashCore() async {
  86. final timeout = const Duration(seconds: 30);
  87. final checkInterval = const Duration(milliseconds: 200);
  88. var startTime = DateTime.now();
  89. await controllers.config.readClashCoreApi();
  90. try {
  91. controllers.global.updateMsg("启动内核---${controllers.config.config.value.selected}");
  92. if (controllers.config.config.value.selected == controllers.config.config.value.selected) {
  93. controllers.global.updateMsg("启动内核初始化");
  94. } else {
  95. controllers.global.updateMsg("启动内核");
  96. }
  97. coreStatus.value = RunningState.starting;
  98. int? exitCode;
  99. clashCoreProcess = await Process.start(
  100. Files.assetsCCore.path,
  101. ['-d', Paths.config.path, '-f', path.join(Paths.config.path, controllers.config.config.value.selected)],
  102. mode: ProcessStartMode.inheritStdio
  103. );
  104. clashCoreProcess!.exitCode.then((code) => exitCode = code);
  105. if (exitCode != null && exitCode != 0) {
  106. controllers.global.updateMsg("启动内核错误,请重启点电脑测试");
  107. return false;
  108. }
  109. controllers.core.setApi(controllers.config.clashCoreApiAddress.value, controllers.config.clashCoreApiSecret.value);
  110. while (DateTime.now().difference(startTime) < timeout) {
  111. try {
  112. controllers.global.updateMsg("等待内核启动..");
  113. await controllers.core.fetchHello();
  114. break;
  115. } catch (_) {
  116. await Future.delayed(checkInterval);
  117. }
  118. }
  119. if (DateTime.now().difference(startTime) >= timeout) {
  120. coreStatus.value = RunningState.error;
  121. controllers.global.updateMsg("内核启动超时,重新点击加速后尝试。");
  122. return false;
  123. }
  124. await controllers.core.updateConfig();
  125. coreStatus.value = RunningState.running;
  126. controllers.global.updateMsg("点击连接 ");
  127. return true;
  128. } catch (e) {
  129. controllers.global.updateMsg("启动内核错误");
  130. coreStatus.value = RunningState.error;
  131. return false;
  132. }
  133. }
  134. Future<void> stopClashCore() async {
  135. coreStatus.value = RunningState.stopping;
  136. await controllers.global.closeProxy();
  137. clashCoreProcess?.kill();
  138. killProcess(ClashName.name);
  139. coreStatus.value = RunningState.stoped;
  140. }
  141. Future<bool> initClashCoreConfig() async {
  142. controllers.config.config.value.selected = Files.makeProxyConfig.path;
  143. //await makeInitConfig();
  144. await startClashCore();
  145. if (coreStatus.value == RunningState.error) {
  146. controllers.global.updateMsg("启动内核失败...");
  147. return false;
  148. } else {
  149. await controllers.core.updateVersion();
  150. controllers.global.updateMsg("启动内核成功...");
  151. return true;
  152. }
  153. }
  154. Future<void> stopClash() async {
  155. controllers.config.config.value.selected = Files.makeInitProxyConfig.path;
  156. if (coreStatus.value == RunningState.running) {
  157. await controllers.config.readClashCoreApi();
  158. controllers.core.setApi(controllers.config.clashCoreApiAddress.value, controllers.config.clashCoreApiSecret.value);
  159. await controllers.core.changeConfig(path.join(Paths.config.path, controllers.config.config.value.selected));
  160. }
  161. }
  162. Future<void> reloadClashCore() async {
  163. try {
  164. // if(coreStatus.value == RunningState.stoped){
  165. // await updatePorts();
  166. // }
  167. controllers.config.config.value.selected = Files.makeProxyConfig.path;
  168. if (coreStatus.value == RunningState.running) {
  169. controllers.global.updateMsg("切换配置...");
  170. await controllers.config.readClashCoreApi();
  171. controllers.core.setApi(controllers.config.clashCoreApiAddress.value, controllers.config.clashCoreApiSecret.value);
  172. await controllers.core.changeConfig(path.join(Paths.config.path, controllers.config.config.value.selected));
  173. controllers.global.updateMsg("fetchReloadConfig${controllers.config.clashCoreApiAddress.value}...");
  174. }
  175. } catch (e) {
  176. // if(coreStatus.value == RunningState.stoped){
  177. // await updatePorts();
  178. // }
  179. controllers.global.updateMsg("重新配置...");
  180. await controllers.config.readClashCoreApi();
  181. controllers.core.setApi(controllers.config.clashCoreApiAddress.value, controllers.config.clashCoreApiSecret.value);
  182. await controllers.core.changeConfig(path.join(Paths.config.path, controllers.config.config.value.selected));
  183. }
  184. }
  185. Future<String> generateYamlConfig(List<NodeMode> nodes) async {
  186. // await updatePorts();
  187. final config = ClashConfig(
  188. mixedPort: controllers.config.mixedPort.value,
  189. allowLan: true,
  190. bindAddress: '*',
  191. mode: controllers.global.modesSelect.value == "global" ? "global" : "rule",
  192. logLevel: 'info',
  193. externalController: '127.0.0.1:${controllers.config.apiAddressPort.value}',
  194. unifiedDelay: false,
  195. geodataMode: true,
  196. tcpConcurrent: false,
  197. findProcessMode: 'strict',
  198. globalClientFingerprint: 'chrome',
  199. profile: {
  200. 'store-selected': true,
  201. 'store-fake-ip': true,
  202. },
  203. sniffer: Sniffer(
  204. enable: true,
  205. sniff: {
  206. 'HTTP': {
  207. 'ports': [80, '8080-8880'],
  208. 'override-destination': true,
  209. },
  210. 'TLS': {
  211. 'ports': [443, 8443],
  212. },
  213. // 'QUIC': {
  214. // 'ports': [443, 8443],
  215. // },
  216. },
  217. skipDomain: ['www.baidu.com'],
  218. ),
  219. dns: DNS(
  220. enable: true,
  221. listen: kDnsListenPort,
  222. ipv6: false,
  223. enhancedMode: kRedirHostMode,
  224. fakeIpFilter: null,
  225. nameserver: kDomesticDNS,
  226. proxyServerNameserver: kDomesticDNS,
  227. nameserverPolicy: {
  228. 'geosite:cn,private': kDomesticDNS,
  229. 'geosite:geolocation-!cn': kForeignDNS,
  230. },
  231. ),
  232. tun: Tun(
  233. enable: controllers.global.routeModesSelect.value == "tun" ? true:false,
  234. stack: 'gvisor',
  235. autoRoute: true,
  236. autoRedirect: false,
  237. autoDetectInterface: true,
  238. dnsHijack: ['any:53'],
  239. ),
  240. proxies: [],
  241. proxyGroups: [
  242. ProxyGroup(
  243. name: 'proxy',
  244. type: 'select',
  245. proxies: [],
  246. ),
  247. ],
  248. rules: [
  249. 'GEOIP,CN,DIRECT',
  250. 'MATCH,proxy',
  251. ],
  252. );
  253. for (final node in nodes) {
  254. BaseProxy proxy;
  255. switch (node.type) {
  256. case 'trojan':
  257. proxy = TrojanProxy(
  258. name: node.name ?? '',
  259. server: node.host ?? '',
  260. port: node.port ?? 0,
  261. password: node.passwd ?? '',
  262. udp: node.udp == 1,
  263. sni: node.sni,
  264. );
  265. break;
  266. case 'shadowsocks':
  267. proxy = SSProxy(
  268. name: node.name ?? '',
  269. type: 'ss',
  270. server: node.host ?? '',
  271. port: node.port ?? 0,
  272. password: node.passwd ?? '',
  273. cipher: node.method ?? '',
  274. udp: node.udp == 1,
  275. );
  276. break;
  277. case 'v2ray':
  278. final type = (node.vless == 1) ? 'vless' : 'vmess';
  279. if (type == 'vless') {
  280. proxy = VlessProxy(
  281. name: node.name ?? '',
  282. uuid: node.uuid ?? '',
  283. server: node.host ?? '',
  284. port: node.port ?? 0,
  285. udp: node.udp == 1,
  286. flow: '',
  287. tls: true,
  288. servername: node.v2Sni,
  289. realityOpts: {'public-key': node.vlessPulkey},
  290. network: 'tcp',
  291. );
  292. } else {
  293. proxy = VmessProxy(
  294. name: node.name ?? '',
  295. uuid: node.uuid ?? '',
  296. server: node.host ?? '',
  297. port: node.port ?? 0,
  298. alterId: node.v2AlterId,
  299. cipher: node.method,
  300. udp: node.udp == 1,
  301. );
  302. }
  303. break;
  304. default:
  305. continue;
  306. }
  307. config.proxies?.add(proxy.toJson());
  308. config.proxyGroups?[0].proxies.add(node.name ?? '');
  309. }
  310. return config.toYaml();
  311. }
  312. Future<void> saveConfigToFile(String filePath, List<NodeMode> nodes) async {
  313. try {
  314. final configYaml = await generateYamlConfig(nodes);
  315. final file = File(filePath);
  316. await file.writeAsString(configYaml);
  317. print('配置文件已成功保存到: $filePath');
  318. } catch (e) {
  319. print('保存配置文件时发生错误: $e');
  320. throw Exception('无法保存配置文件');
  321. }
  322. }
  323. }
  324. extension ConfigToYaml on ClashConfig {
  325. String toYaml() {
  326. final yamlMap = toJson();
  327. final yamlEditor = YamlEditor('');
  328. yamlEditor.update([], yamlMap);
  329. return yamlEditor.toString();
  330. }
  331. }