11 #include <sys/socket.h>
19 #include "dinit-log.h"
23 #include <sys/reboot.h>
27 * "simpleinit" from util-linux-ng package handles signals as follows:
28 * SIGTSTP - spawn no more gettys (in preparation for shutdown etc).
29 * In dinit terms this should probably mean "no more auto restarts"
30 * (for any service). (Actually the signal acts as a toggle, if
31 * respawn is disabled it will be re-enabled and init will
32 * act as if SIGHUP had also been sent)
33 * SIGTERM - kill spawned gettys (which are still alive)
34 * Interestingly, simpleinit just sends a SIGTERM to the gettys,
35 * which will not normall kill shells (eg bash ignores SIGTERM).
36 * "/sbin/initctl -r" - rollback services (ran by "shutdown"/halt etc);
37 * shouldn't return until all services have been stopped.
38 * shutdown calls this after sending SIGTERM to processes running
39 * with uid >= 100 ("mortals").
40 * SIGQUIT - init will exec() shutdown. shutdown will detect that it is
41 * running as pid 1 and will just loop and reap child processes.
42 * This is used by shutdown so that init will not hang on to its
43 * inode, allowing the filesystem to be re-mounted readonly
44 * (this is only an issue if the init binary has been unlinked,
45 * since it's then holding an inode which can't be maintained
46 * when the filesystem is unmounted).
48 * Not sent by shutdown:
49 * SIGHUP - re-read inittab and spawn any new getty entries
50 * SIGINT - (ctrl+alt+del handler) - fork & exec "reboot"
52 * On the contrary dinit currently uses:
53 * SIGTERM - roll back services and then fork/exec /sbin/halt
54 * SIGINT - roll back services and then fork/exec /sbin/reboot
55 * SIGQUIT - exec() /sbin/shutdown as per above.
57 * It's an open question about whether dinit should roll back services *before*
58 * running halt/reboot, since those commands should prompt rollback of services
59 * anyway. But it seems safe to do so.
63 static void sigint_reboot_cb(struct ev_loop *loop, ev_signal *w, int revents);
64 static void sigquit_cb(struct ev_loop *loop, ev_signal *w, int revents);
65 static void sigterm_cb(struct ev_loop *loop, ev_signal *w, int revents);
66 void open_control_socket(struct ev_loop *loop) noexcept;
67 void close_control_socket(struct ev_loop *loop) noexcept;
69 struct ev_io control_socket_io;
74 static ServiceSet *service_set;
76 static bool am_system_init = false; // true if we are the system init process
78 static bool control_socket_open = false;
79 int active_control_conns = 0;
81 // Control socket path. We maintain a string (control_socket_str) in case we need
82 // to allocate storage, but control_socket_path is the authoritative value.
83 static const char *control_socket_path = "/dev/dinitctl";
84 static std::string control_socket_str;
86 static const char *user_home_path = nullptr;
89 // Get user home (and set user_home_path). (The return may become invalid after
90 // changing the evironment (HOME variable) or using the getpwuid() function).
91 const char * get_user_home()
93 if (user_home_path == nullptr) {
94 user_home_path = getenv("HOME");
95 if (user_home_path == nullptr) {
96 struct passwd * pwuid_p = getpwuid(getuid());
97 if (pwuid_p != nullptr) {
98 user_home_path = pwuid_p->pw_dir;
102 return user_home_path;
106 int main(int argc, char **argv)
110 am_system_init = (getpid() == 1);
111 const char * service_dir = nullptr;
112 string service_dir_str; // to hold storage for above if necessary
113 bool control_socket_path_set = false;
115 // list of services to start
116 list<const char *> services_to_start;
118 // Arguments, if given, specify a list of services to start.
119 // If we are running as init (PID=1), the kernel gives us any command line
120 // arguments it was given but didn't recognize, including "single" (usually
121 // for "boot to single user mode" aka just start the shell). We can treat
122 // them as service names. In the worst case we can't find any of the named
123 // services, and so we'll start the "boot" service by default.
125 for (int i = 1; i < argc; i++) {
126 if (argv[i][0] == '-') {
128 if (strcmp(argv[i], "--services-dir") == 0 ||
129 strcmp(argv[i], "-d") == 0) {
131 service_dir = argv[i];
134 cerr << "dinit: '--services-dir' (-d) requires an argument" << endl;
138 else if (strcmp(argv[i], "--system") == 0 ||
139 strcmp(argv[i], "-s") == 0) {
140 am_system_init = true;
142 else if (strcmp(argv[i], "--socket-path") == 0 ||
143 strcmp(argv[i], "-p") == 0) {
145 control_socket_path = argv[i];
146 control_socket_path_set = true;
149 cerr << "dinit: '--socket-path' (-p) requires an argument" << endl;
153 else if (strcmp(argv[i], "--help") == 0) {
154 cout << "dinit, an init with dependency management" << endl;
155 cout << " --help display help" << endl;
156 cout << " --services-dir <dir>, -d <dir>" << endl;
157 cout << " set base directory for service description" << endl;
158 cout << " files (-d <dir>)" << endl;
159 cout << " --system, -s run as the system init process" << endl;
160 cout << " --socket-path <path>, -p <path>" << endl;
161 cout << " path to control socket" << endl;
162 cout << " <service-name> start service with name <service-name>" << endl;
167 if (! am_system_init) {
168 cerr << "dinit: Unrecognized option: " << argv[i] << endl;
174 // LILO puts "auto" on the kernel command line for unattended boots; we'll filter it.
175 if (! am_system_init || strcmp(argv[i], "auto") != 0) {
176 services_to_start.push_back(argv[i]);
182 if (am_system_init) {
183 // setup STDIN, STDOUT, STDERR so that we can use them
184 int onefd = open("/dev/console", O_RDONLY, 0);
186 int twofd = open("/dev/console", O_RDWR, 0);
190 if (onefd > 2) close(onefd);
191 if (twofd > 2) close(twofd);
194 /* Set up signal handlers etc */
195 /* SIG_CHILD is ignored by default: good */
196 /* sigemptyset(&sigwait_set); */
197 /* sigaddset(&sigwait_set, SIGCHLD); */
198 /* sigaddset(&sigwait_set, SIGINT); */
199 /* sigaddset(&sigwait_set, SIGTERM); */
200 /* sigprocmask(SIG_BLOCK, &sigwait_set, NULL); */
202 // Terminal access control signals - we block these so that dinit can't be
203 // suspended if it writes to the terminal after some other process has claimed
205 signal(SIGTSTP, SIG_IGN);
206 signal(SIGTTIN, SIG_IGN);
207 signal(SIGTTOU, SIG_IGN);
209 if (! am_system_init && ! control_socket_path_set) {
210 const char * userhome = get_user_home();
211 if (userhome != nullptr) {
212 control_socket_str = userhome;
213 control_socket_str += "/.dinitctl";
214 control_socket_path = control_socket_str.c_str();
218 /* service directory name */
219 if (service_dir == nullptr && ! am_system_init) {
220 const char * userhome = get_user_home();
221 if (userhome != nullptr) {
222 service_dir_str = get_user_home();
223 service_dir_str += "/dinit.d";
224 service_dir = service_dir_str.c_str();
228 if (service_dir == nullptr) {
229 service_dir = "/etc/dinit.d";
232 if (services_to_start.empty()) {
233 services_to_start.push_back("boot");
236 // Set up signal handlers
237 ev_signal sigint_ev_signal;
238 if (am_system_init) {
239 ev_signal_init(&sigint_ev_signal, sigint_reboot_cb, SIGINT);
242 ev_signal_init(&sigint_ev_signal, sigterm_cb, SIGINT);
245 ev_signal sigquit_ev_signal;
246 if (am_system_init) {
247 // PID 1: SIGQUIT exec's shutdown
248 ev_signal_init(&sigquit_ev_signal, sigquit_cb, SIGQUIT);
251 // Otherwise: SIGQUIT terminates dinit
252 ev_signal_init(&sigquit_ev_signal, sigterm_cb, SIGQUIT);
255 ev_signal sigterm_ev_signal;
256 ev_signal_init(&sigterm_ev_signal, sigterm_cb, SIGTERM);
259 struct ev_loop *loop = ev_default_loop(EVFLAG_AUTO /* | EVFLAG_SIGNALFD */);
260 ev_signal_start(loop, &sigint_ev_signal);
261 ev_signal_start(loop, &sigquit_ev_signal);
262 ev_signal_start(loop, &sigterm_ev_signal);
264 // Try to open control socket (may fail due to readonly filesystem)
265 open_control_socket(loop);
268 if (am_system_init) {
269 // Disable non-critical kernel output to console
270 klogctl(6 /* SYSLOG_ACTION_CONSOLE_OFF */, nullptr, 0);
271 // Make ctrl+alt+del combination send SIGINT to PID 1 (this process)
272 reboot(RB_DISABLE_CAD);
276 /* start requested services */
277 service_set = new ServiceSet(service_dir);
278 for (list<const char *>::iterator i = services_to_start.begin();
279 i != services_to_start.end();
282 service_set->startService(*i);
284 catch (ServiceNotFound &snf) {
285 log(LogLevel::ERROR, snf.serviceName, ": Could not find service description.");
287 catch (ServiceLoadExc &sle) {
288 log(LogLevel::ERROR, sle.serviceName, ": ", sle.excDescription);
290 catch (std::bad_alloc &badalloce) {
291 log(LogLevel::ERROR, "Out of memory when trying to start service: ", *i, ".");
297 // Process events until all services have terminated.
298 while (service_set->count_active_services() != 0) {
299 ev_loop(loop, EVLOOP_ONESHOT);
302 ShutdownType shutdown_type = service_set->getShutdownType();
304 if (am_system_init) {
305 logMsgBegin(LogLevel::INFO, "No more active services.");
307 if (shutdown_type == ShutdownType::REBOOT) {
308 logMsgEnd(" Will reboot.");
310 else if (shutdown_type == ShutdownType::HALT) {
311 logMsgEnd(" Will halt.");
313 else if (shutdown_type == ShutdownType::POWEROFF) {
314 logMsgEnd(" Will power down.");
317 logMsgEnd(" Re-initiating boot sequence.");
321 close_control_socket(ev_default_loop(EVFLAG_AUTO));
323 if (am_system_init) {
324 if (shutdown_type == ShutdownType::CONTINUE) {
325 // It could be that we started in single user mode, and the
326 // user has now exited the shell. We'll try and re-start the
329 service_set->startService("boot");
330 goto event_loop; // yes, the "evil" goto
333 // Now WTF do we do? try to reboot
334 log(LogLevel::ERROR, "Could not start 'boot' service; rebooting.");
335 shutdown_type = ShutdownType::REBOOT;
339 const char * cmd_arg;
340 if (shutdown_type == ShutdownType::HALT) {
343 else if (shutdown_type == ShutdownType::REBOOT) {
351 // Fork and execute dinit-reboot.
352 execl("/sbin/shutdown", "/sbin/shutdown", "--system", cmd_arg, nullptr);
353 log(LogLevel::ERROR, "Could not execute /sbin/shutdown: ", strerror(errno));
355 // PID 1 must not actually exit, although we should never reach this point:
357 ev_loop(loop, EVLOOP_ONESHOT);
364 // Callback for control socket
365 static void control_socket_cb(struct ev_loop *loop, ev_io *w, int revents)
367 // TODO limit the number of active connections. Keep a tally, and disable the
368 // control connection listening socket watcher if it gets high, and re-enable
369 // it once it falls below the maximum.
371 // Accept a connection
374 int newfd = accept4(sockfd, nullptr, nullptr, SOCK_NONBLOCK | SOCK_CLOEXEC);
378 new ControlConn(loop, service_set, newfd); // will delete itself when it's finished
380 catch (std::bad_alloc &bad_alloc_exc) {
381 log(LogLevel::ERROR, "Accepting control connection: Out of memory");
387 void open_control_socket(struct ev_loop *loop) noexcept
389 if (! control_socket_open) {
390 const char * saddrname = control_socket_path;
391 uint sockaddr_size = offsetof(struct sockaddr_un, sun_path) + strlen(saddrname) + 1;
393 struct sockaddr_un * name = static_cast<sockaddr_un *>(malloc(sockaddr_size));
394 if (name == nullptr) {
395 log(LogLevel::ERROR, "Opening control socket: out of memory");
399 if (am_system_init) {
400 // Unlink any stale control socket file, but only if we are system init, since otherwise
401 // the 'stale' file may not be stale at all:
405 name->sun_family = AF_UNIX;
406 strcpy(name->sun_path, saddrname);
408 // OpenBSD and Linux both allow combining NONBLOCK/CLOEXEC flags with socket type, however
409 // it's not actually POSIX. (TODO).
410 int sockfd = socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
412 log(LogLevel::ERROR, "Error creating control socket: ", strerror(errno));
417 if (bind(sockfd, (struct sockaddr *) name, sockaddr_size) == -1) {
418 log(LogLevel::ERROR, "Error binding control socket: ", strerror(errno));
426 // No connections can be made until we listen, so it is fine to change the permissions now
427 // (and anyway there is no way to atomically create the socket and set permissions):
428 if (chmod(saddrname, S_IRUSR | S_IWUSR) == -1) {
429 log(LogLevel::ERROR, "Error setting control socket permissions: ", strerror(errno));
434 if (listen(sockfd, 10) == -1) {
435 log(LogLevel::ERROR, "Error listening on control socket: ", strerror(errno));
440 control_socket_open = true;
441 ev_io_init(&control_socket_io, control_socket_cb, sockfd, EV_READ);
442 ev_io_start(loop, &control_socket_io);
446 void close_control_socket(struct ev_loop *loop) noexcept
448 if (control_socket_open) {
449 int fd = control_socket_io.fd;
450 ev_io_stop(loop, &control_socket_io);
453 // Unlink the socket:
454 unlink(control_socket_path);
458 /* handle SIGINT signal (generated by kernel when ctrl+alt+del pressed) */
459 static void sigint_reboot_cb(struct ev_loop *loop, ev_signal *w, int revents)
461 log_to_console = true;
462 service_set->stop_all_services(ShutdownType::REBOOT);
465 /* handle SIGQUIT (if we are system init) */
466 static void sigquit_cb(struct ev_loop *loop, ev_signal *w, int revents)
468 // This allows remounting the filesystem read-only if the dinit binary has been
469 // unlinked. In that case the kernel holds the binary open, so that it can't be
471 close_control_socket(ev_default_loop(EVFLAG_AUTO));
472 execl("/sbin/shutdown", "/sbin/shutdown", (char *) 0);
473 log(LogLevel::ERROR, "Error executing /sbin/shutdown: ", strerror(errno));
476 /* handle SIGTERM/SIGQUIT - stop all services (not used for system daemon) */
477 static void sigterm_cb(struct ev_loop *loop, ev_signal *w, int revents)
479 log_to_console = true;
480 service_set->stop_all_services();