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) {
108 cerr << "dinitctl: unrecognized option: " << argv[i] << " (use --help for help)\n";
112 else if (command == command_t::NONE) {
113 if (strcmp(argv[i], "start") == 0) {
114 command = command_t::START_SERVICE;
116 else if (strcmp(argv[i], "wake") == 0) {
117 command = command_t::WAKE_SERVICE;
119 else if (strcmp(argv[i], "stop") == 0) {
120 command = command_t::STOP_SERVICE;
122 else if (strcmp(argv[i], "release") == 0) {
123 command = command_t::RELEASE_SERVICE;
125 else if (strcmp(argv[i], "unpin") == 0) {
126 command = command_t::UNPIN_SERVICE;
128 else if (strcmp(argv[i], "unload") == 0) {
129 command = command_t::UNLOAD_SERVICE;
131 else if (strcmp(argv[i], "list") == 0) {
132 command = command_t::LIST_SERVICES;
134 else if (strcmp(argv[i], "shutdown") == 0) {
135 command = command_t::SHUTDOWN;
137 else if (strcmp(argv[i], "add-dep") == 0) {
138 command = command_t::ADD_DEPENDENCY;
140 else if (strcmp(argv[i], "rm-dep") == 0) {
141 command = command_t::RM_DEPENDENCY;
144 cerr << "dinitctl: unrecognized command: " << argv[i] << " (use --help for help)\n";
149 // service name / other non-option
150 if (command == command_t::ADD_DEPENDENCY || command == command_t::RM_DEPENDENCY) {
151 if (! dep_type_set) {
152 if (strcmp(argv[i], "regular") == 0) {
153 dep_type = dependency_type::REGULAR;
155 else if (strcmp(argv[i], "milestone") == 0) {
156 dep_type = dependency_type::MILESTONE;
158 else if (strcmp(argv[i], "waits-for") == 0) {
159 dep_type = dependency_type::WAITS_FOR;
167 else if (service_name == nullptr) {
168 service_name = argv[i];
170 else if (to_service_name == nullptr) {
171 to_service_name = argv[i];
179 if (service_name != nullptr) {
183 service_name = argv[i];
184 // TODO support multiple services
189 bool no_service_cmd = (command == command_t::LIST_SERVICES || command == command_t::SHUTDOWN);
191 if (service_name != nullptr && no_service_cmd) {
195 if ((service_name == nullptr && ! no_service_cmd) || command == command_t::NONE) {
199 if ((command == command_t::ADD_DEPENDENCY || command == command_t::RM_DEPENDENCY)
200 && (! dep_type_set || service_name == nullptr || to_service_name == nullptr)) {
205 cout << "dinitctl: control Dinit services\n"
208 " dinitctl [options] start [options] <service-name> : start and activate service\n"
209 " dinitctl [options] stop [options] <service-name> : stop service and cancel explicit activation\n"
210 " dinitctl [options] wake [options] <service-name> : start but do not mark activated\n"
211 " dinitctl [options] release [options] <service-name> : release activation, stop if no dependents\n"
212 " dinitctl [options] unpin <service-name> : un-pin the service (after a previous pin)\n"
213 " dinitctl unload <service-name> : unload the service\n"
214 " dinitctl list : list loaded services\n"
215 " dinitctl shutdown : stop all services and terminate dinit\n"
216 " dinitctl add-dep <type> <from-service> <to-service> : add a dependency between services\n"
217 " dinitctl rm-dep <type> <from-service> <to-service> : remove a dependency between services\n"
219 "Note: An activated service continues running when its dependents stop.\n"
222 " -s, --system : control system daemon instead of user daemon\n"
223 " --quiet : suppress output (except errors)\n"
226 " --help : show this help\n"
227 " --no-wait : don't wait for service startup/shutdown to complete\n"
228 " --pin : pin the service in the requested (started/stopped) state\n";
232 signal(SIGPIPE, SIG_IGN);
234 control_socket_path = "/dev/dinitctl";
236 // Locate control socket
238 char * userhome = getenv("HOME");
239 if (userhome == nullptr) {
240 struct passwd * pwuid_p = getpwuid(getuid());
241 if (pwuid_p != nullptr) {
242 userhome = pwuid_p->pw_dir;
246 if (userhome != nullptr) {
247 control_socket_str = userhome;
248 control_socket_str += "/.dinitctl";
249 control_socket_path = control_socket_str.c_str();
252 cerr << "Cannot locate user home directory (set HOME or check /etc/passwd file)" << endl;
257 int socknum = socket(AF_UNIX, SOCK_STREAM, 0);
259 perror("dinitctl: socket");
263 struct sockaddr_un * name;
264 uint sockaddr_size = offsetof(struct sockaddr_un, sun_path) + strlen(control_socket_path) + 1;
265 name = (struct sockaddr_un *) malloc(sockaddr_size);
266 if (name == nullptr) {
267 cerr << "dinitctl: Out of memory" << endl;
271 name->sun_family = AF_UNIX;
272 strcpy(name->sun_path, control_socket_path);
274 int connr = connect(socknum, (struct sockaddr *) name, sockaddr_size);
276 perror("dinitctl: connect");
281 // Start by querying protocol version:
283 check_protocol_version(min_cp_version, max_cp_version, rbuffer, socknum);
285 if (command == command_t::UNPIN_SERVICE) {
286 return unpin_service(socknum, rbuffer, service_name, verbose);
288 else if (command == command_t::UNLOAD_SERVICE) {
289 return unload_service(socknum, rbuffer, service_name);
291 else if (command == command_t::LIST_SERVICES) {
292 return list_services(socknum, rbuffer);
294 else if (command == command_t::SHUTDOWN) {
295 return shutdown_dinit(socknum, rbuffer);
297 else if (command == command_t::ADD_DEPENDENCY || command == command_t::RM_DEPENDENCY) {
298 return add_remove_dependency(socknum, rbuffer, command == command_t::ADD_DEPENDENCY,
299 service_name, to_service_name, dep_type);
302 return start_stop_service(socknum, rbuffer, service_name, command, do_pin,
303 wait_for_service, verbose);
306 catch (cp_old_client_exception &e) {
307 std::cerr << "dinitctl: too old (server reports newer protocol version)" << std::endl;
310 catch (cp_old_server_exception &e) {
311 std::cerr << "dinitctl: server too old or protocol error" << std::endl;
314 catch (cp_read_exception &e) {
315 cerr << "dinitctl: control socket read failure or protocol error" << endl;
318 catch (cp_write_exception &e) {
319 cerr << "dinitctl: control socket write error: " << std::strerror(e.errcode) << endl;
324 // Start/stop a service
325 static int start_stop_service(int socknum, cpbuffer_t &rbuffer, const char *service_name,
326 command_t command, bool do_pin, bool wait_for_service, bool verbose)
330 bool do_stop = (command == command_t::STOP_SERVICE || command == command_t::RELEASE_SERVICE);
332 if (issue_load_service(socknum, service_name)) {
336 // Now we expect a reply:
338 wait_for_reply(rbuffer, socknum);
340 service_state_t state;
341 //service_state_t target_state;
344 if (check_load_reply(socknum, rbuffer, &handle, &state) != 0) {
348 service_state_t wanted_state = do_stop ? service_state_t::STOPPED : service_state_t::STARTED;
351 case command_t::STOP_SERVICE:
352 pcommand = DINIT_CP_STOPSERVICE;
354 case command_t::RELEASE_SERVICE:
355 pcommand = DINIT_CP_RELEASESERVICE;
357 case command_t::START_SERVICE:
358 pcommand = DINIT_CP_STARTSERVICE;
360 case command_t::WAKE_SERVICE:
361 pcommand = DINIT_CP_WAKESERVICE;
366 // Need to issue STOPSERVICE/STARTSERVICE
367 // We'll do this regardless of the current service state / target state, since issuing
368 // start/stop also sets or clears the "explicitly started" flag on the service.
370 char buf[2 + sizeof(handle)];
372 buf[1] = do_pin ? 1 : 0;
373 memcpy(buf + 2, &handle, sizeof(handle));
374 write_all_x(socknum, buf, 2 + sizeof(handle));
376 wait_for_reply(rbuffer, socknum);
377 if (rbuffer[0] == DINIT_RP_ALREADYSS) {
378 bool already = (state == wanted_state);
380 cout << "Service " << (already ? "(already) " : "") << describeState(do_stop) << "." << endl;
382 return 0; // success!
384 if (rbuffer[0] != DINIT_RP_ACK) {
385 cerr << "dinitctl: Protocol error." << endl;
391 if (! wait_for_service) {
393 cout << "Issued " << describeVerb(do_stop) << " command successfully." << endl;
398 service_event_t completionEvent;
399 service_event_t cancelledEvent;
402 completionEvent = service_event_t::STOPPED;
403 cancelledEvent = service_event_t::STOPCANCELLED;
406 completionEvent = service_event_t::STARTED;
407 cancelledEvent = service_event_t::STARTCANCELLED;
410 // Wait until service started:
411 int r = rbuffer.fill_to(socknum, 2);
413 if (rbuffer[0] >= 100) {
414 int pktlen = (unsigned char) rbuffer[1];
415 fill_buffer_to(rbuffer, socknum, pktlen);
417 if (rbuffer[0] == DINIT_IP_SERVICEEVENT) {
419 rbuffer.extract((char *) &ev_handle, 2, sizeof(ev_handle));
420 service_event_t event = static_cast<service_event_t>(rbuffer[2 + sizeof(ev_handle)]);
421 if (ev_handle == handle) {
422 if (event == completionEvent) {
424 cout << "Service " << describeState(do_stop) << "." << endl;
428 else if (event == cancelledEvent) {
430 cout << "Service " << describeVerb(do_stop) << " cancelled." << endl;
434 else if (! do_stop && event == service_event_t::FAILEDSTART) {
436 cout << "Service failed to start." << endl;
443 rbuffer.consume(pktlen);
444 r = rbuffer.fill_to(socknum, 2);
447 // Not an information packet?
448 cerr << "dinitctl: protocol error" << endl;
454 perror("dinitctl: read");
457 cerr << "protocol error (connection closed by server)" << endl;
462 // Issue a "load service" command (DINIT_CP_LOADSERVICE), without waiting for
463 // a response. Returns 1 on failure (with error logged), 0 on success.
464 static int issue_load_service(int socknum, const char *service_name, bool find_only)
467 uint16_t sname_len = strlen(service_name);
468 int bufsize = 3 + sname_len;
470 std::unique_ptr<char[]> ubuf(new char[bufsize]);
471 auto buf = ubuf.get();
473 buf[0] = find_only ? DINIT_CP_FINDSERVICE : DINIT_CP_LOADSERVICE;
474 memcpy(buf + 1, &sname_len, 2);
475 memcpy(buf + 3, service_name, sname_len);
477 write_all_x(socknum, buf, bufsize);
482 // Check that a "load service" reply was received, and that the requested service was found.
483 static int check_load_reply(int socknum, cpbuffer_t &rbuffer, handle_t *handle_p, service_state_t *state_p)
487 if (rbuffer[0] == DINIT_RP_SERVICERECORD) {
488 fill_buffer_to(rbuffer, socknum, 2 + sizeof(*handle_p));
489 rbuffer.extract((char *) handle_p, 2, sizeof(*handle_p));
490 if (state_p) *state_p = static_cast<service_state_t>(rbuffer[1]);
491 //target_state = static_cast<service_state_t>(rbuffer[2 + sizeof(handle)]);
492 rbuffer.consume(3 + sizeof(*handle_p));
495 else if (rbuffer[0] == DINIT_RP_NOSERVICE) {
496 cerr << "dinitctl: failed to find/load service." << endl;
500 cerr << "dinitctl: protocol error." << endl;
505 static int unpin_service(int socknum, cpbuffer_t &rbuffer, const char *service_name, bool verbose)
510 if (issue_load_service(socknum, service_name) == 1) {
514 // Now we expect a reply:
516 wait_for_reply(rbuffer, socknum);
520 if (check_load_reply(socknum, rbuffer, &handle, nullptr) != 0) {
524 // Issue UNPIN command.
526 char buf[1 + sizeof(handle)];
527 buf[0] = DINIT_CP_UNPINSERVICE;
528 memcpy(buf + 1, &handle, sizeof(handle));
529 write_all_x(socknum, buf, 2 + sizeof(handle));
531 wait_for_reply(rbuffer, socknum);
532 if (rbuffer[0] != DINIT_RP_ACK) {
533 cerr << "dinitctl: protocol error." << endl;
540 cout << "Service unpinned." << endl;
545 static int unload_service(int socknum, cpbuffer_t &rbuffer, const char *service_name)
550 if (issue_load_service(socknum, service_name, true) == 1) {
554 // Now we expect a reply:
555 wait_for_reply(rbuffer, socknum);
559 if (rbuffer[0] == DINIT_RP_NOSERVICE) {
560 cerr << "dinitctl: service not loaded." << endl;
564 if (check_load_reply(socknum, rbuffer, &handle, nullptr) != 0) {
568 // Issue UNLOAD command.
570 char buf[1 + sizeof(handle)];
571 buf[0] = DINIT_CP_UNLOADSERVICE;
572 memcpy(buf + 1, &handle, sizeof(handle));
573 write_all_x(socknum, buf, 2 + sizeof(handle));
575 wait_for_reply(rbuffer, socknum);
576 if (rbuffer[0] == DINIT_RP_NAK) {
577 cerr << "dinitctl: Could not unload service; service not stopped, or is a dependency of "
578 "other service." << endl;
581 if (rbuffer[0] != DINIT_RP_ACK) {
582 cerr << "dinitctl: Protocol error." << endl;
588 cout << "Service unloaded." << endl;
592 static int list_services(int socknum, cpbuffer_t &rbuffer)
596 char cmdbuf[] = { (char)DINIT_CP_LISTSERVICES };
597 write_all_x(socknum, cmdbuf, 1);
599 wait_for_reply(rbuffer, socknum);
600 while (rbuffer[0] == DINIT_RP_SVCINFO) {
601 int hdrsize = 8 + std::max(sizeof(int), sizeof(pid_t));
602 fill_buffer_to(rbuffer, socknum, hdrsize);
603 int nameLen = rbuffer[1];
604 service_state_t current = static_cast<service_state_t>(rbuffer[2]);
605 service_state_t target = static_cast<service_state_t>(rbuffer[3]);
607 int console_flags = rbuffer[4];
608 bool has_console = (console_flags & 2) != 0;
609 bool waiting_console = (console_flags & 1) != 0;
610 bool was_skipped = (console_flags & 4) != 0;
612 stopped_reason_t stop_reason = static_cast<stopped_reason_t>(rbuffer[5]);
616 if (current != service_state_t::STOPPED) {
617 rbuffer.extract((char *)&service_pid, 8, sizeof(service_pid));
620 rbuffer.extract((char *)&exit_status, 8, sizeof(exit_status));
623 fill_buffer_to(rbuffer, socknum, nameLen + hdrsize);
625 char *name_ptr = rbuffer.get_ptr(hdrsize);
626 int clength = std::min(rbuffer.get_contiguous_length(name_ptr), nameLen);
628 string name = string(name_ptr, clength);
629 name.append(rbuffer.get_buf_base(), nameLen - clength);
633 cout << (target == service_state_t::STARTED ? "{" : " ");
634 if (current == service_state_t::STARTED) {
635 cout << (was_skipped ? "s" : "+");
640 cout << (target == service_state_t::STARTED ? "}" : " ");
642 if (current == service_state_t::STARTING) {
645 else if (current == service_state_t::STOPPING) {
652 cout << (target == service_state_t::STOPPED ? "{" : " ");
653 if (current == service_state_t::STOPPED) {
654 bool did_fail = false;
655 if (stop_reason == stopped_reason_t::TERMINATED) {
656 if (!WIFEXITED(exit_status) || WEXITSTATUS(exit_status) != 0) {
660 else did_fail = (stop_reason != stopped_reason_t::NORMAL);
662 cout << (did_fail ? "X" : "-");
667 cout << (target == service_state_t::STOPPED ? "}" : " ");
669 cout << "] " << name;
671 if (current != service_state_t::STOPPED && service_pid != -1) {
672 cout << " (pid: " << service_pid << ")";
675 if (current == service_state_t::STOPPED && stop_reason == stopped_reason_t::TERMINATED) {
676 if (WIFEXITED(exit_status)) {
677 cout << " (exit status: " << WEXITSTATUS(exit_status) << ")";
679 else if (WIFSIGNALED(exit_status)) {
680 cout << " (signal: " << WSTOPSIG(exit_status) << ")";
685 cout << " (has console)";
687 else if (waiting_console) {
688 cout << " (waiting for console)";
693 rbuffer.consume(hdrsize + nameLen);
694 wait_for_reply(rbuffer, socknum);
697 if (rbuffer[0] != DINIT_RP_LISTDONE) {
698 cerr << "dinitctl: Control socket protocol error" << endl;
705 static int add_remove_dependency(int socknum, cpbuffer_t &rbuffer, bool add, char *service_from,
706 char *service_to, dependency_type dep_type)
710 // First find the "from" service:
711 if (issue_load_service(socknum, service_from, false) == 1) {
715 wait_for_reply(rbuffer, socknum);
717 handle_t from_handle;
719 if (check_load_reply(socknum, rbuffer, &from_handle, nullptr) != 0) {
723 // Then find or load the "to" service:
724 if (issue_load_service(socknum, service_to, false) == 1) {
728 wait_for_reply(rbuffer, socknum);
732 if (check_load_reply(socknum, rbuffer, &to_handle, nullptr) != 0) {
736 constexpr int pktsize = 2 + sizeof(handle_t) * 2;
737 char cmdbuf[pktsize] = { add ? (char)DINIT_CP_ADD_DEP : (char)DINIT_CP_REM_DEP, (char)dep_type};
738 memcpy(cmdbuf + 2, &from_handle, sizeof(from_handle));
739 memcpy(cmdbuf + 2 + sizeof(from_handle), &to_handle, sizeof(to_handle));
740 write_all_x(socknum, cmdbuf, pktsize);
742 wait_for_reply(rbuffer, socknum);
745 if (rbuffer[0] == DINIT_RP_NAK) {
746 cerr << "dinitctl: Could not add dependency: circular dependency or wrong state" << endl;
749 if (rbuffer[0] != DINIT_RP_ACK) {
750 cerr << "dinitctl: Control socket protocol error" << endl;
757 static int shutdown_dinit(int socknum, cpbuffer_t &rbuffer)
759 // TODO support no-wait option.
763 constexpr int bufsize = 2;
766 buf[0] = DINIT_CP_SHUTDOWN;
767 buf[1] = static_cast<char>(shutdown_type_t::HALT);
769 write_all_x(socknum, buf, bufsize);
771 wait_for_reply(rbuffer, socknum);
773 if (rbuffer[0] != DINIT_RP_ACK) {
774 cerr << "dinitctl: Control socket protocol error" << endl;
778 // Now wait for rollback complete:
781 wait_for_info(rbuffer, socknum);
782 if (rbuffer[0] == DINIT_ROLLBACK_COMPLETED) {
787 catch (cp_read_exception &exc) {
788 // Dinit can terminate before replying: let's assume that happened.
789 // TODO: better check, possibly ensure that dinit actually sends rollback complete before