-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddToSidebar.m
More file actions
448 lines (382 loc) · 16.3 KB
/
AddToSidebar.m
File metadata and controls
448 lines (382 loc) · 16.3 KB
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
#import <Foundation/Foundation.h>
#import <CoreServices/CoreServices.h>
#include <unistd.h>
#include <sys/stat.h>
#include <mach-o/dyld.h>
// MARK: - Usage
static void printUsage(const char *prog) {
fprintf(stderr,
"Usage: %s [options] <path> [display-name]\n"
"\n"
"Options:\n"
" --all-users Add sidebar item for every existing user (requires sudo)\n"
" --new-users Install a LaunchAgent so future users get the item (requires sudo)\n"
" --create-dir Create the target directory if it doesn't exist\n"
" --uninstall Remove the LaunchAgent installed by --new-users (requires sudo)\n"
"\n"
"Examples:\n"
" %s ~/NetworkShares NetworkShares\n"
" sudo %s --all-users --new-users --create-dir '~/NetworkShares' NetworkShares\n"
" sudo %s --uninstall '~/NetworkShares'\n",
prog, prog, prog, prog);
}
// MARK: - Helpers
static NSString *sanitizedLabel(NSString *name) {
// Derive a safe label for the LaunchAgent plist filename
NSMutableString *label = [NSMutableString string];
for (NSUInteger i = 0; i < name.length; i++) {
unichar c = [name characterAtIndex:i];
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') || c == '-' || c == '_') {
[label appendFormat:@"%C", c];
}
}
return label.length > 0 ? [label copy] : @"default";
}
static NSString *plistPathForFolder(NSString *folderName) {
NSString *label = sanitizedLabel(folderName);
return [NSString stringWithFormat:@"/Library/LaunchAgents/com.addtosidebar.%@.plist", label];
}
static NSString *executablePath(void) {
// Resolve the path of this running binary
char buf[PATH_MAX];
uint32_t size = sizeof(buf);
if (_NSGetExecutablePath(buf, &size) == 0) {
char resolved[PATH_MAX];
if (realpath(buf, resolved)) {
return [NSString stringWithUTF8String:resolved];
}
}
return @"/usr/local/bin/AddToSidebar";
}
// MARK: - Enumerate real users
static NSArray<NSDictionary *> *enumerateRealUsers(void) {
NSMutableArray *users = [NSMutableArray array];
NSTask *task = [[NSTask alloc] init];
task.launchPath = @"/usr/bin/dscl";
task.arguments = @[@".", @"list", @"/Users", @"UniqueID"];
NSPipe *pipe = [NSPipe pipe];
task.standardOutput = pipe;
task.standardError = [NSFileHandle fileHandleWithNullDevice];
[task launch];
NSData *data = [[pipe fileHandleForReading] readDataToEndOfFile];
[task waitUntilExit];
NSString *output = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
for (NSString *line in [output componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]]) {
NSString *trimmed = [line stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
if (trimmed.length == 0) continue;
// Format: "username UID"
NSArray *parts = [trimmed componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSMutableArray *nonEmpty = [NSMutableArray array];
for (NSString *p in parts) {
if (p.length > 0) [nonEmpty addObject:p];
}
if (nonEmpty.count < 2) continue;
NSString *username = nonEmpty[0];
int uid = [nonEmpty[1] intValue];
// Skip system accounts (UID < 500) and nobody
if (uid < 500 || [username isEqualToString:@"nobody"]) continue;
// Look up home directory
NSTask *readTask = [[NSTask alloc] init];
readTask.launchPath = @"/usr/bin/dscl";
readTask.arguments = @[@".", @"-read", [NSString stringWithFormat:@"/Users/%@", username], @"NFSHomeDirectory"];
NSPipe *readPipe = [NSPipe pipe];
readTask.standardOutput = readPipe;
readTask.standardError = [NSFileHandle fileHandleWithNullDevice];
[readTask launch];
NSData *readData = [[readPipe fileHandleForReading] readDataToEndOfFile];
[readTask waitUntilExit];
NSString *readOutput = [[NSString alloc] initWithData:readData encoding:NSUTF8StringEncoding];
// Output: "NFSHomeDirectory: /Users/foo"
NSRange colonRange = [readOutput rangeOfString:@": "];
if (colonRange.location == NSNotFound) continue;
NSString *homeDir = [[readOutput substringFromIndex:colonRange.location + 2]
stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if (homeDir.length == 0) continue;
[users addObject:@{
@"username": username,
@"uid": @(uid),
@"home": homeDir
}];
}
return [users copy];
}
// MARK: - Single-user sidebar add
static int addToSidebar(NSString *path, NSString *name, BOOL createDir) {
// Expand tilde
path = [path stringByExpandingTildeInPath];
// --create-dir: create directory if missing
if (createDir) {
BOOL isDir;
if (![[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&isDir]) {
NSError *error = nil;
if (![[NSFileManager defaultManager] createDirectoryAtPath:path
withIntermediateDirectories:YES
attributes:nil
error:&error]) {
fprintf(stderr, "Error: Could not create directory %s: %s\n",
[path UTF8String], [[error localizedDescription] UTF8String]);
return 1;
}
printf("Created directory: %s\n", [path UTF8String]);
isDir = YES;
}
}
BOOL isDir;
if (![[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&isDir]) {
fprintf(stderr, "Error: Path does not exist: %s\n", [path UTF8String]);
return 1;
}
NSURL *url = [NSURL fileURLWithPath:path isDirectory:isDir];
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
LSSharedFileListRef list = LSSharedFileListCreate(NULL, kLSSharedFileListFavoriteItems, NULL);
if (!list) {
fprintf(stderr, "Error: Could not access Finder sidebar favorites list\n");
return 1;
}
// Check if already present
UInt32 seed;
CFArrayRef items = LSSharedFileListCopySnapshot(list, &seed);
if (items) {
CFIndex count = CFArrayGetCount(items);
for (CFIndex i = 0; i < count; i++) {
LSSharedFileListItemRef item = (LSSharedFileListItemRef)CFArrayGetValueAtIndex(items, i);
CFURLRef itemURL = LSSharedFileListItemCopyResolvedURL(item, 0, NULL);
if (itemURL) {
if ([(__bridge NSURL *)itemURL isEqual:url]) {
printf("\"%s\" is already in the Finder sidebar.\n", [name UTF8String]);
CFRelease(itemURL);
CFRelease(items);
CFRelease(list);
return 0;
}
CFRelease(itemURL);
}
}
CFRelease(items);
}
// Insert at the end
LSSharedFileListItemRef result = LSSharedFileListInsertItemURL(
list,
kLSSharedFileListItemLast,
(__bridge CFStringRef)name,
NULL,
(__bridge CFURLRef)url,
NULL,
NULL
);
if (result) {
printf("Added \"%s\" to Finder sidebar.\n", [name UTF8String]);
CFRelease(result);
CFRelease(list);
return 0;
} else {
fprintf(stderr, "Error: Failed to add item to sidebar\n");
CFRelease(list);
return 1;
}
#pragma clang diagnostic pop
}
// MARK: - --all-users
static int deployAllUsers(NSString *rawPath, NSString *name, BOOL createDir) {
if (geteuid() != 0) {
fprintf(stderr, "Error: --all-users requires root (use sudo)\n");
return 1;
}
NSArray<NSDictionary *> *users = enumerateRealUsers();
if (users.count == 0) {
fprintf(stderr, "Warning: No real user accounts found (UID >= 500)\n");
return 1;
}
NSString *binary = executablePath();
int failures = 0;
for (NSDictionary *user in users) {
NSString *username = user[@"username"];
int uid = [user[@"uid"] intValue];
NSString *homeDir = user[@"home"];
printf("Deploying for user: %s (UID %d)\n", [username UTF8String], uid);
// Resolve ~ in the path relative to this user's home
NSString *resolvedPath = rawPath;
if ([rawPath hasPrefix:@"~"]) {
resolvedPath = [homeDir stringByAppendingPathComponent:[rawPath substringFromIndex:1]];
// Clean up leading slash from substringFromIndex if path was ~/foo
if ([resolvedPath rangeOfString:@"//"].location != NSNotFound) {
resolvedPath = [resolvedPath stringByReplacingOccurrencesOfString:@"//" withString:@"/"];
}
}
// If --create-dir, create with correct ownership
if (createDir) {
BOOL isDir;
if (![[NSFileManager defaultManager] fileExistsAtPath:resolvedPath isDirectory:&isDir]) {
NSError *error = nil;
if (![[NSFileManager defaultManager] createDirectoryAtPath:resolvedPath
withIntermediateDirectories:YES
attributes:nil
error:&error]) {
fprintf(stderr, " Warning: Could not create directory %s: %s\n",
[resolvedPath UTF8String], [[error localizedDescription] UTF8String]);
failures++;
continue;
}
printf(" Created directory: %s\n", [resolvedPath UTF8String]);
// chown to the user
if (chown([resolvedPath fileSystemRepresentation], uid, 20 /* staff */) != 0) {
fprintf(stderr, " Warning: Could not chown %s to UID %d\n",
[resolvedPath UTF8String], uid);
}
}
}
// Build args for launchctl asuser
NSMutableArray *args = [NSMutableArray array];
[args addObject:@"asuser"];
[args addObject:[NSString stringWithFormat:@"%d", uid]];
[args addObject:binary];
if (createDir) [args addObject:@"--create-dir"];
[args addObject:resolvedPath];
if (name) [args addObject:name];
NSTask *task = [[NSTask alloc] init];
task.launchPath = @"/bin/launchctl";
task.arguments = args;
task.standardOutput = [NSFileHandle fileHandleWithStandardOutput];
task.standardError = [NSFileHandle fileHandleWithStandardError];
@try {
[task launch];
[task waitUntilExit];
if (task.terminationStatus != 0) {
fprintf(stderr, " Warning: launchctl asuser failed for %s (user may not be logged in)\n",
[username UTF8String]);
failures++;
}
} @catch (NSException *e) {
fprintf(stderr, " Warning: Could not run launchctl asuser for %s: %s\n",
[username UTF8String], [[e reason] UTF8String]);
failures++;
}
}
if (failures > 0) {
printf("Completed with %d warning(s). Users not logged in will get the item via LaunchAgent (if --new-users was used).\n", failures);
}
return 0;
}
// MARK: - --new-users
static int installLaunchAgent(NSString *rawPath, NSString *name, BOOL createDir) {
if (geteuid() != 0) {
fprintf(stderr, "Error: --new-users requires root (use sudo)\n");
return 1;
}
NSString *binary = executablePath();
NSString *folderName = name ? name : [[rawPath stringByExpandingTildeInPath] lastPathComponent];
NSString *plistPath = plistPathForFolder(folderName);
NSString *label = [NSString stringWithFormat:@"com.addtosidebar.%@", sanitizedLabel(folderName)];
// Build program arguments
NSMutableArray *programArgs = [NSMutableArray array];
[programArgs addObject:binary];
if (createDir) [programArgs addObject:@"--create-dir"];
[programArgs addObject:rawPath];
if (name) [programArgs addObject:name];
NSDictionary *plist = @{
@"Label": label,
@"ProgramArguments": [programArgs copy],
@"RunAtLoad": @YES,
@"LimitLoadToSessionType": @"Aqua",
};
NSError *error = nil;
NSData *plistData = [NSPropertyListSerialization dataWithPropertyList:plist
format:NSPropertyListXMLFormat_v1_0
options:0
error:&error];
if (!plistData) {
fprintf(stderr, "Error: Could not serialize LaunchAgent plist: %s\n",
[[error localizedDescription] UTF8String]);
return 1;
}
if (![plistData writeToFile:plistPath atomically:YES]) {
fprintf(stderr, "Error: Could not write LaunchAgent to %s\n", [plistPath UTF8String]);
return 1;
}
// Set permissions: root:wheel, 644
chown([plistPath fileSystemRepresentation], 0, 0);
chmod([plistPath fileSystemRepresentation], 0644);
printf("Installed LaunchAgent: %s\n", [plistPath UTF8String]);
return 0;
}
// MARK: - --uninstall
static int uninstallLaunchAgent(NSString *rawPath) {
if (geteuid() != 0) {
fprintf(stderr, "Error: --uninstall requires root (use sudo)\n");
return 1;
}
NSString *folderName = [[rawPath stringByExpandingTildeInPath] lastPathComponent];
NSString *plistPath = plistPathForFolder(folderName);
if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath]) {
fprintf(stderr, "LaunchAgent not found: %s\n", [plistPath UTF8String]);
return 1;
}
NSError *error = nil;
if (![[NSFileManager defaultManager] removeItemAtPath:plistPath error:&error]) {
fprintf(stderr, "Error: Could not remove %s: %s\n",
[plistPath UTF8String], [[error localizedDescription] UTF8String]);
return 1;
}
printf("Removed LaunchAgent: %s\n", [plistPath UTF8String]);
return 0;
}
// MARK: - Main
int main(int argc, const char * argv[]) {
@autoreleasepool {
// Parse flags and positional arguments
BOOL flagAllUsers = NO;
BOOL flagNewUsers = NO;
BOOL flagCreateDir = NO;
BOOL flagUninstall = NO;
NSMutableArray<NSString *> *positional = [NSMutableArray array];
for (int i = 1; i < argc; i++) {
NSString *arg = [NSString stringWithUTF8String:argv[i]];
if ([arg isEqualToString:@"--all-users"]) {
flagAllUsers = YES;
} else if ([arg isEqualToString:@"--new-users"]) {
flagNewUsers = YES;
} else if ([arg isEqualToString:@"--create-dir"]) {
flagCreateDir = YES;
} else if ([arg isEqualToString:@"--uninstall"]) {
flagUninstall = YES;
} else if ([arg isEqualToString:@"--help"] || [arg isEqualToString:@"-h"]) {
printUsage(argv[0]);
return 0;
} else {
[positional addObject:arg];
}
}
if (positional.count < 1) {
printUsage(argv[0]);
return 1;
}
NSString *rawPath = positional[0];
NSString *name = (positional.count >= 2) ? positional[1] : nil;
// --uninstall mode
if (flagUninstall) {
return uninstallLaunchAgent(rawPath);
}
// If no multi-user flags, default display name
if (!name) {
name = [[rawPath stringByExpandingTildeInPath] lastPathComponent];
}
int status = 0;
// --new-users: install LaunchAgent
if (flagNewUsers) {
status = installLaunchAgent(rawPath, name, flagCreateDir);
if (status != 0) return status;
}
// --all-users: deploy to all existing users
if (flagAllUsers) {
status = deployAllUsers(rawPath, name, flagCreateDir);
if (status != 0) return status;
}
// Single-user mode (no multi-user flags)
if (!flagAllUsers && !flagNewUsers) {
status = addToSidebar(rawPath, name, flagCreateDir);
}
return status;
}
}