2 * Copyright (C) 2016 Simon Fels <morphis@gravedo.de>
4 * This program is free software: you can redistribute it and/or modify it
5 * under the terms of the GNU General Public License version 3, as published
6 * by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful, but
9 * WITHOUT ANY WARRANTY; without even the implied warranties of
10 * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
11 * PURPOSE. See the GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program. If not, see <http://www.gnu.org/licenses/>.
18 #include "anbox/qemu/qemud_message_processor.h"
19 #include "anbox/logger.h"
20 #include "anbox/utils.h"
25 static constexpr const long header_size{4};
30 QemudMessageProcessor::QemudMessageProcessor(
31 const std::shared_ptr<network::SocketMessenger> &messenger)
32 : messenger_(messenger) {}
34 QemudMessageProcessor::~QemudMessageProcessor() {}
36 bool QemudMessageProcessor::process_data(const std::vector<std::uint8_t> &data) {
37 for (const auto &byte : data)
38 buffer_.push_back(byte);
40 return process_commands();
43 bool QemudMessageProcessor::process_commands() {
45 if (buffer_.size() < header_size)
48 char header[header_size] = {0};
49 ::memcpy(header, buffer_.data(), header_size);
51 unsigned int body_size = 0;
52 ::sscanf(header, "%04x", &body_size);
54 // Double check that we have enough data to ready the whole body. If
55 // not we have to wait until we have everything.
56 size_t total_size = header_size + body_size;
57 if (buffer_.size() < total_size)
61 // Make sure we only copy as much bytes as we have to and not more
63 reinterpret_cast<const char *>(buffer_.data()) + header_size,
66 handle_command(command);
68 const auto consumed = header_size + body_size;
69 buffer_.erase(buffer_.begin(), buffer_.begin() + consumed);
71 const auto remaining = buffer_.size() - consumed;
79 void QemudMessageProcessor::send_header(const size_t &size) {
80 char header[header_size + 1];
81 std::snprintf(header, header_size + 1, "%04zx", size);
82 messenger_->send(header, header_size);
85 void QemudMessageProcessor::finish_message() {
86 // Send terminating NULL byte
87 messenger_->send(static_cast<const char *>(""), 1);