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