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 &);
41 static const char * describeState(bool stopped)
43 return stopped ? "stopped" : "started";
46 static const char * describeVerb(bool stop)
48 return stop ? "stop" : "start";
51 enum class command_t {
65 int main(int argc, char **argv)
69 bool show_help = argc < 2;
70 char *service_name = nullptr;
72 std::string control_socket_str;
73 const char * control_socket_path = nullptr;
76 bool sys_dinit = false; // communicate with system daemon
77 bool wait_for_service = true;
80 command_t command = command_t::NONE;
82 for (int i = 1; i < argc; i++) {
83 if (argv[i][0] == '-') {
84 if (strcmp(argv[i], "--help") == 0) {
88 else if (strcmp(argv[i], "--no-wait") == 0) {
89 wait_for_service = false;
91 else if (strcmp(argv[i], "--quiet") == 0) {
94 else if (strcmp(argv[i], "--system") == 0 || strcmp(argv[i], "-s") == 0) {
97 else if (strcmp(argv[i], "--pin") == 0) {
104 else if (command == command_t::NONE) {
105 if (strcmp(argv[i], "start") == 0) {
106 command = command_t::START_SERVICE;
108 else if (strcmp(argv[i], "wake") == 0) {
109 command = command_t::WAKE_SERVICE;
111 else if (strcmp(argv[i], "stop") == 0) {
112 command = command_t::STOP_SERVICE;
114 else if (strcmp(argv[i], "release") == 0) {
115 command = command_t::RELEASE_SERVICE;
117 else if (strcmp(argv[i], "unpin") == 0) {
118 command = command_t::UNPIN_SERVICE;
120 else if (strcmp(argv[i], "unload") == 0) {
121 command = command_t::UNLOAD_SERVICE;
123 else if (strcmp(argv[i], "list") == 0) {
124 command = command_t::LIST_SERVICES;
126 else if (strcmp(argv[i], "shutdown") == 0) {
127 command = command_t::SHUTDOWN;
136 if (service_name != nullptr) {
140 service_name = argv[i];
141 // TODO support multiple services
145 bool no_service_cmd = (command == command_t::LIST_SERVICES || command == command_t::SHUTDOWN);
147 if (service_name != nullptr && no_service_cmd) {
151 if ((service_name == nullptr && ! no_service_cmd) || command == command_t::NONE) {
156 cout << "dinitctl: control Dinit services" << endl;
158 cout << "\nUsage:" << endl;
159 cout << " dinitctl [options] start [options] <service-name> : start and activate service" << endl;
160 cout << " dinitctl [options] stop [options] <service-name> : stop service and cancel explicit activation" << endl;
161 cout << " dinitctl [options] wake [options] <service-name> : start but do not mark activated" << endl;
162 cout << " dinitctl [options] release [options] <service-name> : release activation, stop if no dependents" << endl;
163 cout << " dinitctl [options] unpin <service-name> : un-pin the service (after a previous pin)" << endl;
164 cout << " dinitctl unload <service-name> : unload the service" << endl;
165 cout << " dinitctl list : list loaded services" << endl;
166 cout << " dinitctl shutdown : stop all services and terminate dinit" << endl;
168 cout << "\nNote: An activated service continues running when its dependents stop." << endl;
170 cout << "\nGeneral options:" << endl;
171 cout << " -s, --system : control system daemon instead of user daemon" << endl;
172 cout << " --quiet : suppress output (except errors)" << endl;
174 cout << "\nCommand options:" << endl;
175 cout << " --help : show this help" << endl;
176 cout << " --no-wait : don't wait for service startup/shutdown to complete" << endl;
177 cout << " --pin : pin the service in the requested (started/stopped) state" << endl;
181 signal(SIGPIPE, SIG_IGN);
183 control_socket_path = "/dev/dinitctl";
185 // Locate control socket
187 char * userhome = getenv("HOME");
188 if (userhome == nullptr) {
189 struct passwd * pwuid_p = getpwuid(getuid());
190 if (pwuid_p != nullptr) {
191 userhome = pwuid_p->pw_dir;
195 if (userhome != nullptr) {
196 control_socket_str = userhome;
197 control_socket_str += "/.dinitctl";
198 control_socket_path = control_socket_str.c_str();
201 cerr << "Cannot locate user home directory (set HOME or check /etc/passwd file)" << endl;
206 int socknum = socket(AF_UNIX, SOCK_STREAM, 0);
208 perror("dinitctl: socket");
212 struct sockaddr_un * name;
213 uint sockaddr_size = offsetof(struct sockaddr_un, sun_path) + strlen(control_socket_path) + 1;
214 name = (struct sockaddr_un *) malloc(sockaddr_size);
215 if (name == nullptr) {
216 cerr << "dinitctl: Out of memory" << endl;
220 name->sun_family = AF_UNIX;
221 strcpy(name->sun_path, control_socket_path);
223 int connr = connect(socknum, (struct sockaddr *) name, sockaddr_size);
225 perror("dinitctl: connect");
230 // Start by querying protocol version:
232 check_protocol_version(min_cp_version, max_cp_version, rbuffer, socknum);
234 if (command == command_t::UNPIN_SERVICE) {
235 return unpin_service(socknum, rbuffer, service_name, verbose);
237 else if (command == command_t::UNLOAD_SERVICE) {
238 return unload_service(socknum, rbuffer, service_name);
240 else if (command == command_t::LIST_SERVICES) {
241 return list_services(socknum, rbuffer);
243 else if (command == command_t::SHUTDOWN) {
244 return shutdown_dinit(socknum, rbuffer);
247 return start_stop_service(socknum, rbuffer, service_name, command, do_pin,
248 wait_for_service, verbose);
251 catch (cp_old_client_exception &e) {
252 std::cerr << "dinitctl: too old (server reports newer protocol version)" << std::endl;
255 catch (cp_old_server_exception &e) {
256 std::cerr << "dinitctl: server too old or protocol error" << std::endl;
259 catch (cp_read_exception &e) {
260 cerr << "dinitctl: control socket read failure or protocol error" << endl;
263 catch (cp_write_exception &e) {
264 cerr << "dinitctl: control socket write error: " << std::strerror(e.errcode) << endl;
269 // Start/stop a service
270 static int start_stop_service(int socknum, cpbuffer_t &rbuffer, const char *service_name,
271 command_t command, bool do_pin, bool wait_for_service, bool verbose)
275 bool do_stop = (command == command_t::STOP_SERVICE || command == command_t::RELEASE_SERVICE);
277 if (issue_load_service(socknum, service_name)) {
281 // Now we expect a reply:
283 wait_for_reply(rbuffer, socknum);
285 service_state_t state;
286 //service_state_t target_state;
289 if (check_load_reply(socknum, rbuffer, &handle, &state) != 0) {
293 service_state_t wanted_state = do_stop ? service_state_t::STOPPED : service_state_t::STARTED;
296 case command_t::STOP_SERVICE:
297 pcommand = DINIT_CP_STOPSERVICE;
299 case command_t::RELEASE_SERVICE:
300 pcommand = DINIT_CP_RELEASESERVICE;
302 case command_t::START_SERVICE:
303 pcommand = DINIT_CP_STARTSERVICE;
305 case command_t::WAKE_SERVICE:
306 pcommand = DINIT_CP_WAKESERVICE;
311 // Need to issue STOPSERVICE/STARTSERVICE
312 // We'll do this regardless of the current service state / target state, since issuing
313 // start/stop also sets or clears the "explicitly started" flag on the service.
315 char buf[2 + sizeof(handle)];
317 buf[1] = do_pin ? 1 : 0;
318 memcpy(buf + 2, &handle, sizeof(handle));
319 write_all_x(socknum, buf, 2 + sizeof(handle));
321 wait_for_reply(rbuffer, socknum);
322 if (rbuffer[0] == DINIT_RP_ALREADYSS) {
323 bool already = (state == wanted_state);
325 cout << "Service " << (already ? "(already) " : "") << describeState(do_stop) << "." << endl;
327 return 0; // success!
329 if (rbuffer[0] != DINIT_RP_ACK) {
330 cerr << "dinitctl: Protocol error." << endl;
336 if (! wait_for_service) {
338 cout << "Issued " << describeVerb(do_stop) << " command successfully." << endl;
343 service_event_t completionEvent;
344 service_event_t cancelledEvent;
347 completionEvent = service_event_t::STOPPED;
348 cancelledEvent = service_event_t::STOPCANCELLED;
351 completionEvent = service_event_t::STARTED;
352 cancelledEvent = service_event_t::STARTCANCELLED;
355 // Wait until service started:
356 int r = rbuffer.fill_to(socknum, 2);
358 if (rbuffer[0] >= 100) {
359 int pktlen = (unsigned char) rbuffer[1];
360 fill_buffer_to(rbuffer, socknum, pktlen);
362 if (rbuffer[0] == DINIT_IP_SERVICEEVENT) {
364 rbuffer.extract((char *) &ev_handle, 2, sizeof(ev_handle));
365 service_event_t event = static_cast<service_event_t>(rbuffer[2 + sizeof(ev_handle)]);
366 if (ev_handle == handle) {
367 if (event == completionEvent) {
369 cout << "Service " << describeState(do_stop) << "." << endl;
373 else if (event == cancelledEvent) {
375 cout << "Service " << describeVerb(do_stop) << " cancelled." << endl;
379 else if (! do_stop && event == service_event_t::FAILEDSTART) {
381 cout << "Service failed to start." << endl;
388 rbuffer.consume(pktlen);
389 r = rbuffer.fill_to(socknum, 2);
392 // Not an information packet?
393 cerr << "dinitctl: protocol error" << endl;
399 perror("dinitctl: read");
402 cerr << "protocol error (connection closed by server)" << endl;
407 // Issue a "load service" command (DINIT_CP_LOADSERVICE), without waiting for
408 // a response. Returns 1 on failure (with error logged), 0 on success.
409 static int issue_load_service(int socknum, const char *service_name, bool find_only)
412 uint16_t sname_len = strlen(service_name);
413 int bufsize = 3 + sname_len;
415 std::unique_ptr<char[]> ubuf(new char[bufsize]);
416 auto buf = ubuf.get();
418 buf[0] = find_only ? DINIT_CP_FINDSERVICE : DINIT_CP_LOADSERVICE;
419 memcpy(buf + 1, &sname_len, 2);
420 memcpy(buf + 3, service_name, sname_len);
422 write_all_x(socknum, buf, bufsize);
427 // Check that a "load service" reply was received, and that the requested service was found.
428 static int check_load_reply(int socknum, cpbuffer_t &rbuffer, handle_t *handle_p, service_state_t *state_p)
432 if (rbuffer[0] == DINIT_RP_SERVICERECORD) {
433 fill_buffer_to(rbuffer, socknum, 2 + sizeof(*handle_p));
434 rbuffer.extract((char *) handle_p, 2, sizeof(*handle_p));
435 if (state_p) *state_p = static_cast<service_state_t>(rbuffer[1]);
436 //target_state = static_cast<service_state_t>(rbuffer[2 + sizeof(handle)]);
437 rbuffer.consume(3 + sizeof(*handle_p));
440 else if (rbuffer[0] == DINIT_RP_NOSERVICE) {
441 cerr << "dinitctl: failed to find/load service." << endl;
445 cerr << "dinitctl: protocol error." << endl;
450 static int unpin_service(int socknum, cpbuffer_t &rbuffer, const char *service_name, bool verbose)
455 if (issue_load_service(socknum, service_name) == 1) {
459 // Now we expect a reply:
461 wait_for_reply(rbuffer, socknum);
465 if (check_load_reply(socknum, rbuffer, &handle, nullptr) != 0) {
469 // Issue UNPIN command.
471 char buf[1 + sizeof(handle)];
472 buf[0] = DINIT_CP_UNPINSERVICE;
473 memcpy(buf + 1, &handle, sizeof(handle));
474 write_all_x(socknum, buf, 2 + sizeof(handle));
476 wait_for_reply(rbuffer, socknum);
477 if (rbuffer[0] != DINIT_RP_ACK) {
478 cerr << "dinitctl: protocol error." << endl;
485 cout << "Service unpinned." << endl;
490 static int unload_service(int socknum, cpbuffer_t &rbuffer, const char *service_name)
495 if (issue_load_service(socknum, service_name, true) == 1) {
499 // Now we expect a reply:
501 wait_for_reply(rbuffer, socknum);
505 if (check_load_reply(socknum, rbuffer, &handle, nullptr) != 0) {
509 // Issue UNLOAD command.
511 char buf[1 + sizeof(handle)];
512 buf[0] = DINIT_CP_UNLOADSERVICE;
513 memcpy(buf + 1, &handle, sizeof(handle));
514 write_all_x(socknum, buf, 2 + sizeof(handle));
516 wait_for_reply(rbuffer, socknum);
517 if (rbuffer[0] == DINIT_RP_NAK) {
518 cerr << "dinitctl: Could not unload service; service not stopped, or is a dependency of "
519 "other service." << endl;
522 if (rbuffer[0] != DINIT_RP_ACK) {
523 cerr << "dinitctl: Protocol error." << endl;
529 cout << "Service unloaded." << endl;
533 static int list_services(int socknum, cpbuffer_t &rbuffer)
537 char cmdbuf[] = { (char)DINIT_CP_LISTSERVICES };
538 write_all_x(socknum, cmdbuf, 1);
540 wait_for_reply(rbuffer, socknum);
541 while (rbuffer[0] == DINIT_RP_SVCINFO) {
542 int hdrsize = 8 + std::max(sizeof(int), sizeof(pid_t));
543 fill_buffer_to(rbuffer, socknum, hdrsize);
544 int nameLen = rbuffer[1];
545 service_state_t current = static_cast<service_state_t>(rbuffer[2]);
546 service_state_t target = static_cast<service_state_t>(rbuffer[3]);
548 int console_flags = rbuffer[4];
549 bool has_console = (console_flags & 2) != 0;
550 bool waiting_console = (console_flags & 1) != 0;
551 bool was_skipped = (console_flags & 4) != 0;
553 stopped_reason_t stop_reason = static_cast<stopped_reason_t>(rbuffer[5]);
557 if (current != service_state_t::STOPPED) {
558 rbuffer.extract((char *)&service_pid, 8, sizeof(service_pid));
561 rbuffer.extract((char *)&exit_status, 8, sizeof(exit_status));
564 fill_buffer_to(rbuffer, socknum, nameLen + hdrsize);
566 char *name_ptr = rbuffer.get_ptr(hdrsize);
567 int clength = std::min(rbuffer.get_contiguous_length(name_ptr), nameLen);
569 string name = string(name_ptr, clength);
570 name.append(rbuffer.get_buf_base(), nameLen - clength);
574 cout << (target == service_state_t::STARTED ? "{" : " ");
575 if (current == service_state_t::STARTED) {
576 cout << (was_skipped ? "s" : "+");
581 cout << (target == service_state_t::STARTED ? "}" : " ");
583 if (current == service_state_t::STARTING) {
586 else if (current == service_state_t::STOPPING) {
593 cout << (target == service_state_t::STOPPED ? "{" : " ");
594 if (current == service_state_t::STOPPED) {
595 bool did_fail = false;
596 if (stop_reason == stopped_reason_t::TERMINATED) {
597 if (!WIFEXITED(exit_status) || WEXITSTATUS(exit_status) != 0) {
601 else did_fail = (stop_reason != stopped_reason_t::NORMAL);
603 cout << (did_fail ? "X" : "-");
605 cout << (target == service_state_t::STOPPED ? "}" : " ");
607 cout << "] " << name;
609 if (current != service_state_t::STOPPED && service_pid != -1) {
610 cout << " (pid: " << service_pid << ")";
613 if (current == service_state_t::STOPPED && stop_reason == stopped_reason_t::TERMINATED) {
614 if (WIFEXITED(exit_status)) {
615 cout << " (exit status: " << WEXITSTATUS(exit_status) << ")";
617 else if (WIFSIGNALED(exit_status)) {
618 cout << " (signal: " << WSTOPSIG(exit_status) << ")";
623 cout << " (has console)";
625 else if (waiting_console) {
626 cout << " (waiting for console)";
631 rbuffer.consume(hdrsize + nameLen);
632 wait_for_reply(rbuffer, socknum);
635 if (rbuffer[0] != DINIT_RP_LISTDONE) {
636 cerr << "dinitctl: Control socket protocol error" << endl;
643 static int shutdown_dinit(int socknum, cpbuffer_t &rbuffer)
645 // TODO support no-wait option.
649 constexpr int bufsize = 2;
652 buf[0] = DINIT_CP_SHUTDOWN;
653 buf[1] = static_cast<char>(shutdown_type_t::HALT);
655 write_all_x(socknum, buf, bufsize);
657 wait_for_reply(rbuffer, socknum);
659 if (rbuffer[0] != DINIT_RP_ACK) {
660 cerr << "dinitctl: Control socket protocol error" << endl;
664 // Now wait for rollback complete:
667 wait_for_info(rbuffer, socknum);
668 if (rbuffer[0] == DINIT_ROLLBACK_COMPLETED) {
673 catch (cp_read_exception &exc) {
674 // Dinit can terminate before replying: let's assume that happened.
675 // TODO: better check, possibly ensure that dinit actually sends rollback complete before