service.dart 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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/const/const.dart';
  8. import 'package:naiyouwl/app/controller/controllers.dart';
  9. import 'package:naiyouwl/app/utils/logger.dart';
  10. import 'package:naiyouwl/app/utils/shell.dart';
  11. import 'package:naiyouwl/app/utils/system_dns.dart';
  12. import 'package:naiyouwl/app/utils/system_proxy.dart';
  13. import 'package:naiyouwl/app/utils/utils.dart';
  14. import 'package:path/path.dart' as path;
  15. import 'package:flutter/foundation.dart';
  16. import 'package:bot_toast/bot_toast.dart';
  17. import 'package:web_socket_channel/io.dart';
  18. final headers = {"User-Agent": "ccore-for-flutter/0.0.1"};
  19. class ServiceController extends GetxController {
  20. late final dio ;
  21. var serviceMode = false.obs;
  22. var servicePort = 0.obs;
  23. var coreStatus = RunningState.stoped.obs;
  24. var serviceStatus = RunningState.stoped.obs;
  25. Process? clashServiceProcess;
  26. bool get isRunning => serviceStatus.value == RunningState.running && coreStatus.value == RunningState.running;
  27. bool get isCanOperationService =>
  28. ![RunningState.starting, RunningState.stopping].contains(serviceStatus.value) &&
  29. ![RunningState.starting, RunningState.stopping].contains(coreStatus.value);
  30. bool get isCanOperationCore =>
  31. serviceStatus.value == RunningState.running && ![RunningState.starting, RunningState.stopping].contains(coreStatus.value);
  32. ServiceController();
  33. Future<void> startService() async {
  34. servicePort.value = controllers.config.config.value.port;
  35. print('http://127.0.0.1:${servicePort.value}');
  36. dio = Dio(BaseOptions(baseUrl: 'http://127.0.0.1:${servicePort.value}', headers: headers));
  37. serviceStatus.value = RunningState.starting;
  38. if (Platform.isLinux) {
  39. await fixBinaryExecutePermissions(Files.assetsClashService);
  40. await fixBinaryExecutePermissions(Files.assetsClashCore);
  41. }
  42. try {
  43. final data = await fetchInfo();
  44. serviceMode.value = data.mode == 'service-mode';
  45. } catch (e) {
  46. await startUserModeService();
  47. if (serviceStatus.value == RunningState.error) return;
  48. }
  49. serviceStatus.value = RunningState.running;
  50. }
  51. Future<void> fixBinaryExecutePermissions(File file) async {
  52. final stat = await file.stat();
  53. // 0b001000000
  54. final has = (stat.mode & 64) == 64;
  55. if (has) return;
  56. await Process.run('chmod', ['+x', file.path]);
  57. }
  58. Future<void> startUserModeService() async {
  59. serviceMode.value = false;
  60. try {
  61. int? exitCode;
  62. clashServiceProcess = await Process.start(Files.assetsClashService.path, ['user-mode'], mode: ProcessStartMode.inheritStdio);
  63. clashServiceProcess!.exitCode.then((code) => exitCode = code);
  64. while (true) {
  65. await Future.delayed(const Duration(milliseconds: 200));
  66. if (exitCode == 101) {
  67. BotToast.showText(text: 'clash-service exit with code: $exitCode,After 10 seconds, try to restart');
  68. log.error('After 10 seconds, try to restart');
  69. await Future.delayed(const Duration(seconds: 10));
  70. await startUserModeService();
  71. break;
  72. } else if (exitCode != null) {
  73. serviceStatus.value = RunningState.error;
  74. break;
  75. }
  76. try {
  77. await dio.post('/info');
  78. break;
  79. } catch (_) {}
  80. }
  81. } catch (e) {
  82. serviceStatus.value = RunningState.error;
  83. BotToast.showText(text: e.toString());
  84. }
  85. }
  86. Future<void> stopService() async {
  87. serviceStatus.value = RunningState.stopping;
  88. if (coreStatus.value == RunningState.running) await stopClashCore();
  89. if (!serviceMode.value) {
  90. if (clashServiceProcess != null) {
  91. clashServiceProcess!.kill();
  92. clashServiceProcess = null;
  93. } else if (kDebugMode) {
  94. await killProcess(path.basename(Files.assetsClashService.path));
  95. }
  96. }
  97. serviceStatus.value = RunningState.stoped;
  98. }
  99. // for macos
  100. Future<void> waitServiceStart() async {
  101. while (true) {
  102. await Future.delayed(const Duration(milliseconds: 100));
  103. try {
  104. await dio.post('/info');
  105. break;
  106. } catch (_) {}
  107. }
  108. }
  109. // for windows
  110. Future<void> waitServiceStop() async {
  111. while (true) {
  112. await Future.delayed(const Duration(milliseconds: 100));
  113. try {
  114. await dio.post('/info');
  115. } catch (e) {
  116. break;
  117. }
  118. }
  119. }
  120. Future<ClashServiceInfo> fetchInfo() async {
  121. final res = await dio.post('/info');
  122. return ClashServiceInfo.fromJson(res.data);
  123. }
  124. IOWebSocketChannel fetchLogWs() {
  125. return IOWebSocketChannel.connect(Uri.parse('ws://127.0.0.1:${servicePort.value}/logs'), headers: headers);
  126. }
  127. Future<void> fetchStart(String name) async {
  128. await fetchStop();
  129. final res = await dio.post<String>('/start', data: {
  130. "args": ['-d', Paths.config.path, '-f', path.join(Paths.config.path, name)]
  131. });
  132. if (json.decode(res.data!)["code"] != 0) throw json.decode(res.data!)["msg"];
  133. }
  134. Future<void> fetchStop() async {
  135. await dio.post('/stop');
  136. }
  137. Future<void> install() async {
  138. final res = await runAsAdmin(Files.assetsClashService.path, ["stop", "uninstall", "install", "start"]);
  139. log.debug('install', res.stdout, res.stderr);
  140. if (res.exitCode != 0) throw res.stderr;
  141. await waitServiceStart();
  142. }
  143. Future<void> uninstall() async {
  144. final res = await runAsAdmin(Files.assetsClashService.path, ["stop", "uninstall"]);
  145. log.debug('uninstall', res.stdout, res.stderr);
  146. if (res.exitCode != 0) throw res.stderr;
  147. await waitServiceStop();
  148. }
  149. Future<void> serviceModeSwitch(bool open) async {
  150. if (serviceStatus.value == RunningState.running) await stopService();
  151. try {
  152. open ? await install() : await uninstall();
  153. } catch (e) {
  154. BotToast.showText(text: e.toString());
  155. }
  156. await startService();
  157. await startClashCore();
  158. }
  159. Future<void> startClashCore() async {
  160. try {
  161. coreStatus.value = RunningState.starting;
  162. await fetchStart(controllers.config.config.value.selected);
  163. controllers.core.setApi(controllers.config.clashCoreApiAddress.value, controllers.config.clashCoreApiSecret.value);
  164. while (true) {
  165. await Future.delayed(const Duration(milliseconds: 200));
  166. final info = await fetchInfo();
  167. if (info.status == 'running') {
  168. try {
  169. await controllers.core.fetchHello();
  170. break;
  171. } catch (_) {}
  172. } else {
  173. throw 'clash-core start error';
  174. }
  175. }
  176. await controllers.core.updateConfig();
  177. if (Platform.isMacOS &&
  178. controllers.service.serviceMode.value &&
  179. controllers.config.clashCoreTunEnable.value &&
  180. controllers.config.clashCoreDns.isNotEmpty) {
  181. await MacSystemDns.instance.set([controllers.config.clashCoreDns.value]);
  182. }
  183. if (controllers.config.config.value.setSystemProxy) await SystemProxy.instance.set(controllers.core.proxyConfig);
  184. coreStatus.value = RunningState.running;
  185. } catch (e) {
  186. log.error(e);
  187. BotToast.showText(text: e.toString());
  188. coreStatus.value = RunningState.error;
  189. }
  190. }
  191. Future<void> stopClashCore() async {
  192. coreStatus.value = RunningState.stopping;
  193. if (Platform.isMacOS &&
  194. controllers.service.serviceMode.value &&
  195. controllers.config.clashCoreTunEnable.value &&
  196. controllers.config.clashCoreDns.isNotEmpty) {
  197. await MacSystemDns.instance.set([]);
  198. }
  199. if (controllers.config.config.value.setSystemProxy) await SystemProxy.instance.set(SystemProxyConfig());
  200. await fetchStop();
  201. coreStatus.value = RunningState.stoped;
  202. }
  203. Future<void> reloadClashCore() async {
  204. BotToast.showText(text: '正在重启 Clash Core ……');
  205. await stopClashCore();
  206. await controllers.config.readClashCoreApi();
  207. await startClashCore();
  208. if (coreStatus.value == RunningState.error) {
  209. BotToast.showText(text: '重启失败');
  210. } else {
  211. await controllers.core.updateVersion();
  212. BotToast.showText(text: '重启成功');
  213. }
  214. }
  215. Future<int> getFreePort() async {
  216. var server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  217. int port = server.port;
  218. await server.close();
  219. return port;
  220. }
  221. }