63e83253a882a832895bc60b5b0a048c20aae5fd
[iec.git] / src / type3_AndroidCloud / anbox-master / src / anbox / network / tcp_socket_connector.cpp
1 /*
2  * Copyright (C) 2016 Simon Fels <morphis@gravedo.de>
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, as published
6  * by the Free Software Foundation.
7  *
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.
12  *
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/>.
15  *
16  */
17
18 #include "anbox/network/tcp_socket_connector.h"
19 #include "anbox/network/connection_context.h"
20 #include "anbox/network/socket_helper.h"
21
22 namespace anbox {
23 namespace network {
24 TcpSocketConnector::TcpSocketConnector(
25     const boost::asio::ip::address_v4& address, unsigned short port,
26     const std::shared_ptr<Runtime>& rt,
27     const std::shared_ptr<ConnectionCreator<boost::asio::ip::tcp>>&
28         connection_creator)
29     : address_(address),
30       port_(port),
31       runtime_(rt),
32       connection_creator_(connection_creator),
33       acceptor_(rt->service(), boost::asio::ip::tcp::endpoint(address, port)) {
34   start_accept();
35 }
36
37 TcpSocketConnector::~TcpSocketConnector() noexcept { acceptor_.cancel(); }
38
39 void TcpSocketConnector::start_accept() {
40   auto socket =
41       std::make_shared<boost::asio::ip::tcp::socket>(runtime_->service());
42
43   acceptor_.async_accept(*socket,
44                          [this, socket](boost::system::error_code const& err) {
45                            on_new_connection(socket, err);
46                          });
47 }
48
49 void TcpSocketConnector::on_new_connection(
50     std::shared_ptr<boost::asio::ip::tcp::socket> const& socket,
51     boost::system::error_code const& err) {
52   switch (err.value()) {
53     case boost::system::errc::success:
54       connection_creator_->create_connection_for(socket);
55       break;
56     default:
57       // Socket was closed so don't listen for any further incoming
58       // connection attempts.
59       return;
60   }
61
62   start_accept();
63 }
64 }  // namespace network
65 }  // namespace anbox