-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
Copy pathDeviceTransferService+Manifest.swift
280 lines (228 loc) · 11.5 KB
/
DeviceTransferService+Manifest.swift
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
//
// Copyright 2020 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
//
import MultipeerConnectivity
import SignalServiceKit
extension DeviceTransferService {
func buildManifest() throws -> DeviceTransferProtoManifest {
var manifestBuilder = DeviceTransferProtoManifest.builder(grdbSchemaVersion: UInt64(GRDBSchemaMigrator.grdbSchemaVersionLatest))
var estimatedTotalSize: UInt64 = 0
// Database
do {
let database: DeviceTransferProtoFile = try {
let file = SSKEnvironment.shared.databaseStorageRef.grdbStorage.databaseFilePath
guard let size = OWSFileSystem.fileSize(ofPath: file), size.uint64Value > 0 else {
throw OWSAssertionError("Failed to calculate size of database \(file)")
}
estimatedTotalSize += size.uint64Value
let fileBuilder = DeviceTransferProtoFile.builder(
identifier: DeviceTransferService.databaseIdentifier,
relativePath: try pathRelativeToAppSharedDirectory(file),
estimatedSize: size.uint64Value
)
return fileBuilder.buildInfallibly()
}()
let wal: DeviceTransferProtoFile = try {
let file = SSKEnvironment.shared.databaseStorageRef.grdbStorage.databaseWALFilePath
guard let size = OWSFileSystem.fileSize(ofPath: file), size.uint64Value > 0 else {
throw OWSAssertionError("Failed to calculate size of database wal \(file)")
}
estimatedTotalSize += size.uint64Value
let fileBuilder = DeviceTransferProtoFile.builder(
identifier: DeviceTransferService.databaseWALIdentifier,
relativePath: try pathRelativeToAppSharedDirectory(file),
estimatedSize: size.uint64Value
)
return fileBuilder.buildInfallibly()
}()
let databaseBuilder = DeviceTransferProtoDatabase.builder(
key: try SSKEnvironment.shared.databaseStorageRef.keyFetcher.fetchData(),
database: database,
wal: wal
)
manifestBuilder.setDatabase(databaseBuilder.buildInfallibly())
}
// Attachments, Avatars, and Stickers
// TODO: Ideally, these paths would reference constants...
let foldersToTransfer = ["Attachments/", "ProfileAvatars/", "GroupAvatars/", "StickerManager/", "Wallpapers/", "Library/Sounds/", "AvatarHistory/", "attachment_files/"]
let filesToTransfer = try foldersToTransfer.flatMap { folder -> [String] in
let url = URL(fileURLWithPath: folder, relativeTo: DeviceTransferService.appSharedDataDirectory)
return try OWSFileSystem.recursiveFilesInDirectory(url.path)
}
for file in filesToTransfer {
guard let size = OWSFileSystem.fileSize(ofPath: file) else {
throw OWSAssertionError("Failed to calculate size of file \(file)")
}
guard size.uint64Value > 0 else {
owsFailDebug("skipping empty file \(file)")
continue
}
estimatedTotalSize += size.uint64Value
let fileBuilder = DeviceTransferProtoFile.builder(
identifier: UUID().uuidString,
relativePath: try pathRelativeToAppSharedDirectory(file),
estimatedSize: size.uint64Value
)
manifestBuilder.addFiles(fileBuilder.buildInfallibly())
}
// Standard Defaults
func isAppleKey(_ key: String) -> Bool {
return key.starts(with: "NS") || key.starts(with: "Apple")
}
do {
for (key, value) in UserDefaults.standard.dictionaryRepresentation() {
// Filter out any keys we think are managed by Apple, we don't need to transfer them.
guard !isAppleKey(key) else { continue }
guard let encodedValue = try? NSKeyedArchiver.archivedData(withRootObject: value, requiringSecureCoding: true) else { continue }
let defaultBuilder = DeviceTransferProtoDefault.builder(
key: key,
encodedValue: encodedValue
)
manifestBuilder.addStandardDefaults(defaultBuilder.buildInfallibly())
}
}
// App Defaults
do {
for (key, value) in CurrentAppContext().appUserDefaults().dictionaryRepresentation() {
// Filter out any keys we think are managed by Apple, we don't need to transfer them.
guard !isAppleKey(key) else { continue }
guard let encodedValue = try? NSKeyedArchiver.archivedData(withRootObject: value, requiringSecureCoding: true) else { continue }
let defaultBuilder = DeviceTransferProtoDefault.builder(
key: key,
encodedValue: encodedValue
)
manifestBuilder.addAppDefaults(defaultBuilder.buildInfallibly())
}
}
manifestBuilder.setEstimatedTotalSize(estimatedTotalSize)
return manifestBuilder.buildInfallibly()
}
func pathRelativeToAppSharedDirectory(_ path: String) throws -> String {
guard !path.contains("*") else {
throw OWSAssertionError("path contains invalid character: *")
}
let components = path.components(separatedBy: "/")
guard components.first != "~" else {
throw OWSAssertionError("path starts with invalid component: ~")
}
for component in components {
guard component != "." else {
throw OWSAssertionError("path contains invalid component: .")
}
guard component != ".." else {
throw OWSAssertionError("path contains invalid component: ..")
}
}
var path = path.replacingOccurrences(of: DeviceTransferService.appSharedDataDirectory.path, with: "")
if path.starts(with: "/") { path.removeFirst() }
return path
}
func handleReceivedManifest(at localURL: URL, fromPeer peerId: MCPeerID) {
guard case .idle = transferState else {
stopTransfer()
return owsFailDebug("Received manifest in unexpected state \(transferState)")
}
guard let fileSize = OWSFileSystem.fileSize(of: localURL) else {
stopTransfer()
return owsFailDebug("Missing manifest file.")
}
// Not sure why this limit exists in the first place, but 1Gb should be
// plenty high for file descriptors.
guard fileSize.uint64Value < 1024 * 1024 * 1024 else {
stopTransfer()
return owsFailDebug("Unexpectedly received a very large manifest \(fileSize)")
}
guard let data = try? Data(contentsOf: localURL) else {
stopTransfer()
return owsFailDebug("Failed to read manifest data")
}
guard let manifest = try? DeviceTransferProtoManifest(serializedData: data) else {
stopTransfer()
return owsFailDebug("Failed to parse manifest proto")
}
guard !DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isRegistered else {
stopTransfer()
return owsFailDebug("Ignoring incoming transfer to a registered device")
}
resetTransferDirectory(createNewTransferDirectory: true)
do {
try OWSFileSystem.moveFilePath(
localURL.path,
toFilePath: URL(
fileURLWithPath: DeviceTransferService.manifestIdentifier,
relativeTo: DeviceTransferService.pendingTransferDirectory
).path
)
} catch {
owsFailDebug("Failed to move manifest into place: \(error.shortDescription)")
return
}
let progress = Progress(totalUnitCount: Int64(manifest.estimatedTotalSize))
transferState = .incoming(
oldDevicePeerId: peerId,
manifest: manifest,
receivedFileIds: [DeviceTransferService.manifestIdentifier],
skippedFileIds: [],
progress: progress
)
DependenciesBridge.shared.db.write { tx in
DependenciesBridge.shared.registrationStateChangeManager.setIsTransferInProgress(tx: tx)
}
notifyObservers { $0.deviceTransferServiceDidStartTransfer(progress: progress) }
startThroughputCalculation()
// Check if the device has a newer version of the database than we understand
guard manifest.grdbSchemaVersion <= GRDBSchemaMigrator.grdbSchemaVersionLatest else {
return self.failTransfer(.unsupportedVersion, "Ignoring manifest with unsupported schema version")
}
// Check if there is enough space on disk to receive the transfer
guard let freeSpaceInBytes = try? OWSFileSystem.freeSpaceInBytes(
forPath: DeviceTransferService.pendingTransferDirectory
) else {
return self.failTransfer(.assertion, "failed to calculate available disk space")
}
guard freeSpaceInBytes > manifest.estimatedTotalSize else {
return self.failTransfer(.notEnoughSpace, "not enough free space to receive transfer")
}
}
func sendManifest() throws -> Promise<Void> {
Logger.info("Sending manifest to new device.")
guard case .outgoing(let newDevicePeerId, _, let manifest, _, _) = transferState else {
throw OWSAssertionError("attempted to send manifest while no active outgoing transfer")
}
guard let session = session else {
throw OWSAssertionError("attempted to send manifest without an available session")
}
resetTransferDirectory(createNewTransferDirectory: true)
// We write the manifest to a temp file, since MCSession only allows sending "typed"
// data when sending files, unless you do your own stream management.
let manifestData = try manifest.serializedData()
let manifestFileURL = URL(
fileURLWithPath: DeviceTransferService.manifestIdentifier,
relativeTo: DeviceTransferService.pendingTransferDirectory
)
try manifestData.write(to: manifestFileURL, options: .atomic)
let (promise, future) = Promise<Void>.pending()
session.sendResource(at: manifestFileURL, withName: DeviceTransferService.manifestIdentifier, toPeer: newDevicePeerId) { error in
if let error = error {
future.reject(error)
} else {
future.resolve()
Logger.info("Successfully sent manifest to new device.")
self.transferState = self.transferState.appendingFileId(DeviceTransferService.manifestIdentifier)
self.startThroughputCalculation()
}
OWSFileSystem.deleteFileIfExists(manifestFileURL.path)
}
return promise
}
func readManifestFromTransferDirectory() -> DeviceTransferProtoManifest? {
let manifestPath = URL(
fileURLWithPath: DeviceTransferService.manifestIdentifier,
relativeTo: DeviceTransferService.pendingTransferDirectory
).path
guard OWSFileSystem.fileOrFolderExists(atPath: manifestPath) else { return nil }
guard let manifestData = try? Data(contentsOf: URL(fileURLWithPath: manifestPath)) else { return nil }
return try? DeviceTransferProtoManifest(serializedData: manifestData)
}
}