From ecb608bb4094bcc96794ce2dc3b33c4feed787a2 Mon Sep 17 00:00:00 2001 From: Deadpikle Date: Wed, 20 Dec 2017 10:48:51 -0500 Subject: [PATCH 01/20] Bring 2.0 files for SPUDownloader to 1.x --- Sparkle.xcodeproj/project.pbxproj | 48 ++++++ Sparkle/SPUDownloadData.h | 43 ++++++ Sparkle/SPUDownloadData.m | 67 +++++++++ Sparkle/SPUDownloader.h | 21 +++ Sparkle/SPUDownloader.m | 237 ++++++++++++++++++++++++++++++ Sparkle/SPUDownloaderDelegate.h | 34 +++++ Sparkle/SPUDownloaderProtocol.h | 24 +++ Sparkle/SPULocalCacheDirectory.h | 35 +++++ Sparkle/SPULocalCacheDirectory.m | 80 ++++++++++ Sparkle/SPUURLRequest.h | 31 ++++ Sparkle/SPUURLRequest.m | 94 ++++++++++++ 11 files changed, 714 insertions(+) create mode 100755 Sparkle/SPUDownloadData.h create mode 100755 Sparkle/SPUDownloadData.m create mode 100755 Sparkle/SPUDownloader.h create mode 100755 Sparkle/SPUDownloader.m create mode 100755 Sparkle/SPUDownloaderDelegate.h create mode 100755 Sparkle/SPUDownloaderProtocol.h create mode 100755 Sparkle/SPULocalCacheDirectory.h create mode 100755 Sparkle/SPULocalCacheDirectory.m create mode 100755 Sparkle/SPUURLRequest.h create mode 100755 Sparkle/SPUURLRequest.m diff --git a/Sparkle.xcodeproj/project.pbxproj b/Sparkle.xcodeproj/project.pbxproj index de720547..06ddce0a 100644 --- a/Sparkle.xcodeproj/project.pbxproj +++ b/Sparkle.xcodeproj/project.pbxproj @@ -49,6 +49,16 @@ 14950073195FCE4E00BC5B5B /* AppKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 0867D6A5FE840307C02AAC07 /* AppKit.framework */; }; 14958C6E19AEBC950061B14F /* signed-test-file.txt in Resources */ = {isa = PBXBuildFile; fileRef = 14958C6B19AEBC530061B14F /* signed-test-file.txt */; }; 14958C6F19AEBC980061B14F /* test-pubkey.pem in Resources */ = {isa = PBXBuildFile; fileRef = 14958C6C19AEBC610061B14F /* test-pubkey.pem */; }; + 34074B901FEABD08001CB3A5 /* SPUDownloader.m in Sources */ = {isa = PBXBuildFile; fileRef = 34074B8C1FEABD08001CB3A5 /* SPUDownloader.m */; }; + 34074B911FEABD08001CB3A5 /* SPUDownloader.h in Headers */ = {isa = PBXBuildFile; fileRef = 34074B8D1FEABD08001CB3A5 /* SPUDownloader.h */; }; + 34074B921FEABD08001CB3A5 /* SPUDownloaderDelegate.h in Headers */ = {isa = PBXBuildFile; fileRef = 34074B8E1FEABD08001CB3A5 /* SPUDownloaderDelegate.h */; }; + 34074B931FEABD08001CB3A5 /* SPUDownloaderProtocol.h in Headers */ = {isa = PBXBuildFile; fileRef = 34074B8F1FEABD08001CB3A5 /* SPUDownloaderProtocol.h */; }; + 34074B961FEABD24001CB3A5 /* SPULocalCacheDirectory.h in Headers */ = {isa = PBXBuildFile; fileRef = 34074B941FEABD23001CB3A5 /* SPULocalCacheDirectory.h */; }; + 34074B971FEABD24001CB3A5 /* SPULocalCacheDirectory.m in Sources */ = {isa = PBXBuildFile; fileRef = 34074B951FEABD23001CB3A5 /* SPULocalCacheDirectory.m */; }; + 34074B9A1FEABD49001CB3A5 /* SPUURLRequest.m in Sources */ = {isa = PBXBuildFile; fileRef = 34074B981FEABD48001CB3A5 /* SPUURLRequest.m */; }; + 34074B9B1FEABD49001CB3A5 /* SPUURLRequest.h in Headers */ = {isa = PBXBuildFile; fileRef = 34074B991FEABD49001CB3A5 /* SPUURLRequest.h */; }; + 34074B9E1FEABD5A001CB3A5 /* SPUDownloadData.m in Sources */ = {isa = PBXBuildFile; fileRef = 34074B9C1FEABD5A001CB3A5 /* SPUDownloadData.m */; }; + 34074B9F1FEABD5A001CB3A5 /* SPUDownloadData.h in Headers */ = {isa = PBXBuildFile; fileRef = 34074B9D1FEABD5A001CB3A5 /* SPUDownloadData.h */; }; 3772FEA913DE0B6B00F79537 /* SUVersionDisplayProtocol.h in Headers */ = {isa = PBXBuildFile; fileRef = 3772FEA813DE0B6B00F79537 /* SUVersionDisplayProtocol.h */; settings = {ATTRIBUTES = (Public, ); }; }; 55C14BD4136EEFCE00649790 /* Autoupdate.m in Sources */ = {isa = PBXBuildFile; fileRef = 55C14BD3136EEFCE00649790 /* Autoupdate.m */; }; 55C14BD9136EF00C00649790 /* SUStatus.xib in Resources */ = {isa = PBXBuildFile; fileRef = 55C14BD8136EF00C00649790 /* SUStatus.xib */; }; @@ -520,6 +530,16 @@ 1A985A511C5C32BB0001163A /* uk */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = uk; path = uk.lproj/InfoPlist.strings; sourceTree = ""; }; 1A985A521C5C32BC0001163A /* ar */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = ar; path = ar.lproj/InfoPlist.strings; sourceTree = ""; }; 1A985A531C5C32BD0001163A /* el */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = el; path = el.lproj/InfoPlist.strings; sourceTree = ""; }; + 34074B8C1FEABD08001CB3A5 /* SPUDownloader.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SPUDownloader.m; sourceTree = ""; }; + 34074B8D1FEABD08001CB3A5 /* SPUDownloader.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SPUDownloader.h; sourceTree = ""; }; + 34074B8E1FEABD08001CB3A5 /* SPUDownloaderDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SPUDownloaderDelegate.h; sourceTree = ""; }; + 34074B8F1FEABD08001CB3A5 /* SPUDownloaderProtocol.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SPUDownloaderProtocol.h; sourceTree = ""; }; + 34074B941FEABD23001CB3A5 /* SPULocalCacheDirectory.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SPULocalCacheDirectory.h; sourceTree = ""; }; + 34074B951FEABD23001CB3A5 /* SPULocalCacheDirectory.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SPULocalCacheDirectory.m; sourceTree = ""; }; + 34074B981FEABD48001CB3A5 /* SPUURLRequest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SPUURLRequest.m; sourceTree = ""; }; + 34074B991FEABD49001CB3A5 /* SPUURLRequest.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SPUURLRequest.h; sourceTree = ""; }; + 34074B9C1FEABD5A001CB3A5 /* SPUDownloadData.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SPUDownloadData.m; sourceTree = ""; }; + 34074B9D1FEABD5A001CB3A5 /* SPUDownloadData.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SPUDownloadData.h; sourceTree = ""; }; 3772FEA813DE0B6B00F79537 /* SUVersionDisplayProtocol.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SUVersionDisplayProtocol.h; sourceTree = ""; }; 4607BEA21948443800EF8DA4 /* nb */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = nb; path = nb.lproj/Sparkle.strings; sourceTree = ""; }; 4607BEA31948443800EF8DA4 /* nb */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = nb; path = nb.lproj/SUAutomaticUpdateAlert.xib; sourceTree = ""; }; @@ -1049,6 +1069,7 @@ children = ( 61299B3909CB055000B7442F /* Appcast Support */, 55C14BD5136EEFD000649790 /* Autoupdate */, + 34074B8B1FEABCE7001CB3A5 /* Downloader */, 089C1665FE841158C02AAC07 /* Framework Resources */, 618FA6DB0DB485440026945C /* Installation */, 61B5F8F309C4CE5900B25A18 /* Other Sources */, @@ -1079,6 +1100,23 @@ path = Resources; sourceTree = ""; }; + 34074B8B1FEABCE7001CB3A5 /* Downloader */ = { + isa = PBXGroup; + children = ( + 34074B9D1FEABD5A001CB3A5 /* SPUDownloadData.h */, + 34074B9C1FEABD5A001CB3A5 /* SPUDownloadData.m */, + 34074B8D1FEABD08001CB3A5 /* SPUDownloader.h */, + 34074B8C1FEABD08001CB3A5 /* SPUDownloader.m */, + 34074B8E1FEABD08001CB3A5 /* SPUDownloaderDelegate.h */, + 34074B8F1FEABD08001CB3A5 /* SPUDownloaderProtocol.h */, + 34074B941FEABD23001CB3A5 /* SPULocalCacheDirectory.h */, + 34074B951FEABD23001CB3A5 /* SPULocalCacheDirectory.m */, + 34074B991FEABD49001CB3A5 /* SPUURLRequest.h */, + 34074B981FEABD48001CB3A5 /* SPUURLRequest.m */, + ); + name = Downloader; + sourceTree = ""; + }; 55C14BD5136EEFD000649790 /* Autoupdate */ = { isa = PBXGroup; children = ( @@ -1385,6 +1423,8 @@ 61B5FC7009C51F4A00B25A18 /* SUAppcastItem.h in Headers */, 72316BDE1E0E17910039EFD9 /* SUApplicationInfo.h in Headers */, 6120721209CC5C4B007FE0F6 /* SUAutomaticUpdateAlert.h in Headers */, + 34074B921FEABD08001CB3A5 /* SPUDownloaderDelegate.h in Headers */, + 34074B961FEABD24001CB3A5 /* SPULocalCacheDirectory.h in Headers */, 61B93B270DD0FDD300DCD2F8 /* SUAutomaticUpdateDriver.h in Headers */, 61F83F740DBFE141006FDD30 /* SUBasicUpdateDriver.h in Headers */, 5D06E9390FD69271005AE3F6 /* SUBinaryDeltaUnarchiver.h in Headers */, @@ -1393,9 +1433,11 @@ 61299A5C09CA6D4500B7442F /* SUConstants.h in Headers */, 6102FE4A0E07803800F85D09 /* SUDiskImageUnarchiver.h in Headers */, 61299A2F09CA2DAB00B7442F /* SUDSAVerifier.h in Headers */, + 34074B9F1FEABD5A001CB3A5 /* SPUDownloadData.h in Headers */, 55E6F33319EC9F6C00005E76 /* SUErrors.h in Headers */, 14652F8419A978C200959E44 /* SUExport.h in Headers */, 7275F9C11B5F1F2900B1D19E /* SUFileManager.h in Headers */, + 34074B911FEABD08001CB3A5 /* SPUDownloader.h in Headers */, 722954C41D04E66F00ECF9CA /* SUFileOperationConstants.h in Headers */, 767B61AC1972D488004E0C3C /* SUGuidedPackageInstaller.h in Headers */, 61EF67590E25C5B400F754E0 /* SUHost.h in Headers */, @@ -1414,10 +1456,12 @@ 72316BE31E0E1C7F0039EFD9 /* SUSystemUpdateInfo.h in Headers */, E1545EC51E1D7E0200FAECE8 /* SUTouchBarButtonGroup.h in Headers */, 61B93A3C0DD02D7000DCD2F8 /* SUUIBasedUpdateDriver.h in Headers */, + 34074B931FEABD08001CB3A5 /* SPUDownloaderProtocol.h in Headers */, 61299A8D09CA790200B7442F /* SUUnarchiver.h in Headers */, 722589DA1E0B19F4005EA0B9 /* SUUnarchiverNotifier.h in Headers */, 722589D71E0AD86B005EA0B9 /* SUUnarchiverProtocol.h in Headers */, 61B5FCDF09C52A9F00B25A18 /* SUUpdateAlert.h in Headers */, + 34074B9B1FEABD49001CB3A5 /* SPUURLRequest.h in Headers */, 610134730DD250470049ACDF /* SUUpdateDriver.h in Headers */, 612DCBAF0D488BC60015DBEA /* SUUpdatePermissionPrompt.h in Headers */, 7205C4311E1215AD00E370AE /* SUUpdatePermissionResponse.h in Headers */, @@ -1997,6 +2041,7 @@ buildActionMask = 2147483647; files = ( 723B252D1CEAB3A600909873 /* bscommon.c in Sources */, + 34074B9E1FEABD5A001CB3A5 /* SPUDownloadData.m in Sources */, 5D06E8EB0FD68CE4005AE3F6 /* bspatch.c in Sources */, 61B5FBB709C4FAFF00B25A18 /* SUAppcast.m in Sources */, 61B5FC6F09C51F4900B25A18 /* SUAppcastItem.m in Sources */, @@ -2005,6 +2050,7 @@ 61B93B280DD0FDD300DCD2F8 /* SUAutomaticUpdateDriver.m in Sources */, 61F83F720DBFE140006FDD30 /* SUBasicUpdateDriver.m in Sources */, 5D06E8EC0FD68CE4005AE3F6 /* SUBinaryDeltaApply.m in Sources */, + 34074B971FEABD24001CB3A5 /* SPULocalCacheDirectory.m in Sources */, 5D06E8ED0FD68CE4005AE3F6 /* SUBinaryDeltaCommon.m in Sources */, 5D06E93A0FD69271005AE3F6 /* SUBinaryDeltaUnarchiver.m in Sources */, 72316BDA1E0E17180039EFD9 /* SUBundleIcon.m in Sources */, @@ -2017,6 +2063,7 @@ 767B61AD1972D488004E0C3C /* SUGuidedPackageInstaller.m in Sources */, 61EF67560E25B58D00F754E0 /* SUHost.m in Sources */, 618FA5020DAE88B40026945C /* SUInstaller.m in Sources */, + 34074B901FEABD08001CB3A5 /* SPUDownloader.m in Sources */, 55C14F07136EF6DB00649790 /* SULog.m in Sources */, 726F2CE61BC9C33D001971A4 /* SUOperatingSystem.m in Sources */, 618FA5230DAE8E8A0026945C /* SUPackageInstaller.m in Sources */, @@ -2028,6 +2075,7 @@ 6196CFFA09C72149000DC222 /* SUStatusController.m in Sources */, 61A2279D0D1CEE7600430CCD /* SUSystemProfiler.m in Sources */, 72316BE41E0E1C7F0039EFD9 /* SUSystemUpdateInfo.m in Sources */, + 34074B9A1FEABD49001CB3A5 /* SPUURLRequest.m in Sources */, E1545EC61E1D7E0200FAECE8 /* SUTouchBarButtonGroup.m in Sources */, 61B93A3D0DD02D7000DCD2F8 /* SUUIBasedUpdateDriver.m in Sources */, 61299A8E09CA790200B7442F /* SUUnarchiver.m in Sources */, diff --git a/Sparkle/SPUDownloadData.h b/Sparkle/SPUDownloadData.h new file mode 100755 index 00000000..41cd5743 --- /dev/null +++ b/Sparkle/SPUDownloadData.h @@ -0,0 +1,43 @@ +// +// SPUDownloadData.h +// Sparkle +// +// Created by Mayur Pawashe on 8/10/16. +// Copyright © 2016 Sparkle Project. All rights reserved. +// + +#if __has_feature(modules) +@import Foundation; +#else +#import +#endif + +#import "SUExport.h" + +NS_ASSUME_NONNULL_BEGIN + +/*! + * A class for containing downloaded data along with some information about it. + */ +SU_EXPORT @interface SPUDownloadData : NSObject + +- (instancetype)initWithData:(NSData *)data textEncodingName:(NSString * _Nullable)textEncodingName MIMEType:(NSString * _Nullable)MIMEType; + +/*! + * The raw data that was downloaded. + */ +@property (nonatomic, readonly) NSData *data; + +/*! + * The IANA charset encoding name if available. Eg: "utf-8" + */ +@property (nonatomic, readonly, nullable, copy) NSString *textEncodingName; + +/*! + * The MIME type if available. Eg: "text/plain" + */ +@property (nonatomic, readonly, nullable, copy) NSString *MIMEType; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Sparkle/SPUDownloadData.m b/Sparkle/SPUDownloadData.m new file mode 100755 index 00000000..0d090dbe --- /dev/null +++ b/Sparkle/SPUDownloadData.m @@ -0,0 +1,67 @@ +// +// SPUDownloadData.m +// Sparkle +// +// Created by Mayur Pawashe on 8/10/16. +// Copyright © 2016 Sparkle Project. All rights reserved. +// + +#import "SPUDownloadData.h" + + +#include "AppKitPrevention.h" + +static NSString *SPUDownloadDataKey = @"SPUDownloadData"; +static NSString *SPUDownloadTextEncodingKey = @"SPUDownloadTextEncoding"; +static NSString *SPUDownloadMIMETypeKey = @"SPUDownloadMIMEType"; + +@implementation SPUDownloadData + +@synthesize data = _data; +@synthesize textEncodingName = _textEncodingName; +@synthesize MIMEType = _MIMEType; + ++ (BOOL)supportsSecureCoding +{ + return YES; +} + +- (instancetype)initWithData:(NSData *)data textEncodingName:(NSString * _Nullable)textEncodingName MIMEType:(NSString *)MIMEType +{ + self = [super init]; + if (self != nil) { + _data = data; + _textEncodingName = textEncodingName; + _MIMEType = MIMEType; + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder +{ + [coder encodeObject:self.data forKey:SPUDownloadDataKey]; + + if (self.textEncodingName != nil) { + [coder encodeObject:self.textEncodingName forKey:SPUDownloadTextEncodingKey]; + } + + if (self.MIMEType != nil) { + [coder encodeObject:self.MIMEType forKey:SPUDownloadMIMETypeKey]; + } +} + +- (nullable instancetype)initWithCoder:(NSCoder *)decoder +{ + NSData *data = [decoder decodeObjectOfClass:[NSData class] forKey:SPUDownloadDataKey]; + if (data == nil) { + return nil; + } + + NSString *textEncodingName = [decoder decodeObjectOfClass:[NSString class] forKey:SPUDownloadTextEncodingKey]; + + NSString *MIMEType = [decoder decodeObjectOfClass:[NSString class] forKey:SPUDownloadMIMETypeKey]; + + return [self initWithData:data textEncodingName:textEncodingName MIMEType:MIMEType]; +} + +@end diff --git a/Sparkle/SPUDownloader.h b/Sparkle/SPUDownloader.h new file mode 100755 index 00000000..6f7434d8 --- /dev/null +++ b/Sparkle/SPUDownloader.h @@ -0,0 +1,21 @@ +// +// SPUDownloader.h +// Downloader +// +// Created by Mayur Pawashe on 4/1/16. +// Copyright © 2016 Sparkle Project. All rights reserved. +// + +#import +#import "SPUDownloaderProtocol.h" + +@protocol SPUDownloaderDelegate; + +// This object implements the protocol which we have defined. It provides the actual behavior for the service. It is 'exported' by the service to make it available to the process hosting the service over an NSXPCConnection. +@interface SPUDownloader : NSObject + +// Due to XPC remote object reasons, this delegate is strongly referenced +// Invoke cleanup when done with this instance +- (instancetype)initWithDelegate:(id )delegate; + +@end diff --git a/Sparkle/SPUDownloader.m b/Sparkle/SPUDownloader.m new file mode 100755 index 00000000..2f0447de --- /dev/null +++ b/Sparkle/SPUDownloader.m @@ -0,0 +1,237 @@ +// +// SPUDownloader.m +// Downloader +// +// Created by Mayur Pawashe on 4/1/16. +// Copyright © 2016 Sparkle Project. All rights reserved. +// + +#import "SPUDownloader.h" +#import "SPUDownloaderDelegate.h" +#import "SPULocalCacheDirectory.h" +#import "SPUURLRequest.h" +#import "SPUDownloadData.h" +#import "SUErrors.h" + + +#include "AppKitPrevention.h" + +typedef NS_ENUM(NSUInteger, SPUDownloadMode) +{ + SPUDownloadModePersistent, + SPUDownloadModeTemporary +}; + +static NSString *SUDownloadingReason = @"Downloading update related file"; + +@interface SPUDownloader () + +// Delegate is intentionally strongly referenced; see header +@property (nonatomic) id delegate; +@property (nonatomic) NSURLSessionDownloadTask *download; +@property (nonatomic) NSURLSession *downloadSession; +@property (nonatomic, copy) NSString *bundleIdentifier; +@property (nonatomic, copy) NSString *desiredFilename; +@property (nonatomic, copy) NSString *downloadFilename; +@property (nonatomic) BOOL disabledAutomaticTermination; +@property (nonatomic) SPUDownloadMode mode; +@property (nonatomic) BOOL receivedExpectedBytes; + +@end + +@implementation SPUDownloader + +@synthesize delegate = _delegate; +@synthesize download = _download; +@synthesize downloadSession = _downloadSession; +@synthesize bundleIdentifier = _bundleIdentifier; +@synthesize desiredFilename = _desiredFilename; +@synthesize downloadFilename = _downloadFilename; +@synthesize disabledAutomaticTermination = _disabledAutomaticTermination; +@synthesize mode = _mode; +@synthesize receivedExpectedBytes = _receivedExpectedBytes; + +- (instancetype)initWithDelegate:(id )delegate +{ + self = [super init]; + if (self != nil) { + _delegate = delegate; + } + return self; +} + +- (void)startDownloadWithRequest:(SPUURLRequest *)request +{ + self.downloadSession = [NSURLSession + sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] + delegate:self + delegateQueue:[NSOperationQueue mainQueue]]; + self.download = [self.downloadSession downloadTaskWithRequest:request.request]; + [self.download resume]; +} + +// Don't implement dealloc - make the client call cleanup, which is the only way to remove the reference cycle from the delegate anyway + +- (void)startPersistentDownloadWithRequest:(SPUURLRequest *)request bundleIdentifier:(NSString *)bundleIdentifier desiredFilename:(NSString *)desiredFilename +{ + dispatch_async(dispatch_get_main_queue(), ^{ + if (self.download == nil && self.delegate != nil) { + // Prevent service from automatically terminating while downloading the update asynchronously without any reply blocks + [[NSProcessInfo processInfo] disableAutomaticTermination:SUDownloadingReason]; + self.disabledAutomaticTermination = YES; + + self.mode = SPUDownloadModePersistent; + self.desiredFilename = desiredFilename; + self.bundleIdentifier = bundleIdentifier; + + [self startDownloadWithRequest:request]; + } + }); +} + +- (void)startTemporaryDownloadWithRequest:(SPUURLRequest *)request +{ + dispatch_async(dispatch_get_main_queue(), ^{ + if (self.download == nil && self.delegate != nil) { + // Prevent service from automatically terminating while downloading the update asynchronously without any reply blocks + [[NSProcessInfo processInfo] disableAutomaticTermination:SUDownloadingReason]; + self.disabledAutomaticTermination = YES; + + self.mode = SPUDownloadModeTemporary; + [self startDownloadWithRequest:request]; + } + }); +} + +- (void)enableAutomaticTermination +{ + if (self.disabledAutomaticTermination) { + [[NSProcessInfo processInfo] enableAutomaticTermination:SUDownloadingReason]; + self.disabledAutomaticTermination = NO; + } +} + +- (void)cleanup +{ + [self enableAutomaticTermination]; + [self.download cancel]; + self.download = nil; + self.downloadSession = nil; + self.delegate = nil; + + if (self.mode == SPUDownloadModeTemporary && self.downloadFilename != nil) + { + [[NSFileManager defaultManager] removeItemAtPath:self.downloadFilename error:NULL]; + self.downloadFilename = nil; + } +} + +- (void)URLSession:(NSURLSession *)__unused session downloadTask:(NSURLSessionDownloadTask *)__unused downloadTask didFinishDownloadingToURL:(NSURL *)location +{ + if (self.mode == SPUDownloadModeTemporary) + { + self.downloadFilename = location.path; + [self downloadDidFinish]; // file is already in a system temp dir + } + else + { + // Remove our old caches path so we don't start accumulating files in there + NSString *rootPersistentDownloadCachePath = [[SPULocalCacheDirectory cachePathForBundleIdentifier:self.bundleIdentifier] stringByAppendingPathComponent:@"PersistentDownloads"]; + + [SPULocalCacheDirectory removeOldItemsInDirectory:rootPersistentDownloadCachePath]; + + NSString *tempDir = [SPULocalCacheDirectory createUniqueDirectoryInDirectory:rootPersistentDownloadCachePath]; + if (tempDir == nil) + { + // Okay, something's really broken with this user's file structure. + [self.download cancel]; + self.download = nil; + + NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUTemporaryDirectoryError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Can't make a temporary directory for the update download at %@.", tempDir] }]; + + [self.delegate downloaderDidFailWithError:error]; + } else { + NSString *downloadFileName = self.desiredFilename; + NSString *downloadFileNameDirectory = [tempDir stringByAppendingPathComponent:downloadFileName]; + + NSError *createError = nil; + if (![[NSFileManager defaultManager] createDirectoryAtPath:downloadFileNameDirectory withIntermediateDirectories:NO attributes:nil error:&createError]) { + NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUTemporaryDirectoryError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Can't make a download file name %@ directory inside temporary directory for the update download at %@.", downloadFileName, downloadFileNameDirectory] }]; + + [self.delegate downloaderDidFailWithError:error]; + } else { + NSString *name = self.download.response.suggestedFilename; + if (!name) { + name = location.lastPathComponent; // This likely contains nothing useful to identify the file (e.g. CFNetworkDownload_87LVIz.tmp) + } + NSString *toPath = [downloadFileNameDirectory stringByAppendingPathComponent:name]; + NSString *fromPath = location.path; // suppress moveItemAtPath: non-null warning + NSError *error = nil; + if ([[NSFileManager defaultManager] moveItemAtPath:fromPath toPath:toPath error:&error]) { + self.downloadFilename = toPath; + [self.delegate downloaderDidSetDestinationName:name temporaryDirectory:downloadFileNameDirectory]; + [self downloadDidFinish]; + } else { + [self.delegate downloaderDidFailWithError:error]; + } + } + } + } +} + +- (void)URLSession:(NSURLSession *)__unused session downloadTask:(NSURLSessionDownloadTask *)__unused downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)__unused totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite +{ + + if (self.mode == SPUDownloadModePersistent && totalBytesExpectedToWrite > 0 && !self.receivedExpectedBytes) { + self.receivedExpectedBytes = YES; + [self.delegate downloaderDidReceiveExpectedContentLength:totalBytesExpectedToWrite]; + } + + if (self.mode == SPUDownloadModePersistent && bytesWritten >= 0) { + [self.delegate downloaderDidReceiveDataOfLength:(uint64_t)bytesWritten]; + } +} + +- (void)downloadDidFinish +{ + assert(self.downloadFilename != nil); + + SPUDownloadData *downloadData = nil; + if (self.mode == SPUDownloadModeTemporary) { + NSData *data = [NSData dataWithContentsOfFile:self.downloadFilename]; + if (data != nil) { + NSURLResponse *response = self.download.response; + assert(response != nil); + downloadData = [[SPUDownloadData alloc] initWithData:data textEncodingName:response.textEncodingName MIMEType:response.MIMEType]; + } + } + + self.download = nil; + + switch (self.mode) { + case SPUDownloadModeTemporary: + if (downloadData != nil) { + [self.delegate downloaderDidFinishWithTemporaryDownloadData:downloadData]; + } else { + [self.delegate downloaderDidFailWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUDownloadError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to read temporary downloaded data from %@", self.downloadFilename]}]]; + } + break; + case SPUDownloadModePersistent: + [self.delegate downloaderDidFinishWithTemporaryDownloadData:nil]; + break; + } + + [self cleanup]; +} + +- (void)URLSession:(NSURLSession *)__unused session task:(NSURLSessionTask *)__unused task didCompleteWithError:(NSError *)error +{ + self.download = nil; + [self.delegate downloaderDidFailWithError:error]; + [self cleanup]; +} + +// NSURLDownload has a [downlaod:shouldDecodeSourceDataOfMIMEType:] to determine if the data should be decoded. +// This does not exist for NSURLSessionDownloadTask and appears unnecessary. Data tasks will decode data, but not download tasks. + +@end diff --git a/Sparkle/SPUDownloaderDelegate.h b/Sparkle/SPUDownloaderDelegate.h new file mode 100755 index 00000000..760db6c3 --- /dev/null +++ b/Sparkle/SPUDownloaderDelegate.h @@ -0,0 +1,34 @@ +// +// SPUDownloaderDelegate.h +// Sparkle +// +// Created by Mayur Pawashe on 4/1/16. +// Copyright © 2016 Sparkle Project. All rights reserved. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@class SPUDownloadData; + +@protocol SPUDownloaderDelegate + +// This is only invoked for persistent downloads +- (void)downloaderDidSetDestinationName:(NSString *)destinationName temporaryDirectory:(NSString *)temporaryDirectory; + +// Under rare cases, this may be called more than once, in which case the current progress should be reset back to 0 +// This is only invoked for persistent downloads +- (void)downloaderDidReceiveExpectedContentLength:(int64_t)expectedContentLength; + +// This is only invoked for persistent downloads +- (void)downloaderDidReceiveDataOfLength:(uint64_t)length; + +// downloadData is nil if this is a persisent download, otherwise it's non-nil if it's a temporary download +- (void)downloaderDidFinishWithTemporaryDownloadData:(SPUDownloadData * _Nullable)downloadData; + +- (void)downloaderDidFailWithError:(NSError *)error; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Sparkle/SPUDownloaderProtocol.h b/Sparkle/SPUDownloaderProtocol.h new file mode 100755 index 00000000..72982cfd --- /dev/null +++ b/Sparkle/SPUDownloaderProtocol.h @@ -0,0 +1,24 @@ +// +// SPUDownloaderProtocol.h +// PersistentDownloader +// +// Created by Mayur Pawashe on 4/1/16. +// Copyright © 2016 Sparkle Project. All rights reserved. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@class SPUURLRequest; + +// The protocol that this service will vend as its API. This header file will also need to be visible to the process hosting the service. +@protocol SPUDownloaderProtocol + +- (void)startPersistentDownloadWithRequest:(SPUURLRequest *)request bundleIdentifier:(NSString *)bundleIdentifier desiredFilename:(NSString *)desiredFilename; + +- (void)startTemporaryDownloadWithRequest:(SPUURLRequest *)request; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Sparkle/SPULocalCacheDirectory.h b/Sparkle/SPULocalCacheDirectory.h new file mode 100755 index 00000000..eff88ba9 --- /dev/null +++ b/Sparkle/SPULocalCacheDirectory.h @@ -0,0 +1,35 @@ +// +// SULocalCacheDirectory.h +// Sparkle +// +// Created by Mayur Pawashe on 6/23/16. +// Copyright © 2016 Sparkle Project. All rights reserved. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface SPULocalCacheDirectory : NSObject + +// Returns a path to a suitable cache directory to create specifically for Sparkle +// Intermediate directories to this path may not exist yet +// This path may depend on the type of running process, +// such that sandboxed vs non-sandboxed processes could yield different paths +// The caller should create a subdirectory from the path that is returned here so they don't have files that +// conflict with other callers. Once that subdirectory name is decided, the caller can remove old items inside it (using +removeOldItemsInDirectory:) +// and then create a unique temporary directory inside it (using +createUniqueDirectoryInDirectory:) ++ (NSString *)cachePathForBundleIdentifier:(NSString *)bundleIdentifier; + +// Remove old files inside a directory +// A caller may want to invoke this on a directory they own rather than remove and re-create an entire directory +// This does nothing if the supplied directory does not exist yet ++ (void)removeOldItemsInDirectory:(NSString *)directory; + +// Create a unique directory inside a parent directory +// The parent directory doesn't have to exist yet. If it doesn't exist, intermediate directories will be created. ++ (NSString * _Nullable)createUniqueDirectoryInDirectory:(NSString *)directory; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Sparkle/SPULocalCacheDirectory.m b/Sparkle/SPULocalCacheDirectory.m new file mode 100755 index 00000000..975ec1f0 --- /dev/null +++ b/Sparkle/SPULocalCacheDirectory.m @@ -0,0 +1,80 @@ +// +// SULocalCacheDirectory.m +// Sparkle +// +// Created by Mayur Pawashe on 6/23/16. +// Copyright © 2016 Sparkle Project. All rights reserved. +// + +#import "SPULocalCacheDirectory.h" +#import "SULog.h" + + +#include "AppKitPrevention.h" + +static NSTimeInterval OLD_ITEM_DELETION_INTERVAL = 86400 * 10; // 10 days + +@implementation SPULocalCacheDirectory + +// It is important to note this may return a different path whether invoked from a sanboxed vs non-sandboxed process, or from a different user +// For this reason, this method should not be a part of SUHost because its behavior depends on what kind of process it's being invoked from ++ (NSString *)cachePathForBundleIdentifier:(NSString *)bundleIdentifier +{ + NSURL *cacheURL = [[NSFileManager defaultManager] URLForDirectory:NSCachesDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:NULL]; + assert(cacheURL != nil); + + NSString *resultPath = [[[cacheURL URLByAppendingPathComponent:bundleIdentifier] URLByAppendingPathComponent:@SPARKLE_BUNDLE_IDENTIFIER] path]; + assert(resultPath != nil); + + return resultPath; +} + ++ (void)removeOldItemsInDirectory:(NSString *)directory +{ + NSMutableArray *filePathsToRemove = [NSMutableArray array]; + NSFileManager *fileManager = [NSFileManager defaultManager]; + if ([fileManager fileExistsAtPath:directory]) { + NSDirectoryEnumerator *directoryEnumerator = [fileManager enumeratorAtPath:directory]; + NSDate *currentDate = [NSDate date]; + for (NSString *filename in directoryEnumerator) + { + NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:[directory stringByAppendingPathComponent:filename] error:NULL]; + if (fileAttributes != nil) + { + NSDate *lastModificationDate = fileAttributes[NSFileModificationDate]; + if ([currentDate timeIntervalSinceDate:lastModificationDate] >= OLD_ITEM_DELETION_INTERVAL) + { + [filePathsToRemove addObject:[directory stringByAppendingPathComponent:filename]]; + } + } + + [directoryEnumerator skipDescendants]; + } + + for (NSString *filename in filePathsToRemove) + { + [fileManager removeItemAtPath:filename error:NULL]; + } + } +} + ++ (NSString * _Nullable)createUniqueDirectoryInDirectory:(NSString *)directory +{ + NSFileManager *fileManager = [NSFileManager defaultManager]; + NSError *createError = nil; + if (![fileManager createDirectoryAtPath:directory withIntermediateDirectories:YES attributes:nil error:&createError]) { + SULog(SULogLevelError, @"Failed to create directory with intermediate components at %@ with error %@", directory, createError); + return nil; + } + + NSString *templateString = [directory stringByAppendingPathComponent:@"XXXXXXXXX"]; + char buffer[PATH_MAX] = {0}; + if ([templateString getFileSystemRepresentation:buffer maxLength:sizeof(buffer)]) { + if (mkdtemp(buffer) != NULL) { + return [[NSString alloc] initWithUTF8String:buffer]; + } + } + return nil; +} + +@end diff --git a/Sparkle/SPUURLRequest.h b/Sparkle/SPUURLRequest.h new file mode 100755 index 00000000..62a4a70b --- /dev/null +++ b/Sparkle/SPUURLRequest.h @@ -0,0 +1,31 @@ +// +// SPUURLRequest.h +// Sparkle +// +// Created by Mayur Pawashe on 5/19/16. +// Copyright © 2016 Sparkle Project. All rights reserved. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +// A class that wraps NSURLRequest and implements NSSecureCoding +// This class exists because NSURLRequest did not support NSSecureCoding in macOS 10.8 +// I have not verified if NSURLRequest in 10.9 implements NSSecureCoding or not +@interface SPUURLRequest : NSObject + +// Creates a new URL request +// Only these properties are currently tracked: +// * URL +// * Cache policy +// * Timeout interval +// * HTTP header fields +// * networkServiceType ++ (instancetype)URLRequestWithRequest:(NSURLRequest *)request; + +@property (nonatomic, readonly) NSURLRequest *request; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Sparkle/SPUURLRequest.m b/Sparkle/SPUURLRequest.m new file mode 100755 index 00000000..f04f4998 --- /dev/null +++ b/Sparkle/SPUURLRequest.m @@ -0,0 +1,94 @@ +// +// SPUURLRequest.m +// Sparkle +// +// Created by Mayur Pawashe on 5/19/16. +// Copyright © 2016 Sparkle Project. All rights reserved. +// + +#import "SPUURLRequest.h" + + +#include "AppKitPrevention.h" + +static NSString *SPUURLRequestURLKey = @"SPUURLRequestURL"; +static NSString *SPUURLRequestCachePolicyKey = @"SPUURLRequestCachePolicy"; +static NSString *SPUURLRequestTimeoutIntervalKey = @"SPUURLRequestTimeoutInterval"; +static NSString *SPUURLRequestHttpHeaderFieldsKey = @"SPUURLRequestHttpHeaderFields"; +static NSString *SPUURLRequestNetworkServiceTypeKey = @"SPUURLRequestNetworkServiceType"; + +@interface SPUURLRequest () + +@property (nonatomic, readonly) NSURL *url; +@property (nonatomic, readonly) NSURLRequestCachePolicy cachePolicy; +@property (nonatomic, readonly) NSTimeInterval timeoutInterval; +@property (nonatomic, readonly, nullable) NSDictionary *httpHeaderFields; +@property (nonatomic, readonly) NSURLRequestNetworkServiceType networkServiceType; + +@end + +@implementation SPUURLRequest + +@synthesize url = _url; +@synthesize cachePolicy = _cachePolicy; +@synthesize timeoutInterval = _timeoutInterval; +@synthesize httpHeaderFields = _httpHeaderFields; +@synthesize networkServiceType = _networkServiceType; + +- (instancetype)initWithURL:(NSURL *)url cachePolicy:(NSURLRequestCachePolicy)cachePolicy timeoutInterval:(NSTimeInterval)timeoutInterval httpHeaderFields:(NSDictionary *)httpHeaderFields networkServiceType:(NSURLRequestNetworkServiceType)networkServiceType +{ + self = [super init]; + if (self != nil) { + _url = url; + _cachePolicy = cachePolicy; + _timeoutInterval = timeoutInterval; + _httpHeaderFields = httpHeaderFields; + _networkServiceType = networkServiceType; + } + return self; +} + ++ (instancetype)URLRequestWithRequest:(NSURLRequest *)request +{ + return [[[self class] alloc] initWithURL:request.URL cachePolicy:request.cachePolicy timeoutInterval:request.timeoutInterval httpHeaderFields:request.allHTTPHeaderFields networkServiceType:request.networkServiceType]; +} + ++ (BOOL)supportsSecureCoding +{ + return YES; +} + +- (void)encodeWithCoder:(NSCoder *)coder +{ + [coder encodeObject:self.url forKey:SPUURLRequestURLKey]; + [coder encodeInteger:self.cachePolicy forKey:SPUURLRequestCachePolicyKey]; + [coder encodeDouble:self.timeoutInterval forKey:SPUURLRequestTimeoutIntervalKey]; + [coder encodeInteger:self.networkServiceType forKey:SPUURLRequestNetworkServiceTypeKey]; + + if (self.httpHeaderFields != nil) { + [coder encodeObject:self.httpHeaderFields forKey:SPUURLRequestHttpHeaderFieldsKey]; + } +} + +- (instancetype)initWithCoder:(NSCoder *)decoder +{ + NSURL *url = [decoder decodeObjectOfClass:[NSURL class] forKey:SPUURLRequestURLKey]; + NSURLRequestCachePolicy cachePolicy = (NSURLRequestCachePolicy)[decoder decodeIntegerForKey:SPUURLRequestCachePolicyKey]; + NSTimeInterval timeoutInterval = [decoder decodeDoubleForKey:SPUURLRequestTimeoutIntervalKey]; + NSDictionary *httpHeaderFields = [decoder decodeObjectOfClasses:[NSSet setWithArray:@[[NSDictionary class], [NSString class]]] forKey:SPUURLRequestHttpHeaderFieldsKey]; + NSURLRequestNetworkServiceType networkServiceType = (NSURLRequestNetworkServiceType)[decoder decodeIntegerForKey:SPUURLRequestNetworkServiceTypeKey]; + + return [self initWithURL:url cachePolicy:cachePolicy timeoutInterval:timeoutInterval httpHeaderFields:httpHeaderFields networkServiceType:networkServiceType]; +} + +- (NSURLRequest *)request +{ + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:self.url cachePolicy:self.cachePolicy timeoutInterval:self.timeoutInterval]; + if (self.httpHeaderFields != nil) { + request.allHTTPHeaderFields = self.httpHeaderFields; + } + request.networkServiceType = self.networkServiceType; + return [request copy]; +} + +@end From dc8e8b775afda072b86fedb8e788ba16ada08f7d Mon Sep 17 00:00:00 2001 From: Deadpikle Date: Wed, 20 Dec 2017 11:13:41 -0500 Subject: [PATCH 02/20] Remove unnecessary delegate name in header --- Sparkle/SUAppcast.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sparkle/SUAppcast.h b/Sparkle/SUAppcast.h index d7363d0a..f2f43389 100644 --- a/Sparkle/SUAppcast.h +++ b/Sparkle/SUAppcast.h @@ -19,7 +19,7 @@ NS_ASSUME_NONNULL_BEGIN @class SUAppcastItem; -SU_EXPORT @interface SUAppcast : NSObject +SU_EXPORT @interface SUAppcast : NSObject @property (copy, nullable) NSString *userAgentString; From dc85d6386153ca36867a26010d1da286bab92e87 Mon Sep 17 00:00:00 2001 From: Deadpikle Date: Wed, 20 Dec 2017 11:14:02 -0500 Subject: [PATCH 03/20] Refactor download NSURLSession to a child class --- Sparkle.xcodeproj/project.pbxproj | 10 +++ Sparkle/SPUDownloader.m | 119 +------------------------ Sparkle/SPUDownloaderSession.h | 15 ++++ Sparkle/SPUDownloaderSession.m | 142 ++++++++++++++++++++++++++++++ Sparkle/SPUDownloader_Private.h | 38 ++++++++ 5 files changed, 206 insertions(+), 118 deletions(-) create mode 100644 Sparkle/SPUDownloaderSession.h create mode 100644 Sparkle/SPUDownloaderSession.m create mode 100644 Sparkle/SPUDownloader_Private.h diff --git a/Sparkle.xcodeproj/project.pbxproj b/Sparkle.xcodeproj/project.pbxproj index 06ddce0a..c74dae2f 100644 --- a/Sparkle.xcodeproj/project.pbxproj +++ b/Sparkle.xcodeproj/project.pbxproj @@ -59,6 +59,8 @@ 34074B9B1FEABD49001CB3A5 /* SPUURLRequest.h in Headers */ = {isa = PBXBuildFile; fileRef = 34074B991FEABD49001CB3A5 /* SPUURLRequest.h */; }; 34074B9E1FEABD5A001CB3A5 /* SPUDownloadData.m in Sources */ = {isa = PBXBuildFile; fileRef = 34074B9C1FEABD5A001CB3A5 /* SPUDownloadData.m */; }; 34074B9F1FEABD5A001CB3A5 /* SPUDownloadData.h in Headers */ = {isa = PBXBuildFile; fileRef = 34074B9D1FEABD5A001CB3A5 /* SPUDownloadData.h */; }; + 34074BA21FEABFD2001CB3A5 /* SPUDownloaderSession.h in Headers */ = {isa = PBXBuildFile; fileRef = 34074BA01FEABFD2001CB3A5 /* SPUDownloaderSession.h */; }; + 34074BA31FEABFD2001CB3A5 /* SPUDownloaderSession.m in Sources */ = {isa = PBXBuildFile; fileRef = 34074BA11FEABFD2001CB3A5 /* SPUDownloaderSession.m */; }; 3772FEA913DE0B6B00F79537 /* SUVersionDisplayProtocol.h in Headers */ = {isa = PBXBuildFile; fileRef = 3772FEA813DE0B6B00F79537 /* SUVersionDisplayProtocol.h */; settings = {ATTRIBUTES = (Public, ); }; }; 55C14BD4136EEFCE00649790 /* Autoupdate.m in Sources */ = {isa = PBXBuildFile; fileRef = 55C14BD3136EEFCE00649790 /* Autoupdate.m */; }; 55C14BD9136EF00C00649790 /* SUStatus.xib in Resources */ = {isa = PBXBuildFile; fileRef = 55C14BD8136EF00C00649790 /* SUStatus.xib */; }; @@ -540,6 +542,9 @@ 34074B991FEABD49001CB3A5 /* SPUURLRequest.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SPUURLRequest.h; sourceTree = ""; }; 34074B9C1FEABD5A001CB3A5 /* SPUDownloadData.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SPUDownloadData.m; sourceTree = ""; }; 34074B9D1FEABD5A001CB3A5 /* SPUDownloadData.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SPUDownloadData.h; sourceTree = ""; }; + 34074BA01FEABFD2001CB3A5 /* SPUDownloaderSession.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SPUDownloaderSession.h; sourceTree = ""; }; + 34074BA11FEABFD2001CB3A5 /* SPUDownloaderSession.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = SPUDownloaderSession.m; sourceTree = ""; }; + 34074BA41FEAC0BC001CB3A5 /* SPUDownloader_Private.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SPUDownloader_Private.h; sourceTree = ""; }; 3772FEA813DE0B6B00F79537 /* SUVersionDisplayProtocol.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SUVersionDisplayProtocol.h; sourceTree = ""; }; 4607BEA21948443800EF8DA4 /* nb */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = nb; path = nb.lproj/Sparkle.strings; sourceTree = ""; }; 4607BEA31948443800EF8DA4 /* nb */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = nb; path = nb.lproj/SUAutomaticUpdateAlert.xib; sourceTree = ""; }; @@ -1107,6 +1112,9 @@ 34074B9C1FEABD5A001CB3A5 /* SPUDownloadData.m */, 34074B8D1FEABD08001CB3A5 /* SPUDownloader.h */, 34074B8C1FEABD08001CB3A5 /* SPUDownloader.m */, + 34074BA41FEAC0BC001CB3A5 /* SPUDownloader_Private.h */, + 34074BA01FEABFD2001CB3A5 /* SPUDownloaderSession.h */, + 34074BA11FEABFD2001CB3A5 /* SPUDownloaderSession.m */, 34074B8E1FEABD08001CB3A5 /* SPUDownloaderDelegate.h */, 34074B8F1FEABD08001CB3A5 /* SPUDownloaderProtocol.h */, 34074B941FEABD23001CB3A5 /* SPULocalCacheDirectory.h */, @@ -1472,6 +1480,7 @@ 61A354550DF113C70076ECB1 /* SUUserInitiatedUpdateDriver.h in Headers */, 61A2259E0D1C495D00430CCD /* SUVersionComparisonProtocol.h in Headers */, 3772FEA913DE0B6B00F79537 /* SUVersionDisplayProtocol.h in Headers */, + 34074BA21FEABFD2001CB3A5 /* SPUDownloaderSession.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -2052,6 +2061,7 @@ 5D06E8EC0FD68CE4005AE3F6 /* SUBinaryDeltaApply.m in Sources */, 34074B971FEABD24001CB3A5 /* SPULocalCacheDirectory.m in Sources */, 5D06E8ED0FD68CE4005AE3F6 /* SUBinaryDeltaCommon.m in Sources */, + 34074BA31FEABFD2001CB3A5 /* SPUDownloaderSession.m in Sources */, 5D06E93A0FD69271005AE3F6 /* SUBinaryDeltaUnarchiver.m in Sources */, 72316BDA1E0E17180039EFD9 /* SUBundleIcon.m in Sources */, 61B078CF15A5FB6100600039 /* SUCodeSigningVerifier.m in Sources */, diff --git a/Sparkle/SPUDownloader.m b/Sparkle/SPUDownloader.m index 2f0447de..8e3d776f 100755 --- a/Sparkle/SPUDownloader.m +++ b/Sparkle/SPUDownloader.m @@ -12,30 +12,13 @@ #import "SPUURLRequest.h" #import "SPUDownloadData.h" #import "SUErrors.h" - +#import "SPUDownloader_Private.h" #include "AppKitPrevention.h" -typedef NS_ENUM(NSUInteger, SPUDownloadMode) -{ - SPUDownloadModePersistent, - SPUDownloadModeTemporary -}; - -static NSString *SUDownloadingReason = @"Downloading update related file"; - @interface SPUDownloader () -// Delegate is intentionally strongly referenced; see header -@property (nonatomic) id delegate; -@property (nonatomic) NSURLSessionDownloadTask *download; @property (nonatomic) NSURLSession *downloadSession; -@property (nonatomic, copy) NSString *bundleIdentifier; -@property (nonatomic, copy) NSString *desiredFilename; -@property (nonatomic, copy) NSString *downloadFilename; -@property (nonatomic) BOOL disabledAutomaticTermination; -@property (nonatomic) SPUDownloadMode mode; -@property (nonatomic) BOOL receivedExpectedBytes; @end @@ -43,7 +26,6 @@ static NSString *SUDownloadingReason = @"Downloading update related file"; @synthesize delegate = _delegate; @synthesize download = _download; -@synthesize downloadSession = _downloadSession; @synthesize bundleIdentifier = _bundleIdentifier; @synthesize desiredFilename = _desiredFilename; @synthesize downloadFilename = _downloadFilename; @@ -74,33 +56,10 @@ static NSString *SUDownloadingReason = @"Downloading update related file"; - (void)startPersistentDownloadWithRequest:(SPUURLRequest *)request bundleIdentifier:(NSString *)bundleIdentifier desiredFilename:(NSString *)desiredFilename { - dispatch_async(dispatch_get_main_queue(), ^{ - if (self.download == nil && self.delegate != nil) { - // Prevent service from automatically terminating while downloading the update asynchronously without any reply blocks - [[NSProcessInfo processInfo] disableAutomaticTermination:SUDownloadingReason]; - self.disabledAutomaticTermination = YES; - - self.mode = SPUDownloadModePersistent; - self.desiredFilename = desiredFilename; - self.bundleIdentifier = bundleIdentifier; - - [self startDownloadWithRequest:request]; - } - }); } - (void)startTemporaryDownloadWithRequest:(SPUURLRequest *)request { - dispatch_async(dispatch_get_main_queue(), ^{ - if (self.download == nil && self.delegate != nil) { - // Prevent service from automatically terminating while downloading the update asynchronously without any reply blocks - [[NSProcessInfo processInfo] disableAutomaticTermination:SUDownloadingReason]; - self.disabledAutomaticTermination = YES; - - self.mode = SPUDownloadModeTemporary; - [self startDownloadWithRequest:request]; - } - }); } - (void)enableAutomaticTermination @@ -126,72 +85,6 @@ static NSString *SUDownloadingReason = @"Downloading update related file"; } } -- (void)URLSession:(NSURLSession *)__unused session downloadTask:(NSURLSessionDownloadTask *)__unused downloadTask didFinishDownloadingToURL:(NSURL *)location -{ - if (self.mode == SPUDownloadModeTemporary) - { - self.downloadFilename = location.path; - [self downloadDidFinish]; // file is already in a system temp dir - } - else - { - // Remove our old caches path so we don't start accumulating files in there - NSString *rootPersistentDownloadCachePath = [[SPULocalCacheDirectory cachePathForBundleIdentifier:self.bundleIdentifier] stringByAppendingPathComponent:@"PersistentDownloads"]; - - [SPULocalCacheDirectory removeOldItemsInDirectory:rootPersistentDownloadCachePath]; - - NSString *tempDir = [SPULocalCacheDirectory createUniqueDirectoryInDirectory:rootPersistentDownloadCachePath]; - if (tempDir == nil) - { - // Okay, something's really broken with this user's file structure. - [self.download cancel]; - self.download = nil; - - NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUTemporaryDirectoryError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Can't make a temporary directory for the update download at %@.", tempDir] }]; - - [self.delegate downloaderDidFailWithError:error]; - } else { - NSString *downloadFileName = self.desiredFilename; - NSString *downloadFileNameDirectory = [tempDir stringByAppendingPathComponent:downloadFileName]; - - NSError *createError = nil; - if (![[NSFileManager defaultManager] createDirectoryAtPath:downloadFileNameDirectory withIntermediateDirectories:NO attributes:nil error:&createError]) { - NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUTemporaryDirectoryError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Can't make a download file name %@ directory inside temporary directory for the update download at %@.", downloadFileName, downloadFileNameDirectory] }]; - - [self.delegate downloaderDidFailWithError:error]; - } else { - NSString *name = self.download.response.suggestedFilename; - if (!name) { - name = location.lastPathComponent; // This likely contains nothing useful to identify the file (e.g. CFNetworkDownload_87LVIz.tmp) - } - NSString *toPath = [downloadFileNameDirectory stringByAppendingPathComponent:name]; - NSString *fromPath = location.path; // suppress moveItemAtPath: non-null warning - NSError *error = nil; - if ([[NSFileManager defaultManager] moveItemAtPath:fromPath toPath:toPath error:&error]) { - self.downloadFilename = toPath; - [self.delegate downloaderDidSetDestinationName:name temporaryDirectory:downloadFileNameDirectory]; - [self downloadDidFinish]; - } else { - [self.delegate downloaderDidFailWithError:error]; - } - } - } - } -} - -- (void)URLSession:(NSURLSession *)__unused session downloadTask:(NSURLSessionDownloadTask *)__unused downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)__unused totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite -{ - - if (self.mode == SPUDownloadModePersistent && totalBytesExpectedToWrite > 0 && !self.receivedExpectedBytes) { - self.receivedExpectedBytes = YES; - [self.delegate downloaderDidReceiveExpectedContentLength:totalBytesExpectedToWrite]; - } - - if (self.mode == SPUDownloadModePersistent && bytesWritten >= 0) { - [self.delegate downloaderDidReceiveDataOfLength:(uint64_t)bytesWritten]; - } -} - - (void)downloadDidFinish { assert(self.downloadFilename != nil); @@ -224,14 +117,4 @@ static NSString *SUDownloadingReason = @"Downloading update related file"; [self cleanup]; } -- (void)URLSession:(NSURLSession *)__unused session task:(NSURLSessionTask *)__unused task didCompleteWithError:(NSError *)error -{ - self.download = nil; - [self.delegate downloaderDidFailWithError:error]; - [self cleanup]; -} - -// NSURLDownload has a [downlaod:shouldDecodeSourceDataOfMIMEType:] to determine if the data should be decoded. -// This does not exist for NSURLSessionDownloadTask and appears unnecessary. Data tasks will decode data, but not download tasks. - @end diff --git a/Sparkle/SPUDownloaderSession.h b/Sparkle/SPUDownloaderSession.h new file mode 100644 index 00000000..b8a25bf1 --- /dev/null +++ b/Sparkle/SPUDownloaderSession.h @@ -0,0 +1,15 @@ +// +// SPUDownloaderSession.h +// Sparkle +// +// Created by Deadpikle on 12/20/17. +// Copyright © 2017 Sparkle Project. All rights reserved. +// + +#import +#import "SPUDownloader.h" +#import "SPUDownloaderProtocol.h" + +@interface SPUDownloaderSession : SPUDownloader + +@end diff --git a/Sparkle/SPUDownloaderSession.m b/Sparkle/SPUDownloaderSession.m new file mode 100644 index 00000000..d9abbcf4 --- /dev/null +++ b/Sparkle/SPUDownloaderSession.m @@ -0,0 +1,142 @@ +// +// SPUDownloaderSession.m +// Sparkle +// +// Created by Deadpikle on 12/20/17. +// Copyright © 2017 Sparkle Project. All rights reserved. +// + +#import "SPUDownloaderSession.h" +#import "SPUURLRequest.h" +#import "SPUDownloader_Private.h" +#import "SPULocalCacheDirectory.h" +#import "SUErrors.h" + +@interface SPUDownloaderSession () + +@property (nonatomic) NSURLSession *downloadSession; + +@end + +@implementation SPUDownloaderSession + +@synthesize downloadSession = _downloadSession; + +- (void)startDownloadWithRequest:(SPUURLRequest *)request +{ + self.downloadSession = [NSURLSession + sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] + delegate:self + delegateQueue:[NSOperationQueue mainQueue]]; + self.download = [self.downloadSession downloadTaskWithRequest:request.request]; + [self.download resume]; +} + +- (void)startPersistentDownloadWithRequest:(SPUURLRequest *)request bundleIdentifier:(NSString *)bundleIdentifier desiredFilename:(NSString *)desiredFilename +{ + dispatch_async(dispatch_get_main_queue(), ^{ + if (self.download == nil && self.delegate != nil) { + // Prevent service from automatically terminating while downloading the update asynchronously without any reply blocks + [[NSProcessInfo processInfo] disableAutomaticTermination:SUDownloadingReason]; + self.disabledAutomaticTermination = YES; + + self.mode = SPUDownloadModePersistent; + self.desiredFilename = desiredFilename; + self.bundleIdentifier = bundleIdentifier; + + [self startDownloadWithRequest:request]; + } + }); +} + +- (void)startTemporaryDownloadWithRequest:(SPUURLRequest *)request +{ + dispatch_async(dispatch_get_main_queue(), ^{ + if (self.download == nil && self.delegate != nil) { + // Prevent service from automatically terminating while downloading the update asynchronously without any reply blocks + [[NSProcessInfo processInfo] disableAutomaticTermination:SUDownloadingReason]; + self.disabledAutomaticTermination = YES; + + self.mode = SPUDownloadModeTemporary; + [self startDownloadWithRequest:request]; + } + }); +} + +- (void)URLSession:(NSURLSession *)__unused session downloadTask:(NSURLSessionDownloadTask *)__unused downloadTask didFinishDownloadingToURL:(NSURL *)location +{ + if (self.mode == SPUDownloadModeTemporary) + { + self.downloadFilename = location.path; + [self downloadDidFinish]; // file is already in a system temp dir + } + else + { + // Remove our old caches path so we don't start accumulating files in there + NSString *rootPersistentDownloadCachePath = [[SPULocalCacheDirectory cachePathForBundleIdentifier:self.bundleIdentifier] stringByAppendingPathComponent:@"PersistentDownloads"]; + + [SPULocalCacheDirectory removeOldItemsInDirectory:rootPersistentDownloadCachePath]; + + NSString *tempDir = [SPULocalCacheDirectory createUniqueDirectoryInDirectory:rootPersistentDownloadCachePath]; + if (tempDir == nil) + { + // Okay, something's really broken with this user's file structure. + [self.download cancel]; + self.download = nil; + + NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUTemporaryDirectoryError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Can't make a temporary directory for the update download at %@.", tempDir] }]; + + [self.delegate downloaderDidFailWithError:error]; + } else { + NSString *downloadFileName = self.desiredFilename; + NSString *downloadFileNameDirectory = [tempDir stringByAppendingPathComponent:downloadFileName]; + + NSError *createError = nil; + if (![[NSFileManager defaultManager] createDirectoryAtPath:downloadFileNameDirectory withIntermediateDirectories:NO attributes:nil error:&createError]) { + NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUTemporaryDirectoryError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Can't make a download file name %@ directory inside temporary directory for the update download at %@.", downloadFileName, downloadFileNameDirectory] }]; + + [self.delegate downloaderDidFailWithError:error]; + } else { + NSString *name = self.download.response.suggestedFilename; + if (!name) { + name = location.lastPathComponent; // This likely contains nothing useful to identify the file (e.g. CFNetworkDownload_87LVIz.tmp) + } + NSString *toPath = [downloadFileNameDirectory stringByAppendingPathComponent:name]; + NSString *fromPath = location.path; // suppress moveItemAtPath: non-null warning + NSError *error = nil; + if ([[NSFileManager defaultManager] moveItemAtPath:fromPath toPath:toPath error:&error]) { + self.downloadFilename = toPath; + [self.delegate downloaderDidSetDestinationName:name temporaryDirectory:downloadFileNameDirectory]; + [self downloadDidFinish]; + } else { + [self.delegate downloaderDidFailWithError:error]; + } + } + } + } +} + +- (void)URLSession:(NSURLSession *)__unused session downloadTask:(NSURLSessionDownloadTask *)__unused downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)__unused totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite +{ + + if (self.mode == SPUDownloadModePersistent && totalBytesExpectedToWrite > 0 && !self.receivedExpectedBytes) { + self.receivedExpectedBytes = YES; + [self.delegate downloaderDidReceiveExpectedContentLength:totalBytesExpectedToWrite]; + } + + if (self.mode == SPUDownloadModePersistent && bytesWritten >= 0) { + [self.delegate downloaderDidReceiveDataOfLength:(uint64_t)bytesWritten]; + } +} + +- (void)URLSession:(NSURLSession *)__unused session task:(NSURLSessionTask *)__unused task didCompleteWithError:(NSError *)error +{ + self.download = nil; + [self.delegate downloaderDidFailWithError:error]; + [self cleanup]; +} + +// NSURLDownload has a [downlaod:shouldDecodeSourceDataOfMIMEType:] to determine if the data should be decoded. +// This does not exist for NSURLSessionDownloadTask and appears unnecessary. Data tasks will decode data, but not download tasks. + +@end diff --git a/Sparkle/SPUDownloader_Private.h b/Sparkle/SPUDownloader_Private.h new file mode 100644 index 00000000..254c7846 --- /dev/null +++ b/Sparkle/SPUDownloader_Private.h @@ -0,0 +1,38 @@ +// +// SPUDownloader_Private.h +// Sparkle +// +// Created by Deadpikle on 12/20/17. +// Copyright © 2017 Sparkle Project. All rights reserved. +// + +#ifndef SPUDownloader_Private_h +#define SPUDownloader_Private_h + +#import "SPUDownloaderDelegate.h" + +typedef NS_ENUM(NSUInteger, SPUDownloadMode) +{ + SPUDownloadModePersistent, + SPUDownloadModeTemporary +}; + +static NSString *SUDownloadingReason = @"Downloading update related file"; + +@interface SPUDownloader () + +// Delegate is intentionally strongly referenced; see header +@property (nonatomic) id delegate; +@property (nonatomic) NSURLSessionDownloadTask *download; +@property (nonatomic, copy) NSString *bundleIdentifier; +@property (nonatomic, copy) NSString *desiredFilename; +@property (nonatomic, copy) NSString *downloadFilename; +@property (nonatomic) BOOL disabledAutomaticTermination; +@property (nonatomic) SPUDownloadMode mode; +@property (nonatomic) BOOL receivedExpectedBytes; + +-(void)downloadDidFinish; + +@end + +#endif /* SPUDownloader_Private_h */ From 8a0474d6440945f3a51ec13cb1b1765152822fe8 Mon Sep 17 00:00:00 2001 From: Deadpikle Date: Wed, 20 Dec 2017 11:43:13 -0500 Subject: [PATCH 04/20] Continue refactor of downloader to two classes --- Sparkle.xcodeproj/project.pbxproj | 8 ++ Sparkle/SPUDownloader.m | 39 +------ Sparkle/SPUDownloaderDeprecated.h | 13 +++ Sparkle/SPUDownloaderDeprecated.m | 177 ++++++++++++++++++++++++++++++ Sparkle/SPUDownloaderProtocol.h | 4 + Sparkle/SPUDownloaderSession.h | 2 +- Sparkle/SPUDownloaderSession.m | 30 +++++ Sparkle/SPUDownloader_Private.h | 3 +- 8 files changed, 238 insertions(+), 38 deletions(-) create mode 100644 Sparkle/SPUDownloaderDeprecated.h create mode 100644 Sparkle/SPUDownloaderDeprecated.m diff --git a/Sparkle.xcodeproj/project.pbxproj b/Sparkle.xcodeproj/project.pbxproj index c74dae2f..57ef529e 100644 --- a/Sparkle.xcodeproj/project.pbxproj +++ b/Sparkle.xcodeproj/project.pbxproj @@ -61,6 +61,8 @@ 34074B9F1FEABD5A001CB3A5 /* SPUDownloadData.h in Headers */ = {isa = PBXBuildFile; fileRef = 34074B9D1FEABD5A001CB3A5 /* SPUDownloadData.h */; }; 34074BA21FEABFD2001CB3A5 /* SPUDownloaderSession.h in Headers */ = {isa = PBXBuildFile; fileRef = 34074BA01FEABFD2001CB3A5 /* SPUDownloaderSession.h */; }; 34074BA31FEABFD2001CB3A5 /* SPUDownloaderSession.m in Sources */ = {isa = PBXBuildFile; fileRef = 34074BA11FEABFD2001CB3A5 /* SPUDownloaderSession.m */; }; + 34074BA71FEAC417001CB3A5 /* SPUDownloaderDeprecated.h in Headers */ = {isa = PBXBuildFile; fileRef = 34074BA51FEAC417001CB3A5 /* SPUDownloaderDeprecated.h */; }; + 34074BA81FEAC417001CB3A5 /* SPUDownloaderDeprecated.m in Sources */ = {isa = PBXBuildFile; fileRef = 34074BA61FEAC417001CB3A5 /* SPUDownloaderDeprecated.m */; }; 3772FEA913DE0B6B00F79537 /* SUVersionDisplayProtocol.h in Headers */ = {isa = PBXBuildFile; fileRef = 3772FEA813DE0B6B00F79537 /* SUVersionDisplayProtocol.h */; settings = {ATTRIBUTES = (Public, ); }; }; 55C14BD4136EEFCE00649790 /* Autoupdate.m in Sources */ = {isa = PBXBuildFile; fileRef = 55C14BD3136EEFCE00649790 /* Autoupdate.m */; }; 55C14BD9136EF00C00649790 /* SUStatus.xib in Resources */ = {isa = PBXBuildFile; fileRef = 55C14BD8136EF00C00649790 /* SUStatus.xib */; }; @@ -545,6 +547,8 @@ 34074BA01FEABFD2001CB3A5 /* SPUDownloaderSession.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SPUDownloaderSession.h; sourceTree = ""; }; 34074BA11FEABFD2001CB3A5 /* SPUDownloaderSession.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = SPUDownloaderSession.m; sourceTree = ""; }; 34074BA41FEAC0BC001CB3A5 /* SPUDownloader_Private.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SPUDownloader_Private.h; sourceTree = ""; }; + 34074BA51FEAC417001CB3A5 /* SPUDownloaderDeprecated.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SPUDownloaderDeprecated.h; sourceTree = ""; }; + 34074BA61FEAC417001CB3A5 /* SPUDownloaderDeprecated.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = SPUDownloaderDeprecated.m; sourceTree = ""; }; 3772FEA813DE0B6B00F79537 /* SUVersionDisplayProtocol.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SUVersionDisplayProtocol.h; sourceTree = ""; }; 4607BEA21948443800EF8DA4 /* nb */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = nb; path = nb.lproj/Sparkle.strings; sourceTree = ""; }; 4607BEA31948443800EF8DA4 /* nb */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = nb; path = nb.lproj/SUAutomaticUpdateAlert.xib; sourceTree = ""; }; @@ -1113,6 +1117,8 @@ 34074B8D1FEABD08001CB3A5 /* SPUDownloader.h */, 34074B8C1FEABD08001CB3A5 /* SPUDownloader.m */, 34074BA41FEAC0BC001CB3A5 /* SPUDownloader_Private.h */, + 34074BA51FEAC417001CB3A5 /* SPUDownloaderDeprecated.h */, + 34074BA61FEAC417001CB3A5 /* SPUDownloaderDeprecated.m */, 34074BA01FEABFD2001CB3A5 /* SPUDownloaderSession.h */, 34074BA11FEABFD2001CB3A5 /* SPUDownloaderSession.m */, 34074B8E1FEABD08001CB3A5 /* SPUDownloaderDelegate.h */, @@ -1429,6 +1435,7 @@ 61299B3609CB04E000B7442F /* Sparkle.h in Headers */, 61B5FC0D09C4FC8200B25A18 /* SUAppcast.h in Headers */, 61B5FC7009C51F4A00B25A18 /* SUAppcastItem.h in Headers */, + 34074BA71FEAC417001CB3A5 /* SPUDownloaderDeprecated.h in Headers */, 72316BDE1E0E17910039EFD9 /* SUApplicationInfo.h in Headers */, 6120721209CC5C4B007FE0F6 /* SUAutomaticUpdateAlert.h in Headers */, 34074B921FEABD08001CB3A5 /* SPUDownloaderDelegate.h in Headers */, @@ -2081,6 +2088,7 @@ 618FA5060DAE8AB80026945C /* SUPlainInstaller.m in Sources */, 6101347C0DD2541A0049ACDF /* SUProbingUpdateDriver.m in Sources */, 61B93C0A0DD112FF00DCD2F8 /* SUScheduledUpdateDriver.m in Sources */, + 34074BA81FEAC417001CB3A5 /* SPUDownloaderDeprecated.m in Sources */, 61A225A50D1C4AC000430CCD /* SUStandardVersionComparator.m in Sources */, 6196CFFA09C72149000DC222 /* SUStatusController.m in Sources */, 61A2279D0D1CEE7600430CCD /* SUSystemProfiler.m in Sources */, diff --git a/Sparkle/SPUDownloader.m b/Sparkle/SPUDownloader.m index 8e3d776f..e863a4e7 100755 --- a/Sparkle/SPUDownloader.m +++ b/Sparkle/SPUDownloader.m @@ -18,14 +18,11 @@ @interface SPUDownloader () -@property (nonatomic) NSURLSession *downloadSession; - @end @implementation SPUDownloader @synthesize delegate = _delegate; -@synthesize download = _download; @synthesize bundleIdentifier = _bundleIdentifier; @synthesize desiredFilename = _desiredFilename; @synthesize downloadFilename = _downloadFilename; @@ -42,16 +39,6 @@ return self; } -- (void)startDownloadWithRequest:(SPUURLRequest *)request -{ - self.downloadSession = [NSURLSession - sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] - delegate:self - delegateQueue:[NSOperationQueue mainQueue]]; - self.download = [self.downloadSession downloadTaskWithRequest:request.request]; - [self.download resume]; -} - // Don't implement dealloc - make the client call cleanup, which is the only way to remove the reference cycle from the delegate anyway - (void)startPersistentDownloadWithRequest:(SPUURLRequest *)request bundleIdentifier:(NSString *)bundleIdentifier desiredFilename:(NSString *)desiredFilename @@ -73,9 +60,6 @@ - (void)cleanup { [self enableAutomaticTermination]; - [self.download cancel]; - self.download = nil; - self.downloadSession = nil; self.delegate = nil; if (self.mode == SPUDownloadModeTemporary && self.downloadFilename != nil) @@ -85,26 +69,13 @@ } } -- (void)downloadDidFinish + +-(void)downloadDidFinishWithData:(SPUDownloadData*)data { - assert(self.downloadFilename != nil); - - SPUDownloadData *downloadData = nil; - if (self.mode == SPUDownloadModeTemporary) { - NSData *data = [NSData dataWithContentsOfFile:self.downloadFilename]; - if (data != nil) { - NSURLResponse *response = self.download.response; - assert(response != nil); - downloadData = [[SPUDownloadData alloc] initWithData:data textEncodingName:response.textEncodingName MIMEType:response.MIMEType]; - } - } - - self.download = nil; - switch (self.mode) { case SPUDownloadModeTemporary: - if (downloadData != nil) { - [self.delegate downloaderDidFinishWithTemporaryDownloadData:downloadData]; + if (data != nil) { + [self.delegate downloaderDidFinishWithTemporaryDownloadData:data]; } else { [self.delegate downloaderDidFailWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUDownloadError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to read temporary downloaded data from %@", self.downloadFilename]}]]; } @@ -113,8 +84,6 @@ [self.delegate downloaderDidFinishWithTemporaryDownloadData:nil]; break; } - - [self cleanup]; } @end diff --git a/Sparkle/SPUDownloaderDeprecated.h b/Sparkle/SPUDownloaderDeprecated.h new file mode 100644 index 00000000..e667ef1b --- /dev/null +++ b/Sparkle/SPUDownloaderDeprecated.h @@ -0,0 +1,13 @@ +// +// SPUDownloaderDeprecated.h +// Sparkle +// +// Created by School of Computing Macbook on 12/20/17. +// Copyright © 2017 Sparkle Project. All rights reserved. +// + +#import "SPUDownloader.h" + +@interface SPUDownloaderDeprecated : SPUDownloader + +@end diff --git a/Sparkle/SPUDownloaderDeprecated.m b/Sparkle/SPUDownloaderDeprecated.m new file mode 100644 index 00000000..8ae29dbb --- /dev/null +++ b/Sparkle/SPUDownloaderDeprecated.m @@ -0,0 +1,177 @@ +// +// SPUDownloaderDeprecated.m +// Sparkle +// +// Created by School of Computing Macbook on 12/20/17. +// Copyright © 2017 Sparkle Project. All rights reserved. +// + +#import "SPUDownloaderDeprecated.h" +#import "SPUURLRequest.h" +#import "SPUDownloader_Private.h" +#import "SPUDownloadData.h" +#import "SPULocalCacheDirectory.h" +#import "SUErrors.h" + +@interface SPUDownloaderDeprecated () + +@property (nonatomic) NSURLDownload *download; +@property (nonatomic) NSURLResponse *response; + +@end + +@implementation SPUDownloaderDeprecated + +@synthesize download = _download; +@synthesize response = _response; + +- (void)startPersistentDownloadWithRequest:(SPUURLRequest *)request bundleIdentifier:(NSString *)bundleIdentifier desiredFilename:(NSString *)desiredFilename +{ + dispatch_async(dispatch_get_main_queue(), ^{ + if (self.download == nil && self.delegate != nil) { + // Prevent service from automatically terminating while downloading the update asynchronously without any reply blocks + [[NSProcessInfo processInfo] disableAutomaticTermination:SUDownloadingReason]; + self.disabledAutomaticTermination = YES; + + self.mode = SPUDownloadModePersistent; + self.desiredFilename = desiredFilename; + self.bundleIdentifier = bundleIdentifier; + + self.download = [[NSURLDownload alloc] initWithRequest:request.request delegate:self]; + } + }); +} + +- (void)startTemporaryDownloadWithRequest:(SPUURLRequest *)request +{ + dispatch_async(dispatch_get_main_queue(), ^{ + if (self.download == nil && self.delegate != nil) { + // Prevent service from automatically terminating while downloading the update asynchronously without any reply blocks + [[NSProcessInfo processInfo] disableAutomaticTermination:SUDownloadingReason]; + self.disabledAutomaticTermination = YES; + + self.mode = SPUDownloadModeTemporary; + self.download = [[NSURLDownload alloc] initWithRequest:request.request delegate:self]; + } + }); +} + +- (void)download:(NSURLDownload *)__unused d decideDestinationWithSuggestedFilename:(NSString *)name +{ + if (self.mode == SPUDownloadModeTemporary) + { + // Files downloaded in temporary mode should not last for very long, + // so it's ideal to place them in a system temporary directory + NSString *destinationFilename = NSTemporaryDirectory(); + if (destinationFilename) + { + destinationFilename = [destinationFilename stringByAppendingPathComponent:name]; + + [self.download setDestination:destinationFilename allowOverwrite:NO]; + } + } + else + { + // Remove our old caches path so we don't start accumulating files in there + NSString *rootPersistentDownloadCachePath = [[SPULocalCacheDirectory cachePathForBundleIdentifier:self.bundleIdentifier] stringByAppendingPathComponent:@"PersistentDownloads"]; + + [SPULocalCacheDirectory removeOldItemsInDirectory:rootPersistentDownloadCachePath]; + + NSString *tempDir = [SPULocalCacheDirectory createUniqueDirectoryInDirectory:rootPersistentDownloadCachePath]; + if (tempDir == nil) + { + // Okay, something's really broken with this user's file structure. + [self.download cancel]; + self.download = nil; + + NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUTemporaryDirectoryError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Can't make a temporary directory for the update download at %@.", tempDir] }]; + + [self.delegate downloaderDidFailWithError:error]; + } else { + NSString *downloadFileName = self.desiredFilename; + NSString *downloadFileNameDirectory = [tempDir stringByAppendingPathComponent:downloadFileName]; + + NSError *createError = nil; + if (![[NSFileManager defaultManager] createDirectoryAtPath:downloadFileNameDirectory withIntermediateDirectories:NO attributes:nil error:&createError]) { + NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUTemporaryDirectoryError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Can't make a download file name %@ directory inside temporary directory for the update download at %@.", downloadFileName, downloadFileNameDirectory] }]; + + [self.delegate downloaderDidFailWithError:error]; + } else { + [self.download setDestination:[downloadFileNameDirectory stringByAppendingPathComponent:name] allowOverwrite:YES]; + + [self.delegate downloaderDidSetDestinationName:name temporaryDirectory:downloadFileNameDirectory]; + } + } + } +} + +- (void)download:(NSURLDownload *)__unused aDownload didCreateDestination:(NSString *)path +{ + self.downloadFilename = path; +} + +- (void)download:(NSURLDownload *)__unused download didReceiveResponse:(NSURLResponse *)response +{ + self.response = response; + + if (self.mode == SPUDownloadModePersistent) { + // It might be tempting to send over the response object instead of the expected content length but this isn't a good idea + // For one, we are only ever concerned about the expected content length + // Another reason is that NSURLResponse doesn't support NSSecureCoding in older OS releases (eg: 10.8), which cause issues with XPC + [self.delegate downloaderDidReceiveExpectedContentLength:response.expectedContentLength]; + } +} + +- (void)download:(NSURLDownload *)__unused download didReceiveDataOfLength:(NSUInteger)length +{ + if (self.mode == SPUDownloadModePersistent) { + [self.delegate downloaderDidReceiveDataOfLength:length]; + } +} + +- (void)downloadDidFinish:(NSURLDownload *)__unused d +{ + [self downloadDidFinish]; +} + +- (void)download:(NSURLDownload *)__unused download didFailWithError:(NSError *)error +{ + self.download = nil; + [self.delegate downloaderDidFailWithError:error]; + [self cleanup]; +} + +- (BOOL)download:(NSURLDownload *)__unused download shouldDecodeSourceDataOfMIMEType:(NSString *)encodingType +{ + // We don't want the download system to extract our gzips for persistent downloads + // Note that we use a substring matching here instead of direct comparison because the docs say "application/gzip" but the system *uses* "application/x-gzip". This is a documentation bug. + return (self.mode == SPUDownloadModeTemporary || [encodingType rangeOfString:@"gzip"].location == NSNotFound); +} + +- (void)downloadDidFinish +{ + assert(self.response != nil); + assert(self.downloadFilename != nil); + + SPUDownloadData *downloadData = nil; + if (self.mode == SPUDownloadModeTemporary) { + NSData *data = [NSData dataWithContentsOfFile:self.downloadFilename]; + if (data != nil) { + downloadData = [[SPUDownloadData alloc] initWithData:data textEncodingName:self.response.textEncodingName MIMEType:self.response.MIMEType]; + } + } + + self.download = nil; + + [super downloadDidFinishWithData:downloadData]; +} + +-(void)cleanup +{ + [self.download cancel]; + self.download = nil; + self.response = nil; + [super cleanup]; +} + +@end diff --git a/Sparkle/SPUDownloaderProtocol.h b/Sparkle/SPUDownloaderProtocol.h index 72982cfd..d844eb84 100755 --- a/Sparkle/SPUDownloaderProtocol.h +++ b/Sparkle/SPUDownloaderProtocol.h @@ -19,6 +19,10 @@ NS_ASSUME_NONNULL_BEGIN - (void)startTemporaryDownloadWithRequest:(SPUURLRequest *)request; +- (void)downloadDidFinish; + +- (void)cleanup; + @end NS_ASSUME_NONNULL_END diff --git a/Sparkle/SPUDownloaderSession.h b/Sparkle/SPUDownloaderSession.h index b8a25bf1..3ca1754e 100644 --- a/Sparkle/SPUDownloaderSession.h +++ b/Sparkle/SPUDownloaderSession.h @@ -10,6 +10,6 @@ #import "SPUDownloader.h" #import "SPUDownloaderProtocol.h" -@interface SPUDownloaderSession : SPUDownloader +@interface SPUDownloaderSession : SPUDownloader @end diff --git a/Sparkle/SPUDownloaderSession.m b/Sparkle/SPUDownloaderSession.m index d9abbcf4..aae8a76e 100644 --- a/Sparkle/SPUDownloaderSession.m +++ b/Sparkle/SPUDownloaderSession.m @@ -11,16 +11,19 @@ #import "SPUDownloader_Private.h" #import "SPULocalCacheDirectory.h" #import "SUErrors.h" +#import "SPUDownloadData.h" @interface SPUDownloaderSession () @property (nonatomic) NSURLSession *downloadSession; +@property (nonatomic) NSURLSessionDownloadTask *download; @end @implementation SPUDownloaderSession @synthesize downloadSession = _downloadSession; +@synthesize download = _download; - (void)startDownloadWithRequest:(SPUURLRequest *)request { @@ -136,6 +139,33 @@ [self cleanup]; } +- (void)downloadDidFinish +{ + assert(self.downloadFilename != nil); + + SPUDownloadData *downloadData = nil; + if (self.mode == SPUDownloadModeTemporary) { + NSData *data = [NSData dataWithContentsOfFile:self.downloadFilename]; + if (data != nil) { + NSURLResponse *response = self.download.response; + assert(response != nil); + downloadData = [[SPUDownloadData alloc] initWithData:data textEncodingName:response.textEncodingName MIMEType:response.MIMEType]; + } + } + + self.download = nil; + + [super downloadDidFinishWithData:downloadData]; +} + +-(void)cleanup +{ + [self.download cancel]; + self.download = nil; + self.downloadSession = nil; + [super cleanup]; +} + // NSURLDownload has a [downlaod:shouldDecodeSourceDataOfMIMEType:] to determine if the data should be decoded. // This does not exist for NSURLSessionDownloadTask and appears unnecessary. Data tasks will decode data, but not download tasks. diff --git a/Sparkle/SPUDownloader_Private.h b/Sparkle/SPUDownloader_Private.h index 254c7846..c679c881 100644 --- a/Sparkle/SPUDownloader_Private.h +++ b/Sparkle/SPUDownloader_Private.h @@ -23,7 +23,6 @@ static NSString *SUDownloadingReason = @"Downloading update related file"; // Delegate is intentionally strongly referenced; see header @property (nonatomic) id delegate; -@property (nonatomic) NSURLSessionDownloadTask *download; @property (nonatomic, copy) NSString *bundleIdentifier; @property (nonatomic, copy) NSString *desiredFilename; @property (nonatomic, copy) NSString *downloadFilename; @@ -31,7 +30,7 @@ static NSString *SUDownloadingReason = @"Downloading update related file"; @property (nonatomic) SPUDownloadMode mode; @property (nonatomic) BOOL receivedExpectedBytes; --(void)downloadDidFinish; +-(void)downloadDidFinishWithData:(SPUDownloadData*)data; @end From 9c301bfbf34d34c105e5ef8c54620d266b5259c1 Mon Sep 17 00:00:00 2001 From: Deadpikle Date: Wed, 20 Dec 2017 12:11:49 -0500 Subject: [PATCH 05/20] Drivers now use SPUDownloader --- Sparkle/SPUDownloader.m | 10 ++- Sparkle/SPUDownloaderDeprecated.m | 5 ++ Sparkle/SPUDownloaderProtocol.h | 2 + Sparkle/SPUDownloaderSession.m | 5 ++ Sparkle/SUBasicUpdateDriver.h | 18 +++-- Sparkle/SUBasicUpdateDriver.m | 108 ++++++++++++++++++------------ Sparkle/SUUIBasedUpdateDriver.m | 6 +- 7 files changed, 101 insertions(+), 53 deletions(-) diff --git a/Sparkle/SPUDownloader.m b/Sparkle/SPUDownloader.m index e863a4e7..13b57ee6 100755 --- a/Sparkle/SPUDownloader.m +++ b/Sparkle/SPUDownloader.m @@ -16,7 +16,7 @@ #include "AppKitPrevention.h" -@interface SPUDownloader () +@interface SPUDownloader () @end @@ -41,11 +41,11 @@ // Don't implement dealloc - make the client call cleanup, which is the only way to remove the reference cycle from the delegate anyway -- (void)startPersistentDownloadWithRequest:(SPUURLRequest *)request bundleIdentifier:(NSString *)bundleIdentifier desiredFilename:(NSString *)desiredFilename +- (void)startPersistentDownloadWithRequest:(SPUURLRequest *)__unused request bundleIdentifier:(NSString *)__unused bundleIdentifier desiredFilename:(NSString *)__unused desiredFilename { } -- (void)startTemporaryDownloadWithRequest:(SPUURLRequest *)request +- (void)startTemporaryDownloadWithRequest:(SPUURLRequest *)__unused request { } @@ -69,6 +69,10 @@ } } +- (void)cancel +{ + +} -(void)downloadDidFinishWithData:(SPUDownloadData*)data { diff --git a/Sparkle/SPUDownloaderDeprecated.m b/Sparkle/SPUDownloaderDeprecated.m index 8ae29dbb..4c4ee6dc 100644 --- a/Sparkle/SPUDownloaderDeprecated.m +++ b/Sparkle/SPUDownloaderDeprecated.m @@ -174,4 +174,9 @@ [super cleanup]; } +- (void)cancel +{ + [self cleanup]; +} + @end diff --git a/Sparkle/SPUDownloaderProtocol.h b/Sparkle/SPUDownloaderProtocol.h index d844eb84..36f41fd4 100755 --- a/Sparkle/SPUDownloaderProtocol.h +++ b/Sparkle/SPUDownloaderProtocol.h @@ -23,6 +23,8 @@ NS_ASSUME_NONNULL_BEGIN - (void)cleanup; +- (void)cancel; + @end NS_ASSUME_NONNULL_END diff --git a/Sparkle/SPUDownloaderSession.m b/Sparkle/SPUDownloaderSession.m index aae8a76e..0c1c0885 100644 --- a/Sparkle/SPUDownloaderSession.m +++ b/Sparkle/SPUDownloaderSession.m @@ -166,6 +166,11 @@ [super cleanup]; } +- (void)cancel +{ + [self cleanup]; +} + // NSURLDownload has a [downlaod:shouldDecodeSourceDataOfMIMEType:] to determine if the data should be decoded. // This does not exist for NSURLSessionDownloadTask and appears unnecessary. Data tasks will decode data, but not download tasks. diff --git a/Sparkle/SUBasicUpdateDriver.h b/Sparkle/SUBasicUpdateDriver.h index bd83c4dd..937e0f9a 100644 --- a/Sparkle/SUBasicUpdateDriver.h +++ b/Sparkle/SUBasicUpdateDriver.h @@ -10,12 +10,14 @@ #define SUBASICUPDATEDRIVER_H #import "SUUpdateDriver.h" +#import "SPUDownloader.h" +#import "SPUDownloaderDelegate.h" -@class SUAppcast, SUAppcastItem, SUHost; -@interface SUBasicUpdateDriver : SUUpdateDriver +@class SUAppcast, SUAppcastItem, SUHost, SPUDownloadData; +@interface SUBasicUpdateDriver : SUUpdateDriver @property (strong, readonly) SUAppcastItem *updateItem; -@property (strong, readonly) NSURLDownload *download; +@property (strong, readonly) SPUDownloader *download; @property (copy, readonly) NSString *downloadPath; - (void)checkForUpdatesAtURL:(NSURL *)URL host:(SUHost *)host; @@ -29,9 +31,17 @@ - (void)didNotFindUpdate; - (void)downloadUpdate; +// SPUDownloaderDelegate +- (void)downloaderDidSetDestinationName:(NSString *)destinationName temporaryDirectory:(NSString *)temporaryDirectory; +- (void)downloaderDidReceiveExpectedContentLength:(int64_t)expectedContentLength; +- (void)downloaderDidReceiveDataOfLength:(uint64_t)length; +- (void)downloaderDidFinishWithTemporaryDownloadData:(SPUDownloadData * _Nullable)downloadData; +- (void)downloaderDidFailWithError:(NSError *)error; + +/* - (void)download:(NSURLDownload *)d decideDestinationWithSuggestedFilename:(NSString *)name; - (void)downloadDidFinish:(NSURLDownload *)d; -- (void)download:(NSURLDownload *)download didFailWithError:(NSError *)error; +- (void)download:(NSURLDownload *)download didFailWithError:(NSError *)error;*/ - (void)extractUpdate; - (void)failedToApplyDeltaUpdate; diff --git a/Sparkle/SUBasicUpdateDriver.m b/Sparkle/SUBasicUpdateDriver.m index 927f3eae..1ef605ca 100644 --- a/Sparkle/SUBasicUpdateDriver.m +++ b/Sparkle/SUBasicUpdateDriver.m @@ -25,10 +25,14 @@ #import "SUAppcast.h" #import "SUAppcastItem.h" +#import "SPUURLRequest.h" +#import "SPUDownloaderDeprecated.h" +#import "SPUDownloaderSession.h" + @interface SUBasicUpdateDriver () @property (strong) SUAppcastItem *updateItem; -@property (strong) NSURLDownload *download; +@property (strong) SPUDownloader *download; @property (copy) NSString *downloadPath; @property (strong) SUAppcastItem *nonDeltaUpdateItem; @@ -256,6 +260,9 @@ - (void)downloadUpdate { + NSString *bundleIdentifier = self.host.bundle.bundleIdentifier; + assert(bundleIdentifier != nil); + // Clear cache directory so that downloads can't possibly accumulate inside NSString *appCachePath = [self appCachePath]; if ([[NSFileManager defaultManager] fileExistsAtPath:appCachePath]) { @@ -275,9 +282,64 @@ willDownloadUpdate:self.updateItem withRequest:request]; } - self.download = [[NSURLDownload alloc] initWithRequest:request delegate:self]; + // TODO: SPUDownloaderDeprecated vs SPUDownloaderSession + self.download = [[SPUDownloaderDeprecated alloc] initWithDelegate:self]; + SPUURLRequest *urlRequest = [SPUURLRequest URLRequestWithRequest:request]; + NSString *desiredFilename = [NSString stringWithFormat:@"%@ %@", [self.host name], [self.updateItem versionString]]; + [self.download startPersistentDownloadWithRequest:urlRequest bundleIdentifier:bundleIdentifier desiredFilename:desiredFilename]; } + +- (void)downloaderDidSetDestinationName:(NSString *)destinationName temporaryDirectory:(NSString *)temporaryDirectory +{ + self.tempDir = temporaryDirectory; + self.downloadPath = destinationName; // TODO: does this need to be a full path? +} + +- (void)downloaderDidReceiveExpectedContentLength:(int64_t)__unused expectedContentLength +{ + // don't need to do anything here as there's no GUI with this driver (there can be with child classes) +} + +- (void)downloaderDidReceiveDataOfLength:(uint64_t)__unused length +{ + // don't need do anything here as there's no GUI with this driver (there can be with child classes) +} + +- (void)downloaderDidFinishWithTemporaryDownloadData:(SPUDownloadData * _Nullable)__unused downloadData +{ + // finished. downloadData should be nil as this was a permanent download + assert(self.updateItem); + + [self extractUpdate]; +} + +- (void)downloaderDidFailWithError:(NSError *)error +{ + NSURL *failingUrl = [error.userInfo objectForKey:NSURLErrorFailingURLErrorKey]; + if (!failingUrl) { + failingUrl = [self.updateItem fileURL]; + } + + id updater = self.updater; + + if ([[updater delegate] respondsToSelector:@selector(updater:failedToDownloadUpdate:error:)]) { + [[updater delegate] updater:self.updater + failedToDownloadUpdate:self.updateItem + error:error]; + } + + NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:@{ + NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred while downloading the update. Please try again later.", nil), + NSUnderlyingErrorKey: error, + }]; + if (failingUrl) { + [userInfo setObject:failingUrl forKey:NSURLErrorFailingURLErrorKey]; + } + + [self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUDownloadError userInfo:userInfo]]; +} +/* - (void)download:(NSURLDownload *)__unused d decideDestinationWithSuggestedFilename:(NSString *)name { NSString *downloadFileName = [NSString stringWithFormat:@"%@ %@", [self.host name], [self.updateItem versionString]]; @@ -303,47 +365,7 @@ self.downloadPath = [self.tempDir stringByAppendingPathComponent:name]; [self.download setDestination:self.downloadPath allowOverwrite:YES]; } - -- (void)downloadDidFinish:(NSURLDownload *)__unused d -{ - assert(self.updateItem); - - [self extractUpdate]; -} - -- (void)download:(NSURLDownload *)__unused download didFailWithError:(NSError *)error -{ - NSURL *failingUrl = [error.userInfo objectForKey:NSURLErrorFailingURLErrorKey]; - if (!failingUrl) { - failingUrl = [self.updateItem fileURL]; - } - - id updater = self.updater; - - if ([[updater delegate] respondsToSelector:@selector(updater:failedToDownloadUpdate:error:)]) { - [[updater delegate] updater:self.updater - failedToDownloadUpdate:self.updateItem - error:error]; - } - - NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:@{ - NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred while downloading the update. Please try again later.", nil), - NSUnderlyingErrorKey: error, - }]; - if (failingUrl) { - [userInfo setObject:failingUrl forKey:NSURLErrorFailingURLErrorKey]; - } - - [self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUDownloadError userInfo:userInfo]]; -} - -- (BOOL)download:(NSURLDownload *)__unused download shouldDecodeSourceDataOfMIMEType:(NSString *)encodingType -{ - // We don't want the download system to extract our gzips. - // Note that we use a substring matching here instead of direct comparison because the docs say "application/gzip" but the system *uses* "application/x-gzip". This is a documentation bug. - return ([encodingType rangeOfString:@"gzip"].location == NSNotFound); -} - +*/ - (void)extractUpdate { id updater = self.updater; diff --git a/Sparkle/SUUIBasedUpdateDriver.m b/Sparkle/SUUIBasedUpdateDriver.m index 0400e5aa..2aa592bd 100644 --- a/Sparkle/SUUIBasedUpdateDriver.m +++ b/Sparkle/SUUIBasedUpdateDriver.m @@ -169,9 +169,8 @@ [super downloadUpdate]; } -- (void)download:(NSURLDownload *)__unused download didReceiveResponse:(NSURLResponse *)response +- (void)downloaderDidReceiveExpectedContentLength:(int64_t) expectedContentLength { - long long expectedContentLength = [response expectedContentLength]; [self.statusController setMaxProgressValue:expectedContentLength > 0 ? expectedContentLength : self.updateItem.contentLength]; } @@ -205,7 +204,8 @@ #pragma clang diagnostic pop } -- (void)download:(NSURLDownload *)__unused download didReceiveDataOfLength:(NSUInteger)length + +- (void)downloaderDidReceiveDataOfLength:(uint64_t) length { double newProgressValue = [self.statusController progressValue] + (double)length; From 7df50ccfd3f54ed4be49191fd105ca7edd809e22 Mon Sep 17 00:00:00 2001 From: Deadpikle Date: Wed, 20 Dec 2017 12:25:42 -0500 Subject: [PATCH 06/20] Download path should be full path --- Sparkle/SPUDownloader.m | 7 +++++++ Sparkle/SUBasicUpdateDriver.h | 5 ----- Sparkle/SUBasicUpdateDriver.m | 2 +- Sparkle/SUUpdateDriver.h | 2 +- 4 files changed, 9 insertions(+), 7 deletions(-) diff --git a/Sparkle/SPUDownloader.m b/Sparkle/SPUDownloader.m index 13b57ee6..787438c2 100755 --- a/Sparkle/SPUDownloader.m +++ b/Sparkle/SPUDownloader.m @@ -43,10 +43,12 @@ - (void)startPersistentDownloadWithRequest:(SPUURLRequest *)__unused request bundleIdentifier:(NSString *)__unused bundleIdentifier desiredFilename:(NSString *)__unused desiredFilename { + } - (void)startTemporaryDownloadWithRequest:(SPUURLRequest *)__unused request { + } - (void)enableAutomaticTermination @@ -74,6 +76,11 @@ } +- (void)downloadDidFinish +{ + +} + -(void)downloadDidFinishWithData:(SPUDownloadData*)data { switch (self.mode) { diff --git a/Sparkle/SUBasicUpdateDriver.h b/Sparkle/SUBasicUpdateDriver.h index 937e0f9a..2949ce42 100644 --- a/Sparkle/SUBasicUpdateDriver.h +++ b/Sparkle/SUBasicUpdateDriver.h @@ -38,11 +38,6 @@ - (void)downloaderDidFinishWithTemporaryDownloadData:(SPUDownloadData * _Nullable)downloadData; - (void)downloaderDidFailWithError:(NSError *)error; -/* -- (void)download:(NSURLDownload *)d decideDestinationWithSuggestedFilename:(NSString *)name; -- (void)downloadDidFinish:(NSURLDownload *)d; -- (void)download:(NSURLDownload *)download didFailWithError:(NSError *)error;*/ - - (void)extractUpdate; - (void)failedToApplyDeltaUpdate; diff --git a/Sparkle/SUBasicUpdateDriver.m b/Sparkle/SUBasicUpdateDriver.m index 1ef605ca..7044fe88 100644 --- a/Sparkle/SUBasicUpdateDriver.m +++ b/Sparkle/SUBasicUpdateDriver.m @@ -293,7 +293,7 @@ - (void)downloaderDidSetDestinationName:(NSString *)destinationName temporaryDirectory:(NSString *)temporaryDirectory { self.tempDir = temporaryDirectory; - self.downloadPath = destinationName; // TODO: does this need to be a full path? + self.downloadPath = [temporaryDirectory stringByAppendingPathComponent:destinationName]; } - (void)downloaderDidReceiveExpectedContentLength:(int64_t)__unused expectedContentLength diff --git a/Sparkle/SUUpdateDriver.h b/Sparkle/SUUpdateDriver.h index 7c276efd..0be22a08 100644 --- a/Sparkle/SUUpdateDriver.h +++ b/Sparkle/SUUpdateDriver.h @@ -15,7 +15,7 @@ extern NSString *const SUUpdateDriverFinishedNotification; @class SUHost, SUUpdater; @protocol SUUpdaterPrivate; -@interface SUUpdateDriver : NSObject +@interface SUUpdateDriver : NSObject // We only have SUUpdater* forward declared intentionally (i.e, not #import'ing SUUpdater.h in the update drivers) // This is so we can minimize what we can access using SUUpdaterPrivate From 429f9504342864ee55dacade0ab4ce0e03da4677 Mon Sep 17 00:00:00 2001 From: Deadpikle Date: Wed, 20 Dec 2017 12:40:37 -0500 Subject: [PATCH 07/20] Only send back error if non-nil --- Sparkle/SPUDownloaderSession.m | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Sparkle/SPUDownloaderSession.m b/Sparkle/SPUDownloaderSession.m index 0c1c0885..e3bde9f5 100644 --- a/Sparkle/SPUDownloaderSession.m +++ b/Sparkle/SPUDownloaderSession.m @@ -135,7 +135,9 @@ - (void)URLSession:(NSURLSession *)__unused session task:(NSURLSessionTask *)__unused task didCompleteWithError:(NSError *)error { self.download = nil; - [self.delegate downloaderDidFailWithError:error]; + if (error) { + [self.delegate downloaderDidFailWithError:error]; + } [self cleanup]; } From 1cc5f230a574ca9304a31a88c40bc3c737a9848e Mon Sep 17 00:00:00 2001 From: Deadpikle Date: Wed, 20 Dec 2017 12:40:48 -0500 Subject: [PATCH 08/20] Check OS version before creating downloader --- Sparkle/SUBasicUpdateDriver.m | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Sparkle/SUBasicUpdateDriver.m b/Sparkle/SUBasicUpdateDriver.m index 7044fe88..b4e817b1 100644 --- a/Sparkle/SUBasicUpdateDriver.m +++ b/Sparkle/SUBasicUpdateDriver.m @@ -283,7 +283,12 @@ withRequest:request]; } // TODO: SPUDownloaderDeprecated vs SPUDownloaderSession - self.download = [[SPUDownloaderDeprecated alloc] initWithDelegate:self]; + if ([SUOperatingSystem isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){10, 9, 0}]) { + self.download = [[SPUDownloaderSession alloc] initWithDelegate:self]; + } + else { + self.download = [[SPUDownloaderDeprecated alloc] initWithDelegate:self]; + } SPUURLRequest *urlRequest = [SPUURLRequest URLRequestWithRequest:request]; NSString *desiredFilename = [NSString stringWithFormat:@"%@ %@", [self.host name], [self.updateItem versionString]]; [self.download startPersistentDownloadWithRequest:urlRequest bundleIdentifier:bundleIdentifier desiredFilename:desiredFilename]; From 6ee88124ad5702f1d2d37d8bd5b6cb624c4044ff Mon Sep 17 00:00:00 2001 From: Deadpikle Date: Wed, 20 Dec 2017 12:58:45 -0500 Subject: [PATCH 09/20] SUAppcast now uses SPUDownloader --- Sparkle/SUAppcast.m | 113 +++++++++++++++++++--------------- Sparkle/SUBasicUpdateDriver.m | 2 +- 2 files changed, 64 insertions(+), 51 deletions(-) diff --git a/Sparkle/SUAppcast.m b/Sparkle/SUAppcast.m index 6783684d..cdffa764 100644 --- a/Sparkle/SUAppcast.m +++ b/Sparkle/SUAppcast.m @@ -12,6 +12,12 @@ #import "SULocalizations.h" #import "SUErrors.h" +#import "SPUURLRequest.h" +#import "SUOperatingSystem.h" +#import "SPUDownloadData.h" +#import "SPUDownloaderDelegate.h" +#import "SPUDownloaderDeprecated.h" +#import "SPUDownloaderSession.h" #include "AppKitPrevention.h" @@ -39,18 +45,18 @@ } @end -@interface SUAppcast () +@interface SUAppcast () + @property (strong) void (^completionBlock)(NSError *); -@property (copy) NSString *downloadFilename; -@property (strong) NSURLDownload *download; +@property (strong) SPUDownloader *download; @property (copy) NSArray *items; - (void)reportError:(NSError *)error; - (NSXMLNode *)bestNodeInNodes:(NSArray *)nodes; + @end @implementation SUAppcast -@synthesize downloadFilename; @synthesize completionBlock; @synthesize userAgentString; @synthesize httpHeaders; @@ -79,49 +85,71 @@ [request setValue:@"application/rss+xml,*/*;q=0.1" forHTTPHeaderField:@"Accept"]; - self.download = [[NSURLDownload alloc] initWithRequest:request delegate:self]; -} - -- (void)download:(NSURLDownload *)__unused aDownload decideDestinationWithSuggestedFilename:(NSString *)filename -{ - NSString *destinationFilename = NSTemporaryDirectory(); - if (destinationFilename) - { - destinationFilename = [destinationFilename stringByAppendingPathComponent:filename]; - [self.download setDestination:destinationFilename allowOverwrite:NO]; + + if ([SUOperatingSystem isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){10, 9, 0}]) { + self.download = [[SPUDownloaderSession alloc] initWithDelegate:self]; } + else { + self.download = [[SPUDownloaderDeprecated alloc] initWithDelegate:self]; + } + + SPUURLRequest *urlRequest = [SPUURLRequest URLRequestWithRequest:request]; + [self.download startTemporaryDownloadWithRequest:urlRequest]; } -- (void)download:(NSURLDownload *)__unused aDownload didCreateDestination:(NSString *)path +- (void)downloaderDidSetDestinationName:(NSString *)__unused destinationName temporaryDirectory:(NSString *)__unused temporaryDirectory { - self.downloadFilename = path; } -- (void)downloadDidFinish:(NSURLDownload *)__unused aDownload +- (void)downloaderDidReceiveExpectedContentLength:(int64_t)__unused expectedContentLength { - NSError *error = nil; - NSArray *appcastItems = [self parseAppcastItemsFromXMLFile:[NSURL fileURLWithPath:self.downloadFilename] error:&error]; +} - [[NSFileManager defaultManager] removeItemAtPath:self.downloadFilename error:nil]; - self.downloadFilename = nil; +- (void)downloaderDidReceiveDataOfLength:(uint64_t)__unused length +{ +} - if (appcastItems) { - self.items = appcastItems; - self.completionBlock(nil); - self.completionBlock = nil; - } else { - NSMutableDictionary *userInfo = [NSMutableDictionary - dictionaryWithObject: SULocalizedString(@"An error occurred while parsing the update feed.", nil) - forKey: NSLocalizedDescriptionKey]; - if (error) { - [userInfo setObject:error forKey:NSUnderlyingErrorKey]; +- (void)downloaderDidFinishWithTemporaryDownloadData:(SPUDownloadData * _Nullable)downloadData +{ + if (downloadData != nil) { + NSError *parseError = nil; + NSArray *appcastItems = [self parseAppcastItemsFromXMLData:downloadData.data error:&parseError]; + + if (appcastItems != nil) { + self.items = appcastItems; + self.completionBlock(nil); + self.completionBlock = nil; + } else { + NSMutableDictionary *userInfo = [NSMutableDictionary + dictionaryWithObject: SULocalizedString(@"An error occurred while parsing the update feed.", nil) + forKey: NSLocalizedDescriptionKey]; + if (parseError != nil) { + [userInfo setObject:parseError forKey:NSUnderlyingErrorKey]; + } + [self reportError:[NSError errorWithDomain:SUSparkleErrorDomain + code:SUAppcastParseError + userInfo:userInfo]]; } + } else { + SULog(SULogLevelError, @"Temp data download is null in SUAppcast"); + + NSDictionary *userInfo = [NSDictionary + dictionaryWithObject: SULocalizedString(@"An error occurred while downloading the update feed.", nil) + forKey: NSLocalizedDescriptionKey]; + [self reportError:[NSError errorWithDomain:SUSparkleErrorDomain - code:SUAppcastParseError + code:SUDownloadError userInfo:userInfo]]; } } +- (void)downloaderDidFailWithError:(NSError *)error +{ + SULog(SULogLevelError, @"Encountered download feed error: %@", error); + + [self reportError:error]; +} + - (NSDictionary *)attributesOfNode:(NSXMLElement *)node { NSEnumerator *attributeEnum = [[node attributes] objectEnumerator]; @@ -152,17 +180,17 @@ } } --(NSArray *)parseAppcastItemsFromXMLFile:(NSURL *)appcastFile error:(NSError *__autoreleasing*)errorp { +-(NSArray *)parseAppcastItemsFromXMLData:(NSData *)appcastData error:(NSError *__autoreleasing*)errorp { if (errorp) { *errorp = nil; } - if (!appcastFile) { + if (!appcastData) { return nil; } NSUInteger options = NSXMLNodeLoadExternalEntitiesNever; // Prevent inclusion from file:// - NSXMLDocument *document = [[NSXMLDocument alloc] initWithContentsOfURL:appcastFile options:options error:errorp]; + NSXMLDocument *document = [[NSXMLDocument alloc] initWithData:appcastData options:options error:errorp]; if (nil == document) { return nil; } @@ -262,21 +290,6 @@ return appcastItems; } -- (void)download:(NSURLDownload *)__unused aDownload didFailWithError:(NSError *)error -{ - if (self.downloadFilename) { - [[NSFileManager defaultManager] removeItemAtPath:self.downloadFilename error:nil]; - } - self.downloadFilename = nil; - - [self reportError:error]; -} - -- (NSURLRequest *)download:(NSURLDownload *)__unused aDownload willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)__unused redirectResponse -{ - return request; -} - - (void)reportError:(NSError *)error { NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:@{ diff --git a/Sparkle/SUBasicUpdateDriver.m b/Sparkle/SUBasicUpdateDriver.m index b4e817b1..2eb4b21d 100644 --- a/Sparkle/SUBasicUpdateDriver.m +++ b/Sparkle/SUBasicUpdateDriver.m @@ -282,7 +282,7 @@ willDownloadUpdate:self.updateItem withRequest:request]; } - // TODO: SPUDownloaderDeprecated vs SPUDownloaderSession + if ([SUOperatingSystem isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){10, 9, 0}]) { self.download = [[SPUDownloaderSession alloc] initWithDelegate:self]; } From 703e611eb51ed3bb4fbf3359adccb3d580d4f76c Mon Sep 17 00:00:00 2001 From: Deadpikle Date: Wed, 20 Dec 2017 13:01:44 -0500 Subject: [PATCH 10/20] Remove a bunch of warnings --- Sparkle/SUBasicUpdateDriver.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sparkle/SUBasicUpdateDriver.h b/Sparkle/SUBasicUpdateDriver.h index 2949ce42..26660c33 100644 --- a/Sparkle/SUBasicUpdateDriver.h +++ b/Sparkle/SUBasicUpdateDriver.h @@ -35,7 +35,7 @@ - (void)downloaderDidSetDestinationName:(NSString *)destinationName temporaryDirectory:(NSString *)temporaryDirectory; - (void)downloaderDidReceiveExpectedContentLength:(int64_t)expectedContentLength; - (void)downloaderDidReceiveDataOfLength:(uint64_t)length; -- (void)downloaderDidFinishWithTemporaryDownloadData:(SPUDownloadData * _Nullable)downloadData; +- (void)downloaderDidFinishWithTemporaryDownloadData:(SPUDownloadData *)downloadData; - (void)downloaderDidFailWithError:(NSError *)error; - (void)extractUpdate; From 5b1c76db26dfa53ca6c1d5c1c0298419d77cdbb2 Mon Sep 17 00:00:00 2001 From: Deadpikle Date: Wed, 20 Dec 2017 13:22:47 -0500 Subject: [PATCH 11/20] Fix a few header comments --- Sparkle/SPUDownloaderDeprecated.h | 2 +- Sparkle/SPUDownloaderDeprecated.m | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Sparkle/SPUDownloaderDeprecated.h b/Sparkle/SPUDownloaderDeprecated.h index e667ef1b..36302df4 100644 --- a/Sparkle/SPUDownloaderDeprecated.h +++ b/Sparkle/SPUDownloaderDeprecated.h @@ -2,7 +2,7 @@ // SPUDownloaderDeprecated.h // Sparkle // -// Created by School of Computing Macbook on 12/20/17. +// Created by Deadpikle on 12/20/17. // Copyright © 2017 Sparkle Project. All rights reserved. // diff --git a/Sparkle/SPUDownloaderDeprecated.m b/Sparkle/SPUDownloaderDeprecated.m index 4c4ee6dc..dd7924cb 100644 --- a/Sparkle/SPUDownloaderDeprecated.m +++ b/Sparkle/SPUDownloaderDeprecated.m @@ -2,7 +2,7 @@ // SPUDownloaderDeprecated.m // Sparkle // -// Created by School of Computing Macbook on 12/20/17. +// Created by Deadpikle on 12/20/17. // Copyright © 2017 Sparkle Project. All rights reserved. // From 03e28780d9f5387503d318c89e37e32d2f77f090 Mon Sep 17 00:00:00 2001 From: Deadpikle Date: Thu, 21 Dec 2017 09:35:06 -0500 Subject: [PATCH 12/20] Fix AppKitPrevention not being included --- Sparkle/SPUDownloaderDeprecated.m | 2 ++ Sparkle/SPUDownloaderSession.m | 2 ++ 2 files changed, 4 insertions(+) diff --git a/Sparkle/SPUDownloaderDeprecated.m b/Sparkle/SPUDownloaderDeprecated.m index dd7924cb..24204764 100644 --- a/Sparkle/SPUDownloaderDeprecated.m +++ b/Sparkle/SPUDownloaderDeprecated.m @@ -13,6 +13,8 @@ #import "SPULocalCacheDirectory.h" #import "SUErrors.h" +#include "AppKitPrevention.h" + @interface SPUDownloaderDeprecated () @property (nonatomic) NSURLDownload *download; diff --git a/Sparkle/SPUDownloaderSession.m b/Sparkle/SPUDownloaderSession.m index e3bde9f5..60f18fb9 100644 --- a/Sparkle/SPUDownloaderSession.m +++ b/Sparkle/SPUDownloaderSession.m @@ -13,6 +13,8 @@ #import "SUErrors.h" #import "SPUDownloadData.h" +#include "AppKitPrevention.h" + @interface SPUDownloaderSession () @property (nonatomic) NSURLSession *downloadSession; From a7af48f0d130ca7c227b86f40cd9cea993d28a45 Mon Sep 17 00:00:00 2001 From: Deadpikle Date: Sun, 24 Dec 2017 09:38:04 -0500 Subject: [PATCH 13/20] Refactor cache clearing & errors to super --- Sparkle/SPUDownloader.m | 18 ++++++++++++++++++ Sparkle/SPUDownloaderDeprecated.m | 27 +++++---------------------- Sparkle/SPUDownloaderSession.m | 24 ++++-------------------- Sparkle/SPUDownloader_Private.h | 4 ++++ 4 files changed, 31 insertions(+), 42 deletions(-) diff --git a/Sparkle/SPUDownloader.m b/Sparkle/SPUDownloader.m index 787438c2..ef6e9067 100755 --- a/Sparkle/SPUDownloader.m +++ b/Sparkle/SPUDownloader.m @@ -97,4 +97,22 @@ } } +-(NSString*)getAndCleanTempDirectory +{ + NSString *rootPersistentDownloadCachePath = [[SPULocalCacheDirectory cachePathForBundleIdentifier:self.bundleIdentifier] stringByAppendingPathComponent:@"PersistentDownloads"]; + + [SPULocalCacheDirectory removeOldItemsInDirectory:rootPersistentDownloadCachePath]; + + NSString *tempDir = [SPULocalCacheDirectory createUniqueDirectoryInDirectory:rootPersistentDownloadCachePath]; + if (tempDir == nil) { + // Okay, something's really broken with this user's file structure. + NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUTemporaryDirectoryError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Can't make a temporary directory for the update download at %@.", tempDir] }]; + + [self.delegate downloaderDidFailWithError:error]; + + [self cancel]; + } + return tempDir; +} + @end diff --git a/Sparkle/SPUDownloaderDeprecated.m b/Sparkle/SPUDownloaderDeprecated.m index 24204764..ae2a065c 100644 --- a/Sparkle/SPUDownloaderDeprecated.m +++ b/Sparkle/SPUDownloaderDeprecated.m @@ -60,36 +60,19 @@ - (void)download:(NSURLDownload *)__unused d decideDestinationWithSuggestedFilename:(NSString *)name { - if (self.mode == SPUDownloadModeTemporary) - { + if (self.mode == SPUDownloadModeTemporary) { // Files downloaded in temporary mode should not last for very long, // so it's ideal to place them in a system temporary directory NSString *destinationFilename = NSTemporaryDirectory(); - if (destinationFilename) - { + if (destinationFilename) { destinationFilename = [destinationFilename stringByAppendingPathComponent:name]; [self.download setDestination:destinationFilename allowOverwrite:NO]; } - } - else - { - // Remove our old caches path so we don't start accumulating files in there - NSString *rootPersistentDownloadCachePath = [[SPULocalCacheDirectory cachePathForBundleIdentifier:self.bundleIdentifier] stringByAppendingPathComponent:@"PersistentDownloads"]; + } else { + NSString *tempDir = [super getAndCleanTempDirectory]; - [SPULocalCacheDirectory removeOldItemsInDirectory:rootPersistentDownloadCachePath]; - - NSString *tempDir = [SPULocalCacheDirectory createUniqueDirectoryInDirectory:rootPersistentDownloadCachePath]; - if (tempDir == nil) - { - // Okay, something's really broken with this user's file structure. - [self.download cancel]; - self.download = nil; - - NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUTemporaryDirectoryError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Can't make a temporary directory for the update download at %@.", tempDir] }]; - - [self.delegate downloaderDidFailWithError:error]; - } else { + if (tempDir != nil) { NSString *downloadFileName = self.desiredFilename; NSString *downloadFileNameDirectory = [tempDir stringByAppendingPathComponent:downloadFileName]; diff --git a/Sparkle/SPUDownloaderSession.m b/Sparkle/SPUDownloaderSession.m index 60f18fb9..88470ce5 100644 --- a/Sparkle/SPUDownloaderSession.m +++ b/Sparkle/SPUDownloaderSession.m @@ -70,29 +70,13 @@ - (void)URLSession:(NSURLSession *)__unused session downloadTask:(NSURLSessionDownloadTask *)__unused downloadTask didFinishDownloadingToURL:(NSURL *)location { - if (self.mode == SPUDownloadModeTemporary) - { + if (self.mode == SPUDownloadModeTemporary) { self.downloadFilename = location.path; [self downloadDidFinish]; // file is already in a system temp dir - } - else - { - // Remove our old caches path so we don't start accumulating files in there - NSString *rootPersistentDownloadCachePath = [[SPULocalCacheDirectory cachePathForBundleIdentifier:self.bundleIdentifier] stringByAppendingPathComponent:@"PersistentDownloads"]; + } else { + NSString *tempDir = [super getAndCleanTempDirectory]; - [SPULocalCacheDirectory removeOldItemsInDirectory:rootPersistentDownloadCachePath]; - - NSString *tempDir = [SPULocalCacheDirectory createUniqueDirectoryInDirectory:rootPersistentDownloadCachePath]; - if (tempDir == nil) - { - // Okay, something's really broken with this user's file structure. - [self.download cancel]; - self.download = nil; - - NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUTemporaryDirectoryError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Can't make a temporary directory for the update download at %@.", tempDir] }]; - - [self.delegate downloaderDidFailWithError:error]; - } else { + if (tempDir != nil) { NSString *downloadFileName = self.desiredFilename; NSString *downloadFileNameDirectory = [tempDir stringByAppendingPathComponent:downloadFileName]; diff --git a/Sparkle/SPUDownloader_Private.h b/Sparkle/SPUDownloader_Private.h index c679c881..af0464c8 100644 --- a/Sparkle/SPUDownloader_Private.h +++ b/Sparkle/SPUDownloader_Private.h @@ -30,6 +30,10 @@ static NSString *SUDownloadingReason = @"Downloading update related file"; @property (nonatomic) SPUDownloadMode mode; @property (nonatomic) BOOL receivedExpectedBytes; +// returns temp directory location if successful; if not successful, +// returns nil after sending error message to client and canceling download +-(NSString*)getAndCleanTempDirectory; + -(void)downloadDidFinishWithData:(SPUDownloadData*)data; @end From 8b5c8b5cdf5753436e3e0a907d523526249f2706 Mon Sep 17 00:00:00 2001 From: Deadpikle Date: Thu, 28 Dec 2017 15:52:47 -0500 Subject: [PATCH 14/20] Fix SUAppcast tests --- Sparkle/SUAppcast.m | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Sparkle/SUAppcast.m b/Sparkle/SUAppcast.m index cdffa764..357c82a9 100644 --- a/Sparkle/SUAppcast.m +++ b/Sparkle/SUAppcast.m @@ -180,6 +180,11 @@ } } +-(NSArray *)parseAppcastItemsFromXMLFile:(NSURL *)appcastURL error:(NSError *__autoreleasing*)errorp { + NSData *data = [NSData dataWithContentsOfURL:appcastURL]; + return [self parseAppcastItemsFromXMLData:data error:errorp]; +} + -(NSArray *)parseAppcastItemsFromXMLData:(NSData *)appcastData error:(NSError *__autoreleasing*)errorp { if (errorp) { *errorp = nil; From e7cdbfc45e17727cb7ff17cc866e6b98e07df079 Mon Sep 17 00:00:00 2001 From: Deadpikle Date: Thu, 28 Dec 2017 21:40:31 -0500 Subject: [PATCH 15/20] Add tests for temp SPUDownloader dl --- Sparkle.xcodeproj/project.pbxproj | 35 ++++++++-- Sparkle/Sparkle.h | 8 +++ Tests/SPUDownloaderTest.swift | 78 ++++++++++++++++++++++ Tests/Sparkle Unit Tests-Bridging-Header.h | 8 +++ 4 files changed, 122 insertions(+), 7 deletions(-) create mode 100644 Tests/SPUDownloaderTest.swift diff --git a/Sparkle.xcodeproj/project.pbxproj b/Sparkle.xcodeproj/project.pbxproj index 57ef529e..3aa5b330 100644 --- a/Sparkle.xcodeproj/project.pbxproj +++ b/Sparkle.xcodeproj/project.pbxproj @@ -50,19 +50,20 @@ 14958C6E19AEBC950061B14F /* signed-test-file.txt in Resources */ = {isa = PBXBuildFile; fileRef = 14958C6B19AEBC530061B14F /* signed-test-file.txt */; }; 14958C6F19AEBC980061B14F /* test-pubkey.pem in Resources */ = {isa = PBXBuildFile; fileRef = 14958C6C19AEBC610061B14F /* test-pubkey.pem */; }; 34074B901FEABD08001CB3A5 /* SPUDownloader.m in Sources */ = {isa = PBXBuildFile; fileRef = 34074B8C1FEABD08001CB3A5 /* SPUDownloader.m */; }; - 34074B911FEABD08001CB3A5 /* SPUDownloader.h in Headers */ = {isa = PBXBuildFile; fileRef = 34074B8D1FEABD08001CB3A5 /* SPUDownloader.h */; }; - 34074B921FEABD08001CB3A5 /* SPUDownloaderDelegate.h in Headers */ = {isa = PBXBuildFile; fileRef = 34074B8E1FEABD08001CB3A5 /* SPUDownloaderDelegate.h */; }; - 34074B931FEABD08001CB3A5 /* SPUDownloaderProtocol.h in Headers */ = {isa = PBXBuildFile; fileRef = 34074B8F1FEABD08001CB3A5 /* SPUDownloaderProtocol.h */; }; + 34074B911FEABD08001CB3A5 /* SPUDownloader.h in Headers */ = {isa = PBXBuildFile; fileRef = 34074B8D1FEABD08001CB3A5 /* SPUDownloader.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 34074B921FEABD08001CB3A5 /* SPUDownloaderDelegate.h in Headers */ = {isa = PBXBuildFile; fileRef = 34074B8E1FEABD08001CB3A5 /* SPUDownloaderDelegate.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 34074B931FEABD08001CB3A5 /* SPUDownloaderProtocol.h in Headers */ = {isa = PBXBuildFile; fileRef = 34074B8F1FEABD08001CB3A5 /* SPUDownloaderProtocol.h */; settings = {ATTRIBUTES = (Public, ); }; }; 34074B961FEABD24001CB3A5 /* SPULocalCacheDirectory.h in Headers */ = {isa = PBXBuildFile; fileRef = 34074B941FEABD23001CB3A5 /* SPULocalCacheDirectory.h */; }; 34074B971FEABD24001CB3A5 /* SPULocalCacheDirectory.m in Sources */ = {isa = PBXBuildFile; fileRef = 34074B951FEABD23001CB3A5 /* SPULocalCacheDirectory.m */; }; 34074B9A1FEABD49001CB3A5 /* SPUURLRequest.m in Sources */ = {isa = PBXBuildFile; fileRef = 34074B981FEABD48001CB3A5 /* SPUURLRequest.m */; }; - 34074B9B1FEABD49001CB3A5 /* SPUURLRequest.h in Headers */ = {isa = PBXBuildFile; fileRef = 34074B991FEABD49001CB3A5 /* SPUURLRequest.h */; }; + 34074B9B1FEABD49001CB3A5 /* SPUURLRequest.h in Headers */ = {isa = PBXBuildFile; fileRef = 34074B991FEABD49001CB3A5 /* SPUURLRequest.h */; settings = {ATTRIBUTES = (Public, ); }; }; 34074B9E1FEABD5A001CB3A5 /* SPUDownloadData.m in Sources */ = {isa = PBXBuildFile; fileRef = 34074B9C1FEABD5A001CB3A5 /* SPUDownloadData.m */; }; - 34074B9F1FEABD5A001CB3A5 /* SPUDownloadData.h in Headers */ = {isa = PBXBuildFile; fileRef = 34074B9D1FEABD5A001CB3A5 /* SPUDownloadData.h */; }; - 34074BA21FEABFD2001CB3A5 /* SPUDownloaderSession.h in Headers */ = {isa = PBXBuildFile; fileRef = 34074BA01FEABFD2001CB3A5 /* SPUDownloaderSession.h */; }; + 34074B9F1FEABD5A001CB3A5 /* SPUDownloadData.h in Headers */ = {isa = PBXBuildFile; fileRef = 34074B9D1FEABD5A001CB3A5 /* SPUDownloadData.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 34074BA21FEABFD2001CB3A5 /* SPUDownloaderSession.h in Headers */ = {isa = PBXBuildFile; fileRef = 34074BA01FEABFD2001CB3A5 /* SPUDownloaderSession.h */; settings = {ATTRIBUTES = (Public, ); }; }; 34074BA31FEABFD2001CB3A5 /* SPUDownloaderSession.m in Sources */ = {isa = PBXBuildFile; fileRef = 34074BA11FEABFD2001CB3A5 /* SPUDownloaderSession.m */; }; - 34074BA71FEAC417001CB3A5 /* SPUDownloaderDeprecated.h in Headers */ = {isa = PBXBuildFile; fileRef = 34074BA51FEAC417001CB3A5 /* SPUDownloaderDeprecated.h */; }; + 34074BA71FEAC417001CB3A5 /* SPUDownloaderDeprecated.h in Headers */ = {isa = PBXBuildFile; fileRef = 34074BA51FEAC417001CB3A5 /* SPUDownloaderDeprecated.h */; settings = {ATTRIBUTES = (Public, ); }; }; 34074BA81FEAC417001CB3A5 /* SPUDownloaderDeprecated.m in Sources */ = {isa = PBXBuildFile; fileRef = 34074BA61FEAC417001CB3A5 /* SPUDownloaderDeprecated.m */; }; + 342731481FF58E5B00285FBD /* SPUDownloaderTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 342731461FF58E4F00285FBD /* SPUDownloaderTest.swift */; }; 3772FEA913DE0B6B00F79537 /* SUVersionDisplayProtocol.h in Headers */ = {isa = PBXBuildFile; fileRef = 3772FEA813DE0B6B00F79537 /* SUVersionDisplayProtocol.h */; settings = {ATTRIBUTES = (Public, ); }; }; 55C14BD4136EEFCE00649790 /* Autoupdate.m in Sources */ = {isa = PBXBuildFile; fileRef = 55C14BD3136EEFCE00649790 /* Autoupdate.m */; }; 55C14BD9136EF00C00649790 /* SUStatus.xib in Resources */ = {isa = PBXBuildFile; fileRef = 55C14BD8136EF00C00649790 /* SUStatus.xib */; }; @@ -549,6 +550,7 @@ 34074BA41FEAC0BC001CB3A5 /* SPUDownloader_Private.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SPUDownloader_Private.h; sourceTree = ""; }; 34074BA51FEAC417001CB3A5 /* SPUDownloaderDeprecated.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SPUDownloaderDeprecated.h; sourceTree = ""; }; 34074BA61FEAC417001CB3A5 /* SPUDownloaderDeprecated.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = SPUDownloaderDeprecated.m; sourceTree = ""; }; + 342731461FF58E4F00285FBD /* SPUDownloaderTest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SPUDownloaderTest.swift; sourceTree = ""; }; 3772FEA813DE0B6B00F79537 /* SUVersionDisplayProtocol.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SUVersionDisplayProtocol.h; sourceTree = ""; }; 4607BEA21948443800EF8DA4 /* nb */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = nb; path = nb.lproj/Sparkle.strings; sourceTree = ""; }; 4607BEA31948443800EF8DA4 /* nb */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = nb; path = nb.lproj/SUAutomaticUpdateAlert.xib; sourceTree = ""; }; @@ -1196,6 +1198,7 @@ 14958C7019AEBE350061B14F /* Resources */, 72AFC6121B9A944200F6B565 /* Sparkle Unit Tests-Bridging-Header.h */, 612279DA0DB5470200AB99EA /* SparkleTests-Info.plist */, + 342731461FF58E4F00285FBD /* SPUDownloaderTest.swift */, 5AA4DCD01C73E5510078F128 /* SUAppcastTest.swift */, 142E0E0819A83AAC00E4312B /* SUBinaryDeltaTest.m */, F8761EB01ADC5068000C9034 /* SUCodeSigningVerifierTest.m */, @@ -1708,6 +1711,9 @@ LastSwiftMigration = 0800; TestTargetID = 61B5F90109C4CEE200B25A18; }; + 8DC2EF4F0486A6940098B216 = { + LastSwiftMigration = 0920; + }; }; }; buildConfigurationList = 1DEB91B108733DA50010E9CD /* Build configuration list for PBXProject "Sparkle" */; @@ -2003,6 +2009,7 @@ 721CF1A81AD7644100D9AC09 /* bspatch.c in Sources */, 721CF1A91AD7644C00D9AC09 /* sais.c in Sources */, 5A4094481C74EA5200983BE0 /* SUAppcastTest.swift in Sources */, + 342731481FF58E5B00285FBD /* SPUDownloaderTest.swift in Sources */, 72D4DAA11AD7632900B211E2 /* SUBinaryDeltaCreate.m in Sources */, 142E0E0919A83AAC00E4312B /* SUBinaryDeltaTest.m in Sources */, F8761EB11ADC5068000C9034 /* SUCodeSigningVerifierTest.m in Sources */, @@ -2438,6 +2445,11 @@ isa = XCBuildConfiguration; baseConfigurationReference = FA1941CA0D94A70100DD942E /* ConfigFrameworkDebug.xcconfig */; buildSettings = { + CLANG_ENABLE_MODULES = YES; + DEFINES_MODULE = YES; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/Frameworks"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 3.0; }; name = Coverage; }; @@ -2491,6 +2503,11 @@ isa = XCBuildConfiguration; baseConfigurationReference = FA1941CA0D94A70100DD942E /* ConfigFrameworkDebug.xcconfig */; buildSettings = { + CLANG_ENABLE_MODULES = YES; + DEFINES_MODULE = YES; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/Frameworks"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 3.0; }; name = Debug; }; @@ -2498,6 +2515,10 @@ isa = XCBuildConfiguration; baseConfigurationReference = FA1941D50D94A70100DD942E /* ConfigFrameworkRelease.xcconfig */; buildSettings = { + CLANG_ENABLE_MODULES = YES; + DEFINES_MODULE = YES; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/Frameworks"; + SWIFT_VERSION = 3.0; }; name = Release; }; diff --git a/Sparkle/Sparkle.h b/Sparkle/Sparkle.h index d3f6ff2b..661b1312 100644 --- a/Sparkle/Sparkle.h +++ b/Sparkle/Sparkle.h @@ -21,4 +21,12 @@ #import "SUVersionDisplayProtocol.h" #import "SUErrors.h" +#import "SPUDownloader.h" +#import "SPUDownloaderDelegate.h" +#import "SPUDownloaderDeprecated.h" +#import "SPUDownloadData.h" +#import "SPUDownloaderProtocol.h" +#import "SPUDownloaderSession.h" +#import "SPUURLRequest.h" + #endif diff --git a/Tests/SPUDownloaderTest.swift b/Tests/SPUDownloaderTest.swift new file mode 100644 index 00000000..b8473f59 --- /dev/null +++ b/Tests/SPUDownloaderTest.swift @@ -0,0 +1,78 @@ +// +// SPUDownloaderTest.swift +// Sparkle +// +// Created by Deadpikle on 12/28/17. +// Copyright © 2017 Sparkle Project. All rights reserved. +// + +import XCTest +import Sparkle + +class SPUDownloaderTestDelegate: NSObject, SPUDownloaderDelegate { + + var asyncExpectation: XCTestExpectation? + + func downloaderDidFailWithError(_ error: Error) + { + XCTFail(error.localizedDescription); + asyncExpectation?.fulfill() + } + + func downloaderDidReceiveData(ofLength length: UInt64) + { + + } + + func downloaderDidReceiveExpectedContentLength(_ expectedContentLength: Int64) + { + + } + + func downloaderDidFinish(withTemporaryDownloadData downloadData: SPUDownloadData?) + { + XCTAssert(downloadData != nil) + let str = String.init(data: downloadData!.data, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) + XCTAssert(str == "appcast\n") + asyncExpectation?.fulfill() + } + + func downloaderDidSetDestinationName(_ destinationName: String, temporaryDirectory: String) + { + + } +} + +class SPUDownloaderTest: XCTestCase +{ + func performTemporaryDownloadTest(withDownloader downloader: SPUDownloader, delegate: SPUDownloaderTestDelegate) + { + let delegateExpectation = expectation(description: "SPUDownloaderDeprecated temporary download") + delegate.asyncExpectation = delegateExpectation + + let url = URL.init(string: "https://sparkle-project.org/unit_test/test.xml") + var request = URLRequest(url: url!, cachePolicy: .reloadIgnoringCacheData, timeoutInterval: 30.0) + request.setValue("application/rss+xml,*/*;q=0.1", forHTTPHeaderField: "Accept") + + let downloaderRequest = SPUURLRequest(request: request as URLRequest) + downloader.startTemporaryDownload(with: downloaderRequest) + + super.waitForExpectations(timeout: 30.0, handler: nil) + } + + func testDeprecatedDownloader() + { + let delegate = SPUDownloaderTestDelegate() + let downloader = SPUDownloaderDeprecated(delegate: delegate) + + self.performTemporaryDownloadTest(withDownloader: downloader!, delegate: delegate) + } + + func testSessionDownloader() + { + let delegate = SPUDownloaderTestDelegate() + let downloader = SPUDownloaderSession(delegate: delegate) + + self.performTemporaryDownloadTest(withDownloader: downloader!, delegate: delegate) + } +} diff --git a/Tests/Sparkle Unit Tests-Bridging-Header.h b/Tests/Sparkle Unit Tests-Bridging-Header.h index 043587ed..f60ff154 100644 --- a/Tests/Sparkle Unit Tests-Bridging-Header.h +++ b/Tests/Sparkle Unit Tests-Bridging-Header.h @@ -13,6 +13,14 @@ #import "SUVersionComparisonProtocol.h" #import "SUStandardVersionComparator.h" +#import "SPUDownloader.h" +#import "SPUDownloaderDelegate.h" +#import "SPUDownloaderDeprecated.h" +#import "SPUDownloadData.h" +#import "SPUDownloaderProtocol.h" +#import "SPUDownloaderSession.h" +#import "SPUURLRequest.h" + NS_ASSUME_NONNULL_BEGIN // Duplicated to avoid exporting a private symbol from SUFileManager From 1a71456ed9bd6558a6ace3c9cf020be8b5cff096 Mon Sep 17 00:00:00 2001 From: Deadpikle Date: Thu, 28 Dec 2017 21:50:46 -0500 Subject: [PATCH 16/20] Slight refactor of temp download test --- Tests/SPUDownloaderTest.swift | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/Tests/SPUDownloaderTest.swift b/Tests/SPUDownloaderTest.swift index b8473f59..1fbc0e33 100644 --- a/Tests/SPUDownloaderTest.swift +++ b/Tests/SPUDownloaderTest.swift @@ -12,6 +12,7 @@ import Sparkle class SPUDownloaderTestDelegate: NSObject, SPUDownloaderDelegate { var asyncExpectation: XCTestExpectation? + var tempResult: SPUDownloadData? func downloaderDidFailWithError(_ error: Error) { @@ -31,9 +32,7 @@ class SPUDownloaderTestDelegate: NSObject, SPUDownloaderDelegate { func downloaderDidFinish(withTemporaryDownloadData downloadData: SPUDownloadData?) { - XCTAssert(downloadData != nil) - let str = String.init(data: downloadData!.data, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) - XCTAssert(str == "appcast\n") + self.tempResult = downloadData asyncExpectation?.fulfill() } @@ -57,7 +56,19 @@ class SPUDownloaderTest: XCTestCase let downloaderRequest = SPUURLRequest(request: request as URLRequest) downloader.startTemporaryDownload(with: downloaderRequest) - super.waitForExpectations(timeout: 30.0, handler: nil) + super.waitForExpectations(timeout: 30.0) { error in + if let error = error { + XCTFail("waitForExpectationsWithTimeout had error: \(error)") + } + + guard let result = delegate.tempResult else { + XCTFail("Expected delegate to be called") + return + } + + let str = String.init(data: result.data, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) + XCTAssert(str == "appcast\n") + } } func testDeprecatedDownloader() @@ -66,6 +77,7 @@ class SPUDownloaderTest: XCTestCase let downloader = SPUDownloaderDeprecated(delegate: delegate) self.performTemporaryDownloadTest(withDownloader: downloader!, delegate: delegate) + self.performPermanentDownloadTest(withDownloader: downloader!, delegate: delegate) } func testSessionDownloader() @@ -74,5 +86,6 @@ class SPUDownloaderTest: XCTestCase let downloader = SPUDownloaderSession(delegate: delegate) self.performTemporaryDownloadTest(withDownloader: downloader!, delegate: delegate) + self.performPermanentDownloadTest(withDownloader: downloader!, delegate: delegate) } } From f0460033ba7b2647e38e920b302962c7dc96149d Mon Sep 17 00:00:00 2001 From: Deadpikle Date: Thu, 28 Dec 2017 21:58:42 -0500 Subject: [PATCH 17/20] Remove commented out code --- Sparkle/SUBasicUpdateDriver.m | 26 -------------------------- 1 file changed, 26 deletions(-) diff --git a/Sparkle/SUBasicUpdateDriver.m b/Sparkle/SUBasicUpdateDriver.m index 2eb4b21d..ff0f7126 100644 --- a/Sparkle/SUBasicUpdateDriver.m +++ b/Sparkle/SUBasicUpdateDriver.m @@ -344,33 +344,7 @@ [self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUDownloadError userInfo:userInfo]]; } -/* -- (void)download:(NSURLDownload *)__unused d decideDestinationWithSuggestedFilename:(NSString *)name -{ - NSString *downloadFileName = [NSString stringWithFormat:@"%@ %@", [self.host name], [self.updateItem versionString]]; - - NSString *appCachePath = [self appCachePath]; - - self.tempDir = [appCachePath stringByAppendingPathComponent:downloadFileName]; - int cnt = 1; - while ([[NSFileManager defaultManager] fileExistsAtPath:self.tempDir] && cnt <= 999) - { - self.tempDir = [appCachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@ %d", downloadFileName, cnt++]]; - } - // Create the temporary directory if necessary. - BOOL success = [[NSFileManager defaultManager] createDirectoryAtPath:self.tempDir withIntermediateDirectories:YES attributes:nil error:NULL]; - if (!success) - { - // Okay, something's really broken with this user's file structure. - [self.download cancel]; - [self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUTemporaryDirectoryError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Can't make a temporary directory for the update download at %@.", self.tempDir] }]]; - } - - self.downloadPath = [self.tempDir stringByAppendingPathComponent:name]; - [self.download setDestination:self.downloadPath allowOverwrite:YES]; -} -*/ - (void)extractUpdate { id updater = self.updater; From c886947f557c78216c5ce32b9ce960563dcf81ef Mon Sep 17 00:00:00 2001 From: Deadpikle Date: Thu, 28 Dec 2017 22:34:34 -0500 Subject: [PATCH 18/20] Set NSOperationQueue op count to 1 --- Sparkle/SPUDownloaderSession.m | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Sparkle/SPUDownloaderSession.m b/Sparkle/SPUDownloaderSession.m index 88470ce5..4dd0e961 100644 --- a/Sparkle/SPUDownloaderSession.m +++ b/Sparkle/SPUDownloaderSession.m @@ -29,10 +29,12 @@ - (void)startDownloadWithRequest:(SPUURLRequest *)request { + NSOperationQueue *queue = [[NSOperationQueue alloc] init]; + queue.maxConcurrentOperationCount = 1; self.downloadSession = [NSURLSession - sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] - delegate:self - delegateQueue:[NSOperationQueue mainQueue]]; + sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] + delegate:self + delegateQueue:queue]; self.download = [self.downloadSession downloadTaskWithRequest:request.request]; [self.download resume]; } From 25204a66e08ead4149e7858fd275f32e9407fb8d Mon Sep 17 00:00:00 2001 From: Deadpikle Date: Thu, 28 Dec 2017 22:35:27 -0500 Subject: [PATCH 19/20] Finish tests for persistent download --- Tests/SPUDownloaderTest.swift | 94 +++++++++++++++++----- Tests/Sparkle Unit Tests-Bridging-Header.h | 2 + 2 files changed, 75 insertions(+), 21 deletions(-) diff --git a/Tests/SPUDownloaderTest.swift b/Tests/SPUDownloaderTest.swift index 1fbc0e33..a8bcd512 100644 --- a/Tests/SPUDownloaderTest.swift +++ b/Tests/SPUDownloaderTest.swift @@ -13,32 +13,31 @@ class SPUDownloaderTestDelegate: NSObject, SPUDownloaderDelegate { var asyncExpectation: XCTestExpectation? var tempResult: SPUDownloadData? - - func downloaderDidFailWithError(_ error: Error) - { - XCTFail(error.localizedDescription); - asyncExpectation?.fulfill() - } + var downloadPath: URL? func downloaderDidReceiveData(ofLength length: UInt64) { - } func downloaderDidReceiveExpectedContentLength(_ expectedContentLength: Int64) { - + } + + func downloaderDidSetDestinationName(_ destinationName: String, temporaryDirectory: String) + { + self.downloadPath = NSURL(fileURLWithPath: temporaryDirectory).appendingPathComponent(destinationName) + } + + func downloaderDidFailWithError(_ error: Error) + { + XCTFail(error.localizedDescription); + self.asyncExpectation?.fulfill() } func downloaderDidFinish(withTemporaryDownloadData downloadData: SPUDownloadData?) { self.tempResult = downloadData - asyncExpectation?.fulfill() - } - - func downloaderDidSetDestinationName(_ destinationName: String, temporaryDirectory: String) - { - + self.asyncExpectation?.fulfill() } } @@ -46,7 +45,7 @@ class SPUDownloaderTest: XCTestCase { func performTemporaryDownloadTest(withDownloader downloader: SPUDownloader, delegate: SPUDownloaderTestDelegate) { - let delegateExpectation = expectation(description: "SPUDownloaderDeprecated temporary download") + let delegateExpectation = expectation(description: "SPUDownloader temporary download") delegate.asyncExpectation = delegateExpectation let url = URL.init(string: "https://sparkle-project.org/unit_test/test.xml") @@ -58,34 +57,87 @@ class SPUDownloaderTest: XCTestCase super.waitForExpectations(timeout: 30.0) { error in if let error = error { - XCTFail("waitForExpectationsWithTimeout had error: \(error)") + XCTFail("waitForExpectations had error: \(error)") } guard let result = delegate.tempResult else { - XCTFail("Expected delegate to be called") + XCTFail("Expected result to be non-nil") return } - let str = String.init(data: result.data, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) + let str = String.init(data: result.data, + encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) XCTAssert(str == "appcast\n") } } + // SHA256 code from: https://stackoverflow.com/a/42934185/3938401 + func sha256(data: Data) -> Data + { + var digestData = Data(count: Int(CC_SHA256_DIGEST_LENGTH)) + + _ = digestData.withUnsafeMutableBytes {digestBytes in + data.withUnsafeBytes {messageBytes in + CC_SHA256(messageBytes, CC_LONG(data.count), digestBytes) + } + } + return digestData + } + + func performPersistentDownloadTest(withDownloader downloader: SPUDownloader, delegate: SPUDownloaderTestDelegate) + { + let delegateExpectation = expectation(description: "SPUDownloader permanent download") + delegate.asyncExpectation = delegateExpectation + + let url = URL.init(string: "https://sparkle-project.org/unit_test/icon.png") + var request = URLRequest(url: url!, cachePolicy: .reloadIgnoringCacheData, timeoutInterval: 30.0) + request.setValue("image/png", forHTTPHeaderField: "Accept") + + let downloaderRequest = SPUURLRequest(request: request as URLRequest) + let bundleIdentifier = Bundle.init(for: self.superclass!).bundleIdentifier + downloader.startPersistentDownload(with: downloaderRequest, bundleIdentifier: bundleIdentifier!, desiredFilename: "icon") + + super.waitForExpectations(timeout: 30.0) { error in + if let error = error { + XCTFail("waitForExpectations had error: \(error)") + } + + guard let filePath = delegate.downloadPath else { + XCTFail("Expected download path to be non-nil") + return + } + + let fileManager = FileManager.default + XCTAssert(fileManager.fileExists(atPath: filePath.path)) + + do { + let iconData = try Data.init(contentsOf: filePath) + let sha256HashData = self.sha256(data: iconData) + let hashString = sha256HashData.map { String(format: "%02hhx", $0) }.joined().uppercased() + + XCTAssert(hashString == "F262E65663C505B9C6449B61660FA3F223912465AE637014288294A8CB286B85") + } catch { + XCTFail("Something went wrong reading the file data") + } + } + } + func testDeprecatedDownloader() { let delegate = SPUDownloaderTestDelegate() let downloader = SPUDownloaderDeprecated(delegate: delegate) self.performTemporaryDownloadTest(withDownloader: downloader!, delegate: delegate) - self.performPermanentDownloadTest(withDownloader: downloader!, delegate: delegate) + self.performPersistentDownloadTest(withDownloader: downloader!, delegate: delegate) } func testSessionDownloader() { let delegate = SPUDownloaderTestDelegate() - let downloader = SPUDownloaderSession(delegate: delegate) + var downloader = SPUDownloaderSession(delegate: delegate) self.performTemporaryDownloadTest(withDownloader: downloader!, delegate: delegate) - self.performPermanentDownloadTest(withDownloader: downloader!, delegate: delegate) + downloader = SPUDownloaderSession(delegate: delegate) + self.performPersistentDownloadTest(withDownloader: downloader!, delegate: delegate) } } diff --git a/Tests/Sparkle Unit Tests-Bridging-Header.h b/Tests/Sparkle Unit Tests-Bridging-Header.h index f60ff154..d16fb10d 100644 --- a/Tests/Sparkle Unit Tests-Bridging-Header.h +++ b/Tests/Sparkle Unit Tests-Bridging-Header.h @@ -21,6 +21,8 @@ #import "SPUDownloaderSession.h" #import "SPUURLRequest.h" +#import + NS_ASSUME_NONNULL_BEGIN // Duplicated to avoid exporting a private symbol from SUFileManager From bb6203f40ae52b89a4796d258d04e490a9d1aa92 Mon Sep 17 00:00:00 2001 From: Deadpikle Date: Thu, 28 Dec 2017 22:41:22 -0500 Subject: [PATCH 20/20] Fix typo in expectation description --- Tests/SPUDownloaderTest.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/SPUDownloaderTest.swift b/Tests/SPUDownloaderTest.swift index a8bcd512..b08bdb5f 100644 --- a/Tests/SPUDownloaderTest.swift +++ b/Tests/SPUDownloaderTest.swift @@ -86,7 +86,7 @@ class SPUDownloaderTest: XCTestCase func performPersistentDownloadTest(withDownloader downloader: SPUDownloader, delegate: SPUDownloaderTestDelegate) { - let delegateExpectation = expectation(description: "SPUDownloader permanent download") + let delegateExpectation = expectation(description: "SPUDownloader persistent download") delegate.asyncExpectation = delegateExpectation let url = URL.init(string: "https://sparkle-project.org/unit_test/icon.png")