xref: /netbsd-src/sbin/shutdown/shutdown.c (revision e5548b402ae4c44fb816de42c7bba9581ce23ef5)
1 /*	$NetBSD: shutdown.c,v 1.45 2005/06/27 01:00:06 christos 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.45 2005/06/27 01:00:06 christos 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 		const char *args[16];
357 		const char **arg, *path;
358 
359 		arg = &args[0];
360 		if (doreboot) {
361 			path = _PATH_REBOOT;
362 			*arg++ = "reboot";
363 		} else {
364 			path = _PATH_HALT;
365 			*arg++ = "halt";
366 		}
367 		if (dodump)
368 			*arg++ = "-d";
369 		if (nosync)
370 			*arg++ = "-n";
371 		if (dopowerdown)
372 			*arg++ = "-p";
373 		*arg++ = "-l";
374 		if (bootstr)
375 			*arg++ = bootstr;
376 		*arg++ = 0;
377 #ifndef DEBUG
378 		execve(path, __UNCONST(args), NULL);
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(char *timearg)
401 {
402 	struct tm *lt;
403 	char *p;
404 	time_t now;
405 	int yearset;
406 
407 	(void)time(&now);
408 	if (!strcasecmp(timearg, "now")) {		/* now */
409 		offset = 0;
410 		shuttime = now;
411 		return;
412 	}
413 
414 	if (*timearg == '+') {				/* +minutes */
415 		if (!isdigit((unsigned char)*++timearg))
416 			badtime();
417 		offset = atoi(timearg) * 60;
418 		shuttime = now + offset;
419 		return;
420 	}
421 
422 	/* handle hh:mm by getting rid of the colon */
423 	for (p = timearg; *p; ++p)
424 		if (!isascii(*p) || !isdigit((unsigned char)*p)) {
425 			if (*p == ':' && strlen(p) == 3) {
426 				p[0] = p[1];
427 				p[1] = p[2];
428 				p[2] = '\0';
429 			}
430 			else
431 				badtime();
432 		}
433 
434 	unsetenv("TZ");					/* OUR timezone */
435 	lt = localtime(&now);				/* current time val */
436 
437 	lt->tm_sec = 0;
438 
439 	yearset = 0;
440 	switch (strlen(timearg)) {
441 	case 12:
442 		lt->tm_year = ATOI2(timearg) * 100 - TM_YEAR_BASE;
443 		yearset = 1;
444 		/* FALLTHROUGH */
445 	case 10:
446 		if (yearset) {
447 			lt->tm_year += ATOI2(timearg);
448 		} else {
449 			yearset = ATOI2(timearg);
450 			if (yearset < 69)
451 				lt->tm_year = yearset + 2000 - TM_YEAR_BASE;
452 			else
453 				lt->tm_year = yearset + 1900 - TM_YEAR_BASE;
454 		}
455 		/* FALLTHROUGH */
456 	case 8:
457 		lt->tm_mon = ATOI2(timearg);
458 		--lt->tm_mon;
459 		/* FALLTHROUGH */
460 	case 6:
461 		lt->tm_mday = ATOI2(timearg);
462 		/* FALLTHROUGH */
463 	case 4:
464 		lt->tm_hour = ATOI2(timearg);
465 		/* FALLTHROUGH */
466 	case 2:
467 		lt->tm_min = ATOI2(timearg);
468 		break;
469 	default:
470 		badtime();
471 	}
472 
473 	if ((shuttime = mktime(lt)) == -1)
474 		badtime();
475 	if ((offset = shuttime - now) < 0)
476 		errx(1, "time is already past");
477 }
478 
479 void
480 dorcshutdown(void)
481 {
482 	(void)printf("\r\nAbout to run shutdown hooks...\r\n");
483 	(void)system(". " _PATH_RCSHUTDOWN);
484 	(void)sleep(5);		/* Give operator a chance to abort this. */
485 	(void)printf("\r\nDone running shutdown hooks.\r\n");
486 }
487 
488 #define	FSMSG	"fastboot file for fsck\n"
489 void
490 doitfast(void)
491 {
492 	int fastfd;
493 
494 	if ((fastfd = open(_PATH_FASTBOOT, O_WRONLY|O_CREAT|O_TRUNC,
495 	    0664)) >= 0) {
496 		(void)write(fastfd, FSMSG, sizeof(FSMSG) - 1);
497 		(void)close(fastfd);
498 	}
499 }
500 
501 #define	NOMSG	"\n\nNO LOGINS: System going down at "
502 void
503 nolog(void)
504 {
505 	int logfd;
506 	char *ct;
507 
508 	(void)unlink(_PATH_NOLOGIN);	/* in case linked to another file */
509 	(void)signal(SIGINT, finish);
510 	(void)signal(SIGHUP, finish);
511 	(void)signal(SIGQUIT, finish);
512 	(void)signal(SIGTERM, finish);
513 	if ((logfd = open(_PATH_NOLOGIN, O_WRONLY|O_CREAT|O_TRUNC,
514 	    0664)) >= 0) {
515 		(void)write(logfd, NOMSG, sizeof(NOMSG) - 1);
516 		ct = ctime(&shuttime);
517 		(void)write(logfd, ct + 11, 5);
518 		(void)write(logfd, "\n\n", 2);
519 		(void)write(logfd, mbuf, strlen(mbuf));
520 		(void)close(logfd);
521 	}
522 }
523 
524 void
525 finish(int signo)
526 {
527 
528 	if (!killflg)
529 		(void)unlink(_PATH_NOLOGIN);
530 	exit(0);
531 }
532 
533 void
534 badtime(void)
535 {
536 
537 	warnx("illegal time format");
538 	usage();
539 }
540 
541 void
542 usage(void)
543 {
544 
545 	(void)fprintf(stderr,
546 	    "usage: shutdown [-Ddfhknpr] time [message ... | -]\n");
547 	exit(1);
548 }
549