175220f454f1bfe838276f2d4fc6d7d96add9313
[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
8 #include <sys/types.h>
9 #include <sys/socket.h>
10 #include <sys/un.h>
11 #include <unistd.h>
12 #include <pwd.h>
13
14 #include "control-cmds.h"
15 #include "service-constants.h"
16 #include "cpbuffer.h"
17
18 // dinitctl:  utility to control the Dinit daemon, including starting and stopping of services.
19
20 // This utility communicates with the dinit daemon via a unix socket (/dev/initctl).
21
22 using handle_t = uint32_t;
23
24
25 class ReadCPException
26 {
27     public:
28     int errcode;
29     ReadCPException(int err) : errcode(err) { }
30 };
31
32 static void fillBufferTo(CPBuffer *buf, int fd, int rlength)
33 {
34     int r = buf->fillTo(fd, rlength);
35     if (r == -1) {
36         throw ReadCPException(errno);
37     }
38     else if (r == 0) {
39         throw ReadCPException(0);
40     }
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 // Wait for a reply packet, skipping over any information packets
54 // that are received in the meantime.
55 static void wait_for_reply(CPBuffer &rbuffer, int fd)
56 {
57     fillBufferTo(&rbuffer, fd, 1);
58     
59     while (rbuffer[0] >= 100) {
60         // Information packet; discard.
61         fillBufferTo(&rbuffer, fd, 1);
62         int pktlen = (unsigned char) rbuffer[1];
63         
64         rbuffer.consume(1);  // Consume one byte so we'll read one byte of the next packet
65         fillBufferTo(&rbuffer, fd, pktlen);
66         rbuffer.consume(pktlen - 1);
67     }
68 }
69
70
71 // Write *all* the requested buffer and re-try if necessary until
72 // the buffer is written or an unrecoverable error occurs.
73 static int write_all(int fd, const void *buf, size_t count)
74 {
75     const char *cbuf = static_cast<const char *>(buf);
76     int w = 0;
77     while (count > 0) {
78         int r = write(fd, cbuf, count);
79         if (r == -1) {
80             if (errno == EINTR) continue;
81             return r;
82         }
83         w += r;
84         cbuf += r;
85         count -= r;
86     }
87     return w;
88 }
89
90 // Entry point.
91 int main(int argc, char **argv)
92 {
93     using namespace std;
94     
95     bool do_stop = false;
96     bool show_help = argc < 2;
97     char *service_name = nullptr;
98     
99     std::string control_socket_str;
100     const char * control_socket_path = nullptr;
101     
102     bool verbose = true;
103     bool sys_dinit = false;  // communicate with system daemon
104     bool wait_for_service = true;
105     
106     int command = 0;
107     
108     constexpr int START_SERVICE = 1;
109     constexpr int STOP_SERVICE = 2;
110         
111     for (int i = 1; i < argc; i++) {
112         if (argv[i][0] == '-') {
113             if (strcmp(argv[i], "--help") == 0) {
114                 show_help = true;
115                 break;
116             }
117             else if (strcmp(argv[i], "--no-wait") == 0) {
118                 wait_for_service = false;
119             }
120             else if (strcmp(argv[i], "--quiet") == 0) {
121                 verbose = false;
122             }
123             else if (strcmp(argv[i], "--system") == 0 || strcmp(argv[i], "-s") == 0) {
124                 sys_dinit = true;
125             }
126             else {
127                 cerr << "Unrecognized command-line parameter: " << argv[i] << endl;
128                 return 1;
129             }
130         }
131         else if (command == 0) {
132             if (strcmp(argv[i], "start") == 0) {
133                 command = START_SERVICE; 
134             }
135             else if (strcmp(argv[i], "stop") == 0) {
136                 command = STOP_SERVICE;
137             }
138             else {
139                 show_help = true;
140                 break;
141             }
142         }
143         else {
144             // service name
145             service_name = argv[i];
146             // TODO support multiple services (or at least give error if multiple
147             //      services supplied)
148         }
149     }
150     
151     if (service_name == nullptr || command == 0) {
152         show_help = true;
153     }
154
155     if (show_help) {
156         cout << "dinit-start:   start a dinit service" << endl;
157         cout << "  --help           : show this help" << endl;
158         cout << "  --no-wait        : don't wait for service startup/shutdown to complete" << endl;
159         cout << "  --quiet          : suppress output (except errors)" << endl;
160         cout << "  -s, --system     : control system daemon instead of user daemon" << endl;
161         cout << "  <service-name>   : start the named service" << endl;
162         return 1;
163     }
164     
165     do_stop = (command == STOP_SERVICE);
166     
167     control_socket_path = "/dev/dinitctl";
168     
169     if (! sys_dinit) {
170         char * userhome = getenv("HOME");
171         if (userhome == nullptr) {
172             struct passwd * pwuid_p = getpwuid(getuid());
173             if (pwuid_p != nullptr) {
174                 userhome = pwuid_p->pw_dir;
175             }
176         }
177         
178         if (userhome != nullptr) {
179             control_socket_str = userhome;
180             control_socket_str += "/.dinitctl";
181             control_socket_path = control_socket_str.c_str();
182         }
183         else {
184             cerr << "Cannot locate user home directory (set HOME or check /etc/passwd file)" << endl;
185             return 1;
186         }
187     }
188     
189     int socknum = socket(AF_UNIX, SOCK_STREAM, 0);
190     if (socknum == -1) {
191         perror("socket");
192         return 1;
193     }
194
195     struct sockaddr_un * name;
196     uint sockaddr_size = offsetof(struct sockaddr_un, sun_path) + strlen(control_socket_path) + 1;
197     name = (struct sockaddr_un *) malloc(sockaddr_size);
198     if (name == nullptr) {
199         cerr << "dinit-start: out of memory" << endl;
200         return 1;
201     }
202     
203     name->sun_family = AF_UNIX;
204     strcpy(name->sun_path, control_socket_path);
205     
206     int connr = connect(socknum, (struct sockaddr *) name, sockaddr_size);
207     if (connr == -1) {
208         perror("connect");
209         return 1;
210     }
211     
212     // TODO should start by querying protocol version
213     
214     // Build buffer;
215     uint16_t sname_len = strlen(service_name);
216     int bufsize = 3 + sname_len;
217     char * buf = new char[bufsize];
218     
219     buf[0] = DINIT_CP_LOADSERVICE;
220     memcpy(buf + 1, &sname_len, 2);
221     memcpy(buf + 3, service_name, sname_len);
222     
223     int r = write_all(socknum, buf, bufsize);
224     delete [] buf;
225     if (r == -1) {
226         perror("write");
227         return 1;
228     }
229     
230     // Now we expect a reply:
231     
232     try {
233         CPBuffer rbuffer;
234         wait_for_reply(rbuffer, socknum);
235         
236         //ServiceState state;
237         //ServiceState target_state;
238         handle_t handle;
239         
240         if (rbuffer[0] == DINIT_RP_SERVICERECORD) {
241             fillBufferTo(&rbuffer, socknum, 2 + sizeof(handle));
242             rbuffer.extract((char *) &handle, 2, sizeof(handle));
243             //state = static_cast<ServiceState>(rbuffer[1]);
244             //target_state = static_cast<ServiceState>(rbuffer[2 + sizeof(handle)]);
245             rbuffer.consume(3 + sizeof(handle));
246         }
247         else if (rbuffer[0] == DINIT_RP_NOSERVICE) {
248             cerr << "Failed to find/load service." << endl;
249             return 1;
250         }
251         else {
252             cerr << "Protocol error." << endl;
253             return 1;
254         }
255         
256         // ServiceState wanted_state = do_stop ? ServiceState::STOPPED : ServiceState::STARTED;
257         int command = do_stop ? DINIT_CP_STOPSERVICE : DINIT_CP_STARTSERVICE;
258         
259         // Need to issue STOPSERVICE/STARTSERVICE
260         // We'll do this regardless of the current service state / target state, since issuing
261         // start/stop also sets or clears the "explicitly started" flag on the service.
262         //if (target_state != wanted_state) {
263         {
264             buf = new char[2 + sizeof(handle)];
265             buf[0] = command;
266             buf[1] = 0;  // don't pin
267             memcpy(buf + 2, &handle, sizeof(handle));
268             r = write_all(socknum, buf, 2 + sizeof(handle));
269             delete buf;
270             
271             if (r == -1) {
272                 perror("write");
273                 return 1;
274             }
275             
276             wait_for_reply(rbuffer, socknum);
277             if (rbuffer[0] == DINIT_RP_ALREADYSS) {
278                 if (verbose) {
279                     cout << "Service already " << describeState(do_stop) << "." << endl;
280                 }
281                 return 0; // success!
282             }
283             if (rbuffer[0] != DINIT_RP_ACK) {
284                 cerr << "Protocol error." << endl;
285                 return 1;
286             }
287             rbuffer.consume(1);
288         }
289         
290         /*
291         if (state == wanted_state) {
292             if (verbose) {
293                 cout << "Service already " << describeState(do_stop) << "." << endl;
294             }
295             return 0; // success!
296         }
297         */
298         
299         if (! wait_for_service) {
300             if (verbose) {
301                 cout << "Issued " << describeVerb(do_stop) << " command successfully." << endl;
302             }
303             return 0;
304         }
305         
306         ServiceEvent completionEvent;
307         ServiceEvent cancelledEvent;
308         
309         if (do_stop) {
310             completionEvent = ServiceEvent::STOPPED;
311             cancelledEvent = ServiceEvent::STOPCANCELLED;
312         }
313         else {
314             completionEvent = ServiceEvent::STARTED;
315             cancelledEvent = ServiceEvent::STARTCANCELLED;
316         }
317         
318         // Wait until service started:
319         r = rbuffer.fillTo(socknum, 2);
320         while (r > 0) {
321             if (rbuffer[0] >= 100) {
322                 int pktlen = (unsigned char) rbuffer[1];
323                 fillBufferTo(&rbuffer, socknum, pktlen);
324                 
325                 if (rbuffer[0] == DINIT_IP_SERVICEEVENT) {
326                     handle_t ev_handle;
327                     rbuffer.extract((char *) &ev_handle, 2, sizeof(ev_handle));
328                     ServiceEvent event = static_cast<ServiceEvent>(rbuffer[2 + sizeof(ev_handle)]);
329                     if (ev_handle == handle) {
330                         if (event == completionEvent) {
331                             if (verbose) {
332                                 cout << "Service " << describeState(do_stop) << "." << endl;
333                             }
334                             return 0;
335                         }
336                         else if (event == cancelledEvent) {
337                             if (verbose) {
338                                 cout << "Service " << describeVerb(do_stop) << " cancelled." << endl;
339                             }
340                             return 1;
341                         }
342                         else if (! do_stop && event == ServiceEvent::FAILEDSTART) {
343                             if (verbose) {
344                                 cout << "Service failed to start." << endl;
345                             }
346                             return 1;
347                         }
348                     }
349                 }
350                 
351                 rbuffer.consume(pktlen);
352                 r = rbuffer.fillTo(socknum, 2);
353             }
354             else {
355                 // Not an information packet?
356                 cerr << "protocol error" << endl;
357                 return 1;
358             }
359         }
360         
361         if (r == -1) {
362             perror("read");
363         }
364         else {
365             cerr << "protocol error (connection closed by server)" << endl;
366         }
367         return 1;
368     }
369     catch (ReadCPException &exc) {
370         cerr << "control socket read failure or protocol error" << endl;
371         return 1;
372     }
373     catch (std::bad_alloc &exc) {
374         cerr << "out of memory" << endl;
375         return 1;
376     }
377     
378     return 0;
379 }