* Set SHELL to /bin/sh in the environmant of shutdown.
[sysvinit.git] / src / shutdown.c
1 /*
2 * shutdown.c Shut the system down.
3 *
4 * Usage: shutdown [-krhfnc] time [warning message]
5 * -k: don't really shutdown, only warn.
6 * -r: reboot after shutdown.
7 * -h: halt after shutdown.
8 * -f: do a 'fast' reboot (skip fsck).
9 * -F: Force fsck on reboot.
10 * -n: do not go through init but do it ourselves.
11 * -c: cancel an already running shutdown.
12 * -t secs: delay between SIGTERM and SIGKILL for init.
13 *
14 * Author: Miquel van Smoorenburg, miquels@cistron.nl
15 *
16 * Version: @(#)shutdown 2.86-1 31-Jul-2004 miquels@cistron.nl
17 *
18 * This file is part of the sysvinit suite,
19 * Copyright (C) 1991-2004 Miquel van Smoorenburg.
20 *
21 * This program is free software; you can redistribute it and/or modify
22 * it under the terms of the GNU General Public License as published by
23 * the Free Software Foundation; either version 2 of the License, or
24 * (at your option) any later version.
25 *
26 * This program is distributed in the hope that it will be useful,
27 * but WITHOUT ANY WARRANTY; without even the implied warranty of
28 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
29 * GNU General Public License for more details.
30 *
31 * You should have received a copy of the GNU General Public License
32 * along with this program; if not, write to the Free Software
33 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
34 */
35 #include <sys/types.h>
36 #include <sys/stat.h>
37 #include <sys/wait.h>
38 #include <time.h>
39 #include <string.h>
40 #include <unistd.h>
41 #include <errno.h>
42 #include <stdlib.h>
43 #include <stdio.h>
44 #include <signal.h>
45 #include <fcntl.h>
46 #include <stdarg.h>
47 #include <utmp.h>
48 #include <syslog.h>
49 #include "paths.h"
50 #include "reboot.h"
51 #include "initreq.h"
52 #include "init.h"
53
54
55 char *Version = "@(#) shutdown 2.86-1 31-Jul-2004 miquels@cistron.nl";
56
57 #define MESSAGELEN 256
58
59 int dontshut = 0; /* Don't shutdown, only warn */
60 char down_level[2]; /* What runlevel to go to. */
61 int dosync = 1; /* Sync before reboot or halt */
62 int fastboot = 0; /* Do a 'fast' reboot */
63 int forcefsck = 0; /* Force fsck on reboot */
64 char message[MESSAGELEN]; /* Warning message */
65 char *sltime = 0; /* Sleep time */
66 char newstate[64]; /* What are we gonna do */
67 int doself = 0; /* Don't use init */
68 int got_alrm = 0;
69
70 char *clean_env[] = {
71 "HOME=/",
72 "PATH=/bin:/usr/bin:/sbin:/usr/sbin",
73 "TERM=dumb",
74 "SHELL=/bin/sh",
75 NULL,
76 };
77
78 /* From "utmp.c" */
79 extern void write_wtmp(char *user, char *id, int pid, int type, char *line);
80
81 /*
82 * Sleep without being interrupted.
83 */
84 void hardsleep(int secs)
85 {
86 struct timespec ts, rem;
87
88 ts.tv_sec = secs;
89 ts.tv_nsec = 0;
90
91 while(nanosleep(&ts, &rem) < 0 && errno == EINTR)
92 ts = rem;
93 }
94
95 /*
96 * Break off an already running shutdown.
97 */
98 void stopit(int sig)
99 {
100 unlink(NOLOGIN);
101 unlink(FASTBOOT);
102 unlink(FORCEFSCK);
103 unlink(SDPID);
104 printf("\r\nShutdown cancelled.\r\n");
105 exit(0);
106 }
107
108 /*
109 * Show usage message.
110 */
111 void usage(void)
112 {
113 fprintf(stderr,
114 "Usage:\t shutdown [-akrhPHfFnc] [-t sec] time [warning message]\n"
115 "\t\t -a: use /etc/shutdown.allow\n"
116 "\t\t -k: don't really shutdown, only warn.\n"
117 "\t\t -r: reboot after shutdown.\n"
118 "\t\t -h: halt after shutdown.\n"
119 "\t\t -P: halt action is to turn off power.\n"
120 "\t\t -H: halt action is to just halt.\n"
121 "\t\t -f: do a 'fast' reboot (skip fsck).\n"
122 "\t\t -F: Force fsck on reboot.\n"
123 "\t\t -n: do not go through \"init\" but go down real fast.\n"
124 "\t\t -c: cancel a running shutdown.\n"
125 "\t\t -t secs: delay between warning and kill signal.\n"
126 "\t\t ** the \"time\" argument is mandatory! (try \"now\") **\n");
127 exit(1);
128 }
129
130
131 void alrm_handler(int sig)
132 {
133 got_alrm = sig;
134 }
135
136
137 /*
138 * Set environment variables in the init process.
139 */
140 int init_setenv(char *name, char *value)
141 {
142 struct init_request request;
143 struct sigaction sa;
144 int fd;
145 int nl, vl;
146
147 memset(&request, 0, sizeof(request));
148 request.magic = INIT_MAGIC;
149 request.cmd = INIT_CMD_SETENV;
150 nl = strlen(name);
151 vl = value ? strlen(value) : 0;
152
153 if (nl + vl + 3 >= (int)sizeof(request.i.data))
154 return -1;
155
156 memcpy(request.i.data, name, nl);
157 if (value) {
158 request.i.data[nl] = '=';
159 memcpy(request.i.data + nl + 1, value, vl);
160 }
161
162 /*
163 * Open the fifo and write the command.
164 * Make sure we don't hang on opening /dev/initctl
165 */
166 memset(&sa, 0, sizeof(sa));
167 sa.sa_handler = alrm_handler;
168 sigaction(SIGALRM, &sa, NULL);
169 got_alrm = 0;
170 alarm(3);
171 if ((fd = open(INIT_FIFO, O_WRONLY)) >= 0) { &&
172 ssize_t p = 0;
173 size_t s = sizeof(request);
174 void *ptr = &request;
175 while (s > 0) {
176 p = write(fd, ptr, s);
177 if (p < 0) {
178 if (errno == EINTR || errno == EAGAIN)
179 continue;
180 break;
181 }
182 ptr += p;
183 s -= p;
184 }
185 close(fd);
186 alarm(0);
187 return 0;
188 }
189
190 fprintf(stderr, "shutdown: ");
191 if (got_alrm) {
192 fprintf(stderr, "timeout opening/writing control channel %s\n",
193 INIT_FIFO);
194 } else {
195 perror(INIT_FIFO);
196 }
197 return -1;
198 }
199
200
201 /*
202 * Tell everyone the system is going down in 'mins' minutes.
203 */
204 void warn(int mins)
205 {
206 char buf[MESSAGELEN + sizeof(newstate)];
207 int len;
208
209 buf[0] = 0;
210 strncat(buf, message, sizeof(buf) - 1);
211 len = strlen(buf);
212
213 if (mins == 0)
214 snprintf(buf + len, sizeof(buf) - len,
215 "\rThe system is going down %s NOW!\r\n",
216 newstate);
217 else
218 snprintf(buf + len, sizeof(buf) - len,
219 "\rThe system is going DOWN %s in %d minute%s!\r\n",
220 newstate, mins, mins == 1 ? "" : "s");
221 wall(buf, 0);
222 }
223
224 /*
225 * Create the /etc/nologin file.
226 */
227 void donologin(int min)
228 {
229 FILE *fp;
230 time_t t;
231
232 time(&t);
233 t += 60 * min;
234
235 if ((fp = fopen(NOLOGIN, "w")) != NULL) {
236 fprintf(fp, "\rThe system is going down on %s\r\n", ctime(&t));
237 if (message[0]) fputs(message, fp);
238 fclose(fp);
239 }
240 }
241
242 /*
243 * Spawn an external program.
244 */
245 int spawn(int noerr, char *prog, ...)
246 {
247 va_list ap;
248 pid_t pid, rc;
249 int i;
250 char *argv[8];
251
252 i = 0;
253 while ((pid = fork()) < 0 && i < 10) {
254 perror("fork");
255 sleep(5);
256 i++;
257 }
258
259 if (pid < 0) return -1;
260
261 if (pid > 0) {
262 while((rc = wait(&i)) != pid)
263 if (rc < 0 && errno == ECHILD)
264 break;
265 return (rc == pid) ? WEXITSTATUS(i) : -1;
266 }
267
268 if (noerr) fclose(stderr);
269
270 argv[0] = prog;
271 va_start(ap, prog);
272 for (i = 1; i < 7 && (argv[i] = va_arg(ap, char *)) != NULL; i++)
273 ;
274 argv[i] = NULL;
275 va_end(ap);
276
277 chdir("/");
278 environ = clean_env;
279
280 execvp(argv[0], argv);
281 perror(argv[0]);
282 exit(1);
283
284 /*NOTREACHED*/
285 return 0;
286 }
287
288 /*
289 * Kill all processes, call /etc/init.d/halt (if present)
290 */
291 void fastdown()
292 {
293 int do_halt = (down_level[0] == '0');
294 int i;
295 #if 0
296 char cmd[128];
297 char *script;
298
299 /*
300 * Currently, the halt script is either init.d/halt OR rc.d/rc.0,
301 * likewise for the reboot script. Test for the presence
302 * of either.
303 */
304 if (do_halt) {
305 if (access(HALTSCRIPT1, X_OK) == 0)
306 script = HALTSCRIPT1;
307 else
308 script = HALTSCRIPT2;
309 } else {
310 if (access(REBOOTSCRIPT1, X_OK) == 0)
311 script = REBOOTSCRIPT1;
312 else
313 script = REBOOTSCRIPT2;
314 }
315 #endif
316
317 /* First close all files. */
318 for(i = 0; i < 3; i++)
319 if (!isatty(i)) {
320 close(i);
321 open("/dev/null", O_RDWR);
322 }
323 for(i = 3; i < 20; i++) close(i);
324 close(255);
325
326 /* First idle init. */
327 if (kill(1, SIGTSTP) < 0) {
328 fprintf(stderr, "shutdown: can't idle init.\r\n");
329 exit(1);
330 }
331
332 /* Kill all processes. */
333 fprintf(stderr, "shutdown: sending all processes the TERM signal...\r\n");
334 kill(-1, SIGTERM);
335 sleep(sltime ? atoi(sltime) : 3);
336 fprintf(stderr, "shutdown: sending all processes the KILL signal.\r\n");
337 (void) kill(-1, SIGKILL);
338
339 #if 0
340 /* See if we can run /etc/init.d/halt */
341 if (access(script, X_OK) == 0) {
342 spawn(1, cmd, "fast", NULL);
343 fprintf(stderr, "shutdown: %s returned - falling back "
344 "on default routines\r\n", script);
345 }
346 #endif
347
348 /* script failed or not present: do it ourself. */
349 sleep(1); /* Give init the chance to collect zombies. */
350
351 /* Record the fact that we're going down */
352 write_wtmp("shutdown", "~~", 0, RUN_LVL, "~~");
353
354 /* This is for those who have quota installed. */
355 spawn(1, "accton", NULL);
356 spawn(1, "quotaoff", "-a", NULL);
357
358 sync();
359 fprintf(stderr, "shutdown: turning off swap\r\n");
360 spawn(0, "swapoff", "-a", NULL);
361 fprintf(stderr, "shutdown: unmounting all file systems\r\n");
362 spawn(0, "umount", "-a", NULL);
363
364 /* We're done, halt or reboot now. */
365 if (do_halt) {
366 fprintf(stderr, "The system is halted. Press CTRL-ALT-DEL "
367 "or turn off power\r\n");
368 init_reboot(BMAGIC_HALT);
369 exit(0);
370 }
371
372 fprintf(stderr, "Please stand by while rebooting the system.\r\n");
373 init_reboot(BMAGIC_REBOOT);
374 exit(0);
375 }
376
377 /*
378 * Go to runlevel 0, 1 or 6.
379 */
380 void shutdown(char *halttype)
381 {
382 char *args[8];
383 int argp = 0;
384 int do_halt = (down_level[0] == '0');
385
386 /* Warn for the last time */
387 warn(0);
388 if (dontshut) {
389 hardsleep(1);
390 stopit(0);
391 }
392 openlog("shutdown", LOG_PID, LOG_USER);
393 if (do_halt)
394 syslog(LOG_NOTICE, "shutting down for system halt");
395 else
396 syslog(LOG_NOTICE, "shutting down for system reboot");
397 closelog();
398
399 /* See if we have to do it ourself. */
400 if (doself) fastdown();
401
402 /* Create the arguments for init. */
403 args[argp++] = INIT;
404 if (sltime) {
405 args[argp++] = "-t";
406 args[argp++] = sltime;
407 }
408 args[argp++] = down_level;
409 args[argp] = (char *)NULL;
410
411 unlink(SDPID);
412 unlink(NOLOGIN);
413
414 /* Now execute init to change runlevel. */
415 sync();
416 init_setenv("INIT_HALT", halttype);
417 execv(INIT, args);
418
419 /* Oops - failed. */
420 fprintf(stderr, "\rshutdown: cannot execute %s\r\n", INIT);
421 unlink(FASTBOOT);
422 unlink(FORCEFSCK);
423 init_setenv("INIT_HALT", NULL);
424 openlog("shutdown", LOG_PID, LOG_USER);
425 syslog(LOG_NOTICE, "shutdown failed");
426 closelog();
427 exit(1);
428 }
429
430 /*
431 * returns if a warning is to be sent for wt
432 */
433 static int needwarning(int wt)
434 {
435 int ret;
436
437 if (wt < 10)
438 ret = 1;
439 else if (wt < 60)
440 ret = (wt % 15 == 0);
441 else if (wt < 180)
442 ret = (wt % 30 == 0);
443 else
444 ret = (wt % 60 == 0);
445
446 return ret;
447 }
448
449 /*
450 * Main program.
451 * Process the options and do the final countdown.
452 */
453 int main(int argc, char **argv)
454 {
455 FILE *fp;
456 extern int getopt();
457 extern int optind;
458 struct sigaction sa;
459 struct tm *lt;
460 struct stat st;
461 struct utmp *ut;
462 time_t t;
463 uid_t realuid;
464 char *halttype;
465 char *downusers[32];
466 char buf[128];
467 char term[UT_LINESIZE + 6];
468 char *sp;
469 char *when = NULL;
470 int c, i, wt;
471 int hours, mins;
472 int didnolog = 0;
473 int cancel = 0;
474 int useacl = 0;
475 int pid = 0;
476 int user_ok = 0;
477
478 /* We can be installed setuid root (executable for a special group) */
479 realuid = getuid();
480 setuid(geteuid());
481
482 if (getuid() != 0) {
483 fprintf(stderr, "shutdown: you must be root to do that!\n");
484 usage();
485 exit(1);
486 }
487 strcpy(down_level, "1");
488 halttype = NULL;
489
490 /* Process the options. */
491 while((c = getopt(argc, argv, "HPacqkrhnfFyt:g:i:")) != EOF) {
492 switch(c) {
493 case 'H':
494 halttype = "HALT";
495 break;
496 case 'P':
497 halttype = "POWERDOWN";
498 break;
499 case 'a': /* Access control. */
500 useacl = 1;
501 break;
502 case 'c': /* Cancel an already running shutdown. */
503 cancel = 1;
504 break;
505 case 'k': /* Don't really shutdown, only warn.*/
506 dontshut = 1;
507 break;
508 case 'r': /* Automatic reboot */
509 down_level[0] = '6';
510 break;
511 case 'h': /* Halt after shutdown */
512 down_level[0] = '0';
513 break;
514 case 'f': /* Don't perform fsck after next boot */
515 fastboot = 1;
516 break;
517 case 'F': /* Force fsck after next boot */
518 forcefsck = 1;
519 break;
520 case 'n': /* Don't switch runlevels. */
521 doself = 1;
522 break;
523 case 't': /* Delay between TERM and KILL */
524 sltime = optarg;
525 break;
526 case 'y': /* Ignored for sysV compatibility */
527 break;
528 case 'g': /* sysv style to specify time. */
529 when = optarg;
530 break;
531 case 'i': /* Level to go to. */
532 if (!strchr("0156aAbBcCsS", optarg[0])) {
533 fprintf(stderr,
534 "shutdown: `%s': bad runlevel\n",
535 optarg);
536 exit(1);
537 }
538 down_level[0] = optarg[0];
539 break;
540 default:
541 usage();
542 break;
543 }
544 }
545
546 if (NULL != halttype && down_level[0] != '0') {
547 fprintf(stderr, "shutdown: -H and -P flags can only be used along with -h flag.\n");
548 usage();
549 exit(1);
550 }
551
552 /* Do we need to use the shutdown.allow file ? */
553 if (useacl && (fp = fopen(SDALLOW, "r")) != NULL) {
554
555 /* Read /etc/shutdown.allow. */
556 i = 0;
557 while(fgets(buf, 128, fp)) {
558 if (buf[0] == '#' || buf[0] == '\n') continue;
559 if (i > 31) continue;
560 for(sp = buf; *sp; sp++) if (*sp == '\n') *sp = 0;
561 downusers[i++] = strdup(buf);
562 }
563 if (i < 32) downusers[i] = 0;
564 fclose(fp);
565
566 /* Now walk through /var/run/utmp to find logged in users. */
567 while(!user_ok && (ut = getutent()) != NULL) {
568
569 /* See if this is a user process on a VC. */
570 if (ut->ut_type != USER_PROCESS) continue;
571 sprintf(term, "/dev/%.*s", UT_LINESIZE, ut->ut_line);
572 if (stat(term, &st) < 0) continue;
573 #ifdef major /* glibc */
574 if (major(st.st_rdev) != 4 ||
575 minor(st.st_rdev) > 63) continue;
576 #else
577 if ((st.st_rdev & 0xFFC0) != 0x0400) continue;
578 #endif
579 /* Root is always OK. */
580 if (strcmp(ut->ut_user, "root") == 0) {
581 user_ok++;
582 break;
583 }
584
585 /* See if this is an allowed user. */
586 for(i = 0; i < 32 && downusers[i]; i++)
587 if (!strncmp(downusers[i], ut->ut_user,
588 UT_NAMESIZE)) {
589 user_ok++;
590 break;
591 }
592 }
593 endutent();
594
595 /* See if user was allowed. */
596 if (!user_ok) {
597 if ((fp = fopen(CONSOLE, "w")) != NULL) {
598 fprintf(fp, "\rshutdown: no authorized users "
599 "logged in.\r\n");
600 fclose(fp);
601 }
602 exit(1);
603 }
604 }
605
606 /* Read pid of running shutdown from a file */
607 if ((fp = fopen(SDPID, "r")) != NULL) {
608 fscanf(fp, "%d", &pid);
609 fclose(fp);
610 }
611
612 /* Read remaining words, skip time if needed. */
613 message[0] = 0;
614 for(c = optind + (!cancel && !when); c < argc; c++) {
615 if (strlen(message) + strlen(argv[c]) + 4 > MESSAGELEN)
616 break;
617 strcat(message, argv[c]);
618 strcat(message, " ");
619 }
620 if (message[0]) strcat(message, "\r\n");
621
622 /* See if we want to run or cancel. */
623 if (cancel) {
624 if (pid <= 0) {
625 fprintf(stderr, "shutdown: cannot find pid "
626 "of running shutdown.\n");
627 exit(1);
628 }
629 init_setenv("INIT_HALT", NULL);
630 if (kill(pid, SIGINT) < 0) {
631 fprintf(stderr, "shutdown: not running.\n");
632 exit(1);
633 }
634 if (message[0]) wall(message, 0);
635 exit(0);
636 }
637
638 /* Check syntax. */
639 if (when == NULL) {
640 if (optind == argc) usage();
641 when = argv[optind++];
642 }
643
644 /* See if we are already running. */
645 if (pid > 0 && kill(pid, 0) == 0) {
646 fprintf(stderr, "\rshutdown: already running.\r\n");
647 exit(1);
648 }
649
650 /* Extra check. */
651 if (doself && down_level[0] != '0' && down_level[0] != '6') {
652 fprintf(stderr,
653 "shutdown: can use \"-n\" for halt or reboot only.\r\n");
654 exit(1);
655 }
656
657 /* Tell users what we're gonna do. */
658 switch(down_level[0]) {
659 case '0':
660 strcpy(newstate, "for system halt");
661 break;
662 case '6':
663 strcpy(newstate, "for reboot");
664 break;
665 case '1':
666 strcpy(newstate, "to maintenance mode");
667 break;
668 default:
669 sprintf(newstate, "to runlevel %s", down_level);
670 break;
671 }
672
673 /* Create a new PID file. */
674 unlink(SDPID);
675 umask(022);
676 if ((fp = fopen(SDPID, "w")) != NULL) {
677 fprintf(fp, "%d\n", getpid());
678 fclose(fp);
679 } else if (errno != EROFS)
680 fprintf(stderr, "shutdown: warning: cannot open %s\n", SDPID);
681
682 /*
683 * Catch some common signals.
684 */
685 signal(SIGQUIT, SIG_IGN);
686 signal(SIGCHLD, SIG_IGN);
687 signal(SIGHUP, SIG_IGN);
688 signal(SIGTSTP, SIG_IGN);
689 signal(SIGTTIN, SIG_IGN);
690 signal(SIGTTOU, SIG_IGN);
691
692 memset(&sa, 0, sizeof(sa));
693 sa.sa_handler = stopit;
694 sigaction(SIGINT, &sa, NULL);
695
696 /* Go to the root directory */
697 chdir("/");
698 if (fastboot) close(open(FASTBOOT, O_CREAT | O_RDWR, 0644));
699 if (forcefsck) close(open(FORCEFSCK, O_CREAT | O_RDWR, 0644));
700
701 /* Alias now and take care of old '+mins' notation. */
702 if (!strcmp(when, "now")) strcpy(when, "0");
703 if (when[0] == '+') when++;
704
705 /* Decode shutdown time. */
706 for (sp = when; *sp; sp++) {
707 if (*sp != ':' && (*sp < '0' || *sp > '9'))
708 usage();
709 }
710 if (strchr(when, ':') == NULL) {
711 /* Time in minutes. */
712 wt = atoi(when);
713 if (wt == 0 && when[0] != '0') usage();
714 } else {
715 /* Time in hh:mm format. */
716 if (sscanf(when, "%d:%2d", &hours, &mins) != 2) usage();
717 if (hours > 23 || mins > 59) usage();
718 time(&t);
719 lt = localtime(&t);
720 wt = (60*hours + mins) - (60*lt->tm_hour + lt->tm_min);
721 if (wt < 0) wt += 1440;
722 }
723 /* Shutdown NOW if time == 0 */
724 if (wt == 0) shutdown(halttype);
725
726 /* Give warnings on regular intervals and finally shutdown. */
727 if (wt < 15 && !needwarning(wt)) warn(wt);
728 while(wt) {
729 if (wt <= 5 && !didnolog) {
730 donologin(wt);
731 didnolog++;
732 }
733 if (needwarning(wt)) warn(wt);
734 hardsleep(60);
735 wt--;
736 }
737 shutdown(halttype);
738
739 return 0; /* Never happens */
740 }