6 #include <system_error>
11 #include <sys/socket.h>
17 #include "control-cmds.h"
18 #include "service-constants.h"
20 #include "dinit-client.h"
22 // dinitctl: utility to control the Dinit daemon, including starting and stopping of services.
24 // This utility communicates with the dinit daemon via a unix stream socket (/dev/initctl, or $HOME/.dinitctl).
26 static constexpr uint16_t min_cp_version = 1;
27 static constexpr uint16_t max_cp_version = 1;
31 static int issue_load_service(int socknum, const char *service_name, bool find_only = false);
32 static int check_load_reply(int socknum, cpbuffer_t &, handle_t *handle_p, service_state_t *state_p);
33 static int start_stop_service(int socknum, cpbuffer_t &, const char *service_name, command_t command,
34 bool do_pin, bool wait_for_service, bool verbose);
35 static int unpin_service(int socknum, cpbuffer_t &, const char *service_name, bool verbose);
36 static int unload_service(int socknum, cpbuffer_t &, const char *service_name);
37 static int list_services(int socknum, cpbuffer_t &);
38 static int shutdown_dinit(int soclknum, cpbuffer_t &);
39 static int add_remove_dependency(int socknum, cpbuffer_t &rbuffer, bool add, char *service_from,
40 char *service_to, dependency_type dep_type);
43 static const char * describeState(bool stopped)
45 return stopped ? "stopped" : "started";
48 static const char * describeVerb(bool stop)
50 return stop ? "stop" : "start";
53 enum class command_t {
69 int main(int argc, char **argv)
73 bool show_help = argc < 2;
74 char *service_name = nullptr;
75 char *to_service_name = nullptr;
76 dependency_type dep_type;
77 bool dep_type_set = false;
79 std::string control_socket_str;
80 const char * control_socket_path = nullptr;
83 bool sys_dinit = false; // communicate with system daemon
84 bool wait_for_service = true;
87 command_t command = command_t::NONE;
89 for (int i = 1; i < argc; i++) {
90 if (argv[i][0] == '-') {
91 if (strcmp(argv[i], "--help") == 0) {
95 else if (strcmp(argv[i], "--no-wait") == 0) {
96 wait_for_service = false;
98 else if (strcmp(argv[i], "--quiet") == 0) {
101 else if (strcmp(argv[i], "--system") == 0 || strcmp(argv[i], "-s") == 0) {
104 else if (strcmp(argv[i], "--pin") == 0) {
111 else if (command == command_t::NONE) {
112 if (strcmp(argv[i], "start") == 0) {
113 command = command_t::START_SERVICE;
115 else if (strcmp(argv[i], "wake") == 0) {
116 command = command_t::WAKE_SERVICE;
118 else if (strcmp(argv[i], "stop") == 0) {
119 command = command_t::STOP_SERVICE;
121 else if (strcmp(argv[i], "release") == 0) {
122 command = command_t::RELEASE_SERVICE;
124 else if (strcmp(argv[i], "unpin") == 0) {
125 command = command_t::UNPIN_SERVICE;
127 else if (strcmp(argv[i], "unload") == 0) {
128 command = command_t::UNLOAD_SERVICE;
130 else if (strcmp(argv[i], "list") == 0) {
131 command = command_t::LIST_SERVICES;
133 else if (strcmp(argv[i], "shutdown") == 0) {
134 command = command_t::SHUTDOWN;
136 else if (strcmp(argv[i], "add-dep") == 0) {
137 command = command_t::ADD_DEPENDENCY;
139 else if (strcmp(argv[i], "rm-dep") == 0) {
140 command = command_t::RM_DEPENDENCY;
148 // service name / other non-option
149 if (command == command_t::ADD_DEPENDENCY || command == command_t::RM_DEPENDENCY) {
150 if (! dep_type_set) {
151 if (strcmp(argv[i], "regular") == 0) {
152 dep_type = dependency_type::REGULAR;
154 else if (strcmp(argv[i], "milestone") == 0) {
155 dep_type = dependency_type::MILESTONE;
157 else if (strcmp(argv[i], "waits-for") == 0) {
158 dep_type = dependency_type::WAITS_FOR;
166 else if (service_name == nullptr) {
167 service_name = argv[i];
169 else if (to_service_name == nullptr) {
170 to_service_name = argv[i];
178 if (service_name != nullptr) {
182 service_name = argv[i];
183 // TODO support multiple services
188 bool no_service_cmd = (command == command_t::LIST_SERVICES || command == command_t::SHUTDOWN);
190 if (service_name != nullptr && no_service_cmd) {
194 if ((service_name == nullptr && ! no_service_cmd) || command == command_t::NONE) {
198 if ((command == command_t::ADD_DEPENDENCY || command == command_t::RM_DEPENDENCY)
199 && (! dep_type_set || service_name == nullptr || to_service_name == nullptr)) {
204 cout << "dinitctl: control Dinit services" << endl;
206 cout << "\nUsage:" << endl;
207 cout << " dinitctl [options] start [options] <service-name> : start and activate service" << endl;
208 cout << " dinitctl [options] stop [options] <service-name> : stop service and cancel explicit activation" << endl;
209 cout << " dinitctl [options] wake [options] <service-name> : start but do not mark activated" << endl;
210 cout << " dinitctl [options] release [options] <service-name> : release activation, stop if no dependents" << endl;
211 cout << " dinitctl [options] unpin <service-name> : un-pin the service (after a previous pin)" << endl;
212 cout << " dinitctl unload <service-name> : unload the service" << endl;
213 cout << " dinitctl list : list loaded services" << endl;
214 cout << " dinitctl shutdown : stop all services and terminate dinit" << endl;
215 cout << " dinitctl add-dep <type> <from-service> <to-service> : add a dependency between services" << endl;
216 cout << " dinitctl rm-dep <type> <from-service> <to-service> : remove a dependency between services" << endl;
218 cout << "\nNote: An activated service continues running when its dependents stop." << endl;
220 cout << "\nGeneral options:" << endl;
221 cout << " -s, --system : control system daemon instead of user daemon" << endl;
222 cout << " --quiet : suppress output (except errors)" << endl;
224 cout << "\nCommand options:" << endl;
225 cout << " --help : show this help" << endl;
226 cout << " --no-wait : don't wait for service startup/shutdown to complete" << endl;
227 cout << " --pin : pin the service in the requested (started/stopped) state" << endl;
231 signal(SIGPIPE, SIG_IGN);
233 control_socket_path = "/dev/dinitctl";
235 // Locate control socket
237 char * userhome = getenv("HOME");
238 if (userhome == nullptr) {
239 struct passwd * pwuid_p = getpwuid(getuid());
240 if (pwuid_p != nullptr) {
241 userhome = pwuid_p->pw_dir;
245 if (userhome != nullptr) {
246 control_socket_str = userhome;
247 control_socket_str += "/.dinitctl";
248 control_socket_path = control_socket_str.c_str();
251 cerr << "Cannot locate user home directory (set HOME or check /etc/passwd file)" << endl;
256 int socknum = socket(AF_UNIX, SOCK_STREAM, 0);
258 perror("dinitctl: socket");
262 struct sockaddr_un * name;
263 uint sockaddr_size = offsetof(struct sockaddr_un, sun_path) + strlen(control_socket_path) + 1;
264 name = (struct sockaddr_un *) malloc(sockaddr_size);
265 if (name == nullptr) {
266 cerr << "dinitctl: Out of memory" << endl;
270 name->sun_family = AF_UNIX;
271 strcpy(name->sun_path, control_socket_path);
273 int connr = connect(socknum, (struct sockaddr *) name, sockaddr_size);
275 perror("dinitctl: connect");
280 // Start by querying protocol version:
282 check_protocol_version(min_cp_version, max_cp_version, rbuffer, socknum);
284 if (command == command_t::UNPIN_SERVICE) {
285 return unpin_service(socknum, rbuffer, service_name, verbose);
287 else if (command == command_t::UNLOAD_SERVICE) {
288 return unload_service(socknum, rbuffer, service_name);
290 else if (command == command_t::LIST_SERVICES) {
291 return list_services(socknum, rbuffer);
293 else if (command == command_t::SHUTDOWN) {
294 return shutdown_dinit(socknum, rbuffer);
296 else if (command == command_t::ADD_DEPENDENCY || command == command_t::RM_DEPENDENCY) {
297 return add_remove_dependency(socknum, rbuffer, command == command_t::ADD_DEPENDENCY,
298 service_name, to_service_name, dep_type);
301 return start_stop_service(socknum, rbuffer, service_name, command, do_pin,
302 wait_for_service, verbose);
305 catch (cp_old_client_exception &e) {
306 std::cerr << "dinitctl: too old (server reports newer protocol version)" << std::endl;
309 catch (cp_old_server_exception &e) {
310 std::cerr << "dinitctl: server too old or protocol error" << std::endl;
313 catch (cp_read_exception &e) {
314 cerr << "dinitctl: control socket read failure or protocol error" << endl;
317 catch (cp_write_exception &e) {
318 cerr << "dinitctl: control socket write error: " << std::strerror(e.errcode) << endl;
323 // Start/stop a service
324 static int start_stop_service(int socknum, cpbuffer_t &rbuffer, const char *service_name,
325 command_t command, bool do_pin, bool wait_for_service, bool verbose)
329 bool do_stop = (command == command_t::STOP_SERVICE || command == command_t::RELEASE_SERVICE);
331 if (issue_load_service(socknum, service_name)) {
335 // Now we expect a reply:
337 wait_for_reply(rbuffer, socknum);
339 service_state_t state;
340 //service_state_t target_state;
343 if (check_load_reply(socknum, rbuffer, &handle, &state) != 0) {
347 service_state_t wanted_state = do_stop ? service_state_t::STOPPED : service_state_t::STARTED;
350 case command_t::STOP_SERVICE:
351 pcommand = DINIT_CP_STOPSERVICE;
353 case command_t::RELEASE_SERVICE:
354 pcommand = DINIT_CP_RELEASESERVICE;
356 case command_t::START_SERVICE:
357 pcommand = DINIT_CP_STARTSERVICE;
359 case command_t::WAKE_SERVICE:
360 pcommand = DINIT_CP_WAKESERVICE;
365 // Need to issue STOPSERVICE/STARTSERVICE
366 // We'll do this regardless of the current service state / target state, since issuing
367 // start/stop also sets or clears the "explicitly started" flag on the service.
369 char buf[2 + sizeof(handle)];
371 buf[1] = do_pin ? 1 : 0;
372 memcpy(buf + 2, &handle, sizeof(handle));
373 write_all_x(socknum, buf, 2 + sizeof(handle));
375 wait_for_reply(rbuffer, socknum);
376 if (rbuffer[0] == DINIT_RP_ALREADYSS) {
377 bool already = (state == wanted_state);
379 cout << "Service " << (already ? "(already) " : "") << describeState(do_stop) << "." << endl;
381 return 0; // success!
383 if (rbuffer[0] != DINIT_RP_ACK) {
384 cerr << "dinitctl: Protocol error." << endl;
390 if (! wait_for_service) {
392 cout << "Issued " << describeVerb(do_stop) << " command successfully." << endl;
397 service_event_t completionEvent;
398 service_event_t cancelledEvent;
401 completionEvent = service_event_t::STOPPED;
402 cancelledEvent = service_event_t::STOPCANCELLED;
405 completionEvent = service_event_t::STARTED;
406 cancelledEvent = service_event_t::STARTCANCELLED;
409 // Wait until service started:
410 int r = rbuffer.fill_to(socknum, 2);
412 if (rbuffer[0] >= 100) {
413 int pktlen = (unsigned char) rbuffer[1];
414 fill_buffer_to(rbuffer, socknum, pktlen);
416 if (rbuffer[0] == DINIT_IP_SERVICEEVENT) {
418 rbuffer.extract((char *) &ev_handle, 2, sizeof(ev_handle));
419 service_event_t event = static_cast<service_event_t>(rbuffer[2 + sizeof(ev_handle)]);
420 if (ev_handle == handle) {
421 if (event == completionEvent) {
423 cout << "Service " << describeState(do_stop) << "." << endl;
427 else if (event == cancelledEvent) {
429 cout << "Service " << describeVerb(do_stop) << " cancelled." << endl;
433 else if (! do_stop && event == service_event_t::FAILEDSTART) {
435 cout << "Service failed to start." << endl;
442 rbuffer.consume(pktlen);
443 r = rbuffer.fill_to(socknum, 2);
446 // Not an information packet?
447 cerr << "dinitctl: protocol error" << endl;
453 perror("dinitctl: read");
456 cerr << "protocol error (connection closed by server)" << endl;
461 // Issue a "load service" command (DINIT_CP_LOADSERVICE), without waiting for
462 // a response. Returns 1 on failure (with error logged), 0 on success.
463 static int issue_load_service(int socknum, const char *service_name, bool find_only)
466 uint16_t sname_len = strlen(service_name);
467 int bufsize = 3 + sname_len;
469 std::unique_ptr<char[]> ubuf(new char[bufsize]);
470 auto buf = ubuf.get();
472 buf[0] = find_only ? DINIT_CP_FINDSERVICE : DINIT_CP_LOADSERVICE;
473 memcpy(buf + 1, &sname_len, 2);
474 memcpy(buf + 3, service_name, sname_len);
476 write_all_x(socknum, buf, bufsize);
481 // Check that a "load service" reply was received, and that the requested service was found.
482 static int check_load_reply(int socknum, cpbuffer_t &rbuffer, handle_t *handle_p, service_state_t *state_p)
486 if (rbuffer[0] == DINIT_RP_SERVICERECORD) {
487 fill_buffer_to(rbuffer, socknum, 2 + sizeof(*handle_p));
488 rbuffer.extract((char *) handle_p, 2, sizeof(*handle_p));
489 if (state_p) *state_p = static_cast<service_state_t>(rbuffer[1]);
490 //target_state = static_cast<service_state_t>(rbuffer[2 + sizeof(handle)]);
491 rbuffer.consume(3 + sizeof(*handle_p));
494 else if (rbuffer[0] == DINIT_RP_NOSERVICE) {
495 cerr << "dinitctl: failed to find/load service." << endl;
499 cerr << "dinitctl: protocol error." << endl;
504 static int unpin_service(int socknum, cpbuffer_t &rbuffer, const char *service_name, bool verbose)
509 if (issue_load_service(socknum, service_name) == 1) {
513 // Now we expect a reply:
515 wait_for_reply(rbuffer, socknum);
519 if (check_load_reply(socknum, rbuffer, &handle, nullptr) != 0) {
523 // Issue UNPIN command.
525 char buf[1 + sizeof(handle)];
526 buf[0] = DINIT_CP_UNPINSERVICE;
527 memcpy(buf + 1, &handle, sizeof(handle));
528 write_all_x(socknum, buf, 2 + sizeof(handle));
530 wait_for_reply(rbuffer, socknum);
531 if (rbuffer[0] != DINIT_RP_ACK) {
532 cerr << "dinitctl: protocol error." << endl;
539 cout << "Service unpinned." << endl;
544 static int unload_service(int socknum, cpbuffer_t &rbuffer, const char *service_name)
549 if (issue_load_service(socknum, service_name, true) == 1) {
553 // Now we expect a reply:
555 wait_for_reply(rbuffer, socknum);
559 if (check_load_reply(socknum, rbuffer, &handle, nullptr) != 0) {
563 // Issue UNLOAD command.
565 char buf[1 + sizeof(handle)];
566 buf[0] = DINIT_CP_UNLOADSERVICE;
567 memcpy(buf + 1, &handle, sizeof(handle));
568 write_all_x(socknum, buf, 2 + sizeof(handle));
570 wait_for_reply(rbuffer, socknum);
571 if (rbuffer[0] == DINIT_RP_NAK) {
572 cerr << "dinitctl: Could not unload service; service not stopped, or is a dependency of "
573 "other service." << endl;
576 if (rbuffer[0] != DINIT_RP_ACK) {
577 cerr << "dinitctl: Protocol error." << endl;
583 cout << "Service unloaded." << endl;
587 static int list_services(int socknum, cpbuffer_t &rbuffer)
591 char cmdbuf[] = { (char)DINIT_CP_LISTSERVICES };
592 write_all_x(socknum, cmdbuf, 1);
594 wait_for_reply(rbuffer, socknum);
595 while (rbuffer[0] == DINIT_RP_SVCINFO) {
596 int hdrsize = 8 + std::max(sizeof(int), sizeof(pid_t));
597 fill_buffer_to(rbuffer, socknum, hdrsize);
598 int nameLen = rbuffer[1];
599 service_state_t current = static_cast<service_state_t>(rbuffer[2]);
600 service_state_t target = static_cast<service_state_t>(rbuffer[3]);
602 int console_flags = rbuffer[4];
603 bool has_console = (console_flags & 2) != 0;
604 bool waiting_console = (console_flags & 1) != 0;
605 bool was_skipped = (console_flags & 4) != 0;
607 stopped_reason_t stop_reason = static_cast<stopped_reason_t>(rbuffer[5]);
611 if (current != service_state_t::STOPPED) {
612 rbuffer.extract((char *)&service_pid, 8, sizeof(service_pid));
615 rbuffer.extract((char *)&exit_status, 8, sizeof(exit_status));
618 fill_buffer_to(rbuffer, socknum, nameLen + hdrsize);
620 char *name_ptr = rbuffer.get_ptr(hdrsize);
621 int clength = std::min(rbuffer.get_contiguous_length(name_ptr), nameLen);
623 string name = string(name_ptr, clength);
624 name.append(rbuffer.get_buf_base(), nameLen - clength);
628 cout << (target == service_state_t::STARTED ? "{" : " ");
629 if (current == service_state_t::STARTED) {
630 cout << (was_skipped ? "s" : "+");
635 cout << (target == service_state_t::STARTED ? "}" : " ");
637 if (current == service_state_t::STARTING) {
640 else if (current == service_state_t::STOPPING) {
647 cout << (target == service_state_t::STOPPED ? "{" : " ");
648 if (current == service_state_t::STOPPED) {
649 bool did_fail = false;
650 if (stop_reason == stopped_reason_t::TERMINATED) {
651 if (!WIFEXITED(exit_status) || WEXITSTATUS(exit_status) != 0) {
655 else did_fail = (stop_reason != stopped_reason_t::NORMAL);
657 cout << (did_fail ? "X" : "-");
662 cout << (target == service_state_t::STOPPED ? "}" : " ");
664 cout << "] " << name;
666 if (current != service_state_t::STOPPED && service_pid != -1) {
667 cout << " (pid: " << service_pid << ")";
670 if (current == service_state_t::STOPPED && stop_reason == stopped_reason_t::TERMINATED) {
671 if (WIFEXITED(exit_status)) {
672 cout << " (exit status: " << WEXITSTATUS(exit_status) << ")";
674 else if (WIFSIGNALED(exit_status)) {
675 cout << " (signal: " << WSTOPSIG(exit_status) << ")";
680 cout << " (has console)";
682 else if (waiting_console) {
683 cout << " (waiting for console)";
688 rbuffer.consume(hdrsize + nameLen);
689 wait_for_reply(rbuffer, socknum);
692 if (rbuffer[0] != DINIT_RP_LISTDONE) {
693 cerr << "dinitctl: Control socket protocol error" << endl;
700 static int add_remove_dependency(int socknum, cpbuffer_t &rbuffer, bool add, char *service_from,
701 char *service_to, dependency_type dep_type)
705 // First find the "from" service:
706 if (issue_load_service(socknum, service_from, false) == 1) {
710 wait_for_reply(rbuffer, socknum);
712 handle_t from_handle;
714 if (check_load_reply(socknum, rbuffer, &from_handle, nullptr) != 0) {
718 // Then find or load the "to" service:
719 if (issue_load_service(socknum, service_to, false) == 1) {
723 wait_for_reply(rbuffer, socknum);
727 if (check_load_reply(socknum, rbuffer, &to_handle, nullptr) != 0) {
731 constexpr int pktsize = 2 + sizeof(handle_t) * 2;
732 char cmdbuf[pktsize] = { add ? (char)DINIT_CP_ADD_DEP : (char)DINIT_CP_REM_DEP, (char)dep_type};
733 memcpy(cmdbuf + 2, &from_handle, sizeof(from_handle));
734 memcpy(cmdbuf + 2 + sizeof(from_handle), &to_handle, sizeof(to_handle));
735 write_all_x(socknum, cmdbuf, pktsize);
737 wait_for_reply(rbuffer, socknum);
740 if (rbuffer[0] == DINIT_RP_NAK) {
741 cerr << "dinitctl: Could not add dependency: circular dependency or wrong state" << endl;
744 if (rbuffer[0] != DINIT_RP_ACK) {
745 cerr << "dinitctl: Control socket protocol error" << endl;
752 static int shutdown_dinit(int socknum, cpbuffer_t &rbuffer)
754 // TODO support no-wait option.
758 constexpr int bufsize = 2;
761 buf[0] = DINIT_CP_SHUTDOWN;
762 buf[1] = static_cast<char>(shutdown_type_t::HALT);
764 write_all_x(socknum, buf, bufsize);
766 wait_for_reply(rbuffer, socknum);
768 if (rbuffer[0] != DINIT_RP_ACK) {
769 cerr << "dinitctl: Control socket protocol error" << endl;
773 // Now wait for rollback complete:
776 wait_for_info(rbuffer, socknum);
777 if (rbuffer[0] == DINIT_ROLLBACK_COMPLETED) {
782 catch (cp_read_exception &exc) {
783 // Dinit can terminate before replying: let's assume that happened.
784 // TODO: better check, possibly ensure that dinit actually sends rollback complete before