-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathExt4ExtensionFileSystem.swift
More file actions
335 lines (299 loc) · 15.3 KB
/
Copy pathExt4ExtensionFileSystem.swift
File metadata and controls
335 lines (299 loc) · 15.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
// This file is part of ExtendFS which is released under the GNU GPL v3 or later license with an app store exception.
// See the LICENSE file in the root of the repository for full license details.
import Foundation
import FSKit
import UserNotifications
@objc
final class Ext4ExtensionFileSystem: FSUnaryFileSystem & FSUnaryFileSystemOperations {
static let logger = Logger(subsystem: "com.kpchew.ExtendFS.ext4Extension", category: "Ext4Extension")
@MainActor weak var resource: FSBlockDeviceResource?
@MainActor weak var volume: Ext4Volume?
@MainActor func setResources(resource: FSBlockDeviceResource?, volume: Ext4Volume?) {
self.resource = resource
self.volume = volume
}
@MainActor func setContainerStatus(_ status: FSContainerStatus) {
self.containerStatus = status
}
func sendNotification(title: String, body: String, interruptionLevel: UNNotificationInterruptionLevel = .active) {
// TODO: not in release build for now until user-accessible settings are available for this
#if DEBUG
Task.detached {
let content = UNMutableNotificationContent()
content.title = title
content.body = body
content.interruptionLevel = interruptionLevel
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: nil)
let notificationCenter = UNUserNotificationCenter.current()
do {
try await notificationCenter.requestAuthorization(options: [.alert])
try await notificationCenter.add(request)
} catch {
Self.logger.error("Couldn't send notification: \(error)")
}
}
#endif
}
func probeResource(resource: FSResource) async throws -> FSProbeResult {
Self.logger.log("Probing resource")
guard let resource = resource as? FSBlockDeviceResource else {
Self.logger.log("Not block device")
return .notRecognized
}
guard let superblock = try Superblock(blockDevice: resource, offset: 1024) else {
Self.logger.error("Could not read superblock from resource")
var data = Data(count: 1024)
let readCount = try data.withUnsafeMutableBytes { buffer in
return try resource.read(into: buffer, startingAt: 0, length: 1024)
}
let potentialLuksSignature = String(data: data.subdata(in: 0..<4), encoding: .ascii)
let potentialLVMSignature = String(data: data.subdata(in: 536..<544), encoding: .ascii)
if readCount >= 6 && potentialLuksSignature == "LUKS" && data[4] == 0xBA && data[5] == 0xBE {
Self.logger.error("Disk can't be mounted - LUKS")
sendNotification(title: "Unsupported Disk", body: "Disk \(resource.bsdName) can't be mounted because it is encrypted with LUKS, which is currently unsupported.")
} else if readCount >= 1024 && potentialLVMSignature == "LVM2 001" {
Self.logger.error("Disk can't be mounted - LVM")
sendNotification(title: "Unsupported Disk", body: "Disk \(resource.bsdName) can't be mounted because it uses LVM, which is currently unsupported.")
} else {
Self.logger.error("Disk can't be mounted - not ext2/3/4")
}
return .notRecognized
}
if superblock.magic == 0xEF53 {
let name = String(data: superblock.volumeName ?? Data(), encoding: .utf8) ?? ""
let uuid = superblock.uuid ?? UUID()
// seems like recognized and usableButLimited are treated like notRecognized as of macOS 15.6 (24G84)
guard superblock.incompatibleFeatures.isSubset(of: Superblock.IncompatibleFeatures.supportedFeatures) else {
Self.logger.log("Recognized but not usable")
Self.logger.error("Disk can't be mounted - incompatible features")
sendNotification(title: "Unsupported Disk", body: "Disk \"\(name)\" was recognized as an ext2/3/4 volume, but can't be mounted because it uses incompatible features.")
return .recognized(name: name, containerID: FSContainerIdentifier(uuid: uuid))
}
// FIXME: once FB19241327 is fixed, uncomment these and apply them to the fixed OS version
// if #available(macOS 26.4, *) {
// let incompatibleFeaturesForcingReadOnly: Superblock.IncompatibleFeatures = [.needsRecovery, .separateJournalDevice, .multipleMountProtection]
// guard superblock.incompatibleFeatures.isDisjoint(with: incompatibleFeaturesForcingReadOnly) else {
// Self.logger.log("Usable but limited")
// return .usableButLimited(name: name, containerID: FSContainerIdentifier(uuid: uuid))
// }
// guard superblock.readOnlyCompatibleFeatures.isSubset(of: Superblock.ReadOnlyCompatibleFeatures.supportedFeatures) else {
// Self.logger.log("Usable but limited")
// return .usableButLimited(name: name, containerID: FSContainerIdentifier(uuid: uuid))
// }
// }
if superblock.state.contains(.errorsDetected) {
Self.logger.log("Errors detected on volume.")
let errorPolicy = superblock.errorPolicy
switch errorPolicy {
case .continue:
Self.logger.log("Error policy set to continue, continuing as normal.")
break
case .remountReadOnly:
Self.logger.log("Error policy set to remount as read-only, indicating usable but limited.")
// if #available(macOS 26.4, *) {
// return .usableButLimited(name: name, containerID: FSContainerIdentifier(uuid: uuid))
// } else {
// return .usable(name: name, containerID: FSContainerIdentifier(uuid: uuid))
// }
return .usable(name: name, containerID: FSContainerIdentifier(uuid: uuid))
case .panic:
Self.logger.error("Error policy set to panic, indicating recognized but not usable.")
sendNotification(title: "Unsupported Disk", body: "Disk \"\(name)\" can't be mounted because it contains errors and the error policy is set to panic.")
return .recognized(name: name, containerID: FSContainerIdentifier(uuid: uuid))
case .unknown:
Self.logger.error("Error policy is not recognized.")
sendNotification(title: "Unsupported Disk", body: "Disk \"\(name)\" can't be mounted because the error policy is unknown.")
return .recognized(name: name, containerID: FSContainerIdentifier(uuid: uuid))
}
}
return .usable(name: name, containerID: FSContainerIdentifier(uuid: uuid))
} else {
Self.logger.error("Disk can't be mounted - invalid superblock magic")
sendNotification(title: "Unsupported Disk", body: "Disk \(resource.bsdName) is not a valid ext2/3/4 volume.")
return .notRecognized
}
}
func loadResource(resource: FSResource, options: FSTaskOptions) async throws -> FSVolume {
// FIXME: do I need to check probe result here?
Self.logger.log("Loading resource")
let probeResult = try await probeResource(resource: resource)
var readOnly: Bool
switch probeResult.result {
case .notRecognized:
Self.logger.log("Invalid resource")
await setContainerStatus(.blocked(status: FSError(.resourceUnrecognized)))
throw FSError(.resourceUnrecognized)
case .recognized:
Self.logger.log("Recognized but can't mount")
await setContainerStatus(.blocked(status: FSError(.resourceUnusable)))
throw FSError(.resourceUnusable)
case .usableButLimited:
readOnly = true
case .usable:
readOnly = true // write not supported atm
@unknown default:
Self.logger.log("Unknown probe result")
await setContainerStatus(.blocked(status: FSError(.resourceUnrecognized)))
throw FSError(.resourceUnrecognized)
}
guard let resource = resource as? FSBlockDeviceResource else {
Self.logger.log("Not a block resource")
await setContainerStatus(.blocked(status: FSError(.resourceUnrecognized)))
throw FSError(.resourceUnrecognized)
}
Self.logger.log("load options: \(options.taskOptions, privacy: .public)")
for option in options.taskOptions {
switch option {
case "-f":
continue
case "--rdonly":
Self.logger.log("Read only option provided")
readOnly = true
default:
continue
}
}
let volume = try await Ext4Volume(resource: resource, fileSystem: self, readOnly: readOnly)
await setResources(resource: resource, volume: volume)
await setContainerStatus(.ready)
Self.logger.log("Container status ready")
BlockDeviceReader.useMetadataRead = true
return volume
}
func unloadResource(resource: FSResource, options: FSTaskOptions) async throws {
Self.logger.log("Unloading resource")
await setResources(resource: nil, volume: nil)
await setContainerStatus(.notReady(status: POSIXError(.EAGAIN)))
return
}
func didFinishLoading() {
Self.logger.log("did finish loading")
}
}
extension Ext4ExtensionFileSystem: FSManageableResourceMaintenanceOperations {
@MainActor private static func quickCheck(volume: Ext4Volume, task: FSTask) throws {
let superblock = volume.superblock
guard superblock.magic == 0xEF53 else {
task.logMessage("Magic value in superblock did not match expectation. Is this an ext volume?")
throw POSIXError(.EDEVERR)
}
if superblock.incompatibleFeatures.contains(.needsRecovery) {
Self.logger.error("Recovery feature present on disk.")
throw POSIXError(.EDEVERR)
}
if superblock.state.contains(.errorsDetected) {
switch superblock.errorPolicy {
case .continue:
break
case .remountReadOnly:
break
case .panic:
Self.logger.error("Errors detected on disk, and error policy is to panic.")
throw POSIXError(.EDEVERR)
case .unknown:
Self.logger.error("Errors detected on disk, and error policy is unknown.")
throw POSIXError(.EDEVERR)
}
}
if superblock.readOnlyCompatibleFeatures.contains(.supportsMetadataChecksumming) {
let calculatedChecksum = try superblock.calculateChecksum()
guard let storedChecksum = superblock.checksum, storedChecksum == calculatedChecksum else {
Self.logger.error("Checksum found on superblock does not match expected value.")
throw POSIXError(.EDEVERR)
}
}
}
/// Makes a "shadow file" of the provided volume.
///
/// A shadow file contains the metadata for the volume, but excludes file data. It is intended to be included in bug reports for hard-to-debug issues.
/// - Parameters:
/// - destination: The directory at which the shadow file should be created.
/// - volume: The volume to create a shadow file of.
/// - task: The task associated with the check operation that initiated this request.
private static func makeShadowFile(at destination: URL, volume: Ext4Volume, task: FSTask) async throws {
#if DEBUG
let name = "shadow-\(volume.resource.bsdName)"
let shadowURL = destination.appendingPathComponent(name)
FileManager.default.createFile(atPath: shadowURL.path(percentEncoded: false), contents: nil)
// TODO: implement once url options are fixed
#else
task.logMessage("Shadow file requested, but this function is not implemented yet. Ignoring.")
#endif
}
/// A type of check that can be performed.
enum CheckType {
/// A quick, surface-level check.
case quick
/// A more complete check.
///
/// Not currently supported.
case full
}
func startCheck(task: FSTask, options: FSTaskOptions) throws -> Progress {
let yes = options.taskOptions.contains("-y")
let makeShadow = options.taskOptions.contains("-S")
var checkType: CheckType = .full
for option in options.taskOptions {
switch option {
case "-q":
checkType = .quick
break
default:
continue
}
}
if yes {
task.logMessage("-y option provided, but ExtendFS is read-only. Ignoring option.")
}
if checkType == .full {
task.logMessage("Full check requested, but ExtendFS only supports simple quick checks. A quick check will be run.")
checkType = .quick
}
let progress = Progress(totalUnitCount: 100)
Task {
await setContainerStatus(.active)
guard let volume = await volume else {
await setContainerStatus(.notReady(status: FSError(.resourceDamaged)))
task.didComplete(error: FSError(.resourceDamaged))
return
}
defer {
progress.completedUnitCount = 100
}
if makeShadow {
if let destination = options.url(forOption: "S"), destination.startAccessingSecurityScopedResource() {
defer {
destination.stopAccessingSecurityScopedResource()
}
try await Self.makeShadowFile(at: destination, volume: volume, task: task)
} else {
task.logMessage("No valid directory provided to -S option. Shadow file not being created.")
}
}
switch checkType {
case .quick:
do {
try await Self.quickCheck(volume: volume, task: task)
await setContainerStatus(.ready)
task.didComplete(error: nil)
} catch {
await setContainerStatus(.notReady(status: FSError(.resourceDamaged)))
task.didComplete(error: error)
}
case .full:
do {
try await Self.quickCheck(volume: volume, task: task)
await setContainerStatus(.ready)
task.didComplete(error: nil)
} catch {
await setContainerStatus(.notReady(status: FSError(.resourceDamaged)))
task.didComplete(error: error)
}
}
}
return progress
}
func startFormat(task: FSTask, options: FSTaskOptions) throws -> Progress {
throw POSIXError(.ENOSYS)
}
}