dinitctl.cc 56 KB

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