Adjust dependency auto-break logic.
[oweals/dinit.git] / src / dinitctl.cc
1 #include <cstdio>
2 #include <cstddef>
3 #include <cstring>
4 #include <string>
5 #include <iostream>
6 #include <system_error>
7 #include <memory>
8
9 #include <sys/types.h>
10 #include <sys/wait.h>
11 #include <sys/socket.h>
12 #include <sys/un.h>
13 #include <unistd.h>
14 #include <signal.h>
15 #include <pwd.h>
16
17 #include "control-cmds.h"
18 #include "service-constants.h"
19 #include "cpbuffer.h"
20 #include "dinit-client.h"
21
22 // dinitctl:  utility to control the Dinit daemon, including starting and stopping of services.
23
24 // This utility communicates with the dinit daemon via a unix stream socket (/dev/initctl, or $HOME/.dinitctl).
25
26 static constexpr uint16_t min_cp_version = 1;
27 static constexpr uint16_t max_cp_version = 1;
28
29 enum class command_t;
30
31 static int issue_load_service(int socknum, const char *service_name, bool find_only = false);
32 static int check_load_reply(int socknum, cpbuffer_t &, handle_t *handle_p, service_state_t *state_p);
33 static int start_stop_service(int socknum, cpbuffer_t &, const char *service_name, command_t command,
34         bool do_pin, bool wait_for_service, bool verbose);
35 static int unpin_service(int socknum, cpbuffer_t &, const char *service_name, bool verbose);
36 static int unload_service(int socknum, cpbuffer_t &, const char *service_name);
37 static int list_services(int socknum, cpbuffer_t &);
38 static int shutdown_dinit(int soclknum, cpbuffer_t &);
39 static int add_remove_dependency(int socknum, cpbuffer_t &rbuffer, bool add, char *service_from,
40         char *service_to, dependency_type dep_type);
41
42
43 static const char * describeState(bool stopped)
44 {
45     return stopped ? "stopped" : "started";
46 }
47
48 static const char * describeVerb(bool stop)
49 {
50     return stop ? "stop" : "start";
51 }
52
53 enum class command_t {
54     NONE,
55     START_SERVICE,
56     WAKE_SERVICE,
57     STOP_SERVICE,
58     RELEASE_SERVICE,
59     UNPIN_SERVICE,
60     UNLOAD_SERVICE,
61     LIST_SERVICES,
62     SHUTDOWN,
63     ADD_DEPENDENCY,
64     RM_DEPENDENCY
65 };
66
67
68 // Entry point.
69 int main(int argc, char **argv)
70 {
71     using namespace std;
72     
73     bool show_help = argc < 2;
74     char *service_name = nullptr;
75     char *to_service_name = nullptr;
76     dependency_type dep_type;
77     bool dep_type_set = false;
78     
79     std::string control_socket_str;
80     const char * control_socket_path = nullptr;
81     
82     bool verbose = true;
83     bool sys_dinit = false;  // communicate with system daemon
84     bool wait_for_service = true;
85     bool do_pin = false;
86     
87     command_t command = command_t::NONE;
88         
89     for (int i = 1; i < argc; i++) {
90         if (argv[i][0] == '-') {
91             if (strcmp(argv[i], "--help") == 0) {
92                 show_help = true;
93                 break;
94             }
95             else if (strcmp(argv[i], "--no-wait") == 0) {
96                 wait_for_service = false;
97             }
98             else if (strcmp(argv[i], "--quiet") == 0) {
99                 verbose = false;
100             }
101             else if (strcmp(argv[i], "--system") == 0 || strcmp(argv[i], "-s") == 0) {
102                 sys_dinit = true;
103             }
104             else if (strcmp(argv[i], "--pin") == 0) {
105                 do_pin = true;
106             }
107             else {
108                 return 1;
109             }
110         }
111         else if (command == command_t::NONE) {
112             if (strcmp(argv[i], "start") == 0) {
113                 command = command_t::START_SERVICE; 
114             }
115             else if (strcmp(argv[i], "wake") == 0) {
116                 command = command_t::WAKE_SERVICE;
117             }
118             else if (strcmp(argv[i], "stop") == 0) {
119                 command = command_t::STOP_SERVICE;
120             }
121             else if (strcmp(argv[i], "release") == 0) {
122                 command = command_t::RELEASE_SERVICE;
123             }
124             else if (strcmp(argv[i], "unpin") == 0) {
125                 command = command_t::UNPIN_SERVICE;
126             }
127             else if (strcmp(argv[i], "unload") == 0) {
128                 command = command_t::UNLOAD_SERVICE;
129             }
130             else if (strcmp(argv[i], "list") == 0) {
131                 command = command_t::LIST_SERVICES;
132             }
133             else if (strcmp(argv[i], "shutdown") == 0) {
134                 command = command_t::SHUTDOWN;
135             }
136             else if (strcmp(argv[i], "add-dep") == 0) {
137                 command = command_t::ADD_DEPENDENCY;
138             }
139             else if (strcmp(argv[i], "rm-dep") == 0) {
140                 command = command_t::RM_DEPENDENCY;
141             }
142             else {
143                 show_help = true;
144                 break;
145             }
146         }
147         else {
148             // service name / other non-option
149             if (command == command_t::ADD_DEPENDENCY || command == command_t::RM_DEPENDENCY) {
150                 if (! dep_type_set) {
151                     if (strcmp(argv[i], "regular") == 0) {
152                         dep_type = dependency_type::REGULAR;
153                     }
154                     else if (strcmp(argv[i], "milestone") == 0) {
155                         dep_type = dependency_type::MILESTONE;
156                     }
157                     else if (strcmp(argv[i], "waits-for") == 0) {
158                         dep_type = dependency_type::WAITS_FOR;
159                     }
160                     else {
161                         show_help = true;
162                         break;
163                     }
164                     dep_type_set = true;
165                 }
166                 else if (service_name == nullptr) {
167                     service_name = argv[i];
168                 }
169                 else if (to_service_name == nullptr) {
170                     to_service_name = argv[i];
171                 }
172                 else {
173                     show_help = true;
174                     break;
175                 }
176             }
177             else {
178                 if (service_name != nullptr) {
179                     show_help = true;
180                     break;
181                 }
182                 service_name = argv[i];
183                 // TODO support multiple services
184             }
185         }
186     }
187     
188     bool no_service_cmd = (command == command_t::LIST_SERVICES || command == command_t::SHUTDOWN);
189
190     if (service_name != nullptr && no_service_cmd) {
191         show_help = true;
192     }
193     
194     if ((service_name == nullptr && ! no_service_cmd) || command == command_t::NONE) {
195         show_help = true;
196     }
197
198     if ((command == command_t::ADD_DEPENDENCY || command == command_t::RM_DEPENDENCY)
199             && (! dep_type_set || service_name == nullptr || to_service_name == nullptr)) {
200         show_help = true;
201     }
202
203     if (show_help) {
204         cout << "dinitctl:   control Dinit services" << endl;
205         
206         cout << "\nUsage:" << endl;
207         cout << "    dinitctl [options] start [options] <service-name> : start and activate service" << endl;
208         cout << "    dinitctl [options] stop [options] <service-name>  : stop service and cancel explicit activation" << endl;
209         cout << "    dinitctl [options] wake [options] <service-name>  : start but do not mark activated" << endl;
210         cout << "    dinitctl [options] release [options] <service-name> : release activation, stop if no dependents" << endl;
211         cout << "    dinitctl [options] unpin <service-name>           : un-pin the service (after a previous pin)" << endl;
212         cout << "    dinitctl unload <service-name>                    : unload the service" << endl;
213         cout << "    dinitctl list                                     : list loaded services" << endl;
214         cout << "    dinitctl shutdown                                 : stop all services and terminate dinit" << endl;
215         cout << "    dinitctl add-dep <type> <from-service> <to-service> : add a dependency between services" << endl;
216         cout << "    dinitctl rm-dep <type> <from-service> <to-service> : remove a dependency between services" << endl;
217         
218         cout << "\nNote: An activated service continues running when its dependents stop." << endl;
219         
220         cout << "\nGeneral options:" << endl;
221         cout << "  -s, --system     : control system daemon instead of user daemon" << endl;
222         cout << "  --quiet          : suppress output (except errors)" << endl;
223         
224         cout << "\nCommand options:" << endl;
225         cout << "  --help           : show this help" << endl;
226         cout << "  --no-wait        : don't wait for service startup/shutdown to complete" << endl;
227         cout << "  --pin            : pin the service in the requested (started/stopped) state" << endl;
228         return 1;
229     }
230     
231     signal(SIGPIPE, SIG_IGN);
232     
233     control_socket_path = "/dev/dinitctl";
234     
235     // Locate control socket
236     if (! sys_dinit) {
237         char * userhome = getenv("HOME");
238         if (userhome == nullptr) {
239             struct passwd * pwuid_p = getpwuid(getuid());
240             if (pwuid_p != nullptr) {
241                 userhome = pwuid_p->pw_dir;
242             }
243         }
244         
245         if (userhome != nullptr) {
246             control_socket_str = userhome;
247             control_socket_str += "/.dinitctl";
248             control_socket_path = control_socket_str.c_str();
249         }
250         else {
251             cerr << "Cannot locate user home directory (set HOME or check /etc/passwd file)" << endl;
252             return 1;
253         }
254     }
255     
256     int socknum = socket(AF_UNIX, SOCK_STREAM, 0);
257     if (socknum == -1) {
258         perror("dinitctl: socket");
259         return 1;
260     }
261
262     struct sockaddr_un * name;
263     uint sockaddr_size = offsetof(struct sockaddr_un, sun_path) + strlen(control_socket_path) + 1;
264     name = (struct sockaddr_un *) malloc(sockaddr_size);
265     if (name == nullptr) {
266         cerr << "dinitctl: Out of memory" << endl;
267         return 1;
268     }
269     
270     name->sun_family = AF_UNIX;
271     strcpy(name->sun_path, control_socket_path);
272     
273     int connr = connect(socknum, (struct sockaddr *) name, sockaddr_size);
274     if (connr == -1) {
275         perror("dinitctl: connect");
276         return 1;
277     }
278     
279     try {
280         // Start by querying protocol version:
281         cpbuffer_t rbuffer;
282         check_protocol_version(min_cp_version, max_cp_version, rbuffer, socknum);
283
284         if (command == command_t::UNPIN_SERVICE) {
285             return unpin_service(socknum, rbuffer, service_name, verbose);
286         }
287         else if (command == command_t::UNLOAD_SERVICE) {
288             return unload_service(socknum, rbuffer, service_name);
289         }
290         else if (command == command_t::LIST_SERVICES) {
291             return list_services(socknum, rbuffer);
292         }
293         else if (command == command_t::SHUTDOWN) {
294             return shutdown_dinit(socknum, rbuffer);
295         }
296         else if (command == command_t::ADD_DEPENDENCY || command == command_t::RM_DEPENDENCY) {
297             return add_remove_dependency(socknum, rbuffer, command == command_t::ADD_DEPENDENCY,
298                     service_name, to_service_name, dep_type);
299         }
300         else {
301             return start_stop_service(socknum, rbuffer, service_name, command, do_pin,
302                     wait_for_service, verbose);
303         }
304     }
305     catch (cp_old_client_exception &e) {
306         std::cerr << "dinitctl: too old (server reports newer protocol version)" << std::endl;
307         return 1;
308     }
309     catch (cp_old_server_exception &e) {
310         std::cerr << "dinitctl: server too old or protocol error" << std::endl;
311         return 1;
312     }
313     catch (cp_read_exception &e) {
314         cerr << "dinitctl: control socket read failure or protocol error" << endl;
315         return 1;
316     }
317     catch (cp_write_exception &e) {
318         cerr << "dinitctl: control socket write error: " << std::strerror(e.errcode) << endl;
319         return 1;
320     }
321 }
322
323 // Start/stop a service
324 static int start_stop_service(int socknum, cpbuffer_t &rbuffer, const char *service_name,
325         command_t command, bool do_pin, bool wait_for_service, bool verbose)
326 {
327     using namespace std;
328
329     bool do_stop = (command == command_t::STOP_SERVICE || command == command_t::RELEASE_SERVICE);
330     
331     if (issue_load_service(socknum, service_name)) {
332         return 1;
333     }
334
335     // Now we expect a reply:
336     
337     wait_for_reply(rbuffer, socknum);
338
339     service_state_t state;
340     //service_state_t target_state;
341     handle_t handle;
342
343     if (check_load_reply(socknum, rbuffer, &handle, &state) != 0) {
344         return 0;
345     }
346
347     service_state_t wanted_state = do_stop ? service_state_t::STOPPED : service_state_t::STARTED;
348     int pcommand = 0;
349     switch (command) {
350         case command_t::STOP_SERVICE:
351             pcommand = DINIT_CP_STOPSERVICE;
352             break;
353         case command_t::RELEASE_SERVICE:
354             pcommand = DINIT_CP_RELEASESERVICE;
355             break;
356         case command_t::START_SERVICE:
357             pcommand = DINIT_CP_STARTSERVICE;
358             break;
359         case command_t::WAKE_SERVICE:
360             pcommand = DINIT_CP_WAKESERVICE;
361             break;
362         default: ;
363     }
364
365     // Need to issue STOPSERVICE/STARTSERVICE
366     // We'll do this regardless of the current service state / target state, since issuing
367     // start/stop also sets or clears the "explicitly started" flag on the service.
368     {
369         char buf[2 + sizeof(handle)];
370         buf[0] = pcommand;
371         buf[1] = do_pin ? 1 : 0;
372         memcpy(buf + 2, &handle, sizeof(handle));
373         write_all_x(socknum, buf, 2 + sizeof(handle));
374         
375         wait_for_reply(rbuffer, socknum);
376         if (rbuffer[0] == DINIT_RP_ALREADYSS) {
377             bool already = (state == wanted_state);
378             if (verbose) {
379                 cout << "Service " << (already ? "(already) " : "") << describeState(do_stop) << "." << endl;
380             }
381             return 0; // success!
382         }
383         if (rbuffer[0] != DINIT_RP_ACK) {
384             cerr << "dinitctl: Protocol error." << endl;
385             return 1;
386         }
387         rbuffer.consume(1);
388     }
389
390     if (! wait_for_service) {
391         if (verbose) {
392             cout << "Issued " << describeVerb(do_stop) << " command successfully." << endl;
393         }
394         return 0;
395     }
396
397     service_event_t completionEvent;
398     service_event_t cancelledEvent;
399
400     if (do_stop) {
401         completionEvent = service_event_t::STOPPED;
402         cancelledEvent = service_event_t::STOPCANCELLED;
403     }
404     else {
405         completionEvent = service_event_t::STARTED;
406         cancelledEvent = service_event_t::STARTCANCELLED;
407     }
408
409     // Wait until service started:
410     int r = rbuffer.fill_to(socknum, 2);
411     while (r > 0) {
412         if (rbuffer[0] >= 100) {
413             int pktlen = (unsigned char) rbuffer[1];
414             fill_buffer_to(rbuffer, socknum, pktlen);
415
416             if (rbuffer[0] == DINIT_IP_SERVICEEVENT) {
417                 handle_t ev_handle;
418                 rbuffer.extract((char *) &ev_handle, 2, sizeof(ev_handle));
419                 service_event_t event = static_cast<service_event_t>(rbuffer[2 + sizeof(ev_handle)]);
420                 if (ev_handle == handle) {
421                     if (event == completionEvent) {
422                         if (verbose) {
423                             cout << "Service " << describeState(do_stop) << "." << endl;
424                         }
425                         return 0;
426                     }
427                     else if (event == cancelledEvent) {
428                         if (verbose) {
429                             cout << "Service " << describeVerb(do_stop) << " cancelled." << endl;
430                         }
431                         return 1;
432                     }
433                     else if (! do_stop && event == service_event_t::FAILEDSTART) {
434                         if (verbose) {
435                             cout << "Service failed to start." << endl;
436                         }
437                         return 1;
438                     }
439                 }
440             }
441
442             rbuffer.consume(pktlen);
443             r = rbuffer.fill_to(socknum, 2);
444         }
445         else {
446             // Not an information packet?
447             cerr << "dinitctl: protocol error" << endl;
448             return 1;
449         }
450     }
451
452     if (r == -1) {
453         perror("dinitctl: read");
454     }
455     else {
456         cerr << "protocol error (connection closed by server)" << endl;
457     }
458     return 1;
459 }
460
461 // Issue a "load service" command (DINIT_CP_LOADSERVICE), without waiting for
462 // a response. Returns 1 on failure (with error logged), 0 on success.
463 static int issue_load_service(int socknum, const char *service_name, bool find_only)
464 {
465     // Build buffer;
466     uint16_t sname_len = strlen(service_name);
467     int bufsize = 3 + sname_len;
468     
469     std::unique_ptr<char[]> ubuf(new char[bufsize]);
470     auto buf = ubuf.get();
471
472     buf[0] = find_only ? DINIT_CP_FINDSERVICE : DINIT_CP_LOADSERVICE;
473     memcpy(buf + 1, &sname_len, 2);
474     memcpy(buf + 3, service_name, sname_len);
475
476     write_all_x(socknum, buf, bufsize);
477     
478     return 0;
479 }
480
481 // Check that a "load service" reply was received, and that the requested service was found.
482 static int check_load_reply(int socknum, cpbuffer_t &rbuffer, handle_t *handle_p, service_state_t *state_p)
483 {
484     using namespace std;
485     
486     if (rbuffer[0] == DINIT_RP_SERVICERECORD) {
487         fill_buffer_to(rbuffer, socknum, 2 + sizeof(*handle_p));
488         rbuffer.extract((char *) handle_p, 2, sizeof(*handle_p));
489         if (state_p) *state_p = static_cast<service_state_t>(rbuffer[1]);
490         //target_state = static_cast<service_state_t>(rbuffer[2 + sizeof(handle)]);
491         rbuffer.consume(3 + sizeof(*handle_p));
492         return 0;
493     }
494     else if (rbuffer[0] == DINIT_RP_NOSERVICE) {
495         cerr << "dinitctl: failed to find/load service." << endl;
496         return 1;
497     }
498     else {
499         cerr << "dinitctl: protocol error." << endl;
500         return 1;
501     }
502 }
503
504 static int unpin_service(int socknum, cpbuffer_t &rbuffer, const char *service_name, bool verbose)
505 {
506     using namespace std;
507     
508     // Build buffer;
509     if (issue_load_service(socknum, service_name) == 1) {
510         return 1;
511     }
512
513     // Now we expect a reply:
514     
515     wait_for_reply(rbuffer, socknum);
516
517     handle_t handle;
518
519     if (check_load_reply(socknum, rbuffer, &handle, nullptr) != 0) {
520         return 1;
521     }
522
523     // Issue UNPIN command.
524     {
525         char buf[1 + sizeof(handle)];
526         buf[0] = DINIT_CP_UNPINSERVICE;
527         memcpy(buf + 1, &handle, sizeof(handle));
528         write_all_x(socknum, buf, 2 + sizeof(handle));
529         
530         wait_for_reply(rbuffer, socknum);
531         if (rbuffer[0] != DINIT_RP_ACK) {
532             cerr << "dinitctl: protocol error." << endl;
533             return 1;
534         }
535         rbuffer.consume(1);
536     }
537
538     if (verbose) {
539         cout << "Service unpinned." << endl;
540     }
541     return 0;
542 }
543
544 static int unload_service(int socknum, cpbuffer_t &rbuffer, const char *service_name)
545 {
546     using namespace std;
547
548     // Build buffer;
549     if (issue_load_service(socknum, service_name, true) == 1) {
550         return 1;
551     }
552
553     // Now we expect a reply:
554
555     wait_for_reply(rbuffer, socknum);
556
557     handle_t handle;
558
559     if (check_load_reply(socknum, rbuffer, &handle, nullptr) != 0) {
560         return 1;
561     }
562
563     // Issue UNLOAD command.
564     {
565         char buf[1 + sizeof(handle)];
566         buf[0] = DINIT_CP_UNLOADSERVICE;
567         memcpy(buf + 1, &handle, sizeof(handle));
568         write_all_x(socknum, buf, 2 + sizeof(handle));
569
570         wait_for_reply(rbuffer, socknum);
571         if (rbuffer[0] == DINIT_RP_NAK) {
572             cerr << "dinitctl: Could not unload service; service not stopped, or is a dependency of "
573                     "other service." << endl;
574             return 1;
575         }
576         if (rbuffer[0] != DINIT_RP_ACK) {
577             cerr << "dinitctl: Protocol error." << endl;
578             return 1;
579         }
580         rbuffer.consume(1);
581     }
582
583     cout << "Service unloaded." << endl;
584     return 0;
585 }
586
587 static int list_services(int socknum, cpbuffer_t &rbuffer)
588 {
589     using namespace std;
590     
591     char cmdbuf[] = { (char)DINIT_CP_LISTSERVICES };
592     write_all_x(socknum, cmdbuf, 1);
593
594     wait_for_reply(rbuffer, socknum);
595     while (rbuffer[0] == DINIT_RP_SVCINFO) {
596         int hdrsize = 8 + std::max(sizeof(int), sizeof(pid_t));
597         fill_buffer_to(rbuffer, socknum, hdrsize);
598         int nameLen = rbuffer[1];
599         service_state_t current = static_cast<service_state_t>(rbuffer[2]);
600         service_state_t target = static_cast<service_state_t>(rbuffer[3]);
601
602         int console_flags = rbuffer[4];
603         bool has_console = (console_flags & 2) != 0;
604         bool waiting_console = (console_flags & 1) != 0;
605         bool was_skipped = (console_flags & 4) != 0;
606
607         stopped_reason_t stop_reason = static_cast<stopped_reason_t>(rbuffer[5]);
608
609         pid_t service_pid;
610         int exit_status;
611         if (current != service_state_t::STOPPED) {
612             rbuffer.extract((char *)&service_pid, 8, sizeof(service_pid));
613         }
614         else {
615                 rbuffer.extract((char *)&exit_status, 8, sizeof(exit_status));
616         }
617
618         fill_buffer_to(rbuffer, socknum, nameLen + hdrsize);
619
620         char *name_ptr = rbuffer.get_ptr(hdrsize);
621         int clength = std::min(rbuffer.get_contiguous_length(name_ptr), nameLen);
622
623         string name = string(name_ptr, clength);
624         name.append(rbuffer.get_buf_base(), nameLen - clength);
625
626         cout << "[";
627
628         cout << (target  == service_state_t::STARTED ? "{" : " ");
629         if (current == service_state_t::STARTED) {
630             cout << (was_skipped ? "s" : "+");
631         }
632         else {
633             cout << " ";
634         }
635         cout << (target  == service_state_t::STARTED ? "}" : " ");
636         
637         if (current == service_state_t::STARTING) {
638             cout << "<<";
639         }
640         else if (current == service_state_t::STOPPING) {
641             cout << ">>";
642         }
643         else {
644             cout << "  ";
645         }
646         
647         cout << (target  == service_state_t::STOPPED ? "{" : " ");
648         if (current == service_state_t::STOPPED) {
649             bool did_fail = false;
650             if (stop_reason == stopped_reason_t::TERMINATED) {
651                 if (!WIFEXITED(exit_status) || WEXITSTATUS(exit_status) != 0) {
652                     did_fail = true;
653                 }
654             }
655             else did_fail = (stop_reason != stopped_reason_t::NORMAL);
656
657             cout << (did_fail ? "X" : "-");
658         }
659         else {
660                 cout << " ";
661         }
662         cout << (target == service_state_t::STOPPED ? "}" : " ");
663
664         cout << "] " << name;
665
666         if (current != service_state_t::STOPPED && service_pid != -1) {
667                 cout << " (pid: " << service_pid << ")";
668         }
669         
670         if (current == service_state_t::STOPPED && stop_reason == stopped_reason_t::TERMINATED) {
671             if (WIFEXITED(exit_status)) {
672                 cout << " (exit status: " << WEXITSTATUS(exit_status) << ")";
673             }
674             else if (WIFSIGNALED(exit_status)) {
675                 cout << " (signal: " << WSTOPSIG(exit_status) << ")";
676             }
677         }
678
679         if (has_console) {
680                 cout << " (has console)";
681         }
682         else if (waiting_console) {
683                 cout << " (waiting for console)";
684         }
685
686         cout << endl;
687
688         rbuffer.consume(hdrsize + nameLen);
689         wait_for_reply(rbuffer, socknum);
690     }
691
692     if (rbuffer[0] != DINIT_RP_LISTDONE) {
693         cerr << "dinitctl: Control socket protocol error" << endl;
694         return 1;
695     }
696
697     return 0;
698 }
699
700 static int add_remove_dependency(int socknum, cpbuffer_t &rbuffer, bool add, char *service_from,
701         char *service_to, dependency_type dep_type)
702 {
703     using namespace std;
704
705     // First find the "from" service:
706     if (issue_load_service(socknum, service_from, false) == 1) {
707         return 1;
708     }
709
710     wait_for_reply(rbuffer, socknum);
711
712     handle_t from_handle;
713
714     if (check_load_reply(socknum, rbuffer, &from_handle, nullptr) != 0) {
715         return 1;
716     }
717
718     // Then find or load the "to" service:
719     if (issue_load_service(socknum, service_to, false) == 1) {
720         return 1;
721     }
722
723     wait_for_reply(rbuffer, socknum);
724
725     handle_t to_handle;
726
727     if (check_load_reply(socknum, rbuffer, &to_handle, nullptr) != 0) {
728         return 1;
729     }
730
731     constexpr int pktsize = 2 + sizeof(handle_t) * 2;
732     char cmdbuf[pktsize] = { add ? (char)DINIT_CP_ADD_DEP : (char)DINIT_CP_REM_DEP, (char)dep_type};
733     memcpy(cmdbuf + 2, &from_handle, sizeof(from_handle));
734     memcpy(cmdbuf + 2 + sizeof(from_handle), &to_handle, sizeof(to_handle));
735     write_all_x(socknum, cmdbuf, pktsize);
736
737     wait_for_reply(rbuffer, socknum);
738
739     // check reply
740     if (rbuffer[0] == DINIT_RP_NAK) {
741         cerr << "dinitctl: Could not add dependency: circular dependency or wrong state" << endl;
742         return 1;
743     }
744     if (rbuffer[0] != DINIT_RP_ACK) {
745         cerr << "dinitctl: Control socket protocol error" << endl;
746         return 1;
747     }
748
749     return 0;
750 }
751
752 static int shutdown_dinit(int socknum, cpbuffer_t &rbuffer)
753 {
754     // TODO support no-wait option.
755     using namespace std;
756
757     // Build buffer;
758     constexpr int bufsize = 2;
759     char buf[bufsize];
760
761     buf[0] = DINIT_CP_SHUTDOWN;
762     buf[1] = static_cast<char>(shutdown_type_t::HALT);
763
764     write_all_x(socknum, buf, bufsize);
765
766     wait_for_reply(rbuffer, socknum);
767
768     if (rbuffer[0] != DINIT_RP_ACK) {
769         cerr << "dinitctl: Control socket protocol error" << endl;
770         return 1;
771     }
772
773     // Now wait for rollback complete:
774     try {
775         while (true) {
776             wait_for_info(rbuffer, socknum);
777             if (rbuffer[0] == DINIT_ROLLBACK_COMPLETED) {
778                 break;
779             }
780         }
781     }
782     catch (cp_read_exception &exc) {
783         // Dinit can terminate before replying: let's assume that happened.
784         // TODO: better check, possibly ensure that dinit actually sends rollback complete before
785         // termination.
786     }
787
788     return 0;
789 }