dinitctl.cc 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582
  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. // Wait for a service to reached stopped (do_stop == true) or started (do_stop == false) state.
  506. // Returns 0 if the service started/stopped, 1 if start/stop was cancelled or failed.
  507. static int wait_service_state(int socknum, cpbuffer_t &rbuffer, handle_t handle,
  508. const std::string &service_name, bool do_stop, bool verbose)
  509. {
  510. using std::cout;
  511. using std::cerr;
  512. using std::endl;
  513. service_event_t completionEvent;
  514. service_event_t cancelledEvent;
  515. if (do_stop) {
  516. completionEvent = service_event_t::STOPPED;
  517. cancelledEvent = service_event_t::STOPCANCELLED;
  518. }
  519. else {
  520. completionEvent = service_event_t::STARTED;
  521. cancelledEvent = service_event_t::STARTCANCELLED;
  522. }
  523. // Wait until service started:
  524. int r = rbuffer.fill_to(socknum, 2);
  525. while (r > 0) {
  526. if (rbuffer[0] >= 100) {
  527. int pktlen = (unsigned char) rbuffer[1];
  528. fill_buffer_to(rbuffer, socknum, pktlen);
  529. if (rbuffer[0] == DINIT_IP_SERVICEEVENT) {
  530. handle_t ev_handle;
  531. rbuffer.extract((char *) &ev_handle, 2, sizeof(ev_handle));
  532. service_event_t event = static_cast<service_event_t>(rbuffer[2 + sizeof(ev_handle)]);
  533. if (ev_handle == handle) {
  534. if (event == completionEvent) {
  535. if (verbose) {
  536. cout << "Service '" << service_name << "' " << describeState(do_stop) << "." << endl;
  537. }
  538. return 0;
  539. }
  540. else if (event == cancelledEvent) {
  541. if (verbose) {
  542. cout << "Service '" << service_name << "' " << describeVerb(do_stop) << " cancelled." << endl;
  543. }
  544. return 1;
  545. }
  546. else if (! do_stop && event == service_event_t::FAILEDSTART) {
  547. if (verbose) {
  548. cout << "Service '" << service_name << "' failed to start." << endl;
  549. }
  550. return 1;
  551. }
  552. }
  553. }
  554. rbuffer.consume(pktlen);
  555. r = rbuffer.fill_to(socknum, 2);
  556. }
  557. else {
  558. // Not an information packet?
  559. throw dinit_protocol_error();
  560. }
  561. }
  562. if (r == -1) {
  563. perror("dinitctl: read");
  564. }
  565. else {
  566. throw dinit_protocol_error();
  567. }
  568. return 1;
  569. }
  570. // Start/stop a service
  571. static int start_stop_service(int socknum, cpbuffer_t &rbuffer, const char *service_name,
  572. command_t command, bool do_pin, bool do_force, bool wait_for_service, bool ignore_unstarted,
  573. bool verbose)
  574. {
  575. using namespace std;
  576. bool do_stop = (command == command_t::STOP_SERVICE || command == command_t::RELEASE_SERVICE);
  577. service_state_t state;
  578. handle_t handle;
  579. if (command != command_t::RESTART_SERVICE && command != command_t::STOP_SERVICE
  580. && command != command_t::RELEASE_SERVICE) {
  581. ignore_unstarted = false;
  582. }
  583. if (! load_service(socknum, rbuffer, service_name, &handle, &state, !ignore_unstarted)) {
  584. return ignore_unstarted ? 0 : 1;
  585. }
  586. service_state_t wanted_state = do_stop ? service_state_t::STOPPED : service_state_t::STARTED;
  587. int pcommand = 0;
  588. switch (command) {
  589. case command_t::STOP_SERVICE:
  590. case command_t::RESTART_SERVICE: // stop, and then start
  591. pcommand = DINIT_CP_STOPSERVICE;
  592. break;
  593. case command_t::RELEASE_SERVICE:
  594. pcommand = DINIT_CP_RELEASESERVICE;
  595. break;
  596. case command_t::START_SERVICE:
  597. pcommand = DINIT_CP_STARTSERVICE;
  598. break;
  599. case command_t::WAKE_SERVICE:
  600. pcommand = DINIT_CP_WAKESERVICE;
  601. break;
  602. default: ;
  603. }
  604. // Need to issue STOPSERVICE/STARTSERVICE
  605. // We'll do this regardless of the current service state / target state, since issuing
  606. // start/stop also sets or clears the "explicitly started" flag on the service.
  607. {
  608. char flags = (do_pin ? 1 : 0) | ((pcommand == DINIT_CP_STOPSERVICE && !do_force) ? 2 : 0);
  609. if (command == command_t::RESTART_SERVICE) {
  610. flags |= 4;
  611. }
  612. auto m = membuf()
  613. .append((char) pcommand)
  614. .append(flags)
  615. .append(handle);
  616. write_all_x(socknum, m);
  617. wait_for_reply(rbuffer, socknum);
  618. auto reply_pkt_h = rbuffer[0];
  619. rbuffer.consume(1); // consume header
  620. if (reply_pkt_h == DINIT_RP_ALREADYSS) {
  621. bool already = (state == wanted_state);
  622. if (verbose) {
  623. cout << "Service " << (already ? "(already) " : "")
  624. << describeState(do_stop) << "." << endl;
  625. }
  626. return 0; // success!
  627. }
  628. if (reply_pkt_h == DINIT_RP_PINNEDSTARTED) {
  629. cerr << "dinitctl: cannot stop service '" << service_name << "' as it is pinned started\n";
  630. return 1;
  631. }
  632. if (reply_pkt_h == DINIT_RP_PINNEDSTOPPED) {
  633. cerr << "dinitctl: cannot start service '" << service_name << "' as it is pinned stopped\n";
  634. return 1;
  635. }
  636. if (reply_pkt_h == DINIT_RP_DEPENDENTS && pcommand == DINIT_CP_STOPSERVICE) {
  637. cerr << "dinitctl: cannot stop service '" << service_name << "' due to the following dependents:\n";
  638. if (command != command_t::RESTART_SERVICE) {
  639. cerr << "(only direct dependents are listed. Exercise caution before using '--force' !!)\n";
  640. }
  641. // size_t number, N * handle_t handles
  642. size_t number;
  643. rbuffer.fill_to(socknum, sizeof(number));
  644. rbuffer.extract(&number, 0, sizeof(number));
  645. rbuffer.consume(sizeof(number));
  646. std::vector<handle_t> handles;
  647. handles.reserve(number);
  648. for (size_t i = 0; i < number; i++) {
  649. handle_t handle;
  650. rbuffer.fill_to(socknum, sizeof(handle_t));
  651. rbuffer.extract(&handle, 0, sizeof(handle));
  652. handles.push_back(handle);
  653. rbuffer.consume(sizeof(handle));
  654. }
  655. // Print the directly affected dependents:
  656. cerr << " ";
  657. for (handle_t handle : handles) {
  658. cerr << " " << get_service_name(socknum, rbuffer, handle);
  659. }
  660. cerr << "\n";
  661. return 1;
  662. }
  663. if (reply_pkt_h == DINIT_RP_NAK && command == command_t::RESTART_SERVICE) {
  664. if (ignore_unstarted) {
  665. if (verbose) {
  666. cout << "Service '" << service_name << "' is not currently started.\n";
  667. }
  668. return 0;
  669. }
  670. cerr << "dinitctl: cannot restart service; service not started.\n";
  671. return 1;
  672. }
  673. if (reply_pkt_h == DINIT_RP_NAK && command == command_t::WAKE_SERVICE) {
  674. cerr << "dinitctl: service has no active dependents, cannot wake.\n";
  675. return 1;
  676. }
  677. if (reply_pkt_h == DINIT_RP_SHUTTINGDOWN) {
  678. cerr << "dinitctl: cannot start/restart/wake service, shutdown is in progress.\n";
  679. return 1;
  680. }
  681. if (reply_pkt_h != DINIT_RP_ACK && reply_pkt_h != DINIT_RP_ALREADYSS) {
  682. cerr << "dinitctl: protocol error." << endl;
  683. return 1;
  684. }
  685. }
  686. if (! wait_for_service) {
  687. if (verbose) {
  688. cout << "Issued " << describeVerb(do_stop) << " command successfully for service '"
  689. << service_name << "'." << endl;
  690. }
  691. return 0;
  692. }
  693. return wait_service_state(socknum, rbuffer, handle, service_name, do_stop, verbose);
  694. }
  695. // Issue a "load service" command (DINIT_CP_LOADSERVICE), without waiting for
  696. // a response. Returns 1 on failure (with error logged), 0 on success.
  697. static int issue_load_service(int socknum, const char *service_name, bool find_only)
  698. {
  699. // Build buffer;
  700. uint16_t sname_len = strlen(service_name);
  701. int bufsize = 3 + sname_len;
  702. std::unique_ptr<char[]> ubuf(new char[bufsize]);
  703. auto buf = ubuf.get();
  704. buf[0] = find_only ? DINIT_CP_FINDSERVICE : DINIT_CP_LOADSERVICE;
  705. memcpy(buf + 1, &sname_len, 2);
  706. memcpy(buf + 3, service_name, sname_len);
  707. write_all_x(socknum, buf, bufsize);
  708. return 0;
  709. }
  710. // Check that a "load service" reply was received, and that the requested service was found.
  711. // state_p may be null.
  712. static int check_load_reply(int socknum, cpbuffer_t &rbuffer, handle_t *handle_p, service_state_t *state_p, bool write_error)
  713. {
  714. using namespace std;
  715. if (rbuffer[0] == DINIT_RP_SERVICERECORD) {
  716. fill_buffer_to(rbuffer, socknum, 2 + sizeof(*handle_p));
  717. rbuffer.extract((char *) handle_p, 2, sizeof(*handle_p));
  718. if (state_p) *state_p = static_cast<service_state_t>(rbuffer[1]);
  719. //target_state = static_cast<service_state_t>(rbuffer[2 + sizeof(handle)]);
  720. rbuffer.consume(3 + sizeof(*handle_p));
  721. return 0;
  722. }
  723. else if (rbuffer[0] == DINIT_RP_NOSERVICE) {
  724. if (write_error) {
  725. cerr << "dinitctl: failed to find/load service." << endl;
  726. }
  727. return 1;
  728. }
  729. else {
  730. throw dinit_protocol_error();
  731. }
  732. }
  733. static int unpin_service(int socknum, cpbuffer_t &rbuffer, const char *service_name, bool verbose)
  734. {
  735. using namespace std;
  736. handle_t handle;
  737. // Build buffer;
  738. if (! load_service(socknum, rbuffer, service_name, &handle, nullptr)) {
  739. return 1;
  740. }
  741. // Issue UNPIN command.
  742. {
  743. auto m = membuf()
  744. .append<char>(DINIT_CP_UNPINSERVICE)
  745. .append(handle);
  746. write_all_x(socknum, m);
  747. wait_for_reply(rbuffer, socknum);
  748. if (rbuffer[0] != DINIT_RP_ACK) {
  749. cerr << "dinitctl: protocol error." << endl;
  750. return 1;
  751. }
  752. rbuffer.consume(1);
  753. }
  754. if (verbose) {
  755. cout << "Service '" << service_name << "' unpinned." << endl;
  756. }
  757. return 0;
  758. }
  759. static int unload_service(int socknum, cpbuffer_t &rbuffer, const char *service_name, bool verbose)
  760. {
  761. using namespace std;
  762. if (issue_load_service(socknum, service_name, true) == 1) {
  763. return 1;
  764. }
  765. wait_for_reply(rbuffer, socknum);
  766. handle_t handle;
  767. if (rbuffer[0] == DINIT_RP_NOSERVICE) {
  768. cerr << "dinitctl: service not loaded." << endl;
  769. return 1;
  770. }
  771. if (check_load_reply(socknum, rbuffer, &handle, nullptr) != 0) {
  772. return 1;
  773. }
  774. // Issue UNLOAD command.
  775. {
  776. auto m = membuf()
  777. .append<char>(DINIT_CP_UNLOADSERVICE)
  778. .append(handle);
  779. write_all_x(socknum, m);
  780. wait_for_reply(rbuffer, socknum);
  781. if (rbuffer[0] == DINIT_RP_NAK) {
  782. cerr << "dinitctl: could not unload service; service not stopped, or is a dependency of "
  783. "other service." << endl;
  784. return 1;
  785. }
  786. if (rbuffer[0] != DINIT_RP_ACK) {
  787. cerr << "dinitctl: protocol error." << endl;
  788. return 1;
  789. }
  790. rbuffer.consume(1);
  791. }
  792. if (verbose) {
  793. cout << "Service '" << service_name << "' unloaded." << endl;
  794. }
  795. return 0;
  796. }
  797. static int reload_service(int socknum, cpbuffer_t &rbuffer, const char *service_name, bool verbose)
  798. {
  799. using namespace std;
  800. if (issue_load_service(socknum, service_name, true) == 1) {
  801. return 1;
  802. }
  803. wait_for_reply(rbuffer, socknum);
  804. handle_t handle;
  805. if (rbuffer[0] == DINIT_RP_NOSERVICE) {
  806. cerr << "dinitctl: service not loaded." << endl;
  807. return 1;
  808. }
  809. if (check_load_reply(socknum, rbuffer, &handle, nullptr) != 0) {
  810. return 1;
  811. }
  812. // Issue RELOAD command.
  813. {
  814. auto m = membuf()
  815. .append<char>(DINIT_CP_RELOADSERVICE)
  816. .append(handle);
  817. write_all_x(socknum, m);
  818. wait_for_reply(rbuffer, socknum);
  819. if (rbuffer[0] == DINIT_RP_NAK) {
  820. cerr << "dinitctl: could not reload service; service in wrong state, incompatible change, "
  821. "or bad service description." << endl;
  822. return 1;
  823. }
  824. if (rbuffer[0] != DINIT_RP_ACK) {
  825. cerr << "dinitctl: protocol error." << endl;
  826. return 1;
  827. }
  828. rbuffer.consume(1);
  829. }
  830. if (verbose) {
  831. cout << "Service '" << service_name << "' reloaded." << endl;
  832. }
  833. return 0;
  834. }
  835. static int list_services(int socknum, cpbuffer_t &rbuffer)
  836. {
  837. using namespace std;
  838. char cmdbuf[] = { (char)DINIT_CP_LISTSERVICES };
  839. write_all_x(socknum, cmdbuf, 1);
  840. wait_for_reply(rbuffer, socknum);
  841. while (rbuffer[0] == DINIT_RP_SVCINFO) {
  842. int hdrsize = 8 + std::max(sizeof(int), sizeof(pid_t));
  843. fill_buffer_to(rbuffer, socknum, hdrsize);
  844. unsigned name_len = (unsigned char)rbuffer[1];
  845. service_state_t current = static_cast<service_state_t>(rbuffer[2]);
  846. service_state_t target = static_cast<service_state_t>(rbuffer[3]);
  847. int console_flags = rbuffer[4];
  848. bool has_console = (console_flags & 2) != 0;
  849. bool waiting_console = (console_flags & 1) != 0;
  850. bool was_skipped = (console_flags & 4) != 0;
  851. bool marked_active = (console_flags & 8) != 0;
  852. stopped_reason_t stop_reason = static_cast<stopped_reason_t>(rbuffer[5]);
  853. pid_t service_pid;
  854. int exit_status;
  855. if (current != service_state_t::STOPPED) {
  856. rbuffer.extract((char *)&service_pid, 8, sizeof(service_pid));
  857. }
  858. else {
  859. rbuffer.extract((char *)&exit_status, 8, sizeof(exit_status));
  860. }
  861. fill_buffer_to(rbuffer, socknum, name_len + hdrsize);
  862. char *name_ptr = rbuffer.get_ptr(hdrsize);
  863. unsigned clength = std::min(rbuffer.get_contiguous_length(name_ptr), name_len);
  864. string name = string(name_ptr, clength);
  865. name.append(rbuffer.get_buf_base(), name_len - clength);
  866. cout << "[";
  867. // [ ] if marked active; otherwise, { } if target state is STARTED
  868. // + if started, 's' if skipped, space otherwise
  869. char lbracket = target == service_state_t::STARTED ? '{' : ' ';
  870. char rbracket = target == service_state_t::STARTED ? '}' : ' ';
  871. cout << (marked_active ? '[' : lbracket);
  872. if (current == service_state_t::STARTED) {
  873. cout << (was_skipped ? 's' : '+');
  874. }
  875. else {
  876. cout << ' ';
  877. }
  878. cout << (marked_active ? ']' : rbracket);
  879. if (current == service_state_t::STARTING) {
  880. cout << "<<";
  881. }
  882. else if (current == service_state_t::STOPPING) {
  883. cout << ">>";
  884. }
  885. else {
  886. cout << " ";
  887. }
  888. cout << (target == service_state_t::STOPPED ? '{' : ' ');
  889. if (current == service_state_t::STOPPED) {
  890. bool did_fail = false;
  891. if (stop_reason == stopped_reason_t::TERMINATED) {
  892. if (!WIFEXITED(exit_status) || WEXITSTATUS(exit_status) != 0) {
  893. did_fail = true;
  894. }
  895. }
  896. else did_fail = (stop_reason != stopped_reason_t::NORMAL);
  897. cout << (did_fail ? 'X' : '-');
  898. }
  899. else {
  900. cout << ' ';
  901. }
  902. cout << (target == service_state_t::STOPPED ? '}' : ' ');
  903. cout << "] " << name;
  904. if (current != service_state_t::STOPPED && service_pid != -1) {
  905. cout << " (pid: " << service_pid << ")";
  906. }
  907. if (current == service_state_t::STOPPED && stop_reason == stopped_reason_t::TERMINATED) {
  908. if (WIFEXITED(exit_status)) {
  909. cout << " (exit status: " << WEXITSTATUS(exit_status) << ")";
  910. }
  911. else if (WIFSIGNALED(exit_status)) {
  912. cout << " (signal: " << WTERMSIG(exit_status) << ")";
  913. }
  914. }
  915. if (has_console) {
  916. cout << " (has console)";
  917. }
  918. else if (waiting_console) {
  919. cout << " (waiting for console)";
  920. }
  921. cout << endl;
  922. rbuffer.consume(hdrsize + name_len);
  923. wait_for_reply(rbuffer, socknum);
  924. }
  925. if (rbuffer[0] != DINIT_RP_LISTDONE) {
  926. cerr << "dinitctl: control socket protocol error" << endl;
  927. return 1;
  928. }
  929. return 0;
  930. }
  931. static void print_termination_details(int exit_status)
  932. {
  933. using namespace std;
  934. if (WIFSIGNALED(exit_status)) {
  935. cout << "signalled - signal ";
  936. cout << WTERMSIG(exit_status);
  937. }
  938. else if (WIFEXITED(exit_status)) {
  939. cout << "exited - status ";
  940. cout << WEXITSTATUS(exit_status);
  941. }
  942. else {
  943. cout << "unknown";
  944. }
  945. }
  946. static int service_status(int socknum, cpbuffer_t &rbuffer, const char *service_name)
  947. {
  948. using namespace std;
  949. if (issue_load_service(socknum, service_name, true) == 1) {
  950. return 1;
  951. }
  952. wait_for_reply(rbuffer, socknum);
  953. handle_t handle;
  954. if (rbuffer[0] == DINIT_RP_NOSERVICE) {
  955. cerr << "dinitctl: service not loaded." << endl;
  956. return 1;
  957. }
  958. if (check_load_reply(socknum, rbuffer, &handle, nullptr) != 0) {
  959. return 1;
  960. }
  961. // Issue STATUS request
  962. {
  963. auto m = membuf()
  964. .append<char>(DINIT_CP_SERVICESTATUS)
  965. .append(handle);
  966. write_all_x(socknum, m);
  967. wait_for_reply(rbuffer, socknum);
  968. if (rbuffer[0] != DINIT_RP_SERVICESTATUS) {
  969. cerr << "dinitctl: protocol error." << endl;
  970. return 1;
  971. }
  972. rbuffer.consume(1);
  973. int statussize = 6 + std::max(sizeof(pid_t), sizeof(int));;
  974. fill_buffer_to(rbuffer, socknum, statussize + 1 /* reserved */);
  975. rbuffer.consume(1);
  976. service_state_t current = static_cast<service_state_t>(rbuffer[0]);
  977. service_state_t target = static_cast<service_state_t>(rbuffer[1]);
  978. int console_flags = rbuffer[2];
  979. bool has_console = (console_flags & 2) != 0;
  980. bool waiting_console = (console_flags & 1) != 0;
  981. bool was_skipped = (console_flags & 4) != 0;
  982. bool marked_active = (console_flags & 8) != 0;
  983. stopped_reason_t stop_reason = static_cast<stopped_reason_t>(rbuffer[3]);
  984. pid_t service_pid = -1;
  985. int exit_status = 0;
  986. if (current != service_state_t::STOPPED) {
  987. rbuffer.extract((char *)&service_pid, 6, sizeof(service_pid));
  988. }
  989. else {
  990. rbuffer.extract((char *)&exit_status, 6, sizeof(exit_status));
  991. }
  992. cout << "Service: " << service_name << "\n"
  993. " State: ";
  994. switch (current) {
  995. case service_state_t::STOPPED:
  996. cout << "STOPPED";
  997. switch (stop_reason) {
  998. case stopped_reason_t::DEPFAILED:
  999. cout << " (dependency failed/terminated)";
  1000. break;
  1001. case stopped_reason_t::FAILED:
  1002. cout << " (failed to start";
  1003. if (exit_status != 0) {
  1004. cout << "; ";
  1005. print_termination_details(exit_status);
  1006. }
  1007. cout << ")";
  1008. break;
  1009. case stopped_reason_t::EXECFAILED:
  1010. uint16_t launch_stage;
  1011. rbuffer.extract((char *)&launch_stage, 4, 2);
  1012. cout << " (could not be launched)\n";
  1013. cout << " Stage: " << exec_stage_descriptions[launch_stage] << "\n";
  1014. cout << " Error: " << strerror(exit_status);
  1015. break;
  1016. case stopped_reason_t::TERMINATED:
  1017. cout << " (terminated";
  1018. if (exit_status != 0) {
  1019. cout << "; ";
  1020. print_termination_details(exit_status);
  1021. }
  1022. cout << ")";
  1023. break;
  1024. case stopped_reason_t::TIMEDOUT:
  1025. cout << " (start timed out)";
  1026. break;
  1027. case stopped_reason_t::NORMAL:
  1028. break;
  1029. }
  1030. break;
  1031. case service_state_t::STARTING:
  1032. cout << "STARTING";
  1033. if (target == service_state_t::STOPPED) {
  1034. cout << " (target state: STOPPED)";
  1035. }
  1036. break;
  1037. case service_state_t::STARTED:
  1038. cout << "STARTED";
  1039. if (was_skipped) {
  1040. cout << " (startup skipped)";
  1041. }
  1042. break;
  1043. case service_state_t::STOPPING:
  1044. cout << "STOPPING";
  1045. if (target == service_state_t::STARTED) {
  1046. cout << " (target state: STARTED)";
  1047. }
  1048. if (exit_status != 0) {
  1049. cout << "(terminated ;";
  1050. print_termination_details(exit_status);
  1051. cout << ")";
  1052. }
  1053. }
  1054. if (has_console) {
  1055. cout << " (holding console)";
  1056. }
  1057. if (waiting_console) {
  1058. cout << " (waiting for console)";
  1059. }
  1060. cout << "\n";
  1061. if (target == service_state_t::STARTED) {
  1062. cout << " Activation: ";
  1063. if (marked_active) {
  1064. cout << "explicitly started\n";
  1065. }
  1066. else {
  1067. cout << "start due to dependent(s)\n";
  1068. }
  1069. }
  1070. if (service_pid != -1) {
  1071. cout << " Process ID: " << service_pid << "\n";
  1072. }
  1073. }
  1074. return 0;
  1075. }
  1076. static int add_remove_dependency(int socknum, cpbuffer_t &rbuffer, bool add,
  1077. const char *service_from, const char *service_to, dependency_type dep_type, bool verbose)
  1078. {
  1079. using namespace std;
  1080. handle_t from_handle;
  1081. handle_t to_handle;
  1082. if (! load_service(socknum, rbuffer, service_from, &from_handle, nullptr)
  1083. || ! load_service(socknum, rbuffer, service_to, &to_handle, nullptr)) {
  1084. return 1;
  1085. }
  1086. if (from_handle == to_handle) {
  1087. cerr << "dinitctl: can not add/remove a dependency from a service to itself" << endl;
  1088. return 1;
  1089. }
  1090. auto m = membuf()
  1091. .append<char>(add ? (char)DINIT_CP_ADD_DEP : (char)DINIT_CP_REM_DEP)
  1092. .append(static_cast<char>(dep_type))
  1093. .append(from_handle)
  1094. .append(to_handle);
  1095. write_all_x(socknum, m);
  1096. wait_for_reply(rbuffer, socknum);
  1097. // check reply
  1098. if (rbuffer[0] == DINIT_RP_NAK) {
  1099. if (add) {
  1100. cerr << "dinitctl: could not add dependency: circular dependency or wrong state" << endl;
  1101. }
  1102. else {
  1103. cerr << "dinitctl: no such dependency to remove" << endl;
  1104. }
  1105. return 1;
  1106. }
  1107. if (rbuffer[0] != DINIT_RP_ACK) {
  1108. cerr << "dinitctl: control socket protocol error" << endl;
  1109. return 1;
  1110. }
  1111. if (verbose) {
  1112. std::cout << "Service '" << service_from << "': dependency '" << service_to << "' " << (add ? "added" : "removed") << endl;
  1113. }
  1114. return 0;
  1115. }
  1116. static int shutdown_dinit(int socknum, cpbuffer_t &rbuffer, bool verbose)
  1117. {
  1118. // TODO support no-wait option.
  1119. using namespace std;
  1120. auto m = membuf()
  1121. .append<char>(DINIT_CP_SHUTDOWN)
  1122. .append(static_cast<char>(shutdown_type_t::HALT));
  1123. write_all_x(socknum, m);
  1124. wait_for_reply(rbuffer, socknum);
  1125. if (rbuffer[0] != DINIT_RP_ACK) {
  1126. cerr << "dinitctl: control socket protocol error" << endl;
  1127. return 1;
  1128. }
  1129. if (verbose) {
  1130. std::cout << "Shutting down dinit..." << std::endl;
  1131. }
  1132. // Now wait for rollback complete, by waiting for the connection to close:
  1133. try {
  1134. while (true) {
  1135. wait_for_info(rbuffer, socknum);
  1136. rbuffer.consume(rbuffer[1]);
  1137. }
  1138. }
  1139. catch (cp_read_exception &exc) {
  1140. // Assume that the connection closed.
  1141. }
  1142. if (verbose) {
  1143. std::cout << "Connection closed." << std::endl;
  1144. }
  1145. return 0;
  1146. }
  1147. // exception for cancelling a service operation
  1148. class service_op_cancel { };
  1149. static int enable_disable_service(int socknum, cpbuffer_t &rbuffer, const char *from, const char *to,
  1150. bool enable, bool verbose)
  1151. {
  1152. using namespace std;
  1153. service_state_t from_state = service_state_t::STARTED;
  1154. handle_t from_handle;
  1155. handle_t to_handle;
  1156. if (!load_service(socknum, rbuffer, from, &from_handle, &from_state)
  1157. || !load_service(socknum, rbuffer, to, &to_handle, nullptr)) {
  1158. return 1;
  1159. }
  1160. // Get service load path
  1161. char buf[1] = { DINIT_CP_QUERY_LOAD_MECH };
  1162. write_all_x(socknum, buf, 1);
  1163. wait_for_reply(rbuffer, socknum);
  1164. if (rbuffer[0] != DINIT_RP_LOADER_MECH) {
  1165. cerr << "dinitctl: control socket protocol error" << endl;
  1166. return 1;
  1167. }
  1168. // Packet type, load mechanism type, packet size:
  1169. fill_buffer_to(rbuffer, socknum, 2 + sizeof(uint32_t));
  1170. if (rbuffer[1] != SSET_TYPE_DIRLOAD) {
  1171. cerr << "dinitctl: unknown configuration, unable to load service descriptions" << endl;
  1172. return 1;
  1173. }
  1174. vector<string> paths;
  1175. uint32_t pktsize;
  1176. rbuffer.extract(&pktsize, 2, sizeof(uint32_t));
  1177. fill_buffer_to(rbuffer, socknum, 2 + sizeof(uint32_t) * 3); // path entries, cwd length
  1178. uint32_t path_entries; // number of service directories
  1179. rbuffer.extract(&path_entries, 2 + sizeof(uint32_t), sizeof(uint32_t));
  1180. uint32_t cwd_len;
  1181. rbuffer.extract(&cwd_len, 2 + sizeof(uint32_t) * 2, sizeof(uint32_t));
  1182. rbuffer.consume(2 + sizeof(uint32_t) * 3);
  1183. pktsize -= 2 + sizeof(uint32_t) * 3;
  1184. // Read current working directory of daemon:
  1185. std::string dinit_cwd = read_string(socknum, rbuffer, cwd_len);
  1186. // dinit daemon base directory against which service paths are resolved is in dinit_cwd
  1187. for (uint32_t i = 0; i < path_entries; ++i) {
  1188. uint32_t plen;
  1189. fill_buffer_to(rbuffer, socknum, sizeof(uint32_t));
  1190. rbuffer.extract(&plen, 0, sizeof(uint32_t));
  1191. rbuffer.consume(sizeof(uint32_t));
  1192. paths.push_back(read_string(socknum, rbuffer, plen));
  1193. }
  1194. // all service directories are now in the 'paths' vector
  1195. // Load/read service description for 'from' service:
  1196. ifstream service_file;
  1197. string service_file_path;
  1198. for (std::string path : paths) {
  1199. string test_path = combine_paths(combine_paths(dinit_cwd, path.c_str()), from);
  1200. service_file.open(test_path.c_str(), ios::in);
  1201. if (service_file) {
  1202. service_file_path = test_path;
  1203. break;
  1204. }
  1205. }
  1206. if (! service_file) {
  1207. cerr << "dinitctl: could not locate service file for service '" << from << "'" << endl;
  1208. return 1;
  1209. }
  1210. // We now need to read the service file, identify the waits-for.d directory (bail out if more than one),
  1211. // make sure the service is not listed as a dependency individually.
  1212. string waits_for_d;
  1213. try {
  1214. process_service_file(from, service_file, [&](string &line, unsigned line_num, string &setting,
  1215. dinit_load::string_iterator i, dinit_load::string_iterator end) -> void {
  1216. if (setting == "waits-for" || setting == "depends-on" || setting == "depends-ms") {
  1217. string dname = dinit_load::read_setting_value(line_num, i, end);
  1218. if (dname == to) {
  1219. // There is already a dependency
  1220. cerr << "dinitctl: there is a fixed dependency to service '" << to
  1221. << "' in the service description of '" << from << "'." << endl;
  1222. throw service_op_cancel();
  1223. }
  1224. }
  1225. else if (setting == "waits-for.d") {
  1226. string dname = dinit_load::read_setting_value(line_num, i, end);
  1227. if (! waits_for_d.empty()) {
  1228. cerr << "dinitctl: service '" << from << "' has multiple waits-for.d directories "
  1229. << "specified in service description" << endl;
  1230. throw service_op_cancel();
  1231. }
  1232. waits_for_d = std::move(dname);
  1233. }
  1234. });
  1235. }
  1236. catch (const service_op_cancel &cexc) {
  1237. return 1;
  1238. }
  1239. // If the from service has no waits-for.d specified, we can't continue
  1240. if (waits_for_d.empty()) {
  1241. cerr << "dinitctl: service '" << from << "' has no waits-for.d directory specified" << endl;
  1242. return 1;
  1243. }
  1244. // The waits-for.d path is relative to the service file path, combine:
  1245. string waits_for_d_full = combine_paths(parent_path(service_file_path), waits_for_d.c_str());
  1246. // check if dependency already exists
  1247. string dep_link_path = combine_paths(waits_for_d_full, to);
  1248. struct stat stat_buf;
  1249. if (lstat(dep_link_path.c_str(), &stat_buf) == -1) {
  1250. if (errno != ENOENT) {
  1251. cerr << "dinitctl: checking for existing dependency link: " << dep_link_path << ": "
  1252. << strerror(errno) << endl;
  1253. return 1;
  1254. }
  1255. }
  1256. else {
  1257. // dependency already exists
  1258. if (enable) {
  1259. cerr << "dinitctl: service already enabled." << endl;
  1260. return 1;
  1261. }
  1262. }
  1263. // warn if 'from' service is not started
  1264. if (enable && from_state != service_state_t::STARTED) {
  1265. cerr << "dinitctl: warning: enabling dependency for non-started service" << endl;
  1266. }
  1267. // add/remove dependency
  1268. constexpr int enable_pktsize = 2 + sizeof(handle_t) * 2;
  1269. char cmdbuf[enable_pktsize] = { char(enable ? DINIT_CP_ENABLESERVICE : DINIT_CP_REM_DEP),
  1270. char(dependency_type::WAITS_FOR)};
  1271. memcpy(cmdbuf + 2, &from_handle, sizeof(from_handle));
  1272. memcpy(cmdbuf + 2 + sizeof(from_handle), &to_handle, sizeof(to_handle));
  1273. write_all_x(socknum, cmdbuf, enable_pktsize);
  1274. wait_for_reply(rbuffer, socknum);
  1275. // check reply
  1276. if (rbuffer[0] == DINIT_RP_NAK) {
  1277. if (enable) {
  1278. cerr << "dinitctl: could not enable service: possible circular dependency" << endl;
  1279. }
  1280. else {
  1281. cerr << "dinitctl: service not currently enabled" << endl;
  1282. }
  1283. return 1;
  1284. }
  1285. if (rbuffer[0] != DINIT_RP_ACK) {
  1286. cerr << "dinitctl: control socket protocol error" << endl;
  1287. return 1;
  1288. }
  1289. rbuffer.consume(1);
  1290. // create link
  1291. if (enable) {
  1292. if (symlink((string("../") + to).c_str(), dep_link_path.c_str()) == -1) {
  1293. cerr << "dinitctl: could not create symlink at " << dep_link_path << ": " << strerror(errno)
  1294. << "\n" "dinitctl: note: service was enabled for now; persistent enable failed."
  1295. << endl;
  1296. return 1;
  1297. }
  1298. }
  1299. else {
  1300. if (unlink(dep_link_path.c_str()) == -1) {
  1301. cerr << "dinitctl: could not unlink dependency entry " << dep_link_path << ": "
  1302. << strerror(errno) << "\n"
  1303. "dinitctl: note: service was disabled for now; persistent disable failed." << endl;
  1304. return 1;
  1305. }
  1306. }
  1307. // Check status of the service now
  1308. auto m = membuf()
  1309. .append<char>(DINIT_CP_SERVICESTATUS)
  1310. .append(to_handle);
  1311. write_all_x(socknum, m);
  1312. wait_for_reply(rbuffer, socknum);
  1313. if (rbuffer[0] != DINIT_RP_SERVICESTATUS) {
  1314. cerr << "dinitctl: protocol error." << endl;
  1315. return 1;
  1316. }
  1317. rbuffer.consume(1);
  1318. int statussize = 6 + std::max(sizeof(pid_t), sizeof(int));;
  1319. fill_buffer_to(rbuffer, socknum, statussize + 1 /* reserved */);
  1320. rbuffer.consume(1);
  1321. service_state_t current = static_cast<service_state_t>(rbuffer[0]);
  1322. service_state_t target = static_cast<service_state_t>(rbuffer[1]);
  1323. rbuffer.consume(statussize);
  1324. if (verbose) {
  1325. cout << "Service '" << to << "' has been " << (enable ? "enabled" : "disabled") << "." << endl;
  1326. }
  1327. if (enable) {
  1328. if (current != service_state_t::STARTED) {
  1329. wait_service_state(socknum, rbuffer, to_handle, to, false /* start */, verbose);
  1330. }
  1331. }
  1332. else {
  1333. if (target != service_state_t::STOPPED) {
  1334. std::cerr << "dinitctl: note: disabled service may have other dependents\n";
  1335. }
  1336. }
  1337. return 0;
  1338. }
  1339. static int do_setenv(int socknum, cpbuffer_t &rbuffer, std::vector<const char *> &env_names)
  1340. {
  1341. using namespace std;
  1342. string buf;
  1343. for (const char *envp : env_names) {
  1344. buf.clear();
  1345. buf.reserve(6);
  1346. // protocol message and size space
  1347. buf.push_back(DINIT_CP_SETENV);
  1348. buf.append(2, 0);
  1349. const unsigned hdr_len = 3;
  1350. // either full var or name
  1351. auto elen = strlen(envp);
  1352. buf.append(envp, elen);
  1353. // if '=' not found, get value from environment
  1354. if (!memchr(envp, '=', elen)) {
  1355. buf.push_back('=');
  1356. auto *envv = getenv(envp);
  1357. if (envv) {
  1358. buf.append(envv);
  1359. }
  1360. }
  1361. uint16_t bufs = buf.size() - hdr_len;
  1362. // sanitize length early on
  1363. if (buf.size() > cpbuffer_t::get_size()) {
  1364. auto eq = buf.find('=', hdr_len);
  1365. auto name = buf.substr(hdr_len, eq - hdr_len);
  1366. cerr << "dinitctl: environment variable '" << name << "' too long." << endl;
  1367. return 1;
  1368. }
  1369. // set size in protocol message
  1370. memcpy(&buf[1], &bufs, 2);
  1371. // send
  1372. write_all_x(socknum, buf.data(), buf.size());
  1373. wait_for_reply(rbuffer, socknum);
  1374. if (rbuffer[0] == DINIT_RP_BADREQ) {
  1375. cerr << "dinitctl: failed to export environment." << endl;
  1376. return 1;
  1377. } else if (rbuffer[0] != DINIT_RP_ACK) {
  1378. throw dinit_protocol_error();
  1379. }
  1380. rbuffer.consume(1);
  1381. }
  1382. return 0;
  1383. }