service.dart 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  1. import 'dart:io';
  2. import 'dart:async';
  3. import 'dart:convert';
  4. import 'package:dio/dio.dart';
  5. import 'package:get/get.dart';
  6. import 'package:naiyouwl/app/bean/ClashServiceInfo.dart';
  7. import 'package:naiyouwl/app/common/LogHelper.dart';
  8. import 'package:naiyouwl/app/const/const.dart';
  9. import 'package:naiyouwl/app/controller/controllers.dart';
  10. import 'package:naiyouwl/app/utils/logger.dart';
  11. import 'package:naiyouwl/app/utils/shell.dart';
  12. import 'package:naiyouwl/app/utils/system_dns.dart';
  13. import 'package:naiyouwl/app/utils/system_proxy.dart';
  14. import 'package:naiyouwl/app/utils/utils.dart';
  15. import 'package:path/path.dart' as path;
  16. import 'package:flutter/foundation.dart';
  17. import 'package:bot_toast/bot_toast.dart';
  18. import 'package:web_socket_channel/io.dart';
  19. import 'package:http/http.dart' as http;
  20. final headers = {"User-Agent": "ccore-for-flutter/0.0.1"};
  21. class ServiceController extends GetxController {
  22. //late final _dio = Dio(BaseOptions(baseUrl: 'http://127.0.0.1:9899', headers: headers));
  23. var ip = "127.0.0.1";
  24. var url = "";
  25. var client = http.Client();
  26. var serviceMode = false.obs;
  27. var coreStatus = RunningState.stoped.obs;
  28. var serviceStatus = RunningState.stoped.obs;
  29. Process? clashServiceProcess;
  30. Process? clashCoreProcess;
  31. bool get isRunning => serviceStatus.value == RunningState.running && coreStatus.value == RunningState.running;
  32. bool get isCanOperationService =>
  33. ![RunningState.starting, RunningState.stopping].contains(serviceStatus.value) &&
  34. ![RunningState.starting, RunningState.stopping].contains(coreStatus.value);
  35. bool get isCanOperationCore =>
  36. serviceStatus.value == RunningState.running && ![RunningState.starting, RunningState.stopping].contains(coreStatus.value);
  37. bool get coreIsRuning => coreStatus.value == RunningState.running;
  38. bool get serviceIsRuning => serviceStatus.value == RunningState.running;
  39. ServiceController(
  40. );
  41. Future<void> initConfig() async{
  42. url = "$ip:${controllers.config.config.value.servicePort}";
  43. controllers.config.setSerivcePort(controllers.config.config.value.servicePort);
  44. }
  45. Future<void> startTunService() async {
  46. try {
  47. while (true) {
  48. final data = await fetchInfo() ?? ClashServiceInfo.fromJson({'code': -1 , 'mode' : '' , 'status': '-1','version' : '-1'});
  49. if( data.mode != 'service-mode')
  50. {
  51. if (serviceStatus.value == RunningState.running) {
  52. await stopService();
  53. }
  54. await install();
  55. } else {
  56. break;
  57. }
  58. }
  59. } catch (e) {
  60. serviceStatus.value = RunningState.error;
  61. log.debug(e.toString());
  62. // BotToast.showText(text: e.toString());
  63. }
  64. }
  65. Future<void> isService() async {
  66. try {
  67. final data = await fetchInfo() ?? ClashServiceInfo.fromJson({'code': -1 , 'mode' : '' , 'status': '-1','version' : '-1'});
  68. if(data.mode == 'service-mode'){
  69. serviceMode.value = true;
  70. controllers.global.updateMsg("服务模式");
  71. } else {
  72. serviceMode.value = false;
  73. controllers.global.updateMsg("用户模式");
  74. }
  75. } catch (_) {
  76. }
  77. }
  78. Future<void> startService() async {
  79. serviceStatus.value = RunningState.starting;
  80. try {
  81. final data = await fetchInfo();
  82. if(data == null){
  83. await startUserModeService();
  84. controllers.global.updateMsg("开启用户服务");
  85. return;
  86. }
  87. serviceMode.value = data.mode == 'service-mode';
  88. controllers.global.updateMsg("服务模式");
  89. } catch (e) {
  90. await startUserModeService();
  91. controllers.global.updateMsg("开启用户服务");
  92. if (serviceStatus.value == RunningState.error) return;
  93. }
  94. serviceStatus.value = RunningState.running;
  95. }
  96. Future<void> fixBinaryExecutePermissions(File file) async {
  97. final stat = await file.stat();
  98. // 0b001000000
  99. final has = (stat.mode & 64) == 64;
  100. if (has) return;
  101. await Process.run('chmod', ['+x', file.path]);
  102. }
  103. Future<void> startUserModeService() async {
  104. serviceStatus.value = RunningState.stopping;
  105. serviceMode.value = false;
  106. final timeout = const Duration(seconds: 30); // 设置超时时间为30秒
  107. final checkInterval = const Duration(milliseconds: 200);
  108. var startTime = DateTime.now();
  109. try {
  110. final isRun = await controllers.global.onIsProcessRunning(Files.assetsClashService.path);
  111. if(isRun == true){
  112. await isService();
  113. serviceStatus.value = RunningState.running;
  114. return;
  115. }
  116. int? exitCode;
  117. clashServiceProcess = await Process.start(Files.assetsClashService.path, ['-port','${controllers.config.config.value.servicePort}','user-mode'], mode: ProcessStartMode.inheritStdio);
  118. clashServiceProcess!.exitCode.then((code) => exitCode = code);
  119. while (DateTime.now().difference(startTime) < timeout) {
  120. try {
  121. controllers.global.updateMsg("等待内核启动..");
  122. final ret = await fetchInfo();
  123. if(ret != null){
  124. if(ret.code == 0){
  125. break;
  126. }
  127. }
  128. break;
  129. } catch (_) {
  130. // 如果fetchHello失败,等待200毫秒后重试
  131. await Future.delayed(checkInterval);
  132. }
  133. }
  134. // 检查是否超时
  135. if (DateTime.now().difference(startTime) >= timeout) {
  136. // 如果超时,更新状态并抛出异常
  137. coreStatus.value = RunningState.error;
  138. controllers.global.updateMsg("内核启动超时,重新点击加速后尝试。");
  139. return; // 提前退出函数
  140. }
  141. await fetchStartInit();
  142. serviceStatus.value = RunningState.running;
  143. } catch (e) {
  144. serviceStatus.value = RunningState.error;
  145. //BotToast.showText(text: e.toString());
  146. print(e.toString());
  147. }
  148. }
  149. Future<void> stopService() async {
  150. serviceStatus.value = RunningState.stopping;
  151. if (coreStatus.value == RunningState.running) await fetchStop();
  152. if (!serviceMode.value) {
  153. if (clashServiceProcess != null) {
  154. clashServiceProcess!.kill();
  155. clashServiceProcess = null;
  156. } else if (kDebugMode) {
  157. await killProcess(path.basename(Files.assetsClashService.path));
  158. }
  159. }
  160. serviceStatus.value = RunningState.stoped;
  161. }
  162. // for macos
  163. Future<void> waitServiceStart() async {
  164. while (true) {
  165. await Future.delayed(const Duration(milliseconds: 100));
  166. try {
  167. await client.post(Uri.http(url,'info'),headers: headers);
  168. break;
  169. } catch (_) {}
  170. }
  171. }
  172. // for windows
  173. Future<void> waitServiceStop() async {
  174. while (true) {
  175. await Future.delayed(const Duration(milliseconds: 100));
  176. try {
  177. await client.post(Uri.http(url,'info'),headers: headers);
  178. } catch (e) {
  179. break;
  180. }
  181. }
  182. }
  183. Future<ClashServiceInfo?> fetchInfo() async {
  184. try {
  185. final res = await client.post(Uri.http(url,'info'),headers: headers);
  186. var jsonResponse =
  187. jsonDecode(res.body) as Map<String, dynamic>;
  188. return ClashServiceInfo.fromJson(jsonResponse);
  189. } on http.ClientException catch (e) {
  190. // 处理客户端异常,例如没有网络连接
  191. print('Client Exception: ${e.message}');
  192. return null;
  193. } on Exception catch (e) {
  194. // 处理其他类型的异常
  195. print('Exception: $e');
  196. return null;
  197. }
  198. return null;
  199. }
  200. IOWebSocketChannel fetchLogWs() {
  201. return IOWebSocketChannel.connect(Uri.parse('ws://127.0.0.1:${controllers.config.config.value.servicePort}/logs'), headers: headers);
  202. }
  203. Future<void> fetchStartInit() async {
  204. controllers.config.config.value.selected = 'init_proxy.yaml';
  205. controllers.global.updateMsg("启动内核---${controllers.config.config.value.selected}");
  206. if( controllers.config.config.value.selected == 'init_proxy.yaml'){
  207. controllers.global.updateMsg("启动内核初始化");
  208. } else {
  209. controllers.global.updateMsg("启动内核");
  210. }
  211. await fetchStop();
  212. try{
  213. var ut = Uri.http(url,'start');
  214. final body = json.encode({
  215. "args": [
  216. '-d',
  217. Paths.config.path,
  218. '-f',
  219. path.join(Paths.config.path, controllers.config.config.value.selected)
  220. ]
  221. });
  222. final res = await client.post(ut,body: body,headers: headers);
  223. var jsonResponse =
  224. jsonDecode(res.body) as Map<String, dynamic>;
  225. if (jsonResponse["code"] != 0) {
  226. coreStatus.value = RunningState.error;
  227. throw jsonResponse["msg"];
  228. }
  229. coreStatus.value = RunningState.running;
  230. } on http.ClientException catch (e) {
  231. // 处理客户端异常,例如没有网络连接
  232. print('Client Exception: ${e.message}');
  233. } on Exception catch (e) {
  234. // 处理其他类型的异常
  235. print('Exception: $e');
  236. }
  237. }
  238. Future<void> fetchStart() async {
  239. controllers.config.config.value.selected = 'proxy.yaml';
  240. controllers.global.updateMsg("启动内核---${controllers.config.config.value.selected}");
  241. if( controllers.config.config.value.selected == 'init_proxy.yaml'){
  242. controllers.global.updateMsg("启动内核初始化");
  243. } else {
  244. controllers.global.updateMsg("启动内核");
  245. }
  246. await fetchStop();
  247. try{
  248. var ut = Uri.http(url,'start');
  249. final res = await client.post(ut,body: {"args": ['-d', Paths.config.path, '-f', path.join(Paths.config.path, controllers.config.config.value.selected)]},headers: headers);
  250. var jsonResponse =
  251. jsonDecode(res.body) as Map<String, dynamic>;
  252. if (jsonResponse["code"] != 0) throw jsonResponse["msg"];
  253. } on http.ClientException catch (e) {
  254. // 处理客户端异常,例如没有网络连接
  255. print('Client Exception: ${e.message}');
  256. } on Exception catch (e) {
  257. // 处理其他类型的异常
  258. print('Exception: $e');
  259. }
  260. }
  261. Future<void> fetchSetProxy() async {
  262. try {
  263. var dns_ip = "";
  264. if(controllers.global.routeModesSelect.value == "tun"){
  265. dns_ip = "198.18.0.2";
  266. }
  267. var ut = Uri.http(url,'on');
  268. final body = json.encode({
  269. "http_port" : controllers.config.mixedPort.value,
  270. "https_port" : controllers.config.mixedPort.value,
  271. "socks_port" :controllers.config.mixedPort.value,
  272. "bypass": "127.0.0.1, 192.168.0.0/16, 10.0.0.0/8, 172.16.0.0/12, 100.64.0.0/10, 17.0.0.0/8, localhost, *.local, *.crashlytics.com, seed-sequoia.siri.apple.com, sequoia.apple.com,xd.apple.com",
  273. "dns_ip": dns_ip,
  274. "dns_type":"",
  275. "address":"127.0.0.1"
  276. });
  277. await client.post(ut,body: body,headers: headers);
  278. } on http.ClientException catch (e) {
  279. // 处理客户端异常,例如没有网络连接
  280. print('Client Exception: ${e.message}');
  281. } on Exception catch (e) {
  282. // 处理其他类型的异常
  283. print('Exception: $e');
  284. }
  285. }
  286. Future<void> fetchSetDnsProxy() async {
  287. try {
  288. var dns_ip = "";
  289. if(controllers.global.routeModesSelect.value == "tun"){
  290. dns_ip = "198.18.0.2";
  291. }
  292. var ut = Uri.http(url,'on');
  293. final body = json.encode({
  294. "http_port" : 0,
  295. "https_port" : 0,
  296. "socks_port" : 0,
  297. "bypass": "",
  298. "dns_ip": dns_ip,
  299. "dns_type":"",
  300. "address":"127.0.0.1"
  301. });
  302. await client.post(ut,body: body,headers: headers);
  303. } on http.ClientException catch (e) {
  304. // 处理客户端异常,例如没有网络连接
  305. print('Client Exception: ${e.message}');
  306. } on Exception catch (e) {
  307. // 处理其他类型的异常
  308. print('Exception: $e');
  309. }
  310. }
  311. Future<void> fetchSetProxyStop() async {
  312. try {
  313. var dnsIp = "";
  314. if(controllers.global.routeModesSelect.value == "tun"){
  315. dnsIp = "223.5.5.5";
  316. }
  317. var ut = Uri.http(url,'off');
  318. final body = json.encode({
  319. "bypass": "",
  320. "dns_ip": dnsIp
  321. });
  322. await client.post(ut,body:body,headers: headers);
  323. } on http.ClientException catch (e) {
  324. // 处理客户端异常,例如没有网络连接
  325. print('Client Exception: ${e.message}');
  326. } on Exception catch (e) {
  327. // 处理其他类型的异常
  328. print('Exception: $e');
  329. }
  330. }
  331. Future<void> fetchStop() async {
  332. try {
  333. var ut = Uri.http(url,'stop');
  334. await client.post(ut,headers:headers);
  335. } on http.ClientException catch (e) {
  336. // 处理客户端异常,例如没有网络连接
  337. print('Client Exception: ${e.message}');
  338. } on Exception catch (e) {
  339. // 处理其他类型的异常
  340. print('Exception: $e');
  341. }
  342. }
  343. Future<void> install() async {
  344. await initConfig();
  345. final res = await runAsAdmin(Files.assetsClashService.path, ["-port","${controllers.config.config.value.servicePort}","stop", "uninstall", "install", "start"]);
  346. log.debug('install', res.stdout, res.stderr);
  347. if (res.exitCode != 0) throw res.stderr;
  348. await waitServiceStart();
  349. }
  350. Future<void> uninstall() async {
  351. final res = await runAsAdmin(Files.assetsClashService.path, ["stop", "uninstall"]);
  352. log.debug('uninstall', res.stdout, res.stderr);
  353. if (res.exitCode != 0) throw res.stderr;
  354. await waitServiceStop();
  355. }
  356. Future<void> serviceModeSwitch(bool open) async {
  357. if (serviceStatus.value == RunningState.running) await stopService();
  358. if (coreStatus.value == RunningState.running) await stopClashCore();
  359. try {
  360. controllers.global.updateMsg(open ? "安装服务" : "卸载服务");
  361. open ? await install() : await uninstall();
  362. } catch (e) {
  363. BotToast.showText(text: e.toString());
  364. }
  365. await startService();
  366. await fetchStartInit();
  367. }
  368. Future<bool> isPortAvailable(int port) async {
  369. try {
  370. // 尝试绑定一个socket到指定的端口
  371. var server = await ServerSocket.bind(InternetAddress.anyIPv4, port);
  372. // 成功绑定后立即关闭
  373. await server.close();
  374. // 如果成功绑定并关闭了服务器,那么端口是可用的
  375. return true;
  376. } on SocketException {
  377. // 如果绑定失败,端口被占用
  378. return false;
  379. }
  380. }
  381. Future<bool> startClashCore() async {
  382. final timeout = const Duration(seconds: 30); // 设置超时时间为30秒
  383. final checkInterval = const Duration(milliseconds: 200);
  384. var startTime = DateTime.now();
  385. await controllers.config.readClashCoreApi();
  386. try {
  387. controllers.global.updateMsg("启动内核---${controllers.config.config.value.selected}");
  388. if( controllers.config.config.value.selected == 'init_proxy.yaml'){
  389. controllers.global.updateMsg("启动内核初始化");
  390. } else {
  391. controllers.global.updateMsg("启动内核");
  392. }
  393. coreStatus.value = RunningState.starting;
  394. if(serviceMode.value == true){
  395. await fetchStart();
  396. }
  397. else
  398. {
  399. int? exitCode;
  400. clashCoreProcess = await Process.start(Files.assetsCCore.path, ['-d', Paths.config.path, '-f', path.join(Paths.config.path, controllers.config.config.value.selected)], mode: ProcessStartMode.inheritStdio);
  401. clashCoreProcess!.exitCode.then((code) => exitCode = code);
  402. if (exitCode != null && exitCode != 0) {
  403. // 非零退出代码通常表示错误
  404. controllers.global.updateMsg("启动内核错误,请重启点电脑测试");
  405. return false;
  406. }
  407. }
  408. //
  409. log.debug("api${controllers.config.clashCoreApiAddress.value}");
  410. controllers.core.setApi(controllers.config.clashCoreApiAddress.value, controllers.config.clashCoreApiSecret.value);
  411. while (DateTime.now().difference(startTime) < timeout) {
  412. try {
  413. controllers.global.updateMsg("等待内核启动..");
  414. final ret = await controllers.core.fetchHello();
  415. // 如果fetchHello成功,跳出循环
  416. break;
  417. } catch (_) {
  418. // 如果fetchHello失败,等待200毫秒后重试
  419. await Future.delayed(checkInterval);
  420. }
  421. }
  422. // 检查是否超时
  423. if (DateTime.now().difference(startTime) >= timeout) {
  424. // 如果超时,更新状态并抛出异常
  425. coreStatus.value = RunningState.error;
  426. controllers.global.updateMsg("内核启动超时,重新点击加速后尝试。");
  427. return false; // 提前退出函数
  428. }
  429. await controllers.core.updateConfig();
  430. coreStatus.value = RunningState.running;
  431. controllers.global.updateMsg("内核状态:${coreStatus.value == RunningState.running} ");
  432. return true;
  433. } catch (e) {
  434. log.error("core -- $e");
  435. controllers.global.updateMsg("启动内核错误");
  436. //controllers.global.handleApiError(e);
  437. // BotToast.showText(text: e.toString());
  438. coreStatus.value = RunningState.error;
  439. return false;
  440. }
  441. }
  442. Future<void> stopClashCore() async {
  443. coreStatus.value = RunningState.stopping;
  444. await controllers.global.closeProxy();
  445. if(serviceMode.value == true){
  446. await fetchStop();
  447. }
  448. else{
  449. if(clashCoreProcess != null){
  450. clashCoreProcess?.kill();
  451. }
  452. }
  453. killProcess(ClashName.name);
  454. // if (Platform.isMacOS &&
  455. // controllers.service.serviceMode.value &&
  456. // controllers.config.clashCoreTunEnable.value &&
  457. // controllers.config.clashCoreDns.isNotEmpty) {
  458. // await MacSystemDns.instance.set([]);
  459. // }
  460. //if (controllers.config.config.value.setSystemProxy) await SystemProxy.instance.set(SystemProxyConfig());
  461. //await stopClash();
  462. coreStatus.value = RunningState.stoped;
  463. }
  464. Future<void> initClashCoreConfig() async {
  465. controllers.config.config.value.selected = 'init_proxy.yaml';
  466. //await stopClashCore();
  467. await startClashCore();
  468. if (coreStatus.value == RunningState.error) {
  469. controllers.global.updateMsg("启动内核失败...");
  470. //BotToast.showText(text: '重启失败');
  471. } else {
  472. await controllers.core.updateVersion();
  473. controllers.global.updateMsg("启动内核成功...");
  474. //BotToast.showText(text: '重启成功');
  475. }
  476. }
  477. Future<void> stopClash() async {
  478. controllers.config.config.value.selected = 'init_proxy.yaml';
  479. if( coreStatus.value == RunningState.running){
  480. await controllers.config.readClashCoreApi();
  481. controllers.core.setApi(controllers.config.clashCoreApiAddress.value, controllers.config.clashCoreApiSecret.value);
  482. await controllers.core.changeConfig(path.join(Paths.config.path, controllers.config.config.value.selected));
  483. }
  484. }
  485. Future<void> reloadClashCore() async {
  486. try
  487. {
  488. controllers.config.config.value.selected = 'proxy.yaml';
  489. if( coreStatus.value == RunningState.running){
  490. controllers.global.updateMsg("切换配置...");
  491. await controllers.config.readClashCoreApi();
  492. //controllers.global.updateMsg("${controllers.config.clashCoreApiAddress.value}...");
  493. controllers.core.setApi(controllers.config.clashCoreApiAddress.value, controllers.config.clashCoreApiSecret.value);
  494. //controllers.global.updateMsg("setApi${controllers.config.clashCoreApiAddress.value}...");
  495. await controllers.core.changeConfig(path.join(Paths.config.path, controllers.config.config.value.selected));
  496. controllers.global.updateMsg("fetchReloadConfig${controllers.config.clashCoreApiAddress.value}...");
  497. }
  498. } catch(e){
  499. controllers.global.updateMsg("重新配置...");
  500. await controllers.config.readClashCoreApi();
  501. //controllers.global.updateMsg("${controllers.config.clashCoreApiAddress.value}...");
  502. controllers.core.setApi(controllers.config.clashCoreApiAddress.value, controllers.config.clashCoreApiSecret.value);
  503. //controllers.global.updateMsg("setApi${controllers.config.clashCoreApiAddress.value}...");
  504. await controllers.core.changeConfig(path.join(Paths.config.path, controllers.config.config.value.selected));
  505. }
  506. //BotToast.showText(text: '正在重启 Core ……');
  507. // controllers.global.updateMsg("停止内核...");
  508. // await stopClashCore();
  509. // await controllers.config.readClashCoreApi();
  510. // await startClashCore();
  511. // if (coreStatus.value == RunningState.error) {
  512. // controllers.global.updateMsg("启动内核失败...");
  513. // } else {
  514. // await controllers.core.updateVersion();
  515. // controllers.global.updateMsg("启动内核成功...");
  516. // }
  517. }
  518. Future<int> getFreePort() async {
  519. var server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  520. int port = server.port;
  521. await server.close();
  522. return port;
  523. }
  524. }