control.cc 42 KB

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