1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
|
/* upstart
*
* Copyright © 2010 Canonical Ltd.
* Author: Scott James Remnant <scott@netsplit.com>.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2, as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif /* HAVE_CONFIG_H */
#include <dbus/dbus.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/param.h>
#include <pwd.h>
#include <time.h>
#include <utmpx.h>
#include <fcntl.h>
#include <errno.h>
#include <stdio.h>
#include <limits.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <nih/macros.h>
#include <nih/alloc.h>
#include <nih/timer.h>
#include <nih/string.h>
#include <nih/signal.h>
#include <nih/io.h>
#include <nih/main.h>
#include <nih/option.h>
#include <nih/logging.h>
#include <nih/error.h>
#include <nih-dbus/dbus_error.h>
#include <nih-dbus/errors.h>
#include "sysv.h"
/**
* ETC_NOLOGIN:
*
* File we write to to prevent logins.
**/
#define ETC_NOLOGIN "/etc/nologin"
/**
* DEV:
*
* Directory containing tty device nodes.
**/
#define DEV "/dev"
/**
* DEV_INITCTL:
*
* System V init control socket.
**/
#ifndef DEV_INITCTL
#define DEV_INITCTL "/dev/initctl"
#endif
/**
* RUN_INITCTL:
*
* System V init control socket (new location).
**/
#ifndef RUN_INITCTL
#define RUN_INITCTL "/run/initctl"
#endif
/* Prototypes for option functions */
static int runlevel_option (NihOption *option, const char *arg);
/* Prototypes for static functions */
static void shutdown_now (void)
__attribute__ ((noreturn));
static void cancel_callback (void *data, NihSignal *signal)
__attribute__ ((noreturn));
static void timer_callback (const char *message);
static char *warning_message (const char *message)
__attribute__ ((warn_unused_result));
static void wall (const char *message);
static void sysvinit_shutdown (void);
/**
* runlevel:
*
* Runlevel to switch to.
**/
static int runlevel = 0;
/**
* init_halt:
*
* Value of init_halt environment variable for event.
**/
static const char *init_halt = NULL;
/**
* cancel:
*
* TRUE if we should cancel an already running shutdown.
**/
static int cancel = FALSE;
/**
* warn_only:
*
* TRUE if we should only send the warning, and not perform the actual
* shutdown.
**/
static int warn_only = FALSE;
/**
* when:
*
* Time to shutdown, parsed from the old -g argument.
**/
static char *when = NULL;
/**
* delay:
*
* How long until we shutdown.
**/
static int delay = 0;
/**
* runlevel_option:
* @option: option found in arguments,
* @arg: always NULL.
*
* This function is called whenever one of the -r, -h, -H or -P options
* is found in the argument list. It changes the runlevel to that implied
* by the option.
**/
static int
runlevel_option (NihOption *option,
const char *arg)
{
int *value;
nih_assert (option != NULL);
nih_assert (option->value != NULL);
nih_assert (arg == NULL);
value = (int *)option->value;
switch (option->option) {
case 'r':
*value = '6';
init_halt = NULL;
break;
case 'h':
*value = '0';
init_halt = NULL;
break;
case 'H':
*value = '0';
init_halt = "HALT";
break;
case 'P':
*value = '0';
init_halt = "POWEROFF";
break;
}
return 0;
}
/**
* options:
*
* Command-line options accepted for all arguments.
**/
static NihOption options[] = {
{ 'r', NULL, N_("reboot after shutdown"),
NULL, NULL, &runlevel, runlevel_option },
{ 'h', NULL, N_("halt or power off after shutdown"),
NULL, NULL, &runlevel, runlevel_option },
{ 'H', NULL, N_("halt after shutdown (implies -h)"),
NULL, NULL, &runlevel, runlevel_option },
{ 'P', NULL, N_("power off after shutdown (implies -h)"),
NULL, NULL, &runlevel, runlevel_option },
{ 'c', NULL, N_("cancel a running shutdown"),
NULL, NULL, &cancel, NULL },
{ 'k', NULL, N_("only send warnings, don't shutdown"),
NULL, NULL, &warn_only, NULL },
/* Compatibility option for specifying time */
{ 'g', NULL, NULL, NULL, "TIME", &when, NULL },
/* Compatibility options, all ignored */
{ 'a', NULL, NULL, NULL, NULL, NULL, NULL },
{ 'n', NULL, NULL, NULL, NULL, NULL, NULL },
{ 'f', NULL, NULL, NULL, NULL, NULL, NULL },
{ 'F', NULL, NULL, NULL, NULL, NULL, NULL },
{ 'i', NULL, NULL, NULL, "LEVEL", NULL, NULL },
{ 't', NULL, NULL, NULL, "SECS", NULL, NULL },
{ 'y', NULL, NULL, NULL, NULL, NULL, NULL },
NIH_OPTION_LAST
};
int
main (int argc,
char *argv[])
{
char ** args;
nih_local char *message = NULL;
size_t messagelen;
nih_local char *msg = NULL;
int arg;
pid_t pid = 0;
nih_main_init (argv[0]);
nih_option_set_usage (_("TIME [MESSAGE]"));
nih_option_set_synopsis (_("Bring the system down."));
nih_option_set_help (
_("TIME may have different formats, the most common is simply "
"the word 'now' which will bring the system down "
"immediately. Other valid formats are +m, where m is the "
"number of minutes to wait until shutting down and hh:mm "
"which specifies the time on the 24hr clock.\n"
"\n"
"Logged in users are warned by a message sent to their "
"terminal, you may include an optional MESSAGE included "
"with this. Messages can be sent without actually "
"bringing the system down by using the -k option.\n"
"\n"
"If TIME is given, the command will remain in the "
"foreground until the shutdown occurs. It can be cancelled "
"by Control-C, or by another user using the -c option.\n"
"\n"
"The system is brought down into maintenance (single-user) "
"mode by default, you can change this with either the -r or "
"-h option which specify a reboot or system halt "
"respectively. The -h option can be further modified with "
"-H or -P to specify whether to halt the system, or to "
"power it off afterwards. The default is left up to the "
"shutdown scripts."));
args = nih_option_parser (NULL, argc, argv, options, FALSE);
if (! args)
exit (1);
/* If the runlevel wasn't given explicitly, set it to 1 so we go
* down into single-user mode.
*/
if (! runlevel) {
runlevel = '1';
init_halt = NULL;
}
/* When may be specified with -g, or must be first argument */
if (! (cancel || when || args[0])) {
fprintf (stderr, _("%s: time expected\n"), program_name);
nih_main_suggest_help ();
exit (1);
} else if (! (cancel || when)) {
when = NIH_MUST (nih_strdup (NULL, args[0]));
arg = 1;
} else {
arg = 0;
}
/* Parse the time argument */
if (when) {
if (! strcmp (when, "now")) {
/* "now" means, err, now */
delay = 0;
} else if (strchr (when, ':')) {
/* Clock time */
long hours, mins;
char *endptr;
struct tm *tm;
time_t now;
hours = strtoul (when, &endptr, 10);
if ((*endptr != ':') || (hours < 0) || (hours > 23)) {
fprintf (stderr, _("%s: illegal hour value\n"),
program_name);
nih_main_suggest_help ();
exit (1);
}
mins = strtoul (endptr + 1, &endptr, 10);
if (*endptr || (mins < 0) || (mins > 59)) {
fprintf (stderr,
_("%s: illegal minute value\n"),
program_name);
nih_main_suggest_help ();
exit (1);
}
/* Subtract the current time to get the delay.
* Add a whole day if we go negative */
now = time (NULL);
tm = localtime (&now);
delay = (((hours * 60) + mins)
- ((tm->tm_hour * 60) + tm->tm_min));
if (delay < 0)
delay += 1440;
} else {
/* Delay in minutes */
char *endptr;
delay = strtoul (when, &endptr, 10);
if (*endptr || (delay < 0)) {
fprintf (stderr, _("%s: illegal time value\n"),
program_name);
nih_main_suggest_help ();
exit (1);
}
}
nih_free (when);
}
/* The rest of the arguments are a message.
* Really this should be just the next argument, but that's not
* how this has been traditionally done *sigh*
*/
message = NIH_MUST (nih_strdup (NULL, ""));
messagelen = 0;
for (; args[arg]; arg++) {
message = NIH_MUST (nih_realloc (
message, NULL,
messagelen + strlen(args[arg]) + 4));
strcat (message, args[arg]);
strcat (message, " ");
messagelen += strlen (args[arg]) + 1;
}
/* Terminate with \r\n */
if (messagelen)
strcat (message, "\r\n");
/* Check we're root, or setuid root */
if (setuid (geteuid ()) < 0)
nih_warn (_("Couldn't set uid."));
if (getuid ()) {
nih_fatal (_("Need to be root"));
exit (1);
}
/* Look for an existing pid file and deal with the existing
* process if there is one.
*/
pid = nih_main_read_pidfile ();
if (pid > 0) {
if (cancel) {
if (kill (pid, SIGINT) < 0) {
nih_error (_("Shutdown is not running"));
exit (1);
}
if (messagelen)
wall (message);
exit (0);
} else if (kill (pid, 0) == 0) {
nih_error (_("Another shutdown is already running"));
exit (1);
}
} else if (cancel) {
nih_error (_("Cannot find pid of running shutdown"));
exit (1);
}
/* Send an initial message */
msg = NIH_MUST (warning_message (message));
wall (msg);
if (warn_only)
exit (0);
/* Give us a sane environment */
if (chdir ("/") < 0)
nih_warn ("%s: %s", _("Unable to change directory"),
strerror (errno));
umask (022);
/* Shutdown now? */
if (! delay)
shutdown_now ();
/* Save our pid so we can be interrupted later */
if (nih_main_write_pidfile (getpid ()) < 0) {
NihError *err;
err = nih_error_get ();
nih_warn ("%s: %s: %s", nih_main_get_pidfile(),
_("Unable to write pid file"), err->message);
nih_free (err);
}
/* Ignore a whole bunch of signals */
nih_signal_set_ignore (SIGCHLD);
nih_signal_set_ignore (SIGHUP);
nih_signal_set_ignore (SIGTSTP);
nih_signal_set_ignore (SIGTTIN);
nih_signal_set_ignore (SIGTTOU);
/* Catch the usual quit signals */
nih_signal_set_handler (SIGINT, nih_signal_handler);
NIH_MUST (nih_signal_add_handler (NULL, SIGINT,
cancel_callback, NULL));
nih_signal_set_handler (SIGQUIT, nih_signal_handler);
NIH_MUST (nih_signal_add_handler (NULL, SIGQUIT,
cancel_callback, NULL));
nih_signal_set_handler (SIGTERM, nih_signal_handler);
NIH_MUST (nih_signal_add_handler (NULL, SIGTERM,
cancel_callback, NULL));
/* Call a timer every minute until we shutdown */
NIH_MUST (nih_timer_add_periodic (NULL, 60,
(NihTimerCb)timer_callback,
message));
/* Hang around */
nih_main_loop ();
return 0;
}
/**
* shutdown_now:
*
* Send a signal to init to shut down the machine.
*
* This does not return.
**/
static void
shutdown_now (void)
{
nih_local char **extra_env = NULL;
NihDBusError * dbus_err;
int exit_val = 0;
if (init_halt) {
char *e;
e = NIH_MUST (nih_sprintf (NULL, "INIT_HALT=%s", init_halt));
extra_env = NIH_MUST (nih_str_array_new (NULL));
NIH_MUST (nih_str_array_addp (&extra_env, NULL, NULL, e));
}
if (sysv_change_runlevel (runlevel, extra_env, NULL, NULL) < 0) {
dbus_err = (NihDBusError *)nih_error_get ();
if ((dbus_err->number != NIH_DBUS_ERROR)
|| strcmp (dbus_err->name, DBUS_ERROR_NO_SERVER)) {
nih_fatal ("%s", dbus_err->message);
nih_free (dbus_err);
exit (1);
}
nih_free (dbus_err);
/* Connection Refused means that init isn't running, this
* might mean we've just upgraded to upstart and haven't
* yet rebooted ... so try /dev/initctl
*/
sysvinit_shutdown ();
nih_fatal ("Unable to shutdown system");
exit_val = 1;
}
unlink (ETC_NOLOGIN);
nih_main_unlink_pidfile ();
exit (exit_val);
}
/**
* cancel_callback:
* @data: not used,
* @signal: signal caught.
*
* This callback is run whenever one of the "cancel running shutdown"
* signals is sent to us.
*
* This does not return.
**/
static void
cancel_callback (void *data,
NihSignal *signal)
{
nih_error (_("Shutdown cancelled"));
unlink (ETC_NOLOGIN);
nih_main_unlink_pidfile ();
exit (0);
}
/**
* timer_callback:
* @message: message to display.
*
* This callback is run every minute until we are ready to shutdown, it
* ensures regular warnings are sent to logged in users and handles
* preventing new logins. Once time is up, it handles shutting down.
*
* This will modify delay each time it is called.
**/
static void
timer_callback (const char *message)
{
nih_local char *msg = NULL;
int warn = FALSE;
delay--;
msg = NIH_MUST (warning_message (message));
/* Write /etc/nologin with less than 5 minutes remaining */
if (delay <= 5) {
FILE *nologin;
nologin = fopen (ETC_NOLOGIN, "w");
if (nologin) {
fputs (msg, nologin);
fclose (nologin);
}
}
/* Only warn at particular intervals */
if (delay < 10) {
warn = TRUE;
} else if (delay < 60) {
warn = (delay % 15 ? FALSE : TRUE);
} else if (delay < 180) {
warn = (delay % 30 ? FALSE : TRUE);
} else {
warn = (delay % 60 ? FALSE : TRUE);
}
if (warn)
wall (msg);
/* Shutdown the machine at zero */
if (! delay)
shutdown_now ();
}
/**
* warning_message:
* @message: user message.
*
* Prefixes the message with details about how long until the shutdown
* completes.
*
* Returns: newly allocated string.
**/
static char *
warning_message (const char *message)
{
nih_local char *banner = NULL;
char * msg;
nih_assert (message != NULL);
if ((runlevel == '0')
&& init_halt && (! strcmp (init_halt, "POWEROFF"))) {
if (delay) {
banner = nih_sprintf (
NULL, _n("The system is going down for "
"power off in %d minute!",
"The system is going down for "
"power off in %d minutes!",
delay), delay);
} else {
banner = nih_strdup (
NULL, _("The system is going down for "
"power off NOW!"));
}
} else if (runlevel == '0') {
if (delay) {
banner = nih_sprintf (
NULL, _n("The system is going down for "
"halt in %d minute!",
"The system is going down for "
"halt in %d minutes!",
delay), delay);
} else {
banner = nih_strdup (
NULL, _("The system is going down for "
"halt NOW!"));
}
} else if (runlevel == '1') {
if (delay) {
banner = nih_sprintf (
NULL, _n("The system is going down for "
"maintenance in %d minute!",
"The system is going down for "
"maintenance in %d minutes!",
delay), delay);
} else {
banner = nih_strdup (
NULL, _("The system is going down for "
"maintenance NOW!"));
}
} else if (runlevel == '6') {
if (delay) {
banner = nih_sprintf (
NULL, _n("The system is going down for "
"reboot in %d minute!",
"The system is going down for "
"reboot in %d minutes!",
delay), delay);
} else {
banner = nih_strdup (
NULL, _("The system is going down for "
"reboot NOW!"));
}
}
if (! banner)
return NULL;
msg = nih_sprintf (NULL, "\r%s\r\n%s", banner, message);
return msg;
}
/**
* alarm_handler:
* @signum: signal called.
*
* Empty function used to cause the ALRM signal to break a syscall.
**/
static void
alarm_handler (int signum)
{
}
/**
* wall:
* @message: message to send.
*
* Send a message to all logged in users; based largely on the code from
* bsdutils. This is done in a child process to stop anything blocking.
**/
static void
wall (const char *message)
{
struct sigaction act;
struct utmpx * ent;
pid_t pid;
time_t now;
struct tm * tm;
char * user;
char * tty;
char hostname[MAXHOSTNAMELEN];
char * banner1;
char * banner2;
pid = fork ();
if (pid < 0) {
nih_warn (_("Unable to fork child-process to warn users: %s"),
strerror (errno));
return;
} else if (pid > 0) {
return;
}
/* Break syscalls with SIGALRM */
act.sa_handler = alarm_handler;
act.sa_flags = 0;
sigemptyset (&act.sa_mask);
sigaction (SIGALRM, &act, NULL);
/* Get username for banner */
user = getlogin ();
if (! user) {
struct passwd *pw;
pw = getpwuid (getuid ());
if (pw)
user = pw->pw_name;
}
if (! user) {
if (getuid ()) {
user = NIH_MUST (nih_sprintf (NULL, "uid %d",
getuid ()));
} else {
user = "root";
}
}
/* Get hostname for banner */
gethostname (hostname, sizeof (hostname));
/* Get terminal for banner */
tty = ttyname (0);
if (! tty)
tty = "unknown";
/* Get time */
now = time (NULL);
tm = localtime (&now);
/* Construct banner */
banner1 = nih_sprintf (NULL, _("Broadcast message from %s@%s"),
user, hostname);
banner2 = nih_sprintf (NULL, _("(%s) at %d:%02d ..."),
tty, tm->tm_hour, tm->tm_min);
/* Iterate entries in the utmp file */
setutxent ();
while ((ent = getutxent ()) != NULL) {
char dev[PATH_MAX + 1];
int fd;
/* Ignore entries without a name, or not a user process */
if ((ent->ut_type != USER_PROCESS)
|| (! strlen (ent->ut_user)))
continue;
/* Construct the device path */
if (strncmp (ent->ut_line, DEV "/", 5)) {
snprintf (dev, sizeof (dev),
"%s/%s", DEV, ent->ut_line);
} else {
snprintf (dev, sizeof (dev), "%s", ent->ut_line);
}
alarm (2);
fd = open (dev, O_WRONLY | O_NDELAY | O_NOCTTY);
if ((fd >= 0) && isatty (fd)) {
FILE *term;
term = fdopen (fd, "w");
if (term) {
fprintf (term, "\007\r\n%s\r\n\t%s\r\n\r\n",
banner1, banner2);
fputs (message, term);
fflush (term);
fclose (term);
}
}
alarm (0);
}
endutxent ();
nih_free (banner1);
nih_free (banner2);
exit (0);
}
/**
* struct request:
*
* This is the structure passed across /dev/initctl.
**/
struct request {
int magic;
int cmd;
int runlevel;
int sleeptime;
char data[368];
};
/**
* sysvinit_shutdown:
*
* Attempt to shutdown a running sysvinit /sbin/init using its /dev/initctl
* socket.
**/
static void
sysvinit_shutdown (void)
{
struct sigaction act;
struct request request;
int fd;
/* Fill in the magic values */
memset (&request, 0, sizeof (request));
request.magic = 0x03091969;
request.sleeptime = 5;
request.cmd = 1;
/* Select a runlevel based on the event name */
request.runlevel = runlevel;
/* Break syscalls with SIGALRM */
act.sa_handler = alarm_handler;
act.sa_flags = 0;
sigemptyset (&act.sa_mask);
sigaction (SIGALRM, &act, NULL);
alarm (3);
/* Try and open /run/initctl */
fd = open (RUN_INITCTL, O_WRONLY | O_NDELAY | O_NOCTTY);
if (fd < 0) {
/* Fall back to /dev/initctl */
fd = open (DEV_INITCTL, O_WRONLY | O_NDELAY | O_NOCTTY);
}
if (fd >= 0) {
if (write (fd, &request, sizeof (request)) == sizeof (request))
exit (0);
close (fd);
}
alarm (0);
}
|