Factor out service directory option processing
[oweals/dinit.git] / src / options-processing.cc
1 #include <vector>
2
3 #include <cstring>
4 #include <cstdlib>
5
6 #include <sys/types.h>
7 #include <pwd.h>
8 #include <unistd.h>
9
10 #include "options-processing.h"
11
12 const char *service_dir_opt::user_home_path = nullptr;
13
14 const char * service_dir_opt::get_user_home()
15 {
16     if (user_home_path == nullptr) {
17         user_home_path = getenv("HOME");
18         if (user_home_path == nullptr) {
19             struct passwd * pwuid_p = getpwuid(getuid());
20             if (pwuid_p != nullptr) {
21                 user_home_path = pwuid_p->pw_dir;
22             }
23         }
24     }
25     return user_home_path;
26 }
27
28 void service_dir_opt::build_paths()
29 {
30     /* service directory name */
31     if (service_dir == nullptr && ! am_system_init) {
32         const char * user_home = get_user_home();
33         if (user_home != nullptr) {
34             size_t user_home_len = strlen(user_home);
35             size_t dinit_d_len = strlen("/dinit.d");
36             size_t full_len = user_home_len + dinit_d_len + 1;
37             char *service_dir_w = new char[full_len];
38             std::memcpy(service_dir_w, user_home, user_home_len);
39             std::memcpy(service_dir_w + user_home_len, "/dinit.d", dinit_d_len);
40             service_dir_w[full_len - 1] = 0;
41
42             service_dir = service_dir_w;
43             service_dir_dynamic = true;
44         }
45     }
46
47     bool add_all_service_dirs = false;
48     if (service_dir == nullptr) {
49         service_dir = "/etc/dinit.d";
50         add_all_service_dirs = true;
51     }
52
53     service_dir_paths.add_dir(service_dir, service_dir_dynamic);
54     if (add_all_service_dirs) {
55         service_dir_paths.add_dir("/usr/local/lib/dinit.d", false);
56         service_dir_paths.add_dir("/lib/dinit.d", false);
57     }
58 }