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.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
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.
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
33 static const char copyright
[] =
34 "@(#) Copyright (c) 1988, 1990, 1993\n\
35 The Regents of the University of California. All rights reserved.\n";
39 static char sccsid
[] = "@(#)shutdown.c 8.4 (Berkeley) 4/28/95";
42 #include <sys/cdefs.h>
44 __FBSDID("$FreeBSD: src/sbin/shutdown/shutdown.c,v 1.28 2005/01/25 08:40:51 delphij Exp $");
47 #include <sys/param.h>
49 #include <sys/resource.h>
50 #include <sys/syslog.h>
67 #include <bsm/libbsm.h>
68 #include <bsm/audit_uevents.h>
69 #include <sys/types.h>
70 #include <sys/sysctl.h>
72 #include <vproc_priv.h>
74 #include "kextmanager.h"
75 #include <IOKit/kext/kextmanager_types.h>
76 #include <IOKit/pwr_mgt/IOPMLib.h>
77 #include <mach/mach_port.h> // allocate
78 #include <mach/mach.h> // task_self, etc
79 #include <servers/bootstrap.h> // bootstrap
80 #include <bootstrap_priv.h>
84 #include "pathnames.h"
85 #endif /* __APPLE__ */
89 #define _PATH_NOLOGIN "./nologin"
95 #define NOLOG_TIME 5*60
97 int timeleft
, timetowait
;
116 static time_t offset
, shuttime
;
118 static int dohalt
, doreboot
, doups
, killflg
, oflag
;
119 static size_t mbuflen
;
121 static int dohalt
, dopower
, doreboot
, killflg
, mbuflen
, oflag
;
123 static char mbuf
[BUFSIZ
];
124 static const char *nosync
, *whom
;
131 void log_and_exec_reboot_or_halt(void);
133 void die_you_gravy_sucking_pig_dog(void);
136 void getoffset(char *);
140 void timewarn(time_t);
141 void usage(const char *);
143 int audit_shutdown(int);
144 int reserve_reboot(void);
147 extern const char **environ
;
150 main(int argc
, char **argv
)
155 int ch
, len
, readstdin
;
159 errx(1, "NOT super-user");
164 while ((ch
= getopt(argc
, argv
, "-hknopr")) != -1)
166 while ((ch
= getopt(argc
, argv
, "-hknorsu")) != -1)
211 if (killflg
+ doreboot
+ dohalt
+ dopower
> 1)
212 usage("incompatible switches -h, -k, -p and -r");
214 if (oflag
&& !(dohalt
|| dopower
|| doreboot
))
215 usage("-o requires -h, -p or -r");
217 if (nosync
!= NULL
&& !oflag
)
218 usage("-n requires -o");
219 #else /* !__APPLE__ */
220 if (killflg
+ doreboot
+ dohalt
+ dosleep
> 1)
221 usage("incompatible switches -h, -k, -r, and -s");
223 if (!(dohalt
|| doreboot
|| dosleep
|| killflg
))
224 usage("-h, -r, -s, or -k is required");
226 if (doups
&& !dohalt
)
227 usage("-u requires -h");
228 #endif /* !__APPLE__ */
233 for (p
= mbuf
, len
= sizeof(mbuf
); *argv
; ++argv
) {
234 arglen
= strlen(*argv
);
235 if ((len
-= arglen
) <= 2)
239 memmove(p
, *argv
, arglen
);
248 endp
= mbuf
+ sizeof(mbuf
) - 2;
250 if (!fgets(p
, (int)(endp
- p
+ 1), stdin
))
252 for (; *p
&& p
< endp
; ++p
);
260 mbuflen
= strlen(mbuf
);
263 (void)printf("Shutdown at %.24s.\n", ctime(&shuttime
));
265 (void)printf("Shutdown NOW!\n");
267 if (!(whom
= getlogin()))
268 whom
= (pw
= getpwuid(getuid())) ? pw
->pw_name
: "???";
272 (void)putc('\n', stdout
);
274 (void)setpriority(PRIO_PROCESS
, 0, PRIO_MIN
);
288 errx(0, "[pid %d]", forkpid
);
290 /* 5863185: reboot2() needs to talk to launchd. */
291 if (_vprocmgr_detach_from_console(0) != NULL
)
292 warnx("can't detach from console");
293 #endif /* __APPLE__ */
298 openlog("shutdown", LOG_CONS
, LOG_AUTH
);
310 if (offset
<= NOLOG_TIME
) {
317 if (tp
->timeleft
< offset
)
318 (void)sleep((u_int
)(offset
- tp
->timeleft
));
320 while (tp
->timeleft
&& offset
< tp
->timeleft
)
323 * Warn now, if going to sleep more than a fifth of
324 * the next wait time.
326 if ((sltime
= (u_int
)(offset
- tp
->timeleft
))) {
327 if (sltime
> (tp
->timetowait
/ 5))
333 timewarn(tp
->timeleft
);
334 if (!logged
&& tp
->timeleft
<= NOLOG_TIME
) {
338 (void)sleep((u_int
)tp
->timetowait
);
343 log_and_exec_reboot_or_halt();
345 die_you_gravy_sucking_pig_dog();
349 static jmp_buf alarmbuf
;
351 static const char *restricted_environ
[] = {
352 "PATH=" _PATH_STDPATH
,
357 timewarn(time_t timeleft
)
360 static char hostname
[MAXHOSTNAMELEN
+ 1];
362 char wcmd
[MAXPATHLEN
+ 4];
364 /* wall is sometimes missing, e.g. on install media */
365 if (access(_PATH_WALL
, X_OK
) == -1) return;
368 (void)gethostname(hostname
, sizeof(hostname
));
370 /* undoc -n option to wall suppresses normal wall banner */
371 (void)snprintf(wcmd
, sizeof(wcmd
), "%s -n", _PATH_WALL
);
372 environ
= restricted_environ
;
373 if (!(pf
= popen(wcmd
, "w"))) {
374 syslog(LOG_ERR
, "shutdown: can't find %s: %m", _PATH_WALL
);
379 "\007*** %sSystem shutdown message from %s@%s ***\007\n",
380 timeleft
? "": "FINAL ", whom
, hostname
);
382 if (timeleft
> 10*60)
383 (void)fprintf(pf
, "System going down at %5.5s\n\n",
384 ctime(&shuttime
) + 11);
385 else if (timeleft
> 59)
386 (void)fprintf(pf
, "System going down in %ld minute%s\n\n",
387 timeleft
/ 60, (timeleft
> 60) ? "s" : "");
389 (void)fprintf(pf
, "System going down in 30 seconds\n\n");
391 (void)fprintf(pf
, "System going down IMMEDIATELY\n\n");
394 (void)fwrite(mbuf
, sizeof(*mbuf
), mbuflen
, pf
);
397 * play some games, just in case wall doesn't come back
398 * probably unnecessary, given that wall is careful.
400 if (!setjmp(alarmbuf
)) {
401 (void)signal(SIGALRM
, timeout
);
402 (void)alarm((u_int
)30);
404 (void)alarm((u_int
)0);
405 (void)signal(SIGALRM
, SIG_DFL
);
410 timeout(int signo __unused
)
412 longjmp(alarmbuf
, 1);
417 log_and_exec_reboot_or_halt()
419 die_you_gravy_sucking_pig_dog()
423 char *empty_environ
[] = { NULL
};
425 if ((errno
= reserve_reboot())) {
426 warn("couldn't lock for reboot");
431 syslog(LOG_NOTICE
, "%s%s by %s: %s",
433 doreboot
? "reboot" : dohalt
? "halt" : dopower
? "power-down" :
435 doreboot
? "reboot" : dohalt
? "halt" : dosleep
? "sleep" :
437 "shutdown", doups
?" with UPS delay":"", whom
, mbuf
);
442 (void)printf("\r\nSystem shutdown time has arrived\007\007\r\n");
444 (void)printf("\rbut you'll have to do it yourself\r\n");
449 (void)printf("reboot");
451 (void)printf("halt");
454 (void)printf("power-down");
456 (void)printf(" no sync");
459 (void)printf("sleep");
461 (void)printf("\nkill -HUP 1\n");
467 kern_return_t kr
= IOMasterPort(bootstrap_port
, &mp
);
468 if (kr
== kIOReturnSuccess
) {
469 fb
= IOPMFindPowerManagement(mp
);
470 if (fb
!= IO_OBJECT_NULL
) {
471 IOReturn err
= IOPMSleepSystem(fb
);
472 if (err
!= kIOReturnSuccess
) {
473 fprintf(stderr
, "shutdown: sleep failed (0x%08x)\n", err
);
481 #if defined(__APPLE__)
484 bzero(&utx
, sizeof(utx
));
485 utx
.ut_type
= SHUTDOWN_TIME
;
486 gettimeofday(&utx
.ut_tv
, NULL
);
490 logwtmp("~", "shutdown", "");
493 if (dohalt
) howto
|= RB_HALT
;
494 if (doups
) howto
|= RB_UPSDELAY
;
495 if (nosync
) howto
|= RB_NOSYNC
;
497 // launchd(8) handles reboot. This call returns NULL on success.
498 if (reboot3(howto
)) {
499 syslog(LOG_ERR
, "shutdown: launchd reboot failed.");
502 #else /* __APPLE__ */
504 (void)kill(1, doreboot
? SIGINT
: /* reboot */
505 dohalt
? SIGUSR1
: /* halt */
506 dopower
? SIGUSR2
: /* power-down */
507 SIGTERM
); /* single-user */
510 execle(_PATH_REBOOT
, "reboot", "-l", nosync
,
511 (char *)NULL
, empty_environ
);
512 syslog(LOG_ERR
, "shutdown: can't exec %s: %m.",
517 execle(_PATH_HALT
, "halt", "-l", nosync
,
518 (char *)NULL
, empty_environ
);
519 syslog(LOG_ERR
, "shutdown: can't exec %s: %m.",
524 execle(_PATH_HALT
, "halt", "-l", "-p", nosync
,
525 (char *)NULL
, empty_environ
);
526 syslog(LOG_ERR
, "shutdown: can't exec %s: %m.",
530 (void)kill(1, SIGTERM
); /* to single-user */
532 #endif /* __APPLE__ */
537 #define ATOI2(p) (p[0] - '0') * 10 + (p[1] - '0'); p += 2;
540 getoffset(char *timearg
)
549 if (!strcasecmp(timearg
, "now")) { /* now */
555 if (*timearg
== '+') { /* +minutes */
556 if (!isdigit(*++timearg
))
558 if ((offset
= atoi(timearg
) * 60) < 0)
560 shuttime
= now
+ offset
;
564 /* handle hh:mm by getting rid of the colon */
565 for (p
= timearg
; *p
; ++p
)
566 if (!isascii(*p
) || !isdigit(*p
)) {
567 if (*p
== ':' && strlen(p
) == 3) {
576 unsetenv("TZ"); /* OUR timezone */
577 lt
= localtime(&now
); /* current time val */
579 switch(strlen(timearg
)) {
581 this_year
= lt
->tm_year
;
582 lt
->tm_year
= ATOI2(timearg
);
584 * check if the specified year is in the next century.
585 * allow for one year of user error as many people will
586 * enter n - 1 at the start of year n.
588 if (lt
->tm_year
< (this_year
% 100) - 1)
590 /* adjust for the year 2000 and beyond */
591 lt
->tm_year
+= (this_year
- (this_year
% 100));
594 lt
->tm_mon
= ATOI2(timearg
);
595 if (--lt
->tm_mon
< 0 || lt
->tm_mon
> 11)
599 lt
->tm_mday
= ATOI2(timearg
);
600 if (lt
->tm_mday
< 1 || lt
->tm_mday
> 31)
604 lt
->tm_hour
= ATOI2(timearg
);
605 if (lt
->tm_hour
< 0 || lt
->tm_hour
> 23)
607 lt
->tm_min
= ATOI2(timearg
);
608 if (lt
->tm_min
< 0 || lt
->tm_min
> 59)
611 if ((shuttime
= mktime(lt
)) == -1)
613 if ((offset
= shuttime
- now
) < 0)
614 errx(1, "that time is already past.");
621 #define NOMSG "\n\nNO LOGINS: System going down at "
628 (void)unlink(_PATH_NOLOGIN
); /* in case linked to another file */
629 (void)signal(SIGINT
, finish
);
630 (void)signal(SIGHUP
, finish
);
631 (void)signal(SIGQUIT
, finish
);
632 (void)signal(SIGTERM
, finish
);
633 if ((logfd
= open(_PATH_NOLOGIN
, O_WRONLY
|O_CREAT
|O_TRUNC
,
635 (void)write(logfd
, NOMSG
, sizeof(NOMSG
) - 1);
636 ct
= ctime(&shuttime
);
637 (void)write(logfd
, ct
+ 11, 5);
638 (void)write(logfd
, "\n\n", 2);
639 (void)write(logfd
, mbuf
, strlen(mbuf
));
645 finish(int signo __unused
)
648 (void)unlink(_PATH_NOLOGIN
);
655 errx(1, "bad time format");
659 usage(const char *cp
)
663 (void)fprintf(stderr
,
665 "usage: shutdown [-] [-h [-u] [-n] | -r [-n] | -s | -k]"
667 "usage: shutdown [-] [-h | -p | -r | -k] [-o [-n]]"
669 " time [warning-message ...]\n");
675 * The following tokens are included in the audit record for shutdown
681 audit_shutdown(int exitstatus
)
687 /* If we are not auditing, don't cut an audit record; just return */
688 if (auditon(A_GETCOND
, &au_cond
, sizeof(long)) < 0) {
689 fprintf(stderr
, "shutdown: Could not determine audit condition\n");
692 if (au_cond
== AUC_NOAUDIT
)
695 if((aufd
= au_open()) == -1) {
696 fprintf(stderr
, "shutdown: Audit Error: au_open() failed\n");
700 /* The subject that performed the operation */
701 if((tok
= au_to_me()) == NULL
) {
702 fprintf(stderr
, "shutdown: Audit Error: au_to_me() failed\n");
707 /* success and failure status */
708 if((tok
= au_to_return32(exitstatus
, errno
)) == NULL
) {
709 fprintf(stderr
, "shutdown: Audit Error: au_to_return32() failed\n");
714 if(au_close(aufd
, 1, AUE_shutdown
) == -1) {
715 fprintf(stderr
, "shutdown: Audit Error: au_close() failed\n");
725 uint32_t disabled
= 0;
726 size_t sizeOfDisabled
= sizeof(disabled
);
727 if (sysctlbyname("hw.use_kernelmanagerd", &disabled
, &sizeOfDisabled
, NULL
, 0) != 0) {
730 return (disabled
!= 0);
734 // XX copied from reboot.tproj/reboot.c; it would be nice to share the code
736 #define WAITFORLOCK 1
738 * contact kextd to lock for reboot
743 int rval
= ELAST
+ 1;
744 kern_return_t macherr
= KERN_FAILURE
;
745 mach_port_t kxport
, tport
= MACH_PORT_NULL
, myport
= MACH_PORT_NULL
;
746 int busyStatus
= ELAST
+ 1;
747 mountpoint_t busyVol
;
749 if (kextdDisabled()) {
750 /* no need to talk with kextd if it's not running */
754 macherr
= bootstrap_look_up2(bootstrap_port
, KEXTD_SERVER_NAME
, &kxport
, 0, BOOTSTRAP_PRIVILEGED_SERVER
);
755 if (macherr
) goto finish
;
757 // allocate a port to pass to kextd (in case we die)
758 tport
= mach_task_self();
759 if (tport
== MACH_PORT_NULL
) goto finish
;
760 macherr
= mach_port_allocate(tport
, MACH_PORT_RIGHT_RECEIVE
, &myport
);
761 if (macherr
) goto finish
;
763 // try to lock for reboot
764 macherr
= kextmanager_lock_reboot(kxport
, myport
, !WAITFORLOCK
, busyVol
,
766 if (macherr
) goto finish
;
768 if (busyStatus
== EBUSY
) {
769 warnx("%s is busy updating; waiting for lock", busyVol
);
770 macherr
= kextmanager_lock_reboot(kxport
, myport
, WAITFORLOCK
,
771 busyVol
, &busyStatus
);
772 if (macherr
) goto finish
;
775 if (busyStatus
== EALREADY
) {
776 // reboot already in progress
783 // in general, we want to err on the side of allowing the reboot
785 if (macherr
!= BOOTSTRAP_UNKNOWN_SERVICE
)
786 warnx("WARNING: couldn't lock kext manager for reboot: %s",
787 mach_error_string(macherr
));
790 // unless we got the lock, clean up our port
791 if (busyStatus
!= 0 && myport
!= MACH_PORT_NULL
)
792 mach_port_mod_refs(tport
, myport
, MACH_PORT_RIGHT_RECEIVE
, -1);
796 #endif /* __APPLE__ */