Home | History | Annotate | Line # | Download | only in shutdown
shutdown.c revision 1.37
      1 /*	$NetBSD: shutdown.c,v 1.37 2000/07/25 18:59:44 jdolecek 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. All advertising materials mentioning features or use of this software
     16  *    must display the following acknowledgement:
     17  *	This product includes software developed by the University of
     18  *	California, Berkeley and its contributors.
     19  * 4. Neither the name of the University nor the names of its contributors
     20  *    may be used to endorse or promote products derived from this software
     21  *    without specific prior written permission.
     22  *
     23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     33  * SUCH DAMAGE.
     34  */
     35 
     36 #include <sys/cdefs.h>
     37 #ifndef lint
     38 __COPYRIGHT("@(#) Copyright (c) 1988, 1990, 1993\n\
     39 	The Regents of the University of California.  All rights reserved.\n");
     40 #endif /* not lint */
     41 
     42 #ifndef lint
     43 #if 0
     44 static char sccsid[] = "@(#)shutdown.c	8.4 (Berkeley) 4/28/95";
     45 #else
     46 __RCSID("$NetBSD: shutdown.c,v 1.37 2000/07/25 18:59:44 jdolecek Exp $");
     47 #endif
     48 #endif /* not lint */
     49 
     50 #include <sys/param.h>
     51 #include <sys/time.h>
     52 #include <sys/resource.h>
     53 #include <sys/syslog.h>
     54 
     55 #include <ctype.h>
     56 #include <err.h>
     57 #include <fcntl.h>
     58 #include <pwd.h>
     59 #include <setjmp.h>
     60 #include <signal.h>
     61 #include <stdio.h>
     62 #include <stdlib.h>
     63 #include <string.h>
     64 #include <time.h>
     65 #include <tzfile.h>
     66 #include <unistd.h>
     67 
     68 #include "pathnames.h"
     69 
     70 #ifdef DEBUG
     71 #undef _PATH_NOLOGIN
     72 #define	_PATH_NOLOGIN	"./nologin"
     73 #undef _PATH_FASTBOOT
     74 #define	_PATH_FASTBOOT	"./fastboot"
     75 #endif
     76 
     77 #define	H		*60*60
     78 #define	M		*60
     79 #define	S		*1
     80 #define	NOLOG_TIME	5*60
     81 struct interval {
     82 	int timeleft, timetowait;
     83 } tlist[] = {
     84 	{ 10 H,  5 H },	{  5 H,  3 H },	{  2 H,  1 H },	{ 1 H, 30 M },
     85 	{ 30 M, 10 M },	{ 20 M, 10 M },	{ 10 M,  5 M },	{ 5 M,  3 M },
     86 	{  2 M,  1 M },	{  1 M, 30 S },	{ 30 S, 30 S },
     87 	{  0, 0 }
     88 };
     89 #undef H
     90 #undef M
     91 #undef S
     92 
     93 static time_t offset, shuttime;
     94 static int dofast, dohalt, doreboot, killflg, mbuflen, nofork, nosync, dodump;
     95 static int dopowerdown;
     96 static const char *whom;
     97 static char mbuf[BUFSIZ];
     98 
     99 void badtime __P((void));
    100 void die_you_gravy_sucking_pig_dog __P((void));
    101 void doitfast __P((void));
    102 void dorcshutdown __P((void));
    103 void finish __P((int));
    104 void getoffset __P((char *));
    105 void loop __P((void));
    106 int main __P((int, char *[]));
    107 void nolog __P((void));
    108 void timeout __P((int));
    109 void timewarn __P((int));
    110 void usage __P((void));
    111 
    112 int
    113 main(argc, argv)
    114 	int argc;
    115 	char *argv[];
    116 {
    117 	char *p, *endp;
    118 	struct passwd *pw;
    119 	int arglen, ch, len;
    120 
    121 #ifndef DEBUG
    122 	if (geteuid())
    123 		errx(1, "NOT super-user");
    124 #endif
    125 	while ((ch = getopt(argc, argv, "Ddfhknpr")) != -1)
    126 		switch (ch) {
    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 unecessary, 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 		*arg++ = 0;
    379 #ifndef DEBUG
    380 		execve(path, args, (char **)0);
    381 		syslog(LOG_ERR, "shutdown: can't exec %s: %m", path);
    382 		perror("shutdown");
    383 #else
    384 		printf("%s", path);
    385 		for (arg = &args[0]; *arg; arg++)
    386 			printf(" %s", *arg);
    387 		printf("\n");
    388 #endif
    389 	} else {
    390 #ifndef DEBUG
    391 		(void)kill(1, SIGTERM);		/* to single user */
    392 #else
    393 		printf("kill 1\n");
    394 #endif
    395 	}
    396 	finish(0);
    397 }
    398 
    399 #define	ATOI2(s)	((s) += 2, ((s)[-2] - '0') * 10 + ((s)[-1] - '0'))
    400 
    401 void
    402 getoffset(timearg)
    403 	char *timearg;
    404 {
    405 	struct tm *lt;
    406 	char *p;
    407 	time_t now;
    408 	int yearset;
    409 
    410 	(void)time(&now);
    411 	if (!strcasecmp(timearg, "now")) {		/* now */
    412 		offset = 0;
    413 		shuttime = now;
    414 		return;
    415 	}
    416 
    417 	if (*timearg == '+') {				/* +minutes */
    418 		if (!isdigit(*++timearg))
    419 			badtime();
    420 		offset = atoi(timearg) * 60;
    421 		shuttime = now + offset;
    422 		return;
    423 	}
    424 
    425 	/* handle hh:mm by getting rid of the colon */
    426 	for (p = timearg; *p; ++p)
    427 		if (!isascii(*p) || !isdigit(*p)) {
    428 			if (*p == ':' && strlen(p) == 3) {
    429 				p[0] = p[1];
    430 				p[1] = p[2];
    431 				p[2] = '\0';
    432 			}
    433 			else
    434 				badtime();
    435 		}
    436 
    437 	unsetenv("TZ");					/* OUR timezone */
    438 	lt = localtime(&now);				/* current time val */
    439 
    440 	lt->tm_sec = 0;
    441 
    442 	yearset = 0;
    443 	switch (strlen(timearg)) {
    444 	case 12:
    445 		lt->tm_year = ATOI2(timearg) * 100 - TM_YEAR_BASE;
    446 		yearset = 1;
    447 		/* FALLTHROUGH */
    448 	case 10:
    449 		if (yearset) {
    450 			lt->tm_year += ATOI2(timearg);
    451 		} else {
    452 			yearset = ATOI2(timearg);
    453 			if (yearset < 69)
    454 				lt->tm_year = yearset + 2000 - TM_YEAR_BASE;
    455 			else
    456 				lt->tm_year = yearset + 1900 - TM_YEAR_BASE;
    457 		}
    458 		/* FALLTHROUGH */
    459 	case 8:
    460 		lt->tm_mon = ATOI2(timearg);
    461 		--lt->tm_mon;
    462 		/* FALLTHROUGH */
    463 	case 6:
    464 		lt->tm_mday = ATOI2(timearg);
    465 		/* FALLTHROUGH */
    466 	case 4:
    467 		lt->tm_hour = ATOI2(timearg);
    468 		/* FALLTHROUGH */
    469 	case 2:
    470 		lt->tm_min = ATOI2(timearg);
    471 		break;
    472 	default:
    473 		badtime();
    474 	}
    475 
    476 	if ((shuttime = mktime(lt)) == -1)
    477 		badtime();
    478 	if ((offset = shuttime - now) < 0)
    479 		errx(1, "time is already past");
    480 }
    481 
    482 void
    483 dorcshutdown()
    484 {
    485 	(void)printf("\r\nAbout to run shutdown hooks...\r\n");
    486 	(void)system(__CONCAT(". ", _PATH_RCSHUTDOWN));
    487 	(void)sleep(5);		/* Give operator a chance to abort this. */
    488 	(void)printf("\r\nDone running shutdown hooks.\r\n");
    489 }
    490 
    491 #define	FSMSG	"fastboot file for fsck\n"
    492 void
    493 doitfast()
    494 {
    495 	int fastfd;
    496 
    497 	if ((fastfd = open(_PATH_FASTBOOT, O_WRONLY|O_CREAT|O_TRUNC,
    498 	    0664)) >= 0) {
    499 		(void)write(fastfd, FSMSG, sizeof(FSMSG) - 1);
    500 		(void)close(fastfd);
    501 	}
    502 }
    503 
    504 #define	NOMSG	"\n\nNO LOGINS: System going down at "
    505 void
    506 nolog()
    507 {
    508 	int logfd;
    509 	char *ct;
    510 
    511 	(void)unlink(_PATH_NOLOGIN);	/* in case linked to another file */
    512 	(void)signal(SIGINT, finish);
    513 	(void)signal(SIGHUP, finish);
    514 	(void)signal(SIGQUIT, finish);
    515 	(void)signal(SIGTERM, finish);
    516 	if ((logfd = open(_PATH_NOLOGIN, O_WRONLY|O_CREAT|O_TRUNC,
    517 	    0664)) >= 0) {
    518 		(void)write(logfd, NOMSG, sizeof(NOMSG) - 1);
    519 		ct = ctime(&shuttime);
    520 		(void)write(logfd, ct + 11, 5);
    521 		(void)write(logfd, "\n\n", 2);
    522 		(void)write(logfd, mbuf, strlen(mbuf));
    523 		(void)close(logfd);
    524 	}
    525 }
    526 
    527 void
    528 finish(signo)
    529 	int signo;
    530 {
    531 
    532 	if (!killflg)
    533 		(void)unlink(_PATH_NOLOGIN);
    534 	exit(0);
    535 }
    536 
    537 void
    538 badtime()
    539 {
    540 
    541 	warnx("illegal time format");
    542 	usage();
    543 }
    544 
    545 void
    546 usage()
    547 {
    548 
    549 	(void)fprintf(stderr,
    550 	    "usage: shutdown [-Ddfhknpr] time [message ... | -]\n");
    551 	exit(1);
    552 }
    553