diff --git a/Sparkle.xcodeproj/project.pbxproj b/Sparkle.xcodeproj/project.pbxproj index de720547..3aa5b330 100644 --- a/Sparkle.xcodeproj/project.pbxproj +++ b/Sparkle.xcodeproj/project.pbxproj @@ -49,6 +49,21 @@ 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 */; 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 */; 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 */; 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 */; 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 */; }; @@ -520,6 +535,22 @@ 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 = ""; }; + 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 = ""; }; + 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 = ""; }; @@ -1049,6 +1080,7 @@ children = ( 61299B3909CB055000B7442F /* Appcast Support */, 55C14BD5136EEFD000649790 /* Autoupdate */, + 34074B8B1FEABCE7001CB3A5 /* Downloader */, 089C1665FE841158C02AAC07 /* Framework Resources */, 618FA6DB0DB485440026945C /* Installation */, 61B5F8F309C4CE5900B25A18 /* Other Sources */, @@ -1079,6 +1111,28 @@ path = Resources; sourceTree = ""; }; + 34074B8B1FEABCE7001CB3A5 /* Downloader */ = { + isa = PBXGroup; + children = ( + 34074B9D1FEABD5A001CB3A5 /* SPUDownloadData.h */, + 34074B9C1FEABD5A001CB3A5 /* SPUDownloadData.m */, + 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 */, + 34074B8F1FEABD08001CB3A5 /* SPUDownloaderProtocol.h */, + 34074B941FEABD23001CB3A5 /* SPULocalCacheDirectory.h */, + 34074B951FEABD23001CB3A5 /* SPULocalCacheDirectory.m */, + 34074B991FEABD49001CB3A5 /* SPUURLRequest.h */, + 34074B981FEABD48001CB3A5 /* SPUURLRequest.m */, + ); + name = Downloader; + sourceTree = ""; + }; 55C14BD5136EEFD000649790 /* Autoupdate */ = { isa = PBXGroup; children = ( @@ -1144,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 */, @@ -1383,8 +1438,11 @@ 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 */, + 34074B961FEABD24001CB3A5 /* SPULocalCacheDirectory.h in Headers */, 61B93B270DD0FDD300DCD2F8 /* SUAutomaticUpdateDriver.h in Headers */, 61F83F740DBFE141006FDD30 /* SUBasicUpdateDriver.h in Headers */, 5D06E9390FD69271005AE3F6 /* SUBinaryDeltaUnarchiver.h in Headers */, @@ -1393,9 +1451,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 +1474,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 */, @@ -1428,6 +1490,7 @@ 61A354550DF113C70076ECB1 /* SUUserInitiatedUpdateDriver.h in Headers */, 61A2259E0D1C495D00430CCD /* SUVersionComparisonProtocol.h in Headers */, 3772FEA913DE0B6B00F79537 /* SUVersionDisplayProtocol.h in Headers */, + 34074BA21FEABFD2001CB3A5 /* SPUDownloaderSession.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -1648,6 +1711,9 @@ LastSwiftMigration = 0800; TestTargetID = 61B5F90109C4CEE200B25A18; }; + 8DC2EF4F0486A6940098B216 = { + LastSwiftMigration = 0920; + }; }; }; buildConfigurationList = 1DEB91B108733DA50010E9CD /* Build configuration list for PBXProject "Sparkle" */; @@ -1943,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 */, @@ -1997,6 +2064,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,7 +2073,9 @@ 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 */, + 34074BA31FEABFD2001CB3A5 /* SPUDownloaderSession.m in Sources */, 5D06E93A0FD69271005AE3F6 /* SUBinaryDeltaUnarchiver.m in Sources */, 72316BDA1E0E17180039EFD9 /* SUBundleIcon.m in Sources */, 61B078CF15A5FB6100600039 /* SUCodeSigningVerifier.m in Sources */, @@ -2017,6 +2087,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 */, @@ -2024,10 +2095,12 @@ 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 */, 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 */, @@ -2372,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; }; @@ -2425,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; }; @@ -2432,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/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..ef6e9067 --- /dev/null +++ b/Sparkle/SPUDownloader.m @@ -0,0 +1,118 @@ +// +// 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" +#import "SPUDownloader_Private.h" + +#include "AppKitPrevention.h" + +@interface SPUDownloader () + +@end + +@implementation SPUDownloader + +@synthesize delegate = _delegate; +@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; +} + +// 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 *)__unused request bundleIdentifier:(NSString *)__unused bundleIdentifier desiredFilename:(NSString *)__unused desiredFilename +{ + +} + +- (void)startTemporaryDownloadWithRequest:(SPUURLRequest *)__unused request +{ + +} + +- (void)enableAutomaticTermination +{ + if (self.disabledAutomaticTermination) { + [[NSProcessInfo processInfo] enableAutomaticTermination:SUDownloadingReason]; + self.disabledAutomaticTermination = NO; + } +} + +- (void)cleanup +{ + [self enableAutomaticTermination]; + self.delegate = nil; + + if (self.mode == SPUDownloadModeTemporary && self.downloadFilename != nil) + { + [[NSFileManager defaultManager] removeItemAtPath:self.downloadFilename error:NULL]; + self.downloadFilename = nil; + } +} + +- (void)cancel +{ + +} + +- (void)downloadDidFinish +{ + +} + +-(void)downloadDidFinishWithData:(SPUDownloadData*)data +{ + switch (self.mode) { + case SPUDownloadModeTemporary: + 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]}]]; + } + break; + case SPUDownloadModePersistent: + [self.delegate downloaderDidFinishWithTemporaryDownloadData:nil]; + break; + } +} + +-(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/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/SPUDownloaderDeprecated.h b/Sparkle/SPUDownloaderDeprecated.h new file mode 100644 index 00000000..36302df4 --- /dev/null +++ b/Sparkle/SPUDownloaderDeprecated.h @@ -0,0 +1,13 @@ +// +// SPUDownloaderDeprecated.h +// Sparkle +// +// Created by Deadpikle 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..ae2a065c --- /dev/null +++ b/Sparkle/SPUDownloaderDeprecated.m @@ -0,0 +1,167 @@ +// +// SPUDownloaderDeprecated.m +// Sparkle +// +// Created by Deadpikle 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" + +#include "AppKitPrevention.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 { + NSString *tempDir = [super getAndCleanTempDirectory]; + + if (tempDir != nil) { + 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]; +} + +- (void)cancel +{ + [self cleanup]; +} + +@end diff --git a/Sparkle/SPUDownloaderProtocol.h b/Sparkle/SPUDownloaderProtocol.h new file mode 100755 index 00000000..36f41fd4 --- /dev/null +++ b/Sparkle/SPUDownloaderProtocol.h @@ -0,0 +1,30 @@ +// +// 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; + +- (void)downloadDidFinish; + +- (void)cleanup; + +- (void)cancel; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Sparkle/SPUDownloaderSession.h b/Sparkle/SPUDownloaderSession.h new file mode 100644 index 00000000..3ca1754e --- /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..4dd0e961 --- /dev/null +++ b/Sparkle/SPUDownloaderSession.m @@ -0,0 +1,167 @@ +// +// 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" +#import "SPUDownloadData.h" + +#include "AppKitPrevention.h" + +@interface SPUDownloaderSession () + +@property (nonatomic) NSURLSession *downloadSession; +@property (nonatomic) NSURLSessionDownloadTask *download; + +@end + +@implementation SPUDownloaderSession + +@synthesize downloadSession = _downloadSession; +@synthesize download = _download; + +- (void)startDownloadWithRequest:(SPUURLRequest *)request +{ + NSOperationQueue *queue = [[NSOperationQueue alloc] init]; + queue.maxConcurrentOperationCount = 1; + self.downloadSession = [NSURLSession + sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] + delegate:self + delegateQueue:queue]; + 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 { + NSString *tempDir = [super getAndCleanTempDirectory]; + + if (tempDir != nil) { + 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; + if (error) { + [self.delegate downloaderDidFailWithError:error]; + } + [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]; +} + +- (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. + +@end diff --git a/Sparkle/SPUDownloader_Private.h b/Sparkle/SPUDownloader_Private.h new file mode 100644 index 00000000..af0464c8 --- /dev/null +++ b/Sparkle/SPUDownloader_Private.h @@ -0,0 +1,41 @@ +// +// 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, 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; + +// 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 + +#endif /* SPUDownloader_Private_h */ 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 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; diff --git a/Sparkle/SUAppcast.m b/Sparkle/SUAppcast.m index 6783684d..357c82a9 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,22 @@ } } --(NSArray *)parseAppcastItemsFromXMLFile:(NSURL *)appcastFile error:(NSError *__autoreleasing*)errorp { +-(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; } - 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 +295,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.h b/Sparkle/SUBasicUpdateDriver.h index bd83c4dd..26660c33 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,12 @@ - (void)didNotFindUpdate; - (void)downloadUpdate; -- (void)download:(NSURLDownload *)d decideDestinationWithSuggestedFilename:(NSString *)name; -- (void)downloadDidFinish:(NSURLDownload *)d; -- (void)download:(NSURLDownload *)download didFailWithError:(NSError *)error; +// SPUDownloaderDelegate +- (void)downloaderDidSetDestinationName:(NSString *)destinationName temporaryDirectory:(NSString *)temporaryDirectory; +- (void)downloaderDidReceiveExpectedContentLength:(int64_t)expectedContentLength; +- (void)downloaderDidReceiveDataOfLength:(uint64_t)length; +- (void)downloaderDidFinishWithTemporaryDownloadData:(SPUDownloadData *)downloadData; +- (void)downloaderDidFailWithError:(NSError *)error; - (void)extractUpdate; - (void)failedToApplyDeltaUpdate; diff --git a/Sparkle/SUBasicUpdateDriver.m b/Sparkle/SUBasicUpdateDriver.m index 927f3eae..ff0f7126 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,43 +282,44 @@ willDownloadUpdate:self.updateItem withRequest:request]; } - self.download = [[NSURLDownload alloc] initWithRequest:request delegate: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]; } -- (void)download:(NSURLDownload *)__unused d decideDestinationWithSuggestedFilename:(NSString *)name + +- (void)downloaderDidSetDestinationName:(NSString *)destinationName temporaryDirectory:(NSString *)temporaryDirectory { - 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]; + self.tempDir = temporaryDirectory; + self.downloadPath = [temporaryDirectory stringByAppendingPathComponent:destinationName]; } -- (void)downloadDidFinish:(NSURLDownload *)__unused d +- (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)download:(NSURLDownload *)__unused download didFailWithError:(NSError *)error +- (void)downloaderDidFailWithError:(NSError *)error { NSURL *failingUrl = [error.userInfo objectForKey:NSURLErrorFailingURLErrorKey]; if (!failingUrl) { @@ -319,31 +327,24 @@ } id updater = self.updater; - + if ([[updater delegate] respondsToSelector:@selector(updater:failedToDownloadUpdate:error:)]) { [[updater delegate] updater:self.updater - failedToDownloadUpdate:self.updateItem - error:error]; + 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, - }]; + 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; 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 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..b08bdb5f --- /dev/null +++ b/Tests/SPUDownloaderTest.swift @@ -0,0 +1,143 @@ +// +// 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? + var tempResult: SPUDownloadData? + 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 + self.asyncExpectation?.fulfill() + } +} + +class SPUDownloaderTest: XCTestCase +{ + func performTemporaryDownloadTest(withDownloader downloader: SPUDownloader, delegate: SPUDownloaderTestDelegate) + { + let delegateExpectation = expectation(description: "SPUDownloader 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) { error in + if let error = error { + XCTFail("waitForExpectations had error: \(error)") + } + + guard let result = delegate.tempResult else { + XCTFail("Expected result to be non-nil") + return + } + + 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 persistent 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.performPersistentDownloadTest(withDownloader: downloader!, delegate: delegate) + } + + func testSessionDownloader() + { + let delegate = SPUDownloaderTestDelegate() + var downloader = SPUDownloaderSession(delegate: delegate) + + self.performTemporaryDownloadTest(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 043587ed..d16fb10d 100644 --- a/Tests/Sparkle Unit Tests-Bridging-Header.h +++ b/Tests/Sparkle Unit Tests-Bridging-Header.h @@ -13,6 +13,16 @@ #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" + +#import + NS_ASSUME_NONNULL_BEGIN // Duplicated to avoid exporting a private symbol from SUFileManager