dinitctl.cc 60 KB

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