dinitctl.cc 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145
  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 "options-processing.h"
  25. #include "mconfig.h"
  26. #include "control-datatypes.h"
  27. // dinitctl: utility to control the Dinit daemon, including starting and stopping of services.
  28. // This utility communicates with the dinit daemon via a unix stream socket (as specified in
  29. // SYSCONTROLSOCKET, or $HOME/.dinitctl).
  30. // common communication datatypes
  31. using namespace dinit_cptypes;
  32. static constexpr uint16_t min_cp_version = 1;
  33. static constexpr uint16_t max_cp_version = 1;
  34. enum class ctl_cmd;
  35. static int issue_load_service(int socknum, const char *service_name, bool find_only = false);
  36. static int check_load_reply(int socknum, cpbuffer_t &, handle_t *handle_p, service_state_t *state_p,
  37. bool write_error=true);
  38. static int start_stop_service(int socknum, cpbuffer_t &, const char *service_name, ctl_cmd command,
  39. bool do_pin, bool do_force, bool wait_for_service, bool ignore_unstarted, bool verbose);
  40. static int unpin_service(int socknum, cpbuffer_t &, const char *service_name, bool verbose);
  41. static int unload_service(int socknum, cpbuffer_t &, const char *service_name, bool verbose);
  42. static int reload_service(int socknum, cpbuffer_t &, const char *service_name, bool verbose);
  43. static int list_services(int socknum, cpbuffer_t &);
  44. static int service_status(int socknum, cpbuffer_t &rbuffer, const char *service_name, ctl_cmd command, bool verbose);
  45. static int shutdown_dinit(int soclknum, cpbuffer_t &, bool verbose);
  46. static int add_remove_dependency(int socknum, cpbuffer_t &rbuffer, bool add, const char *service_from,
  47. const char *service_to, dependency_type dep_type, bool verbose);
  48. static int enable_disable_service(int socknum, cpbuffer_t &rbuffer, service_dir_opt &service_dir_opts,
  49. const char *from, const char *to, bool enable, bool verbose);
  50. static int do_setenv(int socknum, cpbuffer_t &rbuffer, std::vector<const char *> &env_names);
  51. static int trigger_service(int socknum, cpbuffer_t &rbuffer, const char *service_name, bool trigger_value);
  52. static int cat_service_log(int socknum, cpbuffer_t &rbuffer, const char *service_name, bool do_clear);
  53. static int signal_send(int socknum, cpbuffer_t &rbuffer, const char *service_name, sig_num_t sig_num);
  54. static int signal_list();
  55. enum class ctl_cmd {
  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. SET_TRIGGER,
  74. UNSET_TRIGGER,
  75. CAT_LOG,
  76. SIG_SEND,
  77. SIG_LIST,
  78. IS_STARTED,
  79. IS_FAILED,
  80. };
  81. // Entry point.
  82. int dinitctl_main(int argc, char **argv)
  83. {
  84. using namespace std;
  85. // general options
  86. bool cmdline_error = false;
  87. bool show_help = argc < 2; // show help if no arguments
  88. std::string control_socket_str;
  89. const char * control_socket_path = nullptr;
  90. bool verbose = true;
  91. bool user_dinit = (getuid() != 0); // communicate with user daemon
  92. service_dir_opt service_dir_opts;
  93. bool offline = false;
  94. // general command options
  95. ctl_cmd command = ctl_cmd::NONE;
  96. std::vector<const char *> cmd_args;
  97. // specific command options
  98. const char *service_name = nullptr;
  99. const char *to_service_name = nullptr;
  100. dependency_type dep_type = dependency_type::AFTER; // avoid maybe-uninitialised warning
  101. bool dep_type_set = false;
  102. bool catlog_clear = false;
  103. bool wait_for_service = true;
  104. bool do_pin = false;
  105. bool do_force = false;
  106. bool ignore_unstarted = false;
  107. bool use_passed_cfd = false;
  108. bool show_siglist = false;
  109. std::string sigstr;
  110. sig_num_t sig_num = -1;
  111. for (int i = 1; i < argc; i++) {
  112. if (argv[i][0] == '-') {
  113. if (strcmp(argv[i], "--help") == 0) {
  114. show_help = true;
  115. break;
  116. }
  117. else if (strcmp(argv[i], "--version") == 0) {
  118. cout << "Dinit version " << DINIT_VERSION << ".\n";
  119. return 0;
  120. }
  121. else if (strcmp(argv[i], "--no-wait") == 0) {
  122. wait_for_service = false;
  123. }
  124. else if (strcmp(argv[i], "--ignore-unstarted") == 0) {
  125. ignore_unstarted = true;
  126. }
  127. else if (strcmp(argv[i], "--quiet") == 0) {
  128. verbose = false;
  129. }
  130. else if (strcmp(argv[i], "--system") == 0 || strcmp(argv[i], "-s") == 0) {
  131. user_dinit = false;
  132. }
  133. else if (strcmp(argv[i], "--user") == 0 || strcmp(argv[i], "-u") == 0) {
  134. user_dinit = true;
  135. }
  136. else if (strcmp(argv[i], "--pin") == 0) {
  137. do_pin = true;
  138. }
  139. else if (strcmp(argv[i], "--socket-path") == 0 || strcmp(argv[i], "-p") == 0) {
  140. ++i;
  141. if (i == argc) {
  142. cerr << "dinitctl: --socket-path/-p should be followed by socket path" << std::endl;
  143. return 1;
  144. }
  145. control_socket_str = argv[i];
  146. }
  147. else if (strcmp(argv[i], "--use-passed-cfd") == 0) {
  148. use_passed_cfd = true;
  149. }
  150. else if (strcmp(argv[i], "--from") == 0) {
  151. if (command == ctl_cmd::ENABLE_SERVICE || command == ctl_cmd::DISABLE_SERVICE) {
  152. ++i;
  153. if (i == argc) {
  154. cerr << "dinitctl: --from should be followed by a service name" << std::endl;
  155. return 1;
  156. }
  157. service_name = argv[i];
  158. }
  159. else {
  160. cmdline_error = true;
  161. break;
  162. }
  163. }
  164. else if (strcmp(argv[i], "--force") == 0 || strcmp(argv[i], "-f") == 0) {
  165. if (command == ctl_cmd::STOP_SERVICE || command == ctl_cmd::RESTART_SERVICE) {
  166. do_force = true;
  167. }
  168. else {
  169. cmdline_error = true;
  170. break;
  171. }
  172. }
  173. else if (strcmp(argv[i], "--clear") == 0) {
  174. if (command == ctl_cmd::CAT_LOG) {
  175. catlog_clear = true;
  176. }
  177. else {
  178. cmdline_error = true;
  179. break;
  180. }
  181. }
  182. else if (strcmp(argv[i], "--list") == 0 || strcmp(argv[i], "-l") == 0) {
  183. if (command == ctl_cmd::SIG_SEND) {
  184. show_siglist = true;
  185. }
  186. else {
  187. cmdline_error = true;
  188. break;
  189. }
  190. }
  191. else if (strcmp(argv[i], "--services-dir") == 0 || strcmp(argv[i], "-d") == 0) {
  192. if (++i < argc) {
  193. service_dir_opts.set_specified_service_dir(argv[i]);
  194. }
  195. else {
  196. cerr << "dinitcheck: '--services-dir' (-d) requires an argument" << endl;
  197. return 1;
  198. }
  199. }
  200. else if (strcmp(argv[i], "--offline") == 0 || strcmp(argv[i], "-o") == 0) {
  201. offline = true;
  202. }
  203. else {
  204. cerr << "dinitctl: unrecognized/invalid option: " << argv[i] << " (use --help for help)\n";
  205. return 1;
  206. }
  207. }
  208. else if (command == ctl_cmd::NONE) {
  209. if (strcmp(argv[i], "start") == 0) {
  210. command = ctl_cmd::START_SERVICE;
  211. }
  212. else if (strcmp(argv[i], "wake") == 0) {
  213. command = ctl_cmd::WAKE_SERVICE;
  214. }
  215. else if (strcmp(argv[i], "stop") == 0) {
  216. command = ctl_cmd::STOP_SERVICE;
  217. }
  218. else if (strcmp(argv[i], "restart") == 0) {
  219. command = ctl_cmd::RESTART_SERVICE;
  220. }
  221. else if (strcmp(argv[i], "release") == 0) {
  222. command = ctl_cmd::RELEASE_SERVICE;
  223. }
  224. else if (strcmp(argv[i], "unpin") == 0) {
  225. command = ctl_cmd::UNPIN_SERVICE;
  226. }
  227. else if (strcmp(argv[i], "unload") == 0) {
  228. command = ctl_cmd::UNLOAD_SERVICE;
  229. }
  230. else if (strcmp(argv[i], "reload") == 0) {
  231. command = ctl_cmd::RELOAD_SERVICE;
  232. }
  233. else if (strcmp(argv[i], "list") == 0) {
  234. command = ctl_cmd::LIST_SERVICES;
  235. }
  236. else if (strcmp(argv[i], "status") == 0) {
  237. command = ctl_cmd::SERVICE_STATUS;
  238. }
  239. else if (strcmp(argv[i], "is-started") == 0) {
  240. command = ctl_cmd::IS_STARTED;
  241. }
  242. else if (strcmp(argv[i], "is-failed") == 0) {
  243. command = ctl_cmd::IS_FAILED;
  244. }
  245. else if (strcmp(argv[i], "shutdown") == 0) {
  246. command = ctl_cmd::SHUTDOWN;
  247. }
  248. else if (strcmp(argv[i], "add-dep") == 0) {
  249. command = ctl_cmd::ADD_DEPENDENCY;
  250. }
  251. else if (strcmp(argv[i], "rm-dep") == 0) {
  252. command = ctl_cmd::RM_DEPENDENCY;
  253. }
  254. else if (strcmp(argv[i], "enable") == 0) {
  255. command = ctl_cmd::ENABLE_SERVICE;
  256. }
  257. else if (strcmp(argv[i], "disable") == 0) {
  258. command = ctl_cmd::DISABLE_SERVICE;
  259. }
  260. else if (strcmp(argv[i], "setenv") == 0) {
  261. command = ctl_cmd::SETENV;
  262. }
  263. else if (strcmp(argv[i], "trigger") == 0) {
  264. command = ctl_cmd::SET_TRIGGER;
  265. }
  266. else if (strcmp(argv[i], "untrigger") == 0) {
  267. command = ctl_cmd::UNSET_TRIGGER;
  268. }
  269. else if (strcmp(argv[i], "catlog") == 0) {
  270. command = ctl_cmd::CAT_LOG;
  271. }
  272. else if (strcmp(argv[i], "signal") == 0) {
  273. command = ctl_cmd::SIG_SEND;
  274. }
  275. else {
  276. cerr << "dinitctl: unrecognized command: " << argv[i] << " (use --help for help)\n";
  277. return 1;
  278. }
  279. }
  280. else {
  281. // service name / other non-option
  282. if (command == ctl_cmd::ADD_DEPENDENCY || command == ctl_cmd::RM_DEPENDENCY) {
  283. if (! dep_type_set) {
  284. if (strcmp(argv[i], "need") == 0 || strcmp(argv[i], "regular") == 0) {
  285. dep_type = dependency_type::REGULAR;
  286. }
  287. else if (strcmp(argv[i], "milestone") == 0) {
  288. dep_type = dependency_type::MILESTONE;
  289. }
  290. else if (strcmp(argv[i], "waits-for") == 0) {
  291. dep_type = dependency_type::WAITS_FOR;
  292. }
  293. else {
  294. cmdline_error = true;
  295. break;
  296. }
  297. dep_type_set = true;
  298. }
  299. else if (service_name == nullptr) {
  300. service_name = argv[i];
  301. }
  302. else if (to_service_name == nullptr) {
  303. to_service_name = argv[i];
  304. }
  305. else {
  306. cmdline_error = true;
  307. break;
  308. }
  309. }
  310. else if (command == ctl_cmd::ENABLE_SERVICE || command == ctl_cmd::DISABLE_SERVICE) {
  311. if (to_service_name != nullptr) {
  312. cmdline_error = true;
  313. break;
  314. }
  315. to_service_name = argv[i];
  316. }
  317. else if (command == ctl_cmd::SIG_SEND) {
  318. if (!show_siglist) {
  319. if (sigstr.empty()) {
  320. sigstr = argv[i];
  321. }
  322. else if (service_name == nullptr) {
  323. service_name = argv[i];
  324. }
  325. else {
  326. cmdline_error = true;
  327. }
  328. }
  329. else {
  330. cmdline_error = true;
  331. }
  332. }
  333. else {
  334. cmd_args.push_back(argv[i]);
  335. }
  336. }
  337. }
  338. // Additional argument checks/processing for various commands:
  339. if (command == ctl_cmd::NONE && !show_help) {
  340. cmdline_error = true;
  341. }
  342. else if (command == ctl_cmd::ENABLE_SERVICE || command == ctl_cmd::DISABLE_SERVICE) {
  343. cmdline_error |= (to_service_name == nullptr);
  344. }
  345. else if (command == ctl_cmd::SETENV) {
  346. // Handle SETENV specially, since it needs arguments but they are not service names
  347. if (cmd_args.empty()) {
  348. cmdline_error = true;
  349. }
  350. }
  351. else if (command == ctl_cmd::SIG_SEND) {
  352. if (show_siglist) {
  353. if (sigstr.empty()) {
  354. command = ctl_cmd::SIG_LIST;
  355. }
  356. else {
  357. cmdline_error = true;
  358. }
  359. }
  360. else {
  361. if (sigstr.empty()) {
  362. cerr << "dinitctl: signal number/name must be specified" << std::endl;
  363. return 1;
  364. }
  365. if (service_name == nullptr) {
  366. cerr << "dinitctl: service name must be specified" << std::endl;
  367. return 1;
  368. }
  369. sig_num = dinit_load::signal_name_to_number(sigstr);
  370. if (sig_num <= 0) {
  371. // (0 actually means "none"/"NONE", but we'll just fall through and error out when
  372. // it fails to parse as an integer)
  373. try {
  374. size_t pos;
  375. sig_num = std::stoi(sigstr, &pos);
  376. if (sigstr.size() != pos) {
  377. throw std::invalid_argument("");
  378. }
  379. }
  380. catch (std::exception &) { // invalid_argument, out_of_range
  381. cerr << "dinitctl: '" << sigstr
  382. << "' is not a valid signal name/number" << std::endl;
  383. return 1;
  384. }
  385. }
  386. }
  387. }
  388. else {
  389. bool no_service_cmd = (command == ctl_cmd::LIST_SERVICES
  390. || command == ctl_cmd::SHUTDOWN
  391. || command == ctl_cmd::SIG_LIST);
  392. if (no_service_cmd) {
  393. if (!cmd_args.empty()) {
  394. cmdline_error = true;
  395. }
  396. }
  397. else {
  398. if (command == ctl_cmd::ADD_DEPENDENCY || command == ctl_cmd::RM_DEPENDENCY) {
  399. if (! dep_type_set || service_name == nullptr || to_service_name == nullptr) {
  400. cmdline_error = true;
  401. }
  402. }
  403. else if (cmd_args.empty()) {
  404. cmdline_error = true;
  405. }
  406. else {
  407. // No command can currently accept more than one service argument:
  408. if (cmd_args.size() > 1) {
  409. cmdline_error = true;
  410. }
  411. service_name = cmd_args.front();
  412. }
  413. }
  414. }
  415. if (show_help) {
  416. cout << "dinitctl: control Dinit services\n"
  417. "\n"
  418. "Usage:\n"
  419. " dinitctl [options] status <service-name>\n"
  420. " dinitctl [options] is-started <service-name>\n"
  421. " dinitctl [options] is-failed <service-name>\n"
  422. " dinitctl [options] start [options] <service-name>\n"
  423. " dinitctl [options] stop [options] <service-name>\n"
  424. " dinitctl [options] restart [options] <service-name>\n"
  425. " dinitctl [options] wake [options] <service-name>\n"
  426. " dinitctl [options] release [options] <service-name>\n"
  427. " dinitctl [options] unpin <service-name>\n"
  428. " dinitctl [options] unload <service-name>\n"
  429. " dinitctl [options] reload <service-name>\n"
  430. " dinitctl [options] list\n"
  431. " dinitctl [options] shutdown\n"
  432. " dinitctl [options] add-dep <type> <from-service> <to-service>\n"
  433. " dinitctl [options] rm-dep <type> <from-service> <to-service>\n"
  434. " dinitctl [options] enable [--from <from-service>] <to-service>\n"
  435. " dinitctl [options] disable [--from <from-service>] <to-service>\n"
  436. " dinitctl [options] trigger <service-name>\n"
  437. " dinitctl [options] untrigger <service-name>\n"
  438. " dinitctl [options] setenv [name[=value] ...]\n"
  439. " dinitctl [options] catlog <service-name>\n"
  440. " dinitctl [options] signal <signal> <service-name>\n"
  441. "\n"
  442. "Note: An activated service continues running when its dependents stop.\n"
  443. "\n"
  444. "General options:\n"
  445. " --help : show this help\n"
  446. " -s, --system : control system daemon (default if run as root)\n"
  447. " -u, --user : control user daemon\n"
  448. " --quiet : suppress output (except errors)\n"
  449. " --socket-path <path>, -p <path>\n"
  450. " : specify socket for communication with daemon\n"
  451. " --use-passed-cfd : use the socket file descriptor identified by the DINIT_CS_FD\n"
  452. " environment variable to communicate with the dinit daemon\n"
  453. " -o, --offline : do not contact running dinit daemon\n"
  454. " -d, --services-dir <dir>\n"
  455. " : specify directory for service definitions (offline mode)\n"
  456. "\n"
  457. "Command options:\n"
  458. " --no-wait : don't wait for service startup/shutdown to complete\n"
  459. " --pin : pin the service in the requested state\n"
  460. " --force : force stop even if dependents will be affected\n"
  461. " -l, --list : (signal) list supported signals\n";
  462. return 0;
  463. }
  464. if (cmdline_error) {
  465. cerr << "dinitctl: Invalid command line.\n"
  466. "Try 'dinitctl --help' for more information.\n";
  467. return 1;
  468. }
  469. // SIG_LIST doesn't need a control socket connection so handle it specially.
  470. if (command == ctl_cmd::SIG_LIST) {
  471. return signal_list();
  472. }
  473. cpbuffer_t rbuffer;
  474. if (offline) {
  475. if (command != ctl_cmd::ENABLE_SERVICE && command != ctl_cmd::DISABLE_SERVICE) {
  476. cerr << "dinitctl: offline mode (--offline/-o) not supported for this command\n";
  477. return 1;
  478. }
  479. service_dir_opts.build_paths(!user_dinit);
  480. if (command == ctl_cmd::ENABLE_SERVICE || command == ctl_cmd::DISABLE_SERVICE) {
  481. // If only one service specified, assume that we enable for 'boot' service:
  482. if (service_name == nullptr) {
  483. service_name = "boot";
  484. }
  485. return enable_disable_service(-1, rbuffer, service_dir_opts, service_name, to_service_name,
  486. command == ctl_cmd::ENABLE_SERVICE, verbose);
  487. }
  488. }
  489. // Begin the real work: connect to dinit
  490. signal(SIGPIPE, SIG_IGN);
  491. int socknum = -1;
  492. if (use_passed_cfd) {
  493. socknum = get_passed_cfd();
  494. if (socknum == -1) {
  495. use_passed_cfd = false;
  496. }
  497. }
  498. bool user_specified_cs_path = false;
  499. if (!use_passed_cfd) {
  500. // Locate control socket
  501. if (!control_socket_str.empty()) {
  502. control_socket_path = control_socket_str.c_str();
  503. user_specified_cs_path = true;
  504. }
  505. else {
  506. control_socket_path = get_default_socket_path(control_socket_str, user_dinit);
  507. if (control_socket_path == nullptr) {
  508. cerr << "dinitctl: cannot determine control socket directory (set XDG_RUNTIME_DIR or HOME, check /etc/passwd file, or "
  509. "specify socket path via -p)" << endl;
  510. return 1;
  511. }
  512. }
  513. }
  514. try {
  515. if (!use_passed_cfd) {
  516. socknum = connect_to_daemon(control_socket_path);
  517. }
  518. // Start by querying protocol version:
  519. uint16_t daemon_protocol_ver = check_protocol_version(min_cp_version, max_cp_version, rbuffer, socknum);
  520. if (command == ctl_cmd::UNPIN_SERVICE) {
  521. return unpin_service(socknum, rbuffer, service_name, verbose);
  522. }
  523. else if (command == ctl_cmd::UNLOAD_SERVICE) {
  524. return unload_service(socknum, rbuffer, service_name, verbose);
  525. }
  526. else if (command == ctl_cmd::RELOAD_SERVICE) {
  527. return reload_service(socknum, rbuffer, service_name, verbose);
  528. }
  529. else if (command == ctl_cmd::LIST_SERVICES) {
  530. return list_services(socknum, rbuffer);
  531. }
  532. else if (command == ctl_cmd::SERVICE_STATUS || command == ctl_cmd::IS_STARTED
  533. || command == ctl_cmd::IS_FAILED) {
  534. return service_status(socknum, rbuffer, service_name, command, verbose);
  535. }
  536. else if (command == ctl_cmd::SHUTDOWN) {
  537. return shutdown_dinit(socknum, rbuffer, verbose);
  538. }
  539. else if (command == ctl_cmd::ADD_DEPENDENCY || command == ctl_cmd::RM_DEPENDENCY) {
  540. return add_remove_dependency(socknum, rbuffer, command == ctl_cmd::ADD_DEPENDENCY,
  541. service_name, to_service_name, dep_type, verbose);
  542. }
  543. else if (command == ctl_cmd::ENABLE_SERVICE || command == ctl_cmd::DISABLE_SERVICE) {
  544. // If only one service specified, assume that we enable for 'boot' service:
  545. if (service_name == nullptr) {
  546. service_name = "boot";
  547. }
  548. return enable_disable_service(socknum, rbuffer, service_dir_opts, service_name, to_service_name,
  549. command == ctl_cmd::ENABLE_SERVICE, verbose);
  550. }
  551. else if (command == ctl_cmd::SETENV) {
  552. return do_setenv(socknum, rbuffer, cmd_args);
  553. }
  554. else if (command == ctl_cmd::SET_TRIGGER || command == ctl_cmd::UNSET_TRIGGER) {
  555. if (daemon_protocol_ver < 2) {
  556. throw cp_old_server_exception();
  557. }
  558. return trigger_service(socknum, rbuffer, service_name, (command == ctl_cmd::SET_TRIGGER));
  559. }
  560. else if (command == ctl_cmd::CAT_LOG) {
  561. if (daemon_protocol_ver < 2) {
  562. throw cp_old_server_exception();
  563. }
  564. return cat_service_log(socknum, rbuffer, service_name, catlog_clear);
  565. }
  566. else if (command == ctl_cmd::SIG_SEND) {
  567. if (daemon_protocol_ver < 2) {
  568. throw cp_old_server_exception();
  569. }
  570. return signal_send(socknum, rbuffer, service_name, sig_num);
  571. }
  572. else {
  573. return start_stop_service(socknum, rbuffer, service_name, command, do_pin, do_force,
  574. wait_for_service, ignore_unstarted, verbose);
  575. }
  576. }
  577. catch (cp_old_client_exception &e) {
  578. std::cerr << "dinitctl: too old (daemon reports newer protocol version)" << std::endl;
  579. }
  580. catch (cp_old_server_exception &e) {
  581. std::cerr << "dinitctl: daemon too old or protocol error" << std::endl;
  582. }
  583. catch (cp_read_exception &e) {
  584. cerr << "dinitctl: control socket read failure or protocol error" << endl;
  585. }
  586. catch (cp_write_exception &e) {
  587. cerr << "dinitctl: control socket write error: " << std::strerror(e.errcode) << endl;
  588. }
  589. catch (dinit_protocol_error &e) {
  590. cerr << "dinitctl: protocol error" << endl;
  591. }
  592. catch (control_sock_conn_err &ce) {
  593. cerr << "dinitctl: " << ce.get_action() << ": " << ce.get_arg() << ": " << strerror(ce.get_err()) << "\n";
  594. if (user_dinit && ce.get_err() == ENOENT && !user_specified_cs_path) {
  595. // It is common enough that users don't realise they need to have a user instance
  596. // running in order to control it, so elaborate a little:
  597. cerr << "dinitctl: perhaps no user instance is running?\n";
  598. }
  599. }
  600. catch (general_error &ge) {
  601. std::cerr << "dinitctl";
  602. if (ge.get_action() != nullptr) {
  603. std::cerr << ": " << ge.get_action();
  604. std::string &arg = ge.get_arg();
  605. if (!arg.empty()) {
  606. std::cerr << " " << arg;
  607. }
  608. }
  609. if (ge.get_err() != 0) {
  610. std::cerr << ": " << strerror(ge.get_err());
  611. }
  612. std::cerr << '\n';
  613. }
  614. return 1;
  615. }
  616. int main(int argc, char **argv)
  617. {
  618. try {
  619. return dinitctl_main(argc, argv);
  620. }
  621. catch (std::bad_alloc &e) {
  622. std::cerr << "dinitctl: out of memory\n";
  623. }
  624. return 1;
  625. }
  626. // Size of service status info (in various packets)
  627. constexpr static unsigned STATUS_BUFFER_SIZE = 6 + ((sizeof(pid_t) > sizeof(int)) ? sizeof(pid_t) : sizeof(int));
  628. static const char * describe_state(bool stopped)
  629. {
  630. return stopped ? "stopped" : "started";
  631. }
  632. static const char * describe_verb(bool stop)
  633. {
  634. return stop ? "stop" : "start";
  635. }
  636. // Load a service: issue load command, wait for reply. Return true on success, display error message
  637. // and return false on failure.
  638. // socknum - the socket fd to communicate via
  639. // rbuffer - the buffer for communication
  640. // name - the name of the service to load
  641. // handle - where to store the handle of the loaded service
  642. // state - where to store the state of the loaded service (may be null).
  643. // write_error - whether to write an error message if the service can't be loaded
  644. static bool load_service(int socknum, cpbuffer_t &rbuffer, const char *name, handle_t *handle,
  645. service_state_t *state, bool write_error=true)
  646. {
  647. // Load 'to' service:
  648. if (issue_load_service(socknum, name)) {
  649. return false;
  650. }
  651. wait_for_reply(rbuffer, socknum);
  652. if (check_load_reply(socknum, rbuffer, handle, state, write_error) != 0) {
  653. return false;
  654. }
  655. return true;
  656. }
  657. // Get the service name for a given handle, by querying the daemon.
  658. static std::string get_service_name(int socknum, cpbuffer_t &rbuffer, handle_t handle)
  659. {
  660. auto m = membuf()
  661. .append((char) cp_cmd::QUERYSERVICENAME)
  662. .append((char) 0)
  663. .append(handle);
  664. write_all_x(socknum, m);
  665. wait_for_reply(rbuffer, socknum);
  666. if (rbuffer[0] != (char)cp_rply::SERVICENAME) {
  667. throw cp_read_exception{0};
  668. }
  669. // 1 byte reserved
  670. // uint16_t size
  671. fill_buffer_to(rbuffer, socknum, 2 + sizeof(uint16_t));
  672. uint16_t namesize;
  673. rbuffer.extract(&namesize, 2, sizeof(uint16_t));
  674. rbuffer.consume(2 + sizeof(uint16_t));
  675. std::string name;
  676. do {
  677. if (rbuffer.get_length() == 0) {
  678. fill_some(rbuffer, socknum);
  679. }
  680. size_t to_extract = std::min(size_t(rbuffer.get_length()), namesize - name.length());
  681. size_t contiguous_len = rbuffer.get_contiguous_length(rbuffer.get_ptr(0));
  682. if (contiguous_len <= to_extract) {
  683. name.append(rbuffer.get_ptr(0), contiguous_len);
  684. rbuffer.consume(contiguous_len);
  685. name.append(rbuffer.get_ptr(0), to_extract - contiguous_len);
  686. rbuffer.consume(to_extract - contiguous_len);
  687. }
  688. else {
  689. name.append(rbuffer.get_ptr(0), to_extract);
  690. rbuffer.consume(to_extract);
  691. break;
  692. }
  693. } while (name.length() < namesize);
  694. return name;
  695. }
  696. static void print_termination_details(int exit_status)
  697. {
  698. using namespace std;
  699. if (WIFSIGNALED(exit_status)) {
  700. cout << "signalled - signal ";
  701. cout << WTERMSIG(exit_status);
  702. }
  703. else if (WIFEXITED(exit_status)) {
  704. cout << "exited - status ";
  705. cout << WEXITSTATUS(exit_status);
  706. }
  707. else {
  708. cout << "unknown reason";
  709. }
  710. }
  711. // Wait for a service to reached stopped (do_stop == true) or started (do_stop == false) state.
  712. // Returns 0 if the service started/stopped, 1 if start/stop was cancelled or failed.
  713. static int wait_service_state(int socknum, cpbuffer_t &rbuffer, handle_t handle,
  714. const std::string &service_name, bool do_stop, bool verbose)
  715. {
  716. using std::cout;
  717. using std::cerr;
  718. using std::endl;
  719. service_event_t completionEvent;
  720. service_event_t cancelledEvent;
  721. if (do_stop) {
  722. completionEvent = service_event_t::STOPPED;
  723. cancelledEvent = service_event_t::STOPCANCELLED;
  724. }
  725. else {
  726. completionEvent = service_event_t::STARTED;
  727. cancelledEvent = service_event_t::STARTCANCELLED;
  728. }
  729. // Wait until service started:
  730. int r = rbuffer.fill_to(socknum, 2);
  731. while (r > 0) {
  732. if (rbuffer[0] >= 100) {
  733. unsigned pktlen = (unsigned char) rbuffer[1];
  734. fill_buffer_to(rbuffer, socknum, pktlen);
  735. if (rbuffer[0] == (char)cp_info::SERVICEEVENT) {
  736. // earlier versions do not include status info, the size in that case is base_pkt_size:
  737. constexpr unsigned base_pkt_size = 2 + sizeof(handle_t) + 1;
  738. if (pktlen < base_pkt_size) {
  739. throw dinit_protocol_error();
  740. }
  741. handle_t ev_handle;
  742. rbuffer.extract((char *) &ev_handle, 2, sizeof(ev_handle));
  743. service_event_t event = static_cast<service_event_t>(rbuffer[2 + sizeof(ev_handle)]);
  744. if (ev_handle == handle) {
  745. if (event == completionEvent) {
  746. if (verbose) {
  747. cout << "Service '" << service_name << "' " << describe_state(do_stop) << ".\n";
  748. }
  749. return 0;
  750. }
  751. else if (event == cancelledEvent) {
  752. if (verbose) {
  753. cout << "Service '" << service_name << "' " << describe_verb(do_stop) << " cancelled.\n";
  754. }
  755. return 1;
  756. }
  757. else if (!do_stop && event == service_event_t::FAILEDSTART) {
  758. if (verbose) {
  759. cout << "Service '" << service_name << "' failed to start.\n";
  760. if (pktlen >= base_pkt_size + STATUS_BUFFER_SIZE) {
  761. stopped_reason_t stop_reason =
  762. static_cast<stopped_reason_t>(rbuffer[base_pkt_size + 3]);
  763. int exit_status;
  764. rbuffer.extract((char *)&exit_status, base_pkt_size + 6, sizeof(exit_status));
  765. switch (stop_reason) {
  766. case stopped_reason_t::DEPFAILED:
  767. cout << "Reason: a dependency of the service failed to start. Check dinit log.\n";
  768. break;
  769. case stopped_reason_t::TIMEDOUT:
  770. cout << "Reason: start timed out.\n";
  771. break;
  772. case stopped_reason_t::EXECFAILED:
  773. cout << "Reason: execution of service process failed:\n";
  774. uint16_t launch_stage;
  775. rbuffer.extract((char *)&launch_stage, base_pkt_size + 4, sizeof(uint16_t));
  776. cout << " Stage: " << exec_stage_descriptions[launch_stage] << "\n";
  777. cout << " Error: " << strerror(exit_status) << "\n";
  778. break;
  779. case stopped_reason_t::FAILED:
  780. cout << "Reason: service process terminated before ready: ";
  781. print_termination_details(exit_status);
  782. cout << "\n";
  783. break;
  784. default:
  785. cout << "Reason unknown/unrecognised. Check dinit log.\n";
  786. }
  787. }
  788. }
  789. return 1;
  790. }
  791. }
  792. }
  793. rbuffer.consume(pktlen);
  794. r = rbuffer.fill_to(socknum, 2);
  795. }
  796. else {
  797. // Not an information packet?
  798. throw dinit_protocol_error();
  799. }
  800. }
  801. if (r == -1) {
  802. perror("dinitctl: read");
  803. }
  804. else {
  805. throw dinit_protocol_error();
  806. }
  807. return 1;
  808. }
  809. // Start/stop a service
  810. static int start_stop_service(int socknum, cpbuffer_t &rbuffer, const char *service_name,
  811. ctl_cmd command, bool do_pin, bool do_force, bool wait_for_service, bool ignore_unstarted,
  812. bool verbose)
  813. {
  814. using namespace std;
  815. bool do_stop = (command == ctl_cmd::STOP_SERVICE || command == ctl_cmd::RELEASE_SERVICE);
  816. service_state_t state;
  817. handle_t handle;
  818. if (command != ctl_cmd::RESTART_SERVICE && command != ctl_cmd::STOP_SERVICE
  819. && command != ctl_cmd::RELEASE_SERVICE) {
  820. ignore_unstarted = false;
  821. }
  822. if (!load_service(socknum, rbuffer, service_name, &handle, &state, !ignore_unstarted)) {
  823. return ignore_unstarted ? 0 : 1;
  824. }
  825. service_state_t wanted_state = do_stop ? service_state_t::STOPPED : service_state_t::STARTED;
  826. cp_cmd pcommand;
  827. switch (command) {
  828. case ctl_cmd::STOP_SERVICE:
  829. case ctl_cmd::RESTART_SERVICE: // stop, and then start
  830. pcommand = cp_cmd::STOPSERVICE;
  831. break;
  832. case ctl_cmd::RELEASE_SERVICE:
  833. pcommand = cp_cmd::RELEASESERVICE;
  834. break;
  835. case ctl_cmd::START_SERVICE:
  836. pcommand = cp_cmd::STARTSERVICE;
  837. break;
  838. case ctl_cmd::WAKE_SERVICE:
  839. pcommand = cp_cmd::WAKESERVICE;
  840. break;
  841. default:
  842. // can't get here (hopefully)
  843. pcommand = cp_cmd::STOPSERVICE;
  844. }
  845. // Need to issue STOPSERVICE/STARTSERVICE
  846. // We'll do this regardless of the current service state / target state, since issuing
  847. // start/stop also sets or clears the "explicitly started" flag on the service.
  848. {
  849. char flags = (do_pin ? 1 : 0) | ((pcommand == cp_cmd::STOPSERVICE && !do_force) ? 2 : 0);
  850. if (command == ctl_cmd::RESTART_SERVICE) {
  851. flags |= 4;
  852. }
  853. auto m = membuf()
  854. .append((char) pcommand)
  855. .append(flags)
  856. .append(handle);
  857. write_all_x(socknum, m);
  858. wait_for_reply(rbuffer, socknum);
  859. cp_rply reply_pkt_h = (cp_rply)rbuffer[0];
  860. rbuffer.consume(1); // consume header
  861. if (reply_pkt_h == cp_rply::ALREADYSS) {
  862. bool already = (state == wanted_state);
  863. if (verbose) {
  864. cout << "Service " << (already ? "(already) " : "")
  865. << describe_state(do_stop) << "." << endl;
  866. }
  867. return 0; // success!
  868. }
  869. if (reply_pkt_h == cp_rply::PINNEDSTARTED) {
  870. cerr << "dinitctl: cannot stop service '" << service_name << "' as it is pinned started\n";
  871. return 1;
  872. }
  873. if (reply_pkt_h == cp_rply::PINNEDSTOPPED) {
  874. cerr << "dinitctl: cannot start service '" << service_name << "' as it is pinned stopped\n";
  875. return 1;
  876. }
  877. if (reply_pkt_h == cp_rply::DEPENDENTS && pcommand == cp_cmd::STOPSERVICE) {
  878. cerr << "dinitctl: cannot stop service '" << service_name << "' due to the following dependents:\n";
  879. if (command != ctl_cmd::RESTART_SERVICE) {
  880. cerr << "(only direct dependents are listed. Exercise caution before using '--force' !!)\n";
  881. }
  882. // size_t number, N * handle_t handles
  883. size_t number;
  884. rbuffer.fill_to(socknum, sizeof(number));
  885. rbuffer.extract(&number, 0, sizeof(number));
  886. rbuffer.consume(sizeof(number));
  887. std::vector<handle_t> handles;
  888. handles.reserve(number);
  889. for (size_t i = 0; i < number; i++) {
  890. handle_t handle;
  891. rbuffer.fill_to(socknum, sizeof(handle_t));
  892. rbuffer.extract(&handle, 0, sizeof(handle));
  893. handles.push_back(handle);
  894. rbuffer.consume(sizeof(handle));
  895. }
  896. // Print the directly affected dependents:
  897. cerr << " ";
  898. for (handle_t handle : handles) {
  899. cerr << " " << get_service_name(socknum, rbuffer, handle);
  900. }
  901. cerr << "\n";
  902. return 1;
  903. }
  904. if (reply_pkt_h == cp_rply::NAK && command == ctl_cmd::RESTART_SERVICE) {
  905. if (ignore_unstarted) {
  906. if (verbose) {
  907. cout << "Service '" << service_name << "' is not currently started.\n";
  908. }
  909. return 0;
  910. }
  911. cerr << "dinitctl: cannot restart service; service not started.\n";
  912. return 1;
  913. }
  914. if (reply_pkt_h == cp_rply::NAK && command == ctl_cmd::WAKE_SERVICE) {
  915. cerr << "dinitctl: service has no active dependents, cannot wake.\n";
  916. return 1;
  917. }
  918. if (reply_pkt_h == cp_rply::SHUTTINGDOWN) {
  919. cerr << "dinitctl: cannot start/restart/wake service, shutdown is in progress.\n";
  920. return 1;
  921. }
  922. if (reply_pkt_h != cp_rply::ACK && reply_pkt_h != cp_rply::ALREADYSS) {
  923. cerr << "dinitctl: protocol error." << endl;
  924. return 1;
  925. }
  926. }
  927. if (! wait_for_service) {
  928. if (verbose) {
  929. cout << "Issued " << describe_verb(do_stop) << " command successfully for service '"
  930. << service_name << "'." << endl;
  931. }
  932. return 0;
  933. }
  934. return wait_service_state(socknum, rbuffer, handle, service_name, do_stop, verbose);
  935. }
  936. // Issue a "load service" command (LOADSERVICE), without waiting for
  937. // a response. Returns 1 on failure (with error logged), 0 on success.
  938. static int issue_load_service(int socknum, const char *service_name, bool find_only)
  939. {
  940. // Build buffer;
  941. srvname_len_t srvname_len = strlen(service_name);
  942. int bufsize = 3 + srvname_len;
  943. std::unique_ptr<char[]> ubuf(new char[bufsize]);
  944. auto buf = ubuf.get();
  945. buf[0] = (char)(find_only ? cp_cmd::FINDSERVICE : cp_cmd::LOADSERVICE);
  946. memcpy(buf + 1, &srvname_len, sizeof(srvname_len));
  947. memcpy(buf + 3, service_name, srvname_len);
  948. write_all_x(socknum, buf, bufsize);
  949. return 0;
  950. }
  951. // Check that a "load service" reply was received, and that the requested service was found.
  952. // state_p may be null.
  953. static int check_load_reply(int socknum, cpbuffer_t &rbuffer, handle_t *handle_p, service_state_t *state_p, bool write_error)
  954. {
  955. using namespace std;
  956. cp_rply reply_pkt_h = (cp_rply)rbuffer[0];
  957. if (reply_pkt_h == cp_rply::SERVICERECORD) {
  958. fill_buffer_to(rbuffer, socknum, 2 + sizeof(*handle_p));
  959. rbuffer.extract((char *) handle_p, 2, sizeof(*handle_p));
  960. if (state_p) *state_p = static_cast<service_state_t>(rbuffer[1]);
  961. //target_state = static_cast<service_state_t>(rbuffer[2 + sizeof(handle)]);
  962. rbuffer.consume(3 + sizeof(*handle_p));
  963. return 0;
  964. }
  965. else if (reply_pkt_h == cp_rply::NOSERVICE) {
  966. if (write_error) {
  967. cerr << "dinitctl: failed to find service description.\n";
  968. cerr << "dinitctl: check service description file exists / service name spelling.\n";
  969. }
  970. return 1;
  971. }
  972. else if (reply_pkt_h == cp_rply::SERVICE_DESC_ERR) {
  973. if (write_error) {
  974. cerr << "dinitctl: error in service description.\n";
  975. cerr << "dinitctl: try 'dinitcheck <service-name>' or check log for more information.\n";
  976. }
  977. return 1;
  978. }
  979. else if (reply_pkt_h == cp_rply::SERVICE_LOAD_ERR) {
  980. if (write_error) {
  981. cerr << "dinitctl: error loading service (or dependency of service).\n";
  982. cerr << "dinitctl: try 'dinitcheck <service-name>' or check log for more information.\n";
  983. }
  984. return 1;
  985. }
  986. else {
  987. throw dinit_protocol_error();
  988. }
  989. }
  990. static int unpin_service(int socknum, cpbuffer_t &rbuffer, const char *service_name, bool verbose)
  991. {
  992. using namespace std;
  993. handle_t handle;
  994. // Build buffer;
  995. if (! load_service(socknum, rbuffer, service_name, &handle, nullptr)) {
  996. return 1;
  997. }
  998. // Issue UNPIN command.
  999. {
  1000. auto m = membuf()
  1001. .append((char)cp_cmd::UNPINSERVICE)
  1002. .append(handle);
  1003. write_all_x(socknum, m);
  1004. wait_for_reply(rbuffer, socknum);
  1005. if (rbuffer[0] != (char)cp_rply::ACK) {
  1006. cerr << "dinitctl: protocol error." << endl;
  1007. return 1;
  1008. }
  1009. rbuffer.consume(1);
  1010. }
  1011. if (verbose) {
  1012. cout << "Service '" << service_name << "' unpinned." << endl;
  1013. }
  1014. return 0;
  1015. }
  1016. static int unload_service(int socknum, cpbuffer_t &rbuffer, const char *service_name, bool verbose)
  1017. {
  1018. using namespace std;
  1019. if (issue_load_service(socknum, service_name, true) == 1) {
  1020. return 1;
  1021. }
  1022. wait_for_reply(rbuffer, socknum);
  1023. handle_t handle;
  1024. if (rbuffer[0] == (char)cp_rply::NOSERVICE) {
  1025. cerr << "dinitctl: service not loaded." << endl;
  1026. return 1;
  1027. }
  1028. if (check_load_reply(socknum, rbuffer, &handle, nullptr) != 0) {
  1029. return 1;
  1030. }
  1031. // Issue UNLOAD command.
  1032. {
  1033. auto m = membuf()
  1034. .append((char)cp_cmd::UNLOADSERVICE)
  1035. .append(handle);
  1036. write_all_x(socknum, m);
  1037. wait_for_reply(rbuffer, socknum);
  1038. if (rbuffer[0] == (char)cp_rply::NAK) {
  1039. cerr << "dinitctl: could not unload service; service not stopped, or is a dependency of "
  1040. "other service." << endl;
  1041. return 1;
  1042. }
  1043. if (rbuffer[0] != (char)cp_rply::ACK) {
  1044. cerr << "dinitctl: protocol error." << endl;
  1045. return 1;
  1046. }
  1047. rbuffer.consume(1);
  1048. }
  1049. if (verbose) {
  1050. cout << "Service '" << service_name << "' unloaded." << endl;
  1051. }
  1052. return 0;
  1053. }
  1054. static int reload_service(int socknum, cpbuffer_t &rbuffer, const char *service_name, bool verbose)
  1055. {
  1056. using namespace std;
  1057. if (issue_load_service(socknum, service_name, true) == 1) {
  1058. return 1;
  1059. }
  1060. wait_for_reply(rbuffer, socknum);
  1061. handle_t handle;
  1062. if (rbuffer[0] == (char)cp_rply::NOSERVICE) {
  1063. rbuffer.consume(1);
  1064. // If the service isn't loaded yet at all, just do a basic load:
  1065. if (issue_load_service(socknum, service_name, false) == 1) {
  1066. return 1;
  1067. }
  1068. wait_for_reply(rbuffer, socknum);
  1069. if (check_load_reply(socknum, rbuffer, &handle, nullptr) != 0) {
  1070. return 1;
  1071. }
  1072. if (verbose) {
  1073. cout << "Service '" << service_name << "' reloaded." << endl;
  1074. }
  1075. return 0;
  1076. }
  1077. if (check_load_reply(socknum, rbuffer, &handle, nullptr) != 0) {
  1078. return 1;
  1079. }
  1080. // Issue RELOAD command.
  1081. {
  1082. auto m = membuf()
  1083. .append((char)cp_cmd::RELOADSERVICE)
  1084. .append(handle);
  1085. write_all_x(socknum, m);
  1086. wait_for_reply(rbuffer, socknum);
  1087. if (rbuffer[0] == (char)cp_rply::NAK) {
  1088. cerr << "dinitctl: could not reload service; service in wrong state, incompatible change, "
  1089. "or bad service description." << endl;
  1090. return 1;
  1091. }
  1092. if (rbuffer[0] != (char)cp_rply::ACK) {
  1093. cerr << "dinitctl: protocol error." << endl;
  1094. return 1;
  1095. }
  1096. rbuffer.consume(1);
  1097. }
  1098. if (verbose) {
  1099. cout << "Service '" << service_name << "' reloaded." << endl;
  1100. }
  1101. return 0;
  1102. }
  1103. static int list_services(int socknum, cpbuffer_t &rbuffer)
  1104. {
  1105. using namespace std;
  1106. char cmdbuf[] = { (char)cp_cmd::LISTSERVICES };
  1107. write_all_x(socknum, cmdbuf, 1);
  1108. wait_for_reply(rbuffer, socknum);
  1109. while (rbuffer[0] == (char)cp_rply::SVCINFO) {
  1110. int hdrsize = 8 + std::max(sizeof(int), sizeof(pid_t));
  1111. fill_buffer_to(rbuffer, socknum, hdrsize);
  1112. unsigned name_len = (unsigned char)rbuffer[1];
  1113. service_state_t current = static_cast<service_state_t>(rbuffer[2]);
  1114. service_state_t target = static_cast<service_state_t>(rbuffer[3]);
  1115. int console_flags = rbuffer[4];
  1116. bool has_console = (console_flags & 2) != 0;
  1117. bool waiting_console = (console_flags & 1) != 0;
  1118. bool was_skipped = (console_flags & 4) != 0;
  1119. bool marked_active = (console_flags & 8) != 0;
  1120. bool has_pid = (console_flags & 16) != 0;
  1121. stopped_reason_t stop_reason = static_cast<stopped_reason_t>(rbuffer[5]);
  1122. pid_t service_pid;
  1123. int exit_status;
  1124. if (has_pid) {
  1125. rbuffer.extract((char *)&service_pid, 8, sizeof(service_pid));
  1126. }
  1127. else {
  1128. rbuffer.extract((char *)&exit_status, 8, sizeof(exit_status));
  1129. }
  1130. fill_buffer_to(rbuffer, socknum, name_len + hdrsize);
  1131. char *name_ptr = rbuffer.get_ptr(hdrsize);
  1132. unsigned clength = std::min(rbuffer.get_contiguous_length(name_ptr), name_len);
  1133. string name = string(name_ptr, clength);
  1134. name.append(rbuffer.get_buf_base(), name_len - clength);
  1135. cout << "[";
  1136. // [ ] if marked active; otherwise, { } if target state is STARTED
  1137. // + if started, 's' if skipped, space otherwise
  1138. char lbracket = target == service_state_t::STARTED ? '{' : ' ';
  1139. char rbracket = target == service_state_t::STARTED ? '}' : ' ';
  1140. cout << (marked_active ? '[' : lbracket);
  1141. if (current == service_state_t::STARTED) {
  1142. cout << (was_skipped ? 's' : '+');
  1143. }
  1144. else {
  1145. cout << ' ';
  1146. }
  1147. cout << (marked_active ? ']' : rbracket);
  1148. if (current == service_state_t::STARTING) {
  1149. cout << "<<";
  1150. }
  1151. else if (current == service_state_t::STOPPING) {
  1152. cout << ">>";
  1153. }
  1154. else {
  1155. cout << " ";
  1156. }
  1157. cout << (target == service_state_t::STOPPED ? '{' : ' ');
  1158. if (current == service_state_t::STOPPED) {
  1159. bool did_fail = false;
  1160. if (stop_reason == stopped_reason_t::TERMINATED) {
  1161. if (!WIFEXITED(exit_status) || WEXITSTATUS(exit_status) != 0) {
  1162. did_fail = true;
  1163. }
  1164. }
  1165. else did_fail = (stop_reason != stopped_reason_t::NORMAL);
  1166. cout << (did_fail ? 'X' : '-');
  1167. }
  1168. else {
  1169. cout << ' ';
  1170. }
  1171. cout << (target == service_state_t::STOPPED ? '}' : ' ');
  1172. cout << "] " << name;
  1173. if (current != service_state_t::STOPPED && has_pid) {
  1174. cout << " (pid: " << service_pid << ")";
  1175. }
  1176. if (current == service_state_t::STOPPED && stop_reason == stopped_reason_t::TERMINATED) {
  1177. if (WIFEXITED(exit_status)) {
  1178. cout << " (exit status: " << WEXITSTATUS(exit_status) << ")";
  1179. }
  1180. else if (WIFSIGNALED(exit_status)) {
  1181. cout << " (signal: " << WTERMSIG(exit_status) << ")";
  1182. }
  1183. }
  1184. if (has_console) {
  1185. cout << " (has console)";
  1186. }
  1187. else if (waiting_console) {
  1188. cout << " (waiting for console)";
  1189. }
  1190. cout << endl;
  1191. rbuffer.consume(hdrsize + name_len);
  1192. wait_for_reply(rbuffer, socknum);
  1193. }
  1194. if (rbuffer[0] != (char)cp_rply::LISTDONE) {
  1195. cerr << "dinitctl: control socket protocol error" << endl;
  1196. return 1;
  1197. }
  1198. return 0;
  1199. }
  1200. static int service_status(int socknum, cpbuffer_t &rbuffer, const char *service_name, ctl_cmd command, bool verbose)
  1201. {
  1202. using namespace std;
  1203. bool is_status = command == ctl_cmd::SERVICE_STATUS;
  1204. if (issue_load_service(socknum, service_name, true) == 1) {
  1205. return 1;
  1206. }
  1207. wait_for_reply(rbuffer, socknum);
  1208. handle_t handle;
  1209. if (rbuffer[0] == (char)cp_rply::NOSERVICE) {
  1210. if (is_status) {
  1211. cerr << "dinitctl: service not loaded." << endl;
  1212. }
  1213. return 1;
  1214. }
  1215. if (check_load_reply(socknum, rbuffer, &handle, nullptr, is_status) != 0) {
  1216. return 1;
  1217. }
  1218. // Issue STATUS request
  1219. {
  1220. auto m = membuf()
  1221. .append((char)cp_cmd::SERVICESTATUS)
  1222. .append(handle);
  1223. write_all_x(socknum, m);
  1224. wait_for_reply(rbuffer, socknum);
  1225. if (rbuffer[0] != (char)cp_rply::SERVICESTATUS) {
  1226. cerr << "dinitctl: protocol error." << endl;
  1227. return 1;
  1228. }
  1229. rbuffer.consume(1);
  1230. fill_buffer_to(rbuffer, socknum, STATUS_BUFFER_SIZE + 1 /* reserved */);
  1231. rbuffer.consume(1);
  1232. service_state_t current = static_cast<service_state_t>(rbuffer[0]);
  1233. service_state_t target = static_cast<service_state_t>(rbuffer[1]);
  1234. int console_flags = rbuffer[2];
  1235. bool has_console = (console_flags & 2) != 0;
  1236. bool waiting_console = (console_flags & 1) != 0;
  1237. bool was_skipped = (console_flags & 4) != 0;
  1238. bool marked_active = (console_flags & 8) != 0;
  1239. bool has_pid = (console_flags & 16) != 0;
  1240. stopped_reason_t stop_reason = static_cast<stopped_reason_t>(rbuffer[3]);
  1241. pid_t service_pid = -1;
  1242. int exit_status = 0;
  1243. if (has_pid) {
  1244. rbuffer.extract((char *)&service_pid, 6, sizeof(service_pid));
  1245. }
  1246. else {
  1247. rbuffer.extract((char *)&exit_status, 6, sizeof(exit_status));
  1248. }
  1249. switch (command) {
  1250. case ctl_cmd::IS_STARTED:
  1251. case ctl_cmd::IS_FAILED:
  1252. if (verbose) {
  1253. switch (current) {
  1254. case service_state_t::STOPPED:
  1255. cout << "STOPPED" << endl;
  1256. break;
  1257. case service_state_t::STARTING:
  1258. cout << "STARTING" << endl;
  1259. break;
  1260. case service_state_t::STARTED:
  1261. cout << "STARTED" << endl;
  1262. break;
  1263. case service_state_t::STOPPING:
  1264. cout << "STOPPING" << endl;
  1265. }
  1266. }
  1267. if (command == ctl_cmd::IS_STARTED) {
  1268. // return 0 (success) for started
  1269. return current != service_state_t::STARTED;
  1270. }
  1271. // IS_FAILED:
  1272. // return 0 (success) for specific stopped reasons
  1273. if (current == service_state_t::STOPPED) {
  1274. switch (stop_reason) {
  1275. case stopped_reason_t::DEPFAILED:
  1276. case stopped_reason_t::FAILED:
  1277. case stopped_reason_t::EXECFAILED:
  1278. case stopped_reason_t::TIMEDOUT:
  1279. return 0;
  1280. default:
  1281. break;
  1282. }
  1283. }
  1284. return 1;
  1285. default:
  1286. /* status */
  1287. break;
  1288. }
  1289. cout << "Service: " << service_name << "\n"
  1290. " State: ";
  1291. switch (current) {
  1292. case service_state_t::STOPPED:
  1293. cout << "STOPPED";
  1294. switch (stop_reason) {
  1295. case stopped_reason_t::DEPRESTART:
  1296. cout << " (dependency restarted)";
  1297. break;
  1298. case stopped_reason_t::DEPFAILED:
  1299. cout << " (dependency failed/terminated)";
  1300. break;
  1301. case stopped_reason_t::FAILED:
  1302. cout << " (failed to start";
  1303. if (exit_status != 0) {
  1304. cout << "; ";
  1305. print_termination_details(exit_status);
  1306. }
  1307. cout << ")";
  1308. break;
  1309. case stopped_reason_t::EXECFAILED:
  1310. uint16_t launch_stage;
  1311. rbuffer.extract((char *)&launch_stage, 4, 2);
  1312. cout << " (could not be launched)\n";
  1313. cout << " Stage: " << exec_stage_descriptions[launch_stage] << "\n";
  1314. cout << " Error: " << strerror(exit_status);
  1315. break;
  1316. case stopped_reason_t::TERMINATED:
  1317. cout << " (terminated";
  1318. if (exit_status != 0) {
  1319. cout << "; ";
  1320. print_termination_details(exit_status);
  1321. }
  1322. cout << ")";
  1323. break;
  1324. case stopped_reason_t::TIMEDOUT:
  1325. cout << " (start timed out)";
  1326. break;
  1327. case stopped_reason_t::NORMAL:
  1328. break;
  1329. }
  1330. break;
  1331. case service_state_t::STARTING:
  1332. cout << "STARTING";
  1333. if (target == service_state_t::STOPPED) {
  1334. cout << " (target state: STOPPED)";
  1335. }
  1336. break;
  1337. case service_state_t::STARTED:
  1338. cout << "STARTED";
  1339. if (was_skipped) {
  1340. cout << " (startup skipped)";
  1341. }
  1342. break;
  1343. case service_state_t::STOPPING:
  1344. cout << "STOPPING";
  1345. if (target == service_state_t::STARTED) {
  1346. cout << " (target state: STARTED)";
  1347. }
  1348. if (exit_status != 0) {
  1349. cout << "(terminated ;";
  1350. print_termination_details(exit_status);
  1351. cout << ")";
  1352. }
  1353. }
  1354. if (has_console) {
  1355. cout << " (holding console)";
  1356. }
  1357. if (waiting_console) {
  1358. cout << " (waiting for console)";
  1359. }
  1360. cout << "\n";
  1361. if (target == service_state_t::STARTED) {
  1362. cout << " Activation: ";
  1363. if (marked_active) {
  1364. cout << "explicitly started\n";
  1365. }
  1366. else {
  1367. cout << "start due to dependent(s)\n";
  1368. }
  1369. }
  1370. if (service_pid != -1) {
  1371. cout << " Process ID: " << service_pid << "\n";
  1372. }
  1373. }
  1374. return 0;
  1375. }
  1376. static int add_remove_dependency(int socknum, cpbuffer_t &rbuffer, bool add,
  1377. const char *service_from, const char *service_to, dependency_type dep_type, bool verbose)
  1378. {
  1379. using namespace std;
  1380. handle_t from_handle;
  1381. handle_t to_handle;
  1382. if (! load_service(socknum, rbuffer, service_from, &from_handle, nullptr)
  1383. || ! load_service(socknum, rbuffer, service_to, &to_handle, nullptr)) {
  1384. return 1;
  1385. }
  1386. if (from_handle == to_handle) {
  1387. cerr << "dinitctl: can not add/remove a dependency from a service to itself" << endl;
  1388. return 1;
  1389. }
  1390. auto m = membuf()
  1391. .append<char>(add ? (char)cp_cmd::ADD_DEP : (char)cp_cmd::REM_DEP)
  1392. .append(static_cast<char>(dep_type))
  1393. .append(from_handle)
  1394. .append(to_handle);
  1395. write_all_x(socknum, m);
  1396. wait_for_reply(rbuffer, socknum);
  1397. // check reply
  1398. if (rbuffer[0] == (char)cp_rply::NAK) {
  1399. if (add) {
  1400. cerr << "dinitctl: could not add dependency: circular dependency or wrong state" << endl;
  1401. }
  1402. else {
  1403. cerr << "dinitctl: no such dependency to remove" << endl;
  1404. }
  1405. return 1;
  1406. }
  1407. if (rbuffer[0] != (char)cp_rply::ACK) {
  1408. cerr << "dinitctl: control socket protocol error" << endl;
  1409. return 1;
  1410. }
  1411. if (verbose) {
  1412. std::cout << "Service '" << service_from << "': dependency '" << service_to << "' " << (add ? "added" : "removed") << endl;
  1413. }
  1414. return 0;
  1415. }
  1416. static int shutdown_dinit(int socknum, cpbuffer_t &rbuffer, bool verbose)
  1417. {
  1418. // TODO support no-wait option.
  1419. using namespace std;
  1420. auto m = membuf()
  1421. .append((char)cp_cmd::SHUTDOWN)
  1422. .append(static_cast<char>(shutdown_type_t::HALT));
  1423. write_all_x(socknum, m);
  1424. wait_for_reply(rbuffer, socknum);
  1425. if (rbuffer[0] != (char)cp_rply::ACK) {
  1426. cerr << "dinitctl: control socket protocol error" << endl;
  1427. return 1;
  1428. }
  1429. if (verbose) {
  1430. std::cout << "Shutting down dinit..." << std::endl;
  1431. }
  1432. // Now wait for rollback complete, by waiting for the connection to close:
  1433. try {
  1434. while (true) {
  1435. wait_for_info(rbuffer, socknum);
  1436. rbuffer.consume(rbuffer[1]);
  1437. }
  1438. }
  1439. catch (cp_read_exception &exc) {
  1440. // Assume that the connection closed.
  1441. }
  1442. if (verbose) {
  1443. std::cout << "Connection closed." << std::endl;
  1444. }
  1445. return 0;
  1446. }
  1447. // Get the service description directory for a loaded service
  1448. static std::string get_service_description_dir(int socknum, cpbuffer_t &rbuffer, handle_t service_handle)
  1449. {
  1450. auto m = membuf()
  1451. .append((char)cp_cmd::QUERYSERVICEDSCDIR)
  1452. .append<char>(0)
  1453. .append(service_handle);
  1454. write_all_x(socknum, m);
  1455. wait_for_reply(rbuffer, socknum);
  1456. if (rbuffer[0] != (char)cp_rply::SVCDSCDIR) {
  1457. throw dinit_protocol_error();
  1458. }
  1459. rbuffer.consume(1);
  1460. fill_buffer_to(rbuffer, socknum, 4);
  1461. uint32_t sdir_len;
  1462. rbuffer.extract(&sdir_len, 0, sizeof(uint32_t));
  1463. rbuffer.consume(4);
  1464. std::string result_str;
  1465. static_assert(sizeof(unsigned) >= sizeof(uint32_t), "");
  1466. unsigned needed = sdir_len;
  1467. while (needed > 0) {
  1468. unsigned available = rbuffer.get_length();
  1469. if (available == 0) {
  1470. fill_some(rbuffer, socknum);
  1471. available = rbuffer.get_length();
  1472. }
  1473. unsigned to_use = std::min(available, needed);
  1474. size_t orig_len = result_str.length();
  1475. result_str.resize(orig_len + to_use);
  1476. rbuffer.extract(&result_str[orig_len], 0, to_use);
  1477. rbuffer.consume(to_use);
  1478. needed -= to_use;
  1479. }
  1480. return result_str;
  1481. }
  1482. static std::string get_service_descr_filename(int socknum, cpbuffer_t &rbuffer, handle_t serivce_handle,
  1483. const char *service_name)
  1484. {
  1485. std::string r = get_service_description_dir(socknum, rbuffer, serivce_handle);
  1486. if (r.empty())
  1487. throw dinit_protocol_error();
  1488. if (r.back() != '/')
  1489. r.append(1, '/');
  1490. r.append(service_name);
  1491. return r;
  1492. }
  1493. // find (and open) a service description file in a set of paths
  1494. static void find_service_desc(const char *svc_name, const std::vector<std::string> &paths,
  1495. std::ifstream &service_file, std::string &service_file_path)
  1496. {
  1497. using namespace std;
  1498. for (std::string path : paths) {
  1499. string test_path = combine_paths(path, svc_name);
  1500. service_file.open(test_path.c_str(), ios::in);
  1501. if (service_file || errno != ENOENT) {
  1502. service_file_path = test_path;
  1503. break;
  1504. }
  1505. }
  1506. }
  1507. // exception for cancelling a service operation
  1508. class service_op_cancel { };
  1509. static int enable_disable_service(int socknum, cpbuffer_t &rbuffer, service_dir_opt &service_dir_opts,
  1510. const char *from, const char *to, bool enable, bool verbose)
  1511. {
  1512. using namespace std;
  1513. service_state_t from_state = service_state_t::STARTED;
  1514. handle_t from_handle;
  1515. handle_t to_handle;
  1516. vector<string> service_dir_paths;
  1517. string service_file_path;
  1518. string to_service_file_path;
  1519. ifstream service_file;
  1520. ifstream to_service_file;
  1521. if (socknum >= 0) {
  1522. if (!load_service(socknum, rbuffer, from, &from_handle, &from_state)
  1523. || !load_service(socknum, rbuffer, to, &to_handle, nullptr)) {
  1524. return 1;
  1525. }
  1526. try {
  1527. service_dir_paths = get_service_description_dirs(socknum, rbuffer);
  1528. }
  1529. catch (dinit_protocol_error &) {
  1530. cerr << "dinitctl: unknown configuration or protocol error, unable to load service descriptions" << endl;
  1531. }
  1532. service_file_path = get_service_descr_filename(socknum, rbuffer, from_handle, from);
  1533. to_service_file_path = get_service_descr_filename(socknum, rbuffer, to_handle, to);
  1534. // open from file
  1535. service_file.open(service_file_path.c_str());
  1536. if (!service_file) {
  1537. cerr << "dinitctl: could not open service description file '"
  1538. << service_file_path << "': " << strerror(errno) << "\n";
  1539. return EXIT_FAILURE;
  1540. }
  1541. }
  1542. else {
  1543. // offline case
  1544. const auto &path_list = service_dir_opts.get_paths();
  1545. for (auto &path : path_list) {
  1546. service_dir_paths.emplace_back(path.get_dir());
  1547. }
  1548. find_service_desc(from, service_dir_paths, service_file, service_file_path);
  1549. if (!service_file) {
  1550. if (errno == ENOENT) {
  1551. cerr << "dinitctl: could not locate service file for service '" << from << "'\n";
  1552. }
  1553. else {
  1554. cerr << "dinitctl: could not open service description file '"
  1555. << service_file_path << "': " << strerror(errno) << "\n";
  1556. }
  1557. return EXIT_FAILURE;
  1558. }
  1559. find_service_desc(to, service_dir_paths, to_service_file, to_service_file_path);
  1560. if (!to_service_file) {
  1561. cerr << "dinitctl: could not locate service file for target service '" << to << "'" << endl;
  1562. return EXIT_FAILURE;
  1563. }
  1564. }
  1565. // We now need to read the service file, identify the waits-for.d directory (bail out if more than one),
  1566. // make sure the service is not listed as a dependency individually.
  1567. string waits_for_d;
  1568. try {
  1569. process_service_file(from, service_file, [&](string &line, unsigned line_num, string &setting,
  1570. dinit_load::string_iterator i, dinit_load::string_iterator end) -> void {
  1571. if (setting == "waits-for" || setting == "depends-on" || setting == "depends-ms") {
  1572. string dname = dinit_load::read_setting_value(line_num, i, end);
  1573. if (dname == to) {
  1574. // There is already a dependency
  1575. cerr << "dinitctl: there is a fixed dependency to service '" << to
  1576. << "' in the service description of '" << from << "'." << endl;
  1577. throw service_op_cancel();
  1578. }
  1579. }
  1580. else if (setting == "waits-for.d") {
  1581. string dname = dinit_load::read_setting_value(line_num, i, end);
  1582. if (! waits_for_d.empty()) {
  1583. cerr << "dinitctl: service '" << from << "' has multiple waits-for.d directories "
  1584. << "specified in service description" << endl;
  1585. throw service_op_cancel();
  1586. }
  1587. waits_for_d = std::move(dname);
  1588. }
  1589. });
  1590. }
  1591. catch (const service_op_cancel &cexc) {
  1592. return 1;
  1593. }
  1594. // If the from service has no waits-for.d specified, we can't continue
  1595. if (waits_for_d.empty()) {
  1596. cerr << "dinitctl: service '" << from << "' has no waits-for.d directory specified" << endl;
  1597. return 1;
  1598. }
  1599. // The waits-for.d path is relative to the service file path, combine:
  1600. string waits_for_d_full = combine_paths(parent_path(service_file_path), waits_for_d.c_str());
  1601. // check if dependency already exists
  1602. string dep_link_path = combine_paths(waits_for_d_full, to);
  1603. struct stat stat_buf;
  1604. if (lstat(dep_link_path.c_str(), &stat_buf) == -1) {
  1605. if (errno != ENOENT) {
  1606. cerr << "dinitctl: checking for existing dependency link: " << dep_link_path << ": "
  1607. << strerror(errno) << endl;
  1608. return 1;
  1609. }
  1610. }
  1611. else {
  1612. // dependency already exists
  1613. if (enable) {
  1614. cerr << "dinitctl: service already enabled." << endl;
  1615. return 1;
  1616. }
  1617. }
  1618. if (socknum >= 0) {
  1619. // warn if 'from' service is not started
  1620. if (enable && from_state != service_state_t::STARTED) {
  1621. cerr << "dinitctl: warning: enabling dependency for non-started service" << endl;
  1622. }
  1623. // add/remove dependency
  1624. constexpr int enable_pktsize = 2 + sizeof(handle_t) * 2;
  1625. char cmdbuf[enable_pktsize] = { char(enable ? cp_cmd::ENABLESERVICE : cp_cmd::REM_DEP),
  1626. char(dependency_type::WAITS_FOR)};
  1627. memcpy(cmdbuf + 2, &from_handle, sizeof(from_handle));
  1628. memcpy(cmdbuf + 2 + sizeof(from_handle), &to_handle, sizeof(to_handle));
  1629. write_all_x(socknum, cmdbuf, enable_pktsize);
  1630. wait_for_reply(rbuffer, socknum);
  1631. // check reply
  1632. if (rbuffer[0] == (char)cp_rply::NAK) {
  1633. if (enable) {
  1634. cerr << "dinitctl: could not enable service: possible circular dependency" << endl;
  1635. }
  1636. else {
  1637. cerr << "dinitctl: service not currently enabled" << endl;
  1638. }
  1639. return 1;
  1640. }
  1641. if (rbuffer[0] != (char)cp_rply::ACK) {
  1642. cerr << "dinitctl: control socket protocol error" << endl;
  1643. return 1;
  1644. }
  1645. rbuffer.consume(1);
  1646. }
  1647. // create link
  1648. if (enable) {
  1649. // Guess a relative path to use as the symlink target. Note that if either the waits-for.d directory
  1650. // path, or the "to" service description file path, contains symbolic links or path segments with
  1651. // ".." or ".", this may not produce the "correct" result. We do a "reasonable effort". If the
  1652. // result isn't correct, the only consequence is that the link may be broken or point to the wrong
  1653. // file; Dinit itself won't be affected by this.
  1654. string symlink_target;
  1655. auto spos = waits_for_d_full.rfind('/');
  1656. if (spos != std::string::npos) {
  1657. if (strncmp(waits_for_d_full.c_str(), to_service_file_path.c_str(), spos) == 0) {
  1658. symlink_target = "../";
  1659. symlink_target.append(to_service_file_path, spos + 1, std::string::npos);
  1660. }
  1661. }
  1662. if (symlink_target.empty()) {
  1663. // not yet determined: try full path or just "../(to)"
  1664. if (to_service_file_path[0] == '/') {
  1665. symlink_target = to_service_file_path;
  1666. }
  1667. else {
  1668. symlink_target = "../";
  1669. symlink_target.append(to);
  1670. }
  1671. }
  1672. if (symlink(symlink_target.c_str(), dep_link_path.c_str()) == -1) {
  1673. cerr << "dinitctl: could not create symlink at " << dep_link_path << ": " << strerror(errno);
  1674. if (socknum >= 0) {
  1675. cerr << "\n" "dinitctl: note: service was enabled for now; persistent enable failed.";
  1676. }
  1677. cerr << endl;
  1678. return 1;
  1679. }
  1680. }
  1681. else {
  1682. if (unlink(dep_link_path.c_str()) == -1) {
  1683. cerr << "dinitctl: could not unlink dependency entry " << dep_link_path << ": "
  1684. << strerror(errno);
  1685. if (socknum >= 0) {
  1686. cerr << "\n" "dinitctl: note: service was disabled for now; persistent disable failed.";
  1687. }
  1688. cerr << endl;
  1689. return 1;
  1690. }
  1691. }
  1692. if (socknum >= 0) {
  1693. // Check status of the service now
  1694. auto m = membuf()
  1695. .append((char)cp_cmd::SERVICESTATUS)
  1696. .append(to_handle);
  1697. write_all_x(socknum, m);
  1698. wait_for_reply(rbuffer, socknum);
  1699. if (rbuffer[0] != (char)cp_rply::SERVICESTATUS) {
  1700. cerr << "dinitctl: protocol error." << endl;
  1701. return 1;
  1702. }
  1703. rbuffer.consume(1);
  1704. int statussize = 6 + std::max(sizeof(pid_t), sizeof(int));;
  1705. fill_buffer_to(rbuffer, socknum, statussize + 1 /* reserved */);
  1706. rbuffer.consume(1);
  1707. service_state_t current = static_cast<service_state_t>(rbuffer[0]);
  1708. service_state_t target = static_cast<service_state_t>(rbuffer[1]);
  1709. rbuffer.consume(statussize);
  1710. if (verbose) {
  1711. cout << "Service '" << to << "' has been " << (enable ? "enabled" : "disabled") << "." << endl;
  1712. }
  1713. if (enable) {
  1714. if (current != service_state_t::STARTED) {
  1715. wait_service_state(socknum, rbuffer, to_handle, to, false /* start */, verbose);
  1716. }
  1717. }
  1718. else {
  1719. if (target != service_state_t::STOPPED) {
  1720. std::cerr << "dinitctl: note: disabled service may have other dependents\n";
  1721. }
  1722. }
  1723. }
  1724. else {
  1725. if (verbose) {
  1726. cout << "Service '" << to << "' has been " << (enable ? "enabled" : "disabled") << "." << endl;
  1727. }
  1728. }
  1729. return 0;
  1730. }
  1731. static int do_setenv(int socknum, cpbuffer_t &rbuffer, std::vector<const char *> &env_names)
  1732. {
  1733. using namespace std;
  1734. string buf;
  1735. for (const char *envp : env_names) {
  1736. envvar_len_t envvar_len;
  1737. buf.clear();
  1738. buf.reserve(6);
  1739. // protocol message and size space
  1740. buf.push_back((char)cp_cmd::SETENV);
  1741. buf.append(sizeof(envvar_len), 0);
  1742. const unsigned hdr_len = 1 + sizeof(envvar_len);
  1743. // either full var or name
  1744. auto elen = strlen(envp);
  1745. buf.append(envp, elen);
  1746. // if '=' not found, get value from environment
  1747. if (!memchr(envp, '=', elen)) {
  1748. buf.push_back('=');
  1749. auto *envv = getenv(envp);
  1750. if (envv) {
  1751. buf.append(envv);
  1752. }
  1753. }
  1754. envvar_len = buf.size() - hdr_len;
  1755. // sanitize length early on
  1756. if (buf.size() > cpbuffer_t::get_size()) {
  1757. auto eq = buf.find('=', hdr_len);
  1758. auto name = buf.substr(hdr_len, eq - hdr_len);
  1759. cerr << "dinitctl: environment variable '" << name << "' too long." << endl;
  1760. return 1;
  1761. }
  1762. // set size in protocol message
  1763. memcpy(&buf[1], &envvar_len, sizeof(envvar_len));
  1764. // send
  1765. write_all_x(socknum, buf.data(), buf.size());
  1766. wait_for_reply(rbuffer, socknum);
  1767. if (rbuffer[0] == (char)cp_rply::BADREQ) {
  1768. cerr << "dinitctl: failed to export environment." << endl;
  1769. return 1;
  1770. } else if (rbuffer[0] != (char)cp_rply::ACK) {
  1771. throw dinit_protocol_error();
  1772. }
  1773. rbuffer.consume(1);
  1774. }
  1775. return 0;
  1776. }
  1777. static int trigger_service(int socknum, cpbuffer_t &rbuffer, const char *service_name, bool trigger_value)
  1778. {
  1779. using namespace std;
  1780. handle_t handle;
  1781. if (!load_service(socknum, rbuffer, service_name, &handle, nullptr, true)) {
  1782. return 1;
  1783. }
  1784. // Issue SET_TRIGGER command.
  1785. {
  1786. auto m = membuf()
  1787. .append((char)cp_cmd::SETTRIGGER)
  1788. .append(handle)
  1789. .append<trigger_val_t>(trigger_value);
  1790. write_all_x(socknum, m);
  1791. wait_for_reply(rbuffer, socknum);
  1792. if (rbuffer[0] == (char)cp_rply::NAK) {
  1793. cerr << "dinitctl: cannot trigger a service that is not of 'triggered' type.\n";
  1794. return 1;
  1795. }
  1796. if (rbuffer[0] != (char)cp_rply::ACK) {
  1797. cerr << "dinitctl: protocol error.\n";
  1798. return 1;
  1799. }
  1800. rbuffer.consume(1);
  1801. }
  1802. return 0;
  1803. }
  1804. static int signal_send(int socknum, cpbuffer_t &rbuffer, const char *service_name, sig_num_t sig_num)
  1805. {
  1806. using namespace std;
  1807. handle_t handle;
  1808. if (!load_service(socknum, rbuffer, service_name, &handle, nullptr, true)) {
  1809. return 1;
  1810. }
  1811. // Issue SIGNAL command.
  1812. auto m = membuf()
  1813. .append((char)cp_cmd::SIGNAL)
  1814. .append(sig_num)
  1815. .append(handle);
  1816. write_all_x(socknum, m);
  1817. wait_for_reply(rbuffer, socknum);
  1818. cp_rply reply_pkt_h = (cp_rply)rbuffer[0];
  1819. if (reply_pkt_h == cp_rply::NAK) {
  1820. cerr << "dinitctl: cannot send signal to service.\n";
  1821. return 1;
  1822. }
  1823. if (reply_pkt_h == cp_rply::SIGNAL_NOPID) {
  1824. cerr << "dinitctl: could not get vaild PID of service; service is not process, "
  1825. "service in wrong state." << endl;
  1826. return 1;
  1827. }
  1828. if (reply_pkt_h == cp_rply::SIGNAL_BADSIG) {
  1829. cerr << "dinitctl: provided signal was invalid.\n";
  1830. return 1;
  1831. }
  1832. if (reply_pkt_h == cp_rply::SIGNAL_KILLERR) {
  1833. cerr << "dinitctl: failed sending signal to service.\n";
  1834. return 1;
  1835. }
  1836. if (reply_pkt_h != cp_rply::ACK) {
  1837. cerr << "dinitctl: protocol error.\n";
  1838. return 1;
  1839. }
  1840. rbuffer.consume(1);
  1841. return 0;
  1842. }
  1843. static int signal_list()
  1844. {
  1845. using namespace std;
  1846. using namespace dinit_load;
  1847. cout << "dinitctl: The following signal names are supported:";
  1848. int skip_none = 0;
  1849. for (const auto &signal: signal_to_int_map) {
  1850. if (skip_none < 2) {
  1851. skip_none += 1;
  1852. }
  1853. else {
  1854. cout << endl << "dinitctl: ";
  1855. string sigpad = signal.first;
  1856. sigpad.resize(5,' ');
  1857. cout << sigpad << "-> " << signal.second;
  1858. }
  1859. }
  1860. cout << endl;
  1861. return 0;
  1862. }
  1863. static int cat_service_log(int socknum, cpbuffer_t &rbuffer, const char *service_name, bool do_clear)
  1864. {
  1865. using namespace std;
  1866. handle_t handle;
  1867. if (!load_service(socknum, rbuffer, service_name, &handle, nullptr, true)) {
  1868. return 1;
  1869. }
  1870. char flags = do_clear ? 1 : 0;
  1871. // Issue CATLOG
  1872. auto m = membuf()
  1873. .append((char)cp_cmd::CATLOG)
  1874. .append<char>(flags)
  1875. .append(handle);
  1876. write_all_x(socknum, m);
  1877. wait_for_reply(rbuffer, socknum);
  1878. if (rbuffer[0] == (char)cp_rply::NAK) {
  1879. cerr << "dinitctl: cannot cat log for service not configured to buffer output.\n";
  1880. return 1;
  1881. }
  1882. if (rbuffer[0] != (char)cp_rply::SERVICE_LOG) {
  1883. cerr << "dinitctl: protocol error.\n";
  1884. return 1;
  1885. }
  1886. fill_buffer_to(rbuffer, socknum, 2 + sizeof(unsigned));
  1887. unsigned bufsize;
  1888. rbuffer.extract(&bufsize, 2, sizeof(unsigned));
  1889. rbuffer.consume(2 + sizeof(unsigned));
  1890. // output the log
  1891. if (bufsize > 0) {
  1892. cout << flush;
  1893. bool trailing_nl = false;
  1894. char output_buf[rbuffer.get_size()];
  1895. while (bufsize > 0) {
  1896. unsigned l = rbuffer.get_length();
  1897. if (l == 0) {
  1898. fill_buffer_to(rbuffer, socknum, 1);
  1899. }
  1900. l = std::min(rbuffer.get_length(), bufsize);
  1901. rbuffer.extract(output_buf, 0, l);
  1902. write(STDOUT_FILENO, output_buf, l);
  1903. rbuffer.consume(l);
  1904. bufsize -= l;
  1905. trailing_nl = (output_buf[l - 1] == '\n');
  1906. }
  1907. if (!trailing_nl) {
  1908. cout << "\n(last line is truncated or incomplete)\n";
  1909. }
  1910. }
  1911. return 0;
  1912. }