control.cc 42 KB

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