Merge branch 'meta-proc' into meta-dev

This commit is contained in:
mrFq1 2022-07-27 13:24:12 +08:00
commit 384de6e3c9
21 changed files with 313 additions and 170 deletions

View File

@ -7,6 +7,8 @@
objects = {
/* Begin PBXBuildFile section */
015F1E91288E42A50052B20A /* ClashMetaConfig.swift in Sources */ = {isa = PBXBuildFile; fileRef = 015F1E90288E42A50052B20A /* ClashMetaConfig.swift */; };
015F1E92288E60D30052B20A /* MetaTask.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0162E74E2864B819007218A6 /* MetaTask.swift */; };
0162E74F2864B819007218A6 /* MetaTask.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0162E74E2864B819007218A6 /* MetaTask.swift */; };
018F88F9286DD0CB004DD0F7 /* DualTitleMenuItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 018F88F8286DD0CB004DD0F7 /* DualTitleMenuItem.swift */; };
01943259287D19BC008CC51A /* ClashRuleProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 01943258287D19BC008CC51A /* ClashRuleProvider.swift */; };
@ -131,6 +133,7 @@
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
015F1E90288E42A50052B20A /* ClashMetaConfig.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClashMetaConfig.swift; sourceTree = "<group>"; };
0162E74D2864B818007218A6 /* com.metacubex.ClashX.ProxyConfigHelper-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "com.metacubex.ClashX.ProxyConfigHelper-Bridging-Header.h"; sourceTree = "<group>"; };
0162E74E2864B819007218A6 /* MetaTask.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MetaTask.swift; sourceTree = "<group>"; };
018F88F8286DD0CB004DD0F7 /* DualTitleMenuItem.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DualTitleMenuItem.swift; sourceTree = "<group>"; };
@ -325,6 +328,7 @@
491C250121BD561200AB5D44 /* Managers */,
491C250021BD55B900AB5D44 /* Utils */,
492C4868210EE6B9004554A0 /* ApiRequest.swift */,
015F1E90288E42A50052B20A /* ClashMetaConfig.swift */,
);
path = General;
sourceTree = "<group>";
@ -709,6 +713,7 @@
49722FEF211F338B00650A41 /* FileEvent.swift in Sources */,
49D176A72355FE680093DD7B /* NetworkChangeNotifier.swift in Sources */,
4913C82321157D0200F6B87C /* Notification.swift in Sources */,
015F1E91288E42A50052B20A /* ClashMetaConfig.swift in Sources */,
8ACD21BD27A04ED500BC4632 /* ProxyModeChangeCommand.swift in Sources */,
49228457270AADE20027A4B6 /* RemoteConfigUpdateIntervalSettingView.swift in Sources */,
F9203A26236342820020D57D /* AppDelegate+..swift in Sources */,
@ -729,6 +734,7 @@
F92D0B2A236C759100575E15 /* NSTextField+Vibrancy.swift in Sources */,
F910AA24240134AF00116E95 /* ProxyGroupMenu.swift in Sources */,
4952C3BF2115C7CA004A4FA8 /* MenuItemFactory.swift in Sources */,
015F1E92288E60D30052B20A /* MetaTask.swift in Sources */,
F977FAAC2366790500C17F1F /* AutoUpgardeManager.swift in Sources */,
499A485822ED715200F6C675 /* RemoteConfigModel.swift in Sources */,
49D176AB23575BB20093DD7B /* ProxyGroupMenuItemView.swift in Sources */,

View File

@ -12,6 +12,8 @@ import LetsMove
import RxCocoa
import RxSwift
import SwiftyJSON
import Yams
import PromiseKit
private let statusItemLengthWithSpeed: CGFloat = 72
@ -298,11 +300,11 @@ class AppDelegate: NSObject, NSApplicationDelegate {
.observe(on: MainScheduler.instance)
.bind(onNext: { _ in
self.initMetaCore()
self.updateConfig(showNotification: false)
self.startProxy()
}).disposed(by: disposeBag)
} else {
initMetaCore()
updateConfig(showNotification: false)
startProxy()
}
}
@ -443,6 +445,7 @@ class AppDelegate: NSObject, NSApplicationDelegate {
}
}()
RemoteConfigManager.shared.verifyConfigTask.setLaunchPath(corePath)
PrivilegedHelperManager.shared.helper()?.initMetaCore(withPath: corePath)
Logger.log("initClashCore finish")
}
@ -515,28 +518,14 @@ class AppDelegate: NSObject, NSApplicationDelegate {
let log: String?
}
// setup ui config first
if let htmlPath = Bundle.main.path(forResource: "index", ofType: "html", inDirectory: "dashboard") {
let uiPath = URL(fileURLWithPath: htmlPath).deletingLastPathComponent().path
PrivilegedHelperManager.shared.helper()?.metaSetUIPath(uiPath)
}
let config = ClashMetaConfig.generateInitConfig()
Logger.log("Trying start proxy")
var string = ""
let queue = DispatchGroup()
queue.enter()
PrivilegedHelperManager.shared.helper {
string = "Can't connect to helper."
queue.leave()
}?.startMeta(withConfPath: kConfigFolderPath,
confFilePath: "") {
string = $0 ?? ""
queue.leave()
Logger.log("Trying start meta core")
startMeta(config).map { string -> String in
guard let jsonData = string.data(using: .utf8),
let res = try? JSONDecoder().decode(StartProxyResp.self, from: jsonData) else {
return string == "" ? "unknown error" : string
}
queue.wait()
let jsonData = string.data(using: .utf8) ?? Data()
if let res = try? JSONDecoder().decode(StartProxyResp.self, from: jsonData) {
if let log = res.log {
Logger.log("""
@ -550,17 +539,59 @@ class AppDelegate: NSObject, NSApplicationDelegate {
ConfigManager.shared.apiPort = port
ConfigManager.shared.apiSecret = res.secret
ConfigManager.shared.isRunning = true
proxyModeMenuItem.isEnabled = true
dashboardMenuItem.isEnabled = true
setupSystemData()
} else {
self.proxyModeMenuItem.isEnabled = true
self.dashboardMenuItem.isEnabled = true
return ""
}.then {
self.pushInitConfig($0)
}.done { s in
if s != "" {
ConfigManager.shared.isRunning = false
proxyModeMenuItem.isEnabled = false
Logger.log(string, level: .error)
NSUserNotificationCenter.default.postConfigErrorNotice(msg: string)
self.proxyModeMenuItem.isEnabled = false
Logger.log(s, level: .error)
NSUserNotificationCenter.default.postConfigErrorNotice(msg: s)
} else {
Logger.log("Init config file success.")
}
}.catch { _ in }
}
func startMeta(_ config: ClashMetaConfig.Config) -> Promise<String> {
.init { resolver in
PrivilegedHelperManager.shared.helper {
resolver.fulfill("Can't connect to helper.")
}?.startMeta(withConfPath: kConfigFolderPath,
confFilePath: config.path) {
resolver.fulfill($0 ?? "")
}
}
}
func pushInitConfig(_ s: String) -> Promise<String> {
.init { resolver in
guard s == "" else {
resolver.fulfill(s)
return
}
ClashProxy.cleanCache()
let configName = ConfigManager.selectConfigName
Logger.log("Push init config file: \(configName)")
ApiRequest.requestConfigUpdate(configName: configName) { err in
if let error = err {
resolver.fulfill(error)
} else {
self.syncConfig()
self.resetStreamApi()
self.runAfterConfigReload?()
self.runAfterConfigReload = nil
self.selectProxyGroupWithMemory()
self.selectOutBoundModeWithMenory()
MenuItemFactory.recreateProxyMenuItems()
NotificationCenter.default.post(name: .reloadDashboard, object: nil)
resolver.fulfill("")
}
}
}
Logger.log("Start proxy done")
}
func syncConfig(completeHandler: (() -> Void)? = nil) {
@ -868,7 +899,6 @@ extension AppDelegate {
@IBAction func actionUpdateProxyGroupMenu(_ sender: Any) {
ConfigManager.shared.disableShowCurrentProxyInMenu = !ConfigManager.shared.disableShowCurrentProxyInMenu
updateExperimentalFeatureStatus()
print("211")
MenuItemFactory.recreateProxyMenuItems()
}
@ -938,13 +968,13 @@ extension AppDelegate {
}
@IBAction func updateGEO(_ sender: NSMenuItem) {
ApiRequest.updateGEO() { _ in
ApiRequest.updateGEO { _ in
NSUserNotificationCenter.default.post(title: "Updating GEO Databases...", info: "Good luck to you 🙃")
}
}
@IBAction func flushFakeipCache(_ sender: NSMenuItem) {
ApiRequest.flushFakeipCache() {
ApiRequest.flushFakeipCache {
NSUserNotificationCenter.default.post(title: "Flush fake-ip cache", info: $0 ? "Success" : "Failed")
}
}

View File

@ -0,0 +1,89 @@
//
// ClashMetaConfig.swift
// ClashX Meta
import Foundation
import Cocoa
import Yams
class ClashMetaConfig: NSObject {
struct Config: Codable {
var externalUI: String? = {
guard let htmlPath = Bundle.main.path(forResource: "index", ofType: "html", inDirectory: "dashboard") else {
return nil
}
return URL(fileURLWithPath: htmlPath).deletingLastPathComponent().path
}()
var externalController = "127.0.0.1:9090"
var secret: String?
var port: Int?
var socksPort: Int?
var mixedPort: Int?
var logLevel = ConfigManager.selectLoggingApiLevel.rawValue
var path: String {
get {
guard let s = try? YAMLEncoder().encode(self),
let path = RemoteConfigManager.createCacheConfig(string: s) else {
assertionFailure("Create init config file failed.")
return ""
}
return path
}
}
enum CodingKeys: String, CodingKey {
case externalController = "external-controller",
externalUI = "external-ui",
mixedPort = "mixed-port",
port,
socksPort = "socks-port",
logLevel = "log-level",
secret
}
mutating func loadDefaultConfigFile() {
let fm = FileManager.default
guard let data = fm.contents(atPath: kDefaultConfigFilePath),
let string = String(data: data, encoding: .utf8),
let yaml = try? Yams.load(yaml: string) as? [String: Any] else {
return
}
let keys = Config.CodingKeys.self
if let ec = yaml[keys.externalController.rawValue] as? String {
externalController = ec
}
if let s = yaml[keys.secret.rawValue] as? String {
secret = s
}
if let port = yaml[keys.mixedPort.rawValue] as? Int {
mixedPort = port
} else {
if let p = yaml[keys.port.rawValue] as? Int {
port = p
}
if let sp = yaml[keys.socksPort.rawValue] as? Int {
socksPort = sp
}
}
if port == nil && mixedPort == nil {
mixedPort = 7890
}
}
}
static func generateInitConfig() -> Config {
var config = Config()
config.loadDefaultConfigFile()
return config
}
}

View File

@ -7,7 +7,7 @@
//
import Cocoa
//import Sparkle
// import Sparkle
class AutoUpgardeManager: NSObject {
static let shared = AutoUpgardeManager()
@ -72,7 +72,7 @@ extension AutoUpgardeManager {
}
}
//extension AutoUpgardeManager: SUUpdaterDelegate {
// extension AutoUpgardeManager: SUUpdaterDelegate {
// func feedURLString(for updater: SUUpdater) -> String? {
// return current.urlString
// }
@ -80,7 +80,7 @@ extension AutoUpgardeManager {
// func updaterWillRelaunchApplication(_ updater: SUUpdater) {
// SystemProxyManager.shared.disableProxy(port: 0, socksPort: 0, forceDisable: true)
// }
//}
// }
// MARK: - Channel Enum

View File

@ -301,7 +301,6 @@ extension MenuItemFactory {
}
}
// MARK: - Meta
extension MenuItemFactory {

View File

@ -13,6 +13,8 @@ class RemoteConfigManager {
var configs: [RemoteConfigModel] = []
var refreshActivity: NSBackgroundActivityScheduler?
let verifyConfigTask = MetaTask()
static let shared = RemoteConfigManager()
private init() {
@ -205,29 +207,28 @@ class RemoteConfigManager {
}
}
static func verifyConfig(string: String) -> ErrorString? {
var res: String?
static func createCacheConfig(string: String) -> String? {
let path = NSTemporaryDirectory().appending("com.MetaCubeX.ClashX.meta")
let confPath = path + "/\(UUID().uuidString).yaml"
let fm = FileManager.default
try? fm.createDirectory(atPath: path, withIntermediateDirectories: true)
guard fm.createFile(atPath: confPath, contents: string.data(using: .utf8)) else {
return "Create verify config file failed"
if fm.fileExists(atPath: confPath) {
try? fm.removeItem(atPath: confPath)
}
let queue = DispatchGroup()
queue.enter()
PrivilegedHelperManager.shared.helper {
res = "unknown error"
queue.leave()
}?.verifyMeta(withConfPath: kConfigFolderPath, confFilePath: "", result: {
res = $0
queue.leave()
})
guard fm.createFile(atPath: confPath, contents: string.data(using: .utf8)) else {
return nil
}
return confPath
}
queue.wait()
return res
static func verifyConfig(string: String) -> ErrorString? {
guard let confPath = createCacheConfig(string: string) else {
return "Create verify config file failed"
}
return RemoteConfigManager.shared.verifyConfigTask.test(kConfigFolderPath, confFilePath: confPath)
}
static func showAdd() {

View File

@ -2,9 +2,11 @@
## 配置文件需要放置在 $HOME/.config/clash/*.yaml
## 这份文件是clashX的基础配置文件请尽量新建配置文件进行修改。
## 只有这份文件的端口设置会随ClashX启动生效
## 如果您不知道如何操作,请参阅 官方Github文档 https://github.com/Dreamacro/clash/blob/dev/README.md
## 如果您不知道如何操作,请参阅
## Clash Meta wiki https://docs.metacubex.one
## Clash Meta Github文档 https://github.com/MetaCubeX/Clash.Meta/blob/Alpha/README.md
#---------------------------------------------------#
# (HTTP and SOCKS5 in one port)
@ -14,11 +16,18 @@ external-controller: 127.0.0.1:9090
allow-lan: false
mode: rule
log-level: warning
ipv6: false
proxies:
proxy-groups:
proxy-providers:
rule-providers:
rules:
- DOMAIN-SUFFIX,google.com,DIRECT
- DOMAIN-KEYWORD,google,DIRECT

View File

@ -2,7 +2,6 @@
// DualTitleMenuItem.swift
// ClashX
import Cocoa
class DualTitleMenuItem: NSMenuItem {

View File

@ -28,5 +28,7 @@ target 'ClashX Meta' do
pod 'Starscream','3.1.1'
pod "FlexibleDiff"
pod 'GzipSwift'
pod 'Yams'
pod "PromiseKit", "~> 6.8"
end

View File

@ -6,6 +6,13 @@ PODS:
- FlexibleDiff (0.0.9)
- GzipSwift (5.1.1)
- LetsMove (1.25)
- PromiseKit (6.18.0):
- PromiseKit/CorePromise (= 6.18.0)
- PromiseKit/Foundation (= 6.18.0)
- PromiseKit/UIKit (= 6.18.0)
- PromiseKit/CorePromise (6.18.0)
- PromiseKit/Foundation (6.18.0):
- PromiseKit/CorePromise
- RxCocoa (6.5.0):
- RxRelay (= 6.5.0)
- RxSwift (= 6.5.0)
@ -15,6 +22,7 @@ PODS:
- Starscream (3.1.1)
- SwiftyJSON (5.0.1)
- WebViewJavascriptBridge (6.0.3)
- Yams (5.0.0)
DEPENDENCIES:
- Alamofire (~> 5.0)
@ -22,11 +30,13 @@ DEPENDENCIES:
- FlexibleDiff
- GzipSwift
- LetsMove
- PromiseKit (~> 6.8)
- RxCocoa
- RxSwift
- Starscream (= 3.1.1)
- SwiftyJSON
- WebViewJavascriptBridge
- Yams
SPEC REPOS:
trunk:
@ -35,12 +45,14 @@ SPEC REPOS:
- FlexibleDiff
- GzipSwift
- LetsMove
- PromiseKit
- RxCocoa
- RxRelay
- RxSwift
- Starscream
- SwiftyJSON
- WebViewJavascriptBridge
- Yams
SPEC CHECKSUMS:
Alamofire: 87bd8c952f9a4454320fce00d9cc3de57bcadaf5
@ -48,13 +60,15 @@ SPEC CHECKSUMS:
FlexibleDiff: b9ee9b8305b42c784f5dd40589203c97c55bbaa0
GzipSwift: 893f3e48e597a1a4f62fafcb6514220fcf8287fa
LetsMove: 7b9fe44737707d984fbd3f47af46609a9a07b461
PromiseKit: 879fa89b55fcb8f11ade9aad0c9721850bb71b9f
RxCocoa: 94f817b71c07517321eb4f9ad299112ca8af743b
RxRelay: 1de1523e604c72b6c68feadedd1af3b1b4d0ecbd
RxSwift: 5710a9e6b17f3c3d6e40d6e559b9fa1e813b2ef8
Starscream: 4bb2f9942274833f7b4d296a55504dcfc7edb7b0
SwiftyJSON: 2f33a42c6fbc52764d96f13368585094bfd8aa5e
WebViewJavascriptBridge: 7f5bc4d3581e672e8f32bd0f812d54bc69bb8e29
Yams: b5c3e188ceeb8321a9830b1d0e791ccea9af3201
PODFILE CHECKSUM: f4571fd419858d0946fa886653353d5b9e10a822
PODFILE CHECKSUM: 57cda85d5fd198c1d1f83f6a71b69a86b1884bb5
COCOAPODS: 1.11.3

View File

@ -9,9 +9,9 @@
<key>CFBundleName</key>
<string>com.metacubex.ClashX.ProxyConfigHelper</string>
<key>CFBundleShortVersionString</key>
<string>1.3</string>
<string>1.4</string>
<key>CFBundleVersion</key>
<string>4</string>
<string>5</string>
<key>SMAuthorizedClients</key>
<array>
<string>anchor apple generic and identifier &quot;com.metacubex.ClashX.ProxyConfigHelper&quot; and (certificate leaf[field.1.2.840.113635.100.6.1.9] /* exists */ or certificate 1[field.1.2.840.113635.100.6.2.6] /* exists */ and certificate leaf[field.1.2.840.113635.100.6.1.13] /* exists */ and certificate leaf[subject.OU] = MEWHFZ92DY)</string>

View File

@ -8,7 +8,7 @@ import Cocoa
class MetaTask: NSObject {
struct MetaServer: Encodable {
let externalController: String
var externalController: String
let secret: String
var log: String = ""
@ -29,7 +29,6 @@ class MetaTask: NSObject {
}
let proc = Process()
var uiPath: String?
let procQueue = DispatchQueue(label: Bundle.main.bundleIdentifier! + ".MetaProcess")
var timer: DispatchSourceTimer?
@ -39,10 +38,6 @@ class MetaTask: NSObject {
proc.executableURL = .init(fileURLWithPath: path)
}
@objc func setUIPath(_ path: String) {
uiPath = path
}
@objc func start(_ confPath: String,
confFilePath: String,
result: @escaping stringReplyBlock) {
@ -71,13 +66,6 @@ class MetaTask: NSObject {
])
}
if let uiPath = uiPath {
args.append(contentsOf: [
"-ext-ui",
uiPath
])
}
killOldProc()
procQueue.async {
@ -94,6 +82,17 @@ class MetaTask: NSObject {
return
}
let port = serverResult.externalController.components(separatedBy: ":").last ?? "9090"
if let p = Int(port) {
let newPort = self.updateExternalControllerPort(p)
let ec = "127.0.0.1:\(newPort)"
args.append(contentsOf: [
"-ext-ctl",
ec
])
serverResult.externalController = ec
}
self.proc.arguments = args
let pipe = Pipe()
var logs = [String]()
@ -276,7 +275,7 @@ class MetaTask: NSObject {
return (Int32(pid) ?? 0, addr)
}
func findExternalControllerPort(_ port: Int) -> Int {
func updateExternalControllerPort(_ port: Int) -> Int {
let proc = Process()
let pipe = Pipe()
proc.standardOutput = pipe

View File

@ -79,6 +79,7 @@ ProxyConfigRemoteProcessProtocol
[weakSelf.connections removeObject:weakConnection];
if (weakSelf.connections.count == 0) {
weakSelf.shouldQuit = YES;
[weakSelf.metaTask stop];
}
};
[self.connections addObject:newConnection];
@ -140,10 +141,6 @@ ProxyConfigRemoteProcessProtocol
}
- (void)metaSetUIPath:(NSString *)path {
[self.metaTask setUIPath:path];
}
- (void)startMetaWithConfPath:(NSString *)confPath ConfFilePath:(NSString *)confFilePath result:(stringReplyBlock)reply {
[self.metaTask start:confPath confFilePath:confFilePath result:reply];
}

View File

@ -17,8 +17,6 @@ typedef void(^dictReplyBlock)(NSDictionary *);
- (void)initMetaCoreWithPath:(NSString *)path;
- (void)metaSetUIPath:(NSString *)path;
- (void)startMetaWithConfPath:(NSString *)confPath
ConfFilePath:(NSString *)confFilePath
result:(stringReplyBlock)reply;