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