Home | History | Annotate | Line # | Download | only in shutdown
shutdown.c revision 1.32
      1 /*	$NetBSD: shutdown.c,v 1.32 1998/10/09 03:01:40 enami 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.32 1998/10/09 03:01:40 enami 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 finish __P((int));
    103 void getoffset __P((char *));
    104 void loop __P((void));
    105 int main __P((int, char *[]));
    106 void nolog __P((void));
    107 void timeout __P((int));
    108 void timewarn __P((int));
    109 void usage __P((void));
    110 
    111 int
    112 main(argc, argv)
    113 	int argc;
    114 	char *argv[];
    115 {
    116 	char *p, *endp;
    117 	struct passwd *pw;
    118 	int arglen, ch, len;
    119 
    120 #ifndef DEBUG
    121 	if (geteuid())
    122 		errx(1, "NOT super-user");
    123 #endif
    124 	while ((ch = getopt(argc, argv, "Ddfhknpr")) != -1)
    125 		switch (ch) {
    126 		case 'd':
    127 			dodump = 1;
    128 			break;
    129 		case 'D':
    130 			nofork = 1;
    131 			break;
    132 		case 'f':
    133 			dofast = 1;
    134 			break;
    135 		case 'p':
    136 			dopowerdown = 1;
    137 			/* FALLTHROUGH */
    138 		case 'h':
    139 			dohalt = 1;
    140 			break;
    141 		case 'k':
    142 			killflg = 1;
    143 			break;
    144 		case 'n':
    145 			nosync = 1;
    146 			break;
    147 		case 'r':
    148 			doreboot = 1;
    149 			break;
    150 		case '?':
    151 		default:
    152 			usage();
    153 		}
    154 	argc -= optind;
    155 	argv += optind;
    156 
    157 	if (argc < 1)
    158 		usage();
    159 
    160 	if (dodump && !dohalt && !doreboot)
    161 		doreboot = 1;
    162 
    163 	if (dofast && nosync) {
    164 		warnx("incompatible switches -f and -n");
    165 		usage();
    166 	}
    167 	if (dohalt && doreboot) {
    168 		const char *which_flag = dopowerdown ? "p" : "h";
    169 
    170 		warnx("incompatible switches -%s and -r", which_flag);
    171 		usage();
    172 	}
    173 
    174 	getoffset(*argv++);
    175 
    176 	if (argv[0]) {
    177 		if (strcmp(argv[0], "-") || argv[1]) {
    178 			for (p = mbuf, len = sizeof(mbuf); *argv; ++argv) {
    179 				arglen = strlen(*argv);
    180 				if ((len -= arglen) <= 2)
    181 					break;
    182 				if (p != mbuf)
    183 					*p++ = ' ';
    184 				memmove(p, *argv, arglen);
    185 				p += arglen;
    186 			}
    187 			*p = '\n';
    188 			*++p = '\0';
    189 		} else {
    190 			p = mbuf;
    191 			endp = mbuf + sizeof(mbuf) - 2;
    192 			for (;;) {
    193 				if (!fgets(p, endp - p + 1, stdin))
    194 					break;
    195 				for (; *p &&  p < endp; ++p);
    196 				if (p == endp) {
    197 					*p = '\n';
    198 					*++p = '\0';
    199 					break;
    200 				}
    201 			}
    202 		}
    203 	}
    204 	mbuflen = strlen(mbuf);
    205 
    206 	if (offset)
    207 		(void)printf("Shutdown at %.24s.\n", ctime(&shuttime));
    208 	else
    209 		(void)printf("Shutdown NOW!\n");
    210 
    211 	if (!(whom = getlogin()))
    212 		whom = (pw = getpwuid(getuid())) ? pw->pw_name : "???";
    213 
    214 #ifdef DEBUG
    215 	(void)putc('\n', stdout);
    216 #else
    217 	(void)setpriority(PRIO_PROCESS, 0, PRIO_MIN);
    218 	if (nofork == 0) {
    219 		int forkpid;
    220 
    221 		forkpid = fork();
    222 		if (forkpid == -1) {
    223 			perror("shutdown: fork");
    224 			exit(1);
    225 		}
    226 		if (forkpid) {
    227 			(void)printf("shutdown: [pid %d]\n", forkpid);
    228 			exit(0);
    229 		}
    230 	}
    231 #endif
    232 	openlog("shutdown", LOG_CONS, LOG_AUTH);
    233 	loop();
    234 	/* NOTREACHED */
    235 #ifdef __GNUC__
    236 	return 1;
    237 #endif
    238 }
    239 
    240 void
    241 loop()
    242 {
    243 	struct interval *tp;
    244 	u_int sltime;
    245 	int logged;
    246 
    247 	if (offset <= NOLOG_TIME) {
    248 		logged = 1;
    249 		nolog();
    250 	}
    251 	else
    252 		logged = 0;
    253 	tp = tlist;
    254 	if (tp->timeleft < offset)
    255 		(void)sleep((u_int)(offset - tp->timeleft));
    256 	else {
    257 		while (offset < tp->timeleft)
    258 			++tp;
    259 		/*
    260 		 * Warn now, if going to sleep more than a fifth of
    261 		 * the next wait time.
    262 		 */
    263 		if ((sltime = offset - tp->timeleft) != 0) {
    264 			if (sltime > tp->timetowait / 5)
    265 				timewarn(offset);
    266 			(void)sleep(sltime);
    267 		}
    268 	}
    269 	for (;; ++tp) {
    270 		timewarn(tp->timeleft);
    271 		if (!logged && tp->timeleft <= NOLOG_TIME) {
    272 			logged = 1;
    273 			nolog();
    274 		}
    275 		(void)sleep((u_int)tp->timetowait);
    276 		if (!tp->timeleft)
    277 			break;
    278 	}
    279 	die_you_gravy_sucking_pig_dog();
    280 }
    281 
    282 static jmp_buf alarmbuf;
    283 
    284 void
    285 timewarn(timeleft)
    286 	int timeleft;
    287 {
    288 	static int first;
    289 	static char hostname[MAXHOSTNAMELEN + 1];
    290 	FILE *pf;
    291 	char wcmd[MAXPATHLEN + 4];
    292 
    293 	if (!first++) {
    294 		(void)gethostname(hostname, sizeof(hostname));
    295 		hostname[sizeof(hostname) - 1] = '\0';
    296 	}
    297 
    298 	/* undoc -n option to wall suppresses normal wall banner */
    299 	(void)snprintf(wcmd, sizeof wcmd, "%s -n", _PATH_WALL);
    300 	if (!(pf = popen(wcmd, "w"))) {
    301 		syslog(LOG_ERR, "shutdown: can't find %s: %m", _PATH_WALL);
    302 		return;
    303 	}
    304 
    305 	(void)fprintf(pf,
    306 	    "\007*** %sSystem shutdown message from %s@%s ***\007\n",
    307 	    timeleft ? "": "FINAL ", whom, hostname);
    308 
    309 	if (timeleft > 10*60)
    310 		(void)fprintf(pf, "System going down at %5.5s\n\n",
    311 		    ctime(&shuttime) + 11);
    312 	else if (timeleft > 59)
    313 		(void)fprintf(pf, "System going down in %d minute%s\n\n",
    314 		    timeleft / 60, (timeleft > 60) ? "s" : "");
    315 	else if (timeleft)
    316 		(void)fprintf(pf, "System going down in 30 seconds\n\n");
    317 	else
    318 		(void)fprintf(pf, "System going down IMMEDIATELY\n\n");
    319 
    320 	if (mbuflen)
    321 		(void)fwrite(mbuf, sizeof(*mbuf), mbuflen, pf);
    322 
    323 	/*
    324 	 * play some games, just in case wall doesn't come back
    325 	 * probably unecessary, given that wall is careful.
    326 	 */
    327 	if (!setjmp(alarmbuf)) {
    328 		(void)signal(SIGALRM, timeout);
    329 		(void)alarm((u_int)30);
    330 		(void)pclose(pf);
    331 		(void)alarm((u_int)0);
    332 		(void)signal(SIGALRM, SIG_DFL);
    333 	}
    334 }
    335 
    336 void
    337 timeout(signo)
    338 	int signo;
    339 {
    340 	longjmp(alarmbuf, 1);
    341 }
    342 
    343 void
    344 die_you_gravy_sucking_pig_dog()
    345 {
    346 
    347 	syslog(LOG_NOTICE, "%s by %s: %s",
    348 	    doreboot ? "reboot" : dohalt ? "halt" : "shutdown", whom, mbuf);
    349 	(void)sleep(2);
    350 
    351 	(void)printf("\r\nSystem shutdown time has arrived\007\007\r\n");
    352 	if (killflg) {
    353 		(void)printf("\rbut you'll have to do it yourself\r\n");
    354 		finish(0);
    355 	}
    356 	if (dofast)
    357 		doitfast();
    358 	if (doreboot || dohalt) {
    359 		char *args[16], **arg, *path;
    360 
    361 		arg = &args[0];
    362 		if (doreboot) {
    363 			path = _PATH_REBOOT;
    364 			*arg++ = "reboot";
    365 		} else {
    366 			path = _PATH_HALT;
    367 			*arg++ = "halt";
    368 		}
    369 		if (dodump)
    370 			*arg++ = "-d";
    371 		if (nosync)
    372 			*arg++ = "-n";
    373 		if (dopowerdown)
    374 			*arg++ = "-p";
    375 		*arg++ = "-l";
    376 		*arg++ = 0;
    377 #ifndef DEBUG
    378 		exect(path, args, (char **)0);
    379 		syslog(LOG_ERR, "shutdown: can't exec %s: %m", path);
    380 		perror("shutdown");
    381 #else
    382 		printf("%s", path);
    383 		for (arg = &args[0]; *arg; arg++)
    384 			printf(" %s", *arg);
    385 		printf("\n");
    386 #endif
    387 	} else {
    388 #ifndef DEBUG
    389 		(void)kill(1, SIGTERM);		/* to single user */
    390 #else
    391 		printf("kill 1\n");
    392 #endif
    393 	}
    394 	finish(0);
    395 }
    396 
    397 #define	ATOI2(s)	((s) += 2, ((s)[-2] - '0') * 10 + ((s)[-1] - '0'))
    398 
    399 void
    400 getoffset(timearg)
    401 	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(*++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(*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 #define	FSMSG	"fastboot file for fsck\n"
    481 void
    482 doitfast()
    483 {
    484 	int fastfd;
    485 
    486 	if ((fastfd = open(_PATH_FASTBOOT, O_WRONLY|O_CREAT|O_TRUNC,
    487 	    0664)) >= 0) {
    488 		(void)write(fastfd, FSMSG, sizeof(FSMSG) - 1);
    489 		(void)close(fastfd);
    490 	}
    491 }
    492 
    493 #define	NOMSG	"\n\nNO LOGINS: System going down at "
    494 void
    495 nolog()
    496 {
    497 	int logfd;
    498 	char *ct;
    499 
    500 	(void)unlink(_PATH_NOLOGIN);	/* in case linked to another file */
    501 	(void)signal(SIGINT, finish);
    502 	(void)signal(SIGHUP, finish);
    503 	(void)signal(SIGQUIT, finish);
    504 	(void)signal(SIGTERM, finish);
    505 	if ((logfd = open(_PATH_NOLOGIN, O_WRONLY|O_CREAT|O_TRUNC,
    506 	    0664)) >= 0) {
    507 		(void)write(logfd, NOMSG, sizeof(NOMSG) - 1);
    508 		ct = ctime(&shuttime);
    509 		(void)write(logfd, ct + 11, 5);
    510 		(void)write(logfd, "\n\n", 2);
    511 		(void)write(logfd, mbuf, strlen(mbuf));
    512 		(void)close(logfd);
    513 	}
    514 }
    515 
    516 void
    517 finish(signo)
    518 	int signo;
    519 {
    520 
    521 	if (!killflg)
    522 		(void)unlink(_PATH_NOLOGIN);
    523 	exit(0);
    524 }
    525 
    526 void
    527 badtime()
    528 {
    529 
    530 	warnx("illegal time format");
    531 	usage();
    532 }
    533 
    534 void
    535 usage()
    536 {
    537 
    538 	(void)fprintf(stderr,
    539 	    "usage: shutdown [-Ddfhknpr] time [message ... | -]\n");
    540 	exit(1);
    541 }
    542