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