Logs sideloading-related events with OSLog

This commit is contained in:
Riley Testut
2023-10-18 14:06:10 -05:00
committed by Magesh K
parent 6adf55b4b6
commit 93b6da4855
13 changed files with 161 additions and 22 deletions

View File

@@ -205,7 +205,11 @@ final class AuthenticationOperation: ResultOperation<(ALTTeam, ALTCertificate, A
{
guard !self.isFinished else { return }
print("Finished authenticating with result:", result.error?.localizedDescription ?? "success")
switch result
{
case .failure(let error): Logger.sideload.error("Failed to authenticate account. \(error.localizedDescription, privacy: .public)")
case .success((let team, _, _)): Logger.sideload.notice("Authenticated account for team \(team.identifier, privacy: .public).")
}
let context = DatabaseManager.shared.persistentContainer.newBackgroundContext()
context.perform {
@@ -348,6 +352,8 @@ private extension AuthenticationOperation
if let appleID = Keychain.shared.appleIDEmailAddress, let password = Keychain.shared.appleIDPassword
{
Logger.sideload.notice("Authenticating Apple ID...")
self.authenticate(appleID: appleID, password: password) { (result) in
switch result
{

View File

@@ -114,7 +114,7 @@ final class BackgroundRefreshAppsOperation: ResultOperation<[String: Result<Inst
}
self.managedObjectContext.perform {
print("Apps to refresh:", self.installedApps.map(\.bundleIdentifier))
Logger.sideload.notice("Refreshing apps in background: \(self.installedApps.map(\.bundleIdentifier), privacy: .public)")
self.startListeningForRunningApps()
@@ -125,7 +125,10 @@ final class BackgroundRefreshAppsOperation: ResultOperation<[String: Result<Inst
self.managedObjectContext.perform {
let filteredApps = self.installedApps.filter { !self.runningApplications.contains($0.bundleIdentifier) }
print("Filtered Apps to Refresh:", filteredApps.map { $0.bundleIdentifier })
if !self.runningApplications.isEmpty
{
Logger.sideload.notice("Skipping refreshing running apps: \(self.runningApplications, privacy: .public)")
}
let group = AppManager.shared.refresh(filteredApps, presentingViewController: nil)
group.beginInstallationHandler = { (installedApp) in
@@ -235,6 +238,8 @@ private extension BackgroundRefreshAppsOperation
{
print("Failed to refresh apps in background.", error)
Logger.sideload.error("Failed to refresh apps in background. \(error.localizedDescription, privacy: .public)")
content.title = NSLocalizedString("Failed to Refresh Apps", comment: "")
content.body = error.localizedDescription
}
@@ -275,7 +280,7 @@ private extension BackgroundRefreshAppsOperation
_ = RefreshAttempt(identifier: self.refreshIdentifier, result: result, context: context)
do { try context.save() }
catch { print("Failed to save refresh attempt.", error) }
catch { Logger.sideload.error("Failed to save refresh attempt. \(error.localizedDescription, privacy: .public)") }
}
}

View File

@@ -88,8 +88,8 @@ class BackupAppOperation: ResultOperation<Void>
// Failed too quickly for human to respond to alert, possibly still finalizing installation.
// Try again in a couple seconds.
print("Failed too quickly, retrying after a few seconds...")
Logger.sideload.error("Failed to open app too quickly, retrying after a few seconds...")
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
UIApplication.shared.open(openURL, options: [:]) { (success) in
if success

View File

@@ -51,6 +51,10 @@ final class DownloadAppOperation: ResultOperation<ALTApplication>
print("Downloading App:", self.bundleIdentifier)
Logger.sideload.notice("Downloading app \(self.bundleIdentifier, privacy: .public)...")
// Set _after_ checking self.context.error to prevent overwriting localized failure for previous errors.
self.localizedFailure = String(format: NSLocalizedString("%@ could not be downloaded.", comment: ""), self.appName)
guard let storeApp = self.app as? StoreApp else {
@@ -100,6 +104,7 @@ final class DownloadAppOperation: ResultOperation<ALTApplication>
try FileManager.default.removeItem(at: self.temporaryDirectory)
} catch {
print("Failed to remove DownloadAppOperation temporary directory: \(self.temporaryDirectory).", error)
Logger.sideload.error("Failed to remove DownloadAppOperation temporary directory: \(self.temporaryDirectory, privacy: .public). \(error.localizedDescription, privacy: .public)")
}
super.finish(result)
}
@@ -156,6 +161,9 @@ private extension DownloadAppOperation {
try FileManager.default.copyItem(at: application.fileURL, to: self.destinationURL, shouldReplace: true)
guard let copiedApplication = ALTApplication(fileURL: self.destinationURL) else { throw OperationError.invalidApp }
Logger.sideload.notice("Downloaded app \(copiedApplication.bundleIdentifier, privacy: .public) from \(sourceURL, privacy: .public)")
self.finish(.success(copiedApplication))
self.progress.completedUnitCount += 1

View File

@@ -47,7 +47,9 @@ final class FetchProvisioningProfilesOperation: ResultOperation<[String: ALTProv
return self.finish(.failure(OperationError.invalidParameters("FetchProvisioningProfilesOperation.main: self.context.team or self.context.session is nil"))) }
guard let app = self.context.app else { return self.finish(.failure(OperationError.appNotFound(name: nil))) }
Logger.sideload.notice("Fetching provisioning profiles for app \(self.context.bundleIdentifier, privacy: .public)...")
self.progress.totalUnitCount = Int64(1 + app.appExtensions.count)
self.prepareProvisioningProfile(for: app, parentApp: nil, team: team, session: session) { (result) in
@@ -246,6 +248,8 @@ extension FetchProvisioningProfilesOperation
if let appID = appIDs.first(where: { $0.bundleIdentifier.lowercased() == bundleIdentifier.lowercased() })
{
Logger.sideload.notice("Using existing App ID \(appID.bundleIdentifier, privacy: .public)")
completionHandler(.success(appID))
}
else
@@ -285,6 +289,9 @@ extension FetchProvisioningProfilesOperation
do
{
let appID = try Result(appID, error).get()
Logger.sideload.notice("Registered new App ID \(appID.bundleIdentifier, privacy: .public)")
completionHandler(.success(appID))
}
catch ALTAppleAPIError.maximumAppIDLimitReached
@@ -383,8 +390,15 @@ extension FetchProvisioningProfilesOperation
let appID = appID.copy() as! ALTAppID
appID.features = features
ALTAppleAPI.shared.update(appID, team: team, session: session) { (appID, error) in
completionHandler(Result(appID, error))
ALTAppleAPI.shared.update(appID, team: team, session: session) { (updatedAppID, error) in
let result = Result(updatedAppID, error)
switch result
{
case .success(let appID): Logger.sideload.notice("Updated features for App ID \(appID.bundleIdentifier, privacy: .public).")
case .failure(let error): Logger.sideload.error("Failed to update features for App ID \(appID.bundleIdentifier, privacy: .public). \(error.localizedDescription, privacy: .public)")
}
completionHandler(result)
}
}
else
@@ -402,6 +416,7 @@ extension FetchProvisioningProfilesOperation
}
guard var applicationGroups = entitlements[.appGroups] as? [String], !applicationGroups.isEmpty else {
Logger.sideload.notice("App ID \(appID.bundleIdentifier, privacy: .public) has no app groups, skipping assignment.")
// Assigning an App ID to an empty app group array fails,
// so just do nothing if there are no app groups.
return completionHandler(.success(appID))
@@ -459,7 +474,10 @@ extension FetchProvisioningProfilesOperation
ALTAppleAPI.shared.fetchAppGroups(for: team, session: session) { (groups, error) in
switch Result(groups, error)
{
case .failure(let error): finish(.failure(error))
case .failure(let error):
Logger.sideload.error("Failed to fetch app groups for team \(team.identifier, privacy: .public). \(error.localizedDescription, privacy: .public)")
finish(.failure(error))
case .success(let fetchedGroups):
let dispatchGroup = DispatchGroup()
@@ -484,8 +502,13 @@ extension FetchProvisioningProfilesOperation
ALTAppleAPI.shared.addAppGroup(withName: name, groupIdentifier: adjustedGroupIdentifier, team: team, session: session) { (group, error) in
switch Result(group, error)
{
case .success(let group): groups.append(group)
case .failure(let error): errors.append(error)
case .success(let group):
Logger.sideload.notice("Created new App Group \(group.groupIdentifier, privacy: .public).")
groups.append(group)
case .failure(let error):
Logger.sideload.notice("Failed to create new App Group \(adjustedGroupIdentifier, privacy: .public). \(error.localizedDescription, privacy: .public)")
errors.append(error)
}
dispatchGroup.leave()
@@ -501,8 +524,17 @@ extension FetchProvisioningProfilesOperation
else
{
ALTAppleAPI.shared.assign(appID, to: Array(groups), team: team, session: session) { (success, error) in
let result = Result(success, error)
finish(result.map { _ in appID })
let groupIDs = groups.map { $0.groupIdentifier }
switch Result(success, error)
{
case .success:
Logger.sideload.notice("Assigned App ID \(appID.bundleIdentifier, privacy: .public) to App Groups \(groupIDs.description, privacy: .public).")
finish(.success(appID))
case .failure(let error):
Logger.sideload.error("Failed to assign App ID \(appID.bundleIdentifier, privacy: .public) to App Groups \(groupIDs.description, privacy: .public). \(error.localizedDescription, privacy: .public)")
finish(.failure(error))
}
}
}
}
@@ -529,6 +561,8 @@ extension FetchProvisioningProfilesOperation
completionHandler(.success(profile))
case .success:
Logger.sideload.notice("Generating new free provisioning profile for App ID \(appID.bundleIdentifier, privacy: .public).")
// Fetch new provisioning profile
ALTAppleAPI.shared.fetchProvisioningProfile(for: appID, deviceType: .iphone, team: team, session: session) { (profile, error) in
completionHandler(Result(profile, error))

View File

@@ -47,6 +47,8 @@ final class InstallAppOperation: ResultOperation<InstalledApp>
return self.finish(.failure(OperationError.invalidParameters("InstallAppOperation.main: self.context.certificate or self.context.resignedApp or self.context.provisioningProfiles is nil")))
}
Logger.sideload.notice("Installing resigned app \(resignedApp.bundleIdentifier, privacy: .public)...")
@Managed var appVersion = self.context.appVersion
let storeBuildVersion = $appVersion.buildVersion
@@ -255,6 +257,7 @@ final class InstallAppOperation: ResultOperation<InstalledApp>
catch
{
print("Failed to remove refreshed .ipa: \(error)")
Logger.sideload.error("Failed to remove refreshed .ipa: \(error.localizedDescription, privacy: .public)")
}
}
@@ -264,6 +267,43 @@ final class InstallAppOperation: ResultOperation<InstalledApp>
private extension InstallAppOperation
{
func receive(from connection: ServerConnection, completionHandler: @escaping (Result<Void, Error>) -> Void)
{
connection.receiveResponse() { (result) in
do
{
let response = try result.get()
switch response
{
case .installationProgress(let response):
Logger.sideload.debug("Installing \(self.context.resignedApp?.bundleIdentifier ?? self.context.bundleIdentifier, privacy: .public)... \((response.progress * 100).rounded())%")
if response.progress == 1.0
{
self.progress.completedUnitCount = self.progress.totalUnitCount
completionHandler(.success(()))
}
else
{
self.progress.completedUnitCount = Int64(response.progress * 100)
self.receive(from: connection, completionHandler: completionHandler)
}
case .error(let response):
completionHandler(.failure(response.error))
default:
completionHandler(.failure(ALTServerError(.unknownRequest)))
}
}
catch
{
completionHandler(.failure(ALTServerError(error)))
}
}
}
func cleanUp()
{
guard !self.didCleanUp else { return }
@@ -275,7 +315,7 @@ private extension InstallAppOperation
}
catch
{
print("Failed to remove temporary directory.", error)
Logger.sideload.error("Failed to remove temporary directory: \(error.localizedDescription, privacy: .public)")
}
}
}

View File

@@ -8,6 +8,8 @@
import Foundation
import AltStoreCore
@objc(RemoveAppBackupOperation)
final class RemoveAppBackupOperation: ResultOperation<Void>
{
@@ -63,14 +65,14 @@ final class RemoveAppBackupOperation: ResultOperation<Void>
#else
print("Failed to remove app backup directory:", error)
Logger.sideload.error("Failed to remove app backup directory \(backupDirectoryURL.lastPathComponent, privacy: .public). \(error.localizedDescription, privacy: .public)")
self.finish(.failure(error))
#endif
}
catch
{
print("Failed to remove app backup directory:", error)
Logger.sideload.error("Failed to remove app backup directory \(backupDirectoryURL.lastPathComponent, privacy: .public). \(error.localizedDescription, privacy: .public)")
self.finish(.failure(error))
}
}

View File

@@ -37,6 +37,8 @@ final class RemoveAppOperation: ResultOperation<InstalledApp>
return self.finish(.failure(OperationError.invalidParameters("RemoveAppOperation.main: self.context.installedApp is nil")))
}
Logger.sideload.notice("Removing app \(self.context.bundleIdentifier, privacy: .public)...")
installedApp.managedObjectContext?.perform {
let resignedBundleIdentifier = installedApp.resignedBundleIdentifier

View File

@@ -49,6 +49,8 @@ final class ResignAppOperation: ResultOperation<ALTApplication>
"self.context.certificate is nil")))
}
Logger.sideload.notice("Resigning app \(self.context.bundleIdentifier, privacy: .public)...")
// Prepare app bundle
let prepareAppProgress = Progress.discreteProgress(totalUnitCount: 2)
self.progress.addChild(prepareAppProgress, withPendingUnitCount: 3)
@@ -56,8 +58,6 @@ final class ResignAppOperation: ResultOperation<ALTApplication>
let prepareAppBundleProgress = self.prepareAppBundle(for: app, profiles: profiles) { (result) in
guard let appBundleURL = self.process(result) else { return }
print("Resigning App:", self.context.bundleIdentifier)
// Resign app bundle
let resignProgress = self.resignAppBundle(at: appBundleURL, team: team, certificate: certificate, profiles: Array(profiles.values)) { (result) in
guard let resignedURL = self.process(result) else { return }
@@ -71,6 +71,9 @@ final class ResignAppOperation: ResultOperation<ALTApplication>
// Use appBundleURL since we need an app bundle, not .ipa.
guard let resignedApplication = ALTApplication(fileURL: appBundleURL) else { throw OperationError.invalidApp }
Logger.sideload.notice("Resigned app \(self.context.bundleIdentifier, privacy: .public) to \(resignedApplication.bundleIdentifier, privacy: .public).")
self.finish(.success(resignedApplication))
}
catch

View File

@@ -40,6 +40,8 @@ final class SendAppOperation: ResultOperation<()>
return self.finish(.failure(OperationError.invalidParameters("SendAppOperation.main: self.resignedApp is nil")))
}
Logger.sideload.notice("Sending app \(self.context.bundleIdentifier, privacy: .public) to AltServer \(server.localizedName ?? "nil", privacy: .public)...")
// self.context.resignedApp.fileURL points to the app bundle, but we want the .ipa.
let app = AnyApp(name: resignedApp.name, bundleIdentifier: self.context.bundleIdentifier, url: resignedApp.fileURL)
let fileURL = InstalledApp.refreshedIPAURL(for: app)

View File

@@ -233,9 +233,9 @@ private extension VerifyAppOperation
let data = try Data(contentsOf: ipaURL)
let sha256Hash = SHA256.hash(data: data)
let hashString = sha256Hash.compactMap { String(format: "%02x", $0) }.joined()
print("[ALTLog] Comparing app hash (\(hashString)) against expected hash (\(expectedHash))...")
Logger.sideload.debug("Comparing app hash (\(hashString, privacy: .public)) against expected hash (\(expectedHash, privacy: .public))...")
guard hashString == expectedHash else { throw VerificationError.mismatchedHash(hashString, expectedHash: expectedHash, app: app) }
}