capacitor-background-transfer 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/CapacitorBackgroundTransfer.podspec +19 -0
  2. package/LICENSE +21 -0
  3. package/Package.swift +31 -0
  4. package/README.md +552 -2
  5. package/android/build.gradle +71 -0
  6. package/android/src/main/AndroidManifest.xml +20 -0
  7. package/android/src/main/java/io/github/sandman92/backgroundtransfer/AzureBlockUploader.java +148 -0
  8. package/android/src/main/java/io/github/sandman92/backgroundtransfer/BackgroundTransferPlugin.java +279 -0
  9. package/android/src/main/java/io/github/sandman92/backgroundtransfer/Downloader.java +244 -0
  10. package/android/src/main/java/io/github/sandman92/backgroundtransfer/Http.java +238 -0
  11. package/android/src/main/java/io/github/sandman92/backgroundtransfer/JobRuns.java +40 -0
  12. package/android/src/main/java/io/github/sandman92/backgroundtransfer/Notifications.java +54 -0
  13. package/android/src/main/java/io/github/sandman92/backgroundtransfer/Parts.java +25 -0
  14. package/android/src/main/java/io/github/sandman92/backgroundtransfer/PartsXml.java +199 -0
  15. package/android/src/main/java/io/github/sandman92/backgroundtransfer/Pause.java +28 -0
  16. package/android/src/main/java/io/github/sandman92/backgroundtransfer/Progress.java +13 -0
  17. package/android/src/main/java/io/github/sandman92/backgroundtransfer/PutUploader.java +47 -0
  18. package/android/src/main/java/io/github/sandman92/backgroundtransfer/Runner.java +369 -0
  19. package/android/src/main/java/io/github/sandman92/backgroundtransfer/S3MultipartUploader.java +143 -0
  20. package/android/src/main/java/io/github/sandman92/backgroundtransfer/Scheduler.java +144 -0
  21. package/android/src/main/java/io/github/sandman92/backgroundtransfer/TransferException.java +65 -0
  22. package/android/src/main/java/io/github/sandman92/backgroundtransfer/TransferJobService.java +115 -0
  23. package/android/src/main/java/io/github/sandman92/backgroundtransfer/TransferPaths.java +129 -0
  24. package/android/src/main/java/io/github/sandman92/backgroundtransfer/TransferRecord.java +163 -0
  25. package/android/src/main/java/io/github/sandman92/backgroundtransfer/TransferStore.java +121 -0
  26. package/android/src/main/java/io/github/sandman92/backgroundtransfer/TransferWorker.java +85 -0
  27. package/android/src/main/java/io/github/sandman92/backgroundtransfer/UploadAdapter.java +11 -0
  28. package/android/src/main/java/io/github/sandman92/backgroundtransfer/UploadAdapters.java +89 -0
  29. package/android/src/main/java/io/github/sandman92/backgroundtransfer/UploadOptionsCheck.java +104 -0
  30. package/android/src/main/java/io/github/sandman92/backgroundtransfer/Uploader.java +225 -0
  31. package/android/src/main/res/.gitkeep +0 -0
  32. package/dist/docs.json +527 -0
  33. package/dist/esm/definitions.d.ts +277 -0
  34. package/dist/esm/definitions.js +24 -0
  35. package/dist/esm/definitions.js.map +1 -0
  36. package/dist/esm/index.d.ts +10 -0
  37. package/dist/esm/index.js +26 -0
  38. package/dist/esm/index.js.map +1 -0
  39. package/dist/esm/validate.d.ts +18 -0
  40. package/dist/esm/validate.js +113 -0
  41. package/dist/esm/validate.js.map +1 -0
  42. package/dist/esm/web.d.ts +17 -0
  43. package/dist/esm/web.js +27 -0
  44. package/dist/esm/web.js.map +1 -0
  45. package/dist/plugin.cjs.js +200 -0
  46. package/dist/plugin.cjs.js.map +1 -0
  47. package/dist/plugin.js +203 -0
  48. package/dist/plugin.js.map +1 -0
  49. package/ios/Sources/BackgroundTransferCore/Files.swift +166 -0
  50. package/ios/Sources/BackgroundTransferCore/PartsUpload.swift +327 -0
  51. package/ios/Sources/BackgroundTransferCore/PartsXML.swift +137 -0
  52. package/ios/Sources/BackgroundTransferCore/TransferPaths.swift +103 -0
  53. package/ios/Sources/BackgroundTransferCore/TransferRecord.swift +141 -0
  54. package/ios/Sources/BackgroundTransferCore/TransferStore.swift +69 -0
  55. package/ios/Sources/BackgroundTransferCore/UploadOptionsCheck.swift +90 -0
  56. package/ios/Sources/BackgroundTransferCore/UploadOutcome.swift +96 -0
  57. package/ios/Sources/BackgroundTransferCore/UploadProtocol.swift +30 -0
  58. package/ios/Sources/BackgroundTransferPlugin/BackgroundTransferPlugin.swift +168 -0
  59. package/ios/Sources/BackgroundTransferPlugin/TransferManager.swift +1074 -0
  60. package/package.json +97 -4
@@ -0,0 +1,327 @@
1
+ import Foundation
2
+
3
+ /// The steps of a `put` and of an upload in parts (`s3-multipart`, `azure-blocks`), as functions of
4
+ /// the record: which request comes next, and what each answer means. `TransferManager` hands each
5
+ /// request to the background session; the tests drive the same steps against real servers.
6
+ public enum PartsUpload {
7
+ public enum Step: Equatable {
8
+ case part(n: Int, offset: Int64, length: Int64)
9
+ case commit
10
+ }
11
+
12
+ // MARK: put
13
+
14
+ public static func putRequest(_ r: TransferRecord) -> URLRequest? {
15
+ guard let url = URL(string: r.url) else { return nil }
16
+ var request = URLRequest(url: url)
17
+ request.httpMethod = "PUT"
18
+ request.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type")
19
+ for (k, v) in r.headers { request.setValue(v, forHTTPHeaderField: k) }
20
+ return request
21
+ }
22
+
23
+ /// Finished on any 2xx: the server took the whole body.
24
+ public static func afterPut(status: Int) -> UploadOutcome {
25
+ if (200...299).contains(status) { return .finished }
26
+ return refusal(status, "PUT")
27
+ }
28
+
29
+ // MARK: Parts
30
+
31
+ public static func partSize(_ r: TransferRecord) -> Int64 {
32
+ let size = r.protocol == UploadProtocol.azureBlocks.rawValue ? r.blockSize : r.partSize
33
+ return (size ?? 0) > 0 ? size! : UploadOptionsCheck.defaultPartSize
34
+ }
35
+
36
+ public static func count(_ r: TransferRecord, size: Int64) -> Int {
37
+ PartPlan.count(size: size, partSize: partSize(r), atLeastOne: r.protocol == UploadProtocol.s3Multipart.rawValue)
38
+ }
39
+
40
+ private static func isAzure(_ r: TransferRecord) -> Bool { r.protocol == UploadProtocol.azureBlocks.rawValue }
41
+
42
+ /// Before anything is sent: a commit handed over in an earlier run is never taken as done, and
43
+ /// the file must still fit the parts.
44
+ public static func beforeStart(_ r: TransferRecord, size: Int64) -> UploadOutcome? {
45
+ if r.committing == true {
46
+ let what = isAzure(r) ? "the block list" : "the completion"
47
+ return .failed(reason: Reason.sessionClosed,
48
+ message: "\(what) was sent earlier and its answer never came: check the object before starting a new upload")
49
+ }
50
+ let p = UploadProtocol.resolve(r.protocol) ?? .s3Multipart
51
+ if let bad = UploadOptionsCheck.checkSize(protocol: p, partUrlCount: r.partUrls?.count ?? 0, partSize: partSize(r),
52
+ blockSize: partSize(r), fileSize: size) {
53
+ return .failed(reason: Reason.sizeMismatch, message: bad)
54
+ }
55
+ return nil
56
+ }
57
+
58
+ /// The request asking the server what it holds: ListParts (when its URL was given) or Get Block List.
59
+ public static func probe(_ r: TransferRecord) -> URLRequest? {
60
+ let target: String?
61
+ if isAzure(r) {
62
+ target = withQuery(r.url, "comp=blocklist&blocklisttype=uncommitted")
63
+ } else {
64
+ target = r.listPartsUrl
65
+ }
66
+ guard let t = target, let url = URL(string: t) else { return nil }
67
+ var request = URLRequest(url: url)
68
+ request.httpMethod = "GET"
69
+ for (k, v) in r.headers { request.setValue(v, forHTTPHeaderField: k) }
70
+ return request
71
+ }
72
+
73
+ /// Applies the probe's answer to `r.parts` (`status` nil: no answer). Non-nil stops the upload.
74
+ public static func afterProbe(_ r: inout TransferRecord, status: Int?, body: Data?, size: Int64) -> UploadOutcome? {
75
+ let what = isAzure(r) ? "Get Block List" : "ListParts"
76
+ guard let status = status else { return .interrupted(reason: Reason.network, message: "\(what): no answer") }
77
+ let n = count(r, size: size)
78
+ let plan = partSize(r)
79
+ var parts = r.parts ?? [:]
80
+ if isAzure(r) {
81
+ let ids = PartsXML.blockIds(transferId: r.id, size: size, blockSize: plan, count: n)
82
+ switch status {
83
+ case 200:
84
+ guard let held = PartsXML.uncommittedBlocks(body ?? Data()) else {
85
+ return .failed(reason: Reason.unknown, message: "\(what) answered with XML that couldn't be read")
86
+ }
87
+ parts = [:]
88
+ for i in stride(from: 1, through: n, by: 1) where held[ids[i - 1]] == PartPlan.length(i, size: size, partSize: plan) {
89
+ parts[String(i)] = ids[i - 1]
90
+ }
91
+ case 404:
92
+ // No blob and no blocks yet (or they expired): everything goes.
93
+ parts = [:]
94
+ case 403:
95
+ // The SAS can't read the list (no `r`): trust the record. An expired SAS fails on the first block.
96
+ break
97
+ default:
98
+ return refusal(status, what)
99
+ }
100
+ parts = parts.filter { k, v in Int(k).map { $0 >= 1 && $0 <= n && ids[$0 - 1] == v } ?? false }
101
+ } else {
102
+ guard status == 200 else { return refusal(status, what) }
103
+ guard let listed = PartsXML.listParts(body ?? Data()) else {
104
+ return .failed(reason: Reason.unknown, message: "\(what) answered with XML that couldn't be read")
105
+ }
106
+ var kept: [String: String] = [:]
107
+ for i in stride(from: 1, through: n, by: 1) {
108
+ if let held = listed.parts[i] {
109
+ if held.size == PartPlan.length(i, size: size, partSize: plan) { kept[String(i)] = held.tag }
110
+ } else if listed.truncated && i > listed.highest, let mine = parts[String(i)] {
111
+ kept[String(i)] = mine
112
+ }
113
+ }
114
+ parts = kept
115
+ }
116
+ r.parts = parts
117
+ return nil
118
+ }
119
+
120
+ /// The first part neither stored nor in a task's hands; the commit once every part is stored;
121
+ /// nil while the last parts are still in tasks.
122
+ public static func next(_ r: TransferRecord, size: Int64) -> Step? {
123
+ if let first = pending(r, size: size).first { return first }
124
+ return inFlight(r).isEmpty ? .commit : nil
125
+ }
126
+
127
+ /// Every part neither stored nor in a task's hands, in order.
128
+ public static func pending(_ r: TransferRecord, size: Int64) -> [Step] {
129
+ let plan = partSize(r)
130
+ let busy = inFlight(r)
131
+ return stride(from: 1, through: count(r, size: size), by: 1)
132
+ .filter { r.parts?[String($0)] == nil && !busy.contains($0) }
133
+ .map { .part(n: $0, offset: PartPlan.offset($0, partSize: plan), length: PartPlan.length($0, size: size, partSize: plan)) }
134
+ }
135
+
136
+ /// The parts in tasks' hands.
137
+ public static func inFlight(_ r: TransferRecord) -> Set<Int> {
138
+ Set((r.partTasks ?? [:]).values.map(\.part))
139
+ }
140
+
141
+ /// Records that task `task` carries part `n` from the copy at `copy`.
142
+ public static func assign(_ r: inout TransferRecord, task: Int, part n: Int, copy: String) {
143
+ var tasks = r.partTasks ?? [:]
144
+ tasks[String(task)] = PartTask(part: n, copy: copy)
145
+ r.partTasks = tasks
146
+ }
147
+
148
+ /// The part task `task` carried, taken off the record; nil for a task the record doesn't know
149
+ /// (cancelled with the others, or from an earlier run).
150
+ public static func release(_ r: inout TransferRecord, task: Int) -> PartTask? {
151
+ guard var tasks = r.partTasks, let t = tasks.removeValue(forKey: String(task)) else { return nil }
152
+ r.partTasks = tasks.isEmpty ? nil : tasks
153
+ return t
154
+ }
155
+
156
+ /// Every temporary copy the record names: the parts' and the commit body's.
157
+ public static func copies(_ r: TransferRecord) -> [String] {
158
+ (r.partTasks ?? [:]).values.map(\.copy) + (r.remainderPath.map { [$0] } ?? [])
159
+ }
160
+
161
+ /// Free space kept after a hand-over: the copies must never fill the disk.
162
+ public static let diskMargin: Int64 = 256 * 1024 * 1024
163
+
164
+ /// Whether copies of `bytes` fit in `free` bytes of disk with the margin left over.
165
+ public static func handOverFits(bytes: Int64, free: Int64) -> Bool {
166
+ free - bytes >= diskMargin
167
+ }
168
+
169
+ /// The bytes still to copy and send: the parts neither stored nor in tasks.
170
+ public static func pendingBytes(_ r: TransferRecord, size: Int64) -> Int64 {
171
+ pending(r, size: size).reduce(0) { total, step in
172
+ if case .part(_, _, let length) = step { return total + length }
173
+ return total
174
+ }
175
+ }
176
+
177
+ /// The bytes of the parts stored.
178
+ public static func storedBytes(_ r: TransferRecord, size: Int64) -> Int64 {
179
+ let plan = partSize(r)
180
+ return (r.parts ?? [:]).keys.compactMap(Int.init).reduce(0) { $0 + PartPlan.length($1, size: size, partSize: plan) }
181
+ }
182
+
183
+ public static func partRequest(_ r: TransferRecord, n: Int, size: Int64) -> URLRequest? {
184
+ let target: String?
185
+ if isAzure(r) {
186
+ let id = PartsXML.blockId(transferId: r.id, size: size, blockSize: partSize(r), n: n)
187
+ target = withQuery(r.url, "comp=block&blockid=" + (id.addingPercentEncoding(withAllowedCharacters: .alphanumerics) ?? id))
188
+ } else {
189
+ target = (r.partUrls ?? []).indices.contains(n - 1) ? r.partUrls![n - 1] : nil
190
+ }
191
+ guard let t = target, let url = URL(string: t) else { return nil }
192
+ var request = URLRequest(url: url)
193
+ request.httpMethod = "PUT"
194
+ request.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type")
195
+ for (k, v) in isAzure(r) ? blockHeaders(r.headers) : r.headers { request.setValue(v, forHTTPHeaderField: k) }
196
+ return request
197
+ }
198
+
199
+ /// The headers for an Azure block: all but the blob's properties (`x-ms-blob-content-type` and
200
+ /// the other `x-ms-blob-*` ones), which belong to the commit that creates the blob.
201
+ public static func blockHeaders(_ headers: [String: String]) -> [String: String] {
202
+ headers.filter { !$0.key.lowercased().hasPrefix("x-ms-blob-") }
203
+ }
204
+
205
+ /// Whether a restarted upload is the same one as `existing`, so what that one sent carries over:
206
+ /// the same URL and protocol, and for one in parts the same part or block size and file size too
207
+ /// (parts recorded for other ranges would otherwise be skipped as stored).
208
+ public static func carriesOver(_ existing: TransferRecord?, _ wanted: TransferRecord, fileSize: Int64) -> Bool {
209
+ guard let e = existing, e.url == wanted.url, e.protocol == wanted.protocol else { return false }
210
+ guard UploadProtocol.resolve(wanted.protocol)?.inParts == true else { return true }
211
+ return partSize(e) == partSize(wanted) && e.total == fileSize
212
+ }
213
+
214
+ /// What a task's end means once the app has asked to cancel the transfer.
215
+ public enum AfterCancel: Equatable {
216
+ /// As if no cancel had been asked for.
217
+ case asUsual
218
+ /// The transfer is cancelled: clean up and report `cancelled`.
219
+ case cancelled
220
+ /// A part stored after the cancel: nothing more is sent; the other tasks' ends report it.
221
+ case ignore
222
+ /// The commit was answered: finished if the server confirms the object, cancelled otherwise.
223
+ case confirmOrCancel
224
+ }
225
+
226
+ /// A task of a transfer the app asked to cancel has ended.
227
+ ///
228
+ /// - Upload in parts (`inParts`): a part's error of any kind is the cancel (the user asked to
229
+ /// stop); a part that landed anyway starts nothing more, and reports the cancel if it was the
230
+ /// last task out. The commit isn't cancelled (its body may already be in): its answer decides,
231
+ /// and an error ending it is the cancel, with `committing` kept so a restart reports
232
+ /// `session-closed`.
233
+ /// - Anything else (one task): only a task that ended cancelled reads as the cancel; any
234
+ /// other end is handled as usual, so an object the server took is still finished.
235
+ public static func afterCancel(requested: Bool, inParts: Bool, isCommit: Bool, cancelledError: Bool, otherError: Bool,
236
+ othersInFlight: Bool) -> AfterCancel {
237
+ guard requested else { return .asUsual }
238
+ guard inParts else { return cancelledError ? .cancelled : .asUsual }
239
+ if cancelledError || otherError { return .cancelled }
240
+ if isCommit { return .confirmOrCancel }
241
+ return othersInFlight ? .ignore : .cancelled
242
+ }
243
+
244
+ /// What `cancel()` does with the tasks the session still has for a transfer.
245
+ public enum CancelPlan: Equatable {
246
+ /// Cancel these tasks; their ends report it.
247
+ case cancelTasks
248
+ /// Leave the commit out: its end decides.
249
+ case awaitCommit
250
+ /// A task has ended but its end isn't delivered yet: that end reports it.
251
+ case awaitEnd
252
+ /// No task is left: report it cancelled now.
253
+ case markCancelled
254
+ }
255
+
256
+ public static func cancelPlan(commitOut: Bool, unfinishedTasks: Int, endedTasks: Int) -> CancelPlan {
257
+ if commitOut { return .awaitCommit }
258
+ if unfinishedTasks > 0 { return .cancelTasks }
259
+ return endedTasks > 0 ? .awaitEnd : .markCancelled
260
+ }
261
+
262
+ /// After part `n`'s answer. Nil: it is stored, and recorded in `r.parts`.
263
+ public static func afterPart(_ r: inout TransferRecord, n: Int, status: Int, etag: String?, size: Int64) -> UploadOutcome? {
264
+ let what = "\(isAzure(r) ? "block" : "part") \(n) of \(count(r, size: size))"
265
+ var parts = r.parts ?? [:]
266
+ if isAzure(r) {
267
+ guard status == 201 else { return refusal(status, what) }
268
+ parts[String(n)] = PartsXML.blockId(transferId: r.id, size: size, blockSize: partSize(r), n: n)
269
+ } else {
270
+ guard status == 200 else { return refusal(status, what) }
271
+ guard let etag = etag, !etag.isEmpty else { return .failed(reason: Reason.unknown, message: "\(what) answered without an ETag") }
272
+ parts[String(n)] = etag
273
+ }
274
+ r.parts = parts
275
+ return nil
276
+ }
277
+
278
+ /// The commit: S3's `CompleteMultipartUpload` or Azure's `Put Block List`, and its body.
279
+ public static func commitRequest(_ r: TransferRecord, size: Int64) -> (URLRequest, Data)? {
280
+ let n = count(r, size: size)
281
+ let target = isAzure(r) ? withQuery(r.url, "comp=blocklist") : r.url
282
+ guard let url = URL(string: target) else { return nil }
283
+ var request = URLRequest(url: url)
284
+ request.httpMethod = isAzure(r) ? "PUT" : "POST"
285
+ request.setValue("application/xml", forHTTPHeaderField: "Content-Type")
286
+ for (k, v) in r.headers { request.setValue(v, forHTTPHeaderField: k) }
287
+ let body = isAzure(r)
288
+ ? PartsXML.blockListBody(PartsXML.blockIds(transferId: r.id, size: size, blockSize: partSize(r), count: n))
289
+ : PartsXML.completeBody(etags: r.parts ?? [:], count: n)
290
+ return (request, body)
291
+ }
292
+
293
+ /// After the commit's answer. Finished only when the server confirms the object; any answer
294
+ /// clears `committing` (it wasn't lost), so a refused commit can be tried again.
295
+ public static func afterCommit(_ r: inout TransferRecord, status: Int, body: Data?) -> UploadOutcome {
296
+ if isAzure(r) {
297
+ if status == 201 { return .finished }
298
+ r.committing = false
299
+ return refusal(status, "commit (Put Block List)")
300
+ }
301
+ if status == 200 && PartsXML.isCompleteResult(body) { return .finished }
302
+ r.committing = false
303
+ if status == 404 {
304
+ return .failed(reason: Reason.sessionClosed,
305
+ message: "complete HTTP 404: the upload is no longer open (completed or aborted): check the object")
306
+ }
307
+ guard status == 200 else { return refusal(status, "complete") }
308
+ guard let code = PartsXML.errorCode(body) else {
309
+ return .failed(reason: Reason.unknown, message: "complete answered 200 without the completed object")
310
+ }
311
+ let busy = ["InternalError", "SlowDown", "ServiceUnavailable"].contains(code)
312
+ return busy ? .interrupted(reason: Reason.serverError, message: "complete answered 200 with \(code)")
313
+ : .failed(reason: Reason.sessionRefused, message: "complete answered 200 with \(code)")
314
+ }
315
+
316
+ static func refusal(_ status: Int, _ what: String) -> UploadOutcome {
317
+ let (reason, resumable) = Reason.forStatus(status)
318
+ let message = "\(what) HTTP \(status)"
319
+ return resumable ? .interrupted(reason: reason, message: message) : .failed(reason: reason, message: message)
320
+ }
321
+
322
+ /// `url` with `extra` added to its query.
323
+ public static func withQuery(_ url: String, _ extra: String) -> String {
324
+ let base = url.split(separator: "#", maxSplits: 1, omittingEmptySubsequences: false).first.map(String.init) ?? url
325
+ return base + (base.contains("?") ? "&" : "?") + extra
326
+ }
327
+ }
@@ -0,0 +1,137 @@
1
+ import Foundation
2
+ #if canImport(CryptoKit)
3
+ import CryptoKit
4
+ #endif
5
+
6
+ /// The XML that S3 multipart uploads and Azure block blobs speak, and Azure's block ids.
7
+ public enum PartsXML {
8
+ /// What `ListParts` answered: part number → (ETag, size), and whether more pages follow.
9
+ public struct Listed: Equatable {
10
+ public var parts: [Int: (tag: String, size: Int64)] = [:]
11
+ public var truncated = false
12
+ public var highest = 0
13
+
14
+ public static func == (a: Listed, b: Listed) -> Bool {
15
+ a.truncated == b.truncated && a.highest == b.highest && a.parts.mapValues { "\($0.tag)|\($0.size)" } == b.parts.mapValues { "\($0.tag)|\($0.size)" }
16
+ }
17
+ }
18
+
19
+ /// Nil when the XML can't be read.
20
+ public static func listParts(_ data: Data) -> Listed? {
21
+ guard let root = Element.parse(data) else { return nil }
22
+ var out = Listed()
23
+ out.truncated = root.child("IsTruncated")?.text.lowercased() == "true"
24
+ for part in root.children("Part") {
25
+ guard let n = Int(part.child("PartNumber")?.text.trimmingCharacters(in: .whitespaces) ?? ""),
26
+ let size = Int64(part.child("Size")?.text.trimmingCharacters(in: .whitespaces) ?? "") else { return nil }
27
+ out.parts[n] = (part.child("ETag")?.text ?? "", size)
28
+ out.highest = max(out.highest, n)
29
+ }
30
+ return out
31
+ }
32
+
33
+ /// The `CompleteMultipartUpload` body listing parts 1 to `count`.
34
+ public static func completeBody(etags: [String: String], count: Int) -> Data {
35
+ var b = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><CompleteMultipartUpload>"
36
+ for n in stride(from: 1, through: count, by: 1) {
37
+ b += "<Part><PartNumber>\(n)</PartNumber><ETag>\(escape(etags[String(n)] ?? ""))</ETag></Part>"
38
+ }
39
+ b += "</CompleteMultipartUpload>"
40
+ return Data(b.utf8)
41
+ }
42
+
43
+ /// The error code in an S3 answer, or nil when it isn't an `<Error>`. S3 can answer
44
+ /// `CompleteMultipartUpload` with 200 and an error in the body.
45
+ public static func errorCode(_ data: Data?) -> String? {
46
+ guard let data = data, let text = String(data: data, encoding: .utf8), text.contains("<Error") else { return nil }
47
+ guard let root = Element.parse(data) else { return "Error" }
48
+ guard root.name == "Error" else { return nil }
49
+ let code = root.child("Code")?.text ?? ""
50
+ return code.isEmpty ? "Error" : code
51
+ }
52
+
53
+ /// Whether a 200 answer to `CompleteMultipartUpload` is the completed object.
54
+ public static func isCompleteResult(_ data: Data?) -> Bool {
55
+ guard let data = data, let text = String(data: data, encoding: .utf8) else { return false }
56
+ return text.contains("CompleteMultipartUploadResult") && errorCode(data) == nil
57
+ }
58
+
59
+ /// Azure's `Get Block List`: block id → size, for the uncommitted blocks. Nil when unreadable.
60
+ public static func uncommittedBlocks(_ data: Data) -> [String: Int64]? {
61
+ guard let root = Element.parse(data) else { return nil }
62
+ var out: [String: Int64] = [:]
63
+ for section in root.children("UncommittedBlocks") {
64
+ for block in section.children("Block") {
65
+ guard let size = Int64(block.child("Size")?.text.trimmingCharacters(in: .whitespaces) ?? "") else { return nil }
66
+ out[block.child("Name")?.text ?? ""] = size
67
+ }
68
+ }
69
+ return out
70
+ }
71
+
72
+ /// The `Put Block List` body committing `ids` in order.
73
+ public static func blockListBody(_ ids: [String]) -> Data {
74
+ Data(("<?xml version=\"1.0\" encoding=\"utf-8\"?><BlockList>" + ids.map { "<Latest>\(escape($0))</Latest>" }.joined() + "</BlockList>").utf8)
75
+ }
76
+
77
+ /// Block `n`'s id: the same for the same transfer, file size and block size, so a resumed upload
78
+ /// finds its blocks, and different for a different file. Every id of a blob has the same length,
79
+ /// as Azure requires. Android makes the same ids.
80
+ public static func blockId(transferId: String, size: Int64, blockSize: Int64, n: Int) -> String {
81
+ let digest = SHA256.hash(data: Data("\(transferId)|\(size)|\(blockSize)".utf8))
82
+ let prefix = digest.prefix(8).map { String(format: "%02x", $0) }.joined()
83
+ return Data((prefix + "-" + String(format: "%06d", n)).utf8).base64EncodedString()
84
+ }
85
+
86
+ public static func blockIds(transferId: String, size: Int64, blockSize: Int64, count: Int) -> [String] {
87
+ (0..<count).map { blockId(transferId: transferId, size: size, blockSize: blockSize, n: $0 + 1) }
88
+ }
89
+
90
+ static func escape(_ s: String) -> String {
91
+ s.replacingOccurrences(of: "&", with: "&amp;").replacingOccurrences(of: "<", with: "&lt;")
92
+ .replacingOccurrences(of: ">", with: "&gt;").replacingOccurrences(of: "\"", with: "&quot;")
93
+ }
94
+
95
+ /// A small DOM, enough for these answers.
96
+ final class Element {
97
+ let name: String
98
+ var text = ""
99
+ var elements: [Element] = []
100
+
101
+ init(_ name: String) { self.name = name }
102
+
103
+ func children(_ tag: String) -> [Element] { elements.filter { $0.name == tag } }
104
+ func child(_ tag: String) -> Element? { elements.first { $0.name == tag } }
105
+
106
+ static func parse(_ data: Data) -> Element? {
107
+ let builder = Builder()
108
+ let parser = XMLParser(data: data)
109
+ parser.shouldResolveExternalEntities = false
110
+ parser.delegate = builder
111
+ guard parser.parse(), let root = builder.root else { return nil }
112
+ return root
113
+ }
114
+ }
115
+
116
+ private final class Builder: NSObject, XMLParserDelegate {
117
+ var root: Element?
118
+ var stack: [Element] = []
119
+
120
+ func parser(_ parser: XMLParser, didStartElement name: String, namespaceURI: String?, qualifiedName: String?,
121
+ attributes: [String: String] = [:]) {
122
+ let local = name.split(separator: ":").last.map(String.init) ?? name
123
+ let e = Element(local)
124
+ stack.last?.elements.append(e)
125
+ if root == nil { root = e }
126
+ stack.append(e)
127
+ }
128
+
129
+ func parser(_ parser: XMLParser, didEndElement name: String, namespaceURI: String?, qualifiedName: String?) {
130
+ _ = stack.popLast()
131
+ }
132
+
133
+ func parser(_ parser: XMLParser, foundCharacters string: String) {
134
+ stack.last?.text += string
135
+ }
136
+ }
137
+ }
@@ -0,0 +1,103 @@
1
+ import Foundation
2
+
3
+ /// The checks on a transfer's options that the native side repeats, whatever the JavaScript
4
+ /// wrapper did: a script in the web view can call the plugin directly and skip `validate.ts`. The
5
+ /// refusals use the wrapper's words. Foundation only, so it runs under `swift test` on a Mac.
6
+ public enum TransferPaths {
7
+ public static let notHttp = "url must be an http or https URL"
8
+ public static let outside = "path must be inside the app's storage"
9
+ public static let pluginDir = "path must not be inside the plugin's own storage"
10
+ public static let symlink = "path must not be a symbolic link"
11
+
12
+ /// What is wrong with `url`, or nil.
13
+ public static func checkUrl(_ url: String) -> String? {
14
+ guard let parsed = URL(string: url), let scheme = parsed.scheme?.lowercased(), scheme == "http" || scheme == "https",
15
+ let host = parsed.host, !host.isEmpty else { return notHttp }
16
+ return nil
17
+ }
18
+
19
+ /// What is wrong with the headers (a name or value with a line break or another control
20
+ /// character), or nil.
21
+ public static func checkHeaders(_ headers: [String: String]) -> String? {
22
+ for (name, value) in headers where name.isEmpty || hasControl(name) || hasControl(value) {
23
+ return "header \(name) must be one line"
24
+ }
25
+ return nil
26
+ }
27
+
28
+ private static func hasControl(_ s: String) -> Bool {
29
+ s.unicodeScalars.contains { $0.value < 0x20 || $0.value == 0x7f }
30
+ }
31
+
32
+ /// The wrapper's checks on the path's shape: absolute, naming a file, no `..` segment.
33
+ public static func checkShape(_ path: String) -> String? {
34
+ if path.isEmpty { return "path is required" }
35
+ if !path.hasPrefix("/") { return "path must be absolute or a file:// URI" }
36
+ if path.hasSuffix("/") { return "path must name a file" }
37
+ if path.split(separator: "/", omittingEmptySubsequences: false).contains("..") { return "path must not contain .." }
38
+ return nil
39
+ }
40
+
41
+ /// Refuses a path that isn't under one of `roots` (the app's own directories) once symbolic
42
+ /// links are resolved, or that is inside `refused` (the plugin's own storage, which holds other
43
+ /// transfers' headers). For a download, the destination and its `.part` must not be symbolic
44
+ /// links either, since both are replaced. Returns what is wrong, or nil.
45
+ public static func confine(_ path: String, roots: [URL], refused: URL?, download: Bool) -> String? {
46
+ if let shape = checkShape(path) { return shape }
47
+ let file = URL(fileURLWithPath: path)
48
+ let resolved = canonical(file)
49
+ if let refused = refused, isUnder(resolved, canonical(refused)) { return pluginDir }
50
+ guard roots.contains(where: { isUnder(resolved, canonical($0)) }) else { return outside }
51
+ if download && (isSymbolicLink(file) || isSymbolicLink(Files.partURL(for: file))) { return symlink }
52
+ return nil
53
+ }
54
+
55
+ /// `url` with every symbolic link resolved: its deepest existing ancestor is resolved and the
56
+ /// rest appended, so a file not yet written (a download's destination) resolves too. (On a
57
+ /// device the app's directories are under `/var`, a link to `/private/var`; the roots and the
58
+ /// path both come out the same way.)
59
+ public static func canonical(_ url: URL) -> URL {
60
+ let fm = FileManager.default
61
+ var existing = url.standardizedFileURL
62
+ var rest: [String] = []
63
+ while !fm.fileExists(atPath: existing.path) && existing.pathComponents.count > 1 {
64
+ rest.insert(existing.lastPathComponent, at: 0)
65
+ existing = existing.deletingLastPathComponent()
66
+ }
67
+ var resolved = existing.resolvingSymlinksInPath().standardizedFileURL
68
+ for name in rest { resolved.appendPathComponent(name) }
69
+ return resolved
70
+ }
71
+
72
+ /// Whether `url` is `root` or inside it (both canonical), by path components.
73
+ public static func isUnder(_ url: URL, _ root: URL) -> Bool {
74
+ let a = url.pathComponents
75
+ let b = root.pathComponents
76
+ return a.count >= b.count && Array(a.prefix(b.count)) == b
77
+ }
78
+
79
+ public static func isSymbolicLink(_ url: URL) -> Bool {
80
+ (try? FileManager.default.destinationOfSymbolicLink(atPath: url.path)) != nil
81
+ }
82
+ }
83
+
84
+ /// Where a redirect may go: the same origin (scheme, host and port) as the URL the app named, so
85
+ /// the app's headers never reach a host it didn't send them to.
86
+ public enum Redirects {
87
+ public static func sameOrigin(_ from: URL, _ to: URL) -> Bool {
88
+ guard let a = from.scheme?.lowercased(), let b = to.scheme?.lowercased(), a == b,
89
+ let h = from.host?.lowercased(), let k = to.host?.lowercased(), h == k else { return false }
90
+ return port(from) == port(to)
91
+ }
92
+
93
+ private static func port(_ url: URL) -> Int {
94
+ if let p = url.port { return p }
95
+ return url.scheme?.lowercased() == "https" ? 443 : 80
96
+ }
97
+
98
+ /// Whether a task that began at `original` ended answering from another origin.
99
+ public static func crossedOrigin(original: URL?, final: URL?) -> Bool {
100
+ guard let original = original, let final = final else { return false }
101
+ return !sameOrigin(original, final)
102
+ }
103
+ }