dinitctl.cc 72 KB

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