From be1e86174ad75d3525c06d6039237756e78b3fff Mon Sep 17 00:00:00 2001 From: Zorg Date: Mon, 6 Jun 2016 20:31:23 -0400 Subject: [PATCH 1/3] Wait for the appropriate process when authorizing file operations This changes the way we authorize & execute commands, and how we wait for their completion. In order to obtain the correct child to wait (instead of another one terminating intermediately), we use a wrapper tool (fileop) to output its pid onto the communication pipe that we read from the other end. --- Configurations/ConfigCommon.xcconfig | 3 +- Configurations/ConfigFileop.xcconfig | 5 + Sparkle.xcodeproj/project.pbxproj | 152 ++++++++++- Sparkle/Autoupdate/Autoupdate.m | 25 +- Sparkle/SUBasicUpdateDriver.m | 2 +- Sparkle/SUBinaryDeltaCommon.m | 2 +- Sparkle/SUErrors.h | 1 + Sparkle/SUFileManager.h | 42 ++- Sparkle/SUFileManager.m | 281 +++++++++++++------- Sparkle/SUGuidedPackageInstaller.h | 2 +- Sparkle/SUGuidedPackageInstaller.m | 128 +-------- Sparkle/SUInstaller.h | 2 +- Sparkle/SUInstaller.m | 8 +- Sparkle/SUPackageInstaller.m | 2 +- Sparkle/SUPlainInstaller.h | 2 +- Sparkle/SUPlainInstaller.m | 8 +- TestApplication/SUTestApplicationDelegate.m | 2 +- Tests/SUCodeSigningVerifierTest.m | 2 +- Tests/SUFileManagerTest.swift | 21 +- Tests/SUInstallerTest.m | 8 +- Tests/Sparkle Unit Tests-Bridging-Header.h | 2 - fileop/SUFileOperationConstants.h | 16 ++ fileop/SUFileOperationConstants.m | 18 ++ fileop/fileop.m | 151 +++++++++++ 24 files changed, 619 insertions(+), 266 deletions(-) create mode 100644 Configurations/ConfigFileop.xcconfig create mode 100644 fileop/SUFileOperationConstants.h create mode 100644 fileop/SUFileOperationConstants.m create mode 100644 fileop/fileop.m diff --git a/Configurations/ConfigCommon.xcconfig b/Configurations/ConfigCommon.xcconfig index 5c0f08bd..cd1773b9 100644 --- a/Configurations/ConfigCommon.xcconfig +++ b/Configurations/ConfigCommon.xcconfig @@ -2,6 +2,7 @@ SPARKLE_BUNDLE_IDENTIFIER = org.sparkle-project.Sparkle SPARKLE_RELAUNCH_TOOL_NAME = Autoupdate +SPARKLE_FILEOP_TOOL_NAME = fileop SPARKLE_APPEND_VERSION_NUMBER = 1 @@ -31,7 +32,7 @@ MACOSX_DEPLOYMENT_TARGET = 10.7 PRODUCT_NAME = ${TARGET_NAME} PRODUCT_BUNDLE_IDENTIFIER = org.sparkle-project.Sparkle.${PRODUCT_NAME:rfc1034identifier} -GCC_PREPROCESSOR_DEFINITIONS_COMMON = SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME=$(SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME) SPARKLE_AUTOMATED_DOWNGRADES=$(SPARKLE_AUTOMATED_DOWNGRADES) SPARKLE_APPEND_VERSION_NUMBER=$(SPARKLE_APPEND_VERSION_NUMBER) SPARKLE_BUNDLE_IDENTIFIER=\"$(SPARKLE_BUNDLE_IDENTIFIER)\" SPARKLE_RELAUNCH_TOOL_NAME=\"$(SPARKLE_RELAUNCH_TOOL_NAME)\" +GCC_PREPROCESSOR_DEFINITIONS_COMMON = SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME=$(SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME) SPARKLE_AUTOMATED_DOWNGRADES=$(SPARKLE_AUTOMATED_DOWNGRADES) SPARKLE_APPEND_VERSION_NUMBER=$(SPARKLE_APPEND_VERSION_NUMBER) SPARKLE_BUNDLE_IDENTIFIER=\"$(SPARKLE_BUNDLE_IDENTIFIER)\" SPARKLE_RELAUNCH_TOOL_NAME=\"$(SPARKLE_RELAUNCH_TOOL_NAME)\" SPARKLE_FILEOP_TOOL_NAME=\"$(SPARKLE_FILEOP_TOOL_NAME)\" CLANG_ENABLE_OBJC_ARC = YES GCC_ENABLE_PASCAL_STRINGS = NO diff --git a/Configurations/ConfigFileop.xcconfig b/Configurations/ConfigFileop.xcconfig new file mode 100644 index 00000000..33efd218 --- /dev/null +++ b/Configurations/ConfigFileop.xcconfig @@ -0,0 +1,5 @@ +// Fileop tool only + +PRODUCT_NAME = $(SPARKLE_FILEOP_TOOL_NAME) +SKIP_INSTALL = YES +CLANG_ENABLE_MODULES = NO diff --git a/Sparkle.xcodeproj/project.pbxproj b/Sparkle.xcodeproj/project.pbxproj index 846830df..1eb7175c 100644 --- a/Sparkle.xcodeproj/project.pbxproj +++ b/Sparkle.xcodeproj/project.pbxproj @@ -96,7 +96,7 @@ 5D1AF5900FD767AD0065DB48 /* libxml2.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 5D1AF58F0FD767AD0065DB48 /* libxml2.dylib */; }; 5D1AF59A0FD767E50065DB48 /* libz.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 5D1AF5990FD767E50065DB48 /* libz.dylib */; }; 5D1AF82B0FD768180065DB48 /* libz.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 5D1AF5990FD767E50065DB48 /* libz.dylib */; }; - 5F1510A21C96E591006E1629 /* testnamespaces.xml in Resources */ = {isa = PBXBuildFile; fileRef = 5F1510A11C96E591006E1629 /* testnamespaces.xml */; settings = {ASSET_TAGS = (); }; }; + 5F1510A21C96E591006E1629 /* testnamespaces.xml in Resources */ = {isa = PBXBuildFile; fileRef = 5F1510A11C96E591006E1629 /* testnamespaces.xml */; }; 610134730DD250470049ACDF /* SUUpdateDriver.h in Headers */ = {isa = PBXBuildFile; fileRef = 610134710DD250470049ACDF /* SUUpdateDriver.h */; settings = {ATTRIBUTES = (); }; }; 610134740DD250470049ACDF /* SUUpdateDriver.m in Sources */ = {isa = PBXBuildFile; fileRef = 610134720DD250470049ACDF /* SUUpdateDriver.m */; }; 6101347B0DD2541A0049ACDF /* SUProbingUpdateDriver.h in Headers */ = {isa = PBXBuildFile; fileRef = 610134790DD2541A0049ACDF /* SUProbingUpdateDriver.h */; settings = {ATTRIBUTES = (); }; }; @@ -178,6 +178,18 @@ 721CF1AA1AD7647000D9AC09 /* libxar.1.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 5D1AF5890FD7678C0065DB48 /* libxar.1.dylib */; }; 721CF1AB1AD764EB00D9AC09 /* libbz2.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 5D06E8FB0FD68D61005AE3F6 /* libbz2.dylib */; }; 7223E7631AD1AEFF008E3161 /* sais.c in Sources */ = {isa = PBXBuildFile; fileRef = 7223E7611AD1AEFF008E3161 /* sais.c */; }; + 722954B71D04ADAF00ECF9CA /* fileop.m in Sources */ = {isa = PBXBuildFile; fileRef = 722954B61D04ADAF00ECF9CA /* fileop.m */; }; + 722954BC1D04AE1100ECF9CA /* SUFileManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 7275F9C01B5F1F2900B1D19E /* SUFileManager.m */; }; + 722954BD1D04AE3800ECF9CA /* SUConstants.m in Sources */ = {isa = PBXBuildFile; fileRef = 61299A5F09CA6EB100B7442F /* SUConstants.m */; }; + 722954C11D04D9ED00ECF9CA /* fileop in Copy fileop */ = {isa = PBXBuildFile; fileRef = 722954B41D04ADAF00ECF9CA /* fileop */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; }; + 722954C41D04E66F00ECF9CA /* SUFileOperationConstants.h in Headers */ = {isa = PBXBuildFile; fileRef = 722954C21D04E66F00ECF9CA /* SUFileOperationConstants.h */; }; + 722954C51D04E66F00ECF9CA /* SUFileOperationConstants.m in Sources */ = {isa = PBXBuildFile; fileRef = 722954C31D04E66F00ECF9CA /* SUFileOperationConstants.m */; }; + 722954C61D04E66F00ECF9CA /* SUFileOperationConstants.m in Sources */ = {isa = PBXBuildFile; fileRef = 722954C31D04E66F00ECF9CA /* SUFileOperationConstants.m */; }; + 722954C71D04E66F00ECF9CA /* SUFileOperationConstants.m in Sources */ = {isa = PBXBuildFile; fileRef = 722954C31D04E66F00ECF9CA /* SUFileOperationConstants.m */; }; + 722954C91D04EA5C00ECF9CA /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 0867D69BFE84028FC02AAC07 /* Foundation.framework */; }; + 722954CA1D04EA6000ECF9CA /* AppKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 0867D6A5FE840307C02AAC07 /* AppKit.framework */; }; + 722954CB1D04EA6900ECF9CA /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 61B5F8F609C4CEB300B25A18 /* Security.framework */; }; + 722954CC1D04EA7000ECF9CA /* SUOperatingSystem.m in Sources */ = {isa = PBXBuildFile; fileRef = 726F2CE41BC9C33D001971A4 /* SUOperatingSystem.m */; }; 723B252D1CEAB3A600909873 /* bscommon.c in Sources */ = {isa = PBXBuildFile; fileRef = 723B252B1CEAB3A600909873 /* bscommon.c */; }; 723B252E1CEAB3A600909873 /* bscommon.c in Sources */ = {isa = PBXBuildFile; fileRef = 723B252B1CEAB3A600909873 /* bscommon.c */; }; 723B252F1CEAB3A600909873 /* bscommon.c in Sources */ = {isa = PBXBuildFile; fileRef = 723B252B1CEAB3A600909873 /* bscommon.c */; }; @@ -206,6 +218,7 @@ 72E45CFC1B641961005C701A /* sparkletestcast.xml in Resources */ = {isa = PBXBuildFile; fileRef = 72E45CFB1B641961005C701A /* sparkletestcast.xml */; }; 72E45CFE1B641D0D005C701A /* test_app_only_dsa_priv_dont_ever_do_this_for_real.pem in Resources */ = {isa = PBXBuildFile; fileRef = 72E45CFD1B641D0D005C701A /* test_app_only_dsa_priv_dont_ever_do_this_for_real.pem */; }; 72E45DDD1B65C3BD005C701A /* sign_update in Resources */ = {isa = PBXBuildFile; fileRef = 72E45DDC1B65C3BD005C701A /* sign_update */; }; + 72E641801D08D754000404CA /* fileop in Resources */ = {isa = PBXBuildFile; fileRef = 722954B41D04ADAF00ECF9CA /* fileop */; }; 767B61AC1972D488004E0C3C /* SUGuidedPackageInstaller.h in Headers */ = {isa = PBXBuildFile; fileRef = 767B61AA1972D488004E0C3C /* SUGuidedPackageInstaller.h */; }; 767B61AD1972D488004E0C3C /* SUGuidedPackageInstaller.m in Sources */ = {isa = PBXBuildFile; fileRef = 767B61AB1972D488004E0C3C /* SUGuidedPackageInstaller.m */; }; 767B61AE1972D488004E0C3C /* SUGuidedPackageInstaller.m in Sources */ = {isa = PBXBuildFile; fileRef = 767B61AB1972D488004E0C3C /* SUGuidedPackageInstaller.m */; }; @@ -308,6 +321,13 @@ remoteGlobalIDString = 8DC2EF4F0486A6940098B216; remoteInfo = Sparkle; }; + 722954BE1D04D9CB00ECF9CA /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 0867D690FE84028FC02AAC07 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 722954B31D04ADAF00ECF9CA; + remoteInfo = fileop; + }; 726B2B621C645FC900388755 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 0867D690FE84028FC02AAC07 /* Project object */; @@ -350,6 +370,26 @@ name = "Copy Frameworks"; runOnlyForDeploymentPostprocessing = 0; }; + 722954B21D04ADAF00ECF9CA /* CopyFiles */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = /usr/share/man/man1/; + dstSubfolderSpec = 0; + files = ( + ); + runOnlyForDeploymentPostprocessing = 1; + }; + 722954C01D04D9D600ECF9CA /* Copy fileop */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 6; + files = ( + 722954C11D04D9ED00ECF9CA /* fileop in Copy fileop */, + ); + name = "Copy fileop"; + runOnlyForDeploymentPostprocessing = 0; + }; /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ @@ -634,6 +674,11 @@ 7210C7671B9A9A1500EB90AC /* SUUnarchiverTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SUUnarchiverTest.swift; sourceTree = ""; }; 7223E7611AD1AEFF008E3161 /* sais.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = sais.c; sourceTree = ""; }; 7223E7621AD1AEFF008E3161 /* sais.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = sais.h; sourceTree = ""; }; + 722954B41D04ADAF00ECF9CA /* fileop */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = fileop; sourceTree = BUILT_PRODUCTS_DIR; }; + 722954B61D04ADAF00ECF9CA /* fileop.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = fileop.m; sourceTree = ""; }; + 722954C21D04E66F00ECF9CA /* SUFileOperationConstants.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SUFileOperationConstants.h; sourceTree = ""; }; + 722954C31D04E66F00ECF9CA /* SUFileOperationConstants.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SUFileOperationConstants.m; sourceTree = ""; }; + 722954C81D04E89500ECF9CA /* ConfigFileop.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = ConfigFileop.xcconfig; sourceTree = ""; }; 723B252B1CEAB3A600909873 /* bscommon.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = bscommon.c; sourceTree = ""; }; 723B252C1CEAB3A600909873 /* bscommon.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = bscommon.h; sourceTree = ""; }; 7268AC621AD634C200C3E0C1 /* SUBinaryDeltaCreate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SUBinaryDeltaCreate.m; sourceTree = ""; }; @@ -737,6 +782,16 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + 722954B11D04ADAF00ECF9CA /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 722954CB1D04EA6900ECF9CA /* Security.framework in Frameworks */, + 722954CA1D04EA6000ECF9CA /* AppKit.framework in Frameworks */, + 722954C91D04EA5C00ECF9CA /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; 726B2B5A1C645FC900388755 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; @@ -772,6 +827,7 @@ 612279D90DB5470200AB99EA /* Sparkle Unit Tests.xctest */, 8DC2EF5B0486A6940098B216 /* Sparkle.framework */, 726B2B5D1C645FC900388755 /* UI Tests.xctest */, + 722954B41D04ADAF00ECF9CA /* fileop */, ); name = Products; sourceTree = ""; @@ -930,6 +986,7 @@ 55C14BD5136EEFD000649790 /* Autoupdate */ = { isa = PBXGroup; children = ( + 722954B51D04ADAF00ECF9CA /* fileop */, 55C14BB9136EEF1500649790 /* Autoupdate-Info.plist */, 55C14BD3136EEFCE00649790 /* Autoupdate.m */, ); @@ -1124,6 +1181,17 @@ name = "Update Control"; sourceTree = ""; }; + 722954B51D04ADAF00ECF9CA /* fileop */ = { + isa = PBXGroup; + children = ( + 722954B61D04ADAF00ECF9CA /* fileop.m */, + 722954C21D04E66F00ECF9CA /* SUFileOperationConstants.h */, + 722954C31D04E66F00ECF9CA /* SUFileOperationConstants.m */, + ); + name = fileop; + path = ../../fileop; + sourceTree = ""; + }; 726B2B5E1C645FC900388755 /* UI Tests */ = { isa = PBXGroup; children = ( @@ -1150,6 +1218,7 @@ FA1941CE0D94A70100DD942E /* ConfigRelaunch.xcconfig */, FA1941D30D94A70100DD942E /* ConfigRelaunchDebug.xcconfig */, FA1941D40D94A70100DD942E /* ConfigRelaunchRelease.xcconfig */, + 722954C81D04E89500ECF9CA /* ConfigFileop.xcconfig */, FA1941CD0D94A70100DD942E /* ConfigTestApp.xcconfig */, FA1941CB0D94A70100DD942E /* ConfigTestAppDebug.xcconfig */, FA1941D20D94A70100DD942E /* ConfigTestAppRelease.xcconfig */, @@ -1217,6 +1286,7 @@ 61A354550DF113C70076ECB1 /* SUUserInitiatedUpdateDriver.h in Headers */, 61A2259E0D1C495D00430CCD /* SUVersionComparisonProtocol.h in Headers */, 3772FEA913DE0B6B00F79537 /* SUVersionDisplayProtocol.h in Headers */, + 722954C41D04E66F00ECF9CA /* SUFileOperationConstants.h in Headers */, 61180BCA0D64138900B4E0D1 /* SUWindowController.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; @@ -1267,10 +1337,12 @@ 55C14BB4136EEF1500649790 /* Sources */, 55C14BB5136EEF1500649790 /* Frameworks */, 14652F7B19A945D600959E44 /* Run Script: Set Git Version Info */, + 722954C01D04D9D600ECF9CA /* Copy fileop */, ); buildRules = ( ); dependencies = ( + 722954BF1D04D9CB00ECF9CA /* PBXTargetDependency */, ); name = Autoupdate; productName = Autoupdate; @@ -1332,6 +1404,23 @@ productReference = 61B5F90209C4CEE200B25A18 /* Sparkle Test App.app */; productType = "com.apple.product-type.application"; }; + 722954B31D04ADAF00ECF9CA /* fileop */ = { + isa = PBXNativeTarget; + buildConfigurationList = 722954BB1D04ADAF00ECF9CA /* Build configuration list for PBXNativeTarget "fileop" */; + buildPhases = ( + 722954B01D04ADAF00ECF9CA /* Sources */, + 722954B11D04ADAF00ECF9CA /* Frameworks */, + 722954B21D04ADAF00ECF9CA /* CopyFiles */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = fileop; + productName = fileop; + productReference = 722954B41D04ADAF00ECF9CA /* fileop */; + productType = "com.apple.product-type.tool"; + }; 726B2B5C1C645FC900388755 /* UI Tests */ = { isa = PBXNativeTarget; buildConfigurationList = 726B2B671C645FC900388755 /* Build configuration list for PBXNativeTarget "UI Tests" */; @@ -1388,6 +1477,9 @@ 612279D80DB5470200AB99EA = { TestTargetID = 8DC2EF4F0486A6940098B216; }; + 722954B31D04ADAF00ECF9CA = { + CreatedOnToolsVersion = 7.3.1; + }; 726B2B5C1C645FC900388755 = { CreatedOnToolsVersion = 7.2.1; TestTargetID = 61B5F90109C4CEE200B25A18; @@ -1460,6 +1552,7 @@ 1420DF491962329200203BB0 /* Documentation */, 1495005F195FB89400BC5B5B /* All */, 726B2B5C1C645FC900388755 /* UI Tests */, + 722954B31D04ADAF00ECF9CA /* fileop */, ); }; /* End PBXProject section */ @@ -1469,6 +1562,7 @@ isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( + 72E641801D08D754000404CA /* fileop in Resources */, 14958C6E19AEBC950061B14F /* signed-test-file.txt in Resources */, 5F1510A21C96E591006E1629 /* testnamespaces.xml in Resources */, 72AC6B2E1B9B218C00F62325 /* SparkleTestCodeSignApp.dmg in Resources */, @@ -1615,6 +1709,7 @@ 726F2CE71BC9C3E2001971A4 /* SUOperatingSystem.m in Sources */, 55C14F24136EF86F00649790 /* SUPackageInstaller.m in Sources */, 55C14F21136EF84D00649790 /* SUPlainInstaller.m in Sources */, + 722954C61D04E66F00ECF9CA /* SUFileOperationConstants.m in Sources */, 55C14F22136EF86000649790 /* SUStandardVersionComparator.m in Sources */, 55C14F20136EF84300649790 /* SUStatusController.m in Sources */, 55C14F23136EF86700649790 /* SUSystemProfiler.m in Sources */, @@ -1676,6 +1771,18 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + 722954B01D04ADAF00ECF9CA /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 722954CC1D04EA7000ECF9CA /* SUOperatingSystem.m in Sources */, + 722954BD1D04AE3800ECF9CA /* SUConstants.m in Sources */, + 722954BC1D04AE1100ECF9CA /* SUFileManager.m in Sources */, + 722954B71D04ADAF00ECF9CA /* fileop.m in Sources */, + 722954C71D04E66F00ECF9CA /* SUFileOperationConstants.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; 726B2B591C645FC900388755 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; @@ -1689,6 +1796,7 @@ buildActionMask = 2147483647; files = ( 5D06E8EB0FD68CE4005AE3F6 /* bspatch.c in Sources */, + 722954C51D04E66F00ECF9CA /* SUFileOperationConstants.m in Sources */, 610EC1E00CF3A5FE00AE239E /* NTSynchronousTask.m in Sources */, 61B5FBB709C4FAFF00B25A18 /* SUAppcast.m in Sources */, 61B5FC6F09C51F4900B25A18 /* SUAppcastItem.m in Sources */, @@ -1796,6 +1904,11 @@ target = 8DC2EF4F0486A6940098B216 /* Sparkle */; targetProxy = 61FA528C0E2D9EB200EF58AD /* PBXContainerItemProxy */; }; + 722954BF1D04D9CB00ECF9CA /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 722954B31D04ADAF00ECF9CA /* fileop */; + targetProxy = 722954BE1D04D9CB00ECF9CA /* PBXContainerItemProxy */; + }; 726B2B631C645FC900388755 /* PBXTargetDependency */ = { isa = PBXTargetDependency; target = 61B5F90109C4CEE200B25A18 /* Sparkle Test App */; @@ -2176,6 +2289,33 @@ }; name = Release; }; + 722954B81D04ADAF00ECF9CA /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 722954C81D04E89500ECF9CA /* ConfigFileop.xcconfig */; + buildSettings = { + GCC_WARN_UNUSED_VARIABLE = YES; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Debug; + }; + 722954B91D04ADAF00ECF9CA /* Coverage */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 722954C81D04E89500ECF9CA /* ConfigFileop.xcconfig */; + buildSettings = { + GCC_WARN_UNUSED_VARIABLE = YES; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Coverage; + }; + 722954BA1D04ADAF00ECF9CA /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 722954C81D04E89500ECF9CA /* ConfigFileop.xcconfig */; + buildSettings = { + GCC_WARN_UNUSED_VARIABLE = YES; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Release; + }; 726B2B641C645FC900388755 /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = 729F10FF1C65A9B500DFCCC5 /* ConfigUITestDebug.xcconfig */; @@ -2298,6 +2438,16 @@ defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; + 722954BB1D04ADAF00ECF9CA /* Build configuration list for PBXNativeTarget "fileop" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 722954B81D04ADAF00ECF9CA /* Debug */, + 722954B91D04ADAF00ECF9CA /* Coverage */, + 722954BA1D04ADAF00ECF9CA /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; 726B2B671C645FC900388755 /* Build configuration list for PBXNativeTarget "UI Tests" */ = { isa = XCConfigurationList; buildConfigurations = ( diff --git a/Sparkle/Autoupdate/Autoupdate.m b/Sparkle/Autoupdate/Autoupdate.m index 51b9619a..51d145f9 100644 --- a/Sparkle/Autoupdate/Autoupdate.m +++ b/Sparkle/Autoupdate/Autoupdate.m @@ -166,18 +166,31 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.5; [self.statusController showWindow:self]; } + NSString *fileOperationToolPath = [[[[NSBundle mainBundle] executablePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@""SPARKLE_FILEOP_TOOL_NAME]; + + if (![[NSFileManager defaultManager] fileExistsAtPath:fileOperationToolPath]) { + SULog(@"Potential Installation Error: File operation tool path %@ is not found", fileOperationToolPath); + } + [SUInstaller installFromUpdateFolder:self.updateFolderPath overHost:host installationPath:installationPath + fileOperationToolPath:fileOperationToolPath versionComparator:[SUStandardVersionComparator defaultComparator] completionHandler:^(NSError *error) { if (error) { - SULog(@"Installation Error: %@", error); - if (self.shouldShowUI) { - NSAlert *alert = [[NSAlert alloc] init]; - alert.messageText = @""; - alert.informativeText = [NSString stringWithFormat:@"%@", [error localizedDescription]]; - [alert runModal]; + NSError *underlyingError = [error.userInfo objectForKey:NSUnderlyingErrorKey]; + if (underlyingError == nil || underlyingError.code != SUInstallationCancelledError) { + SULog(@"Installation Error: %@", error); + if (underlyingError != nil) { + SULog(@"Installation Underlying Error: %@", underlyingError); + } + if (self.shouldShowUI) { + NSAlert *alert = [[NSAlert alloc] init]; + alert.messageText = @""; + alert.informativeText = [NSString stringWithFormat:@"%@", [error localizedDescription]]; + [alert runModal]; + } } exit(EXIT_FAILURE); } else { diff --git a/Sparkle/SUBasicUpdateDriver.m b/Sparkle/SUBasicUpdateDriver.m index e40b3893..32567d11 100644 --- a/Sparkle/SUBasicUpdateDriver.m +++ b/Sparkle/SUBasicUpdateDriver.m @@ -511,7 +511,7 @@ if (relaunchPathToCopy != nil) { NSString *targetPath = [[self appCachePath] stringByAppendingPathComponent:[relaunchPathToCopy lastPathComponent]]; - SUFileManager *fileManager = [SUFileManager fileManagerAllowingAuthorization:NO]; + SUFileManager *fileManager = [SUFileManager defaultManager]; NSError *error = nil; NSURL *relaunchURLToCopy = [NSURL fileURLWithPath:relaunchPathToCopy]; diff --git a/Sparkle/SUBinaryDeltaCommon.m b/Sparkle/SUBinaryDeltaCommon.m index de247ee5..5f6ce079 100644 --- a/Sparkle/SUBinaryDeltaCommon.m +++ b/Sparkle/SUBinaryDeltaCommon.m @@ -221,7 +221,7 @@ BOOL removeTree(NSString *path) BOOL copyTree(NSString *source, NSString *dest) { - return [[SUFileManager fileManagerAllowingAuthorization:NO] copyItemAtURL:[NSURL fileURLWithPath:source] toURL:[NSURL fileURLWithPath:dest] error:NULL]; + return [[SUFileManager defaultManager] copyItemAtURL:[NSURL fileURLWithPath:source] toURL:[NSURL fileURLWithPath:dest] error:NULL]; } BOOL modifyPermissions(NSString *path, mode_t desiredPermissions) diff --git a/Sparkle/SUErrors.h b/Sparkle/SUErrors.h index 54b0e8ff..93da51a7 100644 --- a/Sparkle/SUErrors.h +++ b/Sparkle/SUErrors.h @@ -40,6 +40,7 @@ typedef NS_ENUM(OSStatus, SUError) { SURelaunchError = 4004, SUInstallationError = 4005, SUDowngradeError = 4006, + SUInstallationCancelledError = 4007, // System phase errors SUSystemPowerOffError = 5000 diff --git a/Sparkle/SUFileManager.h b/Sparkle/SUFileManager.h index c3d2acd7..e914cdc3 100644 --- a/Sparkle/SUFileManager.h +++ b/Sparkle/SUFileManager.h @@ -9,21 +9,27 @@ #import /** - * A class used for performing file operations that may also perform authentication if allowed and if permission is denied when trying to + * A class used for performing file operations that may also perform authorization if allowed and if permission is denied when trying to * perform them normally as the running user. All operations on this class may be used on thread other than the main thread. * This class provides basic file operations and stays away from including much application-level logic. */ @interface SUFileManager : NSObject /** - * Creates a file manager that allows or disallows authorizing for file operations - * @param allowsAuthorization Specifies whether operations invoked on this instance are allowed to acquire authorization in order - * to perform file operations when read or write access is denied +* Creates a file manager that will not authorize for file operations +* @return A new file manager instance +*/ ++ (instancetype)defaultManager; + +/** + * Creates a file manager that allows authorizing for file operations + * @param authorizationToolPath Specifies the path to the tool that can perform file operations and be run as root. + * This tool will be invoked when read or write access is denied when attempting ordinary file operations. See the `fileop` tool included in Sparkle. * @return A new file manager instance - * - * This method just creates the file manager. It doesn't acquire authorization immediately if allowsAuthorization is YES + * + * This method just creates the file manager. It doesn't acquire authorization immediately or if it doesn't need to. */ -+ (instancetype)fileManagerAllowingAuthorization:(BOOL)allowsAuthorization; ++ (instancetype)fileManagerWithAuthorizationToolPath:(NSString *)authorizationToolPath; /** * Returns a file manager that allows or disallows authorizing for file operations based on the current file manager @@ -46,6 +52,16 @@ */ - (NSURL *)makeTemporaryDirectoryWithPreferredName:(NSString *)preferredName appropriateForDirectoryURL:(NSURL *)appropriateURL error:(NSError **)error; +/** + * Creates a directory at the target URL + * @param targetURL A URL pointing to the directory to create. The item at this URL must not exist, and the parent directory of this URL must already exist. + * @param error If an error occurs, upon returns contains an NSError object that describes the problem. If you are not interested in possible errors, you may pass in NULL. + * @return YES if the item was created successfully, otherwise NO along with a populated error object + * + * This is an atomic operation. + */ +- (BOOL)makeDirectoryAtURL:(NSURL *)targetURL error:(NSError **)error; + /** * Moves an item from a source to a destination * @param sourceURL A URL pointing to the item to move. The item at this URL must exist. @@ -140,4 +156,16 @@ */ - (BOOL)releaseItemFromQuarantineAtRootURL:(NSURL *)rootURL error:(NSError **)error; +/** + * Runs an installer package (pkg) in a headless mode using /usr/sbin/installer + * @param packageURL A URL pointing to the package to execute. The item at this URL must exist. + * @param error If an error occurs, upon returns contains an NSError object that describes the problem. If you are not interested in possible errors, you may pass in NULL. + * @return YES if the installer ran the package successfully, otherwise NO with a populated error object + * + * This method uses the system wide installer tool to run the provided package. This process does not show any UI, except for + * an initial authorization prompt if the calling process does not have root privileges. In other words, root privileges are required to use this method, and the file manager instance must have been created by allowing authorization. + * An error can occur if the package is unable to be ran by the installer, or if the installer reports a non-zero exit status code. + */ +- (BOOL)executePackageAtURL:(NSURL *)packageURL error:(NSError **)error; + @end diff --git a/Sparkle/SUFileManager.m b/Sparkle/SUFileManager.m index 4e85fcae..45080920 100644 --- a/Sparkle/SUFileManager.m +++ b/Sparkle/SUFileManager.m @@ -8,6 +8,7 @@ #import "SUFileManager.h" #import "SUOperatingSystem.h" +#import "SUFileOperationConstants.h" #include #include @@ -15,30 +16,6 @@ static char SUAppleQuarantineIdentifier[] = "com.apple.quarantine"; -// Authorization code based on generous contribution from Allan Odgaard. Thanks, Allan! -static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authorization, const char *executablePath, AuthorizationFlags options, char *const *arguments) -{ - sig_t oldSigChildHandler = signal(SIGCHLD, SIG_DFL); - BOOL returnValue = YES; - -#pragma clang diagnostic push - // In the future, we may have to look at SMJobBless API to avoid deprecation. See issue #558 -#pragma clang diagnostic ignored "-Wdeprecated-declarations" - if (AuthorizationExecuteWithPrivileges(authorization, executablePath, options, arguments, NULL) == errAuthorizationSuccess) -#pragma clang diagnostic pop - { - int status; - pid_t pid = wait(&status); - if (pid == -1 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) - returnValue = NO; - } - else - returnValue = NO; - - signal(SIGCHLD, oldSigChildHandler); - return returnValue; -} - static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { char path[PATH_MAX] = {0}; @@ -75,32 +52,37 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { { AuthorizationRef _auth; NSFileManager *_fileManager; - BOOL _allowsAuthorization; + NSString *_authorizationToolPath; } -- (instancetype)initAllowingAuthorization:(BOOL)allowsAuthorization +- (instancetype)initWithAuthorizationToolPath:(NSString *)authorizationToolPath { self = [super init]; if (self != nil) { _fileManager = [[NSFileManager alloc] init]; - _allowsAuthorization = allowsAuthorization; + _authorizationToolPath = [authorizationToolPath copy]; } return self; } -+ (instancetype)fileManagerAllowingAuthorization:(BOOL)allowsAuthorization ++ (instancetype)defaultManager { - return [[self alloc] initAllowingAuthorization:allowsAuthorization]; + return [[self alloc] initWithAuthorizationToolPath:nil]; +} + ++ (instancetype)fileManagerWithAuthorizationToolPath:(NSString *)authorizationToolPath +{ + return [[self alloc] initWithAuthorizationToolPath:authorizationToolPath]; } - (instancetype)fileManagerByPreservingAuthorizationRights { // Check if we don't allow authorization, or that we haven't needed to authorize yet, to create or re-use a // file manager instance with these restrictions - return (_allowsAuthorization && _auth != NULL) ? self : [SUFileManager fileManagerAllowingAuthorization:NO]; + return (_authorizationToolPath != nil && _auth != NULL) ? self : [SUFileManager defaultManager]; } -// Acquires an authorization reference which is intended to be used for future authorized file operations +// Acquires an authorization reference with root privileges which is intended to be used for authorized file operations - (BOOL)_acquireAuthorizationWithError:(NSError *__autoreleasing *)error { // No need to continue if we already acquired an authorization reference @@ -108,21 +90,112 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { return YES; } - if (!_allowsAuthorization) { + if (_authorizationToolPath == nil) { if (error != NULL) { *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: @"Unable to grant authorization to perform action because it is explicitly turned off" }]; } return NO; } - OSStatus status = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, kAuthorizationFlagDefaults, &_auth); - if (status != errAuthorizationSuccess) { + OSStatus createStatus = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, kAuthorizationFlagDefaults, &_auth); + if (createStatus != errAuthorizationSuccess) { if (error != NULL) { - *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed creating authorization reference with status code %d.", status] }]; + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed creating authorization reference with status code %d.", createStatus] }]; } _auth = NULL; return NO; } + + AuthorizationItem rightItems[] = { + // The right that allows us to run tools as root user + {.name = kAuthorizationRightExecute, .valueLength = 0, .value = NULL, .flags = 0} + }; + + AuthorizationRights rights = { + .count = sizeof(rightItems) / sizeof(*rightItems), + .items = rightItems + }; + + AuthorizationFlags flags = + (AuthorizationFlags)(kAuthorizationFlagDefaults | kAuthorizationFlagInteractionAllowed | kAuthorizationFlagExtendRights | kAuthorizationFlagPreAuthorize); + + // This will test if we can gain authorization for running utlities as root + OSStatus copyStatus = AuthorizationCopyRights(_auth, &rights, kAuthorizationEmptyEnvironment, flags, NULL); + if (copyStatus != errAuthorizationSuccess) { + if (error != NULL) { + if (copyStatus == errAuthorizationCanceled) { + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationCancelledError userInfo:@{ NSLocalizedDescriptionKey: @"Authorization access was cancelled by the user." }]; + } else { + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed granting authorization rights with status code %d.", copyStatus] }]; + } + } + + AuthorizationFree(_auth, kAuthorizationFlagDefaults); + _auth = NULL; + + return NO; + } + + return YES; +} + +- (BOOL)_authorizeAndExecuteCommand:(char *)command sourcePath:(char *)sourcePath destinationPath:(char *)destinationPath error:(NSError * __autoreleasing *)error +{ + NSError *acquireError = nil; + if (![self _acquireAuthorizationWithError:&acquireError]) { + if (error != NULL) { + *error = acquireError; + } + return NO; + } + + char *arguments[] = { command, sourcePath, destinationPath, NULL }; + + char toolPath[PATH_MAX] = {0}; + if (![_authorizationToolPath getFileSystemRepresentation:toolPath maxLength:sizeof(toolPath)]) { + if (error != NULL) { + *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Authorization tool (%@) cannot be represented as a valid file name.", _authorizationToolPath.lastPathComponent] }]; + } + return NO; + } + + FILE *pipe = NULL; +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + if (AuthorizationExecuteWithPrivileges(_auth, toolPath, kAuthorizationFlagDefaults, arguments, &pipe) != errAuthorizationSuccess) { +#pragma clang diagnostic pop + if (error != NULL) { + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey:@"Failed to run authorization tool." }]; + } + return NO; + } + + uint32_t pidData = 0; + if (fread(&pidData, sizeof(pidData), 1, pipe) < 1) { + if (error != NULL) { + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey:@"Failed to retrieve authorized executable process identifier." }]; + } + fclose(pipe); + return NO; + } + + pid_t childPid = (int32_t)CFSwapInt32LittleToHost(pidData); + int status = 0; + + pid_t waitResult; + do { + waitResult = waitpid(childPid, &status, 0); + } while (waitResult == -1 && errno == EINTR); + + fclose(pipe); + + if (waitResult == -1 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) { + if (error != NULL) { + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Failed to execute authorized executable with result %d and status (%d, %d, %d).", waitResult, status, WIFEXITED(status), WEXITSTATUS(status)] }]; + } + return NO; + } + return YES; } @@ -189,7 +262,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { #define XATTR_UTILITY_PATH "/usr/bin/xattr" // Recursively remove an xattr at a specified root URL with authentication -- (BOOL)_removeXAttrWithAuthentication:(char *__nonnull)xattrName fromRootURL:(NSURL *)rootURL error:(NSError *__autoreleasing *)error +- (BOOL)_removeQuarantineWithAuthenticationAtRootURL:(NSURL *)rootURL error:(NSError *__autoreleasing *)error { // Because this is a system utility, it's fine to follow the symbolic link if one exists if (![_fileManager fileExistsAtPath:@(XATTR_UTILITY_PATH)]) { @@ -206,16 +279,11 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { } return NO; } - - if (![self _acquireAuthorizationWithError:error]) { - return NO; - } - - BOOL success = AuthorizationExecuteWithPrivilegesAndWait(_auth, XATTR_UTILITY_PATH, kAuthorizationFlagDefaults, (char *[]){ "-s", "-r", "-d", xattrName, path, NULL }); - + + NSError *executeError = nil; + BOOL success = [self _authorizeAndExecuteCommand:SUFileOpRemoveQuarantineCommand sourcePath:path destinationPath:NULL error:&executeError]; if (!success && error != NULL) { - NSString *errorMessage = [NSString stringWithFormat:@"Authenticated extended attribute deletion for %@ failed on %@.", [NSString stringWithUTF8String:xattrName], rootURL.path.lastPathComponent]; - *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey:errorMessage }]; + *error = executeError; } return success; @@ -240,7 +308,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { removedQuarantine = YES; } else { if (isAccessError(removalError)) { - removedQuarantine = [self _removeXAttrWithAuthentication:SUAppleQuarantineIdentifier fromRootURL:rootURL error:error]; + removedQuarantine = [self _removeQuarantineWithAuthenticationAtRootURL:rootURL error:error]; attemptedAuthentication = YES; } else { if (success != NULL) { @@ -394,11 +462,6 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { return NO; } - if (![self _acquireAuthorizationWithError:error]) { - return NO; - } - - char sourcePath[PATH_MAX] = {0}; if (![sourceURL.path getFileSystemRepresentation:sourcePath maxLength:sizeof(sourcePath)]) { if (error != NULL) { @@ -414,11 +477,11 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { } return NO; } - - if (!AuthorizationExecuteWithPrivilegesAndWait(_auth, "/bin/cp", kAuthorizationFlagDefaults, (char *[]){ "-Rf", "--", sourcePath, destinationPath, NULL })) { + + NSError *executeError = nil; + if (![self _authorizeAndExecuteCommand:SUFileOpCopyCommand sourcePath:sourcePath destinationPath:destinationPath error:&executeError]) { if (error != NULL) { - NSString *errorMessage = [NSString stringWithFormat:@"Failed to perform authenticated file copy for %@.", sourceURL.lastPathComponent]; - *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey:errorMessage }]; + *error = executeError; } return NO; } @@ -507,10 +570,6 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { return NO; } - if (![self _acquireAuthorizationWithError:error]) { - return NO; - } - char sourcePath[PATH_MAX] = {0}; if (![sourceURL.path getFileSystemRepresentation:sourcePath maxLength:sizeof(sourcePath)]) { if (error != NULL) { @@ -526,11 +585,12 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { } return NO; } - - if (!AuthorizationExecuteWithPrivilegesAndWait(_auth, "/bin/mv", kAuthorizationFlagDefaults, (char *[]){ "-f", "--", sourcePath, destinationPath, NULL })) { + + NSError *executeError = nil; + if (![self _authorizeAndExecuteCommand:SUFileOpMoveCommand sourcePath:sourcePath destinationPath:destinationPath error:&executeError]) { if (error != NULL) { - NSString *errorMessage = [NSString stringWithFormat:@"Failed to perform authenticated file move for %@.", sourceURL.lastPathComponent]; - *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey:errorMessage }]; + NSString *errorMessage = [NSString stringWithFormat:@"Failed to perform authorized file move for %@.", sourceURL.lastPathComponent]; + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey:errorMessage, NSUnderlyingErrorKey: executeError }]; } return NO; } @@ -670,21 +730,20 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { } return NO; } - - char userAndGroup[100]; - int written = snprintf(userAndGroup, sizeof(userAndGroup), "%u:%u", ownerID.unsignedIntValue, groupID.unsignedIntValue); - if (written < 0 || written >= 100) { - return NO; // No custom error, because it's too unlikely to ever happen - } - - if (![self _acquireAuthorizationWithError:error]) { + + char matchPath[PATH_MAX] = {0}; + if (![matchURLPath getFileSystemRepresentation:matchPath maxLength:sizeof(matchPath)]) { + if (error != NULL) { + *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Match file (%@) cannot be represented as a valid file name.", matchURL.path.lastPathComponent] }]; + } return NO; } - BOOL success = AuthorizationExecuteWithPrivilegesAndWait(_auth, "/usr/sbin/chown", kAuthorizationFlagDefaults, (char *[]){ "-R", userAndGroup, targetPath, NULL }); + NSError *executeError = nil; + BOOL success = [self _authorizeAndExecuteCommand:SUFileOpChangeOwnerAndGroupCommand sourcePath:targetPath destinationPath:matchPath error:&executeError]; if (!success && error != NULL) { - NSString *errorMessage = [NSString stringWithFormat:@"Failed to change owner:group %@ on %@ with authentication.", [NSString stringWithUTF8String:userAndGroup], targetURL.path.lastPathComponent]; - *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: errorMessage }]; + NSString *errorMessage = [NSString stringWithFormat:@"Failed to change owner & group on %@ to match %@ with authorization.", targetURL.path.lastPathComponent, matchURLPath.lastPathComponent]; + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: errorMessage, NSUnderlyingErrorKey: executeError }]; } return success; @@ -736,15 +795,12 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { } return NO; } - - if (![self _acquireAuthorizationWithError:error]) { - return NO; - } - - BOOL success = AuthorizationExecuteWithPrivilegesAndWait(_auth, "/usr/bin/touch", kAuthorizationFlagDefaults, (char *[]){ "-h", "--", path, NULL }); + + NSError *executeError = nil; + BOOL success = [self _authorizeAndExecuteCommand:SUFileOpUpdateModificationAndAccessTimeCommand sourcePath:path destinationPath:NULL error:&executeError]; if (!success && error != NULL) { - NSString *errorMessage = [NSString stringWithFormat:@"Failed to update modification & access time on %@ with authentication.", targetURL.path.lastPathComponent]; - *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: errorMessage }]; + NSString *errorMessage = [NSString stringWithFormat:@"Failed to update modification & access time on %@ with authorization.", targetURL.path.lastPathComponent]; + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: errorMessage, NSUnderlyingErrorKey: executeError }]; } return success; @@ -752,7 +808,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { // Creates a directory at the item pointed by url // An item cannot already exist at the url, but the parent must be a directory that exists -- (BOOL)_makeDirectoryAtURL:(NSURL *)url error:(NSError * __autoreleasing *)error +- (BOOL)makeDirectoryAtURL:(NSURL *)url error:(NSError * __autoreleasing *)error { if ([self _itemExistsAtURL:url]) { if (error != NULL) { @@ -789,16 +845,16 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { } return NO; } - - if (![self _acquireAuthorizationWithError:error]) { - return NO; - } - - BOOL success = AuthorizationExecuteWithPrivilegesAndWait(_auth, "/bin/mkdir", kAuthorizationFlagDefaults, (char *[]){ "--", path, NULL }); - if (!success && error != NULL) { - NSString *errorMessage = [NSString stringWithFormat:@"Failed to make directory %@ with authentication.", url.path.lastPathComponent]; - *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: errorMessage }]; + + NSError *executeError = nil; + BOOL success = [self _authorizeAndExecuteCommand:SUFileOpMakeDirectoryCommand sourcePath:path destinationPath:NULL error:&executeError]; + if (!success) { + if (error != NULL) { + NSString *errorMessage = [NSString stringWithFormat:@"Failed to make directory %@ with authorization.", url.path.lastPathComponent]; + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: errorMessage, NSUnderlyingErrorKey: executeError }]; + } } + return success; } @@ -820,7 +876,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { desiredURL = [directoryURL URLByAppendingPathComponent:[preferredName stringByAppendingFormat:@" (%lu)", (unsigned long)++tagIndex]]; } - return [self _makeDirectoryAtURL:desiredURL error:error] ? desiredURL : nil; + return [self makeDirectoryAtURL:desiredURL error:error] ? desiredURL : nil; } - (BOOL)removeItemAtURL:(NSURL *)url error:(NSError * __autoreleasing *)error @@ -844,10 +900,6 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { return NO; } - if (![self _acquireAuthorizationWithError:error]) { - return NO; - } - char path[PATH_MAX] = {0}; if (![url.path getFileSystemRepresentation:path maxLength:sizeof(path)]) { if (error != NULL) { @@ -855,11 +907,14 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { } return NO; } + + NSError *executeError = nil; + BOOL success = [self _authorizeAndExecuteCommand:SUFileOpRemoveCommand sourcePath:path destinationPath:NULL error:&executeError]; - BOOL success = AuthorizationExecuteWithPrivilegesAndWait(_auth, "/bin/rm", kAuthorizationFlagDefaults, (char *[]){ "-rf", "--", path, NULL }); if (!success && error != NULL) { - *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to remove %@ with authentication.", url.path.lastPathComponent] }]; + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to remove %@ with authentication.", url.path.lastPathComponent], NSUnderlyingErrorKey: executeError }]; } + return success; } @@ -948,6 +1003,34 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { return success; } +// Unlike other methods, authorization is required to execute this method successfully +- (BOOL)executePackageAtURL:(NSURL *)packageURL error:(NSError * __autoreleasing *)error +{ + if (![self _itemExistsAtURL:packageURL]) { + if (error != NULL) { + *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileNoSuchFileError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to execute package %@ because the file does not exist.", packageURL.path.lastPathComponent] }]; + } + return NO; + } + + char path[PATH_MAX] = {0}; + if (![packageURL.path getFileSystemRepresentation:path maxLength:sizeof(path)]) { + if (error != NULL) { + *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Package to execute (%@) cannot be represented as a valid file name.", packageURL.path.lastPathComponent] }]; + } + return NO; + } + + NSError *executeError = nil; + BOOL success = [self _authorizeAndExecuteCommand:SUFileOpInstallCommand sourcePath:path destinationPath:NULL error:&executeError]; + + if (!success && error != NULL) { + NSString* errorMessage = @"Failed to execute package installer."; + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{NSLocalizedDescriptionKey: errorMessage, NSUnderlyingErrorKey: executeError}]; + } + return success; +} + @end #pragma clang diagnostic pop diff --git a/Sparkle/SUGuidedPackageInstaller.h b/Sparkle/SUGuidedPackageInstaller.h index 292f14af..100e0198 100644 --- a/Sparkle/SUGuidedPackageInstaller.h +++ b/Sparkle/SUGuidedPackageInstaller.h @@ -29,7 +29,7 @@ A guided installation can be started by applications other than the application @interface SUGuidedPackageInstaller : SUInstaller /*! Perform the guided installation */ -+ (void)performInstallationToPath:(NSString *)path fromPath:(NSString *)installerGuide host:(SUHost *)host versionComparator:(id)comparator completionHandler:(void (^)(NSError *))completionHandler; ++ (void)performInstallationToPath:(NSString *)path fromPath:(NSString *)installerGuide host:(SUHost *)host fileOperationToolPath:(NSString *)fileOperationToolPath versionComparator:(id)comparator completionHandler:(void (^)(NSError *))completionHandler; @end #endif diff --git a/Sparkle/SUGuidedPackageInstaller.m b/Sparkle/SUGuidedPackageInstaller.m index c2d25de2..97decfa2 100644 --- a/Sparkle/SUGuidedPackageInstaller.m +++ b/Sparkle/SUGuidedPackageInstaller.m @@ -6,137 +6,27 @@ // Copyright 2010 Dragon Systems Software Limited. All rights reserved. // -#import -#import - #import "SUGuidedPackageInstaller.h" - -static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authorization, const char* executablePath, AuthorizationFlags options, char* const* arguments) -{ - sig_t oldSigChildHandler = signal(SIGCHLD, SIG_DFL); - BOOL returnValue = YES; - -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdeprecated-declarations" - /* AuthorizationExecuteWithPrivileges used to support 10.4+; should be replaced with XPC or external process */ - if (AuthorizationExecuteWithPrivileges(authorization, executablePath, options, arguments, NULL) == errAuthorizationSuccess) -#pragma clang diagnostic pop - { - int status = 0; - pid_t pid = wait(&status); - if (pid == -1 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) - returnValue = NO; - } - else - returnValue = NO; - - signal(SIGCHLD, oldSigChildHandler); - return returnValue; -} - -@implementation SUGuidedPackageInstaller (SUGuidedPackageInstallerAuthentication) - -+ (AuthorizationRef)authorizationForExecutable:(NSString*)executablePath -{ - SUParameterAssert(executablePath); - - // Get authorization using advice in Apple's Technical Q&A1172 - - // ...create authorization without specific rights - AuthorizationRef auth = NULL; - OSStatus validAuth = AuthorizationCreate(NULL, - kAuthorizationEmptyEnvironment, - kAuthorizationFlagDefaults, - &auth); - // ...then extend authorization with desired rights - if ((validAuth == errAuthorizationSuccess) && - (auth != NULL)) - { - char executableFileSystemRepresentation[PATH_MAX]; - [executablePath getFileSystemRepresentation:executableFileSystemRepresentation maxLength:sizeof(executableFileSystemRepresentation)]; - - // Prepare a right allowing script to execute with privileges - AuthorizationItem right = { - .name = kAuthorizationRightExecute, - .value = executableFileSystemRepresentation, - .valueLength = strlen(executableFileSystemRepresentation), - }; - - // Package up the single right - AuthorizationRights rights; - memset(&rights,0,sizeof(rights)); - rights.count = 1; - rights.items = &right; - - // Extend rights to run script - validAuth = AuthorizationCopyRights(auth, - &rights, - kAuthorizationEmptyEnvironment, - (AuthorizationFlags) - (kAuthorizationFlagPreAuthorize | - kAuthorizationFlagExtendRights | - kAuthorizationFlagInteractionAllowed), - NULL); - if (validAuth != errAuthorizationSuccess) - { - // Error, clean up authorization - (void) AuthorizationFree(auth,kAuthorizationFlagDefaults); - auth = NULL; - } - } - - return auth; -} - -@end +#import "SUFileManager.h" @implementation SUGuidedPackageInstaller -+ (void)performInstallationToPath:(NSString *)destinationPath fromPath:(NSString *)packagePath host:(SUHost *)__unused host versionComparator:(id)__unused comparator completionHandler:(void (^)(NSError *))completionHandler ++ (void)performInstallationToPath:(NSString *)destinationPath fromPath:(NSString *)packagePath host:(SUHost *)__unused host fileOperationToolPath:(NSString *)fileOperationToolPath versionComparator:(id)__unused comparator completionHandler:(void (^)(NSError *))completionHandler { SUParameterAssert(packagePath); - + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ - - // Preflight - NSString* installerPath = @"/usr/sbin/installer"; // Mac OS X 10.2+ command line installer tool - NSError* error = nil; - - // Create authorization for installer executable - BOOL validInstallation = NO; - AuthorizationRef auth = [self authorizationForExecutable:installerPath]; - if (auth != NULL) - { - char pathBuffer[PATH_MAX] = {0}; - [packagePath getFileSystemRepresentation:pathBuffer maxLength:sizeof(pathBuffer)]; - - // Permission was granted to execute the installer with privileges - char * const arguments[] = { - "-pkg", - pathBuffer, - "-target", - "/", - NULL - }; - validInstallation = AuthorizationExecuteWithPrivilegesAndWait(auth, - [installerPath fileSystemRepresentation], - kAuthorizationFlagDefaults, - arguments); - // TODO: wait for communications pipe to close via fileno & CFSocketCreateWithNative - AuthorizationFree(auth,kAuthorizationFlagDefaults); - } - else - { - NSString* errorMessage = [NSString stringWithFormat:@"Sparkle Updater: Script authorization denied."]; - error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:[NSDictionary dictionaryWithObject:errorMessage forKey:NSLocalizedDescriptionKey]]; - } - + SUFileManager *fileManager = [SUFileManager fileManagerWithAuthorizationToolPath:fileOperationToolPath]; + + NSError *error = nil; + BOOL validInstallation = [fileManager executePackageAtURL:[NSURL fileURLWithPath:packagePath] error:&error]; + dispatch_async(dispatch_get_main_queue(), ^{ [self finishInstallationToPath:destinationPath withResult:validInstallation error:error completionHandler:completionHandler]; - + }); }); } diff --git a/Sparkle/SUInstaller.h b/Sparkle/SUInstaller.h index 4afe1cbe..0bb08c11 100644 --- a/Sparkle/SUInstaller.h +++ b/Sparkle/SUInstaller.h @@ -16,7 +16,7 @@ @interface SUInstaller : NSObject + (NSString *)installSourcePathInUpdateFolder:(NSString *)inUpdateFolder forHost:(SUHost *)host isPackage:(BOOL *)isPackagePtr isGuided:(BOOL *)isGuidedPtr; -+ (void)installFromUpdateFolder:(NSString *)updateFolder overHost:(SUHost *)host installationPath:(NSString *)installationPath versionComparator:(id)comparator completionHandler:(void (^)(NSError *))completionHandler; ++ (void)installFromUpdateFolder:(NSString *)inUpdateFolder overHost:(SUHost *)host installationPath:(NSString *)installationPath fileOperationToolPath:(NSString *)fileOperationToolPath versionComparator:(id)comparator completionHandler:(void (^)(NSError *))completionHandler; + (void)finishInstallationToPath:(NSString *)installationPath withResult:(BOOL)result error:(NSError *)error completionHandler:(void (^)(NSError *))completionHandler; @end diff --git a/Sparkle/SUInstaller.m b/Sparkle/SUInstaller.m index 400f9597..45919ea3 100644 --- a/Sparkle/SUInstaller.m +++ b/Sparkle/SUInstaller.m @@ -103,7 +103,7 @@ return newAppDownloadPath; } -+ (void)installFromUpdateFolder:(NSString *)inUpdateFolder overHost:(SUHost *)host installationPath:(NSString *)installationPath versionComparator:(id)comparator completionHandler:(void (^)(NSError *))completionHandler ++ (void)installFromUpdateFolder:(NSString *)inUpdateFolder overHost:(SUHost *)host installationPath:(NSString *)installationPath fileOperationToolPath:(NSString *)fileOperationToolPath versionComparator:(id)comparator completionHandler:(void (^)(NSError *))completionHandler { BOOL isPackage = NO; BOOL isGuided = NO; @@ -113,11 +113,11 @@ [self finishInstallationToPath:installationPath withResult:NO error:[NSError errorWithDomain:SUSparkleErrorDomain code:SUMissingUpdateError userInfo:@{ NSLocalizedDescriptionKey: @"Couldn't find an appropriate update in the downloaded package." }] completionHandler:completionHandler]; } else { if (isPackage && isGuided) { - [SUGuidedPackageInstaller performInstallationToPath:installationPath fromPath:newAppDownloadPath host:host versionComparator:comparator completionHandler:completionHandler]; + [SUGuidedPackageInstaller performInstallationToPath:installationPath fromPath:newAppDownloadPath host:host fileOperationToolPath:fileOperationToolPath versionComparator:comparator completionHandler:completionHandler]; } else if (isPackage) { - [SUPackageInstaller performInstallationToPath:installationPath fromPath:newAppDownloadPath host:host versionComparator:comparator completionHandler:completionHandler]; + [SUPackageInstaller performInstallationToPath:installationPath fromPath:newAppDownloadPath host:host fileOperationToolPath:fileOperationToolPath versionComparator:comparator completionHandler:completionHandler]; } else { - [SUPlainInstaller performInstallationToPath:installationPath fromPath:newAppDownloadPath host:host versionComparator:comparator completionHandler:completionHandler]; + [SUPlainInstaller performInstallationToPath:installationPath fromPath:newAppDownloadPath host:host fileOperationToolPath:fileOperationToolPath versionComparator:comparator completionHandler:completionHandler]; } } } diff --git a/Sparkle/SUPackageInstaller.m b/Sparkle/SUPackageInstaller.m index 64637433..2a38db44 100644 --- a/Sparkle/SUPackageInstaller.m +++ b/Sparkle/SUPackageInstaller.m @@ -12,7 +12,7 @@ @implementation SUPackageInstaller -+ (void)performInstallationToPath:(NSString *)installationPath fromPath:(NSString *)path host:(SUHost *)__unused host versionComparator:(id)__unused comparator completionHandler:(void (^)(NSError *))completionHandler ++ (void)performInstallationToPath:(NSString *)installationPath fromPath:(NSString *)path host:(SUHost *)__unused host fileOperationToolPath:(NSString *)__unused fileOperationToolPath versionComparator:(id)__unused comparator completionHandler:(void (^)(NSError *))completionHandler { // Run installer using the "open" command to ensure it is launched in front of current application. // -W = wait until the app has quit. diff --git a/Sparkle/SUPlainInstaller.h b/Sparkle/SUPlainInstaller.h index 1119aaab..5bebdee8 100644 --- a/Sparkle/SUPlainInstaller.h +++ b/Sparkle/SUPlainInstaller.h @@ -23,7 +23,7 @@ @interface SUPlainInstaller : SUInstaller -+ (void)performInstallationToPath:(NSString *)installationPath fromPath:(NSString *)path host:(SUHost *)host versionComparator:(id)comparator completionHandler:(void (^)(NSError *))completionHandler; ++ (void)performInstallationToPath:(NSString *)installationPath fromPath:(NSString *)path host:(SUHost *)host fileOperationToolPath:(NSString *)fileOperationToolPath versionComparator:(id)comparator completionHandler:(void (^)(NSError *))completionHandler; @end diff --git a/Sparkle/SUPlainInstaller.m b/Sparkle/SUPlainInstaller.m index 3e9f1b8f..4f06d47d 100644 --- a/Sparkle/SUPlainInstaller.m +++ b/Sparkle/SUPlainInstaller.m @@ -31,7 +31,7 @@ return trimmedVersion.length > 0 ? trimmedVersion : nil; } -+ (BOOL)performInstallationToURL:(NSURL *)installationURL fromUpdateAtURL:(NSURL *)newURL withHost:(SUHost *)host error:(NSError * __autoreleasing *)error ++ (BOOL)performInstallationToURL:(NSURL *)installationURL fromUpdateAtURL:(NSURL *)newURL withHost:(SUHost *)host fileOperationToolPath:(NSString *)fileOperationToolPath error:(NSError * __autoreleasing *)error { if (installationURL == nil || newURL == nil) { // this really shouldn't happen but just in case @@ -42,7 +42,7 @@ return NO; } - SUFileManager *fileManager = [SUFileManager fileManagerAllowingAuthorization:YES]; + SUFileManager *fileManager = [SUFileManager fileManagerWithAuthorizationToolPath:fileOperationToolPath]; // Create a temporary directory for our new app that resides on our destination's volume NSURL *tempNewDirectoryURL = [fileManager makeTemporaryDirectoryWithPreferredName:[installationURL.lastPathComponent.stringByDeletingPathExtension stringByAppendingString:@" (Incomplete Update)"] appropriateForDirectoryURL:installationURL.URLByDeletingLastPathComponent error:error]; @@ -155,7 +155,7 @@ return YES; } -+ (void)performInstallationToPath:(NSString *)installationPath fromPath:(NSString *)path host:(SUHost *)host versionComparator:(id)comparator completionHandler:(void (^)(NSError *))completionHandler ++ (void)performInstallationToPath:(NSString *)installationPath fromPath:(NSString *)path host:(SUHost *)host fileOperationToolPath:(NSString *)fileOperationToolPath versionComparator:(id)comparator completionHandler:(void (^)(NSError *))completionHandler { SUParameterAssert(host); @@ -173,7 +173,7 @@ dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSError *error = nil; - BOOL result = [self performInstallationToURL:[NSURL fileURLWithPath:installationPath] fromUpdateAtURL:[NSURL fileURLWithPath:path] withHost:host error:&error]; + BOOL result = [self performInstallationToURL:[NSURL fileURLWithPath:installationPath] fromUpdateAtURL:[NSURL fileURLWithPath:path] withHost:host fileOperationToolPath:fileOperationToolPath error:&error]; dispatch_async(dispatch_get_main_queue(), ^{ [self finishInstallationToPath:installationPath withResult:result error:error completionHandler:completionHandler]; diff --git a/TestApplication/SUTestApplicationDelegate.m b/TestApplication/SUTestApplicationDelegate.m index dbf0f22a..10929a4b 100644 --- a/TestApplication/SUTestApplicationDelegate.m +++ b/TestApplication/SUTestApplicationDelegate.m @@ -39,7 +39,7 @@ static NSString * const UPDATED_VERSION = @"2.0"; [[NSApplication sharedApplication] terminate:nil]; } - SUFileManager *fileManager = [SUFileManager fileManagerAllowingAuthorization:NO]; + SUFileManager *fileManager = [SUFileManager defaultManager]; // Locate user's cache directory NSError *cacheError = nil; diff --git a/Tests/SUCodeSigningVerifierTest.m b/Tests/SUCodeSigningVerifierTest.m index 43f91d7e..40aa79ac 100644 --- a/Tests/SUCodeSigningVerifierTest.m +++ b/Tests/SUCodeSigningVerifierTest.m @@ -34,7 +34,7 @@ NSString *unitTestBundleIdentifier = unitTestBundle.bundleIdentifier; NSString *zippedAppPath = [unitTestBundle pathForResource:@"SparkleTestCodeSignApp" ofType:@"zip"]; - SUFileManager *fileManager = [SUFileManager fileManagerAllowingAuthorization:NO]; + SUFileManager *fileManager = [SUFileManager defaultManager]; NSError *tempError = nil; NSURL *tempDir = [fileManager makeTemporaryDirectoryWithPreferredName:unitTestBundleIdentifier appropriateForDirectoryURL:[NSURL fileURLWithPath:zippedAppPath] error:&tempError]; diff --git a/Tests/SUFileManagerTest.swift b/Tests/SUFileManagerTest.swift index 30f6286f..3287cddf 100644 --- a/Tests/SUFileManagerTest.swift +++ b/Tests/SUFileManagerTest.swift @@ -12,7 +12,7 @@ class SUFileManagerTest: XCTestCase { func makeTempFiles(testBlock: (SUFileManager, NSURL, NSURL, NSURL, NSURL, NSURL, NSURL) -> Void) { - let fileManager = SUFileManager(allowingAuthorization: false) + let fileManager = SUFileManager.defaultManager() let tempDirectoryURL = try! fileManager.makeTemporaryDirectoryWithPreferredName("Sparkle Unit Test Data", appropriateForDirectoryURL: NSURL(fileURLWithPath: NSHomeDirectory())) @@ -291,33 +291,26 @@ class SUFileManagerTest: XCTestCase func testMakeDirectory() { makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL, validSymlinkURL, invalidSymlinkURL in - XCTAssertNil(try? fileManager._makeDirectoryAtURL(ordinaryFileURL)) - XCTAssertNil(try? fileManager._makeDirectoryAtURL(directoryURL)) + XCTAssertNil(try? fileManager.makeDirectoryAtURL(ordinaryFileURL)) + XCTAssertNil(try? fileManager.makeDirectoryAtURL(directoryURL)) - XCTAssertNil(try? fileManager._makeDirectoryAtURL(rootURL.URLByAppendingPathComponent("this should").URLByAppendingPathComponent("be a failure"))) + XCTAssertNil(try? fileManager.makeDirectoryAtURL(rootURL.URLByAppendingPathComponent("this should").URLByAppendingPathComponent("be a failure"))) let newDirectoryURL = rootURL.URLByAppendingPathComponent("new test directory") XCTAssertFalse(fileManager._itemExistsAtURL(newDirectoryURL)) - try! fileManager._makeDirectoryAtURL(newDirectoryURL) + try! fileManager.makeDirectoryAtURL(newDirectoryURL) var isDirectory: ObjCBool = false XCTAssertTrue(fileManager._itemExistsAtURL(newDirectoryURL, isDirectory: &isDirectory)) try! fileManager.removeItemAtURL(directoryURL) - XCTAssertNil(try? fileManager._makeDirectoryAtURL(validSymlinkURL)) + XCTAssertNil(try? fileManager.makeDirectoryAtURL(validSymlinkURL)) } } - // This alone shouldn't prompt a password dialog and should always succeed - func testAcquireAuthorization() - { - let fileManager = SUFileManager(allowingAuthorization: true) - try! fileManager._acquireAuthorization() - } - func testAcquireBadAuthorization() { - let fileManager = SUFileManager(allowingAuthorization: false) + let fileManager = SUFileManager.defaultManager() XCTAssertNil(try? fileManager._acquireAuthorization()) } } diff --git a/Tests/SUInstallerTest.m b/Tests/SUInstallerTest.m index 8b73abe3..278060b0 100644 --- a/Tests/SUInstallerTest.m +++ b/Tests/SUInstallerTest.m @@ -53,7 +53,13 @@ SUHost *host = [[SUHost alloc] initWithBundle:bundle]; - [SUInstaller installFromUpdateFolder:[path stringByDeletingLastPathComponent] overHost:host installationPath:@"/tmp" versionComparator:nil completionHandler:^(NSError *error) { + NSString *fileOperationToolPath = [bundle pathForResource:@""SPARKLE_FILEOP_TOOL_NAME ofType:@""]; + XCTAssertNotNil(fileOperationToolPath); + + [SUInstaller installFromUpdateFolder:[path stringByDeletingLastPathComponent] overHost:host installationPath:@"/tmp" fileOperationToolPath:fileOperationToolPath versionComparator:nil completionHandler:^(NSError *error) { + if (error != nil) { + NSLog(@"Underlying error: %@", [error.userInfo objectForKey:NSUnderlyingErrorKey]); + } XCTAssertNil(error); XCTAssertTrue([fm fileExistsAtPath:expectedDestination isDirectory:nil]); [done fulfill]; diff --git a/Tests/Sparkle Unit Tests-Bridging-Header.h b/Tests/Sparkle Unit Tests-Bridging-Header.h index d08dafb8..bc07f867 100644 --- a/Tests/Sparkle Unit Tests-Bridging-Header.h +++ b/Tests/Sparkle Unit Tests-Bridging-Header.h @@ -22,8 +22,6 @@ static const char *SUAppleQuarantineIdentifier = "com.apple.quarantine"; - (BOOL)_itemExistsAtURL:(NSURL *)fileURL; - (BOOL)_itemExistsAtURL:(NSURL *)fileURL isDirectory:(BOOL *)isDirectory; -- (BOOL)_makeDirectoryAtURL:(NSURL *)url error:(NSError * __autoreleasing *)error; - @end @interface SUBasicUpdateDriver (Private) diff --git a/fileop/SUFileOperationConstants.h b/fileop/SUFileOperationConstants.h new file mode 100644 index 00000000..9f4ba685 --- /dev/null +++ b/fileop/SUFileOperationConstants.h @@ -0,0 +1,16 @@ +// +// SUFileOperationConstants.h +// Sparkle +// +// Created by Mayur Pawashe on 6/5/16. +// Copyright © 2016 Sparkle Project. All rights reserved. +// + +extern char * const SUFileOpRemoveQuarantineCommand; +extern char * const SUFileOpCopyCommand; +extern char * const SUFileOpMoveCommand; +extern char * const SUFileOpChangeOwnerAndGroupCommand; +extern char * const SUFileOpUpdateModificationAndAccessTimeCommand; +extern char * const SUFileOpMakeDirectoryCommand; +extern char * const SUFileOpRemoveCommand; +extern char * const SUFileOpInstallCommand; diff --git a/fileop/SUFileOperationConstants.m b/fileop/SUFileOperationConstants.m new file mode 100644 index 00000000..5ece5917 --- /dev/null +++ b/fileop/SUFileOperationConstants.m @@ -0,0 +1,18 @@ +// +// SUFileOperationConstants.m +// Sparkle +// +// Created by Mayur Pawashe on 6/5/16. +// Copyright © 2016 Sparkle Project. All rights reserved. +// + +#import "SUFileOperationConstants.h" + +char * const SUFileOpRemoveQuarantineCommand = "xattr-d-apple-quarantine"; +char * const SUFileOpCopyCommand = "cp"; +char * const SUFileOpMoveCommand = "mv"; +char * const SUFileOpChangeOwnerAndGroupCommand = "chown"; +char * const SUFileOpUpdateModificationAndAccessTimeCommand = "touch"; +char * const SUFileOpMakeDirectoryCommand = "mkdir"; +char * const SUFileOpRemoveCommand = "rm"; +char * const SUFileOpInstallCommand = "installer"; diff --git a/fileop/fileop.m b/fileop/fileop.m new file mode 100644 index 00000000..43efac6b --- /dev/null +++ b/fileop/fileop.m @@ -0,0 +1,151 @@ +// +// fileop.m +// fileop +// +// Created by Mayur Pawashe on 6/5/16. +// Copyright © 2016 Sparkle Project. All rights reserved. +// + +#import +#import "SUFileManager.h" +#import "SUFileOperationConstants.h" + +// If we fail, we exit with a unique status code +// We don't try to NSLog because the logs can't be seen anywhere, +// and we don't want to log to a file irresponsibly (especially as root), +// nor want to communicate to the parent forcing the parent to read from the stdout pipe +// (allowing us to avoid any sort of potential blocking issues?) +typedef NS_ENUM(uint8_t, SUFileOpError) +{ + SUWritePIDFailure = 0x02, + SUFlushFailure = 0x03, + SUInsufficientNumberOfArguments = 0x04, + SUCommandNameUTF8ParseFailure = 0x05, + SUPathUTF8ParseFailure = 0x06, + SUQuarantineRemovalFailure = 0x07, + SUCopyFailure = 0x08, + SUMoveFailure = 0x09, + SUChangeOwnerAndGroupFailure = 0x0A, + SUTouchFailure = 0x0B, + SUMakeDirectoryFailure = 0x0C, + SURemoveFailure = 0x0D, + SUPackageFailureStatusCode = 0x0E, + SUPackageRaisedExceptionFailure = 0x0F, + SUInvalidCommandFailure = 0x10, + // This code can be OR'd with another one to produce a unique combination + SUInvalidOrNoDestination = 0x80 +}; + +int main(int argc, const char *argv[]) +{ + @autoreleasepool { + // Before we do anything, we should let the parent know our pid so they can wait() on us + // We do this because AuthorizationExecuteWithPrivileges() has no way of reporting back the child pid, + // but it does give us a communication pipe + uint32_t pid = CFSwapInt32HostToLittle((uint32_t)getpid()); + if (fwrite(&pid, sizeof(pid), 1, stdout) < 1) { + exit(SUWritePIDFailure); + } + + if (fflush(stdout) != 0) { + exit(SUFlushFailure); + } + + // At least we need the command name and file path arguments + if (argc < 3) { + exit(SUInsufficientNumberOfArguments); + } + + NSString *command = [[NSString alloc] initWithUTF8String:argv[1]]; + if (command == nil) { + exit(SUCommandNameUTF8ParseFailure); + } + + NSString *filepath = [[NSString alloc] initWithUTF8String:argv[2]]; + if (filepath == nil) { + exit(SUPathUTF8ParseFailure); + } + + NSURL *fileURL = [NSURL fileURLWithPath:filepath]; + if (fileURL == nil) { + exit(SUPathUTF8ParseFailure); + } + + NSURL *destinationURL = nil; + if (argc >= 4) { + NSString *destinationPath = [[NSString alloc] initWithUTF8String:argv[3]]; + if (destinationPath != nil) { + destinationURL = [NSURL fileURLWithPath:destinationPath]; + } + } + + // This tool should be executed as root, so we should not try to authorize + SUFileManager *fileManager = [SUFileManager defaultManager]; + + if ([command isEqualToString:@(SUFileOpRemoveQuarantineCommand)]) { + if (![fileManager releaseItemFromQuarantineAtRootURL:fileURL error:NULL]) { + exit(SUQuarantineRemovalFailure); + } + } else if ([command isEqualToString:@(SUFileOpCopyCommand)]) { + if (destinationURL != nil) { + if (![fileManager copyItemAtURL:fileURL toURL:destinationURL error:NULL]) { + exit(SUCopyFailure); + } + } else { + exit(SUInvalidOrNoDestination | SUCopyFailure); + } + } else if ([command isEqualToString:@(SUFileOpMoveCommand)]) { + if (destinationURL != nil) { + if (![fileManager moveItemAtURL:fileURL toURL:destinationURL error:NULL]) { + exit(SUMoveFailure); + } + } else { + exit(SUInvalidOrNoDestination | SUMoveFailure); + } + } else if ([command isEqualToString:@(SUFileOpChangeOwnerAndGroupCommand)]) { + if (destinationURL != nil) { + if (![fileManager changeOwnerAndGroupOfItemAtRootURL:fileURL toMatchURL:destinationURL error:NULL]) { + exit(SUChangeOwnerAndGroupFailure); + } + } else { + exit(SUInvalidOrNoDestination | SUChangeOwnerAndGroupFailure); + } + } else if ([command isEqualToString:@(SUFileOpUpdateModificationAndAccessTimeCommand)]) { + if (![fileManager updateModificationAndAccessTimeOfItemAtURL:fileURL error:NULL]) { + exit(SUTouchFailure); + } + } else if ([command isEqualToString:@(SUFileOpMakeDirectoryCommand)]) { + if (![fileManager makeDirectoryAtURL:fileURL error:NULL]) { + exit(SUMakeDirectoryFailure); + } + } else if ([command isEqualToString:@(SUFileOpRemoveCommand)]) { + if (![fileManager removeItemAtURL:fileURL error:NULL]) { + exit(SURemoveFailure); + } + } else if ([command isEqualToString:@(SUFileOpInstallCommand)]) { + // The one command that can *only* be run as the root user + NSString *installerPath = @"/usr/sbin/installer"; // Mac OS X 10.2+ command line installer tool + + NSTask *task = [[NSTask alloc] init]; + task.launchPath = installerPath; + task.arguments = @[@"-pkg", filepath, @"-target", @"/"]; + // Output won't show up anyway, so we may as well ignore it + task.standardError = [NSPipe pipe]; + task.standardOutput = [NSPipe pipe]; + + @try { + [task launch]; + [task waitUntilExit]; + if (task.terminationStatus != EXIT_SUCCESS) { + exit(SUPackageFailureStatusCode); + } + } @catch (NSException *) { + exit(SUPackageRaisedExceptionFailure); + } + } else { + exit(SUInvalidCommandFailure); + } + + return EXIT_SUCCESS; + } +} From e4c3c29a85990c51cef480ebd3fd3fb62b6ac483 Mon Sep 17 00:00:00 2001 From: Zorg Date: Thu, 9 Jun 2016 07:59:46 -0400 Subject: [PATCH 2/3] Fix SUFileOperationConstants link errors in BinaryDelta --- Sparkle.xcodeproj/project.pbxproj | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Sparkle.xcodeproj/project.pbxproj b/Sparkle.xcodeproj/project.pbxproj index 1eb7175c..3a396628 100644 --- a/Sparkle.xcodeproj/project.pbxproj +++ b/Sparkle.xcodeproj/project.pbxproj @@ -194,6 +194,7 @@ 723B252E1CEAB3A600909873 /* bscommon.c in Sources */ = {isa = PBXBuildFile; fileRef = 723B252B1CEAB3A600909873 /* bscommon.c */; }; 723B252F1CEAB3A600909873 /* bscommon.c in Sources */ = {isa = PBXBuildFile; fileRef = 723B252B1CEAB3A600909873 /* bscommon.c */; }; 723B25301CEAB3A600909873 /* bscommon.h in Headers */ = {isa = PBXBuildFile; fileRef = 723B252C1CEAB3A600909873 /* bscommon.h */; }; + 72544FFC1D0991A4000CFB2C /* SUFileOperationConstants.m in Sources */ = {isa = PBXBuildFile; fileRef = 722954C31D04E66F00ECF9CA /* SUFileOperationConstants.m */; }; 7268AC631AD634C200C3E0C1 /* SUBinaryDeltaCreate.m in Sources */ = {isa = PBXBuildFile; fileRef = 7268AC621AD634C200C3E0C1 /* SUBinaryDeltaCreate.m */; }; 726F2CDE1BC9BE5B001971A4 /* SUFileManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 7275F9C01B5F1F2900B1D19E /* SUFileManager.m */; }; 726F2CE51BC9C33D001971A4 /* SUOperatingSystem.h in Headers */ = {isa = PBXBuildFile; fileRef = 726F2CE31BC9C33D001971A4 /* SUOperatingSystem.h */; }; @@ -1721,6 +1722,7 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + 72544FFC1D0991A4000CFB2C /* SUFileOperationConstants.m in Sources */, 5D06E8E90FD68CDB005AE3F6 /* bsdiff.c in Sources */, 14652F7E19A9728A00959E44 /* bspatch.c in Sources */, 7223E7631AD1AEFF008E3161 /* sais.c in Sources */, From dd0805c05bc0ead40a2434cc1b234cbd13513ef1 Mon Sep 17 00:00:00 2001 From: Zorg Date: Fri, 10 Jun 2016 16:13:18 -0400 Subject: [PATCH 3/3] No need to log the underlying error This is already logged when logging the main error --- Sparkle/Autoupdate/Autoupdate.m | 3 --- 1 file changed, 3 deletions(-) diff --git a/Sparkle/Autoupdate/Autoupdate.m b/Sparkle/Autoupdate/Autoupdate.m index 51d145f9..a021172b 100644 --- a/Sparkle/Autoupdate/Autoupdate.m +++ b/Sparkle/Autoupdate/Autoupdate.m @@ -182,9 +182,6 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.5; NSError *underlyingError = [error.userInfo objectForKey:NSUnderlyingErrorKey]; if (underlyingError == nil || underlyingError.code != SUInstallationCancelledError) { SULog(@"Installation Error: %@", error); - if (underlyingError != nil) { - SULog(@"Installation Underlying Error: %@", underlyingError); - } if (self.shouldShowUI) { NSAlert *alert = [[NSAlert alloc] init]; alert.messageText = @"";