xref: /freebsd/sbin/shutdown/shutdown.c (revision ca27f0cef04fe67c812aae3568211798f52f28ee)
1 /*
2  * Copyright (c) 1988, 1990, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 4. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #if 0
31 #ifndef lint
32 static const char copyright[] =
33 "@(#) Copyright (c) 1988, 1990, 1993\n\
34 	The Regents of the University of California.  All rights reserved.\n";
35 #endif /* not lint */
36 
37 #ifndef lint
38 static char sccsid[] = "@(#)shutdown.c	8.4 (Berkeley) 4/28/95";
39 #endif /* not lint */
40 #endif
41 #include <sys/cdefs.h>
42 __FBSDID("$FreeBSD$");
43 
44 #include <sys/param.h>
45 #include <sys/time.h>
46 #include <sys/resource.h>
47 #include <sys/syslog.h>
48 
49 #include <ctype.h>
50 #include <err.h>
51 #include <fcntl.h>
52 #include <paths.h>
53 #include <pwd.h>
54 #include <setjmp.h>
55 #include <signal.h>
56 #include <stdio.h>
57 #include <stdlib.h>
58 #include <string.h>
59 #include <unistd.h>
60 
61 #ifdef DEBUG
62 #undef _PATH_NOLOGIN
63 #define	_PATH_NOLOGIN	"./nologin"
64 #endif
65 
66 #define	H		*60*60
67 #define	M		*60
68 #define	S		*1
69 #define	NOLOG_TIME	5*60
70 static struct interval {
71 	int timeleft, timetowait;
72 } tlist[] = {
73 	{ 10 H,  5 H },
74 	{  5 H,  3 H },
75 	{  2 H,  1 H },
76 	{  1 H, 30 M },
77 	{ 30 M, 10 M },
78 	{ 20 M, 10 M },
79 	{ 10 M,  5 M },
80 	{  5 M,  3 M },
81 	{  2 M,  1 M },
82 	{  1 M, 30 S },
83 	{ 30 S, 30 S },
84 	{  0  ,  0   }
85 };
86 #undef H
87 #undef M
88 #undef S
89 
90 static time_t offset, shuttime;
91 static int dohalt, dopower, doreboot, killflg, mbuflen, oflag;
92 static char mbuf[BUFSIZ];
93 static const char *nosync, *whom;
94 
95 static void badtime(void);
96 static void perform_shutdown(void);
97 static void finish(int);
98 static void getoffset(char *);
99 static void loop(void);
100 static void nolog(void);
101 static void timeout(int);
102 static void timewarn(int);
103 static void usage(const char *);
104 
105 extern const char **environ;
106 
107 int
108 main(int argc, char **argv)
109 {
110 	char *p, *endp;
111 	struct passwd *pw;
112 	int arglen, ch, len, readstdin;
113 
114 #ifndef DEBUG
115 	if (geteuid())
116 		errx(1, "NOT super-user");
117 #endif
118 
119 	nosync = NULL;
120 	readstdin = 0;
121 
122 	/*
123 	 * Test for the special case where the utility is called as
124 	 * "poweroff", for which it runs 'shutdown -p now'.
125 	 */
126 	if ((p = strrchr(argv[0], '/')) == NULL)
127 		p = argv[0];
128 	else
129 		++p;
130 	if (strcmp(p, "poweroff") == 0) {
131 		if (getopt(argc, argv, "") != -1)
132 			usage((char *)NULL);
133 		argc -= optind;
134 		argv += optind;
135 		if (argc != 0)
136 			usage((char *)NULL);
137 		dopower = 1;
138 		offset = 0;
139 		(void)time(&shuttime);
140 		goto poweroff;
141 	}
142 
143 	while ((ch = getopt(argc, argv, "-hknopr")) != -1)
144 		switch (ch) {
145 		case '-':
146 			readstdin = 1;
147 			break;
148 		case 'h':
149 			dohalt = 1;
150 			break;
151 		case 'k':
152 			killflg = 1;
153 			break;
154 		case 'n':
155 			nosync = "-n";
156 			break;
157 		case 'o':
158 			oflag = 1;
159 			break;
160 		case 'p':
161 			dopower = 1;
162 			break;
163 		case 'r':
164 			doreboot = 1;
165 			break;
166 		case '?':
167 		default:
168 			usage((char *)NULL);
169 		}
170 	argc -= optind;
171 	argv += optind;
172 
173 	if (argc < 1)
174 		usage((char *)NULL);
175 
176 	if (killflg + doreboot + dohalt + dopower > 1)
177 		usage("incompatible switches -h, -k, -p and -r");
178 
179 	if (oflag && !(dohalt || dopower || doreboot))
180 		usage("-o requires -h, -p or -r");
181 
182 	if (nosync != NULL && !oflag)
183 		usage("-n requires -o");
184 
185 	getoffset(*argv++);
186 
187 poweroff:
188 	if (*argv) {
189 		for (p = mbuf, len = sizeof(mbuf); *argv; ++argv) {
190 			arglen = strlen(*argv);
191 			if ((len -= arglen) <= 2)
192 				break;
193 			if (p != mbuf)
194 				*p++ = ' ';
195 			memmove(p, *argv, arglen);
196 			p += arglen;
197 		}
198 		*p = '\n';
199 		*++p = '\0';
200 	}
201 
202 	if (readstdin) {
203 		p = mbuf;
204 		endp = mbuf + sizeof(mbuf) - 2;
205 		for (;;) {
206 			if (!fgets(p, endp - p + 1, stdin))
207 				break;
208 			for (; *p &&  p < endp; ++p);
209 			if (p == endp) {
210 				*p = '\n';
211 				*++p = '\0';
212 				break;
213 			}
214 		}
215 	}
216 	mbuflen = strlen(mbuf);
217 
218 	if (offset)
219 		(void)printf("Shutdown at %.24s.\n", ctime(&shuttime));
220 	else
221 		(void)printf("Shutdown NOW!\n");
222 
223 	if (!(whom = getlogin()))
224 		whom = (pw = getpwuid(getuid())) ? pw->pw_name : "???";
225 
226 #ifdef DEBUG
227 	(void)putc('\n', stdout);
228 #else
229 	(void)setpriority(PRIO_PROCESS, 0, PRIO_MIN);
230 	{
231 		int forkpid;
232 
233 		forkpid = fork();
234 		if (forkpid == -1)
235 			err(1, "fork");
236 		if (forkpid)
237 			errx(0, "[pid %d]", forkpid);
238 	}
239 	setsid();
240 #endif
241 	openlog("shutdown", LOG_CONS, LOG_AUTH);
242 	loop();
243 	return(0);
244 }
245 
246 static void
247 loop(void)
248 {
249 	struct interval *tp;
250 	u_int sltime;
251 	int logged;
252 
253 	if (offset <= NOLOG_TIME) {
254 		logged = 1;
255 		nolog();
256 	}
257 	else
258 		logged = 0;
259 	tp = tlist;
260 	if (tp->timeleft < offset)
261 		(void)sleep((u_int)(offset - tp->timeleft));
262 	else {
263 		while (tp->timeleft && offset < tp->timeleft)
264 			++tp;
265 		/*
266 		 * Warn now, if going to sleep more than a fifth of
267 		 * the next wait time.
268 		 */
269 		if ((sltime = offset - tp->timeleft)) {
270 			if (sltime > (u_int)(tp->timetowait / 5))
271 				timewarn(offset);
272 			(void)sleep(sltime);
273 		}
274 	}
275 	for (;; ++tp) {
276 		timewarn(tp->timeleft);
277 		if (!logged && tp->timeleft <= NOLOG_TIME) {
278 			logged = 1;
279 			nolog();
280 		}
281 		(void)sleep((u_int)tp->timetowait);
282 		if (!tp->timeleft)
283 			break;
284 	}
285 	perform_shutdown();
286 }
287 
288 static jmp_buf alarmbuf;
289 
290 static const char *restricted_environ[] = {
291 	"PATH=" _PATH_STDPATH,
292 	NULL
293 };
294 
295 static void
296 timewarn(int timeleft)
297 {
298 	static int first;
299 	static char hostname[MAXHOSTNAMELEN + 1];
300 	FILE *pf;
301 	char wcmd[MAXPATHLEN + 4];
302 
303 	if (!first++)
304 		(void)gethostname(hostname, sizeof(hostname));
305 
306 	/* undoc -n option to wall suppresses normal wall banner */
307 	(void)snprintf(wcmd, sizeof(wcmd), "%s -n", _PATH_WALL);
308 	environ = restricted_environ;
309 	if (!(pf = popen(wcmd, "w"))) {
310 		syslog(LOG_ERR, "shutdown: can't find %s: %m", _PATH_WALL);
311 		return;
312 	}
313 
314 	(void)fprintf(pf,
315 	    "\007*** %sSystem shutdown message from %s@%s ***\007\n",
316 	    timeleft ? "": "FINAL ", whom, hostname);
317 
318 	if (timeleft > 10*60)
319 		(void)fprintf(pf, "System going down at %5.5s\n\n",
320 		    ctime(&shuttime) + 11);
321 	else if (timeleft > 59)
322 		(void)fprintf(pf, "System going down in %d minute%s\n\n",
323 		    timeleft / 60, (timeleft > 60) ? "s" : "");
324 	else if (timeleft)
325 		(void)fprintf(pf, "System going down in 30 seconds\n\n");
326 	else
327 		(void)fprintf(pf, "System going down IMMEDIATELY\n\n");
328 
329 	if (mbuflen)
330 		(void)fwrite(mbuf, sizeof(*mbuf), mbuflen, pf);
331 
332 	/*
333 	 * play some games, just in case wall doesn't come back
334 	 * probably unnecessary, given that wall is careful.
335 	 */
336 	if (!setjmp(alarmbuf)) {
337 		(void)signal(SIGALRM, timeout);
338 		(void)alarm((u_int)30);
339 		(void)pclose(pf);
340 		(void)alarm((u_int)0);
341 		(void)signal(SIGALRM, SIG_DFL);
342 	}
343 }
344 
345 static void
346 timeout(int signo __unused)
347 {
348 	longjmp(alarmbuf, 1);
349 }
350 
351 static void
352 perform_shutdown(void)
353 {
354 	char *empty_environ[] = { NULL };
355 
356 	syslog(LOG_NOTICE, "%s by %s: %s",
357 	    doreboot ? "reboot" : dohalt ? "halt" : dopower ? "power-down" :
358 	    "shutdown", whom, mbuf);
359 	(void)sleep(2);
360 
361 	(void)printf("\r\nSystem shutdown time has arrived\007\007\r\n");
362 	if (killflg) {
363 		(void)printf("\rbut you'll have to do it yourself\r\n");
364 		exit(0);
365 	}
366 #ifdef DEBUG
367 	if (doreboot)
368 		(void)printf("reboot");
369 	else if (dohalt)
370 		(void)printf("halt");
371 	else if (dopower)
372 		(void)printf("power-down");
373 	if (nosync != NULL)
374 		(void)printf(" no sync");
375 	(void)printf("\nkill -HUP 1\n");
376 #else
377 	if (!oflag) {
378 		(void)kill(1, doreboot ? SIGINT :	/* reboot */
379 			      dohalt ? SIGUSR1 :	/* halt */
380 			      dopower ? SIGUSR2 :	/* power-down */
381 			      SIGTERM);			/* single-user */
382 	} else {
383 		if (doreboot) {
384 			execle(_PATH_REBOOT, "reboot", "-l", nosync,
385 				(char *)NULL, empty_environ);
386 			syslog(LOG_ERR, "shutdown: can't exec %s: %m.",
387 				_PATH_REBOOT);
388 			warn(_PATH_REBOOT);
389 		}
390 		else if (dohalt) {
391 			execle(_PATH_HALT, "halt", "-l", nosync,
392 				(char *)NULL, empty_environ);
393 			syslog(LOG_ERR, "shutdown: can't exec %s: %m.",
394 				_PATH_HALT);
395 			warn(_PATH_HALT);
396 		}
397 		else if (dopower) {
398 			execle(_PATH_HALT, "halt", "-l", "-p", nosync,
399 				(char *)NULL, empty_environ);
400 			syslog(LOG_ERR, "shutdown: can't exec %s: %m.",
401 				_PATH_HALT);
402 			warn(_PATH_HALT);
403 		}
404 		(void)kill(1, SIGTERM);		/* to single-user */
405 	}
406 #endif
407 	finish(0);
408 }
409 
410 #define	ATOI2(p)	(p[0] - '0') * 10 + (p[1] - '0'); p += 2;
411 
412 static void
413 getoffset(char *timearg)
414 {
415 	struct tm *lt;
416 	char *p;
417 	time_t now;
418 	int this_year;
419 
420 	(void)time(&now);
421 
422 	if (!strcasecmp(timearg, "now")) {		/* now */
423 		offset = 0;
424 		shuttime = now;
425 		return;
426 	}
427 
428 	if (*timearg == '+') {				/* +minutes */
429 		if (!isdigit(*++timearg))
430 			badtime();
431 		if ((offset = atoi(timearg) * 60) < 0)
432 			badtime();
433 		shuttime = now + offset;
434 		return;
435 	}
436 
437 	/* handle hh:mm by getting rid of the colon */
438 	for (p = timearg; *p; ++p)
439 		if (!isascii(*p) || !isdigit(*p)) {
440 			if (*p == ':' && strlen(p) == 3) {
441 				p[0] = p[1];
442 				p[1] = p[2];
443 				p[2] = '\0';
444 			}
445 			else
446 				badtime();
447 		}
448 
449 	unsetenv("TZ");					/* OUR timezone */
450 	lt = localtime(&now);				/* current time val */
451 
452 	switch(strlen(timearg)) {
453 	case 10:
454 		this_year = lt->tm_year;
455 		lt->tm_year = ATOI2(timearg);
456 		/*
457 		 * check if the specified year is in the next century.
458 		 * allow for one year of user error as many people will
459 		 * enter n - 1 at the start of year n.
460 		 */
461 		if (lt->tm_year < (this_year % 100) - 1)
462 			lt->tm_year += 100;
463 		/* adjust for the year 2000 and beyond */
464 		lt->tm_year += (this_year - (this_year % 100));
465 		/* FALLTHROUGH */
466 	case 8:
467 		lt->tm_mon = ATOI2(timearg);
468 		if (--lt->tm_mon < 0 || lt->tm_mon > 11)
469 			badtime();
470 		/* FALLTHROUGH */
471 	case 6:
472 		lt->tm_mday = ATOI2(timearg);
473 		if (lt->tm_mday < 1 || lt->tm_mday > 31)
474 			badtime();
475 		/* FALLTHROUGH */
476 	case 4:
477 		lt->tm_hour = ATOI2(timearg);
478 		if (lt->tm_hour < 0 || lt->tm_hour > 23)
479 			badtime();
480 		lt->tm_min = ATOI2(timearg);
481 		if (lt->tm_min < 0 || lt->tm_min > 59)
482 			badtime();
483 		lt->tm_sec = 0;
484 		if ((shuttime = mktime(lt)) == -1)
485 			badtime();
486 		if ((offset = shuttime - now) < 0)
487 			errx(1, "that time is already past.");
488 		break;
489 	default:
490 		badtime();
491 	}
492 }
493 
494 #define	NOMSG	"\n\nNO LOGINS: System going down at "
495 static void
496 nolog(void)
497 {
498 	int logfd;
499 	char *ct;
500 
501 	(void)unlink(_PATH_NOLOGIN);	/* in case linked to another file */
502 	(void)signal(SIGINT, finish);
503 	(void)signal(SIGHUP, finish);
504 	(void)signal(SIGQUIT, finish);
505 	(void)signal(SIGTERM, finish);
506 	if ((logfd = open(_PATH_NOLOGIN, O_WRONLY|O_CREAT|O_TRUNC,
507 	    0664)) >= 0) {
508 		(void)write(logfd, NOMSG, sizeof(NOMSG) - 1);
509 		ct = ctime(&shuttime);
510 		(void)write(logfd, ct + 11, 5);
511 		(void)write(logfd, "\n\n", 2);
512 		(void)write(logfd, mbuf, strlen(mbuf));
513 		(void)close(logfd);
514 	}
515 }
516 
517 static void
518 finish(int signo __unused)
519 {
520 	if (!killflg)
521 		(void)unlink(_PATH_NOLOGIN);
522 	exit(0);
523 }
524 
525 static void
526 badtime(void)
527 {
528 	errx(1, "bad time format");
529 }
530 
531 static void
532 usage(const char *cp)
533 {
534 	if (cp != NULL)
535 		warnx("%s", cp);
536 	(void)fprintf(stderr,
537 	    "usage: shutdown [-] [-h | -p | -r | -k] [-o [-n]] time [warning-message ...]\n"
538 	    "       poweroff\n");
539 	exit(1);
540 }
541