Home | History | Annotate | Line # | Download | only in shutdown
shutdown.c revision 1.29
      1 /*	$NetBSD: shutdown.c,v 1.29 1998/07/26 20:18:32 mycroft 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.29 1998/07/26 20:18:32 mycroft 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 	mbuflen = strlen(mbuf);
    204 
    205 	if (offset)
    206 		(void)printf("Shutdown at %.24s.\n", ctime(&shuttime));
    207 	else
    208 		(void)printf("Shutdown NOW!\n");
    209 
    210 	if (!(whom = getlogin()))
    211 		whom = (pw = getpwuid(getuid())) ? pw->pw_name : "???";
    212 
    213 #ifdef DEBUG
    214 	(void)putc('\n', stdout);
    215 #else
    216 	(void)setpriority(PRIO_PROCESS, 0, PRIO_MIN);
    217 	if (nofork == 0) {
    218 		int forkpid;
    219 
    220 		forkpid = fork();
    221 		if (forkpid == -1) {
    222 			perror("shutdown: fork");
    223 			exit(1);
    224 		}
    225 		if (forkpid) {
    226 			(void)printf("shutdown: [pid %d]\n", forkpid);
    227 			exit(0);
    228 		}
    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()
    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(timeleft)
    285 	int timeleft;
    286 {
    287 	static int first;
    288 	static char hostname[MAXHOSTNAMELEN + 1];
    289 	FILE *pf;
    290 	char wcmd[MAXPATHLEN + 4];
    291 
    292 	if (!first++) {
    293 		(void)gethostname(hostname, sizeof(hostname));
    294 		hostname[sizeof(hostname) - 1] = '\0';
    295 	}
    296 
    297 	/* undoc -n option to wall suppresses normal wall banner */
    298 	(void)snprintf(wcmd, sizeof wcmd, "%s -n", _PATH_WALL);
    299 	if (!(pf = popen(wcmd, "w"))) {
    300 		syslog(LOG_ERR, "shutdown: can't find %s: %m", _PATH_WALL);
    301 		return;
    302 	}
    303 
    304 	(void)fprintf(pf,
    305 	    "\007*** %sSystem shutdown message from %s@%s ***\007\n",
    306 	    timeleft ? "": "FINAL ", whom, hostname);
    307 
    308 	if (timeleft > 10*60)
    309 		(void)fprintf(pf, "System going down at %5.5s\n\n",
    310 		    ctime(&shuttime) + 11);
    311 	else if (timeleft > 59)
    312 		(void)fprintf(pf, "System going down in %d minute%s\n\n",
    313 		    timeleft / 60, (timeleft > 60) ? "s" : "");
    314 	else if (timeleft)
    315 		(void)fprintf(pf, "System going down in 30 seconds\n\n");
    316 	else
    317 		(void)fprintf(pf, "System going down IMMEDIATELY\n\n");
    318 
    319 	if (mbuflen)
    320 		(void)fwrite(mbuf, sizeof(*mbuf), mbuflen, pf);
    321 
    322 	/*
    323 	 * play some games, just in case wall doesn't come back
    324 	 * probably unecessary, given that wall is careful.
    325 	 */
    326 	if (!setjmp(alarmbuf)) {
    327 		(void)signal(SIGALRM, timeout);
    328 		(void)alarm((u_int)30);
    329 		(void)pclose(pf);
    330 		(void)alarm((u_int)0);
    331 		(void)signal(SIGALRM, SIG_DFL);
    332 	}
    333 }
    334 
    335 void
    336 timeout(signo)
    337 	int signo;
    338 {
    339 	longjmp(alarmbuf, 1);
    340 }
    341 
    342 void
    343 die_you_gravy_sucking_pig_dog()
    344 {
    345 
    346 	syslog(LOG_NOTICE, "%s by %s: %s",
    347 	    doreboot ? "reboot" : dohalt ? "halt" : "shutdown", whom, mbuf);
    348 	(void)sleep(2);
    349 
    350 	(void)printf("\r\nSystem shutdown time has arrived\007\007\r\n");
    351 	if (killflg) {
    352 		(void)printf("\rbut you'll have to do it yourself\r\n");
    353 		finish(0);
    354 	}
    355 	if (dofast)
    356 		doitfast();
    357 	if (doreboot || dohalt) {
    358 		char *args[16], **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 		*arg++ = 0;
    376 #ifndef DEBUG
    377 		exect(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(timearg)
    400 	char *timearg;
    401 {
    402 	struct tm *lt;
    403 	char *p;
    404 	time_t now;
    405 	int yearset;
    406 
    407 	if (!strcasecmp(timearg, "now")) {		/* now */
    408 		offset = 0;
    409 		return;
    410 	}
    411 
    412 	(void)time(&now);
    413 	if (*timearg == '+') {				/* +minutes */
    414 		if (!isdigit(*++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(*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 	unsetenv("TZ");					/* OUR timezone */
    433 	lt = localtime(&now);				/* current time val */
    434 
    435 	lt->tm_sec = 0;
    436 
    437 	yearset = 0;
    438 	switch (strlen(timearg)) {
    439 	case 12:
    440 		lt->tm_year = ATOI2(timearg) * 100 - TM_YEAR_BASE;
    441 		yearset = 1;
    442 		/* FALLTHROUGH */
    443 	case 10:
    444 		if (yearset) {
    445 			lt->tm_year += ATOI2(timearg);
    446 		} else {
    447 			yearset = ATOI2(timearg);
    448 			if (yearset < 69)
    449 				lt->tm_year = yearset + 2000 - TM_YEAR_BASE;
    450 			else
    451 				lt->tm_year = yearset + 1900 - TM_YEAR_BASE;
    452 		}
    453 		/* FALLTHROUGH */
    454 	case 8:
    455 		lt->tm_mon = ATOI2(timearg);
    456 		--lt->tm_mon;
    457 		/* FALLTHROUGH */
    458 	case 6:
    459 		lt->tm_mday = ATOI2(timearg);
    460 		/* FALLTHROUGH */
    461 	case 4:
    462 		lt->tm_hour = ATOI2(timearg);
    463 		/* FALLTHROUGH */
    464 	case 2:
    465 		lt->tm_min = ATOI2(timearg);
    466 		break;
    467 	default:
    468 		badtime();
    469 	}
    470 
    471 	if ((shuttime = mktime(lt)) == -1)
    472 		badtime();
    473 	if ((offset = shuttime - now) < 0)
    474 		errx(1, "time is already past");
    475 }
    476 
    477 #define	FSMSG	"fastboot file for fsck\n"
    478 void
    479 doitfast()
    480 {
    481 	int fastfd;
    482 
    483 	if ((fastfd = open(_PATH_FASTBOOT, O_WRONLY|O_CREAT|O_TRUNC,
    484 	    0664)) >= 0) {
    485 		(void)write(fastfd, FSMSG, sizeof(FSMSG) - 1);
    486 		(void)close(fastfd);
    487 	}
    488 }
    489 
    490 #define	NOMSG	"\n\nNO LOGINS: System going down at "
    491 void
    492 nolog()
    493 {
    494 	int logfd;
    495 	char *ct;
    496 
    497 	(void)unlink(_PATH_NOLOGIN);	/* in case linked to another file */
    498 	(void)signal(SIGINT, finish);
    499 	(void)signal(SIGHUP, finish);
    500 	(void)signal(SIGQUIT, finish);
    501 	(void)signal(SIGTERM, finish);
    502 	if ((logfd = open(_PATH_NOLOGIN, O_WRONLY|O_CREAT|O_TRUNC,
    503 	    0664)) >= 0) {
    504 		(void)write(logfd, NOMSG, sizeof(NOMSG) - 1);
    505 		ct = ctime(&shuttime);
    506 		(void)write(logfd, ct + 11, 5);
    507 		(void)write(logfd, "\n\n", 2);
    508 		(void)write(logfd, mbuf, strlen(mbuf));
    509 		(void)close(logfd);
    510 	}
    511 }
    512 
    513 void
    514 finish(signo)
    515 	int signo;
    516 {
    517 
    518 	if (!killflg)
    519 		(void)unlink(_PATH_NOLOGIN);
    520 	exit(0);
    521 }
    522 
    523 void
    524 badtime()
    525 {
    526 
    527 	warnx("illegal time format");
    528 	usage();
    529 }
    530 
    531 void
    532 usage()
    533 {
    534 
    535 	(void)fprintf(stderr,
    536 	    "usage: shutdown [-Ddfhknr] time [message ... | -]\n");
    537 	exit(1);
    538 }
    539