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