11 #include <sys/socket.h>
16 #include <sys/prctl.h>
18 #include <sys/reboot.h>
20 #if defined(__FreeBSD__) || defined(__DragonFly__)
21 #include <sys/procctl.h>
28 #include "dinit-log.h"
29 #include "dinit-socket.h"
32 * When running as the system init process, Dinit processes the following signals:
34 * SIGTERM - roll back services and then fork/exec /sbin/halt
35 * SIGINT - roll back services and then fork/exec /sbin/reboot
36 * SIGQUIT - exec() /sbin/shutdown without rolling back services
38 * It's an open question about whether Dinit should roll back services *before*
39 * running halt/reboot, since those commands should prompt rollback of services
40 * anyway. But it seems safe to do so, and it means the user can at least stop
41 * services even if the halt/reboot commands are unavailable for some reason.
44 using eventloop_t = dasynq::event_loop<dasynq::null_mutex>;
46 eventloop_t event_loop;
48 static void sigint_reboot_cb(eventloop_t &eloop) noexcept;
49 static void sigquit_cb(eventloop_t &eloop) noexcept;
50 static void sigterm_cb(eventloop_t &eloop) noexcept;
51 static void close_control_socket() noexcept;
52 static void wait_for_user_input() noexcept;
54 static void control_socket_cb(eventloop_t *loop, int fd);
59 static dirload_service_set *services;
61 static bool am_system_init = false; // true if we are the system init process
63 static bool control_socket_open = false;
64 static bool external_log_open = false;
65 int active_control_conns = 0;
67 // Control socket path. We maintain a string (control_socket_str) in case we need
68 // to allocate storage, but control_socket_path is the authoritative value.
69 static const char *control_socket_path = "/dev/dinitctl";
70 static std::string control_socket_str;
72 static const char *log_socket_path = "/dev/log";
74 static const char *user_home_path = nullptr;
77 // Get user home (and set user_home_path). (The return may become invalid after
78 // changing the evironment (HOME variable) or using the getpwuid() function).
79 const char * get_user_home()
81 if (user_home_path == nullptr) {
82 user_home_path = getenv("HOME");
83 if (user_home_path == nullptr) {
84 struct passwd * pwuid_p = getpwuid(getuid());
85 if (pwuid_p != nullptr) {
86 user_home_path = pwuid_p->pw_dir;
90 return user_home_path;
95 class callback_signal_handler : public eventloop_t::signal_watcher_impl<callback_signal_handler>
97 using rearm = dasynq::rearm;
100 typedef void (*cb_func_t)(eventloop_t &);
106 callback_signal_handler() : cb_func(nullptr) { }
107 callback_signal_handler(cb_func_t pcb_func) : cb_func(pcb_func) { }
109 void setCbFunc(cb_func_t cb_func)
111 this->cb_func = cb_func;
114 rearm received(eventloop_t &eloop, int signo, siginfo_p siginfo)
121 class control_socket_watcher : public eventloop_t::fd_watcher_impl<control_socket_watcher>
123 using rearm = dasynq::rearm;
126 rearm fd_event(eventloop_t &loop, int fd, int flags) noexcept
128 control_socket_cb(&loop, fd);
133 // Simple timer used to limit the amount of time waiting for the log flush to complete (at shutdown)
134 class log_flush_timer_t : public eventloop_t::timer_impl<log_flush_timer_t>
136 using rearm = dasynq::rearm;
138 bool expired = false;
141 rearm timer_expiry(eventloop_t &, int expiry_count)
144 return rearm::DISARM;
153 control_socket_watcher control_socket_io;
154 log_flush_timer_t log_flush_timer;
157 int dinit_main(int argc, char **argv)
161 am_system_init = (getpid() == 1);
162 const char * service_dir = nullptr;
163 string service_dir_str; // to hold storage for above if necessary
164 bool control_socket_path_set = false;
166 // list of services to start
167 list<const char *> services_to_start;
169 // Arguments, if given, specify a list of services to start.
170 // If we are running as init (PID=1), the kernel gives us any command line
171 // arguments it was given but didn't recognize, including "single" (usually
172 // for "boot to single user mode" aka just start the shell). We can treat
173 // them as service names. In the worst case we can't find any of the named
174 // services, and so we'll start the "boot" service by default.
176 for (int i = 1; i < argc; i++) {
177 if (argv[i][0] == '-') {
179 if (strcmp(argv[i], "--services-dir") == 0 ||
180 strcmp(argv[i], "-d") == 0) {
182 service_dir = argv[i];
185 cerr << "dinit: '--services-dir' (-d) requires an argument" << endl;
189 else if (strcmp(argv[i], "--system") == 0 ||
190 strcmp(argv[i], "-s") == 0) {
191 am_system_init = true;
193 else if (strcmp(argv[i], "--socket-path") == 0 ||
194 strcmp(argv[i], "-p") == 0) {
196 control_socket_path = argv[i];
197 control_socket_path_set = true;
200 cerr << "dinit: '--socket-path' (-p) requires an argument" << endl;
204 else if (strcmp(argv[i], "--help") == 0) {
205 cout << "dinit, an init with dependency management" << endl;
206 cout << " --help display help" << endl;
207 cout << " --services-dir <dir>, -d <dir>" << endl;
208 cout << " set base directory for service description" << endl;
209 cout << " files (-d <dir>)" << endl;
210 cout << " --system, -s run as the system init process" << endl;
211 cout << " --socket-path <path>, -p <path>" << endl;
212 cout << " path to control socket" << endl;
213 cout << " <service-name> start service with name <service-name>" << endl;
218 if (! am_system_init) {
219 cerr << "dinit: Unrecognized option: " << argv[i] << endl;
226 // LILO puts "auto" on the kernel command line for unattended boots; we'll filter it.
227 if (! am_system_init || strcmp(argv[i], "auto") != 0) {
228 services_to_start.push_back(argv[i]);
235 if (am_system_init) {
236 // setup STDIN, STDOUT, STDERR so that we can use them
237 int onefd = open("/dev/console", O_RDONLY, 0);
239 int twofd = open("/dev/console", O_RDWR, 0);
243 if (onefd > 2) close(onefd);
244 if (twofd > 2) close(twofd);
247 /* Set up signal handlers etc */
248 /* SIG_CHILD is ignored by default: good */
249 sigset_t sigwait_set;
250 sigemptyset(&sigwait_set);
251 sigaddset(&sigwait_set, SIGCHLD);
252 sigaddset(&sigwait_set, SIGINT);
253 sigaddset(&sigwait_set, SIGTERM);
254 if (am_system_init) sigaddset(&sigwait_set, SIGQUIT);
255 sigprocmask(SIG_BLOCK, &sigwait_set, NULL);
257 // Terminal access control signals - we block these so that dinit can't be
258 // suspended if it writes to the terminal after some other process has claimed
260 signal(SIGTSTP, SIG_IGN);
261 signal(SIGTTIN, SIG_IGN);
262 signal(SIGTTOU, SIG_IGN);
264 signal(SIGPIPE, SIG_IGN);
266 if (! am_system_init && ! control_socket_path_set) {
267 const char * userhome = get_user_home();
268 if (userhome != nullptr) {
269 control_socket_str = userhome;
270 control_socket_str += "/.dinitctl";
271 control_socket_path = control_socket_str.c_str();
275 /* service directory name */
276 if (service_dir == nullptr && ! am_system_init) {
277 const char * userhome = get_user_home();
278 if (userhome != nullptr) {
279 service_dir_str = get_user_home();
280 service_dir_str += "/dinit.d";
281 service_dir = service_dir_str.c_str();
285 if (service_dir == nullptr) {
286 service_dir = "/etc/dinit.d";
289 if (services_to_start.empty()) {
290 services_to_start.push_back("boot");
293 // Set up signal handlers
294 callback_signal_handler sigterm_watcher {sigterm_cb};
295 callback_signal_handler sigint_watcher;
296 callback_signal_handler sigquit_watcher;
298 if (am_system_init) {
299 sigint_watcher.setCbFunc(sigint_reboot_cb);
300 sigquit_watcher.setCbFunc(sigquit_cb);
303 sigint_watcher.setCbFunc(sigterm_cb);
306 sigint_watcher.add_watch(event_loop, SIGINT);
307 sigterm_watcher.add_watch(event_loop, SIGTERM);
309 if (am_system_init) {
310 // PID 1: SIGQUIT exec's shutdown
311 sigquit_watcher.add_watch(event_loop, SIGQUIT);
312 // As a user process, we instead just let SIGQUIT perform the default action.
315 // Try to open control socket (may fail due to readonly filesystem)
316 open_control_socket(false);
319 if (am_system_init) {
320 // Disable non-critical kernel output to console
321 klogctl(6 /* SYSLOG_ACTION_CONSOLE_OFF */, nullptr, 0);
322 // Make ctrl+alt+del combination send SIGINT to PID 1 (this process)
323 reboot(RB_DISABLE_CAD);
326 // Mark ourselves as a subreaper. This means that if a process we start double-forks, the
327 // orphaned child will re-parent to us rather than to PID 1 (although that could be us too).
328 prctl(PR_SET_CHILD_SUBREAPER, 1);
330 #if defined(__FreeBSD__) || defined(__DragonFly__)
331 // Documentation (man page) for this kind of sucks. PROC_REAP_ACQUIRE "acquires the reaper status for
332 // the current process" but does that mean the first two arguments still need valid values to be
333 // supplied? We'll play itself and explicitly target our own process:
334 procctl(P_PID, getpid(), PROC_REAP_ACQUIRE);
337 log_flush_timer.add_timer(event_loop, dasynq::clock_type::MONOTONIC);
339 /* start requested services */
340 services = new dirload_service_set(service_dir);
344 for (auto svc : services_to_start) {
346 services->start_service(svc);
347 // Note in general if we fail to start a service we don't need any special error handling,
348 // since we either leave other services running or, if it was the only service, then no
349 // services will be running and we will process normally (reboot if system process,
350 // exit if user process).
352 catch (service_not_found &snf) {
353 log(loglevel_t::ERROR, snf.serviceName, ": Could not find service description.");
355 catch (service_load_exc &sle) {
356 log(loglevel_t::ERROR, sle.serviceName, ": ", sle.excDescription);
358 catch (std::bad_alloc &badalloce) {
359 log(loglevel_t::ERROR, "Out of memory when trying to start service: ", svc, ".");
366 // Process events until all services have terminated.
367 while (services->count_active_services() != 0) {
371 shutdown_type_t shutdown_type = services->get_shutdown_type();
373 if (am_system_init) {
374 log_msg_begin(loglevel_t::INFO, "No more active services.");
376 if (shutdown_type == shutdown_type_t::REBOOT) {
377 log_msg_end(" Will reboot.");
379 else if (shutdown_type == shutdown_type_t::HALT) {
380 log_msg_end(" Will halt.");
382 else if (shutdown_type == shutdown_type_t::POWEROFF) {
383 log_msg_end(" Will power down.");
386 log_msg_end(" Re-initiating boot sequence.");
390 log_flush_timer.arm_timer_rel(event_loop, timespec{5,0}); // 5 seconds
391 while (! is_log_flushed() && ! log_flush_timer.has_expired()) {
395 close_control_socket();
397 if (am_system_init) {
398 if (shutdown_type == shutdown_type_t::CONTINUE) {
399 // It could be that we started in single user mode, and the
400 // user has now exited the shell. We'll try and re-start the
403 services->start_service("boot");
404 goto event_loop; // yes, the "evil" goto
407 // Now what do we do? try to reboot, but wait for user ack to avoid boot loop.
408 log(loglevel_t::ERROR, "Could not start 'boot' service. Will attempt reboot.");
409 wait_for_user_input();
410 shutdown_type = shutdown_type_t::REBOOT;
414 const char * cmd_arg;
415 if (shutdown_type == shutdown_type_t::HALT) {
418 else if (shutdown_type == shutdown_type_t::REBOOT) {
426 // Fork and execute dinit-reboot.
427 execl("/sbin/shutdown", "/sbin/shutdown", "--system", cmd_arg, nullptr);
428 log(loglevel_t::ERROR, "Could not execute /sbin/shutdown: ", strerror(errno));
430 // PID 1 must not actually exit, although we should never reach this point:
435 else if (shutdown_type == shutdown_type_t::REBOOT) {
436 // Non-system-process. If we got SIGINT, let's die due to it:
437 sigset_t sigwait_set;
438 sigemptyset(&sigwait_set);
439 sigaddset(&sigwait_set, SIGINT);
441 sigprocmask(SIG_UNBLOCK, &sigwait_set, NULL);
447 // In exception situations we want user confirmation before proceeding (eg on critical boot failure
448 // we wait before rebooting to avoid a reboot loop).
449 static void wait_for_user_input() noexcept
451 std::cout << "Press Enter to continue." << std::endl;
453 read(STDIN_FILENO, buf, 1);
456 // Callback for control socket
457 static void control_socket_cb(eventloop_t *loop, int sockfd)
459 // Considered keeping a limit the number of active connections, however, there doesn't
460 // seem much to be gained from that. Only root can create connections and not being
461 // able to establish a control connection is as much a denial-of-service as is not being
462 // able to start a service due to lack of fd's.
464 // Accept a connection
465 int newfd = dinit_accept4(sockfd, nullptr, nullptr, SOCK_NONBLOCK | SOCK_CLOEXEC);
469 new control_conn_t(*loop, services, newfd); // will delete itself when it's finished
471 catch (std::exception &exc) {
472 log(loglevel_t::ERROR, "Accepting control connection: ", exc.what());
478 void open_control_socket(bool report_ro_failure) noexcept
480 if (! control_socket_open) {
481 const char * saddrname = control_socket_path;
482 size_t saddrname_len = strlen(saddrname);
483 uint sockaddr_size = offsetof(struct sockaddr_un, sun_path) + saddrname_len + 1;
485 struct sockaddr_un * name = static_cast<sockaddr_un *>(malloc(sockaddr_size));
486 if (name == nullptr) {
487 log(loglevel_t::ERROR, "Opening control socket: out of memory");
491 if (am_system_init) {
492 // Unlink any stale control socket file, but only if we are system init, since otherwise
493 // the 'stale' file may not be stale at all:
497 name->sun_family = AF_UNIX;
498 memcpy(name->sun_path, saddrname, saddrname_len + 1);
500 int sockfd = dinit_socket(AF_UNIX, SOCK_STREAM, 0, SOCK_NONBLOCK | SOCK_CLOEXEC);
502 log(loglevel_t::ERROR, "Error creating control socket: ", strerror(errno));
507 if (bind(sockfd, (struct sockaddr *) name, sockaddr_size) == -1) {
508 if (errno != EROFS || report_ro_failure) {
509 log(loglevel_t::ERROR, "Error binding control socket: ", strerror(errno));
518 // No connections can be made until we listen, so it is fine to change the permissions now
519 // (and anyway there is no way to atomically create the socket and set permissions):
520 if (chmod(saddrname, S_IRUSR | S_IWUSR) == -1) {
521 log(loglevel_t::ERROR, "Error setting control socket permissions: ", strerror(errno));
526 if (listen(sockfd, 10) == -1) {
527 log(loglevel_t::ERROR, "Error listening on control socket: ", strerror(errno));
533 control_socket_io.add_watch(event_loop, sockfd, dasynq::IN_EVENTS);
534 control_socket_open = true;
536 catch (std::exception &e)
538 log(loglevel_t::ERROR, "Could not setup I/O on control socket: ", e.what());
544 static void close_control_socket() noexcept
546 if (control_socket_open) {
547 int fd = control_socket_io.get_watched_fd();
548 control_socket_io.deregister(event_loop);
551 // Unlink the socket:
552 unlink(control_socket_path);
556 void setup_external_log() noexcept
558 if (! external_log_open) {
560 const char * saddrname = log_socket_path;
561 size_t saddrname_len = strlen(saddrname);
562 uint sockaddr_size = offsetof(struct sockaddr_un, sun_path) + saddrname_len + 1;
564 struct sockaddr_un * name = static_cast<sockaddr_un *>(malloc(sockaddr_size));
565 if (name == nullptr) {
566 log(loglevel_t::ERROR, "Connecting to log socket: out of memory");
570 name->sun_family = AF_UNIX;
571 memcpy(name->sun_path, saddrname, saddrname_len + 1);
573 int sockfd = dinit_socket(AF_UNIX, SOCK_DGRAM, 0, SOCK_NONBLOCK | SOCK_CLOEXEC);
575 log(loglevel_t::ERROR, "Error creating log socket: ", strerror(errno));
580 if (connect(sockfd, (struct sockaddr *) name, sockaddr_size) == 0 || errno == EINPROGRESS) {
581 // For EINPROGRESS, connection is still being established; however, we can select on
582 // the file descriptor so we will be notified when it's ready. In other words we can
583 // basically use it anyway.
585 setup_main_log(sockfd);
587 catch (std::exception &e) {
588 log(loglevel_t::ERROR, "Setting up log failed: ", e.what());
593 // Note if connect fails, we haven't warned at all, because the syslog server might not
602 /* handle SIGINT signal (generated by Linux kernel when ctrl+alt+del pressed) */
603 static void sigint_reboot_cb(eventloop_t &eloop) noexcept
605 services->stop_all_services(shutdown_type_t::REBOOT);
608 /* handle SIGQUIT (if we are system init) */
609 static void sigquit_cb(eventloop_t &eloop) noexcept
611 // This performs an immediate shutdown, without service rollback.
612 close_control_socket();
613 execl("/sbin/shutdown", "/sbin/shutdown", "--system", (char *) 0);
614 log(loglevel_t::ERROR, "Error executing /sbin/shutdown: ", strerror(errno));
615 sync(); // since a hard poweroff might be required at this point...
618 /* handle SIGTERM/SIGQUIT(non-system-daemon) - stop all services and shut down */
619 static void sigterm_cb(eventloop_t &eloop) noexcept
621 services->stop_all_services();