containerization-framework 0.4.0

Rust bindings for Apple's Containerization framework: Linux containers in lightweight VMs, in-process and without a daemon.
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
//===----------------------------------------------------------------------===//
// ContainerizationArchive: `ArchiveWriter`, `ArchiveReader` and `WriteEntry`,
// and `EXT4Unpacker.unpack(archive:compression:at:)`, which takes its
// `Filter`.
//
// Enums cross as their `rawValue`s.
//===----------------------------------------------------------------------===//

import Containerization
import ContainerizationArchive
import Foundation
import SystemPackage

func unpackExt4Archive(unpacker: RustExt4Unpacker, archive: RustStr, compression: RustStr, at: RustStr) -> CzOutcome {
  // Not `Sendable`, but a value only the task below uses.
  nonisolated(unsafe) let unpacker = EXT4Unpacker(unpacker)
  let archive = URL(filePath: archive.toString())
  let compression = compression.toString()
  let at = URL(filePath: at.toString())

  return CzOutcome {
    let filter = try archiveFilter(compression)
    return try blocking { try await unpacker.unpack(archive: archive, compression: filter, at: at) }
  }
}

func xattrFormatDescription(format: RustStr) -> CzOutcome {
  let format = format.toString()

  return CzOutcome {
    guard let format = Options.XattrFormat(rawValue: format) else {
      throw BridgeError.malformed("extended attribute format", format)
    }
    return format.description
  }
}

/// For a unit test: the raw values of the enum `name`, in the order of Rust's
/// `ALL`.
func archiveRawValues(name: RustStr) -> RustVec<RustString> {
  let name = name.toString()
  let rawValues: [String] =
    switch name {
    case "Format":
      [
        Format.ustar, .gnutar, .pax, .paxRestricted, .cpio, .cpioNewc, .zip, .shar, .sharDump, .iso9660,
        .sevenZip, .arBSD, .arGNU, .mtree, .xar,
      ].map(\.rawValue)
    case "Filter":
      [
        Filter.none, .gzip, .bzip2, .compress, .lzma, .xz, .uu, .rpm, .lzip, .lrzip, .lzop, .grzip, .lz4, .zstd,
      ].map(\.rawValue)
    case "XattrFormat":
      [Options.XattrFormat.schily, .libarchive, .all].map(\.rawValue)
    case "URLFileResourceType":
      [
        URLFileResourceType.namedPipe, .characterSpecial, .directory, .blockSpecial, .regular, .symbolicLink,
        .socket, .unknown,
      ].map(\.rawValue)
    default:
      preconditionFailure("no enum named \(name)")
    }

  return rustStrings(rawValues)
}

func archiveDefaultLocales() -> RustVec<RustString> {
  rustStrings(ArchiveWriterConfiguration.defaultLocales)
}

func archiveFormat(_ rawValue: String) throws -> Format {
  guard let format = Format(rawValue: rawValue) else {
    throw BridgeError.malformed("archive format", rawValue)
  }
  return format
}

func archiveFilter(_ rawValue: String) throws -> Filter {
  guard let filter = Filter(rawValue: rawValue) else {
    throw BridgeError.malformed("archive filter", rawValue)
  }
  return filter
}

extension ArchiveWriterConfiguration {
  init(_ configuration: RustArchiveWriterConfiguration) throws {
    let options = try list(configuration.optionsLen()) { index -> Options in
      switch configuration.optionKindAt(index) {
      case .CompressionLevel:
        return .compressionLevel(configuration.optionCompressionLevelAt(index))
      case .CompressionStore:
        return .compression(.store)
      case .CompressionDeflate:
        return .compression(.deflate)
      case .Xattrformat:
        let rawValue = configuration.optionXattrFormatAt(index).toString()
        guard let format = Options.XattrFormat(rawValue: rawValue) else {
          throw BridgeError.malformed("extended attribute format", rawValue)
        }
        return .xattrformat(format)
      }
    }

    self.init(
      format: try archiveFormat(configuration.format().toString()),
      filter: try archiveFilter(configuration.filter().toString()),
      options: options,
      locales: strings(configuration.localesLen()) { configuration.localesAt($0) }
    )
  }
}

func newWriteEntry() -> CzOutcome {
  CzOutcome { CzWriteEntry(WriteEntry()) }
}

/// Unchecked: Rust's `WriteEntry` isn't `Sync`, so one call runs at a time.
final class CzWriteEntry: @unchecked Sendable {
  let entry: WriteEntry

  init(_ entry: WriteEntry) {
    self.entry = entry
  }

  /// Another handle on the same entry, for a writer to take.
  func duplicate() -> CzWriteEntry {
    CzWriteEntry(entry)
  }

  func hasSize() -> Bool {
    entry.size != nil
  }

  func size() -> Int64 {
    entry.size ?? 0
  }

  func setSize(isSet: Bool, size: Int64) {
    entry.size = isSet ? size : nil
  }

  func permissions() -> UInt16 {
    entry.permissions
  }

  func setPermissions(permissions: UInt16) {
    entry.permissions = permissions
  }

  func hasOwner() -> Bool {
    entry.owner != nil
  }

  func owner() -> UInt32 {
    entry.owner ?? 0
  }

  func setOwner(isSet: Bool, owner: UInt32) {
    entry.owner = isSet ? owner : nil
  }

  func hasGroup() -> Bool {
    entry.group != nil
  }

  func group() -> UInt32 {
    entry.group ?? 0
  }

  func setGroup(isSet: Bool, group: UInt32) {
    entry.group = isSet ? group : nil
  }

  func hardlink() -> String? {
    entry.hardlink
  }

  func setHardlink(hardlink: RustString?) {
    entry.hardlink = hardlink?.toString()
  }

  func hardlinkUtf8() -> String? {
    entry.hardlinkUtf8
  }

  func setHardlinkUtf8(hardlink: RustString?) {
    entry.hardlinkUtf8 = hardlink?.toString()
  }

  func strmode() -> String? {
    entry.strmode
  }

  func fileType() -> String {
    entry.fileType.rawValue
  }

  func setFileType(fileType: RustStr) {
    entry.fileType = URLFileResourceType(rawValue: fileType.toString())
  }

  // Dates, as seconds since 1970.

  func hasContentAccessDate() -> Bool {
    entry.contentAccessDate != nil
  }

  func contentAccessDate() -> Double {
    entry.contentAccessDate?.timeIntervalSince1970 ?? 0
  }

  func setContentAccessDate(isSet: Bool, seconds: Double) {
    entry.contentAccessDate = isSet ? Date(timeIntervalSince1970: seconds) : nil
  }

  func hasCreationDate() -> Bool {
    entry.creationDate != nil
  }

  func creationDate() -> Double {
    entry.creationDate?.timeIntervalSince1970 ?? 0
  }

  func setCreationDate(isSet: Bool, seconds: Double) {
    entry.creationDate = isSet ? Date(timeIntervalSince1970: seconds) : nil
  }

  func hasModificationDate() -> Bool {
    entry.modificationDate != nil
  }

  func modificationDate() -> Double {
    entry.modificationDate?.timeIntervalSince1970 ?? 0
  }

  func setModificationDate(isSet: Bool, seconds: Double) {
    entry.modificationDate = isSet ? Date(timeIntervalSince1970: seconds) : nil
  }

  func path() -> String? {
    entry.path
  }

  func setPath(path: RustString?) {
    entry.path = path?.toString()
  }

  func pathUtf8() -> String? {
    entry.pathUtf8
  }

  func setPathUtf8(path: RustString?) {
    entry.pathUtf8 = path?.toString()
  }

  func symlinkTarget() -> String? {
    entry.symlinkTarget
  }

  func setSymlinkTarget(target: RustString?) {
    entry.symlinkTarget = target?.toString()
  }

  func xattrs() -> CzOutcome {
    CzOutcome { entry.xattrs }
  }

  /// `values` is every value joined, each `lengths` long in turn.
  func setXattrs(names: RustVec<RustString>, lengths: RustVec<UInt64>, values: RustVec<UInt8>) {
    entry.xattrs = dataMap(names: names, lengths: lengths, values: values)
  }
}

/// A `[String: Data]`, crossing as its keys and its values joined into one,
/// with each one's length.
func dataMap(names: RustVec<RustString>, lengths: RustVec<UInt64>, values: RustVec<UInt8>) -> [String: Data] {
  let values = Data(values)
  var map: [String: Data] = [:]
  var offset = values.startIndex
  for (name, length) in zip(strings(names), lengths) {
    let end = offset + Int(length)
    map[name] = values.subdata(in: offset..<end)
    offset = end
  }
  return map
}

func newArchiveWriter(configuration: RustArchiveWriterConfiguration) -> CzOutcome {
  CzOutcome { CzArchiveWriter(try ArchiveWriter(configuration: try ArchiveWriterConfiguration(configuration))) }
}

func archiveWriterWithFile(configuration: RustArchiveWriterConfiguration, file: RustStr) -> CzOutcome {
  let file = URL(filePath: file.toString())

  return CzOutcome {
    let configuration = try ArchiveWriterConfiguration(configuration)
    return CzArchiveWriter(
      try ArchiveWriter(
        format: configuration.format,
        filter: configuration.filter,
        options: configuration.options,
        locales: configuration.locales,
        file: file
      )
    )
  }
}

/// Unchecked: Rust's `ArchiveWriter` isn't `Sync`, so one call runs at a time.
final class CzArchiveWriter: @unchecked Sendable {
  let writer: ArchiveWriter

  init(_ writer: ArchiveWriter) {
    self.writer = writer
  }

  func newEntry() -> CzWriteEntry {
    CzWriteEntry(WriteEntry(writer))
  }

  func open(file: RustStr) -> CzOutcome {
    let file = URL(filePath: file.toString())

    return CzOutcome { try writer.open(file: file) }
  }

  func openWithFileDescriptor(fileDescriptor: Int32) -> CzOutcome {
    CzOutcome { try writer.open(fileDescriptor: fileDescriptor) }
  }

  func finishEncoding() -> CzOutcome {
    CzOutcome { try writer.finishEncoding() }
  }

  func makeTransactionWriter() -> CzArchiveWriterTransaction {
    CzArchiveWriterTransaction(writer.makeTransactionWriter())
  }

  func writeEntry(entry: CzWriteEntry, hasData: Bool, data: RustVec<UInt8>) -> CzOutcome {
    let data = hasData ? Data(data) : nil

    return CzOutcome {
      if let data {
        try data.withUnsafeBytes { try writer.writeEntry(entry: entry.entry, data: $0) }
      } else {
        try writer.writeEntry(entry: entry.entry, data: nil)
      }
      return ()
    }
  }

  func archiveDirectory(dir: RustStr) -> CzOutcome {
    let dir = URL(filePath: dir.toString())

    return CzOutcome { try writer.archiveDirectory(dir) }
  }

  func archive(paths: RustVec<RustString>, base: RustStr) -> CzOutcome {
    let paths = strings(paths).map { FilePath($0) }
    let base = FilePath(base.toString())

    return CzOutcome { try writer.archive(paths, base: base) }
  }
}

/// Unchecked: Rust's `ArchiveWriterTransaction` isn't `Sync`, so one call
/// runs at a time.
final class CzArchiveWriterTransaction: @unchecked Sendable {
  let transaction: ArchiveWriterTransaction

  init(_ transaction: ArchiveWriterTransaction) {
    self.transaction = transaction
  }

  func writeHeader(entry: CzWriteEntry) -> CzOutcome {
    CzOutcome { try transaction.writeHeader(entry: entry.entry) }
  }

  func writeChunk(data: RustVec<UInt8>) -> CzOutcome {
    let data = Data(data)

    return CzOutcome { try data.withUnsafeBytes { try transaction.writeChunk(data: $0) } }
  }

  func finish() -> CzOutcome {
    CzOutcome { try transaction.finish() }
  }
}

func openArchiveReader(file: RustStr) -> CzOutcome {
  let file = URL(filePath: file.toString())

  return CzOutcome { CzArchiveReader(try ArchiveReader(file: file)) }
}

func archiveReaderWithFormat(format: RustStr, filter: RustStr, file: RustStr) -> CzOutcome {
  let format = format.toString()
  let filter = filter.toString()
  let file = URL(filePath: file.toString())

  return CzOutcome {
    CzArchiveReader(try ArchiveReader(format: try archiveFormat(format), filter: try archiveFilter(filter), file: file))
  }
}

/// The reader owns the descriptor, and closes it.
func archiveReaderWithFileHandle(format: RustStr, filter: RustStr, fileHandle: Int32) -> CzOutcome {
  let format = format.toString()
  let filter = filter.toString()
  let fileHandle = FileHandle(fileDescriptor: fileHandle, closeOnDealloc: true)

  return CzOutcome {
    CzArchiveReader(
      try ArchiveReader(
        format: try archiveFormat(format),
        filter: try archiveFilter(filter),
        fileHandle: fileHandle
      )
    )
  }
}

func archiveReaderWithBundle(name: RustStr, bundle: RustVec<UInt8>, tempDirectoryBaseName: RustString?) -> CzOutcome {
  let name = name.toString()
  let bundle = Data(bundle)
  let tempDirectoryBaseName = tempDirectoryBaseName?.toString()

  return CzOutcome {
    CzArchiveReader(try ArchiveReader(name: name, bundle: bundle, tempDirectoryBaseName: tempDirectoryBaseName))
  }
}

/// Unchecked: Rust's `ArchiveReader` isn't `Sync`, so one call runs at a time.
final class CzArchiveReader: @unchecked Sendable {
  let reader: ArchiveReader

  init(_ reader: ArchiveReader) {
    self.reader = reader
  }

  /// Another handle on the same reader, for a formatter to take.
  func duplicate() -> CzArchiveReader {
    CzArchiveReader(reader)
  }

  func makeIterator() -> CzArchiveIterator {
    CzArchiveIterator(reader.makeIterator())
  }

  func makeStreamingIterator() -> CzStreamingIterator {
    CzStreamingIterator(reader.makeStreamingIterator())
  }

  func throwIfStreamFailed() -> CzOutcome {
    CzOutcome { try reader.throwIfStreamFailed() }
  }

  func extractContents(to: RustStr) -> CzOutcome {
    let to = URL(filePath: to.toString())

    return CzOutcome { try reader.extractContents(to: to) }
  }

  func extractFile(path: RustStr) -> CzOutcome {
    let path = path.toString()

    return CzOutcome { try reader.extractFile(path: path) }
  }
}

/// Unchecked: Rust's iterator borrows its reader, and isn't `Sync`.
final class CzArchiveIterator: @unchecked Sendable {
  var iterator: ArchiveReader.Iterator

  init(_ iterator: ArchiveReader.Iterator) {
    self.iterator = iterator
  }

  func next() -> CzOutcome {
    CzOutcome.holding(iterator.next())
  }
}

/// Unchecked: Rust's iterator borrows its reader, and isn't `Sync`.
final class CzStreamingIterator: @unchecked Sendable {
  var iterator: ArchiveReader.StreamingIterator

  init(_ iterator: ArchiveReader.StreamingIterator) {
    self.iterator = iterator
  }

  func next() -> CzOutcome {
    CzOutcome.holding(iterator.next())
  }
}

/// Unchecked: Rust's reader borrows the archive's reader, and isn't `Sync`.
final class CzArchiveEntryReader: @unchecked Sendable {
  let reader: ArchiveEntryReader

  init(_ reader: ArchiveEntryReader) {
    self.reader = reader
  }

  /// The bytes read, or a failure for Swift's `-1`.
  func read(maxLength: UInt) -> CzOutcome {
    CzOutcome {
      var buffer = [UInt8](repeating: 0, count: Int(maxLength))
      let count = buffer.withUnsafeMutableBufferPointer { buffer in
        guard let baseAddress = buffer.baseAddress else { return 0 }
        return reader.read(baseAddress, maxLength: buffer.count)
      }
      guard count >= 0 else {
        throw BridgeError.readFailed
      }
      return Array(buffer[..<count])
    }
  }
}