Add CI/CD configuration and API documentation
This commit is contained in:
@@ -0,0 +1,39 @@
|
||||
import Foundation
|
||||
import GRDB
|
||||
|
||||
enum Database {
|
||||
static let sharedWriter = makeShared()
|
||||
|
||||
private static func makeShared() -> any DatabaseWriter {
|
||||
do {
|
||||
try FileManager.default.createDirectory(at: FilePath.sharedDirectory, withIntermediateDirectories: true)
|
||||
let database = try DatabasePool(path: FilePath.sharedDirectory.appendingPathComponent("settings.db").relativePath)
|
||||
var migrator = DatabaseMigrator().disablingDeferredForeignKeyChecks()
|
||||
migrator.registerMigration("initialize") { db in
|
||||
try db.create(table: "profiles") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
t.column("order", .integer).notNull()
|
||||
t.column("type", .integer).notNull().defaults(to: ProfileType.local.rawValue)
|
||||
t.column("path", .text).notNull()
|
||||
t.column("remoteURL", .text)
|
||||
t.column("autoUpdate", .boolean).notNull().defaults(to: false)
|
||||
t.column("lastUpdated", .datetime)
|
||||
}
|
||||
try db.create(table: "preferences") { t in
|
||||
t.primaryKey("name", .text, onConflict: .replace).notNull()
|
||||
t.column("data", .blob)
|
||||
}
|
||||
}
|
||||
migrator.registerMigration("add_auto_update_interval") { db in
|
||||
try db.alter(table: "profiles") { t in
|
||||
t.add(column: "autoUpdateInterval", .integer).notNull().defaults(to: 0)
|
||||
}
|
||||
}
|
||||
try migrator.migrate(database)
|
||||
return database
|
||||
} catch {
|
||||
fatalError(error.localizedDescription)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import Foundation
|
||||
|
||||
public extension Profile {
|
||||
var lastUpdatedString: String {
|
||||
let dateFormatter = DateFormatter()
|
||||
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
|
||||
return dateFormatter.string(from: lastUpdated!)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import Foundation
|
||||
|
||||
extension Profile: Hashable {
|
||||
public static func == (lhs: Profile, rhs: Profile) -> Bool {
|
||||
lhs.id == rhs.id
|
||||
}
|
||||
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(id)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import Foundation
|
||||
|
||||
public extension Profile {
|
||||
func read() throws -> String {
|
||||
switch type {
|
||||
case .local, .remote:
|
||||
return try String(contentsOfFile: path)
|
||||
case .icloud:
|
||||
let saveURL = FilePath.iCloudDirectory.appendingPathComponent(path)
|
||||
_ = saveURL.startAccessingSecurityScopedResource()
|
||||
defer {
|
||||
saveURL.stopAccessingSecurityScopedResource()
|
||||
}
|
||||
return try String(contentsOf: saveURL)
|
||||
}
|
||||
}
|
||||
|
||||
func write(_ content: String) throws {
|
||||
switch type {
|
||||
case .local, .remote:
|
||||
try content.write(toFile: path, atomically: true, encoding: .utf8)
|
||||
case .icloud:
|
||||
let saveURL = FilePath.iCloudDirectory.appendingPathComponent(path)
|
||||
_ = saveURL.startAccessingSecurityScopedResource()
|
||||
defer {
|
||||
saveURL.stopAccessingSecurityScopedResource()
|
||||
}
|
||||
try content.write(to: saveURL, atomically: true, encoding: .utf8)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import Foundation
|
||||
import Libbox
|
||||
|
||||
public extension Profile {
|
||||
var shareLink: URL {
|
||||
URL(string: LibboxGenerateRemoteProfileImportLink(name, remoteURL!))!
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import Foundation
|
||||
import Libbox
|
||||
import SwiftUI
|
||||
import UniformTypeIdentifiers
|
||||
|
||||
public extension Profile {
|
||||
func toContent() throws -> LibboxProfileContent {
|
||||
let content = LibboxProfileContent()
|
||||
content.name = name
|
||||
content.type = Int32(type.rawValue)
|
||||
content.config = try read()
|
||||
if type != .local {
|
||||
content.remotePath = remoteURL!
|
||||
}
|
||||
if type == .remote {
|
||||
content.autoUpdate = autoUpdate
|
||||
content.autoUpdateInterval = autoUpdateInterval
|
||||
if let lastUpdated {
|
||||
content.lastUpdated = Int64(lastUpdated.timeIntervalSince1970)
|
||||
}
|
||||
}
|
||||
return content
|
||||
}
|
||||
}
|
||||
|
||||
@available(iOS 16.0, macOS 13.0, *)
|
||||
extension Profile: Transferable {
|
||||
public static var transferRepresentation: some TransferRepresentation {
|
||||
ProxyRepresentation { profile in
|
||||
try TypedProfile(profile.toContent())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public extension LibboxProfileContent {
|
||||
static func from(_ data: Data) throws -> LibboxProfileContent {
|
||||
var error: NSError?
|
||||
let content = LibboxDecodeProfileContent(data, &error)
|
||||
if let error {
|
||||
throw error
|
||||
}
|
||||
return content!
|
||||
}
|
||||
|
||||
func importProfile() async throws {
|
||||
let nextProfileID = try await ProfileManager.nextID()
|
||||
let profileConfigDirectory = FilePath.sharedDirectory.appendingPathComponent("configs", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: profileConfigDirectory, withIntermediateDirectories: true)
|
||||
let profileConfig = profileConfigDirectory.appendingPathComponent("config_\(nextProfileID).json")
|
||||
try config.write(to: profileConfig, atomically: true, encoding: .utf8)
|
||||
var lastUpdatedAt: Date?
|
||||
if lastUpdated > 0 {
|
||||
lastUpdatedAt = Date(timeIntervalSince1970: Double(lastUpdated))
|
||||
}
|
||||
try await ProfileManager.create(Profile(name: name, type: ProfileType(rawValue: Int(type))!, path: profileConfig.relativePath, remoteURL: remotePath, autoUpdate: autoUpdate, autoUpdateInterval: autoUpdateInterval, lastUpdated: lastUpdatedAt))
|
||||
}
|
||||
|
||||
func generateShareFile() throws -> URL {
|
||||
let shareDirectory = FilePath.cacheDirectory.appendingPathComponent("share", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: shareDirectory, withIntermediateDirectories: true)
|
||||
let shareFile = shareDirectory.appendingPathComponent("\(name).bpf")
|
||||
try encode()!.write(to: shareFile)
|
||||
return shareFile
|
||||
}
|
||||
}
|
||||
|
||||
public extension String {
|
||||
func generateShareFile(name: String) throws -> URL {
|
||||
let shareDirectory = FilePath.cacheDirectory.appendingPathComponent("share", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: shareDirectory, withIntermediateDirectories: true)
|
||||
let shareFile = shareDirectory.appendingPathComponent(name)
|
||||
try write(to: shareFile, atomically: true, encoding: .utf8)
|
||||
return shareFile
|
||||
}
|
||||
}
|
||||
|
||||
@available(iOS 16.0, macOS 13.0, *)
|
||||
public struct TypedProfile: Transferable, Codable {
|
||||
public let content: LibboxProfileContent
|
||||
public init(_ content: LibboxProfileContent) {
|
||||
self.content = content
|
||||
}
|
||||
|
||||
public init(from decoder: Decoder) throws {
|
||||
let container = try decoder.singleValueContainer()
|
||||
let data = try container.decode(Data.self)
|
||||
try self.init(.from(data))
|
||||
}
|
||||
|
||||
public static var transferRepresentation: some TransferRepresentation {
|
||||
FileRepresentation(contentType: .profile) { typed in
|
||||
try SentTransferredFile(typed.content.generateShareFile(), allowAccessingOriginalFile: true)
|
||||
} importing: { received in
|
||||
try TypedProfile(.from(Data(contentsOf: received.file)))
|
||||
}
|
||||
}
|
||||
|
||||
public func encode(to encoder: Encoder) throws {
|
||||
var container = encoder.singleValueContainer()
|
||||
try container.encode(content.encode()!)
|
||||
}
|
||||
}
|
||||
|
||||
public extension UTType {
|
||||
static var profile: UTType { .init(exportedAs: "com.uuvpn.appleaman.profile") }
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import Foundation
|
||||
import GRDB
|
||||
import Libbox
|
||||
|
||||
public extension Profile {
|
||||
nonisolated func updateRemoteProfile() async throws {
|
||||
if type != .remote {
|
||||
return
|
||||
}
|
||||
let remoteContent = try HTTPClient().getString(remoteURL)
|
||||
var error: NSError?
|
||||
LibboxCheckConfig(remoteContent, &error)
|
||||
if let error {
|
||||
throw error
|
||||
}
|
||||
try write(remoteContent)
|
||||
lastUpdated = Date()
|
||||
try await ProfileManager.update(self)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import Foundation
|
||||
import GRDB
|
||||
import Network
|
||||
|
||||
public class Profile: Record, Identifiable, ObservableObject {
|
||||
public var id: Int64?
|
||||
public var mustID: Int64 {
|
||||
id!
|
||||
}
|
||||
|
||||
@Published public var name: String
|
||||
public var order: UInt32
|
||||
public var type: ProfileType
|
||||
public var path: String
|
||||
@Published public var remoteURL: String?
|
||||
@Published public var autoUpdate: Bool
|
||||
@Published public var autoUpdateInterval: Int32
|
||||
public var lastUpdated: Date?
|
||||
|
||||
public init(id: Int64? = nil, name: String, order: UInt32 = 0, type: ProfileType, path: String, remoteURL: String? = nil, autoUpdate: Bool = false, autoUpdateInterval: Int32 = 0, lastUpdated: Date? = nil) {
|
||||
self.id = id
|
||||
self.name = name
|
||||
self.order = order
|
||||
self.type = type
|
||||
self.path = path
|
||||
self.remoteURL = remoteURL
|
||||
self.autoUpdate = autoUpdate
|
||||
self.autoUpdateInterval = autoUpdateInterval
|
||||
self.lastUpdated = lastUpdated
|
||||
super.init()
|
||||
}
|
||||
|
||||
override public class var databaseTableName: String {
|
||||
"profiles"
|
||||
}
|
||||
|
||||
enum Columns: String, ColumnExpression {
|
||||
case id, name, order, type, path, remoteURL, autoUpdate, autoUpdateInterval, lastUpdated, userAgent
|
||||
}
|
||||
|
||||
required init(row: Row) throws {
|
||||
id = row[Columns.id]
|
||||
name = row[Columns.name] ?? ""
|
||||
order = row[Columns.order] ?? 0
|
||||
type = ProfileType(rawValue: row[Columns.type] ?? ProfileType.local.rawValue)!
|
||||
path = row[Columns.path] ?? ""
|
||||
remoteURL = row[Columns.remoteURL] ?? ""
|
||||
autoUpdate = row[Columns.autoUpdate] ?? false
|
||||
autoUpdateInterval = row[Columns.autoUpdateInterval] ?? 0
|
||||
lastUpdated = row[Columns.lastUpdated] ?? Date()
|
||||
try super.init(row: row)
|
||||
}
|
||||
|
||||
override public func encode(to container: inout PersistenceContainer) throws {
|
||||
container[Columns.id] = id
|
||||
container[Columns.name] = name
|
||||
container[Columns.order] = order
|
||||
container[Columns.type] = type.rawValue
|
||||
container[Columns.path] = path
|
||||
container[Columns.remoteURL] = remoteURL
|
||||
container[Columns.autoUpdate] = autoUpdate
|
||||
container[Columns.autoUpdateInterval] = autoUpdateInterval
|
||||
container[Columns.lastUpdated] = lastUpdated
|
||||
}
|
||||
|
||||
override public func didInsert(_ inserted: InsertionSuccess) {
|
||||
super.didInsert(inserted)
|
||||
id = inserted.rowID
|
||||
}
|
||||
}
|
||||
|
||||
public struct ProfilePreview: Identifiable, Hashable {
|
||||
public let id: Int64
|
||||
public let name: String
|
||||
public var order: UInt32
|
||||
public let type: ProfileType
|
||||
public let path: String
|
||||
public let remoteURL: String?
|
||||
public let autoUpdate: Bool
|
||||
public let autoUpdateInterval: Int32
|
||||
public let lastUpdated: Date?
|
||||
public let origin: Profile
|
||||
|
||||
public init(_ profile: Profile) {
|
||||
id = profile.mustID
|
||||
name = profile.name
|
||||
order = profile.order
|
||||
type = profile.type
|
||||
path = profile.path
|
||||
remoteURL = profile.remoteURL
|
||||
autoUpdate = profile.autoUpdate
|
||||
autoUpdateInterval = profile.autoUpdateInterval
|
||||
lastUpdated = profile.lastUpdated
|
||||
origin = profile
|
||||
}
|
||||
}
|
||||
|
||||
public enum ProfileType: Int {
|
||||
case local = 0, icloud, remote
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import Foundation
|
||||
import GRDB
|
||||
|
||||
public enum ProfileManager {
|
||||
public nonisolated static func create(_ profile: Profile) async throws {
|
||||
profile.order = try await nextOrder()
|
||||
try await Database.sharedWriter.write { db in
|
||||
try profile.insert(db, onConflict: .fail)
|
||||
}
|
||||
}
|
||||
|
||||
public nonisolated static func get(_ profileID: Int64) async throws -> Profile? {
|
||||
try await Database.sharedWriter.read { db in
|
||||
try Profile.fetchOne(db, id: profileID)
|
||||
}
|
||||
}
|
||||
|
||||
public nonisolated static func get(by profileName: String) async throws -> Profile? {
|
||||
try await Database.sharedWriter.read { db in
|
||||
try Profile.filter(Column("name") == profileName).fetchOne(db)
|
||||
}
|
||||
}
|
||||
|
||||
public nonisolated static func delete(_ profile: Profile) async throws {
|
||||
_ = try await Database.sharedWriter.write { db in
|
||||
try profile.delete(db)
|
||||
}
|
||||
}
|
||||
|
||||
public nonisolated static func delete(by id: Int64) async throws {
|
||||
_ = try await Database.sharedWriter.write { db in
|
||||
try Profile.deleteOne(db, id: id)
|
||||
}
|
||||
}
|
||||
|
||||
public nonisolated static func delete(_ profileList: [Profile]) async throws -> Int {
|
||||
try await Database.sharedWriter.write { db in
|
||||
try Profile.deleteAll(db, keys: profileList.map {
|
||||
["id": $0.id!]
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
public nonisolated static func delete(by id: [Int64]) async throws -> Int {
|
||||
try await Database.sharedWriter.write { db in
|
||||
try Profile.deleteAll(db, ids: id)
|
||||
}
|
||||
}
|
||||
|
||||
public nonisolated static func update(_ profile: Profile) async throws {
|
||||
_ = try await Database.sharedWriter.write { db in
|
||||
try profile.updateChanges(db)
|
||||
}
|
||||
}
|
||||
|
||||
public nonisolated static func update(_ profileList: [Profile]) async throws {
|
||||
// TODO: batch update
|
||||
try await Database.sharedWriter.write { db in
|
||||
for profile in profileList {
|
||||
try profile.updateChanges(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public nonisolated static func list() async throws -> [Profile] {
|
||||
try await Database.sharedWriter.read { db in
|
||||
try Profile.all().order(Column("order").asc).fetchAll(db)
|
||||
}
|
||||
}
|
||||
|
||||
public nonisolated static func listRemote() async throws -> [Profile] {
|
||||
try await Database.sharedWriter.read { db in
|
||||
try Profile.filter(Column("type") == ProfileType.remote.rawValue).order(Column("order").asc).fetchAll(db)
|
||||
}
|
||||
}
|
||||
|
||||
public nonisolated static func listAutoUpdateEnabled() async throws -> [Profile] {
|
||||
try await Database.sharedWriter.read { db in
|
||||
try Profile.filter(Column("autoUpdate") == true).order(Column("order").asc).fetchAll(db)
|
||||
}
|
||||
}
|
||||
|
||||
public nonisolated static func nextID() async throws -> Int64 {
|
||||
try await Database.sharedWriter.read { db in
|
||||
if let lastProfile = try Profile.select(Column("id")).order(Column("id").desc).fetchOne(db) {
|
||||
return lastProfile.id! + 1
|
||||
} else {
|
||||
return 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private nonisolated static func nextOrder() async throws -> UInt32 {
|
||||
try await Database.sharedWriter.read { db in
|
||||
try UInt32(Profile.fetchCount(db))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import BinaryCodable
|
||||
import Foundation
|
||||
import GRDB
|
||||
|
||||
extension SharedPreferences {
|
||||
public class Preference<T: Codable> {
|
||||
private let name: String
|
||||
private let defaultValue: T
|
||||
|
||||
init(_ name: String, defaultValue: T) {
|
||||
self.name = name
|
||||
self.defaultValue = defaultValue
|
||||
}
|
||||
|
||||
public nonisolated func get() async -> T {
|
||||
do {
|
||||
return try await SharedPreferences.read(name) ?? defaultValue
|
||||
} catch {
|
||||
NSLog("read preferences error: \(error)")
|
||||
return defaultValue
|
||||
}
|
||||
}
|
||||
|
||||
public func getBlocking() -> T {
|
||||
runBlocking { [self] in
|
||||
await get()
|
||||
}
|
||||
}
|
||||
|
||||
public nonisolated func set(_ newValue: T?) async {
|
||||
do {
|
||||
try await SharedPreferences.write(name, newValue)
|
||||
} catch {
|
||||
NSLog("write preferences error: \(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private nonisolated static func read<T: Codable>(_ name: String) async throws -> T? {
|
||||
guard let item = try await (Database.sharedWriter.read { db in
|
||||
try Item.fetchOne(db, id: name)
|
||||
})
|
||||
else {
|
||||
return nil
|
||||
}
|
||||
return try BinaryDecoder().decode(from: item.data)
|
||||
}
|
||||
|
||||
private nonisolated static func write(_ name: String, _ value: (some Codable)?) async throws {
|
||||
if value == nil {
|
||||
_ = try await Database.sharedWriter.write { db in
|
||||
try Item.deleteOne(db, id: name)
|
||||
}
|
||||
} else {
|
||||
let data = try BinaryEncoder().encode(value)
|
||||
try await Database.sharedWriter.write { db in
|
||||
try Item(name: name, data: data).insert(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class Item: Record, Identifiable {
|
||||
public var id: String {
|
||||
name
|
||||
}
|
||||
|
||||
public var name: String
|
||||
public var data: Data
|
||||
|
||||
init(name: String, data: Data) {
|
||||
self.name = name
|
||||
self.data = data
|
||||
super.init()
|
||||
}
|
||||
|
||||
override public class var databaseTableName: String {
|
||||
"preferences"
|
||||
}
|
||||
|
||||
enum Columns: String, ColumnExpression {
|
||||
case name, data
|
||||
}
|
||||
|
||||
required init(row: Row) throws {
|
||||
name = row[Columns.name]
|
||||
data = row[Columns.data]
|
||||
try super.init(row: row)
|
||||
}
|
||||
|
||||
override public func encode(to container: inout PersistenceContainer) throws {
|
||||
container[Columns.name] = name
|
||||
container[Columns.data] = data
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import Foundation
|
||||
|
||||
public enum SharedPreferences {
|
||||
public static let selectedProfileID = Preference<Int64>("selected_profile_id", defaultValue: -1)
|
||||
|
||||
#if os(macOS)
|
||||
private static let ignoreMemoryLimitByDefault = true
|
||||
#else
|
||||
private static let ignoreMemoryLimitByDefault = false
|
||||
#endif
|
||||
|
||||
public static let ignoreMemoryLimit = Preference<Bool>("ignore_memory_limit", defaultValue: ignoreMemoryLimitByDefault)
|
||||
|
||||
#if os(iOS)
|
||||
public static let excludeLocalNetworksByDefault = true
|
||||
#elseif os(macOS)
|
||||
public static let excludeLocalNetworksByDefault = false
|
||||
#endif
|
||||
|
||||
#if !os(tvOS)
|
||||
public static let includeAllNetworks = Preference<Bool>("include_all_networks", defaultValue: false)
|
||||
public static let excludeAPNs = Preference<Bool>("exclude_apns", defaultValue: true)
|
||||
public static let excludeLocalNetworks = Preference<Bool>("exclude_local_networks", defaultValue: excludeLocalNetworksByDefault)
|
||||
public static let excludeCellularServices = Preference<Bool>("exclude_celluar_services", defaultValue: true)
|
||||
public static let enforceRoutes = Preference<Bool>("enforce_routes", defaultValue: false)
|
||||
|
||||
#endif
|
||||
|
||||
public static func resetPacketTunnel() async {
|
||||
await ignoreMemoryLimit.set(nil)
|
||||
#if !os(tvOS)
|
||||
await includeAllNetworks.set(nil)
|
||||
await excludeAPNs.set(nil)
|
||||
await excludeLocalNetworks.set(nil)
|
||||
await excludeCellularServices.set(nil)
|
||||
await enforceRoutes.set(nil)
|
||||
#endif
|
||||
}
|
||||
|
||||
public static let maxLogLines = Preference<Int>("max_log_lines", defaultValue: 300)
|
||||
|
||||
#if os(macOS)
|
||||
public static let showMenuBarExtra = Preference<Bool>("show_menu_bar_extra", defaultValue: true)
|
||||
public static let menuBarExtraInBackground = Preference<Bool>("menu_bar_extra_in_background", defaultValue: false)
|
||||
public static let startedByUser = Preference<Bool>("started_by_user", defaultValue: false)
|
||||
|
||||
public static func resetMacOS() async {
|
||||
await showMenuBarExtra.set(nil)
|
||||
await menuBarExtraInBackground.set(nil)
|
||||
}
|
||||
#endif
|
||||
|
||||
#if os(iOS)
|
||||
public static let networkPermissionRequested = Preference<Bool>("network_permission_requested", defaultValue: false)
|
||||
#endif
|
||||
|
||||
public static let systemProxyEnabled = Preference<Bool>("system_proxy_enabled", defaultValue: true)
|
||||
|
||||
// Profile Override
|
||||
|
||||
public static let excludeDefaultRoute = Preference<Bool>("exclude_default_route", defaultValue: false)
|
||||
public static let autoRouteUseSubRangesByDefault = Preference<Bool>("auto_route_use_sub_ranges_by_default", defaultValue: false)
|
||||
public static let excludeAPNsRoute = Preference<Bool>("exclude_apple_push_notification_services", defaultValue: false)
|
||||
|
||||
public static func resetProfileOverride() async {
|
||||
await excludeDefaultRoute.set(nil)
|
||||
await autoRouteUseSubRangesByDefault.set(nil)
|
||||
await excludeAPNsRoute.set(nil)
|
||||
}
|
||||
|
||||
// On Demand Rules
|
||||
|
||||
public static let alwaysOn = Preference<Bool>("always_on", defaultValue: false)
|
||||
|
||||
public static func resetOnDemandRules() async {
|
||||
await alwaysOn.set(nil)
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
public static let inDebug = true
|
||||
#else
|
||||
public static let inDebug = false
|
||||
#endif
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import Foundation
|
||||
import Libbox
|
||||
import Network
|
||||
|
||||
public class NWSocket {
|
||||
private let connection: NWConnection
|
||||
|
||||
public init(_ connection: NWConnection) {
|
||||
self.connection = connection
|
||||
}
|
||||
|
||||
public func read() throws -> Data {
|
||||
let semaphore = DispatchSemaphore(value: 0)
|
||||
var result: Result<Data, Error>!
|
||||
connection.receive(minimumIncompleteLength: 2, maximumLength: 2) { content, _, _, error in
|
||||
if let error {
|
||||
result = .failure(error)
|
||||
} else {
|
||||
result = .success(content!)
|
||||
}
|
||||
semaphore.signal()
|
||||
}
|
||||
semaphore.wait()
|
||||
let lengthChunk = try result.get()
|
||||
let length = Int(LibboxDecodeLengthChunk(lengthChunk))
|
||||
connection.receive(minimumIncompleteLength: length, maximumLength: length) { content, _, _, error in
|
||||
if let error {
|
||||
result = .failure(error)
|
||||
} else {
|
||||
result = .success(content!)
|
||||
}
|
||||
semaphore.signal()
|
||||
}
|
||||
semaphore.wait()
|
||||
return try result.get()
|
||||
}
|
||||
|
||||
public func write(_ data: Data?) throws {
|
||||
guard let data else {
|
||||
return
|
||||
}
|
||||
let semaphore = DispatchSemaphore(value: 0)
|
||||
var result: Error?
|
||||
connection.send(content: LibboxEncodeChunkedMessage(data), isComplete: false, completion: .contentProcessed { error in
|
||||
result = error
|
||||
semaphore.wait()
|
||||
})
|
||||
if let result {
|
||||
throw result
|
||||
}
|
||||
}
|
||||
|
||||
public func send(_ data: Data?) {
|
||||
guard let data else {
|
||||
return
|
||||
}
|
||||
connection.send(content: LibboxEncodeChunkedMessage(data), completion: .idempotent)
|
||||
}
|
||||
|
||||
public func cancel() {
|
||||
connection.cancel()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
import Foundation
|
||||
import Libbox
|
||||
import Network
|
||||
|
||||
public class ProfileServer {
|
||||
private var listener: NWListener
|
||||
|
||||
@available(iOS 16.0, macOS 13.0, *)
|
||||
public init() throws {
|
||||
listener = try NWListener(using: .applicationService)
|
||||
listener.service = NWListener.Service(applicationService: "sing-box:profile")
|
||||
listener.newConnectionHandler = { connection in
|
||||
connection.stateUpdateHandler = { state in
|
||||
if state == .ready {
|
||||
Task.detached {
|
||||
try await Task.sleep(nanoseconds: NSEC_PER_MSEC * 100)
|
||||
await ProfileConnection(connection).process()
|
||||
}
|
||||
}
|
||||
}
|
||||
connection.start(queue: .global())
|
||||
}
|
||||
}
|
||||
|
||||
public func start() {
|
||||
listener.start(queue: .global())
|
||||
}
|
||||
|
||||
public func cancel() {
|
||||
listener.cancel()
|
||||
}
|
||||
|
||||
class ProfileConnection {
|
||||
private let connection: NWSocket
|
||||
|
||||
init(_ connection: NWConnection) {
|
||||
self.connection = NWSocket(connection)
|
||||
}
|
||||
|
||||
func process() async {
|
||||
do {
|
||||
try await writeProfilePreviewList()
|
||||
} catch {
|
||||
NSLog("profile server: write profile list: \(error.localizedDescription)")
|
||||
writeError(error.localizedDescription)
|
||||
return
|
||||
}
|
||||
do {
|
||||
while true {
|
||||
let message = try connection.read()
|
||||
try processMessage(message)
|
||||
}
|
||||
} catch {
|
||||
NSLog("profile server: process connection: \(error.localizedDescription)")
|
||||
writeError(error.localizedDescription)
|
||||
}
|
||||
}
|
||||
|
||||
private func processMessage(_ data: Data) throws {
|
||||
if data.count == 0 {
|
||||
return
|
||||
}
|
||||
let messageType = Int64(data[0])
|
||||
switch messageType {
|
||||
case LibboxMessageTypeProfileContentRequest:
|
||||
Task {
|
||||
try await processProfileContentRequest(data)
|
||||
}
|
||||
default:
|
||||
throw NSError(domain: "unexpected message type \(messageType)", code: 0)
|
||||
}
|
||||
}
|
||||
|
||||
private func processProfileContentRequest(_ data: Data) async throws {
|
||||
var error: NSError?
|
||||
let request = LibboxDecodeProfileContentRequest(data, &error)
|
||||
if let error {
|
||||
throw error
|
||||
}
|
||||
|
||||
let profile = try await ProfileManager.get(request!.profileID)
|
||||
guard let profile else {
|
||||
throw NSError(domain: "profile not found", code: 0)
|
||||
}
|
||||
let content = LibboxProfileContent()
|
||||
content.name = profile.name
|
||||
switch profile.type {
|
||||
case .local:
|
||||
content.type = LibboxProfileTypeLocal
|
||||
case .icloud:
|
||||
content.type = LibboxProfileTypeiCloud
|
||||
case .remote:
|
||||
content.type = LibboxProfileTypeRemote
|
||||
}
|
||||
content.config = try profile.read()
|
||||
if profile.type != .local {
|
||||
content.remotePath = profile.remoteURL!
|
||||
}
|
||||
if profile.type == .remote {
|
||||
content.autoUpdate = profile.autoUpdate
|
||||
content.autoUpdateInterval = profile.autoUpdateInterval
|
||||
if let lastUpdated = profile.lastUpdated {
|
||||
content.lastUpdated = Int64(lastUpdated.timeIntervalSince1970)
|
||||
}
|
||||
}
|
||||
try connection.write(content.encode())
|
||||
}
|
||||
|
||||
private func writeProfilePreviewList() async throws {
|
||||
let profiles = try await ProfileManager.list()
|
||||
let encoder = LibboxProfileEncoder()
|
||||
for profile in profiles {
|
||||
let preview = LibboxProfilePreview()
|
||||
preview.profileID = profile.mustID
|
||||
preview.name = profile.name
|
||||
switch profile.type {
|
||||
case .local:
|
||||
preview.type = LibboxProfileTypeLocal
|
||||
case .icloud:
|
||||
preview.type = LibboxProfileTypeiCloud
|
||||
case .remote:
|
||||
preview.type = LibboxProfileTypeRemote
|
||||
}
|
||||
encoder.append(preview)
|
||||
}
|
||||
try connection.write(encoder.encode())
|
||||
}
|
||||
|
||||
private func writeError(_ message: String) {
|
||||
let errorMessage = LibboxErrorMessage()
|
||||
errorMessage.message = message
|
||||
try? connection.write(errorMessage.encode())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
import Foundation
|
||||
|
||||
public class Library {}
|
||||
@@ -0,0 +1,188 @@
|
||||
import Foundation
|
||||
import Libbox
|
||||
|
||||
public class CommandClient: ObservableObject {
|
||||
public enum ConnectionType {
|
||||
case status
|
||||
case groups
|
||||
case log
|
||||
case clashMode
|
||||
}
|
||||
|
||||
private let connectionType: ConnectionType
|
||||
private let logMaxLines: Int
|
||||
private var commandClient: LibboxCommandClient?
|
||||
private var connectTask: Task<Void, Error>?
|
||||
|
||||
@Published public var isConnected: Bool
|
||||
@Published public var status: LibboxStatusMessage?
|
||||
@Published public var groups: [LibboxOutboundGroup]?
|
||||
@Published public var logList: [String]
|
||||
@Published public var clashModeList: [String]
|
||||
@Published public var clashMode: String
|
||||
|
||||
public init(_ connectionType: ConnectionType, logMaxLines: Int = 300) {
|
||||
self.connectionType = connectionType
|
||||
self.logMaxLines = logMaxLines
|
||||
logList = []
|
||||
clashModeList = []
|
||||
clashMode = ""
|
||||
isConnected = false
|
||||
}
|
||||
|
||||
public func connect() {
|
||||
if isConnected {
|
||||
return
|
||||
}
|
||||
if let connectTask {
|
||||
connectTask.cancel()
|
||||
}
|
||||
connectTask = Task {
|
||||
await connect0()
|
||||
}
|
||||
}
|
||||
|
||||
public func disconnect() {
|
||||
if let connectTask {
|
||||
connectTask.cancel()
|
||||
self.connectTask = nil
|
||||
}
|
||||
if let commandClient {
|
||||
try? commandClient.disconnect()
|
||||
self.commandClient = nil
|
||||
}
|
||||
}
|
||||
|
||||
private nonisolated func connect0() async {
|
||||
print("connect0...")
|
||||
let clientOptions = LibboxCommandClientOptions()
|
||||
switch connectionType {
|
||||
case .status:
|
||||
print("connectionType = .status")
|
||||
clientOptions.command = LibboxCommandStatus
|
||||
case .groups:
|
||||
print("connectionType = .groups")
|
||||
clientOptions.command = LibboxCommandGroup
|
||||
case .log:
|
||||
print("connectionType = .log")
|
||||
clientOptions.command = LibboxCommandLog
|
||||
case .clashMode:
|
||||
print("connectionType = .clashMode")
|
||||
clientOptions.command = LibboxCommandClashMode
|
||||
}
|
||||
clientOptions.statusInterval = Int64(2 * NSEC_PER_SEC)
|
||||
let client = LibboxNewCommandClient(clientHandler(self), clientOptions)!
|
||||
do {
|
||||
//连接失败时的行为
|
||||
// 第一个版本:如果连接失败,它将不会重试;它将在捕获错误后尝试断开连接。
|
||||
// 第二个版本:如果在循环的任何迭代中连接失败,它将进行下一次迭代,在重试连接之前再次休眠。这允许多次尝试连接,每次尝试之间的等待时间逐渐变长
|
||||
for i in 0 ..< 2 {
|
||||
try await Task.sleep(nanoseconds: UInt64(Double(100 + (i * 50)) * Double(NSEC_PER_MSEC)))
|
||||
try Task.checkCancellation()
|
||||
do {
|
||||
try client.connect()
|
||||
await MainActor.run {
|
||||
commandClient = client
|
||||
}
|
||||
return
|
||||
} catch {}
|
||||
try Task.checkCancellation()
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
} catch {
|
||||
try? client.disconnect()
|
||||
}
|
||||
|
||||
/*
|
||||
do {
|
||||
try client.connect()
|
||||
await MainActor.run {
|
||||
commandClient = client
|
||||
}
|
||||
return
|
||||
} catch {
|
||||
print("URLTesting... \(error)")
|
||||
try? client.disconnect()
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
private class clientHandler: NSObject, LibboxCommandClientHandlerProtocol {
|
||||
private let commandClient: CommandClient
|
||||
|
||||
init(_ commandClient: CommandClient) {
|
||||
self.commandClient = commandClient
|
||||
}
|
||||
|
||||
func connected() {
|
||||
DispatchQueue.main.async { [self] in
|
||||
if commandClient.connectionType == .log {
|
||||
commandClient.logList = []
|
||||
}
|
||||
commandClient.isConnected = true
|
||||
}
|
||||
}
|
||||
|
||||
func disconnected(_: String?) {
|
||||
DispatchQueue.main.async { [self] in
|
||||
commandClient.isConnected = false
|
||||
}
|
||||
}
|
||||
|
||||
func clearLog() {
|
||||
DispatchQueue.main.async { [self] in
|
||||
commandClient.logList.removeAll()
|
||||
}
|
||||
}
|
||||
|
||||
func writeLog(_ message: String?) {
|
||||
// print("writeStatus \(String(describing: message))")
|
||||
guard let message else {
|
||||
return
|
||||
}
|
||||
DispatchQueue.main.async { [self] in
|
||||
if commandClient.logList.count > commandClient.logMaxLines {
|
||||
commandClient.logList.removeFirst()
|
||||
}
|
||||
commandClient.logList.append(message)
|
||||
}
|
||||
}
|
||||
|
||||
func writeStatus(_ message: LibboxStatusMessage?) {
|
||||
// print("writeStatus \(String(describing: message?.description))")
|
||||
DispatchQueue.main.async { [self] in
|
||||
commandClient.status = message
|
||||
}
|
||||
}
|
||||
|
||||
func writeGroups(_ groups: LibboxOutboundGroupIteratorProtocol?) {
|
||||
// print("writeGroups \(String(describing: groups?.next()))")
|
||||
guard let groups else {
|
||||
return
|
||||
}
|
||||
var newGroups: [LibboxOutboundGroup] = []
|
||||
while groups.hasNext() {
|
||||
newGroups.append(groups.next()!)
|
||||
}
|
||||
DispatchQueue.main.async { [self] in
|
||||
commandClient.groups = newGroups
|
||||
}
|
||||
}
|
||||
|
||||
func initializeClashMode(_ modeList: LibboxStringIteratorProtocol?, currentMode: String?) {
|
||||
DispatchQueue.main.async { [self] in
|
||||
commandClient.clashModeList = modeList!.toArray()
|
||||
commandClient.clashMode = currentMode!
|
||||
}
|
||||
}
|
||||
|
||||
func updateClashMode(_ newMode: String?) {
|
||||
DispatchQueue.main.async { [self] in
|
||||
commandClient.clashMode = newMode!
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import Foundation
|
||||
import Libbox
|
||||
|
||||
extension LibboxStringIteratorProtocol {
|
||||
func toArray() -> [String] {
|
||||
var array: [String] = []
|
||||
while hasNext() {
|
||||
array.append(next())
|
||||
}
|
||||
return array
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import Foundation
|
||||
import Libbox
|
||||
import NetworkExtension
|
||||
|
||||
func runBlocking<T>(_ block: @escaping () async -> T) -> T {
|
||||
let semaphore = DispatchSemaphore(value: 0)
|
||||
let box = resultBox<T>()
|
||||
Task.detached {
|
||||
let value = await block()
|
||||
box.result0 = value
|
||||
semaphore.signal()
|
||||
}
|
||||
semaphore.wait()
|
||||
return box.result0
|
||||
}
|
||||
|
||||
func runBlocking<T>(_ tBlock: @escaping () async throws -> T) throws -> T {
|
||||
let semaphore = DispatchSemaphore(value: 0)
|
||||
let box = resultBox<T>()
|
||||
Task.detached {
|
||||
do {
|
||||
let value = try await tBlock()
|
||||
box.result = .success(value)
|
||||
} catch {
|
||||
box.result = .failure(error)
|
||||
}
|
||||
semaphore.signal()
|
||||
}
|
||||
semaphore.wait()
|
||||
return try box.result.get()
|
||||
}
|
||||
|
||||
private class resultBox<T> {
|
||||
var result: Result<T, Error>!
|
||||
var result0: T!
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import Foundation
|
||||
import SwiftUI
|
||||
|
||||
public class ExtensionEnvironments: ObservableObject {
|
||||
@Published public var logClient = CommandClient(.log)
|
||||
@Published public var extensionProfileLoading = true
|
||||
@Published public var extensionProfile: ExtensionProfile?
|
||||
@Published public var emptyProfiles = false
|
||||
|
||||
public let profileUpdate = ObjectWillChangePublisher()
|
||||
public let selectedProfileUpdate = ObjectWillChangePublisher()
|
||||
public let openSettings = ObjectWillChangePublisher()
|
||||
public let openProfileGetSuccess = ObjectWillChangePublisher() //用户订阅地址更新
|
||||
public let opentixingSubnodes = ObjectWillChangePublisher() //提醒订阅节点弹出续费
|
||||
public let updateTixingdingyueEnabled = ObjectWillChangePublisher() //更新提醒boolean 动态
|
||||
|
||||
public init() {}
|
||||
|
||||
deinit {
|
||||
logClient.disconnect()
|
||||
}
|
||||
|
||||
public func postReload() {
|
||||
Task {
|
||||
await reload()
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
public func reload() async {
|
||||
if let newProfile = try? await ExtensionProfile.load() {
|
||||
if extensionProfile == nil || extensionProfile?.status == .invalid {
|
||||
newProfile.register()
|
||||
extensionProfile = newProfile
|
||||
extensionProfileLoading = false
|
||||
}
|
||||
} else {
|
||||
extensionProfile = nil
|
||||
extensionProfileLoading = false
|
||||
}
|
||||
}
|
||||
|
||||
public func connectLog() {
|
||||
guard let profile = extensionProfile else {
|
||||
return
|
||||
}
|
||||
if profile.status.isConnected, !logClient.isConnected {
|
||||
logClient.connect()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,338 @@
|
||||
import Foundation
|
||||
import Libbox
|
||||
import NetworkExtension
|
||||
#if canImport(CoreWLAN)
|
||||
import CoreWLAN
|
||||
#endif
|
||||
|
||||
public class ExtensionPlatformInterface: NSObject, LibboxPlatformInterfaceProtocol, LibboxCommandServerHandlerProtocol {
|
||||
private let tunnel: ExtensionProvider
|
||||
private var networkSettings: NEPacketTunnelNetworkSettings?
|
||||
|
||||
init(_ tunnel: ExtensionProvider) {
|
||||
self.tunnel = tunnel
|
||||
}
|
||||
|
||||
public func openTun(_ options: LibboxTunOptionsProtocol?, ret0_: UnsafeMutablePointer<Int32>?) throws {
|
||||
try runBlocking { [self] in
|
||||
try await openTun0(options, ret0_)
|
||||
}
|
||||
}
|
||||
|
||||
private func openTun0(_ options: LibboxTunOptionsProtocol?, _ ret0_: UnsafeMutablePointer<Int32>?) async throws {
|
||||
guard let options else {
|
||||
throw NSError(domain: "nil options", code: 0)
|
||||
}
|
||||
guard let ret0_ else {
|
||||
throw NSError(domain: "nil return pointer", code: 0)
|
||||
}
|
||||
|
||||
let autoRouteUseSubRangesByDefault = await SharedPreferences.autoRouteUseSubRangesByDefault.get()
|
||||
let excludeAPNs = await SharedPreferences.excludeAPNsRoute.get()
|
||||
|
||||
let settings = NEPacketTunnelNetworkSettings(tunnelRemoteAddress: "127.0.0.1")
|
||||
if options.getAutoRoute() {
|
||||
settings.mtu = NSNumber(value: options.getMTU())
|
||||
|
||||
var error: NSError?
|
||||
let dnsServer = options.getDNSServerAddress(&error)
|
||||
if let error {
|
||||
throw error
|
||||
}
|
||||
settings.dnsSettings = NEDNSSettings(servers: [dnsServer])
|
||||
|
||||
var ipv4Address: [String] = []
|
||||
var ipv4Mask: [String] = []
|
||||
let ipv4AddressIterator = options.getInet4Address()!
|
||||
while ipv4AddressIterator.hasNext() {
|
||||
let ipv4Prefix = ipv4AddressIterator.next()!
|
||||
ipv4Address.append(ipv4Prefix.address())
|
||||
ipv4Mask.append(ipv4Prefix.mask())
|
||||
}
|
||||
|
||||
let ipv4Settings = NEIPv4Settings(addresses: ipv4Address, subnetMasks: ipv4Mask)
|
||||
var ipv4Routes: [NEIPv4Route] = []
|
||||
var ipv4ExcludeRoutes: [NEIPv4Route] = []
|
||||
|
||||
let inet4RouteAddressIterator = options.getInet4RouteAddress()!
|
||||
if inet4RouteAddressIterator.hasNext() {
|
||||
while inet4RouteAddressIterator.hasNext() {
|
||||
let ipv4RoutePrefix = inet4RouteAddressIterator.next()!
|
||||
ipv4Routes.append(NEIPv4Route(destinationAddress: ipv4RoutePrefix.address(), subnetMask: ipv4RoutePrefix.mask()))
|
||||
}
|
||||
} else if autoRouteUseSubRangesByDefault {
|
||||
ipv4Routes.append(NEIPv4Route(destinationAddress: "1.0.0.0", subnetMask: "255.0.0.0"))
|
||||
ipv4Routes.append(NEIPv4Route(destinationAddress: "2.0.0.0", subnetMask: "254.0.0.0"))
|
||||
ipv4Routes.append(NEIPv4Route(destinationAddress: "4.0.0.0", subnetMask: "252.0.0.0"))
|
||||
ipv4Routes.append(NEIPv4Route(destinationAddress: "8.0.0.0", subnetMask: "248.0.0.0"))
|
||||
ipv4Routes.append(NEIPv4Route(destinationAddress: "16.0.0.0", subnetMask: "240.0.0.0"))
|
||||
ipv4Routes.append(NEIPv4Route(destinationAddress: "32.0.0.0", subnetMask: "224.0.0.0"))
|
||||
ipv4Routes.append(NEIPv4Route(destinationAddress: "64.0.0.0", subnetMask: "192.0.0.0"))
|
||||
ipv4Routes.append(NEIPv4Route(destinationAddress: "128.0.0.0", subnetMask: "128.0.0.0"))
|
||||
} else {
|
||||
ipv4Routes.append(NEIPv4Route.default())
|
||||
}
|
||||
|
||||
let inet4RouteExcludeAddressIterator = options.getInet4RouteExcludeAddress()!
|
||||
while inet4RouteExcludeAddressIterator.hasNext() {
|
||||
let ipv4RoutePrefix = inet4RouteExcludeAddressIterator.next()!
|
||||
ipv4ExcludeRoutes.append(NEIPv4Route(destinationAddress: ipv4RoutePrefix.address(), subnetMask: ipv4RoutePrefix.mask()))
|
||||
}
|
||||
if await SharedPreferences.excludeDefaultRoute.get(), !ipv4Routes.isEmpty {
|
||||
if !ipv4ExcludeRoutes.contains(where: { it in
|
||||
it.destinationAddress == "0.0.0.0" && it.destinationSubnetMask == "255.255.255.254"
|
||||
}) {
|
||||
ipv4ExcludeRoutes.append(NEIPv4Route(destinationAddress: "0.0.0.0", subnetMask: "255.255.255.254"))
|
||||
}
|
||||
}
|
||||
if excludeAPNs, !ipv4Routes.isEmpty {
|
||||
if !ipv4ExcludeRoutes.contains(where: { it in
|
||||
it.destinationAddress == "17.0.0.0" && it.destinationSubnetMask == "255.0.0.0"
|
||||
}) {
|
||||
ipv4ExcludeRoutes.append(NEIPv4Route(destinationAddress: "17.0.0.0", subnetMask: "255.0.0.0"))
|
||||
}
|
||||
}
|
||||
|
||||
ipv4Settings.includedRoutes = ipv4Routes
|
||||
ipv4Settings.excludedRoutes = ipv4ExcludeRoutes
|
||||
settings.ipv4Settings = ipv4Settings
|
||||
|
||||
var ipv6Address: [String] = []
|
||||
var ipv6Prefixes: [NSNumber] = []
|
||||
let ipv6AddressIterator = options.getInet6Address()!
|
||||
while ipv6AddressIterator.hasNext() {
|
||||
let ipv6Prefix = ipv6AddressIterator.next()!
|
||||
ipv6Address.append(ipv6Prefix.address())
|
||||
ipv6Prefixes.append(NSNumber(value: ipv6Prefix.prefix()))
|
||||
}
|
||||
let ipv6Settings = NEIPv6Settings(addresses: ipv6Address, networkPrefixLengths: ipv6Prefixes)
|
||||
var ipv6Routes: [NEIPv6Route] = []
|
||||
var ipv6ExcludeRoutes: [NEIPv6Route] = []
|
||||
|
||||
let inet6RouteAddressIterator = options.getInet6RouteAddress()!
|
||||
if inet6RouteAddressIterator.hasNext() {
|
||||
while inet6RouteAddressIterator.hasNext() {
|
||||
let ipv6RoutePrefix = inet6RouteAddressIterator.next()!
|
||||
ipv6Routes.append(NEIPv6Route(destinationAddress: ipv6RoutePrefix.address(), networkPrefixLength: NSNumber(value: ipv6RoutePrefix.prefix())))
|
||||
}
|
||||
} else if autoRouteUseSubRangesByDefault {
|
||||
ipv6Routes.append(NEIPv6Route(destinationAddress: "100::", networkPrefixLength: 8))
|
||||
ipv6Routes.append(NEIPv6Route(destinationAddress: "200::", networkPrefixLength: 7))
|
||||
ipv6Routes.append(NEIPv6Route(destinationAddress: "400::", networkPrefixLength: 6))
|
||||
ipv6Routes.append(NEIPv6Route(destinationAddress: "800::", networkPrefixLength: 5))
|
||||
ipv6Routes.append(NEIPv6Route(destinationAddress: "1000::", networkPrefixLength: 4))
|
||||
ipv6Routes.append(NEIPv6Route(destinationAddress: "2000::", networkPrefixLength: 3))
|
||||
ipv6Routes.append(NEIPv6Route(destinationAddress: "4000::", networkPrefixLength: 2))
|
||||
ipv6Routes.append(NEIPv6Route(destinationAddress: "8000::", networkPrefixLength: 1))
|
||||
} else {
|
||||
ipv6Routes.append(NEIPv6Route.default())
|
||||
}
|
||||
|
||||
let inet6RouteExcludeAddressIterator = options.getInet6RouteExcludeAddress()!
|
||||
while inet6RouteExcludeAddressIterator.hasNext() {
|
||||
let ipv6RoutePrefix = inet6RouteExcludeAddressIterator.next()!
|
||||
ipv6ExcludeRoutes.append(NEIPv6Route(destinationAddress: ipv6RoutePrefix.address(), networkPrefixLength: NSNumber(value: ipv6RoutePrefix.prefix())))
|
||||
}
|
||||
|
||||
ipv6Settings.includedRoutes = ipv6Routes
|
||||
ipv6Settings.excludedRoutes = ipv6ExcludeRoutes
|
||||
settings.ipv6Settings = ipv6Settings
|
||||
}
|
||||
|
||||
if options.isHTTPProxyEnabled() {
|
||||
let proxySettings = NEProxySettings()
|
||||
let proxyServer = NEProxyServer(address: options.getHTTPProxyServer(), port: Int(options.getHTTPProxyServerPort()))
|
||||
proxySettings.httpServer = proxyServer
|
||||
proxySettings.httpsServer = proxyServer
|
||||
if await SharedPreferences.systemProxyEnabled.get() {
|
||||
proxySettings.httpEnabled = true
|
||||
proxySettings.httpsEnabled = true
|
||||
}
|
||||
var bypassDomains: [String] = []
|
||||
let bypassDomainIterator = options.getHTTPProxyBypassDomain()!
|
||||
while bypassDomainIterator.hasNext() {
|
||||
bypassDomains.append(bypassDomainIterator.next())
|
||||
}
|
||||
if excludeAPNs {
|
||||
if !bypassDomains.contains(where: { it in
|
||||
it == "push.apple.com"
|
||||
}) {
|
||||
bypassDomains.append("push.apple.com")
|
||||
}
|
||||
}
|
||||
if !bypassDomains.isEmpty {
|
||||
proxySettings.exceptionList = bypassDomains
|
||||
}
|
||||
var matchDomains: [String] = []
|
||||
let matchDomainIterator = options.getHTTPProxyMatchDomain()!
|
||||
while matchDomainIterator.hasNext() {
|
||||
matchDomains.append(matchDomainIterator.next())
|
||||
}
|
||||
if !matchDomains.isEmpty {
|
||||
proxySettings.matchDomains = matchDomains
|
||||
}
|
||||
settings.proxySettings = proxySettings
|
||||
}
|
||||
|
||||
networkSettings = settings
|
||||
try await tunnel.setTunnelNetworkSettings(settings)
|
||||
|
||||
if let tunFd = tunnel.packetFlow.value(forKeyPath: "socket.fileDescriptor") as? Int32 {
|
||||
ret0_.pointee = tunFd
|
||||
return
|
||||
}
|
||||
|
||||
let tunFdFromLoop = LibboxGetTunnelFileDescriptor()
|
||||
if tunFdFromLoop != -1 {
|
||||
ret0_.pointee = tunFdFromLoop
|
||||
} else {
|
||||
throw NSError(domain: "missing file descriptor", code: 0)
|
||||
}
|
||||
}
|
||||
|
||||
public func usePlatformAutoDetectControl() -> Bool {
|
||||
true
|
||||
}
|
||||
|
||||
public func autoDetectControl(_: Int32) throws {}
|
||||
|
||||
public func findConnectionOwner(_: Int32, sourceAddress _: String?, sourcePort _: Int32, destinationAddress _: String?, destinationPort _: Int32, ret0_ _: UnsafeMutablePointer<Int32>?) throws {
|
||||
throw NSError(domain: "not implemented", code: 0)
|
||||
}
|
||||
|
||||
public func packageName(byUid _: Int32, error _: NSErrorPointer) -> String {
|
||||
""
|
||||
}
|
||||
|
||||
public func uid(byPackageName _: String?, ret0_ _: UnsafeMutablePointer<Int32>?) throws {
|
||||
throw NSError(domain: "not implemented", code: 0)
|
||||
}
|
||||
|
||||
public func useProcFS() -> Bool {
|
||||
false
|
||||
}
|
||||
|
||||
public func writeLog(_ message: String?) {
|
||||
guard let message else {
|
||||
return
|
||||
}
|
||||
tunnel.writeMessage(message)
|
||||
}
|
||||
|
||||
public func usePlatformDefaultInterfaceMonitor() -> Bool {
|
||||
false
|
||||
}
|
||||
|
||||
public func startDefaultInterfaceMonitor(_: LibboxInterfaceUpdateListenerProtocol?) throws {}
|
||||
|
||||
public func closeDefaultInterfaceMonitor(_: LibboxInterfaceUpdateListenerProtocol?) throws {}
|
||||
|
||||
public func useGetter() -> Bool {
|
||||
false
|
||||
}
|
||||
|
||||
public func getInterfaces() throws -> LibboxNetworkInterfaceIteratorProtocol {
|
||||
throw NSError(domain: "not implemented", code: 0)
|
||||
}
|
||||
|
||||
public func underNetworkExtension() -> Bool {
|
||||
true
|
||||
}
|
||||
|
||||
public func includeAllNetworks() -> Bool {
|
||||
#if !os(tvOS)
|
||||
return SharedPreferences.includeAllNetworks.getBlocking()
|
||||
#else
|
||||
return false
|
||||
#endif
|
||||
}
|
||||
|
||||
public func clearDNSCache() {
|
||||
guard let networkSettings else {
|
||||
return
|
||||
}
|
||||
tunnel.reasserting = true
|
||||
tunnel.setTunnelNetworkSettings(nil) { _ in
|
||||
}
|
||||
tunnel.setTunnelNetworkSettings(networkSettings) { _ in
|
||||
}
|
||||
tunnel.reasserting = false
|
||||
}
|
||||
|
||||
public func readWIFIState() -> LibboxWIFIState? {
|
||||
#if os(iOS)
|
||||
let network = runBlocking {
|
||||
await NEHotspotNetwork.fetchCurrent()
|
||||
}
|
||||
guard let network else {
|
||||
return nil
|
||||
}
|
||||
return LibboxWIFIState(network.ssid, wifiBSSID: network.bssid)!
|
||||
#elseif os(macOS)
|
||||
guard let interface = CWWiFiClient.shared().interface() else {
|
||||
return nil
|
||||
}
|
||||
guard let ssid = interface.ssid() else {
|
||||
return nil
|
||||
}
|
||||
guard let bssid = interface.bssid() else {
|
||||
return nil
|
||||
}
|
||||
return LibboxWIFIState(ssid, wifiBSSID: bssid)!
|
||||
#else
|
||||
return nil
|
||||
#endif
|
||||
}
|
||||
|
||||
public func serviceReload() throws {
|
||||
runBlocking { [self] in
|
||||
await tunnel.reloadService()
|
||||
}
|
||||
}
|
||||
|
||||
public func postServiceClose() {
|
||||
reset()
|
||||
tunnel.postServiceClose()
|
||||
}
|
||||
|
||||
public func getSystemProxyStatus() -> LibboxSystemProxyStatus? {
|
||||
let status = LibboxSystemProxyStatus()
|
||||
guard let networkSettings else {
|
||||
return status
|
||||
}
|
||||
guard let proxySettings = networkSettings.proxySettings else {
|
||||
return status
|
||||
}
|
||||
if proxySettings.httpServer == nil {
|
||||
return status
|
||||
}
|
||||
status.available = true
|
||||
status.enabled = proxySettings.httpEnabled
|
||||
return status
|
||||
}
|
||||
|
||||
public func setSystemProxyEnabled(_ isEnabled: Bool) throws {
|
||||
guard let networkSettings else {
|
||||
return
|
||||
}
|
||||
guard let proxySettings = networkSettings.proxySettings else {
|
||||
return
|
||||
}
|
||||
if proxySettings.httpServer == nil {
|
||||
return
|
||||
}
|
||||
if proxySettings.httpEnabled == isEnabled {
|
||||
return
|
||||
}
|
||||
proxySettings.httpEnabled = isEnabled
|
||||
proxySettings.httpsEnabled = isEnabled
|
||||
networkSettings.proxySettings = proxySettings
|
||||
try runBlocking {
|
||||
try await self.tunnel.setTunnelNetworkSettings(networkSettings)
|
||||
}
|
||||
}
|
||||
|
||||
func reset() {
|
||||
networkSettings = nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import Foundation
|
||||
import Libbox
|
||||
import NetworkExtension
|
||||
|
||||
public class ExtensionProfile: ObservableObject {
|
||||
private let manager: NEVPNManager
|
||||
private var connection: NEVPNConnection
|
||||
private var observer: Any?
|
||||
|
||||
@Published public var status: NEVPNStatus
|
||||
|
||||
public init(_ manager: NEVPNManager) {
|
||||
self.manager = manager
|
||||
connection = manager.connection
|
||||
status = manager.connection.status
|
||||
}
|
||||
|
||||
public func register() {
|
||||
observer = NotificationCenter.default.addObserver(
|
||||
forName: NSNotification.Name.NEVPNStatusDidChange,
|
||||
object: manager.connection,
|
||||
queue: .main
|
||||
) { [weak self] notification in
|
||||
guard let self else {
|
||||
return
|
||||
}
|
||||
self.connection = notification.object as! NEVPNConnection
|
||||
self.status = self.connection.status
|
||||
}
|
||||
}
|
||||
|
||||
private func unregister() {
|
||||
if let observer {
|
||||
NotificationCenter.default.removeObserver(observer)
|
||||
}
|
||||
}
|
||||
|
||||
private func setOnDemandRules() {
|
||||
let interfaceRule = NEOnDemandRuleConnect()
|
||||
interfaceRule.interfaceTypeMatch = .any
|
||||
let probeRule = NEOnDemandRuleConnect()
|
||||
probeRule.probeURL = URL(string: "http://captive.apple.com")
|
||||
manager.onDemandRules = [interfaceRule, probeRule]
|
||||
}
|
||||
|
||||
public func updateAlwaysOn(_ newState: Bool) async throws {
|
||||
manager.isOnDemandEnabled = newState
|
||||
setOnDemandRules()
|
||||
try await manager.saveToPreferences()
|
||||
}
|
||||
|
||||
public func start() async throws {
|
||||
await fetchProfile()
|
||||
manager.isEnabled = true
|
||||
if await SharedPreferences.alwaysOn.get() {
|
||||
manager.isOnDemandEnabled = true
|
||||
setOnDemandRules()
|
||||
}
|
||||
#if !os(tvOS)
|
||||
if let protocolConfiguration = manager.protocolConfiguration {
|
||||
let includeAllNetworks = await SharedPreferences.includeAllNetworks.get()
|
||||
protocolConfiguration.includeAllNetworks = includeAllNetworks
|
||||
if #available(iOS 16.4, macOS 13.3, *) {
|
||||
protocolConfiguration.excludeCellularServices = !includeAllNetworks
|
||||
}
|
||||
}
|
||||
#endif
|
||||
try await manager.saveToPreferences()
|
||||
#if os(macOS)
|
||||
if Variant.useSystemExtension {
|
||||
try manager.connection.startVPNTunnel(options: [
|
||||
"username": NSString(string: NSUserName()),
|
||||
])
|
||||
return
|
||||
}
|
||||
#endif
|
||||
try manager.connection.startVPNTunnel()
|
||||
}
|
||||
|
||||
public func fetchProfile() async {
|
||||
do {
|
||||
if let profile = try await ProfileManager.get(Int64(SharedPreferences.selectedProfileID.get())) {
|
||||
if profile.type == .icloud {
|
||||
_ = try profile.read()
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
|
||||
public func stop() async throws {
|
||||
if manager.isOnDemandEnabled {
|
||||
manager.isOnDemandEnabled = false
|
||||
try await manager.saveToPreferences()
|
||||
}
|
||||
do {
|
||||
try LibboxNewStandaloneCommandClient()!.serviceClose()
|
||||
} catch {}
|
||||
manager.connection.stopVPNTunnel()
|
||||
}
|
||||
|
||||
public static func load() async throws -> ExtensionProfile? {
|
||||
let managers = try await NETunnelProviderManager.loadAllFromPreferences()
|
||||
if managers.isEmpty {
|
||||
return nil
|
||||
}
|
||||
let profile = ExtensionProfile(managers[0])
|
||||
return profile
|
||||
}
|
||||
|
||||
public static func install() async throws {
|
||||
let manager = NETunnelProviderManager()
|
||||
manager.localizedDescription = Variant.applicationName
|
||||
let tunnelProtocol = NETunnelProviderProtocol()
|
||||
if Variant.useSystemExtension {
|
||||
tunnelProtocol.providerBundleIdentifier = "\(FilePath.packageName).system"
|
||||
} else {
|
||||
tunnelProtocol.providerBundleIdentifier = "\(FilePath.packageName).extension"
|
||||
}
|
||||
tunnelProtocol.serverAddress = Variant.applicationName// "sing-box"
|
||||
manager.protocolConfiguration = tunnelProtocol
|
||||
manager.isEnabled = true
|
||||
try await manager.saveToPreferences()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
import Foundation
|
||||
import Libbox
|
||||
import NetworkExtension
|
||||
|
||||
open class ExtensionProvider: NEPacketTunnelProvider {
|
||||
public var username: String? = nil
|
||||
private var commandServer: LibboxCommandServer!
|
||||
private var boxService: LibboxBoxService!
|
||||
private var systemProxyAvailable = false
|
||||
private var systemProxyEnabled = false
|
||||
private var platformInterface: ExtensionPlatformInterface!
|
||||
|
||||
override open func startTunnel(options _: [String: NSObject]?) async throws {
|
||||
LibboxClearServiceError()
|
||||
|
||||
if let username {
|
||||
var error: NSError?
|
||||
LibboxSetupWithUsername(FilePath.sharedDirectory.relativePath, FilePath.workingDirectory.relativePath, FilePath.cacheDirectory.relativePath, username, &error)
|
||||
if let error {
|
||||
writeFatalError("(packet-tunnel) error: setup service: \(error.localizedDescription)")
|
||||
return
|
||||
}
|
||||
} else {
|
||||
var isTVOS = false
|
||||
#if os(tvOS)
|
||||
isTVOS = true
|
||||
#endif
|
||||
LibboxSetup(FilePath.sharedDirectory.relativePath, FilePath.workingDirectory.relativePath, FilePath.cacheDirectory.relativePath, isTVOS)
|
||||
}
|
||||
|
||||
var error: NSError?
|
||||
LibboxRedirectStderr(FilePath.cacheDirectory.appendingPathComponent("stderr.log").relativePath, &error)
|
||||
if let error {
|
||||
writeFatalError("(packet-tunnel) redirect stderr error: \(error.localizedDescription)")
|
||||
}
|
||||
|
||||
await LibboxSetMemoryLimit(!SharedPreferences.ignoreMemoryLimit.get())
|
||||
|
||||
if platformInterface == nil {
|
||||
platformInterface = ExtensionPlatformInterface(self)
|
||||
}
|
||||
commandServer = await LibboxNewCommandServer(platformInterface, Int32(SharedPreferences.maxLogLines.get()))
|
||||
do {
|
||||
try commandServer.start()
|
||||
} catch {
|
||||
writeFatalError("(packet-tunnel): log server start error: \(error.localizedDescription)")
|
||||
return
|
||||
}
|
||||
writeMessage("(packet-tunnel): Here I stand")
|
||||
await startService()
|
||||
}
|
||||
|
||||
func writeMessage(_ message: String) {
|
||||
if let commandServer {
|
||||
commandServer.writeMessage(message)
|
||||
} else {
|
||||
NSLog(message)
|
||||
}
|
||||
}
|
||||
|
||||
public func writeFatalError(_ message: String) {
|
||||
#if DEBUG
|
||||
NSLog(message)
|
||||
#endif
|
||||
writeMessage(message)
|
||||
var error: NSError?
|
||||
LibboxWriteServiceError(message, &error)
|
||||
cancelTunnelWithError(NSError(domain: message, code: 0))
|
||||
}
|
||||
|
||||
private func startService() async {
|
||||
let profile: Profile?
|
||||
do {
|
||||
profile = try await ProfileManager.get(Int64(SharedPreferences.selectedProfileID.get()))
|
||||
} catch {
|
||||
writeFatalError("(packet-tunnel) error: read selected profile: \(error.localizedDescription)")
|
||||
return
|
||||
}
|
||||
guard let profile else {
|
||||
writeFatalError("(packet-tunnel) error: missing selected profile")
|
||||
return
|
||||
}
|
||||
let configContent: String
|
||||
do {
|
||||
configContent = try profile.read()
|
||||
} catch {
|
||||
writeFatalError("(packet-tunnel) error: read config file \(profile.path): \(error.localizedDescription)")
|
||||
return
|
||||
}
|
||||
var error: NSError?
|
||||
let service = LibboxNewService(configContent, platformInterface, &error)
|
||||
if let error {
|
||||
writeFatalError("(packet-tunnel) error: create service: \(error.localizedDescription)")
|
||||
return
|
||||
}
|
||||
guard let service else {
|
||||
return
|
||||
}
|
||||
commandServer.setService(service)
|
||||
do {
|
||||
try service.start()
|
||||
} catch {
|
||||
commandServer.setService(nil)
|
||||
writeFatalError("(packet-tunnel) error: start service: \(error.localizedDescription)")
|
||||
return
|
||||
}
|
||||
boxService = service
|
||||
#if os(macOS)
|
||||
await SharedPreferences.startedByUser.set(true)
|
||||
#endif
|
||||
}
|
||||
|
||||
private func stopService() {
|
||||
if let service = boxService {
|
||||
do {
|
||||
try service.close()
|
||||
} catch {
|
||||
writeMessage("(packet-tunnel) error: stop service: \(error.localizedDescription)")
|
||||
}
|
||||
boxService = nil
|
||||
commandServer.setService(nil)
|
||||
}
|
||||
if let platformInterface {
|
||||
platformInterface.reset()
|
||||
}
|
||||
}
|
||||
|
||||
func reloadService() async {
|
||||
writeMessage("(packet-tunnel) reloading service")
|
||||
reasserting = true
|
||||
defer {
|
||||
reasserting = false
|
||||
}
|
||||
stopService()
|
||||
commandServer.resetLog()
|
||||
await startService()
|
||||
}
|
||||
|
||||
func postServiceClose() {
|
||||
boxService = nil
|
||||
}
|
||||
|
||||
override open func stopTunnel(with reason: NEProviderStopReason) async {
|
||||
writeMessage("(packet-tunnel) stopping, reason: \(reason)")
|
||||
stopService()
|
||||
if let server = commandServer {
|
||||
try? await Task.sleep(nanoseconds: 100 * NSEC_PER_MSEC)
|
||||
try? server.close()
|
||||
commandServer = nil
|
||||
}
|
||||
#if os(macOS)
|
||||
if reason == .userInitiated {
|
||||
await SharedPreferences.startedByUser.set(reason == .userInitiated)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
override open func handleAppMessage(_ messageData: Data) async -> Data? {
|
||||
messageData
|
||||
}
|
||||
|
||||
override open func sleep() async {
|
||||
if let boxService {
|
||||
boxService.pause()
|
||||
}
|
||||
}
|
||||
|
||||
override open func wake() {
|
||||
if let boxService {
|
||||
boxService.wake()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import Foundation
|
||||
import Libbox
|
||||
|
||||
public class HTTPClient {
|
||||
private static var userAgent: String {
|
||||
var userAgent = Variant.applicationName
|
||||
userAgent += "/"
|
||||
userAgent += Bundle.main.version
|
||||
userAgent += " (Build "
|
||||
userAgent += Bundle.main.versionNumber
|
||||
userAgent += "; sing-box "
|
||||
userAgent += LibboxVersion()
|
||||
userAgent += ")"
|
||||
return userAgent
|
||||
}
|
||||
|
||||
private let client: any LibboxHTTPClientProtocol
|
||||
|
||||
public init() {
|
||||
client = LibboxNewHTTPClient()!
|
||||
client.modernTLS()
|
||||
}
|
||||
|
||||
public func getString(_ url: String?) throws -> String {
|
||||
let request = client.newRequest()!
|
||||
request.setUserAgent(HTTPClient.userAgent)
|
||||
try request.setURL(url)
|
||||
let response = try request.execute()
|
||||
var error: NSError?
|
||||
let contentString = response.getContentString(&error)
|
||||
if let error {
|
||||
throw error
|
||||
}
|
||||
return contentString
|
||||
}
|
||||
|
||||
deinit {
|
||||
client.close()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import Foundation
|
||||
import NetworkExtension
|
||||
|
||||
public extension NEVPNStatus {
|
||||
var isEnabled: Bool {
|
||||
switch self {
|
||||
case .connected, .disconnected, .reasserting:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
var isSwitchable: Bool {
|
||||
switch self {
|
||||
case .connected, .disconnected:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
var isConnected: Bool {
|
||||
switch self {
|
||||
case .connecting, .connected, .disconnecting, .reasserting:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
var isConnectedStrict: Bool {
|
||||
switch self {
|
||||
case .connected, .reasserting:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
#if os(macOS)
|
||||
import Foundation
|
||||
import SystemExtensions
|
||||
|
||||
public class SystemExtension: NSObject, OSSystemExtensionRequestDelegate {
|
||||
private let forceUpdate: Bool
|
||||
private let inBackground: Bool
|
||||
private let semaphore = DispatchSemaphore(value: 0)
|
||||
private var result: OSSystemExtensionRequest.Result?
|
||||
private var properties: [OSSystemExtensionProperties]?
|
||||
private var error: Error?
|
||||
|
||||
private init(_ forceUpdate: Bool = false, _ inBackground: Bool = false) {
|
||||
self.forceUpdate = forceUpdate
|
||||
self.inBackground = inBackground
|
||||
}
|
||||
|
||||
public func request(_: OSSystemExtensionRequest, actionForReplacingExtension existing: OSSystemExtensionProperties, withExtension ext: OSSystemExtensionProperties) -> OSSystemExtensionRequest.ReplacementAction {
|
||||
if forceUpdate {
|
||||
return .replace
|
||||
}
|
||||
if existing.isAwaitingUserApproval, !inBackground {
|
||||
return .replace
|
||||
}
|
||||
if existing.bundleIdentifier == ext.bundleIdentifier,
|
||||
existing.bundleVersion == ext.bundleVersion,
|
||||
existing.bundleShortVersion == ext.bundleShortVersion
|
||||
{
|
||||
NSLog("Skip update system extension")
|
||||
return .cancel
|
||||
} else {
|
||||
NSLog("Update system extension")
|
||||
return .replace
|
||||
}
|
||||
}
|
||||
|
||||
public func requestNeedsUserApproval(_: OSSystemExtensionRequest) {
|
||||
semaphore.signal()
|
||||
}
|
||||
|
||||
public func request(_: OSSystemExtensionRequest, didFinishWithResult result: OSSystemExtensionRequest.Result) {
|
||||
self.result = result
|
||||
semaphore.signal()
|
||||
}
|
||||
|
||||
public func request(_: OSSystemExtensionRequest, didFailWithError error: Error) {
|
||||
self.error = error
|
||||
semaphore.signal()
|
||||
}
|
||||
|
||||
public func request(_: OSSystemExtensionRequest, foundProperties properties: [OSSystemExtensionProperties]) {
|
||||
self.properties = properties
|
||||
semaphore.signal()
|
||||
}
|
||||
|
||||
public func activation() throws -> OSSystemExtensionRequest.Result? {
|
||||
let request = OSSystemExtensionRequest.activationRequest(forExtensionWithIdentifier: FilePath.packageName + ".system", queue: .main)
|
||||
request.delegate = self
|
||||
OSSystemExtensionManager.shared.submitRequest(request)
|
||||
semaphore.wait()
|
||||
if let error {
|
||||
throw error
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
public func deactivation() throws -> OSSystemExtensionRequest.Result? {
|
||||
let request = OSSystemExtensionRequest.deactivationRequest(forExtensionWithIdentifier: FilePath.packageName + ".system", queue: .main)
|
||||
request.delegate = self
|
||||
OSSystemExtensionManager.shared.submitRequest(request)
|
||||
semaphore.wait()
|
||||
if let error {
|
||||
throw error
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
public func getProperties() throws -> [OSSystemExtensionProperties] {
|
||||
let request = OSSystemExtensionRequest.propertiesRequest(forExtensionWithIdentifier: FilePath.packageName + ".system", queue: .main)
|
||||
request.delegate = self
|
||||
OSSystemExtensionManager.shared.submitRequest(request)
|
||||
semaphore.wait()
|
||||
if let error {
|
||||
throw error
|
||||
}
|
||||
return properties!
|
||||
}
|
||||
|
||||
public static func isInstalled() async -> Bool {
|
||||
await (try? Task {
|
||||
try await isInstalledBackground()
|
||||
}.result.get()) == true
|
||||
}
|
||||
|
||||
public nonisolated static func isInstalledBackground() async throws -> Bool {
|
||||
for _ in 0 ..< 3 {
|
||||
do {
|
||||
let propList = try SystemExtension().getProperties()
|
||||
if propList.isEmpty {
|
||||
return false
|
||||
}
|
||||
for extensionProp in propList {
|
||||
if !extensionProp.isAwaitingUserApproval, !extensionProp.isUninstalling {
|
||||
return true
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
try await Task.sleep(nanoseconds: NSEC_PER_SEC)
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
public nonisolated static func install(forceUpdate: Bool = false, inBackground: Bool = false) async throws -> OSSystemExtensionRequest.Result? {
|
||||
try await Task.detached {
|
||||
try SystemExtension(forceUpdate, inBackground).activation()
|
||||
}.result.get()
|
||||
}
|
||||
|
||||
public nonisolated static func uninstall() async throws -> OSSystemExtensionRequest.Result? {
|
||||
try await Task.detached {
|
||||
try SystemExtension().deactivation()
|
||||
}.result.get()
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,11 @@
|
||||
import Foundation
|
||||
|
||||
extension Bundle {
|
||||
var version: String {
|
||||
infoDictionary?["CFBundleShortVersionString"] as? String ?? "unknown"
|
||||
}
|
||||
|
||||
var versionNumber: String {
|
||||
infoDictionary?["CFBundleVersion"] as? String ?? "unknown"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import Foundation
|
||||
import SwiftUI
|
||||
#if canImport(UIKit)
|
||||
import UIKit
|
||||
#elseif canImport(AppKit)
|
||||
import AppKit
|
||||
#endif
|
||||
|
||||
public extension Color {
|
||||
static var textColor: Color {
|
||||
#if canImport(UIKit)
|
||||
if #available(iOSApplicationExtension 15.0, *) {
|
||||
return Color(uiColor: .label)
|
||||
}else{
|
||||
return Color.black
|
||||
}
|
||||
|
||||
#elseif canImport(AppKit)
|
||||
return Color(nsColor: .textColor)
|
||||
#endif
|
||||
}
|
||||
|
||||
static var linkColor: Color {
|
||||
#if canImport(UIKit)
|
||||
if #available(iOSApplicationExtension 15.0, *) {
|
||||
return Color(uiColor: .link)
|
||||
}else{
|
||||
return Color.black
|
||||
}
|
||||
|
||||
#elseif canImport(AppKit)
|
||||
return Color(nsColor: .linkColor)
|
||||
#endif
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import Foundation
|
||||
|
||||
public enum FilePath {
|
||||
public static let packageName = "com.uuvpn.appleaman"
|
||||
}
|
||||
|
||||
public extension FilePath {
|
||||
static let groupName = "group.\(packageName)"
|
||||
|
||||
private static let defaultSharedDirectory: URL! = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: FilePath.groupName)
|
||||
|
||||
#if os(iOS)
|
||||
static let sharedDirectory = defaultSharedDirectory!
|
||||
#elseif os(tvOS)
|
||||
static let sharedDirectory = defaultSharedDirectory
|
||||
.appendingPathComponent("Library", isDirectory: true)
|
||||
.appendingPathComponent("Caches", isDirectory: true)
|
||||
#elseif os(macOS)
|
||||
static var sharedDirectory: URL! = defaultSharedDirectory
|
||||
#endif
|
||||
|
||||
#if os(iOS)
|
||||
static let cacheDirectory = sharedDirectory
|
||||
.appendingPathComponent("Library", isDirectory: true)
|
||||
.appendingPathComponent("Caches", isDirectory: true)
|
||||
#elseif os(tvOS)
|
||||
static let cacheDirectory = sharedDirectory
|
||||
#elseif os(macOS)
|
||||
static var cacheDirectory: URL {
|
||||
sharedDirectory
|
||||
.appendingPathComponent("Library", isDirectory: true)
|
||||
.appendingPathComponent("Caches", isDirectory: true)
|
||||
}
|
||||
#endif
|
||||
|
||||
#if os(macOS)
|
||||
static var workingDirectory: URL {
|
||||
cacheDirectory.appendingPathComponent("Working", isDirectory: true)
|
||||
}
|
||||
#else
|
||||
static let workingDirectory = cacheDirectory.appendingPathComponent("Working", isDirectory: true)
|
||||
|
||||
#endif
|
||||
|
||||
static var iCloudDirectory = FileManager.default.url(forUbiquityContainerIdentifier: nil)?.appendingPathComponent("Documents", isDirectory: true) ?? URL(string: "stub")!
|
||||
}
|
||||
|
||||
public extension URL {
|
||||
var fileName: String {
|
||||
var path = relativePath
|
||||
if let index = path.lastIndex(of: "/") {
|
||||
path = String(path[path.index(index, offsetBy: 1)...])
|
||||
}
|
||||
return path
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import Foundation
|
||||
|
||||
public enum Variant {
|
||||
#if os(macOS)
|
||||
public static var useSystemExtension = false
|
||||
#else
|
||||
public static let useSystemExtension = false
|
||||
#endif
|
||||
|
||||
#if os(iOS)
|
||||
public static let applicationName = "UUVPN"
|
||||
#elseif os(macOS)
|
||||
public static let applicationName = "UUVPN"
|
||||
#elseif os(tvOS)
|
||||
public static let applicationName = "UUVPN"
|
||||
#endif
|
||||
}
|
||||
Reference in New Issue
Block a user