Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions apple/ClashClient/Shared/ConfigResourceStore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,8 @@ final class ConfigResourceStore {
activeDirectoryURL.appendingPathComponent(Name.compatibilityConfiguration)
}

var workingDirectoryURL: URL { workingURL }

init(
containerURL: URL,
maximumConfigurationBytes: Int = ConfigResourceStore.defaultMaximumConfigurationBytes,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,11 @@ final class ActiveRevisionMigrator {
profileID: currentPointer.profileID,
revision: currentPointer.revision
)
if validates(active) {
let inputsChanged = ProfileInputsStamp.inputsChanged(
currentPointer,
workingDirectory: store.workingDirectoryURL
)
if !inputsChanged, validates(active) {
return StartupConfigurationPreparation(
configuration: active,
recovery: .current
Expand All @@ -112,8 +116,12 @@ final class ActiveRevisionMigrator {
}
expectedPointer = rebuiltPointer
} catch {


if validates(active) {
return StartupConfigurationPreparation(
configuration: active,
recovery: .current
)
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3482,6 +3482,7 @@ final class ProfileActivationCoordinator {
}
PublishedSourceLedger.record(published, digest: sourceDigest?.ledger)
PublishedRulesAsWritten.record(published, section: rulesAsWritten, workingDirectory: coreHomeDir)
ProfileInputsStamp.record(published, profile: profile, workingDirectory: coreHomeDir)



Expand Down
77 changes: 77 additions & 0 deletions apple/ClashClient/Sources/ConfigStore/ProfileInputsStamp.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import CryptoKit
import Foundation

enum ProfileInputsStamp {
static let fileName = "published-inputs.json"
private static let schemaVersion = 1
private static let storeDirectoryName = "store"

private struct Record: Codable {
let schemaVersion: Int
let profileID: String
let revision: String
let inputs: String
}

private struct Inputs: Encodable {
let appendRules: [String]
let prependRules: Bool
let legacyRuntimePatchJSON: String?
}

private static func url(workingDirectory: URL) -> URL {
workingDirectory
.appendingPathComponent(storeDirectoryName, isDirectory: true)
.appendingPathComponent(fileName)
}

private static func digest(of profile: Profile) -> String {
let encoder = JSONEncoder()
encoder.outputFormatting = [.sortedKeys]
guard let data = try? encoder.encode(Inputs(
appendRules: profile.override.appendRules,
prependRules: profile.override.prependRules,
legacyRuntimePatchJSON: profile.legacyRuntimePatchJSON
)) else { return "" }
return SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()
}

static func record(_ pointer: ActiveConfigurationPointer, profile: Profile, workingDirectory: URL) {
let file = url(workingDirectory: workingDirectory)
let record = Record(
schemaVersion: schemaVersion,
profileID: pointer.profileID,
revision: pointer.revision,
inputs: digest(of: profile)
)
guard let data = try? JSONEncoder().encode(record) else { return }
try? FileManager.default.createDirectory(
at: file.deletingLastPathComponent(),
withIntermediateDirectories: true
)
try? data.write(to: file, options: [.atomic, .completeFileProtectionUntilFirstUserAuthentication])
}

private static func read(workingDirectory: URL) -> Record? {
guard let data = try? Data(contentsOf: url(workingDirectory: workingDirectory)) else { return nil }
return try? JSONDecoder().decode(Record.self, from: data)
}

static func inputsChanged(_ pointer: ActiveConfigurationPointer, workingDirectory: URL) -> Bool {
guard let profile = storedProfile(pointer.profileID, workingDirectory: workingDirectory) else {
return false
}
guard let record = read(workingDirectory: workingDirectory) else { return true }
return record.schemaVersion != schemaVersion
|| record.profileID != pointer.profileID
|| record.revision != pointer.revision
|| record.inputs != digest(of: profile)
}

private static func storedProfile(_ profileID: String, workingDirectory: URL) -> Profile? {
let file = workingDirectory
.appendingPathComponent(storeDirectoryName, isDirectory: true)
.appendingPathComponent("profiles.json")
return ProfileStore(fileURL: file).load().first { $0.id == profileID }
}
}
42 changes: 36 additions & 6 deletions apple/ClashClient/Sources/ConfigStore/ProfileStore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,34 @@ final class ProfileStore {
}

func save(_ profiles: [Profile]) throws {
try Self.withWriteLock { try write(profiles) }
try withWriteLock { try write(profiles) }
}

// Every write takes the in-process lock, then the cross-process lock file
// the kernel and the tunnel extension use, so a concurrent CLI write cannot
// land between our read and our save.
func withWriteLock<T>(_ body: () throws -> T) throws -> T {
try Self.withWriteLock {
try fileManager.createDirectory(at: fileURL.deletingLastPathComponent(),
withIntermediateDirectories: true)
let lock = crossProcessLock()
try lock.lock()
defer { lock.unlock() }
return try body()
}
}

// Guarded by `writeLock`; one lock object per store directory so a nested
// hold on the same thread re-enters instead of deadlocking on flock.
nonisolated(unsafe) private static var crossProcessLocks: [String: ProfileStoreCrossProcessLock] = [:]

private func crossProcessLock() -> ProfileStoreCrossProcessLock {
let directory = fileURL.deletingLastPathComponent().standardizedFileURL.path
if let lock = Self.crossProcessLocks[directory] { return lock }
let lock = ProfileStoreCrossProcessLock(
directory: URL(fileURLWithPath: directory, isDirectory: true))
Self.crossProcessLocks[directory] = lock
return lock
}


Expand Down Expand Up @@ -98,7 +125,7 @@ final class ProfileStore {
@discardableResult
func updateIfPresent(id: String, when condition: (Profile) -> Bool = { _ in true },
_ change: (inout Profile) throws -> Void) throws -> Profile? {
try Self.withWriteLock {
try withWriteLock {
var profiles = load()
guard let index = profiles.firstIndex(where: { $0.id == id }), condition(profiles[index]) else {
return nil
Expand All @@ -111,6 +138,9 @@ final class ProfileStore {



// In-process only. Code that reads and then saves the whole list needs the
// instance variant, which holds the cross-process lock for the whole
// read-modify-write.
static func withWriteLock<T>(_ body: () throws -> T) rethrows -> T {
writeLock.lock()
lockDepth += 1
Expand All @@ -131,7 +161,7 @@ final class ProfileStore {
static let didChangeNotification = Notification.Name("ClashProfileStoreDidChange")

func upsert(_ profile: Profile) throws {
try Self.withWriteLock {
try withWriteLock {
var profiles = load()
if let idx = profiles.firstIndex(where: { $0.id == profile.id }) {
profiles[idx] = profile
Expand All @@ -143,7 +173,7 @@ final class ProfileStore {
}

func remove(id: String) throws {
try Self.withWriteLock { try write(load().filter { $0.id != id }) }
try withWriteLock { try write(load().filter { $0.id != id }) }
}


Expand All @@ -153,7 +183,7 @@ final class ProfileStore {

@discardableResult
func updateAll(_ change: (inout [Profile]) throws -> Void) throws -> Bool {
try Self.withWriteLock {
try withWriteLock {
var profiles = load()
let before = profiles
try change(&profiles)
Expand All @@ -167,7 +197,7 @@ final class ProfileStore {

@discardableResult
func insertIfAbsent(_ profile: Profile) throws -> Bool {
try Self.withWriteLock {
try withWriteLock {
var profiles = load()
guard !profiles.contains(where: { $0.id == profile.id }) else { return false }
profiles.append(profile)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import Foundation

/// The lock every writer of `profiles.json` takes, in this process and in the
/// others: the App, the tunnel extension's app-store endpoints and `clash-cli`
/// all flock `<store>/profiles.lock` around a read-modify-write, so a save can
/// never drop an edit made by another process in the meantime.
///
/// The file is the same one the kernel takes (`app_store_route.go`); the
/// protocol is "flock the lock file, re-read `profiles.json`, write a new file
/// and rename it over the old one". Locking the lock file rather than the
/// store itself keeps the lock valid across the rename.
final class ProfileStoreCrossProcessLock {
enum Failure: LocalizedError, Equatable {
case unavailable(Int32)
case timedOut

var errorDescription: String? {
switch self {
case .unavailable:
return "The profile list's lock file could not be opened, so the change was not saved."
case .timedOut:
return "Another process is still editing the profile list, so the change was not saved. Try again."
}
}
}

private static let retryInterval: useconds_t = 20_000

private let fileURL: URL
private var descriptor: Int32 = -1
private var depth = 0

init(directory: URL) {
fileURL = directory.appendingPathComponent("profiles.lock")
}

/// Reentrant. A nested call deepens the hold instead of opening a second
/// descriptor, which flock would block on against its own holder.
func lock(waitingUpTo timeout: TimeInterval = 5) throws {
if depth > 0 {
depth += 1
return
}
let descriptor = open(fileURL.path, O_CREAT | O_RDWR | O_CLOEXEC, 0o600)
guard descriptor >= 0 else { throw Failure.unavailable(errno) }
let deadline = Date().addingTimeInterval(timeout)
while flock(descriptor, LOCK_EX | LOCK_NB) != 0 {
let code = errno
guard code == EWOULDBLOCK || code == EAGAIN else {
close(descriptor)
throw Failure.unavailable(code)
}
guard Date() < deadline else {
close(descriptor)
throw Failure.timedOut
}
usleep(Self.retryInterval)
}
self.descriptor = descriptor
depth = 1
}

func unlock() {
guard depth > 0 else { return }
depth -= 1
guard depth == 0, descriptor >= 0 else { return }
_ = flock(descriptor, LOCK_UN)
close(descriptor)
descriptor = -1
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import Foundation

extension Notification.Name {
/// Posted when the profile store directory changed on disk. Writes from
/// this process post it too; observers compare the re-read store with what
/// they already have before doing anything.
static let clashProfileStoreDirectoryDidChange =
Notification.Name("ClashProfileStoreDirectoryDidChange")
}

/// Watches a profile store directory so the App notices writes made outside
/// this process: `clash-cli`, or the tunnel extension's app-store endpoints.
@MainActor
final class ProfileStoreDirectoryWatcher {
static let shared = ProfileStoreDirectoryWatcher()

private struct Watched {
let source: DispatchSourceFileSystemObject
}

private var watched: [String: Watched] = [:]
private var retries: [String: DispatchWorkItem] = [:]

func watch(directory: URL?) {
guard let directory else { return }
let path = directory.standardizedFileURL.path
guard watched[path] == nil, retries[path] == nil else { return }
start(path: path)
}

private func start(path: String) {
let descriptor = open(path, O_EVTONLY)
guard descriptor >= 0 else {
// The store directory is created on the first save; try again a
// little later instead of watching nothing for the whole session.
retry(path: path)
return
}
let source = DispatchSource.makeFileSystemObjectSource(
fileDescriptor: descriptor,
eventMask: [.write, .rename, .delete],
queue: .main
)
source.setEventHandler { [weak self, weak source] in
guard let self, let source else { return }
if source.data.contains(.delete) || source.data.contains(.rename) {
// The directory itself moved or vanished: re-open it later.
self.restart(path: path)
} else {
NotificationCenter.default.post(
name: .clashProfileStoreDirectoryDidChange, object: nil)
}
}
source.setCancelHandler { close(descriptor) }
source.resume()
watched[path] = Watched(source: source)
}

private func restart(path: String) {
watched.removeValue(forKey: path)?.source.cancel()
retry(path: path)
}

private func retry(path: String) {
guard retries[path] == nil else { return }
let work = DispatchWorkItem { [weak self] in
self?.retries[path] = nil
self?.start(path: path)
}
retries[path] = work
DispatchQueue.main.asyncAfter(deadline: .now() + 2, execute: work)
}
}
Loading