dinitcheck.cc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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 <unistd.h>
  10. #include <sys/types.h>
  11. #include <sys/stat.h>
  12. #include <sys/time.h>
  13. #include <sys/resource.h>
  14. #include <pwd.h>
  15. #include <dirent.h>
  16. #include "dinit-util.h"
  17. #include "service-constants.h"
  18. #include "load-service.h"
  19. #include "options-processing.h"
  20. // dinitcheck: utility to check Dinit configuration for correctness/lint
  21. using string = std::string;
  22. using string_iterator = std::string::iterator;
  23. static void report_service_description_err(const std::string &service_name, const std::string &what);
  24. // prelim_dep: A preliminary (unresolved) service dependency
  25. class prelim_dep
  26. {
  27. public:
  28. std::string name;
  29. dependency_type dep_type;
  30. prelim_dep(const std::string &name_p, dependency_type dep_type_p)
  31. : name(name_p), dep_type(dep_type_p) { }
  32. prelim_dep(std::string &&name_p, dependency_type dep_type_p)
  33. : name(std::move(name_p)), dep_type(dep_type_p) { }
  34. };
  35. class service_record
  36. {
  37. public:
  38. service_record(const std::string &name_p, const std::string &chain_to_p,
  39. std::list<prelim_dep> dependencies_p)
  40. : name(name_p), dependencies(dependencies_p) {}
  41. std::string name;
  42. std::string chain_to;
  43. std::list<prelim_dep> dependencies;
  44. bool visited = false; // flag used to detect cyclic dependencies
  45. bool cycle_free = false;
  46. };
  47. using service_set_t = std::map<std::string, service_record *>;
  48. service_record *load_service(service_set_t &services, const std::string &name,
  49. const service_dir_pathlist &service_dirs);
  50. // Add some missing standard library functionality...
  51. template <typename T> bool contains(std::vector<T> vec, const T& elem)
  52. {
  53. return std::find(vec.begin(), vec.end(), elem) != vec.end();
  54. }
  55. static bool errors_found = false;
  56. int main(int argc, char **argv)
  57. {
  58. using namespace std;
  59. service_dir_opt service_dir_opts;
  60. bool am_system_init = (getuid() == 0);
  61. std::vector<std::string> services_to_check;
  62. // Process command line
  63. if (argc > 1) {
  64. for (int i = 1; i < argc; i++) {
  65. if (argv[i][0] == '-') {
  66. // An option...
  67. if (strcmp(argv[i], "--services-dir") == 0 || strcmp(argv[i], "-d") == 0) {
  68. if (++i < argc) {
  69. service_dir_opts.set_specified_service_dir(argv[i]);
  70. }
  71. else {
  72. cerr << "dinitcheck: '--services-dir' (-d) requires an argument" << endl;
  73. return 1;
  74. }
  75. }
  76. else if (strcmp(argv[i], "--help") == 0) {
  77. cout << "dinitcheck: check dinit service descriptions\n"
  78. " --help display help\n"
  79. " --services-dir <dir>, -d <dir>\n"
  80. " set base directory for service description\n"
  81. " files, can be specified multiple times\n"
  82. " <service-name> check service with name <service-name>\n";
  83. return EXIT_SUCCESS;
  84. }
  85. else {
  86. std::cerr << "dinitcheck: Unrecognized option: '" << argv[i] << "' (use '--help' for help)\n";
  87. return EXIT_FAILURE;
  88. }
  89. }
  90. else {
  91. services_to_check.push_back(argv[i]);
  92. }
  93. }
  94. }
  95. service_dir_opts.build_paths(am_system_init);
  96. if (services_to_check.empty()) {
  97. services_to_check.push_back("boot");
  98. }
  99. size_t num_services_to_check = services_to_check.size();
  100. // Load named service(s)
  101. // - load the service, store dependencies as strings
  102. // - recurse
  103. std::map<std::string, service_record *> service_set;
  104. for (size_t i = 0; i < services_to_check.size(); ++i) {
  105. const std::string &name = services_to_check[i];
  106. std::cout << "Checking service: " << name << "...\n";
  107. try {
  108. service_record *sr = load_service(service_set, name, service_dir_opts.get_paths());
  109. service_set[name] = sr;
  110. // add dependencies to services_to_check
  111. for (auto &dep : sr->dependencies) {
  112. if (service_set.count(dep.name) == 0 && !contains(services_to_check, dep.name)) {
  113. services_to_check.push_back(dep.name);
  114. }
  115. }
  116. // add chain_to to services_to_check
  117. if (!sr->chain_to.empty() && !contains(services_to_check, sr->chain_to)) {
  118. services_to_check.push_back(sr->chain_to);
  119. }
  120. }
  121. catch (service_load_exc &exc) {
  122. std::cerr << "Unable to load service '" << name << "': " << exc.exc_description << "\n";
  123. errors_found = true;
  124. }
  125. }
  126. // Check for circular dependencies
  127. std::vector<std::tuple<service_record *, size_t>> service_chain;
  128. for (size_t i = 0; i < num_services_to_check; ++i) {
  129. service_record *root = service_set[services_to_check[i]];
  130. if (! root) continue;
  131. if (root->visited) continue;
  132. // invariant: service_chain is empty
  133. service_chain.emplace_back(root, 0);
  134. // Depth first traversal. If we find a link (dependency) on a service already visited (but not
  135. // marked as cycle-free), we know then that we've found a cycle.
  136. while (true) {
  137. auto n = service_chain.size() - 1;
  138. auto &last = service_chain[n];
  139. service_record *last_record = std::get<0>(last);
  140. size_t &index = std::get<1>(last);
  141. if (index >= last_record->dependencies.size()) {
  142. // Processed all dependencies, go back up:
  143. last_record->cycle_free = true;
  144. service_chain.pop_back();
  145. if (n == 0) break;
  146. size_t &prev_index = std::get<1>(service_chain[n - 1]);
  147. ++prev_index;
  148. continue;
  149. }
  150. // Down the tree:
  151. auto dep_it = std::next(last_record->dependencies.begin(), index);
  152. service_record *next_link = service_set[dep_it->name];
  153. if (next_link == nullptr) {
  154. ++index;
  155. continue;
  156. }
  157. if (next_link->visited) {
  158. if (! next_link->cycle_free) {
  159. // We've found a cycle. Clear entries before the beginning of the cycle, then
  160. // exit the loop.
  161. auto first = std::find_if(service_chain.begin(), service_chain.end(),
  162. [next_link](std::tuple<service_record *, size_t> &a) -> bool {
  163. return std::get<0>(a) == next_link;
  164. });
  165. service_chain.erase(service_chain.begin(), first);
  166. break;
  167. }
  168. }
  169. next_link->visited = true;
  170. service_chain.emplace_back(next_link, 0);
  171. }
  172. // Report only one cycle; otherwise difficult to avoid reporting duplicates or overlapping
  173. // cycles.
  174. if (!service_chain.empty()) break;
  175. }
  176. if (!service_chain.empty()) {
  177. errors_found = true;
  178. std::cerr << "Found dependency cycle:\n";
  179. for (auto chain_link : service_chain) {
  180. std::cerr << " " << std::get<0>(chain_link)->name << " ->\n";
  181. }
  182. std::cerr << " " << std::get<0>(service_chain[0])->name << ".\n";
  183. }
  184. if (! errors_found) {
  185. std::cout << "No problems found.\n";
  186. }
  187. else {
  188. std::cout << "One or more errors/warnings issued.\n";
  189. }
  190. return errors_found ? EXIT_FAILURE : EXIT_SUCCESS;
  191. }
  192. static void report_service_description_err(const std::string &service_name, unsigned line_num,
  193. const std::string &what)
  194. {
  195. std::cerr << "Service '" << service_name << "' (line " << line_num << "): " << what << "\n";
  196. errors_found = true;
  197. }
  198. static void report_service_description_err(const std::string &service_name, const char *setting_name,
  199. const std::string &what)
  200. {
  201. std::cerr << "Service '" << service_name << "' setting '" << setting_name << "': " << what << "\n";
  202. errors_found = true;
  203. }
  204. static void report_service_description_err(const std::string &service_name, const std::string &what)
  205. {
  206. std::cerr << "Service '" << service_name << "': " << what << "\n";
  207. errors_found = true;
  208. }
  209. static void report_service_description_exc(service_description_exc &exc)
  210. {
  211. if (exc.line_num != (unsigned)-1) {
  212. report_service_description_err(exc.service_name, exc.line_num, exc.exc_description);
  213. }
  214. else {
  215. report_service_description_err(exc.service_name, exc.setting_name, exc.exc_description);
  216. }
  217. }
  218. static void report_error(std::system_error &exc, const std::string &service_name)
  219. {
  220. std::cerr << "Service '" << service_name << "', error reading service description: " << exc.what() << "\n";
  221. errors_found = true;
  222. }
  223. static void report_dir_error(const char *service_name, const std::string &dirpath)
  224. {
  225. std::cerr << "Service '" << service_name << "', error reading dependencies from directory " << dirpath
  226. << ": " << strerror(errno) << "\n";
  227. errors_found = true;
  228. }
  229. // Process a dependency directory - filenames contained within correspond to service names which
  230. // are loaded and added as a dependency of the given type. Expected use is with a directory
  231. // containing symbolic links to other service descriptions, but this isn't required.
  232. // Failure to read the directory contents, or to find a service listed within, is not considered
  233. // a fatal error.
  234. static void process_dep_dir(const char *servicename,
  235. const string &service_filename,
  236. std::list<prelim_dep> &deplist, const std::string &depdirpath,
  237. dependency_type dep_type)
  238. {
  239. std::string depdir_fname = combine_paths(parent_path(service_filename), depdirpath.c_str());
  240. DIR *depdir = opendir(depdir_fname.c_str());
  241. if (depdir == nullptr) {
  242. report_dir_error(servicename, depdirpath);
  243. return;
  244. }
  245. errno = 0;
  246. dirent * dent = readdir(depdir);
  247. while (dent != nullptr) {
  248. char * name = dent->d_name;
  249. if (name[0] != '.') {
  250. deplist.emplace_back(name, dep_type);
  251. }
  252. dent = readdir(depdir);
  253. }
  254. if (errno != 0) {
  255. report_dir_error(servicename, depdirpath);
  256. }
  257. closedir(depdir);
  258. }
  259. service_record *load_service(service_set_t &services, const std::string &name,
  260. const service_dir_pathlist &service_dirs)
  261. {
  262. using namespace std;
  263. using namespace dinit_load;
  264. auto found = services.find(name);
  265. if (found != services.end()) {
  266. return found->second;
  267. }
  268. string service_filename;
  269. ifstream service_file;
  270. int fail_load_errno = 0;
  271. std::string fail_load_path;
  272. // Couldn't find one. Have to load it.
  273. for (auto &service_dir : service_dirs) {
  274. service_filename = service_dir.get_dir();
  275. if (*(service_filename.rbegin()) != '/') {
  276. service_filename += '/';
  277. }
  278. service_filename += name;
  279. service_file.open(service_filename.c_str(), ios::in);
  280. if (service_file) break;
  281. if (errno != ENOENT && fail_load_errno == 0) {
  282. fail_load_errno = errno;
  283. fail_load_path = std::move(service_filename);
  284. }
  285. }
  286. if (!service_file) {
  287. if (fail_load_errno == 0) {
  288. throw service_not_found(string(name));
  289. }
  290. else {
  291. throw service_load_error(name, std::move(fail_load_path), fail_load_errno);
  292. }
  293. }
  294. service_settings_wrapper<prelim_dep> settings;
  295. string line;
  296. service_file.exceptions(ios::badbit);
  297. try {
  298. process_service_file(name, service_file,
  299. [&](string &line, unsigned line_num, string &setting,
  300. string_iterator &i, string_iterator &end) -> void {
  301. auto process_dep_dir_n = [&](std::list<prelim_dep> &deplist, const std::string &waitsford,
  302. dependency_type dep_type) -> void {
  303. process_dep_dir(name.c_str(), service_filename, deplist, waitsford, dep_type);
  304. };
  305. auto load_service_n = [&](const string &dep_name) -> const string & {
  306. return dep_name;
  307. };
  308. try {
  309. process_service_line(settings, name.c_str(), line, line_num, setting, i, end,
  310. load_service_n, process_dep_dir_n);
  311. }
  312. catch (service_description_exc &exc) {
  313. report_service_description_exc(exc);
  314. }
  315. });
  316. }
  317. catch (std::system_error &sys_err)
  318. {
  319. report_error(sys_err, name);
  320. throw service_load_exc(name, "error while reading service description.");
  321. }
  322. auto report_err = [&](const char *msg) {
  323. report_service_description_err(name, msg);
  324. };
  325. bool issued_var_subst_warning = false;
  326. auto resolve_var = [&](const string &name) {
  327. if (!issued_var_subst_warning) {
  328. report_service_description_err(name, "warning: variable substitution performed by dinitcheck "
  329. "for file paths may not match dinitd (environment may differ)");
  330. issued_var_subst_warning = true;
  331. }
  332. return resolve_env_var(name);
  333. };
  334. settings.finalise(report_err, report_err, resolve_var);
  335. auto check_command = [&](const char *setting_name, const char *command) {
  336. struct stat command_stat;
  337. if (stat(command, &command_stat) == -1) {
  338. report_service_description_err(name,
  339. std::string("could not stat ") + setting_name + " executable '" + command
  340. + "': " + strerror(errno));
  341. }
  342. else {
  343. if ((command_stat.st_mode & S_IFMT) != S_IFREG) {
  344. report_service_description_err(name, std::string(setting_name) + " executable '"
  345. + command + "' is not a regular file.");
  346. }
  347. else if ((command_stat.st_mode & S_IXUSR) == 0) {
  348. report_service_description_err(name, std::string(setting_name) + " executable '" + command
  349. + "' is not executable by owner.");
  350. }
  351. }
  352. };
  353. if (!settings.command.empty()) {
  354. int offset_start = settings.command_offsets.front().first;
  355. int offset_end = settings.command_offsets.front().second;
  356. check_command("command", settings.command.substr(offset_start, offset_end - offset_start).c_str());
  357. }
  358. if (!settings.stop_command.empty()) {
  359. int offset_start = settings.stop_command_offsets.front().first;
  360. int offset_end = settings.stop_command_offsets.front().second;
  361. check_command("stop command",
  362. settings.stop_command.substr(offset_start, offset_end - offset_start).c_str());
  363. }
  364. return new service_record(name, settings.chain_to_name, settings.depends);
  365. }