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(int 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 { 43 INIT = 0, 44 OK, 45 BAD, 46 RECVING 47 }; 48 49 struct RequestST { 50 int stat = RequstParseStat::INIT; 51 std::string method; 52 std::string uri; 53 const uint8_t* body; 54 size_t bodyLen; 55 }; 56 57 bool CreateSocket(int port); 58 void ProcessClient(HttpSocket& client); 59 void ProcessRequest(HttpSocket& client, RequestST& request); 60 static void HttpResponse(HttpSocket& client, const std::string& status, bool hasBody = false); 61 void ParseRequest(const uint8_t* requst, size_t& len, RequestST& httpReq); 62 void ClearDeadClientThread(); 63 static std::vector<std::string_view> StringSplit(std::string_view source, std::string_view split); 64 65 static const int COUNT_SOCKET = 1; 66 HttpSocket sockets_[COUNT_SOCKET]; // ipv4 and ipv6 67 std::atomic_bool isExit_ = {false}; 68 std::vector<std::unique_ptr<ClientThread>> clientThreads_; 69 using RpcFunction = std::function<bool(const uint8_t*, size_t, RpcServer::ResultCallBack)>; 70 std::map<std::string_view, RpcFunction> rpcFunctions_; 71 const int pollTimeOut_ = 1000; 72 #ifdef _WIN32 73 const uint32_t WS_VERSION_FIRST = 2; 74 const uint32_t WS_VERSION_SEC = 2; 75 #endif 76 }; 77 } // namespace TraceStreamer 78 } // namespace SysTuning 79 80 #endif // RPC_HTTPD_H 81