control.cc 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347
  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 (this may fail with bad_alloc)
  410. services->unload_service(service);
  411. // drop handle
  412. service_key_map.erase(service);
  413. key_service_map.erase(handle);
  414. // send ack
  415. char ack_buf[] = { (char) DINIT_RP_ACK };
  416. if (!queue_packet(ack_buf, 1)) return false;
  417. }
  418. // Clear the packet from the buffer
  419. rbuf.consume(pkt_size);
  420. chklen = 0;
  421. return true;
  422. }
  423. bool control_conn_t::process_reload_service()
  424. {
  425. using std::string;
  426. constexpr int pkt_size = 1 + sizeof(handle_t);
  427. if (rbuf.get_length() < pkt_size) {
  428. chklen = pkt_size;
  429. return true;
  430. }
  431. // 1 byte: packet type
  432. // 4 bytes: service handle
  433. handle_t handle;
  434. rbuf.extract((char *) &handle, 1, sizeof(handle));
  435. service_record *service = find_service_for_key(handle);
  436. if (service == nullptr) {
  437. // Service handle is bad
  438. char badreq_rep[] = { DINIT_RP_BADREQ };
  439. if (! queue_packet(badreq_rep, 1)) return false;
  440. bad_conn_close = true;
  441. iob.set_watches(OUT_EVENTS);
  442. return true;
  443. }
  444. if (!service->has_lone_ref(false)) {
  445. // Cannot unload: has other references
  446. char nak_rep[] = { DINIT_RP_NAK };
  447. if (! queue_packet(nak_rep, 1)) return false;
  448. }
  449. else {
  450. try {
  451. // drop handle
  452. key_service_map.erase(handle);
  453. service_key_map.erase(service);
  454. // reload
  455. service->remove_listener(this);
  456. services->reload_service(service);
  457. services->process_queues();
  458. // send ack
  459. char ack_buf[] = { (char) DINIT_RP_ACK };
  460. if (! queue_packet(ack_buf, 1)) return false;
  461. }
  462. catch (service_load_exc &slexc) {
  463. log(loglevel_t::ERROR, "Could not reload service ", slexc.service_name, ": ",
  464. slexc.exc_description);
  465. char nak_rep[] = { DINIT_RP_NAK };
  466. if (! queue_packet(nak_rep, 1)) return false;
  467. }
  468. }
  469. // Clear the packet from the buffer
  470. rbuf.consume(pkt_size);
  471. chklen = 0;
  472. return true;
  473. }
  474. constexpr static unsigned SIZEOF_INT_PIDT_UNION = ((sizeof(pid_t) > sizeof(int)) ? sizeof(pid_t) : sizeof(int));
  475. constexpr static unsigned STATUS_BUFFER_SIZE = 6 + SIZEOF_INT_PIDT_UNION;
  476. static void fill_status_buffer(char *buffer, service_record *service)
  477. {
  478. buffer[0] = static_cast<char>(service->get_state());
  479. buffer[1] = static_cast<char>(service->get_target_state());
  480. pid_t proc_pid = service->get_pid();
  481. char b0 = service->is_waiting_for_console() ? 1 : 0;
  482. b0 |= service->has_console() ? 2 : 0;
  483. b0 |= service->was_start_skipped() ? 4 : 0;
  484. b0 |= service->is_marked_active() ? 8 : 0;
  485. b0 |= (proc_pid != -1) ? 16 : 0;
  486. buffer[2] = b0;
  487. buffer[3] = static_cast<char>(service->get_stop_reason());
  488. buffer[4] = 0; // (if exec failed, these are replaced with stage)
  489. buffer[5] = 0;
  490. if (proc_pid != -1) {
  491. memcpy(buffer + 6, &proc_pid, sizeof(proc_pid));
  492. }
  493. else {
  494. // These values only make sense in STOPPING/STOPPED, but we'll fill them in regardless:
  495. if (buffer[3] == (char)stopped_reason_t::EXECFAILED) {
  496. base_process_service *bsp = (base_process_service *)service;
  497. run_proc_err exec_err = bsp->get_exec_err_info();
  498. uint16_t stage = (uint16_t)exec_err.stage;
  499. memcpy(buffer + 4, &stage, 2);
  500. memcpy(buffer + 6, &exec_err.st_errno, sizeof(int));
  501. }
  502. else {
  503. int exit_status = service->get_exit_status();
  504. memcpy(buffer + 6, &exit_status, sizeof(exit_status));
  505. }
  506. }
  507. }
  508. bool control_conn_t::list_services()
  509. {
  510. rbuf.consume(1); // clear request packet
  511. chklen = 0;
  512. try {
  513. auto slist = services->list_services();
  514. for (auto sptr : slist) {
  515. if (sptr->get_type() == service_type_t::PLACEHOLDER) continue;
  516. std::vector<char> pkt_buf;
  517. int hdrsize = 2 + STATUS_BUFFER_SIZE;
  518. const std::string &name = sptr->get_name();
  519. int nameLen = std::min((size_t)256, name.length());
  520. pkt_buf.resize(hdrsize + nameLen);
  521. pkt_buf[0] = DINIT_RP_SVCINFO;
  522. pkt_buf[1] = nameLen;
  523. fill_status_buffer(&pkt_buf[2], sptr);
  524. for (int i = 0; i < nameLen; i++) {
  525. pkt_buf[hdrsize+i] = name[i];
  526. }
  527. if (!queue_packet(std::move(pkt_buf))) return false;
  528. }
  529. char ack_buf[] = { (char) DINIT_RP_LISTDONE };
  530. if (! queue_packet(ack_buf, 1)) return false;
  531. return true;
  532. }
  533. catch (std::bad_alloc &exc)
  534. {
  535. do_oom_close();
  536. return true;
  537. }
  538. }
  539. bool control_conn_t::process_service_status()
  540. {
  541. constexpr int pkt_size = 1 + sizeof(handle_t);
  542. if (rbuf.get_length() < pkt_size) {
  543. chklen = pkt_size;
  544. return true;
  545. }
  546. handle_t handle;
  547. rbuf.extract(&handle, 1, sizeof(handle));
  548. rbuf.consume(pkt_size);
  549. chklen = 0;
  550. service_record *service = find_service_for_key(handle);
  551. if (service == nullptr || service->get_name().length() > std::numeric_limits<uint16_t>::max()) {
  552. char nak_rep[] = { DINIT_RP_NAK };
  553. return queue_packet(nak_rep, 1);
  554. }
  555. // Reply:
  556. // 1 byte packet type = DINIT_RP_SERVICESTATUS
  557. // 1 byte reserved ( = 0)
  558. // STATUS_BUFFER_SIZE bytes status
  559. std::vector<char> pkt_buf(2 + STATUS_BUFFER_SIZE);
  560. pkt_buf[0] = DINIT_RP_SERVICESTATUS;
  561. pkt_buf[1] = 0;
  562. fill_status_buffer(pkt_buf.data() + 2, service);
  563. return queue_packet(std::move(pkt_buf));
  564. }
  565. bool control_conn_t::add_service_dep(bool do_enable)
  566. {
  567. // 1 byte packet type
  568. // 1 byte dependency type
  569. // handle: "from"
  570. // handle: "to"
  571. constexpr int pkt_size = 2 + sizeof(handle_t) * 2;
  572. if (rbuf.get_length() < pkt_size) {
  573. chklen = pkt_size;
  574. return true;
  575. }
  576. handle_t from_handle;
  577. handle_t to_handle;
  578. rbuf.extract((char *) &from_handle, 2, sizeof(from_handle));
  579. rbuf.extract((char *) &to_handle, 2 + sizeof(from_handle), sizeof(to_handle));
  580. service_record *from_service = find_service_for_key(from_handle);
  581. service_record *to_service = find_service_for_key(to_handle);
  582. if (from_service == nullptr || to_service == nullptr || from_service == to_service) {
  583. // Service handle is bad
  584. char badreq_rep[] = { DINIT_RP_BADREQ };
  585. if (! queue_packet(badreq_rep, 1)) return false;
  586. bad_conn_close = true;
  587. iob.set_watches(OUT_EVENTS);
  588. return true;
  589. }
  590. // Check dependency type is valid:
  591. int dep_type_int = rbuf[1];
  592. if (! contains({dependency_type::MILESTONE, dependency_type::REGULAR,
  593. dependency_type::WAITS_FOR}, dep_type_int)) {
  594. char badreqRep[] = { DINIT_RP_BADREQ };
  595. if (! queue_packet(badreqRep, 1)) return false;
  596. bad_conn_close = true;
  597. iob.set_watches(OUT_EVENTS);
  598. }
  599. dependency_type dep_type = static_cast<dependency_type>(dep_type_int);
  600. // Check current service states are valid for given dep type
  601. if (dep_type == dependency_type::REGULAR) {
  602. if (from_service->get_state() != service_state_t::STOPPED &&
  603. to_service->get_state() != service_state_t::STARTED) {
  604. // Cannot create dependency now since it would be contradicted:
  605. char nak_rep[] = { DINIT_RP_NAK };
  606. if (! queue_packet(nak_rep, 1)) return false;
  607. rbuf.consume(pkt_size);
  608. chklen = 0;
  609. return true;
  610. }
  611. }
  612. // Check for creation of circular dependency chain
  613. std::unordered_set<service_record *> dep_marks;
  614. std::vector<service_record *> dep_queue;
  615. dep_queue.push_back(to_service);
  616. while (! dep_queue.empty()) {
  617. service_record * sr = dep_queue.back();
  618. dep_queue.pop_back();
  619. // iterate deps; if dep == from, abort; otherwise add to set/queue
  620. // (only add to queue if not already in set)
  621. for (auto &dep : sr->get_dependencies()) {
  622. service_record * dep_to = dep.get_to();
  623. if (dep_to == from_service) {
  624. // fail, circular dependency!
  625. char nak_rep[] = { DINIT_RP_NAK };
  626. if (! queue_packet(nak_rep, 1)) return false;
  627. rbuf.consume(pkt_size);
  628. chklen = 0;
  629. return true;
  630. }
  631. if (dep_marks.insert(dep_to).second) {
  632. dep_queue.push_back(dep_to);
  633. }
  634. }
  635. }
  636. dep_marks.clear();
  637. dep_queue.clear();
  638. bool dep_exists = false;
  639. service_dep * dep_record = nullptr;
  640. // Prevent creation of duplicate dependency:
  641. for (auto &dep : from_service->get_dependencies()) {
  642. service_record * dep_to = dep.get_to();
  643. if (dep_to == to_service && dep.dep_type == dep_type) {
  644. // Dependency already exists
  645. dep_exists = true;
  646. dep_record = &dep;
  647. break;
  648. }
  649. }
  650. if (! dep_exists) {
  651. // Create dependency:
  652. dep_record = &(from_service->add_dep(to_service, dep_type));
  653. services->process_queues();
  654. }
  655. if (do_enable && contains({service_state_t::STARTED, service_state_t::STARTING},
  656. from_service->get_state())) {
  657. // The dependency record is activated: mark it as holding acquisition of the dependency, and start
  658. // the dependency.
  659. if (!services->is_shutting_down()) {
  660. dep_record->get_from()->start_dep(*dep_record);
  661. services->process_queues();
  662. }
  663. }
  664. char ack_rep[] = { DINIT_RP_ACK };
  665. if (! queue_packet(ack_rep, 1)) return false;
  666. rbuf.consume(pkt_size);
  667. chklen = 0;
  668. return true;
  669. }
  670. bool control_conn_t::rm_service_dep()
  671. {
  672. // 1 byte packet type
  673. // 1 byte dependency type
  674. // handle: "from"
  675. // handle: "to"
  676. constexpr int pkt_size = 2 + sizeof(handle_t) * 2;
  677. if (rbuf.get_length() < pkt_size) {
  678. chklen = pkt_size;
  679. return true;
  680. }
  681. handle_t from_handle;
  682. handle_t to_handle;
  683. rbuf.extract((char *) &from_handle, 2, sizeof(from_handle));
  684. rbuf.extract((char *) &to_handle, 2 + sizeof(from_handle), sizeof(to_handle));
  685. service_record *from_service = find_service_for_key(from_handle);
  686. service_record *to_service = find_service_for_key(to_handle);
  687. if (from_service == nullptr || to_service == nullptr || from_service == to_service) {
  688. // Service handle is bad
  689. char badreq_rep[] = { DINIT_RP_BADREQ };
  690. if (! queue_packet(badreq_rep, 1)) return false;
  691. bad_conn_close = true;
  692. iob.set_watches(OUT_EVENTS);
  693. return true;
  694. }
  695. // Check dependency type is valid:
  696. int dep_type_int = rbuf[1];
  697. if (! contains({dependency_type::MILESTONE, dependency_type::REGULAR,
  698. dependency_type::WAITS_FOR}, dep_type_int)) {
  699. char badreqRep[] = { DINIT_RP_BADREQ };
  700. if (! queue_packet(badreqRep, 1)) return false;
  701. bad_conn_close = true;
  702. iob.set_watches(OUT_EVENTS);
  703. }
  704. dependency_type dep_type = static_cast<dependency_type>(dep_type_int);
  705. // Remove dependency:
  706. bool did_remove = from_service->rm_dep(to_service, dep_type);
  707. services->process_queues();
  708. char ack_rep[] = { did_remove ? (char)DINIT_RP_ACK : (char)DINIT_RP_NAK };
  709. if (! queue_packet(ack_rep, 1)) return false;
  710. rbuf.consume(pkt_size);
  711. chklen = 0;
  712. return true;
  713. }
  714. bool control_conn_t::process_query_name()
  715. {
  716. // 1 byte packet type
  717. // 1 byte reserved
  718. // handle: service
  719. constexpr int pkt_size = 2 + sizeof(handle_t);
  720. if (rbuf.get_length() < pkt_size) {
  721. chklen = pkt_size;
  722. return true;
  723. }
  724. handle_t handle;
  725. rbuf.extract(&handle, 2, sizeof(handle));
  726. rbuf.consume(pkt_size);
  727. chklen = 0;
  728. service_record *service = find_service_for_key(handle);
  729. if (service == nullptr || service->get_name().length() > std::numeric_limits<uint16_t>::max()) {
  730. char nak_rep[] = { DINIT_RP_NAK };
  731. return queue_packet(nak_rep, 1);
  732. }
  733. // Reply:
  734. // 1 byte packet type = DINIT_RP_SERVICENAME
  735. // 1 byte reserved
  736. // uint16_t length
  737. // N bytes name
  738. std::vector<char> reply;
  739. const std::string &name = service->get_name();
  740. uint16_t name_length = name.length();
  741. reply.resize(2 + sizeof(uint16_t) + name_length);
  742. reply[0] = DINIT_RP_SERVICENAME;
  743. memcpy(reply.data() + 2, &name_length, sizeof(name_length));
  744. memcpy(reply.data() + 2 + sizeof(uint16_t), name.c_str(), name_length);
  745. return queue_packet(std::move(reply));
  746. }
  747. bool control_conn_t::process_setenv()
  748. {
  749. using std::string;
  750. string envVar;
  751. typename string::size_type eq;
  752. constexpr int pkt_size = 4;
  753. char badreqRep[] = { DINIT_RP_BADREQ };
  754. char okRep[] = { DINIT_RP_ACK };
  755. if (rbuf.get_length() < pkt_size) {
  756. chklen = pkt_size;
  757. return true;
  758. }
  759. uint16_t envSize;
  760. rbuf.extract((char *)&envSize, 1, 2);
  761. if (envSize <= 0 || envSize > (1024 - 3)) {
  762. goto badreq;
  763. }
  764. chklen = envSize + 3; // packet type + (2 byte) length + envvar
  765. if (rbuf.get_length() < chklen) {
  766. // packet not complete yet; read more
  767. return true;
  768. }
  769. envVar = rbuf.extract_string(3, envSize);
  770. eq = envVar.find('=');
  771. if (!eq || eq == envVar.npos) {
  772. // Not found or at the beginning of the string
  773. goto badreq;
  774. }
  775. main_env.set_var(std::move(envVar));
  776. // Success response
  777. if (!queue_packet(okRep, 1)) return false;
  778. // Clear the packet from the buffer
  779. rbuf.consume(chklen);
  780. chklen = 0;
  781. return true;
  782. badreq:
  783. // Queue error response / mark connection bad
  784. if (! queue_packet(badreqRep, 1)) return false;
  785. bad_conn_close = true;
  786. iob.set_watches(OUT_EVENTS);
  787. return true;
  788. }
  789. bool control_conn_t::process_set_trigger()
  790. {
  791. // 1 byte packet type
  792. // handle: service
  793. // 1 byte trigger value
  794. constexpr int pkt_size = 2 + sizeof(handle_t);
  795. if (rbuf.get_length() < pkt_size) {
  796. chklen = pkt_size;
  797. return true;
  798. }
  799. handle_t handle;
  800. char trigger_val;
  801. rbuf.extract(&handle, 1, sizeof(handle));
  802. rbuf.extract(&trigger_val, 1 + sizeof(handle), sizeof(trigger_val));
  803. rbuf.consume(pkt_size);
  804. chklen = 0;
  805. service_record *service = find_service_for_key(handle);
  806. if (service == nullptr || service->get_type() != service_type_t::TRIGGERED) {
  807. char nak_rep[] = { DINIT_RP_NAK };
  808. return queue_packet(nak_rep, 1);
  809. }
  810. triggered_service *tservice = static_cast<triggered_service *>(service);
  811. tservice->set_trigger(trigger_val != 0);
  812. services->process_queues();
  813. char ack_rep[] = { DINIT_RP_ACK };
  814. return queue_packet(ack_rep, 1);
  815. }
  816. bool control_conn_t::process_catlog()
  817. {
  818. // 1 byte packet type
  819. // 1 byte reserved for future use
  820. // handle
  821. constexpr int pkt_size = 2 + sizeof(handle_t);
  822. if (rbuf.get_length() < pkt_size) {
  823. chklen = pkt_size;
  824. return true;
  825. }
  826. handle_t handle;
  827. rbuf.extract(&handle, 1, sizeof(handle));
  828. rbuf.consume(pkt_size);
  829. chklen = 0;
  830. service_record *service = find_service_for_key(handle);
  831. if (service == nullptr || (service->get_type() != service_type_t::PROCESS
  832. && service->get_type() != service_type_t::BGPROCESS
  833. && service->get_type() != service_type_t::SCRIPTED)) {
  834. char nak_rep[] = { DINIT_RP_NAK };
  835. return queue_packet(nak_rep, 1);
  836. }
  837. base_process_service *bps = static_cast<base_process_service *>(service);
  838. if (bps->get_log_mode() != log_type_id::BUFFER) {
  839. char nak_rep[] = { DINIT_RP_NAK };
  840. return queue_packet(nak_rep, 1);
  841. }
  842. auto buffer_details = bps->get_log_buffer();
  843. const char *bufaddr = buffer_details.first;
  844. unsigned buflen = buffer_details.second;
  845. std::vector<char> pkt = { (char)DINIT_RP_SERVICE_LOG };
  846. pkt.insert(pkt.end(), (char *)(&buflen), (char *)(&buflen + 1));
  847. pkt.insert(pkt.end(), bufaddr, bufaddr + buflen);
  848. return queue_packet(std::move(pkt));
  849. }
  850. bool control_conn_t::query_load_mech()
  851. {
  852. rbuf.consume(1);
  853. chklen = 0;
  854. if (services->get_set_type_id() == SSET_TYPE_DIRLOAD) {
  855. dirload_service_set *dss = static_cast<dirload_service_set *>(services);
  856. std::vector<char> reppkt;
  857. reppkt.resize(2 + sizeof(uint32_t) * 2); // packet type, loader type, packet size, # dirs
  858. reppkt[0] = DINIT_RP_LOADER_MECH;
  859. reppkt[1] = SSET_TYPE_DIRLOAD;
  860. // Number of directories in load path:
  861. uint32_t sdirs = dss->get_service_dir_count();
  862. std::memcpy(reppkt.data() + 2 + sizeof(uint32_t), &sdirs, sizeof(sdirs));
  863. // Our current working directory, which above are relative to:
  864. // leave sizeof(uint32_t) for size, which we'll fill in afterwards:
  865. std::size_t curpos = reppkt.size() + sizeof(uint32_t);
  866. #ifdef PATH_MAX
  867. uint32_t try_path_size = PATH_MAX;
  868. #else
  869. uint32_t try_path_size = 2048;
  870. #endif
  871. char *wd;
  872. while (true) {
  873. std::size_t total_size = curpos + std::size_t(try_path_size);
  874. if (total_size < curpos) {
  875. // Overflow. In theory we could now limit to size_t max, but the size must already
  876. // be crazy long; let's abort.
  877. char ack_rep[] = { DINIT_RP_NAK };
  878. if (! queue_packet(ack_rep, 1)) return false;
  879. return true;
  880. }
  881. reppkt.resize(total_size);
  882. wd = getcwd(reppkt.data() + curpos, try_path_size);
  883. if (wd != nullptr) break;
  884. // Keep doubling the path size we try until it's big enough, or we get numeric overflow
  885. uint32_t new_try_path_size = try_path_size * uint32_t(2u);
  886. if (new_try_path_size < try_path_size) {
  887. // Overflow.
  888. char ack_rep[] = { DINIT_RP_NAK };
  889. return queue_packet(ack_rep, 1);
  890. }
  891. try_path_size = new_try_path_size;
  892. }
  893. uint32_t wd_len = std::strlen(reppkt.data() + curpos);
  894. reppkt.resize(curpos + std::size_t(wd_len));
  895. std::memcpy(reppkt.data() + curpos - sizeof(uint32_t), &wd_len, sizeof(wd_len));
  896. // Each directory in the load path:
  897. for (int i = 0; uint32_t(i) < sdirs; i++) {
  898. const char *sdir = dss->get_service_dir(i);
  899. uint32_t dlen = std::strlen(sdir);
  900. auto cursize = reppkt.size();
  901. reppkt.resize(cursize + sizeof(dlen) + dlen);
  902. std::memcpy(reppkt.data() + cursize, &dlen, sizeof(dlen));
  903. std::memcpy(reppkt.data() + cursize + sizeof(dlen), sdir, dlen);
  904. }
  905. // Total packet size:
  906. uint32_t fsize = reppkt.size();
  907. std::memcpy(reppkt.data() + 2, &fsize, sizeof(fsize));
  908. if (! queue_packet(std::move(reppkt))) return false;
  909. return true;
  910. }
  911. else {
  912. // If we don't know how to deal with the service set type, send a NAK reply:
  913. char ack_rep[] = { DINIT_RP_NAK };
  914. return queue_packet(ack_rep, 1);
  915. }
  916. }
  917. control_conn_t::handle_t control_conn_t::allocate_service_handle(service_record *record)
  918. {
  919. // Try to find a unique handle (integer) in a single pass. Since the map is ordered, we can search until
  920. // we find a gap in the handle values.
  921. handle_t candidate = 0;
  922. for (auto p : key_service_map) {
  923. if (p.first == candidate) ++candidate;
  924. else break;
  925. }
  926. bool is_unique = (service_key_map.find(record) == service_key_map.end());
  927. // The following operations perform allocation (can throw std::bad_alloc). If an exception occurs we
  928. // must undo any previous actions:
  929. if (is_unique) {
  930. record->add_listener(this);
  931. }
  932. try {
  933. key_service_map[candidate] = record;
  934. service_key_map.insert(std::make_pair(record, candidate));
  935. }
  936. catch (...) {
  937. if (is_unique) {
  938. record->remove_listener(this);
  939. }
  940. key_service_map.erase(candidate);
  941. }
  942. return candidate;
  943. }
  944. void control_conn_t::service_event(service_record *service, service_event_t event) noexcept
  945. {
  946. // For each service handle corresponding to the event, send an information packet.
  947. auto range = service_key_map.equal_range(service);
  948. auto &i = range.first;
  949. auto &end = range.second;
  950. try {
  951. while (i != end) {
  952. uint32_t key = i->second;
  953. std::vector<char> pkt;
  954. constexpr int pktsize = 3 + sizeof(key) + STATUS_BUFFER_SIZE;
  955. pkt.reserve(pktsize);
  956. pkt.push_back(DINIT_IP_SERVICEEVENT);
  957. pkt.push_back(pktsize);
  958. char *p = (char *)&key;
  959. for (unsigned j = 0; j < sizeof(key); j++) {
  960. pkt.push_back(*p++);
  961. }
  962. pkt.push_back(static_cast<char>(event));
  963. pkt.resize(pktsize);
  964. fill_status_buffer(pkt.data() + 3 + sizeof(key), service);
  965. queue_packet(std::move(pkt));
  966. ++i;
  967. }
  968. }
  969. catch (std::bad_alloc &exc) {
  970. do_oom_close();
  971. }
  972. }
  973. bool control_conn_t::queue_packet(const char *pkt, unsigned size) noexcept
  974. {
  975. int in_flag = bad_conn_close ? 0 : IN_EVENTS;
  976. bool was_empty = outbuf.empty();
  977. // If the queue is empty, we can try to write the packet out now rather than queueing it.
  978. // If the write is unsuccessful or partial, we queue the remainder.
  979. if (was_empty) {
  980. int wr = bp_sys::write(iob.get_watched_fd(), pkt, size);
  981. if (wr == -1) {
  982. if (errno == EPIPE) {
  983. return false;
  984. }
  985. if (errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR) {
  986. log(loglevel_t::WARN, "Error writing to control connection: ", strerror(errno));
  987. return false;
  988. }
  989. // EAGAIN etc: fall through to below
  990. }
  991. else {
  992. if ((unsigned)wr == size) {
  993. // Ok, all written.
  994. iob.set_watches(in_flag);
  995. return true;
  996. }
  997. pkt += wr;
  998. size -= wr;
  999. }
  1000. }
  1001. // Create a vector out of the (remaining part of the) packet:
  1002. try {
  1003. outbuf.emplace_back(pkt, pkt + size);
  1004. iob.set_watches(in_flag | OUT_EVENTS);
  1005. return true;
  1006. }
  1007. catch (std::bad_alloc &baexc) {
  1008. // Mark the connection bad, and stop reading further requests
  1009. bad_conn_close = true;
  1010. oom_close = true;
  1011. if (was_empty) {
  1012. // We can't send out-of-memory response as we already wrote as much as we
  1013. // could above. Neither can we later send the response since we have currently
  1014. // sent an incomplete packet. All we can do is close the connection.
  1015. return false;
  1016. }
  1017. else {
  1018. iob.set_watches(OUT_EVENTS);
  1019. return true;
  1020. }
  1021. }
  1022. }
  1023. // This queue_packet method is frustratingly similar to the one above, but the subtle differences
  1024. // make them extraordinary difficult to combine into a single method.
  1025. bool control_conn_t::queue_packet(std::vector<char> &&pkt) noexcept
  1026. {
  1027. int in_flag = bad_conn_close ? 0 : IN_EVENTS;
  1028. bool was_empty = outbuf.empty();
  1029. if (was_empty) {
  1030. outpkt_index = 0;
  1031. // We can try sending the packet immediately:
  1032. int wr = bp_sys::write(iob.get_watched_fd(), pkt.data(), pkt.size());
  1033. if (wr == -1) {
  1034. if (errno == EPIPE) {
  1035. return false;
  1036. }
  1037. if (errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR) {
  1038. log(loglevel_t::WARN, "Error writing to control connection: ", strerror(errno));
  1039. return false;
  1040. }
  1041. // EAGAIN etc: fall through to below
  1042. }
  1043. else {
  1044. if ((unsigned)wr == pkt.size()) {
  1045. // Ok, all written.
  1046. iob.set_watches(in_flag);
  1047. return true;
  1048. }
  1049. outpkt_index = wr;
  1050. }
  1051. }
  1052. try {
  1053. outbuf.emplace_back(std::move(pkt));
  1054. iob.set_watches(in_flag | OUT_EVENTS);
  1055. return true;
  1056. }
  1057. catch (std::bad_alloc &baexc) {
  1058. // Mark the connection bad, and stop reading further requests
  1059. bad_conn_close = true;
  1060. oom_close = true;
  1061. if (was_empty) {
  1062. // We can't send out-of-memory response as we already wrote as much as we
  1063. // could above. Neither can we later send the response since we have currently
  1064. // sent an incomplete packet. All we can do is close the connection.
  1065. return false;
  1066. }
  1067. else {
  1068. iob.set_watches(OUT_EVENTS);
  1069. return true;
  1070. }
  1071. }
  1072. }
  1073. bool control_conn_t::data_ready() noexcept
  1074. {
  1075. int fd = iob.get_watched_fd();
  1076. int r = rbuf.fill(fd);
  1077. // Note file descriptor is non-blocking
  1078. if (r == -1) {
  1079. if (errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR) {
  1080. log(loglevel_t::WARN, "Error reading from control connection: ", strerror(errno));
  1081. return true;
  1082. }
  1083. return false;
  1084. }
  1085. if (r == 0) {
  1086. return true;
  1087. }
  1088. // complete packet?
  1089. if (rbuf.get_length() >= chklen) {
  1090. try {
  1091. return !process_packet();
  1092. }
  1093. catch (std::bad_alloc &baexc) {
  1094. do_oom_close();
  1095. return false;
  1096. }
  1097. }
  1098. else if (rbuf.get_length() == rbuf.get_size()) {
  1099. // Too big packet
  1100. log(loglevel_t::WARN, "Received too-large control packet; dropping connection");
  1101. bad_conn_close = true;
  1102. iob.set_watches(OUT_EVENTS);
  1103. }
  1104. else {
  1105. int out_flags = (bad_conn_close || !outbuf.empty()) ? OUT_EVENTS : 0;
  1106. iob.set_watches(IN_EVENTS | out_flags);
  1107. }
  1108. return false;
  1109. }
  1110. bool control_conn_t::send_data() noexcept
  1111. {
  1112. if (outbuf.empty() && bad_conn_close) {
  1113. if (oom_close) {
  1114. // Send oom response
  1115. char oomBuf[] = { DINIT_RP_OOM };
  1116. bp_sys::write(iob.get_watched_fd(), oomBuf, 1);
  1117. }
  1118. return true;
  1119. }
  1120. vector<char> & pkt = outbuf.front();
  1121. char *data = pkt.data();
  1122. int written = bp_sys::write(iob.get_watched_fd(), data + outpkt_index, pkt.size() - outpkt_index);
  1123. if (written == -1) {
  1124. if (errno == EPIPE) {
  1125. // read end closed
  1126. return true;
  1127. }
  1128. else if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) {
  1129. // spurious readiness notification?
  1130. return false;
  1131. }
  1132. else {
  1133. log(loglevel_t::ERROR, "Error writing to control connection: ", strerror(errno));
  1134. return true;
  1135. }
  1136. }
  1137. outpkt_index += written;
  1138. if (outpkt_index == pkt.size()) {
  1139. // We've finished this packet, move on to the next:
  1140. outbuf.pop_front();
  1141. outpkt_index = 0;
  1142. if (oom_close) {
  1143. // remain active, try to send DINIT_RP_OOM shortly
  1144. return false;
  1145. }
  1146. if (outbuf.empty()) {
  1147. if (bad_conn_close) {
  1148. return true;
  1149. }
  1150. iob.set_watches(IN_EVENTS);
  1151. }
  1152. }
  1153. // more to send
  1154. return false;
  1155. }
  1156. control_conn_t::~control_conn_t() noexcept
  1157. {
  1158. int fd = iob.get_watched_fd();
  1159. iob.deregister(loop);
  1160. bp_sys::close(fd);
  1161. // Clear service listeners
  1162. for (auto p : service_key_map) {
  1163. p.first->remove_listener(this);
  1164. }
  1165. active_control_conns--;
  1166. }