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 #if defined(__APPLE__) && !(TARGET_OS_IPHONE && !TARGET_OS_SIMULATOR)
75 #include "kextmanager.h"
76 #include <IOKit/kext/kextmanager_types.h>
78 #include <IOKit/pwr_mgt/IOPMLib.h>
79 #include <mach/mach_port.h> // allocate
80 #include <mach/mach.h> // task_self, etc
81 #include <servers/bootstrap.h> // bootstrap
82 #include <bootstrap_priv.h>
86 #include "pathnames.h"
87 #endif /* __APPLE__ */
93 #define _PATH_NOLOGIN "./nologin"
99 #define NOLOG_TIME 5*60
101 int timeleft
, timetowait
;
120 static time_t offset
, shuttime
;
122 static int dohalt
, doreboot
, doups
, killflg
, oflag
;
123 static size_t mbuflen
;
125 static int dohalt
, dopower
, doreboot
, killflg
, mbuflen
, oflag
;
127 static char mbuf
[BUFSIZ
];
128 static const char *nosync
, *whom
;
135 void log_and_exec_reboot_or_halt(void);
137 void die_you_gravy_sucking_pig_dog(void);
140 void getoffset(char *);
144 void timewarn(time_t);
145 void usage(const char *);
146 int audit_shutdown(int);
147 #if defined(__APPLE__) && !(TARGET_OS_IPHONE && !TARGET_OS_SIMULATOR)
148 int reserve_reboot(void);
151 extern const char **environ
;
154 main(int argc
, char **argv
)
159 int ch
, len
, readstdin
;
163 errx(1, "NOT super-user");
168 while ((ch
= getopt(argc
, argv
, "-hknopr")) != -1)
170 while ((ch
= getopt(argc
, argv
, "-hknorsu")) != -1)
215 if (killflg
+ doreboot
+ dohalt
+ dopower
> 1)
216 usage("incompatible switches -h, -k, -p and -r");
218 if (oflag
&& !(dohalt
|| dopower
|| doreboot
))
219 usage("-o requires -h, -p or -r");
221 if (nosync
!= NULL
&& !oflag
)
222 usage("-n requires -o");
223 #else /* !__APPLE__ */
224 if (killflg
+ doreboot
+ dohalt
+ dosleep
> 1)
225 usage("incompatible switches -h, -k, -r, and -s");
227 if (!(dohalt
|| doreboot
|| dosleep
|| killflg
))
228 usage("-h, -r, -s, or -k is required");
230 if (doups
&& !dohalt
)
231 usage("-u requires -h");
232 #endif /* !__APPLE__ */
237 for (p
= mbuf
, len
= sizeof(mbuf
); *argv
; ++argv
) {
238 arglen
= strlen(*argv
);
239 if ((len
-= arglen
) <= 2)
243 memmove(p
, *argv
, arglen
);
252 endp
= mbuf
+ sizeof(mbuf
) - 2;
254 if (!fgets(p
, (int)(endp
- p
+ 1), stdin
))
256 for (; *p
&& p
< endp
; ++p
);
264 mbuflen
= strlen(mbuf
);
267 (void)printf("Shutdown at %.24s.\n", ctime(&shuttime
));
269 (void)printf("Shutdown NOW!\n");
271 if (!(whom
= getlogin()))
272 whom
= (pw
= getpwuid(getuid())) ? pw
->pw_name
: "???";
276 (void)putc('\n', stdout
);
278 (void)setpriority(PRIO_PROCESS
, 0, PRIO_MIN
);
292 errx(0, "[pid %d]", forkpid
);
294 /* 5863185: reboot2() needs to talk to launchd. */
295 if (_vprocmgr_detach_from_console(0) != NULL
)
296 warnx("can't detach from console");
297 #endif /* __APPLE__ */
302 openlog("shutdown", LOG_CONS
, LOG_AUTH
);
314 if (offset
<= NOLOG_TIME
) {
321 if (tp
->timeleft
< offset
)
322 (void)sleep((u_int
)(offset
- tp
->timeleft
));
324 while (tp
->timeleft
&& offset
< tp
->timeleft
)
327 * Warn now, if going to sleep more than a fifth of
328 * the next wait time.
330 if ((sltime
= (u_int
)(offset
- tp
->timeleft
))) {
331 if (sltime
> (tp
->timetowait
/ 5))
337 timewarn(tp
->timeleft
);
338 if (!logged
&& tp
->timeleft
<= NOLOG_TIME
) {
342 (void)sleep((u_int
)tp
->timetowait
);
347 log_and_exec_reboot_or_halt();
349 die_you_gravy_sucking_pig_dog();
353 static jmp_buf alarmbuf
;
355 static const char *restricted_environ
[] = {
356 "PATH=" _PATH_STDPATH
,
361 timewarn(time_t timeleft
)
364 static char hostname
[MAXHOSTNAMELEN
+ 1];
366 char wcmd
[MAXPATHLEN
+ 4];
368 /* wall is sometimes missing, e.g. on install media */
369 if (access(_PATH_WALL
, X_OK
) == -1) return;
372 (void)gethostname(hostname
, sizeof(hostname
));
374 /* undoc -n option to wall suppresses normal wall banner */
375 (void)snprintf(wcmd
, sizeof(wcmd
), "%s -n", _PATH_WALL
);
376 environ
= restricted_environ
;
377 if (!(pf
= popen(wcmd
, "w"))) {
378 syslog(LOG_ERR
, "shutdown: can't find %s: %m", _PATH_WALL
);
383 "\007*** %sSystem shutdown message from %s@%s ***\007\n",
384 timeleft
? "": "FINAL ", whom
, hostname
);
386 if (timeleft
> 10*60)
387 (void)fprintf(pf
, "System going down at %5.5s\n\n",
388 ctime(&shuttime
) + 11);
389 else if (timeleft
> 59)
390 (void)fprintf(pf
, "System going down in %ld minute%s\n\n",
391 timeleft
/ 60, (timeleft
> 60) ? "s" : "");
393 (void)fprintf(pf
, "System going down in 30 seconds\n\n");
395 (void)fprintf(pf
, "System going down IMMEDIATELY\n\n");
398 (void)fwrite(mbuf
, sizeof(*mbuf
), mbuflen
, pf
);
401 * play some games, just in case wall doesn't come back
402 * probably unnecessary, given that wall is careful.
404 if (!setjmp(alarmbuf
)) {
405 (void)signal(SIGALRM
, timeout
);
406 (void)alarm((u_int
)30);
408 (void)alarm((u_int
)0);
409 (void)signal(SIGALRM
, SIG_DFL
);
414 timeout(int signo __unused
)
416 longjmp(alarmbuf
, 1);
421 log_and_exec_reboot_or_halt()
423 die_you_gravy_sucking_pig_dog()
426 #if defined(__APPLE__) && !(TARGET_OS_IPHONE && !TARGET_OS_SIMULATOR)
427 if ((errno
= reserve_reboot())) {
428 warn("couldn't lock for reboot");
432 char *empty_environ
[] = { NULL
};
435 syslog(LOG_NOTICE
, "%s%s by %s: %s",
437 doreboot
? "reboot" : dohalt
? "halt" : dopower
? "power-down" :
439 doreboot
? "reboot" : dohalt
? "halt" : dosleep
? "sleep" :
441 "shutdown", doups
?" with UPS delay":"", whom
, mbuf
);
446 (void)printf("\r\nSystem shutdown time has arrived\007\007\r\n");
448 (void)printf("\rbut you'll have to do it yourself\r\n");
453 (void)printf("reboot");
455 (void)printf("halt");
458 (void)printf("power-down");
460 (void)printf(" no sync");
463 (void)printf("sleep");
465 (void)printf("\nkill -HUP 1\n");
471 kern_return_t kr
= IOMasterPort(bootstrap_port
, &mp
);
472 if (kr
== kIOReturnSuccess
) {
473 fb
= IOPMFindPowerManagement(mp
);
474 if (fb
!= IO_OBJECT_NULL
) {
475 IOReturn err
= IOPMSleepSystem(fb
);
476 if (err
!= kIOReturnSuccess
) {
477 fprintf(stderr
, "shutdown: sleep failed (0x%08x)\n", err
);
485 #if defined(__APPLE__)
488 bzero(&utx
, sizeof(utx
));
489 utx
.ut_type
= SHUTDOWN_TIME
;
490 gettimeofday(&utx
.ut_tv
, NULL
);
494 logwtmp("~", "shutdown", "");
497 if (dohalt
) howto
|= RB_HALT
;
498 if (doups
) howto
|= RB_UPSDELAY
;
499 if (nosync
) howto
|= RB_NOSYNC
;
501 // launchd(8) handles reboot. This call returns NULL on success.
502 if (reboot3(howto
)) {
503 syslog(LOG_ERR
, "shutdown: launchd reboot failed.");
506 #else /* __APPLE__ */
508 (void)kill(1, doreboot
? SIGINT
: /* reboot */
509 dohalt
? SIGUSR1
: /* halt */
510 dopower
? SIGUSR2
: /* power-down */
511 SIGTERM
); /* single-user */
514 execle(_PATH_REBOOT
, "reboot", "-l", nosync
,
515 (char *)NULL
, empty_environ
);
516 syslog(LOG_ERR
, "shutdown: can't exec %s: %m.",
521 execle(_PATH_HALT
, "halt", "-l", nosync
,
522 (char *)NULL
, empty_environ
);
523 syslog(LOG_ERR
, "shutdown: can't exec %s: %m.",
528 execle(_PATH_HALT
, "halt", "-l", "-p", nosync
,
529 (char *)NULL
, empty_environ
);
530 syslog(LOG_ERR
, "shutdown: can't exec %s: %m.",
534 (void)kill(1, SIGTERM
); /* to single-user */
536 #endif /* __APPLE__ */
541 #define ATOI2(p) (p[0] - '0') * 10 + (p[1] - '0'); p += 2;
544 getoffset(char *timearg
)
553 if (!strcasecmp(timearg
, "now")) { /* now */
559 if (*timearg
== '+') { /* +minutes */
560 if (!isdigit(*++timearg
))
562 if ((offset
= atoi(timearg
) * 60) < 0)
564 shuttime
= now
+ offset
;
568 /* handle hh:mm by getting rid of the colon */
569 for (p
= timearg
; *p
; ++p
)
570 if (!isascii(*p
) || !isdigit(*p
)) {
571 if (*p
== ':' && strlen(p
) == 3) {
580 unsetenv("TZ"); /* OUR timezone */
581 lt
= localtime(&now
); /* current time val */
583 switch(strlen(timearg
)) {
585 this_year
= lt
->tm_year
;
586 lt
->tm_year
= ATOI2(timearg
);
588 * check if the specified year is in the next century.
589 * allow for one year of user error as many people will
590 * enter n - 1 at the start of year n.
592 if (lt
->tm_year
< (this_year
% 100) - 1)
594 /* adjust for the year 2000 and beyond */
595 lt
->tm_year
+= (this_year
- (this_year
% 100));
598 lt
->tm_mon
= ATOI2(timearg
);
599 if (--lt
->tm_mon
< 0 || lt
->tm_mon
> 11)
603 lt
->tm_mday
= ATOI2(timearg
);
604 if (lt
->tm_mday
< 1 || lt
->tm_mday
> 31)
608 lt
->tm_hour
= ATOI2(timearg
);
609 if (lt
->tm_hour
< 0 || lt
->tm_hour
> 23)
611 lt
->tm_min
= ATOI2(timearg
);
612 if (lt
->tm_min
< 0 || lt
->tm_min
> 59)
615 if ((shuttime
= mktime(lt
)) == -1)
617 if ((offset
= shuttime
- now
) < 0)
618 errx(1, "that time is already past.");
625 #define NOMSG "\n\nNO LOGINS: System going down at "
632 (void)unlink(_PATH_NOLOGIN
); /* in case linked to another file */
633 (void)signal(SIGINT
, finish
);
634 (void)signal(SIGHUP
, finish
);
635 (void)signal(SIGQUIT
, finish
);
636 (void)signal(SIGTERM
, finish
);
637 if ((logfd
= open(_PATH_NOLOGIN
, O_WRONLY
|O_CREAT
|O_TRUNC
,
639 (void)write(logfd
, NOMSG
, sizeof(NOMSG
) - 1);
640 ct
= ctime(&shuttime
);
641 (void)write(logfd
, ct
+ 11, 5);
642 (void)write(logfd
, "\n\n", 2);
643 (void)write(logfd
, mbuf
, strlen(mbuf
));
649 finish(int signo __unused
)
652 (void)unlink(_PATH_NOLOGIN
);
659 errx(1, "bad time format");
663 usage(const char *cp
)
667 (void)fprintf(stderr
,
669 "usage: shutdown [-] [-h [-u] [-n] | -r [-n] | -s | -k]"
671 "usage: shutdown [-] [-h | -p | -r | -k] [-o [-n]]"
673 " time [warning-message ...]\n");
678 * The following tokens are included in the audit record for shutdown
684 audit_shutdown(int exitstatus
)
690 /* If we are not auditing, don't cut an audit record; just return */
691 if (auditon(A_GETCOND
, &au_cond
, sizeof(long)) < 0) {
692 fprintf(stderr
, "shutdown: Could not determine audit condition\n");
695 if (au_cond
== AUC_NOAUDIT
)
698 if((aufd
= au_open()) == -1) {
699 fprintf(stderr
, "shutdown: Audit Error: au_open() failed\n");
703 /* The subject that performed the operation */
704 if((tok
= au_to_me()) == NULL
) {
705 fprintf(stderr
, "shutdown: Audit Error: au_to_me() failed\n");
710 /* success and failure status */
711 if((tok
= au_to_return32(exitstatus
, errno
)) == NULL
) {
712 fprintf(stderr
, "shutdown: Audit Error: au_to_return32() failed\n");
717 if(au_close(aufd
, 1, AUE_shutdown
) == -1) {
718 fprintf(stderr
, "shutdown: Audit Error: au_close() failed\n");
724 #if defined(__APPLE__) && !(TARGET_OS_IPHONE && !TARGET_OS_SIMULATOR)
729 uint32_t disabled
= 0;
730 size_t sizeOfDisabled
= sizeof(disabled
);
731 if (sysctlbyname("hw.use_kernelmanagerd", &disabled
, &sizeOfDisabled
, NULL
, 0) != 0) {
734 return (disabled
!= 0);
738 // XX copied from reboot.tproj/reboot.c; it would be nice to share the code
740 #define WAITFORLOCK 1
742 * contact kextd to lock for reboot
747 int rval
= ELAST
+ 1;
748 kern_return_t macherr
= KERN_FAILURE
;
749 mach_port_t kxport
, tport
= MACH_PORT_NULL
, myport
= MACH_PORT_NULL
;
750 int busyStatus
= ELAST
+ 1;
751 mountpoint_t busyVol
;
753 if (kextdDisabled()) {
754 /* no need to talk with kextd if it's not running */
758 macherr
= bootstrap_look_up2(bootstrap_port
, KEXTD_SERVER_NAME
, &kxport
, 0, BOOTSTRAP_PRIVILEGED_SERVER
);
759 if (macherr
) goto finish
;
761 // allocate a port to pass to kextd (in case we die)
762 tport
= mach_task_self();
763 if (tport
== MACH_PORT_NULL
) goto finish
;
764 macherr
= mach_port_allocate(tport
, MACH_PORT_RIGHT_RECEIVE
, &myport
);
765 if (macherr
) goto finish
;
767 // try to lock for reboot
768 macherr
= kextmanager_lock_reboot(kxport
, myport
, !WAITFORLOCK
, busyVol
,
770 if (macherr
) goto finish
;
772 if (busyStatus
== EBUSY
) {
773 warnx("%s is busy updating; waiting for lock", busyVol
);
774 macherr
= kextmanager_lock_reboot(kxport
, myport
, WAITFORLOCK
,
775 busyVol
, &busyStatus
);
776 if (macherr
) goto finish
;
779 if (busyStatus
== EALREADY
) {
780 // reboot already in progress
787 // in general, we want to err on the side of allowing the reboot
789 if (macherr
!= BOOTSTRAP_UNKNOWN_SERVICE
)
790 warnx("WARNING: couldn't lock kext manager for reboot: %s",
791 mach_error_string(macherr
));
794 // unless we got the lock, clean up our port
795 if (busyStatus
!= 0 && myport
!= MACH_PORT_NULL
)
796 mach_port_mod_refs(tport
, myport
, MACH_PORT_RIGHT_RECEIVE
, -1);
800 #endif /* __APPLE__ */