Read environment from file at startup.
[oweals/dinit.git] / src / dinit.cc
1 #include <iostream>
2 #include <fstream>
3 #include <list>
4 #include <cstring>
5 #include <csignal>
6 #include <cstddef>
7 #include <cstdlib>
8
9 #include <sys/types.h>
10 #include <sys/stat.h>
11 #include <sys/un.h>
12 #include <sys/socket.h>
13 #include <unistd.h>
14 #include <fcntl.h>
15 #include <pwd.h>
16 #ifdef __linux__
17 #include <sys/prctl.h>
18 #include <sys/klog.h>
19 #include <sys/reboot.h>
20 #endif
21 #if defined(__FreeBSD__) || defined(__DragonFly__)
22 #include <sys/procctl.h>
23 #endif
24
25 #include "dinit.h"
26 #include "dasynq.h"
27 #include "service.h"
28 #include "control.h"
29 #include "dinit-log.h"
30 #include "dinit-socket.h"
31
32 /*
33  * When running as the system init process, Dinit processes the following signals:
34  *
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
38  *
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.
43  */
44
45 using eventloop_t = dasynq::event_loop<dasynq::null_mutex>;
46
47 eventloop_t event_loop;
48
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 *);
55
56 static void control_socket_cb(eventloop_t *loop, int fd);
57
58
59 // Variables
60
61 static dirload_service_set *services;
62
63 static bool am_system_init = false; // true if we are the system init process
64
65 static bool control_socket_open = false;
66 static bool external_log_open = false;
67 int active_control_conns = 0;
68
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;
73
74 static const char *env_file_path = "/etc/dinit/environment";
75
76 static const char *log_socket_path = "/dev/log";
77
78 static const char *user_home_path = nullptr;
79
80
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()
84 {
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;
91             }
92         }
93     }
94     return user_home_path;
95 }
96
97
98 namespace {
99     class callback_signal_handler : public eventloop_t::signal_watcher_impl<callback_signal_handler>
100     {
101         using rearm = dasynq::rearm;
102
103         public:
104         typedef void (*cb_func_t)(eventloop_t &);
105         
106         private:
107         cb_func_t cb_func;
108         
109         public:
110         callback_signal_handler() : cb_func(nullptr) { }
111         callback_signal_handler(cb_func_t pcb_func) :  cb_func(pcb_func) { }
112         
113         void setCbFunc(cb_func_t cb_func)
114         {
115             this->cb_func = cb_func;
116         }
117         
118         rearm received(eventloop_t &eloop, int signo, siginfo_p siginfo)
119         {
120             cb_func(eloop);
121             return rearm::REARM;
122         }
123     };
124
125     class control_socket_watcher : public eventloop_t::fd_watcher_impl<control_socket_watcher>
126     {
127         using rearm = dasynq::rearm;
128
129         public:
130         rearm fd_event(eventloop_t &loop, int fd, int flags) noexcept
131         {
132             control_socket_cb(&loop, fd);
133             return rearm::REARM;
134         }
135     };
136
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>
139     {
140         using rearm = dasynq::rearm;
141
142         bool expired = false;
143
144         public:
145         rearm timer_expiry(eventloop_t &, int expiry_count)
146         {
147             expired = true;
148             return rearm::DISARM;
149         }
150
151         bool has_expired()
152         {
153             return expired;
154         }
155     };
156
157     control_socket_watcher control_socket_io;
158     log_flush_timer_t log_flush_timer;
159 }
160
161 int dinit_main(int argc, char **argv)
162 {
163     using namespace std;
164     
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;
171
172     // list of services to start
173     list<const char *> services_to_start;
174     
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.
180     if (argc > 1) {
181       for (int i = 1; i < argc; i++) {
182         if (argv[i][0] == '-') {
183             // An option...
184             if (strcmp(argv[i], "--env-file") == 0 || strcmp(argv[i], "-e") == 0) {
185                 if (++i < argc) {
186                     env_file_set = true;
187                     env_file = argv[i];
188                 }
189                 else {
190                     cerr << "dinit: '--env-file' (-e) requires an argument" << endl;
191                 }
192             }
193             else if (strcmp(argv[i], "--services-dir") == 0 || strcmp(argv[i], "-d") == 0) {
194                 if (++i < argc) {
195                     service_dir = argv[i];
196                 }
197                 else {
198                     cerr << "dinit: '--services-dir' (-d) requires an argument" << endl;
199                     return 1;
200                 }
201             }
202             else if (strcmp(argv[i], "--system") == 0 || strcmp(argv[i], "-s") == 0) {
203                 am_system_init = true;
204             }
205             else if (strcmp(argv[i], "--socket-path") == 0 || strcmp(argv[i], "-p") == 0) {
206                 if (++i < argc) {
207                     control_socket_path = argv[i];
208                     control_socket_path_set = true;
209                 }
210                 else {
211                     cerr << "dinit: '--socket-path' (-p) requires an argument" << endl;
212                     return 1;
213                 }
214             }
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;
227                 return 0;
228             }
229             else {
230                 // unrecognized
231                 if (! am_system_init) {
232                     cerr << "dinit: Unrecognized option: " << argv[i] << endl;
233                     return 1;
234                 }
235             }
236         }
237         else {
238 #ifdef __linux__
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]);
242             }
243 #else
244             services_to_start.push_back(argv[i]);
245 #endif
246         }
247       }
248     }
249     
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);
253         dup2(onefd, 0);
254         int twofd = open("/dev/console", O_RDWR, 0);
255         dup2(twofd, 1);
256         dup2(twofd, 2);
257         
258         if (onefd > 2) close(onefd);
259         if (twofd > 2) close(twofd);
260
261         if (! env_file_set) {
262             env_file = env_file_path;
263         }
264     }
265
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);
275
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
278     // ownership of it.
279     signal(SIGTSTP, SIG_IGN);
280     signal(SIGTTIN, SIG_IGN);
281     signal(SIGTTOU, SIG_IGN);
282     
283     signal(SIGPIPE, SIG_IGN);
284     
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();
291         }
292     }
293     
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();
301         }
302     }
303     
304     if (service_dir == nullptr) {
305         service_dir = "/etc/dinit.d";
306     }
307     
308     if (services_to_start.empty()) {
309         services_to_start.push_back("boot");
310     }
311
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;
316
317     if (am_system_init) {
318         sigint_watcher.setCbFunc(sigint_reboot_cb);
319         sigquit_watcher.setCbFunc(sigquit_cb);
320     }
321     else {
322         sigint_watcher.setCbFunc(sigterm_cb);
323     }
324
325     sigint_watcher.add_watch(event_loop, SIGINT);
326     sigterm_watcher.add_watch(event_loop, SIGTERM);
327     
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.
332     }
333
334     // Try to open control socket (may fail due to readonly filesystem)
335     open_control_socket(false);
336     
337 #ifdef __linux__
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);
343     }
344
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);
348 #endif
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);
354 #endif
355     
356     log_flush_timer.add_timer(event_loop, dasynq::clock_type::MONOTONIC);
357
358     /* start requested services */
359     services = new dirload_service_set(service_dir);
360     
361     init_log(services);
362     
363     if (env_file != nullptr) {
364         read_env_file(env_file);
365     }
366
367     for (auto svc : services_to_start) {
368         try {
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).
374         }
375         catch (service_not_found &snf) {
376             log(loglevel_t::ERROR, snf.serviceName, ": Could not find service description.");
377         }
378         catch (service_load_exc &sle) {
379             log(loglevel_t::ERROR, sle.serviceName, ": ", sle.excDescription);
380         }
381         catch (std::bad_alloc &badalloce) {
382             log(loglevel_t::ERROR, "Out of memory when trying to start service: ", svc, ".");
383             break;
384         }
385     }
386     
387     event_loop:
388     
389     // Process events until all services have terminated.
390     while (services->count_active_services() != 0) {
391         event_loop.run();
392     }
393
394     shutdown_type_t shutdown_type = services->get_shutdown_type();
395     
396     if (am_system_init) {
397         log_msg_begin(loglevel_t::INFO, "No more active services.");
398         
399         if (shutdown_type == shutdown_type_t::REBOOT) {
400             log_msg_end(" Will reboot.");
401         }
402         else if (shutdown_type == shutdown_type_t::HALT) {
403             log_msg_end(" Will halt.");
404         }
405         else if (shutdown_type == shutdown_type_t::POWEROFF) {
406             log_msg_end(" Will power down.");
407         }
408         else {
409             log_msg_end(" Re-initiating boot sequence.");
410         }
411     }
412     
413     log_flush_timer.arm_timer_rel(event_loop, timespec{5,0}); // 5 seconds
414     while (! is_log_flushed() && ! log_flush_timer.has_expired()) {
415         event_loop.run();
416     }
417     
418     close_control_socket();
419     
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
424             // boot process...
425             try {
426                 services->start_service("boot");
427                 goto event_loop; // yes, the "evil" goto
428             }
429             catch (...) {
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;
434             }
435         }
436         
437         const char * cmd_arg;
438         if (shutdown_type == shutdown_type_t::HALT) {
439             cmd_arg = "-h";
440         }
441         else if (shutdown_type == shutdown_type_t::REBOOT) {
442             cmd_arg = "-r";
443         }
444         else {
445             // power off.
446             cmd_arg = "-p";
447         }
448         
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));
452         
453         // PID 1 must not actually exit, although we should never reach this point:
454         while (true) {
455             event_loop.run();
456         }
457     }
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);
463         raise(SIGINT);
464         sigprocmask(SIG_UNBLOCK, &sigwait_set, NULL);
465     }
466     
467     return 0;
468 }
469
470 static void log_bad_env(int linenum)
471 {
472     log(loglevel_t::ERROR, "invalid environment variable setting in environment file (line ", linenum, ")");
473 }
474
475 // Read and set environment variables from a file.
476 static void read_env_file(const char *env_file_path)
477 {
478     // Note that we can't use the log in this function; it hasn't been initialised yet.
479
480     std::ifstream env_file(env_file_path);
481     if (! env_file) return;
482
483     env_file.exceptions(std::ios::badbit);
484
485     auto &clocale = std::locale::classic();
486     std::string line;
487     int linenum = 0;
488
489     while (std::getline(env_file, line)) {
490         linenum++;
491         auto lpos = line.begin();
492         auto lend = line.end();
493         while (lpos != lend && std::isspace(*lpos, clocale)) {
494             ++lpos;
495         }
496
497         if (lpos != lend) {
498             if (*lpos != '#') {
499                 if (*lpos == '=') {
500                     log_bad_env(linenum);
501                     continue;
502                 }
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;
507                 //  skip whitespace:
508                 while (lpos != lend && std::isspace(*lpos, clocale)) ++lpos;
509                 if (lpos == lend) {
510                     log_bad_env(linenum);
511                     continue;
512                 }
513
514                 ++lpos;
515                 auto val_begin = lpos;
516                 while (lpos != lend && *lpos != '\n') ++lpos;
517                 auto val_end = lpos;
518
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());
523                 }
524             }
525         }
526     }
527 }
528
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
532 {
533     std::cout << "Press Enter to continue." << std::endl;
534     char buf[1];
535     read(STDIN_FILENO, buf, 1);
536 }
537
538 // Callback for control socket
539 static void control_socket_cb(eventloop_t *loop, int sockfd)
540 {
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.
545
546     // Accept a connection
547     int newfd = dinit_accept4(sockfd, nullptr, nullptr, SOCK_NONBLOCK | SOCK_CLOEXEC);
548
549     if (newfd != -1) {
550         try {
551             new control_conn_t(*loop, services, newfd);  // will delete itself when it's finished
552         }
553         catch (std::exception &exc) {
554             log(loglevel_t::ERROR, "Accepting control connection: ", exc.what());
555             close(newfd);
556         }
557     }
558 }
559
560 void open_control_socket(bool report_ro_failure) noexcept
561 {
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;
566         
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");
570             return;
571         }
572
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:
576             unlink(saddrname);
577         }
578
579         name->sun_family = AF_UNIX;
580         memcpy(name->sun_path, saddrname, saddrname_len + 1);
581
582         int sockfd = dinit_socket(AF_UNIX, SOCK_STREAM, 0, SOCK_NONBLOCK | SOCK_CLOEXEC);
583         if (sockfd == -1) {
584             log(loglevel_t::ERROR, "Error creating control socket: ", strerror(errno));
585             free(name);
586             return;
587         }
588
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));
592             }
593             close(sockfd);
594             free(name);
595             return;
596         }
597         
598         free(name);
599
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));
604             close(sockfd);
605             return;
606         }
607
608         if (listen(sockfd, 10) == -1) {
609             log(loglevel_t::ERROR, "Error listening on control socket: ", strerror(errno));
610             close(sockfd);
611             return;
612         }
613
614         try {
615             control_socket_io.add_watch(event_loop, sockfd, dasynq::IN_EVENTS);
616             control_socket_open = true;
617         }
618         catch (std::exception &e)
619         {
620             log(loglevel_t::ERROR, "Could not setup I/O on control socket: ", e.what());
621             close(sockfd);
622         }
623     }
624 }
625
626 static void close_control_socket() noexcept
627 {
628     if (control_socket_open) {
629         int fd = control_socket_io.get_watched_fd();
630         control_socket_io.deregister(event_loop);
631         close(fd);
632         
633         // Unlink the socket:
634         unlink(control_socket_path);
635     }
636 }
637
638 void setup_external_log() noexcept
639 {
640     if (! external_log_open) {
641     
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;
645         
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");
649             return;
650         }
651         
652         name->sun_family = AF_UNIX;
653         memcpy(name->sun_path, saddrname, saddrname_len + 1);
654         
655         int sockfd = dinit_socket(AF_UNIX, SOCK_DGRAM, 0, SOCK_NONBLOCK | SOCK_CLOEXEC);
656         if (sockfd == -1) {
657             log(loglevel_t::ERROR, "Error creating log socket: ", strerror(errno));
658             free(name);
659             return;
660         }
661         
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.
666             try {
667                 setup_main_log(sockfd);
668             }
669             catch (std::exception &e) {
670                 log(loglevel_t::ERROR, "Setting up log failed: ", e.what());
671                 close(sockfd);
672             }
673         }
674         else {
675             // Note if connect fails, we haven't warned at all, because the syslog server might not
676             // have started yet.
677             close(sockfd);
678         }
679         
680         free(name);
681     }
682 }
683
684 /* handle SIGINT signal (generated by Linux kernel when ctrl+alt+del pressed) */
685 static void sigint_reboot_cb(eventloop_t &eloop) noexcept
686 {
687     services->stop_all_services(shutdown_type_t::REBOOT);
688 }
689
690 /* handle SIGQUIT (if we are system init) */
691 static void sigquit_cb(eventloop_t &eloop) noexcept
692 {
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...
698 }
699
700 /* handle SIGTERM/SIGQUIT(non-system-daemon) - stop all services and shut down */
701 static void sigterm_cb(eventloop_t &eloop) noexcept
702 {
703     services->stop_all_services();
704 }