diff --git a/Configurations/ConfigFramework.xcconfig b/Configurations/ConfigFramework.xcconfig index fb394e01..d5ee6f5d 100644 --- a/Configurations/ConfigFramework.xcconfig +++ b/Configurations/ConfigFramework.xcconfig @@ -9,5 +9,5 @@ INFOPLIST_FILE = Sparkle/Sparkle-Info.plist GCC_PREPROCESSOR_DEFINITIONS = $(inherited) BUILDING_SPARKLE=1 OTHER_LDFLAGS = -Wl,-U,_NSURLQuarantinePropertiesKey SKIP_INSTALL = YES -DEFINES_MODULE = YES +DEFINES_MODULE = NO PRODUCT_BUNDLE_IDENTIFIER = ${SPARKLE_BUNDLE_IDENTIFIER} diff --git a/Sparkle Test App.entitlements b/Sparkle Test App.entitlements new file mode 100644 index 00000000..0c67376e --- /dev/null +++ b/Sparkle Test App.entitlements @@ -0,0 +1,5 @@ + + + + + diff --git a/Sparkle.xcodeproj/project.pbxproj b/Sparkle.xcodeproj/project.pbxproj index 501ba0e3..4ba21aa8 100644 --- a/Sparkle.xcodeproj/project.pbxproj +++ b/Sparkle.xcodeproj/project.pbxproj @@ -49,6 +49,17 @@ 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 */; }; + 33545B8D1B4679080059250D /* com.devmate.UpdateInstaller.xpc in Embed XPC Services */ = {isa = PBXBuildFile; fileRef = 33545B811B4679080059250D /* com.devmate.UpdateInstaller.xpc */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; }; + 33545B921B4679810059250D /* install_service.m in Sources */ = {isa = PBXBuildFile; fileRef = 33545B771B46774D0059250D /* install_service.m */; }; + 33545B931B4687CD0059250D /* SUConstants.m in Sources */ = {isa = PBXBuildFile; fileRef = 61299A5F09CA6EB100B7442F /* SUConstants.m */; }; + 33545B941B468A160059250D /* SULog.m in Sources */ = {isa = PBXBuildFile; fileRef = 55C14F05136EF6DB00649790 /* SULog.m */; }; + 33545B951B468A280059250D /* SUPlainInstallerInternals.m in Sources */ = {isa = PBXBuildFile; fileRef = 61B5F8E509C4CE3C00B25A18 /* SUPlainInstallerInternals.m */; }; + 33545B961B468A730059250D /* SUPlainInstaller.m in Sources */ = {isa = PBXBuildFile; fileRef = 618FA5040DAE8AB80026945C /* SUPlainInstaller.m */; }; + 33545B971B468ABB0059250D /* SUCodeSigningVerifier.m in Sources */ = {isa = PBXBuildFile; fileRef = 61B078CD15A5FB6100600039 /* SUCodeSigningVerifier.m */; }; + 33545B981B468AC80059250D /* SUInstaller.m in Sources */ = {isa = PBXBuildFile; fileRef = 618FA5000DAE88B40026945C /* SUInstaller.m */; }; + 33545B991B468AD60059250D /* SUGuidedPackageInstaller.m in Sources */ = {isa = PBXBuildFile; fileRef = 767B61AB1972D488004E0C3C /* SUGuidedPackageInstaller.m */; }; + 33545B9A1B468AE30059250D /* SUPackageInstaller.m in Sources */ = {isa = PBXBuildFile; fileRef = 618FA5210DAE8E8A0026945C /* SUPackageInstaller.m */; }; + 33545B9C1B46A5430059250D /* SUXPCInstaller.m in Sources */ = {isa = PBXBuildFile; fileRef = 33545B7C1B46774D0059250D /* SUXPCInstaller.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 */; }; @@ -247,6 +258,13 @@ remoteGlobalIDString = 55C14BB6136EEF1500649790; remoteInfo = Autoupdate; }; + 33545B8B1B4679080059250D /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 0867D690FE84028FC02AAC07 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33545B801B4679080059250D; + remoteInfo = "Installation XPC Service"; + }; 55C14F96136F044100649790 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 0867D690FE84028FC02AAC07 /* Project object */; @@ -298,6 +316,17 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + 33545B911B4679080059250D /* Embed XPC Services */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = "$(CONTENTS_FOLDER_PATH)/XPCServices"; + dstSubfolderSpec = 16; + files = ( + 33545B8D1B4679080059250D /* com.devmate.UpdateInstaller.xpc in Embed XPC Services */, + ); + name = "Embed XPC Services"; + runOnlyForDeploymentPostprocessing = 0; + }; 61B5FB4D09C4E9FA00B25A18 /* Copy Frameworks */ = { isa = PBXCopyFilesBuildPhase; buildActionMask = 2147483647; @@ -342,6 +371,14 @@ 14950074195FDF5900BC5B5B /* SUUpdaterTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SUUpdaterTest.m; sourceTree = ""; usesTabs = 0; }; 14958C6B19AEBC530061B14F /* signed-test-file.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = "signed-test-file.txt"; sourceTree = ""; }; 14958C6C19AEBC610061B14F /* test-pubkey.pem */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = "test-pubkey.pem"; sourceTree = ""; }; + 33545B771B46774D0059250D /* install_service.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = install_service.m; sourceTree = ""; }; + 33545B781B46774D0059250D /* install_service.pch */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = install_service.pch; sourceTree = ""; }; + 33545B791B46774D0059250D /* SandboxService.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = SandboxService.plist; sourceTree = ""; }; + 33545B7A1B46774D0059250D /* SUInstallServiceConstants.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SUInstallServiceConstants.h; sourceTree = ""; }; + 33545B7B1B46774D0059250D /* SUXPCInstaller.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SUXPCInstaller.h; sourceTree = ""; }; + 33545B7C1B46774D0059250D /* SUXPCInstaller.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = SUXPCInstaller.m; sourceTree = ""; }; + 33545B811B4679080059250D /* com.devmate.UpdateInstaller.xpc */ = {isa = PBXFileReference; explicitFileType = "wrapper.xpc-service"; includeInIndex = 0; path = com.devmate.UpdateInstaller.xpc; sourceTree = BUILT_PRODUCTS_DIR; }; + 33545B9B1B469BE60059250D /* Sparkle Test App.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.xml; path = "Sparkle Test App.entitlements"; 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 = ""; }; @@ -579,6 +616,13 @@ /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ + 33545B7E1B4679080059250D /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; 55C14BB5136EEF1500649790 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; @@ -652,6 +696,7 @@ 61B5F90209C4CEE200B25A18 /* Sparkle Test App.app */, 612279D90DB5470200AB99EA /* Sparkle Unit Tests.xctest */, 8DC2EF5B0486A6940098B216 /* Sparkle.framework */, + 33545B811B4679080059250D /* com.devmate.UpdateInstaller.xpc */, ); name = Products; sourceTree = ""; @@ -659,6 +704,7 @@ 0867D691FE84028FC02AAC07 /* Sparkle */ = { isa = PBXGroup; children = ( + 33545B9B1B469BE60059250D /* Sparkle Test App.entitlements */, 1495006D195FBBBD00BC5B5B /* Sparkle */, 14732BB81960EEB600593899 /* Resources */, 61227A100DB5484000AB99EA /* Tests */, @@ -772,6 +818,7 @@ 1495006D195FBBBD00BC5B5B /* Sparkle */ = { isa = PBXGroup; children = ( + 33545B761B46774D0059250D /* Installation XPC Service */, 61299B3909CB055000B7442F /* Appcast Support */, 55C14BD5136EEFD000649790 /* Autoupdate */, 089C1665FE841158C02AAC07 /* Framework Resources */, @@ -796,6 +843,19 @@ path = Resources; sourceTree = ""; }; + 33545B761B46774D0059250D /* Installation XPC Service */ = { + isa = PBXGroup; + children = ( + 33545B771B46774D0059250D /* install_service.m */, + 33545B781B46774D0059250D /* install_service.pch */, + 33545B791B46774D0059250D /* SandboxService.plist */, + 33545B7A1B46774D0059250D /* SUInstallServiceConstants.h */, + 33545B7B1B46774D0059250D /* SUXPCInstaller.h */, + 33545B7C1B46774D0059250D /* SUXPCInstaller.m */, + ); + path = "Installation XPC Service"; + sourceTree = ""; + }; 55C14BD5136EEFD000649790 /* Autoupdate */ = { isa = PBXGroup; children = ( @@ -1096,6 +1156,23 @@ /* End PBXLegacyTarget section */ /* Begin PBXNativeTarget section */ + 33545B801B4679080059250D /* Installation XPC Service */ = { + isa = PBXNativeTarget; + buildConfigurationList = 33545B8E1B4679080059250D /* Build configuration list for PBXNativeTarget "Installation XPC Service" */; + buildPhases = ( + 33545B7D1B4679080059250D /* Sources */, + 33545B7E1B4679080059250D /* Frameworks */, + 33545B7F1B4679080059250D /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = "Installation XPC Service"; + productName = "Installation XPC Service"; + productReference = 33545B811B4679080059250D /* com.devmate.UpdateInstaller.xpc */; + productType = "com.apple.product-type.xpc-service"; + }; 55C14BB6136EEF1500649790 /* Autoupdate */ = { isa = PBXNativeTarget; buildConfigurationList = 55C14BBE136EEF1500649790 /* Build configuration list for PBXNativeTarget "Autoupdate" */; @@ -1159,11 +1236,13 @@ 61B5F8FF09C4CEE200B25A18 /* Sources */, 61B5F90009C4CEE200B25A18 /* Frameworks */, 61B5FB4D09C4E9FA00B25A18 /* Copy Frameworks */, + 33545B911B4679080059250D /* Embed XPC Services */, ); buildRules = ( ); dependencies = ( 61B5F91C09C4CF7200B25A18 /* PBXTargetDependency */, + 33545B8C1B4679080059250D /* PBXTargetDependency */, ); name = "Sparkle Test App"; productName = "Test Application"; @@ -1204,9 +1283,19 @@ LastUpgradeCheck = 0700; ORGANIZATIONNAME = "Sparkle Project"; TargetAttributes = { + 33545B801B4679080059250D = { + CreatedOnToolsVersion = 6.3.2; + }; 612279D80DB5470200AB99EA = { TestTargetID = 8DC2EF4F0486A6940098B216; }; + 61B5F90109C4CEE200B25A18 = { + SystemCapabilities = { + com.apple.Sandbox = { + enabled = 0; + }; + }; + }; }; }; buildConfigurationList = 1DEB91B108733DA50010E9CD /* Build configuration list for PBXProject "Sparkle" */; @@ -1266,6 +1355,7 @@ 612279D80DB5470200AB99EA /* Sparkle Unit Tests */, 5D06E8CF0FD68C7C005AE3F6 /* BinaryDelta */, 55C14BB6136EEF1500649790 /* Autoupdate */, + 33545B801B4679080059250D /* Installation XPC Service */, 14732BC51960F69300593899 /* Distribution */, 1420DF491962329200203BB0 /* Documentation */, 1495005F195FB89400BC5B5B /* All */, @@ -1286,6 +1376,13 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + 33545B7F1B4679080059250D /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; 55C14BB3136EEF1500649790 /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; @@ -1404,6 +1501,22 @@ /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ + 33545B7D1B4679080059250D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33545B981B468AC80059250D /* SUInstaller.m in Sources */, + 33545B991B468AD60059250D /* SUGuidedPackageInstaller.m in Sources */, + 33545B9A1B468AE30059250D /* SUPackageInstaller.m in Sources */, + 33545B951B468A280059250D /* SUPlainInstallerInternals.m in Sources */, + 33545B961B468A730059250D /* SUPlainInstaller.m in Sources */, + 33545B941B468A160059250D /* SULog.m in Sources */, + 33545B921B4679810059250D /* install_service.m in Sources */, + 33545B971B468ABB0059250D /* SUCodeSigningVerifier.m in Sources */, + 33545B931B4687CD0059250D /* SUConstants.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; 55C14BB4136EEF1500649790 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; @@ -1488,6 +1601,7 @@ 55C14F07136EF6DB00649790 /* SULog.m in Sources */, 618FA5230DAE8E8A0026945C /* SUPackageInstaller.m in Sources */, 61D85D6D0E10B2ED00F9B4A9 /* SUPipedUnarchiver.m in Sources */, + 33545B9C1B46A5430059250D /* SUXPCInstaller.m in Sources */, 618FA5060DAE8AB80026945C /* SUPlainInstaller.m in Sources */, 61B5F8EF09C4CE3C00B25A18 /* SUPlainInstallerInternals.m in Sources */, 6101347C0DD2541A0049ACDF /* SUProbingUpdateDriver.m in Sources */, @@ -1554,6 +1668,11 @@ target = 55C14BB6136EEF1500649790 /* Autoupdate */; targetProxy = 1495006B195FB8A600BC5B5B /* PBXContainerItemProxy */; }; + 33545B8C1B4679080059250D /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33545B801B4679080059250D /* Installation XPC Service */; + targetProxy = 33545B8B1B4679080059250D /* PBXContainerItemProxy */; + }; 55C14F97136F044100649790 /* PBXTargetDependency */ = { isa = PBXTargetDependency; target = 55C14BB6136EEF1500649790 /* Autoupdate */; @@ -1796,6 +1915,73 @@ }; name = Release; }; + 33545B8F1B4679080059250D /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGN_IDENTITY = "Mac Developer"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREFIX_HEADER = "Sparkle/Installation XPC Service/install_service.pch"; + GCC_SYMBOLS_PRIVATE_EXTERN = NO; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + INFOPLIST_FILE = "Sparkle/Installation XPC Service/SandboxService.plist"; + MTL_ENABLE_DEBUG_INFO = YES; + PRODUCT_NAME = com.devmate.UpdateInstaller; + }; + name = Debug; + }; + 33545B901B4679080059250D /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGN_IDENTITY = "Mac Developer"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Sparkle/Installation XPC Service/install_service.pch"; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + INFOPLIST_FILE = "Sparkle/Installation XPC Service/SandboxService.plist"; + MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_NAME = com.devmate.UpdateInstaller; + }; + name = Release; + }; 55C14BBB136EEF1500649790 /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = FA1941D30D94A70100DD942E /* ConfigRelaunchDebug.xcconfig */; @@ -1842,6 +2028,7 @@ isa = XCBuildConfiguration; baseConfigurationReference = FA1941CB0D94A70100DD942E /* ConfigTestAppDebug.xcconfig */; buildSettings = { + CODE_SIGN_IDENTITY = "Mac Developer: Dmytro Tretiakov (425KC2B4DX)"; }; name = Debug; }; @@ -1849,6 +2036,7 @@ isa = XCBuildConfiguration; baseConfigurationReference = FA1941D20D94A70100DD942E /* ConfigTestAppRelease.xcconfig */; buildSettings = { + CODE_SIGN_IDENTITY = "Mac Developer: Dmytro Tretiakov (425KC2B4DX)"; }; name = Release; }; @@ -1900,6 +2088,15 @@ defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; + 33545B8E1B4679080059250D /* Build configuration list for PBXNativeTarget "Installation XPC Service" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33545B8F1B4679080059250D /* Debug */, + 33545B901B4679080059250D /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; 55C14BBE136EEF1500649790 /* Build configuration list for PBXNativeTarget "Autoupdate" */ = { isa = XCConfigurationList; buildConfigurations = ( diff --git a/Sparkle/Downloading XPC Service/Downloading XPC Service-Info.plist b/Sparkle/Downloading XPC Service/Downloading XPC Service-Info.plist new file mode 100644 index 00000000..0eaa5ef3 --- /dev/null +++ b/Sparkle/Downloading XPC Service/Downloading XPC Service-Info.plist @@ -0,0 +1,31 @@ + + + + + CFBundleDevelopmentRegion + English + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${EXECUTABLE_NAME} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + XPC! + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1 + XPCService + + ServiceType + Application + JoinExistingSession + + + + diff --git a/Sparkle/Downloading XPC Service/Downloading XPC Service-Prefix.pch b/Sparkle/Downloading XPC Service/Downloading XPC Service-Prefix.pch new file mode 100644 index 00000000..7b8ac2e3 --- /dev/null +++ b/Sparkle/Downloading XPC Service/Downloading XPC Service-Prefix.pch @@ -0,0 +1,4 @@ +// +// Prefix header for all source files of the 'Downloading XPC Service' target in the 'Downloading XPC Service' project +// + diff --git a/Sparkle/Downloading XPC Service/SUDSDownloader.h b/Sparkle/Downloading XPC Service/SUDSDownloader.h new file mode 100644 index 00000000..4275cb2b --- /dev/null +++ b/Sparkle/Downloading XPC Service/SUDSDownloader.h @@ -0,0 +1,60 @@ +// +// SUDSDownloader.h +// Sparkle +// +// Created by Dmytro Tretiakov on 8/1/13. +// +// + +#import + +#define DEBUG_LOGGING_ENABLED defined(DEBUG) && 1 + +@class SUDSDownloader; + +typedef void (^SUDSDownloadDidBegin)(SUDSDownloader *downloader); +typedef void (^SUDSDownloadDidFinish)(SUDSDownloader *downloader); +typedef void (^SUDSDownloadDidFail)(SUDSDownloader *downloader, NSError *error); +typedef void (^SUDSDownloadDidReceiveResponse)(SUDSDownloader *downloader, NSURLResponse *response); +typedef void (^SUDSDownloadDidReceiveData)(SUDSDownloader *downloader, NSUInteger dataLength); +typedef void (^SUDSDownloadDidCreateDestination)(SUDSDownloader *downloader, NSString *destinationPath); +typedef BOOL (^SUDSDownloadShouldDecodeSourceData)(SUDSDownloader *downloader, NSString *MIMEType); + +typedef struct SUDSDownloaderCallBacks +{ + SUDSDownloadDidBegin downloadDidBegin; + SUDSDownloadDidFinish downloadDidFinish; + SUDSDownloadDidFail downloadDidFail; + + SUDSDownloadDidReceiveResponse downloadDidReceiveResponse; + SUDSDownloadDidReceiveData downloadDidReceiveData; + SUDSDownloadDidCreateDestination downloadDidCreateDestination; + + SUDSDownloadShouldDecodeSourceData downloadShouldDecodeSourceData; +} SUDSDownloaderCallBacks; + +FOUNDATION_EXTERN SUDSDownloaderCallBacks SUDSCopyDownloaderCallBacks(SUDSDownloaderCallBacks callBacks); +FOUNDATION_EXTERN void SUDSReleaseDownloaderCallBacks(SUDSDownloaderCallBacks callBacks); + +@interface SUDSDownloader : NSObject +{ +@private + NSURLRequest *_request; + NSString *_destFilePath; + SUDSDownloaderCallBacks _callBacks; + + NSURLDownload *_download; +} + +- (id)initWithURLRequest:(NSURLRequest *)request destinationPath:(NSString *)filePath; ++ (id)downloaderWithURLRequest:(NSURLRequest *)request destinationPath:(NSString *)filePath; + +- (NSURLRequest *)request; +- (NSString *)destinationPath; +- (void)setCallBacks:(SUDSDownloaderCallBacks)callBacks; + +- (void)startDownload; +- (void)stopDownload; +- (BOOL)isInProgress; + +@end diff --git a/Sparkle/Downloading XPC Service/SUDSDownloader.m b/Sparkle/Downloading XPC Service/SUDSDownloader.m new file mode 100644 index 00000000..fbf8aba3 --- /dev/null +++ b/Sparkle/Downloading XPC Service/SUDSDownloader.m @@ -0,0 +1,210 @@ +// +// SUDSDownloader.m +// Sparkle +// +// Created by Dmytro Tretiakov on 8/1/13. +// +// + +#import "SUDSDownloader.h" + +SUDSDownloaderCallBacks SUDSCopyDownloaderCallBacks(SUDSDownloaderCallBacks callBacks) +{ + SUDSDownloaderCallBacks callBacksCopy = {0}; + + if (callBacks.downloadDidBegin) + callBacksCopy.downloadDidBegin = Block_copy(callBacks.downloadDidBegin); + if (callBacks.downloadDidFinish) + callBacksCopy.downloadDidFinish = Block_copy(callBacks.downloadDidFinish); + if (callBacks.downloadDidFail) + callBacksCopy.downloadDidFail = Block_copy(callBacks.downloadDidFail); + if (callBacks.downloadDidReceiveData) + callBacksCopy.downloadDidReceiveData = Block_copy(callBacks.downloadDidReceiveData); + if (callBacks.downloadDidCreateDestination) + callBacksCopy.downloadDidCreateDestination = Block_copy(callBacks.downloadDidCreateDestination); + if (callBacks.downloadDidReceiveResponse) + callBacksCopy.downloadDidReceiveResponse = Block_copy(callBacks.downloadDidReceiveResponse); + if (callBacks.downloadShouldDecodeSourceData) + callBacksCopy.downloadShouldDecodeSourceData = Block_copy(callBacks.downloadShouldDecodeSourceData); + + return callBacksCopy; +} + +void SUDSReleaseDownloaderCallBacks(SUDSDownloaderCallBacks callBacks) +{ + if (callBacks.downloadDidBegin) + Block_release(callBacks.downloadDidBegin); + if (callBacks.downloadDidFinish) + Block_release(callBacks.downloadDidFinish); + if (callBacks.downloadDidFail) + Block_release(callBacks.downloadDidFail); + if (callBacks.downloadDidReceiveData) + Block_release(callBacks.downloadDidReceiveData); + if (callBacks.downloadDidCreateDestination) + Block_release(callBacks.downloadDidCreateDestination); + if (callBacks.downloadDidReceiveResponse) + Block_release(callBacks.downloadDidReceiveResponse); + if (callBacks.downloadShouldDecodeSourceData) + Block_release(callBacks.downloadShouldDecodeSourceData); +} + +@implementation SUDSDownloader + +- (id)initWithURLRequest:(NSURLRequest *)request destinationPath:(NSString *)filePath +{ + self = [super init]; + if (self != nil) + { + _request = [request retain]; + _destFilePath = [filePath copy]; + } + + return self; +} + ++ (id)downloaderWithURLRequest:(NSURLRequest *)request destinationPath:(NSString *)filePath +{ + return [[[[self class] alloc] initWithURLRequest:request destinationPath:filePath] autorelease]; +} + +- (void)dealloc +{ + [self stopDownload]; + + [_request release]; + [_destFilePath release]; + SUDSReleaseDownloaderCallBacks(_callBacks); + + [super dealloc]; +} + +- (NSURLRequest *)request +{ + return _request; +} + +- (NSString *)destinationPath +{ + return _destFilePath; +} + +- (void)setCallBacks:(SUDSDownloaderCallBacks)callBacks +{ + SUDSDownloaderCallBacks oldCallBacks = _callBacks; + _callBacks = SUDSCopyDownloaderCallBacks(callBacks); + SUDSReleaseDownloaderCallBacks(oldCallBacks); +} + +- (void)startDownload +{ + [self stopDownload]; + + // to ensure that parent folder exists + [[NSFileManager defaultManager] createDirectoryAtPath:[_destFilePath stringByDeletingLastPathComponent] + withIntermediateDirectories:YES + attributes:nil + error:NULL]; + NSURLDownload *urlDownload = [[NSURLDownload alloc] initWithRequest:_request delegate:self]; + @synchronized (self) + { + _download = urlDownload; + } + + [urlDownload setDestination:_destFilePath allowOverwrite:YES]; +} + +- (void)stopDownload +{ + @synchronized (self) + { + [_download cancel]; + [_download release]; + _download = nil; + } +} + +- (BOOL)isInProgress +{ + BOOL result = YES; + @synchronized (self) + { + result = _download != nil; + } + + return result; +} + +#pragma mark - + +- (void)downloadDidBegin:(NSURLDownload *)download +{ +#if DEBUG_LOGGING_ENABLED + NSLog(@"XPC Downloader did begin process."); +#endif + if (_callBacks.downloadDidBegin) + _callBacks.downloadDidBegin(self); +} + +- (void)download:(NSURLDownload *)download didReceiveResponse:(NSURLResponse *)response +{ +#if DEBUG_LOGGING_ENABLED + NSLog(@"XPC Downloader did receive response: %@", [response description]); +#endif + if (_callBacks.downloadDidReceiveResponse) + _callBacks.downloadDidReceiveResponse(self, response); +} + +- (void)download:(NSURLDownload *)download didCreateDestination:(NSString *)path +{ +#if DEBUG_LOGGING_ENABLED + NSLog(@"XPC Downloader did create destination: %@", path); +#endif + if (_callBacks.downloadDidCreateDestination) + _callBacks.downloadDidCreateDestination(self, path); +} + +- (void)download:(NSURLDownload *)download didReceiveDataOfLength:(NSUInteger)length +{ +#if DEBUG_LOGGING_ENABLED + NSLog(@"XPC Downloader did receive data of length %ld bytes", (unsigned long)length); +#endif + if (_callBacks.downloadDidReceiveData) + _callBacks.downloadDidReceiveData(self, length); +} + +- (void)download:(NSURLDownload *)download didFailWithError:(NSError *)error +{ +#if DEBUG_LOGGING_ENABLED + NSLog(@"XPC Downloader did fail: %@", [error description]); +#endif + if (_callBacks.downloadDidFail) + _callBacks.downloadDidFail(self, error); + + [self stopDownload]; +} + +- (void)downloadDidFinish:(NSURLDownload *)download +{ +#if DEBUG_LOGGING_ENABLED + NSLog(@"XPC Downloader did finish"); +#endif + if (_callBacks.downloadDidFinish) + _callBacks.downloadDidFinish(self); + + [self stopDownload]; +} + +- (BOOL)download:(NSURLDownload *)download shouldDecodeSourceDataOfMIMEType:(NSString *)encodingType +{ + BOOL shouldDecode = NO; + +#if DEBUG_LOGGING_ENABLED + NSLog(@"XPC Downloader wants decode source data of MIME type: %@", encodingType); +#endif + if (_callBacks.downloadShouldDecodeSourceData) + shouldDecode = _callBacks.downloadShouldDecodeSourceData(self, encodingType); + + return shouldDecode; +} + +@end diff --git a/Sparkle/Downloading XPC Service/SUDownloadServiceConstants.h b/Sparkle/Downloading XPC Service/SUDownloadServiceConstants.h new file mode 100644 index 00000000..b20f4ebf --- /dev/null +++ b/Sparkle/Downloading XPC Service/SUDownloadServiceConstants.h @@ -0,0 +1,29 @@ +// +// SUDownloadServiceConstants.h +// Sparkle +// +// Created by Dmytro Tretiakov on 7/29/13. +// +// + +#ifndef Sparkle_SUDownloadServiceConstants_h +#define Sparkle_SUDownloadServiceConstants_h + +const char * SUDownloadServiceURLRequestDataKey = "request_data"; // data of archived NSURLRequest +const char * SUDownloadServiceDelegateConnectionKey = "connection"; // xpc_connection_t +const char * SUDownloadServiceFilePathKey = "file_path"; // c-string + +const char * SUDownloadServiceReceivedDataLengthKey = "received_data_length"; // int64_t +const char * SUDownloadServiceReceivedResponseDataKey = "received_response_data"; // data of archived NSURLResponse +const char * SUDownloadServiceCreatedDestinationPathKey = "created_destination_path"; // c-string +const char * SUDownloadServiceDidBeginDownloadingKey = "did_begin_downloading"; // bool 1 +const char * SUDownloadServiceDidFinishDownloadingKey = "did_finish_downloading"; // bool 1 +const char * SUDownloadServiceReceivedFailErrorKey = "received_fail_error"; // data of archived NSError +const char * SUDownloadServiceMIMETypeToDecodeKey = "MIME_type_to_decode"; // c-string +const char * SUDownloadServiceShouldDecodeMIMETypeKey = "should_decode_MIME_type"; // bool + +const char * SUDownloadServiceErrorCodeKey = "errcode"; // int64_t +const char * SUDownloadServiceErrorMessageKey = "errmsg"; // c-string +const char * SUDownloadServiceErrorDomainKey = "errdomain"; // c-string + +#endif diff --git a/Sparkle/Downloading XPC Service/SUXPCURLDownload.h b/Sparkle/Downloading XPC Service/SUXPCURLDownload.h new file mode 100644 index 00000000..b9bf4bc2 --- /dev/null +++ b/Sparkle/Downloading XPC Service/SUXPCURLDownload.h @@ -0,0 +1,36 @@ +// +// SUXPCURLDownload.h +// Sparkle +// +// Created by Erik Aderstedt on 2012-08-09. +// +// + +#import + +@interface SUXPCURLDownload : NSObject +{ +@private + id _delegate; // weak ref + xpc_connection_t _connection; + xpc_connection_t _delegateConnection; + NSURLRequest *_request; + NSThread *_startedThread; // weak ref + BOOL _isDownloading; + + BOOL _allowOverwrite; + NSString *_destination; + NSString *_connectionDestination; + NSError *_downloadError; +} + +- (id )delegate; +- (void)setDelegate:(id )delegate; + +- (id)initWithRequest:(NSURLRequest *)request delegate:(id )delegate; +- (void)setDestination:(NSString *)path allowOverwrite:(BOOL)allowOverwrite; + +// Delegate methods for this method will be called from another thread. ++ (NSData *)sendSynchronousRequest:(NSURLRequest *)request delegate:(id )delegate; + +@end diff --git a/Sparkle/Downloading XPC Service/SUXPCURLDownload.m b/Sparkle/Downloading XPC Service/SUXPCURLDownload.m new file mode 100644 index 00000000..6d28e6e3 --- /dev/null +++ b/Sparkle/Downloading XPC Service/SUXPCURLDownload.m @@ -0,0 +1,448 @@ +// +// SUXPCURLDownload.m +// Sparkle +// +// Created by Erik Aderstedt on 2012-08-09. +// +// + +#import "SUXPCURLDownload.h" +#import "SUDownloadServiceConstants.h" +#import "SUConstants.h" +#import "SULog.h" + +static NSString * const kSUFetchFolderName = @"fetch.XXXXXXXX"; + +@interface SUXPCURLDownload (Private) + +- (void)performBlock:(void (^)(void))block onThread:(NSThread *)thread synchronous:(BOOL)flag; +- (void)fireBlock:(void (^)(void))block; + +@end + +@implementation SUXPCURLDownload + ++ (NSData *)sendSynchronousRequest:(NSURLRequest *)request delegate:(id )delegate +{ + __block SUXPCURLDownload *download = nil; + + static const char *sSynchronousDownloadQueueName = "com.devmate.SynchronousXPCDownloadQueue"; + dispatch_queue_t queue = dispatch_queue_create(sSynchronousDownloadQueueName, NULL); + dispatch_sync(queue, ^{ + download = [[SUXPCURLDownload alloc] initWithRequest:request delegate:delegate]; + }); + + while (download && download->_isDownloading) + { + [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.5]]; + } + + NSData *downloadData = (nil == download->_downloadError) ? [NSData dataWithContentsOfFile:download->_destination] : nil; + [download release]; + dispatch_release(queue); + + return downloadData; +} + +- (id)initWithRequest:(NSURLRequest *)request delegate:(id )delegate +{ + self = [super init]; + if (self != nil) + { + _request = [request retain]; + _delegate = [delegate retain]; + _startedThread = [NSThread currentThread]; + + // Set up a connection. + _connection = [self getSandboxXPCService]; + dispatch_async(dispatch_get_current_queue(), ^{ + [self startDownload:request]; + }); + + _isDownloading = YES; + } + + return self; +} + +- (void)dealloc +{ + [self cancel]; + + [_request release]; + [_destination release]; + [_connectionDestination release]; + [_downloadError release]; + + [super dealloc]; +} + +- (NSURLRequest *)request +{ + return _request; +} + +- (void)startDownload:(NSURLRequest *)urlRequest +{ + // Send a message to download a specific url. + if ([_delegate respondsToSelector:@selector(download:decideDestinationWithSuggestedFilename:)] && _destination == nil) + { + void (^block)(void) = ^{ + [_delegate download:(NSURLDownload *)self decideDestinationWithSuggestedFilename:[[urlRequest URL] lastPathComponent]]; + }; + [self performBlock:block onThread:_startedThread synchronous:YES]; + } + if (nil == _destination) + { + _destination = [[[urlRequest URL] lastPathComponent] copy]; + } + + // ivar 'destination' now contains the destination URL. + + NSURL *tempFolder = [NSURL fileURLWithPath:NSTemporaryDirectory()]; + NSString *tempFileTemplate = [[tempFolder URLByAppendingPathComponent:kSUFetchFolderName] path]; + NSString *tempFilePath = [tempFileTemplate stringByAppendingPathComponent:[_destination lastPathComponent]]; + + NSFileManager *fileManager = [NSFileManager defaultManager]; + if ([fileManager fileExistsAtPath:tempFilePath]) + [fileManager removeItemAtPath:tempFilePath error:nil]; + + _connectionDestination = [tempFilePath copy]; + + NSData *requestData = [NSKeyedArchiver archivedDataWithRootObject:urlRequest]; + + xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0); + xpc_dictionary_set_data(message, SUDownloadServiceURLRequestDataKey, [requestData bytes], [requestData length]); + xpc_dictionary_set_string(message, SUDownloadServiceFilePathKey, [tempFilePath cStringUsingEncoding:NSUTF8StringEncoding]); + xpc_dictionary_set_connection(message, SUDownloadServiceDelegateConnectionKey, _delegateConnection); + xpc_connection_send_message_with_reply(_connection, message, dispatch_get_main_queue(), ^(xpc_object_t object) { + xpc_type_t type = xpc_get_type(object); + + if (type == XPC_TYPE_ERROR && nil == _downloadError) + { + NSString *errMessage = @""; + if (object == XPC_ERROR_CONNECTION_INTERRUPTED) + { + errMessage = @"Got XPC_ERROR_CONNECTION_INTERRUPTED error."; + } + else if (object == XPC_ERROR_CONNECTION_INVALID) + { + errMessage = @"Got XPC_ERROR_CONNECTION_INVALID error."; + } + + NSDictionary *errInfo = [NSDictionary dictionaryWithObject:errMessage forKey:NSLocalizedDescriptionKey]; + _downloadError = [[NSError alloc] initWithDomain:SUSparkleErrorDomain code:SUXPCServiceError userInfo:errInfo]; + } + else if (type == XPC_TYPE_DICTIONARY && noErr != xpc_dictionary_get_int64(object, SUDownloadServiceErrorCodeKey) && nil == _downloadError) + { + NSInteger errCode = (NSInteger)xpc_dictionary_get_int64(object, SUDownloadServiceErrorCodeKey); + + const char *errDomainStr = xpc_dictionary_get_string(object, SUDownloadServiceErrorDomainKey); + NSString *errDomain = errDomainStr ? [NSString stringWithUTF8String:errDomainStr] : NSCocoaErrorDomain; + + const char *errMessage = xpc_dictionary_get_string(object, SUDownloadServiceErrorMessageKey) ? : ""; + NSDictionary *errInfo = [NSDictionary dictionaryWithObject:[NSString stringWithUTF8String:errMessage] + forKey:NSLocalizedDescriptionKey]; + + _downloadError = [[NSError alloc] initWithDomain:errDomain code:errCode userInfo:errInfo]; + } + + if (nil != _downloadError) + { + if ([_delegate respondsToSelector:@selector(download:didFailWithError:)]) + { + void (^block)(void) = ^{ + [_delegate download:(NSURLDownload *)self didFailWithError:_downloadError]; + _isDownloading = NO; + }; + [self performBlock:block onThread:_startedThread synchronous:NO]; + } + else + { + SULog(@"SUXPCURLDownload: got download error (%d - %@)", [_downloadError code], [_downloadError localizedDescription]); + _isDownloading = NO; + } + } + }); + xpc_release(message); +} + +- (id )delegate +{ + return _delegate; +} + +- (void)setDelegate:(id )delegate +{ + _delegate = delegate; +} + +- (void)setDestination:(NSString *)path allowOverwrite:(BOOL)allowOverwrite +{ + [_destination release]; + _destination = [path copy]; + _allowOverwrite = allowOverwrite; +} + +- (void)cancel +{ + if (_connection) + { + xpc_connection_cancel(_connection); + xpc_release(_connection); + _connection = NULL; + } + if (_delegateConnection) + { + xpc_connection_cancel(_delegateConnection); + xpc_release(_delegateConnection); + _delegateConnection = NULL; + } +} + +- (xpc_connection_t)getSandboxXPCService +{ + // Set up two connections, one for instructing the XPC and getting a response, + // and another to listen for incoming connections for progress and file creation + // notifications. + + _connection = xpc_connection_create("com.devmate.UpdateDownloader", dispatch_get_main_queue()); + if (!_connection) + { + NSLog(@"Can't connect to XPC service"); + return (NULL); + } + + xpc_connection_set_event_handler(_connection, ^(xpc_object_t event) { + xpc_type_t type = xpc_get_type(event); + + if (type == XPC_TYPE_ERROR) + { + if (event == XPC_ERROR_CONNECTION_INTERRUPTED) + { + NSLog(@"Got XPC_ERROR_CONNECTION_INTERRUPTED error."); + // The service has either cancaled itself, crashed, or been + // terminated. The XPC connection is still valid and sending a + // message to it will re-launch the service. If the service is + // state-full, this is the time to initialize the new service. + + } + else if (event == XPC_ERROR_CONNECTION_INVALID) + { + NSLog(@"Got XPC_ERROR_CONNECTION_INVALID error."); + // The service is invalid. Either the service name supplied to + // xpc_connection_create() is incorrect or we (this process) have + // canceled the service; we can do any cleanup of appliation + // state at this point. + if (_delegateConnection) + { + xpc_connection_cancel(_delegateConnection); + xpc_release(_delegateConnection); + _delegateConnection = NULL; + } + } + } + }); + + dispatch_queue_t delegate_queue = dispatch_queue_create("com.devmate.UpdateDownloader.delegate", NULL); + assert(delegate_queue != NULL); + + _delegateConnection = xpc_connection_create(NULL, delegate_queue); + xpc_connection_set_event_handler(_delegateConnection, ^(xpc_object_t event) { + xpc_type_t type = xpc_get_type(event); + + if (type == XPC_TYPE_ERROR) + { + if (event == XPC_ERROR_TERMINATION_IMMINENT) + { + NSLog(@"received XPC_ERROR_TERMINATION_IMMINENT"); + } + else if (event == XPC_ERROR_CONNECTION_INVALID) + { + NSLog(@"progress connection is closed"); + dispatch_release(delegate_queue); + } + } + else if (type == XPC_TYPE_CONNECTION) + { + xpc_connection_t peer = (xpc_connection_t)event; + // A new anonymous connection, from an XPC service that wants to supply us with updates. + char *queue_name = NULL; + dispatch_queue_t peer_event_queue = dispatch_queue_create(queue_name, NULL); + assert(peer_event_queue != NULL); + free(queue_name); + + xpc_connection_set_target_queue(peer, peer_event_queue); + xpc_connection_set_event_handler(peer, ^(xpc_object_t nevent) { + xpc_type_t ntype = xpc_get_type(nevent); + + if (ntype == XPC_TYPE_ERROR && nevent == XPC_ERROR_CONNECTION_INVALID) + dispatch_release(peer_event_queue); + if (ntype != XPC_TYPE_DICTIONARY) + return; + + __block xpc_object_t answer = xpc_dictionary_create_reply(nevent); + + xpc_dictionary_apply(nevent, ^bool(const char *key, xpc_object_t value) { + NSAutoreleasePool *localPool = [[NSAutoreleasePool alloc] init]; + + if (0 == strcmp(key, SUDownloadServiceDidBeginDownloadingKey)) + { + if ([_delegate respondsToSelector:@selector(downloadDidBegin:)]) + { + void (^block)(void) = ^ { + [_delegate downloadDidBegin:(NSURLDownload *)self]; + }; + [self performBlock:block onThread:_startedThread synchronous:NO]; + } + } + else if (0 == strcmp(key, SUDownloadServiceReceivedResponseDataKey)) + { + if ([_delegate respondsToSelector:@selector(download:didReceiveResponse:)]) + { + size_t dataLength = 0; + const void * responseDataBytes = xpc_dictionary_get_data(nevent, SUDownloadServiceReceivedResponseDataKey, &dataLength); + NSData *responseData = [NSData dataWithBytes:responseDataBytes length:(NSUInteger)dataLength]; + + NSURLResponse *response = [NSKeyedUnarchiver unarchiveObjectWithData:responseData]; + void (^block)(void) = ^ { + [_delegate download:(NSURLDownload *)self didReceiveResponse:response]; + }; + [self performBlock:block onThread:_startedThread synchronous:NO]; + } + } + else if (0 == strcmp(key, SUDownloadServiceReceivedDataLengthKey)) + { + if ([_delegate respondsToSelector:@selector(download:didReceiveDataOfLength:)]) + { + int64_t dataLength = xpc_dictionary_get_int64(nevent, SUDownloadServiceReceivedDataLengthKey); + void (^block)(void) = ^ { + [_delegate download:(NSURLDownload *)self didReceiveDataOfLength:(NSUInteger)dataLength]; + }; + [self performBlock:block onThread:_startedThread synchronous:NO]; + } + } + else if (0 == strcmp(key, SUDownloadServiceCreatedDestinationPathKey)) + { + [_connectionDestination release]; + _connectionDestination = [[NSString alloc] initWithCString:xpc_dictionary_get_string(nevent, SUDownloadServiceCreatedDestinationPathKey) + encoding:NSUTF8StringEncoding]; + } + else if (0 == strcmp(key, SUDownloadServiceReceivedFailErrorKey)) + { + size_t dataLength = 0; + const void * errorDataBytes = xpc_dictionary_get_data(nevent, SUDownloadServiceReceivedFailErrorKey, &dataLength); + NSData *errorData = [NSData dataWithBytes:errorDataBytes length:dataLength]; + + NSError *error = [NSKeyedUnarchiver unarchiveObjectWithData:errorData]; + _downloadError = [error retain]; + } + else if (0 == strcmp(key, SUDownloadServiceDidFinishDownloadingKey)) + { + NSFileManager *fileManager = [NSFileManager defaultManager]; + + NSString *destPath = _destination; + if (nil == destPath || [destPath isEqualToString:[destPath lastPathComponent]]) + { + destPath = _connectionDestination; + } + else if (!_allowOverwrite) + { + NSUInteger index = 1; + NSString *parentFolder = [destPath stringByDeletingLastPathComponent]; + NSString *initialFileName = [[destPath lastPathComponent] stringByDeletingPathExtension]; + NSString *fileExtension = [destPath pathExtension]; + + while ([fileManager fileExistsAtPath:destPath]) + { + NSString *fileName = [initialFileName stringByAppendingFormat:@"_%ld", index]; + destPath = [[parentFolder stringByAppendingPathComponent:fileName] stringByAppendingPathExtension:fileExtension]; + ++index; + } + } + + NSError *error = nil; + BOOL success = YES; + + if (![destPath isEqualToString:_connectionDestination]) + { + success = success && [fileManager createDirectoryAtPath:[destPath stringByDeletingLastPathComponent] + withIntermediateDirectories:YES + attributes:nil + error:&error]; + if (success && [fileManager fileExistsAtPath:destPath]) + success = [fileManager removeItemAtPath:destPath error:&error]; + success = success && [fileManager moveItemAtPath:_connectionDestination toPath:destPath error:&error]; + } + + if (success) + { + [self setDestination:destPath allowOverwrite:_allowOverwrite]; + + void (^block)(void) = ^ { + if ([_delegate respondsToSelector:@selector(download:didCreateDestination:)]) + [_delegate download:(NSURLDownload *)self didCreateDestination:destPath]; + + if ([_delegate respondsToSelector:@selector(downloadDidFinish:)]) + [_delegate downloadDidFinish:(NSURLDownload *)self]; + + _isDownloading = NO; + }; + [self performBlock:block onThread:_startedThread synchronous:NO]; + } + else + { + _downloadError = [error retain]; + } + } + else if (0 == strcmp(key, SUDownloadServiceMIMETypeToDecodeKey)) + { + void (^block)(void) = ^{ + BOOL shouldDecode = NO; + if ([_delegate respondsToSelector:@selector(download:shouldDecodeSourceDataOfMIMEType:)]) + { + NSString *MIMEType = [NSString stringWithCString:xpc_dictionary_get_string(nevent, SUDownloadServiceMIMETypeToDecodeKey) + encoding:NSUTF8StringEncoding]; + shouldDecode = [_delegate download:(NSURLDownload *)self shouldDecodeSourceDataOfMIMEType:MIMEType]; + } + xpc_dictionary_set_bool(answer, SUDownloadServiceShouldDecodeMIMETypeKey, YES); + }; + [self performBlock:block onThread:_startedThread synchronous:YES]; + } + + [localPool release]; + + return true; + }); + + xpc_connection_send_message(peer, answer); + xpc_release(answer); + }); + xpc_connection_resume(peer); + } + }); + + // Need to resume the service in order for it to process messages. + xpc_connection_resume(_delegateConnection); + xpc_connection_resume(_connection); + return _connection; +} + +#pragma mark - Private + +- (void)performBlock:(void (^)(void))block onThread:(NSThread *)thread synchronous:(BOOL)flag +{ + void (^blockCopy)(void) = block != NULL ? Block_copy(block) : NULL; + [self performSelector:@selector(fireBlock:) onThread:thread withObject:blockCopy waitUntilDone:flag]; +} + +- (void)fireBlock:(void (^)(void))block +{ + if (NULL == block) + return; + + block(); + Block_release(block); +} + +@end diff --git a/Sparkle/Downloading XPC Service/download_service.m b/Sparkle/Downloading XPC Service/download_service.m new file mode 100644 index 00000000..36454c65 --- /dev/null +++ b/Sparkle/Downloading XPC Service/download_service.m @@ -0,0 +1,265 @@ +// +// main.m +// Downloading XPC Service +// +// Created by Erik Aderstedt on 2012-08-09. +// Based on the Apple sample code 'SandboxedFetch'. +// + +#import +#import +#import +#import +#import + +#import "SUDownloadServiceConstants.h" +#import "SUDSDownloader.h" +#import "SUConstants.h" + +static void fetch_process_request(xpc_object_t request, xpc_object_t reply); +static void fetch_peer_event_handler(xpc_connection_t peer, xpc_object_t event); +static void fetch_event_handler(xpc_connection_t peer); + +#pragma mark - + +// Process the XPC request, create a temporary file to hold downloaded, +// data, and build/return XPC reply. +static void fetch_process_request(xpc_object_t request, xpc_object_t reply) +{ + __block int32_t errcode = 0; + __block const char *errmsg = NULL; + __block const char *errdomain = NULL; + + xpc_connection_t connection = NULL; + + NSAutoreleasePool *localPool = [[NSAutoreleasePool alloc] init]; + do + { + size_t dataLength = 0; + const void *data = xpc_dictionary_get_data(request, SUDownloadServiceURLRequestDataKey, &dataLength); + NSData *requestData = [NSData dataWithBytes:data length:dataLength]; + + NSURLRequest *urlRequest = [NSKeyedUnarchiver unarchiveObjectWithData:requestData]; + if (nil == urlRequest) + { + errcode = SUXPCServiceError; + errdomain = [SUSparkleErrorDomain cStringUsingEncoding:NSUTF8StringEncoding]; + errmsg = "Invalid URL request data"; + break; + } + + // Get the URL and XPC connection from the XPC request + connection = xpc_dictionary_create_connection(request, SUDownloadServiceDelegateConnectionKey); + if (connection == NULL) + { + errcode = SUXPCServiceError; + errdomain = [SUSparkleErrorDomain cStringUsingEncoding:NSUTF8StringEncoding]; + errmsg = "Invalid XPC delegate connection"; + break; + } + + // Set up XPC connection endpoint for sending progress reports and receiving cancel notification. + __block BOOL shouldStopDownload = NO; + xpc_connection_set_event_handler(connection, ^(xpc_object_t event) { + xpc_type_t type = xpc_get_type(event); + + // If the remote end of this connection has gone away then stop download + if (XPC_TYPE_ERROR == type && + (XPC_ERROR_CONNECTION_INTERRUPTED == event || XPC_ERROR_CONNECTION_INVALID == event)) + { + asl_log(NULL, NULL, ASL_LEVEL_NOTICE, "Stopping download process...\n"); + shouldStopDownload = YES; + } + }); + xpc_connection_resume(connection); + + NSString *destinationPath = [NSString stringWithCString:xpc_dictionary_get_string(request, SUDownloadServiceFilePathKey) + encoding:NSUTF8StringEncoding]; + SUDSDownloader *downloader = [SUDSDownloader downloaderWithURLRequest:urlRequest + destinationPath:destinationPath]; + + SUDSDownloaderCallBacks callBacks = {0}; + + callBacks.downloadDidReceiveData = ^(SUDSDownloader *downloader, NSUInteger dataLength) { + xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0); + xpc_dictionary_set_int64(message, SUDownloadServiceReceivedDataLengthKey, (int64_t)dataLength); + xpc_object_t answer = xpc_connection_send_message_with_reply_sync(connection, message); + xpc_release(message); + xpc_release(answer); + }; + + callBacks.downloadDidReceiveResponse = ^(SUDSDownloader *downloader, NSURLResponse *response) { + NSData *responseData = [NSKeyedArchiver archivedDataWithRootObject:response]; + + xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0); + xpc_dictionary_set_data(message, SUDownloadServiceReceivedResponseDataKey, [responseData bytes], [responseData length]); + xpc_object_t answer = xpc_connection_send_message_with_reply_sync(connection, message); + xpc_release(message); + xpc_release(answer); + }; + + callBacks.downloadDidCreateDestination = ^(SUDSDownloader *downloader, NSString *destinationPath) { + xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0); + xpc_dictionary_set_string(message, SUDownloadServiceCreatedDestinationPathKey, [destinationPath cStringUsingEncoding:NSUTF8StringEncoding]); + xpc_object_t answer = xpc_connection_send_message_with_reply_sync(connection, message); + xpc_release(message); + xpc_release(answer); + }; + + callBacks.downloadDidBegin = ^(SUDSDownloader *downloader) { + xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0); + xpc_dictionary_set_bool(message, SUDownloadServiceDidBeginDownloadingKey, true); + xpc_object_t answer = xpc_connection_send_message_with_reply_sync(connection, message); + xpc_release(message); + xpc_release(answer); + }; + + callBacks.downloadDidFail = ^(SUDSDownloader *downloader, NSError *error) { + errcode = (int32_t)[error code]; + errdomain = [[error domain] cStringUsingEncoding:NSUTF8StringEncoding]; + errmsg = [[error localizedDescription] cStringUsingEncoding:NSUTF8StringEncoding]; + + NSData *errorData = [NSKeyedArchiver archivedDataWithRootObject:error]; + + xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0); + xpc_dictionary_set_data(message, SUDownloadServiceReceivedFailErrorKey, [errorData bytes], [errorData length]); + xpc_object_t answer = xpc_connection_send_message_with_reply_sync(connection, message); + xpc_release(message); + xpc_release(answer); + }; + + callBacks.downloadDidFinish = ^(SUDSDownloader *downloader) { + xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0); + xpc_dictionary_set_bool(message, SUDownloadServiceDidFinishDownloadingKey, true); + xpc_object_t answer = xpc_connection_send_message_with_reply_sync(connection, message); + xpc_release(message); + xpc_release(answer); + }; + + callBacks.downloadShouldDecodeSourceData = ^BOOL(SUDSDownloader *downloader, NSString *MIMEType) { + xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0); + xpc_dictionary_set_string(message, SUDownloadServiceMIMETypeToDecodeKey, [MIMEType cStringUsingEncoding:NSUTF8StringEncoding]); + xpc_object_t answer = xpc_connection_send_message_with_reply_sync(connection, message); + xpc_release(message); + + BOOL result = NO; + if (xpc_get_type(answer) == XPC_TYPE_DICTIONARY) + result = (BOOL)xpc_dictionary_get_bool(answer, SUDownloadServiceShouldDecodeMIMETypeKey); + xpc_release(answer); + + return result; + }; + + [downloader setCallBacks:callBacks]; + + [downloader startDownload]; + while ([downloader isInProgress]) + { + if (shouldStopDownload) + { + [downloader stopDownload]; + asl_log(NULL, NULL, ASL_LEVEL_NOTICE, "Download process stopped.\n"); + break; + } + + CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, true); + } + } + while (NO); + [localPool release]; + +#if DEBUG_LOGGING_ENABLED + NSLog(@"Download process finished. Will send last message..."); +#endif + // Clean up and add errcode/errmsg to reply + if (connection) + { + xpc_connection_cancel(connection); + xpc_release(connection); + } + + xpc_dictionary_set_int64(reply, SUDownloadServiceErrorCodeKey, (int64_t)errcode); + if (errmsg) + { + xpc_dictionary_set_string(reply, SUDownloadServiceErrorMessageKey, errmsg); + } + if (errdomain) + { + xpc_dictionary_set_string(reply, SUDownloadServiceErrorDomainKey, errdomain); + } +} + +static void fetch_peer_event_handler(xpc_connection_t peer, xpc_object_t event) +{ + // Get the object type. + xpc_type_t type = xpc_get_type(event); + if (XPC_TYPE_ERROR == type) + { + // Handle an error. + if (XPC_ERROR_CONNECTION_INVALID == event) + { + // The client process on the other end of the connection + // has either crashed or cancelled the connection. + asl_log(NULL, NULL, ASL_LEVEL_NOTICE, "peer(%d) received " + "XPC_ERROR_CONNECTION_INVALID", + xpc_connection_get_pid(peer)); + xpc_connection_cancel(peer); + } + else if (XPC_ERROR_TERMINATION_IMMINENT == event) + { + // Handle per-connection termination cleanup. This + // service is about to exit. + asl_log(NULL, NULL, ASL_LEVEL_NOTICE, "peer(%d) received " + "XPC_ERROR_TERMINATION_IMMINENT", + xpc_connection_get_pid(peer)); + } + } + else if (XPC_TYPE_DICTIONARY == type) + { + xpc_object_t requestMessage = event; + xpc_object_t replyMessage = xpc_dictionary_create_reply(requestMessage); + assert(replyMessage != NULL); + + // Process request and build a reply message. + fetch_process_request(requestMessage, replyMessage); + + xpc_connection_send_message(peer, replyMessage); + xpc_release(replyMessage); + } +} + +static void release_dispatch_queue(void *queue) +{ + dispatch_release(queue); +} + +static void fetch_event_handler(xpc_connection_t peer) +{ + // Generate an unique name for the queue to handle messages from + // this peer and create a new dispatch queue for it. + char *queue_name = NULL; + asprintf(&queue_name, "%s-peer-%d", "com.devmate.UpdateDownloader", xpc_connection_get_pid(peer)); + dispatch_queue_t peer_event_queue = dispatch_queue_create(queue_name, DISPATCH_QUEUE_SERIAL); + assert(peer_event_queue != NULL); + free(queue_name); + + // Set the target queue for connection. + xpc_connection_set_target_queue(peer, peer_event_queue); + xpc_connection_set_context(peer, peer_event_queue); + xpc_connection_set_finalizer_f(peer, release_dispatch_queue); + + // Set the handler block for connection. + xpc_connection_set_event_handler(peer, ^(xpc_object_t event) { + fetch_peer_event_handler(peer, event); + }); + + // Enable the peer connection to receive messages. + xpc_connection_resume(peer); +} + +int main(int argc, const char *argv[]) +{ + xpc_main(fetch_event_handler); + exit(EXIT_FAILURE); +} + diff --git a/Sparkle/Downloading XPC Service/en.lproj/InfoPlist.strings b/Sparkle/Downloading XPC Service/en.lproj/InfoPlist.strings new file mode 100644 index 00000000..477b28ff --- /dev/null +++ b/Sparkle/Downloading XPC Service/en.lproj/InfoPlist.strings @@ -0,0 +1,2 @@ +/* Localized versions of Info.plist keys */ + diff --git a/Sparkle/Installation XPC Service/SUInstallServiceConstants.h b/Sparkle/Installation XPC Service/SUInstallServiceConstants.h new file mode 100644 index 00000000..3b5a1491 --- /dev/null +++ b/Sparkle/Installation XPC Service/SUInstallServiceConstants.h @@ -0,0 +1,40 @@ +// +// SUInstallServiceConstants.h +// Sparkle +// +// Created by Dmytro Tretiakov on 8/2/13. +// +// + +#ifndef Sparkle_SUInstallServiceConstants_h +#define Sparkle_SUInstallServiceConstants_h + +typedef NS_ENUM(UInt64, SUInstallServiceTask) +{ + SUInstallServiceTaskUnknown = 0, + SUInstallServiceTaskCopyPath = 1LL, + SUInstallServiceTaskAuthCopyPath = 2LL, + SUInstallServiceTaskLaunchTask = 3LL +}; + +static const char * SUInstallServiceTaskTypeKey = "task_type"; // int64_t + +// SUInstallServiceTaskCopyPath & SUInstallServiceTaskAuthCopyPath keys +static const char * SUInstallServiceSourcePathKey = "source_path"; // c-string +static const char * SUInstallServiceDestinationPathKey = "destination_path"; // c-string +static const char * SUInstallServiceTempNameKey = "tmp_name"; // c-string + +// SUInstallServiceTaskLaunchTask keys +static const char * SUInstallServiceLaunchTaksPathKey = "launch_task_path"; +static const char * SUInstallServiceLaunchTaskArgumentsKey = "launch_task_arguments"; // xpc_array of c-strings +static const char * SUInstallServiceLaunchTaskEnvironmentKey = "launch_task_environment"; // xpc_dictionary with keys and values of c-strings +static const char * SUInstallServiceLaunchTaskCurrentDirKey = "launch_task_cur_dir"; // c-string +static const char * SUInstallServiceLaunchTaskInputDataKey = "launch_task_input_data"; // xpc_data +static const char * SUInstallServiceLaunchTaskReplyImmediatelyKey = "launch_task_reply_immediately"; // bool + +// Reply keys +static const char * SUInstallServiceErrorCodeKey = "error_code"; // int64_t +static const char * SUInstallServiceErrorLocalizedDescriptionKey = "error_localized_description"; // c-string +static const char * SUInstallServiceLaunchTaskOutputDataKey = "launch_task_output_data"; // xpc_data + +#endif diff --git a/Sparkle/Installation XPC Service/SUXPCInstaller.h b/Sparkle/Installation XPC Service/SUXPCInstaller.h new file mode 100644 index 00000000..2b64a666 --- /dev/null +++ b/Sparkle/Installation XPC Service/SUXPCInstaller.h @@ -0,0 +1,31 @@ +// +// SUXPCInstaller.h +// Sparkle +// +// Created by Whitney Young on 3/19/12. +// Copyright (c) 2012 FadingRed. All rights reserved. +// + +#import + + +@interface SUXPCInstaller : NSObject + ++ (BOOL)copyPathWithAuthentication:(NSString *)src overPath:(NSString *)dst temporaryName:(NSString *)tmp error:(NSError **)outError; + ++ (BOOL)copyPathContent:(NSString *)src toDirectory:(NSString *)dstDir error:(NSError **)outError; // dstDir will be created if absent + ++ (void)launchTaskWithLaunchPath:(NSString *)path arguments:(NSArray *)arguments; + ++ (void)launchTaskWithPath:(NSString *)launchPath + arguments:(NSArray *)arguments + environment:(NSDictionary *)environment + currentDirectoryPath:(NSString *)currentDirPath + inputData:(NSData *)inputData + waitForTaskResult:(BOOL)waitForTaskResult + waitUntilDone:(BOOL)waitUntilDone // for sync/async logic + completionHandler:(void (^)(int result, NSData *outputData))completionHandler; + +@end + +FOUNDATION_EXPORT BOOL SUShouldUseXPCInstaller(void); diff --git a/Sparkle/Installation XPC Service/SUXPCInstaller.m b/Sparkle/Installation XPC Service/SUXPCInstaller.m new file mode 100644 index 00000000..cbde9ffb --- /dev/null +++ b/Sparkle/Installation XPC Service/SUXPCInstaller.m @@ -0,0 +1,277 @@ +// +// SUXPCInstaller.m +// Sparkle +// +// Created by Whitney Young on 3/19/12. +// Copyright (c) 2012 FadingRed. All rights reserved. +// + +#import +#import "SUXPCInstaller.h" +#import "SUInstallServiceConstants.h" +#import "SUCodeSigningVerifier.h" + +BOOL SUShouldUseXPCInstaller(void) +{ + if (![SUCodeSigningVerifier hostApplicationIsSandboxed]) + return NO; + + NSString *xpcServicePrefixPath = [[NSBundle mainBundle] bundlePath]; + NSString *xpcServiceSuffixPath = @"Contents/XPCServices/com.devmate.UpdateInstaller.xpc"; + return [[NSFileManager defaultManager] fileExistsAtPath:[xpcServicePrefixPath stringByAppendingPathComponent:xpcServiceSuffixPath]]; +} + +@implementation SUXPCInstaller + ++ (xpc_connection_t)getSandboxXPCService +{ + __block xpc_connection_t serviceConnection = xpc_connection_create("com.devmate.UpdateInstaller", dispatch_get_main_queue()); + + if (!serviceConnection) + { + NSLog(@"Can't connect to XPC service"); + return (NULL); + } + + xpc_connection_set_event_handler(serviceConnection, ^(xpc_object_t event) { + xpc_type_t type = xpc_get_type(event); + + if (type == XPC_TYPE_ERROR) + { + if (event == XPC_ERROR_CONNECTION_INVALID) + { + // The service is invalid. Either the service name supplied to + // xpc_connection_create() is incorrect or we (this process) have + // canceled the service; we can do any cleanup of appliation + // state at this point. + xpc_release(serviceConnection); + } + } + }); + + // Need to resume the service in order for it to process messages. + xpc_connection_resume(serviceConnection); + return (serviceConnection); +} + ++ (BOOL)copyPathWithAuthentication:(NSString *)src overPath:(NSString *)dst temporaryName:(NSString *)tmp error:(NSError * __autoreleasing*)outError +{ + xpc_connection_t connection = [self getSandboxXPCService]; + + xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0); + xpc_dictionary_set_int64(message, SUInstallServiceTaskTypeKey, (int64_t)SUInstallServiceTaskAuthCopyPath); + + if (src) + xpc_dictionary_set_string(message, SUInstallServiceSourcePathKey, [src fileSystemRepresentation]); + if (dst) + xpc_dictionary_set_string(message, SUInstallServiceDestinationPathKey, [dst fileSystemRepresentation]); + if (tmp) + xpc_dictionary_set_string(message, SUInstallServiceTempNameKey, [tmp UTF8String]); + + __block BOOL xpcDidReply = NO; + __block NSError *error = nil; + + dispatch_queue_t queue = dispatch_queue_create(NULL, DISPATCH_QUEUE_SERIAL); + xpc_connection_send_message_with_reply(connection, message, queue, ^(xpc_object_t response) { + if (XPC_TYPE_ERROR == xpc_get_type(response)) + { + NSDictionary *errorInfo = [NSDictionary dictionaryWithObject:@"Internal XPC error." + forKey:NSLocalizedDescriptionKey]; + error = [[NSError alloc] initWithDomain:SUSparkleErrorDomain code:SUXPCServiceError userInfo:errorInfo]; + } + else if (XPC_TYPE_DICTIONARY == xpc_get_type(response)) + { + const char *errorString = xpc_dictionary_get_string(response, SUInstallServiceErrorLocalizedDescriptionKey); + if (errorString != NULL) + { + NSDictionary *errorInfo = [NSDictionary dictionaryWithObject:[NSString stringWithCString:errorString encoding:NSUTF8StringEncoding] + forKey:NSLocalizedDescriptionKey]; + error = [[NSError alloc] initWithDomain:SUSparkleErrorDomain code:SUXPCServiceError userInfo:errorInfo]; + } + } + + xpcDidReply = YES; + }); + + while (NO == xpcDidReply) + { + [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.2]]; + } + + xpc_release(message); + dispatch_release(queue); + + if (nil != error && NULL != outError) + { + *outError = error; + } + + return (nil == error); +} + ++ (BOOL)copyPathContent:(NSString *)src toDirectory:(NSString *)dstDir error:(NSError * __autoreleasing*)outError +{ + xpc_connection_t connection = [self getSandboxXPCService]; + + xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0); + xpc_dictionary_set_int64(message, SUInstallServiceTaskTypeKey, (int64_t)SUInstallServiceTaskCopyPath); + + if (src) + xpc_dictionary_set_string(message, SUInstallServiceSourcePathKey, [src fileSystemRepresentation]); + if (dstDir) + xpc_dictionary_set_string(message, SUInstallServiceDestinationPathKey, [dstDir fileSystemRepresentation]); + + __block BOOL xpcDidReply = NO; + __block NSError *error = nil; + + dispatch_queue_t queue = dispatch_queue_create(NULL, DISPATCH_QUEUE_SERIAL); + xpc_connection_send_message_with_reply(connection, message, queue, ^(xpc_object_t response) { + if (XPC_TYPE_ERROR == xpc_get_type(response)) + { + NSDictionary *errorInfo = [NSDictionary dictionaryWithObject:@"Internal XPC error." + forKey:NSLocalizedDescriptionKey]; + error = [[NSError alloc] initWithDomain:SUSparkleErrorDomain code:SUXPCServiceError userInfo:errorInfo]; + } + else if (XPC_TYPE_DICTIONARY == xpc_get_type(response)) + { + const char *errorString = xpc_dictionary_get_string(response, SUInstallServiceErrorLocalizedDescriptionKey); + if (errorString != NULL) + { + NSDictionary *errorInfo = [NSDictionary dictionaryWithObject:[NSString stringWithCString:errorString encoding:NSUTF8StringEncoding] + forKey:NSLocalizedDescriptionKey]; + error = [[NSError alloc] initWithDomain:SUSparkleErrorDomain code:SUXPCServiceError userInfo:errorInfo]; + } + } + + xpcDidReply = YES; + }); + + while (NO == xpcDidReply) + { + [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.2]]; + } + + xpc_release(message); + dispatch_release(queue); + + if (nil != error && NULL != outError) + { + *outError = error; + } + + return (nil == error); +} + ++ (void)launchTaskWithLaunchPath:(NSString *)path arguments:(NSArray *)arguments +{ + [self launchTaskWithPath:path + arguments:arguments + environment:nil + currentDirectoryPath:nil + inputData:nil + waitForTaskResult:NO + waitUntilDone:YES + completionHandler:nil]; +} + ++ (void)launchTaskWithPath:(NSString *)launchPath + arguments:(NSArray *)arguments + environment:(NSDictionary *)environment + currentDirectoryPath:(NSString *)currentDirPath + inputData:(NSData *)inputData + waitForTaskResult:(BOOL)waitForTaskResult + waitUntilDone:(BOOL)waitUntilDone + completionHandler:(void (^)(int result, NSData *outputData))completionHandler +{ + xpc_connection_t connection = [self getSandboxXPCService]; + + xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0); + xpc_dictionary_set_int64(message, SUInstallServiceTaskTypeKey, (int64_t)SUInstallServiceTaskLaunchTask); + + if ([launchPath length]) + { + xpc_dictionary_set_string(message, SUInstallServiceLaunchTaksPathKey, [launchPath fileSystemRepresentation]); + } + + if ([arguments count]) + { + xpc_object_t array = xpc_array_create(NULL, 0); + for (id argument in arguments) + { + NSString *strArgument = argument; + if (![strArgument isKindOfClass:[NSString class]]) + strArgument = [argument description]; + + xpc_array_set_string(array, XPC_ARRAY_APPEND, [strArgument UTF8String]); + } + xpc_dictionary_set_value(message, SUInstallServiceLaunchTaskArgumentsKey, array); + xpc_release(array); + } + + if ([environment count]) + { + __block xpc_object_t dict = xpc_dictionary_create(NULL, NULL, 0); + [environment enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL __unused *stop) { + NSString *xpc_key = [key isKindOfClass:[NSString class]] ? key : [key description]; + NSString *xpc_value = [obj isKindOfClass:[NSString class]] ? obj : [obj description]; + + xpc_dictionary_set_string(dict, [xpc_key UTF8String], [xpc_value UTF8String]); + }]; + + xpc_dictionary_set_value(message, SUInstallServiceLaunchTaskEnvironmentKey, dict); + xpc_release(dict); + } + + if ([currentDirPath length]) + { + xpc_dictionary_set_string(message, SUInstallServiceLaunchTaskCurrentDirKey, [currentDirPath fileSystemRepresentation]); + } + + if ([inputData length]) + { + xpc_dictionary_set_data(message, SUInstallServiceLaunchTaskInputDataKey, [inputData bytes], [inputData length]); + } + + xpc_dictionary_set_bool(message, SUInstallServiceLaunchTaskReplyImmediatelyKey, waitForTaskResult ? false : true); + + __block BOOL xpcTaskDidReply = NO; + xpc_connection_send_message_with_reply(connection, message, dispatch_get_current_queue(), ^(xpc_object_t response) { + int taskResult = 0; + NSData *outputData = nil; + + if (completionHandler != NULL) + { + xpc_type_t type = xpc_get_type(response); + if (type == XPC_TYPE_ERROR) + { + taskResult = SUXPCServiceError; + } + else if (type == XPC_TYPE_DICTIONARY) + { + taskResult = (int)xpc_dictionary_get_int64(response, SUInstallServiceErrorCodeKey); + + size_t bytesLen = 0; + const void *bytes = xpc_dictionary_get_data(response, SUInstallServiceLaunchTaskOutputDataKey, &bytesLen); + if (NULL != bytes) + { + outputData = [NSData dataWithBytes:bytes length:bytesLen]; + } + } + + completionHandler(taskResult, outputData); + } + + xpcTaskDidReply = YES; + }); + xpc_release(message); + + if (waitUntilDone) + { + while (NO == xpcTaskDidReply) + { + [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.2]]; + } + } +} + +@end diff --git a/Sparkle/Installation XPC Service/SandboxService.plist b/Sparkle/Installation XPC Service/SandboxService.plist new file mode 100644 index 00000000..0eaa5ef3 --- /dev/null +++ b/Sparkle/Installation XPC Service/SandboxService.plist @@ -0,0 +1,31 @@ + + + + + CFBundleDevelopmentRegion + English + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${EXECUTABLE_NAME} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + XPC! + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1 + XPCService + + ServiceType + Application + JoinExistingSession + + + + diff --git a/Sparkle/Installation XPC Service/install_service.m b/Sparkle/Installation XPC Service/install_service.m new file mode 100644 index 00000000..94bc2b8c --- /dev/null +++ b/Sparkle/Installation XPC Service/install_service.m @@ -0,0 +1,375 @@ +// +// main.m +// Update +// +// Created by Whitney Young on 3/19/12. +// Copyright (c) 2012 FadingRed. All rights reserved. +// + +#include +#include + +#import +#import "SUPlainInstallerInternals.h" +#import "SUInstallServiceConstants.h" + +static xpc_object_t SUSICopyPathContent(xpc_object_t message) +{ + if (NULL == message) + return NULL; + + const char *src = xpc_dictionary_get_string(message, SUInstallServiceSourcePathKey); + const char *dst = xpc_dictionary_get_string(message, SUInstallServiceDestinationPathKey); + + NSFileManager *manager = [NSFileManager defaultManager]; + NSString *sourcePath = src ? [manager stringWithFileSystemRepresentation:src length:strlen(src)] : nil; + NSString *targetPath = dst ? [manager stringWithFileSystemRepresentation:dst length:strlen(dst)] : nil; + + NSError *error = nil; + do + { + if (nil == sourcePath) + { + NSDictionary *errorInfo = [NSDictionary dictionaryWithObject:@"Source path is absent." forKey:NSLocalizedDescriptionKey]; + error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUXPCServiceError userInfo:errorInfo]; + break; + } + + if (nil == targetPath) + { + NSDictionary *errorInfo = [NSDictionary dictionaryWithObject:@"Destination path is absent." forKey:NSLocalizedDescriptionKey]; + error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUXPCServiceError userInfo:errorInfo]; + break; + } + + NSArray *contents = nil; + + BOOL isSrcDirectory = NO; + BOOL isSrcExist = [manager fileExistsAtPath:sourcePath isDirectory:&isSrcDirectory]; + isSrcDirectory = isSrcDirectory && ![[NSWorkspace sharedWorkspace] isFilePackageAtPath:sourcePath]; + if (isSrcExist && isSrcDirectory) + { + contents = [manager contentsOfDirectoryAtPath:sourcePath error:&error]; + } + else if (isSrcExist) + { + contents = [NSArray arrayWithObject:@""]; + } + else + { + NSDictionary *errorInfo = [NSDictionary dictionaryWithObject:@"Source does not exist on disk." forKey:NSLocalizedDescriptionKey]; + error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUXPCServiceError userInfo:errorInfo]; + } + + if (nil != error) + { + break; + } + + BOOL isDstDirectory = NO; + BOOL isDstExist = [manager fileExistsAtPath:targetPath isDirectory:&isDstDirectory]; + if (isSrcDirectory && (!isDstExist || !isDstDirectory)) + { + if (isDstExist) + [manager removeItemAtPath:targetPath error:&error]; + [manager createDirectoryAtPath:targetPath withIntermediateDirectories:YES attributes:nil error:&error]; + } + else if (!isSrcDirectory) + { + if (isDstExist && !isDstDirectory) + [manager removeItemAtPath:targetPath error:&error]; + [manager createDirectoryAtPath:targetPath withIntermediateDirectories:YES attributes:nil error:&error]; + } + + if (nil != error) + { + break; + } + + for (NSString *item in contents) + { + NSString *fromPath = [item length] ? [sourcePath stringByAppendingPathComponent:item] : sourcePath; + NSString *toPath = [item length] ? [targetPath stringByAppendingPathComponent:item] : [targetPath stringByAppendingPathComponent:[sourcePath lastPathComponent]]; + + if (![manager isReadableFileAtPath:fromPath]) + { + SULog(@"XPC Install Service: will skip \"%@\"", fromPath); + continue; + } + + SULog(@"XPC Install Service: will copy \"%@\" to \"%@\"", fromPath, toPath); + + if ([manager fileExistsAtPath:toPath]) + [manager removeItemAtPath:toPath error:&error]; + + if (![manager copyItemAtPath:fromPath toPath:toPath error:&error]) + break; + } + } + while (NO); + + xpc_object_t reply = xpc_dictionary_create_reply(message); + if (nil != error) + { + xpc_dictionary_set_int64(reply, SUInstallServiceErrorCodeKey, (int64_t)[error code]); + const char *errorMsg = [[error localizedDescription] length] ? [[error localizedDescription] UTF8String] : ""; + xpc_dictionary_set_string(reply, SUInstallServiceErrorLocalizedDescriptionKey, errorMsg); + } + + return reply; +} + +static xpc_object_t SUISCopyPathWithAuthentication(xpc_object_t message) +{ + if (NULL == message) + return NULL; + + const char *src = xpc_dictionary_get_string(message, SUInstallServiceSourcePathKey); + const char *dst = xpc_dictionary_get_string(message, SUInstallServiceDestinationPathKey); + const char *tmp = xpc_dictionary_get_string(message, SUInstallServiceTempNameKey); + + NSFileManager *manager = [NSFileManager defaultManager]; + NSString *relaunchPathToCopy = src ? [manager stringWithFileSystemRepresentation:src length:strlen(src)] : nil; + NSString *targetPath = dst ? [manager stringWithFileSystemRepresentation:dst length:strlen(dst)] : nil; + NSString *temporaryName = tmp ? [NSString stringWithUTF8String:tmp] : nil; + NSError *error = nil; + BOOL result = [SUPlainInstaller copyPathWithAuthentication:relaunchPathToCopy overPath:targetPath temporaryName:temporaryName error:&error]; + + // send response to indicate ok + xpc_object_t reply = xpc_dictionary_create_reply(message); + if (!result && error != nil) + { + xpc_dictionary_set_int64(reply, SUInstallServiceErrorCodeKey, (int64_t)[error code]); + const char *errorMsg = [[error localizedDescription] length] ? [[error localizedDescription] UTF8String] : ""; + xpc_dictionary_set_string(reply, SUInstallServiceErrorLocalizedDescriptionKey, errorMsg); + } + + return reply; +} + +static xpc_object_t SUISLaunchTask(xpc_object_t message) +{ + if (NULL == message) + return NULL; + + const char *path = xpc_dictionary_get_string(message, SUInstallServiceLaunchTaksPathKey); + NSString *launchPath = path ? [[NSFileManager defaultManager] stringWithFileSystemRepresentation:path length:strlen(path)] : nil; + + xpc_object_t array = xpc_dictionary_get_value(message, SUInstallServiceLaunchTaskArgumentsKey); + NSArray *arguments = nil; + if (NULL != array) + { + size_t count = xpc_array_get_count(array); + NSMutableArray *mutableArgs = [NSMutableArray arrayWithCapacity:count]; + for (size_t i = 0; i < count; i++) + { + [mutableArgs addObject:[NSString stringWithUTF8String:xpc_array_get_string(array, i)]]; + } + + arguments = mutableArgs; + } + + xpc_object_t dict = xpc_dictionary_get_value(message, SUInstallServiceLaunchTaskEnvironmentKey); + NSDictionary *environment = nil; + if (NULL != dict) + { + size_t count = xpc_dictionary_get_count(dict); + __block NSMutableDictionary *mutableEnv = [NSMutableDictionary dictionaryWithCapacity:count]; + + xpc_dictionary_apply(dict, ^bool(const char *key, xpc_object_t value) { + NSString *envKey = [NSString stringWithUTF8String:key]; + NSString *envValue = [NSString stringWithUTF8String:value]; + [mutableEnv setObject:envValue forKey:envKey]; + return true; + }); + + environment = mutableEnv; + } + + path = xpc_dictionary_get_string(message, SUInstallServiceLaunchTaskCurrentDirKey); + NSString *currentDirPath = path ? [[NSFileManager defaultManager] stringWithFileSystemRepresentation:path length:strlen(path)] : nil; + + size_t bytesLen = 0; + const void *bytes = xpc_dictionary_get_data(message, SUInstallServiceLaunchTaskInputDataKey, &bytesLen); + NSData *inputData = bytes ? [NSData dataWithBytes:bytes length:bytesLen] : nil; + + bool shouldReplyImmediatly = xpc_dictionary_get_bool(message, SUInstallServiceLaunchTaskReplyImmediatelyKey); + + // prepare NSTask + NSTask *task = [[NSTask alloc] init]; + NSPipe *inputPipe = [NSPipe pipe]; + NSPipe *outputPipe = [NSPipe pipe]; + + [task setStandardInput:inputPipe]; + [task setStandardOutput:outputPipe]; + [task setStandardError:outputPipe]; + + if (launchPath != nil) + [task setLaunchPath:launchPath]; + if ([arguments count]) + [task setArguments:arguments]; + if ([environment count]) + [task setEnvironment:environment]; + if (currentDirPath != nil) + [task setCurrentDirectoryPath:currentDirPath]; + + __block NSData *outputData = nil; + __block int taskResult = 0; + __block BOOL isTaskRunning = YES; + + NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; + NSArray *notificationObjects = nil; + + if (!shouldReplyImmediatly) + { + id object1 = [notificationCenter addObserverForName:NSFileHandleReadToEndOfFileCompletionNotification + object:[outputPipe fileHandleForReading] + queue:[NSOperationQueue mainQueue] + usingBlock:^(NSNotification *note) { + outputData = [[note userInfo] objectForKey:NSFileHandleNotificationDataItem]; + isTaskRunning = NO; + }]; + + id object2 = [notificationCenter addObserverForName:NSTaskDidTerminateNotification + object:task + queue:[NSOperationQueue mainQueue] + usingBlock:^(NSNotification __unused *note) { + taskResult = [task terminationStatus]; + }]; + + notificationObjects = [NSArray arrayWithObjects:object1, object2, nil]; + } + + [[outputPipe fileHandleForReading] readToEndOfFileInBackgroundAndNotifyForModes:[NSArray arrayWithObject:NSDefaultRunLoopMode]]; + + @try + { + [task launch]; + + if ([inputData length]) + { + [[inputPipe fileHandleForWriting] writeData:inputData]; + [[inputPipe fileHandleForWriting] closeFile]; + } + + if (!shouldReplyImmediatly) + { + // loop until we are done receiving the data + while (YES == isTaskRunning) + { + CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.5, true); + } + } + } + @catch (...) + { + taskResult = SUXPCServiceError; + } + + // send response to indicate ok + xpc_object_t reply = xpc_dictionary_create_reply(message); + xpc_dictionary_set_int64(reply, SUInstallServiceErrorCodeKey, (int64_t)taskResult); + if (outputData != nil) + { + xpc_dictionary_set_data(reply, SUInstallServiceLaunchTaskOutputDataKey, [outputData bytes], [outputData length]); + } + + for (id object in notificationObjects) + { + [notificationCenter removeObserver:object]; + } + outputData = nil; + + return reply; +} + +static void peer_event_handler(xpc_connection_t peer, xpc_object_t event) +{ + xpc_type_t type = xpc_get_type(event); + if (type == XPC_TYPE_ERROR) + { + if (event == XPC_ERROR_CONNECTION_INVALID) + { + // The client process on the other end of the connection has either + // crashed or cancelled the connection. After receiving this error, + // the connection is in an invalid state, and you do not need to + // call xpc_connection_cancel(). Just tear down any associated state + // here. + } + else if (event == XPC_ERROR_TERMINATION_IMMINENT) + { + // Handle per-connection termination cleanup. + } + } + else if (type == XPC_TYPE_DICTIONARY) + { + // Handle the message. + SUInstallServiceTask task = (SUInstallServiceTask)xpc_dictionary_get_int64(event, SUInstallServiceTaskTypeKey); + + NSLog(@"XPC Installer: should start task with id = %lld", (int64_t)task); + + xpc_object_t reply = NULL; + + @autoreleasepool + { + switch (task) + { + case SUInstallServiceTaskCopyPath: + { + reply = SUSICopyPathContent(event); + break; + } + + case SUInstallServiceTaskAuthCopyPath: + { + reply = SUISCopyPathWithAuthentication(event); + break; + } + + case SUInstallServiceTaskLaunchTask: + { + reply = SUISLaunchTask(event); + break; + } + + default: + { + SULog(@"XPC Install Service: Unknown XPC service task %lld", (int64_t)task); + + reply = xpc_dictionary_create_reply(event); + xpc_dictionary_set_int64(reply, SUInstallServiceErrorCodeKey, (int64_t)SUXPCServiceError); + xpc_dictionary_set_string(reply, SUInstallServiceErrorLocalizedDescriptionKey, "Unknown install cervice task."); + + break; + } + } + } + + if (NULL == reply) + { + reply = xpc_dictionary_create_reply(event); + } + + xpc_connection_send_message(peer, reply); + xpc_release(reply); + } +} + +static void event_handler(xpc_connection_t peer) +{ + // By defaults, new connections will target the default dispatch + // concurrent queue. + xpc_connection_set_event_handler(peer, ^(xpc_object_t event) { + peer_event_handler(peer, event); + }); + + // This will tell the connection to begin listening for events. If you + // have some other initialization that must be done asynchronously, then + // you can defer this call until after that initialization is done. + xpc_connection_resume(peer); +} + +int main(int __unused argc, const char __unused *argv[]) +{ + xpc_main(event_handler); +} diff --git a/Sparkle/Installation XPC Service/install_service.pch b/Sparkle/Installation XPC Service/install_service.pch new file mode 100644 index 00000000..57b6b375 --- /dev/null +++ b/Sparkle/Installation XPC Service/install_service.pch @@ -0,0 +1,14 @@ +// +// install_service.pch +// Sparkle +// +// Created by Dmytro Tretiakov on 4/25/14. +// +// + +#define SPARKLE_BUNDLE [NSBundle mainBundle] +#define SULocalizedString(key,comment) NSLocalizedStringFromTableInBundle(key, @"Sparkle", SPARKLE_BUNDLE, comment) + +#import "SUErrors.h" +#import "SUConstants.h" +#import "SULog.h" diff --git a/Sparkle/SUBasicUpdateDriver.m b/Sparkle/SUBasicUpdateDriver.m index d6f72f53..02f518e7 100644 --- a/Sparkle/SUBasicUpdateDriver.m +++ b/Sparkle/SUBasicUpdateDriver.m @@ -20,6 +20,7 @@ #import "SUBinaryDeltaCommon.h" #import "SUCodeSigningVerifier.h" #import "SUUpdater_Private.h" +#import "SUXPCInstaller.h" @interface SUBasicUpdateDriver () @@ -419,7 +420,16 @@ NSError *error = nil; [[NSFileManager defaultManager] createDirectoryAtPath:[targetPath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:@{} error:&error]; - if ([SUPlainInstaller copyPathWithAuthentication:relaunchPathToCopy overPath:targetPath temporaryName:nil error:&error]) { + BOOL copySuccess = NO; + if (SUShouldUseXPCInstaller()) + { + copySuccess = [SUXPCInstaller copyPathWithAuthentication:relaunchPathToCopy overPath:targetPath temporaryName:nil error:&error]; + } + else + { + copySuccess = [SUPlainInstaller copyPathWithAuthentication:relaunchPathToCopy overPath:targetPath temporaryName:nil error:&error]; + } + if (copySuccess) { self.relaunchPath = targetPath; } else { [self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SURelaunchError userInfo:@{ @@ -448,12 +458,20 @@ pathToRelaunch = [updaterDelegate pathToRelaunchForUpdater:self.updater]; } NSString *relaunchToolPath = [[NSBundle bundleWithPath:self.relaunchPath] executablePath]; - [NSTask launchedTaskWithLaunchPath:relaunchToolPath arguments:@[[self.host bundlePath], - pathToRelaunch, - [NSString stringWithFormat:@"%d", [[NSProcessInfo processInfo] processIdentifier]], - self.tempDir, - relaunch ? @"1" : @"0", - showUI ? @"1" : @"0"]]; + NSArray *arguments = @[[self.host bundlePath], + pathToRelaunch, + [NSString stringWithFormat:@"%d", [[NSProcessInfo processInfo] processIdentifier]], + self.tempDir, + relaunch ? @"1" : @"0", + showUI ? @"1" : @"0"]; + if (SUShouldUseXPCInstaller()) + { + [SUXPCInstaller launchTaskWithPath:relaunchToolPath arguments:arguments environment:nil currentDirectoryPath:nil inputData:nil waitForTaskResult:NO waitUntilDone:NO completionHandler:nil]; + } + else + { + [NSTask launchedTaskWithLaunchPath:relaunchToolPath arguments:arguments]; + } [self terminateApp]; } diff --git a/Sparkle/SUCodeSigningVerifier.h b/Sparkle/SUCodeSigningVerifier.h index eddd1b26..cad9b178 100644 --- a/Sparkle/SUCodeSigningVerifier.h +++ b/Sparkle/SUCodeSigningVerifier.h @@ -16,6 +16,7 @@ + (BOOL)codeSignatureIsValidAtPath:(NSString *)applicationPath error:(NSError **)error; + (BOOL)hostApplicationIsCodeSigned; + (BOOL)applicationAtPathIsCodeSigned:(NSString *)applicationPath; ++ (BOOL)hostApplicationIsSandboxed; @end #endif diff --git a/Sparkle/SUCodeSigningVerifier.m b/Sparkle/SUCodeSigningVerifier.m index 73efc6c1..df55265f 100644 --- a/Sparkle/SUCodeSigningVerifier.m +++ b/Sparkle/SUCodeSigningVerifier.m @@ -164,6 +164,44 @@ static id valueOrNSNull(id value) { return (result == 0); } ++ (BOOL)hostApplicationIsSandboxed +{ + static BOOL sIsAppSandboxed = NO; + + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + __block SecCodeRef hostCode = NULL; + __block SecRequirementRef hostRequirement = NULL; + + void (^Cleanup)(void) = ^ { + if (hostCode) { CFRelease(hostCode); hostCode = NULL; } + if (hostRequirement) { CFRelease(hostRequirement); hostRequirement = NULL; } + }; + + OSStatus status = SecCodeCopySelf(kSecCSDefaultFlags, &hostCode); + if (status != noErr || hostCode == NULL) + { + Cleanup(); + return; + } + + CFStringRef requirementString = CFSTR("entitlement[\"com.apple.security.app-sandbox\"] exists"); + status = SecRequirementCreateWithString(requirementString, kSecCSDefaultFlags, &hostRequirement); + + if (status != noErr || hostRequirement == NULL) + { + Cleanup(); + return; + } + + status = SecCodeCheckValidity(hostCode, kSecCSDefaultFlags, hostRequirement); + sIsAppSandboxed = (noErr == status); + Cleanup(); + }); + + return sIsAppSandboxed; +} + + (BOOL)applicationAtPathIsCodeSigned:(NSString *)applicationPath { OSStatus result; diff --git a/Sparkle/SUConstants.m b/Sparkle/SUConstants.m index 31c80ca3..91079b0f 100644 --- a/Sparkle/SUConstants.m +++ b/Sparkle/SUConstants.m @@ -12,6 +12,7 @@ #import "SUAppcastItem.h" #import "SUVersionComparisonProtocol.h" #import "SUConstants.h" +#import "SUErrors.h" #ifndef DEBUG #define DEBUG 0 diff --git a/Sparkle/SUDiskImageUnarchiver.m b/Sparkle/SUDiskImageUnarchiver.m index a7ee21c6..131482ff 100644 --- a/Sparkle/SUDiskImageUnarchiver.m +++ b/Sparkle/SUDiskImageUnarchiver.m @@ -11,6 +11,7 @@ #import "NTSynchronousTask.h" #import "SULog.h" #include +#import "SUXPCInstaller.h" @implementation SUDiskImageUnarchiver @@ -35,12 +36,6 @@ SULog(@"Extracting %@ as a DMG", self.archivePath); - // get a unique mount point path - NSString *mountPoint = nil; - FSRef tmpRef; - NSFileManager *manager; - NSError *error; - NSArray *contents; // We have to declare these before a goto to prevent an error under ARC. // No, we cannot have them in the dispatch_async calls, as the goto "jump enters // lifetime of block which strongly captures a variable" @@ -50,7 +45,10 @@ dispatch_block_t delegateSuccess = ^{ [self notifyDelegateOfSuccess]; }; - do + + // get a unique mount point path + NSString *mountPoint = nil; + do { // Using NSUUID would make creating UUIDs be done in Cocoa, // and thus managed under ARC. Sadly, the class is in 10.8 and later. @@ -65,23 +63,37 @@ CFRelease(uuid); } } - while (noErr == FSPathMakeRefWithOptions((const UInt8 *)[mountPoint fileSystemRepresentation], kFSPathMakeRefDoNotFollowLeafSymlink, &tmpRef, NULL)); + while ([[NSFileManager defaultManager] fileExistsAtPath:mountPoint]); NSData *promptData = nil; promptData = [NSData dataWithBytes:"yes\n" length:4]; + NSString *hdiutilPath = @"/usr/bin/hdiutil"; NSArray *arguments = @[@"attach", self.archivePath, @"-mountpoint", mountPoint, /*@"-noverify",*/ @"-nobrowse", @"-noautoopen"]; + NSString *currentDirPath = @"/"; - NSData *output = nil; - NSInteger taskResult = -1; + BOOL shouldUseXPC = SUShouldUseXPCInstaller(); + + __block NSData *output = nil; + __block NSInteger taskResult = -1; @try { - NTSynchronousTask *task = [[NTSynchronousTask alloc] init]; + if (shouldUseXPC) + { + [SUXPCInstaller launchTaskWithPath:hdiutilPath arguments:arguments environment:nil currentDirectoryPath:currentDirPath inputData:promptData waitForTaskResult:YES waitUntilDone:YES completionHandler:^(int result, NSData *outputData) { + taskResult = (NSInteger)result; + output = [outputData copy]; + }]; + } + else + { + NTSynchronousTask *task = [[NTSynchronousTask alloc] init]; - [task run:@"/usr/bin/hdiutil" directory:@"/" withArgs:arguments input:promptData]; + [task run:hdiutilPath directory:currentDirPath withArgs:arguments input:promptData]; - taskResult = [task result]; - output = [[task output] copy]; + taskResult = [task result]; + output = [[task output] copy]; + } } @catch (NSException *) { @@ -97,30 +109,45 @@ mountedSuccessfully = YES; // Now that we've mounted it, we need to copy out its contents. - manager = [[NSFileManager alloc] init]; - contents = [manager contentsOfDirectoryAtPath:mountPoint error:&error]; - if (error) - { - SULog(@"Couldn't enumerate contents of archive mounted at %@: %@", mountPoint, error); - goto reportError; + if (shouldUseXPC) + { + NSError *error = nil; + [SUXPCInstaller copyPathContent:mountPoint toDirectory:[self.archivePath stringByDeletingLastPathComponent] error:&error]; + + if (nil != error) + { + SULog(@"Couldn't copy volume content: %ld - %@", error.code, error.localizedDescription); + goto reportError; + } } - - for (NSString *item in contents) - { - NSString *fromPath = [mountPoint stringByAppendingPathComponent:item]; - NSString *toPath = [[self.archivePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:item]; - - // We skip any files in the DMG which are not readable. - if (![manager isReadableFileAtPath:fromPath]) { - continue; + else + { + NSFileManager *manager = [[NSFileManager alloc] init]; + NSError *error = nil; + NSArray *contents = [manager contentsOfDirectoryAtPath:mountPoint error:&error]; + if (error) + { + SULog(@"Couldn't enumerate contents of archive mounted at %@: %@", mountPoint, error); + goto reportError; } - SULog(@"copyItemAtPath:%@ toPath:%@", fromPath, toPath); + for (NSString *item in contents) + { + NSString *fromPath = [mountPoint stringByAppendingPathComponent:item]; + NSString *toPath = [[self.archivePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:item]; - if (![manager copyItemAtPath:fromPath toPath:toPath error:&error]) - { - SULog(@"Couldn't copy item: %@ : %@", error, error.userInfo ? error.userInfo : @""); - goto reportError; + // We skip any files in the DMG which are not readable. + if (![manager isReadableFileAtPath:fromPath]) { + continue; + } + + SULog(@"copyItemAtPath:%@ toPath:%@", fromPath, toPath); + + if (![manager copyItemAtPath:fromPath toPath:toPath error:&error]) + { + SULog(@"Couldn't copy item: %@ : %@", error, error.userInfo ? error.userInfo : @""); + goto reportError; + } } } @@ -132,9 +159,21 @@ finally: if (mountedSuccessfully) - [NSTask launchedTaskWithLaunchPath:@"/usr/bin/hdiutil" arguments:@[@"detach", mountPoint, @"-force"]]; + { + arguments = @[@"detach", mountPoint, @"-force"]; + if (shouldUseXPC) + { + [SUXPCInstaller launchTaskWithPath:hdiutilPath arguments:arguments environment:nil currentDirectoryPath:nil inputData:nil waitForTaskResult:NO waitUntilDone:NO completionHandler:nil]; + } + else + { + [NSTask launchedTaskWithLaunchPath:hdiutilPath arguments:arguments]; + } + } else + { SULog(@"Can't mount DMG %@", self.archivePath); + } } } diff --git a/Sparkle/SUErrors.h b/Sparkle/SUErrors.h index e624bb05..5662ff2e 100644 --- a/Sparkle/SUErrors.h +++ b/Sparkle/SUErrors.h @@ -38,7 +38,9 @@ typedef NS_ENUM(OSStatus, SUError) { SUMissingInstallerToolError = 4003, SURelaunchError = 4004, SUInstallationError = 4005, - SUDowngradeError = 4006 + SUDowngradeError = 4006, + + SUXPCServiceError = 4007 }; #endif