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"
33 * When running as the system init process, Dinit processes the following signals:
35 * SIGTERM - roll back services and then fork/exec /sbin/halt
36 * SIGINT - roll back services and then fork/exec /sbin/reboot
37 * SIGQUIT - exec() /sbin/shutdown without rolling back services
39 * It's an open question about whether Dinit should roll back services *before*
40 * running halt/reboot, since those commands should prompt rollback of services
41 * anyway. But it seems safe to do so, and it means the user can at least stop
42 * services even if the halt/reboot commands are unavailable for some reason.
45 using eventloop_t = dasynq::event_loop<dasynq::null_mutex>;
47 eventloop_t event_loop;
49 static void sigint_reboot_cb(eventloop_t &eloop) noexcept;
50 static void sigquit_cb(eventloop_t &eloop) noexcept;
51 static void sigterm_cb(eventloop_t &eloop) noexcept;
52 static void close_control_socket() noexcept;
53 static void wait_for_user_input() noexcept;
54 static void read_env_file(const char *);
56 static void control_socket_cb(eventloop_t *loop, int fd);
61 static dirload_service_set *services;
63 static bool am_system_init = false; // true if we are the system init process
65 static bool control_socket_open = false;
66 static bool external_log_open = false;
67 int active_control_conns = 0;
69 // Control socket path. We maintain a string (control_socket_str) in case we need
70 // to allocate storage, but control_socket_path is the authoritative value.
71 static const char *control_socket_path = "/dev/dinitctl";
72 static std::string control_socket_str;
74 static const char *env_file_path = "/etc/dinit/environment";
76 static const char *log_socket_path = "/dev/log";
78 static const char *user_home_path = nullptr;
81 // Get user home (and set user_home_path). (The return may become invalid after
82 // changing the evironment (HOME variable) or using the getpwuid() function).
83 const char * get_user_home()
85 if (user_home_path == nullptr) {
86 user_home_path = getenv("HOME");
87 if (user_home_path == nullptr) {
88 struct passwd * pwuid_p = getpwuid(getuid());
89 if (pwuid_p != nullptr) {
90 user_home_path = pwuid_p->pw_dir;
94 return user_home_path;
99 class callback_signal_handler : public eventloop_t::signal_watcher_impl<callback_signal_handler>
101 using rearm = dasynq::rearm;
104 typedef void (*cb_func_t)(eventloop_t &);
110 callback_signal_handler() : cb_func(nullptr) { }
111 callback_signal_handler(cb_func_t pcb_func) : cb_func(pcb_func) { }
113 void setCbFunc(cb_func_t cb_func)
115 this->cb_func = cb_func;
118 rearm received(eventloop_t &eloop, int signo, siginfo_p siginfo)
125 class control_socket_watcher : public eventloop_t::fd_watcher_impl<control_socket_watcher>
127 using rearm = dasynq::rearm;
130 rearm fd_event(eventloop_t &loop, int fd, int flags) noexcept
132 control_socket_cb(&loop, fd);
137 // Simple timer used to limit the amount of time waiting for the log flush to complete (at shutdown)
138 class log_flush_timer_t : public eventloop_t::timer_impl<log_flush_timer_t>
140 using rearm = dasynq::rearm;
142 bool expired = false;
145 rearm timer_expiry(eventloop_t &, int expiry_count)
148 return rearm::DISARM;
157 control_socket_watcher control_socket_io;
158 log_flush_timer_t log_flush_timer;
161 int dinit_main(int argc, char **argv)
165 am_system_init = (getpid() == 1);
166 const char * service_dir = nullptr;
167 const char * env_file = nullptr;
168 string service_dir_str; // to hold storage for above if necessary
169 bool control_socket_path_set = false;
170 bool env_file_set = false;
172 // list of services to start
173 list<const char *> services_to_start;
175 // Arguments, if given, specify a list of services to start.
176 // If we are running as init (PID=1), the Linux kernel gives us any command line arguments it was given
177 // but didn't recognize, including "single" (usually for "boot to single user mode" aka just start the
178 // shell). We can treat them as service names. In the worst case we can't find any of the named
179 // services, and so we'll start the "boot" service by default.
181 for (int i = 1; i < argc; i++) {
182 if (argv[i][0] == '-') {
184 if (strcmp(argv[i], "--env-file") == 0 || strcmp(argv[i], "-e") == 0) {
190 cerr << "dinit: '--env-file' (-e) requires an argument" << endl;
193 else if (strcmp(argv[i], "--services-dir") == 0 || strcmp(argv[i], "-d") == 0) {
195 service_dir = argv[i];
198 cerr << "dinit: '--services-dir' (-d) requires an argument" << endl;
202 else if (strcmp(argv[i], "--system") == 0 || strcmp(argv[i], "-s") == 0) {
203 am_system_init = true;
205 else if (strcmp(argv[i], "--socket-path") == 0 || strcmp(argv[i], "-p") == 0) {
207 control_socket_path = argv[i];
208 control_socket_path_set = true;
211 cerr << "dinit: '--socket-path' (-p) requires an argument" << endl;
215 else if (strcmp(argv[i], "--help") == 0) {
216 cout << "dinit, an init with dependency management" << endl;
217 cout << " --help display help" << endl;
218 cout << " --env-file <file>, -e <file>" << endl;
219 cout << " environment variable initialisation file" << endl;
220 cout << " --services-dir <dir>, -d <dir>" << endl;
221 cout << " set base directory for service description" << endl;
222 cout << " files (-d <dir>)" << endl;
223 cout << " --system, -s run as the system init process" << endl;
224 cout << " --socket-path <path>, -p <path>" << endl;
225 cout << " path to control socket" << endl;
226 cout << " <service-name> start service with name <service-name>" << endl;
231 if (! am_system_init) {
232 cerr << "dinit: Unrecognized option: " << argv[i] << endl;
239 // LILO puts "auto" on the kernel command line for unattended boots; we'll filter it.
240 if (! am_system_init || strcmp(argv[i], "auto") != 0) {
241 services_to_start.push_back(argv[i]);
244 services_to_start.push_back(argv[i]);
250 if (am_system_init) {
251 // setup STDIN, STDOUT, STDERR so that we can use them
252 int onefd = open("/dev/console", O_RDONLY, 0);
254 int twofd = open("/dev/console", O_RDWR, 0);
258 if (onefd > 2) close(onefd);
259 if (twofd > 2) close(twofd);
261 if (! env_file_set) {
262 env_file = env_file_path;
266 /* Set up signal handlers etc */
267 /* SIG_CHILD is ignored by default: good */
268 sigset_t sigwait_set;
269 sigemptyset(&sigwait_set);
270 sigaddset(&sigwait_set, SIGCHLD);
271 sigaddset(&sigwait_set, SIGINT);
272 sigaddset(&sigwait_set, SIGTERM);
273 if (am_system_init) sigaddset(&sigwait_set, SIGQUIT);
274 sigprocmask(SIG_BLOCK, &sigwait_set, NULL);
276 // Terminal access control signals - we block these so that dinit can't be
277 // suspended if it writes to the terminal after some other process has claimed
279 signal(SIGTSTP, SIG_IGN);
280 signal(SIGTTIN, SIG_IGN);
281 signal(SIGTTOU, SIG_IGN);
283 signal(SIGPIPE, SIG_IGN);
285 if (! am_system_init && ! control_socket_path_set) {
286 const char * userhome = get_user_home();
287 if (userhome != nullptr) {
288 control_socket_str = userhome;
289 control_socket_str += "/.dinitctl";
290 control_socket_path = control_socket_str.c_str();
294 /* service directory name */
295 if (service_dir == nullptr && ! am_system_init) {
296 const char * userhome = get_user_home();
297 if (userhome != nullptr) {
298 service_dir_str = get_user_home();
299 service_dir_str += "/dinit.d";
300 service_dir = service_dir_str.c_str();
304 if (service_dir == nullptr) {
305 service_dir = "/etc/dinit.d";
308 if (services_to_start.empty()) {
309 services_to_start.push_back("boot");
312 // Set up signal handlers
313 callback_signal_handler sigterm_watcher {sigterm_cb};
314 callback_signal_handler sigint_watcher;
315 callback_signal_handler sigquit_watcher;
317 if (am_system_init) {
318 sigint_watcher.setCbFunc(sigint_reboot_cb);
319 sigquit_watcher.setCbFunc(sigquit_cb);
322 sigint_watcher.setCbFunc(sigterm_cb);
325 sigint_watcher.add_watch(event_loop, SIGINT);
326 sigterm_watcher.add_watch(event_loop, SIGTERM);
328 if (am_system_init) {
329 // PID 1: SIGQUIT exec's shutdown
330 sigquit_watcher.add_watch(event_loop, SIGQUIT);
331 // As a user process, we instead just let SIGQUIT perform the default action.
334 // Try to open control socket (may fail due to readonly filesystem)
335 open_control_socket(false);
338 if (am_system_init) {
339 // Disable non-critical kernel output to console
340 klogctl(6 /* SYSLOG_ACTION_CONSOLE_OFF */, nullptr, 0);
341 // Make ctrl+alt+del combination send SIGINT to PID 1 (this process)
342 reboot(RB_DISABLE_CAD);
345 // Mark ourselves as a subreaper. This means that if a process we start double-forks, the
346 // orphaned child will re-parent to us rather than to PID 1 (although that could be us too).
347 prctl(PR_SET_CHILD_SUBREAPER, 1);
349 #if defined(__FreeBSD__) || defined(__DragonFly__)
350 // Documentation (man page) for this kind of sucks. PROC_REAP_ACQUIRE "acquires the reaper status for
351 // the current process" but does that mean the first two arguments still need valid values to be
352 // supplied? We'll play it safe and explicitly target our own process:
353 procctl(P_PID, getpid(), PROC_REAP_ACQUIRE, NULL);
356 log_flush_timer.add_timer(event_loop, dasynq::clock_type::MONOTONIC);
358 /* start requested services */
359 services = new dirload_service_set(service_dir);
363 if (env_file != nullptr) {
364 read_env_file(env_file);
367 for (auto svc : services_to_start) {
369 services->start_service(svc);
370 // Note in general if we fail to start a service we don't need any special error handling,
371 // since we either leave other services running or, if it was the only service, then no
372 // services will be running and we will process normally (reboot if system process,
373 // exit if user process).
375 catch (service_not_found &snf) {
376 log(loglevel_t::ERROR, snf.serviceName, ": Could not find service description.");
378 catch (service_load_exc &sle) {
379 log(loglevel_t::ERROR, sle.serviceName, ": ", sle.excDescription);
381 catch (std::bad_alloc &badalloce) {
382 log(loglevel_t::ERROR, "Out of memory when trying to start service: ", svc, ".");
389 // Process events until all services have terminated.
390 while (services->count_active_services() != 0) {
394 shutdown_type_t shutdown_type = services->get_shutdown_type();
396 if (am_system_init) {
397 log_msg_begin(loglevel_t::INFO, "No more active services.");
399 if (shutdown_type == shutdown_type_t::REBOOT) {
400 log_msg_end(" Will reboot.");
402 else if (shutdown_type == shutdown_type_t::HALT) {
403 log_msg_end(" Will halt.");
405 else if (shutdown_type == shutdown_type_t::POWEROFF) {
406 log_msg_end(" Will power down.");
409 log_msg_end(" Re-initiating boot sequence.");
413 log_flush_timer.arm_timer_rel(event_loop, timespec{5,0}); // 5 seconds
414 while (! is_log_flushed() && ! log_flush_timer.has_expired()) {
418 close_control_socket();
420 if (am_system_init) {
421 if (shutdown_type == shutdown_type_t::CONTINUE) {
422 // It could be that we started in single user mode, and the
423 // user has now exited the shell. We'll try and re-start the
426 services->start_service("boot");
427 goto event_loop; // yes, the "evil" goto
430 // Now what do we do? try to reboot, but wait for user ack to avoid boot loop.
431 log(loglevel_t::ERROR, "Could not start 'boot' service. Will attempt reboot.");
432 wait_for_user_input();
433 shutdown_type = shutdown_type_t::REBOOT;
437 const char * cmd_arg;
438 if (shutdown_type == shutdown_type_t::HALT) {
441 else if (shutdown_type == shutdown_type_t::REBOOT) {
449 // Fork and execute dinit-reboot.
450 execl("/sbin/shutdown", "/sbin/shutdown", "--system", cmd_arg, nullptr);
451 log(loglevel_t::ERROR, "Could not execute /sbin/shutdown: ", strerror(errno));
453 // PID 1 must not actually exit, although we should never reach this point:
458 else if (shutdown_type == shutdown_type_t::REBOOT) {
459 // Non-system-process. If we got SIGINT, let's die due to it:
460 sigset_t sigwait_set;
461 sigemptyset(&sigwait_set);
462 sigaddset(&sigwait_set, SIGINT);
464 sigprocmask(SIG_UNBLOCK, &sigwait_set, NULL);
470 static void log_bad_env(int linenum)
472 log(loglevel_t::ERROR, "invalid environment variable setting in environment file (line ", linenum, ")");
475 // Read and set environment variables from a file.
476 static void read_env_file(const char *env_file_path)
478 // Note that we can't use the log in this function; it hasn't been initialised yet.
480 std::ifstream env_file(env_file_path);
481 if (! env_file) return;
483 env_file.exceptions(std::ios::badbit);
485 auto &clocale = std::locale::classic();
489 while (std::getline(env_file, line)) {
491 auto lpos = line.begin();
492 auto lend = line.end();
493 while (lpos != lend && std::isspace(*lpos, clocale)) {
500 log_bad_env(linenum);
503 auto name_begin = lpos++;
504 // skip until '=' or whitespace:
505 while (lpos != lend && *lpos != '=' && ! std::isspace(*lpos, clocale)) ++lpos;
506 auto name_end = lpos;
508 while (lpos != lend && std::isspace(*lpos, clocale)) ++lpos;
510 log_bad_env(linenum);
515 auto val_begin = lpos;
516 while (lpos != lend && *lpos != '\n') ++lpos;
519 std::string name = line.substr(name_begin - line.begin(), name_end - name_begin);
520 std::string value = line.substr(val_begin - line.begin(), val_end - val_begin);
521 if (setenv(name.c_str(), value.c_str(), true) == -1) {
522 throw std::system_error(errno, std::system_category());
529 // In exception situations we want user confirmation before proceeding (eg on critical boot failure
530 // we wait before rebooting to avoid a reboot loop).
531 static void wait_for_user_input() noexcept
533 std::cout << "Press Enter to continue." << std::endl;
535 read(STDIN_FILENO, buf, 1);
538 // Callback for control socket
539 static void control_socket_cb(eventloop_t *loop, int sockfd)
541 // Considered keeping a limit the number of active connections, however, there doesn't
542 // seem much to be gained from that. Only root can create connections and not being
543 // able to establish a control connection is as much a denial-of-service as is not being
544 // able to start a service due to lack of fd's.
546 // Accept a connection
547 int newfd = dinit_accept4(sockfd, nullptr, nullptr, SOCK_NONBLOCK | SOCK_CLOEXEC);
551 new control_conn_t(*loop, services, newfd); // will delete itself when it's finished
553 catch (std::exception &exc) {
554 log(loglevel_t::ERROR, "Accepting control connection: ", exc.what());
560 void open_control_socket(bool report_ro_failure) noexcept
562 if (! control_socket_open) {
563 const char * saddrname = control_socket_path;
564 size_t saddrname_len = strlen(saddrname);
565 uint sockaddr_size = offsetof(struct sockaddr_un, sun_path) + saddrname_len + 1;
567 struct sockaddr_un * name = static_cast<sockaddr_un *>(malloc(sockaddr_size));
568 if (name == nullptr) {
569 log(loglevel_t::ERROR, "Opening control socket: out of memory");
573 if (am_system_init) {
574 // Unlink any stale control socket file, but only if we are system init, since otherwise
575 // the 'stale' file may not be stale at all:
579 name->sun_family = AF_UNIX;
580 memcpy(name->sun_path, saddrname, saddrname_len + 1);
582 int sockfd = dinit_socket(AF_UNIX, SOCK_STREAM, 0, SOCK_NONBLOCK | SOCK_CLOEXEC);
584 log(loglevel_t::ERROR, "Error creating control socket: ", strerror(errno));
589 if (bind(sockfd, (struct sockaddr *) name, sockaddr_size) == -1) {
590 if (errno != EROFS || report_ro_failure) {
591 log(loglevel_t::ERROR, "Error binding control socket: ", strerror(errno));
600 // No connections can be made until we listen, so it is fine to change the permissions now
601 // (and anyway there is no way to atomically create the socket and set permissions):
602 if (chmod(saddrname, S_IRUSR | S_IWUSR) == -1) {
603 log(loglevel_t::ERROR, "Error setting control socket permissions: ", strerror(errno));
608 if (listen(sockfd, 10) == -1) {
609 log(loglevel_t::ERROR, "Error listening on control socket: ", strerror(errno));
615 control_socket_io.add_watch(event_loop, sockfd, dasynq::IN_EVENTS);
616 control_socket_open = true;
618 catch (std::exception &e)
620 log(loglevel_t::ERROR, "Could not setup I/O on control socket: ", e.what());
626 static void close_control_socket() noexcept
628 if (control_socket_open) {
629 int fd = control_socket_io.get_watched_fd();
630 control_socket_io.deregister(event_loop);
633 // Unlink the socket:
634 unlink(control_socket_path);
638 void setup_external_log() noexcept
640 if (! external_log_open) {
642 const char * saddrname = log_socket_path;
643 size_t saddrname_len = strlen(saddrname);
644 uint sockaddr_size = offsetof(struct sockaddr_un, sun_path) + saddrname_len + 1;
646 struct sockaddr_un * name = static_cast<sockaddr_un *>(malloc(sockaddr_size));
647 if (name == nullptr) {
648 log(loglevel_t::ERROR, "Connecting to log socket: out of memory");
652 name->sun_family = AF_UNIX;
653 memcpy(name->sun_path, saddrname, saddrname_len + 1);
655 int sockfd = dinit_socket(AF_UNIX, SOCK_DGRAM, 0, SOCK_NONBLOCK | SOCK_CLOEXEC);
657 log(loglevel_t::ERROR, "Error creating log socket: ", strerror(errno));
662 if (connect(sockfd, (struct sockaddr *) name, sockaddr_size) == 0 || errno == EINPROGRESS) {
663 // For EINPROGRESS, connection is still being established; however, we can select on
664 // the file descriptor so we will be notified when it's ready. In other words we can
665 // basically use it anyway.
667 setup_main_log(sockfd);
669 catch (std::exception &e) {
670 log(loglevel_t::ERROR, "Setting up log failed: ", e.what());
675 // Note if connect fails, we haven't warned at all, because the syslog server might not
684 /* handle SIGINT signal (generated by Linux kernel when ctrl+alt+del pressed) */
685 static void sigint_reboot_cb(eventloop_t &eloop) noexcept
687 services->stop_all_services(shutdown_type_t::REBOOT);
690 /* handle SIGQUIT (if we are system init) */
691 static void sigquit_cb(eventloop_t &eloop) noexcept
693 // This performs an immediate shutdown, without service rollback.
694 close_control_socket();
695 execl("/sbin/shutdown", "/sbin/shutdown", "--system", (char *) 0);
696 log(loglevel_t::ERROR, "Error executing /sbin/shutdown: ", strerror(errno));
697 sync(); // since a hard poweroff might be required at this point...
700 /* handle SIGTERM/SIGQUIT(non-system-daemon) - stop all services and shut down */
701 static void sigterm_cb(eventloop_t &eloop) noexcept
703 services->stop_all_services();