2018-11-14 13:22:10 +00:00
|
|
|
// SPDX-License-Identifier: MIT
|
2021-06-17 14:56:46 +00:00
|
|
|
// Copyright © 2018-2021 WireGuard LLC. All Rights Reserved.
|
2018-11-14 13:22:10 +00:00
|
|
|
|
2018-12-22 11:38:55 +00:00
|
|
|
import Foundation
|
2018-11-14 13:22:10 +00:00
|
|
|
|
|
|
|
class ZipImporter {
|
2019-04-08 07:52:06 +00:00
|
|
|
static func importConfigFiles(from url: URL, completion: @escaping (Result<[TunnelConfiguration?], ZipArchiveError>) -> Void) {
|
2018-11-14 13:33:33 +00:00
|
|
|
DispatchQueue.global(qos: .userInitiated).async {
|
2018-12-12 10:31:24 +00:00
|
|
|
var unarchivedFiles: [(fileBaseName: String, contents: Data)]
|
2018-11-14 13:33:33 +00:00
|
|
|
do {
|
|
|
|
unarchivedFiles = try ZipArchive.unarchive(url: url, requiredFileExtensions: ["conf"])
|
2018-12-12 17:40:57 +00:00
|
|
|
for (index, unarchivedFile) in unarchivedFiles.enumerated().reversed() {
|
2018-12-12 10:31:24 +00:00
|
|
|
let fileBaseName = unarchivedFile.fileBaseName
|
|
|
|
let trimmedName = fileBaseName.trimmingCharacters(in: .whitespacesAndNewlines)
|
2018-12-12 18:28:27 +00:00
|
|
|
if !trimmedName.isEmpty {
|
2018-12-12 17:40:57 +00:00
|
|
|
unarchivedFiles[index].fileBaseName = trimmedName
|
2018-11-14 13:33:33 +00:00
|
|
|
} else {
|
2018-12-12 17:40:57 +00:00
|
|
|
unarchivedFiles.remove(at: index)
|
2018-11-14 13:33:33 +00:00
|
|
|
}
|
|
|
|
}
|
2018-11-14 13:22:10 +00:00
|
|
|
|
2018-12-12 18:28:27 +00:00
|
|
|
if unarchivedFiles.isEmpty {
|
2019-04-08 07:52:06 +00:00
|
|
|
throw ZipArchiveError.noTunnelsInZipArchive
|
2018-11-14 13:33:33 +00:00
|
|
|
}
|
2019-04-08 07:52:06 +00:00
|
|
|
} catch let error as ZipArchiveError {
|
2018-12-06 13:35:46 +00:00
|
|
|
DispatchQueue.main.async { completion(.failure(error)) }
|
2018-11-14 13:33:33 +00:00
|
|
|
return
|
2018-12-06 13:35:46 +00:00
|
|
|
} catch {
|
|
|
|
fatalError()
|
2018-11-14 13:22:10 +00:00
|
|
|
}
|
|
|
|
|
2019-03-17 09:28:27 +00:00
|
|
|
unarchivedFiles.sort { TunnelsManager.tunnelNameIsLessThan($0.fileBaseName, $1.fileBaseName) }
|
2018-12-12 18:28:27 +00:00
|
|
|
var configs: [TunnelConfiguration?] = Array(repeating: nil, count: unarchivedFiles.count)
|
2018-12-12 17:40:57 +00:00
|
|
|
for (index, file) in unarchivedFiles.enumerated() {
|
2018-12-12 18:28:27 +00:00
|
|
|
if index > 0 && file == unarchivedFiles[index - 1] {
|
2018-11-14 13:33:33 +00:00
|
|
|
continue
|
|
|
|
}
|
2018-12-21 21:16:09 +00:00
|
|
|
guard let fileContents = String(data: file.contents, encoding: .utf8) else { continue }
|
2018-12-21 23:28:18 +00:00
|
|
|
guard let tunnelConfig = try? TunnelConfiguration(fromWgQuickConfig: fileContents, called: file.fileBaseName) else { continue }
|
2018-12-12 17:40:57 +00:00
|
|
|
configs[index] = tunnelConfig
|
2018-11-14 13:22:10 +00:00
|
|
|
}
|
2018-12-06 13:35:46 +00:00
|
|
|
DispatchQueue.main.async { completion(.success(configs)) }
|
2018-11-14 13:22:10 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|