control.cc 34 KB

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