Allow user to choose action when boot fails.
[oweals/dinit.git] / src / dinit.cc
1 #include <iostream>
2 #include <fstream>
3 #include <list>
4 #include <cstring>
5 #include <csignal>
6 #include <cstddef>
7 #include <cstdlib>
8
9 #include <sys/types.h>
10 #include <sys/stat.h>
11 #include <sys/un.h>
12 #include <sys/socket.h>
13 #include <unistd.h>
14 #include <fcntl.h>
15 #include <pwd.h>
16 #include <termios.h>
17 #ifdef __linux__
18 #include <sys/prctl.h>
19 #include <sys/klog.h>
20 #include <sys/reboot.h>
21 #endif
22 #if defined(__FreeBSD__) || defined(__DragonFly__)
23 #include <sys/procctl.h>
24 #endif
25
26 #include "dinit.h"
27 #include "dasynq.h"
28 #include "service.h"
29 #include "control.h"
30 #include "dinit-log.h"
31 #include "dinit-socket.h"
32 #include "static-string.h"
33 #include "dinit-utmp.h"
34
35 #include "mconfig.h"
36
37 /*
38  * When running as the system init process, Dinit processes the following signals:
39  *
40  * SIGTERM - roll back services and then fork/exec /sbin/halt
41  * SIGINT - roll back services and then fork/exec /sbin/reboot
42  * SIGQUIT - exec() /sbin/shutdown without rolling back services
43  *
44  * It's an open question about whether Dinit should roll back services *before*
45  * running halt/reboot, since those commands should prompt rollback of services
46  * anyway. But it seems safe to do so, and it means the user can at least stop
47  * services even if the halt/reboot commands are unavailable for some reason.
48  */
49
50 using namespace cts;
51
52 using eventloop_t = dasynq::event_loop<dasynq::null_mutex>;
53
54 eventloop_t event_loop;
55
56 static void sigint_reboot_cb(eventloop_t &eloop) noexcept;
57 static void sigquit_cb(eventloop_t &eloop) noexcept;
58 static void sigterm_cb(eventloop_t &eloop) noexcept;
59 static void open_control_socket(bool report_ro_failure = true) noexcept;
60 static void close_control_socket() noexcept;
61 static void confirm_restart_boot() noexcept;
62 static void read_env_file(const char *);
63
64 static void control_socket_cb(eventloop_t *loop, int fd);
65
66
67 // Variables
68
69 static dirload_service_set *services;
70
71 static bool am_pid_one = false;     // true if we are PID 1
72 static bool am_system_init = false; // true if we are the system init process
73
74 static bool did_log_boot = false;
75 static bool control_socket_open = false;
76 static bool external_log_open = false;
77 int active_control_conns = 0;
78
79 // Control socket path. We maintain a string (control_socket_str) in case we need
80 // to allocate storage, but control_socket_path is the authoritative value.
81 static const char *control_socket_path = SYSCONTROLSOCKET;
82 static std::string control_socket_str;
83
84 static const char *env_file_path = "/etc/dinit/environment";
85
86 static const char *log_path = "/dev/log";
87 static bool log_is_syslog = true; // if false, log is a file
88
89 static const char *user_home_path = nullptr;
90
91 // Set to true (when console_input_watcher is active) if console input becomes available
92 static bool console_input_ready = false;
93
94 // Get user home (and set user_home_path). (The return may become invalid after
95 // changing the evironment (HOME variable) or using the getpwuid() function).
96 static const char * get_user_home()
97 {
98     if (user_home_path == nullptr) {
99         user_home_path = getenv("HOME");
100         if (user_home_path == nullptr) {
101             struct passwd * pwuid_p = getpwuid(getuid());
102             if (pwuid_p != nullptr) {
103                 user_home_path = pwuid_p->pw_dir;
104             }
105         }
106     }
107     return user_home_path;
108 }
109
110
111 namespace {
112     // Event-loop handler for a signal, which just delegates to a function (pointer).
113     class callback_signal_handler : public eventloop_t::signal_watcher_impl<callback_signal_handler>
114     {
115         using rearm = dasynq::rearm;
116
117         public:
118         typedef void (*cb_func_t)(eventloop_t &);
119         
120         private:
121         cb_func_t cb_func;
122         
123         public:
124         callback_signal_handler() : cb_func(nullptr) { }
125         callback_signal_handler(cb_func_t pcb_func) :  cb_func(pcb_func) { }
126         
127         void set_cb_func(cb_func_t cb_func)
128         {
129             this->cb_func = cb_func;
130         }
131         
132         rearm received(eventloop_t &eloop, int signo, siginfo_p siginfo)
133         {
134             cb_func(eloop);
135             return rearm::REARM;
136         }
137     };
138
139     // Event-loop handler for when a connection is made to the control socket.
140     class control_socket_watcher : public eventloop_t::fd_watcher_impl<control_socket_watcher>
141     {
142         using rearm = dasynq::rearm;
143
144         public:
145         rearm fd_event(eventloop_t &loop, int fd, int flags) noexcept
146         {
147             control_socket_cb(&loop, fd);
148             return rearm::REARM;
149         }
150     };
151
152     class console_input_watcher : public eventloop_t::fd_watcher_impl<console_input_watcher>
153     {
154         using rearm = dasynq::rearm;
155
156         public:
157         rearm fd_event(eventloop_t &loop, int fd, int flags) noexcept
158         {
159             control_socket_cb(&loop, fd); // DAV
160             return rearm::REARM;
161         }
162     };
163
164     // Simple timer used to limit the amount of time waiting for the log flush to complete (at shutdown)
165     class log_flush_timer_t : public eventloop_t::timer_impl<log_flush_timer_t>
166     {
167         using rearm = dasynq::rearm;
168
169         bool expired = false;
170
171         public:
172         rearm timer_expiry(eventloop_t &, int expiry_count)
173         {
174             expired = true;
175             return rearm::DISARM;
176         }
177
178         bool has_expired()
179         {
180             return expired;
181         }
182     };
183
184     control_socket_watcher control_socket_io;
185     console_input_watcher console_input_io;
186     log_flush_timer_t log_flush_timer;
187 }
188
189 int dinit_main(int argc, char **argv)
190 {
191     using namespace std;
192     
193     am_pid_one = (getpid() == 1);
194     am_system_init = (getuid() == 0);
195     const char * service_dir = nullptr;
196     bool service_dir_dynamic = false; // service_dir dynamically allocated?
197     const char * env_file = nullptr;
198     bool control_socket_path_set = false;
199     bool env_file_set = false;
200
201     // list of services to start
202     list<const char *> services_to_start;
203     
204     // Arguments, if given, specify a list of services to start.
205     // If we are running as init (PID=1), the Linux kernel gives us any command line arguments it was given
206     // but didn't recognize, including "single" (usually for "boot to single user mode" aka just start the
207     // shell). We can treat them as service names. In the worst case we can't find any of the named
208     // services, and so we'll start the "boot" service by default.
209     if (argc > 1) {
210         for (int i = 1; i < argc; i++) {
211             if (argv[i][0] == '-') {
212                 // An option...
213                 if (strcmp(argv[i], "--env-file") == 0 || strcmp(argv[i], "-e") == 0) {
214                     if (++i < argc) {
215                         env_file_set = true;
216                         env_file = argv[i];
217                     }
218                     else {
219                         cerr << "dinit: '--env-file' (-e) requires an argument" << endl;
220                     }
221                 }
222                 else if (strcmp(argv[i], "--services-dir") == 0 || strcmp(argv[i], "-d") == 0) {
223                     if (++i < argc) {
224                         service_dir = argv[i];
225                     }
226                     else {
227                         cerr << "dinit: '--services-dir' (-d) requires an argument" << endl;
228                         return 1;
229                     }
230                 }
231                 else if (strcmp(argv[i], "--system") == 0 || strcmp(argv[i], "-s") == 0) {
232                     am_system_init = true;
233                 }
234                 else if (strcmp(argv[i], "--user") == 0 || strcmp(argv[i], "-u") == 0) {
235                     am_system_init = false;
236                 }
237                 else if (strcmp(argv[i], "--socket-path") == 0 || strcmp(argv[i], "-p") == 0) {
238                     if (++i < argc) {
239                         control_socket_path = argv[i];
240                         control_socket_path_set = true;
241                     }
242                     else {
243                         cerr << "dinit: '--socket-path' (-p) requires an argument" << endl;
244                         return 1;
245                     }
246                 }
247                 else if (strcmp(argv[i], "--log-file") == 0 || strcmp(argv[i], "-l") == 0) {
248                     if (++i < argc) {
249                         log_path = argv[i];
250                         log_is_syslog = false;
251                     }
252                     else {
253                         cerr << "dinit: '--log-file' (-l) requires an argument" << endl;
254                         return 1;
255                     }
256                 }
257                 else if (strcmp(argv[i], "--help") == 0) {
258                     cout << "dinit, an init with dependency management\n"
259                             " --help                       display help\n"
260                             " --env-file <file>, -e <file>\n"
261                             "                              environment variable initialisation file\n"
262                             " --services-dir <dir>, -d <dir>\n"
263                             "                              set base directory for service description\n"
264                             "                              files (-d <dir>)\n"
265                             " --system, -s                 run as the system service manager\n"
266                             " --user, -u                   run as a user service manager\n"
267                             " --socket-path <path>, -p <path>\n"
268                             "                              path to control socket\n"
269                             " <service-name>               start service with name <service-name>\n";
270                     return 0;
271                 }
272                 else {
273                     // unrecognized
274                     if (! am_system_init) {
275                         cerr << "dinit: Unrecognized option: " << argv[i] << endl;
276                         return 1;
277                     }
278                 }
279             }
280             else {
281 #ifdef __linux__
282                 // LILO puts "auto" on the kernel command line for unattended boots; we'll filter it.
283                 if (! am_pid_one || strcmp(argv[i], "auto") != 0) {
284                     services_to_start.push_back(argv[i]);
285                 }
286 #else
287                 services_to_start.push_back(argv[i]);
288 #endif
289             }
290         }
291     }
292     
293     if (am_system_init) {
294         // setup STDIN, STDOUT, STDERR so that we can use them
295         int onefd = open("/dev/console", O_RDONLY, 0);
296         dup2(onefd, 0);
297         int twofd = open("/dev/console", O_RDWR, 0);
298         dup2(twofd, 1);
299         dup2(twofd, 2);
300         
301         if (onefd > 2) close(onefd);
302         if (twofd > 2) close(twofd);
303
304         if (! env_file_set) {
305             env_file = env_file_path;
306         }
307     }
308
309     /* Set up signal handlers etc */
310     /* SIG_CHILD is ignored by default: good */
311     sigset_t sigwait_set;
312     sigemptyset(&sigwait_set);
313     sigaddset(&sigwait_set, SIGCHLD);
314     sigaddset(&sigwait_set, SIGINT);
315     sigaddset(&sigwait_set, SIGTERM);
316     if (am_pid_one) sigaddset(&sigwait_set, SIGQUIT);
317     sigprocmask(SIG_BLOCK, &sigwait_set, NULL);
318
319     // Terminal access control signals - we block these so that dinit can't be
320     // suspended if it writes to the terminal after some other process has claimed
321     // ownership of it.
322     signal(SIGTSTP, SIG_IGN);
323     signal(SIGTTIN, SIG_IGN);
324     signal(SIGTTOU, SIG_IGN);
325     
326     signal(SIGPIPE, SIG_IGN);
327     
328     if (! am_system_init && ! control_socket_path_set) {
329         const char * userhome = get_user_home();
330         if (userhome != nullptr) {
331             control_socket_str = userhome;
332             control_socket_str += "/.dinitctl";
333             control_socket_path = control_socket_str.c_str();
334         }
335     }
336     
337     /* service directory name */
338     if (service_dir == nullptr && ! am_system_init) {
339         const char * userhome = get_user_home();
340         if (userhome != nullptr) {
341             const char * user_home = get_user_home();
342             size_t user_home_len = strlen(user_home);
343             size_t dinit_d_len = strlen("/dinit.d");
344             size_t full_len = user_home_len + dinit_d_len + 1;
345             char *service_dir_w = new char[full_len];
346             std::memcpy(service_dir_w, user_home, user_home_len);
347             std::memcpy(service_dir_w + user_home_len, "/dinit.d", dinit_d_len);
348             service_dir_w[full_len - 1] = 0;
349
350             service_dir = service_dir_w;
351             service_dir_dynamic = true;
352         }
353     }
354     
355     if (services_to_start.empty()) {
356         services_to_start.push_back("boot");
357     }
358
359     // Set up signal handlers
360     callback_signal_handler sigterm_watcher {sigterm_cb};
361     callback_signal_handler sigint_watcher;
362     callback_signal_handler sigquit_watcher;
363
364     if (am_pid_one) {
365         sigint_watcher.set_cb_func(sigint_reboot_cb);
366         sigquit_watcher.set_cb_func(sigquit_cb);
367     }
368     else {
369         sigint_watcher.set_cb_func(sigterm_cb);
370     }
371
372     sigint_watcher.add_watch(event_loop, SIGINT);
373     sigterm_watcher.add_watch(event_loop, SIGTERM);
374     console_input_io.add_watch(event_loop, STDIN_FILENO, dasynq::IN_EVENTS, false);
375     
376     if (am_pid_one) {
377         // PID 1: SIGQUIT exec's shutdown
378         sigquit_watcher.add_watch(event_loop, SIGQUIT);
379         // As a user process, we instead just let SIGQUIT perform the default action.
380     }
381
382     // Try to open control socket (may fail due to readonly filesystem)
383     open_control_socket(false);
384     
385 #ifdef __linux__
386     if (am_system_init) {
387         // Disable non-critical kernel output to console
388         klogctl(6 /* SYSLOG_ACTION_CONSOLE_OFF */, nullptr, 0);
389         // Make ctrl+alt+del combination send SIGINT to PID 1 (this process)
390         reboot(RB_DISABLE_CAD);
391     }
392
393     // Mark ourselves as a subreaper. This means that if a process we start double-forks, the
394     // orphaned child will re-parent to us rather than to PID 1 (although that could be us too).
395     prctl(PR_SET_CHILD_SUBREAPER, 1);
396 #elif defined(__FreeBSD__) || defined(__DragonFly__)
397     // Documentation (man page) for this kind of sucks. PROC_REAP_ACQUIRE "acquires the reaper status for
398     // the current process" but does that mean the first two arguments still need valid values to be
399     // supplied? We'll play it safe and explicitly target our own process:
400     procctl(P_PID, getpid(), PROC_REAP_ACQUIRE, NULL);
401 #endif
402     
403     log_flush_timer.add_timer(event_loop, dasynq::clock_type::MONOTONIC);
404
405     bool add_all_service_dirs = false;
406     if (service_dir == nullptr) {
407         service_dir = "/etc/dinit.d";
408         add_all_service_dirs = true;
409     }
410
411     /* start requested services */
412     services = new dirload_service_set(service_dir, service_dir_dynamic);
413     if (add_all_service_dirs) {
414         services->add_service_dir("/usr/local/lib/dinit.d", false);
415         services->add_service_dir("/lib/dinit.d", false);
416     }
417     
418     init_log(services, log_is_syslog);
419     if (am_system_init) {
420         log(loglevel_t::INFO, false, "starting system");
421     }
422     
423     // Only try to set up the external log now if we aren't the system init. (If we are the
424     // system init, wait until the log service starts).
425     if (! am_system_init) setup_external_log();
426
427     if (env_file != nullptr) {
428         read_env_file(env_file);
429     }
430
431     for (auto svc : services_to_start) {
432         try {
433             services->start_service(svc);
434             // Note in general if we fail to start a service we don't need any special error handling,
435             // since we either leave other services running or, if it was the only service, then no
436             // services will be running and we will process normally (reboot if system process,
437             // exit if user process).
438         }
439         catch (service_not_found &snf) {
440             log(loglevel_t::ERROR, snf.service_name, ": Could not find service description.");
441         }
442         catch (service_load_exc &sle) {
443             log(loglevel_t::ERROR, sle.service_name, ": ", sle.exc_description);
444         }
445         catch (std::bad_alloc &badalloce) {
446             log(loglevel_t::ERROR, "Out of memory when trying to start service: ", svc, ".");
447             break;
448         }
449     }
450     
451     run_event_loop:
452     
453     // Process events until all services have terminated.
454     while (services->count_active_services() != 0) {
455         event_loop.run();
456     }
457
458     shutdown_type_t shutdown_type = services->get_shutdown_type();
459     if (shutdown_type == shutdown_type_t::REMAIN) {
460         goto run_event_loop;
461     }
462     
463     if (am_pid_one) {
464         log_msg_begin(loglevel_t::INFO, "No more active services.");
465         
466         if (shutdown_type == shutdown_type_t::REBOOT) {
467             log_msg_end(" Will reboot.");
468         }
469         else if (shutdown_type == shutdown_type_t::HALT) {
470             log_msg_end(" Will halt.");
471         }
472         else if (shutdown_type == shutdown_type_t::POWEROFF) {
473             log_msg_end(" Will power down.");
474         }
475     }
476     
477     log_flush_timer.arm_timer_rel(event_loop, timespec{5,0}); // 5 seconds
478     while (! is_log_flushed() && ! log_flush_timer.has_expired()) {
479         event_loop.run();
480     }
481     
482     close_control_socket();
483     
484     if (am_pid_one) {
485         if (shutdown_type == shutdown_type_t::NONE) {
486             // Services all stopped but there was no shutdown issued. Inform user, wait for ack, and
487             // re-start boot sequence.
488             sync(); // Sync to minimise data loss if user elects to power off / hard reset
489             confirm_restart_boot();
490             if (services->count_active_services() != 0) {
491                 // Recovery service started
492                 goto run_event_loop;
493             }
494             shutdown_type = services->get_shutdown_type();
495             if (shutdown_type == shutdown_type_t::NONE) {
496                 try {
497                     services->start_service("boot");
498                     goto run_event_loop; // yes, the "evil" goto
499                 }
500                 catch (...) {
501                     // Now what do we do? try to reboot, but wait for user ack to avoid boot loop.
502                     log(loglevel_t::ERROR, "Could not start 'boot' service. Will attempt reboot.");
503                     shutdown_type = shutdown_type_t::REBOOT;
504                 }
505             }
506         }
507         
508         const char * cmd_arg;
509         if (shutdown_type == shutdown_type_t::HALT) {
510             cmd_arg = "-h";
511         }
512         else if (shutdown_type == shutdown_type_t::REBOOT) {
513             cmd_arg = "-r";
514         }
515         else {
516             // power off.
517             cmd_arg = "-p";
518         }
519         
520         // Fork and execute dinit-reboot.
521         constexpr auto shutdown_exec = literal(SBINDIR) + "/shutdown";
522         execl(shutdown_exec.c_str(), shutdown_exec.c_str(), "--system", cmd_arg, nullptr);
523         log(loglevel_t::ERROR, (literal("Could not execute ") + SBINDIR + "/shutdown: ").c_str(),
524                 strerror(errno));
525         
526         // PID 1 must not actually exit, although we should never reach this point:
527         while (true) {
528             event_loop.run();
529         }
530     }
531     else if (shutdown_type == shutdown_type_t::REBOOT) {
532         // Non-system-process. If we got SIGINT, let's die due to it:
533         sigset_t sigwait_set_int;
534         sigemptyset(&sigwait_set_int);
535         sigaddset(&sigwait_set_int, SIGINT);
536         raise(SIGINT);
537         sigprocmask(SIG_UNBLOCK, &sigwait_set_int, NULL);
538     }
539     
540     return 0;
541 }
542
543 // Log a parse error when reading the environment file.
544 static void log_bad_env(int linenum)
545 {
546     log(loglevel_t::ERROR, "invalid environment variable setting in environment file (line ", linenum, ")");
547 }
548
549 // Read and set environment variables from a file.
550 static void read_env_file(const char *env_file_path)
551 {
552     // Note that we can't use the log in this function; it hasn't been initialised yet.
553
554     std::ifstream env_file(env_file_path);
555     if (! env_file) return;
556
557     env_file.exceptions(std::ios::badbit);
558
559     auto &clocale = std::locale::classic();
560     std::string line;
561     int linenum = 0;
562
563     while (std::getline(env_file, line)) {
564         linenum++;
565         auto lpos = line.begin();
566         auto lend = line.end();
567         while (lpos != lend && std::isspace(*lpos, clocale)) {
568             ++lpos;
569         }
570
571         if (lpos != lend) {
572             if (*lpos != '#') {
573                 if (*lpos == '=') {
574                     log_bad_env(linenum);
575                     continue;
576                 }
577                 auto name_begin = lpos++;
578                 // skip until '=' or whitespace:
579                 while (lpos != lend && *lpos != '=' && ! std::isspace(*lpos, clocale)) ++lpos;
580                 auto name_end = lpos;
581                 //  skip whitespace:
582                 while (lpos != lend && std::isspace(*lpos, clocale)) ++lpos;
583                 if (lpos == lend) {
584                     log_bad_env(linenum);
585                     continue;
586                 }
587
588                 ++lpos;
589                 auto val_begin = lpos;
590                 while (lpos != lend && *lpos != '\n') ++lpos;
591                 auto val_end = lpos;
592
593                 std::string name = line.substr(name_begin - line.begin(), name_end - name_begin);
594                 std::string value = line.substr(val_begin - line.begin(), val_end - val_begin);
595                 if (setenv(name.c_str(), value.c_str(), true) == -1) {
596                     throw std::system_error(errno, std::system_category());
597                 }
598             }
599         }
600     }
601 }
602
603 // Get user confirmation before proceeding with restarting boot sequence.
604 // Returns after confirmation, possibly with shutdown type altered.
605 static void confirm_restart_boot() noexcept
606 {
607     // Bypass log; we want to make certain the message is seen:
608     std::cout << "All services have stopped with no shutdown issued; boot failure?\n";
609
610     // Drain input, set non-canonical input mode (receive characters as they are typed)
611     struct termios term_attr;
612     if (tcgetattr(STDIN_FILENO, &term_attr) != 0) {
613         // Not a terminal?
614         std::cout << "Halting." << std::endl;
615         services->stop_all_services(shutdown_type_t::HALT);
616         return;
617     }
618     term_attr.c_lflag &= ~ICANON;
619     tcsetattr(STDIN_FILENO, TCSAFLUSH, &term_attr);
620
621     // Set non-blocking mode
622     int origFlags = fcntl(STDIN_FILENO, F_GETFL);
623     fcntl(STDIN_FILENO, F_SETFL, origFlags | O_NONBLOCK);
624
625     do_prompt:
626     std::cout << "Please choose: (r)eboot, r(e)covery, re(s)tart boot sequence, (p)ower off?" << std::endl;
627
628     console_input_io.set_enabled(event_loop, true);
629     do {
630         event_loop.run();
631     } while (! console_input_ready && services->get_shutdown_type() == shutdown_type_t::NONE);
632     console_input_io.set_enabled(event_loop, false);
633
634     // We either have input, or shutdown type has been set, or both.
635     if (console_input_ready) {
636         char buf[1];
637         int r = read(STDIN_FILENO, buf, 1);  // read a single character, to make sure we wait for input
638         if (r == 1) {
639             if (buf[0] == 'r' || buf[0] == 'R') {
640                 services->stop_all_services(shutdown_type_t::REBOOT);
641             }
642             else if (buf[0] == 'e' || buf[0] == 'E') {
643                 try {
644                     services->start_service("recovery");
645                 }
646                 catch (...) {
647                     std::cout << "Unable to start recovery service.\n";
648                     goto do_prompt;
649                 }
650             }
651             else if (buf[0] == 's' || buf[0] == 'S') {
652                 // nothing - leave no shutdown type
653             }
654             else if (buf[0] == 'p' || buf[0] == 'P') {
655                 services->stop_all_services(shutdown_type_t::POWEROFF);
656             }
657             else {
658                 goto do_prompt;
659             }
660         }
661         tcflush(STDIN_FILENO, TCIFLUSH); // discard the rest of input
662         console_input_ready = false;
663     }
664
665     term_attr.c_lflag |= ICANON;
666     tcsetattr(STDIN_FILENO, TCSANOW, &term_attr);
667     fcntl(STDIN_FILENO, F_SETFL, origFlags);
668 }
669
670 // Callback for control socket
671 static void control_socket_cb(eventloop_t *loop, int sockfd)
672 {
673     // Considered keeping a limit the number of active connections, however, there doesn't
674     // seem much to be gained from that. Only root can create connections and not being
675     // able to establish a control connection is as much a denial-of-service as is not being
676     // able to start a service due to lack of fd's.
677
678     // Accept a connection
679     int newfd = dinit_accept4(sockfd, nullptr, nullptr, SOCK_NONBLOCK | SOCK_CLOEXEC);
680
681     if (newfd != -1) {
682         try {
683             new control_conn_t(*loop, services, newfd);  // will delete itself when it's finished
684         }
685         catch (std::exception &exc) {
686             log(loglevel_t::ERROR, "Accepting control connection: ", exc.what());
687             close(newfd);
688         }
689     }
690 }
691
692 // Callback when the root filesystem is read/write:
693 void rootfs_is_rw() noexcept
694 {
695     open_control_socket(true);
696     if (! did_log_boot) {
697         did_log_boot = log_boot();
698     }
699 }
700
701 // Open/create the control socket, normally /dev/dinitctl, used to allow client programs to connect
702 // and issue service orders and shutdown commands etc. This can safely be called multiple times;
703 // once the socket has been successfully opened, further calls have no effect.
704 static void open_control_socket(bool report_ro_failure) noexcept
705 {
706     if (! control_socket_open) {
707         const char * saddrname = control_socket_path;
708         size_t saddrname_len = strlen(saddrname);
709         uint sockaddr_size = offsetof(struct sockaddr_un, sun_path) + saddrname_len + 1;
710         
711         struct sockaddr_un * name = static_cast<sockaddr_un *>(malloc(sockaddr_size));
712         if (name == nullptr) {
713             log(loglevel_t::ERROR, "Opening control socket: out of memory");
714             return;
715         }
716
717         if (am_system_init) {
718             // Unlink any stale control socket file, but only if we are system init, since otherwise
719             // the 'stale' file may not be stale at all:
720             unlink(saddrname);
721         }
722
723         name->sun_family = AF_UNIX;
724         memcpy(name->sun_path, saddrname, saddrname_len + 1);
725
726         int sockfd = dinit_socket(AF_UNIX, SOCK_STREAM, 0, SOCK_NONBLOCK | SOCK_CLOEXEC);
727         if (sockfd == -1) {
728             log(loglevel_t::ERROR, "Error creating control socket: ", strerror(errno));
729             free(name);
730             return;
731         }
732
733         if (bind(sockfd, (struct sockaddr *) name, sockaddr_size) == -1) {
734             if (errno != EROFS || report_ro_failure) {
735                 log(loglevel_t::ERROR, "Error binding control socket: ", strerror(errno));
736             }
737             close(sockfd);
738             free(name);
739             return;
740         }
741         
742         free(name);
743
744         // No connections can be made until we listen, so it is fine to change the permissions now
745         // (and anyway there is no way to atomically create the socket and set permissions):
746         if (chmod(saddrname, S_IRUSR | S_IWUSR) == -1) {
747             log(loglevel_t::ERROR, "Error setting control socket permissions: ", strerror(errno));
748             close(sockfd);
749             return;
750         }
751
752         if (listen(sockfd, 10) == -1) {
753             log(loglevel_t::ERROR, "Error listening on control socket: ", strerror(errno));
754             close(sockfd);
755             return;
756         }
757
758         try {
759             control_socket_io.add_watch(event_loop, sockfd, dasynq::IN_EVENTS);
760             control_socket_open = true;
761         }
762         catch (std::exception &e)
763         {
764             log(loglevel_t::ERROR, "Could not setup I/O on control socket: ", e.what());
765             close(sockfd);
766         }
767     }
768 }
769
770 static void close_control_socket() noexcept
771 {
772     if (control_socket_open) {
773         int fd = control_socket_io.get_watched_fd();
774         control_socket_io.deregister(event_loop);
775         close(fd);
776         
777         // Unlink the socket:
778         unlink(control_socket_path);
779
780         control_socket_open = false;
781     }
782 }
783
784 void setup_external_log() noexcept
785 {
786     if (! external_log_open) {
787         if (log_is_syslog) {
788             const char * saddrname = log_path;
789             size_t saddrname_len = strlen(saddrname);
790             uint sockaddr_size = offsetof(struct sockaddr_un, sun_path) + saddrname_len + 1;
791
792             struct sockaddr_un * name = static_cast<sockaddr_un *>(malloc(sockaddr_size));
793             if (name == nullptr) {
794                 log(loglevel_t::ERROR, "Connecting to log socket: out of memory");
795                 return;
796             }
797
798             name->sun_family = AF_UNIX;
799             memcpy(name->sun_path, saddrname, saddrname_len + 1);
800
801             int sockfd = dinit_socket(AF_UNIX, SOCK_DGRAM, 0, SOCK_NONBLOCK | SOCK_CLOEXEC);
802             if (sockfd == -1) {
803                 log(loglevel_t::ERROR, "Error creating log socket: ", strerror(errno));
804                 free(name);
805                 return;
806             }
807
808             if (connect(sockfd, (struct sockaddr *) name, sockaddr_size) == 0 || errno == EINPROGRESS) {
809                 // For EINPROGRESS, connection is still being established; however, we can select on
810                 // the file descriptor so we will be notified when it's ready. In other words we can
811                 // basically use it anyway.
812                 try {
813                     setup_main_log(sockfd);
814                     external_log_open = true;
815                 }
816                 catch (std::exception &e) {
817                     log(loglevel_t::ERROR, "Setting up log failed: ", e.what());
818                     close(sockfd);
819                 }
820             }
821             else {
822                 // Note if connect fails, we haven't warned at all, because the syslog server might not
823                 // have started yet.
824                 close(sockfd);
825             }
826
827             free(name);
828         }
829         else {
830             // log to file:
831             int log_fd = open(log_path, O_WRONLY | O_CREAT | O_APPEND | O_NONBLOCK | O_CLOEXEC, 0644);
832             if (log_fd >= 0) {
833                 try {
834                     setup_main_log(log_fd);
835                     external_log_open = true;
836                 }
837                 catch (std::exception &e) {
838                     log(loglevel_t::ERROR, "Setting up log failed: ", e.what());
839                     close(log_fd);
840                 }
841             }
842             else {
843                 // log failure to log? It makes more sense than first appears, because we also log
844                 // to console:
845                 log(loglevel_t::ERROR, "Setting up log failed: ", strerror(errno));
846             }
847         }
848     }
849 }
850
851 /* handle SIGINT signal (generated by Linux kernel when ctrl+alt+del pressed) */
852 static void sigint_reboot_cb(eventloop_t &eloop) noexcept
853 {
854     services->stop_all_services(shutdown_type_t::REBOOT);
855 }
856
857 /* handle SIGQUIT (if we are system init) */
858 static void sigquit_cb(eventloop_t &eloop) noexcept
859 {
860     // This performs an immediate shutdown, without service rollback.
861     close_control_socket();
862     constexpr auto shutdown_exec = literal(SBINDIR) + "/shutdown";
863     execl(shutdown_exec.c_str(), shutdown_exec.c_str(), "--system", (char *) 0);
864     log(loglevel_t::ERROR, literal("Error executing ") + SBINDIR + "/sbin/shutdown: ", strerror(errno));
865     sync(); // since a hard poweroff might be required at this point...
866 }
867
868 /* handle SIGTERM/SIGQUIT(non-system-daemon) - stop all services and shut down */
869 static void sigterm_cb(eventloop_t &eloop) noexcept
870 {
871     services->stop_all_services();
872 }