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