12 #include <sys/socket.h>
17 #include <sys/prctl.h>
19 #include <sys/reboot.h>
21 #if defined(__FreeBSD__) || defined(__DragonFly__)
22 #include <sys/procctl.h>
29 #include "dinit-log.h"
30 #include "dinit-socket.h"
31 #include "static-string.h"
36 * When running as the system init process, Dinit processes the following signals:
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
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.
50 using eventloop_t = dasynq::event_loop<dasynq::null_mutex>;
52 eventloop_t event_loop;
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 *);
61 static void control_socket_cb(eventloop_t *loop, int fd);
66 static dirload_service_set *services;
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
71 static bool control_socket_open = false;
72 static bool external_log_open = false;
73 int active_control_conns = 0;
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;
80 static const char *env_file_path = "/etc/dinit/environment";
82 static const char *log_path = "/dev/log";
83 static bool log_is_syslog = true; // if false, log is a file
85 static const char *user_home_path = nullptr;
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()
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;
101 return user_home_path;
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>
109 using rearm = dasynq::rearm;
112 typedef void (*cb_func_t)(eventloop_t &);
118 callback_signal_handler() : cb_func(nullptr) { }
119 callback_signal_handler(cb_func_t pcb_func) : cb_func(pcb_func) { }
121 void set_cb_func(cb_func_t cb_func)
123 this->cb_func = cb_func;
126 rearm received(eventloop_t &eloop, int signo, siginfo_p siginfo)
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>
136 using rearm = dasynq::rearm;
139 rearm fd_event(eventloop_t &loop, int fd, int flags) noexcept
141 control_socket_cb(&loop, fd);
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>
149 using rearm = dasynq::rearm;
151 bool expired = false;
154 rearm timer_expiry(eventloop_t &, int expiry_count)
157 return rearm::DISARM;
166 control_socket_watcher control_socket_io;
167 log_flush_timer_t log_flush_timer;
170 int dinit_main(int argc, char **argv)
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;
182 // list of services to start
183 list<const char *> services_to_start;
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.
191 for (int i = 1; i < argc; i++) {
192 if (argv[i][0] == '-') {
194 if (strcmp(argv[i], "--env-file") == 0 || strcmp(argv[i], "-e") == 0) {
200 cerr << "dinit: '--env-file' (-e) requires an argument" << endl;
203 else if (strcmp(argv[i], "--services-dir") == 0 || strcmp(argv[i], "-d") == 0) {
205 service_dir = argv[i];
208 cerr << "dinit: '--services-dir' (-d) requires an argument" << endl;
212 else if (strcmp(argv[i], "--system") == 0 || strcmp(argv[i], "-s") == 0) {
213 am_system_init = true;
215 else if (strcmp(argv[i], "--socket-path") == 0 || strcmp(argv[i], "-p") == 0) {
217 control_socket_path = argv[i];
218 control_socket_path_set = true;
221 cerr << "dinit: '--socket-path' (-p) requires an argument" << endl;
225 else if (strcmp(argv[i], "--log-file") == 0 || strcmp(argv[i], "-l") == 0) {
228 log_is_syslog = false;
231 cerr << "dinit: '--log-file' (-l) requires an argument" << endl;
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";
251 if (! am_system_init) {
252 cerr << "dinit: Unrecognized option: " << argv[i] << endl;
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]);
264 services_to_start.push_back(argv[i]);
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);
274 int twofd = open("/dev/console", O_RDWR, 0);
278 if (onefd > 2) close(onefd);
279 if (twofd > 2) close(twofd);
281 if (! env_file_set) {
282 env_file = env_file_path;
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);
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
299 signal(SIGTSTP, SIG_IGN);
300 signal(SIGTTIN, SIG_IGN);
301 signal(SIGTTOU, SIG_IGN);
303 signal(SIGPIPE, SIG_IGN);
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();
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;
327 service_dir = service_dir_w;
328 service_dir_dynamic = true;
332 if (services_to_start.empty()) {
333 services_to_start.push_back("boot");
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;
342 sigint_watcher.set_cb_func(sigint_reboot_cb);
343 sigquit_watcher.set_cb_func(sigquit_cb);
346 sigint_watcher.set_cb_func(sigterm_cb);
349 sigint_watcher.add_watch(event_loop, SIGINT);
350 sigterm_watcher.add_watch(event_loop, SIGTERM);
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.
358 // Try to open control socket (may fail due to readonly filesystem)
359 open_control_socket(false);
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);
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);
379 log_flush_timer.add_timer(event_loop, dasynq::clock_type::MONOTONIC);
381 bool add_all_service_dirs = false;
382 if (service_dir == nullptr) {
383 service_dir = "/etc/dinit.d";
384 add_all_service_dirs = true;
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);
394 init_log(services, log_is_syslog);
395 if (am_system_init) {
396 log(loglevel_t::INFO, false, "starting system");
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();
403 if (env_file != nullptr) {
404 read_env_file(env_file);
407 for (auto svc : services_to_start) {
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).
415 catch (service_not_found &snf) {
416 log(loglevel_t::ERROR, snf.serviceName, ": Could not find service description.");
418 catch (service_load_exc &sle) {
419 log(loglevel_t::ERROR, sle.serviceName, ": ", sle.excDescription);
421 catch (std::bad_alloc &badalloce) {
422 log(loglevel_t::ERROR, "Out of memory when trying to start service: ", svc, ".");
429 // Process events until all services have terminated.
430 while (services->count_active_services() != 0) {
434 shutdown_type_t shutdown_type = services->get_shutdown_type();
437 log_msg_begin(loglevel_t::INFO, "No more active services.");
439 if (shutdown_type == shutdown_type_t::REBOOT) {
440 log_msg_end(" Will reboot.");
442 else if (shutdown_type == shutdown_type_t::HALT) {
443 log_msg_end(" Will halt.");
445 else if (shutdown_type == shutdown_type_t::POWEROFF) {
446 log_msg_end(" Will power down.");
449 log_msg_end(" Re-initiating boot sequence.");
453 log_flush_timer.arm_timer_rel(event_loop, timespec{5,0}); // 5 seconds
454 while (! is_log_flushed() && ! log_flush_timer.has_expired()) {
458 close_control_socket();
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
466 services->start_service("boot");
467 goto event_loop; // yes, the "evil" goto
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;
477 const char * cmd_arg;
478 if (shutdown_type == shutdown_type_t::HALT) {
481 else if (shutdown_type == shutdown_type_t::REBOOT) {
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(),
495 // PID 1 must not actually exit, although we should never reach this point:
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);
506 sigprocmask(SIG_UNBLOCK, &sigwait_set, NULL);
512 // Log a parse error when reading the environment file.
513 static void log_bad_env(int linenum)
515 log(loglevel_t::ERROR, "invalid environment variable setting in environment file (line ", linenum, ")");
518 // Read and set environment variables from a file.
519 static void read_env_file(const char *env_file_path)
521 // Note that we can't use the log in this function; it hasn't been initialised yet.
523 std::ifstream env_file(env_file_path);
524 if (! env_file) return;
526 env_file.exceptions(std::ios::badbit);
528 auto &clocale = std::locale::classic();
532 while (std::getline(env_file, line)) {
534 auto lpos = line.begin();
535 auto lend = line.end();
536 while (lpos != lend && std::isspace(*lpos, clocale)) {
543 log_bad_env(linenum);
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;
551 while (lpos != lend && std::isspace(*lpos, clocale)) ++lpos;
553 log_bad_env(linenum);
558 auto val_begin = lpos;
559 while (lpos != lend && *lpos != '\n') ++lpos;
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());
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
576 std::cout << "Press Enter to continue." << std::endl;
578 read(STDIN_FILENO, buf, 1);
581 // Callback for control socket
582 static void control_socket_cb(eventloop_t *loop, int sockfd)
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.
589 // Accept a connection
590 int newfd = dinit_accept4(sockfd, nullptr, nullptr, SOCK_NONBLOCK | SOCK_CLOEXEC);
594 new control_conn_t(*loop, services, newfd); // will delete itself when it's finished
596 catch (std::exception &exc) {
597 log(loglevel_t::ERROR, "Accepting control connection: ", exc.what());
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
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;
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");
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:
625 name->sun_family = AF_UNIX;
626 memcpy(name->sun_path, saddrname, saddrname_len + 1);
628 int sockfd = dinit_socket(AF_UNIX, SOCK_STREAM, 0, SOCK_NONBLOCK | SOCK_CLOEXEC);
630 log(loglevel_t::ERROR, "Error creating control socket: ", strerror(errno));
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));
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));
654 if (listen(sockfd, 10) == -1) {
655 log(loglevel_t::ERROR, "Error listening on control socket: ", strerror(errno));
661 control_socket_io.add_watch(event_loop, sockfd, dasynq::IN_EVENTS);
662 control_socket_open = true;
664 catch (std::exception &e)
666 log(loglevel_t::ERROR, "Could not setup I/O on control socket: ", e.what());
672 static void close_control_socket() noexcept
674 if (control_socket_open) {
675 int fd = control_socket_io.get_watched_fd();
676 control_socket_io.deregister(event_loop);
679 // Unlink the socket:
680 unlink(control_socket_path);
682 control_socket_open = false;
686 void setup_external_log() noexcept
688 if (! external_log_open) {
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;
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");
700 name->sun_family = AF_UNIX;
701 memcpy(name->sun_path, saddrname, saddrname_len + 1);
703 int sockfd = dinit_socket(AF_UNIX, SOCK_DGRAM, 0, SOCK_NONBLOCK | SOCK_CLOEXEC);
705 log(loglevel_t::ERROR, "Error creating log socket: ", strerror(errno));
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.
715 setup_main_log(sockfd);
716 external_log_open = true;
718 catch (std::exception &e) {
719 log(loglevel_t::ERROR, "Setting up log failed: ", e.what());
724 // Note if connect fails, we haven't warned at all, because the syslog server might not
733 int log_fd = open(log_path, O_WRONLY | O_CREAT | O_APPEND | O_NONBLOCK | O_CLOEXEC, 0644);
736 setup_main_log(log_fd);
737 external_log_open = true;
739 catch (std::exception &e) {
740 log(loglevel_t::ERROR, "Setting up log failed: ", e.what());
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));
752 /* handle SIGINT signal (generated by Linux kernel when ctrl+alt+del pressed) */
753 static void sigint_reboot_cb(eventloop_t &eloop) noexcept
755 services->stop_all_services(shutdown_type_t::REBOOT);
758 /* handle SIGQUIT (if we are system init) */
759 static void sigquit_cb(eventloop_t &eloop) noexcept
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...
769 /* handle SIGTERM/SIGQUIT(non-system-daemon) - stop all services and shut down */
770 static void sigterm_cb(eventloop_t &eloop) noexcept
772 services->stop_all_services();