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