forked from BOINC/boinc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAddRemoveUser.cpp
506 lines (443 loc) · 18.2 KB
/
AddRemoveUser.cpp
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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
// This file is part of BOINC.
// http://boinc.berkeley.edu
// Copyright (C) 2009 University of California
//
// BOINC is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any later version.
//
// BOINC is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with BOINC. If not, see <http://www.gnu.org/licenses/>.
/* AddRemoveUser.cpp */
#define VERBOSE 0
#include <Carbon/Carbon.h>
#include <unistd.h> // getlogin
#include <sys/types.h> // getpwname, getpwuid, getuid
#include <pwd.h> // getpwname, getpwuid, getuid
#include <grp.h> // getgrnam
void printUsage(void);
Boolean SetLoginItemOSAScript(Boolean addLogInItem, char *userName);
static char * PersistentFGets(char *buf, size_t buflen, FILE *f);
static int compareOSVersionTo(int toMajor, int toMinor);
OSErr FindProcess (OSType typeToFind, OSType creatorToFind, ProcessSerialNumberPtr processSN);
static void SleepTicks(UInt32 ticksToSleep);
static OSErr QuitOneProcess(OSType signature);
int main(int argc, char *argv[])
{
Boolean AddUsers = false;
Boolean SetSavers = false;
Boolean isBMGroupMember, isBPGroupMember;
Boolean saverIsSet = false;
passwd *pw;
uid_t saved_uid;
group grpBOINC_master, *grpBOINC_masterPtr;
group grpBOINC_project, *grpBOINC_projectPtr;
char bmBuf[32768];
char bpBuf[32768];
short index, i;
char *p;
char s[256];
FILE *f;
OSStatus err;
#ifndef _DEBUG
if (getuid() != 0) {
printf("This program must be run as root\n");
printUsage();
return 0;
}
#endif
if (argc < 3) {
printUsage();
return 0;
}
if (strcmp(argv[1], "-a") == 0) {
AddUsers = true;
} else if (strcmp(argv[1], "-s") == 0) {
AddUsers = true;
SetSavers = true;
} else if (strcmp(argv[1], "-r") != 0) {
printUsage();
return 0;
}
err = getgrnam_r("boinc_master", &grpBOINC_master, bmBuf, sizeof(bmBuf), &grpBOINC_masterPtr);
if (err) { // Should never happen unless buffer too small
puts("getgrnam(\"boinc_master\") failed\n");
return -1;
}
err = getgrnam_r("boinc_project", &grpBOINC_project, bpBuf, sizeof(bpBuf), &grpBOINC_projectPtr);
if (err) { // Should never happen unless buffer too small
puts("getgrnam(\"boinc_project\") failed\n");
return -1;
}
for (index=2; index<argc; index++) {
// getpwnam works with either the full / login name (pw->pw_gecos)
// or the short / Posix name (pw->pw_name)
pw = getpwnam(argv[index]);
if (pw == NULL) {
printf("User %s not found.\n", argv[index]);
continue;
}
isBMGroupMember = false;
i = 0;
while ((p = grpBOINC_master.gr_mem[i]) != NULL) { // Step through all users in group boinc_master
if (strcmp(p, pw->pw_name) == 0) { // Only the short / Posix names are in the list
// User is a member of group boinc_master
isBMGroupMember = true;
break;
}
++i;
}
isBPGroupMember = false;
i = 0;
while ((p = grpBOINC_project.gr_mem[i]) != NULL) { // Step through all users in group boinc_project
if (strcmp(p, pw->pw_name) == 0) { // Only the short / Posix names are in the list
// User is a member of group boinc_master
isBPGroupMember = true;
break;
}
++i;
}
if ((!isBMGroupMember) && AddUsers) {
sprintf(s, "dscl . -merge /groups/boinc_master GroupMembership %s", pw->pw_name);
system(s);
}
if ((!isBPGroupMember) && AddUsers) {
sprintf(s, "dscl . -merge /groups/boinc_project GroupMembership %s", pw->pw_name);
system(s);
}
if (isBMGroupMember && (!AddUsers)) {
sprintf(s, "dscl . -delete /Groups/boinc_master GroupMembership %s", pw->pw_name);
system(s);
}
if (isBPGroupMember && (!AddUsers)) {
sprintf(s, "dscl . -delete /Groups/boinc_project GroupMembership %s", pw->pw_name);
system(s);
}
// Set or remove login item for this user
SetLoginItemOSAScript(AddUsers, pw->pw_name);
saved_uid = geteuid();
seteuid(pw->pw_uid); // Temporarily set effective uid to this user
if (compareOSVersionTo(10, 6) < 0) {
sprintf(s, "sudo -u %s defaults -currentHost read com.apple.screensaver moduleName",
pw->pw_name);
} else {
sprintf(s, "sudo -u %s defaults -currentHost read com.apple.screensaver moduleDict -dict",
pw->pw_name);
}
f = popen(s, "r");
if (f) {
saverIsSet = false;
while (PersistentFGets(s, sizeof(s), f)) {
if (strstr(s, "BOINCSaver")) {
saverIsSet = true;
break;
}
}
pclose(f);
}
if ((!saverIsSet) && SetSavers) {
if (compareOSVersionTo(10, 6) < 0) {
sprintf(s, "sudo -u %s defaults -currentHost write com.apple.screensaver moduleName BOINCSaver",
pw->pw_name);
system(s);
sprintf(s, "sudo -u %s defaults -currentHost write com.apple.screensaver modulePath \"/Library/Screen Savers/BOINCSaver.saver\"",
pw->pw_name);
system(s);
} else {
sprintf(s, "sudo -u %s defaults -currentHost write com.apple.screensaver moduleDict -dict moduleName BOINCSaver path \"/Library/Screen Savers/BOINCSaver.saver\"",
pw->pw_name);
system(s);
}
}
if (saverIsSet && (!AddUsers)) {
if (compareOSVersionTo(10, 6) < 0) {
sprintf(s, "sudo -u %s defaults -currentHost write com.apple.screensaver moduleName Flurry",
pw->pw_name);
system(s);
sprintf(s, "sudo -u %s defaults -currentHost write com.apple.screensaver modulePath \"/System/Library/Screen Savers/Flurry.saver\"",
pw->pw_name);
system(s);
} else {
sprintf(s, "sudo -u %s defaults -currentHost write com.apple.screensaver moduleDict -dict moduleName Flurry path \"/System/Library/Screen Savers/Flurry.saver\"",
pw->pw_name);
system(s);
}
}
seteuid(saved_uid); // Set effective uid back to privileged user
}
printf("WARNING: Changes may require a system restart to take effect.\n");
return 0;
}
void printUsage() {
printf("Usage: sudo AddRemoveUser [-a | -s | -r] [user1 [user2 [user3...]]]\n");
printf(" -a: add users to those with permission to run BOINC Manager.\n");
printf(" -s: same as -a plus set users' screensaver to BOINC.\n");
printf(" -r: remove users' permission to run BOINC Manager, and \n");
printf(" if their screensaver was set to BOINC change it to Flurry.\n");
printf("\n");
}
enum {
kSystemEventsCreator = 'sevs'
};
Boolean SetLoginItemOSAScript(Boolean addLogInItem, char *userName)
{
int i, j;
char cmd[2048];
char systemEventsPath[1024];
ProcessSerialNumber SystemEventsPSN;
FSRef appRef;
OSErr err, err2;
#if VERBOSE
fprintf(stderr, "Adjusting login items for user %s\n", userName);
fflush(stderr);
#endif
// We must launch the System Events application for the target user
err = FindProcess ('APPL', kSystemEventsCreator, &SystemEventsPSN);
if (err == noErr) {
// Find SystemEvents process. If found, quit it in case
// it is running under a different user.
#if VERBOSE
fprintf(stderr, "Telling System Events to quit (at start of SetLoginItemOSAScript)\n");
fflush(stderr);
#endif
err = QuitOneProcess(kSystemEventsCreator);
if (err != noErr) {
fprintf(stderr, "QuitOneProcess(kSystemEventsCreator) returned error %d \n", (int) err);
fflush(stderr);
}
// Wait for the process to be gone
for (i=0; i<50; ++i) { // 5 seconds max delay
SleepTicks(6); // 6 Ticks == 1/10 second
err = FindProcess ('APPL', kSystemEventsCreator, &SystemEventsPSN);
if (err != noErr) break;
}
if (i >= 50) {
fprintf(stderr, "Failed to make System Events quit\n");
fflush(stderr);
err = noErr;
goto cleanupSystemEvents;
}
sleep(4);
}
err = LSFindApplicationForInfo(kSystemEventsCreator, NULL, NULL, &appRef, NULL);
if (err != noErr) {
fprintf(stderr, "LSFindApplicationForInfo(kSystemEventsCreator) returned error %d \n", (int) err);
fflush(stderr);
goto cleanupSystemEvents;
} else {
FSRefMakePath(&appRef, (UInt8*)systemEventsPath, sizeof(systemEventsPath));
#if VERBOSE
fprintf(stderr, "SystemEvents is at %s\n", systemEventsPath);
fprintf(stderr, "Launching SystemEvents for user %s\n", userName);
fflush(stderr);
#endif
for (j=0; j<5; ++j) {
sprintf(cmd, "sudo -u \"%s\" \"%s/Contents/MacOS/System Events\" &", userName, systemEventsPath);
err = system(cmd);
if (err) {
fprintf(stderr, "Command: %s returned error %d (try %d of 5)\n", cmd, (int) err, j);
}
// Wait for the process to start
for (i=0; i<50; ++i) { // 5 seconds max delay
SleepTicks(6); // 6 Ticks == 1/10 second
err = FindProcess ('APPL', kSystemEventsCreator, &SystemEventsPSN);
if (err == noErr) break;
}
if (i < 50) break; // Exit j loop on success
}
if (j >= 5) {
fprintf(stderr, "Failed to launch System Events for user %s\n", userName);
fflush(stderr);
err = noErr;
goto cleanupSystemEvents;
}
}
sleep(2);
#if VERBOSE
fprintf(stderr, "Deleting any login items containing BOINCManager for user %s\n", userName);
fflush(stderr);
#endif
sprintf(cmd, "sudo -u \"%s\" osascript -e 'tell application \"System Events\"' -e 'delete (every login item whose path contains \"BOINCManager\")' -e 'end tell'", userName);
err = system(cmd);
if (err) {
fprintf(stderr, "Command: %s\n", cmd);
fprintf(stderr, "Delete login item containing \"BOINCManager\" returned error %d\n", err);
fflush(stderr);
}
if (addLogInItem == false) {
err = noErr;
goto cleanupSystemEvents;
}
fprintf(stdout, "Making new login item %s for user %s\n", "BOINCManager", userName);
fflush(stderr);
sprintf(cmd, "sudo -u \"%s\" osascript -e 'tell application \"System Events\"' -e 'make new login item at end with properties {path:\"/Applications/BOINCManager.app\", hidden:true, name:\"BOINCManager\"}' -e 'end tell'", userName);
err = system(cmd);
if (err) {
fprintf(stderr, "Command: %s\n", cmd);
printf("Make login item for %s returned error %d\n", "/Applications/BOINCManager.app", err);
}
fflush(stderr);
cleanupSystemEvents:
// Clean up in case this was our last user
#if VERBOSE
fprintf(stderr, "Telling System Events to quit (at end of SetLoginItemOSAScript)\n");
fflush(stderr);
#endif
err2 = QuitOneProcess(kSystemEventsCreator);
if (err2 != noErr) {
fprintf(stderr, "QuitOneProcess(kSystemEventsCreator) returned error %d \n", (int) err2);
fflush(stderr);
}
// Wait for the process to be gone
for (i=0; i<50; ++i) { // 5 seconds max delay
SleepTicks(6); // 6 Ticks == 1/10 second
err2 = FindProcess ('APPL', kSystemEventsCreator, &SystemEventsPSN);
if (err2 != noErr) break;
}
if (i >= 50) {
fprintf(stderr, "Failed to make System Events quit\n");
fflush(stderr);
}
sleep(4);
return (err == noErr);
}
static char * PersistentFGets(char *buf, size_t buflen, FILE *f) {
char *p = buf;
size_t len = buflen;
size_t datalen = 0;
*buf = '\0';
while (datalen < (buflen - 1)) {
fgets(p, len, f);
if (feof(f)) break;
if (ferror(f) && (errno != EINTR)) break;
if (strchr(buf, '\n')) break;
datalen = strlen(buf);
p = buf + datalen;
len -= datalen;
}
return (buf[0] ? buf : NULL);
}
static int compareOSVersionTo(int toMajor, int toMinor) {
SInt32 major, minor;
OSStatus err = noErr;
err = Gestalt(gestaltSystemVersionMajor, &major);
if (err != noErr) {
fprintf(stderr, "Gestalt(gestaltSystemVersionMajor) returned error %ld\n", err);
fflush(stderr);
return -1; // gestaltSystemVersionMajor selector was not available before OS 10.4
}
if (major < toMajor) return -1;
if (major > toMajor) return 1;
err = Gestalt(gestaltSystemVersionMinor, &minor);
if (err != noErr) {
fprintf(stderr, "Gestalt(gestaltSystemVersionMinor) returned error %ld\n", err);
fflush(stderr);
return -1; // gestaltSystemVersionMajor selector was not available before OS 10.4
}
if (minor < toMinor) return -1;
if (minor > toMinor) return 1;
return 0;
}
// ---------------------------------------------------------------------------
/* This runs through the process list looking for the indicated application */
/* Searches for process by file type and signature (creator code) */
// ---------------------------------------------------------------------------
OSErr FindProcess (OSType typeToFind, OSType creatorToFind, ProcessSerialNumberPtr processSN)
{
ProcessInfoRec tempInfo;
FSSpec procSpec;
Str31 processName;
OSErr myErr = noErr;
/* null out the PSN so we're starting at the beginning of the list */
processSN->lowLongOfPSN = kNoProcess;
processSN->highLongOfPSN = kNoProcess;
/* initialize the process information record */
tempInfo.processInfoLength = sizeof(ProcessInfoRec);
tempInfo.processName = processName;
tempInfo.processAppSpec = &procSpec;
/* loop through all the processes until we */
/* 1) find the process we want */
/* 2) error out because of some reason (usually, no more processes) */
do {
myErr = GetNextProcess(processSN);
if (myErr == noErr)
GetProcessInformation(processSN, &tempInfo);
}
while ((tempInfo.processSignature != creatorToFind || tempInfo.processType != typeToFind) &&
myErr == noErr);
return(myErr);
}
// Uses usleep to sleep for full duration even if a signal is received
static void SleepTicks(UInt32 ticksToSleep) {
UInt32 endSleep, timeNow, ticksRemaining;
timeNow = TickCount();
ticksRemaining = ticksToSleep;
endSleep = timeNow + ticksToSleep;
while ( (timeNow < endSleep) && (ticksRemaining <= ticksToSleep) ) {
usleep(16667 * ticksRemaining);
timeNow = TickCount();
ticksRemaining = endSleep - timeNow;
}
}
static OSErr QuitOneProcess(OSType signature) {
bool done = false;
ProcessSerialNumber thisPSN;
ProcessInfoRec thisPIR;
OSErr err = noErr;
Str63 thisProcessName;
AEAddressDesc thisPSNDesc;
AppleEvent thisQuitEvent, thisReplyEvent;
thisPIR.processInfoLength = sizeof (ProcessInfoRec);
thisPIR.processName = thisProcessName;
thisPIR.processAppSpec = nil;
thisPSN.highLongOfPSN = 0;
thisPSN.lowLongOfPSN = kNoProcess;
while (done == false) {
err = GetNextProcess(&thisPSN);
if (err == procNotFound) {
done = true; // Finished stepping through all running applications.
err = noErr; // Success
} else {
err = GetProcessInformation(&thisPSN,&thisPIR);
if (err != noErr)
goto bail;
if (thisPIR.processSignature == signature) { // is it our target process?
err = AECreateDesc(typeProcessSerialNumber, (Ptr)&thisPSN,
sizeof(thisPSN), &thisPSNDesc);
if (err != noErr)
goto bail;
// Create the 'quit' Apple event for this process.
err = AECreateAppleEvent(kCoreEventClass, kAEQuitApplication, &thisPSNDesc,
kAutoGenerateReturnID, kAnyTransactionID, &thisQuitEvent);
if (err != noErr) {
AEDisposeDesc (&thisPSNDesc);
goto bail; // don't know how this could happen, but limp gamely onward
}
// send the event
err = AESend(&thisQuitEvent, &thisReplyEvent, kAEWaitReply,
kAENormalPriority, kAEDefaultTimeout, 0L, 0L);
AEDisposeDesc (&thisQuitEvent);
AEDisposeDesc (&thisPSNDesc);
if (err != noErr)
goto bail;
#if 0
if (err == errAETimeout) {
pid_t thisPID;
err = GetProcessPID(&thisPSN , &thisPID);
if (err == noErr)
err = kill(thisPID, SIGKILL);
}
#endif
continue; // There can be multiple instances of the Manager
}
}
}
bail:
return err;
}