Fix some issues

Optimize Windows service mode

Update core
This commit is contained in:
chen08209
2025-09-23 21:02:47 +08:00
parent 2ab70f193a
commit 45b163184d
29 changed files with 300 additions and 180 deletions

View File

@@ -1,5 +1,6 @@
import 'dart:async';
import 'package:fl_clash/common/common.dart';
import 'package:fl_clash/enum/enum.dart';
class Debouncer {
@@ -68,7 +69,7 @@ Future<T> retry<T>({
required Future<T> Function() task,
int maxAttempts = 3,
required bool Function(T res) retryIf,
Duration delay = Duration.zero,
Duration delay = midDuration,
}) async {
int attempts = 0;
while (attempts < maxAttempts) {
@@ -78,7 +79,7 @@ Future<T> retry<T>({
}
attempts++;
}
throw 'unknown error';
throw 'retry error';
}
final debouncer = Debouncer();

View File

@@ -71,6 +71,11 @@ class AppPath {
return join(homeDirPath, 'config.json');
}
Future<String> get validateFilePath async {
final homeDirPath = await appPath.homeDirPath;
return join(homeDirPath, 'temp', 'validate${utils.id}.yaml');
}
Future<String> get sharedPreferencesPath async {
final directory = await dataDir.future;
return join(directory.path, 'shared_preferences.json');

View File

@@ -186,26 +186,26 @@ class Windows {
logLevel: LogLevel.warning,
);
if (result < 42) {
if (result <= 32) {
return false;
}
return true;
}
Future<void> _killProcess(int port) async {
final result = await Process.run('netstat', ['-ano']);
final lines = result.stdout.toString().trim().split('\n');
for (final line in lines) {
if (!line.contains(':$port') || !line.contains('LISTENING')) {
continue;
}
final parts = line.trim().split(RegExp(r'\s+'));
final pid = int.tryParse(parts.last);
if (pid != null) {
await Process.run('taskkill', ['/PID', pid.toString(), '/F']);
}
}
}
// Future<void> _killProcess(int port) async {
// final result = await Process.run('netstat', ['-ano']);
// final lines = result.stdout.toString().trim().split('\n');
// for (final line in lines) {
// if (!line.contains(':$port') || !line.contains('LISTENING')) {
// continue;
// }
// final parts = line.trim().split(RegExp(r'\s+'));
// final pid = int.tryParse(parts.last);
// if (pid != null) {
// await Process.run('taskkill', ['/PID', pid.toString(), '/F']);
// }
// }
// }
Future<WindowsHelperServiceStatus> checkService() async {
// final qcResult = await Process.run('sc', ['qc', appHelperService]);
@@ -231,16 +231,18 @@ class Windows {
return true;
}
await _killProcess(helperPort);
final command = [
'/c',
if (status == WindowsHelperServiceStatus.presence) ...[
'sc',
'taskkill',
'/F',
'/IM',
'$appHelperService.exe'
' & '
'sc',
'delete',
appHelperService,
'/force',
'&&',
'&',
],
'sc',
'create',
@@ -256,8 +258,12 @@ class Windows {
final res = runas('cmd.exe', command);
await Future.delayed(Duration(milliseconds: 300));
return res;
final retryStatus = await retry(
task: checkService,
retryIf: (status) => status == WindowsHelperServiceStatus.running,
delay: commonDuration,
);
return res && retryStatus == WindowsHelperServiceStatus.running;
}
Future<bool> registerTask(String appName) async {

View File

@@ -322,12 +322,15 @@ class Utils {
return SingleActivator(trigger, control: control, meta: !control);
}
FutureOr<T> handleWatch<T>(Function function) async {
FutureOr<T> handleWatch<T>({
required Function function,
required void Function(T data, int elapsedMilliseconds) onWatch,
}) async {
if (kDebugMode) {
final stopwatch = Stopwatch()..start();
final res = await function();
stopwatch.stop();
commonPrint.log('耗时:${stopwatch.elapsedMilliseconds} ms');
onWatch(res, stopwatch.elapsedMilliseconds);
return res;
}
return await function();

View File

@@ -71,8 +71,20 @@ class CoreController {
FutureOr<bool> get isInit => _interface.isInit;
FutureOr<String> validateConfig(String data) {
return _interface.validateConfig(data);
Future<String> validateConfig(String data) async {
final path = await appPath.validateFilePath;
await globalState.genValidateFile(path, data);
final res = await _interface.validateConfig(path);
await File(path).delete();
return res;
}
Future<String> validateConfigFormBytes(Uint8List bytes) async {
final path = await appPath.validateFilePath;
await globalState.genValidateFileFormBytes(path, bytes);
final res = await _interface.validateConfig(path);
await File(path).delete();
return res;
}
Future<String> updateConfig(UpdateParams updateParams) async {

View File

@@ -5,6 +5,7 @@ import 'dart:isolate';
import 'package:fl_clash/common/common.dart';
import 'package:fl_clash/enum/enum.dart';
import 'package:fl_clash/models/models.dart';
import 'package:flutter/foundation.dart';
mixin CoreInterface {
Future<bool> init(InitParams params);
@@ -17,7 +18,7 @@ mixin CoreInterface {
Future<bool> forceGc();
Future<String> validateConfig(String data);
Future<String> validateConfig(String path);
Future<Result> getConfig(String path);
@@ -86,7 +87,18 @@ abstract class CoreHandlerInterface with CoreInterface {
Duration? timeout,
}) async {
await connected;
return invoke(method: method, data: data, timeout: timeout);
if (kDebugMode) {
commonPrint.log('Invoke ${method.name} ${DateTime.now()} $data');
}
return utils.handleWatch(
function: () async {
return await invoke(method: method, data: data, timeout: timeout);
},
onWatch: (data, elapsedMilliseconds) {
commonPrint.log('Invoke ${method.name} ${elapsedMilliseconds}ms');
},
);
}
Future<T?> invoke<T>({
@@ -125,10 +137,10 @@ abstract class CoreHandlerInterface with CoreInterface {
}
@override
Future<String> validateConfig(String data) async {
Future<String> validateConfig(String path) async {
return await _invoke<String>(
method: ActionMethod.validateConfig,
data: data,
data: path,
) ??
'';
}

View File

@@ -38,23 +38,29 @@ class CoreService extends CoreHandlerInterface {
completer?.complete(data);
}
void _initServer() {
runZonedGuarded(
() async {
final address = !system.isWindows
? InternetAddress(unixSocketPath, type: InternetAddressType.unix)
: InternetAddress(localhost, type: InternetAddressType.IPv4);
await _deleteSocketFile();
final server = await ServerSocket.bind(address, 0, shared: true);
_serverCompleter.complete(server);
await for (final socket in server) {
await _attachSocket(socket);
Future<void> _initServer() async {
final server = await retry(
task: () async {
try {
final address = !system.isWindows
? InternetAddress(unixSocketPath, type: InternetAddressType.unix)
: InternetAddress(localhost, type: InternetAddressType.IPv4);
await _deleteSocketFile();
final server = await ServerSocket.bind(address, 0, shared: true);
server.listen((socket) async {
await _attachSocket(socket);
});
return server;
} catch (_) {
return null;
}
},
(error, stack) async {
commonPrint.log('Service error: $error', logLevel: LogLevel.warning);
},
retryIf: (server) => server == null,
);
if (server == null) {
exit(0);
}
_serverCompleter.complete(server);
}
Future<void> _attachSocket(Socket socket) async {

View File

@@ -1,4 +1,3 @@
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
@@ -174,7 +173,7 @@ extension ProfileExtension on Profile {
}
Future<Profile> saveFile(Uint8List bytes) async {
final message = await coreController.validateConfig(utf8.decode(bytes));
final message = await coreController.validateConfigFormBytes(bytes);
if (message.isNotEmpty) {
throw message;
}
@@ -182,14 +181,4 @@ extension ProfileExtension on Profile {
await file.writeAsBytes(bytes);
return copyWith(lastUpdateDate: DateTime.now());
}
Future<Profile> saveFileWithString(String value) async {
final message = await coreController.validateConfig(value);
if (message.isNotEmpty) {
throw message;
}
final file = await getFile();
await file.writeAsString(value);
return copyWith(lastUpdateDate: DateTime.now());
}
}

View File

@@ -239,7 +239,7 @@ class GlobalState {
return VpnOptions(
stack: config.patchClashConfig.tun.stack.name,
enable: vpnProps.enable,
systemProxy: networkProps.systemProxy,
systemProxy: vpnProps.systemProxy,
port: port,
ipv6: vpnProps.ipv6,
dnsHijacking: vpnProps.dnsHijacking,
@@ -323,6 +323,42 @@ class GlobalState {
}
}
Future<void> genValidateFile(String path, String data) async {
final res = await Isolate.run<String>(() async {
try {
final file = File(path);
if (!await file.exists()) {
await file.create(recursive: true);
}
await file.writeAsString(data);
return '';
} catch (e) {
return e.toString();
}
});
if (res.isNotEmpty) {
throw res;
}
}
Future<void> genValidateFileFormBytes(String path, Uint8List bytes) async {
final res = await Isolate.run<String>(() async {
try {
final file = File(path);
if (!await file.exists()) {
await file.create(recursive: true);
}
await file.writeAsBytes(bytes);
return '';
} catch (e) {
return e.toString();
}
});
if (res.isNotEmpty) {
throw res;
}
}
AndroidState getAndroidState() {
return AndroidState(
currentProfileName: config.currentProfile?.label ?? '',