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);
279 init_log(service_set);
281 for (list<const char *>::iterator i = services_to_start.begin();
282 i != services_to_start.end();
285 service_set->startService(*i);
287 catch (ServiceNotFound &snf) {
288 log(LogLevel::ERROR, snf.serviceName, ": Could not find service description.");
290 catch (ServiceLoadExc &sle) {
291 log(LogLevel::ERROR, sle.serviceName, ": ", sle.excDescription);
293 catch (std::bad_alloc &badalloce) {
294 log(LogLevel::ERROR, "Out of memory when trying to start service: ", *i, ".");
300 // Process events until all services have terminated.
301 while (service_set->count_active_services() != 0) {
302 ev_loop(loop, EVLOOP_ONESHOT);
305 ShutdownType shutdown_type = service_set->getShutdownType();
307 if (am_system_init) {
308 logMsgBegin(LogLevel::INFO, "No more active services.");
310 if (shutdown_type == ShutdownType::REBOOT) {
311 logMsgEnd(" Will reboot.");
313 else if (shutdown_type == ShutdownType::HALT) {
314 logMsgEnd(" Will halt.");
316 else if (shutdown_type == ShutdownType::POWEROFF) {
317 logMsgEnd(" Will power down.");
320 logMsgEnd(" Re-initiating boot sequence.");
324 close_control_socket(ev_default_loop(EVFLAG_AUTO));
326 if (am_system_init) {
327 if (shutdown_type == ShutdownType::CONTINUE) {
328 // It could be that we started in single user mode, and the
329 // user has now exited the shell. We'll try and re-start the
332 service_set->startService("boot");
333 goto event_loop; // yes, the "evil" goto
336 // Now WTF do we do? try to reboot
337 log(LogLevel::ERROR, "Could not start 'boot' service; rebooting.");
338 shutdown_type = ShutdownType::REBOOT;
342 const char * cmd_arg;
343 if (shutdown_type == ShutdownType::HALT) {
346 else if (shutdown_type == ShutdownType::REBOOT) {
354 // Fork and execute dinit-reboot.
355 execl("/sbin/shutdown", "/sbin/shutdown", "--system", cmd_arg, nullptr);
356 log(LogLevel::ERROR, "Could not execute /sbin/shutdown: ", strerror(errno));
358 // PID 1 must not actually exit, although we should never reach this point:
360 ev_loop(loop, EVLOOP_ONESHOT);
367 // Callback for control socket
368 static void control_socket_cb(struct ev_loop *loop, ev_io *w, int revents)
370 // TODO limit the number of active connections. Keep a tally, and disable the
371 // control connection listening socket watcher if it gets high, and re-enable
372 // it once it falls below the maximum.
374 // Accept a connection
377 int newfd = accept4(sockfd, nullptr, nullptr, SOCK_NONBLOCK | SOCK_CLOEXEC);
381 new ControlConn(loop, service_set, newfd); // will delete itself when it's finished
383 catch (std::bad_alloc &bad_alloc_exc) {
384 log(LogLevel::ERROR, "Accepting control connection: Out of memory");
390 void open_control_socket(struct ev_loop *loop) noexcept
392 if (! control_socket_open) {
393 const char * saddrname = control_socket_path;
394 uint sockaddr_size = offsetof(struct sockaddr_un, sun_path) + strlen(saddrname) + 1;
396 struct sockaddr_un * name = static_cast<sockaddr_un *>(malloc(sockaddr_size));
397 if (name == nullptr) {
398 log(LogLevel::ERROR, "Opening control socket: out of memory");
402 if (am_system_init) {
403 // Unlink any stale control socket file, but only if we are system init, since otherwise
404 // the 'stale' file may not be stale at all:
408 name->sun_family = AF_UNIX;
409 strcpy(name->sun_path, saddrname);
411 // OpenBSD and Linux both allow combining NONBLOCK/CLOEXEC flags with socket type, however
412 // it's not actually POSIX. (TODO).
413 int sockfd = socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
415 log(LogLevel::ERROR, "Error creating control socket: ", strerror(errno));
420 if (bind(sockfd, (struct sockaddr *) name, sockaddr_size) == -1) {
421 log(LogLevel::ERROR, "Error binding control socket: ", strerror(errno));
429 // No connections can be made until we listen, so it is fine to change the permissions now
430 // (and anyway there is no way to atomically create the socket and set permissions):
431 if (chmod(saddrname, S_IRUSR | S_IWUSR) == -1) {
432 log(LogLevel::ERROR, "Error setting control socket permissions: ", strerror(errno));
437 if (listen(sockfd, 10) == -1) {
438 log(LogLevel::ERROR, "Error listening on control socket: ", strerror(errno));
443 control_socket_open = true;
444 ev_io_init(&control_socket_io, control_socket_cb, sockfd, EV_READ);
445 ev_io_start(loop, &control_socket_io);
449 void close_control_socket(struct ev_loop *loop) noexcept
451 if (control_socket_open) {
452 int fd = control_socket_io.fd;
453 ev_io_stop(loop, &control_socket_io);
456 // Unlink the socket:
457 unlink(control_socket_path);
461 /* handle SIGINT signal (generated by kernel when ctrl+alt+del pressed) */
462 static void sigint_reboot_cb(struct ev_loop *loop, ev_signal *w, int revents)
464 service_set->stop_all_services(ShutdownType::REBOOT);
467 /* handle SIGQUIT (if we are system init) */
468 static void sigquit_cb(struct ev_loop *loop, ev_signal *w, int revents)
470 // This allows remounting the filesystem read-only if the dinit binary has been
471 // unlinked. In that case the kernel holds the binary open, so that it can't be
473 close_control_socket(ev_default_loop(EVFLAG_AUTO));
474 execl("/sbin/shutdown", "/sbin/shutdown", (char *) 0);
475 log(LogLevel::ERROR, "Error executing /sbin/shutdown: ", strerror(errno));
478 /* handle SIGTERM/SIGQUIT - stop all services (not used for system daemon) */
479 static void sigterm_cb(struct ev_loop *loop, ev_signal *w, int revents)
481 service_set->stop_all_services();