Skip to content

Instantly share code, notes, and snippets.

@shunsuke0125
Created February 24, 2014 04:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shunsuke0125/9182051 to your computer and use it in GitHub Desktop.
Save shunsuke0125/9182051 to your computer and use it in GitHub Desktop.
【Objective-C】特権ユーザーとしてアプリケーションを再実行するサンプル
// ====
// 特権ユーザーとしてアプリケーションを再実行するサンプル
// - アプリケーション実行時に特権ユーザーの認証ダイアログが表示されます
// - 認証後に特権ユーザーとして自身を起動します
// - 本サンプルは非特権ユーザーのアプリケーションは終了させずに戻り値を取得しています
//
// (参考)
// Authorization Services C Reference | Mac Developer Library
// https://developer.apple.com/library/mac/documentation/Security/Reference/authorization_ref/Reference/reference.html
// ====
#import <Cocoa/Cocoa.h>
int main(int argc, const char * argv[])
{
if (argc == 2 && strcmp(argv[1], "isPrivileges") == 0) { // == 特権ユーザー時の処理
// TODO 特権ユーザー時の処理を記述する
return 0;
} else { // == 非特権ユーザー時の処理 ==
// アプリケーションのパスを取得
NSString *productName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
NSString *exePath = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:[NSString stringWithFormat:@"Contents/MacOS/%@", productName]];
// 実行引数を設定(今回はisPrivilegesが渡った場合特権ユーザーモードで実行)
char *exeArgv[] = {"isPrivileges", NULL};
OSStatus status;
AuthorizationRef authRef;
FILE *stdOut;
// Authorizationハンドル作成
status = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, kAuthorizationFlagDefaults, &authRef);
if (status != errAuthorizationSuccess) {
NSLog(@"AuthorizationCreate : %d", status);
}
// 権限情報を生成
AuthorizationItem tRightItem;
tRightItem.name = kAuthorizationRightExecute;
tRightItem.valueLength = [exePath lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
tRightItem.value = (void *)CFBridgingRetain(exePath);
tRightItem.flags = 0;
AuthorizationRights tRights;
tRights.count = 1;
tRights.items = &tRightItem;
status = AuthorizationCopyRights( authRef, &tRights, kAuthorizationEmptyEnvironment,
kAuthorizationFlagInteractionAllowed | kAuthorizationFlagExtendRights, NULL );
if ( status != errAuthorizationSuccess ) {
NSLog(@"AuthorizationCopyRights : %d", status);
}
// 特権モードでの実行
status = AuthorizationExecuteWithPrivileges(authRef, [exePath UTF8String], kAuthorizationFlagDefaults, exeArgv, &stdOut);
if ( status != errAuthorizationSuccess ) {
NSLog(@"AuthorizationExecuteWithPrivileges : %d", status);
}
// 特権モードでの実行からの返却値を取得
char cResult[128];
fgets(cResult, sizeof(cResult), stdOut);
fclose(stdOut);
NSLog(@"Adjust %s", cResult);
// 権限を開放
AuthorizationFree (authRef, kAuthorizationFlagDefaults);
// 特権ユーザーでの実行結果を検証
if (strcmp(cResult, "0") == 0) {
return 0;
} else {
return -1;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment