1 /*
2  * Copyright 2018, The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "commander.h"
18 
19 #include "commands/command.h"
20 #include "log.h"
21 
22 #include <errno.h>
23 #include <qemu_pipe_bp.h>
24 #include <string.h>
25 #include <sys/socket.h>
26 #include <sys/types.h>
27 
28 static const char kQemuPipeName[] = "qemud:network";
29 
30 // How much space to use for each command received
31 static const size_t kReceiveSpace = 1024;
32 // The maximum amount of bytes to keep in the receive buffer for a single
33 // command before dropping data.
34 static const size_t kMaxReceiveBufferSize = 65536;
35 
Commander()36 Commander::Commander() : mPipeFd(-1) {
37 }
38 
~Commander()39 Commander::~Commander() {
40     closePipe();
41 }
42 
init()43 Result Commander::init() {
44     if (mPipeFd != -1) {
45         return Result::error("Commander already initialized");
46     }
47 
48     openPipe();
49 
50     return Result::success();
51 }
52 
registerCommand(const char * commandStr,Command * command)53 void Commander::registerCommand(const char* commandStr, Command* command) {
54     mCommands[commandStr] = command;
55 }
56 
getPollData(std::vector<pollfd> * fds) const57 void Commander::getPollData(std::vector<pollfd>* fds) const {
58     if (mPipeFd != -1) {
59         fds->push_back(pollfd{mPipeFd, POLLIN, 0});
60     }
61 }
62 
getTimeout() const63 Pollable::Timestamp Commander::getTimeout() const {
64     return mDeadline;
65 }
66 
onReadAvailable(int,int *)67 bool Commander::onReadAvailable(int /*fd*/, int* /*status*/) {
68     size_t offset = mReceiveBuffer.size();
69     mReceiveBuffer.resize(offset + kReceiveSpace);
70     if (mReceiveBuffer.size() > kMaxReceiveBufferSize) {
71         // We have buffered too much data, this should never happen but as a
72         // seurity measure let's just drop everything we have and keep
73         // receiving. Maybe the situation will improve.
74         mReceiveBuffer.resize(kReceiveSpace);
75         offset = 0;
76     }
77     while (true) {
78         int status = qemu_pipe_read(mPipeFd, &mReceiveBuffer[offset], kReceiveSpace);
79 
80         if (status < 0) {
81             if (errno == EINTR) {
82                 // We got an interrupt, try again
83                 continue;
84             }
85             LOGE("Commander failed to receive on pipe: %s", strerror(errno));
86             // Don't exit the looper because of this, keep trying
87             return true;
88         }
89         size_t length = static_cast<size_t>(status);
90         mReceiveBuffer.resize(offset + length);
91 
92         while (true) {
93             auto endline = std::find(mReceiveBuffer.begin(),
94                                      mReceiveBuffer.end(),
95                                      '\n');
96             if (endline == mReceiveBuffer.end()) {
97                 // No endline in sight, keep waiting and buffering
98                 return true;
99             }
100 
101             *endline = '\0';
102 
103             char* args = ::strchr(mReceiveBuffer.data(), ' ');
104             if (args) {
105                 *args++ = '\0';
106             }
107             auto command = mCommands.find(mReceiveBuffer.data());
108 
109             if (command != mCommands.end()) {
110                 command->second->onCommand(mReceiveBuffer.data(), args);
111             }
112             // Now that we have processed this line let's remove it from the
113             // receive buffer
114             ++endline;
115             if (endline == mReceiveBuffer.end()) {
116                 mReceiveBuffer.clear();
117                 // There can be nothing left, just return
118                 return true;
119             } else {
120                 mReceiveBuffer.erase(mReceiveBuffer.begin(), endline + 1);
121                 // There may be another line in there so keep looping and look
122                 // for more
123             }
124         }
125         return true;
126     }
127 }
128 
onClose(int,int *)129 bool Commander::onClose(int /*fd*/, int* /*status*/) {
130     // Pipe was closed from the other end, close it on our side and re-open
131     closePipe();
132     openPipe();
133     return true;
134 }
135 
onTimeout(int *)136 bool Commander::onTimeout(int* /*status*/) {
137     if (mPipeFd == -1) {
138         openPipe();
139     }
140     return true;
141 }
142 
openPipe()143 void Commander::openPipe() {
144     mPipeFd = qemu_pipe_open_ns(NULL, kQemuPipeName, O_RDWR);
145     if (mPipeFd == -1) {
146         LOGE("Failed to open QEMU pipe '%s': %s",
147              kQemuPipeName,
148              strerror(errno));
149         // Try again in the future
150         mDeadline = Pollable::Clock::now() + std::chrono::minutes(1);
151     } else {
152         mDeadline = Pollable::Timestamp::max();
153     }
154 }
155 
closePipe()156 void Commander::closePipe() {
157     if (qemu_pipe_valid(mPipeFd)) {
158         qemu_pipe_close(mPipeFd);
159         mPipeFd = QEMU_PIPE_INVALID_HANDLE;
160     }
161 }
162