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