4 bool ControlConn::processPacket()
8 // Note that where we call queuePacket, we must generally check the return value. If it
9 // returns false it has either deleted the connection or marked it for deletion; we
10 // shouldn't touch instance members after that point.
12 int pktType = rbuf[0];
13 if (pktType == DINIT_CP_QUERYVERSION) {
15 // DINIT_RP_CVERSION, (2 byte) minimum compatible version, (2 byte) maximum compatible version
16 char replyBuf[] = { DINIT_RP_CPVERSION, 0, 0, 0, 0 };
17 if (! queuePacket(replyBuf, 1)) return false;
21 if (pktType == DINIT_CP_FINDSERVICE || pktType == DINIT_CP_LOADSERVICE) {
22 return processFindLoad(pktType);
24 if (pktType == DINIT_CP_STARTSERVICE || pktType == DINIT_CP_STOPSERVICE
25 || pktType == DINIT_CP_WAKESERVICE || pktType == DINIT_CP_RELEASESERVICE) {
26 return processStartStop(pktType);
28 if (pktType == DINIT_CP_UNPINSERVICE) {
29 return processUnpinService();
31 if (pktType == DINIT_CP_SHUTDOWN) {
33 if (rbuf.get_length() < 2) {
38 auto sd_type = static_cast<ShutdownType>(rbuf[1]);
40 service_set->stop_all_services(sd_type);
41 char ackBuf[] = { DINIT_RP_ACK };
42 if (! queuePacket(ackBuf, 1)) return false;
44 // Clear the packet from the buffer
50 // Unrecognized: give error response
51 char outbuf[] = { DINIT_RP_BADREQ };
52 if (! queuePacket(outbuf, 1)) return false;
53 bad_conn_close = true;
54 iob.setWatches(OUT_EVENTS);
59 bool ControlConn::processFindLoad(int pktType)
63 constexpr int pkt_size = 4;
65 if (rbuf.get_length() < pkt_size) {
71 rbuf.extract((char *)&svcSize, 1, 2);
72 chklen = svcSize + 3; // packet type + (2 byte) length + service name
73 if (svcSize <= 0 || chklen > 1024) {
74 // Queue error response / mark connection bad
75 char badreqRep[] = { DINIT_RP_BADREQ };
76 if (! queuePacket(badreqRep, 1)) return false;
77 bad_conn_close = true;
78 iob.setWatches(OUT_EVENTS);
82 if (rbuf.get_length() < chklen) {
83 // packet not complete yet; read more
87 ServiceRecord * record = nullptr;
89 string serviceName = rbuf.extract_string(3, svcSize);
91 if (pktType == DINIT_CP_LOADSERVICE) {
94 record = service_set->loadService(serviceName);
96 catch (ServiceLoadExc &slexc) {
97 log(LogLevel::ERROR, "Could not load service ", slexc.serviceName, ": ", slexc.excDescription);
102 record = service_set->findService(serviceName.c_str());
105 if (record != nullptr) {
106 // Allocate a service handle
107 handle_t handle = allocateServiceHandle(record);
108 std::vector<char> rp_buf;
110 rp_buf.push_back(DINIT_RP_SERVICERECORD);
111 rp_buf.push_back(static_cast<char>(record->getState()));
112 for (int i = 0; i < (int) sizeof(handle); i++) {
113 rp_buf.push_back(*(((char *) &handle) + i));
115 rp_buf.push_back(static_cast<char>(record->getTargetState()));
116 if (! queuePacket(std::move(rp_buf))) return false;
119 std::vector<char> rp_buf = { DINIT_RP_NOSERVICE };
120 if (! queuePacket(std::move(rp_buf))) return false;
123 // Clear the packet from the buffer
124 rbuf.consume(chklen);
129 bool ControlConn::processStartStop(int pktType)
133 constexpr int pkt_size = 2 + sizeof(handle_t);
135 if (rbuf.get_length() < pkt_size) {
140 // 1 byte: packet type
141 // 1 byte: pin in requested state (0 = no pin, 1 = pin)
142 // 4 bytes: service handle
144 bool do_pin = (rbuf[1] == 1);
146 rbuf.extract((char *) &handle, 2, sizeof(handle));
148 ServiceRecord *service = findServiceForKey(handle);
149 if (service == nullptr) {
150 // Service handle is bad
151 char badreqRep[] = { DINIT_RP_BADREQ };
152 if (! queuePacket(badreqRep, 1)) return false;
153 bad_conn_close = true;
154 iob.setWatches(OUT_EVENTS);
158 bool already_there = false;
160 case DINIT_CP_STARTSERVICE:
161 // start service, mark as required
162 if (do_pin) service->pinStart();
164 service_set->processQueues(true);
165 already_there = service->getState() == ServiceState::STARTED;
167 case DINIT_CP_STOPSERVICE:
168 // force service to stop
169 if (do_pin) service->pinStop();
171 service->forceStop();
172 service_set->processQueues(false);
173 already_there = service->getState() == ServiceState::STOPPED;
175 case DINIT_CP_WAKESERVICE:
176 // re-start a stopped service (do not mark as required)
177 if (do_pin) service->pinStart();
178 service->start(false);
179 service_set->processQueues(true);
180 already_there = service->getState() == ServiceState::STARTED;
182 case DINIT_CP_RELEASESERVICE:
183 // remove required mark, stop if not required by dependents
184 if (do_pin) service->pinStop();
186 service_set->processQueues(false);
187 already_there = service->getState() == ServiceState::STOPPED;
190 // TODO return an error
194 char ack_buf[] = { (char)(already_there ? DINIT_RP_ALREADYSS : DINIT_RP_ACK) };
196 if (! queuePacket(ack_buf, 1)) return false;
199 // Clear the packet from the buffer
200 rbuf.consume(pkt_size);
205 bool ControlConn::processUnpinService()
209 constexpr int pkt_size = 1 + sizeof(handle_t);
211 if (rbuf.get_length() < pkt_size) {
216 // 1 byte: packet type
217 // 4 bytes: service handle
220 rbuf.extract((char *) &handle, 1, sizeof(handle));
222 ServiceRecord *service = findServiceForKey(handle);
223 if (service == nullptr) {
224 // Service handle is bad
225 char badreqRep[] = { DINIT_RP_BADREQ };
226 if (! queuePacket(badreqRep, 1)) return false;
227 bad_conn_close = true;
228 iob.setWatches(OUT_EVENTS);
233 service_set->processQueues(true);
234 char ack_buf[] = { (char) DINIT_RP_ACK };
235 if (! queuePacket(ack_buf, 1)) return false;
238 // Clear the packet from the buffer
239 rbuf.consume(pkt_size);
244 ControlConn::handle_t ControlConn::allocateServiceHandle(ServiceRecord *record)
246 bool is_unique = true;
247 handle_t largest_seen = 0;
248 handle_t candidate = 0;
249 for (auto p : keyServiceMap) {
250 if (p.first > largest_seen) largest_seen = p.first;
251 if (p.first == candidate) {
252 if (largest_seen == std::numeric_limits<handle_t>::max()) throw std::bad_alloc();
253 candidate = largest_seen + 1;
255 is_unique &= (p.second != record);
258 keyServiceMap[candidate] = record;
259 serviceKeyMap.insert(std::make_pair(record, candidate));
262 record->addListener(this);
269 bool ControlConn::queuePacket(const char *pkt, unsigned size) noexcept
271 int in_flag = bad_conn_close ? 0 : IN_EVENTS;
272 bool was_empty = outbuf.empty();
274 // If the queue is empty, we can try to write the packet out now rather than queueing it.
275 // If the write is unsuccessful or partial, we queue the remainder.
277 int wr = write(iob.fd, pkt, size);
279 if (errno == EPIPE) {
282 if (errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR) {
286 // EAGAIN etc: fall through to below
289 if ((unsigned)wr == size) {
291 iob.setWatches(in_flag);
299 // Create a vector out of the (remaining part of the) packet:
301 outbuf.emplace_back(pkt, pkt + size);
302 iob.setWatches(in_flag | OUT_EVENTS);
305 catch (std::bad_alloc &baexc) {
306 // Mark the connection bad, and stop reading further requests
307 bad_conn_close = true;
310 // We can't send out-of-memory response as we already wrote as much as we
311 // could above. Neither can we later send the response since we have currently
312 // sent an incomplete packet. All we can do is close the connection.
316 iob.setWatches(OUT_EVENTS);
322 // This queuePacket method is frustratingly similar to the one above, but the subtle differences
323 // make them extraordinary difficult to combine into a single method.
324 bool ControlConn::queuePacket(std::vector<char> &&pkt) noexcept
326 int in_flag = bad_conn_close ? 0 : IN_EVENTS;
327 bool was_empty = outbuf.empty();
331 // We can try sending the packet immediately:
332 int wr = write(iob.fd, pkt.data(), pkt.size());
334 if (errno == EPIPE) {
337 if (errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR) {
341 // EAGAIN etc: fall through to below
344 if ((unsigned)wr == pkt.size()) {
346 iob.setWatches(in_flag);
354 outbuf.emplace_back(pkt);
355 iob.setWatches(in_flag | OUT_EVENTS);
358 catch (std::bad_alloc &baexc) {
359 // Mark the connection bad, and stop reading further requests
360 bad_conn_close = true;
363 // We can't send out-of-memory response as we already wrote as much as we
364 // could above. Neither can we later send the response since we have currently
365 // sent an incomplete packet. All we can do is close the connection.
369 iob.setWatches(OUT_EVENTS);
375 bool ControlConn::rollbackComplete() noexcept
377 char ackBuf[2] = { DINIT_ROLLBACK_COMPLETED, 2 };
378 return queuePacket(ackBuf, 2);
381 bool ControlConn::dataReady() noexcept
385 int r = rbuf.fill(fd);
387 // Note file descriptor is non-blocking
389 if (errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR) {
401 if (rbuf.get_length() >= chklen) {
403 return !processPacket();
405 catch (std::bad_alloc &baexc) {
410 else if (rbuf.get_length() == 1024) {
413 // TODO error response?
414 bad_conn_close = true;
415 iob.setWatches(OUT_EVENTS);
418 int out_flags = (bad_conn_close || !outbuf.empty()) ? OUT_EVENTS : 0;
419 iob.setWatches(IN_EVENTS | out_flags);
425 bool ControlConn::sendData() noexcept
427 if (outbuf.empty() && bad_conn_close) {
430 char oomBuf[] = { DINIT_RP_OOM };
431 write(iob.fd, oomBuf, 1);
436 vector<char> & pkt = outbuf.front();
437 char *data = pkt.data();
438 int written = write(iob.fd, data + outpkt_index, pkt.size() - outpkt_index);
440 if (errno == EPIPE) {
444 else if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) {
445 // spurious readiness notification?
448 log(LogLevel::ERROR, "Error writing to control connection: ", strerror(errno));
454 outpkt_index += written;
455 if (outpkt_index == pkt.size()) {
456 // We've finished this packet, move on to the next:
459 if (outbuf.empty() && ! oom_close) {
460 if (! bad_conn_close) {
461 iob.setWatches(IN_EVENTS);
472 ControlConn::~ControlConn() noexcept
475 iob.deregister(*loop);
477 // Clear service listeners
478 for (auto p : serviceKeyMap) {
479 p.first->removeListener(this);
482 active_control_conns--;