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