Home | History | Annotate | Line # | Download | only in shutdown
shutdown.c revision 1.41
      1 /*	$NetBSD: shutdown.c,v 1.41 2004/10/09 02:51:19 dsainty 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.41 2004/10/09 02:51:19 dsainty 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 
     64 #include "pathnames.h"
     65 
     66 #ifdef DEBUG
     67 #undef _PATH_NOLOGIN
     68 #define	_PATH_NOLOGIN	"./nologin"
     69 #undef _PATH_FASTBOOT
     70 #define	_PATH_FASTBOOT	"./fastboot"
     71 #endif
     72 
     73 #define	H		*60*60
     74 #define	M		*60
     75 #define	S		*1
     76 #define	NOLOG_TIME	5*60
     77 struct interval {
     78 	int timeleft, timetowait;
     79 } tlist[] = {
     80 	{ 10 H,  5 H },	{  5 H,  3 H },	{  2 H,  1 H },	{ 1 H, 30 M },
     81 	{ 30 M, 10 M },	{ 20 M, 10 M },	{ 10 M,  5 M },	{ 5 M,  3 M },
     82 	{  2 M,  1 M },	{  1 M, 30 S },	{ 30 S, 30 S },
     83 	{  0, 0 }
     84 };
     85 #undef H
     86 #undef M
     87 #undef S
     88 
     89 static time_t offset, shuttime;
     90 static int dofast, dohalt, doreboot, killflg, mbuflen, nofork, nosync, dodump;
     91 static int dopowerdown;
     92 static const char *whom;
     93 static char mbuf[BUFSIZ];
     94 char *bootstr;
     95 
     96 void badtime __P((void));
     97 void die_you_gravy_sucking_pig_dog __P((void));
     98 void doitfast __P((void));
     99 void dorcshutdown __P((void));
    100 void finish __P((int));
    101 void getoffset __P((char *));
    102 void loop __P((void));
    103 int main __P((int, char *[]));
    104 void nolog __P((void));
    105 void timeout __P((int));
    106 void timewarn __P((int));
    107 void usage __P((void));
    108 
    109 int
    110 main(argc, argv)
    111 	int argc;
    112 	char *argv[];
    113 {
    114 	char *p, *endp;
    115 	struct passwd *pw;
    116 	int arglen, ch, len;
    117 
    118 #ifndef DEBUG
    119 	if (geteuid())
    120 		errx(1, "NOT super-user");
    121 #endif
    122 	while ((ch = getopt(argc, argv, "b:Ddfhknpr")) != -1)
    123 		switch (ch) {
    124 		case 'b':
    125 			bootstr = optarg;
    126 			break;
    127 		case 'd':
    128 			dodump = 1;
    129 			break;
    130 		case 'D':
    131 			nofork = 1;
    132 			break;
    133 		case 'f':
    134 			dofast = 1;
    135 			break;
    136 		case 'p':
    137 			dopowerdown = 1;
    138 			/* FALLTHROUGH */
    139 		case 'h':
    140 			dohalt = 1;
    141 			break;
    142 		case 'k':
    143 			killflg = 1;
    144 			break;
    145 		case 'n':
    146 			nosync = 1;
    147 			break;
    148 		case 'r':
    149 			doreboot = 1;
    150 			break;
    151 		case '?':
    152 		default:
    153 			usage();
    154 		}
    155 	argc -= optind;
    156 	argv += optind;
    157 
    158 	if (argc < 1)
    159 		usage();
    160 
    161 	if (dodump && !dohalt && !doreboot)
    162 		doreboot = 1;
    163 
    164 	if (dofast && nosync) {
    165 		warnx("incompatible switches -f and -n");
    166 		usage();
    167 	}
    168 	if (dohalt && doreboot) {
    169 		const char *which_flag = dopowerdown ? "p" : "h";
    170 
    171 		warnx("incompatible switches -%s and -r", which_flag);
    172 		usage();
    173 	}
    174 
    175 	getoffset(*argv++);
    176 
    177 	if (argv[0]) {
    178 		if (strcmp(argv[0], "-") || argv[1]) {
    179 			for (p = mbuf, len = sizeof(mbuf); *argv; ++argv) {
    180 				arglen = strlen(*argv);
    181 				if ((len -= arglen) <= 2)
    182 					break;
    183 				if (p != mbuf)
    184 					*p++ = ' ';
    185 				memmove(p, *argv, arglen);
    186 				p += arglen;
    187 			}
    188 			*p = '\n';
    189 			*++p = '\0';
    190 		} else {
    191 			p = mbuf;
    192 			endp = mbuf + sizeof(mbuf) - 2;
    193 			for (;;) {
    194 				if (!fgets(p, endp - p + 1, stdin))
    195 					break;
    196 				for (; *p &&  p < endp; ++p);
    197 				if (p == endp) {
    198 					*p = '\n';
    199 					*++p = '\0';
    200 					break;
    201 				}
    202 			}
    203 		}
    204 	}
    205 	mbuflen = strlen(mbuf);
    206 
    207 	if (offset)
    208 		(void)printf("Shutdown at %.24s.\n", ctime(&shuttime));
    209 	else
    210 		(void)printf("Shutdown NOW!\n");
    211 
    212 	if (!(whom = getlogin()))
    213 		whom = (pw = getpwuid(getuid())) ? pw->pw_name : "???";
    214 
    215 #ifdef DEBUG
    216 	(void)putc('\n', stdout);
    217 #else
    218 	(void)setpriority(PRIO_PROCESS, 0, PRIO_MIN);
    219 	if (nofork == 0) {
    220 		int forkpid;
    221 
    222 		forkpid = fork();
    223 		if (forkpid == -1) {
    224 			perror("shutdown: fork");
    225 			exit(1);
    226 		}
    227 		if (forkpid) {
    228 			(void)printf("shutdown: [pid %d]\n", forkpid);
    229 			exit(0);
    230 		}
    231 	}
    232 #endif
    233 	openlog("shutdown", LOG_CONS, LOG_AUTH);
    234 	loop();
    235 	/* NOTREACHED */
    236 #ifdef __GNUC__
    237 	return 1;
    238 #endif
    239 }
    240 
    241 void
    242 loop()
    243 {
    244 	struct interval *tp;
    245 	u_int sltime;
    246 	int logged;
    247 
    248 	if (offset <= NOLOG_TIME) {
    249 		logged = 1;
    250 		nolog();
    251 	}
    252 	else
    253 		logged = 0;
    254 	tp = tlist;
    255 	if (tp->timeleft < offset)
    256 		(void)sleep((u_int)(offset - tp->timeleft));
    257 	else {
    258 		while (offset < tp->timeleft)
    259 			++tp;
    260 		/*
    261 		 * Warn now, if going to sleep more than a fifth of
    262 		 * the next wait time.
    263 		 */
    264 		if ((sltime = offset - tp->timeleft) != 0) {
    265 			if (sltime > tp->timetowait / 5)
    266 				timewarn(offset);
    267 			(void)sleep(sltime);
    268 		}
    269 	}
    270 	for (;; ++tp) {
    271 		timewarn(tp->timeleft);
    272 		if (!logged && tp->timeleft <= NOLOG_TIME) {
    273 			logged = 1;
    274 			nolog();
    275 		}
    276 		(void)sleep((u_int)tp->timetowait);
    277 		if (!tp->timeleft)
    278 			break;
    279 	}
    280 	die_you_gravy_sucking_pig_dog();
    281 }
    282 
    283 static jmp_buf alarmbuf;
    284 
    285 void
    286 timewarn(timeleft)
    287 	int timeleft;
    288 {
    289 	static int first;
    290 	static char hostname[MAXHOSTNAMELEN + 1];
    291 	FILE *pf;
    292 	char wcmd[MAXPATHLEN + 4];
    293 
    294 	if (!first++) {
    295 		(void)gethostname(hostname, sizeof(hostname));
    296 		hostname[sizeof(hostname) - 1] = '\0';
    297 	}
    298 
    299 	/* undoc -n option to wall suppresses normal wall banner */
    300 	(void)snprintf(wcmd, sizeof wcmd, "%s -n", _PATH_WALL);
    301 	if (!(pf = popen(wcmd, "w"))) {
    302 		syslog(LOG_ERR, "shutdown: can't find %s: %m", _PATH_WALL);
    303 		return;
    304 	}
    305 
    306 	(void)fprintf(pf,
    307 	    "\007*** %sSystem shutdown message from %s@%s ***\007\n",
    308 	    timeleft ? "": "FINAL ", whom, hostname);
    309 
    310 	if (timeleft > 10*60)
    311 		(void)fprintf(pf, "System going down at %5.5s\n\n",
    312 		    ctime(&shuttime) + 11);
    313 	else if (timeleft > 59)
    314 		(void)fprintf(pf, "System going down in %d minute%s\n\n",
    315 		    timeleft / 60, (timeleft > 60) ? "s" : "");
    316 	else if (timeleft)
    317 		(void)fprintf(pf, "System going down in 30 seconds\n\n");
    318 	else
    319 		(void)fprintf(pf, "System going down IMMEDIATELY\n\n");
    320 
    321 	if (mbuflen)
    322 		(void)fwrite(mbuf, sizeof(*mbuf), mbuflen, pf);
    323 
    324 	/*
    325 	 * play some games, just in case wall doesn't come back
    326 	 * probably unnecessary, given that wall is careful.
    327 	 */
    328 	if (!setjmp(alarmbuf)) {
    329 		(void)signal(SIGALRM, timeout);
    330 		(void)alarm((u_int)30);
    331 		(void)pclose(pf);
    332 		(void)alarm((u_int)0);
    333 		(void)signal(SIGALRM, SIG_DFL);
    334 	}
    335 }
    336 
    337 void
    338 timeout(signo)
    339 	int signo;
    340 {
    341 	longjmp(alarmbuf, 1);
    342 }
    343 
    344 void
    345 die_you_gravy_sucking_pig_dog()
    346 {
    347 
    348 	syslog(LOG_NOTICE, "%s by %s: %s",
    349 	    doreboot ? "reboot" : dohalt ? "halt" : "shutdown", whom, mbuf);
    350 	(void)sleep(2);
    351 
    352 	(void)printf("\r\nSystem shutdown time has arrived\007\007\r\n");
    353 	if (killflg) {
    354 		(void)printf("\rbut you'll have to do it yourself\r\n");
    355 		finish(0);
    356 	}
    357 	if (dofast)
    358 		doitfast();
    359 	dorcshutdown();
    360 	if (doreboot || dohalt) {
    361 		char *args[16], **arg, *path;
    362 
    363 		arg = &args[0];
    364 		if (doreboot) {
    365 			path = _PATH_REBOOT;
    366 			*arg++ = "reboot";
    367 		} else {
    368 			path = _PATH_HALT;
    369 			*arg++ = "halt";
    370 		}
    371 		if (dodump)
    372 			*arg++ = "-d";
    373 		if (nosync)
    374 			*arg++ = "-n";
    375 		if (dopowerdown)
    376 			*arg++ = "-p";
    377 		*arg++ = "-l";
    378 		if (bootstr)
    379 			*arg++ = bootstr;
    380 		*arg++ = 0;
    381 #ifndef DEBUG
    382 		execve(path, args, (char **)0);
    383 		syslog(LOG_ERR, "shutdown: can't exec %s: %m", path);
    384 		perror("shutdown");
    385 #else
    386 		printf("%s", path);
    387 		for (arg = &args[0]; *arg; arg++)
    388 			printf(" %s", *arg);
    389 		printf("\n");
    390 #endif
    391 	} else {
    392 #ifndef DEBUG
    393 		(void)kill(1, SIGTERM);		/* to single user */
    394 #else
    395 		printf("kill 1\n");
    396 #endif
    397 	}
    398 	finish(0);
    399 }
    400 
    401 #define	ATOI2(s)	((s) += 2, ((s)[-2] - '0') * 10 + ((s)[-1] - '0'))
    402 
    403 void
    404 getoffset(timearg)
    405 	char *timearg;
    406 {
    407 	struct tm *lt;
    408 	char *p;
    409 	time_t now;
    410 	int yearset;
    411 
    412 	(void)time(&now);
    413 	if (!strcasecmp(timearg, "now")) {		/* now */
    414 		offset = 0;
    415 		shuttime = now;
    416 		return;
    417 	}
    418 
    419 	if (*timearg == '+') {				/* +minutes */
    420 		if (!isdigit(*++timearg))
    421 			badtime();
    422 		offset = atoi(timearg) * 60;
    423 		shuttime = now + offset;
    424 		return;
    425 	}
    426 
    427 	/* handle hh:mm by getting rid of the colon */
    428 	for (p = timearg; *p; ++p)
    429 		if (!isascii(*p) || !isdigit(*p)) {
    430 			if (*p == ':' && strlen(p) == 3) {
    431 				p[0] = p[1];
    432 				p[1] = p[2];
    433 				p[2] = '\0';
    434 			}
    435 			else
    436 				badtime();
    437 		}
    438 
    439 	unsetenv("TZ");					/* OUR timezone */
    440 	lt = localtime(&now);				/* current time val */
    441 
    442 	lt->tm_sec = 0;
    443 
    444 	yearset = 0;
    445 	switch (strlen(timearg)) {
    446 	case 12:
    447 		lt->tm_year = ATOI2(timearg) * 100 - TM_YEAR_BASE;
    448 		yearset = 1;
    449 		/* FALLTHROUGH */
    450 	case 10:
    451 		if (yearset) {
    452 			lt->tm_year += ATOI2(timearg);
    453 		} else {
    454 			yearset = ATOI2(timearg);
    455 			if (yearset < 69)
    456 				lt->tm_year = yearset + 2000 - TM_YEAR_BASE;
    457 			else
    458 				lt->tm_year = yearset + 1900 - TM_YEAR_BASE;
    459 		}
    460 		/* FALLTHROUGH */
    461 	case 8:
    462 		lt->tm_mon = ATOI2(timearg);
    463 		--lt->tm_mon;
    464 		/* FALLTHROUGH */
    465 	case 6:
    466 		lt->tm_mday = ATOI2(timearg);
    467 		/* FALLTHROUGH */
    468 	case 4:
    469 		lt->tm_hour = ATOI2(timearg);
    470 		/* FALLTHROUGH */
    471 	case 2:
    472 		lt->tm_min = ATOI2(timearg);
    473 		break;
    474 	default:
    475 		badtime();
    476 	}
    477 
    478 	if ((shuttime = mktime(lt)) == -1)
    479 		badtime();
    480 	if ((offset = shuttime - now) < 0)
    481 		errx(1, "time is already past");
    482 }
    483 
    484 void
    485 dorcshutdown()
    486 {
    487 	(void)printf("\r\nAbout to run shutdown hooks...\r\n");
    488 	(void)system(". " _PATH_RCSHUTDOWN);
    489 	(void)sleep(5);		/* Give operator a chance to abort this. */
    490 	(void)printf("\r\nDone running shutdown hooks.\r\n");
    491 }
    492 
    493 #define	FSMSG	"fastboot file for fsck\n"
    494 void
    495 doitfast()
    496 {
    497 	int fastfd;
    498 
    499 	if ((fastfd = open(_PATH_FASTBOOT, O_WRONLY|O_CREAT|O_TRUNC,
    500 	    0664)) >= 0) {
    501 		(void)write(fastfd, FSMSG, sizeof(FSMSG) - 1);
    502 		(void)close(fastfd);
    503 	}
    504 }
    505 
    506 #define	NOMSG	"\n\nNO LOGINS: System going down at "
    507 void
    508 nolog()
    509 {
    510 	int logfd;
    511 	char *ct;
    512 
    513 	(void)unlink(_PATH_NOLOGIN);	/* in case linked to another file */
    514 	(void)signal(SIGINT, finish);
    515 	(void)signal(SIGHUP, finish);
    516 	(void)signal(SIGQUIT, finish);
    517 	(void)signal(SIGTERM, finish);
    518 	if ((logfd = open(_PATH_NOLOGIN, O_WRONLY|O_CREAT|O_TRUNC,
    519 	    0664)) >= 0) {
    520 		(void)write(logfd, NOMSG, sizeof(NOMSG) - 1);
    521 		ct = ctime(&shuttime);
    522 		(void)write(logfd, ct + 11, 5);
    523 		(void)write(logfd, "\n\n", 2);
    524 		(void)write(logfd, mbuf, strlen(mbuf));
    525 		(void)close(logfd);
    526 	}
    527 }
    528 
    529 void
    530 finish(signo)
    531 	int signo;
    532 {
    533 
    534 	if (!killflg)
    535 		(void)unlink(_PATH_NOLOGIN);
    536 	exit(0);
    537 }
    538 
    539 void
    540 badtime()
    541 {
    542 
    543 	warnx("illegal time format");
    544 	usage();
    545 }
    546 
    547 void
    548 usage()
    549 {
    550 
    551 	(void)fprintf(stderr,
    552 	    "usage: shutdown [-Ddfhknpr] time [message ... | -]\n");
    553 	exit(1);
    554 }
    555