UTMScriptingConfigImpl.swift 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672
  1. //
  2. // Copyright © 2023 osy. All rights reserved.
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. //
  16. import Foundation
  17. @objc extension UTMScriptingVirtualMachineImpl {
  18. @objc var configuration: [AnyHashable : Any] {
  19. let wrapper = UTMScriptingConfigImpl(vm.config, data: data)
  20. return wrapper.serializeConfiguration()
  21. }
  22. @objc func updateConfiguration(_ command: NSScriptCommand) {
  23. let newConfiguration = command.evaluatedArguments?["newConfiguration"] as? [AnyHashable : Any]
  24. withScriptCommand(command) { [self] in
  25. guard let newConfiguration = newConfiguration else {
  26. throw ScriptingError.invalidParameter
  27. }
  28. guard vm.state == .stopped else {
  29. throw ScriptingError.notStopped
  30. }
  31. let wrapper = UTMScriptingConfigImpl(vm.config)
  32. try wrapper.updateConfiguration(from: newConfiguration)
  33. try await data.save(vm: box)
  34. }
  35. }
  36. }
  37. @MainActor
  38. class UTMScriptingConfigImpl {
  39. private var bytesInMib: Int64 {
  40. 1048576
  41. }
  42. private(set) var config: any UTMConfiguration
  43. private weak var data: UTMData?
  44. init(_ config: any UTMConfiguration, data: UTMData? = nil) {
  45. self.config = config
  46. self.data = data
  47. }
  48. func serializeConfiguration() -> [AnyHashable : Any] {
  49. if let qemuConfig = config as? UTMQemuConfiguration {
  50. return serializeQemuConfiguration(qemuConfig)
  51. } else if let appleConfig = config as? UTMAppleConfiguration {
  52. return serializeAppleConfiguration(appleConfig)
  53. } else {
  54. fatalError()
  55. }
  56. }
  57. func updateConfiguration(from record: [AnyHashable : Any]) throws {
  58. if let _ = config as? UTMQemuConfiguration {
  59. try updateQemuConfiguration(from: record)
  60. } else if let _ = config as? UTMAppleConfiguration {
  61. try updateAppleConfiguration(from: record)
  62. } else {
  63. fatalError()
  64. }
  65. }
  66. private func size(of drive: any UTMConfigurationDrive) -> Int {
  67. guard let data = data else {
  68. return 0
  69. }
  70. guard let url = drive.imageURL else {
  71. return 0
  72. }
  73. return Int(data.computeSize(for: url) / bytesInMib)
  74. }
  75. }
  76. @MainActor
  77. extension UTMScriptingConfigImpl {
  78. private func qemuDirectoryShareMode(from mode: QEMUFileShareMode) -> UTMScriptingQemuDirectoryShareMode {
  79. switch mode {
  80. case .none: return .none
  81. case .webdav: return .webDAV
  82. case .virtfs: return .virtFS
  83. }
  84. }
  85. private func serializeQemuConfiguration(_ config: UTMQemuConfiguration) -> [AnyHashable : Any] {
  86. [
  87. "name": config.information.name,
  88. "notes": config.information.notes ?? "",
  89. "architecture": config.system.architecture.rawValue,
  90. "machine": config.system.target.rawValue,
  91. "memory": config.system.memorySize,
  92. "cpuCores": config.system.cpuCount,
  93. "hypervisor": config.qemu.hasHypervisor,
  94. "uefi": config.qemu.hasUefiBoot,
  95. "directoryShareMode": qemuDirectoryShareMode(from: config.sharing.directoryShareMode).rawValue,
  96. "drives": config.drives.map({ serializeQemuDriveExisting($0) }),
  97. "networkInterfaces": config.networks.enumerated().map({ serializeQemuNetwork($1, index: $0) }),
  98. "serialPorts": config.serials.enumerated().map({ serializeQemuSerial($1, index: $0) }),
  99. "qemuAdditionalArguments": config.qemu.additionalArguments.map({ serializeQemuAdditionalArgument($0)}),
  100. ]
  101. }
  102. private func qemuDriveInterface(from interface: QEMUDriveInterface) -> UTMScriptingQemuDriveInterface {
  103. switch interface {
  104. case .none: return .none
  105. case .ide: return .ide
  106. case .scsi: return .scsi
  107. case .sd: return .sd
  108. case .mtd: return .mtd
  109. case .floppy: return .floppy
  110. case .pflash: return .pFlash
  111. case .virtio: return .virtIO
  112. case .nvme: return .nvMe
  113. case .usb: return .usb
  114. }
  115. }
  116. private func serializeQemuDriveExisting(_ config: UTMQemuConfigurationDrive) -> [AnyHashable : Any] {
  117. [
  118. "id": config.id,
  119. "removable": config.isExternal,
  120. "interface": qemuDriveInterface(from: config.interface).rawValue,
  121. "hostSize": size(of: config),
  122. ]
  123. }
  124. private func qemuNetworkMode(from mode: QEMUNetworkMode) -> UTMScriptingQemuNetworkMode {
  125. switch mode {
  126. case .emulated: return .emulated
  127. case .shared: return .shared
  128. case .host: return .host
  129. case .bridged: return .bridged
  130. }
  131. }
  132. private func serializeQemuNetwork(_ config: UTMQemuConfigurationNetwork, index: Int) -> [AnyHashable : Any] {
  133. [
  134. "index": index,
  135. "hardware": config.hardware.rawValue,
  136. "mode": qemuNetworkMode(from: config.mode).rawValue,
  137. "address": config.macAddress,
  138. "hostInterface": config.bridgeInterface ?? "",
  139. "portForwards": config.portForward.map({ serializeQemuPortForward($0) }),
  140. ]
  141. }
  142. private func networkProtocol(from protc: QEMUNetworkProtocol) -> UTMScriptingNetworkProtocol {
  143. switch protc {
  144. case .tcp: return .tcp
  145. case .udp: return .udp
  146. }
  147. }
  148. private func serializeQemuPortForward(_ config: UTMQemuConfigurationPortForward) -> [AnyHashable : Any] {
  149. [
  150. "protocol": networkProtocol(from: config.protocol).rawValue,
  151. "hostAddress": config.hostAddress ?? "",
  152. "hostPort": config.hostPort,
  153. "guestAddress": config.guestAddress ?? "",
  154. "guestPort": config.guestPort,
  155. ]
  156. }
  157. private func qemuSerialInterface(from mode: QEMUSerialMode) -> UTMScriptingSerialInterface {
  158. switch mode {
  159. case .ptty: return .ptty
  160. case .tcpServer: return .tcp
  161. default: return .unavailable
  162. }
  163. }
  164. private func serializeQemuSerial(_ config: UTMQemuConfigurationSerial, index: Int) -> [AnyHashable : Any] {
  165. [
  166. "index": index,
  167. "hardware": config.hardware?.rawValue ?? "",
  168. "interface": qemuSerialInterface(from: config.mode).rawValue,
  169. "port": config.tcpPort ?? 0,
  170. ]
  171. }
  172. private func serializeQemuAdditionalArgument(_ argument: QEMUArgument) -> [AnyHashable: Any] {
  173. var serializedArgument: [AnyHashable: Any] = [
  174. "argumentString": argument.string
  175. ]
  176. // Only add fileUrls if it is not nil and contains URLs
  177. if let fileUrls = argument.fileUrls, !fileUrls.isEmpty {
  178. serializedArgument["fileUrls"] = fileUrls.map({ $0 as AnyHashable })
  179. }
  180. return serializedArgument
  181. }
  182. private func serializeAppleConfiguration(_ config: UTMAppleConfiguration) -> [AnyHashable : Any] {
  183. [
  184. "name": config.information.name,
  185. "notes": config.information.notes ?? "",
  186. "memory": config.system.memorySize,
  187. "cpuCores": config.system.cpuCount,
  188. "directoryShares": config.sharedDirectories.enumerated().map({ serializeAppleDirectoryShare($1, index: $0) }),
  189. "drives": config.drives.map({ serializeAppleDriveExisting($0) }),
  190. "networkInterfaces": config.networks.enumerated().map({ serializeAppleNetwork($1, index: $0) }),
  191. "serialPorts": config.serials.enumerated().map({ serializeAppleSerial($1, index: $0) }),
  192. ]
  193. }
  194. private func serializeAppleDirectoryShare(_ config: UTMAppleConfigurationSharedDirectory, index: Int) -> [AnyHashable : Any] {
  195. [
  196. "index": index,
  197. "readOnly": config.isReadOnly
  198. ]
  199. }
  200. private func serializeAppleDriveExisting(_ config: UTMAppleConfigurationDrive) -> [AnyHashable : Any] {
  201. [
  202. "id": config.id,
  203. "removable": config.isExternal,
  204. "hostSize": size(of: config),
  205. ]
  206. }
  207. private func appleNetworkMode(from mode: UTMAppleConfigurationNetwork.NetworkMode) -> UTMScriptingAppleNetworkMode {
  208. switch mode {
  209. case .shared: return .shared
  210. case .bridged: return .bridged
  211. }
  212. }
  213. private func serializeAppleNetwork(_ config: UTMAppleConfigurationNetwork, index: Int) -> [AnyHashable : Any] {
  214. [
  215. "index": index,
  216. "mode": appleNetworkMode(from: config.mode).rawValue,
  217. "address": config.macAddress,
  218. "hostInterface": config.bridgeInterface ?? "",
  219. ]
  220. }
  221. private func appleSerialInterface(from mode: UTMAppleConfigurationSerial.SerialMode) -> UTMScriptingSerialInterface {
  222. switch mode {
  223. case .ptty: return .ptty
  224. default: return .unavailable
  225. }
  226. }
  227. private func serializeAppleSerial(_ config: UTMAppleConfigurationSerial, index: Int) -> [AnyHashable : Any] {
  228. [
  229. "index": index,
  230. "interface": appleSerialInterface(from: config.mode).rawValue,
  231. ]
  232. }
  233. }
  234. @MainActor
  235. extension UTMScriptingConfigImpl {
  236. private func updateElements<T>(_ array: inout [T], with records: [[AnyHashable : Any]], onExisting: @MainActor (inout T, [AnyHashable : Any]) throws -> Void, onNew: @MainActor ([AnyHashable : Any]) throws -> T) throws {
  237. var unseenIndicies = IndexSet(integersIn: array.indices)
  238. for record in records {
  239. if let index = record["index"] as? Int {
  240. guard array.indices.contains(index) else {
  241. throw ConfigurationError.indexNotFound(index: index)
  242. }
  243. try onExisting(&array[index], record)
  244. unseenIndicies.remove(index)
  245. } else {
  246. array.append(try onNew(record))
  247. }
  248. }
  249. array.remove(atOffsets: unseenIndicies)
  250. }
  251. private func updateIdentifiedElements<T: Identifiable>(_ array: inout [T], with records: [[AnyHashable : Any]], onExisting: @MainActor (inout T, [AnyHashable : Any]) throws -> Void, onNew: @MainActor ([AnyHashable : Any]) throws -> T) throws {
  252. var unseenIndicies = IndexSet(integersIn: array.indices)
  253. for record in records {
  254. if let id = record["id"] as? T.ID {
  255. guard let index = array.enumerated().first(where: { $1.id == id })?.offset else {
  256. throw ConfigurationError.identifierNotFound(id: id)
  257. }
  258. try onExisting(&array[index], record)
  259. unseenIndicies.remove(index)
  260. } else {
  261. array.append(try onNew(record))
  262. }
  263. }
  264. array.remove(atOffsets: unseenIndicies)
  265. }
  266. private func parseQemuDirectoryShareMode(_ value: AEKeyword?) -> QEMUFileShareMode? {
  267. guard let value = value, let parsed = UTMScriptingQemuDirectoryShareMode(rawValue: value) else {
  268. return Optional.none
  269. }
  270. switch parsed {
  271. case .none: return QEMUFileShareMode.none
  272. case .webDAV: return .webdav
  273. case .virtFS: return .virtfs
  274. default: return Optional.none
  275. }
  276. }
  277. private func updateQemuConfiguration(from record: [AnyHashable : Any]) throws {
  278. let config = config as! UTMQemuConfiguration
  279. if let name = record["name"] as? String, !name.isEmpty {
  280. config.information.name = name
  281. }
  282. if let notes = record["notes"] as? String, !notes.isEmpty {
  283. config.information.notes = notes
  284. }
  285. let architecture = record["architecture"] as? String
  286. let arch = QEMUArchitecture(rawValue: architecture ?? "")
  287. let machine = record["machine"] as? String
  288. let target = arch?.targetType.init(rawValue: machine ?? "")
  289. if let arch = arch, arch != config.system.architecture {
  290. let target = target ?? arch.targetType.default
  291. config.system.architecture = arch
  292. config.system.target = target
  293. config.reset(forArchitecture: arch, target: target)
  294. } else if let target = target, target.rawValue != config.system.target.rawValue {
  295. config.system.target = target
  296. config.reset(forArchitecture: config.system.architecture, target: target)
  297. }
  298. if let memory = record["memory"] as? Int, memory != 0 {
  299. config.system.memorySize = memory
  300. }
  301. if let cpuCores = record["cpuCores"] as? Int {
  302. config.system.cpuCount = cpuCores
  303. }
  304. if let hypervisor = record["hypervisor"] as? Bool {
  305. config.qemu.hasHypervisor = hypervisor
  306. }
  307. if let uefi = record["uefi"] as? Bool {
  308. config.qemu.hasUefiBoot = uefi
  309. }
  310. if let directoryShareMode = parseQemuDirectoryShareMode(record["directoryShareMode"] as? AEKeyword) {
  311. config.sharing.directoryShareMode = directoryShareMode
  312. }
  313. if let drives = record["drives"] as? [[AnyHashable : Any]] {
  314. try updateQemuDrives(from: drives)
  315. }
  316. if let networkInterfaces = record["networkInterfaces"] as? [[AnyHashable : Any]] {
  317. try updateQemuNetworks(from: networkInterfaces)
  318. }
  319. if let serialPorts = record["serialPorts"] as? [[AnyHashable : Any]] {
  320. try updateQemuSerials(from: serialPorts)
  321. }
  322. if let qemuAdditionalArguments = record["qemuAdditionalArguments"] as? [[AnyHashable: Any]] {
  323. try updateQemuAdditionalArguments(from: qemuAdditionalArguments)
  324. }
  325. }
  326. private func parseQemuDriveInterface(_ value: AEKeyword?) -> QEMUDriveInterface? {
  327. guard let value = value, let parsed = UTMScriptingQemuDriveInterface(rawValue: value) else {
  328. return Optional.none
  329. }
  330. switch parsed {
  331. case .none: return QEMUDriveInterface.none
  332. case .ide: return .ide
  333. case .scsi: return .scsi
  334. case .sd: return .sd
  335. case .mtd: return .mtd
  336. case .floppy: return .floppy
  337. case .pFlash: return .pflash
  338. case .virtIO: return .virtio
  339. case .nvMe: return .nvme
  340. case .usb: return .usb
  341. default: return Optional.none
  342. }
  343. }
  344. private func updateQemuDrives(from records: [[AnyHashable : Any]]) throws {
  345. let config = config as! UTMQemuConfiguration
  346. try updateIdentifiedElements(&config.drives, with: records, onExisting: updateQemuExistingDrive, onNew: unserializeQemuDriveNew)
  347. }
  348. private func updateQemuExistingDrive(_ drive: inout UTMQemuConfigurationDrive, from record: [AnyHashable : Any]) throws {
  349. if let interface = parseQemuDriveInterface(record["interface"] as? AEKeyword) {
  350. drive.interface = interface
  351. }
  352. if let source = record["source"] as? URL {
  353. drive.imageURL = source
  354. }
  355. }
  356. private func unserializeQemuDriveNew(from record: [AnyHashable : Any]) throws -> UTMQemuConfigurationDrive {
  357. let config = config as! UTMQemuConfiguration
  358. let removable = record["removable"] as? Bool ?? false
  359. var newDrive = UTMQemuConfigurationDrive(forArchitecture: config.system.architecture, target: config.system.target, isExternal: removable)
  360. if let importUrl = record["source"] as? URL {
  361. newDrive.imageURL = importUrl
  362. } else if let size = record["guestSize"] as? Int {
  363. newDrive.sizeMib = size
  364. }
  365. if let interface = parseQemuDriveInterface(record["interface"] as? AEKeyword) {
  366. newDrive.interface = interface
  367. }
  368. if let raw = record["raw"] as? Bool {
  369. newDrive.isRawImage = raw
  370. }
  371. return newDrive
  372. }
  373. private func updateQemuNetworks(from records: [[AnyHashable : Any]]) throws {
  374. let config = config as! UTMQemuConfiguration
  375. try updateElements(&config.networks, with: records, onExisting: updateQemuExistingNetwork, onNew: { record in
  376. guard var newNetwork = UTMQemuConfigurationNetwork(forArchitecture: config.system.architecture, target: config.system.target) else {
  377. throw ConfigurationError.deviceNotSupported
  378. }
  379. try updateQemuExistingNetwork(&newNetwork, from: record)
  380. return newNetwork
  381. })
  382. }
  383. private func parseQemuNetworkMode(_ value: AEKeyword?) -> QEMUNetworkMode? {
  384. guard let value = value, let parsed = UTMScriptingQemuNetworkMode(rawValue: value) else {
  385. return Optional.none
  386. }
  387. switch parsed {
  388. case .emulated: return .emulated
  389. case .shared: return .shared
  390. case .host: return .host
  391. case .bridged: return .bridged
  392. default: return .none
  393. }
  394. }
  395. private func updateQemuExistingNetwork(_ network: inout UTMQemuConfigurationNetwork, from record: [AnyHashable : Any]) throws {
  396. let config = config as! UTMQemuConfiguration
  397. if let hardware = record["hardware"] as? String, let hardware = config.system.architecture.networkDeviceType.init(rawValue: hardware) {
  398. network.hardware = hardware
  399. }
  400. if let mode = parseQemuNetworkMode(record["mode"] as? AEKeyword) {
  401. network.mode = mode
  402. }
  403. if let address = record["address"] as? String, !address.isEmpty {
  404. network.macAddress = address
  405. }
  406. if let interface = record["hostInterface"] as? String, !interface.isEmpty {
  407. network.bridgeInterface = interface
  408. }
  409. if let portForwards = record["portForwards"] as? [[AnyHashable : Any]] {
  410. network.portForward = portForwards.map({ unserializeQemuPortForward(from: $0) })
  411. }
  412. }
  413. private func parseNetworkProtocol(_ value: AEKeyword?) -> QEMUNetworkProtocol? {
  414. guard let value = value, let parsed = UTMScriptingNetworkProtocol(rawValue: value) else {
  415. return Optional.none
  416. }
  417. switch parsed {
  418. case .tcp: return .tcp
  419. case .udp: return .udp
  420. default: return Optional.none
  421. }
  422. }
  423. private func unserializeQemuPortForward(from record: [AnyHashable : Any]) -> UTMQemuConfigurationPortForward {
  424. var forward = UTMQemuConfigurationPortForward()
  425. if let protoc = parseNetworkProtocol(record["protocol"] as? AEKeyword) {
  426. forward.protocol = protoc
  427. }
  428. if let hostAddress = record["hostAddress"] as? String, !hostAddress.isEmpty {
  429. forward.hostAddress = hostAddress
  430. }
  431. if let hostPort = record["hostPort"] as? Int {
  432. forward.hostPort = hostPort
  433. }
  434. if let guestAddress = record["guestAddress"] as? String, !guestAddress.isEmpty {
  435. forward.guestAddress = guestAddress
  436. }
  437. if let guestPort = record["guestPort"] as? Int {
  438. forward.guestPort = guestPort
  439. }
  440. return forward
  441. }
  442. private func updateQemuSerials(from records: [[AnyHashable : Any]]) throws {
  443. let config = config as! UTMQemuConfiguration
  444. try updateElements(&config.serials, with: records, onExisting: updateQemuExistingSerial, onNew: { record in
  445. guard var newSerial = UTMQemuConfigurationSerial(forArchitecture: config.system.architecture, target: config.system.target) else {
  446. throw ConfigurationError.deviceNotSupported
  447. }
  448. try updateQemuExistingSerial(&newSerial, from: record)
  449. return newSerial
  450. })
  451. }
  452. private func parseQemuSerialInterface(_ value: AEKeyword?) -> QEMUSerialMode? {
  453. guard let value = value, let parsed = UTMScriptingSerialInterface(rawValue: value) else {
  454. return Optional.none
  455. }
  456. switch parsed {
  457. case .ptty: return .ptty
  458. case .tcp: return .tcpServer
  459. default: return Optional.none
  460. }
  461. }
  462. private func updateQemuExistingSerial(_ serial: inout UTMQemuConfigurationSerial, from record: [AnyHashable : Any]) throws {
  463. let config = config as! UTMQemuConfiguration
  464. if let hardware = record["hardware"] as? String, let hardware = config.system.architecture.serialDeviceType.init(rawValue: hardware) {
  465. serial.hardware = hardware
  466. }
  467. if let interface = parseQemuSerialInterface(record["interface"] as? AEKeyword) {
  468. serial.mode = interface
  469. }
  470. if let port = record["port"] as? Int {
  471. serial.tcpPort = port
  472. }
  473. }
  474. private func updateQemuAdditionalArguments(from records: [[AnyHashable: Any]]) throws {
  475. let config = config as! UTMQemuConfiguration
  476. let additionalArguments = records.compactMap { record -> QEMUArgument? in
  477. guard let argumentString = record["argumentString"] as? String else { return nil }
  478. var argument = QEMUArgument(argumentString)
  479. // fileUrls are used as required resources by QEMU.
  480. if let fileUrls = record["fileUrls"] as? [URL] {
  481. argument.fileUrls = fileUrls
  482. }
  483. return argument
  484. }
  485. // Update entire additional arguments with new one.
  486. config.qemu.additionalArguments = additionalArguments
  487. }
  488. private func updateAppleConfiguration(from record: [AnyHashable : Any]) throws {
  489. let config = config as! UTMAppleConfiguration
  490. if let name = record["name"] as? String, !name.isEmpty {
  491. config.information.name = name
  492. }
  493. if let notes = record["notes"] as? String, !notes.isEmpty {
  494. config.information.notes = notes
  495. }
  496. if let memory = record["memory"] as? Int, memory != 0 {
  497. config.system.memorySize = memory
  498. }
  499. if let cpuCores = record["cpuCores"] as? Int {
  500. config.system.cpuCount = cpuCores
  501. }
  502. if let directoryShares = record["directoryShares"] as? [[AnyHashable : Any]] {
  503. try updateAppleDirectoryShares(from: directoryShares)
  504. }
  505. if let drives = record["drives"] as? [[AnyHashable : Any]] {
  506. try updateAppleDrives(from: drives)
  507. }
  508. if let networkInterfaces = record["networkInterfaces"] as? [[AnyHashable : Any]] {
  509. try updateAppleNetworks(from: networkInterfaces)
  510. }
  511. if let serialPorts = record["serialPorts"] as? [[AnyHashable : Any]] {
  512. try updateAppleSerials(from: serialPorts)
  513. }
  514. }
  515. private func updateAppleDirectoryShares(from records: [[AnyHashable : Any]]) throws {
  516. let config = config as! UTMAppleConfiguration
  517. try updateElements(&config.sharedDirectories, with: records, onExisting: updateAppleExistingDirectoryShare, onNew: { record in
  518. var newShare = UTMAppleConfigurationSharedDirectory(directoryURL: nil, isReadOnly: false)
  519. try updateAppleExistingDirectoryShare(&newShare, from: record)
  520. return newShare
  521. })
  522. }
  523. private func updateAppleExistingDirectoryShare(_ share: inout UTMAppleConfigurationSharedDirectory, from record: [AnyHashable : Any]) throws {
  524. if let readOnly = record["readOnly"] as? Bool {
  525. share.isReadOnly = readOnly
  526. }
  527. }
  528. private func updateAppleDrives(from records: [[AnyHashable : Any]]) throws {
  529. let config = config as! UTMAppleConfiguration
  530. try updateIdentifiedElements(&config.drives, with: records, onExisting: updateAppleExistingDrive, onNew: unserializeAppleNewDrive)
  531. }
  532. private func updateAppleExistingDrive(_ drive: inout UTMAppleConfigurationDrive, from record: [AnyHashable : Any]) throws {
  533. if let source = record["source"] as? URL {
  534. drive.imageURL = source
  535. }
  536. }
  537. private func unserializeAppleNewDrive(from record: [AnyHashable : Any]) throws -> UTMAppleConfigurationDrive {
  538. let removable = record["removable"] as? Bool ?? false
  539. var newDrive: UTMAppleConfigurationDrive
  540. if let size = record["guestSize"] as? Int {
  541. newDrive = UTMAppleConfigurationDrive(newSize: size)
  542. } else {
  543. newDrive = UTMAppleConfigurationDrive(existingURL: record["source"] as? URL, isExternal: removable)
  544. }
  545. return newDrive
  546. }
  547. private func updateAppleNetworks(from records: [[AnyHashable : Any]]) throws {
  548. let config = config as! UTMAppleConfiguration
  549. try updateElements(&config.networks, with: records, onExisting: updateAppleExistingNetwork, onNew: { record in
  550. var newNetwork = UTMAppleConfigurationNetwork()
  551. try updateAppleExistingNetwork(&newNetwork, from: record)
  552. return newNetwork
  553. })
  554. }
  555. private func parseAppleNetworkMode(_ value: AEKeyword?) -> UTMAppleConfigurationNetwork.NetworkMode? {
  556. guard let value = value, let parsed = UTMScriptingQemuNetworkMode(rawValue: value) else {
  557. return Optional.none
  558. }
  559. switch parsed {
  560. case .shared: return .shared
  561. case .bridged: return .bridged
  562. default: return Optional.none
  563. }
  564. }
  565. private func updateAppleExistingNetwork(_ network: inout UTMAppleConfigurationNetwork, from record: [AnyHashable : Any]) throws {
  566. if let mode = parseAppleNetworkMode(record["mode"] as? AEKeyword) {
  567. network.mode = mode
  568. }
  569. if let address = record["address"] as? String, !address.isEmpty {
  570. network.macAddress = address
  571. }
  572. if let interface = record["hostInterface"] as? String, !interface.isEmpty {
  573. network.bridgeInterface = interface
  574. }
  575. }
  576. private func updateAppleSerials(from records: [[AnyHashable : Any]]) throws {
  577. let config = config as! UTMAppleConfiguration
  578. try updateElements(&config.serials, with: records, onExisting: updateAppleExistingSerial, onNew: { record in
  579. var newSerial = UTMAppleConfigurationSerial()
  580. try updateAppleExistingSerial(&newSerial, from: record)
  581. return newSerial
  582. })
  583. }
  584. private func parseAppleSerialInterface(_ value: AEKeyword?) -> UTMAppleConfigurationSerial.SerialMode? {
  585. guard let value = value, let parsed = UTMScriptingSerialInterface(rawValue: value) else {
  586. return Optional.none
  587. }
  588. switch parsed {
  589. case .ptty: return .ptty
  590. default: return Optional.none
  591. }
  592. }
  593. private func updateAppleExistingSerial(_ serial: inout UTMAppleConfigurationSerial, from record: [AnyHashable : Any]) throws {
  594. if let interface = parseAppleSerialInterface(record["interface"] as? AEKeyword) {
  595. serial.mode = interface
  596. }
  597. }
  598. enum ConfigurationError: Error, LocalizedError {
  599. case identifierNotFound(id: any Hashable)
  600. case invalidDriveDescription
  601. case indexNotFound(index: Int)
  602. case deviceNotSupported
  603. var errorDescription: String? {
  604. switch self {
  605. case .identifierNotFound(let id): return String.localizedStringWithFormat(NSLocalizedString("Identifier '%@' cannot be found.", comment: "UTMScriptingConfigImpl"), String(describing: id))
  606. case .invalidDriveDescription: return NSLocalizedString("Drive description is invalid.", comment: "UTMScriptingConfigImpl")
  607. case .indexNotFound(let index): return String.localizedStringWithFormat(NSLocalizedString("Index %lld cannot be found.", comment: "UTMScriptingConfigImpl"), index)
  608. case .deviceNotSupported: return NSLocalizedString("This device is not supported by the target.", comment: "UTMScriptingConfigImpl")
  609. }
  610. }
  611. }
  612. }