7 #include <system_error>
11 #include <sys/types.h>
14 #include <sys/socket.h>
20 #include "control-cmds.h"
21 #include "service-constants.h"
23 #include "dinit-client.h"
24 #include "load-service.h"
25 #include "dinit-util.h"
28 // dinitctl: utility to control the Dinit daemon, including starting and stopping of services.
30 // This utility communicates with the dinit daemon via a unix stream socket (as specified in
31 // SYSCONTROLSOCKET, or $HOME/.dinitctl).
33 static constexpr uint16_t min_cp_version = 1;
34 static constexpr uint16_t max_cp_version = 1;
38 static int issue_load_service(int socknum, const char *service_name, bool find_only = false);
39 static int check_load_reply(int socknum, cpbuffer_t &, handle_t *handle_p, service_state_t *state_p);
40 static int start_stop_service(int socknum, cpbuffer_t &, const char *service_name, command_t command,
41 bool do_pin, bool do_force, bool wait_for_service, bool verbose);
42 static int unpin_service(int socknum, cpbuffer_t &, const char *service_name, bool verbose);
43 static int unload_service(int socknum, cpbuffer_t &, const char *service_name);
44 static int reload_service(int socknum, cpbuffer_t &, const char *service_name);
45 static int list_services(int socknum, cpbuffer_t &);
46 static int shutdown_dinit(int soclknum, cpbuffer_t &);
47 static int add_remove_dependency(int socknum, cpbuffer_t &rbuffer, bool add, const char *service_from,
48 const char *service_to, dependency_type dep_type);
49 static int enable_disable_service(int socknum, cpbuffer_t &rbuffer, const char *from, const char *to,
52 static const char * describeState(bool stopped)
54 return stopped ? "stopped" : "started";
57 static const char * describeVerb(bool stop)
59 return stop ? "stop" : "start";
62 enum class command_t {
82 int main(int argc, char **argv)
86 bool show_help = argc < 2;
87 const char *service_name = nullptr;
88 const char *to_service_name = nullptr;
89 dependency_type dep_type;
90 bool dep_type_set = false;
92 std::string control_socket_str;
93 const char * control_socket_path = nullptr;
96 bool user_dinit = (getuid() != 0); // communicate with user daemon
97 bool wait_for_service = true;
99 bool do_force = false;
101 command_t command = command_t::NONE;
103 for (int i = 1; i < argc; i++) {
104 if (argv[i][0] == '-') {
105 if (strcmp(argv[i], "--help") == 0) {
109 else if (strcmp(argv[i], "--no-wait") == 0) {
110 wait_for_service = false;
112 else if (strcmp(argv[i], "--quiet") == 0) {
115 else if (strcmp(argv[i], "--system") == 0 || strcmp(argv[i], "-s") == 0) {
118 else if (strcmp(argv[i], "--user") == 0 || strcmp(argv[i], "-u") == 0) {
121 else if (strcmp(argv[i], "--pin") == 0) {
124 else if (strcmp(argv[i], "--socket-path") == 0 || strcmp(argv[i], "-p") == 0) {
127 cerr << "dinitctl: --socket-path/-p should be followed by socket path" << std::endl;
130 control_socket_str = argv[i];
132 else if ((command == command_t::ENABLE_SERVICE || command == command_t::DISABLE_SERVICE)
133 && strcmp(argv[i], "--from") == 0) {
136 cerr << "dinitctl: --from should be followed by a service name" << std::endl;
139 service_name = argv[i];
141 else if ((command == command_t::STOP_SERVICE || command == command_t::RESTART_SERVICE)
142 && (strcmp(argv[i], "--force") == 0 || strcmp(argv[i], "-f") == 0)) {
146 cerr << "dinitctl: unrecognized/invalid option: " << argv[i] << " (use --help for help)\n";
150 else if (command == command_t::NONE) {
151 if (strcmp(argv[i], "start") == 0) {
152 command = command_t::START_SERVICE;
154 else if (strcmp(argv[i], "wake") == 0) {
155 command = command_t::WAKE_SERVICE;
157 else if (strcmp(argv[i], "stop") == 0) {
158 command = command_t::STOP_SERVICE;
160 else if (strcmp(argv[i], "restart") == 0) {
161 command = command_t::RESTART_SERVICE;
163 else if (strcmp(argv[i], "release") == 0) {
164 command = command_t::RELEASE_SERVICE;
166 else if (strcmp(argv[i], "unpin") == 0) {
167 command = command_t::UNPIN_SERVICE;
169 else if (strcmp(argv[i], "unload") == 0) {
170 command = command_t::UNLOAD_SERVICE;
172 else if (strcmp(argv[i], "reload") == 0) {
173 command = command_t::RELOAD_SERVICE;
175 else if (strcmp(argv[i], "list") == 0) {
176 command = command_t::LIST_SERVICES;
178 else if (strcmp(argv[i], "shutdown") == 0) {
179 command = command_t::SHUTDOWN;
181 else if (strcmp(argv[i], "add-dep") == 0) {
182 command = command_t::ADD_DEPENDENCY;
184 else if (strcmp(argv[i], "rm-dep") == 0) {
185 command = command_t::RM_DEPENDENCY;
187 else if (strcmp(argv[i], "enable") == 0) {
188 command = command_t::ENABLE_SERVICE;
190 else if (strcmp(argv[i], "disable") == 0) {
191 command = command_t::DISABLE_SERVICE;
194 cerr << "dinitctl: unrecognized command: " << argv[i] << " (use --help for help)\n";
199 // service name / other non-option
200 if (command == command_t::ADD_DEPENDENCY || command == command_t::RM_DEPENDENCY) {
201 if (! dep_type_set) {
202 if (strcmp(argv[i], "regular") == 0) {
203 dep_type = dependency_type::REGULAR;
205 else if (strcmp(argv[i], "milestone") == 0) {
206 dep_type = dependency_type::MILESTONE;
208 else if (strcmp(argv[i], "waits-for") == 0) {
209 dep_type = dependency_type::WAITS_FOR;
217 else if (service_name == nullptr) {
218 service_name = argv[i];
220 else if (to_service_name == nullptr) {
221 to_service_name = argv[i];
228 else if (command == command_t::ENABLE_SERVICE || command == command_t::DISABLE_SERVICE) {
229 if (to_service_name != nullptr) {
233 to_service_name = argv[i];
236 if (service_name != nullptr) {
240 service_name = argv[i];
241 // TODO support multiple services
246 bool no_service_cmd = (command == command_t::LIST_SERVICES || command == command_t::SHUTDOWN);
248 if (command == command_t::ENABLE_SERVICE || command == command_t::DISABLE_SERVICE) {
249 show_help |= (to_service_name == nullptr);
251 else if ((service_name == nullptr && ! no_service_cmd) || command == command_t::NONE) {
255 if (service_name != nullptr && no_service_cmd) {
259 if ((command == command_t::ADD_DEPENDENCY || command == command_t::RM_DEPENDENCY)
260 && (! dep_type_set || service_name == nullptr || to_service_name == nullptr)) {
265 cout << "dinitctl: control Dinit services\n"
268 " dinitctl [options] start [options] <service-name>\n"
269 " dinitctl [options] stop [options] <service-name>\n"
270 " dinitctl [options] restart [options] <service-name>\n"
271 " dinitctl [options] wake [options] <service-name>\n"
272 " dinitctl [options] release [options] <service-name>\n"
273 " dinitctl [options] unpin <service-name>\n"
274 " dinitctl [options] unload <service-name>\n"
275 " dinitctl [options] reload <service-name>\n"
276 " dinitctl [options] list\n"
277 " dinitctl [options] shutdown\n"
278 " dinitctl [options] add-dep <type> <from-service> <to-service>\n"
279 " dinitctl [options] rm-dep <type> <from-service> <to-service>\n"
280 " dinitctl [options] enable [--from <from-service>] <to-service>\n"
281 " dinitctl [options] disable [--from <from-service>] <to-service>\n"
283 "Note: An activated service continues running when its dependents stop.\n"
286 " --help : show this help\n"
287 " -s, --system : control system daemon (default if run as root)\n"
288 " -u, --user : control user daemon\n"
289 " --quiet : suppress output (except errors)\n"
290 " --socket-path <path>, -p <path>\n"
291 " : specify socket for communication with daemon\n"
294 " --no-wait : don't wait for service startup/shutdown to complete\n"
295 " --pin : pin the service in the requested state\n"
296 " --force : force stop even if dependents will be affected\n";
300 signal(SIGPIPE, SIG_IGN);
302 // Locate control socket
303 if (! control_socket_str.empty()) {
304 control_socket_path = control_socket_str.c_str();
307 control_socket_path = SYSCONTROLSOCKET; // default to system
309 char * userhome = getenv("HOME");
310 if (userhome == nullptr) {
311 struct passwd * pwuid_p = getpwuid(getuid());
312 if (pwuid_p != nullptr) {
313 userhome = pwuid_p->pw_dir;
317 if (userhome != nullptr) {
318 control_socket_str = userhome;
319 control_socket_str += "/.dinitctl";
320 control_socket_path = control_socket_str.c_str();
323 cerr << "Cannot locate user home directory (set HOME or check /etc/passwd file)" << endl;
329 int socknum = socket(AF_UNIX, SOCK_STREAM, 0);
331 perror("dinitctl: socket");
335 struct sockaddr_un * name;
336 uint sockaddr_size = offsetof(struct sockaddr_un, sun_path) + strlen(control_socket_path) + 1;
337 name = (struct sockaddr_un *) malloc(sockaddr_size);
338 if (name == nullptr) {
339 cerr << "dinitctl: Out of memory" << endl;
343 name->sun_family = AF_UNIX;
344 strcpy(name->sun_path, control_socket_path);
346 int connr = connect(socknum, (struct sockaddr *) name, sockaddr_size);
348 perror("dinitctl: connect");
353 // Start by querying protocol version:
355 check_protocol_version(min_cp_version, max_cp_version, rbuffer, socknum);
357 if (command == command_t::UNPIN_SERVICE) {
358 return unpin_service(socknum, rbuffer, service_name, verbose);
360 else if (command == command_t::UNLOAD_SERVICE) {
361 return unload_service(socknum, rbuffer, service_name);
363 else if (command == command_t::RELOAD_SERVICE) {
364 return reload_service(socknum, rbuffer, service_name);
366 else if (command == command_t::LIST_SERVICES) {
367 return list_services(socknum, rbuffer);
369 else if (command == command_t::SHUTDOWN) {
370 return shutdown_dinit(socknum, rbuffer);
372 else if (command == command_t::ADD_DEPENDENCY || command == command_t::RM_DEPENDENCY) {
373 return add_remove_dependency(socknum, rbuffer, command == command_t::ADD_DEPENDENCY,
374 service_name, to_service_name, dep_type);
376 else if (command == command_t::ENABLE_SERVICE || command == command_t::DISABLE_SERVICE) {
377 // If only one service specified, assume that we enable for 'boot' service:
378 if (service_name == nullptr) {
379 service_name = "boot";
381 return enable_disable_service(socknum, rbuffer, service_name, to_service_name,
382 command == command_t::ENABLE_SERVICE);
385 return start_stop_service(socknum, rbuffer, service_name, command, do_pin, do_force,
386 wait_for_service, verbose);
389 catch (cp_old_client_exception &e) {
390 std::cerr << "dinitctl: too old (server reports newer protocol version)" << std::endl;
393 catch (cp_old_server_exception &e) {
394 std::cerr << "dinitctl: server too old or protocol error" << std::endl;
397 catch (cp_read_exception &e) {
398 cerr << "dinitctl: control socket read failure or protocol error" << endl;
401 catch (cp_write_exception &e) {
402 cerr << "dinitctl: control socket write error: " << std::strerror(e.errcode) << endl;
407 // Extract/read a string of specified length from the buffer/socket. The string is consumed
409 static std::string read_string(int socknum, cpbuffer_t &rbuffer, uint32_t length)
411 int rb_len = rbuffer.get_length();
412 if (uint32_t(rb_len) >= length) {
413 std::string r = rbuffer.extract_string(0, length);
414 rbuffer.consume(length);
418 std::string r = rbuffer.extract_string(0, rb_len);
419 uint32_t rlen = length - rb_len;
423 rbuffer.fill(socknum);
424 char *bptr = rbuffer.get_ptr(0);
425 clen = rbuffer.get_length();
426 clen = std::min(clen, rlen);
427 r.append(bptr, clen);
431 rbuffer.consume(clen);
436 // Load a service: issue load command, wait for reply. Return true on success, display error message
437 // and return false on failure.
438 // socknum - the socket fd to communicate via
439 // rbuffer - the buffer for communication
440 // name - the name of the service to load
441 // handle - where to store the handle of the loaded service
442 // state - where to store the state of the loaded service (may be null).
443 static bool load_service(int socknum, cpbuffer_t &rbuffer, const char *name, handle_t *handle,
444 service_state_t *state)
446 // Load 'to' service:
447 if (issue_load_service(socknum, name)) {
451 wait_for_reply(rbuffer, socknum);
453 if (check_load_reply(socknum, rbuffer, handle, state) != 0) {
460 // Get the service name for a given handle, by querying the daemon.
461 static std::string get_service_name(int socknum, cpbuffer_t &rbuffer, handle_t handle)
464 .append((char) DINIT_CP_QUERYSERVICENAME)
467 write_all_x(socknum, m);
469 wait_for_reply(rbuffer, socknum);
471 if (rbuffer[0] != DINIT_RP_SERVICENAME) {
472 throw cp_read_exception{0};
477 fill_buffer_to(rbuffer, socknum, 2 + sizeof(uint16_t));
479 rbuffer.extract(&namesize, 2, sizeof(uint16_t));
480 rbuffer.consume(2 + sizeof(uint16_t));
485 if (rbuffer.get_length() == 0) {
486 rbuffer.fill(socknum);
489 size_t to_extract = std::min(size_t(rbuffer.get_length()), namesize - name.length());
490 size_t contiguous_len = rbuffer.get_contiguous_length(rbuffer.get_ptr(0));
491 if (contiguous_len <= to_extract) {
492 name.append(rbuffer.get_ptr(0), contiguous_len);
493 rbuffer.consume(contiguous_len);
494 name.append(rbuffer.get_ptr(0), to_extract - contiguous_len);
495 rbuffer.consume(to_extract - contiguous_len);
498 name.append(rbuffer.get_ptr(0), to_extract);
499 rbuffer.consume(to_extract);
503 } while (name.length() < namesize);
508 // Start/stop a service
509 static int start_stop_service(int socknum, cpbuffer_t &rbuffer, const char *service_name,
510 command_t command, bool do_pin, bool do_force, bool wait_for_service, bool verbose)
514 bool do_stop = (command == command_t::STOP_SERVICE || command == command_t::RELEASE_SERVICE);
516 service_state_t state;
519 if (! load_service(socknum, rbuffer, service_name, &handle, &state)) {
523 service_state_t wanted_state = do_stop ? service_state_t::STOPPED : service_state_t::STARTED;
526 case command_t::STOP_SERVICE:
527 case command_t::RESTART_SERVICE: // stop, and then start
528 pcommand = DINIT_CP_STOPSERVICE;
530 case command_t::RELEASE_SERVICE:
531 pcommand = DINIT_CP_RELEASESERVICE;
533 case command_t::START_SERVICE:
534 pcommand = DINIT_CP_STARTSERVICE;
536 case command_t::WAKE_SERVICE:
537 pcommand = DINIT_CP_WAKESERVICE;
542 // Need to issue STOPSERVICE/STARTSERVICE
543 // We'll do this regardless of the current service state / target state, since issuing
544 // start/stop also sets or clears the "explicitly started" flag on the service.
546 char flags = (do_pin ? 1 : 0) | ((pcommand == DINIT_CP_STOPSERVICE && !do_force) ? 2 : 0);
547 if (command == command_t::RESTART_SERVICE) {
552 .append((char) pcommand)
555 write_all_x(socknum, m);
557 wait_for_reply(rbuffer, socknum);
558 auto reply_pkt_h = rbuffer[0];
559 rbuffer.consume(1); // consume header
560 if (reply_pkt_h == DINIT_RP_ALREADYSS) {
561 bool already = (state == wanted_state);
563 cout << "Service " << (already ? "(already) " : "")
564 << describeState(do_stop) << "." << endl;
566 return 0; // success!
568 if (reply_pkt_h == DINIT_RP_DEPENDENTS && pcommand == DINIT_CP_STOPSERVICE) {
569 cerr << "dinitctl: cannot stop service due to the following dependents:\n";
570 if (command != command_t::RESTART_SERVICE) {
571 cerr << "(Only direct dependents are listed. Exercise caution before using '--force' !!)\n";
573 // size_t number, N * handle_t handles
575 rbuffer.fill_to(socknum, sizeof(number));
576 rbuffer.extract(&number, 0, sizeof(number));
577 rbuffer.consume(sizeof(number));
578 std::vector<handle_t> handles;
579 handles.reserve(number);
580 for (size_t i = 0; i < number; i++) {
582 rbuffer.fill_to(socknum, sizeof(handle_t));
583 rbuffer.extract(&handle, 0, sizeof(handle));
584 handles.push_back(handle);
585 rbuffer.consume(sizeof(handle));
587 // Print the directly affected dependents:
589 for (handle_t handle : handles) {
590 cerr << " " << get_service_name(socknum, rbuffer, handle);
595 if (reply_pkt_h == DINIT_RP_NAK && command == command_t::RESTART_SERVICE) {
596 cerr << "dinitctl: cannot restart service; service not started.\n";
599 if (reply_pkt_h == DINIT_RP_NAK && command == command_t::START_SERVICE) {
600 cerr << "dinitctl: cannot start service (during shut down).\n";
603 if (reply_pkt_h == DINIT_RP_NAK && command == command_t::WAKE_SERVICE) {
604 cerr << "dinitctl: service has no active dependents (or system is shutting down), cannot wake.\n";
607 if (reply_pkt_h != DINIT_RP_ACK && reply_pkt_h != DINIT_RP_ALREADYSS) {
608 cerr << "dinitctl: protocol error." << endl;
613 if (! wait_for_service) {
615 cout << "Issued " << describeVerb(do_stop) << " command successfully." << endl;
620 service_event_t completionEvent;
621 service_event_t cancelledEvent;
624 completionEvent = service_event_t::STOPPED;
625 cancelledEvent = service_event_t::STOPCANCELLED;
628 completionEvent = service_event_t::STARTED;
629 cancelledEvent = service_event_t::STARTCANCELLED;
632 // Wait until service started:
633 int r = rbuffer.fill_to(socknum, 2);
635 if (rbuffer[0] >= 100) {
636 int pktlen = (unsigned char) rbuffer[1];
637 fill_buffer_to(rbuffer, socknum, pktlen);
639 if (rbuffer[0] == DINIT_IP_SERVICEEVENT) {
641 rbuffer.extract((char *) &ev_handle, 2, sizeof(ev_handle));
642 service_event_t event = static_cast<service_event_t>(rbuffer[2 + sizeof(ev_handle)]);
643 if (ev_handle == handle) {
644 if (event == completionEvent) {
646 cout << "Service " << describeState(do_stop) << "." << endl;
650 else if (event == cancelledEvent) {
652 cout << "Service " << describeVerb(do_stop) << " cancelled." << endl;
656 else if (! do_stop && event == service_event_t::FAILEDSTART) {
658 cout << "Service failed to start." << endl;
665 rbuffer.consume(pktlen);
666 r = rbuffer.fill_to(socknum, 2);
669 // Not an information packet?
670 cerr << "dinitctl: protocol error" << endl;
676 perror("dinitctl: read");
679 cerr << "protocol error (connection closed by server)" << endl;
684 // Issue a "load service" command (DINIT_CP_LOADSERVICE), without waiting for
685 // a response. Returns 1 on failure (with error logged), 0 on success.
686 static int issue_load_service(int socknum, const char *service_name, bool find_only)
689 uint16_t sname_len = strlen(service_name);
690 int bufsize = 3 + sname_len;
692 std::unique_ptr<char[]> ubuf(new char[bufsize]);
693 auto buf = ubuf.get();
695 buf[0] = find_only ? DINIT_CP_FINDSERVICE : DINIT_CP_LOADSERVICE;
696 memcpy(buf + 1, &sname_len, 2);
697 memcpy(buf + 3, service_name, sname_len);
699 write_all_x(socknum, buf, bufsize);
704 // Check that a "load service" reply was received, and that the requested service was found.
705 // state_p may be null.
706 static int check_load_reply(int socknum, cpbuffer_t &rbuffer, handle_t *handle_p, service_state_t *state_p)
710 if (rbuffer[0] == DINIT_RP_SERVICERECORD) {
711 fill_buffer_to(rbuffer, socknum, 2 + sizeof(*handle_p));
712 rbuffer.extract((char *) handle_p, 2, sizeof(*handle_p));
713 if (state_p) *state_p = static_cast<service_state_t>(rbuffer[1]);
714 //target_state = static_cast<service_state_t>(rbuffer[2 + sizeof(handle)]);
715 rbuffer.consume(3 + sizeof(*handle_p));
718 else if (rbuffer[0] == DINIT_RP_NOSERVICE) {
719 cerr << "dinitctl: failed to find/load service." << endl;
723 cerr << "dinitctl: protocol error." << endl;
728 static int unpin_service(int socknum, cpbuffer_t &rbuffer, const char *service_name, bool verbose)
735 if (! load_service(socknum, rbuffer, service_name, &handle, nullptr)) {
739 // Issue UNPIN command.
742 .append<char>(DINIT_CP_UNPINSERVICE)
744 write_all_x(socknum, m);
746 wait_for_reply(rbuffer, socknum);
747 if (rbuffer[0] != DINIT_RP_ACK) {
748 cerr << "dinitctl: protocol error." << endl;
755 cout << "Service unpinned." << endl;
760 static int unload_service(int socknum, cpbuffer_t &rbuffer, const char *service_name)
764 if (issue_load_service(socknum, service_name, true) == 1) {
768 wait_for_reply(rbuffer, socknum);
772 if (rbuffer[0] == DINIT_RP_NOSERVICE) {
773 cerr << "dinitctl: service not loaded." << endl;
777 if (check_load_reply(socknum, rbuffer, &handle, nullptr) != 0) {
781 // Issue UNLOAD command.
784 .append<char>(DINIT_CP_UNLOADSERVICE)
786 write_all_x(socknum, m);
788 wait_for_reply(rbuffer, socknum);
789 if (rbuffer[0] == DINIT_RP_NAK) {
790 cerr << "dinitctl: Could not unload service; service not stopped, or is a dependency of "
791 "other service." << endl;
794 if (rbuffer[0] != DINIT_RP_ACK) {
795 cerr << "dinitctl: Protocol error." << endl;
801 cout << "Service unloaded." << endl;
805 static int reload_service(int socknum, cpbuffer_t &rbuffer, const char *service_name)
809 if (issue_load_service(socknum, service_name, true) == 1) {
813 wait_for_reply(rbuffer, socknum);
817 if (rbuffer[0] == DINIT_RP_NOSERVICE) {
818 cerr << "dinitctl: service not loaded." << endl;
822 if (check_load_reply(socknum, rbuffer, &handle, nullptr) != 0) {
826 // Issue RELOAD command.
829 .append<char>(DINIT_CP_RELOADSERVICE)
831 write_all_x(socknum, m);
833 wait_for_reply(rbuffer, socknum);
834 if (rbuffer[0] == DINIT_RP_NAK) {
835 cerr << "dinitctl: Could not reload service; service in wrong state, incompatible change, "
836 "or bad service description." << endl;
839 if (rbuffer[0] != DINIT_RP_ACK) {
840 cerr << "dinitctl: Protocol error." << endl;
846 cout << "Service reloaded." << endl;
850 static int list_services(int socknum, cpbuffer_t &rbuffer)
854 char cmdbuf[] = { (char)DINIT_CP_LISTSERVICES };
855 write_all_x(socknum, cmdbuf, 1);
857 wait_for_reply(rbuffer, socknum);
858 while (rbuffer[0] == DINIT_RP_SVCINFO) {
859 int hdrsize = 8 + std::max(sizeof(int), sizeof(pid_t));
860 fill_buffer_to(rbuffer, socknum, hdrsize);
861 int nameLen = rbuffer[1];
862 service_state_t current = static_cast<service_state_t>(rbuffer[2]);
863 service_state_t target = static_cast<service_state_t>(rbuffer[3]);
865 int console_flags = rbuffer[4];
866 bool has_console = (console_flags & 2) != 0;
867 bool waiting_console = (console_flags & 1) != 0;
868 bool was_skipped = (console_flags & 4) != 0;
870 stopped_reason_t stop_reason = static_cast<stopped_reason_t>(rbuffer[5]);
874 if (current != service_state_t::STOPPED) {
875 rbuffer.extract((char *)&service_pid, 8, sizeof(service_pid));
878 rbuffer.extract((char *)&exit_status, 8, sizeof(exit_status));
881 fill_buffer_to(rbuffer, socknum, nameLen + hdrsize);
883 char *name_ptr = rbuffer.get_ptr(hdrsize);
884 int clength = std::min(rbuffer.get_contiguous_length(name_ptr), nameLen);
886 string name = string(name_ptr, clength);
887 name.append(rbuffer.get_buf_base(), nameLen - clength);
891 cout << (target == service_state_t::STARTED ? "{" : " ");
892 if (current == service_state_t::STARTED) {
893 cout << (was_skipped ? "s" : "+");
898 cout << (target == service_state_t::STARTED ? "}" : " ");
900 if (current == service_state_t::STARTING) {
903 else if (current == service_state_t::STOPPING) {
910 cout << (target == service_state_t::STOPPED ? "{" : " ");
911 if (current == service_state_t::STOPPED) {
912 bool did_fail = false;
913 if (stop_reason == stopped_reason_t::TERMINATED) {
914 if (!WIFEXITED(exit_status) || WEXITSTATUS(exit_status) != 0) {
918 else did_fail = (stop_reason != stopped_reason_t::NORMAL);
920 cout << (did_fail ? "X" : "-");
925 cout << (target == service_state_t::STOPPED ? "}" : " ");
927 cout << "] " << name;
929 if (current != service_state_t::STOPPED && service_pid != -1) {
930 cout << " (pid: " << service_pid << ")";
933 if (current == service_state_t::STOPPED && stop_reason == stopped_reason_t::TERMINATED) {
934 if (WIFEXITED(exit_status)) {
935 cout << " (exit status: " << WEXITSTATUS(exit_status) << ")";
937 else if (WIFSIGNALED(exit_status)) {
938 cout << " (signal: " << WTERMSIG(exit_status) << ")";
943 cout << " (has console)";
945 else if (waiting_console) {
946 cout << " (waiting for console)";
951 rbuffer.consume(hdrsize + nameLen);
952 wait_for_reply(rbuffer, socknum);
955 if (rbuffer[0] != DINIT_RP_LISTDONE) {
956 cerr << "dinitctl: Control socket protocol error" << endl;
963 static int add_remove_dependency(int socknum, cpbuffer_t &rbuffer, bool add,
964 const char *service_from, const char *service_to, dependency_type dep_type)
968 handle_t from_handle;
971 if (! load_service(socknum, rbuffer, service_from, &from_handle, nullptr)
972 || ! load_service(socknum, rbuffer, service_to, &to_handle, nullptr)) {
977 .append<char>(add ? (char)DINIT_CP_ADD_DEP : (char)DINIT_CP_REM_DEP)
981 write_all_x(socknum, m);
983 wait_for_reply(rbuffer, socknum);
986 if (rbuffer[0] == DINIT_RP_NAK) {
987 cerr << "dinitctl: Could not add dependency: circular dependency or wrong state" << endl;
990 if (rbuffer[0] != DINIT_RP_ACK) {
991 cerr << "dinitctl: Control socket protocol error" << endl;
998 static int shutdown_dinit(int socknum, cpbuffer_t &rbuffer)
1000 // TODO support no-wait option.
1001 using namespace std;
1004 .append<char>(DINIT_CP_SHUTDOWN)
1005 .append(static_cast<char>(shutdown_type_t::HALT));
1006 write_all_x(socknum, m);
1008 wait_for_reply(rbuffer, socknum);
1010 if (rbuffer[0] != DINIT_RP_ACK) {
1011 cerr << "dinitctl: Control socket protocol error" << endl;
1015 // Now wait for rollback complete, by waiting for the connection to close:
1018 wait_for_info(rbuffer, socknum);
1019 rbuffer.consume(rbuffer[1]);
1022 catch (cp_read_exception &exc) {
1023 // Assume that the connection closed.
1029 // exception for cancelling a service operation
1030 class service_op_cancel { };
1032 static int enable_disable_service(int socknum, cpbuffer_t &rbuffer, const char *from, const char *to,
1035 using namespace std;
1037 service_state_t from_state = service_state_t::STARTED;
1038 handle_t from_handle;
1042 if (! load_service(socknum, rbuffer, from, &from_handle, &from_state)
1043 || ! load_service(socknum, rbuffer, to, &to_handle, nullptr)) {
1047 // Get service load path
1048 char buf[1] = { DINIT_CP_QUERY_LOAD_MECH };
1049 write_all_x(socknum, buf, 1);
1051 wait_for_reply(rbuffer, socknum);
1053 if (rbuffer[0] != DINIT_RP_LOADER_MECH) {
1054 cerr << "dinitctl: Control socket protocol error" << endl;
1058 // Packet type, load mechanism type, packet size:
1059 fill_buffer_to(rbuffer, socknum, 2 + sizeof(uint32_t));
1061 if (rbuffer[1] != SSET_TYPE_DIRLOAD) {
1062 cerr << "dinitctl: unknown configuration, unable to load service descriptions" << endl;
1066 vector<string> paths;
1069 rbuffer.extract(&pktsize, 2, sizeof(uint32_t));
1071 fill_buffer_to(rbuffer, socknum, 2 + sizeof(uint32_t) * 3); // path entries, cwd length
1073 uint32_t path_entries; // number of service directories
1074 rbuffer.extract(&path_entries, 2 + sizeof(uint32_t), sizeof(uint32_t));
1077 rbuffer.extract(&cwd_len, 2 + sizeof(uint32_t) * 2, sizeof(uint32_t));
1078 rbuffer.consume(2 + sizeof(uint32_t) * 3);
1079 pktsize -= 2 + sizeof(uint32_t) * 3;
1081 // Read current working directory of daemon:
1082 std::string dinit_cwd = read_string(socknum, rbuffer, cwd_len);
1084 // dinit daemon base directory against which service paths are resolved is in dinit_cwd
1086 for (int i = 0; i < (int)path_entries; i++) {
1088 fill_buffer_to(rbuffer, socknum, sizeof(uint32_t));
1089 rbuffer.extract(&plen, 0, sizeof(uint32_t));
1090 rbuffer.consume(sizeof(uint32_t));
1091 paths.push_back(read_string(socknum, rbuffer, plen));
1094 // all service directories are now in the 'paths' vector
1095 // Load/read service description for 'from' service:
1097 ifstream service_file;
1098 string service_file_path;
1100 for (std::string path : paths) {
1101 string test_path = combine_paths(combine_paths(dinit_cwd, path.c_str()), from);
1103 service_file.open(test_path.c_str(), ios::in);
1105 service_file_path = test_path;
1110 if (! service_file) {
1111 cerr << "dinitctl: could not locate service file for service '" << from << "'" << endl;
1115 // We now need to read the service file, identify the waits-for.d directory (bail out if more than one),
1116 // make sure the service is not listed as a dependency individually.
1121 process_service_file(from, service_file, [&](string &line, string &setting,
1122 dinit_load::string_iterator i, dinit_load::string_iterator end) -> void {
1123 if (setting == "waits-for" || setting == "depends-on" || setting == "depends-ms") {
1124 string dname = dinit_load::read_setting_value(i, end);
1126 // There is already a dependency
1127 cerr << "dinitctl: there is a fixed dependency to service '" << to
1128 << "' in the service description of '" << from << "'." << endl;
1129 throw service_op_cancel();
1132 else if (setting == "waits-for.d") {
1133 string dname = dinit_load::read_setting_value(i, end);
1134 if (! waits_for_d.empty()) {
1135 cerr << "dinitctl: service '" << from << "' has multiple waits-for.d directories "
1136 << "specified in service description" << endl;
1137 throw service_op_cancel();
1139 waits_for_d = std::move(dname);
1143 catch (const service_op_cancel &cexc) {
1147 // If the from service has no waits-for.d specified, we can't continue
1148 if (waits_for_d.empty()) {
1149 cerr << "dinitctl: service '" << from << "' has no waits-for.d directory specified" << endl;
1153 // The waits-for.d path is relative to the service file path, combine:
1154 string waits_for_d_full = combine_paths(parent_path(service_file_path), waits_for_d.c_str());
1156 // check if dependency already exists
1157 string dep_link_path = combine_paths(waits_for_d_full, to);
1158 struct stat stat_buf;
1159 if (lstat(dep_link_path.c_str(), &stat_buf) == -1) {
1160 if (errno != ENOENT) {
1161 cerr << "dinitctl: checking for existing dependency link: " << dep_link_path << ": "
1162 << strerror(errno) << endl;
1167 // dependency already exists
1169 cerr << "dinitctl: service already enabled." << endl;
1174 // warn if 'from' service is not started
1175 if (enable && from_state != service_state_t::STARTED) {
1176 cerr << "dinitctl: warning: enabling dependency for non-started service" << endl;
1179 // add/remove dependency
1180 constexpr int enable_pktsize = 2 + sizeof(handle_t) * 2;
1181 char cmdbuf[enable_pktsize] = { char(enable ? DINIT_CP_ENABLESERVICE : DINIT_CP_REM_DEP),
1182 char(dependency_type::WAITS_FOR)};
1183 memcpy(cmdbuf + 2, &from_handle, sizeof(from_handle));
1184 memcpy(cmdbuf + 2 + sizeof(from_handle), &to_handle, sizeof(to_handle));
1185 write_all_x(socknum, cmdbuf, enable_pktsize);
1187 wait_for_reply(rbuffer, socknum);
1190 if (enable && rbuffer[0] == DINIT_RP_NAK) {
1191 cerr << "dinitctl: Could not enable service: possible circular dependency" << endl;
1194 if (rbuffer[0] != DINIT_RP_ACK) {
1195 cerr << "dinitctl: Control socket protocol error" << endl;
1201 if (symlink((string("../") + to).c_str(), dep_link_path.c_str()) == -1) {
1202 cerr << "dinitctl: Could not create symlink at " << dep_link_path << ": " << strerror(errno)
1203 << "\n" "dinitctl: Note: service was activated, but will not be enabled on restart."
1209 if (unlink(dep_link_path.c_str()) == -1) {
1210 cerr << "dinitctl: Could not unlink dependency entry " << dep_link_path << ": "
1211 << strerror(errno) << "\n"
1212 "dinitctl: Note: service was disabled, but will be re-enabled on restart." << endl;