control.cc 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227
  1. #include <algorithm>
  2. #include <unordered_set>
  3. #include <climits>
  4. #include "control.h"
  5. #include "service.h"
  6. #include "proc-service.h"
  7. // Server-side control protocol implementation. This implements the functionality that allows
  8. // clients (such as dinitctl) to query service state and issue commands to control services.
  9. namespace {
  10. constexpr auto OUT_EVENTS = dasynq::OUT_EVENTS;
  11. constexpr auto IN_EVENTS = dasynq::IN_EVENTS;
  12. // Control protocol minimum compatible version and current version:
  13. constexpr uint16_t min_compat_version = 1;
  14. constexpr uint16_t cp_version = 1;
  15. // check for value in a set
  16. template <typename T, int N, typename U>
  17. inline bool contains(const T (&v)[N], U i)
  18. {
  19. return std::find_if(std::begin(v), std::end(v),
  20. [=](T p){ return i == static_cast<U>(p); }) != std::end(v);
  21. }
  22. }
  23. bool control_conn_t::process_packet()
  24. {
  25. using std::string;
  26. // Note that where we call queue_packet, we must generally check the return value. If it
  27. // returns false it has either deleted the connection or marked it for deletion; we
  28. // shouldn't touch instance members after that point.
  29. int pktType = rbuf[0];
  30. if (pktType == DINIT_CP_QUERYVERSION) {
  31. // Responds with:
  32. // DINIT_RP_CVERSION, (2 byte) minimum compatible version, (2 byte) actual version
  33. char replyBuf[] = { DINIT_RP_CPVERSION, 0, 0, 0, 0 };
  34. memcpy(replyBuf + 1, &min_compat_version, 2);
  35. memcpy(replyBuf + 3, &cp_version, 2);
  36. if (! queue_packet(replyBuf, sizeof(replyBuf))) return false;
  37. rbuf.consume(1);
  38. return true;
  39. }
  40. if (pktType == DINIT_CP_FINDSERVICE || pktType == DINIT_CP_LOADSERVICE) {
  41. return process_find_load(pktType);
  42. }
  43. if (pktType == DINIT_CP_STARTSERVICE || pktType == DINIT_CP_STOPSERVICE
  44. || pktType == DINIT_CP_WAKESERVICE || pktType == DINIT_CP_RELEASESERVICE) {
  45. return process_start_stop(pktType);
  46. }
  47. if (pktType == DINIT_CP_UNPINSERVICE) {
  48. return process_unpin_service();
  49. }
  50. if (pktType == DINIT_CP_UNLOADSERVICE) {
  51. return process_unload_service();
  52. }
  53. if (pktType == DINIT_CP_RELOADSERVICE) {
  54. return process_reload_service();
  55. }
  56. if (pktType == DINIT_CP_SHUTDOWN) {
  57. // Shutdown/reboot
  58. if (rbuf.get_length() < 2) {
  59. chklen = 2;
  60. return true;
  61. }
  62. if (contains({shutdown_type_t::REMAIN, shutdown_type_t::HALT,
  63. shutdown_type_t::POWEROFF, shutdown_type_t::REBOOT}, rbuf[1])) {
  64. auto sd_type = static_cast<shutdown_type_t>(rbuf[1]);
  65. services->stop_all_services(sd_type);
  66. char ackBuf[] = { DINIT_RP_ACK };
  67. if (! queue_packet(ackBuf, 1)) return false;
  68. // Clear the packet from the buffer
  69. rbuf.consume(2);
  70. chklen = 0;
  71. return true;
  72. }
  73. // (otherwise fall through to below).
  74. }
  75. if (pktType == DINIT_CP_LISTSERVICES) {
  76. return list_services();
  77. }
  78. if (pktType == DINIT_CP_SERVICESTATUS) {
  79. return process_service_status();
  80. }
  81. if (pktType == DINIT_CP_ADD_DEP) {
  82. return add_service_dep();
  83. }
  84. if (pktType == DINIT_CP_REM_DEP) {
  85. return rm_service_dep();
  86. }
  87. if (pktType == DINIT_CP_QUERY_LOAD_MECH) {
  88. return query_load_mech();
  89. }
  90. if (pktType == DINIT_CP_ENABLESERVICE) {
  91. return add_service_dep(true);
  92. }
  93. if (pktType == DINIT_CP_QUERYSERVICENAME) {
  94. return process_query_name();
  95. }
  96. if (pktType == DINIT_CP_SETENV) {
  97. return process_setenv();
  98. }
  99. // Unrecognized: give error response
  100. char outbuf[] = { DINIT_RP_BADREQ };
  101. if (! queue_packet(outbuf, 1)) return false;
  102. bad_conn_close = true;
  103. iob.set_watches(OUT_EVENTS);
  104. return true;
  105. }
  106. bool control_conn_t::process_find_load(int pktType)
  107. {
  108. using std::string;
  109. constexpr int pkt_size = 4;
  110. if (rbuf.get_length() < pkt_size) {
  111. chklen = pkt_size;
  112. return true;
  113. }
  114. uint16_t svcSize;
  115. rbuf.extract((char *)&svcSize, 1, 2);
  116. if (svcSize <= 0 || svcSize > (1024 - 3)) {
  117. // Queue error response / mark connection bad
  118. char badreqRep[] = { DINIT_RP_BADREQ };
  119. if (! queue_packet(badreqRep, 1)) return false;
  120. bad_conn_close = true;
  121. iob.set_watches(OUT_EVENTS);
  122. return true;
  123. }
  124. chklen = svcSize + 3; // packet type + (2 byte) length + service name
  125. if (rbuf.get_length() < chklen) {
  126. // packet not complete yet; read more
  127. return true;
  128. }
  129. service_record * record = nullptr;
  130. string serviceName = rbuf.extract_string(3, svcSize);
  131. if (pktType == DINIT_CP_LOADSERVICE) {
  132. // LOADSERVICE
  133. try {
  134. record = services->load_service(serviceName.c_str());
  135. }
  136. catch (service_description_exc &sdexc) {
  137. log_service_load_failure(sdexc);
  138. }
  139. catch (service_load_exc &slexc) {
  140. log(loglevel_t::ERROR, "Could not load service ", slexc.service_name, ": ",
  141. slexc.exc_description);
  142. }
  143. }
  144. else {
  145. // FINDSERVICE
  146. record = services->find_service(serviceName.c_str());
  147. }
  148. if (record != nullptr) {
  149. // Allocate a service handle
  150. handle_t handle = allocate_service_handle(record);
  151. std::vector<char> rp_buf;
  152. rp_buf.reserve(7);
  153. rp_buf.push_back(DINIT_RP_SERVICERECORD);
  154. rp_buf.push_back(static_cast<char>(record->get_state()));
  155. for (int i = 0; i < (int) sizeof(handle); i++) {
  156. rp_buf.push_back(*(((char *) &handle) + i));
  157. }
  158. rp_buf.push_back(static_cast<char>(record->get_target_state()));
  159. if (! queue_packet(std::move(rp_buf))) return false;
  160. }
  161. else {
  162. std::vector<char> rp_buf = { DINIT_RP_NOSERVICE };
  163. if (! queue_packet(std::move(rp_buf))) return false;
  164. }
  165. // Clear the packet from the buffer
  166. rbuf.consume(chklen);
  167. chklen = 0;
  168. return true;
  169. }
  170. bool control_conn_t::check_dependents(service_record *service, bool &had_dependents)
  171. {
  172. std::vector<char> reply_pkt;
  173. size_t num_depts = 0;
  174. for (service_dep *dep : service->get_dependents()) {
  175. if (dep->dep_type == dependency_type::REGULAR && dep->holding_acq) {
  176. num_depts++;
  177. // find or allocate a service handle
  178. handle_t dept_handle = allocate_service_handle(dep->get_from());
  179. if (reply_pkt.empty()) {
  180. // packet type, size
  181. reply_pkt.reserve(1 + sizeof(size_t) + sizeof(handle_t));
  182. reply_pkt.resize(1 + sizeof(size_t));
  183. reply_pkt[0] = DINIT_RP_DEPENDENTS;
  184. }
  185. auto old_size = reply_pkt.size();
  186. reply_pkt.resize(old_size + sizeof(handle_t));
  187. memcpy(reply_pkt.data() + old_size, &dept_handle, sizeof(dept_handle));
  188. }
  189. }
  190. if (num_depts != 0) {
  191. // There are affected dependents
  192. had_dependents = true;
  193. memcpy(reply_pkt.data() + 1, &num_depts, sizeof(num_depts));
  194. return queue_packet(std::move(reply_pkt));
  195. }
  196. had_dependents = false;
  197. return true;
  198. }
  199. bool control_conn_t::process_start_stop(int pktType)
  200. {
  201. using std::string;
  202. constexpr int pkt_size = 2 + sizeof(handle_t);
  203. if (rbuf.get_length() < pkt_size) {
  204. chklen = pkt_size;
  205. return true;
  206. }
  207. // 1 byte: packet type
  208. // 1 byte: flags eg. pin in requested state (0 = no pin, 1 = pin)
  209. // 4 bytes: service handle
  210. bool do_pin = ((rbuf[1] & 1) == 1);
  211. handle_t handle;
  212. rbuf.extract((char *) &handle, 2, sizeof(handle));
  213. service_record *service = find_service_for_key(handle);
  214. if (service == nullptr) {
  215. // Service handle is bad
  216. char badreqRep[] = { DINIT_RP_BADREQ };
  217. if (! queue_packet(badreqRep, 1)) return false;
  218. bad_conn_close = true;
  219. iob.set_watches(OUT_EVENTS);
  220. return true;
  221. }
  222. else {
  223. char ack_buf[1] = { DINIT_RP_ACK };
  224. switch (pktType) {
  225. case DINIT_CP_STARTSERVICE:
  226. // start service, mark as required
  227. if (services->is_shutting_down()) {
  228. ack_buf[0] = DINIT_RP_SHUTTINGDOWN;
  229. break;
  230. }
  231. if ((service->get_state() == service_state_t::STOPPED
  232. || service->get_state() == service_state_t::STOPPING)
  233. && service->is_stop_pinned()) {
  234. ack_buf[0] = DINIT_RP_PINNEDSTOPPED;
  235. break;
  236. }
  237. if (do_pin) service->pin_start();
  238. service->start();
  239. services->process_queues();
  240. if (service->get_state() == service_state_t::STARTED) ack_buf[0] = DINIT_RP_ALREADYSS;
  241. break;
  242. case DINIT_CP_STOPSERVICE:
  243. {
  244. // force service to stop
  245. bool do_restart = ((rbuf[1] & 4) == 4);
  246. bool gentle = ((rbuf[1] & 2) == 2) || do_restart; // restart is always "gentle"
  247. if (do_restart && services->is_shutting_down()) {
  248. ack_buf[0] = DINIT_RP_SHUTTINGDOWN;
  249. break;
  250. }
  251. if ((service->get_state() == service_state_t::STARTED
  252. || service->get_state() == service_state_t::STARTING)
  253. && service->is_start_pinned()) {
  254. ack_buf[0] = DINIT_RP_PINNEDSTARTED;
  255. break;
  256. }
  257. if (gentle) {
  258. // Check dependents; return appropriate response if any will be affected
  259. bool has_dependents;
  260. if (! check_dependents(service, has_dependents)) {
  261. return false;
  262. }
  263. if (has_dependents) {
  264. // Reply packet has already been sent
  265. goto clear_out;
  266. }
  267. }
  268. service_state_t wanted_state;
  269. if (do_restart) {
  270. if (! service->restart()) {
  271. ack_buf[0] = DINIT_RP_NAK;
  272. break;
  273. }
  274. wanted_state = service_state_t::STARTED;
  275. }
  276. else {
  277. if (do_pin) service->pin_stop();
  278. service->stop(true);
  279. service->forced_stop();
  280. wanted_state = service_state_t::STOPPED;
  281. }
  282. services->process_queues();
  283. if (service->get_state() == wanted_state && !do_restart) ack_buf[0] = DINIT_RP_ALREADYSS;
  284. break;
  285. }
  286. case DINIT_CP_WAKESERVICE:
  287. {
  288. // re-attach a service to its (started) dependents, causing it to start.
  289. if (services->is_shutting_down()) {
  290. ack_buf[0] = DINIT_RP_SHUTTINGDOWN;
  291. break;
  292. }
  293. if ((service->get_state() == service_state_t::STOPPED
  294. || service->get_state() == service_state_t::STOPPING)
  295. && service->is_stop_pinned()) {
  296. ack_buf[0] = DINIT_RP_PINNEDSTOPPED;
  297. break;
  298. }
  299. bool found_dpt = false;
  300. for (auto dpt : service->get_dependents()) {
  301. auto from = dpt->get_from();
  302. auto from_state = from->get_state();
  303. if (from_state == service_state_t::STARTED || from_state == service_state_t::STARTING) {
  304. found_dpt = true;
  305. if (! dpt->holding_acq) {
  306. dpt->get_from()->start_dep(*dpt);
  307. }
  308. }
  309. }
  310. if (! found_dpt) {
  311. ack_buf[0] = DINIT_RP_NAK;
  312. }
  313. if (do_pin) service->pin_start();
  314. services->process_queues();
  315. if (service->get_state() == service_state_t::STARTED) ack_buf[0] = DINIT_RP_ALREADYSS;
  316. break;
  317. }
  318. case DINIT_CP_RELEASESERVICE:
  319. // remove required mark, stop if not required by dependents
  320. if (do_pin) service->pin_stop();
  321. service->stop(false);
  322. services->process_queues();
  323. if (service->get_state() == service_state_t::STOPPED) ack_buf[0] = DINIT_RP_ALREADYSS;
  324. break;
  325. }
  326. if (! queue_packet(ack_buf, 1)) return false;
  327. }
  328. clear_out:
  329. // Clear the packet from the buffer
  330. rbuf.consume(pkt_size);
  331. chklen = 0;
  332. return true;
  333. }
  334. bool control_conn_t::process_unpin_service()
  335. {
  336. using std::string;
  337. constexpr int pkt_size = 1 + sizeof(handle_t);
  338. if (rbuf.get_length() < pkt_size) {
  339. chklen = pkt_size;
  340. return true;
  341. }
  342. // 1 byte: packet type
  343. // 4 bytes: service handle
  344. handle_t handle;
  345. rbuf.extract((char *) &handle, 1, sizeof(handle));
  346. service_record *service = find_service_for_key(handle);
  347. if (service == nullptr) {
  348. // Service handle is bad
  349. char badreqRep[] = { DINIT_RP_BADREQ };
  350. if (! queue_packet(badreqRep, 1)) return false;
  351. bad_conn_close = true;
  352. iob.set_watches(OUT_EVENTS);
  353. return true;
  354. }
  355. service->unpin();
  356. services->process_queues();
  357. char ack_buf[] = { (char) DINIT_RP_ACK };
  358. if (! queue_packet(ack_buf, 1)) return false;
  359. // Clear the packet from the buffer
  360. rbuf.consume(pkt_size);
  361. chklen = 0;
  362. return true;
  363. }
  364. bool control_conn_t::process_unload_service()
  365. {
  366. using std::string;
  367. constexpr int pkt_size = 1 + sizeof(handle_t);
  368. if (rbuf.get_length() < pkt_size) {
  369. chklen = pkt_size;
  370. return true;
  371. }
  372. // 1 byte: packet type
  373. // 4 bytes: service handle
  374. handle_t handle;
  375. rbuf.extract((char *) &handle, 1, sizeof(handle));
  376. service_record *service = find_service_for_key(handle);
  377. if (service == nullptr) {
  378. // Service handle is bad
  379. char badreq_rep[] = { DINIT_RP_BADREQ };
  380. if (! queue_packet(badreq_rep, 1)) return false;
  381. bad_conn_close = true;
  382. iob.set_watches(OUT_EVENTS);
  383. return true;
  384. }
  385. if (! service->has_lone_ref() || service->get_state() != service_state_t::STOPPED) {
  386. // Cannot unload: has other references
  387. char nak_rep[] = { DINIT_RP_NAK };
  388. if (! queue_packet(nak_rep, 1)) return false;
  389. }
  390. else {
  391. // unload
  392. service->prepare_for_unload();
  393. services->remove_service(service);
  394. delete service;
  395. // drop handle
  396. service_key_map.erase(service);
  397. key_service_map.erase(handle);
  398. // send ack
  399. char ack_buf[] = { (char) DINIT_RP_ACK };
  400. if (! queue_packet(ack_buf, 1)) return false;
  401. }
  402. // Clear the packet from the buffer
  403. rbuf.consume(pkt_size);
  404. chklen = 0;
  405. return true;
  406. }
  407. bool control_conn_t::process_reload_service()
  408. {
  409. using std::string;
  410. constexpr int pkt_size = 1 + sizeof(handle_t);
  411. if (rbuf.get_length() < pkt_size) {
  412. chklen = pkt_size;
  413. return true;
  414. }
  415. // 1 byte: packet type
  416. // 4 bytes: service handle
  417. handle_t handle;
  418. rbuf.extract((char *) &handle, 1, sizeof(handle));
  419. service_record *service = find_service_for_key(handle);
  420. if (service == nullptr) {
  421. // Service handle is bad
  422. char badreq_rep[] = { DINIT_RP_BADREQ };
  423. if (! queue_packet(badreq_rep, 1)) return false;
  424. bad_conn_close = true;
  425. iob.set_watches(OUT_EVENTS);
  426. return true;
  427. }
  428. if (! service->has_lone_ref(false)) {
  429. // Cannot unload: has other references
  430. char nak_rep[] = { DINIT_RP_NAK };
  431. if (! queue_packet(nak_rep, 1)) return false;
  432. }
  433. else {
  434. try {
  435. // reload
  436. auto *new_service = services->reload_service(service);
  437. if (new_service != service) {
  438. service->prepare_for_unload();
  439. services->replace_service(service, new_service);
  440. delete service;
  441. }
  442. else {
  443. service->remove_listener(this);
  444. }
  445. // drop handle
  446. key_service_map.erase(handle);
  447. service_key_map.erase(service);
  448. services->process_queues();
  449. // send ack
  450. char ack_buf[] = { (char) DINIT_RP_ACK };
  451. if (! queue_packet(ack_buf, 1)) return false;
  452. }
  453. catch (service_load_exc &slexc) {
  454. log(loglevel_t::ERROR, "Could not reload service ", slexc.service_name, ": ",
  455. slexc.exc_description);
  456. char nak_rep[] = { DINIT_RP_NAK };
  457. if (! queue_packet(nak_rep, 1)) return false;
  458. }
  459. }
  460. // Clear the packet from the buffer
  461. rbuf.consume(pkt_size);
  462. chklen = 0;
  463. return true;
  464. }
  465. constexpr static int STATUS_BUFFER_SIZE = 6 + ((sizeof(pid_t) > sizeof(int)) ? sizeof(pid_t) : sizeof(int));
  466. static void fill_status_buffer(char *buffer, service_record *service)
  467. {
  468. buffer[0] = static_cast<char>(service->get_state());
  469. buffer[1] = static_cast<char>(service->get_target_state());
  470. char b0 = service->is_waiting_for_console() ? 1 : 0;
  471. b0 |= service->has_console() ? 2 : 0;
  472. b0 |= service->was_start_skipped() ? 4 : 0;
  473. b0 |= service->is_marked_active() ? 8 : 0;
  474. buffer[2] = b0;
  475. buffer[3] = static_cast<char>(service->get_stop_reason());
  476. buffer[4] = 0; // (if exec failed, these are replaced with stage)
  477. buffer[5] = 0;
  478. // Next: either the exit status, or the process ID
  479. if (service->get_state() != service_state_t::STOPPED) {
  480. pid_t proc_pid = service->get_pid();
  481. memcpy(buffer + 6, &proc_pid, sizeof(proc_pid));
  482. }
  483. else {
  484. // If exec failed,
  485. if (buffer[3] == (char)stopped_reason_t::EXECFAILED) {
  486. base_process_service *bsp = (base_process_service *)service;
  487. run_proc_err exec_err = bsp->get_exec_err_info();
  488. uint16_t stage = (uint16_t)exec_err.stage;
  489. memcpy(buffer + 4, &stage, 2);
  490. memcpy(buffer + 6, &exec_err.st_errno, sizeof(int));
  491. }
  492. else {
  493. int exit_status = service->get_exit_status();
  494. memcpy(buffer + 6, &exit_status, sizeof(exit_status));
  495. }
  496. }
  497. }
  498. bool control_conn_t::list_services()
  499. {
  500. rbuf.consume(1); // clear request packet
  501. chklen = 0;
  502. try {
  503. auto slist = services->list_services();
  504. for (auto sptr : slist) {
  505. std::vector<char> pkt_buf;
  506. int hdrsize = 2 + STATUS_BUFFER_SIZE;
  507. const std::string &name = sptr->get_name();
  508. int nameLen = std::min((size_t)256, name.length());
  509. pkt_buf.resize(hdrsize + nameLen);
  510. pkt_buf[0] = DINIT_RP_SVCINFO;
  511. pkt_buf[1] = nameLen;
  512. fill_status_buffer(&pkt_buf[2], sptr);
  513. for (int i = 0; i < nameLen; i++) {
  514. pkt_buf[hdrsize+i] = name[i];
  515. }
  516. if (!queue_packet(std::move(pkt_buf))) return false;
  517. }
  518. char ack_buf[] = { (char) DINIT_RP_LISTDONE };
  519. if (! queue_packet(ack_buf, 1)) return false;
  520. return true;
  521. }
  522. catch (std::bad_alloc &exc)
  523. {
  524. do_oom_close();
  525. return true;
  526. }
  527. }
  528. bool control_conn_t::process_service_status()
  529. {
  530. constexpr int pkt_size = 1 + sizeof(handle_t);
  531. if (rbuf.get_length() < pkt_size) {
  532. chklen = pkt_size;
  533. return true;
  534. }
  535. handle_t handle;
  536. rbuf.extract(&handle, 1, sizeof(handle));
  537. rbuf.consume(pkt_size);
  538. chklen = 0;
  539. service_record *service = find_service_for_key(handle);
  540. if (service == nullptr || service->get_name().length() > std::numeric_limits<uint16_t>::max()) {
  541. char nak_rep[] = { DINIT_RP_NAK };
  542. return queue_packet(nak_rep, 1);
  543. }
  544. // Reply:
  545. // 1 byte packet type = DINIT_RP_SERVICESTATUS
  546. // 1 byte reserved ( = 0)
  547. // STATUS_BUFFER_SIZE bytes status
  548. std::vector<char> pkt_buf(2 + STATUS_BUFFER_SIZE);
  549. pkt_buf[0] = DINIT_RP_SERVICESTATUS;
  550. pkt_buf[1] = 0;
  551. fill_status_buffer(pkt_buf.data() + 2, service);
  552. return queue_packet(std::move(pkt_buf));
  553. }
  554. bool control_conn_t::add_service_dep(bool do_enable)
  555. {
  556. // 1 byte packet type
  557. // 1 byte dependency type
  558. // handle: "from"
  559. // handle: "to"
  560. constexpr int pkt_size = 2 + sizeof(handle_t) * 2;
  561. if (rbuf.get_length() < pkt_size) {
  562. chklen = pkt_size;
  563. return true;
  564. }
  565. handle_t from_handle;
  566. handle_t to_handle;
  567. rbuf.extract((char *) &from_handle, 2, sizeof(from_handle));
  568. rbuf.extract((char *) &to_handle, 2 + sizeof(from_handle), sizeof(to_handle));
  569. service_record *from_service = find_service_for_key(from_handle);
  570. service_record *to_service = find_service_for_key(to_handle);
  571. if (from_service == nullptr || to_service == nullptr || from_service == to_service) {
  572. // Service handle is bad
  573. char badreq_rep[] = { DINIT_RP_BADREQ };
  574. if (! queue_packet(badreq_rep, 1)) return false;
  575. bad_conn_close = true;
  576. iob.set_watches(OUT_EVENTS);
  577. return true;
  578. }
  579. // Check dependency type is valid:
  580. int dep_type_int = rbuf[1];
  581. if (! contains({dependency_type::MILESTONE, dependency_type::REGULAR,
  582. dependency_type::WAITS_FOR}, dep_type_int)) {
  583. char badreqRep[] = { DINIT_RP_BADREQ };
  584. if (! queue_packet(badreqRep, 1)) return false;
  585. bad_conn_close = true;
  586. iob.set_watches(OUT_EVENTS);
  587. }
  588. dependency_type dep_type = static_cast<dependency_type>(dep_type_int);
  589. // Check current service states are valid for given dep type
  590. if (dep_type == dependency_type::REGULAR) {
  591. if (from_service->get_state() != service_state_t::STOPPED &&
  592. to_service->get_state() != service_state_t::STARTED) {
  593. // Cannot create dependency now since it would be contradicted:
  594. char nak_rep[] = { DINIT_RP_NAK };
  595. if (! queue_packet(nak_rep, 1)) return false;
  596. rbuf.consume(pkt_size);
  597. chklen = 0;
  598. return true;
  599. }
  600. }
  601. // Check for creation of circular dependency chain
  602. std::unordered_set<service_record *> dep_marks;
  603. std::vector<service_record *> dep_queue;
  604. dep_queue.push_back(to_service);
  605. while (! dep_queue.empty()) {
  606. service_record * sr = dep_queue.back();
  607. dep_queue.pop_back();
  608. // iterate deps; if dep == from, abort; otherwise add to set/queue
  609. // (only add to queue if not already in set)
  610. for (auto &dep : sr->get_dependencies()) {
  611. service_record * dep_to = dep.get_to();
  612. if (dep_to == from_service) {
  613. // fail, circular dependency!
  614. char nak_rep[] = { DINIT_RP_NAK };
  615. if (! queue_packet(nak_rep, 1)) return false;
  616. rbuf.consume(pkt_size);
  617. chklen = 0;
  618. return true;
  619. }
  620. if (dep_marks.insert(dep_to).second) {
  621. dep_queue.push_back(dep_to);
  622. }
  623. }
  624. }
  625. dep_marks.clear();
  626. dep_queue.clear();
  627. bool dep_exists = false;
  628. service_dep * dep_record = nullptr;
  629. // Prevent creation of duplicate dependency:
  630. for (auto &dep : from_service->get_dependencies()) {
  631. service_record * dep_to = dep.get_to();
  632. if (dep_to == to_service && dep.dep_type == dep_type) {
  633. // Dependency already exists
  634. dep_exists = true;
  635. dep_record = &dep;
  636. break;
  637. }
  638. }
  639. if (! dep_exists) {
  640. // Create dependency:
  641. dep_record = &(from_service->add_dep(to_service, dep_type));
  642. services->process_queues();
  643. }
  644. if (do_enable && contains({service_state_t::STARTED, service_state_t::STARTING},
  645. from_service->get_state())) {
  646. // The dependency record is activated: mark it as holding acquisition of the dependency, and start
  647. // the dependency.
  648. if (!services->is_shutting_down()) {
  649. dep_record->get_from()->start_dep(*dep_record);
  650. services->process_queues();
  651. }
  652. }
  653. char ack_rep[] = { DINIT_RP_ACK };
  654. if (! queue_packet(ack_rep, 1)) return false;
  655. rbuf.consume(pkt_size);
  656. chklen = 0;
  657. return true;
  658. }
  659. bool control_conn_t::rm_service_dep()
  660. {
  661. // 1 byte packet type
  662. // 1 byte dependency type
  663. // handle: "from"
  664. // handle: "to"
  665. constexpr int pkt_size = 2 + sizeof(handle_t) * 2;
  666. if (rbuf.get_length() < pkt_size) {
  667. chklen = pkt_size;
  668. return true;
  669. }
  670. handle_t from_handle;
  671. handle_t to_handle;
  672. rbuf.extract((char *) &from_handle, 2, sizeof(from_handle));
  673. rbuf.extract((char *) &to_handle, 2 + sizeof(from_handle), sizeof(to_handle));
  674. service_record *from_service = find_service_for_key(from_handle);
  675. service_record *to_service = find_service_for_key(to_handle);
  676. if (from_service == nullptr || to_service == nullptr || from_service == to_service) {
  677. // Service handle is bad
  678. char badreq_rep[] = { DINIT_RP_BADREQ };
  679. if (! queue_packet(badreq_rep, 1)) return false;
  680. bad_conn_close = true;
  681. iob.set_watches(OUT_EVENTS);
  682. return true;
  683. }
  684. // Check dependency type is valid:
  685. int dep_type_int = rbuf[1];
  686. if (! contains({dependency_type::MILESTONE, dependency_type::REGULAR,
  687. dependency_type::WAITS_FOR}, dep_type_int)) {
  688. char badreqRep[] = { DINIT_RP_BADREQ };
  689. if (! queue_packet(badreqRep, 1)) return false;
  690. bad_conn_close = true;
  691. iob.set_watches(OUT_EVENTS);
  692. }
  693. dependency_type dep_type = static_cast<dependency_type>(dep_type_int);
  694. // Remove dependency:
  695. bool did_remove = from_service->rm_dep(to_service, dep_type);
  696. services->process_queues();
  697. char ack_rep[] = { did_remove ? (char)DINIT_RP_ACK : (char)DINIT_RP_NAK };
  698. if (! queue_packet(ack_rep, 1)) return false;
  699. rbuf.consume(pkt_size);
  700. chklen = 0;
  701. return true;
  702. }
  703. bool control_conn_t::process_query_name()
  704. {
  705. // 1 byte packet type
  706. // 1 byte reserved
  707. // handle: service
  708. constexpr int pkt_size = 2 + sizeof(handle_t);
  709. if (rbuf.get_length() < pkt_size) {
  710. chklen = pkt_size;
  711. return true;
  712. }
  713. handle_t handle;
  714. rbuf.extract(&handle, 2, sizeof(handle));
  715. rbuf.consume(pkt_size);
  716. chklen = 0;
  717. service_record *service = find_service_for_key(handle);
  718. if (service == nullptr || service->get_name().length() > std::numeric_limits<uint16_t>::max()) {
  719. char nak_rep[] = { DINIT_RP_NAK };
  720. return queue_packet(nak_rep, 1);
  721. }
  722. // Reply:
  723. // 1 byte packet type = DINIT_RP_SERVICENAME
  724. // 1 byte reserved
  725. // uint16_t length
  726. // N bytes name
  727. std::vector<char> reply;
  728. const std::string &name = service->get_name();
  729. uint16_t name_length = name.length();
  730. reply.resize(2 + sizeof(uint16_t) + name_length);
  731. reply[0] = DINIT_RP_SERVICENAME;
  732. memcpy(reply.data() + 2, &name_length, sizeof(name_length));
  733. memcpy(reply.data() + 2 + sizeof(uint16_t), name.c_str(), name_length);
  734. return queue_packet(std::move(reply));
  735. }
  736. bool control_conn_t::process_setenv()
  737. {
  738. using std::string;
  739. string envVar;
  740. typename string::size_type eq;
  741. constexpr int pkt_size = 4;
  742. char badreqRep[] = { DINIT_RP_BADREQ };
  743. char okRep[] = { DINIT_RP_ACK };
  744. if (rbuf.get_length() < pkt_size) {
  745. chklen = pkt_size;
  746. return true;
  747. }
  748. uint16_t envSize;
  749. rbuf.extract((char *)&envSize, 1, 2);
  750. if (envSize <= 0 || envSize > (1024 - 3)) {
  751. goto badreq;
  752. }
  753. chklen = envSize + 3; // packet type + (2 byte) length + envvar
  754. if (rbuf.get_length() < chklen) {
  755. // packet not complete yet; read more
  756. return true;
  757. }
  758. envVar = rbuf.extract_string(3, envSize);
  759. eq = envVar.find('=');
  760. if (!eq || eq == envVar.npos) {
  761. // not found or at the beginning of the string
  762. goto badreq;
  763. }
  764. envVar[eq] = '\0';
  765. if (setenv(envVar.c_str(), &envVar[eq + 1], 1) != 0) {
  766. // failed to set the var
  767. goto badreq;
  768. }
  769. // success response
  770. if (! queue_packet(okRep, 1)) return false;
  771. // Clear the packet from the buffer
  772. rbuf.consume(chklen);
  773. chklen = 0;
  774. return true;
  775. badreq:
  776. // Queue error response / mark connection bad
  777. if (! queue_packet(badreqRep, 1)) return false;
  778. bad_conn_close = true;
  779. iob.set_watches(OUT_EVENTS);
  780. return true;
  781. }
  782. bool control_conn_t::query_load_mech()
  783. {
  784. rbuf.consume(1);
  785. chklen = 0;
  786. if (services->get_set_type_id() == SSET_TYPE_DIRLOAD) {
  787. dirload_service_set *dss = static_cast<dirload_service_set *>(services);
  788. std::vector<char> reppkt;
  789. reppkt.resize(2 + sizeof(uint32_t) * 2); // packet type, loader type, packet size, # dirs
  790. reppkt[0] = DINIT_RP_LOADER_MECH;
  791. reppkt[1] = SSET_TYPE_DIRLOAD;
  792. // Number of directories in load path:
  793. uint32_t sdirs = dss->get_service_dir_count();
  794. std::memcpy(reppkt.data() + 2 + sizeof(uint32_t), &sdirs, sizeof(sdirs));
  795. // Our current working directory, which above are relative to:
  796. // leave sizeof(uint32_t) for size, which we'll fill in afterwards:
  797. std::size_t curpos = reppkt.size() + sizeof(uint32_t);
  798. #ifdef PATH_MAX
  799. uint32_t try_path_size = PATH_MAX;
  800. #else
  801. uint32_t try_path_size = 2048;
  802. #endif
  803. char *wd;
  804. while (true) {
  805. std::size_t total_size = curpos + std::size_t(try_path_size);
  806. if (total_size < curpos) {
  807. // Overflow. In theory we could now limit to size_t max, but the size must already
  808. // be crazy long; let's abort.
  809. char ack_rep[] = { DINIT_RP_NAK };
  810. if (! queue_packet(ack_rep, 1)) return false;
  811. return true;
  812. }
  813. reppkt.resize(total_size);
  814. wd = getcwd(reppkt.data() + curpos, try_path_size);
  815. if (wd != nullptr) break;
  816. // Keep doubling the path size we try until it's big enough, or we get numeric overflow
  817. uint32_t new_try_path_size = try_path_size * uint32_t(2u);
  818. if (new_try_path_size < try_path_size) {
  819. // Overflow.
  820. char ack_rep[] = { DINIT_RP_NAK };
  821. return queue_packet(ack_rep, 1);
  822. }
  823. try_path_size = new_try_path_size;
  824. }
  825. uint32_t wd_len = std::strlen(reppkt.data() + curpos);
  826. reppkt.resize(curpos + std::size_t(wd_len));
  827. std::memcpy(reppkt.data() + curpos - sizeof(uint32_t), &wd_len, sizeof(wd_len));
  828. // Each directory in the load path:
  829. for (int i = 0; uint32_t(i) < sdirs; i++) {
  830. const char *sdir = dss->get_service_dir(i);
  831. uint32_t dlen = std::strlen(sdir);
  832. auto cursize = reppkt.size();
  833. reppkt.resize(cursize + sizeof(dlen) + dlen);
  834. std::memcpy(reppkt.data() + cursize, &dlen, sizeof(dlen));
  835. std::memcpy(reppkt.data() + cursize + sizeof(dlen), sdir, dlen);
  836. }
  837. // Total packet size:
  838. uint32_t fsize = reppkt.size();
  839. std::memcpy(reppkt.data() + 2, &fsize, sizeof(fsize));
  840. if (! queue_packet(std::move(reppkt))) return false;
  841. return true;
  842. }
  843. else {
  844. // If we don't know how to deal with the service set type, send a NAK reply:
  845. char ack_rep[] = { DINIT_RP_NAK };
  846. return queue_packet(ack_rep, 1);
  847. }
  848. }
  849. control_conn_t::handle_t control_conn_t::allocate_service_handle(service_record *record)
  850. {
  851. // Try to find a unique handle (integer) in a single pass. Since the map is ordered, we can search until
  852. // we find a gap in the handle values.
  853. handle_t candidate = 0;
  854. for (auto p : key_service_map) {
  855. if (p.first == candidate) ++candidate;
  856. else break;
  857. }
  858. bool is_unique = (service_key_map.find(record) == service_key_map.end());
  859. // The following operations perform allocation (can throw std::bad_alloc). If an exception occurs we
  860. // must undo any previous actions:
  861. if (is_unique) {
  862. record->add_listener(this);
  863. }
  864. try {
  865. key_service_map[candidate] = record;
  866. service_key_map.insert(std::make_pair(record, candidate));
  867. }
  868. catch (...) {
  869. if (is_unique) {
  870. record->remove_listener(this);
  871. }
  872. key_service_map.erase(candidate);
  873. }
  874. return candidate;
  875. }
  876. bool control_conn_t::queue_packet(const char *pkt, unsigned size) noexcept
  877. {
  878. int in_flag = bad_conn_close ? 0 : IN_EVENTS;
  879. bool was_empty = outbuf.empty();
  880. // If the queue is empty, we can try to write the packet out now rather than queueing it.
  881. // If the write is unsuccessful or partial, we queue the remainder.
  882. if (was_empty) {
  883. int wr = bp_sys::write(iob.get_watched_fd(), pkt, size);
  884. if (wr == -1) {
  885. if (errno == EPIPE) {
  886. return false;
  887. }
  888. if (errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR) {
  889. log(loglevel_t::WARN, "Error writing to control connection: ", strerror(errno));
  890. return false;
  891. }
  892. // EAGAIN etc: fall through to below
  893. }
  894. else {
  895. if ((unsigned)wr == size) {
  896. // Ok, all written.
  897. iob.set_watches(in_flag);
  898. return true;
  899. }
  900. pkt += wr;
  901. size -= wr;
  902. }
  903. }
  904. // Create a vector out of the (remaining part of the) packet:
  905. try {
  906. outbuf.emplace_back(pkt, pkt + size);
  907. iob.set_watches(in_flag | OUT_EVENTS);
  908. return true;
  909. }
  910. catch (std::bad_alloc &baexc) {
  911. // Mark the connection bad, and stop reading further requests
  912. bad_conn_close = true;
  913. oom_close = true;
  914. if (was_empty) {
  915. // We can't send out-of-memory response as we already wrote as much as we
  916. // could above. Neither can we later send the response since we have currently
  917. // sent an incomplete packet. All we can do is close the connection.
  918. return false;
  919. }
  920. else {
  921. iob.set_watches(OUT_EVENTS);
  922. return true;
  923. }
  924. }
  925. }
  926. // This queue_packet method is frustratingly similar to the one above, but the subtle differences
  927. // make them extraordinary difficult to combine into a single method.
  928. bool control_conn_t::queue_packet(std::vector<char> &&pkt) noexcept
  929. {
  930. int in_flag = bad_conn_close ? 0 : IN_EVENTS;
  931. bool was_empty = outbuf.empty();
  932. if (was_empty) {
  933. outpkt_index = 0;
  934. // We can try sending the packet immediately:
  935. int wr = bp_sys::write(iob.get_watched_fd(), pkt.data(), pkt.size());
  936. if (wr == -1) {
  937. if (errno == EPIPE) {
  938. return false;
  939. }
  940. if (errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR) {
  941. log(loglevel_t::WARN, "Error writing to control connection: ", strerror(errno));
  942. return false;
  943. }
  944. // EAGAIN etc: fall through to below
  945. }
  946. else {
  947. if ((unsigned)wr == pkt.size()) {
  948. // Ok, all written.
  949. iob.set_watches(in_flag);
  950. return true;
  951. }
  952. outpkt_index = wr;
  953. }
  954. }
  955. try {
  956. outbuf.emplace_back(pkt);
  957. iob.set_watches(in_flag | OUT_EVENTS);
  958. return true;
  959. }
  960. catch (std::bad_alloc &baexc) {
  961. // Mark the connection bad, and stop reading further requests
  962. bad_conn_close = true;
  963. oom_close = true;
  964. if (was_empty) {
  965. // We can't send out-of-memory response as we already wrote as much as we
  966. // could above. Neither can we later send the response since we have currently
  967. // sent an incomplete packet. All we can do is close the connection.
  968. return false;
  969. }
  970. else {
  971. iob.set_watches(OUT_EVENTS);
  972. return true;
  973. }
  974. }
  975. }
  976. bool control_conn_t::data_ready() noexcept
  977. {
  978. int fd = iob.get_watched_fd();
  979. int r = rbuf.fill(fd);
  980. // Note file descriptor is non-blocking
  981. if (r == -1) {
  982. if (errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR) {
  983. log(loglevel_t::WARN, "Error writing to control connection: ", strerror(errno));
  984. return true;
  985. }
  986. return false;
  987. }
  988. if (r == 0) {
  989. return true;
  990. }
  991. // complete packet?
  992. if (rbuf.get_length() >= chklen) {
  993. try {
  994. return !process_packet();
  995. }
  996. catch (std::bad_alloc &baexc) {
  997. do_oom_close();
  998. return false;
  999. }
  1000. }
  1001. else if (rbuf.get_length() == rbuf.get_size()) {
  1002. // Too big packet
  1003. log(loglevel_t::WARN, "Received too-large control packet; dropping connection");
  1004. bad_conn_close = true;
  1005. iob.set_watches(OUT_EVENTS);
  1006. }
  1007. else {
  1008. int out_flags = (bad_conn_close || !outbuf.empty()) ? OUT_EVENTS : 0;
  1009. iob.set_watches(IN_EVENTS | out_flags);
  1010. }
  1011. return false;
  1012. }
  1013. bool control_conn_t::send_data() noexcept
  1014. {
  1015. if (outbuf.empty() && bad_conn_close) {
  1016. if (oom_close) {
  1017. // Send oom response
  1018. char oomBuf[] = { DINIT_RP_OOM };
  1019. bp_sys::write(iob.get_watched_fd(), oomBuf, 1);
  1020. }
  1021. return true;
  1022. }
  1023. vector<char> & pkt = outbuf.front();
  1024. char *data = pkt.data();
  1025. int written = bp_sys::write(iob.get_watched_fd(), data + outpkt_index, pkt.size() - outpkt_index);
  1026. if (written == -1) {
  1027. if (errno == EPIPE) {
  1028. // read end closed
  1029. return true;
  1030. }
  1031. else if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) {
  1032. // spurious readiness notification?
  1033. }
  1034. else {
  1035. log(loglevel_t::ERROR, "Error writing to control connection: ", strerror(errno));
  1036. return true;
  1037. }
  1038. return false;
  1039. }
  1040. outpkt_index += written;
  1041. if (outpkt_index == pkt.size()) {
  1042. // We've finished this packet, move on to the next:
  1043. outbuf.pop_front();
  1044. outpkt_index = 0;
  1045. if (outbuf.empty() && ! oom_close) {
  1046. if (! bad_conn_close) {
  1047. iob.set_watches(IN_EVENTS);
  1048. }
  1049. else {
  1050. return true;
  1051. }
  1052. }
  1053. }
  1054. return false;
  1055. }
  1056. control_conn_t::~control_conn_t() noexcept
  1057. {
  1058. bp_sys::close(iob.get_watched_fd());
  1059. iob.deregister(loop);
  1060. // Clear service listeners
  1061. for (auto p : service_key_map) {
  1062. p.first->remove_listener(this);
  1063. }
  1064. active_control_conns--;
  1065. }