]> git.cameronkatri.com Git - apple_cmds.git/blob - system_cmds/shutdown.tproj/shutdown.c
Merge branch 'apple'
[apple_cmds.git] / system_cmds / shutdown.tproj / shutdown.c
1 /*
2 * Copyright (c) 1988, 1990, 1993
3 * The Regents of the University of California. All rights reserved.
4 * Portions copyright (c) 2007 Apple Inc. All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * 3. Neither the name of the University nor the names of its contributors
15 * may be used to endorse or promote products derived from this software
16 * without specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
19 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
22 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28 * SUCH DAMAGE.
29 */
30
31 #if 0
32 #ifndef lint
33 static const char copyright[] =
34 "@(#) Copyright (c) 1988, 1990, 1993\n\
35 The Regents of the University of California. All rights reserved.\n";
36 #endif /* not lint */
37
38 #ifndef lint
39 static char sccsid[] = "@(#)shutdown.c 8.4 (Berkeley) 4/28/95";
40 #endif /* not lint */
41 #endif
42 #include <sys/cdefs.h>
43 #ifndef __APPLE__
44 __FBSDID("$FreeBSD: src/sbin/shutdown/shutdown.c,v 1.28 2005/01/25 08:40:51 delphij Exp $");
45 #endif
46
47 #include <sys/param.h>
48 #include <sys/time.h>
49 #include <sys/resource.h>
50 #include <sys/syslog.h>
51
52 #include <ctype.h>
53 #include <err.h>
54 #include <fcntl.h>
55 #include <paths.h>
56 #include <pwd.h>
57 #include <setjmp.h>
58 #include <signal.h>
59 #include <stdio.h>
60 #include <stdlib.h>
61 #include <string.h>
62 #include <unistd.h>
63
64 #ifdef __APPLE__
65 #include <errno.h>
66 #include <util.h>
67 typedef char *kobject_description_t[512];
68 #include <bsm/libbsm.h>
69 #include <bsm/audit_uevents.h>
70 #include <sys/types.h>
71 #include <sys/sysctl.h>
72 #include <vproc.h>
73 #include <vproc_priv.h>
74
75 #if defined(__APPLE__) && !(TARGET_OS_IPHONE && !TARGET_OS_SIMULATOR)
76 #include "kextmanager.h"
77 #include <IOKit/kext/kextmanager_types.h>
78 #endif
79 #include <IOKit/pwr_mgt/IOPMLib.h>
80 #include <mach/mach_port.h> // allocate
81 #include <mach/mach.h> // task_self, etc
82 #include <servers/bootstrap.h> // bootstrap
83 #include <bootstrap_priv.h>
84 #include <reboot2.h>
85 #include <utmpx.h>
86
87 #include "pathnames.h"
88 #endif /* __APPLE__ */
89
90 #include <libiosexec.h>
91
92 int reboot3(int);
93
94 #ifdef DEBUG
95 #undef _PATH_NOLOGIN
96 #define _PATH_NOLOGIN "./nologin"
97 #endif
98
99 #define H *60*60
100 #define M *60
101 #define S *1
102 #define NOLOG_TIME 5*60
103 struct interval {
104 int timeleft, timetowait;
105 } tlist[] = {
106 { 10 H, 5 H },
107 { 5 H, 3 H },
108 { 2 H, 1 H },
109 { 1 H, 30 M },
110 { 30 M, 10 M },
111 { 20 M, 10 M },
112 { 10 M, 5 M },
113 { 5 M, 3 M },
114 { 2 M, 1 M },
115 { 1 M, 30 S },
116 { 30 S, 30 S },
117 { 0 , 0 }
118 };
119 #undef H
120 #undef M
121 #undef S
122
123 static time_t offset, shuttime;
124 #ifdef __APPLE__
125 static int dohalt, doreboot, doups, killflg, oflag;
126 static size_t mbuflen;
127 #else
128 static int dohalt, dopower, doreboot, killflg, mbuflen, oflag;
129 #endif
130 static char mbuf[BUFSIZ];
131 static const char *nosync, *whom;
132 #ifdef __APPLE__
133 static int dosleep;
134 #endif
135
136 void badtime(void);
137 #ifdef __APPLE__
138 void log_and_exec_reboot_or_halt(void);
139 #else
140 void die_you_gravy_sucking_pig_dog(void);
141 #endif
142 void finish(int);
143 void getoffset(char *);
144 void loop(void);
145 void nolog(void);
146 void timeout(int);
147 void timewarn(time_t);
148 void usage(const char *);
149 int audit_shutdown(int);
150 #if defined(__APPLE__) && !(TARGET_OS_IPHONE && !TARGET_OS_SIMULATOR)
151 int reserve_reboot(void);
152 #endif
153
154 extern const char **environ;
155
156 int
157 main(int argc, char **argv)
158 {
159 char *p, *endp;
160 struct passwd *pw;
161 size_t arglen;
162 int ch, len, readstdin;
163
164 #ifndef DEBUG
165 if (geteuid())
166 errx(1, "NOT super-user");
167 #endif
168 nosync = NULL;
169 readstdin = 0;
170 #ifndef __APPLE__
171 while ((ch = getopt(argc, argv, "-hknopr")) != -1)
172 #else
173 while ((ch = getopt(argc, argv, "-hknorsu")) != -1)
174 #endif
175 switch (ch) {
176 case '-':
177 readstdin = 1;
178 break;
179 case 'h':
180 dohalt = 1;
181 break;
182 case 'k':
183 killflg = 1;
184 break;
185 case 'n':
186 nosync = "-n";
187 break;
188 case 'o':
189 oflag = 1;
190 break;
191 #ifndef __APPLE__
192 case 'p':
193 dopower = 1;
194 break;
195 #endif
196 case 'u':
197 doups = 1;
198 break;
199 case 'r':
200 doreboot = 1;
201 break;
202 #ifdef __APPLE__
203 case 's':
204 dosleep = 1;
205 break;
206 #endif
207 case '?':
208 default:
209 usage((char *)NULL);
210 }
211 argc -= optind;
212 argv += optind;
213
214 if (argc < 1)
215 usage((char *)NULL);
216
217 #ifndef __APPLE__
218 if (killflg + doreboot + dohalt + dopower > 1)
219 usage("incompatible switches -h, -k, -p and -r");
220
221 if (oflag && !(dohalt || dopower || doreboot))
222 usage("-o requires -h, -p or -r");
223
224 if (nosync != NULL && !oflag)
225 usage("-n requires -o");
226 #else /* !__APPLE__ */
227 if (killflg + doreboot + dohalt + dosleep > 1)
228 usage("incompatible switches -h, -k, -r, and -s");
229
230 if (!(dohalt || doreboot || dosleep || killflg))
231 usage("-h, -r, -s, or -k is required");
232
233 if (doups && !dohalt)
234 usage("-u requires -h");
235 #endif /* !__APPLE__ */
236
237 getoffset(*argv++);
238
239 if (*argv) {
240 for (p = mbuf, len = sizeof(mbuf); *argv; ++argv) {
241 arglen = strlen(*argv);
242 if ((len -= arglen) <= 2)
243 break;
244 if (p != mbuf)
245 *p++ = ' ';
246 memmove(p, *argv, arglen);
247 p += arglen;
248 }
249 *p = '\n';
250 *++p = '\0';
251 }
252
253 if (readstdin) {
254 p = mbuf;
255 endp = mbuf + sizeof(mbuf) - 2;
256 for (;;) {
257 if (!fgets(p, (int)(endp - p + 1), stdin))
258 break;
259 for (; *p && p < endp; ++p);
260 if (p == endp) {
261 *p = '\n';
262 *++p = '\0';
263 break;
264 }
265 }
266 }
267 mbuflen = strlen(mbuf);
268
269 if (offset)
270 (void)printf("Shutdown at %.24s.\n", ctime(&shuttime));
271 else
272 (void)printf("Shutdown NOW!\n");
273
274 if (!(whom = getlogin()))
275 whom = (pw = getpwuid(getuid())) ? pw->pw_name : "???";
276
277 #ifdef DEBUG
278 audit_shutdown(0);
279 (void)putc('\n', stdout);
280 #else
281 (void)setpriority(PRIO_PROCESS, 0, PRIO_MIN);
282 #ifdef __APPLE__
283 if (offset) {
284 #else
285 {
286 #endif
287 int forkpid;
288
289 forkpid = fork();
290 if (forkpid == -1) {
291 audit_shutdown(1);
292 err(1, "fork");
293 }
294 if (forkpid)
295 errx(0, "[pid %d]", forkpid);
296 #ifdef __APPLE__
297 /* 5863185: reboot2() needs to talk to launchd. */
298 if (_vprocmgr_detach_from_console(0) != NULL)
299 warnx("can't detach from console");
300 #endif /* __APPLE__ */
301 }
302 audit_shutdown(0);
303 setsid();
304 #endif
305 openlog("shutdown", LOG_CONS, LOG_AUTH);
306 loop();
307 return(0);
308 }
309
310 void
311 loop(void)
312 {
313 struct interval *tp;
314 u_int sltime;
315 int logged;
316
317 if (offset <= NOLOG_TIME) {
318 logged = 1;
319 nolog();
320 }
321 else
322 logged = 0;
323 tp = tlist;
324 if (tp->timeleft < offset)
325 (void)sleep((u_int)(offset - tp->timeleft));
326 else {
327 while (tp->timeleft && offset < tp->timeleft)
328 ++tp;
329 /*
330 * Warn now, if going to sleep more than a fifth of
331 * the next wait time.
332 */
333 if ((sltime = (u_int)(offset - tp->timeleft))) {
334 if (sltime > (tp->timetowait / 5))
335 timewarn(offset);
336 (void)sleep(sltime);
337 }
338 }
339 for (;; ++tp) {
340 timewarn(tp->timeleft);
341 if (!logged && tp->timeleft <= NOLOG_TIME) {
342 logged = 1;
343 nolog();
344 }
345 (void)sleep((u_int)tp->timetowait);
346 if (!tp->timeleft)
347 break;
348 }
349 #ifdef __APPLE__
350 log_and_exec_reboot_or_halt();
351 #else
352 die_you_gravy_sucking_pig_dog();
353 #endif
354 }
355
356 static jmp_buf alarmbuf;
357
358 static const char *restricted_environ[] = {
359 "PATH=" _PATH_STDPATH,
360 NULL
361 };
362
363 void
364 timewarn(time_t timeleft)
365 {
366 static int first;
367 static char hostname[MAXHOSTNAMELEN + 1];
368 FILE *pf;
369 char wcmd[MAXPATHLEN + 4];
370
371 /* wall is sometimes missing, e.g. on install media */
372 if (access(_PATH_WALL, X_OK) == -1) return;
373
374 if (!first++)
375 (void)gethostname(hostname, sizeof(hostname));
376
377 /* undoc -n option to wall suppresses normal wall banner */
378 (void)snprintf(wcmd, sizeof(wcmd), "%s -n", _PATH_WALL);
379 environ = restricted_environ;
380 if (!(pf = popen(wcmd, "w"))) {
381 syslog(LOG_ERR, "shutdown: can't find %s: %m", _PATH_WALL);
382 return;
383 }
384
385 (void)fprintf(pf,
386 "\007*** %sSystem shutdown message from %s@%s ***\007\n",
387 timeleft ? "": "FINAL ", whom, hostname);
388
389 if (timeleft > 10*60)
390 (void)fprintf(pf, "System going down at %5.5s\n\n",
391 ctime(&shuttime) + 11);
392 else if (timeleft > 59)
393 (void)fprintf(pf, "System going down in %ld minute%s\n\n",
394 timeleft / 60, (timeleft > 60) ? "s" : "");
395 else if (timeleft)
396 (void)fprintf(pf, "System going down in 30 seconds\n\n");
397 else
398 (void)fprintf(pf, "System going down IMMEDIATELY\n\n");
399
400 if (mbuflen)
401 (void)fwrite(mbuf, sizeof(*mbuf), mbuflen, pf);
402
403 /*
404 * play some games, just in case wall doesn't come back
405 * probably unnecessary, given that wall is careful.
406 */
407 if (!setjmp(alarmbuf)) {
408 (void)signal(SIGALRM, timeout);
409 (void)alarm((u_int)30);
410 (void)pclose(pf);
411 (void)alarm((u_int)0);
412 (void)signal(SIGALRM, SIG_DFL);
413 }
414 }
415
416 void
417 timeout(int signo __unused)
418 {
419 longjmp(alarmbuf, 1);
420 }
421
422 void
423 #ifdef __APPLE__
424 log_and_exec_reboot_or_halt()
425 #else
426 die_you_gravy_sucking_pig_dog()
427 #endif
428 {
429 #if defined(__APPLE__) && !(TARGET_OS_IPHONE && !TARGET_OS_SIMULATOR)
430 if ((errno = reserve_reboot())) {
431 warn("couldn't lock for reboot");
432 finish(0);
433 }
434 #else
435 char *empty_environ[] = { NULL };
436 #endif
437
438 syslog(LOG_NOTICE, "%s%s by %s: %s",
439 #ifndef __APPLE__
440 doreboot ? "reboot" : dohalt ? "halt" : dopower ? "power-down" :
441 #else
442 doreboot ? "reboot" : dohalt ? "halt" : dosleep ? "sleep" :
443 #endif
444 "shutdown", doups?" with UPS delay":"", whom, mbuf);
445 #ifndef __APPLE__
446 (void)sleep(2);
447 #endif
448
449 (void)printf("\r\nSystem shutdown time has arrived\007\007\r\n");
450 if (killflg) {
451 (void)printf("\rbut you'll have to do it yourself\r\n");
452 exit(0);
453 }
454 #ifdef DEBUG
455 if (doreboot)
456 (void)printf("reboot");
457 else if (dohalt)
458 (void)printf("halt");
459 #ifndef __APPLE__
460 else if (dopower)
461 (void)printf("power-down");
462 if (nosync != NULL)
463 (void)printf(" no sync");
464 #else
465 else if (dosleep)
466 (void)printf("sleep");
467 #endif
468 (void)printf("\nkill -HUP 1\n");
469 #else
470 #ifdef __APPLE__
471 if (dosleep) {
472 mach_port_t mp;
473 io_connect_t fb;
474 kern_return_t kr = IOMasterPort(bootstrap_port, &mp);
475 if (kr == kIOReturnSuccess) {
476 fb = IOPMFindPowerManagement(mp);
477 if (fb != IO_OBJECT_NULL) {
478 IOReturn err = IOPMSleepSystem(fb);
479 if (err != kIOReturnSuccess) {
480 fprintf(stderr, "shutdown: sleep failed (0x%08x)\n", err);
481 kr = -1;
482 }
483 }
484 }
485 } else {
486 int howto = 0;
487
488 #if defined(__APPLE__)
489 {
490 struct utmpx utx;
491 bzero(&utx, sizeof(utx));
492 utx.ut_type = SHUTDOWN_TIME;
493 gettimeofday(&utx.ut_tv, NULL);
494 pututxline(&utx);
495 }
496 #else
497 logwtmp("~", "shutdown", "");
498 #endif
499
500 if (dohalt) howto |= RB_HALT;
501 if (doups) howto |= RB_UPSDELAY;
502 if (nosync) howto |= RB_NOSYNC;
503
504 // launchd(8) handles reboot. This call returns NULL on success.
505 if (reboot3(howto)) {
506 syslog(LOG_ERR, "shutdown: launchd reboot failed.");
507 }
508 }
509 #else /* __APPLE__ */
510 if (!oflag) {
511 (void)kill(1, doreboot ? SIGINT : /* reboot */
512 dohalt ? SIGUSR1 : /* halt */
513 dopower ? SIGUSR2 : /* power-down */
514 SIGTERM); /* single-user */
515 } else {
516 if (doreboot) {
517 execle(_PATH_REBOOT, "reboot", "-l", nosync,
518 (char *)NULL, empty_environ);
519 syslog(LOG_ERR, "shutdown: can't exec %s: %m.",
520 _PATH_REBOOT);
521 warn(_PATH_REBOOT);
522 }
523 else if (dohalt) {
524 execle(_PATH_HALT, "halt", "-l", nosync,
525 (char *)NULL, empty_environ);
526 syslog(LOG_ERR, "shutdown: can't exec %s: %m.",
527 _PATH_HALT);
528 warn(_PATH_HALT);
529 }
530 else if (dopower) {
531 execle(_PATH_HALT, "halt", "-l", "-p", nosync,
532 (char *)NULL, empty_environ);
533 syslog(LOG_ERR, "shutdown: can't exec %s: %m.",
534 _PATH_HALT);
535 warn(_PATH_HALT);
536 }
537 (void)kill(1, SIGTERM); /* to single-user */
538 }
539 #endif /* __APPLE__ */
540 #endif
541 finish(0);
542 }
543
544 #define ATOI2(p) (p[0] - '0') * 10 + (p[1] - '0'); p += 2;
545
546 void
547 getoffset(char *timearg)
548 {
549 struct tm *lt;
550 char *p;
551 time_t now;
552 int this_year;
553
554 (void)time(&now);
555
556 if (!strcasecmp(timearg, "now")) { /* now */
557 offset = 0;
558 shuttime = now;
559 return;
560 }
561
562 if (*timearg == '+') { /* +minutes */
563 if (!isdigit(*++timearg))
564 badtime();
565 if ((offset = atoi(timearg) * 60) < 0)
566 badtime();
567 shuttime = now + offset;
568 return;
569 }
570
571 /* handle hh:mm by getting rid of the colon */
572 for (p = timearg; *p; ++p)
573 if (!isascii(*p) || !isdigit(*p)) {
574 if (*p == ':' && strlen(p) == 3) {
575 p[0] = p[1];
576 p[1] = p[2];
577 p[2] = '\0';
578 }
579 else
580 badtime();
581 }
582
583 unsetenv("TZ"); /* OUR timezone */
584 lt = localtime(&now); /* current time val */
585
586 switch(strlen(timearg)) {
587 case 10:
588 this_year = lt->tm_year;
589 lt->tm_year = ATOI2(timearg);
590 /*
591 * check if the specified year is in the next century.
592 * allow for one year of user error as many people will
593 * enter n - 1 at the start of year n.
594 */
595 if (lt->tm_year < (this_year % 100) - 1)
596 lt->tm_year += 100;
597 /* adjust for the year 2000 and beyond */
598 lt->tm_year += (this_year - (this_year % 100));
599 /* FALLTHROUGH */
600 case 8:
601 lt->tm_mon = ATOI2(timearg);
602 if (--lt->tm_mon < 0 || lt->tm_mon > 11)
603 badtime();
604 /* FALLTHROUGH */
605 case 6:
606 lt->tm_mday = ATOI2(timearg);
607 if (lt->tm_mday < 1 || lt->tm_mday > 31)
608 badtime();
609 /* FALLTHROUGH */
610 case 4:
611 lt->tm_hour = ATOI2(timearg);
612 if (lt->tm_hour < 0 || lt->tm_hour > 23)
613 badtime();
614 lt->tm_min = ATOI2(timearg);
615 if (lt->tm_min < 0 || lt->tm_min > 59)
616 badtime();
617 lt->tm_sec = 0;
618 if ((shuttime = mktime(lt)) == -1)
619 badtime();
620 if ((offset = shuttime - now) < 0)
621 errx(1, "that time is already past.");
622 break;
623 default:
624 badtime();
625 }
626 }
627
628 #define NOMSG "\n\nNO LOGINS: System going down at "
629 void
630 nolog(void)
631 {
632 int logfd;
633 char *ct;
634
635 (void)unlink(_PATH_NOLOGIN); /* in case linked to another file */
636 (void)signal(SIGINT, finish);
637 (void)signal(SIGHUP, finish);
638 (void)signal(SIGQUIT, finish);
639 (void)signal(SIGTERM, finish);
640 if ((logfd = open(_PATH_NOLOGIN, O_WRONLY|O_CREAT|O_TRUNC,
641 0664)) >= 0) {
642 (void)write(logfd, NOMSG, sizeof(NOMSG) - 1);
643 ct = ctime(&shuttime);
644 (void)write(logfd, ct + 11, 5);
645 (void)write(logfd, "\n\n", 2);
646 (void)write(logfd, mbuf, strlen(mbuf));
647 (void)close(logfd);
648 }
649 }
650
651 void
652 finish(int signo __unused)
653 {
654 if (!killflg)
655 (void)unlink(_PATH_NOLOGIN);
656 exit(0);
657 }
658
659 void
660 badtime(void)
661 {
662 errx(1, "bad time format");
663 }
664
665 void
666 usage(const char *cp)
667 {
668 if (cp != NULL)
669 warnx("%s", cp);
670 (void)fprintf(stderr,
671 #ifdef __APPLE__
672 "usage: shutdown [-] [-h [-u] [-n] | -r [-n] | -s | -k]"
673 #else
674 "usage: shutdown [-] [-h | -p | -r | -k] [-o [-n]]"
675 #endif
676 " time [warning-message ...]\n");
677 exit(1);
678 }
679
680 /*
681 * The following tokens are included in the audit record for shutdown
682 * header
683 * subject
684 * return
685 */
686 int
687 audit_shutdown(int exitstatus)
688 {
689 int aufd;
690 token_t *tok;
691 long au_cond;
692
693 /* If we are not auditing, don't cut an audit record; just return */
694 if (auditon(A_GETCOND, &au_cond, sizeof(long)) < 0) {
695 fprintf(stderr, "shutdown: Could not determine audit condition\n");
696 return 0;
697 }
698 if (au_cond == AUC_NOAUDIT)
699 return 0;
700
701 if((aufd = au_open()) == -1) {
702 fprintf(stderr, "shutdown: Audit Error: au_open() failed\n");
703 exit(1);
704 }
705
706 /* The subject that performed the operation */
707 if((tok = au_to_me()) == NULL) {
708 fprintf(stderr, "shutdown: Audit Error: au_to_me() failed\n");
709 exit(1);
710 }
711 au_write(aufd, tok);
712
713 /* success and failure status */
714 if((tok = au_to_return32(exitstatus, errno)) == NULL) {
715 fprintf(stderr, "shutdown: Audit Error: au_to_return32() failed\n");
716 exit(1);
717 }
718 au_write(aufd, tok);
719
720 if(au_close(aufd, 1, AUE_shutdown) == -1) {
721 fprintf(stderr, "shutdown: Audit Error: au_close() failed\n");
722 exit(1);
723 }
724 return 1;
725 }
726
727 #if defined(__APPLE__) && !(TARGET_OS_IPHONE && !TARGET_OS_SIMULATOR)
728
729 static bool
730 kextdDisabled(void)
731 {
732 uint32_t disabled = 0;
733 size_t sizeOfDisabled = sizeof(disabled);
734 if (sysctlbyname("hw.use_kernelmanagerd", &disabled, &sizeOfDisabled, NULL, 0) != 0) {
735 return false;
736 }
737 return (disabled != 0);
738 }
739
740
741 // XX copied from reboot.tproj/reboot.c; it would be nice to share the code
742
743 #define WAITFORLOCK 1
744 /*
745 * contact kextd to lock for reboot
746 */
747 int
748 reserve_reboot(void)
749 {
750 int rval = ELAST + 1;
751 kern_return_t macherr = KERN_FAILURE;
752 mach_port_t kxport, tport = MACH_PORT_NULL, myport = MACH_PORT_NULL;
753 int busyStatus = ELAST + 1;
754 mountpoint_t busyVol;
755
756 if (kextdDisabled()) {
757 /* no need to talk with kextd if it's not running */
758 return 0;
759 }
760
761 macherr = bootstrap_look_up2(bootstrap_port, KEXTD_SERVER_NAME, &kxport, 0, BOOTSTRAP_PRIVILEGED_SERVER);
762 if (macherr) goto finish;
763
764 // allocate a port to pass to kextd (in case we die)
765 tport = mach_task_self();
766 if (tport == MACH_PORT_NULL) goto finish;
767 macherr = mach_port_allocate(tport, MACH_PORT_RIGHT_RECEIVE, &myport);
768 if (macherr) goto finish;
769
770 // try to lock for reboot
771 macherr = kextmanager_lock_reboot(kxport, myport, !WAITFORLOCK, busyVol,
772 &busyStatus);
773 if (macherr) goto finish;
774
775 if (busyStatus == EBUSY) {
776 warnx("%s is busy updating; waiting for lock", busyVol);
777 macherr = kextmanager_lock_reboot(kxport, myport, WAITFORLOCK,
778 busyVol, &busyStatus);
779 if (macherr) goto finish;
780 }
781
782 if (busyStatus == EALREADY) {
783 // reboot already in progress
784 rval = 0;
785 } else {
786 rval = busyStatus;
787 }
788
789 finish:
790 // in general, we want to err on the side of allowing the reboot
791 if (macherr) {
792 if (macherr != BOOTSTRAP_UNKNOWN_SERVICE)
793 warnx("WARNING: couldn't lock kext manager for reboot: %s",
794 mach_error_string(macherr));
795 rval = 0;
796 }
797 // unless we got the lock, clean up our port
798 if (busyStatus != 0 && myport != MACH_PORT_NULL)
799 mach_port_mod_refs(tport, myport, MACH_PORT_RIGHT_RECEIVE, -1);
800
801 return rval;
802 }
803 #endif /* __APPLE__ */