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