6 #include <system_error>
10 #include <sys/socket.h>
15 #include "control-cmds.h"
16 #include "service-constants.h"
19 // dinitctl: utility to control the Dinit daemon, including starting and stopping of services.
21 // This utility communicates with the dinit daemon via a unix socket (/dev/initctl).
23 using handle_t = uint32_t;
30 ReadCPException(int err) : errcode(err) { }
33 static void fillBufferTo(CPBuffer *buf, int fd, int rlength)
35 int r = buf->fillTo(fd, rlength);
37 throw ReadCPException(errno);
40 throw ReadCPException(0);
44 static const char * describeState(bool stopped)
46 return stopped ? "stopped" : "started";
49 static const char * describeVerb(bool stop)
51 return stop ? "stop" : "start";
54 // Wait for a reply packet, skipping over any information packets
55 // that are received in the meantime.
56 static void wait_for_reply(CPBuffer &rbuffer, int fd)
58 fillBufferTo(&rbuffer, fd, 1);
60 while (rbuffer[0] >= 100) {
61 // Information packet; discard.
62 fillBufferTo(&rbuffer, fd, 1);
63 int pktlen = (unsigned char) rbuffer[1];
65 rbuffer.consume(1); // Consume one byte so we'll read one byte of the next packet
66 fillBufferTo(&rbuffer, fd, pktlen);
67 rbuffer.consume(pktlen - 1);
72 // Write *all* the requested buffer and re-try if necessary until
73 // the buffer is written or an unrecoverable error occurs.
74 static int write_all(int fd, const void *buf, size_t count)
76 const char *cbuf = static_cast<const char *>(buf);
79 int r = write(fd, cbuf, count);
81 if (errno == EINTR) continue;
91 static int unpinService(int socknum, const char *service_name);
95 int main(int argc, char **argv)
100 bool show_help = argc < 2;
101 char *service_name = nullptr;
103 std::string control_socket_str;
104 const char * control_socket_path = nullptr;
107 bool sys_dinit = false; // communicate with system daemon
108 bool wait_for_service = true;
113 constexpr int START_SERVICE = 1;
114 constexpr int STOP_SERVICE = 2;
115 constexpr int UNPIN_SERVICE = 3;
117 for (int i = 1; i < argc; i++) {
118 if (argv[i][0] == '-') {
119 if (strcmp(argv[i], "--help") == 0) {
123 else if (strcmp(argv[i], "--no-wait") == 0) {
124 wait_for_service = false;
126 else if (strcmp(argv[i], "--quiet") == 0) {
129 else if (strcmp(argv[i], "--system") == 0 || strcmp(argv[i], "-s") == 0) {
132 else if (strcmp(argv[i], "--pin") == 0) {
136 cerr << "Unrecognized command-line parameter: " << argv[i] << endl;
140 else if (command == 0) {
141 if (strcmp(argv[i], "start") == 0) {
142 command = START_SERVICE;
144 else if (strcmp(argv[i], "stop") == 0) {
145 command = STOP_SERVICE;
147 else if (strcmp(argv[i], "unpin") == 0) {
148 command = UNPIN_SERVICE;
157 service_name = argv[i];
158 // TODO support multiple services (or at least give error if multiple
159 // services supplied)
163 if (service_name == nullptr || command == 0) {
168 cout << "dinitctl: control Dinit services" << endl;
170 cout << "\nUsage:" << endl;
171 cout << " dinitctl [options] start [options] <service-name> : start and activate service" << endl;
172 cout << " dinitctl [options] stop [options] <service-name> : stop service and cancel explicit activation" << endl;
174 // cout << " dinitctl [options] wake <service-name> : start but don't activate service" << endl;
176 cout << "\nNote: An activated service keeps its dependencies running when possible." << endl;
178 cout << "\nGeneral options:" << endl;
179 cout << " -s, --system : control system daemon instead of user daemon" << endl;
180 cout << " --quiet : suppress output (except errors)" << endl;
182 cout << "\nCommand options:" << endl;
183 cout << " --help : show this help" << endl;
184 cout << " --no-wait : don't wait for service startup/shutdown to complete" << endl;
185 cout << " --pin : pin the service in the requested (started/stopped) state" << endl;
189 control_socket_path = "/dev/dinitctl";
192 char * userhome = getenv("HOME");
193 if (userhome == nullptr) {
194 struct passwd * pwuid_p = getpwuid(getuid());
195 if (pwuid_p != nullptr) {
196 userhome = pwuid_p->pw_dir;
200 if (userhome != nullptr) {
201 control_socket_str = userhome;
202 control_socket_str += "/.dinitctl";
203 control_socket_path = control_socket_str.c_str();
206 cerr << "Cannot locate user home directory (set HOME or check /etc/passwd file)" << endl;
211 int socknum = socket(AF_UNIX, SOCK_STREAM, 0);
217 struct sockaddr_un * name;
218 uint sockaddr_size = offsetof(struct sockaddr_un, sun_path) + strlen(control_socket_path) + 1;
219 name = (struct sockaddr_un *) malloc(sockaddr_size);
220 if (name == nullptr) {
221 cerr << "dinit-start: out of memory" << endl;
225 name->sun_family = AF_UNIX;
226 strcpy(name->sun_path, control_socket_path);
228 int connr = connect(socknum, (struct sockaddr *) name, sockaddr_size);
234 // TODO should start by querying protocol version
236 if (command == UNPIN_SERVICE) {
237 return unpinService(socknum, service_name);
240 do_stop = (command == STOP_SERVICE);
243 uint16_t sname_len = strlen(service_name);
244 int bufsize = 3 + sname_len;
248 unique_ptr<char[]> ubuf(new char[bufsize]);
249 auto *buf = ubuf.get();
251 buf[0] = DINIT_CP_LOADSERVICE;
252 memcpy(buf + 1, &sname_len, 2);
253 memcpy(buf + 3, service_name, sname_len);
255 r = write_all(socknum, buf, bufsize);
263 // Now we expect a reply:
267 wait_for_reply(rbuffer, socknum);
269 //ServiceState state;
270 //ServiceState target_state;
273 if (rbuffer[0] == DINIT_RP_SERVICERECORD) {
274 fillBufferTo(&rbuffer, socknum, 2 + sizeof(handle));
275 rbuffer.extract((char *) &handle, 2, sizeof(handle));
276 //state = static_cast<ServiceState>(rbuffer[1]);
277 //target_state = static_cast<ServiceState>(rbuffer[2 + sizeof(handle)]);
278 rbuffer.consume(3 + sizeof(handle));
280 else if (rbuffer[0] == DINIT_RP_NOSERVICE) {
281 cerr << "Failed to find/load service." << endl;
285 cerr << "Protocol error." << endl;
289 // ServiceState wanted_state = do_stop ? ServiceState::STOPPED : ServiceState::STARTED;
290 int command = do_stop ? DINIT_CP_STOPSERVICE : DINIT_CP_STARTSERVICE;
292 // Need to issue STOPSERVICE/STARTSERVICE
293 // We'll do this regardless of the current service state / target state, since issuing
294 // start/stop also sets or clears the "explicitly started" flag on the service.
295 //if (target_state != wanted_state) {
298 auto buf = new char[2 + sizeof(handle)];
299 unique_ptr<char[]> ubuf(buf);
302 buf[1] = do_pin ? 1 : 0;
303 memcpy(buf + 2, &handle, sizeof(handle));
304 r = write_all(socknum, buf, 2 + sizeof(handle));
312 wait_for_reply(rbuffer, socknum);
313 if (rbuffer[0] == DINIT_RP_ALREADYSS) {
315 cout << "Service already " << describeState(do_stop) << "." << endl;
317 return 0; // success!
319 if (rbuffer[0] != DINIT_RP_ACK) {
320 cerr << "Protocol error." << endl;
327 if (state == wanted_state) {
329 cout << "Service already " << describeState(do_stop) << "." << endl;
331 return 0; // success!
335 if (! wait_for_service) {
337 cout << "Issued " << describeVerb(do_stop) << " command successfully." << endl;
342 ServiceEvent completionEvent;
343 ServiceEvent cancelledEvent;
346 completionEvent = ServiceEvent::STOPPED;
347 cancelledEvent = ServiceEvent::STOPCANCELLED;
350 completionEvent = ServiceEvent::STARTED;
351 cancelledEvent = ServiceEvent::STARTCANCELLED;
354 // Wait until service started:
355 r = rbuffer.fillTo(socknum, 2);
357 if (rbuffer[0] >= 100) {
358 int pktlen = (unsigned char) rbuffer[1];
359 fillBufferTo(&rbuffer, socknum, pktlen);
361 if (rbuffer[0] == DINIT_IP_SERVICEEVENT) {
363 rbuffer.extract((char *) &ev_handle, 2, sizeof(ev_handle));
364 ServiceEvent event = static_cast<ServiceEvent>(rbuffer[2 + sizeof(ev_handle)]);
365 if (ev_handle == handle) {
366 if (event == completionEvent) {
368 cout << "Service " << describeState(do_stop) << "." << endl;
372 else if (event == cancelledEvent) {
374 cout << "Service " << describeVerb(do_stop) << " cancelled." << endl;
378 else if (! do_stop && event == ServiceEvent::FAILEDSTART) {
380 cout << "Service failed to start." << endl;
387 rbuffer.consume(pktlen);
388 r = rbuffer.fillTo(socknum, 2);
391 // Not an information packet?
392 cerr << "protocol error" << endl;
401 cerr << "protocol error (connection closed by server)" << endl;
405 catch (ReadCPException &exc) {
406 cerr << "control socket read failure or protocol error" << endl;
409 catch (std::bad_alloc &exc) {
410 cerr << "out of memory" << endl;
417 // TODO refactor shared code with above
418 static int unpinService(int socknum, const char *service_name)
423 uint16_t sname_len = strlen(service_name);
424 int bufsize = 3 + sname_len;
428 char * buf = new char[bufsize];
429 unique_ptr<char[]> ubuf(buf);
431 buf[0] = DINIT_CP_LOADSERVICE;
432 memcpy(buf + 1, &sname_len, 2);
433 memcpy(buf + 3, service_name, sname_len);
435 r = write_all(socknum, buf, bufsize);
443 // Now we expect a reply:
447 wait_for_reply(rbuffer, socknum);
449 //ServiceState state;
450 //ServiceState target_state;
453 if (rbuffer[0] == DINIT_RP_SERVICERECORD) {
454 fillBufferTo(&rbuffer, socknum, 2 + sizeof(handle));
455 rbuffer.extract((char *) &handle, 2, sizeof(handle));
456 //state = static_cast<ServiceState>(rbuffer[1]);
457 //target_state = static_cast<ServiceState>(rbuffer[2 + sizeof(handle)]);
458 rbuffer.consume(3 + sizeof(handle));
460 else if (rbuffer[0] == DINIT_RP_NOSERVICE) {
461 cerr << "Failed to find/load service." << endl;
465 cerr << "Protocol error." << endl;
469 // Issue UNPIN command.
472 char *buf = new char[1 + sizeof(handle)];
473 unique_ptr<char[]> ubuf(buf);
474 buf[0] = DINIT_CP_UNPINSERVICE;
475 memcpy(buf + 1, &handle, sizeof(handle));
476 r = write_all(socknum, buf, 2 + sizeof(handle));
484 wait_for_reply(rbuffer, socknum);
485 if (rbuffer[0] != DINIT_RP_ACK) {
486 cerr << "Protocol error." << endl;
492 catch (ReadCPException &exc) {
493 cerr << "control socket read failure or protocol error" << endl;
496 catch (std::bad_alloc &exc) {
497 cerr << "out of memory" << endl;
501 cout << "Service unpinned." << endl;