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