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