02c079d45f362ce8b87fdb8557fe254e10495e7b
[iec.git] / src / type3_AndroidCloud / anbox-master / src / anbox / network / socket_connection.cpp
1 /*
2  * Copyright © 2012 Canonical Ltd.
3  *
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,
6  * as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11  * GNU General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License
14  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
15  *
16  * Authored by: Alan Griffiths <alan@octopull.co.uk>
17  */
18
19 #include "anbox/logger.h"
20
21 #include "anbox/network/message_receiver.h"
22 #include "anbox/network/message_sender.h"
23 #include "anbox/network/socket_connection.h"
24
25 #include <boost/signals2.hpp>
26 #include <boost/throw_exception.hpp>
27
28 #include <stdexcept>
29
30 #include <sys/socket.h>
31 #include <sys/types.h>
32
33 namespace ba = boost::asio;
34 namespace bs = boost::system;
35
36 namespace anbox {
37 namespace network {
38 SocketConnection::SocketConnection(
39     std::shared_ptr<MessageReceiver> const& message_receiver,
40     std::shared_ptr<MessageSender> const& message_sender, int id_,
41     std::shared_ptr<Connections<SocketConnection>> const& connections,
42     std::shared_ptr<MessageProcessor> const& processor)
43     : message_receiver_(message_receiver),
44       message_sender_(message_sender),
45       id_(id_),
46       connections_(connections),
47       processor_(processor) {}
48
49 SocketConnection::~SocketConnection() noexcept {}
50
51 void SocketConnection::send(char const* data, size_t length) {
52   message_sender_->send(data, length);
53 }
54
55 void SocketConnection::read_next_message() {
56   auto callback = std::bind(&SocketConnection::on_read_size, this, std::placeholders::_1, std::placeholders::_2);
57   message_receiver_->async_receive_msg(callback, ba::buffer(buffer_));
58 }
59
60 void SocketConnection::on_read_size(const boost::system::error_code& error, std::size_t bytes_read) {
61   if (error) {
62     connections_->remove(id());
63     return;
64   }
65
66   std::vector<std::uint8_t> data(bytes_read);
67   std::copy(buffer_.data(), buffer_.data() + bytes_read, data.data());
68
69   if (processor_->process_data(data))
70     read_next_message();
71   else
72       connections_->remove(id());
73 }
74 }  // namespace anbox
75 }  // namespace network