Files
ucvl-zonghengjia-open-source/ios/PacketTunnel/XrayBridge.swift
T

47 lines
1.9 KiB
Swift
Raw Permalink Normal View History

import Darwin
import Foundation
import LibXray
enum XrayBridge {
static func start(configJSON: String) throws {
_ = try invoke(method: "runXrayFromJson", payload: ["configJSON": configJSON])
}
static func stop() {
_ = try? invoke(method: "stopXray", payload: nil)
}
static func isRunning() -> Bool {
guard let data = try? invoke(method: "getXrayState", payload: nil) else { return false }
return data["running"] as? Bool ?? false
}
@discardableResult
private static func invoke(method: String, payload: [String: Any]?) throws -> [String: Any] {
var request: [String: Any] = ["apiVersion": 1, "method": method]
if let payload { request["payload"] = payload }
let requestData = try JSONSerialization.data(withJSONObject: request, options: [])
let requestText = String(decoding: requestData, as: UTF8.self)
guard let requestPointer = requestText.withCString({ strdup($0) }) else {
throw UCVLError.invalidConfiguration("无法调用 Xray 核心。")
}
defer { free(requestPointer) }
guard let responsePointer = CGoInvoke(requestPointer) else {
throw UCVLError.invalidConfiguration("Xray 核心没有返回结果。")
}
defer { CGoFree(responsePointer) }
let responseText = String(cString: responsePointer)
guard let responseData = responseText.data(using: .utf8),
let response = try JSONSerialization.jsonObject(with: responseData) as? [String: Any]
else {
throw UCVLError.invalidConfiguration("Xray 核心返回格式错误。")
}
guard response["success"] as? Bool == true else {
let error = response["error"] as? String ?? "Xray 核心启动失败。"
throw UCVLError.invalidConfiguration(error)
}
return response["data"] as? [String: Any] ?? [:]
}
}