From b9d113924ec2861ab7779811f62c91d9d5a6f873 Mon Sep 17 00:00:00 2001 From: Zorg Date: Sat, 7 Jan 2017 10:49:42 -0500 Subject: [PATCH] Upgrade SULog to use logging APIs that Apple provides built in With this change, we ensure distinct per-app, per-process logging. Note that the global file ~/Library/Logs/SparkleUpdateLog.log is no longer written into. On 10.12 and above, SULog uses the os_log APIs. You may want to use log(1) to view logs in addition to Console.app. See the WWDC video on the new logging API and how the Console app has changed. On older systems, this uses ASL (Apple System Log). We don't want to reinvent logging, or rely on 3rd party libraries, thus we use what the system provides to us. Two logging levels were added: Default and Error. The code documents their intended purpose. Now when you call SULog you must make a decision which level to use rather than rely on an implicit level. --- Sparkle.xcodeproj/project.pbxproj | 2 + Sparkle/Autoupdate/Autoupdate.m | 12 +-- Sparkle/SUAppcast.m | 2 +- Sparkle/SUAppcastItem.m | 6 +- Sparkle/SUBasicUpdateDriver.m | 8 +- Sparkle/SUBinaryDeltaUnarchiver.m | 2 +- Sparkle/SUCodeSigningVerifier.m | 14 +-- Sparkle/SUDSAVerifier.m | 18 ++-- Sparkle/SUDiskImageUnarchiver.m | 12 +-- Sparkle/SUHost.m | 2 +- Sparkle/SUInstaller.m | 2 +- Sparkle/SULog.h | 43 ++++---- Sparkle/SULog.m | 172 ++++++++++++++++++------------ Sparkle/SUPackageInstaller.m | 2 +- Sparkle/SUPipedUnarchiver.m | 2 +- Sparkle/SUPlainInstaller.m | 20 ++-- Sparkle/SUUpdateAlert.m | 2 +- Sparkle/SUUpdateDriver.m | 2 +- Sparkle/SUUpdateValidator.m | 26 ++--- Sparkle/SUUpdater.m | 6 +- 20 files changed, 195 insertions(+), 160 deletions(-) diff --git a/Sparkle.xcodeproj/project.pbxproj b/Sparkle.xcodeproj/project.pbxproj index e83078b9..13ac27fe 100644 --- a/Sparkle.xcodeproj/project.pbxproj +++ b/Sparkle.xcodeproj/project.pbxproj @@ -229,6 +229,7 @@ 723B252E1CEAB3A600909873 /* bscommon.c in Sources */ = {isa = PBXBuildFile; fileRef = 723B252B1CEAB3A600909873 /* bscommon.c */; }; 723B252F1CEAB3A600909873 /* bscommon.c in Sources */ = {isa = PBXBuildFile; fileRef = 723B252B1CEAB3A600909873 /* bscommon.c */; }; 723B25301CEAB3A600909873 /* bscommon.h in Headers */ = {isa = PBXBuildFile; fileRef = 723B252C1CEAB3A600909873 /* bscommon.h */; }; + 72464F7D1E213ED400FB341C /* SUOperatingSystem.m in Sources */ = {isa = PBXBuildFile; fileRef = 726F2CE41BC9C33D001971A4 /* SUOperatingSystem.m */; }; 72544FFC1D0991A4000CFB2C /* SUFileOperationConstants.m in Sources */ = {isa = PBXBuildFile; fileRef = 722954C31D04E66F00ECF9CA /* SUFileOperationConstants.m */; }; 7268AC631AD634C200C3E0C1 /* SUBinaryDeltaCreate.m in Sources */ = {isa = PBXBuildFile; fileRef = 7268AC621AD634C200C3E0C1 /* SUBinaryDeltaCreate.m */; }; 726F2CDE1BC9BE5B001971A4 /* SUFileManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 7275F9C01B5F1F2900B1D19E /* SUFileManager.m */; }; @@ -1868,6 +1869,7 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + 72464F7D1E213ED400FB341C /* SUOperatingSystem.m in Sources */, 5AE13FA01E0D4F65000D2C2C /* Appcast.swift in Sources */, 5AAD00521E0BE6BE00AF411E /* ArchiveItem.swift in Sources */, 5AAD00681E0C2DAB00AF411E /* bscommon.c in Sources */, diff --git a/Sparkle/Autoupdate/Autoupdate.m b/Sparkle/Autoupdate/Autoupdate.m index 1a8834b4..06099eae 100644 --- a/Sparkle/Autoupdate/Autoupdate.m +++ b/Sparkle/Autoupdate/Autoupdate.m @@ -173,13 +173,13 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.5; NSString *fileOperationToolPath = [[[[NSBundle mainBundle] executablePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@""SPARKLE_FILEOP_TOOL_NAME]; if (![[NSFileManager defaultManager] fileExistsAtPath:fileOperationToolPath]) { - SULog(@"Potential Installation Error: File operation tool path %@ is not found", fileOperationToolPath); + SULog(SULogLevelError, @"Potential Installation Error: File operation tool path %@ is not found", fileOperationToolPath); } NSError *retrieveInstallerError = nil; id installer = [SUInstaller installerForHost:host fileOperationToolPath:fileOperationToolPath updateDirectory:self.updateFolderPath error:&retrieveInstallerError]; if (installer == nil) { - SULog(@"Retrieved Installer Error: %@", retrieveInstallerError); + SULog(SULogLevelError, @"Retrieved Installer Error: %@", retrieveInstallerError); exit(EXIT_FAILURE); } @@ -194,7 +194,7 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.5; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSError *initialInstallationError = nil; if (![installer performInitialInstallation:&initialInstallationError]) { - SULog(@"Failed to perform initial installation with error: %@", initialInstallationError); + SULog(SULogLevelError, @"Failed to perform initial installation with error: %@", initialInstallationError); dispatch_async(dispatch_get_main_queue(), ^{ [self showError:initialInstallationError]; exit(EXIT_FAILURE); @@ -207,7 +207,7 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.5; NSError *underlyingError = [finalInstallationError.userInfo objectForKey:NSUnderlyingErrorKey]; dispatch_async(dispatch_get_main_queue(), ^{ if (underlyingError == nil || underlyingError.code != SUInstallationCancelledError) { - SULog(@"Failed to perform final installation Error: %@", finalInstallationError); + SULog(SULogLevelError, @"Failed to perform final installation Error: %@", finalInstallationError); [self showError:finalInstallationError]; } exit(EXIT_FAILURE); @@ -238,7 +238,7 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.5; dispatch_block_t cleanupAndExit = ^{ NSError *theError = nil; if (![[NSFileManager defaultManager] removeItemAtPath:self.updateFolderPath error:&theError]) { - SULog(@"Couldn't remove update folder: %@.", theError); + SULog(SULogLevelError, @"Couldn't remove update folder: %@.", theError); } [[NSFileManager defaultManager] removeItemAtPath:[[NSBundle mainBundle] bundlePath] error:NULL]; @@ -254,7 +254,7 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.5; // Don't use -launchApplication: because we may not be launching an application. Eg: it could be a system prefpane if (![[NSWorkspace sharedWorkspace] openFile:relaunchPath]) { - SULog(@"Failed to launch %@", relaunchPath); + SULog(SULogLevelError, @"Failed to launch %@", relaunchPath); } [self.statusController close]; diff --git a/Sparkle/SUAppcast.m b/Sparkle/SUAppcast.m index 8873854a..e76fc5c8 100644 --- a/Sparkle/SUAppcast.m +++ b/Sparkle/SUAppcast.m @@ -242,7 +242,7 @@ [appcastItems addObject:anItem]; } else { - SULog(@"Sparkle Updater: Failed to parse appcast item: %@.\nAppcast dictionary was: %@", errString, dict); + SULog(SULogLevelError, @"Sparkle Updater: Failed to parse appcast item: %@.\nAppcast dictionary was: %@", errString, dict); if (errorp) *errorp = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAppcastParseError userInfo:@{NSLocalizedDescriptionKey: errString}]; diff --git a/Sparkle/SUAppcastItem.m b/Sparkle/SUAppcastItem.m index 164b5bad..b30c970a 100644 --- a/Sparkle/SUAppcastItem.m +++ b/Sparkle/SUAppcastItem.m @@ -83,7 +83,7 @@ } if (newVersion == nil) // no sparkle:version attribute anywhere? { - SULog(@"warning: <%@> for URL '%@' is missing %@ attribute. Version comparison may be unreliable. Please always specify %@", SURSSElementEnclosure, [enclosure objectForKey:SURSSAttributeURL], SUAppcastAttributeVersion, SUAppcastAttributeVersion); + SULog(SULogLevelError, @"warning: <%@> for URL '%@' is missing %@ attribute. Version comparison may be unreliable. Please always specify %@", SURSSElementEnclosure, [enclosure objectForKey:SURSSAttributeURL], SUAppcastAttributeVersion, SUAppcastAttributeVersion); // Separate the url by underscores and take the last component, as that'll be closest to the end, // then we remove the extension. Hopefully, this will be the version. @@ -108,7 +108,7 @@ NSString *theInfoURL = [dict objectForKey:SURSSElementLink]; if (theInfoURL) { if (![theInfoURL isKindOfClass:[NSString class]]) { - SULog(@"%@ -%@ Info URL is not of valid type.", NSStringFromClass([self class]), NSStringFromSelector(_cmd)); + SULog(SULogLevelError, @"%@ -%@ Info URL is not of valid type.", NSStringFromClass([self class]), NSStringFromSelector(_cmd)); } else { self.infoURL = [NSURL URLWithString:theInfoURL]; } @@ -169,7 +169,7 @@ if (releaseNotesString) { NSURL *url = [NSURL URLWithString:releaseNotesString]; if ([url isFileURL]) { - SULog(@"Release notes with file:// URLs are not supported"); + SULog(SULogLevelError, @"Release notes with file:// URLs are not supported"); } else { self.releaseNotesURL = url; } diff --git a/Sparkle/SUBasicUpdateDriver.m b/Sparkle/SUBasicUpdateDriver.m index 54489936..358c0d6a 100644 --- a/Sparkle/SUBasicUpdateDriver.m +++ b/Sparkle/SUBasicUpdateDriver.m @@ -237,7 +237,7 @@ cachePath = [cachePaths objectAtIndex:0]; } if (!cachePath) { - SULog(@"Failed to find user's cache directory! Using system default"); + SULog(SULogLevelError, @"Failed to find user's cache directory! Using system default"); cachePath = NSTemporaryDirectory(); } @@ -344,7 +344,7 @@ BOOL success; if (!unarchiver) { - SULog(@"Error: No valid unarchiver for %@!", self.downloadPath); + SULog(SULogLevelError, @"Error: No valid unarchiver for %@!", self.downloadPath); success = NO; } else { @@ -514,7 +514,7 @@ // Perhaps in a sandboxed environment this matters more. Note that this may not be a fatal error. NSError *quarantineError = nil; if (![fileManager releaseItemFromQuarantineAtRootURL:relaunchCopyTargetURL error:&quarantineError]) { - SULog(@"Failed to release quarantine on %@ with error %@", relaunchCopyTargetPath, quarantineError); + SULog(SULogLevelError, @"Failed to release quarantine on %@ with error %@", relaunchCopyTargetPath, quarantineError); } } } @@ -606,7 +606,7 @@ NSError *errorToDisplay = error; int finiteRecursion=5; do { - SULog(@"Error: %@ %@ (URL %@)", errorToDisplay.localizedDescription, errorToDisplay.localizedFailureReason, [errorToDisplay.userInfo objectForKey:NSURLErrorFailingURLErrorKey]); + SULog(SULogLevelError, @"Error: %@ %@ (URL %@)", errorToDisplay.localizedDescription, errorToDisplay.localizedFailureReason, [errorToDisplay.userInfo objectForKey:NSURLErrorFailingURLErrorKey]); errorToDisplay = [errorToDisplay.userInfo objectForKey:NSUnderlyingErrorKey]; } while(--finiteRecursion && errorToDisplay); } diff --git a/Sparkle/SUBinaryDeltaUnarchiver.m b/Sparkle/SUBinaryDeltaUnarchiver.m index 6dc2a666..3863ce10 100644 --- a/Sparkle/SUBinaryDeltaUnarchiver.m +++ b/Sparkle/SUBinaryDeltaUnarchiver.m @@ -64,7 +64,7 @@ for (NSURL *file in filesToUpdate) { NSError *error = nil; if (![fileManager updateModificationAndAccessTimeOfItemAtURL:file error:&error]) { - SULog(@"Error: During delta unarchiving, failed to touch %@", error); + SULog(SULogLevelError, @"Error: During delta unarchiving, failed to touch %@", error); } } } diff --git a/Sparkle/SUCodeSigningVerifier.m b/Sparkle/SUCodeSigningVerifier.m index 1da556f2..6f4da51d 100644 --- a/Sparkle/SUCodeSigningVerifier.m +++ b/Sparkle/SUCodeSigningVerifier.m @@ -31,13 +31,13 @@ result = SecCodeCopyDesignatedRequirement(oldCode, kSecCSDefaultFlags, &requirement); if (result != noErr) { - SULog(@"Failed to copy designated requirement. Code Signing OSStatus code: %d", result); + SULog(SULogLevelError, @"Failed to copy designated requirement. Code Signing OSStatus code: %d", result); goto finally; } result = SecStaticCodeCreateWithPath((__bridge CFURLRef)newBundleURL, kSecCSDefaultFlags, &staticCode); if (result != noErr) { - SULog(@"Failed to get static code %d", result); + SULog(SULogLevelError, @"Failed to get static code %d", result); goto finally; } @@ -55,12 +55,12 @@ if (result != noErr) { if (result == errSecCSUnsigned) { - SULog(@"The host app is signed, but the new version of the app is not signed using Apple Code Signing. Please ensure that the new app is signed and that archiving did not corrupt the signature."); + SULog(SULogLevelError, @"The host app is signed, but the new version of the app is not signed using Apple Code Signing. Please ensure that the new app is signed and that archiving did not corrupt the signature."); } if (result == errSecCSReqFailed) { CFStringRef requirementString = nil; if (SecRequirementCopyString(requirement, kSecCSDefaultFlags, &requirementString) == noErr) { - SULog(@"Code signature of the new version doesn't match the old version: %@. Please ensure that old and new app is signed using exactly the same certificate.", requirementString); + SULog(SULogLevelError, @"Code signature of the new version doesn't match the old version: %@. Please ensure that old and new app is signed using exactly the same certificate.", requirementString); CFRelease(requirementString); } @@ -87,7 +87,7 @@ finally: result = SecStaticCodeCreateWithPath((__bridge CFURLRef)bundleURL, kSecCSDefaultFlags, &staticCode); if (result != noErr) { - SULog(@"Failed to get static code %d", result); + SULog(SULogLevelError, @"Failed to get static code %d", result); goto finally; } @@ -102,7 +102,7 @@ finally: if (result != noErr) { if (result == errSecCSUnsigned) { - SULog(@"Error: The app is not signed using Apple Code Signing. %@", bundleURL); + SULog(SULogLevelError, @"Error: The app is not signed using Apple Code Signing. %@", bundleURL); } if (result == errSecCSReqFailed) { [self logSigningInfoForCode:staticCode label:@"new info"]; @@ -130,7 +130,7 @@ static id valueOrNSNull(id value) { NSDictionary *infoPlist = [signingDict objectForKey:@"info-plist"]; [relevantInfo setObject:valueOrNSNull([infoPlist objectForKey:@"CFBundleShortVersionString"]) forKey:@"version"]; [relevantInfo setObject:valueOrNSNull([infoPlist objectForKey:(__bridge NSString *)kCFBundleVersionKey]) forKey:@"build"]; - SULog(@"%@: %@", label, relevantInfo); + SULog(SULogLevelDefault, @"%@: %@", label, relevantInfo); } } diff --git a/Sparkle/SUDSAVerifier.m b/Sparkle/SUDSAVerifier.m index fa5f9934..9f959f05 100644 --- a/Sparkle/SUDSAVerifier.m +++ b/Sparkle/SUDSAVerifier.m @@ -23,7 +23,7 @@ + (BOOL)validatePath:(NSString *)path withEncodedDSASignature:(NSString *)encodedSignature withPublicDSAKey:(NSString *)pkeyString { if (!encodedSignature) { - SULog(@"There is no DSA signature to check"); + SULog(SULogLevelError, @"There is no DSA signature to check"); return NO; } @@ -47,7 +47,7 @@ self = [super init]; if (!self || !data.length) { - SULog(@"Could not read public DSA key"); + SULog(SULogLevelError, @"Could not read public DSA key"); return nil; } @@ -60,7 +60,7 @@ if (items) { CFRelease(items); } - SULog(@"Public DSA key could not be imported: %d", status); + SULog(SULogLevelError, @"Public DSA key could not be imported: %d", status); return nil; } @@ -118,7 +118,7 @@ dataReadTransform = SecTransformCreateReadTransformWithReadStream((__bridge CFReadStreamRef)stream); if (!dataReadTransform) { - SULog(@"File containing update archive could not be read (failed to create SecTransform for input stream)"); + SULog(SULogLevelError, @"File containing update archive could not be read (failed to create SecTransform for input stream)"); return cleanup(); } @@ -132,30 +132,30 @@ dataVerifyTransform = SecVerifyTransformCreate(_secKey, (__bridge CFDataRef)signature, &error); #pragma clang diagnostic pop if (!dataVerifyTransform || error) { - SULog(@"Could not understand format of the signature: %@; Signature data: %@", error, signature); + SULog(SULogLevelError, @"Could not understand format of the signature: %@; Signature data: %@", error, signature); return cleanup(); } SecTransformConnectTransforms(dataReadTransform, kSecTransformOutputAttributeName, dataDigestTransform, kSecTransformInputAttributeName, group, &error); if (error) { - SULog(@"%@", error); + SULog(SULogLevelError, @"%@", error); return cleanup(); } SecTransformConnectTransforms(dataDigestTransform, kSecTransformOutputAttributeName, dataVerifyTransform, kSecTransformInputAttributeName, group, &error); if (error) { - SULog(@"%@", error); + SULog(SULogLevelError, @"%@", error); return cleanup(); } NSNumber *result = CFBridgingRelease(SecTransformExecute(group, &error)); if (error) { - SULog(@"DSA signature verification failed: %@", error); + SULog(SULogLevelError, @"DSA signature verification failed: %@", error); return cleanup(); } if (!result.boolValue) { - SULog(@"DSA signature does not match. Data of the update file being checked is different than data that has been signed, or the public key and the private key are not from the same set."); + SULog(SULogLevelError, @"DSA signature does not match. Data of the update file being checked is different than data that has been signed, or the public key and the private key are not from the same set."); } cleanup(); diff --git a/Sparkle/SUDiskImageUnarchiver.m b/Sparkle/SUDiskImageUnarchiver.m index 60f59780..c2207076 100644 --- a/Sparkle/SUDiskImageUnarchiver.m +++ b/Sparkle/SUDiskImageUnarchiver.m @@ -135,7 +135,7 @@ if (taskResult != 0) { NSString *resultStr = output ? [[NSString alloc] initWithData:output encoding:NSUTF8StringEncoding] : nil; - SULog(@"hdiutil failed with code: %ld data: <<%@>>", (long)taskResult, resultStr); + SULog(SULogLevelError, @"hdiutil failed with code: %ld data: <<%@>>", (long)taskResult, resultStr); goto reportError; } mountedSuccessfully = YES; @@ -145,7 +145,7 @@ contents = [manager contentsOfDirectoryAtPath:mountPoint error:&error]; if (error) { - SULog(@"Couldn't enumerate contents of archive mounted at %@: %@", mountPoint, error); + SULog(SULogLevelError, @"Couldn't enumerate contents of archive mounted at %@: %@", mountPoint, error); goto reportError; } @@ -164,7 +164,7 @@ itemsCopied += 1.0; [notifier notifyProgress:0.5 + itemsCopied/(totalItems*2.0)]; - SULog(@"copyItemAtPath:%@ toPath:%@", fromPath, toPath); + SULog(SULogLevelDefault, @"copyItemAtPath:%@ toPath:%@", fromPath, toPath); if (![manager copyItemAtPath:fromPath toPath:toPath error:&error]) { @@ -189,11 +189,11 @@ @try { [task launch]; } @catch (NSException *exception) { - SULog(@"Failed to unmount %@", mountPoint); - SULog(@"Exception: %@", exception); + SULog(SULogLevelError, @"Failed to unmount %@", mountPoint); + SULog(SULogLevelError, @"Exception: %@", exception); } } else { - SULog(@"Can't mount DMG %@", self.archivePath); + SULog(SULogLevelError, @"Can't mount DMG %@", self.archivePath); } } } diff --git a/Sparkle/SUHost.m b/Sparkle/SUHost.m index 8470ae22..19abc204 100644 --- a/Sparkle/SUHost.m +++ b/Sparkle/SUHost.m @@ -38,7 +38,7 @@ NSParameterAssert(aBundle); self.bundle = aBundle; if (![self.bundle bundleIdentifier]) { - SULog(@"Error: the bundle being updated at %@ has no %@! This will cause preference read/write to not work properly.", self.bundle, kCFBundleIdentifierKey); + SULog(SULogLevelError, @"Error: the bundle being updated at %@ has no %@! This will cause preference read/write to not work properly.", self.bundle, kCFBundleIdentifierKey); } self.defaultsDomain = [self.bundle objectForInfoDictionaryKey:SUDefaultsDomainKey]; diff --git a/Sparkle/SUInstaller.m b/Sparkle/SUInstaller.m index 3ef0c5ff..6abef25b 100644 --- a/Sparkle/SUInstaller.m +++ b/Sparkle/SUInstaller.m @@ -102,7 +102,7 @@ *isGuidedPtr = isGuided; if (!newAppDownloadPath) { - SULog(@"Searched %@ for %@.(app|pkg)", inUpdateFolder, bundleFileNameNoExtension); + SULog(SULogLevelError, @"Searched %@ for %@.(app|pkg)", inUpdateFolder, bundleFileNameNoExtension); } return newAppDownloadPath; } diff --git a/Sparkle/SULog.h b/Sparkle/SULog.h index 1693f535..d6d6d699 100644 --- a/Sparkle/SULog.h +++ b/Sparkle/SULog.h @@ -1,32 +1,29 @@ -/* - * SULog.h - * EyeTV - * - * Created by Uli Kusterer on 12/03/2009. - * Copyright 2008 Elgato Systems GmbH. All rights reserved. - * - */ - -/* - Log output for troubleshooting Sparkle failures on end-user machines. - Your tech support will hug you if you tell them about this. -*/ +// +// SULog.h +// Sparkle +// +// Created by Mayur Pawashe on 5/18/16. +// Copyright © 2016 Sparkle Project. All rights reserved. +// #ifndef SULOG_H #define SULOG_H -// ----------------------------------------------------------------------------- -// Headers: -// ----------------------------------------------------------------------------- - #include +typedef NS_ENUM(uint8_t, SULogLevel) { + // This level is for information that *might* result a failure + // For now until other levels are added, this may serve as a level for other information as well + SULogLevelDefault, + // This level is for errors that occurred + SULogLevelError +}; -// ----------------------------------------------------------------------------- -// Prototypes: -// ----------------------------------------------------------------------------- - -void SUClearLog(void); -void SULog(NSString *format, ...) NS_FORMAT_FUNCTION(1, 2); +// Logging utlity function that is thread-safe +// On 10.12 or later this uses os_log +// Otherwise on older systems this uses ASL +// For debugging command line tools, you may have to use Console.app or log(1) to view log messages +// Try to keep log messages as compact/short as possible +void SULog(SULogLevel level, NSString *format, ...) NS_FORMAT_FUNCTION(2, 3); #endif diff --git a/Sparkle/SULog.m b/Sparkle/SULog.m index 5941aac7..e500c460 100644 --- a/Sparkle/SULog.m +++ b/Sparkle/SULog.m @@ -1,78 +1,114 @@ -/* - * SULog.m - * EyeTV - * - * Created by Uli Kusterer on 12/03/2009. - * Copyright 2009 Elgato Systems GmbH. All rights reserved. - * - */ - -// ----------------------------------------------------------------------------- -// Headers: -// ----------------------------------------------------------------------------- +// +// SULog.m +// Sparkle +// +// Created by Mayur Pawashe on 5/18/16. +// Copyright © 2016 Sparkle Project. All rights reserved. +// #include "SULog.h" +#include +#include +#import "SUOperatingSystem.h" +// For converting constants to string literals using the preprocessor +#define STRINGIFY(x) #x +#define TO_STRING(x) STRINGIFY(x) -// ----------------------------------------------------------------------------- -// Constants: -// ----------------------------------------------------------------------------- - -static NSString *const SULogFilePath = @"~/Library/Logs/SparkleUpdateLog.log"; - - -// ----------------------------------------------------------------------------- -// SUClearLog: -// Erase the log at the start of an update. We don't want to litter the -// user's hard disk with logging data that's mostly unused, so each app -// should clear the log before it starts updating, so only the most recent -// update is kept around. -// -// TAKES: -// sender - Object that sent this message, typically of type X. -// ----------------------------------------------------------------------------- - -void SUClearLog(void) +void SULog(SULogLevel level, NSString *format, ...) { - FILE *logfile = fopen([[SULogFilePath stringByExpandingTildeInPath] fileSystemRepresentation], "w"); - if (logfile) { - fclose(logfile); - SULog(@"===== %@ =====", [[NSFileManager defaultManager] displayNameAtPath:[[NSBundle mainBundle] bundlePath]]); + static aslclient client; + static dispatch_queue_t queue; + static dispatch_once_t onceToken; + + static os_log_t logger; + static BOOL hasOSLogging; + + dispatch_once(&onceToken, ^{ + NSBundle *mainBundle = [NSBundle mainBundle]; + + hasOSLogging = [SUOperatingSystem isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){10, 12, 0}]; + + NSString *mainBundleIdentifier = mainBundle.bundleIdentifier; + NSString *bundleIdentifier = (mainBundleIdentifier != nil) ? mainBundleIdentifier : @""SPARKLE_BUNDLE_IDENTIFIER; + + if (hasOSLogging) { + const char *subsystem = [[bundleIdentifier stringByAppendingString:@".Sparkle"] UTF8String]; +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wpartial-availability" + // This creates a thread-safe object + logger = os_log_create(subsystem, "Sparkle"); +#pragma clang diagnostic pop + } else { + uint32_t options = ASL_OPT_NO_DELAY; + // Act the same way os_log() does; don't log to stderr if a terminal device is attached + if (!isatty(STDERR_FILENO)) { + options |= ASL_OPT_STDERR; + } + + NSString *displayName = [[NSFileManager defaultManager] displayNameAtPath:mainBundle.bundlePath]; + client = asl_open([displayName stringByAppendingString:@" [Sparkle]"].UTF8String, bundleIdentifier.UTF8String, options); + queue = dispatch_queue_create(NULL, DISPATCH_QUEUE_SERIAL); + } + }); + + if (!hasOSLogging && client == NULL) { + return; } -} - - -// ----------------------------------------------------------------------------- -// SULog: -// Like NSLog, but logs to one specific log file. Each line is prefixed -// with the current date and time, to help in regressing issues. -// -// TAKES: -// format - NSLog/printf-style format string. -// ... - More parameters depending on format string's contents. -// ----------------------------------------------------------------------------- - -void SULog(NSString *format, ...) -{ - static BOOL loggedYet = NO; - if (!loggedYet) { - loggedYet = YES; - SUClearLog(); - } - + va_list ap; va_start(ap, format); - NSString *theStr = [[NSString alloc] initWithFormat:format arguments:ap]; - NSLog(@"Sparkle: %@", theStr); - - FILE *logfile = fopen([[SULogFilePath stringByExpandingTildeInPath] fileSystemRepresentation], "a"); - if (logfile) { - theStr = [NSString stringWithFormat:@"%@: %@\n", [NSDate date], theStr]; - NSData *theData = [theStr dataUsingEncoding:NSUTF8StringEncoding]; - fwrite([theData bytes], 1, [theData length], logfile); - fclose(logfile); - } + NSString *logMessage = [[NSString alloc] initWithFormat:format arguments:ap]; va_end(ap); + + // Use os_log if available (on 10.12+) + if (hasOSLogging) { + // We'll make all of our messages formatted as public; just don't log sensitive information. + // Note we don't take advantage of info like the source line number because we wrap this macro inside our own function + // And we don't really leverage of os_log's deferred formatting processing because we format the string before passing it in +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wpartial-availability" + switch (level) { + case SULogLevelDefault: + // See docs for OS_LOG_TYPE_DEFAULT + // By default, OS_LOG_TYPE_DEFAULT seems to be more noticable than OS_LOG_TYPE_INFO + os_log(logger, "%{public}@", logMessage); + break; + case SULogLevelError: + // See docs for OS_LOG_TYPE_ERROR + os_log_error(logger, "%{public}@", logMessage); + break; + } +#pragma clang diagnostic pop + return; + } + + // Otherwise use ASL + // Make sure we do not async, because if we async, the log may not be delivered deterministically + dispatch_sync(queue, ^{ + aslmsg message = asl_new(ASL_TYPE_MSG); + if (message == NULL) { + return; + } + + if (asl_set(message, ASL_KEY_MSG, logMessage.UTF8String) != 0) { + return; + } + + int levelSetResult; + switch (level) { + case SULogLevelDefault: + // Just use one level below the error level + levelSetResult = asl_set(message, ASL_KEY_LEVEL, TO_STRING(ASL_LEVEL_WARNING)); + break; + case SULogLevelError: + levelSetResult = asl_set(message, ASL_KEY_LEVEL, TO_STRING(ASL_LEVEL_ERR)); + break; + } + if (levelSetResult != 0) { + return; + } + + asl_send(client, message); + }); } - - diff --git a/Sparkle/SUPackageInstaller.m b/Sparkle/SUPackageInstaller.m index 226cde20..61f3355a 100644 --- a/Sparkle/SUPackageInstaller.m +++ b/Sparkle/SUPackageInstaller.m @@ -60,7 +60,7 @@ static NSString *SUOpenUtilityPath = @"/usr/bin/open"; [installer waitUntilExit]; } @catch (NSException *exception) { - SULog(@"Error: Failed to launch package installer: %@", exception); + SULog(SULogLevelError, @"Error: Failed to launch package installer: %@", exception); if (error != NULL) { *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey: @"Package installer failed to launch." }]; } diff --git a/Sparkle/SUPipedUnarchiver.m b/Sparkle/SUPipedUnarchiver.m index b155b408..d5d7ad4d 100644 --- a/Sparkle/SUPipedUnarchiver.m +++ b/Sparkle/SUPipedUnarchiver.m @@ -93,7 +93,7 @@ NSError *error = nil; NSString *destination = [self.archivePath stringByDeletingLastPathComponent]; - SULog(@"Extracting using '%@' '%@' < '%@' '%@'", command, [args componentsJoinedByString:@"' '"], self.archivePath, destination); + SULog(SULogLevelDefault, @"Extracting using '%@' '%@' < '%@' '%@'", command, [args componentsJoinedByString:@"' '"], self.archivePath, destination); // Get the file size. NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:self.archivePath error:nil]; diff --git a/Sparkle/SUPlainInstaller.m b/Sparkle/SUPlainInstaller.m index 586ce47f..a845a47e 100644 --- a/Sparkle/SUPlainInstaller.m +++ b/Sparkle/SUPlainInstaller.m @@ -62,7 +62,7 @@ { if (installationURL == nil || newURL == nil) { // this really shouldn't happen but just in case - SULog(@"Failed to perform installation because either installation URL (%@) or new URL (%@) is nil", installationURL, newURL); + SULog(SULogLevelError, @"Failed to perform installation because either installation URL (%@) or new URL (%@) is nil", installationURL, newURL); if (error != NULL) { *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey: @"Failed to perform installation because the paths to install at and from are not valid" }]; } @@ -76,7 +76,7 @@ NSURL *installationDirectory = installationURL.URLByDeletingLastPathComponent; NSURL *tempNewDirectoryURL = [fileManager makeTemporaryDirectoryWithPreferredName:preferredName appropriateForDirectoryURL:installationDirectory error:error]; if (tempNewDirectoryURL == nil) { - SULog(@"Failed to make new temp directory"); + SULog(SULogLevelError, @"Failed to make new temp directory"); return NO; } @@ -84,7 +84,7 @@ NSString *newURLLastPathComponent = newURL.lastPathComponent; NSURL *newTempURL = [tempNewDirectoryURL URLByAppendingPathComponent:newURLLastPathComponent]; if (![fileManager moveItemAtURL:newURL toURL:newTempURL error:error]) { - SULog(@"Failed to move the new app from %@ to its temp directory at %@", newURL.path, newTempURL.path); + SULog(SULogLevelError, @"Failed to move the new app from %@ to its temp directory at %@", newURL.path, newTempURL.path); [fileManager removeItemAtURL:tempNewDirectoryURL error:NULL]; return NO; } @@ -96,13 +96,13 @@ NSError *quarantineError = nil; if (![fileManager releaseItemFromQuarantineAtRootURL:newTempURL error:&quarantineError]) { // Not big enough of a deal to fail the entire installation - SULog(@"Failed to release quarantine at %@ with error %@", newTempURL.path, quarantineError); + SULog(SULogLevelError, @"Failed to release quarantine at %@ with error %@", newTempURL.path, quarantineError); } NSURL *oldURL = [NSURL fileURLWithPath:host.bundlePath]; if (oldURL == nil) { // this really shouldn't happen but just in case - SULog(@"Failed to construct URL from bundle path: %@", host.bundlePath); + SULog(SULogLevelError, @"Failed to construct URL from bundle path: %@", host.bundlePath); if (error != NULL) { *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey: @"Failed to perform installation because a path could not be constructed for the old installation" }]; } @@ -111,14 +111,14 @@ if (![fileManager changeOwnerAndGroupOfItemAtRootURL:newTempURL toMatchURL:oldURL error:error]) { // But this is big enough of a deal to fail - SULog(@"Failed to change owner and group of new app at %@ to match old app at %@", newTempURL.path, oldURL.path); + SULog(SULogLevelError, @"Failed to change owner and group of new app at %@ to match old app at %@", newTempURL.path, oldURL.path); [fileManager removeItemAtURL:tempNewDirectoryURL error:NULL]; return NO; } if (![fileManager updateModificationAndAccessTimeOfItemAtURL:newTempURL error:error]) { // Not a fatal error, but a pretty unfortunate one - SULog(@"Failed to update modification and access time of new app at %@", newTempURL.path); + SULog(SULogLevelError, @"Failed to update modification and access time of new app at %@", newTempURL.path); } // Decide on a destination name we should use for the older app when we move it around the file system @@ -138,7 +138,7 @@ // Create a temporary directory for our old app that resides on its volume NSURL *tempOldDirectoryURL = [fileManager makeTemporaryDirectoryWithPreferredName:oldDestinationName appropriateForDirectoryURL:oldURLDirectory error:error]; if (tempOldDirectoryURL == nil) { - SULog(@"Failed to create temporary directory for old app at %@", oldURL.path); + SULog(SULogLevelError, @"Failed to create temporary directory for old app at %@", oldURL.path); [fileManager removeItemAtURL:tempNewDirectoryURL error:NULL]; return NO; } @@ -146,7 +146,7 @@ // Move the old app to the temporary directory NSURL *oldTempURL = [tempOldDirectoryURL URLByAppendingPathComponent:oldDestinationNameWithPathExtension]; if (![fileManager moveItemAtURL:oldURL toURL:oldTempURL error:error]) { - SULog(@"Failed to move the old app at %@ to a temporary location at %@", oldURL.path, oldTempURL.path); + SULog(SULogLevelError, @"Failed to move the old app at %@ to a temporary location at %@", oldURL.path, oldTempURL.path); // Just forget about our updated app on failure [fileManager removeItemAtURL:tempNewDirectoryURL error:NULL]; @@ -157,7 +157,7 @@ // Move the new app to its final destination if (![fileManager moveItemAtURL:newTempURL toURL:installationURL error:error]) { - SULog(@"Failed to move new app at %@ to final destination %@", newTempURL.path, installationURL.path); + SULog(SULogLevelError, @"Failed to move new app at %@ to final destination %@", newTempURL.path, installationURL.path); // Forget about our updated app on failure [fileManager removeItemAtURL:tempNewDirectoryURL error:NULL]; diff --git a/Sparkle/SUUpdateAlert.m b/Sparkle/SUUpdateAlert.m index efda7f45..c10d6e8f 100644 --- a/Sparkle/SUUpdateAlert.m +++ b/Sparkle/SUUpdateAlert.m @@ -269,7 +269,7 @@ // Do not allow redirects to dangerous protocols such as file:// if (!whitelistedSafe) { - SULog(@"Blocked display of %@ URL which may be dangerous", scheme); + SULog(SULogLevelDefault, @"Blocked display of %@ URL which may be dangerous", scheme); [listener ignore]; return; } diff --git a/Sparkle/SUUpdateDriver.m b/Sparkle/SUUpdateDriver.m index f83d2355..7ee50845 100644 --- a/Sparkle/SUUpdateDriver.m +++ b/Sparkle/SUUpdateDriver.m @@ -58,7 +58,7 @@ NSString *const SUUpdateDriverFinishedNotification = @"SUUpdateDriverFinished"; - (void)showAlert:(NSAlert *)alert { // Only UI-based subclass shows the actual alert - SULog(@"ALERT: %@\n%@", alert.messageText, alert.informativeText); + SULog(SULogLevelDefault, @"ALERT: %@\n%@", alert.messageText, alert.informativeText); } @end diff --git a/Sparkle/SUUpdateValidator.m b/Sparkle/SUUpdateValidator.m index 164da998..deb8f01d 100644 --- a/Sparkle/SUUpdateValidator.m +++ b/Sparkle/SUUpdateValidator.m @@ -41,14 +41,14 @@ if (publicDSAKey == nil) { prevalidatedDsaSignature = NO; - SULog(@"Failed to validate update before unarchiving because no DSA key was found"); + SULog(SULogLevelError, @"Failed to validate update before unarchiving because no DSA key was found"); } else if (dsaSignature == nil) { prevalidatedDsaSignature = NO; - SULog(@"Failed to validate update before unarchiving because no DSA signature was found"); + SULog(SULogLevelError, @"Failed to validate update before unarchiving because no DSA signature was found"); } else { prevalidatedDsaSignature = [SUDSAVerifier validatePath:downloadPath withEncodedDSASignature:dsaSignature withPublicDSAKey:publicDSAKey]; if (!prevalidatedDsaSignature) { - SULog(@"DSA signature validation before unarchiving failed for update %@", downloadPath); + SULog(SULogLevelError, @"DSA signature validation before unarchiving failed for update %@", downloadPath); } } @@ -83,7 +83,7 @@ // install source could point to a new bundle or a package NSString *installSource = [SUInstaller installSourcePathInUpdateFolder:updateDirectory forHost:host isPackage:&isPackage isGuided:NULL]; if (installSource == nil) { - SULog(@"No suitable install is found in the update. The update will be rejected."); + SULog(SULogLevelError, @"No suitable install is found in the update. The update will be rejected."); return NO; } @@ -95,7 +95,7 @@ // For package type updates, all we do is check if the DSA signature is valid BOOL validationCheckSuccess = [SUDSAVerifier validatePath:downloadPath withEncodedDSASignature:DSASignature withPublicDSAKey:publicDSAKey]; if (!validationCheckSuccess) { - SULog(@"DSA signature validation of the package failed. The update contains an installer package, and valid DSA signatures are mandatory for all installer packages. The update will be rejected. Sign the installer with a valid DSA key or use an .app bundle update instead."); + SULog(SULogLevelError, @"DSA signature validation of the package failed. The update contains an installer package, and valid DSA signatures are mandatory for all installer packages. The update will be rejected. Sign the installer with a valid DSA key or use an .app bundle update instead."); } return validationCheckSuccess; } else { @@ -104,7 +104,7 @@ } } else if (isPackage) { // We shouldn't get here because we don't validate packages before extracting them currently - SULog(@"Error: not expecting to find package after being required to validate update before extraction"); + SULog(SULogLevelError, @"Error: not expecting to find package after being required to validate update before extraction"); return NO; } else { // Because we already validated the DSA signature, this is just a consistency check to see @@ -112,7 +112,7 @@ // Currently, this case only gets hit for binary delta updates NSError *error = nil; if ([SUCodeSigningVerifier bundleAtURLIsCodeSigned:installSourceURL] && ![SUCodeSigningVerifier codeSignatureIsValidAtBundleURL:installSourceURL error:&error]) { - SULog(@"Failed to validate apple code sign signature on bundle after archive validation with error: %@", error); + SULog(SULogLevelError, @"Failed to validate apple code sign signature on bundle after archive validation with error: %@", error); return NO; } else { return YES; @@ -132,7 +132,7 @@ { NSBundle *newBundle = [NSBundle bundleWithURL:newBundleURL]; if (newBundle == nil) { - SULog(@"No suitable bundle is found in the update. The update will be rejected."); + SULog(SULogLevelError, @"No suitable bundle is found in the update. The update will be rejected."); return NO; } @@ -143,7 +143,7 @@ // Downgrade in DSA security should not be possible if (publicDSAKey != nil && newPublicDSAKey == nil) { - SULog(@"A public DSA key is found in the old bundle but no public DSA key is found in the new update. For security reasons, the update will be rejected."); + SULog(SULogLevelError, @"A public DSA key is found in the old bundle but no public DSA key is found in the new update. For security reasons, the update will be rejected."); return NO; } @@ -154,7 +154,7 @@ // However if the new and old DSA keys are the same, then this is a security measure. if (newPublicDSAKey != nil) { if (![SUDSAVerifier validatePath:downloadedPath withEncodedDSASignature:DSASignature withPublicDSAKey:newPublicDSAKey]) { - SULog(@"DSA signature validation failed. The update has a public DSA key and is signed with a DSA key, but the %@ doesn't match the signature. The update will be rejected.", + SULog(SULogLevelError, @"DSA signature validation failed. The update has a public DSA key and is signed with a DSA key, but the %@ doesn't match the signature. The update will be rejected.", dsaKeysMatch ? @"public key" : @"new public key shipped with the update"); return NO; } @@ -164,7 +164,7 @@ if (dsaKeysMatch) { NSError *error = nil; if (updateIsCodeSigned && ![SUCodeSigningVerifier codeSignatureIsValidAtBundleURL:newHost.bundle.bundleURL error:&error]) { - SULog(@"The update archive has a valid DSA signature, but the app is also signed with Code Signing, which is corrupted: %@. The update will be rejected.", error); + SULog(SULogLevelError, @"The update archive has a valid DSA signature, but the app is also signed with Code Signing, which is corrupted: %@. The update will be rejected.", error); return NO; } } else { @@ -173,13 +173,13 @@ NSString *dsaStatus = newPublicDSAKey ? @"has a new DSA key that doesn't match the previous one" : (publicDSAKey ? @"removes the DSA key" : @"isn't signed with a DSA key"); if (!hostIsCodeSigned || !updateIsCodeSigned) { NSString *acsStatus = !hostIsCodeSigned ? @"old app hasn't been signed with app Code Signing" : @"new app isn't signed with app Code Signing"; - SULog(@"The update archive %@, and the %@. At least one method of signature verification must be valid. The update will be rejected.", dsaStatus, acsStatus); + SULog(SULogLevelError, @"The update archive %@, and the %@. At least one method of signature verification must be valid. The update will be rejected.", dsaStatus, acsStatus); return NO; } NSError *error = nil; if (![SUCodeSigningVerifier codeSignatureAtBundleURL:host.bundle.bundleURL matchesSignatureAtBundleURL:newHost.bundle.bundleURL error:&error]) { - SULog(@"The update archive %@, and the app is signed with a new Code Signing identity that doesn't match code signing of the original app: %@. At least one method of signature verification must be valid. The update will be rejected.", dsaStatus, error); + SULog(SULogLevelError, @"The update archive %@, and the app is signed with a new Code Signing identity that doesn't match code signing of the original app: %@. At least one method of signature verification must be valid. The update will be rejected.", dsaStatus, error); return NO; } } diff --git a/Sparkle/SUUpdater.m b/Sparkle/SUUpdater.m index 7794db19..ca3b8e24 100644 --- a/Sparkle/SUUpdater.m +++ b/Sparkle/SUUpdater.m @@ -99,7 +99,7 @@ static NSString *const SUUpdaterDefaultsObservationContext = @"SUUpdaterDefaults // Use explicit class to use the correct bundle even when subclassed self.sparkleBundle = [NSBundle bundleForClass:[SUUpdater class]]; if (!self.sparkleBundle) { - SULog(@"Error: SUUpdater can't find Sparkle.framework it belongs to"); + SULog(SULogLevelError, @"Error: SUUpdater can't find Sparkle.framework it belongs to"); return nil; } @@ -170,7 +170,7 @@ static NSString *const SUUpdaterDefaultsObservationContext = @"SUUpdaterDefaults [self showAlertText:SULocalizedString(@"Insecure feed URL is blocked in macOS 10.11", nil) informativeText:[NSString stringWithFormat:SULocalizedString(@"You must change the feed URL (%@) to use HTTPS or disable App Transport Security.\n\nFor more information:\nhttps://sparkle-project.org/documentation/app-transport-security/", nil), [feedURL absoluteString]]]; } else if (!isMainBundle) { - SULog(@"WARNING: Serving updates over HTTP may be blocked in macOS 10.11. Please change the feed URL (%@) to use HTTPS. For more information:\nhttps://sparkle-project.org/documentation/app-transport-security/", feedURL); + SULog(SULogLevelDefault, @"WARNING: Serving updates over HTTP may be blocked in macOS 10.11. Please change the feed URL (%@) to use HTTPS. For more information:\nhttps://sparkle-project.org/documentation/app-transport-security/", feedURL); } } #endif @@ -367,7 +367,7 @@ static NSString *const SUUpdaterDefaultsObservationContext = @"SUUpdaterDefaults } @catch (NSException *) { - SULog(@"Error: [SUUpdater unregisterAsObserver] called, but the updater wasn't registered as an observer."); + SULog(SULogLevelError, @"Error: [SUUpdater unregisterAsObserver] called, but the updater wasn't registered as an observer."); } }