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