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