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 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>
73 #include <vproc_priv.h>
75 #if defined(__APPLE__) && !(TARGET_OS_IPHONE && !TARGET_OS_SIMULATOR)
76 #include "kextmanager.h"
77 #include <IOKit/kext/kextmanager_types.h>
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>
87 #include "pathnames.h"
88 #endif /* __APPLE__ */
90 #include <libiosexec.h>
96 #define _PATH_NOLOGIN "./nologin"
102 #define NOLOG_TIME 5*60
104 int timeleft
, timetowait
;
123 static time_t offset
, shuttime
;
125 static int dohalt
, doreboot
, doups
, killflg
, oflag
;
126 static size_t mbuflen
;
128 static int dohalt
, dopower
, doreboot
, killflg
, mbuflen
, oflag
;
130 static char mbuf
[BUFSIZ
];
131 static const char *nosync
, *whom
;
138 void log_and_exec_reboot_or_halt(void);
140 void die_you_gravy_sucking_pig_dog(void);
143 void getoffset(char *);
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);
154 extern const char **environ
;
157 main(int argc
, char **argv
)
162 int ch
, len
, readstdin
;
166 errx(1, "NOT super-user");
171 while ((ch
= getopt(argc
, argv
, "-hknopr")) != -1)
173 while ((ch
= getopt(argc
, argv
, "-hknorsu")) != -1)
218 if (killflg
+ doreboot
+ dohalt
+ dopower
> 1)
219 usage("incompatible switches -h, -k, -p and -r");
221 if (oflag
&& !(dohalt
|| dopower
|| doreboot
))
222 usage("-o requires -h, -p or -r");
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");
230 if (!(dohalt
|| doreboot
|| dosleep
|| killflg
))
231 usage("-h, -r, -s, or -k is required");
233 if (doups
&& !dohalt
)
234 usage("-u requires -h");
235 #endif /* !__APPLE__ */
240 for (p
= mbuf
, len
= sizeof(mbuf
); *argv
; ++argv
) {
241 arglen
= strlen(*argv
);
242 if ((len
-= arglen
) <= 2)
246 memmove(p
, *argv
, arglen
);
255 endp
= mbuf
+ sizeof(mbuf
) - 2;
257 if (!fgets(p
, (int)(endp
- p
+ 1), stdin
))
259 for (; *p
&& p
< endp
; ++p
);
267 mbuflen
= strlen(mbuf
);
270 (void)printf("Shutdown at %.24s.\n", ctime(&shuttime
));
272 (void)printf("Shutdown NOW!\n");
274 if (!(whom
= getlogin()))
275 whom
= (pw
= getpwuid(getuid())) ? pw
->pw_name
: "???";
279 (void)putc('\n', stdout
);
281 (void)setpriority(PRIO_PROCESS
, 0, PRIO_MIN
);
295 errx(0, "[pid %d]", forkpid
);
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__ */
305 openlog("shutdown", LOG_CONS
, LOG_AUTH
);
317 if (offset
<= NOLOG_TIME
) {
324 if (tp
->timeleft
< offset
)
325 (void)sleep((u_int
)(offset
- tp
->timeleft
));
327 while (tp
->timeleft
&& offset
< tp
->timeleft
)
330 * Warn now, if going to sleep more than a fifth of
331 * the next wait time.
333 if ((sltime
= (u_int
)(offset
- tp
->timeleft
))) {
334 if (sltime
> (tp
->timetowait
/ 5))
340 timewarn(tp
->timeleft
);
341 if (!logged
&& tp
->timeleft
<= NOLOG_TIME
) {
345 (void)sleep((u_int
)tp
->timetowait
);
350 log_and_exec_reboot_or_halt();
352 die_you_gravy_sucking_pig_dog();
356 static jmp_buf alarmbuf
;
358 static const char *restricted_environ
[] = {
359 "PATH=" _PATH_STDPATH
,
364 timewarn(time_t timeleft
)
367 static char hostname
[MAXHOSTNAMELEN
+ 1];
369 char wcmd
[MAXPATHLEN
+ 4];
371 /* wall is sometimes missing, e.g. on install media */
372 if (access(_PATH_WALL
, X_OK
) == -1) return;
375 (void)gethostname(hostname
, sizeof(hostname
));
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
);
386 "\007*** %sSystem shutdown message from %s@%s ***\007\n",
387 timeleft
? "": "FINAL ", whom
, hostname
);
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" : "");
396 (void)fprintf(pf
, "System going down in 30 seconds\n\n");
398 (void)fprintf(pf
, "System going down IMMEDIATELY\n\n");
401 (void)fwrite(mbuf
, sizeof(*mbuf
), mbuflen
, pf
);
404 * play some games, just in case wall doesn't come back
405 * probably unnecessary, given that wall is careful.
407 if (!setjmp(alarmbuf
)) {
408 (void)signal(SIGALRM
, timeout
);
409 (void)alarm((u_int
)30);
411 (void)alarm((u_int
)0);
412 (void)signal(SIGALRM
, SIG_DFL
);
417 timeout(int signo __unused
)
419 longjmp(alarmbuf
, 1);
424 log_and_exec_reboot_or_halt()
426 die_you_gravy_sucking_pig_dog()
429 #if defined(__APPLE__) && !(TARGET_OS_IPHONE && !TARGET_OS_SIMULATOR)
430 if ((errno
= reserve_reboot())) {
431 warn("couldn't lock for reboot");
435 char *empty_environ
[] = { NULL
};
438 syslog(LOG_NOTICE
, "%s%s by %s: %s",
440 doreboot
? "reboot" : dohalt
? "halt" : dopower
? "power-down" :
442 doreboot
? "reboot" : dohalt
? "halt" : dosleep
? "sleep" :
444 "shutdown", doups
?" with UPS delay":"", whom
, mbuf
);
449 (void)printf("\r\nSystem shutdown time has arrived\007\007\r\n");
451 (void)printf("\rbut you'll have to do it yourself\r\n");
456 (void)printf("reboot");
458 (void)printf("halt");
461 (void)printf("power-down");
463 (void)printf(" no sync");
466 (void)printf("sleep");
468 (void)printf("\nkill -HUP 1\n");
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
);
488 #if defined(__APPLE__)
491 bzero(&utx
, sizeof(utx
));
492 utx
.ut_type
= SHUTDOWN_TIME
;
493 gettimeofday(&utx
.ut_tv
, NULL
);
497 logwtmp("~", "shutdown", "");
500 if (dohalt
) howto
|= RB_HALT
;
501 if (doups
) howto
|= RB_UPSDELAY
;
502 if (nosync
) howto
|= RB_NOSYNC
;
504 // launchd(8) handles reboot. This call returns NULL on success.
505 if (reboot3(howto
)) {
506 syslog(LOG_ERR
, "shutdown: launchd reboot failed.");
509 #else /* __APPLE__ */
511 (void)kill(1, doreboot
? SIGINT
: /* reboot */
512 dohalt
? SIGUSR1
: /* halt */
513 dopower
? SIGUSR2
: /* power-down */
514 SIGTERM
); /* single-user */
517 execle(_PATH_REBOOT
, "reboot", "-l", nosync
,
518 (char *)NULL
, empty_environ
);
519 syslog(LOG_ERR
, "shutdown: can't exec %s: %m.",
524 execle(_PATH_HALT
, "halt", "-l", nosync
,
525 (char *)NULL
, empty_environ
);
526 syslog(LOG_ERR
, "shutdown: can't exec %s: %m.",
531 execle(_PATH_HALT
, "halt", "-l", "-p", nosync
,
532 (char *)NULL
, empty_environ
);
533 syslog(LOG_ERR
, "shutdown: can't exec %s: %m.",
537 (void)kill(1, SIGTERM
); /* to single-user */
539 #endif /* __APPLE__ */
544 #define ATOI2(p) (p[0] - '0') * 10 + (p[1] - '0'); p += 2;
547 getoffset(char *timearg
)
556 if (!strcasecmp(timearg
, "now")) { /* now */
562 if (*timearg
== '+') { /* +minutes */
563 if (!isdigit(*++timearg
))
565 if ((offset
= atoi(timearg
) * 60) < 0)
567 shuttime
= now
+ offset
;
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) {
583 unsetenv("TZ"); /* OUR timezone */
584 lt
= localtime(&now
); /* current time val */
586 switch(strlen(timearg
)) {
588 this_year
= lt
->tm_year
;
589 lt
->tm_year
= ATOI2(timearg
);
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.
595 if (lt
->tm_year
< (this_year
% 100) - 1)
597 /* adjust for the year 2000 and beyond */
598 lt
->tm_year
+= (this_year
- (this_year
% 100));
601 lt
->tm_mon
= ATOI2(timearg
);
602 if (--lt
->tm_mon
< 0 || lt
->tm_mon
> 11)
606 lt
->tm_mday
= ATOI2(timearg
);
607 if (lt
->tm_mday
< 1 || lt
->tm_mday
> 31)
611 lt
->tm_hour
= ATOI2(timearg
);
612 if (lt
->tm_hour
< 0 || lt
->tm_hour
> 23)
614 lt
->tm_min
= ATOI2(timearg
);
615 if (lt
->tm_min
< 0 || lt
->tm_min
> 59)
618 if ((shuttime
= mktime(lt
)) == -1)
620 if ((offset
= shuttime
- now
) < 0)
621 errx(1, "that time is already past.");
628 #define NOMSG "\n\nNO LOGINS: System going down at "
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
,
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
));
652 finish(int signo __unused
)
655 (void)unlink(_PATH_NOLOGIN
);
662 errx(1, "bad time format");
666 usage(const char *cp
)
670 (void)fprintf(stderr
,
672 "usage: shutdown [-] [-h [-u] [-n] | -r [-n] | -s | -k]"
674 "usage: shutdown [-] [-h | -p | -r | -k] [-o [-n]]"
676 " time [warning-message ...]\n");
681 * The following tokens are included in the audit record for shutdown
687 audit_shutdown(int exitstatus
)
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");
698 if (au_cond
== AUC_NOAUDIT
)
701 if((aufd
= au_open()) == -1) {
702 fprintf(stderr
, "shutdown: Audit Error: au_open() failed\n");
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");
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");
720 if(au_close(aufd
, 1, AUE_shutdown
) == -1) {
721 fprintf(stderr
, "shutdown: Audit Error: au_close() failed\n");
727 #if defined(__APPLE__) && !(TARGET_OS_IPHONE && !TARGET_OS_SIMULATOR)
732 uint32_t disabled
= 0;
733 size_t sizeOfDisabled
= sizeof(disabled
);
734 if (sysctlbyname("hw.use_kernelmanagerd", &disabled
, &sizeOfDisabled
, NULL
, 0) != 0) {
737 return (disabled
!= 0);
741 // XX copied from reboot.tproj/reboot.c; it would be nice to share the code
743 #define WAITFORLOCK 1
745 * contact kextd to lock for reboot
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
;
756 if (kextdDisabled()) {
757 /* no need to talk with kextd if it's not running */
761 macherr
= bootstrap_look_up2(bootstrap_port
, KEXTD_SERVER_NAME
, &kxport
, 0, BOOTSTRAP_PRIVILEGED_SERVER
);
762 if (macherr
) goto finish
;
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
;
770 // try to lock for reboot
771 macherr
= kextmanager_lock_reboot(kxport
, myport
, !WAITFORLOCK
, busyVol
,
773 if (macherr
) goto finish
;
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
;
782 if (busyStatus
== EALREADY
) {
783 // reboot already in progress
790 // in general, we want to err on the side of allowing the reboot
792 if (macherr
!= BOOTSTRAP_UNKNOWN_SERVICE
)
793 warnx("WARNING: couldn't lock kext manager for reboot: %s",
794 mach_error_string(macherr
));
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);
803 #endif /* __APPLE__ */