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 char ack_buf[1] = { DINIT_RP_ACK };
210 case DINIT_CP_STARTSERVICE:
211 // start service, mark as required
212 if (services->is_shutting_down()) {
213 ack_buf[0] = DINIT_RP_NAK;
216 if (do_pin) service->pin_start();
218 services->process_queues();
219 if (service->get_state() == service_state_t::STARTED) ack_buf[0] = DINIT_RP_ALREADYSS;
221 case DINIT_CP_STOPSERVICE:
222 // force service to stop
223 if (do_pin) service->pin_stop();
225 service->forced_stop();
226 services->process_queues();
227 if (service->get_state() == service_state_t::STOPPED) ack_buf[0] = DINIT_RP_ALREADYSS;
229 case DINIT_CP_WAKESERVICE:
230 // re-start a stopped service (do not mark as required)
231 if (services->is_shutting_down()) {
232 ack_buf[0] = DINIT_RP_NAK;
235 if (do_pin) service->pin_start();
236 service->start(false);
237 services->process_queues();
238 if (service->get_state() == service_state_t::STARTED) ack_buf[0] = DINIT_RP_ALREADYSS;
240 case DINIT_CP_RELEASESERVICE:
241 // remove required mark, stop if not required by dependents
242 if (do_pin) service->pin_stop();
243 service->stop(false);
244 services->process_queues();
245 if (service->get_state() == service_state_t::STOPPED) ack_buf[0] = DINIT_RP_ALREADYSS;
249 if (! queue_packet(ack_buf, 1)) return false;
252 // Clear the packet from the buffer
253 rbuf.consume(pkt_size);
258 bool control_conn_t::process_unpin_service()
262 constexpr int pkt_size = 1 + sizeof(handle_t);
264 if (rbuf.get_length() < pkt_size) {
269 // 1 byte: packet type
270 // 4 bytes: service handle
273 rbuf.extract((char *) &handle, 1, sizeof(handle));
275 service_record *service = find_service_for_key(handle);
276 if (service == nullptr) {
277 // Service handle is bad
278 char badreqRep[] = { DINIT_RP_BADREQ };
279 if (! queue_packet(badreqRep, 1)) return false;
280 bad_conn_close = true;
281 iob.set_watches(OUT_EVENTS);
286 services->process_queues();
287 char ack_buf[] = { (char) DINIT_RP_ACK };
288 if (! queue_packet(ack_buf, 1)) return false;
290 // Clear the packet from the buffer
291 rbuf.consume(pkt_size);
296 bool control_conn_t::process_unload_service()
300 constexpr int pkt_size = 1 + sizeof(handle_t);
302 if (rbuf.get_length() < pkt_size) {
307 // 1 byte: packet type
308 // 4 bytes: service handle
311 rbuf.extract((char *) &handle, 1, sizeof(handle));
313 service_record *service = find_service_for_key(handle);
314 if (service == nullptr) {
315 // Service handle is bad
316 char badreq_rep[] = { DINIT_RP_BADREQ };
317 if (! queue_packet(badreq_rep, 1)) return false;
318 bad_conn_close = true;
319 iob.set_watches(OUT_EVENTS);
323 if (! service->has_lone_ref() || service->get_state() != service_state_t::STOPPED) {
324 // Cannot unload: has other references
325 char nak_rep[] = { DINIT_RP_NAK };
326 if (! queue_packet(nak_rep, 1)) return false;
330 service->prepare_for_unload();
331 services->remove_service(service);
335 service_key_map.erase(service);
336 key_service_map.erase(handle);
339 char ack_buf[] = { (char) DINIT_RP_ACK };
340 if (! queue_packet(ack_buf, 1)) return false;
343 // Clear the packet from the buffer
344 rbuf.consume(pkt_size);
349 bool control_conn_t::list_services()
351 rbuf.consume(1); // clear request packet
355 auto slist = services->list_services();
356 for (auto sptr : slist) {
357 std::vector<char> pkt_buf;
359 int hdrsize = 8 + std::max(sizeof(int), sizeof(pid_t));
361 const std::string &name = sptr->get_name();
362 int nameLen = std::min((size_t)256, name.length());
363 pkt_buf.resize(hdrsize + nameLen);
365 pkt_buf[0] = DINIT_RP_SVCINFO;
366 pkt_buf[1] = nameLen;
367 pkt_buf[2] = static_cast<char>(sptr->get_state());
368 pkt_buf[3] = static_cast<char>(sptr->get_target_state());
370 char b0 = sptr->is_waiting_for_console() ? 1 : 0;
371 b0 |= sptr->has_console() ? 2 : 0;
372 b0 |= sptr->was_start_skipped() ? 4 : 0;
374 pkt_buf[5] = static_cast<char>(sptr->get_stop_reason());
376 pkt_buf[6] = 0; // reserved
379 // Next: either the exit status, or the process ID
380 if (sptr->get_state() != service_state_t::STOPPED) {
381 pid_t proc_pid = sptr->get_pid();
382 memcpy(pkt_buf.data() + 8, &proc_pid, sizeof(proc_pid));
385 int exit_status = sptr->get_exit_status();
386 memcpy(pkt_buf.data() + 8, &exit_status, sizeof(exit_status));
389 for (int i = 0; i < nameLen; i++) {
390 pkt_buf[hdrsize+i] = name[i];
393 if (! queue_packet(std::move(pkt_buf))) return false;
396 char ack_buf[] = { (char) DINIT_RP_LISTDONE };
397 if (! queue_packet(ack_buf, 1)) return false;
401 catch (std::bad_alloc &exc)
408 bool control_conn_t::add_service_dep(bool do_enable)
410 // 1 byte packet type
411 // 1 byte dependency type
415 constexpr int pkt_size = 2 + sizeof(handle_t) * 2;
417 if (rbuf.get_length() < pkt_size) {
422 handle_t from_handle;
424 rbuf.extract((char *) &from_handle, 2, sizeof(from_handle));
425 rbuf.extract((char *) &to_handle, 2 + sizeof(from_handle), sizeof(to_handle));
427 service_record *from_service = find_service_for_key(from_handle);
428 service_record *to_service = find_service_for_key(to_handle);
429 if (from_service == nullptr || to_service == nullptr || from_service == to_service) {
430 // Service handle is bad
431 char badreq_rep[] = { DINIT_RP_BADREQ };
432 if (! queue_packet(badreq_rep, 1)) return false;
433 bad_conn_close = true;
434 iob.set_watches(OUT_EVENTS);
438 // Check dependency type is valid:
439 int dep_type_int = rbuf[1];
440 if (! contains({dependency_type::MILESTONE, dependency_type::REGULAR,
441 dependency_type::WAITS_FOR}, dep_type_int)) {
442 char badreqRep[] = { DINIT_RP_BADREQ };
443 if (! queue_packet(badreqRep, 1)) return false;
444 bad_conn_close = true;
445 iob.set_watches(OUT_EVENTS);
447 dependency_type dep_type = static_cast<dependency_type>(dep_type_int);
449 // Check current service states are valid for given dep type
450 if (dep_type == dependency_type::REGULAR) {
451 if (from_service->get_state() != service_state_t::STOPPED &&
452 to_service->get_state() != service_state_t::STARTED) {
453 // Cannot create dependency now since it would be contradicted:
454 char nak_rep[] = { DINIT_RP_NAK };
455 if (! queue_packet(nak_rep, 1)) return false;
456 rbuf.consume(pkt_size);
462 // Check for creation of circular dependency chain
463 std::unordered_set<service_record *> dep_marks;
464 std::vector<service_record *> dep_queue;
465 dep_queue.push_back(to_service);
466 while (! dep_queue.empty()) {
467 service_record * sr = dep_queue.back();
468 dep_queue.pop_back();
469 // iterate deps; if dep == from, abort; otherwise add to set/queue
470 // (only add to queue if not already in set)
471 for (auto &dep : sr->get_dependencies()) {
472 service_record * dep_to = dep.get_to();
473 if (dep_to == from_service) {
474 // fail, circular dependency!
475 char nak_rep[] = { DINIT_RP_NAK };
476 if (! queue_packet(nak_rep, 1)) return false;
477 rbuf.consume(pkt_size);
481 if (dep_marks.insert(dep_to).second) {
482 dep_queue.push_back(dep_to);
489 bool dep_exists = false;
490 service_dep * dep_record = nullptr;
492 // Prevent creation of duplicate dependency:
493 for (auto &dep : from_service->get_dependencies()) {
494 service_record * dep_to = dep.get_to();
495 if (dep_to == to_service && dep.dep_type == dep_type) {
496 // Dependency already exists
504 // Create dependency:
505 dep_record = &(from_service->add_dep(to_service, dep_type));
506 services->process_queues();
509 if (do_enable && contains({service_state_t::STARTED, service_state_t::STARTING},
510 from_service->get_state())) {
511 // The dependency record is activated: mark it as holding acquisition of the dependency, and start
513 if (!services->is_shutting_down()) {
514 dep_record->get_from()->start_dep(*dep_record);
515 services->process_queues();
519 char ack_rep[] = { DINIT_RP_ACK };
520 if (! queue_packet(ack_rep, 1)) return false;
521 rbuf.consume(pkt_size);
526 bool control_conn_t::rm_service_dep()
528 // 1 byte packet type
529 // 1 byte dependency type
533 constexpr int pkt_size = 2 + sizeof(handle_t) * 2;
535 if (rbuf.get_length() < pkt_size) {
540 handle_t from_handle;
542 rbuf.extract((char *) &from_handle, 2, sizeof(from_handle));
543 rbuf.extract((char *) &to_handle, 2 + sizeof(from_handle), sizeof(to_handle));
545 service_record *from_service = find_service_for_key(from_handle);
546 service_record *to_service = find_service_for_key(to_handle);
547 if (from_service == nullptr || to_service == nullptr || from_service == to_service) {
548 // Service handle is bad
549 char badreq_rep[] = { DINIT_RP_BADREQ };
550 if (! queue_packet(badreq_rep, 1)) return false;
551 bad_conn_close = true;
552 iob.set_watches(OUT_EVENTS);
556 // Check dependency type is valid:
557 int dep_type_int = rbuf[1];
558 if (! contains({dependency_type::MILESTONE, dependency_type::REGULAR,
559 dependency_type::WAITS_FOR}, dep_type_int)) {
560 char badreqRep[] = { DINIT_RP_BADREQ };
561 if (! queue_packet(badreqRep, 1)) return false;
562 bad_conn_close = true;
563 iob.set_watches(OUT_EVENTS);
565 dependency_type dep_type = static_cast<dependency_type>(dep_type_int);
567 // Remove dependency:
568 from_service->rm_dep(to_service, dep_type);
569 services->process_queues();
571 char ack_rep[] = { DINIT_RP_ACK };
572 if (! queue_packet(ack_rep, 1)) return false;
573 rbuf.consume(pkt_size);
578 bool control_conn_t::query_load_mech()
583 if (services->get_set_type_id() == SSET_TYPE_DIRLOAD) {
584 dirload_service_set *dss = static_cast<dirload_service_set *>(services);
585 std::vector<char> reppkt;
586 reppkt.resize(2 + sizeof(uint32_t) * 2); // packet type, loader type, packet size, # dirs
587 reppkt[0] = DINIT_RP_LOADER_MECH;
588 reppkt[1] = SSET_TYPE_DIRLOAD;
590 // Number of directories in load path:
591 uint32_t sdirs = dss->get_service_dir_count();
592 std::memcpy(reppkt.data() + 2 + sizeof(uint32_t), &sdirs, sizeof(sdirs));
594 // Our current working directory, which above are relative to:
595 // leave sizeof(uint32_t) for size, which we'll fill in afterwards:
596 std::size_t curpos = reppkt.size() + sizeof(uint32_t);
598 uint32_t try_path_size = PATH_MAX;
600 uint32_t try_path_size = 2048;
604 std::size_t total_size = curpos + std::size_t(try_path_size);
605 reppkt.resize(total_size);
606 if (total_size < curpos) {
608 char ack_rep[] = { DINIT_RP_NAK };
609 if (! queue_packet(ack_rep, 1)) return false;
612 wd = getcwd(reppkt.data() + curpos, try_path_size);
613 if (wd != nullptr) break;
615 try_path_size *= uint32_t(2u);
616 if (try_path_size == 0) {
618 char ack_rep[] = { DINIT_RP_NAK };
619 if (! queue_packet(ack_rep, 1)) return false;
624 uint32_t wd_len = std::strlen(reppkt.data() + curpos);
625 reppkt.resize(curpos + std::size_t(wd_len));
626 std::memcpy(reppkt.data() + curpos - sizeof(uint32_t), &wd_len, sizeof(wd_len));
628 // Each directory in the load path:
629 for (int i = 0; uint32_t(i) < sdirs; i++) {
630 const char *sdir = dss->get_service_dir(i);
631 uint32_t dlen = std::strlen(sdir);
632 auto cursize = reppkt.size();
633 reppkt.resize(cursize + sizeof(dlen) + dlen);
634 std::memcpy(reppkt.data() + cursize, &dlen, sizeof(dlen));
635 std::memcpy(reppkt.data() + cursize + sizeof(dlen), sdir, dlen);
638 // Total packet size:
639 uint32_t fsize = reppkt.size();
640 std::memcpy(reppkt.data() + 2, &fsize, sizeof(fsize));
642 if (! queue_packet(std::move(reppkt))) return false;
646 // If we don't know how to deal with the service set type, send a NAK reply:
647 char ack_rep[] = { DINIT_RP_NAK };
648 if (! queue_packet(ack_rep, 1)) return false;
653 control_conn_t::handle_t control_conn_t::allocate_service_handle(service_record *record)
655 // Try to find a unique handle (integer) in a single pass. Since the map is ordered, we can search until
656 // we find a gap in the handle values.
657 handle_t candidate = 0;
658 for (auto p : key_service_map) {
659 if (p.first == candidate) ++candidate;
663 bool is_unique = (service_key_map.find(record) == service_key_map.end());
665 // The following operations perform allocation (can throw std::bad_alloc). If an exception occurs we
666 // must undo any previous actions:
668 record->add_listener(this);
672 key_service_map[candidate] = record;
673 service_key_map.insert(std::make_pair(record, candidate));
677 record->remove_listener(this);
680 key_service_map.erase(candidate);
686 bool control_conn_t::queue_packet(const char *pkt, unsigned size) noexcept
688 int in_flag = bad_conn_close ? 0 : IN_EVENTS;
689 bool was_empty = outbuf.empty();
691 // If the queue is empty, we can try to write the packet out now rather than queueing it.
692 // If the write is unsuccessful or partial, we queue the remainder.
694 int wr = bp_sys::write(iob.get_watched_fd(), pkt, size);
696 if (errno == EPIPE) {
699 if (errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR) {
700 log(loglevel_t::WARN, "Error writing to control connection: ", strerror(errno));
703 // EAGAIN etc: fall through to below
706 if ((unsigned)wr == size) {
708 iob.set_watches(in_flag);
716 // Create a vector out of the (remaining part of the) packet:
718 outbuf.emplace_back(pkt, pkt + size);
719 iob.set_watches(in_flag | OUT_EVENTS);
722 catch (std::bad_alloc &baexc) {
723 // Mark the connection bad, and stop reading further requests
724 bad_conn_close = true;
727 // We can't send out-of-memory response as we already wrote as much as we
728 // could above. Neither can we later send the response since we have currently
729 // sent an incomplete packet. All we can do is close the connection.
733 iob.set_watches(OUT_EVENTS);
739 // This queue_packet method is frustratingly similar to the one above, but the subtle differences
740 // make them extraordinary difficult to combine into a single method.
741 bool control_conn_t::queue_packet(std::vector<char> &&pkt) noexcept
743 int in_flag = bad_conn_close ? 0 : IN_EVENTS;
744 bool was_empty = outbuf.empty();
748 // We can try sending the packet immediately:
749 int wr = bp_sys::write(iob.get_watched_fd(), pkt.data(), pkt.size());
751 if (errno == EPIPE) {
754 if (errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR) {
755 log(loglevel_t::WARN, "Error writing to control connection: ", strerror(errno));
758 // EAGAIN etc: fall through to below
761 if ((unsigned)wr == pkt.size()) {
763 iob.set_watches(in_flag);
771 outbuf.emplace_back(pkt);
772 iob.set_watches(in_flag | OUT_EVENTS);
775 catch (std::bad_alloc &baexc) {
776 // Mark the connection bad, and stop reading further requests
777 bad_conn_close = true;
780 // We can't send out-of-memory response as we already wrote as much as we
781 // could above. Neither can we later send the response since we have currently
782 // sent an incomplete packet. All we can do is close the connection.
786 iob.set_watches(OUT_EVENTS);
792 bool control_conn_t::data_ready() noexcept
794 int fd = iob.get_watched_fd();
796 int r = rbuf.fill(fd);
798 // Note file descriptor is non-blocking
800 if (errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR) {
801 log(loglevel_t::WARN, "Error writing to control connection: ", strerror(errno));
812 if (rbuf.get_length() >= chklen) {
814 return !process_packet();
816 catch (std::bad_alloc &baexc) {
821 else if (rbuf.get_length() == 1024) {
823 log(loglevel_t::WARN, "Received too-large control package; dropping connection");
824 bad_conn_close = true;
825 iob.set_watches(OUT_EVENTS);
828 int out_flags = (bad_conn_close || !outbuf.empty()) ? OUT_EVENTS : 0;
829 iob.set_watches(IN_EVENTS | out_flags);
835 bool control_conn_t::send_data() noexcept
837 if (outbuf.empty() && bad_conn_close) {
840 char oomBuf[] = { DINIT_RP_OOM };
841 bp_sys::write(iob.get_watched_fd(), oomBuf, 1);
846 vector<char> & pkt = outbuf.front();
847 char *data = pkt.data();
848 int written = bp_sys::write(iob.get_watched_fd(), data + outpkt_index, pkt.size() - outpkt_index);
850 if (errno == EPIPE) {
854 else if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) {
855 // spurious readiness notification?
858 log(loglevel_t::ERROR, "Error writing to control connection: ", strerror(errno));
864 outpkt_index += written;
865 if (outpkt_index == pkt.size()) {
866 // We've finished this packet, move on to the next:
869 if (outbuf.empty() && ! oom_close) {
870 if (! bad_conn_close) {
871 iob.set_watches(IN_EVENTS);
882 control_conn_t::~control_conn_t() noexcept
884 bp_sys::close(iob.get_watched_fd());
885 iob.deregister(loop);
887 // Clear service listeners
888 for (auto p : service_key_map) {
889 p.first->remove_listener(this);
892 active_control_conns--;