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