-
Notifications
You must be signed in to change notification settings - Fork 70
/
Copy pathNSAuthorization.m
86 lines (64 loc) · 2.69 KB
/
NSAuthorization.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
//
// NSAuthorization.m
// OSXvnc
//
// Created by Jonathan Gillaspie on Fri Dec 12 2003.
// Copyright (c) 2003 __MyCompanyName__. All rights reserved.
//
#import "NSAuthorization.h"
#include "unistd.h"
@implementation NSAuthorization
- (instancetype) init {
AuthorizationFlags myFlags = kAuthorizationFlagDefaults |
kAuthorizationFlagInteractionAllowed |
kAuthorizationFlagPreAuthorize |
kAuthorizationFlagExtendRights;
OSStatus myStatus;
AuthorizationItem myItems = {kAuthorizationRightExecute, 0, NULL, 0};
AuthorizationRights myRights = {1, &myItems};
self = [super init];
myStatus = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, myFlags, &myAuthorizationRef);
// This will pre-authorize the authentication
if (myStatus == errAuthorizationSuccess)
myStatus = AuthorizationCopyRights(myAuthorizationRef, &myRights, NULL, myFlags, NULL);
if (myStatus != errAuthorizationSuccess) {
return nil;
}
return self;
}
- (BOOL) executeCommand:(NSString *) command withArgs: (NSArray *) argumentArray {
return [self executeCommand:(NSString *) command withArgs: (NSArray *) argumentArray synchronous:TRUE];
}
- (BOOL) executeCommand:(NSString *) command withArgs: (NSArray *) argumentArray synchronous: (BOOL) sync {
FILE *communicationStream = NULL;
int i;
OSStatus myStatus;
char outputString[1024];
time_t startTime = time(NULL);
char **copyArguments = malloc(sizeof(char *) * (argumentArray.count + 1));
for (i = 0; i < argumentArray.count; i++) {
copyArguments[i] = (char *)[argumentArray[i] UTF8String];
}
copyArguments[i] = NULL;
myStatus = AuthorizationExecuteWithPrivileges(myAuthorizationRef,
command.UTF8String,
kAuthorizationFlagDefaults,
copyArguments,
(sync ? &communicationStream : NULL)); // FILE HANDLE for I/O
if (myStatus==errAuthorizationSuccess && sync) {
while (!myStatus && !feof(communicationStream) && fgets(outputString, 1024, communicationStream) && time(NULL)-startTime<10) {
if (strlen(outputString) > 1)
NSLog(@"NSAuthorization: %s",outputString);
}
fclose(communicationStream);
}
free(copyArguments);
if (myStatus != errAuthorizationSuccess)
NSLog(@"Error: Executing %@ with Authorization: %d", command, (int)myStatus);
return (myStatus == errAuthorizationSuccess);
}
- (void) dealloc {
AuthorizationFree (myAuthorizationRef, kAuthorizationFlagDefaults);
[super dealloc];
}
@end