1/* 2 * Copyright (c) 2023 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 ARKCOMPILER_TOOLCHAIN_WEBSOCKET_CLIENT_WEBSOCKET_CLIENT_H 17#define ARKCOMPILER_TOOLCHAIN_WEBSOCKET_CLIENT_WEBSOCKET_CLIENT_H 18 19#include "http.h" 20#include "websocket_base.h" 21 22#include <array> 23#include <atomic> 24#include <iostream> 25#include <map> 26#include <memory> 27 28namespace OHOS::ArkCompiler::Toolchain { 29class WebSocketClient final : public WebSocketBase { 30public: 31 ~WebSocketClient() noexcept override = default; 32 33 void Close(); 34 35 bool InitToolchainWebSocketForPort(int port, uint32_t timeoutLimit = 5); 36 bool InitToolchainWebSocketForSockName(const std::string &sockName, uint32_t timeoutLimit = 5); 37 bool ClientSendWSUpgradeReq(); 38 bool ClientRecvWSUpgradeRsp(); 39 40 std::string GetSocketStateString(); 41 42private: 43 bool DecodeMessage(WebSocketFrame& wsFrame) const override; 44 45 void CloseOnInitFailure(); 46 bool ValidateIncomingFrame(const WebSocketFrame& wsFrame) const override; 47 std::string CreateFrame(bool isLast, FrameType frameType) const override; 48 std::string CreateFrame(bool isLast, FrameType frameType, const std::string& payload) const override; 49 std::string CreateFrame(bool isLast, FrameType frameType, std::string&& payload) const override; 50 51private: 52 static constexpr std::array<std::string_view, 4> SOCKET_STATE_NAMES = { 53 "connecting", 54 "open", 55 "closing", 56 "closed" 57 }; 58 59 // May replace default websocket-key with randomly generated, as required by spec. 60 static constexpr char CLIENT_WEBSOCKET_UPGRADE_REQ[] = "GET / HTTP/1.1\r\n" 61 "Connection: Upgrade\r\n" 62 "Pragma: no-cache\r\n" 63 "Cache-Control: no-cache\r\n" 64 "Upgrade: websocket\r\n" 65 "Sec-WebSocket-Version: 13\r\n" 66 "Accept-Encoding: gzip, deflate, br\r\n" 67 "Sec-WebSocket-Key: 64b4B+s5JDlgkdg7NekJ+g==\r\n" 68 "Sec-WebSocket-Extensions: permessage-deflate\r\n" 69 "\r\n"; 70 71 static constexpr int NET_SUCCESS = 1; 72 static constexpr uint8_t MASK_KEY[] = {0xa, 0xb, 0xc, 0xd}; 73}; 74} // namespace OHOS::ArkCompiler::Toolchain 75 76#endif // ARKCOMPILER_TOOLCHAIN_WEBSOCKET_CLIENT_WEBSOCKET_CLIENT_H 77