xref: /netbsd-src/sbin/shutdown/shutdown.c (revision 2a399c6883d870daece976daec6ffa7bb7f934ce)
1 /*	$NetBSD: shutdown.c,v 1.16 1997/10/01 02:24:29 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.16 1997/10/01 02:24:29 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 <fcntl.h>
57 #include <pwd.h>
58 #include <setjmp.h>
59 #include <signal.h>
60 #include <stdio.h>
61 #include <stdlib.h>
62 #include <string.h>
63 #include <tzfile.h>
64 #include <unistd.h>
65 
66 #include "pathnames.h"
67 
68 #ifdef DEBUG
69 #undef _PATH_NOLOGIN
70 #define	_PATH_NOLOGIN	"./nologin"
71 #undef _PATH_FASTBOOT
72 #define	_PATH_FASTBOOT	"./fastboot"
73 #endif
74 
75 #define	H		*60*60
76 #define	M		*60
77 #define	S		*1
78 #define	NOLOG_TIME	5*60
79 struct interval {
80 	int timeleft, timetowait;
81 } tlist[] = {
82 	{ 10 H,  5 H },	{  5 H,  3 H },	{  2 H,  1 H },	{ 1 H, 30 M },
83 	{ 30 M, 10 M },	{ 20 M, 10 M },	{ 10 M,  5 M },	{ 5 M,  3 M },
84 	{  2 M,  1 M },	{  1 M, 30 S },	{ 30 S, 30 S },
85 	{  0, 0 }
86 };
87 #undef H
88 #undef M
89 #undef S
90 
91 static time_t offset, shuttime;
92 static int dofast, dohalt, doreboot, killflg, mbuflen, nosync, dodump;
93 static char *whom, mbuf[BUFSIZ];
94 
95 void badtime __P((void));
96 void die_you_gravy_sucking_pig_dog __P((void));
97 void doitfast __P((void));
98 void finish __P((int));
99 void getoffset __P((char *));
100 void loop __P((void));
101 int main __P((int, char *[]));
102 void nolog __P((void));
103 void timeout __P((int));
104 void timewarn __P((int));
105 void usage __P((void));
106 
107 int
108 main(argc, argv)
109 	int argc;
110 	char *argv[];
111 {
112 	char *p, *endp;
113 	struct passwd *pw;
114 	int arglen, ch, len, readstdin;
115 
116 #ifndef DEBUG
117 	if (geteuid()) {
118 		(void)fprintf(stderr, "shutdown: NOT super-user\n");
119 		exit(1);
120 	}
121 #endif
122 	readstdin = 0;
123 	while ((ch = getopt(argc, argv, "-fhknrd")) != -1)
124 		switch (ch) {
125 		case '-':
126 			readstdin = 1;
127 			break;
128 		case 'f':
129 			dofast = 1;
130 			break;
131 		case 'h':
132 			dohalt = 1;
133 			break;
134 		case 'k':
135 			killflg = 1;
136 			break;
137 		case 'n':
138 			nosync = 1;
139 			break;
140 		case 'r':
141 			doreboot = 1;
142 			break;
143 		case 'd':
144 			dodump = 1;
145 			break;
146 		case '?':
147 		default:
148 			usage();
149 		}
150 	argc -= optind;
151 	argv += optind;
152 
153 	if (argc < 1)
154 		usage();
155 
156 	if (dofast && nosync) {
157 		(void)fprintf(stderr,
158 		    "shutdown: incompatible switches -f and -n.\n");
159 		usage();
160 	}
161 	if (doreboot && dohalt) {
162 		(void)fprintf(stderr,
163 		    "shutdown: incompatible switches -h and -r.\n");
164 		usage();
165 	}
166 	if (dodump && dohalt) {
167 		(void)fprintf(stderr,
168 		    "shutdown: incompatible switches -h and -d.\n");
169 		usage();
170 	}
171 	getoffset(*argv++);
172 
173 	if (*argv) {
174 		for (p = mbuf, len = sizeof(mbuf); *argv; ++argv) {
175 			arglen = strlen(*argv);
176 			if ((len -= arglen) <= 2)
177 				break;
178 			if (p != mbuf)
179 				*p++ = ' ';
180 			memmove(p, *argv, arglen);
181 			p += arglen;
182 		}
183 		*p = '\n';
184 		*++p = '\0';
185 	}
186 
187 	if (readstdin) {
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 	mbuflen = strlen(mbuf);
202 
203 	if (offset)
204 		(void)printf("Shutdown at %.24s.\n", ctime(&shuttime));
205 	else
206 		(void)printf("Shutdown NOW!\n");
207 
208 	if (!(whom = getlogin()))
209 		whom = (pw = getpwuid(getuid())) ? pw->pw_name : "???";
210 
211 #ifdef DEBUG
212 	(void)putc('\n', stdout);
213 #else
214 	(void)setpriority(PRIO_PROCESS, 0, PRIO_MIN);
215 	{
216 		int forkpid;
217 
218 		forkpid = fork();
219 		if (forkpid == -1) {
220 			perror("shutdown: fork");
221 			exit(1);
222 		}
223 		if (forkpid) {
224 			(void)printf("shutdown: [pid %d]\n", forkpid);
225 			exit(0);
226 		}
227 	}
228 #endif
229 	openlog("shutdown", LOG_CONS, LOG_AUTH);
230 	loop();
231 	/* NOTREACHED */
232 #ifdef __GNUC__
233 	return 1;
234 #endif
235 }
236 
237 void
238 loop()
239 {
240 	struct interval *tp;
241 	u_int sltime;
242 	int logged;
243 
244 	if (offset <= NOLOG_TIME) {
245 		logged = 1;
246 		nolog();
247 	}
248 	else
249 		logged = 0;
250 	tp = tlist;
251 	if (tp->timeleft < offset)
252 		(void)sleep((u_int)(offset - tp->timeleft));
253 	else {
254 		while (offset < tp->timeleft)
255 			++tp;
256 		/*
257 		 * Warn now, if going to sleep more than a fifth of
258 		 * the next wait time.
259 		 */
260 		if ((sltime = offset - tp->timeleft) != 0) {
261 			if (sltime > tp->timetowait / 5)
262 				timewarn(offset);
263 			(void)sleep(sltime);
264 		}
265 	}
266 	for (;; ++tp) {
267 		timewarn(tp->timeleft);
268 		if (!logged && tp->timeleft <= NOLOG_TIME) {
269 			logged = 1;
270 			nolog();
271 		}
272 		(void)sleep((u_int)tp->timetowait);
273 		if (!tp->timeleft)
274 			break;
275 	}
276 	die_you_gravy_sucking_pig_dog();
277 }
278 
279 static jmp_buf alarmbuf;
280 
281 void
282 timewarn(timeleft)
283 	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 
293 	/* undoc -n option to wall suppresses normal wall banner */
294 	(void)snprintf(wcmd, sizeof(wcmd), "%s -n", _PATH_WALL);
295 	if (!(pf = popen(wcmd, "w"))) {
296 		syslog(LOG_ERR, "shutdown: can't find %s: %m", _PATH_WALL);
297 		return;
298 	}
299 
300 	(void)fprintf(pf,
301 	    "\007*** %sSystem shutdown message from %s@%s ***\007\n",
302 	    timeleft ? "": "FINAL ", whom, hostname);
303 
304 	if (timeleft > 10*60)
305 		(void)fprintf(pf, "System going down at %5.5s\n\n",
306 		    ctime(&shuttime) + 11);
307 	else if (timeleft > 59)
308 		(void)fprintf(pf, "System going down in %d minute%s\n\n",
309 		    timeleft / 60, (timeleft > 60) ? "s" : "");
310 	else if (timeleft)
311 		(void)fprintf(pf, "System going down in 30 seconds\n\n");
312 	else
313 		(void)fprintf(pf, "System going down IMMEDIATELY\n\n");
314 
315 	if (mbuflen)
316 		(void)fwrite(mbuf, sizeof(*mbuf), mbuflen, pf);
317 
318 	/*
319 	 * play some games, just in case wall doesn't come back
320 	 * probably unecessary, given that wall is careful.
321 	 */
322 	if (!setjmp(alarmbuf)) {
323 		(void)signal(SIGALRM, timeout);
324 		(void)alarm((u_int)30);
325 		(void)pclose(pf);
326 		(void)alarm((u_int)0);
327 		(void)signal(SIGALRM, SIG_DFL);
328 	}
329 }
330 
331 void
332 timeout(signo)
333 	int signo;
334 {
335 	longjmp(alarmbuf, 1);
336 }
337 
338 void
339 die_you_gravy_sucking_pig_dog()
340 {
341 
342 	syslog(LOG_NOTICE, "%s by %s: %s",
343 	    doreboot || dodump ? "reboot" : dohalt ? "halt" : "shutdown", whom, mbuf);
344 	(void)sleep(2);
345 
346 	(void)printf("\r\nSystem shutdown time has arrived\007\007\r\n");
347 	if (killflg) {
348 		(void)printf("\rbut you'll have to do it yourself\r\n");
349 		finish(0);
350 	}
351 	if (dofast)
352 		doitfast();
353 #ifdef DEBUG
354 	if (doreboot || dodump)
355 		(void)printf("reboot%s", dodump ? " -d" : "");
356 	else if (dohalt)
357 		(void)printf("halt");
358 	if (nosync)
359 		(void)printf(" no sync");
360 	if (dofast)
361 		(void)printf(" no fsck");
362 	(void)printf("\nkill -HUP 1\n");
363 #else
364 	if (doreboot || dodump) {
365 		execle(_PATH_REBOOT, "reboot",
366 		       dodump ? (nosync ? "-ldn" : "-ld") :
367 		       (nosync ? "-ln" : "-l"), 0, (char **)0);
368 		syslog(LOG_ERR, "shutdown: can't exec %s: %m.", _PATH_REBOOT);
369 		perror("shutdown");
370 	}
371 	else if (dohalt) {
372 		execle(_PATH_HALT, "halt", nosync ? "-ln" : "-l",
373 		    (char *)0, (char **)0);
374 		syslog(LOG_ERR, "shutdown: can't exec %s: %m.", _PATH_HALT);
375 		perror("shutdown");
376 	}
377 	(void)kill(1, SIGTERM);		/* to single user */
378 #endif
379 	finish(0);
380 }
381 
382 #define	ATOI2(p)	(p[0] - '0') * 10 + (p[1] - '0'); p += 2;
383 
384 void
385 getoffset(timearg)
386 	char *timearg;
387 {
388 	struct tm *lt;
389 	char *p;
390 	time_t now;
391 
392 	if (!strcasecmp(timearg, "now")) {		/* now */
393 		offset = 0;
394 		return;
395 	}
396 
397 	(void)time(&now);
398 	if (*timearg == '+') {				/* +minutes */
399 		if (!isdigit(*++timearg))
400 			badtime();
401 		offset = atoi(timearg) * 60;
402 		shuttime = now + offset;
403 		return;
404 	}
405 
406 	/* handle hh:mm by getting rid of the colon */
407 	for (p = timearg; *p; ++p)
408 		if (!isascii(*p) || !isdigit(*p))
409 			if (*p == ':' && strlen(p) == 3) {
410 				p[0] = p[1];
411 				p[1] = p[2];
412 				p[2] = '\0';
413 			}
414 			else
415 				badtime();
416 
417 	unsetenv("TZ");					/* OUR timezone */
418 	lt = localtime(&now);				/* current time val */
419 
420 	switch(strlen(timearg)) {
421 	case 10:
422 		lt->tm_year = ATOI2(timearg);
423 		/* FALLTHROUGH */
424 	case 8:
425 		lt->tm_mon = ATOI2(timearg);
426 		if (--lt->tm_mon < 0 || lt->tm_mon > 11)
427 			badtime();
428 		/* FALLTHROUGH */
429 	case 6:
430 		lt->tm_mday = ATOI2(timearg);
431 		if (lt->tm_mday < 1 || lt->tm_mday > 31)
432 			badtime();
433 		/* FALLTHROUGH */
434 	case 4:
435 		lt->tm_hour = ATOI2(timearg);
436 		if (lt->tm_hour < 0 || lt->tm_hour > 23)
437 			badtime();
438 		lt->tm_min = ATOI2(timearg);
439 		if (lt->tm_min < 0 || lt->tm_min > 59)
440 			badtime();
441 		lt->tm_sec = 0;
442 		if ((shuttime = mktime(lt)) == -1)
443 			badtime();
444 		if ((offset = shuttime - now) < 0) {
445 			(void)fprintf(stderr,
446 			    "shutdown: that time is already past.\n");
447 			exit(1);
448 		}
449 		break;
450 	default:
451 		badtime();
452 	}
453 }
454 
455 #define	FSMSG	"fastboot file for fsck\n"
456 void
457 doitfast()
458 {
459 	int fastfd;
460 
461 	if ((fastfd = open(_PATH_FASTBOOT, O_WRONLY|O_CREAT|O_TRUNC,
462 	    0664)) >= 0) {
463 		(void)write(fastfd, FSMSG, sizeof(FSMSG) - 1);
464 		(void)close(fastfd);
465 	}
466 }
467 
468 #define	NOMSG	"\n\nNO LOGINS: System going down at "
469 void
470 nolog()
471 {
472 	int logfd;
473 	char *ct;
474 
475 	(void)unlink(_PATH_NOLOGIN);	/* in case linked to another file */
476 	(void)signal(SIGINT, finish);
477 	(void)signal(SIGHUP, finish);
478 	(void)signal(SIGQUIT, finish);
479 	(void)signal(SIGTERM, finish);
480 	if ((logfd = open(_PATH_NOLOGIN, O_WRONLY|O_CREAT|O_TRUNC,
481 	    0664)) >= 0) {
482 		(void)write(logfd, NOMSG, sizeof(NOMSG) - 1);
483 		ct = ctime(&shuttime);
484 		(void)write(logfd, ct + 11, 5);
485 		(void)write(logfd, "\n\n", 2);
486 		(void)write(logfd, mbuf, strlen(mbuf));
487 		(void)close(logfd);
488 	}
489 }
490 
491 void
492 finish(signo)
493 	int signo;
494 {
495 	if (!killflg)
496 		(void)unlink(_PATH_NOLOGIN);
497 	exit(0);
498 }
499 
500 void
501 badtime()
502 {
503 	(void)fprintf(stderr, "shutdown: bad time format.\n");
504 	exit(1);
505 }
506 
507 void
508 usage()
509 {
510 	fprintf(stderr, "usage: shutdown [-fhknrd] shutdowntime [ message ]\n");
511 	exit(1);
512 }
513