1bf06f771ce10821869d4223abe789cec7a87e6a
[oweals/dinit.git] / src / dinitctl.cc
1 #include <cstdio>
2 #include <cstddef>
3 #include <cstring>
4 #include <string>
5 #include <iostream>
6 #include <system_error>
7 #include <memory>
8
9 #include <sys/types.h>
10 #include <sys/socket.h>
11 #include <sys/un.h>
12 #include <unistd.h>
13 #include <signal.h>
14 #include <pwd.h>
15
16 #include "control-cmds.h"
17 #include "service-constants.h"
18 #include "cpbuffer.h"
19 #include "dinit-client.h"
20
21 // dinitctl:  utility to control the Dinit daemon, including starting and stopping of services.
22
23 // This utility communicates with the dinit daemon via a unix stream socket (/dev/initctl, or $HOME/.dinitctl).
24
25 static constexpr uint16_t min_cp_version = 1;
26 static constexpr uint16_t max_cp_version = 1;
27
28 enum class command_t;
29
30 static int issue_load_service(int socknum, const char *service_name, bool find_only = false);
31 static int check_load_reply(int socknum, cpbuffer_t &, handle_t *handle_p, service_state_t *state_p);
32 static int start_stop_service(int socknum, cpbuffer_t &, const char *service_name, command_t command,
33         bool do_pin, bool wait_for_service, bool verbose);
34 static int unpin_service(int socknum, cpbuffer_t &, const char *service_name, bool verbose);
35 static int unload_service(int socknum, cpbuffer_t &, const char *service_name);
36 static int list_services(int socknum, cpbuffer_t &);
37 static int shutdown_dinit(int soclknum, cpbuffer_t &);
38
39
40 static const char * describeState(bool stopped)
41 {
42     return stopped ? "stopped" : "started";
43 }
44
45 static const char * describeVerb(bool stop)
46 {
47     return stop ? "stop" : "start";
48 }
49
50 enum class command_t {
51     NONE,
52     START_SERVICE,
53     WAKE_SERVICE,
54     STOP_SERVICE,
55     RELEASE_SERVICE,
56     UNPIN_SERVICE,
57     UNLOAD_SERVICE,
58     LIST_SERVICES,
59     SHUTDOWN
60 };
61
62
63 // Entry point.
64 int main(int argc, char **argv)
65 {
66     using namespace std;
67     
68     bool show_help = argc < 2;
69     char *service_name = nullptr;
70     
71     std::string control_socket_str;
72     const char * control_socket_path = nullptr;
73     
74     bool verbose = true;
75     bool sys_dinit = false;  // communicate with system daemon
76     bool wait_for_service = true;
77     bool do_pin = false;
78     
79     command_t command = command_t::NONE;
80         
81     for (int i = 1; i < argc; i++) {
82         if (argv[i][0] == '-') {
83             if (strcmp(argv[i], "--help") == 0) {
84                 show_help = true;
85                 break;
86             }
87             else if (strcmp(argv[i], "--no-wait") == 0) {
88                 wait_for_service = false;
89             }
90             else if (strcmp(argv[i], "--quiet") == 0) {
91                 verbose = false;
92             }
93             else if (strcmp(argv[i], "--system") == 0 || strcmp(argv[i], "-s") == 0) {
94                 sys_dinit = true;
95             }
96             else if (strcmp(argv[i], "--pin") == 0) {
97                 do_pin = true;
98             }
99             else {
100                 return 1;
101             }
102         }
103         else if (command == command_t::NONE) {
104             if (strcmp(argv[i], "start") == 0) {
105                 command = command_t::START_SERVICE; 
106             }
107             else if (strcmp(argv[i], "wake") == 0) {
108                 command = command_t::WAKE_SERVICE;
109             }
110             else if (strcmp(argv[i], "stop") == 0) {
111                 command = command_t::STOP_SERVICE;
112             }
113             else if (strcmp(argv[i], "release") == 0) {
114                 command = command_t::RELEASE_SERVICE;
115             }
116             else if (strcmp(argv[i], "unpin") == 0) {
117                 command = command_t::UNPIN_SERVICE;
118             }
119             else if (strcmp(argv[i], "unload") == 0) {
120                 command = command_t::UNLOAD_SERVICE;
121             }
122             else if (strcmp(argv[i], "list") == 0) {
123                 command = command_t::LIST_SERVICES;
124             }
125             else if (strcmp(argv[i], "shutdown") == 0) {
126                 command = command_t::SHUTDOWN;
127             }
128             else {
129                 show_help = true;
130                 break;
131             }
132         }
133         else {
134             // service name
135             if (service_name != nullptr) {
136                 show_help = true;
137                 break;
138             }
139             service_name = argv[i];
140             // TODO support multiple services
141         }
142     }
143     
144     bool no_service_cmd = (command == command_t::LIST_SERVICES || command == command_t::SHUTDOWN);
145
146     if (service_name != nullptr && no_service_cmd) {
147         show_help = true;
148     }
149     
150     if ((service_name == nullptr && ! no_service_cmd) || command == command_t::NONE) {
151         show_help = true;
152     }
153
154     if (show_help) {
155         cout << "dinitctl:   control Dinit services" << endl;
156         
157         cout << "\nUsage:" << endl;
158         cout << "    dinitctl [options] start [options] <service-name> : start and activate service" << endl;
159         cout << "    dinitctl [options] stop [options] <service-name>  : stop service and cancel explicit activation" << endl;
160         cout << "    dinitctl [options] wake [options] <service-name>  : start but do not mark activated" << endl;
161         cout << "    dinitctl [options] release [options] <service-name> : release activation, stop if no dependents" << endl;
162         cout << "    dinitctl [options] unpin <service-name>           : un-pin the service (after a previous pin)" << endl;
163         cout << "    dinitctl unload <service-name>                    : unload the service" << endl;
164         cout << "    dinitctl list                                     : list loaded services" << endl;
165         cout << "    dinitctl shutdown                                 : stop all services and terminate dinit" << endl;
166         
167         cout << "\nNote: An activated service continues running when its dependents stop." << endl;
168         
169         cout << "\nGeneral options:" << endl;
170         cout << "  -s, --system     : control system daemon instead of user daemon" << endl;
171         cout << "  --quiet          : suppress output (except errors)" << endl;
172         
173         cout << "\nCommand options:" << endl;
174         cout << "  --help           : show this help" << endl;
175         cout << "  --no-wait        : don't wait for service startup/shutdown to complete" << endl;
176         cout << "  --pin            : pin the service in the requested (started/stopped) state" << endl;
177         return 1;
178     }
179     
180     signal(SIGPIPE, SIG_IGN);
181     
182     control_socket_path = "/dev/dinitctl";
183     
184     // Locate control socket
185     if (! sys_dinit) {
186         char * userhome = getenv("HOME");
187         if (userhome == nullptr) {
188             struct passwd * pwuid_p = getpwuid(getuid());
189             if (pwuid_p != nullptr) {
190                 userhome = pwuid_p->pw_dir;
191             }
192         }
193         
194         if (userhome != nullptr) {
195             control_socket_str = userhome;
196             control_socket_str += "/.dinitctl";
197             control_socket_path = control_socket_str.c_str();
198         }
199         else {
200             cerr << "Cannot locate user home directory (set HOME or check /etc/passwd file)" << endl;
201             return 1;
202         }
203     }
204     
205     int socknum = socket(AF_UNIX, SOCK_STREAM, 0);
206     if (socknum == -1) {
207         perror("dinitctl: socket");
208         return 1;
209     }
210
211     struct sockaddr_un * name;
212     uint sockaddr_size = offsetof(struct sockaddr_un, sun_path) + strlen(control_socket_path) + 1;
213     name = (struct sockaddr_un *) malloc(sockaddr_size);
214     if (name == nullptr) {
215         cerr << "dinitctl: Out of memory" << endl;
216         return 1;
217     }
218     
219     name->sun_family = AF_UNIX;
220     strcpy(name->sun_path, control_socket_path);
221     
222     int connr = connect(socknum, (struct sockaddr *) name, sockaddr_size);
223     if (connr == -1) {
224         perror("dinitctl: connect");
225         return 1;
226     }
227     
228     try {
229         // Start by querying protocol version:
230         cpbuffer_t rbuffer;
231         check_protocol_version(min_cp_version, max_cp_version, rbuffer, socknum);
232
233         if (command == command_t::UNPIN_SERVICE) {
234             return unpin_service(socknum, rbuffer, service_name, verbose);
235         }
236         else if (command == command_t::UNLOAD_SERVICE) {
237             return unload_service(socknum, rbuffer, service_name);
238         }
239         else if (command == command_t::LIST_SERVICES) {
240             return list_services(socknum, rbuffer);
241         }
242         else if (command == command_t::SHUTDOWN) {
243             return shutdown_dinit(socknum, rbuffer);
244         }
245         else {
246             return start_stop_service(socknum, rbuffer, service_name, command, do_pin,
247                     wait_for_service, verbose);
248         }
249     }
250     catch (cp_old_client_exception &e) {
251         std::cerr << "dinitctl: too old (server reports newer protocol version)" << std::endl;
252         return 1;
253     }
254     catch (cp_old_server_exception &e) {
255         std::cerr << "dinitctl: server too old or protocol error" << std::endl;
256         return 1;
257     }
258     catch (cp_read_exception &e) {
259         cerr << "dinitctl: control socket read failure or protocol error" << endl;
260         return 1;
261     }
262     catch (cp_write_exception &e) {
263         cerr << "dinitctl: control socket write error: " << std::strerror(e.errcode) << endl;
264         return 1;
265     }
266 }
267
268 // Start/stop a service
269 static int start_stop_service(int socknum, cpbuffer_t &rbuffer, const char *service_name,
270         command_t command, bool do_pin, bool wait_for_service, bool verbose)
271 {
272     using namespace std;
273
274     bool do_stop = (command == command_t::STOP_SERVICE || command == command_t::RELEASE_SERVICE);
275     
276     if (issue_load_service(socknum, service_name)) {
277         return 1;
278     }
279
280     // Now we expect a reply:
281     
282     wait_for_reply(rbuffer, socknum);
283
284     service_state_t state;
285     //service_state_t target_state;
286     handle_t handle;
287
288     if (check_load_reply(socknum, rbuffer, &handle, &state) != 0) {
289         return 0;
290     }
291
292     service_state_t wanted_state = do_stop ? service_state_t::STOPPED : service_state_t::STARTED;
293     int pcommand = 0;
294     switch (command) {
295         case command_t::STOP_SERVICE:
296             pcommand = DINIT_CP_STOPSERVICE;
297             break;
298         case command_t::RELEASE_SERVICE:
299             pcommand = DINIT_CP_RELEASESERVICE;
300             break;
301         case command_t::START_SERVICE:
302             pcommand = DINIT_CP_STARTSERVICE;
303             break;
304         case command_t::WAKE_SERVICE:
305             pcommand = DINIT_CP_WAKESERVICE;
306             break;
307         default: ;
308     }
309
310     // Need to issue STOPSERVICE/STARTSERVICE
311     // We'll do this regardless of the current service state / target state, since issuing
312     // start/stop also sets or clears the "explicitly started" flag on the service.
313     {
314         char buf[2 + sizeof(handle)];
315         buf[0] = pcommand;
316         buf[1] = do_pin ? 1 : 0;
317         memcpy(buf + 2, &handle, sizeof(handle));
318         write_all_x(socknum, buf, 2 + sizeof(handle));
319         
320         wait_for_reply(rbuffer, socknum);
321         if (rbuffer[0] == DINIT_RP_ALREADYSS) {
322             bool already = (state == wanted_state);
323             if (verbose) {
324                 cout << "Service " << (already ? "(already) " : "") << describeState(do_stop) << "." << endl;
325             }
326             return 0; // success!
327         }
328         if (rbuffer[0] != DINIT_RP_ACK) {
329             cerr << "dinitctl: Protocol error." << endl;
330             return 1;
331         }
332         rbuffer.consume(1);
333     }
334
335     if (! wait_for_service) {
336         if (verbose) {
337             cout << "Issued " << describeVerb(do_stop) << " command successfully." << endl;
338         }
339         return 0;
340     }
341
342     service_event_t completionEvent;
343     service_event_t cancelledEvent;
344
345     if (do_stop) {
346         completionEvent = service_event_t::STOPPED;
347         cancelledEvent = service_event_t::STOPCANCELLED;
348     }
349     else {
350         completionEvent = service_event_t::STARTED;
351         cancelledEvent = service_event_t::STARTCANCELLED;
352     }
353
354     // Wait until service started:
355     int r = rbuffer.fill_to(socknum, 2);
356     while (r > 0) {
357         if (rbuffer[0] >= 100) {
358             int pktlen = (unsigned char) rbuffer[1];
359             fill_buffer_to(rbuffer, socknum, pktlen);
360
361             if (rbuffer[0] == DINIT_IP_SERVICEEVENT) {
362                 handle_t ev_handle;
363                 rbuffer.extract((char *) &ev_handle, 2, sizeof(ev_handle));
364                 service_event_t event = static_cast<service_event_t>(rbuffer[2 + sizeof(ev_handle)]);
365                 if (ev_handle == handle) {
366                     if (event == completionEvent) {
367                         if (verbose) {
368                             cout << "Service " << describeState(do_stop) << "." << endl;
369                         }
370                         return 0;
371                     }
372                     else if (event == cancelledEvent) {
373                         if (verbose) {
374                             cout << "Service " << describeVerb(do_stop) << " cancelled." << endl;
375                         }
376                         return 1;
377                     }
378                     else if (! do_stop && event == service_event_t::FAILEDSTART) {
379                         if (verbose) {
380                             cout << "Service failed to start." << endl;
381                         }
382                         return 1;
383                     }
384                 }
385             }
386
387             rbuffer.consume(pktlen);
388             r = rbuffer.fill_to(socknum, 2);
389         }
390         else {
391             // Not an information packet?
392             cerr << "dinitctl: protocol error" << endl;
393             return 1;
394         }
395     }
396
397     if (r == -1) {
398         perror("dinitctl: read");
399     }
400     else {
401         cerr << "protocol error (connection closed by server)" << endl;
402     }
403     return 1;
404 }
405
406 // Issue a "load service" command (DINIT_CP_LOADSERVICE), without waiting for
407 // a response. Returns 1 on failure (with error logged), 0 on success.
408 static int issue_load_service(int socknum, const char *service_name, bool find_only)
409 {
410     // Build buffer;
411     uint16_t sname_len = strlen(service_name);
412     int bufsize = 3 + sname_len;
413     
414     std::unique_ptr<char[]> ubuf(new char[bufsize]);
415     auto buf = ubuf.get();
416
417     buf[0] = find_only ? DINIT_CP_FINDSERVICE : DINIT_CP_LOADSERVICE;
418     memcpy(buf + 1, &sname_len, 2);
419     memcpy(buf + 3, service_name, sname_len);
420
421     write_all_x(socknum, buf, bufsize);
422     
423     return 0;
424 }
425
426 // Check that a "load service" reply was received, and that the requested service was found.
427 static int check_load_reply(int socknum, cpbuffer_t &rbuffer, handle_t *handle_p, service_state_t *state_p)
428 {
429     using namespace std;
430     
431     if (rbuffer[0] == DINIT_RP_SERVICERECORD) {
432         fill_buffer_to(rbuffer, socknum, 2 + sizeof(*handle_p));
433         rbuffer.extract((char *) handle_p, 2, sizeof(*handle_p));
434         if (state_p) *state_p = static_cast<service_state_t>(rbuffer[1]);
435         //target_state = static_cast<service_state_t>(rbuffer[2 + sizeof(handle)]);
436         rbuffer.consume(3 + sizeof(*handle_p));
437         return 0;
438     }
439     else if (rbuffer[0] == DINIT_RP_NOSERVICE) {
440         cerr << "dinitctl: failed to find/load service." << endl;
441         return 1;
442     }
443     else {
444         cerr << "dinitctl: protocol error." << endl;
445         return 1;
446     }
447 }
448
449 static int unpin_service(int socknum, cpbuffer_t &rbuffer, const char *service_name, bool verbose)
450 {
451     using namespace std;
452     
453     // Build buffer;
454     if (issue_load_service(socknum, service_name) == 1) {
455         return 1;
456     }
457
458     // Now we expect a reply:
459     
460     wait_for_reply(rbuffer, socknum);
461
462     handle_t handle;
463
464     if (check_load_reply(socknum, rbuffer, &handle, nullptr) != 0) {
465         return 1;
466     }
467
468     // Issue UNPIN command.
469     {
470         char buf[1 + sizeof(handle)];
471         buf[0] = DINIT_CP_UNPINSERVICE;
472         memcpy(buf + 1, &handle, sizeof(handle));
473         write_all_x(socknum, buf, 2 + sizeof(handle));
474         
475         wait_for_reply(rbuffer, socknum);
476         if (rbuffer[0] != DINIT_RP_ACK) {
477             cerr << "dinitctl: protocol error." << endl;
478             return 1;
479         }
480         rbuffer.consume(1);
481     }
482
483     if (verbose) {
484         cout << "Service unpinned." << endl;
485     }
486     return 0;
487 }
488
489 static int unload_service(int socknum, cpbuffer_t &rbuffer, const char *service_name)
490 {
491     using namespace std;
492
493     // Build buffer;
494     if (issue_load_service(socknum, service_name, true) == 1) {
495         return 1;
496     }
497
498     // Now we expect a reply:
499
500     wait_for_reply(rbuffer, socknum);
501
502     handle_t handle;
503
504     if (check_load_reply(socknum, rbuffer, &handle, nullptr) != 0) {
505         return 1;
506     }
507
508     // Issue UNLOAD command.
509     {
510         char buf[1 + sizeof(handle)];
511         buf[0] = DINIT_CP_UNLOADSERVICE;
512         memcpy(buf + 1, &handle, sizeof(handle));
513         write_all_x(socknum, buf, 2 + sizeof(handle));
514
515         wait_for_reply(rbuffer, socknum);
516         if (rbuffer[0] == DINIT_RP_NAK) {
517             cerr << "dinitctl: Could not unload service; service not stopped, or is a dependency of "
518                     "other service." << endl;
519             return 1;
520         }
521         if (rbuffer[0] != DINIT_RP_ACK) {
522             cerr << "dinitctl: Protocol error." << endl;
523             return 1;
524         }
525         rbuffer.consume(1);
526     }
527
528     cout << "Service unloaded." << endl;
529     return 0;
530 }
531
532 static int list_services(int socknum, cpbuffer_t &rbuffer)
533 {
534     using namespace std;
535     
536     char cmdbuf[] = { (char)DINIT_CP_LISTSERVICES };
537     write_all_x(socknum, cmdbuf, 1);
538
539     wait_for_reply(rbuffer, socknum);
540     while (rbuffer[0] == DINIT_RP_SVCINFO) {
541         int hdrsize = 8 + std::max(sizeof(int), sizeof(pid_t));
542         fill_buffer_to(rbuffer, socknum, hdrsize);
543         int nameLen = rbuffer[1];
544         service_state_t current = static_cast<service_state_t>(rbuffer[2]);
545         service_state_t target = static_cast<service_state_t>(rbuffer[3]);
546
547         int console_flags = rbuffer[4];
548         bool has_console = (console_flags & 2) != 0;
549         bool waiting_console = (console_flags & 1) != 0;
550
551         // stopped_reason_t stop_reason = static_cast<stopped_reason_t>(rbuffer[5]);
552
553         pid_t service_pid;
554         int exit_status;
555         if (current != service_state_t::STOPPED) {
556             rbuffer.extract((char *)&service_pid, 8, sizeof(service_pid));
557         }
558         else {
559                 rbuffer.extract((char *)&exit_status, 8, sizeof(exit_status));
560         }
561
562         fill_buffer_to(rbuffer, socknum, nameLen + hdrsize);
563
564         char *name_ptr = rbuffer.get_ptr(hdrsize);
565         int clength = std::min(rbuffer.get_contiguous_length(name_ptr), nameLen);
566
567         string name = string(name_ptr, clength);
568         name.append(rbuffer.get_buf_base(), nameLen - clength);
569
570         cout << "[";
571
572         cout << (target  == service_state_t::STARTED ? "{" : " ");
573         cout << (current == service_state_t::STARTED ? "+" : " ");
574         cout << (target  == service_state_t::STARTED ? "}" : " ");
575         
576         if (current == service_state_t::STARTING) {
577             cout << "<<";
578         }
579         else if (current == service_state_t::STOPPING) {
580             cout << ">>";
581         }
582         else {
583             cout << "  ";
584         }
585         
586         cout << (target  == service_state_t::STOPPED ? "{" : " ");
587         cout << (current == service_state_t::STOPPED ? "-" : " ");
588         cout << (target  == service_state_t::STOPPED ? "}" : " ");
589
590         cout << "] " << name;
591
592         if (current != service_state_t::STOPPED && service_pid != -1) {
593                 cout << " (pid: " << service_pid << ")";
594         }
595
596         if (has_console) {
597                 cout << " (has console)";
598         }
599         else if (waiting_console) {
600                 cout << " (waiting for console)";
601         }
602
603         cout << endl;
604
605         rbuffer.consume(hdrsize + nameLen);
606         wait_for_reply(rbuffer, socknum);
607     }
608
609     if (rbuffer[0] != DINIT_RP_LISTDONE) {
610         cerr << "dinitctl: Control socket protocol error" << endl;
611         return 1;
612     }
613
614     return 0;
615 }
616
617 static int shutdown_dinit(int socknum, cpbuffer_t &rbuffer)
618 {
619     // TODO support no-wait option.
620     using namespace std;
621
622     // Build buffer;
623     constexpr int bufsize = 2;
624     char buf[bufsize];
625
626     buf[0] = DINIT_CP_SHUTDOWN;
627     buf[1] = static_cast<char>(shutdown_type_t::HALT);
628
629     write_all_x(socknum, buf, bufsize);
630
631     wait_for_reply(rbuffer, socknum);
632
633     if (rbuffer[0] != DINIT_RP_ACK) {
634         cerr << "dinitctl: Control socket protocol error" << endl;
635         return 1;
636     }
637
638     // Now wait for rollback complete:
639     try {
640         while (true) {
641             wait_for_info(rbuffer, socknum);
642             if (rbuffer[0] == DINIT_ROLLBACK_COMPLETED) {
643                 break;
644             }
645         }
646     }
647     catch (cp_read_exception &exc) {
648         // Dinit can terminate before replying: let's assume that happened.
649         // TODO: better check, possibly ensure that dinit actually sends rollback complete before
650         // termination.
651     }
652
653     return 0;
654 }