11 #include <sys/socket.h>
16 #include <sys/prctl.h>
18 #include <sys/reboot.h>
25 #include "dinit-log.h"
26 #include "dinit-socket.h"
29 * When running as the system init process, Dinit processes the following signals:
31 * SIGTERM - roll back services and then fork/exec /sbin/halt
32 * SIGINT - roll back services and then fork/exec /sbin/reboot
33 * SIGQUIT - exec() /sbin/shutdown without rolling back services
35 * It's an open question about whether Dinit should roll back services *before*
36 * running halt/reboot, since those commands should prompt rollback of services
37 * anyway. But it seems safe to do so, and it means the user can at least stop
38 * services even if the halt/reboot commands are unavailable for some reason.
41 using eventloop_t = dasynq::event_loop<dasynq::null_mutex>;
43 eventloop_t event_loop;
45 static void sigint_reboot_cb(eventloop_t &eloop) noexcept;
46 static void sigquit_cb(eventloop_t &eloop) noexcept;
47 static void sigterm_cb(eventloop_t &eloop) noexcept;
48 static void close_control_socket() noexcept;
49 static void wait_for_user_input() noexcept;
51 static void control_socket_cb(eventloop_t *loop, int fd);
56 static dirload_service_set *services;
58 static bool am_system_init = false; // true if we are the system init process
60 static bool control_socket_open = false;
61 static bool external_log_open = false;
62 int active_control_conns = 0;
64 // Control socket path. We maintain a string (control_socket_str) in case we need
65 // to allocate storage, but control_socket_path is the authoritative value.
66 static const char *control_socket_path = "/dev/dinitctl";
67 static std::string control_socket_str;
69 static const char *log_socket_path = "/dev/log";
71 static const char *user_home_path = nullptr;
74 // Get user home (and set user_home_path). (The return may become invalid after
75 // changing the evironment (HOME variable) or using the getpwuid() function).
76 const char * get_user_home()
78 if (user_home_path == nullptr) {
79 user_home_path = getenv("HOME");
80 if (user_home_path == nullptr) {
81 struct passwd * pwuid_p = getpwuid(getuid());
82 if (pwuid_p != nullptr) {
83 user_home_path = pwuid_p->pw_dir;
87 return user_home_path;
92 class callback_signal_handler : public eventloop_t::signal_watcher_impl<callback_signal_handler>
94 using rearm = dasynq::rearm;
97 typedef void (*cb_func_t)(eventloop_t &);
103 callback_signal_handler() : cb_func(nullptr) { }
104 callback_signal_handler(cb_func_t pcb_func) : cb_func(pcb_func) { }
106 void setCbFunc(cb_func_t cb_func)
108 this->cb_func = cb_func;
111 rearm received(eventloop_t &eloop, int signo, siginfo_p siginfo)
118 class control_socket_watcher : public eventloop_t::fd_watcher_impl<control_socket_watcher>
120 using rearm = dasynq::rearm;
123 rearm fd_event(eventloop_t &loop, int fd, int flags) noexcept
125 control_socket_cb(&loop, fd);
130 control_socket_watcher control_socket_io;
133 int dinit_main(int argc, char **argv)
137 am_system_init = (getpid() == 1);
138 const char * service_dir = nullptr;
139 string service_dir_str; // to hold storage for above if necessary
140 bool control_socket_path_set = false;
142 // list of services to start
143 list<const char *> services_to_start;
145 // Arguments, if given, specify a list of services to start.
146 // If we are running as init (PID=1), the kernel gives us any command line
147 // arguments it was given but didn't recognize, including "single" (usually
148 // for "boot to single user mode" aka just start the shell). We can treat
149 // them as service names. In the worst case we can't find any of the named
150 // services, and so we'll start the "boot" service by default.
152 for (int i = 1; i < argc; i++) {
153 if (argv[i][0] == '-') {
155 if (strcmp(argv[i], "--services-dir") == 0 ||
156 strcmp(argv[i], "-d") == 0) {
158 service_dir = argv[i];
161 cerr << "dinit: '--services-dir' (-d) requires an argument" << endl;
165 else if (strcmp(argv[i], "--system") == 0 ||
166 strcmp(argv[i], "-s") == 0) {
167 am_system_init = true;
169 else if (strcmp(argv[i], "--socket-path") == 0 ||
170 strcmp(argv[i], "-p") == 0) {
172 control_socket_path = argv[i];
173 control_socket_path_set = true;
176 cerr << "dinit: '--socket-path' (-p) requires an argument" << endl;
180 else if (strcmp(argv[i], "--help") == 0) {
181 cout << "dinit, an init with dependency management" << endl;
182 cout << " --help display help" << endl;
183 cout << " --services-dir <dir>, -d <dir>" << endl;
184 cout << " set base directory for service description" << endl;
185 cout << " files (-d <dir>)" << endl;
186 cout << " --system, -s run as the system init process" << endl;
187 cout << " --socket-path <path>, -p <path>" << endl;
188 cout << " path to control socket" << endl;
189 cout << " <service-name> start service with name <service-name>" << endl;
194 if (! am_system_init) {
195 cerr << "dinit: Unrecognized option: " << argv[i] << endl;
202 // LILO puts "auto" on the kernel command line for unattended boots; we'll filter it.
203 if (! am_system_init || strcmp(argv[i], "auto") != 0) {
204 services_to_start.push_back(argv[i]);
211 if (am_system_init) {
212 // setup STDIN, STDOUT, STDERR so that we can use them
213 int onefd = open("/dev/console", O_RDONLY, 0);
215 int twofd = open("/dev/console", O_RDWR, 0);
219 if (onefd > 2) close(onefd);
220 if (twofd > 2) close(twofd);
223 /* Set up signal handlers etc */
224 /* SIG_CHILD is ignored by default: good */
225 sigset_t sigwait_set;
226 sigemptyset(&sigwait_set);
227 sigaddset(&sigwait_set, SIGCHLD);
228 sigaddset(&sigwait_set, SIGINT);
229 sigaddset(&sigwait_set, SIGTERM);
230 if (am_system_init) sigaddset(&sigwait_set, SIGQUIT);
231 sigprocmask(SIG_BLOCK, &sigwait_set, NULL);
233 // Terminal access control signals - we block these so that dinit can't be
234 // suspended if it writes to the terminal after some other process has claimed
236 signal(SIGTSTP, SIG_IGN);
237 signal(SIGTTIN, SIG_IGN);
238 signal(SIGTTOU, SIG_IGN);
240 signal(SIGPIPE, SIG_IGN);
242 if (! am_system_init && ! control_socket_path_set) {
243 const char * userhome = get_user_home();
244 if (userhome != nullptr) {
245 control_socket_str = userhome;
246 control_socket_str += "/.dinitctl";
247 control_socket_path = control_socket_str.c_str();
251 /* service directory name */
252 if (service_dir == nullptr && ! am_system_init) {
253 const char * userhome = get_user_home();
254 if (userhome != nullptr) {
255 service_dir_str = get_user_home();
256 service_dir_str += "/dinit.d";
257 service_dir = service_dir_str.c_str();
261 if (service_dir == nullptr) {
262 service_dir = "/etc/dinit.d";
265 if (services_to_start.empty()) {
266 services_to_start.push_back("boot");
269 // Set up signal handlers
270 callback_signal_handler sigterm_watcher {sigterm_cb};
271 callback_signal_handler sigint_watcher;
272 callback_signal_handler sigquit_watcher;
274 if (am_system_init) {
275 sigint_watcher.setCbFunc(sigint_reboot_cb);
276 sigquit_watcher.setCbFunc(sigquit_cb);
279 sigint_watcher.setCbFunc(sigterm_cb);
282 sigint_watcher.add_watch(event_loop, SIGINT);
283 sigterm_watcher.add_watch(event_loop, SIGTERM);
285 if (am_system_init) {
286 // PID 1: SIGQUIT exec's shutdown
287 sigquit_watcher.add_watch(event_loop, SIGQUIT);
288 // As a user process, we instead just let SIGQUIT perform the default action.
291 // Try to open control socket (may fail due to readonly filesystem)
292 open_control_socket(false);
295 if (am_system_init) {
296 // Disable non-critical kernel output to console
297 klogctl(6 /* SYSLOG_ACTION_CONSOLE_OFF */, nullptr, 0);
298 // Make ctrl+alt+del combination send SIGINT to PID 1 (this process)
299 reboot(RB_DISABLE_CAD);
302 // Mark ourselves as a subreaper. This means that if a process we start double-forks, the
303 // orphaned child will re-parent to us rather than to PID 1 (although that could be us too).
304 prctl(PR_SET_CHILD_SUBREAPER, 1);
307 /* start requested services */
308 services = new dirload_service_set(service_dir);
312 for (auto svc : services_to_start) {
314 services->start_service(svc);
315 // Note in general if we fail to start a service we don't need any special error handling,
316 // since we either leave other services running or, if it was the only service, then no
317 // services will be running and we will process normally (reboot if system process,
318 // exit if user process).
320 catch (service_not_found &snf) {
321 log(loglevel_t::ERROR, snf.serviceName, ": Could not find service description.");
323 catch (service_load_exc &sle) {
324 log(loglevel_t::ERROR, sle.serviceName, ": ", sle.excDescription);
326 catch (std::bad_alloc &badalloce) {
327 log(loglevel_t::ERROR, "Out of memory when trying to start service: ", svc, ".");
334 // Process events until all services have terminated.
335 while (services->count_active_services() != 0) {
339 shutdown_type_t shutdown_type = services->getShutdownType();
341 if (am_system_init) {
342 log_msg_begin(loglevel_t::INFO, "No more active services.");
344 if (shutdown_type == shutdown_type_t::REBOOT) {
345 log_msg_end(" Will reboot.");
347 else if (shutdown_type == shutdown_type_t::HALT) {
348 log_msg_end(" Will halt.");
350 else if (shutdown_type == shutdown_type_t::POWEROFF) {
351 log_msg_end(" Will power down.");
354 log_msg_end(" Re-initiating boot sequence.");
358 while (! is_log_flushed()) {
362 close_control_socket();
364 if (am_system_init) {
365 if (shutdown_type == shutdown_type_t::CONTINUE) {
366 // It could be that we started in single user mode, and the
367 // user has now exited the shell. We'll try and re-start the
370 services->start_service("boot");
371 goto event_loop; // yes, the "evil" goto
374 // Now what do we do? try to reboot, but wait for user ack to avoid boot loop.
375 log(loglevel_t::ERROR, "Could not start 'boot' service. Will attempt reboot.");
376 wait_for_user_input();
377 shutdown_type = shutdown_type_t::REBOOT;
381 const char * cmd_arg;
382 if (shutdown_type == shutdown_type_t::HALT) {
385 else if (shutdown_type == shutdown_type_t::REBOOT) {
393 // Fork and execute dinit-reboot.
394 execl("/sbin/shutdown", "/sbin/shutdown", "--system", cmd_arg, nullptr);
395 log(loglevel_t::ERROR, "Could not execute /sbin/shutdown: ", strerror(errno));
397 // PID 1 must not actually exit, although we should never reach this point:
402 else if (shutdown_type == shutdown_type_t::REBOOT) {
403 // Non-system-process. If we got SIGINT, let's die due to it:
404 sigset_t sigwait_set;
405 sigemptyset(&sigwait_set);
406 sigaddset(&sigwait_set, SIGINT);
408 sigprocmask(SIG_UNBLOCK, &sigwait_set, NULL);
414 // In exception situations we want user confirmation before proceeding (eg on critical boot failure
415 // we wait before rebooting to avoid a reboot loop).
416 static void wait_for_user_input() noexcept
418 std::cout << "Press Enter to continue." << std::endl;
420 read(STDIN_FILENO, buf, 1);
423 // Callback for control socket
424 static void control_socket_cb(eventloop_t *loop, int sockfd)
426 // Considered keeping a limit the number of active connections, however, there doesn't
427 // seem much to be gained from that. Only root can create connections and not being
428 // able to establish a control connection is as much a denial-of-service as is not being
429 // able to start a service due to lack of fd's.
431 // Accept a connection
432 int newfd = dinit_accept4(sockfd, nullptr, nullptr, SOCK_NONBLOCK | SOCK_CLOEXEC);
436 new control_conn_t(*loop, services, newfd); // will delete itself when it's finished
438 catch (std::exception &exc) {
439 log(loglevel_t::ERROR, "Accepting control connection: ", exc.what());
445 void open_control_socket(bool report_ro_failure) noexcept
447 if (! control_socket_open) {
448 const char * saddrname = control_socket_path;
449 size_t saddrname_len = strlen(saddrname);
450 uint sockaddr_size = offsetof(struct sockaddr_un, sun_path) + saddrname_len + 1;
452 struct sockaddr_un * name = static_cast<sockaddr_un *>(malloc(sockaddr_size));
453 if (name == nullptr) {
454 log(loglevel_t::ERROR, "Opening control socket: out of memory");
458 if (am_system_init) {
459 // Unlink any stale control socket file, but only if we are system init, since otherwise
460 // the 'stale' file may not be stale at all:
464 name->sun_family = AF_UNIX;
465 memcpy(name->sun_path, saddrname, saddrname_len + 1);
467 int sockfd = dinit_socket(AF_UNIX, SOCK_STREAM, 0, SOCK_NONBLOCK | SOCK_CLOEXEC);
469 log(loglevel_t::ERROR, "Error creating control socket: ", strerror(errno));
474 if (bind(sockfd, (struct sockaddr *) name, sockaddr_size) == -1) {
475 if (errno != EROFS || report_ro_failure) {
476 log(loglevel_t::ERROR, "Error binding control socket: ", strerror(errno));
485 // No connections can be made until we listen, so it is fine to change the permissions now
486 // (and anyway there is no way to atomically create the socket and set permissions):
487 if (chmod(saddrname, S_IRUSR | S_IWUSR) == -1) {
488 log(loglevel_t::ERROR, "Error setting control socket permissions: ", strerror(errno));
493 if (listen(sockfd, 10) == -1) {
494 log(loglevel_t::ERROR, "Error listening on control socket: ", strerror(errno));
500 control_socket_io.add_watch(event_loop, sockfd, dasynq::IN_EVENTS);
501 control_socket_open = true;
503 catch (std::exception &e)
505 log(loglevel_t::ERROR, "Could not setup I/O on control socket: ", e.what());
511 static void close_control_socket() noexcept
513 if (control_socket_open) {
514 int fd = control_socket_io.get_watched_fd();
515 control_socket_io.deregister(event_loop);
518 // Unlink the socket:
519 unlink(control_socket_path);
523 void setup_external_log() noexcept
525 if (! external_log_open) {
527 const char * saddrname = log_socket_path;
528 size_t saddrname_len = strlen(saddrname);
529 uint sockaddr_size = offsetof(struct sockaddr_un, sun_path) + saddrname_len + 1;
531 struct sockaddr_un * name = static_cast<sockaddr_un *>(malloc(sockaddr_size));
532 if (name == nullptr) {
533 log(loglevel_t::ERROR, "Connecting to log socket: out of memory");
537 name->sun_family = AF_UNIX;
538 memcpy(name->sun_path, saddrname, saddrname_len + 1);
540 int sockfd = dinit_socket(AF_UNIX, SOCK_DGRAM, 0, SOCK_NONBLOCK | SOCK_CLOEXEC);
542 log(loglevel_t::ERROR, "Error creating log socket: ", strerror(errno));
547 if (connect(sockfd, (struct sockaddr *) name, sockaddr_size) == 0 || errno == EINPROGRESS) {
548 // For EINPROGRESS, connection is still being established; however, we can select on
549 // the file descriptor so we will be notified when it's ready. In other words we can
550 // basically use it anyway.
552 setup_main_log(sockfd);
554 catch (std::exception &e) {
555 log(loglevel_t::ERROR, "Setting up log failed: ", e.what());
560 // Note if connect fails, we haven't warned at all, because the syslog server might not
569 /* handle SIGINT signal (generated by Linux kernel when ctrl+alt+del pressed) */
570 static void sigint_reboot_cb(eventloop_t &eloop) noexcept
572 services->stop_all_services(shutdown_type_t::REBOOT);
575 /* handle SIGQUIT (if we are system init) */
576 static void sigquit_cb(eventloop_t &eloop) noexcept
578 // This performs an immediate shutdown, without service rollback.
579 close_control_socket();
580 execl("/sbin/shutdown", "/sbin/shutdown", "--system", (char *) 0);
581 log(loglevel_t::ERROR, "Error executing /sbin/shutdown: ", strerror(errno));
582 sync(); // since a hard poweroff might be required at this point...
585 /* handle SIGTERM/SIGQUIT(non-system-daemon) - stop all services and shut down */
586 static void sigterm_cb(eventloop_t &eloop) noexcept
588 services->stop_all_services();