2 #include <unordered_set>
7 // Server-side control protocol implementation. This implements the functionality that allows
8 // clients (such as dinitctl) to query service state and issue commands to control services.
11 constexpr auto OUT_EVENTS = dasynq::OUT_EVENTS;
12 constexpr auto IN_EVENTS = dasynq::IN_EVENTS;
14 // Control protocol minimum compatible version and current version:
15 constexpr uint16_t min_compat_version = 1;
16 constexpr uint16_t cp_version = 1;
18 // check for value in a set
19 template <typename T, int N>
20 inline bool contains(const T (&v)[N], int i)
22 return std::find_if(std::begin(v), std::end(v),
23 [=](T p){ return i == static_cast<int>(p); }) != std::end(v);
27 bool control_conn_t::process_packet()
31 // Note that where we call queue_packet, we must generally check the return value. If it
32 // returns false it has either deleted the connection or marked it for deletion; we
33 // shouldn't touch instance members after that point.
35 int pktType = rbuf[0];
36 if (pktType == DINIT_CP_QUERYVERSION) {
38 // DINIT_RP_CVERSION, (2 byte) minimum compatible version, (2 byte) actual version
39 char replyBuf[] = { DINIT_RP_CPVERSION, 0, 0, 0, 0 };
40 memcpy(replyBuf + 1, &min_compat_version, 2);
41 memcpy(replyBuf + 3, &cp_version, 2);
42 if (! queue_packet(replyBuf, sizeof(replyBuf))) return false;
46 if (pktType == DINIT_CP_FINDSERVICE || pktType == DINIT_CP_LOADSERVICE) {
47 return process_find_load(pktType);
49 if (pktType == DINIT_CP_STARTSERVICE || pktType == DINIT_CP_STOPSERVICE
50 || pktType == DINIT_CP_WAKESERVICE || pktType == DINIT_CP_RELEASESERVICE) {
51 return process_start_stop(pktType);
53 if (pktType == DINIT_CP_UNPINSERVICE) {
54 return process_unpin_service();
56 if (pktType == DINIT_CP_UNLOADSERVICE) {
57 return process_unload_service();
59 if (pktType == DINIT_CP_SHUTDOWN) {
61 if (rbuf.get_length() < 2) {
66 if (contains({shutdown_type_t::CONTINUE, 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]);
70 services->stop_all_services(sd_type);
71 char ackBuf[] = { DINIT_RP_ACK };
72 if (! queue_packet(ackBuf, 1)) return false;
74 // Clear the packet from the buffer
80 // (otherwise fall through to below).
82 if (pktType == DINIT_CP_LISTSERVICES) {
83 return list_services();
85 if (pktType == DINIT_CP_ADD_DEP) {
86 return add_service_dep();
88 if (pktType == DINIT_CP_REM_DEP) {
89 return rm_service_dep();
91 if (pktType == DINIT_CP_QUERY_LOAD_MECH) {
92 return query_load_mech();
95 // Unrecognized: give error response
96 char outbuf[] = { DINIT_RP_BADREQ };
97 if (! queue_packet(outbuf, 1)) return false;
98 bad_conn_close = true;
99 iob.set_watches(OUT_EVENTS);
103 bool control_conn_t::process_find_load(int pktType)
107 constexpr int pkt_size = 4;
109 if (rbuf.get_length() < pkt_size) {
115 rbuf.extract((char *)&svcSize, 1, 2);
116 chklen = svcSize + 3; // packet type + (2 byte) length + service name
117 if (svcSize <= 0 || chklen > 1024) {
118 // Queue error response / mark connection bad
119 char badreqRep[] = { DINIT_RP_BADREQ };
120 if (! queue_packet(badreqRep, 1)) return false;
121 bad_conn_close = true;
122 iob.set_watches(OUT_EVENTS);
126 if (rbuf.get_length() < chklen) {
127 // packet not complete yet; read more
131 service_record * record = nullptr;
133 string serviceName = rbuf.extract_string(3, svcSize);
135 if (pktType == DINIT_CP_LOADSERVICE) {
138 record = services->load_service(serviceName.c_str());
140 catch (service_load_exc &slexc) {
141 log(loglevel_t::ERROR, "Could not load service ", slexc.serviceName, ": ", slexc.excDescription);
146 record = services->find_service(serviceName.c_str());
149 if (record != nullptr) {
150 // Allocate a service handle
151 handle_t handle = allocate_service_handle(record);
152 std::vector<char> rp_buf;
154 rp_buf.push_back(DINIT_RP_SERVICERECORD);
155 rp_buf.push_back(static_cast<char>(record->get_state()));
156 for (int i = 0; i < (int) sizeof(handle); i++) {
157 rp_buf.push_back(*(((char *) &handle) + i));
159 rp_buf.push_back(static_cast<char>(record->get_target_state()));
160 if (! queue_packet(std::move(rp_buf))) return false;
163 std::vector<char> rp_buf = { DINIT_RP_NOSERVICE };
164 if (! queue_packet(std::move(rp_buf))) return false;
167 // Clear the packet from the buffer
168 rbuf.consume(chklen);
173 bool control_conn_t::process_start_stop(int pktType)
177 constexpr int pkt_size = 2 + sizeof(handle_t);
179 if (rbuf.get_length() < pkt_size) {
184 // 1 byte: packet type
185 // 1 byte: pin in requested state (0 = no pin, 1 = pin)
186 // 4 bytes: service handle
188 bool do_pin = (rbuf[1] == 1);
190 rbuf.extract((char *) &handle, 2, sizeof(handle));
192 service_record *service = find_service_for_key(handle);
193 if (service == nullptr) {
194 // Service handle is bad
195 char badreqRep[] = { DINIT_RP_BADREQ };
196 if (! queue_packet(badreqRep, 1)) return false;
197 bad_conn_close = true;
198 iob.set_watches(OUT_EVENTS);
202 bool already_there = false;
205 case DINIT_CP_STARTSERVICE:
206 // start service, mark as required
207 if (do_pin) service->pin_start();
209 services->process_queues();
210 already_there = service->get_state() == service_state_t::STARTED;
212 case DINIT_CP_STOPSERVICE:
213 // force service to stop
214 if (do_pin) service->pin_stop();
216 service->forced_stop();
217 services->process_queues();
218 already_there = service->get_state() == service_state_t::STOPPED;
220 case DINIT_CP_WAKESERVICE:
221 // re-start a stopped service (do not mark as required)
222 if (do_pin) service->pin_start();
223 service->start(false);
224 services->process_queues();
225 already_there = service->get_state() == service_state_t::STARTED;
227 case DINIT_CP_RELEASESERVICE:
228 // remove required mark, stop if not required by dependents
229 if (do_pin) service->pin_stop();
230 service->stop(false);
231 services->process_queues();
232 already_there = service->get_state() == service_state_t::STOPPED;
236 char ack_buf[] = { (char)(already_there ? DINIT_RP_ALREADYSS : DINIT_RP_ACK) };
238 if (! queue_packet(ack_buf, 1)) return false;
241 // Clear the packet from the buffer
242 rbuf.consume(pkt_size);
247 bool control_conn_t::process_unpin_service()
251 constexpr int pkt_size = 1 + sizeof(handle_t);
253 if (rbuf.get_length() < pkt_size) {
258 // 1 byte: packet type
259 // 4 bytes: service handle
262 rbuf.extract((char *) &handle, 1, sizeof(handle));
264 service_record *service = find_service_for_key(handle);
265 if (service == nullptr) {
266 // Service handle is bad
267 char badreqRep[] = { DINIT_RP_BADREQ };
268 if (! queue_packet(badreqRep, 1)) return false;
269 bad_conn_close = true;
270 iob.set_watches(OUT_EVENTS);
275 services->process_queues();
276 char ack_buf[] = { (char) DINIT_RP_ACK };
277 if (! queue_packet(ack_buf, 1)) return false;
279 // Clear the packet from the buffer
280 rbuf.consume(pkt_size);
285 bool control_conn_t::process_unload_service()
289 constexpr int pkt_size = 1 + sizeof(handle_t);
291 if (rbuf.get_length() < pkt_size) {
296 // 1 byte: packet type
297 // 4 bytes: service handle
300 rbuf.extract((char *) &handle, 1, sizeof(handle));
302 service_record *service = find_service_for_key(handle);
303 if (service == nullptr) {
304 // Service handle is bad
305 char badreq_rep[] = { DINIT_RP_BADREQ };
306 if (! queue_packet(badreq_rep, 1)) return false;
307 bad_conn_close = true;
308 iob.set_watches(OUT_EVENTS);
312 if (! service->has_lone_ref() || service->get_state() != service_state_t::STOPPED) {
313 // Cannot unload: has other references
314 char nak_rep[] = { DINIT_RP_NAK };
315 if (! queue_packet(nak_rep, 1)) return false;
319 service->prepare_for_unload();
320 services->remove_service(service);
324 service_key_map.erase(service);
325 key_service_map.erase(handle);
328 char ack_buf[] = { (char) DINIT_RP_ACK };
329 if (! queue_packet(ack_buf, 1)) return false;
332 // Clear the packet from the buffer
333 rbuf.consume(pkt_size);
338 bool control_conn_t::list_services()
340 rbuf.consume(1); // clear request packet
344 auto slist = services->list_services();
345 for (auto sptr : slist) {
346 std::vector<char> pkt_buf;
348 int hdrsize = 8 + std::max(sizeof(int), sizeof(pid_t));
350 const std::string &name = sptr->get_name();
351 int nameLen = std::min((size_t)256, name.length());
352 pkt_buf.resize(hdrsize + nameLen);
354 pkt_buf[0] = DINIT_RP_SVCINFO;
355 pkt_buf[1] = nameLen;
356 pkt_buf[2] = static_cast<char>(sptr->get_state());
357 pkt_buf[3] = static_cast<char>(sptr->get_target_state());
359 char b0 = sptr->is_waiting_for_console() ? 1 : 0;
360 b0 |= sptr->has_console() ? 2 : 0;
361 b0 |= sptr->was_start_skipped() ? 4 : 0;
363 pkt_buf[5] = static_cast<char>(sptr->get_stop_reason());
365 pkt_buf[6] = 0; // reserved
368 // Next: either the exit status, or the process ID
369 if (sptr->get_state() != service_state_t::STOPPED) {
370 pid_t proc_pid = sptr->get_pid();
371 memcpy(pkt_buf.data() + 8, &proc_pid, sizeof(proc_pid));
374 int exit_status = sptr->get_exit_status();
375 memcpy(pkt_buf.data() + 8, &exit_status, sizeof(exit_status));
378 for (int i = 0; i < nameLen; i++) {
379 pkt_buf[hdrsize+i] = name[i];
382 if (! queue_packet(std::move(pkt_buf))) return false;
385 char ack_buf[] = { (char) DINIT_RP_LISTDONE };
386 if (! queue_packet(ack_buf, 1)) return false;
390 catch (std::bad_alloc &exc)
397 bool control_conn_t::add_service_dep()
399 // 1 byte packet type
400 // 1 byte dependency type
404 constexpr int pkt_size = 2 + sizeof(handle_t) * 2;
406 if (rbuf.get_length() < pkt_size) {
411 handle_t from_handle;
413 rbuf.extract((char *) &from_handle, 2, sizeof(from_handle));
414 rbuf.extract((char *) &to_handle, 2 + sizeof(from_handle), sizeof(to_handle));
416 service_record *from_service = find_service_for_key(from_handle);
417 service_record *to_service = find_service_for_key(to_handle);
418 if (from_service == nullptr || to_service == nullptr || from_service == to_service) {
419 // Service handle is bad
420 char badreq_rep[] = { DINIT_RP_BADREQ };
421 if (! queue_packet(badreq_rep, 1)) return false;
422 bad_conn_close = true;
423 iob.set_watches(OUT_EVENTS);
427 // Check dependency type is valid:
428 int dep_type_int = rbuf[1];
429 if (! contains({(int)dependency_type::MILESTONE, (int)dependency_type::REGULAR,
430 (int)dependency_type::WAITS_FOR}, dep_type_int)) {
431 char badreqRep[] = { DINIT_RP_BADREQ };
432 if (! queue_packet(badreqRep, 1)) return false;
433 bad_conn_close = true;
434 iob.set_watches(OUT_EVENTS);
436 dependency_type dep_type = static_cast<dependency_type>(dep_type_int);
438 // Check current service states are valid for given dep type
439 if (dep_type == dependency_type::REGULAR) {
440 if (from_service->get_state() != service_state_t::STOPPED &&
441 to_service->get_state() != service_state_t::STARTED) {
442 // Cannot create dependency now since it would be contradicted:
443 char nak_rep[] = { DINIT_RP_NAK };
444 if (! queue_packet(nak_rep, 1)) return false;
445 rbuf.consume(pkt_size);
451 // Check for creation of circular dependency chain
452 std::unordered_set<service_record *> dep_marks;
453 std::vector<service_record *> dep_queue;
454 dep_queue.push_back(to_service);
455 while (! dep_queue.empty()) {
456 service_record * sr = dep_queue.back();
457 dep_queue.pop_back();
458 // iterate deps; if dep == from, abort; otherwise add to set/queue
459 // (only add to queue if not already in set)
460 for (auto &dep : sr->get_dependencies()) {
461 service_record * dep_to = dep.get_to();
462 if (dep_to == from_service) {
463 // fail, circular dependency!
464 char nak_rep[] = { DINIT_RP_NAK };
465 if (! queue_packet(nak_rep, 1)) return false;
466 rbuf.consume(pkt_size);
470 if (dep_marks.insert(dep_to).second) {
471 dep_queue.push_back(dep_to);
478 // Prevent creation of duplicate dependency:
479 for (auto &dep : from_service->get_dependencies()) {
480 service_record * dep_to = dep.get_to();
481 if (dep_to == to_service && dep.dep_type == dep_type) {
482 // Dependency already exists: return success
483 char ack_rep[] = { DINIT_RP_ACK };
484 if (! queue_packet(ack_rep, 1)) return false;
485 rbuf.consume(pkt_size);
491 // Create dependency:
492 from_service->add_dep(to_service, dep_type);
493 services->process_queues();
495 char ack_rep[] = { DINIT_RP_ACK };
496 if (! queue_packet(ack_rep, 1)) return false;
497 rbuf.consume(pkt_size);
502 bool control_conn_t::rm_service_dep()
504 // 1 byte packet type
505 // 1 byte dependency type
509 constexpr int pkt_size = 2 + sizeof(handle_t) * 2;
511 if (rbuf.get_length() < pkt_size) {
516 handle_t from_handle;
518 rbuf.extract((char *) &from_handle, 2, sizeof(from_handle));
519 rbuf.extract((char *) &to_handle, 2 + sizeof(from_handle), sizeof(to_handle));
521 service_record *from_service = find_service_for_key(from_handle);
522 service_record *to_service = find_service_for_key(to_handle);
523 if (from_service == nullptr || to_service == nullptr || from_service == to_service) {
524 // Service handle is bad
525 char badreq_rep[] = { DINIT_RP_BADREQ };
526 if (! queue_packet(badreq_rep, 1)) return false;
527 bad_conn_close = true;
528 iob.set_watches(OUT_EVENTS);
532 // Check dependency type is valid:
533 int dep_type_int = rbuf[1];
534 if (! contains({(int)dependency_type::MILESTONE, (int)dependency_type::REGULAR,
535 (int)dependency_type::WAITS_FOR}, dep_type_int)) {
536 char badreqRep[] = { DINIT_RP_BADREQ };
537 if (! queue_packet(badreqRep, 1)) return false;
538 bad_conn_close = true;
539 iob.set_watches(OUT_EVENTS);
541 dependency_type dep_type = static_cast<dependency_type>(dep_type_int);
543 // Remove dependency:
544 from_service->rm_dep(to_service, dep_type);
545 services->process_queues();
547 char ack_rep[] = { DINIT_RP_ACK };
548 if (! queue_packet(ack_rep, 1)) return false;
549 rbuf.consume(pkt_size);
554 bool control_conn_t::query_load_mech()
556 if (services->get_set_type_id() == SSET_TYPE_DIRLOAD) {
557 dirload_service_set *dss = static_cast<dirload_service_set *>(services);
558 std::vector<char> reppkt;
559 reppkt.resize(2 + sizeof(uint32_t) * 2); // packet type, loader type, packet size, # dirs
560 reppkt[0] = DINIT_RP_LOADER_MECH;
561 reppkt[1] = SSET_TYPE_DIRLOAD;
563 // Number of directories in load path:
564 uint32_t sdirs = dss->get_service_dir_count();
565 std::memcpy(reppkt.data() + 2 + sizeof(uint32_t), &sdirs, sizeof(sdirs));
567 for (int i = 0; i < sdirs; i++) {
568 const char *sdir = dss->get_service_dir(i);
569 uint32_t dlen = std::strlen(sdir);
570 auto cursize = reppkt.size();
571 reppkt.resize(cursize + sizeof(dlen) + dlen);
572 std::memcpy(reppkt.data() + cursize, &dlen, sizeof(dlen));
573 std::memcpy(reppkt.data() + cursize + sizeof(dlen), sdir, dlen);
576 // Total packet size:
577 uint32_t fsize = reppkt.size();
578 std::memcpy(reppkt.data() + 2, &fsize, sizeof(fsize));
580 if (! queue_packet(std::move(reppkt))) return false;
586 // If we don't know how to deal with the service set type, send a NAK reply:
587 char ack_rep[] = { DINIT_RP_NAK };
588 if (! queue_packet(ack_rep, 1)) return false;
595 control_conn_t::handle_t control_conn_t::allocate_service_handle(service_record *record)
597 // Try to find a unique handle (integer) in a single pass. Since the map is ordered, we can search until
598 // we find a gap in the handle values.
599 handle_t candidate = 0;
600 for (auto p : key_service_map) {
601 if (p.first == candidate) candidate++;
605 bool is_unique = (service_key_map.find(record) == service_key_map.end());
607 // The following operations perform allocation (can throw std::bad_alloc). If an exception occurs we
608 // must undo any previous actions:
610 record->add_listener(this);
614 key_service_map[candidate] = record;
615 service_key_map.insert(std::make_pair(record, candidate));
619 record->remove_listener(this);
622 key_service_map.erase(candidate);
628 bool control_conn_t::queue_packet(const char *pkt, unsigned size) noexcept
630 int in_flag = bad_conn_close ? 0 : IN_EVENTS;
631 bool was_empty = outbuf.empty();
633 // If the queue is empty, we can try to write the packet out now rather than queueing it.
634 // If the write is unsuccessful or partial, we queue the remainder.
636 int wr = bp_sys::write(iob.get_watched_fd(), pkt, size);
638 if (errno == EPIPE) {
641 if (errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR) {
642 log(loglevel_t::WARN, "Error writing to control connection: ", strerror(errno));
645 // EAGAIN etc: fall through to below
648 if ((unsigned)wr == size) {
650 iob.set_watches(in_flag);
658 // Create a vector out of the (remaining part of the) packet:
660 outbuf.emplace_back(pkt, pkt + size);
661 iob.set_watches(in_flag | OUT_EVENTS);
664 catch (std::bad_alloc &baexc) {
665 // Mark the connection bad, and stop reading further requests
666 bad_conn_close = true;
669 // We can't send out-of-memory response as we already wrote as much as we
670 // could above. Neither can we later send the response since we have currently
671 // sent an incomplete packet. All we can do is close the connection.
675 iob.set_watches(OUT_EVENTS);
681 // This queue_packet method is frustratingly similar to the one above, but the subtle differences
682 // make them extraordinary difficult to combine into a single method.
683 bool control_conn_t::queue_packet(std::vector<char> &&pkt) noexcept
685 int in_flag = bad_conn_close ? 0 : IN_EVENTS;
686 bool was_empty = outbuf.empty();
690 // We can try sending the packet immediately:
691 int wr = bp_sys::write(iob.get_watched_fd(), pkt.data(), pkt.size());
693 if (errno == EPIPE) {
696 if (errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR) {
697 log(loglevel_t::WARN, "Error writing to control connection: ", strerror(errno));
700 // EAGAIN etc: fall through to below
703 if ((unsigned)wr == pkt.size()) {
705 iob.set_watches(in_flag);
713 outbuf.emplace_back(pkt);
714 iob.set_watches(in_flag | OUT_EVENTS);
717 catch (std::bad_alloc &baexc) {
718 // Mark the connection bad, and stop reading further requests
719 bad_conn_close = true;
722 // We can't send out-of-memory response as we already wrote as much as we
723 // could above. Neither can we later send the response since we have currently
724 // sent an incomplete packet. All we can do is close the connection.
728 iob.set_watches(OUT_EVENTS);
734 bool control_conn_t::rollback_complete() noexcept
736 char ackBuf[2] = { DINIT_ROLLBACK_COMPLETED, 2 };
737 return queue_packet(ackBuf, 2);
740 bool control_conn_t::data_ready() noexcept
742 int fd = iob.get_watched_fd();
744 int r = rbuf.fill(fd);
746 // Note file descriptor is non-blocking
748 if (errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR) {
749 log(loglevel_t::WARN, "Error writing to control connection: ", strerror(errno));
760 if (rbuf.get_length() >= chklen) {
762 return !process_packet();
764 catch (std::bad_alloc &baexc) {
769 else if (rbuf.get_length() == 1024) {
771 log(loglevel_t::WARN, "Received too-large control package; dropping connection");
772 bad_conn_close = true;
773 iob.set_watches(OUT_EVENTS);
776 int out_flags = (bad_conn_close || !outbuf.empty()) ? OUT_EVENTS : 0;
777 iob.set_watches(IN_EVENTS | out_flags);
783 bool control_conn_t::send_data() noexcept
785 if (outbuf.empty() && bad_conn_close) {
788 char oomBuf[] = { DINIT_RP_OOM };
789 bp_sys::write(iob.get_watched_fd(), oomBuf, 1);
794 vector<char> & pkt = outbuf.front();
795 char *data = pkt.data();
796 int written = bp_sys::write(iob.get_watched_fd(), data + outpkt_index, pkt.size() - outpkt_index);
798 if (errno == EPIPE) {
802 else if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) {
803 // spurious readiness notification?
806 log(loglevel_t::ERROR, "Error writing to control connection: ", strerror(errno));
812 outpkt_index += written;
813 if (outpkt_index == pkt.size()) {
814 // We've finished this packet, move on to the next:
817 if (outbuf.empty() && ! oom_close) {
818 if (! bad_conn_close) {
819 iob.set_watches(IN_EVENTS);
830 control_conn_t::~control_conn_t() noexcept
832 bp_sys::close(iob.get_watched_fd());
833 iob.deregister(loop);
835 // Clear service listeners
836 for (auto p : service_key_map) {
837 p.first->remove_listener(this);
840 active_control_conns--;