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