Home | History | Annotate | Line # | Download | only in shutdown
shutdown.c revision 1.46
      1 /*	$NetBSD: shutdown.c,v 1.46 2006/03/07 22:19:55 jnemeth 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.46 2006/03/07 22:19:55 jnemeth 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 		(void)setsid();
    229 	}
    230 #endif
    231 	openlog("shutdown", LOG_CONS, LOG_AUTH);
    232 	loop();
    233 	/* NOTREACHED */
    234 #ifdef __GNUC__
    235 	return 1;
    236 #endif
    237 }
    238 
    239 void
    240 loop(void)
    241 {
    242 	struct interval *tp;
    243 	u_int sltime;
    244 	int logged;
    245 
    246 	if (offset <= NOLOG_TIME) {
    247 		logged = 1;
    248 		nolog();
    249 	}
    250 	else
    251 		logged = 0;
    252 	tp = tlist;
    253 	if (tp->timeleft < offset)
    254 		(void)sleep((u_int)(offset - tp->timeleft));
    255 	else {
    256 		while (offset < tp->timeleft)
    257 			++tp;
    258 		/*
    259 		 * Warn now, if going to sleep more than a fifth of
    260 		 * the next wait time.
    261 		 */
    262 		if ((sltime = offset - tp->timeleft) != 0) {
    263 			if (sltime > tp->timetowait / 5)
    264 				timewarn(offset);
    265 			(void)sleep(sltime);
    266 		}
    267 	}
    268 	for (;; ++tp) {
    269 		timewarn(tp->timeleft);
    270 		if (!logged && tp->timeleft <= NOLOG_TIME) {
    271 			logged = 1;
    272 			nolog();
    273 		}
    274 		(void)sleep((u_int)tp->timetowait);
    275 		if (!tp->timeleft)
    276 			break;
    277 	}
    278 	die_you_gravy_sucking_pig_dog();
    279 }
    280 
    281 static jmp_buf alarmbuf;
    282 
    283 void
    284 timewarn(int timeleft)
    285 {
    286 	static int first;
    287 	static char hostname[MAXHOSTNAMELEN + 1];
    288 	FILE *pf;
    289 	char wcmd[MAXPATHLEN + 4];
    290 
    291 	if (!first++) {
    292 		(void)gethostname(hostname, sizeof(hostname));
    293 		hostname[sizeof(hostname) - 1] = '\0';
    294 	}
    295 
    296 	/* undoc -n option to wall suppresses normal wall banner */
    297 	(void)snprintf(wcmd, sizeof wcmd, "%s -n", _PATH_WALL);
    298 	if (!(pf = popen(wcmd, "w"))) {
    299 		syslog(LOG_ERR, "shutdown: can't find %s: %m", _PATH_WALL);
    300 		return;
    301 	}
    302 
    303 	(void)fprintf(pf,
    304 	    "\007*** %sSystem shutdown message from %s@%s ***\007\n",
    305 	    timeleft ? "": "FINAL ", whom, hostname);
    306 
    307 	if (timeleft > 10*60)
    308 		(void)fprintf(pf, "System going down at %5.5s\n\n",
    309 		    ctime(&shuttime) + 11);
    310 	else if (timeleft > 59)
    311 		(void)fprintf(pf, "System going down in %d minute%s\n\n",
    312 		    timeleft / 60, (timeleft > 60) ? "s" : "");
    313 	else if (timeleft)
    314 		(void)fprintf(pf, "System going down in 30 seconds\n\n");
    315 	else
    316 		(void)fprintf(pf, "System going down IMMEDIATELY\n\n");
    317 
    318 	if (mbuflen)
    319 		(void)fwrite(mbuf, sizeof(*mbuf), mbuflen, pf);
    320 
    321 	/*
    322 	 * play some games, just in case wall doesn't come back
    323 	 * probably unnecessary, given that wall is careful.
    324 	 */
    325 	if (!setjmp(alarmbuf)) {
    326 		(void)signal(SIGALRM, timeout);
    327 		(void)alarm((u_int)30);
    328 		(void)pclose(pf);
    329 		(void)alarm((u_int)0);
    330 		(void)signal(SIGALRM, SIG_DFL);
    331 	}
    332 }
    333 
    334 void
    335 timeout(int signo)
    336 {
    337 	longjmp(alarmbuf, 1);
    338 }
    339 
    340 void
    341 die_you_gravy_sucking_pig_dog(void)
    342 {
    343 
    344 	syslog(LOG_NOTICE, "%s by %s: %s",
    345 	    doreboot ? "reboot" : dohalt ? "halt" : "shutdown", whom, mbuf);
    346 	(void)sleep(2);
    347 
    348 	(void)printf("\r\nSystem shutdown time has arrived\007\007\r\n");
    349 	if (killflg) {
    350 		(void)printf("\rbut you'll have to do it yourself\r\n");
    351 		finish(0);
    352 	}
    353 	if (dofast)
    354 		doitfast();
    355 	dorcshutdown();
    356 	if (doreboot || dohalt) {
    357 		const char *args[16];
    358 		const char **arg, *path;
    359 
    360 		arg = &args[0];
    361 		if (doreboot) {
    362 			path = _PATH_REBOOT;
    363 			*arg++ = "reboot";
    364 		} else {
    365 			path = _PATH_HALT;
    366 			*arg++ = "halt";
    367 		}
    368 		if (dodump)
    369 			*arg++ = "-d";
    370 		if (nosync)
    371 			*arg++ = "-n";
    372 		if (dopowerdown)
    373 			*arg++ = "-p";
    374 		*arg++ = "-l";
    375 		if (bootstr)
    376 			*arg++ = bootstr;
    377 		*arg++ = 0;
    378 #ifndef DEBUG
    379 		execve(path, __UNCONST(args), NULL);
    380 		syslog(LOG_ERR, "shutdown: can't exec %s: %m", path);
    381 		perror("shutdown");
    382 #else
    383 		printf("%s", path);
    384 		for (arg = &args[0]; *arg; arg++)
    385 			printf(" %s", *arg);
    386 		printf("\n");
    387 #endif
    388 	} else {
    389 #ifndef DEBUG
    390 		(void)kill(1, SIGTERM);		/* to single user */
    391 #else
    392 		printf("kill 1\n");
    393 #endif
    394 	}
    395 	finish(0);
    396 }
    397 
    398 #define	ATOI2(s)	((s) += 2, ((s)[-2] - '0') * 10 + ((s)[-1] - '0'))
    399 
    400 void
    401 getoffset(char *timearg)
    402 {
    403 	struct tm *lt;
    404 	char *p;
    405 	time_t now;
    406 	int yearset;
    407 
    408 	(void)time(&now);
    409 	if (!strcasecmp(timearg, "now")) {		/* now */
    410 		offset = 0;
    411 		shuttime = now;
    412 		return;
    413 	}
    414 
    415 	if (*timearg == '+') {				/* +minutes */
    416 		if (!isdigit((unsigned char)*++timearg))
    417 			badtime();
    418 		offset = atoi(timearg) * 60;
    419 		shuttime = now + offset;
    420 		return;
    421 	}
    422 
    423 	/* handle hh:mm by getting rid of the colon */
    424 	for (p = timearg; *p; ++p)
    425 		if (!isascii(*p) || !isdigit((unsigned char)*p)) {
    426 			if (*p == ':' && strlen(p) == 3) {
    427 				p[0] = p[1];
    428 				p[1] = p[2];
    429 				p[2] = '\0';
    430 			}
    431 			else
    432 				badtime();
    433 		}
    434 
    435 	unsetenv("TZ");					/* OUR timezone */
    436 	lt = localtime(&now);				/* current time val */
    437 
    438 	lt->tm_sec = 0;
    439 
    440 	yearset = 0;
    441 	switch (strlen(timearg)) {
    442 	case 12:
    443 		lt->tm_year = ATOI2(timearg) * 100 - TM_YEAR_BASE;
    444 		yearset = 1;
    445 		/* FALLTHROUGH */
    446 	case 10:
    447 		if (yearset) {
    448 			lt->tm_year += ATOI2(timearg);
    449 		} else {
    450 			yearset = ATOI2(timearg);
    451 			if (yearset < 69)
    452 				lt->tm_year = yearset + 2000 - TM_YEAR_BASE;
    453 			else
    454 				lt->tm_year = yearset + 1900 - TM_YEAR_BASE;
    455 		}
    456 		/* FALLTHROUGH */
    457 	case 8:
    458 		lt->tm_mon = ATOI2(timearg);
    459 		--lt->tm_mon;
    460 		/* FALLTHROUGH */
    461 	case 6:
    462 		lt->tm_mday = ATOI2(timearg);
    463 		/* FALLTHROUGH */
    464 	case 4:
    465 		lt->tm_hour = ATOI2(timearg);
    466 		/* FALLTHROUGH */
    467 	case 2:
    468 		lt->tm_min = ATOI2(timearg);
    469 		break;
    470 	default:
    471 		badtime();
    472 	}
    473 
    474 	if ((shuttime = mktime(lt)) == -1)
    475 		badtime();
    476 	if ((offset = shuttime - now) < 0)
    477 		errx(1, "time is already past");
    478 }
    479 
    480 void
    481 dorcshutdown(void)
    482 {
    483 	(void)printf("\r\nAbout to run shutdown hooks...\r\n");
    484 	(void)system(". " _PATH_RCSHUTDOWN);
    485 	(void)sleep(5);		/* Give operator a chance to abort this. */
    486 	(void)printf("\r\nDone running shutdown hooks.\r\n");
    487 }
    488 
    489 #define	FSMSG	"fastboot file for fsck\n"
    490 void
    491 doitfast(void)
    492 {
    493 	int fastfd;
    494 
    495 	if ((fastfd = open(_PATH_FASTBOOT, O_WRONLY|O_CREAT|O_TRUNC,
    496 	    0664)) >= 0) {
    497 		(void)write(fastfd, FSMSG, sizeof(FSMSG) - 1);
    498 		(void)close(fastfd);
    499 	}
    500 }
    501 
    502 #define	NOMSG	"\n\nNO LOGINS: System going down at "
    503 void
    504 nolog(void)
    505 {
    506 	int logfd;
    507 	char *ct;
    508 
    509 	(void)unlink(_PATH_NOLOGIN);	/* in case linked to another file */
    510 	(void)signal(SIGINT, finish);
    511 	(void)signal(SIGHUP, finish);
    512 	(void)signal(SIGQUIT, finish);
    513 	(void)signal(SIGTERM, finish);
    514 	if ((logfd = open(_PATH_NOLOGIN, O_WRONLY|O_CREAT|O_TRUNC,
    515 	    0664)) >= 0) {
    516 		(void)write(logfd, NOMSG, sizeof(NOMSG) - 1);
    517 		ct = ctime(&shuttime);
    518 		(void)write(logfd, ct + 11, 5);
    519 		(void)write(logfd, "\n\n", 2);
    520 		(void)write(logfd, mbuf, strlen(mbuf));
    521 		(void)close(logfd);
    522 	}
    523 }
    524 
    525 void
    526 finish(int signo)
    527 {
    528 
    529 	if (!killflg)
    530 		(void)unlink(_PATH_NOLOGIN);
    531 	exit(0);
    532 }
    533 
    534 void
    535 badtime(void)
    536 {
    537 
    538 	warnx("illegal time format");
    539 	usage();
    540 }
    541 
    542 void
    543 usage(void)
    544 {
    545 
    546 	(void)fprintf(stderr,
    547 	    "usage: shutdown [-Ddfhknpr] time [message ... | -]\n");
    548 	exit(1);
    549 }
    550