1 /* 2 * Copyright (c) 2021 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 #ifndef RPC_HTTPD_H 17 #define RPC_HTTPD_H 18 19 #include <atomic> 20 #include <functional> 21 #include <map> 22 #include <string> 23 #include <thread> 24 #include "http_socket.h" 25 #include "rpc_server.h" 26 namespace SysTuning { 27 namespace TraceStreamer { 28 class HttpServer { 29 public: 30 void RegisterRpcFunction(RpcServer* rpc); 31 void Run(int32_t port = 9001); 32 void Exit(); 33 34 static constexpr size_t MAXLEN_REQUEST = 2 * 1024 + 1024 * 1024; // header 2K + body 1M 35 36 private: 37 struct ClientThread { 38 HttpSocket sock_; 39 std::thread thread_; 40 }; 41 42 enum RequstParseStat { INIT = 0, OK, BAD, RECVING }; 43 44 struct RequestST { 45 int32_t stat = RequstParseStat::INIT; 46 std::string method; 47 std::string uri; 48 const uint8_t* body; 49 size_t bodyLen; 50 }; 51 52 bool CreateSocket(int32_t port); 53 void ProcessClient(HttpSocket& client); 54 static void ProcessRequest(HttpSocket& client, RequestST& request); 55 static void ParseRequest(const uint8_t* requst, size_t& len, RequestST& httpReq); 56 void ClearDeadClientThread(); 57 static std::vector<std::string_view> StringSplit(std::string_view source, std::string_view split); 58 59 static const int32_t COUNT_SOCKET = 1; 60 HttpSocket sockets_[COUNT_SOCKET]; // ipv4 and ipv6 61 std::atomic_bool isExit_ = {false}; 62 std::vector<std::unique_ptr<ClientThread>> clientThreads_; 63 using RpcFunction = std::function<bool(const uint8_t*, size_t, RpcServer::ResultCallBack)>; 64 std::map<std::string_view, RpcFunction> rpcFunctions_; 65 const int32_t pollTimeOut_ = 1000; 66 #ifdef _WIN32 67 const uint32_t WS_VERSION_FIRST = 2; 68 const uint32_t WS_VERSION_SEC = 2; 69 #endif 70 }; 71 } // namespace TraceStreamer 72 } // namespace SysTuning 73 74 #endif // RPC_HTTPD_H 75