• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #ifndef ARKCOMPILER_TOOLCHAIN_WEBSOCKET_WS_FRAME_H
17 #define ARKCOMPILER_TOOLCHAIN_WEBSOCKET_WS_FRAME_H
18 
19 #include <string>
20 
21 namespace OHOS::ArkCompiler::Toolchain {
22 enum class FrameType : uint8_t {
23     CONTINUATION = 0x0,
24     TEXT = 0x1,
25     BINARY = 0x2,
26     CLOSE = 0x8,
27     PING = 0x9,
28     PONG = 0xa,
29 };
30 
IsControlFrame(uint8_t opcode)31 constexpr inline bool IsControlFrame(uint8_t opcode)
32 {
33     return opcode >= static_cast<uint8_t>(FrameType::CLOSE);
34 }
35 
36 template<typename T, typename = std::enable_if_t<std::is_enum_v<T>>>
EnumToNumber(T type)37 constexpr inline auto EnumToNumber(T type)
38 {
39     using UnderlyingT = std::underlying_type_t<T>;
40     return static_cast<UnderlyingT>(type);
41 }
42 
43 struct WebSocketFrame {
44     static constexpr size_t MASK_LEN = 4;
45     static constexpr size_t HEADER_LEN = 2;
46     static constexpr size_t ONE_BYTE_LENTH_ENC_LIMIT = 125;
47     static constexpr size_t TWO_BYTES_LENTH_ENC = 126;
48     static constexpr size_t TWO_BYTES_LENTH = 2;
49     static constexpr size_t TWO_BYTES_LENGTH_LIMIT = 65536;
50     static constexpr size_t EIGHT_BYTES_LENTH_ENC = 127;
51     static constexpr size_t EIGHT_BYTES_LENTH = 8;
52 
53     uint64_t payloadLen = 0;
54     uint8_t fin = 0;
55     uint8_t opcode = 0;
56     uint8_t mask = 0;
57     uint8_t maskingKey[MASK_LEN] = {0};
58     std::string payload;
59 
60     WebSocketFrame() = default;
WebSocketFrameWebSocketFrame61     explicit WebSocketFrame(const uint8_t headerRaw[HEADER_LEN])
62         : payloadLen(static_cast<uint64_t>(headerRaw[1]) & 0x7f),
63           fin(static_cast<uint8_t>((headerRaw[0] >> MSB_SHIFT_COUNT) & 0x1)),
64           opcode(static_cast<uint8_t>(headerRaw[0] & 0xf)),
65           mask(static_cast<uint8_t>((headerRaw[1] >> MSB_SHIFT_COUNT) & 0x1))
66     {
67     }
68 
69 private:
70     static constexpr int MSB_SHIFT_COUNT = 7;
71 };
72 } // namespace OHOS::ArkCompiler::Toolchain
73 
74 #endif // ARKCOMPILER_TOOLCHAIN_WEBSOCKET_WS_FRAME_H
75