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