文件
dayu-color/大鱼调色/Wrapper Application/DYBetaUpdater.mm
T

167 行
16 KiB
Plaintext
原始文件 Blame 文件历史

此文件含有模棱两可的 Unicode 字符
此文件含有可能会与其他字符混淆的 Unicode 字符。 如果您是想特意这样的,可以安全地忽略该警告。 使用 Escape 按钮显示他们。
#import "DYBetaUpdater.h"
#import "../Shared/DYBetaDiagnostics.h"
#import <AppKit/AppKit.h>
#import <CommonCrypto/CommonDigest.h>
#include <atomic>
#include <sys/xattr.h>
static NSError *DYUpdateError(NSString *message) { return [NSError errorWithDomain:@"com.dayu.color.update" code:1 userInfo:@{NSLocalizedDescriptionKey:message}]; }
static NSURL *updateFolder(void) {
NSURL *folder=[[NSFileManager.defaultManager URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask].firstObject URLByAppendingPathComponent:@"com.dayu.color/Updates" isDirectory:YES];
[NSFileManager.defaultManager createDirectoryAtURL:folder withIntermediateDirectories:YES attributes:@{NSFilePosixPermissions:@0700} error:nil];return folder;
}
static NSString *digest(NSURL *url) {
NSFileHandle *file=[NSFileHandle fileHandleForReadingFromURL:url error:nil];if(!file)return nil;
CC_SHA256_CTX context;CC_SHA256_Init(&context);for(;;){NSData *data=[file readDataUpToLength:1024*1024 error:nil];if(!data.length)break;CC_SHA256_Update(&context,data.bytes,(CC_LONG)data.length);}[file closeFile];
unsigned char bytes[CC_SHA256_DIGEST_LENGTH];CC_SHA256_Final(bytes,&context);NSMutableString *text=[NSMutableString string];for(int i=0;i<CC_SHA256_DIGEST_LENGTH;i++)[text appendFormat:@"%02x",bytes[i]];return text;
}
static NSString *command(NSString *path,NSArray *arguments,NSError **error) {
NSTask *task=[[[NSTask alloc]init]autorelease];task.executableURL=[NSURL fileURLWithPath:path];task.arguments=arguments;
NSPipe *output=[NSPipe pipe];task.standardOutput=output;task.standardError=output;
if(![task launchAndReturnError:error])return nil;NSDate *deadline=[NSDate dateWithTimeIntervalSinceNow:40];
while(task.running&&deadline.timeIntervalSinceNow>0)[NSThread sleepForTimeInterval:.05];
if(task.running){[task terminate];if(error)*error=DYUpdateError(@"更新包验证超时,请稍后重试。");return nil;}
NSData *data=[output.fileHandleForReading readDataToEndOfFile];NSString *value=[[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]autorelease]?:@"";
if(task.terminationStatus!=0){if(error)*error=DYUpdateError(@"更新包未通过系统签名或完整性验证。");return nil;}return value;
}
@interface DYBetaUpdater () {
NSURLSession *_session;
NSURLSessionTask *_task;
NSURL *_package;
NSDictionary *_state,*_manifest;
std::atomic_uint _generation;
}
- (void)emit:(NSString *)phase message:(NSString *)message;
@end
@implementation DYBetaUpdater
- (instancetype)init {
if((self=[super init])){_generation.store(0);NSURLSessionConfiguration *config=NSURLSessionConfiguration.ephemeralSessionConfiguration;
config.timeoutIntervalForRequest=6;config.timeoutIntervalForResource=300;config.HTTPShouldSetCookies=NO;config.URLCache=nil;
_session=[[NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil]retain];_state=[@{@"phase":@"idle",@"message":@"启动时自动检查公测更新。"}copy];
// Only this updater's abandoned inspection folders are disposable.
dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY,0),^{for(NSURL *url in [NSFileManager.defaultManager contentsOfDirectoryAtURL:updateFolder() includingPropertiesForKeys:nil options:0 error:nil])if([url.lastPathComponent hasPrefix:@"inspection-"])[NSFileManager.defaultManager removeItemAtURL:url error:nil];});
}return self;
}
- (void)dealloc {[_session invalidateAndCancel];[_session release];[_task release];[_package release];[_state release];[_manifest release];[_changed release];[super dealloc];}
- (NSDictionary *)state { return [[_state copy]autorelease]; }
- (double)downloadFraction {int64_t expected=[_manifest[@"size"]longLongValue];return expected>0?MIN(1.,double(_task.countOfBytesReceived)/expected):0;}
- (void)emit:(NSString *)phase message:(NSString *)message {
if(!NSThread.isMainThread){dispatch_async(dispatch_get_main_queue(),^{[self emit:phase message:message];});return;}
[_state release];_state=[@{@"phase":phase,@"message":message?:@"",@"version":_manifest[@"version"]?:@""}copy];if(self.changed)self.changed(_state);
}
+ (BOOL)validateManifest:(NSDictionary *)manifest error:(NSError **)error {
if(![manifest isKindOfClass:NSDictionary.class]){if(error)*error=DYUpdateError(@"公测更新清单格式错误。");return NO;}
id build=manifest[@"build"],size=manifest[@"size"];
BOOL numbers=[build isKindOfClass:NSNumber.class]&&[size isKindOfClass:NSNumber.class]&&
CFGetTypeID((CFTypeRef)build)!=CFBooleanGetTypeID()&&CFGetTypeID((CFTypeRef)size)!=CFBooleanGetTypeID();
BOOL valid=numbers&&[manifest[@"bundle_id"]isEqual:@"com.dayu.color"]&&[manifest[@"channel"]isEqual:@"beta"]&&
[manifest[@"version"]isKindOfClass:NSString.class]&&[manifest[@"version"]length]>0&&[manifest[@"version"]length]<33&&
[build doubleValue]==[build longLongValue]&&[build longLongValue]>0&&[build longLongValue]<1000000000&&
[manifest[@"package_type"]isEqual:@"pkg"]&&[manifest[@"install_mode"]isEqual:@"pkg_installer"]&&
[size doubleValue]==[size longLongValue]&&[size longLongValue]>0&&[size longLongValue]<=1024LL*1024*1024;
NSString *hash=[manifest[@"sha256"]isKindOfClass:NSString.class]?manifest[@"sha256"]:@"";
valid=valid&&hash.length==64&&[hash rangeOfString:@"^[a-f0-9]{64}$" options:NSRegularExpressionSearch].location!=NSNotFound;
NSURL *url=[manifest[@"download_url"]isKindOfClass:NSString.class]?[NSURL URLWithString:manifest[@"download_url"]]:nil;
valid=valid&&DYBetaAllowedURL(url,YES)&&[url.pathExtension.lowercaseString isEqual:@"pkg"];
if(!valid&&error)*error=DYUpdateError(@"公测更新清单不完整或不属于大鱼调色。");return valid;
}
+ (BOOL)validatePackage:(NSURL *)package manifest:(NSDictionary *)manifest error:(NSError **)error {
if(![self validateManifest:manifest error:error])return NO;
NSDictionary *attributes=[NSFileManager.defaultManager attributesOfItemAtPath:package.path error:error];
if(!attributes||[attributes[NSFileSize]longLongValue]!=[manifest[@"size"]longLongValue]||![[digest(package)lowercaseString]isEqual:manifest[@"sha256"]]){if(error)*error=DYUpdateError(@"更新包大小或 SHA-256 不匹配,未打开安装程序。");return NO;}
NSString *signature=command(@"/usr/sbin/pkgutil",@[@"--check-signature",package.path],error);
if(!signature||![signature containsString:@"Developer ID Installer:"]||![signature containsString:@"(B3W25FX5H5)"]){if(error)*error=DYUpdateError(@"更新包签名团队不匹配。");return NO;}
if(!command(@"/usr/sbin/spctl",@[@"--assess",@"--type",@"install",@"--verbose=2",package.path],error))return NO;
NSURL *inspection=[updateFolder() URLByAppendingPathComponent:[@"inspection-" stringByAppendingString:NSUUID.UUID.UUIDString]];
@try {
if(!command(@"/usr/sbin/pkgutil",@[@"--expand-full",package.path,inspection.path],error))return NO;
NSMutableArray *apps=[NSMutableArray array];NSUInteger entries=0;
NSDirectoryEnumerator *iterator=[NSFileManager.defaultManager enumeratorAtURL:inspection includingPropertiesForKeys:@[NSURLIsSymbolicLinkKey] options:0 errorHandler:nil];
for(NSURL *url in iterator){if(++entries>50000){if(error)*error=DYUpdateError(@"更新包文件数量异常。");return NO;}
if([url.pathExtension isEqual:@"app"]){[apps addObject:url];[iterator skipDescendants];}
}
if(apps.count!=1){if(error)*error=DYUpdateError(@"更新包必须包含一个完整的大鱼调色 APP。");return NO;}
NSURL *app=apps.firstObject;NSDictionary *info=[NSDictionary dictionaryWithContentsOfURL:[app URLByAppendingPathComponent:@"Contents/Info.plist"]];
NSDictionary *plugin=[NSDictionary dictionaryWithContentsOfURL:[app URLByAppendingPathComponent:@"Contents/PlugIns/大鱼调色 XPC Service.pluginkit/Contents/Info.plist"]];
if(![info[@"CFBundleIdentifier"]isEqual:@"com.dayu.color"]||![plugin[@"CFBundleIdentifier"]isEqual:@"com.dayu.color.XPC"]||
[info[@"CFBundleVersion"]integerValue]!=[manifest[@"build"]integerValue]||[plugin[@"CFBundleVersion"]integerValue]!=[manifest[@"build"]integerValue]||
![info[@"CFBundleShortVersionString"]isEqual:manifest[@"version"]]){if(error)*error=DYUpdateError(@"更新包产品或版本与清单不一致。");return NO;}
if(!command(@"/usr/bin/codesign",@[@"--verify",@"--deep",@"--strict",app.path],error))return NO;
NSString *identity=command(@"/usr/bin/codesign",@[@"-dvvv",app.path],error);
if(![identity containsString:@"TeamIdentifier=B3W25FX5H5"]){if(error)*error=DYUpdateError(@"包内 APP 签名团队不匹配。");return NO;}
// Product PKGs install the wrapper at its fixed FxPlug location and carry templates.
BOOL appTarget=NO,templates=NO;
for(NSURL *url in [NSFileManager.defaultManager enumeratorAtURL:inspection includingPropertiesForKeys:nil options:0 errorHandler:nil]){
if([url.lastPathComponent isEqual:@"PackageInfo"]){NSString *xml=[NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
if([xml containsString:@"install-location=\"/Library/Plug-Ins/FxPlug\""])appTarget=YES;
if(![xml containsString:@"com.dayu.color.installer"]){if(error)*error=DYUpdateError(@"更新包含不属于本产品的安装组件。");return NO;}
}
if([url.lastPathComponent isEqual:@"大鱼调色.moef"])templates=YES;
}
if(!appTarget||!templates){if(error)*error=DYUpdateError(@"更新包缺少正确的插件安装位置或 FCP 模板。");return NO;}
return YES;
} @finally {[NSFileManager.defaultManager removeItemAtURL:inspection error:nil];}
}
- (void)check {
NSString *phase=_state[@"phase"];if([@[@"checking",@"downloading",@"validating"]containsObject:phase])return;
unsigned generation=++_generation;[self emit:@"checking" message:@"正在检查公测更新…"];
NSString *url=[NSString stringWithFormat:@"https://dayu.media/wp-json/dayu-color/v1/update?bundle_id=com.dayu.color&channel=beta&current_build=%@",[NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleVersion"]];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:6];
[_task release];_task=[[_session dataTaskWithRequest:request completionHandler:^(NSData *data,NSURLResponse *response,NSError *error){@autoreleasepool{
NSDictionary *value=data.length<=32768?[NSJSONSerialization JSONObjectWithData:data?:[NSData data] options:0 error:nil]:nil;
if(![value isKindOfClass:NSDictionary.class])value=nil;
BOOL ok=!error&&[(NSHTTPURLResponse*)response statusCode]==200&&[value[@"bundle_id"]isEqual:@"com.dayu.color"]&&[value[@"channel"]isEqual:@"beta"]&&[value[@"update_available"]isKindOfClass:NSNumber.class]&&CFGetTypeID((CFTypeRef)value[@"update_available"])==CFBooleanGetTypeID();
if(ok&&[value[@"update_available"]boolValue])ok=[DYBetaUpdater validateManifest:value error:&error];
NSDictionary *result=[[value copy]autorelease];
dispatch_async(dispatch_get_main_queue(),^{if(generation!=self->_generation.load())return;
if(!ok){[self emit:@"failed" message:@"暂时无法检查更新,不影响插件使用。"];
DYBetaEvent(@"update_check",@{@"status":@"failed",@"error_code":@(error.code)});return;}
[self->_manifest release];self->_manifest=[result copy];
BOOL newer=[result[@"update_available"]boolValue]&&[result[@"build"]integerValue]>[[NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleVersion"]integerValue];
[self emit:newer?@"available":@"latest" message:newer?[NSString stringWithFormat:@"发现公测版 %@(%@)",result[@"version"],result[@"build"]]:@"当前已是最新公测版。"];
DYBetaEvent(@"update_check",@{@"status":newer?@"available":@"latest"});
});
}}]retain];[_task resume];
}
- (void)download {
if(![_state[@"phase"]isEqual:@"available"])return;NSError *error=nil;
if(![DYBetaUpdater validateManifest:_manifest error:&error]){[self emit:@"failed" message:error.localizedDescription];return;}
if([_manifest[@"build"]integerValue]<=[[NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleVersion"]integerValue])return;
unsigned generation=++_generation;NSDictionary *manifest=[[_manifest copy]autorelease];[self emit:@"downloading" message:@"正在下载公测更新,可随时取消。"];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:manifest[@"download_url"]]];request.timeoutInterval=30;
[_task release];_task=[[_session downloadTaskWithRequest:request completionHandler:^(NSURL *temporary,NSURLResponse *response,NSError *failure){@autoreleasepool{
if(generation!=self->_generation.load())return;
NSError *error=failure;NSURL *destination=[updateFolder() URLByAppendingPathComponent:[NSString stringWithFormat:@"dayu-color-update-%@.pkg",manifest[@"build"]]];
if(!error&&[(NSHTTPURLResponse*)response statusCode]==200&&DYBetaAllowedURL(response.URL,YES)){
[NSFileManager.defaultManager removeItemAtURL:destination error:nil];
if([NSFileManager.defaultManager moveItemAtURL:temporary toURL:destination error:&error]){
[self emit:@"validating" message:@"正在验证完整性、签名、公证和插件版本…"];
BOOL valid=[DYBetaUpdater validatePackage:destination manifest:manifest error:&error];
if(!valid&&!error)error=DYUpdateError(@"更新包未通过验证。");
}
}else if(!error)error=DYUpdateError(@"更新包下载失败。");
if(generation!=self->_generation.load()){[NSFileManager.defaultManager removeItemAtURL:destination error:nil];return;}
if(error)[NSFileManager.defaultManager removeItemAtURL:destination error:nil];
dispatch_async(dispatch_get_main_queue(),^{if(generation!=self->_generation.load())return;
if(error){[self emit:@"available" message:error.localizedDescription];DYBetaEvent(@"update_download",@{@"status":@"failed",@"error_code":@(error.code)});}
else{[self->_package release];self->_package=[destination retain];[self emit:@"ready" message:@"更新包已通过校验。保存并退出 FCP / Motion 后可安装。"];
DYBetaEvent(@"update_validation",@{@"status":@"passed"});}
});
}}]retain];[_task resume];
}
- (void)install {
if(![_state[@"phase"]isEqual:@"ready"]&&![_state[@"phase"]isEqual:@"host_wait"])return;
for(NSString *ID in @[@"com.apple.FinalCut",@"com.apple.FinalCutApp",@"com.apple.motionapp",@"com.apple.motionappApp"])
if([NSRunningApplication runningApplicationsWithBundleIdentifier:ID].count){[self emit:@"host_wait" message:@"请先保存并正常退出 FCP / Motion,再点击安装更新。不会强制退出宿主。"];
DYBetaEvent(@"update_installer",@{@"status":@"waiting_for_host"});return;}
if(_package&&[NSWorkspace.sharedWorkspace openURL:_package]){
[NSUserDefaults.standardUserDefaults setObject:_manifest[@"build"] forKey:@"betaPendingUpdateBuild"];[self emit:@"installer" message:@"已打开系统安装程序,请按提示授权并完成安装。"];
DYBetaEvent(@"update_installer",@{@"status":@"system_installer_opened"});}
else [self emit:@"failed" message:@"无法打开系统安装程序,请重试。"];
}
- (void)cancel {++_generation;[_task cancel];BOOL newer=[_manifest[@"build"]integerValue]>[[NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleVersion"]integerValue];[self emit:newer?@"available":@"idle" message:@"已取消,不影响当前插件。"];}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest *))completion {
BOOL download=[task isKindOfClass:NSURLSessionDownloadTask.class];completion(DYBetaAllowedURL(request.URL,download)?request:nil);
}
@end