1 /*
2 * Copyright (c) 2023 Unionman Technology Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "tcp_server.h"
17 #include <fstream>
18 #include <iostream>
19 using namespace boost::asio;
20 using namespace std::placeholders;
21 constexpr int listen_port = 5022;
TcpServer(boost::asio::io_context & context)22 TcpServer::TcpServer(boost::asio::io_context& context)
23 : io_context(context),
24 endpoint(ip::tcp::v4(), listen_port),
25 accepter(context, endpoint),
26 ssl_context(ssl::context::tlsv12_server)
27 {
28 ssl_context.set_options(ssl::verify_none | ssl::context::no_compression);
29 ssl_context.use_certificate_file("config/serverCert.cer", ssl::context::file_format::pem);
30 ssl_context.use_private_key_file("config/serverKey.pem", ssl::context::file_format::pem);
31 ssl_socket = new ssl::stream<ip::tcp::socket>(context, ssl_context);
32 accepter.async_accept(ssl_socket->lowest_layer(), std::bind(&TcpServer::accept_handler, this, _1));
33 }
34
~TcpServer()35 TcpServer::~TcpServer()
36 {
37 delete ssl_socket;
38 }
39
accept_handler(const boost::system::error_code & ec)40 void TcpServer::accept_handler(const boost::system::error_code& ec)
41 {
42 ssl_socket->async_handshake(ssl::stream_base::server, std::bind(&TcpServer::handshake_handler, this, _1));
43 }
handshake_handler(const boost::system::error_code & ec)44 void TcpServer::handshake_handler(const boost::system::error_code& ec)
45 {
46 std::string jsonInfo = readjsonFile("config/serverInfo.json");
47 ssl_socket->async_write_some(buffer(jsonInfo), std::bind(&TcpServer::write_handler, this, _1, _2));
48 }
write_handler(const boost::system::error_code & ec,std::size_t bytes_transferred)49 void TcpServer::write_handler(const boost::system::error_code& ec, std::size_t bytes_transferred)
50 {
51 ssl_socket->shutdown();
52 ssl_socket->lowest_layer().close();
53 delete ssl_socket;
54 ssl_socket = new ssl::stream<ip::tcp::socket>(io_context, ssl_context);
55 accepter.async_accept(ssl_socket->lowest_layer(), std::bind(&TcpServer::accept_handler, this, _1));
56 }
readjsonFile(const std::string path)57 std::string TcpServer::readjsonFile(const std::string path)
58 {
59 std::string jsonSource;
60 std::fstream jsonFile;
61 std::stringstream jsonStream;
62 jsonFile.open(path);
63 jsonStream << jsonFile.rdbuf();
64 jsonSource = jsonStream.str();
65 return jsonSource;
66 }
67