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