2 #include <unordered_set>
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.
12 constexpr auto OUT_EVENTS = dasynq::OUT_EVENTS;
13 constexpr auto IN_EVENTS = dasynq::IN_EVENTS;
15 // Control protocol minimum compatible version and current version:
16 constexpr uint16_t min_compat_version = 1;
17 constexpr uint16_t cp_version = 1;
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)
23 return std::find_if(std::begin(v), std::end(v),
24 [=](T p){ return i == static_cast<U>(p); }) != std::end(v);
28 bool control_conn_t::process_packet()
32 // Note that where we call queue_packet, we must generally check the return value. If it
33 // returns false it has either deleted the connection or marked it for deletion; we
34 // shouldn't touch instance members after that point.
36 int pktType = rbuf[0];
37 if (pktType == DINIT_CP_QUERYVERSION) {
39 // DINIT_RP_CVERSION, (2 byte) minimum compatible version, (2 byte) actual version
40 char replyBuf[] = { DINIT_RP_CPVERSION, 0, 0, 0, 0 };
41 memcpy(replyBuf + 1, &min_compat_version, 2);
42 memcpy(replyBuf + 3, &cp_version, 2);
43 if (! queue_packet(replyBuf, sizeof(replyBuf))) return false;
47 if (pktType == DINIT_CP_FINDSERVICE || pktType == DINIT_CP_LOADSERVICE) {
48 return process_find_load(pktType);
50 if (pktType == DINIT_CP_STARTSERVICE || pktType == DINIT_CP_STOPSERVICE
51 || pktType == DINIT_CP_WAKESERVICE || pktType == DINIT_CP_RELEASESERVICE) {
52 return process_start_stop(pktType);
54 if (pktType == DINIT_CP_UNPINSERVICE) {
55 return process_unpin_service();
57 if (pktType == DINIT_CP_UNLOADSERVICE) {
58 return process_unload_service();
60 if (pktType == DINIT_CP_SHUTDOWN) {
62 if (rbuf.get_length() < 2) {
67 if (contains({shutdown_type_t::REMAIN, shutdown_type_t::HALT,
68 shutdown_type_t::POWEROFF, shutdown_type_t::REBOOT}, rbuf[1])) {
69 auto sd_type = static_cast<shutdown_type_t>(rbuf[1]);
71 services->stop_all_services(sd_type);
72 char ackBuf[] = { DINIT_RP_ACK };
73 if (! queue_packet(ackBuf, 1)) return false;
75 // Clear the packet from the buffer
81 // (otherwise fall through to below).
83 if (pktType == DINIT_CP_LISTSERVICES) {
84 return list_services();
86 if (pktType == DINIT_CP_ADD_DEP) {
87 return add_service_dep();
89 if (pktType == DINIT_CP_REM_DEP) {
90 return rm_service_dep();
92 if (pktType == DINIT_CP_QUERY_LOAD_MECH) {
93 return query_load_mech();
95 if (pktType == DINIT_CP_ENABLESERVICE) {
96 return add_service_dep(true);
99 // Unrecognized: give error response
100 char outbuf[] = { DINIT_RP_BADREQ };
101 if (! queue_packet(outbuf, 1)) return false;
102 bad_conn_close = true;
103 iob.set_watches(OUT_EVENTS);
107 bool control_conn_t::process_find_load(int pktType)
111 constexpr int pkt_size = 4;
113 if (rbuf.get_length() < pkt_size) {
119 rbuf.extract((char *)&svcSize, 1, 2);
120 if (svcSize <= 0 || svcSize > (1024 - 3)) {
121 // Queue error response / mark connection bad
122 char badreqRep[] = { DINIT_RP_BADREQ };
123 if (! queue_packet(badreqRep, 1)) return false;
124 bad_conn_close = true;
125 iob.set_watches(OUT_EVENTS);
128 chklen = svcSize + 3; // packet type + (2 byte) length + service name
130 if (rbuf.get_length() < chklen) {
131 // packet not complete yet; read more
135 service_record * record = nullptr;
137 string serviceName = rbuf.extract_string(3, svcSize);
139 if (pktType == DINIT_CP_LOADSERVICE) {
142 record = services->load_service(serviceName.c_str());
144 catch (service_load_exc &slexc) {
145 log(loglevel_t::ERROR, "Could not load service ", slexc.service_name, ": ",
146 slexc.exc_description);
151 record = services->find_service(serviceName.c_str());
154 if (record != nullptr) {
155 // Allocate a service handle
156 handle_t handle = allocate_service_handle(record);
157 std::vector<char> rp_buf;
159 rp_buf.push_back(DINIT_RP_SERVICERECORD);
160 rp_buf.push_back(static_cast<char>(record->get_state()));
161 for (int i = 0; i < (int) sizeof(handle); i++) {
162 rp_buf.push_back(*(((char *) &handle) + i));
164 rp_buf.push_back(static_cast<char>(record->get_target_state()));
165 if (! queue_packet(std::move(rp_buf))) return false;
168 std::vector<char> rp_buf = { DINIT_RP_NOSERVICE };
169 if (! queue_packet(std::move(rp_buf))) return false;
172 // Clear the packet from the buffer
173 rbuf.consume(chklen);
178 bool control_conn_t::process_start_stop(int pktType)
182 constexpr int pkt_size = 2 + sizeof(handle_t);
184 if (rbuf.get_length() < pkt_size) {
189 // 1 byte: packet type
190 // 1 byte: pin in requested state (0 = no pin, 1 = pin)
191 // 4 bytes: service handle
193 bool do_pin = (rbuf[1] == 1);
195 rbuf.extract((char *) &handle, 2, sizeof(handle));
197 service_record *service = find_service_for_key(handle);
198 if (service == nullptr) {
199 // Service handle is bad
200 char badreqRep[] = { DINIT_RP_BADREQ };
201 if (! queue_packet(badreqRep, 1)) return false;
202 bad_conn_close = true;
203 iob.set_watches(OUT_EVENTS);
207 bool already_there = false;
210 case DINIT_CP_STARTSERVICE:
211 // start service, mark as required
212 if (do_pin) service->pin_start();
214 services->process_queues();
215 already_there = service->get_state() == service_state_t::STARTED;
217 case DINIT_CP_STOPSERVICE:
218 // force service to stop
219 if (do_pin) service->pin_stop();
221 service->forced_stop();
222 services->process_queues();
223 already_there = service->get_state() == service_state_t::STOPPED;
225 case DINIT_CP_WAKESERVICE:
226 // re-start a stopped service (do not mark as required)
227 if (do_pin) service->pin_start();
228 service->start(false);
229 services->process_queues();
230 already_there = service->get_state() == service_state_t::STARTED;
232 case DINIT_CP_RELEASESERVICE:
233 // remove required mark, stop if not required by dependents
234 if (do_pin) service->pin_stop();
235 service->stop(false);
236 services->process_queues();
237 already_there = service->get_state() == service_state_t::STOPPED;
241 char ack_buf[] = { (char)(already_there ? DINIT_RP_ALREADYSS : DINIT_RP_ACK) };
243 if (! queue_packet(ack_buf, 1)) return false;
246 // Clear the packet from the buffer
247 rbuf.consume(pkt_size);
252 bool control_conn_t::process_unpin_service()
256 constexpr int pkt_size = 1 + sizeof(handle_t);
258 if (rbuf.get_length() < pkt_size) {
263 // 1 byte: packet type
264 // 4 bytes: service handle
267 rbuf.extract((char *) &handle, 1, sizeof(handle));
269 service_record *service = find_service_for_key(handle);
270 if (service == nullptr) {
271 // Service handle is bad
272 char badreqRep[] = { DINIT_RP_BADREQ };
273 if (! queue_packet(badreqRep, 1)) return false;
274 bad_conn_close = true;
275 iob.set_watches(OUT_EVENTS);
280 services->process_queues();
281 char ack_buf[] = { (char) DINIT_RP_ACK };
282 if (! queue_packet(ack_buf, 1)) return false;
284 // Clear the packet from the buffer
285 rbuf.consume(pkt_size);
290 bool control_conn_t::process_unload_service()
294 constexpr int pkt_size = 1 + sizeof(handle_t);
296 if (rbuf.get_length() < pkt_size) {
301 // 1 byte: packet type
302 // 4 bytes: service handle
305 rbuf.extract((char *) &handle, 1, sizeof(handle));
307 service_record *service = find_service_for_key(handle);
308 if (service == nullptr) {
309 // Service handle is bad
310 char badreq_rep[] = { DINIT_RP_BADREQ };
311 if (! queue_packet(badreq_rep, 1)) return false;
312 bad_conn_close = true;
313 iob.set_watches(OUT_EVENTS);
317 if (! service->has_lone_ref() || service->get_state() != service_state_t::STOPPED) {
318 // Cannot unload: has other references
319 char nak_rep[] = { DINIT_RP_NAK };
320 if (! queue_packet(nak_rep, 1)) return false;
324 service->prepare_for_unload();
325 services->remove_service(service);
329 service_key_map.erase(service);
330 key_service_map.erase(handle);
333 char ack_buf[] = { (char) DINIT_RP_ACK };
334 if (! queue_packet(ack_buf, 1)) return false;
337 // Clear the packet from the buffer
338 rbuf.consume(pkt_size);
343 bool control_conn_t::list_services()
345 rbuf.consume(1); // clear request packet
349 auto slist = services->list_services();
350 for (auto sptr : slist) {
351 std::vector<char> pkt_buf;
353 int hdrsize = 8 + std::max(sizeof(int), sizeof(pid_t));
355 const std::string &name = sptr->get_name();
356 int nameLen = std::min((size_t)256, name.length());
357 pkt_buf.resize(hdrsize + nameLen);
359 pkt_buf[0] = DINIT_RP_SVCINFO;
360 pkt_buf[1] = nameLen;
361 pkt_buf[2] = static_cast<char>(sptr->get_state());
362 pkt_buf[3] = static_cast<char>(sptr->get_target_state());
364 char b0 = sptr->is_waiting_for_console() ? 1 : 0;
365 b0 |= sptr->has_console() ? 2 : 0;
366 b0 |= sptr->was_start_skipped() ? 4 : 0;
368 pkt_buf[5] = static_cast<char>(sptr->get_stop_reason());
370 pkt_buf[6] = 0; // reserved
373 // Next: either the exit status, or the process ID
374 if (sptr->get_state() != service_state_t::STOPPED) {
375 pid_t proc_pid = sptr->get_pid();
376 memcpy(pkt_buf.data() + 8, &proc_pid, sizeof(proc_pid));
379 int exit_status = sptr->get_exit_status();
380 memcpy(pkt_buf.data() + 8, &exit_status, sizeof(exit_status));
383 for (int i = 0; i < nameLen; i++) {
384 pkt_buf[hdrsize+i] = name[i];
387 if (! queue_packet(std::move(pkt_buf))) return false;
390 char ack_buf[] = { (char) DINIT_RP_LISTDONE };
391 if (! queue_packet(ack_buf, 1)) return false;
395 catch (std::bad_alloc &exc)
402 bool control_conn_t::add_service_dep(bool do_enable)
404 // 1 byte packet type
405 // 1 byte dependency type
409 constexpr int pkt_size = 2 + sizeof(handle_t) * 2;
411 if (rbuf.get_length() < pkt_size) {
416 handle_t from_handle;
418 rbuf.extract((char *) &from_handle, 2, sizeof(from_handle));
419 rbuf.extract((char *) &to_handle, 2 + sizeof(from_handle), sizeof(to_handle));
421 service_record *from_service = find_service_for_key(from_handle);
422 service_record *to_service = find_service_for_key(to_handle);
423 if (from_service == nullptr || to_service == nullptr || from_service == to_service) {
424 // Service handle is bad
425 char badreq_rep[] = { DINIT_RP_BADREQ };
426 if (! queue_packet(badreq_rep, 1)) return false;
427 bad_conn_close = true;
428 iob.set_watches(OUT_EVENTS);
432 // Check dependency type is valid:
433 int dep_type_int = rbuf[1];
434 if (! contains({dependency_type::MILESTONE, dependency_type::REGULAR,
435 dependency_type::WAITS_FOR}, dep_type_int)) {
436 char badreqRep[] = { DINIT_RP_BADREQ };
437 if (! queue_packet(badreqRep, 1)) return false;
438 bad_conn_close = true;
439 iob.set_watches(OUT_EVENTS);
441 dependency_type dep_type = static_cast<dependency_type>(dep_type_int);
443 // Check current service states are valid for given dep type
444 if (dep_type == dependency_type::REGULAR) {
445 if (from_service->get_state() != service_state_t::STOPPED &&
446 to_service->get_state() != service_state_t::STARTED) {
447 // Cannot create dependency now since it would be contradicted:
448 char nak_rep[] = { DINIT_RP_NAK };
449 if (! queue_packet(nak_rep, 1)) return false;
450 rbuf.consume(pkt_size);
456 // Check for creation of circular dependency chain
457 std::unordered_set<service_record *> dep_marks;
458 std::vector<service_record *> dep_queue;
459 dep_queue.push_back(to_service);
460 while (! dep_queue.empty()) {
461 service_record * sr = dep_queue.back();
462 dep_queue.pop_back();
463 // iterate deps; if dep == from, abort; otherwise add to set/queue
464 // (only add to queue if not already in set)
465 for (auto &dep : sr->get_dependencies()) {
466 service_record * dep_to = dep.get_to();
467 if (dep_to == from_service) {
468 // fail, circular dependency!
469 char nak_rep[] = { DINIT_RP_NAK };
470 if (! queue_packet(nak_rep, 1)) return false;
471 rbuf.consume(pkt_size);
475 if (dep_marks.insert(dep_to).second) {
476 dep_queue.push_back(dep_to);
483 bool dep_exists = false;
484 service_dep * dep_record = nullptr;
486 // Prevent creation of duplicate dependency:
487 for (auto &dep : from_service->get_dependencies()) {
488 service_record * dep_to = dep.get_to();
489 if (dep_to == to_service && dep.dep_type == dep_type) {
490 // Dependency already exists
498 // Create dependency:
499 dep_record = &(from_service->add_dep(to_service, dep_type));
500 services->process_queues();
503 if (do_enable && contains({service_state_t::STARTED, service_state_t::STARTING},
504 from_service->get_state())) {
505 // The dependency record is activated: mark it as holding acquisition of the dependency, and start
507 dep_record->get_from()->start_dep(*dep_record);
508 services->process_queues();
511 char ack_rep[] = { DINIT_RP_ACK };
512 if (! queue_packet(ack_rep, 1)) return false;
513 rbuf.consume(pkt_size);
518 bool control_conn_t::rm_service_dep()
520 // 1 byte packet type
521 // 1 byte dependency type
525 constexpr int pkt_size = 2 + sizeof(handle_t) * 2;
527 if (rbuf.get_length() < pkt_size) {
532 handle_t from_handle;
534 rbuf.extract((char *) &from_handle, 2, sizeof(from_handle));
535 rbuf.extract((char *) &to_handle, 2 + sizeof(from_handle), sizeof(to_handle));
537 service_record *from_service = find_service_for_key(from_handle);
538 service_record *to_service = find_service_for_key(to_handle);
539 if (from_service == nullptr || to_service == nullptr || from_service == to_service) {
540 // Service handle is bad
541 char badreq_rep[] = { DINIT_RP_BADREQ };
542 if (! queue_packet(badreq_rep, 1)) return false;
543 bad_conn_close = true;
544 iob.set_watches(OUT_EVENTS);
548 // Check dependency type is valid:
549 int dep_type_int = rbuf[1];
550 if (! contains({dependency_type::MILESTONE, dependency_type::REGULAR,
551 dependency_type::WAITS_FOR}, dep_type_int)) {
552 char badreqRep[] = { DINIT_RP_BADREQ };
553 if (! queue_packet(badreqRep, 1)) return false;
554 bad_conn_close = true;
555 iob.set_watches(OUT_EVENTS);
557 dependency_type dep_type = static_cast<dependency_type>(dep_type_int);
559 // Remove dependency:
560 from_service->rm_dep(to_service, dep_type);
561 services->process_queues();
563 char ack_rep[] = { DINIT_RP_ACK };
564 if (! queue_packet(ack_rep, 1)) return false;
565 rbuf.consume(pkt_size);
570 bool control_conn_t::query_load_mech()
575 if (services->get_set_type_id() == SSET_TYPE_DIRLOAD) {
576 dirload_service_set *dss = static_cast<dirload_service_set *>(services);
577 std::vector<char> reppkt;
578 reppkt.resize(2 + sizeof(uint32_t) * 2); // packet type, loader type, packet size, # dirs
579 reppkt[0] = DINIT_RP_LOADER_MECH;
580 reppkt[1] = SSET_TYPE_DIRLOAD;
582 // Number of directories in load path:
583 uint32_t sdirs = dss->get_service_dir_count();
584 std::memcpy(reppkt.data() + 2 + sizeof(uint32_t), &sdirs, sizeof(sdirs));
586 // Our current working directory, which above are relative to:
587 // leave sizeof(uint32_t) for size, which we'll fill in afterwards:
588 std::size_t curpos = reppkt.size() + sizeof(uint32_t);
590 uint32_t try_path_size = PATH_MAX;
592 uint32_t try_path_size = 2048;
596 std::size_t total_size = curpos + std::size_t(try_path_size);
597 reppkt.resize(total_size);
598 if (total_size < curpos) {
600 char ack_rep[] = { DINIT_RP_NAK };
601 if (! queue_packet(ack_rep, 1)) return false;
604 wd = getcwd(reppkt.data() + curpos, try_path_size);
605 if (wd != nullptr) break;
607 try_path_size *= uint32_t(2u);
608 if (try_path_size == 0) {
610 char ack_rep[] = { DINIT_RP_NAK };
611 if (! queue_packet(ack_rep, 1)) return false;
616 uint32_t wd_len = std::strlen(reppkt.data() + curpos);
617 reppkt.resize(curpos + std::size_t(wd_len));
618 std::memcpy(reppkt.data() + curpos - sizeof(uint32_t), &wd_len, sizeof(wd_len));
620 // Each directory in the load path:
621 for (int i = 0; uint32_t(i) < sdirs; i++) {
622 const char *sdir = dss->get_service_dir(i);
623 uint32_t dlen = std::strlen(sdir);
624 auto cursize = reppkt.size();
625 reppkt.resize(cursize + sizeof(dlen) + dlen);
626 std::memcpy(reppkt.data() + cursize, &dlen, sizeof(dlen));
627 std::memcpy(reppkt.data() + cursize + sizeof(dlen), sdir, dlen);
630 // Total packet size:
631 uint32_t fsize = reppkt.size();
632 std::memcpy(reppkt.data() + 2, &fsize, sizeof(fsize));
634 if (! queue_packet(std::move(reppkt))) return false;
638 // If we don't know how to deal with the service set type, send a NAK reply:
639 char ack_rep[] = { DINIT_RP_NAK };
640 if (! queue_packet(ack_rep, 1)) return false;
645 control_conn_t::handle_t control_conn_t::allocate_service_handle(service_record *record)
647 // Try to find a unique handle (integer) in a single pass. Since the map is ordered, we can search until
648 // we find a gap in the handle values.
649 handle_t candidate = 0;
650 for (auto p : key_service_map) {
651 if (p.first == candidate) ++candidate;
655 bool is_unique = (service_key_map.find(record) == service_key_map.end());
657 // The following operations perform allocation (can throw std::bad_alloc). If an exception occurs we
658 // must undo any previous actions:
660 record->add_listener(this);
664 key_service_map[candidate] = record;
665 service_key_map.insert(std::make_pair(record, candidate));
669 record->remove_listener(this);
672 key_service_map.erase(candidate);
678 bool control_conn_t::queue_packet(const char *pkt, unsigned size) noexcept
680 int in_flag = bad_conn_close ? 0 : IN_EVENTS;
681 bool was_empty = outbuf.empty();
683 // If the queue is empty, we can try to write the packet out now rather than queueing it.
684 // If the write is unsuccessful or partial, we queue the remainder.
686 int wr = bp_sys::write(iob.get_watched_fd(), pkt, size);
688 if (errno == EPIPE) {
691 if (errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR) {
692 log(loglevel_t::WARN, "Error writing to control connection: ", strerror(errno));
695 // EAGAIN etc: fall through to below
698 if ((unsigned)wr == size) {
700 iob.set_watches(in_flag);
708 // Create a vector out of the (remaining part of the) packet:
710 outbuf.emplace_back(pkt, pkt + size);
711 iob.set_watches(in_flag | OUT_EVENTS);
714 catch (std::bad_alloc &baexc) {
715 // Mark the connection bad, and stop reading further requests
716 bad_conn_close = true;
719 // We can't send out-of-memory response as we already wrote as much as we
720 // could above. Neither can we later send the response since we have currently
721 // sent an incomplete packet. All we can do is close the connection.
725 iob.set_watches(OUT_EVENTS);
731 // This queue_packet method is frustratingly similar to the one above, but the subtle differences
732 // make them extraordinary difficult to combine into a single method.
733 bool control_conn_t::queue_packet(std::vector<char> &&pkt) noexcept
735 int in_flag = bad_conn_close ? 0 : IN_EVENTS;
736 bool was_empty = outbuf.empty();
740 // We can try sending the packet immediately:
741 int wr = bp_sys::write(iob.get_watched_fd(), pkt.data(), pkt.size());
743 if (errno == EPIPE) {
746 if (errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR) {
747 log(loglevel_t::WARN, "Error writing to control connection: ", strerror(errno));
750 // EAGAIN etc: fall through to below
753 if ((unsigned)wr == pkt.size()) {
755 iob.set_watches(in_flag);
763 outbuf.emplace_back(pkt);
764 iob.set_watches(in_flag | OUT_EVENTS);
767 catch (std::bad_alloc &baexc) {
768 // Mark the connection bad, and stop reading further requests
769 bad_conn_close = true;
772 // We can't send out-of-memory response as we already wrote as much as we
773 // could above. Neither can we later send the response since we have currently
774 // sent an incomplete packet. All we can do is close the connection.
778 iob.set_watches(OUT_EVENTS);
784 bool control_conn_t::data_ready() noexcept
786 int fd = iob.get_watched_fd();
788 int r = rbuf.fill(fd);
790 // Note file descriptor is non-blocking
792 if (errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR) {
793 log(loglevel_t::WARN, "Error writing to control connection: ", strerror(errno));
804 if (rbuf.get_length() >= chklen) {
806 return !process_packet();
808 catch (std::bad_alloc &baexc) {
813 else if (rbuf.get_length() == 1024) {
815 log(loglevel_t::WARN, "Received too-large control package; dropping connection");
816 bad_conn_close = true;
817 iob.set_watches(OUT_EVENTS);
820 int out_flags = (bad_conn_close || !outbuf.empty()) ? OUT_EVENTS : 0;
821 iob.set_watches(IN_EVENTS | out_flags);
827 bool control_conn_t::send_data() noexcept
829 if (outbuf.empty() && bad_conn_close) {
832 char oomBuf[] = { DINIT_RP_OOM };
833 bp_sys::write(iob.get_watched_fd(), oomBuf, 1);
838 vector<char> & pkt = outbuf.front();
839 char *data = pkt.data();
840 int written = bp_sys::write(iob.get_watched_fd(), data + outpkt_index, pkt.size() - outpkt_index);
842 if (errno == EPIPE) {
846 else if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) {
847 // spurious readiness notification?
850 log(loglevel_t::ERROR, "Error writing to control connection: ", strerror(errno));
856 outpkt_index += written;
857 if (outpkt_index == pkt.size()) {
858 // We've finished this packet, move on to the next:
861 if (outbuf.empty() && ! oom_close) {
862 if (! bad_conn_close) {
863 iob.set_watches(IN_EVENTS);
874 control_conn_t::~control_conn_t() noexcept
876 bp_sys::close(iob.get_watched_fd());
877 iob.deregister(loop);
879 // Clear service listeners
880 for (auto p : service_key_map) {
881 p.first->remove_listener(this);
884 active_control_conns--;