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