a3f40d8c571f6c9897963156a066bae81c4f0b0f
[oweals/dinit.git] / src / dinitctl.cc
1 #include <cstdio>
2 #include <cstddef>
3 #include <cstring>
4 #include <string>
5 #include <iostream>
6 #include <fstream>
7 #include <system_error>
8 #include <memory>
9 #include <algorithm>
10
11 #include <sys/types.h>
12 #include <sys/stat.h>
13 #include <sys/wait.h>
14 #include <sys/socket.h>
15 #include <sys/un.h>
16 #include <unistd.h>
17 #include <signal.h>
18 #include <pwd.h>
19
20 #include "control-cmds.h"
21 #include "service-constants.h"
22 #include "cpbuffer.h"
23 #include "dinit-client.h"
24 #include "load-service.h"
25
26 // dinitctl:  utility to control the Dinit daemon, including starting and stopping of services.
27
28 // This utility communicates with the dinit daemon via a unix stream socket (/dev/initctl,
29 // or $HOME/.dinitctl).
30
31 static constexpr uint16_t min_cp_version = 1;
32 static constexpr uint16_t max_cp_version = 1;
33
34 enum class command_t;
35
36 static int issue_load_service(int socknum, const char *service_name, bool find_only = false);
37 static int check_load_reply(int socknum, cpbuffer_t &, handle_t *handle_p, service_state_t *state_p);
38 static int start_stop_service(int socknum, cpbuffer_t &, const char *service_name, command_t command,
39         bool do_pin, bool wait_for_service, bool verbose);
40 static int unpin_service(int socknum, cpbuffer_t &, const char *service_name, bool verbose);
41 static int unload_service(int socknum, cpbuffer_t &, const char *service_name);
42 static int list_services(int socknum, cpbuffer_t &);
43 static int shutdown_dinit(int soclknum, cpbuffer_t &);
44 static int add_remove_dependency(int socknum, cpbuffer_t &rbuffer, bool add, const char *service_from,
45         const char *service_to, dependency_type dep_type);
46 static int enable_disable_service(int socknum, cpbuffer_t &rbuffer, const char *from, const char *to,
47         bool enable);
48
49 static const char * describeState(bool stopped)
50 {
51     return stopped ? "stopped" : "started";
52 }
53
54 static const char * describeVerb(bool stop)
55 {
56     return stop ? "stop" : "start";
57 }
58
59 enum class command_t {
60     NONE,
61     START_SERVICE,
62     WAKE_SERVICE,
63     STOP_SERVICE,
64     RELEASE_SERVICE,
65     UNPIN_SERVICE,
66     UNLOAD_SERVICE,
67     LIST_SERVICES,
68     SHUTDOWN,
69     ADD_DEPENDENCY,
70     RM_DEPENDENCY,
71     ENABLE_SERVICE,
72     DISABLE_SERVICE
73 };
74
75
76 // Entry point.
77 int main(int argc, char **argv)
78 {
79     using namespace std;
80     
81     bool show_help = argc < 2;
82     const char *service_name = nullptr;
83     const char *to_service_name = nullptr;
84     dependency_type dep_type;
85     bool dep_type_set = false;
86     
87     std::string control_socket_str;
88     const char * control_socket_path = nullptr;
89     
90     bool verbose = true;
91     bool sys_dinit = false;  // communicate with system daemon
92     bool wait_for_service = true;
93     bool do_pin = false;
94     
95     command_t command = command_t::NONE;
96         
97     for (int i = 1; i < argc; i++) {
98         if (argv[i][0] == '-') {
99             if (strcmp(argv[i], "--help") == 0) {
100                 show_help = true;
101                 break;
102             }
103             else if (strcmp(argv[i], "--no-wait") == 0) {
104                 wait_for_service = false;
105             }
106             else if (strcmp(argv[i], "--quiet") == 0) {
107                 verbose = false;
108             }
109             else if (strcmp(argv[i], "--system") == 0 || strcmp(argv[i], "-s") == 0) {
110                 sys_dinit = true;
111             }
112             else if (strcmp(argv[i], "--pin") == 0) {
113                 do_pin = true;
114             }
115             else if ((command == command_t::ENABLE_SERVICE || command == command_t::DISABLE_SERVICE)
116                     && strcmp(argv[i], "--from") == 0) {
117                 ++i;
118                 if (i == argc) {
119                     cerr << "dinitctl: --from should be followed by a service name" << std::endl;
120                     return 1;
121                 }
122                 service_name = argv[i];
123             }
124             else {
125                 cerr << "dinitctl: unrecognized option: " << argv[i] << " (use --help for help)\n";
126                 return 1;
127             }
128         }
129         else if (command == command_t::NONE) {
130             if (strcmp(argv[i], "start") == 0) {
131                 command = command_t::START_SERVICE; 
132             }
133             else if (strcmp(argv[i], "wake") == 0) {
134                 command = command_t::WAKE_SERVICE;
135             }
136             else if (strcmp(argv[i], "stop") == 0) {
137                 command = command_t::STOP_SERVICE;
138             }
139             else if (strcmp(argv[i], "release") == 0) {
140                 command = command_t::RELEASE_SERVICE;
141             }
142             else if (strcmp(argv[i], "unpin") == 0) {
143                 command = command_t::UNPIN_SERVICE;
144             }
145             else if (strcmp(argv[i], "unload") == 0) {
146                 command = command_t::UNLOAD_SERVICE;
147             }
148             else if (strcmp(argv[i], "list") == 0) {
149                 command = command_t::LIST_SERVICES;
150             }
151             else if (strcmp(argv[i], "shutdown") == 0) {
152                 command = command_t::SHUTDOWN;
153             }
154             else if (strcmp(argv[i], "add-dep") == 0) {
155                 command = command_t::ADD_DEPENDENCY;
156             }
157             else if (strcmp(argv[i], "rm-dep") == 0) {
158                 command = command_t::RM_DEPENDENCY;
159             }
160             else if (strcmp(argv[i], "enable") == 0) {
161                 command = command_t::ENABLE_SERVICE;
162             }
163             else if (strcmp(argv[i], "disable") == 0) {
164                 command = command_t::DISABLE_SERVICE;
165             }
166             else {
167                 cerr << "dinitctl: unrecognized command: " << argv[i] << " (use --help for help)\n";
168                 return 1;
169             }
170         }
171         else {
172             // service name / other non-option
173             if (command == command_t::ADD_DEPENDENCY || command == command_t::RM_DEPENDENCY) {
174                 if (! dep_type_set) {
175                     if (strcmp(argv[i], "regular") == 0) {
176                         dep_type = dependency_type::REGULAR;
177                     }
178                     else if (strcmp(argv[i], "milestone") == 0) {
179                         dep_type = dependency_type::MILESTONE;
180                     }
181                     else if (strcmp(argv[i], "waits-for") == 0) {
182                         dep_type = dependency_type::WAITS_FOR;
183                     }
184                     else {
185                         show_help = true;
186                         break;
187                     }
188                     dep_type_set = true;
189                 }
190                 else if (service_name == nullptr) {
191                     service_name = argv[i];
192                 }
193                 else if (to_service_name == nullptr) {
194                     to_service_name = argv[i];
195                 }
196                 else {
197                     show_help = true;
198                     break;
199                 }
200             }
201             else if (command == command_t::ENABLE_SERVICE || command == command_t::DISABLE_SERVICE) {
202                 if (to_service_name != nullptr) {
203                     show_help = true;
204                     break;
205                 }
206                 to_service_name = argv[i];
207             }
208             else {
209                 if (service_name != nullptr) {
210                     show_help = true;
211                     break;
212                 }
213                 service_name = argv[i];
214                 // TODO support multiple services
215             }
216         }
217     }
218     
219     bool no_service_cmd = (command == command_t::LIST_SERVICES || command == command_t::SHUTDOWN);
220
221     if (service_name != nullptr && no_service_cmd) {
222         show_help = true;
223     }
224     
225     if ((service_name == nullptr && ! no_service_cmd) || command == command_t::NONE) {
226         show_help = true;
227     }
228
229     if ((command == command_t::ADD_DEPENDENCY || command == command_t::RM_DEPENDENCY)
230             && (! dep_type_set || service_name == nullptr || to_service_name == nullptr)) {
231         show_help = true;
232     }
233
234     if (show_help) {
235         cout << "dinitctl:   control Dinit services\n"
236           "\n"
237           "Usage:\n"
238           "    dinitctl [options] start [options] <service-name>\n"
239           "    dinitctl [options] stop [options] <service-name>\n"
240           "    dinitctl [options] wake [options] <service-name>\n"
241           "    dinitctl [options] release [options] <service-name>\n"
242           "    dinitctl [options] unpin <service-name>\n"
243           "    dinitctl unload <service-name>\n"
244           "    dinitctl list\n"
245           "    dinitctl shutdown\n"
246           "    dinitctl add-dep <type> <from-service> <to-service>\n"
247           "    dinitctl rm-dep <type> <from-service> <to-service>\n"
248           "    dinitctl enable [--from <from-service>] <to-service>\n"
249           "    dinitctl disable [--from <from-service>] <to-service>\n"
250           "\n"
251           "Note: An activated service continues running when its dependents stop.\n"
252           "\n"
253           "General options:\n"
254           "  -s, --system     : control system daemon instead of user daemon\n"
255           "  --quiet          : suppress output (except errors)\n"
256           "\n"
257           "Command options:\n"
258           "  --help           : show this help\n"
259           "  --no-wait        : don't wait for service startup/shutdown to complete\n"
260           "  --pin            : pin the service in the requested state\n";
261         return 1;
262     }
263     
264     signal(SIGPIPE, SIG_IGN);
265     
266     control_socket_path = "/dev/dinitctl";
267     
268     // Locate control socket
269     if (! sys_dinit) {
270         char * userhome = getenv("HOME");
271         if (userhome == nullptr) {
272             struct passwd * pwuid_p = getpwuid(getuid());
273             if (pwuid_p != nullptr) {
274                 userhome = pwuid_p->pw_dir;
275             }
276         }
277         
278         if (userhome != nullptr) {
279             control_socket_str = userhome;
280             control_socket_str += "/.dinitctl";
281             control_socket_path = control_socket_str.c_str();
282         }
283         else {
284             cerr << "Cannot locate user home directory (set HOME or check /etc/passwd file)" << endl;
285             return 1;
286         }
287     }
288     
289     int socknum = socket(AF_UNIX, SOCK_STREAM, 0);
290     if (socknum == -1) {
291         perror("dinitctl: socket");
292         return 1;
293     }
294
295     struct sockaddr_un * name;
296     uint sockaddr_size = offsetof(struct sockaddr_un, sun_path) + strlen(control_socket_path) + 1;
297     name = (struct sockaddr_un *) malloc(sockaddr_size);
298     if (name == nullptr) {
299         cerr << "dinitctl: Out of memory" << endl;
300         return 1;
301     }
302     
303     name->sun_family = AF_UNIX;
304     strcpy(name->sun_path, control_socket_path);
305     
306     int connr = connect(socknum, (struct sockaddr *) name, sockaddr_size);
307     if (connr == -1) {
308         perror("dinitctl: connect");
309         return 1;
310     }
311     
312     try {
313         // Start by querying protocol version:
314         cpbuffer_t rbuffer;
315         check_protocol_version(min_cp_version, max_cp_version, rbuffer, socknum);
316
317         if (command == command_t::UNPIN_SERVICE) {
318             return unpin_service(socknum, rbuffer, service_name, verbose);
319         }
320         else if (command == command_t::UNLOAD_SERVICE) {
321             return unload_service(socknum, rbuffer, service_name);
322         }
323         else if (command == command_t::LIST_SERVICES) {
324             return list_services(socknum, rbuffer);
325         }
326         else if (command == command_t::SHUTDOWN) {
327             return shutdown_dinit(socknum, rbuffer);
328         }
329         else if (command == command_t::ADD_DEPENDENCY || command == command_t::RM_DEPENDENCY) {
330             return add_remove_dependency(socknum, rbuffer, command == command_t::ADD_DEPENDENCY,
331                     service_name, to_service_name, dep_type);
332         }
333         else if (command == command_t::ENABLE_SERVICE || command == command_t::DISABLE_SERVICE) {
334             // If only one service specified, assume that we enable for 'boot' service:
335             if (service_name == nullptr) {
336                 service_name = "boot";
337             }
338             return enable_disable_service(socknum, rbuffer, service_name, to_service_name,
339                     command == command_t::ENABLE_SERVICE);
340         }
341         else {
342             return start_stop_service(socknum, rbuffer, service_name, command, do_pin,
343                     wait_for_service, verbose);
344         }
345     }
346     catch (cp_old_client_exception &e) {
347         std::cerr << "dinitctl: too old (server reports newer protocol version)" << std::endl;
348         return 1;
349     }
350     catch (cp_old_server_exception &e) {
351         std::cerr << "dinitctl: server too old or protocol error" << std::endl;
352         return 1;
353     }
354     catch (cp_read_exception &e) {
355         cerr << "dinitctl: control socket read failure or protocol error" << endl;
356         return 1;
357     }
358     catch (cp_write_exception &e) {
359         cerr << "dinitctl: control socket write error: " << std::strerror(e.errcode) << endl;
360         return 1;
361     }
362 }
363
364 // Extract/read a string of specified length from the buffer/socket. The string is consumed
365 // from the buffer.
366 static std::string read_string(int socknum, cpbuffer_t &rbuffer, uint32_t length)
367 {
368     int rb_len = rbuffer.get_length();
369     if (uint32_t(rb_len) >= length) {
370         std::string r = rbuffer.extract_string(0, length);
371         rbuffer.consume(length);
372         return r;
373     }
374
375     std::string r = rbuffer.extract_string(0, rb_len);
376     uint32_t rlen = length - rb_len;
377     uint32_t clen;
378     do {
379         rbuffer.reset();
380         rbuffer.fill(socknum);
381         char *bptr = rbuffer.get_ptr(0);
382         clen = rbuffer.get_length();
383         clen = std::min(clen, rlen);
384         r.append(bptr, clen);
385         rlen -= clen;
386     } while (rlen > 0);
387
388     rbuffer.consume(clen);
389
390     return r;
391 }
392
393 // Load a service: issue load command, wait for reply. Return true on success, display error message
394 // and return false on failure.
395 //      socknum  - the socket fd to communicate via
396 //      rbuffer  - the buffer for communication
397 //      name     - the name of the service to load
398 //      handle   - where to store the handle of the loaded service
399 //      state    - where to store the state of the loaded service (may be null).
400 static bool load_service(int socknum, cpbuffer_t &rbuffer, const char *name, handle_t *handle,
401         service_state_t *state)
402 {
403     // Load 'to' service:
404     if (issue_load_service(socknum, name)) {
405         return false;
406     }
407
408     wait_for_reply(rbuffer, socknum);
409
410     if (check_load_reply(socknum, rbuffer, handle, state) != 0) {
411         return false;
412     }
413
414     return true;
415 }
416
417 // Start/stop a service
418 static int start_stop_service(int socknum, cpbuffer_t &rbuffer, const char *service_name,
419         command_t command, bool do_pin, bool wait_for_service, bool verbose)
420 {
421     using namespace std;
422
423     bool do_stop = (command == command_t::STOP_SERVICE || command == command_t::RELEASE_SERVICE);
424
425     service_state_t state;
426     handle_t handle;
427     
428     if (! load_service(socknum, rbuffer, service_name, &handle, &state)) {
429         return 1;
430     }
431
432     service_state_t wanted_state = do_stop ? service_state_t::STOPPED : service_state_t::STARTED;
433     int pcommand = 0;
434     switch (command) {
435         case command_t::STOP_SERVICE:
436             pcommand = DINIT_CP_STOPSERVICE;
437             break;
438         case command_t::RELEASE_SERVICE:
439             pcommand = DINIT_CP_RELEASESERVICE;
440             break;
441         case command_t::START_SERVICE:
442             pcommand = DINIT_CP_STARTSERVICE;
443             break;
444         case command_t::WAKE_SERVICE:
445             pcommand = DINIT_CP_WAKESERVICE;
446             break;
447         default: ;
448     }
449
450     // Need to issue STOPSERVICE/STARTSERVICE
451     // We'll do this regardless of the current service state / target state, since issuing
452     // start/stop also sets or clears the "explicitly started" flag on the service.
453     {
454         char buf[2 + sizeof(handle)];
455         buf[0] = pcommand;
456         buf[1] = do_pin ? 1 : 0;
457         memcpy(buf + 2, &handle, sizeof(handle));
458         write_all_x(socknum, buf, 2 + sizeof(handle));
459         
460         wait_for_reply(rbuffer, socknum);
461         if (rbuffer[0] == DINIT_RP_ALREADYSS) {
462             bool already = (state == wanted_state);
463             if (verbose) {
464                 cout << "Service " << (already ? "(already) " : "")
465                         << describeState(do_stop) << "." << endl;
466             }
467             return 0; // success!
468         }
469         if (rbuffer[0] != DINIT_RP_ACK) {
470             cerr << "dinitctl: Protocol error." << endl;
471             return 1;
472         }
473         rbuffer.consume(1);
474     }
475
476     if (! wait_for_service) {
477         if (verbose) {
478             cout << "Issued " << describeVerb(do_stop) << " command successfully." << endl;
479         }
480         return 0;
481     }
482
483     service_event_t completionEvent;
484     service_event_t cancelledEvent;
485
486     if (do_stop) {
487         completionEvent = service_event_t::STOPPED;
488         cancelledEvent = service_event_t::STOPCANCELLED;
489     }
490     else {
491         completionEvent = service_event_t::STARTED;
492         cancelledEvent = service_event_t::STARTCANCELLED;
493     }
494
495     // Wait until service started:
496     int r = rbuffer.fill_to(socknum, 2);
497     while (r > 0) {
498         if (rbuffer[0] >= 100) {
499             int pktlen = (unsigned char) rbuffer[1];
500             fill_buffer_to(rbuffer, socknum, pktlen);
501
502             if (rbuffer[0] == DINIT_IP_SERVICEEVENT) {
503                 handle_t ev_handle;
504                 rbuffer.extract((char *) &ev_handle, 2, sizeof(ev_handle));
505                 service_event_t event = static_cast<service_event_t>(rbuffer[2 + sizeof(ev_handle)]);
506                 if (ev_handle == handle) {
507                     if (event == completionEvent) {
508                         if (verbose) {
509                             cout << "Service " << describeState(do_stop) << "." << endl;
510                         }
511                         return 0;
512                     }
513                     else if (event == cancelledEvent) {
514                         if (verbose) {
515                             cout << "Service " << describeVerb(do_stop) << " cancelled." << endl;
516                         }
517                         return 1;
518                     }
519                     else if (! do_stop && event == service_event_t::FAILEDSTART) {
520                         if (verbose) {
521                             cout << "Service failed to start." << endl;
522                         }
523                         return 1;
524                     }
525                 }
526             }
527
528             rbuffer.consume(pktlen);
529             r = rbuffer.fill_to(socknum, 2);
530         }
531         else {
532             // Not an information packet?
533             cerr << "dinitctl: protocol error" << endl;
534             return 1;
535         }
536     }
537
538     if (r == -1) {
539         perror("dinitctl: read");
540     }
541     else {
542         cerr << "protocol error (connection closed by server)" << endl;
543     }
544     return 1;
545 }
546
547 // Issue a "load service" command (DINIT_CP_LOADSERVICE), without waiting for
548 // a response. Returns 1 on failure (with error logged), 0 on success.
549 static int issue_load_service(int socknum, const char *service_name, bool find_only)
550 {
551     // Build buffer;
552     uint16_t sname_len = strlen(service_name);
553     int bufsize = 3 + sname_len;
554     
555     std::unique_ptr<char[]> ubuf(new char[bufsize]);
556     auto buf = ubuf.get();
557
558     buf[0] = find_only ? DINIT_CP_FINDSERVICE : DINIT_CP_LOADSERVICE;
559     memcpy(buf + 1, &sname_len, 2);
560     memcpy(buf + 3, service_name, sname_len);
561
562     write_all_x(socknum, buf, bufsize);
563     
564     return 0;
565 }
566
567 // Check that a "load service" reply was received, and that the requested service was found.
568 //   state_p may be null.
569 static int check_load_reply(int socknum, cpbuffer_t &rbuffer, handle_t *handle_p, service_state_t *state_p)
570 {
571     using namespace std;
572     
573     if (rbuffer[0] == DINIT_RP_SERVICERECORD) {
574         fill_buffer_to(rbuffer, socknum, 2 + sizeof(*handle_p));
575         rbuffer.extract((char *) handle_p, 2, sizeof(*handle_p));
576         if (state_p) *state_p = static_cast<service_state_t>(rbuffer[1]);
577         //target_state = static_cast<service_state_t>(rbuffer[2 + sizeof(handle)]);
578         rbuffer.consume(3 + sizeof(*handle_p));
579         return 0;
580     }
581     else if (rbuffer[0] == DINIT_RP_NOSERVICE) {
582         cerr << "dinitctl: failed to find/load service." << endl;
583         return 1;
584     }
585     else {
586         cerr << "dinitctl: protocol error." << endl;
587         return 1;
588     }
589 }
590
591 static int unpin_service(int socknum, cpbuffer_t &rbuffer, const char *service_name, bool verbose)
592 {
593     using namespace std;
594
595     handle_t handle;
596     
597     // Build buffer;
598     if (! load_service(socknum, rbuffer, service_name, &handle, nullptr)) {
599         return 1;
600     }
601     
602     // Issue UNPIN command.
603     {
604         char buf[1 + sizeof(handle)];
605         buf[0] = DINIT_CP_UNPINSERVICE;
606         memcpy(buf + 1, &handle, sizeof(handle));
607         write_all_x(socknum, buf, 2 + sizeof(handle));
608         
609         wait_for_reply(rbuffer, socknum);
610         if (rbuffer[0] != DINIT_RP_ACK) {
611             cerr << "dinitctl: protocol error." << endl;
612             return 1;
613         }
614         rbuffer.consume(1);
615     }
616
617     if (verbose) {
618         cout << "Service unpinned." << endl;
619     }
620     return 0;
621 }
622
623 static int unload_service(int socknum, cpbuffer_t &rbuffer, const char *service_name)
624 {
625     using namespace std;
626
627     if (issue_load_service(socknum, service_name, true) == 1) {
628         return 1;
629     }
630
631     wait_for_reply(rbuffer, socknum);
632
633     handle_t handle;
634
635     if (rbuffer[0] == DINIT_RP_NOSERVICE) {
636         cerr << "dinitctl: service not loaded." << endl;
637         return 1;
638     }
639
640     if (check_load_reply(socknum, rbuffer, &handle, nullptr) != 0) {
641         return 1;
642     }
643
644     // Issue UNLOAD command.
645     {
646         char buf[1 + sizeof(handle)];
647         buf[0] = DINIT_CP_UNLOADSERVICE;
648         memcpy(buf + 1, &handle, sizeof(handle));
649         write_all_x(socknum, buf, 2 + sizeof(handle));
650
651         wait_for_reply(rbuffer, socknum);
652         if (rbuffer[0] == DINIT_RP_NAK) {
653             cerr << "dinitctl: Could not unload service; service not stopped, or is a dependency of "
654                     "other service." << endl;
655             return 1;
656         }
657         if (rbuffer[0] != DINIT_RP_ACK) {
658             cerr << "dinitctl: Protocol error." << endl;
659             return 1;
660         }
661         rbuffer.consume(1);
662     }
663
664     cout << "Service unloaded." << endl;
665     return 0;
666 }
667
668 static int list_services(int socknum, cpbuffer_t &rbuffer)
669 {
670     using namespace std;
671     
672     char cmdbuf[] = { (char)DINIT_CP_LISTSERVICES };
673     write_all_x(socknum, cmdbuf, 1);
674
675     wait_for_reply(rbuffer, socknum);
676     while (rbuffer[0] == DINIT_RP_SVCINFO) {
677         int hdrsize = 8 + std::max(sizeof(int), sizeof(pid_t));
678         fill_buffer_to(rbuffer, socknum, hdrsize);
679         int nameLen = rbuffer[1];
680         service_state_t current = static_cast<service_state_t>(rbuffer[2]);
681         service_state_t target = static_cast<service_state_t>(rbuffer[3]);
682
683         int console_flags = rbuffer[4];
684         bool has_console = (console_flags & 2) != 0;
685         bool waiting_console = (console_flags & 1) != 0;
686         bool was_skipped = (console_flags & 4) != 0;
687
688         stopped_reason_t stop_reason = static_cast<stopped_reason_t>(rbuffer[5]);
689
690         pid_t service_pid;
691         int exit_status;
692         if (current != service_state_t::STOPPED) {
693             rbuffer.extract((char *)&service_pid, 8, sizeof(service_pid));
694         }
695         else {
696                 rbuffer.extract((char *)&exit_status, 8, sizeof(exit_status));
697         }
698
699         fill_buffer_to(rbuffer, socknum, nameLen + hdrsize);
700
701         char *name_ptr = rbuffer.get_ptr(hdrsize);
702         int clength = std::min(rbuffer.get_contiguous_length(name_ptr), nameLen);
703
704         string name = string(name_ptr, clength);
705         name.append(rbuffer.get_buf_base(), nameLen - clength);
706
707         cout << "[";
708
709         cout << (target  == service_state_t::STARTED ? "{" : " ");
710         if (current == service_state_t::STARTED) {
711             cout << (was_skipped ? "s" : "+");
712         }
713         else {
714             cout << " ";
715         }
716         cout << (target  == service_state_t::STARTED ? "}" : " ");
717         
718         if (current == service_state_t::STARTING) {
719             cout << "<<";
720         }
721         else if (current == service_state_t::STOPPING) {
722             cout << ">>";
723         }
724         else {
725             cout << "  ";
726         }
727         
728         cout << (target  == service_state_t::STOPPED ? "{" : " ");
729         if (current == service_state_t::STOPPED) {
730             bool did_fail = false;
731             if (stop_reason == stopped_reason_t::TERMINATED) {
732                 if (!WIFEXITED(exit_status) || WEXITSTATUS(exit_status) != 0) {
733                     did_fail = true;
734                 }
735             }
736             else did_fail = (stop_reason != stopped_reason_t::NORMAL);
737
738             cout << (did_fail ? "X" : "-");
739         }
740         else {
741                 cout << " ";
742         }
743         cout << (target == service_state_t::STOPPED ? "}" : " ");
744
745         cout << "] " << name;
746
747         if (current != service_state_t::STOPPED && service_pid != -1) {
748                 cout << " (pid: " << service_pid << ")";
749         }
750         
751         if (current == service_state_t::STOPPED && stop_reason == stopped_reason_t::TERMINATED) {
752             if (WIFEXITED(exit_status)) {
753                 cout << " (exit status: " << WEXITSTATUS(exit_status) << ")";
754             }
755             else if (WIFSIGNALED(exit_status)) {
756                 cout << " (signal: " << WSTOPSIG(exit_status) << ")";
757             }
758         }
759
760         if (has_console) {
761                 cout << " (has console)";
762         }
763         else if (waiting_console) {
764                 cout << " (waiting for console)";
765         }
766
767         cout << endl;
768
769         rbuffer.consume(hdrsize + nameLen);
770         wait_for_reply(rbuffer, socknum);
771     }
772
773     if (rbuffer[0] != DINIT_RP_LISTDONE) {
774         cerr << "dinitctl: Control socket protocol error" << endl;
775         return 1;
776     }
777
778     return 0;
779 }
780
781 static int add_remove_dependency(int socknum, cpbuffer_t &rbuffer, bool add,
782         const char *service_from, const char *service_to, dependency_type dep_type)
783 {
784     using namespace std;
785
786
787     handle_t from_handle;
788     handle_t to_handle;
789
790     if (! load_service(socknum, rbuffer, service_from, &from_handle, nullptr)
791             || ! load_service(socknum, rbuffer, service_to, &to_handle, nullptr)) {
792         return 1;
793     }
794
795     constexpr int pktsize = 2 + sizeof(handle_t) * 2;
796     char cmdbuf[pktsize] = { add ? (char)DINIT_CP_ADD_DEP : (char)DINIT_CP_REM_DEP, (char)dep_type};
797     memcpy(cmdbuf + 2, &from_handle, sizeof(from_handle));
798     memcpy(cmdbuf + 2 + sizeof(from_handle), &to_handle, sizeof(to_handle));
799     write_all_x(socknum, cmdbuf, pktsize);
800
801     wait_for_reply(rbuffer, socknum);
802
803     // check reply
804     if (rbuffer[0] == DINIT_RP_NAK) {
805         cerr << "dinitctl: Could not add dependency: circular dependency or wrong state" << endl;
806         return 1;
807     }
808     if (rbuffer[0] != DINIT_RP_ACK) {
809         cerr << "dinitctl: Control socket protocol error" << endl;
810         return 1;
811     }
812
813     return 0;
814 }
815
816 static int shutdown_dinit(int socknum, cpbuffer_t &rbuffer)
817 {
818     // TODO support no-wait option.
819     using namespace std;
820
821     // Build buffer;
822     constexpr int bufsize = 2;
823     char buf[bufsize];
824
825     buf[0] = DINIT_CP_SHUTDOWN;
826     buf[1] = static_cast<char>(shutdown_type_t::HALT);
827
828     write_all_x(socknum, buf, bufsize);
829
830     wait_for_reply(rbuffer, socknum);
831
832     if (rbuffer[0] != DINIT_RP_ACK) {
833         cerr << "dinitctl: Control socket protocol error" << endl;
834         return 1;
835     }
836
837     // Now wait for rollback complete:
838     try {
839         while (true) {
840             wait_for_info(rbuffer, socknum);
841             if (rbuffer[0] == DINIT_ROLLBACK_COMPLETED) {
842                 break;
843             }
844         }
845     }
846     catch (cp_read_exception &exc) {
847         // Dinit can terminate before replying: let's assume that happened.
848         // TODO: better check, possibly ensure that dinit actually sends rollback complete before
849         // termination.
850     }
851
852     return 0;
853 }
854
855 // Join two paths; the 2nd must be relative
856 static std::string join_paths(std::string p1, std::string p2)
857 {
858     std::string r = p1;
859     if (*(r.rbegin()) != '/') {
860         r += '/';
861     }
862     return r + p2;
863 }
864
865 // exception for cancelling a service operation
866 class service_op_cancel { };
867
868 static int enable_disable_service(int socknum, cpbuffer_t &rbuffer, const char *from, const char *to, bool enable)
869 {
870     using namespace std;
871
872     service_state_t from_state = service_state_t::STARTED;
873     handle_t from_handle;
874
875     handle_t to_handle;
876
877     if (! load_service(socknum, rbuffer, from, &from_handle, &from_state)
878             || ! load_service(socknum, rbuffer, to, &to_handle, nullptr)) {
879         return 1;
880     }
881
882     // Get service load path
883     char buf[1] = { DINIT_CP_QUERY_LOAD_MECH };
884     write_all_x(socknum, buf, 1);
885
886     wait_for_reply(rbuffer, socknum);
887
888     if (rbuffer[0] != DINIT_RP_LOADER_MECH) {
889         cerr << "dinitctl: Control socket protocol error" << endl;
890         return 1;
891     }
892
893     // Packet type, load mechanism type, packet size:
894     fill_buffer_to(rbuffer, socknum, 2 + sizeof(uint32_t));
895
896     if (rbuffer[1] != SSET_TYPE_DIRLOAD) {
897         cerr << "dinitctl: unknown configuration, unable to load service descriptions" << endl;
898         return 1;
899     }
900
901     vector<string> paths;
902
903     uint32_t pktsize;
904     rbuffer.extract(&pktsize, 2, sizeof(uint32_t));
905
906     fill_buffer_to(rbuffer, socknum, 2 + sizeof(uint32_t) * 3); // path entries, cwd length
907
908     uint32_t path_entries;  // number of service directories
909     rbuffer.extract(&path_entries, 2 + sizeof(uint32_t), sizeof(uint32_t));
910
911     uint32_t cwd_len;
912     rbuffer.extract(&cwd_len, 2 + sizeof(uint32_t) * 2, sizeof(uint32_t));
913     rbuffer.consume(2 + sizeof(uint32_t) * 3);
914     pktsize -= 2 + sizeof(uint32_t) * 3;
915
916     // Read current working directory of daemon:
917     std::string dinit_cwd = read_string(socknum, rbuffer, cwd_len);
918
919     // dinit daemon base directory against which service paths are resolved is in dinit_cwd
920
921     for (int i = 0; i < (int)path_entries; i++) {
922         uint32_t plen;
923         fill_buffer_to(rbuffer, socknum, sizeof(uint32_t));
924         rbuffer.extract(&plen, 0, sizeof(uint32_t));
925         rbuffer.consume(sizeof(uint32_t));
926         paths.push_back(read_string(socknum, rbuffer, plen));
927     }
928
929     // all service directories are now in the 'paths' vector
930     // Load/read service description for 'from' service:
931
932     ifstream service_file;
933     string service_file_path;
934
935     for (std::string path : paths) {
936         string test_path = join_paths(dinit_cwd + '/' + path, from);
937
938         service_file.open(test_path.c_str(), ios::in);
939         if (service_file) {
940             service_file_path = test_path;
941             break;
942         }
943     }
944
945     if (! service_file) {
946         cerr << "dinitctl: could not locate service file for service '" << from << "'" << endl;
947         return 1;
948     }
949
950     // We now need to read the service file, identify the waits-for.d directory (bail out if more than one),
951     // make sure the service is not listed as a dependency individually.
952
953     string waits_for_d;
954
955     try {
956         process_service_file(from, service_file, [&](string &line, string &setting,
957                 dinit_load::string_iterator i, dinit_load::string_iterator end) -> void {
958             if (setting == "waits-for" || setting == "depends-on" || setting == "depends-ms") {
959                 string dname = dinit_load::read_setting_value(i, end);
960                 if (dname == to) {
961                     // There is already a dependency
962                     cerr << "dinitctl: there is a fixed dependency to service '" << to
963                             << "' in the service description of '" << from << "'." << endl;
964                     throw service_op_cancel();
965                 }
966             }
967             else if (setting == "waits-for.d") {
968                 string dname = dinit_load::read_setting_value(i, end);
969                 if (! waits_for_d.empty()) {
970                     cerr << "dinitctl: service '" << from << "' has multiple waits-for.d directories "
971                             << "specified in service description" << endl;
972                     throw service_op_cancel();
973                 }
974                 waits_for_d = std::move(dname);
975             }
976         });
977     }
978     catch (const service_op_cancel &cexc) {
979         return 1;
980     }
981
982     // If the from service has no waits-for.d specified, we can't continue
983     if (waits_for_d.empty()) {
984         cerr << "dinitctl: service '" << from << "' has no waits-for.d directory specified" << endl;
985         return 1;
986     }
987
988     // check if dependency already exists
989     string dep_link_path = join_paths(waits_for_d, to);
990     struct stat stat_buf;
991     if (lstat(dep_link_path.c_str(), &stat_buf) == -1) {
992         if (errno != ENOENT) {
993             cerr << "dinitctl: checking for existing dependency link: " << dep_link_path << ": "
994                     << strerror(errno) << endl;
995             return 1;
996         }
997     }
998     else {
999         // dependency already exists
1000         if (enable) {
1001             cerr << "dinitctl: service already enabled." << endl;
1002             return 1;
1003         }
1004     }
1005
1006     // warn if 'from' service is not started
1007     if (enable && from_state != service_state_t::STARTED) {
1008         cerr << "dinitctl: warning: enabling dependency for non-started service" << endl;
1009     }
1010
1011     // add/remove dependency
1012     constexpr int enable_pktsize = 2 + sizeof(handle_t) * 2;
1013     char cmdbuf[enable_pktsize] = { char(enable ? DINIT_CP_ENABLESERVICE : DINIT_CP_REM_DEP),
1014             char(dependency_type::WAITS_FOR)};
1015     memcpy(cmdbuf + 2, &from_handle, sizeof(from_handle));
1016     memcpy(cmdbuf + 2 + sizeof(from_handle), &to_handle, sizeof(to_handle));
1017     write_all_x(socknum, cmdbuf, enable_pktsize);
1018
1019     wait_for_reply(rbuffer, socknum);
1020
1021     // check reply
1022     if (enable && rbuffer[0] == DINIT_RP_NAK) {
1023         cerr << "dinitctl: Could not enable service: possible circular dependency" << endl;
1024         return 1;
1025     }
1026     if (rbuffer[0] != DINIT_RP_ACK) {
1027         cerr << "dinitctl: Control socket protocol error" << endl;
1028         return 1;
1029     }
1030
1031     // create link
1032     if (enable) {
1033         if (symlink(dep_link_path.c_str(), (string("../") + to).c_str()) == -1) {
1034             cerr << "dinitctl: Could not create symlink at " << dep_link_path << ": " << strerror(errno) << "\n"
1035                     "dinitctl: Note: service was activated, but will not be enabled on restart." << endl;
1036             return 1;
1037         }
1038     }
1039     else {
1040         if (unlink(dep_link_path.c_str()) == -1) {
1041             cerr << "dinitctl: Could not unlink dependency entry " << dep_link_path << ": " << strerror(errno) << "\n"
1042                     "dinitctl: Note: service was disabled, but will be re-enabled on restart." << endl;
1043             return 1;
1044         }
1045     }
1046
1047     return 0;
1048 }