dinitcheck.cc 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <fstream>
  4. #include <cstring>
  5. #include <string>
  6. #include <vector>
  7. #include <list>
  8. #include <map>
  9. #include <sys/types.h>
  10. #include <sys/stat.h>
  11. #include <sys/time.h>
  12. #include <sys/resource.h>
  13. #include <sys/socket.h>
  14. #include <sys/un.h>
  15. #include <signal.h>
  16. #include <unistd.h>
  17. #include <pwd.h>
  18. #include <dirent.h>
  19. #include "dinit-util.h"
  20. #include "dinit-client.h"
  21. #include "service-constants.h"
  22. #include "load-service.h"
  23. #include "options-processing.h"
  24. // dinitcheck: utility to check Dinit configuration for correctness/lint
  25. using string = std::string;
  26. using string_iterator = std::string::iterator;
  27. static constexpr uint16_t min_cp_version = 1;
  28. static constexpr uint16_t max_cp_version = 1;
  29. static void report_service_description_err(const std::string &service_name, const std::string &what);
  30. // prelim_dep: A preliminary (unresolved) service dependency
  31. class prelim_dep
  32. {
  33. public:
  34. std::string name;
  35. dependency_type dep_type;
  36. prelim_dep(const std::string &name_p, dependency_type dep_type_p)
  37. : name(name_p), dep_type(dep_type_p) { }
  38. prelim_dep(std::string &&name_p, dependency_type dep_type_p)
  39. : name(std::move(name_p)), dep_type(dep_type_p) { }
  40. };
  41. class service_record
  42. {
  43. public:
  44. service_record(const std::string &name_p, const std::string &chain_to_p,
  45. std::list<prelim_dep> dependencies_p, const std::list<string> &before_svcs, const std::list<string> &after_svcs,
  46. std::string consumer_of_name, log_type_id log_type)
  47. : name(name_p), dependencies(dependencies_p), before_svcs(before_svcs), after_svcs(after_svcs),
  48. consumer_of_name(consumer_of_name), log_type(log_type)
  49. {
  50. // (constructor)
  51. }
  52. std::string name;
  53. std::string chain_to;
  54. std::list<prelim_dep> dependencies;
  55. std::list<string> before_svcs;
  56. std::list<string> after_svcs;
  57. std::string consumer_of_name;
  58. log_type_id log_type;
  59. bool visited = false; // flag used to detect cyclic dependencies
  60. bool cycle_free = false;
  61. };
  62. using service_set_t = std::map<std::string, service_record *>;
  63. service_record *load_service(service_set_t &services, const std::string &name,
  64. const service_dir_pathlist &service_dirs);
  65. // Add some missing standard library functionality...
  66. template <typename T> bool contains(std::vector<T> vec, const T& elem)
  67. {
  68. return std::find(vec.begin(), vec.end(), elem) != vec.end();
  69. }
  70. static bool errors_found = false;
  71. static bool offline_operation = true;
  72. // environment - populated from running dinit instance if possible
  73. environment menv;
  74. // Get the environment from remote dinit instance
  75. static void get_remote_env(int csfd, cpbuffer_t &rbuffer)
  76. {
  77. char buf[2] = { (char)cp_cmd::GETALLENV, 0 };
  78. write_all_x(csfd, buf, 2);
  79. wait_for_reply(rbuffer, csfd);
  80. if (rbuffer[0] != (char)cp_rply::ALLENV) {
  81. throw dinit_protocol_error();
  82. }
  83. // 1-byte packet header, then size_t data size
  84. constexpr size_t allenv_hdr_size = 1 + sizeof(size_t);
  85. rbuffer.fill_to(csfd, allenv_hdr_size);
  86. size_t data_size;
  87. rbuffer.extract(&data_size, 1, sizeof(data_size));
  88. rbuffer.consume(allenv_hdr_size);
  89. if (data_size == 0) return;
  90. if (rbuffer.get_length() == 0) {
  91. fill_some(rbuffer, csfd);
  92. }
  93. std::string env_var;
  94. while (data_size > 0) {
  95. // look for a nul terminator
  96. get_var:
  97. unsigned contig_len = rbuffer.get_contiguous_length(rbuffer.get_ptr(0));
  98. unsigned check_len = std::min((size_t) contig_len, data_size);
  99. for (unsigned i = 0; i < check_len; ++i) {
  100. if (rbuffer[i] == '\0') {
  101. // append the last portion
  102. env_var.append(rbuffer.get_ptr(0), rbuffer.get_ptr(0) + i);
  103. rbuffer.consume(i + 1);
  104. data_size -= (i + 1);
  105. menv.set_var(std::move(env_var));
  106. env_var.clear();
  107. if (data_size == 0) {
  108. // that's the last one
  109. return;
  110. }
  111. goto get_var;
  112. }
  113. }
  114. // copy what we have so far to the string, and fill some more
  115. env_var.append(rbuffer.get_ptr(0), rbuffer.get_ptr(0) + check_len);
  116. rbuffer.consume(check_len);
  117. data_size -= check_len;
  118. if (data_size == 0) {
  119. // This shouldn't happen, we didn't find the nul terminator at the end
  120. throw dinit_protocol_error();
  121. }
  122. if (rbuffer.get_length() == 0) {
  123. fill_some(rbuffer, csfd);
  124. }
  125. }
  126. }
  127. int main(int argc, char **argv)
  128. {
  129. using namespace std;
  130. service_dir_opt service_dir_opts;
  131. bool user_dinit = (getuid() != 0); // use user instance defaults/daemon instance
  132. std::string control_socket_str;
  133. const char * control_socket_path = nullptr;
  134. std::string env_file;
  135. std::vector<std::string> services_to_check;
  136. // Process command line
  137. if (argc > 1) {
  138. for (int i = 1; i < argc; i++) {
  139. if (argv[i][0] == '-') {
  140. // An option...
  141. if (strcmp(argv[i], "--services-dir") == 0 || strcmp(argv[i], "-d") == 0) {
  142. if (++i < argc && argv[i][0] != '\0') {
  143. service_dir_opts.set_specified_service_dir(argv[i]);
  144. }
  145. else {
  146. cerr << "dinitcheck: '--services-dir' (-d) requires an argument" << endl;
  147. return 1;
  148. }
  149. }
  150. else if (strcmp(argv[i], "--system") == 0 || strcmp(argv[i], "-s") == 0) {
  151. user_dinit = false;
  152. }
  153. else if (strcmp(argv[i], "--user") == 0 || strcmp(argv[i], "-u") == 0) {
  154. user_dinit = true;
  155. }
  156. else if (strcmp(argv[i], "--socket-path") == 0 || strcmp(argv[i], "-p") == 0) {
  157. ++i;
  158. if (i == argc || argv[i][0] == '\0') {
  159. cerr << "dinitcheck: --socket-path/-p should be followed by socket path\n";
  160. return 1;
  161. }
  162. control_socket_str = argv[i];
  163. }
  164. else if (strcmp(argv[i], "--online") == 0 || strcmp(argv[i], "-n") == 0) {
  165. offline_operation = false;
  166. }
  167. else if (strcmp(argv[i], "--env-file") == 0 || strcmp(argv[i], "-e") == 0) {
  168. ++i;
  169. if (i == argc || argv[i][0] == '\0') {
  170. cerr << "dinitcheck: --env-file/-e should be followed by environment file path\n";
  171. return 1;
  172. }
  173. env_file = argv[i];
  174. }
  175. else if (strcmp(argv[i], "--help") == 0) {
  176. cout << "dinitcheck: check dinit service descriptions\n"
  177. " --help display help\n"
  178. " --services-dir <dir>, -d <dir>\n"
  179. " set base directory for service description\n"
  180. " files, can be specified multiple times\n"
  181. " --online, -n use service dirs and environment from running\n"
  182. " dinit instance\n"
  183. " --socket-path <path>, -p <path>\n"
  184. " use specified socket to connect to daemon (online\n"
  185. " mode)\n"
  186. " --env-file, -e <file> read environment from specified file\n"
  187. " --system, -s use defaults for system manager mode\n"
  188. " --user, -u use defaults for user mode\n"
  189. " <service-name> check service with name <service-name>\n";
  190. return EXIT_SUCCESS;
  191. }
  192. else {
  193. std::cerr << "dinitcheck: Unrecognized option: '" << argv[i] << "' (use '--help' for help)\n";
  194. return EXIT_FAILURE;
  195. }
  196. }
  197. else {
  198. services_to_check.push_back(argv[i]);
  199. }
  200. }
  201. }
  202. int socknum = -1;
  203. cpbuffer_t rbuffer;
  204. signal(SIGPIPE, SIG_IGN);
  205. service_dir_pathlist service_dir_paths;
  206. std::vector<std::string> service_dir_strs; // storage if needed for service_dir_paths
  207. if (offline_operation) {
  208. service_dir_opts.build_paths(!user_dinit);
  209. service_dir_paths = std::move(service_dir_opts.get_paths());
  210. if (env_file.empty()) {
  211. if (!user_dinit) {
  212. env_file = "/etc/dinit/environment";
  213. }
  214. }
  215. if (!env_file.empty()) {
  216. auto log_inv_env_setting = [&](int line_num) {
  217. std::cerr << "dinitcheck: warning: Invalid environment variable setting in environment file "
  218. << env_file << " (line " << std::to_string(line_num) << ")\n";
  219. };
  220. auto log_bad_env_command = [&](int line_num) {
  221. std::cerr << "dinitcheck: warning: Bad command in environment file "
  222. << env_file << " (line " << std::to_string(line_num) << ")\n";
  223. };
  224. try {
  225. read_env_file_inline(env_file.c_str(), true, menv, false, log_inv_env_setting, log_bad_env_command);
  226. }
  227. catch (std::system_error &err) {
  228. std::cerr << "dinitcheck: error read environment file " << env_file << ": "
  229. << err.code().message() << "\n";
  230. return EXIT_FAILURE;
  231. }
  232. }
  233. }
  234. else {
  235. if (!control_socket_str.empty()) {
  236. control_socket_path = control_socket_str.c_str();
  237. }
  238. else {
  239. control_socket_path = get_default_socket_path(control_socket_str, user_dinit);
  240. if (control_socket_path == nullptr) {
  241. cerr << "dinitcheck: cannot locate user home directory (set XDG_RUNTIME_DIR, HOME, check /etc/passwd file, or "
  242. "specify socket path via -p)" << endl;
  243. return EXIT_FAILURE;
  244. }
  245. }
  246. try {
  247. socknum = connect_to_daemon(control_socket_path);
  248. // Start by querying protocol version:
  249. check_protocol_version(min_cp_version, max_cp_version, rbuffer, socknum);
  250. // Read service directories
  251. service_dir_strs = get_service_description_dirs(socknum, rbuffer);
  252. for (const std::string &service_dir : service_dir_strs) {
  253. service_dir_paths.emplace_back(dir_entry(service_dir.c_str(), false));
  254. }
  255. menv.clear_no_inherit();
  256. get_remote_env(socknum, rbuffer);
  257. }
  258. catch (cp_old_client_exception &e) {
  259. std::cerr << "dinitcheck: too old (daemon reports newer protocol version)" << std::endl;
  260. return EXIT_FAILURE;
  261. }
  262. catch (cp_old_server_exception &e) {
  263. std::cerr << "dinitcheck: daemon too old or protocol error" << std::endl;
  264. return EXIT_FAILURE;
  265. }
  266. catch (cp_read_exception &e) {
  267. cerr << "dinitcheck: control socket read failure or protocol error" << endl;
  268. return EXIT_FAILURE;
  269. }
  270. catch (cp_write_exception &e) {
  271. cerr << "dinitcheck: control socket write error: " << std::strerror(e.errcode) << endl;
  272. return EXIT_FAILURE;
  273. }
  274. catch (dinit_protocol_error &e) {
  275. cerr << "dinitcheck: protocol error" << endl;
  276. return EXIT_FAILURE;
  277. }
  278. catch (general_error &ge) {
  279. std::cerr << "dinitcheck";
  280. if (ge.get_action() != nullptr) {
  281. std::cerr << ": " << ge.get_action();
  282. std::string &arg = ge.get_arg();
  283. if (!arg.empty()) {
  284. std::cerr << " " << arg;
  285. }
  286. }
  287. if (ge.get_err() != 0) {
  288. std::cerr << ": " << strerror(ge.get_err());
  289. }
  290. std::cerr << '\n';
  291. return EXIT_FAILURE;
  292. }
  293. }
  294. if (services_to_check.empty()) {
  295. services_to_check.push_back("boot");
  296. }
  297. size_t num_services_to_check = services_to_check.size();
  298. // Load named service(s)
  299. // - load the service, store dependencies as strings
  300. // - recurse
  301. std::map<std::string, service_record *> service_set;
  302. for (size_t i = 0; i < services_to_check.size(); ++i) {
  303. const std::string &name = services_to_check[i];
  304. std::cout << "Checking service: " << name << "...\n";
  305. try {
  306. service_record *sr = load_service(service_set, name, service_dir_paths);
  307. service_set[name] = sr;
  308. // add dependencies to services_to_check
  309. for (auto &dep : sr->dependencies) {
  310. if (service_set.count(dep.name) == 0 && !contains(services_to_check, dep.name)) {
  311. services_to_check.push_back(dep.name);
  312. }
  313. }
  314. // add chain_to to services_to_check
  315. if (!sr->chain_to.empty() && !contains(services_to_check, sr->chain_to)) {
  316. if (!contains(services_to_check, sr->chain_to)) {
  317. services_to_check.push_back(sr->chain_to);
  318. }
  319. }
  320. // add before_svcs and after_svcs to services_to_check
  321. for (const std::string &before_name : sr->before_svcs) {
  322. if (!contains(services_to_check, before_name)) {
  323. services_to_check.push_back(before_name);
  324. }
  325. }
  326. for (const std::string &after_name : sr->after_svcs) {
  327. if (!contains(services_to_check, after_name)) {
  328. services_to_check.push_back(after_name);
  329. }
  330. }
  331. // add consumed service (if any) to services to check
  332. if (!sr->consumer_of_name.empty()) {
  333. services_to_check.push_back(sr->consumer_of_name);
  334. }
  335. }
  336. catch (service_load_exc &exc) {
  337. std::cerr << "Unable to load service '" << name << "': " << exc.exc_description << "\n";
  338. errors_found = true;
  339. }
  340. }
  341. std::cout << "Performing secondary checks...\n";
  342. for (const auto &svc_name_record : service_set) {
  343. if (!svc_name_record.second->consumer_of_name.empty()) {
  344. auto consumer_of_it = service_set.find(svc_name_record.second->consumer_of_name);
  345. if (consumer_of_it != service_set.end()) {
  346. if (consumer_of_it->second->log_type != log_type_id::PIPE) {
  347. std::cerr << "Service '" << svc_name_record.first << "': specified as consumer of service '"
  348. << consumer_of_it->first << "' which has log-type that is not 'pipe'\n";
  349. errors_found = true;
  350. }
  351. }
  352. else {
  353. std::cerr << "Warning: Service '" << svc_name_record.first << "' specified as consumer of service '"
  354. << consumer_of_it->first << "' which was not found\n";
  355. }
  356. }
  357. // "before" ordering links are like reverse-dependencies: set up dependencies in the forwards direction
  358. // (from the dependent). Similarly for "after" links set up a dependency. These dependencies allow cycle
  359. // checking.
  360. for (const std::string &before_name : svc_name_record.second->before_svcs) {
  361. auto before_svc_it = service_set.find(before_name);
  362. if (before_svc_it != service_set.end()) {
  363. before_svc_it->second->dependencies.emplace_back(svc_name_record.first,
  364. dependency_type::BEFORE);
  365. }
  366. }
  367. for (const std::string &after_name : svc_name_record.second->after_svcs) {
  368. auto after_svc_it = service_set.find(after_name);
  369. if (after_svc_it != service_set.end()) {
  370. svc_name_record.second->dependencies.emplace_back(after_svc_it->first,
  371. dependency_type::AFTER);
  372. }
  373. }
  374. }
  375. // Check for circular dependencies
  376. std::vector<std::tuple<service_record *, size_t>> service_chain;
  377. for (size_t i = 0; i < num_services_to_check; ++i) {
  378. service_record *root = service_set[services_to_check[i]];
  379. if (! root) continue;
  380. if (root->visited) continue;
  381. // invariant: service_chain is empty
  382. service_chain.emplace_back(root, 0);
  383. // Depth first traversal. If we find a link (dependency) on a service already visited (but not
  384. // marked as cycle-free), we know then that we've found a cycle.
  385. while (true) {
  386. auto n = service_chain.size() - 1;
  387. auto &last = service_chain[n];
  388. service_record *last_record = std::get<0>(last);
  389. size_t &index = std::get<1>(last);
  390. if (index >= last_record->dependencies.size()) {
  391. // Processed all dependencies, go back up:
  392. last_record->cycle_free = true;
  393. service_chain.pop_back();
  394. if (n == 0) break;
  395. size_t &prev_index = std::get<1>(service_chain[n - 1]);
  396. ++prev_index;
  397. continue;
  398. }
  399. // Down the tree:
  400. auto dep_it = std::next(last_record->dependencies.begin(), index);
  401. service_record *next_link = service_set[dep_it->name];
  402. if (next_link == nullptr) {
  403. ++index;
  404. continue;
  405. }
  406. if (next_link->visited) {
  407. if (! next_link->cycle_free) {
  408. // We've found a cycle. Clear entries before the beginning of the cycle, then
  409. // exit the loop.
  410. auto first = std::find_if(service_chain.begin(), service_chain.end(),
  411. [next_link](std::tuple<service_record *, size_t> &a) -> bool {
  412. return std::get<0>(a) == next_link;
  413. });
  414. service_chain.erase(service_chain.begin(), first);
  415. break;
  416. }
  417. }
  418. next_link->visited = true;
  419. service_chain.emplace_back(next_link, 0);
  420. }
  421. // Report only one cycle; otherwise difficult to avoid reporting duplicates or overlapping
  422. // cycles.
  423. if (!service_chain.empty()) break;
  424. }
  425. if (!service_chain.empty()) {
  426. errors_found = true;
  427. std::cerr << "Found dependency cycle:\n";
  428. for (auto chain_link : service_chain) {
  429. service_record *svc = std::get<0>(chain_link);
  430. size_t dep_index = std::get<1>(chain_link);
  431. std::cerr << " " << svc->name << " ->";
  432. auto dep_it = std::next(svc->dependencies.begin(), dep_index);
  433. if (dep_it->dep_type == dependency_type::BEFORE) {
  434. std::cerr << " (via 'before')";
  435. }
  436. if (dep_it->dep_type == dependency_type::AFTER) {
  437. std::cerr << " (via 'after')";
  438. }
  439. std::cerr << "\n";
  440. }
  441. std::cerr << " " << std::get<0>(service_chain[0])->name << ".\n";
  442. }
  443. std::cerr << "Secondary checks complete.\n";
  444. if (! errors_found) {
  445. std::cout << "No problems found.\n";
  446. }
  447. else {
  448. std::cout << "One or more errors/warnings issued.\n";
  449. }
  450. return errors_found ? EXIT_FAILURE : EXIT_SUCCESS;
  451. }
  452. static void report_service_description_err(const std::string &service_name, unsigned line_num,
  453. const std::string &what)
  454. {
  455. std::cerr << "Service '" << service_name << "' (line " << line_num << "): " << what << "\n";
  456. errors_found = true;
  457. }
  458. static void report_service_description_err(const std::string &service_name, const char *setting_name,
  459. const std::string &what)
  460. {
  461. std::cerr << "Service '" << service_name << "' setting '" << setting_name << "': " << what << "\n";
  462. errors_found = true;
  463. }
  464. static void report_service_description_err(const std::string &service_name, const std::string &what)
  465. {
  466. std::cerr << "Service '" << service_name << "': " << what << "\n";
  467. errors_found = true;
  468. }
  469. static void report_service_description_exc(service_description_exc &exc)
  470. {
  471. if (exc.line_num != (unsigned)-1) {
  472. report_service_description_err(exc.service_name, exc.line_num, exc.exc_description);
  473. }
  474. else {
  475. report_service_description_err(exc.service_name, exc.setting_name, exc.exc_description);
  476. }
  477. }
  478. static void report_error(std::system_error &exc, const std::string &service_name)
  479. {
  480. std::cerr << "Service '" << service_name << "', error reading service description: " << exc.what() << "\n";
  481. errors_found = true;
  482. }
  483. static void report_dir_error(const char *service_name, const std::string &dirpath)
  484. {
  485. std::cerr << "Service '" << service_name << "', error reading dependencies from directory " << dirpath
  486. << ": " << strerror(errno) << "\n";
  487. errors_found = true;
  488. }
  489. static void report_general_warning(string_view msg)
  490. {
  491. std::cerr << "dinitcheck: Warning: " << msg.data() << "\n";
  492. }
  493. // Process a dependency directory - filenames contained within correspond to service names which
  494. // are loaded and added as a dependency of the given type. Expected use is with a directory
  495. // containing symbolic links to other service descriptions, but this isn't required.
  496. // Failure to read the directory contents, or to find a service listed within, is not considered
  497. // a fatal error.
  498. static void process_dep_dir(const char *servicename,
  499. const string &service_filename,
  500. std::list<prelim_dep> &deplist, const std::string &depdirpath,
  501. dependency_type dep_type)
  502. {
  503. std::string depdir_fname = combine_paths(parent_path(service_filename), depdirpath.c_str());
  504. DIR *depdir = opendir(depdir_fname.c_str());
  505. if (depdir == nullptr) {
  506. report_dir_error(servicename, depdirpath);
  507. return;
  508. }
  509. errno = 0;
  510. dirent * dent = readdir(depdir);
  511. while (dent != nullptr) {
  512. char * name = dent->d_name;
  513. if (name[0] != '.') {
  514. deplist.emplace_back(name, dep_type);
  515. }
  516. dent = readdir(depdir);
  517. }
  518. if (errno != 0) {
  519. report_dir_error(servicename, depdirpath);
  520. }
  521. closedir(depdir);
  522. }
  523. service_record *load_service(service_set_t &services, const std::string &name,
  524. const service_dir_pathlist &service_dirs)
  525. {
  526. using namespace std;
  527. using namespace dinit_load;
  528. auto found = services.find(name);
  529. if (found != services.end()) {
  530. return found->second;
  531. }
  532. string service_wdir;
  533. string service_filename;
  534. ifstream service_file;
  535. int dirfd;
  536. int fail_load_errno = 0;
  537. std::string fail_load_path;
  538. // Couldn't find one. Have to load it.
  539. for (auto &service_dir : service_dirs) {
  540. service_filename = service_dir.get_dir();
  541. service_wdir = service_filename;
  542. if (*(service_filename.rbegin()) != '/') {
  543. service_filename += '/';
  544. }
  545. service_filename += name;
  546. service_file.open(service_filename.c_str(), ios::in);
  547. if (service_file) break;
  548. if (errno != ENOENT && fail_load_errno == 0) {
  549. fail_load_errno = errno;
  550. fail_load_path = std::move(service_filename);
  551. }
  552. }
  553. if (!service_file) {
  554. if (fail_load_errno == 0) {
  555. throw service_not_found(string(name));
  556. }
  557. else {
  558. throw service_load_error(name, std::move(fail_load_path), fail_load_errno);
  559. }
  560. }
  561. service_settings_wrapper<prelim_dep> settings;
  562. string line;
  563. service_file.exceptions(ios::badbit);
  564. try {
  565. process_service_file(name, service_file,
  566. [&](string &line, unsigned line_num, string &setting,
  567. string_iterator &i, string_iterator &end) -> void {
  568. auto process_dep_dir_n = [&](std::list<prelim_dep> &deplist, const std::string &waitsford,
  569. dependency_type dep_type) -> void {
  570. process_dep_dir(name.c_str(), service_filename, deplist, waitsford, dep_type);
  571. };
  572. auto load_service_n = [&](const string &dep_name) -> const string & {
  573. return dep_name;
  574. };
  575. try {
  576. process_service_line(settings, name.c_str(), line, line_num, setting, i, end,
  577. load_service_n, process_dep_dir_n);
  578. }
  579. catch (service_description_exc &exc) {
  580. if (exc.service_name.empty()) {
  581. exc.service_name = name;
  582. }
  583. report_service_description_exc(exc);
  584. }
  585. });
  586. }
  587. catch (std::system_error &sys_err)
  588. {
  589. report_error(sys_err, name);
  590. throw service_load_exc(name, "error while reading service description.");
  591. }
  592. auto report_err = [&](const char *msg) {
  593. report_service_description_err(name, msg);
  594. };
  595. bool issued_var_subst_warning = false;
  596. environment srv_env{};
  597. // Fill user vars before reading env file
  598. if (settings.export_passwd_vars) {
  599. try {
  600. fill_environment_userinfo(settings.run_as_uid, name, srv_env);
  601. }
  602. catch (service_load_exc &load_exc) {
  603. report_service_description_err(name, load_exc.exc_description);
  604. }
  605. }
  606. // Set service name in environment if desired
  607. if (settings.export_service_name) {
  608. std::string envname = "DINIT_SERVICE=";
  609. envname += name;
  610. srv_env.set_var(std::move(envname));
  611. }
  612. if (!settings.env_file.empty()) {
  613. try {
  614. std::string fullpath = combine_paths(service_wdir, settings.env_file.c_str());
  615. auto log_inv_env_setting = [&](int line_num) {
  616. report_service_description_err(name,
  617. std::string("Invalid environment variable setting in environment file " + fullpath
  618. + " (line ") + std::to_string(line_num) + ")");
  619. };
  620. auto log_bad_env_command = [&](int line_num) {
  621. report_service_description_err(name,
  622. std::string("Bad command in environment file ") + fullpath + " (line " + std::to_string(line_num) + ")");
  623. };
  624. read_env_file_inline(fullpath.c_str(), false, srv_env, true, log_inv_env_setting, log_bad_env_command);
  625. } catch (const std::system_error &se) {
  626. report_service_description_err(name, std::string("could not load environment file: ") + se.what());
  627. }
  628. }
  629. environment::env_map renvmap = srv_env.build(menv);
  630. auto resolve_var = [&](const string &name, environment::env_map const &envmap) {
  631. if (offline_operation && !issued_var_subst_warning) {
  632. report_general_warning("Variable substitution performed by dinitcheck "
  633. "for file paths may not match dinit daemon (environment may differ); "
  634. "use --online to avoid this warning");
  635. issued_var_subst_warning = true;
  636. }
  637. return resolve_env_var(name, envmap);
  638. };
  639. settings.finalise(report_err, renvmap, report_err, resolve_var);
  640. if (!settings.working_dir.empty()) {
  641. service_wdir = settings.working_dir;
  642. }
  643. int oflags = O_DIRECTORY;
  644. #ifdef O_PATH
  645. oflags |= O_PATH;
  646. #else
  647. oflags |= O_RDONLY;
  648. #endif
  649. dirfd = open(service_wdir.c_str(), oflags);
  650. if (dirfd < 0) {
  651. report_service_description_err(name,
  652. std::string("could not open service working directory: ") + strerror(errno));
  653. dirfd = AT_FDCWD;
  654. }
  655. auto check_command = [&](const char *setting_name, const char *command) {
  656. struct stat command_stat;
  657. if (fstatat(dirfd, command, &command_stat, 0) == -1) {
  658. report_service_description_err(name,
  659. std::string("could not stat ") + setting_name + " executable '" + command
  660. + "': " + strerror(errno));
  661. }
  662. else {
  663. if ((command_stat.st_mode & S_IFMT) != S_IFREG) {
  664. report_service_description_err(name, std::string(setting_name) + " executable '"
  665. + command + "' is not a regular file.");
  666. }
  667. else if ((command_stat.st_mode & S_IXUSR) == 0) {
  668. report_service_description_err(name, std::string(setting_name) + " executable '" + command
  669. + "' is not executable by owner.");
  670. }
  671. }
  672. };
  673. if (!settings.command.empty()) {
  674. int offset_start = settings.command_offsets.front().first;
  675. int offset_end = settings.command_offsets.front().second;
  676. check_command("command", settings.command.substr(offset_start, offset_end - offset_start).c_str());
  677. }
  678. if (!settings.stop_command.empty()) {
  679. int offset_start = settings.stop_command_offsets.front().first;
  680. int offset_end = settings.stop_command_offsets.front().second;
  681. check_command("stop command",
  682. settings.stop_command.substr(offset_start, offset_end - offset_start).c_str());
  683. }
  684. if (dirfd != AT_FDCWD) {
  685. close(dirfd);
  686. }
  687. return new service_record(name, settings.chain_to_name, settings.depends, settings.before_svcs,
  688. settings.after_svcs, settings.consumer_of_name, settings.log_type);
  689. }