Home | History | Annotate | Line # | Download | only in shutdown
shutdown.c revision 1.47
      1 /*	$NetBSD: shutdown.c,v 1.47 2007/03/14 03:52:28 christos Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1988, 1990, 1993
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  * 3. Neither the name of the University nor the names of its contributors
     16  *    may be used to endorse or promote products derived from this software
     17  *    without specific prior written permission.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     29  * SUCH DAMAGE.
     30  */
     31 
     32 #include <sys/cdefs.h>
     33 #ifndef lint
     34 __COPYRIGHT("@(#) 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 #if 0
     40 static char sccsid[] = "@(#)shutdown.c	8.4 (Berkeley) 4/28/95";
     41 #else
     42 __RCSID("$NetBSD: shutdown.c,v 1.47 2007/03/14 03:52:28 christos Exp $");
     43 #endif
     44 #endif /* not lint */
     45 
     46 #include <sys/param.h>
     47 #include <sys/time.h>
     48 #include <sys/resource.h>
     49 #include <sys/syslog.h>
     50 
     51 #include <ctype.h>
     52 #include <err.h>
     53 #include <fcntl.h>
     54 #include <pwd.h>
     55 #include <setjmp.h>
     56 #include <signal.h>
     57 #include <stdio.h>
     58 #include <stdlib.h>
     59 #include <string.h>
     60 #include <time.h>
     61 #include <tzfile.h>
     62 #include <unistd.h>
     63 #include <errno.h>
     64 
     65 #include "pathnames.h"
     66 
     67 #ifdef DEBUG
     68 #undef _PATH_NOLOGIN
     69 #define	_PATH_NOLOGIN	"./nologin"
     70 #undef _PATH_FASTBOOT
     71 #define	_PATH_FASTBOOT	"./fastboot"
     72 #endif
     73 
     74 #define	H		*60*60
     75 #define	M		*60
     76 #define	S		*1
     77 #define	NOLOG_TIME	5*60
     78 static const struct interval {
     79 	time_t timeleft, timetowait;
     80 } tlist[] = {
     81 	{ 10 H,  5 H },	{  5 H,  3 H },	{  2 H,  1 H },	{ 1 H, 30 M },
     82 	{ 30 M, 10 M },	{ 20 M, 10 M },	{ 10 M,  5 M },	{ 5 M,  3 M },
     83 	{  2 M,  1 M },	{  1 M, 30 S },	{ 30 S, 30 S },
     84 	{  0, 0 }
     85 };
     86 #undef H
     87 #undef M
     88 #undef S
     89 
     90 static time_t offset, shuttime;
     91 static int dofast, dohalt, doreboot, killflg, nofork, nosync, dodump;
     92 static size_t mbuflen;
     93 static int dopowerdown;
     94 static const char *whom;
     95 static char mbuf[BUFSIZ];
     96 static char *bootstr;
     97 
     98 static void badtime(void) __attribute__((__noreturn__));
     99 static void die_you_gravy_sucking_pig_dog(void) __attribute__((__noreturn__));
    100 static void doitfast(void);
    101 void dorcshutdown(void);
    102 static void finish(int) __attribute__((__noreturn__));
    103 static void getoffset(char *);
    104 static void loop(void);
    105 static void nolog(void);
    106 static void timeout(int);
    107 static void timewarn(time_t);
    108 static void usage(void) __attribute__((__noreturn__));
    109 
    110 int
    111 main(int argc, char *argv[])
    112 {
    113 	char *p, *endp;
    114 	struct passwd *pw;
    115 	size_t arglen, len;
    116 	int ch;
    117 
    118 	(void)setprogname(argv[0]);
    119 #ifndef DEBUG
    120 	if (geteuid())
    121 		errx(1, "NOT super-user");
    122 #endif
    123 	while ((ch = getopt(argc, argv, "b:Ddfhknpr")) != -1)
    124 		switch (ch) {
    125 		case 'b':
    126 			bootstr = optarg;
    127 			break;
    128 		case 'd':
    129 			dodump = 1;
    130 			break;
    131 		case 'D':
    132 			nofork = 1;
    133 			break;
    134 		case 'f':
    135 			dofast = 1;
    136 			break;
    137 		case 'p':
    138 			dopowerdown = 1;
    139 			/* FALLTHROUGH */
    140 		case 'h':
    141 			dohalt = 1;
    142 			break;
    143 		case 'k':
    144 			killflg = 1;
    145 			break;
    146 		case 'n':
    147 			nosync = 1;
    148 			break;
    149 		case 'r':
    150 			doreboot = 1;
    151 			break;
    152 		case '?':
    153 		default:
    154 			usage();
    155 		}
    156 	argc -= optind;
    157 	argv += optind;
    158 
    159 	if (argc < 1)
    160 		usage();
    161 
    162 	if (dodump && !dohalt && !doreboot)
    163 		doreboot = 1;
    164 
    165 	if (dofast && nosync) {
    166 		warnx("incompatible switches -f and -n");
    167 		usage();
    168 	}
    169 	if (dohalt && doreboot) {
    170 		const char *which_flag = dopowerdown ? "p" : "h";
    171 
    172 		warnx("incompatible switches -%s and -r", which_flag);
    173 		usage();
    174 	}
    175 
    176 	getoffset(*argv++);
    177 
    178 	if (argv[0]) {
    179 		if (strcmp(argv[0], "-") || argv[1]) {
    180 			for (p = mbuf, len = sizeof(mbuf); *argv; ++argv) {
    181 				arglen = strlen(*argv);
    182 				if ((len -= arglen) <= 2)
    183 					break;
    184 				if (p != mbuf)
    185 					*p++ = ' ';
    186 				(void)memmove(p, *argv, arglen);
    187 				p += arglen;
    188 			}
    189 			*p = '\n';
    190 			*++p = '\0';
    191 		} else {
    192 			p = mbuf;
    193 			endp = mbuf + sizeof(mbuf) - 2;
    194 			for (;;) {
    195 				if (!fgets(p, endp - p + 1, stdin))
    196 					break;
    197 				for (; *p &&  p < endp; ++p);
    198 				if (p == endp) {
    199 					*p = '\n';
    200 					*++p = '\0';
    201 					break;
    202 				}
    203 			}
    204 		}
    205 	}
    206 	mbuflen = strlen(mbuf);
    207 
    208 	if (offset)
    209 		(void)printf("Shutdown at %.24s.\n", ctime(&shuttime));
    210 	else
    211 		(void)printf("Shutdown NOW!\n");
    212 
    213 	if (!(whom = getlogin()))
    214 		whom = (pw = getpwuid(getuid())) ? pw->pw_name : "???";
    215 
    216 #ifdef DEBUG
    217 	(void)putc('\n', stdout);
    218 #else
    219 	(void)setpriority(PRIO_PROCESS, 0, PRIO_MIN);
    220 	if (nofork == 0) {
    221 		int forkpid;
    222 
    223 		forkpid = fork();
    224 		if (forkpid == -1) {
    225 			perror("shutdown: fork");
    226 			exit(1);
    227 		}
    228 		if (forkpid) {
    229 			(void)printf("shutdown: [pid %d]\n", forkpid);
    230 			exit(0);
    231 		}
    232 		(void)setsid();
    233 	}
    234 #endif
    235 	openlog("shutdown", LOG_CONS, LOG_AUTH);
    236 	loop();
    237 	/* NOTREACHED */
    238 #ifdef __GNUC__
    239 	return 1;
    240 #endif
    241 }
    242 
    243 void
    244 loop(void)
    245 {
    246 	const struct interval *tp;
    247 	u_int sltime;
    248 	int logged;
    249 
    250 	if (offset <= NOLOG_TIME) {
    251 		logged = 1;
    252 		nolog();
    253 	}
    254 	else
    255 		logged = 0;
    256 	tp = tlist;
    257 	if (tp->timeleft < offset)
    258 		(void)sleep((u_int)(offset - tp->timeleft));
    259 	else {
    260 		while (offset < tp->timeleft)
    261 			++tp;
    262 		/*
    263 		 * Warn now, if going to sleep more than a fifth of
    264 		 * the next wait time.
    265 		 */
    266 		if ((sltime = offset - tp->timeleft) != 0) {
    267 			if (sltime > tp->timetowait / 5)
    268 				timewarn(offset);
    269 			(void)sleep(sltime);
    270 		}
    271 	}
    272 	for (;; ++tp) {
    273 		timewarn(tp->timeleft);
    274 		if (!logged && tp->timeleft <= NOLOG_TIME) {
    275 			logged = 1;
    276 			nolog();
    277 		}
    278 		(void)sleep((u_int)tp->timetowait);
    279 		if (!tp->timeleft)
    280 			break;
    281 	}
    282 	die_you_gravy_sucking_pig_dog();
    283 }
    284 
    285 static jmp_buf alarmbuf;
    286 
    287 void
    288 timewarn(time_t timeleft)
    289 {
    290 	static int first;
    291 	static char hostname[MAXHOSTNAMELEN + 1];
    292 	FILE *pf;
    293 	char wcmd[MAXPATHLEN + 4];
    294 
    295 	if (!first++) {
    296 		(void)gethostname(hostname, sizeof(hostname));
    297 		hostname[sizeof(hostname) - 1] = '\0';
    298 	}
    299 
    300 	/* undoc -n option to wall suppresses normal wall banner */
    301 	(void)snprintf(wcmd, sizeof wcmd, "%s -n", _PATH_WALL);
    302 	if ((pf = popen(wcmd, "w")) == NULL) {
    303 		syslog(LOG_ERR, "%s: Can't find `%s' (%m)", getprogname(),
    304 		    _PATH_WALL);
    305 		return;
    306 	}
    307 
    308 	(void)fprintf(pf,
    309 	    "\007*** %sSystem shutdown message from %s@%s ***\007\n",
    310 	    timeleft ? "": "FINAL ", whom, hostname);
    311 
    312 	if (timeleft > 10*60)
    313 		(void)fprintf(pf, "System going down at %5.5s\n\n",
    314 		    ctime(&shuttime) + 11);
    315 	else if (timeleft > 59)
    316 		(void)fprintf(pf, "System going down in %ld minute%s\n\n",
    317 		    (long)timeleft / 60, (timeleft > 60) ? "s" : "");
    318 	else if (timeleft)
    319 		(void)fprintf(pf, "System going down in 30 seconds\n\n");
    320 	else
    321 		(void)fprintf(pf, "System going down IMMEDIATELY\n\n");
    322 
    323 	if (mbuflen)
    324 		(void)fwrite(mbuf, sizeof(*mbuf), mbuflen, pf);
    325 
    326 	/*
    327 	 * play some games, just in case wall doesn't come back
    328 	 * probably unnecessary, given that wall is careful.
    329 	 */
    330 	if (!setjmp(alarmbuf)) {
    331 		(void)signal(SIGALRM, timeout);
    332 		(void)alarm((u_int)30);
    333 		(void)pclose(pf);
    334 		(void)alarm((u_int)0);
    335 		(void)signal(SIGALRM, SIG_DFL);
    336 	}
    337 }
    338 
    339 static void
    340 /*ARGSUSED*/
    341 timeout(int signo)
    342 {
    343 	longjmp(alarmbuf, 1);
    344 }
    345 
    346 static void
    347 die_you_gravy_sucking_pig_dog(void)
    348 {
    349 
    350 	syslog(LOG_NOTICE, "%s by %s: %s",
    351 	    doreboot ? "reboot" : dohalt ? "halt" : "shutdown", whom, mbuf);
    352 	(void)sleep(2);
    353 
    354 	(void)printf("\r\nSystem shutdown time has arrived\007\007\r\n");
    355 	if (killflg) {
    356 		(void)printf("\rbut you'll have to do it yourself\r\n");
    357 		finish(0);
    358 	}
    359 	if (dofast)
    360 		doitfast();
    361 	dorcshutdown();
    362 	if (doreboot || dohalt) {
    363 		const char *args[16];
    364 		const char **arg, *path;
    365 		int serrno;
    366 
    367 		arg = &args[0];
    368 		if (doreboot) {
    369 			path = _PATH_REBOOT;
    370 			*arg++ = "reboot";
    371 		} else {
    372 			path = _PATH_HALT;
    373 			*arg++ = "halt";
    374 		}
    375 		if (dodump)
    376 			*arg++ = "-d";
    377 		if (nosync)
    378 			*arg++ = "-n";
    379 		if (dopowerdown)
    380 			*arg++ = "-p";
    381 		*arg++ = "-l";
    382 		if (bootstr)
    383 			*arg++ = bootstr;
    384 		*arg++ = 0;
    385 #ifndef DEBUG
    386 		(void)execve(path, __UNCONST(args), NULL);
    387 		serrno = errno;
    388 		syslog(LOG_ERR, "%s: Can't exec `%s' (%m)", getprogname(),
    389 		    path);
    390 		errno = serrno;
    391 		warn("Can't exec `%s'", path);
    392 #else
    393 		printf("%s", path);
    394 		for (arg = &args[0]; *arg; arg++)
    395 			printf(" %s", *arg);
    396 		printf("\n");
    397 #endif
    398 	} else {
    399 #ifndef DEBUG
    400 		(void)kill(1, SIGTERM);		/* to single user */
    401 #else
    402 		printf("kill 1\n");
    403 #endif
    404 	}
    405 	finish(0);
    406 }
    407 
    408 #define	ATOI2(s)	((s) += 2, ((s)[-2] - '0') * 10 + ((s)[-1] - '0'))
    409 
    410 void
    411 getoffset(char *timearg)
    412 {
    413 	struct tm *lt;
    414 	char *p;
    415 	time_t now;
    416 	int yearset;
    417 
    418 	(void)time(&now);
    419 	if (!strcasecmp(timearg, "now")) {		/* now */
    420 		offset = 0;
    421 		shuttime = now;
    422 		return;
    423 	}
    424 
    425 	if (*timearg == '+') {				/* +minutes */
    426 		if (!isdigit((unsigned char)*++timearg))
    427 			badtime();
    428 		offset = atoi(timearg) * 60;
    429 		shuttime = now + offset;
    430 		return;
    431 	}
    432 
    433 	/* handle hh:mm by getting rid of the colon */
    434 	for (p = timearg; *p; ++p)
    435 		if (!isascii(*p) || !isdigit((unsigned char)*p)) {
    436 			if (*p == ':' && strlen(p) == 3) {
    437 				p[0] = p[1];
    438 				p[1] = p[2];
    439 				p[2] = '\0';
    440 			}
    441 			else
    442 				badtime();
    443 		}
    444 
    445 	(void)unsetenv("TZ");				/* OUR timezone */
    446 	lt = localtime(&now);				/* current time val */
    447 
    448 	lt->tm_sec = 0;
    449 
    450 	yearset = 0;
    451 	switch (strlen(timearg)) {
    452 	case 12:
    453 		lt->tm_year = ATOI2(timearg) * 100 - TM_YEAR_BASE;
    454 		yearset = 1;
    455 		/* FALLTHROUGH */
    456 	case 10:
    457 		if (yearset) {
    458 			lt->tm_year += ATOI2(timearg);
    459 		} else {
    460 			yearset = ATOI2(timearg);
    461 			if (yearset < 69)
    462 				lt->tm_year = yearset + 2000 - TM_YEAR_BASE;
    463 			else
    464 				lt->tm_year = yearset + 1900 - TM_YEAR_BASE;
    465 		}
    466 		/* FALLTHROUGH */
    467 	case 8:
    468 		lt->tm_mon = ATOI2(timearg);
    469 		--lt->tm_mon;
    470 		/* FALLTHROUGH */
    471 	case 6:
    472 		lt->tm_mday = ATOI2(timearg);
    473 		/* FALLTHROUGH */
    474 	case 4:
    475 		lt->tm_hour = ATOI2(timearg);
    476 		/* FALLTHROUGH */
    477 	case 2:
    478 		lt->tm_min = ATOI2(timearg);
    479 		break;
    480 	default:
    481 		badtime();
    482 	}
    483 
    484 	if ((shuttime = mktime(lt)) == -1)
    485 		badtime();
    486 	if ((offset = shuttime - now) < 0)
    487 		errx(1, "time is already past");
    488 }
    489 
    490 void
    491 dorcshutdown(void)
    492 {
    493 	(void)printf("\r\nAbout to run shutdown hooks...\r\n");
    494 #ifndef DEBUG
    495 	(void)setuid(0);
    496 	(void)system(". " _PATH_RCSHUTDOWN);
    497 #endif
    498 	(void)sleep(5);		/* Give operator a chance to abort this. */
    499 	(void)printf("\r\nDone running shutdown hooks.\r\n");
    500 }
    501 
    502 #define	FSMSG	"fastboot file for fsck\n"
    503 void
    504 doitfast(void)
    505 {
    506 	int fastfd;
    507 
    508 	if ((fastfd = open(_PATH_FASTBOOT, O_WRONLY|O_CREAT|O_TRUNC,
    509 	    0664)) >= 0) {
    510 		(void)write(fastfd, FSMSG, sizeof(FSMSG) - 1);
    511 		(void)close(fastfd);
    512 	}
    513 }
    514 
    515 #define	NOMSG	"\n\nNO LOGINS: System going down at "
    516 void
    517 nolog(void)
    518 {
    519 	int logfd;
    520 	char *ct;
    521 
    522 	(void)unlink(_PATH_NOLOGIN);	/* in case linked to another file */
    523 	(void)signal(SIGINT, finish);
    524 	(void)signal(SIGHUP, finish);
    525 	(void)signal(SIGQUIT, finish);
    526 	(void)signal(SIGTERM, finish);
    527 	if ((logfd = open(_PATH_NOLOGIN, O_WRONLY|O_CREAT|O_TRUNC,
    528 	    0664)) >= 0) {
    529 		(void)write(logfd, NOMSG, sizeof(NOMSG) - 1);
    530 		ct = ctime(&shuttime);
    531 		(void)write(logfd, ct + 11, 5);
    532 		(void)write(logfd, "\n\n", 2);
    533 		(void)write(logfd, mbuf, strlen(mbuf));
    534 		(void)close(logfd);
    535 	}
    536 }
    537 
    538 static void
    539 /*ARGSUSED*/
    540 finish(int signo)
    541 {
    542 
    543 	if (!killflg)
    544 		(void)unlink(_PATH_NOLOGIN);
    545 	exit(0);
    546 }
    547 
    548 static void
    549 badtime(void)
    550 {
    551 
    552 	warnx("illegal time format");
    553 	usage();
    554 }
    555 
    556 static void
    557 usage(void)
    558 {
    559 
    560 	(void)fprintf(stderr,
    561 	    "Usage: %s [-Ddfhknpr] time [message ... | -]\n",
    562 	    getprogname());
    563 	exit(1);
    564 }
    565