shutdown.c revision 235855
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
32static 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
38static char sccsid[] = "@(#)shutdown.c	8.4 (Berkeley) 4/28/95";
39#endif /* not lint */
40#endif
41#include <sys/cdefs.h>
42__FBSDID("$FreeBSD: head/sbin/shutdown/shutdown.c 235855 2012-05-23 19:25:46Z jilles $");
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
70static 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
90static time_t offset, shuttime;
91static int dohalt, dopower, doreboot, killflg, mbuflen, oflag;
92static char mbuf[BUFSIZ];
93static const char *nosync, *whom;
94
95static void badtime(void);
96static void perform_shutdown(void);
97static void finish(int);
98static void getoffset(char *);
99static void loop(void);
100static void nolog(void);
101static void timeout(int);
102static void timewarn(int);
103static void usage(const char *);
104
105extern const char **environ;
106
107int
108main(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
187poweroff:
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
246static void
247loop(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
288static jmp_buf alarmbuf;
289
290static const char *restricted_environ[] = {
291	"PATH=" _PATH_STDPATH,
292	NULL
293};
294
295static void
296timewarn(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
345static void
346timeout(int signo __unused)
347{
348	longjmp(alarmbuf, 1);
349}
350
351static void
352perform_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
360	(void)printf("\r\nSystem shutdown time has arrived\007\007\r\n");
361	if (killflg) {
362		(void)printf("\rbut you'll have to do it yourself\r\n");
363		exit(0);
364	}
365#ifdef DEBUG
366	if (doreboot)
367		(void)printf("reboot");
368	else if (dohalt)
369		(void)printf("halt");
370	else if (dopower)
371		(void)printf("power-down");
372	if (nosync != NULL)
373		(void)printf(" no sync");
374	(void)printf("\nkill -HUP 1\n");
375#else
376	if (!oflag) {
377		(void)kill(1, doreboot ? SIGINT :	/* reboot */
378			      dohalt ? SIGUSR1 :	/* halt */
379			      dopower ? SIGUSR2 :	/* power-down */
380			      SIGTERM);			/* single-user */
381	} else {
382		if (doreboot) {
383			execle(_PATH_REBOOT, "reboot", "-l", nosync,
384				(char *)NULL, empty_environ);
385			syslog(LOG_ERR, "shutdown: can't exec %s: %m.",
386				_PATH_REBOOT);
387			warn(_PATH_REBOOT);
388		}
389		else if (dohalt) {
390			execle(_PATH_HALT, "halt", "-l", nosync,
391				(char *)NULL, empty_environ);
392			syslog(LOG_ERR, "shutdown: can't exec %s: %m.",
393				_PATH_HALT);
394			warn(_PATH_HALT);
395		}
396		else if (dopower) {
397			execle(_PATH_HALT, "halt", "-l", "-p", nosync,
398				(char *)NULL, empty_environ);
399			syslog(LOG_ERR, "shutdown: can't exec %s: %m.",
400				_PATH_HALT);
401			warn(_PATH_HALT);
402		}
403		(void)kill(1, SIGTERM);		/* to single-user */
404	}
405#endif
406	finish(0);
407}
408
409#define	ATOI2(p)	(p[0] - '0') * 10 + (p[1] - '0'); p += 2;
410
411static void
412getoffset(char *timearg)
413{
414	struct tm *lt;
415	char *p;
416	time_t now;
417	int this_year;
418
419	(void)time(&now);
420
421	if (!strcasecmp(timearg, "now")) {		/* now */
422		offset = 0;
423		shuttime = now;
424		return;
425	}
426
427	if (*timearg == '+') {				/* +minutes */
428		if (!isdigit(*++timearg))
429			badtime();
430		if ((offset = atoi(timearg) * 60) < 0)
431			badtime();
432		shuttime = now + offset;
433		return;
434	}
435
436	/* handle hh:mm by getting rid of the colon */
437	for (p = timearg; *p; ++p)
438		if (!isascii(*p) || !isdigit(*p)) {
439			if (*p == ':' && strlen(p) == 3) {
440				p[0] = p[1];
441				p[1] = p[2];
442				p[2] = '\0';
443			}
444			else
445				badtime();
446		}
447
448	unsetenv("TZ");					/* OUR timezone */
449	lt = localtime(&now);				/* current time val */
450
451	switch(strlen(timearg)) {
452	case 10:
453		this_year = lt->tm_year;
454		lt->tm_year = ATOI2(timearg);
455		/*
456		 * check if the specified year is in the next century.
457		 * allow for one year of user error as many people will
458		 * enter n - 1 at the start of year n.
459		 */
460		if (lt->tm_year < (this_year % 100) - 1)
461			lt->tm_year += 100;
462		/* adjust for the year 2000 and beyond */
463		lt->tm_year += (this_year - (this_year % 100));
464		/* FALLTHROUGH */
465	case 8:
466		lt->tm_mon = ATOI2(timearg);
467		if (--lt->tm_mon < 0 || lt->tm_mon > 11)
468			badtime();
469		/* FALLTHROUGH */
470	case 6:
471		lt->tm_mday = ATOI2(timearg);
472		if (lt->tm_mday < 1 || lt->tm_mday > 31)
473			badtime();
474		/* FALLTHROUGH */
475	case 4:
476		lt->tm_hour = ATOI2(timearg);
477		if (lt->tm_hour < 0 || lt->tm_hour > 23)
478			badtime();
479		lt->tm_min = ATOI2(timearg);
480		if (lt->tm_min < 0 || lt->tm_min > 59)
481			badtime();
482		lt->tm_sec = 0;
483		if ((shuttime = mktime(lt)) == -1)
484			badtime();
485		if ((offset = shuttime - now) < 0)
486			errx(1, "that time is already past.");
487		break;
488	default:
489		badtime();
490	}
491}
492
493#define	NOMSG	"\n\nNO LOGINS: System going down at "
494static void
495nolog(void)
496{
497	int logfd;
498	char *ct;
499
500	(void)unlink(_PATH_NOLOGIN);	/* in case linked to another file */
501	(void)signal(SIGINT, finish);
502	(void)signal(SIGHUP, finish);
503	(void)signal(SIGQUIT, finish);
504	(void)signal(SIGTERM, finish);
505	if ((logfd = open(_PATH_NOLOGIN, O_WRONLY|O_CREAT|O_TRUNC,
506	    0664)) >= 0) {
507		(void)write(logfd, NOMSG, sizeof(NOMSG) - 1);
508		ct = ctime(&shuttime);
509		(void)write(logfd, ct + 11, 5);
510		(void)write(logfd, "\n\n", 2);
511		(void)write(logfd, mbuf, strlen(mbuf));
512		(void)close(logfd);
513	}
514}
515
516static void
517finish(int signo __unused)
518{
519	if (!killflg)
520		(void)unlink(_PATH_NOLOGIN);
521	exit(0);
522}
523
524static void
525badtime(void)
526{
527	errx(1, "bad time format");
528}
529
530static void
531usage(const char *cp)
532{
533	if (cp != NULL)
534		warnx("%s", cp);
535	(void)fprintf(stderr,
536	    "usage: shutdown [-] [-h | -p | -r | -k] [-o [-n]] time [warning-message ...]\n"
537	    "       poweroff\n");
538	exit(1);
539}
540