1 /**
2 * Copyright (c) 2022 Huawei Device 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 "asio_server.h"
17 #include "asio_config.h"
18
19 #include "utils/logger.h"
20 #include "websocketpp/uri.hpp"
21
22 #include <memory>
23 #include <system_error>
24
25 #define CONFIG AsioConfig // NOLINT(cppcoreguidelines-macro-usage)
26 #include "server_endpoint-inl.h"
27 #undef CONFIG
28
29 namespace panda::tooling::inspector {
Initialize()30 bool AsioServer::Initialize()
31 {
32 if (initialized_) {
33 return true;
34 }
35
36 std::error_code ec;
37
38 endpoint_.init_asio(ec);
39 if (ec) {
40 LOG(ERROR, DEBUGGER) << "Failed to initialize endpoint";
41 return false;
42 }
43
44 endpoint_.set_reuse_addr(true);
45 initialized_ = true;
46 return true;
47 }
48
Start(uint32_t port)49 websocketpp::uri_ptr AsioServer::Start(uint32_t port)
50 {
51 if (!Initialize()) {
52 return nullptr;
53 }
54
55 std::error_code ec;
56
57 endpoint_.listen(port, ec);
58 if (ec) {
59 LOG(ERROR, DEBUGGER) << "Failed to bind Inspector server on port " << port;
60 return nullptr;
61 }
62
63 endpoint_.start_accept(ec);
64
65 if (!ec) {
66 auto ep = endpoint_.get_local_endpoint(ec);
67
68 if (!ec) {
69 LOG(INFO, DEBUGGER) << "Inspector server listening on " << ep;
70 return std::make_shared<websocketpp::uri>(false, ep.address().to_string(), ep.port(), "/");
71 }
72
73 LOG(ERROR, DEBUGGER) << "Failed to get the TCP endpoint";
74 } else {
75 LOG(ERROR, DEBUGGER) << "Failed to start Inspector connection acceptance loop";
76 }
77
78 endpoint_.stop_listening(ec);
79 return nullptr;
80 }
81
Stop()82 bool AsioServer::Stop()
83 {
84 if (!Initialize()) {
85 return false;
86 }
87
88 std::error_code ec;
89 endpoint_.stop_listening(ec);
90 return !ec;
91 }
92 } // namespace panda::tooling::inspector
93