8bdc93da310d8043aa6da89ab5dd2f48bc45e063
[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/wait.h>
11 #include <sys/socket.h>
12 #include <sys/un.h>
13 #include <unistd.h>
14 #include <signal.h>
15 #include <pwd.h>
16
17 #include "control-cmds.h"
18 #include "service-constants.h"
19 #include "cpbuffer.h"
20 #include "dinit-client.h"
21
22 // dinitctl:  utility to control the Dinit daemon, including starting and stopping of services.
23
24 // This utility communicates with the dinit daemon via a unix stream socket (/dev/initctl, or $HOME/.dinitctl).
25
26 static constexpr uint16_t min_cp_version = 1;
27 static constexpr uint16_t max_cp_version = 1;
28
29 enum class command_t;
30
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
40
41 static const char * describeState(bool stopped)
42 {
43     return stopped ? "stopped" : "started";
44 }
45
46 static const char * describeVerb(bool stop)
47 {
48     return stop ? "stop" : "start";
49 }
50
51 enum class command_t {
52     NONE,
53     START_SERVICE,
54     WAKE_SERVICE,
55     STOP_SERVICE,
56     RELEASE_SERVICE,
57     UNPIN_SERVICE,
58     UNLOAD_SERVICE,
59     LIST_SERVICES,
60     SHUTDOWN
61 };
62
63
64 // Entry point.
65 int main(int argc, char **argv)
66 {
67     using namespace std;
68     
69     bool show_help = argc < 2;
70     char *service_name = nullptr;
71     
72     std::string control_socket_str;
73     const char * control_socket_path = nullptr;
74     
75     bool verbose = true;
76     bool sys_dinit = false;  // communicate with system daemon
77     bool wait_for_service = true;
78     bool do_pin = false;
79     
80     command_t command = command_t::NONE;
81         
82     for (int i = 1; i < argc; i++) {
83         if (argv[i][0] == '-') {
84             if (strcmp(argv[i], "--help") == 0) {
85                 show_help = true;
86                 break;
87             }
88             else if (strcmp(argv[i], "--no-wait") == 0) {
89                 wait_for_service = false;
90             }
91             else if (strcmp(argv[i], "--quiet") == 0) {
92                 verbose = false;
93             }
94             else if (strcmp(argv[i], "--system") == 0 || strcmp(argv[i], "-s") == 0) {
95                 sys_dinit = true;
96             }
97             else if (strcmp(argv[i], "--pin") == 0) {
98                 do_pin = true;
99             }
100             else {
101                 return 1;
102             }
103         }
104         else if (command == command_t::NONE) {
105             if (strcmp(argv[i], "start") == 0) {
106                 command = command_t::START_SERVICE; 
107             }
108             else if (strcmp(argv[i], "wake") == 0) {
109                 command = command_t::WAKE_SERVICE;
110             }
111             else if (strcmp(argv[i], "stop") == 0) {
112                 command = command_t::STOP_SERVICE;
113             }
114             else if (strcmp(argv[i], "release") == 0) {
115                 command = command_t::RELEASE_SERVICE;
116             }
117             else if (strcmp(argv[i], "unpin") == 0) {
118                 command = command_t::UNPIN_SERVICE;
119             }
120             else if (strcmp(argv[i], "unload") == 0) {
121                 command = command_t::UNLOAD_SERVICE;
122             }
123             else if (strcmp(argv[i], "list") == 0) {
124                 command = command_t::LIST_SERVICES;
125             }
126             else if (strcmp(argv[i], "shutdown") == 0) {
127                 command = command_t::SHUTDOWN;
128             }
129             else {
130                 show_help = true;
131                 break;
132             }
133         }
134         else {
135             // service name
136             if (service_name != nullptr) {
137                 show_help = true;
138                 break;
139             }
140             service_name = argv[i];
141             // TODO support multiple services
142         }
143     }
144     
145     bool no_service_cmd = (command == command_t::LIST_SERVICES || command == command_t::SHUTDOWN);
146
147     if (service_name != nullptr && no_service_cmd) {
148         show_help = true;
149     }
150     
151     if ((service_name == nullptr && ! no_service_cmd) || command == command_t::NONE) {
152         show_help = true;
153     }
154
155     if (show_help) {
156         cout << "dinitctl:   control Dinit services" << endl;
157         
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;
167         
168         cout << "\nNote: An activated service continues running when its dependents stop." << endl;
169         
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;
173         
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;
178         return 1;
179     }
180     
181     signal(SIGPIPE, SIG_IGN);
182     
183     control_socket_path = "/dev/dinitctl";
184     
185     // Locate control socket
186     if (! sys_dinit) {
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;
192             }
193         }
194         
195         if (userhome != nullptr) {
196             control_socket_str = userhome;
197             control_socket_str += "/.dinitctl";
198             control_socket_path = control_socket_str.c_str();
199         }
200         else {
201             cerr << "Cannot locate user home directory (set HOME or check /etc/passwd file)" << endl;
202             return 1;
203         }
204     }
205     
206     int socknum = socket(AF_UNIX, SOCK_STREAM, 0);
207     if (socknum == -1) {
208         perror("dinitctl: socket");
209         return 1;
210     }
211
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;
217         return 1;
218     }
219     
220     name->sun_family = AF_UNIX;
221     strcpy(name->sun_path, control_socket_path);
222     
223     int connr = connect(socknum, (struct sockaddr *) name, sockaddr_size);
224     if (connr == -1) {
225         perror("dinitctl: connect");
226         return 1;
227     }
228     
229     try {
230         // Start by querying protocol version:
231         cpbuffer_t rbuffer;
232         check_protocol_version(min_cp_version, max_cp_version, rbuffer, socknum);
233
234         if (command == command_t::UNPIN_SERVICE) {
235             return unpin_service(socknum, rbuffer, service_name, verbose);
236         }
237         else if (command == command_t::UNLOAD_SERVICE) {
238             return unload_service(socknum, rbuffer, service_name);
239         }
240         else if (command == command_t::LIST_SERVICES) {
241             return list_services(socknum, rbuffer);
242         }
243         else if (command == command_t::SHUTDOWN) {
244             return shutdown_dinit(socknum, rbuffer);
245         }
246         else {
247             return start_stop_service(socknum, rbuffer, service_name, command, do_pin,
248                     wait_for_service, verbose);
249         }
250     }
251     catch (cp_old_client_exception &e) {
252         std::cerr << "dinitctl: too old (server reports newer protocol version)" << std::endl;
253         return 1;
254     }
255     catch (cp_old_server_exception &e) {
256         std::cerr << "dinitctl: server too old or protocol error" << std::endl;
257         return 1;
258     }
259     catch (cp_read_exception &e) {
260         cerr << "dinitctl: control socket read failure or protocol error" << endl;
261         return 1;
262     }
263     catch (cp_write_exception &e) {
264         cerr << "dinitctl: control socket write error: " << std::strerror(e.errcode) << endl;
265         return 1;
266     }
267 }
268
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)
272 {
273     using namespace std;
274
275     bool do_stop = (command == command_t::STOP_SERVICE || command == command_t::RELEASE_SERVICE);
276     
277     if (issue_load_service(socknum, service_name)) {
278         return 1;
279     }
280
281     // Now we expect a reply:
282     
283     wait_for_reply(rbuffer, socknum);
284
285     service_state_t state;
286     //service_state_t target_state;
287     handle_t handle;
288
289     if (check_load_reply(socknum, rbuffer, &handle, &state) != 0) {
290         return 0;
291     }
292
293     service_state_t wanted_state = do_stop ? service_state_t::STOPPED : service_state_t::STARTED;
294     int pcommand = 0;
295     switch (command) {
296         case command_t::STOP_SERVICE:
297             pcommand = DINIT_CP_STOPSERVICE;
298             break;
299         case command_t::RELEASE_SERVICE:
300             pcommand = DINIT_CP_RELEASESERVICE;
301             break;
302         case command_t::START_SERVICE:
303             pcommand = DINIT_CP_STARTSERVICE;
304             break;
305         case command_t::WAKE_SERVICE:
306             pcommand = DINIT_CP_WAKESERVICE;
307             break;
308         default: ;
309     }
310
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.
314     {
315         char buf[2 + sizeof(handle)];
316         buf[0] = pcommand;
317         buf[1] = do_pin ? 1 : 0;
318         memcpy(buf + 2, &handle, sizeof(handle));
319         write_all_x(socknum, buf, 2 + sizeof(handle));
320         
321         wait_for_reply(rbuffer, socknum);
322         if (rbuffer[0] == DINIT_RP_ALREADYSS) {
323             bool already = (state == wanted_state);
324             if (verbose) {
325                 cout << "Service " << (already ? "(already) " : "") << describeState(do_stop) << "." << endl;
326             }
327             return 0; // success!
328         }
329         if (rbuffer[0] != DINIT_RP_ACK) {
330             cerr << "dinitctl: Protocol error." << endl;
331             return 1;
332         }
333         rbuffer.consume(1);
334     }
335
336     if (! wait_for_service) {
337         if (verbose) {
338             cout << "Issued " << describeVerb(do_stop) << " command successfully." << endl;
339         }
340         return 0;
341     }
342
343     service_event_t completionEvent;
344     service_event_t cancelledEvent;
345
346     if (do_stop) {
347         completionEvent = service_event_t::STOPPED;
348         cancelledEvent = service_event_t::STOPCANCELLED;
349     }
350     else {
351         completionEvent = service_event_t::STARTED;
352         cancelledEvent = service_event_t::STARTCANCELLED;
353     }
354
355     // Wait until service started:
356     int r = rbuffer.fill_to(socknum, 2);
357     while (r > 0) {
358         if (rbuffer[0] >= 100) {
359             int pktlen = (unsigned char) rbuffer[1];
360             fill_buffer_to(rbuffer, socknum, pktlen);
361
362             if (rbuffer[0] == DINIT_IP_SERVICEEVENT) {
363                 handle_t ev_handle;
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) {
368                         if (verbose) {
369                             cout << "Service " << describeState(do_stop) << "." << endl;
370                         }
371                         return 0;
372                     }
373                     else if (event == cancelledEvent) {
374                         if (verbose) {
375                             cout << "Service " << describeVerb(do_stop) << " cancelled." << endl;
376                         }
377                         return 1;
378                     }
379                     else if (! do_stop && event == service_event_t::FAILEDSTART) {
380                         if (verbose) {
381                             cout << "Service failed to start." << endl;
382                         }
383                         return 1;
384                     }
385                 }
386             }
387
388             rbuffer.consume(pktlen);
389             r = rbuffer.fill_to(socknum, 2);
390         }
391         else {
392             // Not an information packet?
393             cerr << "dinitctl: protocol error" << endl;
394             return 1;
395         }
396     }
397
398     if (r == -1) {
399         perror("dinitctl: read");
400     }
401     else {
402         cerr << "protocol error (connection closed by server)" << endl;
403     }
404     return 1;
405 }
406
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)
410 {
411     // Build buffer;
412     uint16_t sname_len = strlen(service_name);
413     int bufsize = 3 + sname_len;
414     
415     std::unique_ptr<char[]> ubuf(new char[bufsize]);
416     auto buf = ubuf.get();
417
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);
421
422     write_all_x(socknum, buf, bufsize);
423     
424     return 0;
425 }
426
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)
429 {
430     using namespace std;
431     
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));
438         return 0;
439     }
440     else if (rbuffer[0] == DINIT_RP_NOSERVICE) {
441         cerr << "dinitctl: failed to find/load service." << endl;
442         return 1;
443     }
444     else {
445         cerr << "dinitctl: protocol error." << endl;
446         return 1;
447     }
448 }
449
450 static int unpin_service(int socknum, cpbuffer_t &rbuffer, const char *service_name, bool verbose)
451 {
452     using namespace std;
453     
454     // Build buffer;
455     if (issue_load_service(socknum, service_name) == 1) {
456         return 1;
457     }
458
459     // Now we expect a reply:
460     
461     wait_for_reply(rbuffer, socknum);
462
463     handle_t handle;
464
465     if (check_load_reply(socknum, rbuffer, &handle, nullptr) != 0) {
466         return 1;
467     }
468
469     // Issue UNPIN command.
470     {
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));
475         
476         wait_for_reply(rbuffer, socknum);
477         if (rbuffer[0] != DINIT_RP_ACK) {
478             cerr << "dinitctl: protocol error." << endl;
479             return 1;
480         }
481         rbuffer.consume(1);
482     }
483
484     if (verbose) {
485         cout << "Service unpinned." << endl;
486     }
487     return 0;
488 }
489
490 static int unload_service(int socknum, cpbuffer_t &rbuffer, const char *service_name)
491 {
492     using namespace std;
493
494     // Build buffer;
495     if (issue_load_service(socknum, service_name, true) == 1) {
496         return 1;
497     }
498
499     // Now we expect a reply:
500
501     wait_for_reply(rbuffer, socknum);
502
503     handle_t handle;
504
505     if (check_load_reply(socknum, rbuffer, &handle, nullptr) != 0) {
506         return 1;
507     }
508
509     // Issue UNLOAD command.
510     {
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));
515
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;
520             return 1;
521         }
522         if (rbuffer[0] != DINIT_RP_ACK) {
523             cerr << "dinitctl: Protocol error." << endl;
524             return 1;
525         }
526         rbuffer.consume(1);
527     }
528
529     cout << "Service unloaded." << endl;
530     return 0;
531 }
532
533 static int list_services(int socknum, cpbuffer_t &rbuffer)
534 {
535     using namespace std;
536     
537     char cmdbuf[] = { (char)DINIT_CP_LISTSERVICES };
538     write_all_x(socknum, cmdbuf, 1);
539
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]);
547
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;
552
553         stopped_reason_t stop_reason = static_cast<stopped_reason_t>(rbuffer[5]);
554
555         pid_t service_pid;
556         int exit_status;
557         if (current != service_state_t::STOPPED) {
558             rbuffer.extract((char *)&service_pid, 8, sizeof(service_pid));
559         }
560         else {
561                 rbuffer.extract((char *)&exit_status, 8, sizeof(exit_status));
562         }
563
564         fill_buffer_to(rbuffer, socknum, nameLen + hdrsize);
565
566         char *name_ptr = rbuffer.get_ptr(hdrsize);
567         int clength = std::min(rbuffer.get_contiguous_length(name_ptr), nameLen);
568
569         string name = string(name_ptr, clength);
570         name.append(rbuffer.get_buf_base(), nameLen - clength);
571
572         cout << "[";
573
574         cout << (target  == service_state_t::STARTED ? "{" : " ");
575         if (current == service_state_t::STARTED) {
576             cout << (was_skipped ? "s" : "+");
577         }
578         else {
579             cout << " ";
580         }
581         cout << (target  == service_state_t::STARTED ? "}" : " ");
582         
583         if (current == service_state_t::STARTING) {
584             cout << "<<";
585         }
586         else if (current == service_state_t::STOPPING) {
587             cout << ">>";
588         }
589         else {
590             cout << "  ";
591         }
592         
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) {
598                     did_fail = true;
599                 }
600             }
601             else did_fail = (stop_reason != stopped_reason_t::NORMAL);
602
603             cout << (did_fail ? "X" : "-");
604         }
605         cout << (target  == service_state_t::STOPPED ? "}" : " ");
606
607         cout << "] " << name;
608
609         if (current != service_state_t::STOPPED && service_pid != -1) {
610                 cout << " (pid: " << service_pid << ")";
611         }
612         
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) << ")";
616             }
617             else if (WIFSIGNALED(exit_status)) {
618                 cout << " (signal: " << WSTOPSIG(exit_status) << ")";
619             }
620         }
621
622         if (has_console) {
623                 cout << " (has console)";
624         }
625         else if (waiting_console) {
626                 cout << " (waiting for console)";
627         }
628
629         cout << endl;
630
631         rbuffer.consume(hdrsize + nameLen);
632         wait_for_reply(rbuffer, socknum);
633     }
634
635     if (rbuffer[0] != DINIT_RP_LISTDONE) {
636         cerr << "dinitctl: Control socket protocol error" << endl;
637         return 1;
638     }
639
640     return 0;
641 }
642
643 static int shutdown_dinit(int socknum, cpbuffer_t &rbuffer)
644 {
645     // TODO support no-wait option.
646     using namespace std;
647
648     // Build buffer;
649     constexpr int bufsize = 2;
650     char buf[bufsize];
651
652     buf[0] = DINIT_CP_SHUTDOWN;
653     buf[1] = static_cast<char>(shutdown_type_t::HALT);
654
655     write_all_x(socknum, buf, bufsize);
656
657     wait_for_reply(rbuffer, socknum);
658
659     if (rbuffer[0] != DINIT_RP_ACK) {
660         cerr << "dinitctl: Control socket protocol error" << endl;
661         return 1;
662     }
663
664     // Now wait for rollback complete:
665     try {
666         while (true) {
667             wait_for_info(rbuffer, socknum);
668             if (rbuffer[0] == DINIT_ROLLBACK_COMPLETED) {
669                 break;
670             }
671         }
672     }
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
676         // termination.
677     }
678
679     return 0;
680 }