dinitctl.cc 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527
  1. #include <cstdio>
  2. #include <cstddef>
  3. #include <cstring>
  4. #include <string>
  5. #include <iostream>
  6. #include <fstream>
  7. #include <system_error>
  8. #include <memory>
  9. #include <algorithm>
  10. #include <sys/types.h>
  11. #include <sys/stat.h>
  12. #include <sys/wait.h>
  13. #include <sys/socket.h>
  14. #include <sys/un.h>
  15. #include <unistd.h>
  16. #include <signal.h>
  17. #include <pwd.h>
  18. #include "control-cmds.h"
  19. #include "service-constants.h"
  20. #include "cpbuffer.h"
  21. #include "dinit-client.h"
  22. #include "load-service.h"
  23. #include "dinit-util.h"
  24. #include "mconfig.h"
  25. // dinitctl: utility to control the Dinit daemon, including starting and stopping of services.
  26. // This utility communicates with the dinit daemon via a unix stream socket (as specified in
  27. // SYSCONTROLSOCKET, or $HOME/.dinitctl).
  28. static constexpr uint16_t min_cp_version = 1;
  29. static constexpr uint16_t max_cp_version = 1;
  30. enum class command_t;
  31. static int issue_load_service(int socknum, const char *service_name, bool find_only = false);
  32. static int check_load_reply(int socknum, cpbuffer_t &, handle_t *handle_p, service_state_t *state_p,
  33. bool write_error=true);
  34. static int start_stop_service(int socknum, cpbuffer_t &, const char *service_name, command_t command,
  35. bool do_pin, bool do_force, bool wait_for_service, bool ignore_unstarted, bool verbose);
  36. static int unpin_service(int socknum, cpbuffer_t &, const char *service_name, bool verbose);
  37. static int unload_service(int socknum, cpbuffer_t &, const char *service_name, bool verbose);
  38. static int reload_service(int socknum, cpbuffer_t &, const char *service_name, bool verbose);
  39. static int list_services(int socknum, cpbuffer_t &);
  40. static int service_status(int socknum, cpbuffer_t &rbuffer, const char *service_name);
  41. static int shutdown_dinit(int soclknum, cpbuffer_t &, bool verbose);
  42. static int add_remove_dependency(int socknum, cpbuffer_t &rbuffer, bool add, const char *service_from,
  43. const char *service_to, dependency_type dep_type, bool verbose);
  44. static int enable_disable_service(int socknum, cpbuffer_t &rbuffer, const char *from, const char *to,
  45. bool enable, bool verbose);
  46. static int do_setenv(int socknum, cpbuffer_t &rbuffer, std::vector<const char *> &env_names);
  47. static const char * describeState(bool stopped)
  48. {
  49. return stopped ? "stopped" : "started";
  50. }
  51. static const char * describeVerb(bool stop)
  52. {
  53. return stop ? "stop" : "start";
  54. }
  55. enum class command_t {
  56. NONE,
  57. START_SERVICE,
  58. WAKE_SERVICE,
  59. STOP_SERVICE,
  60. RESTART_SERVICE,
  61. RELEASE_SERVICE,
  62. UNPIN_SERVICE,
  63. UNLOAD_SERVICE,
  64. RELOAD_SERVICE,
  65. LIST_SERVICES,
  66. SERVICE_STATUS,
  67. SHUTDOWN,
  68. ADD_DEPENDENCY,
  69. RM_DEPENDENCY,
  70. ENABLE_SERVICE,
  71. DISABLE_SERVICE,
  72. SETENV,
  73. };
  74. class dinit_protocol_error
  75. {
  76. // no body
  77. };
  78. // Entry point.
  79. int dinitctl_main(int argc, char **argv)
  80. {
  81. using namespace std;
  82. bool show_help = argc < 2;
  83. const char *service_name = nullptr;
  84. const char *to_service_name = nullptr;
  85. dependency_type dep_type;
  86. bool dep_type_set = false;
  87. std::string control_socket_str;
  88. const char * control_socket_path = nullptr;
  89. bool verbose = true;
  90. bool user_dinit = (getuid() != 0); // communicate with user daemon
  91. bool wait_for_service = true;
  92. bool do_pin = false;
  93. bool do_force = false;
  94. bool ignore_unstarted = false;
  95. command_t command = command_t::NONE;
  96. std::vector<const char *> cmd_args;
  97. for (int i = 1; i < argc; i++) {
  98. if (argv[i][0] == '-') {
  99. if (strcmp(argv[i], "--help") == 0) {
  100. show_help = true;
  101. break;
  102. }
  103. else if (strcmp(argv[i], "--version") == 0) {
  104. cout << "Dinit version " << DINIT_VERSION << ".\n";
  105. return 0;
  106. }
  107. else if (strcmp(argv[i], "--no-wait") == 0) {
  108. wait_for_service = false;
  109. }
  110. else if (strcmp(argv[i], "--ignore-unstarted") == 0) {
  111. ignore_unstarted = true;
  112. }
  113. else if (strcmp(argv[i], "--quiet") == 0) {
  114. verbose = false;
  115. }
  116. else if (strcmp(argv[i], "--system") == 0 || strcmp(argv[i], "-s") == 0) {
  117. user_dinit = false;
  118. }
  119. else if (strcmp(argv[i], "--user") == 0 || strcmp(argv[i], "-u") == 0) {
  120. user_dinit = true;
  121. }
  122. else if (strcmp(argv[i], "--pin") == 0) {
  123. do_pin = true;
  124. }
  125. else if (strcmp(argv[i], "--socket-path") == 0 || strcmp(argv[i], "-p") == 0) {
  126. ++i;
  127. if (i == argc) {
  128. cerr << "dinitctl: --socket-path/-p should be followed by socket path" << std::endl;
  129. return 1;
  130. }
  131. control_socket_str = argv[i];
  132. }
  133. else if ((command == command_t::ENABLE_SERVICE || command == command_t::DISABLE_SERVICE)
  134. && strcmp(argv[i], "--from") == 0) {
  135. ++i;
  136. if (i == argc) {
  137. cerr << "dinitctl: --from should be followed by a service name" << std::endl;
  138. return 1;
  139. }
  140. service_name = argv[i];
  141. }
  142. else if ((command == command_t::STOP_SERVICE || command == command_t::RESTART_SERVICE)
  143. && (strcmp(argv[i], "--force") == 0 || strcmp(argv[i], "-f") == 0)) {
  144. do_force = true;
  145. }
  146. else {
  147. cerr << "dinitctl: unrecognized/invalid option: " << argv[i] << " (use --help for help)\n";
  148. return 1;
  149. }
  150. }
  151. else if (command == command_t::NONE) {
  152. if (strcmp(argv[i], "start") == 0) {
  153. command = command_t::START_SERVICE;
  154. }
  155. else if (strcmp(argv[i], "wake") == 0) {
  156. command = command_t::WAKE_SERVICE;
  157. }
  158. else if (strcmp(argv[i], "stop") == 0) {
  159. command = command_t::STOP_SERVICE;
  160. }
  161. else if (strcmp(argv[i], "restart") == 0) {
  162. command = command_t::RESTART_SERVICE;
  163. }
  164. else if (strcmp(argv[i], "release") == 0) {
  165. command = command_t::RELEASE_SERVICE;
  166. }
  167. else if (strcmp(argv[i], "unpin") == 0) {
  168. command = command_t::UNPIN_SERVICE;
  169. }
  170. else if (strcmp(argv[i], "unload") == 0) {
  171. command = command_t::UNLOAD_SERVICE;
  172. }
  173. else if (strcmp(argv[i], "reload") == 0) {
  174. command = command_t::RELOAD_SERVICE;
  175. }
  176. else if (strcmp(argv[i], "list") == 0) {
  177. command = command_t::LIST_SERVICES;
  178. }
  179. else if (strcmp(argv[i], "status") == 0) {
  180. command = command_t::SERVICE_STATUS;
  181. }
  182. else if (strcmp(argv[i], "shutdown") == 0) {
  183. command = command_t::SHUTDOWN;
  184. }
  185. else if (strcmp(argv[i], "add-dep") == 0) {
  186. command = command_t::ADD_DEPENDENCY;
  187. }
  188. else if (strcmp(argv[i], "rm-dep") == 0) {
  189. command = command_t::RM_DEPENDENCY;
  190. }
  191. else if (strcmp(argv[i], "enable") == 0) {
  192. command = command_t::ENABLE_SERVICE;
  193. }
  194. else if (strcmp(argv[i], "disable") == 0) {
  195. command = command_t::DISABLE_SERVICE;
  196. }
  197. else if (strcmp(argv[i], "setenv") == 0) {
  198. command = command_t::SETENV;
  199. }
  200. else {
  201. cerr << "dinitctl: unrecognized command: " << argv[i] << " (use --help for help)\n";
  202. return 1;
  203. }
  204. }
  205. else {
  206. // service name / other non-option
  207. if (command == command_t::ADD_DEPENDENCY || command == command_t::RM_DEPENDENCY) {
  208. if (! dep_type_set) {
  209. if (strcmp(argv[i], "regular") == 0) {
  210. dep_type = dependency_type::REGULAR;
  211. }
  212. else if (strcmp(argv[i], "milestone") == 0) {
  213. dep_type = dependency_type::MILESTONE;
  214. }
  215. else if (strcmp(argv[i], "waits-for") == 0) {
  216. dep_type = dependency_type::WAITS_FOR;
  217. }
  218. else {
  219. show_help = true;
  220. break;
  221. }
  222. dep_type_set = true;
  223. }
  224. else if (service_name == nullptr) {
  225. service_name = argv[i];
  226. }
  227. else if (to_service_name == nullptr) {
  228. to_service_name = argv[i];
  229. }
  230. else {
  231. show_help = true;
  232. break;
  233. }
  234. }
  235. else if (command == command_t::ENABLE_SERVICE || command == command_t::DISABLE_SERVICE) {
  236. if (to_service_name != nullptr) {
  237. show_help = true;
  238. break;
  239. }
  240. to_service_name = argv[i];
  241. }
  242. else {
  243. cmd_args.push_back(argv[i]);
  244. }
  245. }
  246. }
  247. // Additional argument checks for various commands:
  248. if (command == command_t::NONE) {
  249. show_help = true;
  250. }
  251. else if (command == command_t::ENABLE_SERVICE || command == command_t::DISABLE_SERVICE) {
  252. show_help |= (to_service_name == nullptr);
  253. }
  254. else if (command == command_t::SETENV) {
  255. // Handle SETENV specially, since it needs arguments but they are not service names
  256. if (cmd_args.empty()) {
  257. show_help = true;
  258. }
  259. }
  260. else {
  261. bool no_service_cmd = (command == command_t::LIST_SERVICES || command == command_t::SHUTDOWN);
  262. if (no_service_cmd) {
  263. if (!cmd_args.empty()) {
  264. show_help = true;
  265. }
  266. }
  267. else {
  268. if (command == command_t::ADD_DEPENDENCY || command == command_t::RM_DEPENDENCY) {
  269. if (! dep_type_set || service_name == nullptr || to_service_name == nullptr) {
  270. show_help = true;
  271. }
  272. }
  273. else if (cmd_args.empty()) {
  274. show_help = true;
  275. }
  276. else {
  277. // No command can currently accept more than one service argument:
  278. if (cmd_args.size() > 1) {
  279. show_help = true;
  280. }
  281. service_name = cmd_args.front();
  282. }
  283. }
  284. }
  285. if (show_help) {
  286. cout << "dinitctl: control Dinit services\n"
  287. "\n"
  288. "Usage:\n"
  289. " dinitctl [options] status <service-name>\n"
  290. " dinitctl [options] start [options] <service-name>\n"
  291. " dinitctl [options] stop [options] <service-name>\n"
  292. " dinitctl [options] restart [options] <service-name>\n"
  293. " dinitctl [options] wake [options] <service-name>\n"
  294. " dinitctl [options] release [options] <service-name>\n"
  295. " dinitctl [options] unpin <service-name>\n"
  296. " dinitctl [options] unload <service-name>\n"
  297. " dinitctl [options] reload <service-name>\n"
  298. " dinitctl [options] list\n"
  299. " dinitctl [options] shutdown\n"
  300. " dinitctl [options] add-dep <type> <from-service> <to-service>\n"
  301. " dinitctl [options] rm-dep <type> <from-service> <to-service>\n"
  302. " dinitctl [options] enable [--from <from-service>] <to-service>\n"
  303. " dinitctl [options] disable [--from <from-service>] <to-service>\n"
  304. " dinitctl [options] setenv [name[=value] ...]\n"
  305. "\n"
  306. "Note: An activated service continues running when its dependents stop.\n"
  307. "\n"
  308. "General options:\n"
  309. " --help : show this help\n"
  310. " -s, --system : control system daemon (default if run as root)\n"
  311. " -u, --user : control user daemon\n"
  312. " --quiet : suppress output (except errors)\n"
  313. " --socket-path <path>, -p <path>\n"
  314. " : specify socket for communication with daemon\n"
  315. "\n"
  316. "Command options:\n"
  317. " --no-wait : don't wait for service startup/shutdown to complete\n"
  318. " --pin : pin the service in the requested state\n"
  319. " --force : force stop even if dependents will be affected\n";
  320. return 1;
  321. }
  322. // Begin the real work: connect to dinit
  323. signal(SIGPIPE, SIG_IGN);
  324. // Locate control socket
  325. if (! control_socket_str.empty()) {
  326. control_socket_path = control_socket_str.c_str();
  327. }
  328. else {
  329. control_socket_path = get_default_socket_path(control_socket_str, user_dinit);
  330. if (control_socket_path == nullptr) {
  331. cerr << "dinitctl: cannot locate user home directory (set XDG_RUNTIME_DIR, HOME, check /etc/passwd file, or "
  332. "specify socket path via -p)" << endl;
  333. return 1;
  334. }
  335. }
  336. try {
  337. int socknum = connect_to_daemon(control_socket_path);
  338. // Start by querying protocol version:
  339. cpbuffer_t rbuffer;
  340. check_protocol_version(min_cp_version, max_cp_version, rbuffer, socknum);
  341. if (command == command_t::UNPIN_SERVICE) {
  342. return unpin_service(socknum, rbuffer, service_name, verbose);
  343. }
  344. else if (command == command_t::UNLOAD_SERVICE) {
  345. return unload_service(socknum, rbuffer, service_name, verbose);
  346. }
  347. else if (command == command_t::RELOAD_SERVICE) {
  348. return reload_service(socknum, rbuffer, service_name, verbose);
  349. }
  350. else if (command == command_t::LIST_SERVICES) {
  351. return list_services(socknum, rbuffer);
  352. }
  353. else if (command == command_t::SERVICE_STATUS) {
  354. return service_status(socknum, rbuffer, service_name);
  355. }
  356. else if (command == command_t::SHUTDOWN) {
  357. return shutdown_dinit(socknum, rbuffer, verbose);
  358. }
  359. else if (command == command_t::ADD_DEPENDENCY || command == command_t::RM_DEPENDENCY) {
  360. return add_remove_dependency(socknum, rbuffer, command == command_t::ADD_DEPENDENCY,
  361. service_name, to_service_name, dep_type, verbose);
  362. }
  363. else if (command == command_t::ENABLE_SERVICE || command == command_t::DISABLE_SERVICE) {
  364. // If only one service specified, assume that we enable for 'boot' service:
  365. if (service_name == nullptr) {
  366. service_name = "boot";
  367. }
  368. return enable_disable_service(socknum, rbuffer, service_name, to_service_name,
  369. command == command_t::ENABLE_SERVICE, verbose);
  370. }
  371. else if (command == command_t::SETENV) {
  372. return do_setenv(socknum, rbuffer, cmd_args);
  373. }
  374. else {
  375. return start_stop_service(socknum, rbuffer, service_name, command, do_pin, do_force,
  376. wait_for_service, ignore_unstarted, verbose);
  377. }
  378. }
  379. catch (cp_old_client_exception &e) {
  380. std::cerr << "dinitctl: too old (server reports newer protocol version)" << std::endl;
  381. }
  382. catch (cp_old_server_exception &e) {
  383. std::cerr << "dinitctl: server too old or protocol error" << std::endl;
  384. }
  385. catch (cp_read_exception &e) {
  386. cerr << "dinitctl: control socket read failure or protocol error" << endl;
  387. }
  388. catch (cp_write_exception &e) {
  389. cerr << "dinitctl: control socket write error: " << std::strerror(e.errcode) << endl;
  390. }
  391. catch (dinit_protocol_error &e) {
  392. cerr << "dinitctl: protocol error" << endl;
  393. }
  394. catch (general_error &ge) {
  395. std::cerr << "dinit-client";
  396. if (ge.get_action() != nullptr) {
  397. std::cerr << ": " << ge.get_action();
  398. std::string &arg = ge.get_arg();
  399. if (!arg.empty()) {
  400. std::cerr << " " << arg;
  401. }
  402. }
  403. if (ge.get_err() != 0) {
  404. std::cerr << ": " << strerror(ge.get_err());
  405. }
  406. std::cerr << '\n';
  407. }
  408. return 1;
  409. }
  410. int main(int argc, char **argv)
  411. {
  412. try {
  413. return dinitctl_main(argc, argv);
  414. }
  415. catch (std::bad_alloc &e) {
  416. std::cerr << "dinitctl: out of memory\n";
  417. }
  418. return 1;
  419. }
  420. // Extract/read a string of specified length from the buffer/socket. The string is consumed
  421. // from the buffer.
  422. static std::string read_string(int socknum, cpbuffer_t &rbuffer, uint32_t length)
  423. {
  424. int rb_len = rbuffer.get_length();
  425. if (uint32_t(rb_len) >= length) {
  426. std::string r = rbuffer.extract_string(0, length);
  427. rbuffer.consume(length);
  428. return r;
  429. }
  430. std::string r = rbuffer.extract_string(0, rb_len);
  431. uint32_t rlen = length - rb_len;
  432. uint32_t clen;
  433. do {
  434. rbuffer.reset();
  435. fill_some(rbuffer, socknum);
  436. char *bptr = rbuffer.get_ptr(0);
  437. clen = rbuffer.get_length();
  438. clen = std::min(clen, rlen);
  439. r.append(bptr, clen);
  440. rlen -= clen;
  441. } while (rlen > 0);
  442. rbuffer.consume(clen);
  443. return r;
  444. }
  445. // Load a service: issue load command, wait for reply. Return true on success, display error message
  446. // and return false on failure.
  447. // socknum - the socket fd to communicate via
  448. // rbuffer - the buffer for communication
  449. // name - the name of the service to load
  450. // handle - where to store the handle of the loaded service
  451. // state - where to store the state of the loaded service (may be null).
  452. // write_error - whether to write an error message if the service can't be loaded
  453. static bool load_service(int socknum, cpbuffer_t &rbuffer, const char *name, handle_t *handle,
  454. service_state_t *state, bool write_error=true)
  455. {
  456. // Load 'to' service:
  457. if (issue_load_service(socknum, name)) {
  458. return false;
  459. }
  460. wait_for_reply(rbuffer, socknum);
  461. if (check_load_reply(socknum, rbuffer, handle, state, write_error) != 0) {
  462. return false;
  463. }
  464. return true;
  465. }
  466. // Get the service name for a given handle, by querying the daemon.
  467. static std::string get_service_name(int socknum, cpbuffer_t &rbuffer, handle_t handle)
  468. {
  469. auto m = membuf()
  470. .append((char) DINIT_CP_QUERYSERVICENAME)
  471. .append((char) 0)
  472. .append(handle);
  473. write_all_x(socknum, m);
  474. wait_for_reply(rbuffer, socknum);
  475. if (rbuffer[0] != DINIT_RP_SERVICENAME) {
  476. throw cp_read_exception{0};
  477. }
  478. // 1 byte reserved
  479. // uint16_t size
  480. fill_buffer_to(rbuffer, socknum, 2 + sizeof(uint16_t));
  481. uint16_t namesize;
  482. rbuffer.extract(&namesize, 2, sizeof(uint16_t));
  483. rbuffer.consume(2 + sizeof(uint16_t));
  484. std::string name;
  485. do {
  486. if (rbuffer.get_length() == 0) {
  487. fill_some(rbuffer, socknum);
  488. }
  489. size_t to_extract = std::min(size_t(rbuffer.get_length()), namesize - name.length());
  490. size_t contiguous_len = rbuffer.get_contiguous_length(rbuffer.get_ptr(0));
  491. if (contiguous_len <= to_extract) {
  492. name.append(rbuffer.get_ptr(0), contiguous_len);
  493. rbuffer.consume(contiguous_len);
  494. name.append(rbuffer.get_ptr(0), to_extract - contiguous_len);
  495. rbuffer.consume(to_extract - contiguous_len);
  496. }
  497. else {
  498. name.append(rbuffer.get_ptr(0), to_extract);
  499. rbuffer.consume(to_extract);
  500. break;
  501. }
  502. } while (name.length() < namesize);
  503. return name;
  504. }
  505. // Start/stop a service
  506. static int start_stop_service(int socknum, cpbuffer_t &rbuffer, const char *service_name,
  507. command_t command, bool do_pin, bool do_force, bool wait_for_service, bool ignore_unstarted,
  508. bool verbose)
  509. {
  510. using namespace std;
  511. bool do_stop = (command == command_t::STOP_SERVICE || command == command_t::RELEASE_SERVICE);
  512. service_state_t state;
  513. handle_t handle;
  514. if (command != command_t::RESTART_SERVICE && command != command_t::STOP_SERVICE
  515. && command != command_t::RELEASE_SERVICE) {
  516. ignore_unstarted = false;
  517. }
  518. if (! load_service(socknum, rbuffer, service_name, &handle, &state, !ignore_unstarted)) {
  519. return ignore_unstarted ? 0 : 1;
  520. }
  521. service_state_t wanted_state = do_stop ? service_state_t::STOPPED : service_state_t::STARTED;
  522. int pcommand = 0;
  523. switch (command) {
  524. case command_t::STOP_SERVICE:
  525. case command_t::RESTART_SERVICE: // stop, and then start
  526. pcommand = DINIT_CP_STOPSERVICE;
  527. break;
  528. case command_t::RELEASE_SERVICE:
  529. pcommand = DINIT_CP_RELEASESERVICE;
  530. break;
  531. case command_t::START_SERVICE:
  532. pcommand = DINIT_CP_STARTSERVICE;
  533. break;
  534. case command_t::WAKE_SERVICE:
  535. pcommand = DINIT_CP_WAKESERVICE;
  536. break;
  537. default: ;
  538. }
  539. // Need to issue STOPSERVICE/STARTSERVICE
  540. // We'll do this regardless of the current service state / target state, since issuing
  541. // start/stop also sets or clears the "explicitly started" flag on the service.
  542. {
  543. char flags = (do_pin ? 1 : 0) | ((pcommand == DINIT_CP_STOPSERVICE && !do_force) ? 2 : 0);
  544. if (command == command_t::RESTART_SERVICE) {
  545. flags |= 4;
  546. }
  547. auto m = membuf()
  548. .append((char) pcommand)
  549. .append(flags)
  550. .append(handle);
  551. write_all_x(socknum, m);
  552. wait_for_reply(rbuffer, socknum);
  553. auto reply_pkt_h = rbuffer[0];
  554. rbuffer.consume(1); // consume header
  555. if (reply_pkt_h == DINIT_RP_ALREADYSS) {
  556. bool already = (state == wanted_state);
  557. if (verbose) {
  558. cout << "Service " << (already ? "(already) " : "")
  559. << describeState(do_stop) << "." << endl;
  560. }
  561. return 0; // success!
  562. }
  563. if (reply_pkt_h == DINIT_RP_PINNEDSTARTED) {
  564. cerr << "dinitctl: cannot stop service '" << service_name << "' as it is pinned started\n";
  565. return 1;
  566. }
  567. if (reply_pkt_h == DINIT_RP_PINNEDSTOPPED) {
  568. cerr << "dinitctl: cannot start service '" << service_name << "' as it is pinned stopped\n";
  569. return 1;
  570. }
  571. if (reply_pkt_h == DINIT_RP_DEPENDENTS && pcommand == DINIT_CP_STOPSERVICE) {
  572. cerr << "dinitctl: cannot stop service '" << service_name << "' due to the following dependents:\n";
  573. if (command != command_t::RESTART_SERVICE) {
  574. cerr << "(only direct dependents are listed. Exercise caution before using '--force' !!)\n";
  575. }
  576. // size_t number, N * handle_t handles
  577. size_t number;
  578. rbuffer.fill_to(socknum, sizeof(number));
  579. rbuffer.extract(&number, 0, sizeof(number));
  580. rbuffer.consume(sizeof(number));
  581. std::vector<handle_t> handles;
  582. handles.reserve(number);
  583. for (size_t i = 0; i < number; i++) {
  584. handle_t handle;
  585. rbuffer.fill_to(socknum, sizeof(handle_t));
  586. rbuffer.extract(&handle, 0, sizeof(handle));
  587. handles.push_back(handle);
  588. rbuffer.consume(sizeof(handle));
  589. }
  590. // Print the directly affected dependents:
  591. cerr << " ";
  592. for (handle_t handle : handles) {
  593. cerr << " " << get_service_name(socknum, rbuffer, handle);
  594. }
  595. cerr << "\n";
  596. return 1;
  597. }
  598. if (reply_pkt_h == DINIT_RP_NAK && command == command_t::RESTART_SERVICE) {
  599. if (ignore_unstarted) {
  600. if (verbose) {
  601. cout << "Service '" << service_name << "' is not currently started.\n";
  602. }
  603. return 0;
  604. }
  605. cerr << "dinitctl: cannot restart service; service not started.\n";
  606. return 1;
  607. }
  608. if (reply_pkt_h == DINIT_RP_NAK && command == command_t::WAKE_SERVICE) {
  609. cerr << "dinitctl: service has no active dependents, cannot wake.\n";
  610. return 1;
  611. }
  612. if (reply_pkt_h == DINIT_RP_SHUTTINGDOWN) {
  613. cerr << "dinitctl: cannot start/restart/wake service, shutdown is in progress.\n";
  614. return 1;
  615. }
  616. if (reply_pkt_h != DINIT_RP_ACK && reply_pkt_h != DINIT_RP_ALREADYSS) {
  617. cerr << "dinitctl: protocol error." << endl;
  618. return 1;
  619. }
  620. }
  621. if (! wait_for_service) {
  622. if (verbose) {
  623. cout << "Issued " << describeVerb(do_stop) << " command successfully for service '"
  624. << service_name << "'." << endl;
  625. }
  626. return 0;
  627. }
  628. service_event_t completionEvent;
  629. service_event_t cancelledEvent;
  630. if (do_stop) {
  631. completionEvent = service_event_t::STOPPED;
  632. cancelledEvent = service_event_t::STOPCANCELLED;
  633. }
  634. else {
  635. completionEvent = service_event_t::STARTED;
  636. cancelledEvent = service_event_t::STARTCANCELLED;
  637. }
  638. // Wait until service started:
  639. int r = rbuffer.fill_to(socknum, 2);
  640. while (r > 0) {
  641. if (rbuffer[0] >= 100) {
  642. int pktlen = (unsigned char) rbuffer[1];
  643. fill_buffer_to(rbuffer, socknum, pktlen);
  644. if (rbuffer[0] == DINIT_IP_SERVICEEVENT) {
  645. handle_t ev_handle;
  646. rbuffer.extract((char *) &ev_handle, 2, sizeof(ev_handle));
  647. service_event_t event = static_cast<service_event_t>(rbuffer[2 + sizeof(ev_handle)]);
  648. if (ev_handle == handle) {
  649. if (event == completionEvent) {
  650. if (verbose) {
  651. cout << "Service '" << service_name << "' " << describeState(do_stop) << "." << endl;
  652. }
  653. return 0;
  654. }
  655. else if (event == cancelledEvent) {
  656. if (verbose) {
  657. cout << "Service '" << service_name << "' " << describeVerb(do_stop) << " cancelled." << endl;
  658. }
  659. return 1;
  660. }
  661. else if (! do_stop && event == service_event_t::FAILEDSTART) {
  662. if (verbose) {
  663. cout << "Service '" << service_name << "' failed to start." << endl;
  664. }
  665. return 1;
  666. }
  667. }
  668. }
  669. rbuffer.consume(pktlen);
  670. r = rbuffer.fill_to(socknum, 2);
  671. }
  672. else {
  673. // Not an information packet?
  674. cerr << "dinitctl: protocol error" << endl;
  675. return 1;
  676. }
  677. }
  678. if (r == -1) {
  679. perror("dinitctl: read");
  680. }
  681. else {
  682. cerr << "protocol error (connection closed by server)" << endl;
  683. }
  684. return 1;
  685. }
  686. // Issue a "load service" command (DINIT_CP_LOADSERVICE), without waiting for
  687. // a response. Returns 1 on failure (with error logged), 0 on success.
  688. static int issue_load_service(int socknum, const char *service_name, bool find_only)
  689. {
  690. // Build buffer;
  691. uint16_t sname_len = strlen(service_name);
  692. int bufsize = 3 + sname_len;
  693. std::unique_ptr<char[]> ubuf(new char[bufsize]);
  694. auto buf = ubuf.get();
  695. buf[0] = find_only ? DINIT_CP_FINDSERVICE : DINIT_CP_LOADSERVICE;
  696. memcpy(buf + 1, &sname_len, 2);
  697. memcpy(buf + 3, service_name, sname_len);
  698. write_all_x(socknum, buf, bufsize);
  699. return 0;
  700. }
  701. // Check that a "load service" reply was received, and that the requested service was found.
  702. // state_p may be null.
  703. static int check_load_reply(int socknum, cpbuffer_t &rbuffer, handle_t *handle_p, service_state_t *state_p, bool write_error)
  704. {
  705. using namespace std;
  706. if (rbuffer[0] == DINIT_RP_SERVICERECORD) {
  707. fill_buffer_to(rbuffer, socknum, 2 + sizeof(*handle_p));
  708. rbuffer.extract((char *) handle_p, 2, sizeof(*handle_p));
  709. if (state_p) *state_p = static_cast<service_state_t>(rbuffer[1]);
  710. //target_state = static_cast<service_state_t>(rbuffer[2 + sizeof(handle)]);
  711. rbuffer.consume(3 + sizeof(*handle_p));
  712. return 0;
  713. }
  714. else if (rbuffer[0] == DINIT_RP_NOSERVICE) {
  715. if (write_error) {
  716. cerr << "dinitctl: failed to find/load service." << endl;
  717. }
  718. return 1;
  719. }
  720. else {
  721. throw dinit_protocol_error();
  722. }
  723. }
  724. static int unpin_service(int socknum, cpbuffer_t &rbuffer, const char *service_name, bool verbose)
  725. {
  726. using namespace std;
  727. handle_t handle;
  728. // Build buffer;
  729. if (! load_service(socknum, rbuffer, service_name, &handle, nullptr)) {
  730. return 1;
  731. }
  732. // Issue UNPIN command.
  733. {
  734. auto m = membuf()
  735. .append<char>(DINIT_CP_UNPINSERVICE)
  736. .append(handle);
  737. write_all_x(socknum, m);
  738. wait_for_reply(rbuffer, socknum);
  739. if (rbuffer[0] != DINIT_RP_ACK) {
  740. cerr << "dinitctl: protocol error." << endl;
  741. return 1;
  742. }
  743. rbuffer.consume(1);
  744. }
  745. if (verbose) {
  746. cout << "Service '" << service_name << "' unpinned." << endl;
  747. }
  748. return 0;
  749. }
  750. static int unload_service(int socknum, cpbuffer_t &rbuffer, const char *service_name, bool verbose)
  751. {
  752. using namespace std;
  753. if (issue_load_service(socknum, service_name, true) == 1) {
  754. return 1;
  755. }
  756. wait_for_reply(rbuffer, socknum);
  757. handle_t handle;
  758. if (rbuffer[0] == DINIT_RP_NOSERVICE) {
  759. cerr << "dinitctl: service not loaded." << endl;
  760. return 1;
  761. }
  762. if (check_load_reply(socknum, rbuffer, &handle, nullptr) != 0) {
  763. return 1;
  764. }
  765. // Issue UNLOAD command.
  766. {
  767. auto m = membuf()
  768. .append<char>(DINIT_CP_UNLOADSERVICE)
  769. .append(handle);
  770. write_all_x(socknum, m);
  771. wait_for_reply(rbuffer, socknum);
  772. if (rbuffer[0] == DINIT_RP_NAK) {
  773. cerr << "dinitctl: could not unload service; service not stopped, or is a dependency of "
  774. "other service." << endl;
  775. return 1;
  776. }
  777. if (rbuffer[0] != DINIT_RP_ACK) {
  778. cerr << "dinitctl: protocol error." << endl;
  779. return 1;
  780. }
  781. rbuffer.consume(1);
  782. }
  783. if (verbose) {
  784. cout << "Service '" << service_name << "' unloaded." << endl;
  785. }
  786. return 0;
  787. }
  788. static int reload_service(int socknum, cpbuffer_t &rbuffer, const char *service_name, bool verbose)
  789. {
  790. using namespace std;
  791. if (issue_load_service(socknum, service_name, true) == 1) {
  792. return 1;
  793. }
  794. wait_for_reply(rbuffer, socknum);
  795. handle_t handle;
  796. if (rbuffer[0] == DINIT_RP_NOSERVICE) {
  797. cerr << "dinitctl: service not loaded." << endl;
  798. return 1;
  799. }
  800. if (check_load_reply(socknum, rbuffer, &handle, nullptr) != 0) {
  801. return 1;
  802. }
  803. // Issue RELOAD command.
  804. {
  805. auto m = membuf()
  806. .append<char>(DINIT_CP_RELOADSERVICE)
  807. .append(handle);
  808. write_all_x(socknum, m);
  809. wait_for_reply(rbuffer, socknum);
  810. if (rbuffer[0] == DINIT_RP_NAK) {
  811. cerr << "dinitctl: could not reload service; service in wrong state, incompatible change, "
  812. "or bad service description." << endl;
  813. return 1;
  814. }
  815. if (rbuffer[0] != DINIT_RP_ACK) {
  816. cerr << "dinitctl: protocol error." << endl;
  817. return 1;
  818. }
  819. rbuffer.consume(1);
  820. }
  821. if (verbose) {
  822. cout << "Service '" << service_name << "' reloaded." << endl;
  823. }
  824. return 0;
  825. }
  826. static int list_services(int socknum, cpbuffer_t &rbuffer)
  827. {
  828. using namespace std;
  829. char cmdbuf[] = { (char)DINIT_CP_LISTSERVICES };
  830. write_all_x(socknum, cmdbuf, 1);
  831. wait_for_reply(rbuffer, socknum);
  832. while (rbuffer[0] == DINIT_RP_SVCINFO) {
  833. int hdrsize = 8 + std::max(sizeof(int), sizeof(pid_t));
  834. fill_buffer_to(rbuffer, socknum, hdrsize);
  835. int nameLen = rbuffer[1];
  836. service_state_t current = static_cast<service_state_t>(rbuffer[2]);
  837. service_state_t target = static_cast<service_state_t>(rbuffer[3]);
  838. int console_flags = rbuffer[4];
  839. bool has_console = (console_flags & 2) != 0;
  840. bool waiting_console = (console_flags & 1) != 0;
  841. bool was_skipped = (console_flags & 4) != 0;
  842. bool marked_active = (console_flags & 8) != 0;
  843. stopped_reason_t stop_reason = static_cast<stopped_reason_t>(rbuffer[5]);
  844. pid_t service_pid;
  845. int exit_status;
  846. if (current != service_state_t::STOPPED) {
  847. rbuffer.extract((char *)&service_pid, 8, sizeof(service_pid));
  848. }
  849. else {
  850. rbuffer.extract((char *)&exit_status, 8, sizeof(exit_status));
  851. }
  852. fill_buffer_to(rbuffer, socknum, nameLen + hdrsize);
  853. char *name_ptr = rbuffer.get_ptr(hdrsize);
  854. int clength = std::min(rbuffer.get_contiguous_length(name_ptr), nameLen);
  855. string name = string(name_ptr, clength);
  856. name.append(rbuffer.get_buf_base(), nameLen - clength);
  857. cout << "[";
  858. // [ ] if marked active; otherwise, { } if target state is STARTED
  859. // + if started, 's' if skipped, space otherwise
  860. char lbracket = target == service_state_t::STARTED ? '{' : ' ';
  861. char rbracket = target == service_state_t::STARTED ? '}' : ' ';
  862. cout << (marked_active ? '[' : lbracket);
  863. if (current == service_state_t::STARTED) {
  864. cout << (was_skipped ? 's' : '+');
  865. }
  866. else {
  867. cout << ' ';
  868. }
  869. cout << (marked_active ? ']' : rbracket);
  870. if (current == service_state_t::STARTING) {
  871. cout << "<<";
  872. }
  873. else if (current == service_state_t::STOPPING) {
  874. cout << ">>";
  875. }
  876. else {
  877. cout << " ";
  878. }
  879. cout << (target == service_state_t::STOPPED ? '{' : ' ');
  880. if (current == service_state_t::STOPPED) {
  881. bool did_fail = false;
  882. if (stop_reason == stopped_reason_t::TERMINATED) {
  883. if (!WIFEXITED(exit_status) || WEXITSTATUS(exit_status) != 0) {
  884. did_fail = true;
  885. }
  886. }
  887. else did_fail = (stop_reason != stopped_reason_t::NORMAL);
  888. cout << (did_fail ? 'X' : '-');
  889. }
  890. else {
  891. cout << ' ';
  892. }
  893. cout << (target == service_state_t::STOPPED ? '}' : ' ');
  894. cout << "] " << name;
  895. if (current != service_state_t::STOPPED && service_pid != -1) {
  896. cout << " (pid: " << service_pid << ")";
  897. }
  898. if (current == service_state_t::STOPPED && stop_reason == stopped_reason_t::TERMINATED) {
  899. if (WIFEXITED(exit_status)) {
  900. cout << " (exit status: " << WEXITSTATUS(exit_status) << ")";
  901. }
  902. else if (WIFSIGNALED(exit_status)) {
  903. cout << " (signal: " << WTERMSIG(exit_status) << ")";
  904. }
  905. }
  906. if (has_console) {
  907. cout << " (has console)";
  908. }
  909. else if (waiting_console) {
  910. cout << " (waiting for console)";
  911. }
  912. cout << endl;
  913. rbuffer.consume(hdrsize + nameLen);
  914. wait_for_reply(rbuffer, socknum);
  915. }
  916. if (rbuffer[0] != DINIT_RP_LISTDONE) {
  917. cerr << "dinitctl: control socket protocol error" << endl;
  918. return 1;
  919. }
  920. return 0;
  921. }
  922. static void print_termination_details(int exit_status)
  923. {
  924. using namespace std;
  925. if (WIFSIGNALED(exit_status)) {
  926. cout << "signalled - signal ";
  927. cout << WTERMSIG(exit_status);
  928. }
  929. else if (WIFEXITED(exit_status)) {
  930. cout << "exited - status ";
  931. cout << WEXITSTATUS(exit_status);
  932. }
  933. else {
  934. cout << "unknown";
  935. }
  936. }
  937. static int service_status(int socknum, cpbuffer_t &rbuffer, const char *service_name)
  938. {
  939. using namespace std;
  940. if (issue_load_service(socknum, service_name, true) == 1) {
  941. return 1;
  942. }
  943. wait_for_reply(rbuffer, socknum);
  944. handle_t handle;
  945. if (rbuffer[0] == DINIT_RP_NOSERVICE) {
  946. cerr << "dinitctl: service not loaded." << endl;
  947. return 1;
  948. }
  949. if (check_load_reply(socknum, rbuffer, &handle, nullptr) != 0) {
  950. return 1;
  951. }
  952. // Issue STATUS request
  953. {
  954. auto m = membuf()
  955. .append<char>(DINIT_CP_SERVICESTATUS)
  956. .append(handle);
  957. write_all_x(socknum, m);
  958. wait_for_reply(rbuffer, socknum);
  959. if (rbuffer[0] != DINIT_RP_SERVICESTATUS) {
  960. cerr << "dinitctl: protocol error." << endl;
  961. return 1;
  962. }
  963. rbuffer.consume(1);
  964. int statussize = 6 + std::max(sizeof(pid_t), sizeof(int));;
  965. fill_buffer_to(rbuffer, socknum, statussize + 1 /* reserved */);
  966. rbuffer.consume(1);
  967. service_state_t current = static_cast<service_state_t>(rbuffer[0]);
  968. service_state_t target = static_cast<service_state_t>(rbuffer[1]);
  969. int console_flags = rbuffer[2];
  970. bool has_console = (console_flags & 2) != 0;
  971. bool waiting_console = (console_flags & 1) != 0;
  972. bool was_skipped = (console_flags & 4) != 0;
  973. bool marked_active = (console_flags & 8) != 0;
  974. stopped_reason_t stop_reason = static_cast<stopped_reason_t>(rbuffer[3]);
  975. pid_t service_pid = -1;
  976. int exit_status = 0;
  977. if (current != service_state_t::STOPPED) {
  978. rbuffer.extract((char *)&service_pid, 6, sizeof(service_pid));
  979. }
  980. else {
  981. rbuffer.extract((char *)&exit_status, 6, sizeof(exit_status));
  982. }
  983. cout << "Service: " << service_name << "\n"
  984. " State: ";
  985. switch (current) {
  986. case service_state_t::STOPPED:
  987. cout << "STOPPED";
  988. switch (stop_reason) {
  989. case stopped_reason_t::DEPFAILED:
  990. cout << " (dependency failed/terminated)";
  991. break;
  992. case stopped_reason_t::FAILED:
  993. cout << " (failed to start";
  994. if (exit_status != 0) {
  995. cout << "; ";
  996. print_termination_details(exit_status);
  997. }
  998. cout << ")";
  999. break;
  1000. case stopped_reason_t::EXECFAILED:
  1001. uint16_t launch_stage;
  1002. rbuffer.extract((char *)&launch_stage, 4, 2);
  1003. cout << " (could not be launched)\n";
  1004. cout << " Stage: " << exec_stage_descriptions[launch_stage] << "\n";
  1005. cout << " Error: " << strerror(exit_status);
  1006. break;
  1007. case stopped_reason_t::TERMINATED:
  1008. cout << " (terminated";
  1009. if (exit_status != 0) {
  1010. cout << "; ";
  1011. print_termination_details(exit_status);
  1012. }
  1013. cout << ")";
  1014. break;
  1015. case stopped_reason_t::TIMEDOUT:
  1016. cout << " (start timed out)";
  1017. break;
  1018. case stopped_reason_t::NORMAL:
  1019. break;
  1020. }
  1021. break;
  1022. case service_state_t::STARTING:
  1023. cout << "STARTING";
  1024. if (target == service_state_t::STOPPED) {
  1025. cout << " (target state: STOPPED)";
  1026. }
  1027. break;
  1028. case service_state_t::STARTED:
  1029. cout << "STARTED";
  1030. if (was_skipped) {
  1031. cout << " (startup skipped)";
  1032. }
  1033. break;
  1034. case service_state_t::STOPPING:
  1035. cout << "STOPPING";
  1036. if (target == service_state_t::STARTED) {
  1037. cout << " (target state: STARTED)";
  1038. }
  1039. if (exit_status != 0) {
  1040. cout << "(terminated ;";
  1041. print_termination_details(exit_status);
  1042. cout << ")";
  1043. }
  1044. }
  1045. if (has_console) {
  1046. cout << " (holding console)";
  1047. }
  1048. if (waiting_console) {
  1049. cout << " (waiting for console)";
  1050. }
  1051. cout << "\n";
  1052. if (target == service_state_t::STARTED) {
  1053. cout << " Activation: ";
  1054. if (marked_active) {
  1055. cout << "explicitly started\n";
  1056. }
  1057. else {
  1058. cout << "start due to dependent(s)\n";
  1059. }
  1060. }
  1061. if (service_pid != -1) {
  1062. cout << " Process ID: " << service_pid << "\n";
  1063. }
  1064. }
  1065. return 0;
  1066. }
  1067. static int add_remove_dependency(int socknum, cpbuffer_t &rbuffer, bool add,
  1068. const char *service_from, const char *service_to, dependency_type dep_type, bool verbose)
  1069. {
  1070. using namespace std;
  1071. handle_t from_handle;
  1072. handle_t to_handle;
  1073. if (! load_service(socknum, rbuffer, service_from, &from_handle, nullptr)
  1074. || ! load_service(socknum, rbuffer, service_to, &to_handle, nullptr)) {
  1075. return 1;
  1076. }
  1077. if (from_handle == to_handle) {
  1078. cerr << "dinitctl: can not add/remove a dependency from a service to itself" << endl;
  1079. return 1;
  1080. }
  1081. auto m = membuf()
  1082. .append<char>(add ? (char)DINIT_CP_ADD_DEP : (char)DINIT_CP_REM_DEP)
  1083. .append(static_cast<char>(dep_type))
  1084. .append(from_handle)
  1085. .append(to_handle);
  1086. write_all_x(socknum, m);
  1087. wait_for_reply(rbuffer, socknum);
  1088. // check reply
  1089. if (rbuffer[0] == DINIT_RP_NAK) {
  1090. cerr << "dinitctl: could not add dependency: circular dependency or wrong state" << endl;
  1091. return 1;
  1092. }
  1093. if (rbuffer[0] != DINIT_RP_ACK) {
  1094. cerr << "dinitctl: control socket protocol error" << endl;
  1095. return 1;
  1096. }
  1097. if (verbose) {
  1098. std::cout << "Service '" << service_from << "': dependency '" << service_to << "' " << (add ? "added" : "removed") << endl;
  1099. }
  1100. return 0;
  1101. }
  1102. static int shutdown_dinit(int socknum, cpbuffer_t &rbuffer, bool verbose)
  1103. {
  1104. // TODO support no-wait option.
  1105. using namespace std;
  1106. auto m = membuf()
  1107. .append<char>(DINIT_CP_SHUTDOWN)
  1108. .append(static_cast<char>(shutdown_type_t::HALT));
  1109. write_all_x(socknum, m);
  1110. wait_for_reply(rbuffer, socknum);
  1111. if (rbuffer[0] != DINIT_RP_ACK) {
  1112. cerr << "dinitctl: control socket protocol error" << endl;
  1113. return 1;
  1114. }
  1115. if (verbose) {
  1116. std::cout << "Shutting down dinit..." << std::endl;
  1117. }
  1118. // Now wait for rollback complete, by waiting for the connection to close:
  1119. try {
  1120. while (true) {
  1121. wait_for_info(rbuffer, socknum);
  1122. rbuffer.consume(rbuffer[1]);
  1123. }
  1124. }
  1125. catch (cp_read_exception &exc) {
  1126. // Assume that the connection closed.
  1127. }
  1128. if (verbose) {
  1129. std::cout << "Connection closed." << std::endl;
  1130. }
  1131. return 0;
  1132. }
  1133. // exception for cancelling a service operation
  1134. class service_op_cancel { };
  1135. static int enable_disable_service(int socknum, cpbuffer_t &rbuffer, const char *from, const char *to,
  1136. bool enable, bool verbose)
  1137. {
  1138. using namespace std;
  1139. service_state_t from_state = service_state_t::STARTED;
  1140. handle_t from_handle;
  1141. handle_t to_handle;
  1142. if (! load_service(socknum, rbuffer, from, &from_handle, &from_state)
  1143. || ! load_service(socknum, rbuffer, to, &to_handle, nullptr)) {
  1144. return 1;
  1145. }
  1146. // Get service load path
  1147. char buf[1] = { DINIT_CP_QUERY_LOAD_MECH };
  1148. write_all_x(socknum, buf, 1);
  1149. wait_for_reply(rbuffer, socknum);
  1150. if (rbuffer[0] != DINIT_RP_LOADER_MECH) {
  1151. cerr << "dinitctl: control socket protocol error" << endl;
  1152. return 1;
  1153. }
  1154. // Packet type, load mechanism type, packet size:
  1155. fill_buffer_to(rbuffer, socknum, 2 + sizeof(uint32_t));
  1156. if (rbuffer[1] != SSET_TYPE_DIRLOAD) {
  1157. cerr << "dinitctl: unknown configuration, unable to load service descriptions" << endl;
  1158. return 1;
  1159. }
  1160. vector<string> paths;
  1161. uint32_t pktsize;
  1162. rbuffer.extract(&pktsize, 2, sizeof(uint32_t));
  1163. fill_buffer_to(rbuffer, socknum, 2 + sizeof(uint32_t) * 3); // path entries, cwd length
  1164. uint32_t path_entries; // number of service directories
  1165. rbuffer.extract(&path_entries, 2 + sizeof(uint32_t), sizeof(uint32_t));
  1166. uint32_t cwd_len;
  1167. rbuffer.extract(&cwd_len, 2 + sizeof(uint32_t) * 2, sizeof(uint32_t));
  1168. rbuffer.consume(2 + sizeof(uint32_t) * 3);
  1169. pktsize -= 2 + sizeof(uint32_t) * 3;
  1170. // Read current working directory of daemon:
  1171. std::string dinit_cwd = read_string(socknum, rbuffer, cwd_len);
  1172. // dinit daemon base directory against which service paths are resolved is in dinit_cwd
  1173. for (int i = 0; i < (int)path_entries; i++) {
  1174. uint32_t plen;
  1175. fill_buffer_to(rbuffer, socknum, sizeof(uint32_t));
  1176. rbuffer.extract(&plen, 0, sizeof(uint32_t));
  1177. rbuffer.consume(sizeof(uint32_t));
  1178. paths.push_back(read_string(socknum, rbuffer, plen));
  1179. }
  1180. // all service directories are now in the 'paths' vector
  1181. // Load/read service description for 'from' service:
  1182. ifstream service_file;
  1183. string service_file_path;
  1184. for (std::string path : paths) {
  1185. string test_path = combine_paths(combine_paths(dinit_cwd, path.c_str()), from);
  1186. service_file.open(test_path.c_str(), ios::in);
  1187. if (service_file) {
  1188. service_file_path = test_path;
  1189. break;
  1190. }
  1191. }
  1192. if (! service_file) {
  1193. cerr << "dinitctl: could not locate service file for service '" << from << "'" << endl;
  1194. return 1;
  1195. }
  1196. // We now need to read the service file, identify the waits-for.d directory (bail out if more than one),
  1197. // make sure the service is not listed as a dependency individually.
  1198. string waits_for_d;
  1199. try {
  1200. process_service_file(from, service_file, [&](string &line, string &setting,
  1201. dinit_load::string_iterator i, dinit_load::string_iterator end) -> void {
  1202. if (setting == "waits-for" || setting == "depends-on" || setting == "depends-ms") {
  1203. string dname = dinit_load::read_setting_value(i, end);
  1204. if (dname == to) {
  1205. // There is already a dependency
  1206. cerr << "dinitctl: there is a fixed dependency to service '" << to
  1207. << "' in the service description of '" << from << "'." << endl;
  1208. throw service_op_cancel();
  1209. }
  1210. }
  1211. else if (setting == "waits-for.d") {
  1212. string dname = dinit_load::read_setting_value(i, end);
  1213. if (! waits_for_d.empty()) {
  1214. cerr << "dinitctl: service '" << from << "' has multiple waits-for.d directories "
  1215. << "specified in service description" << endl;
  1216. throw service_op_cancel();
  1217. }
  1218. waits_for_d = std::move(dname);
  1219. }
  1220. });
  1221. }
  1222. catch (const service_op_cancel &cexc) {
  1223. return 1;
  1224. }
  1225. // If the from service has no waits-for.d specified, we can't continue
  1226. if (waits_for_d.empty()) {
  1227. cerr << "dinitctl: service '" << from << "' has no waits-for.d directory specified" << endl;
  1228. return 1;
  1229. }
  1230. // The waits-for.d path is relative to the service file path, combine:
  1231. string waits_for_d_full = combine_paths(parent_path(service_file_path), waits_for_d.c_str());
  1232. // check if dependency already exists
  1233. string dep_link_path = combine_paths(waits_for_d_full, to);
  1234. struct stat stat_buf;
  1235. if (lstat(dep_link_path.c_str(), &stat_buf) == -1) {
  1236. if (errno != ENOENT) {
  1237. cerr << "dinitctl: checking for existing dependency link: " << dep_link_path << ": "
  1238. << strerror(errno) << endl;
  1239. return 1;
  1240. }
  1241. }
  1242. else {
  1243. // dependency already exists
  1244. if (enable) {
  1245. cerr << "dinitctl: service already enabled." << endl;
  1246. return 1;
  1247. }
  1248. }
  1249. // warn if 'from' service is not started
  1250. if (enable && from_state != service_state_t::STARTED) {
  1251. cerr << "dinitctl: warning: enabling dependency for non-started service" << endl;
  1252. }
  1253. // add/remove dependency
  1254. constexpr int enable_pktsize = 2 + sizeof(handle_t) * 2;
  1255. char cmdbuf[enable_pktsize] = { char(enable ? DINIT_CP_ENABLESERVICE : DINIT_CP_REM_DEP),
  1256. char(dependency_type::WAITS_FOR)};
  1257. memcpy(cmdbuf + 2, &from_handle, sizeof(from_handle));
  1258. memcpy(cmdbuf + 2 + sizeof(from_handle), &to_handle, sizeof(to_handle));
  1259. write_all_x(socknum, cmdbuf, enable_pktsize);
  1260. wait_for_reply(rbuffer, socknum);
  1261. // check reply
  1262. if (enable && rbuffer[0] == DINIT_RP_NAK) {
  1263. cerr << "dinitctl: could not enable service: possible circular dependency" << endl;
  1264. return 1;
  1265. }
  1266. if (rbuffer[0] != DINIT_RP_ACK) {
  1267. cerr << "dinitctl: control socket protocol error" << endl;
  1268. return 1;
  1269. }
  1270. // create link
  1271. if (enable) {
  1272. if (symlink((string("../") + to).c_str(), dep_link_path.c_str()) == -1) {
  1273. cerr << "dinitctl: could not create symlink at " << dep_link_path << ": " << strerror(errno)
  1274. << "\n" "dinitctl: note: service was enabled for now; persistent enable failed."
  1275. << endl;
  1276. return 1;
  1277. }
  1278. }
  1279. else {
  1280. if (unlink(dep_link_path.c_str()) == -1) {
  1281. cerr << "dinitctl: could not unlink dependency entry " << dep_link_path << ": "
  1282. << strerror(errno) << "\n"
  1283. "dinitctl: note: service was disabled for now; persistent disable failed." << endl;
  1284. return 1;
  1285. }
  1286. }
  1287. if (verbose) {
  1288. cout << "Service '" << to << "' has been " << (enable ? "enabled" : "disabled") << "." << endl;
  1289. }
  1290. return 0;
  1291. }
  1292. static int do_setenv(int socknum, cpbuffer_t &rbuffer, std::vector<const char *> &env_names)
  1293. {
  1294. using namespace std;
  1295. string buf;
  1296. for (const char *envp : env_names) {
  1297. buf.clear();
  1298. buf.reserve(6);
  1299. // protocol message and size space
  1300. buf.push_back(DINIT_CP_SETENV);
  1301. buf.append(2, 0);
  1302. // either full var or name
  1303. auto elen = strlen(envp);
  1304. buf.append(envp, elen);
  1305. // = not found, get value from environment
  1306. if (!memchr(envp, '=', elen)) {
  1307. buf.push_back('=');
  1308. auto *envv = getenv(envp);
  1309. if (envv) {
  1310. buf.append(envv);
  1311. }
  1312. }
  1313. uint16_t bufs = buf.size() - 3;
  1314. // sanitize length early on
  1315. if (bufs > (1024 - 3)) {
  1316. auto eq = buf.find('=', 3);
  1317. auto name = buf.substr(3, eq - 3);
  1318. cerr << "dinitctl: environment variable '" << name << "' too long." << endl;
  1319. return 1;
  1320. }
  1321. // set size in protocol message
  1322. memcpy(&buf[1], &bufs, 2);
  1323. // send
  1324. write_all_x(socknum, buf.data(), bufs + 3);
  1325. wait_for_reply(rbuffer, socknum);
  1326. if (rbuffer[0] == DINIT_RP_BADREQ) {
  1327. cerr << "dinitctl: failed to export environment." << endl;
  1328. return 1;
  1329. } else if (rbuffer[0] != DINIT_RP_ACK) {
  1330. throw dinit_protocol_error();
  1331. }
  1332. rbuffer.consume(1);
  1333. }
  1334. return 0;
  1335. }