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