Symbian platform (C++)
SDK native APIs, runtime and tooling
Loading...
Searching...
No Matches
framing.h
Go to the documentation of this file.
1// Copyright 2026 The A11 Authors
2//
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// Extracted from A11's Http2WebSocketChannel. Helpers and ParseFrames are
16// verbatim, except the thread annotation: the SDK endpoint has one owner.
17// WriteFrame only replaces the unavailable transport/RNG/lock boundary and
18// accepts string_view to avoid a payload copy.
19#ifndef SYMBIAN_WEBSOCKET_FRAMING_H_
20#define SYMBIAN_WEBSOCKET_FRAMING_H_
21
22#include <cstddef>
23#include <cstdint>
24#include <cstring>
25#include <limits>
26#include <optional>
27#include <string>
28#include <string_view>
29#include <vector>
30
31#include <absl/base/nullability.h>
32
33#include "absl/status/status.h"
35
37constexpr std::uint8_t kContinuation = 0x0;
38constexpr std::uint8_t kText = 0x1;
39constexpr std::uint8_t kBinary = 0x2;
40constexpr std::uint8_t kClose = 0x8;
41constexpr std::uint8_t kPing = 0x9;
42constexpr std::uint8_t kPong = 0xa;
43
44void AppendBigEndian16(std::string* absl_nonnull output, std::uint16_t value) {
45 output->push_back(static_cast<char>((value >> 8U) & 0xffU));
46 output->push_back(static_cast<char>(value & 0xffU));
47}
48
49void AppendBigEndian64(std::string* absl_nonnull output, std::uint64_t value) {
50 for (int shift = 56; shift >= 0; shift -= 8) {
51 output->push_back(static_cast<char>((value >> shift) & 0xffU));
52 }
53}
54
70void MaskInPlace(char* absl_nonnull data, size_t length,
71 const char (&mask)[4]) {
72 std::uint32_t word = 0;
73 std::memcpy(&word, mask, sizeof(word));
74 size_t index = 0;
75 for (; index + sizeof(word) <= length; index += sizeof(word)) {
76 std::uint32_t chunk = 0;
77 std::memcpy(&chunk, data + index, sizeof(chunk));
78 chunk ^= word;
79 std::memcpy(data + index, &chunk, sizeof(chunk));
80 }
81 for (; index < length; ++index) {
82 data[index] ^= mask[index % 4];
83 }
84}
85
86std::uint16_t ReadBigEndian16(std::string_view input, size_t offset) {
87 return static_cast<std::uint16_t>(
88 (static_cast<std::uint16_t>(static_cast<unsigned char>(input[offset]))
89 << 8U) |
90 static_cast<std::uint16_t>(
91 static_cast<unsigned char>(input[offset + 1])));
92}
93
94std::uint64_t ReadBigEndian64(std::string_view input, size_t offset) {
95 std::uint64_t result = 0;
96 for (size_t index = 0; index < sizeof(result); ++index) {
97 result = (result << 8U) | static_cast<unsigned char>(input[offset + index]);
98 }
99 return result;
100}
101
102class Framing {
103 public:
104 Framing(Role role, size_t maximum)
105 : role_(role), max_message_size_(maximum) {}
106
107 struct ParsedActions {
108 std::vector<std::string> messages;
109 std::vector<std::string> pongs;
110 std::optional<std::string> close;
111 };
112
113 absl::Status ParseFrames(ParsedActions* absl_nonnull actions) {
114 size_t consumed = 0;
115 while (input_.size() - consumed >= 2) {
116 const auto first = static_cast<unsigned char>(input_[consumed]);
117 const auto second = static_cast<unsigned char>(input_[consumed + 1]);
118 const bool final = (first & 0x80U) != 0;
119 const std::uint8_t opcode = first & 0x0fU;
120 if ((first & 0x70U) != 0) {
121 return absl::InvalidArgumentError("WebSocket RSV bits are not zero");
122 }
123 const bool masked = (second & 0x80U) != 0;
124 if (masked != (role_ == Role::kServer)) {
125 return absl::InvalidArgumentError(
126 role_ == Role::kServer
127 ? "WebSocket client frame is not masked"
128 : "WebSocket server frame is unexpectedly masked");
129 }
130
131 std::uint64_t payload_size = second & 0x7fU;
132 size_t header_size = 2;
133 if (payload_size == 126) {
134 if (input_.size() - consumed < 4) {
135 break;
136 }
137 payload_size = ReadBigEndian16(input_, consumed + 2);
138 header_size = 4;
139 } else if (payload_size == 127) {
140 if (input_.size() - consumed < 10) {
141 break;
142 }
143 payload_size = ReadBigEndian64(input_, consumed + 2);
144 if ((payload_size & (std::uint64_t{1} << 63U)) != 0) {
145 return absl::InvalidArgumentError("WebSocket length is invalid");
146 }
147 header_size = 10;
148 }
149 if (payload_size > max_message_size_ ||
150 payload_size > std::numeric_limits<size_t>::max()) {
151 return absl::OutOfRangeError(
152 "WebSocket frame exceeds max_message_size");
153 }
154 if (const bool control = opcode >= kClose;
155 control && (!final || payload_size > 125)) {
156 return absl::InvalidArgumentError(
157 "WebSocket control frame must be final and at most 125 bytes");
158 }
159 const size_t mask_size = masked ? 4 : 0;
160 const size_t full_size =
161 header_size + mask_size + static_cast<size_t>(payload_size);
162 if (input_.size() - consumed < full_size) {
163 break;
164 }
165
166 const size_t mask_offset = consumed + header_size;
167 const size_t payload_offset = mask_offset + mask_size;
168 // Copied out before the payload is taken, because taking it may move the
169 // buffer the mask lives in.
170 char mask[4] = {0, 0, 0, 0};
171 if (masked) {
172 std::memcpy(mask, input_.data() + mask_offset, sizeof(mask));
173 }
174 std::string payload;
175 bool taken = false;
176 if (consumed == 0 && payload_offset + payload_size == input_.size()) {
177 // The buffer holds exactly this one frame and nothing before it, which
178 // is the common case for a message that arrived in its own TCP read.
179 payload = std::move(input_);
180 input_.clear();
181 payload.erase(0, payload_offset);
182 taken = true;
183 } else {
184 payload =
185 input_.substr(payload_offset, static_cast<size_t>(payload_size));
186 }
187 if (masked) {
188 MaskInPlace(payload.data(), payload.size(), mask);
189 }
190 // Taking the buffer already consumed it: there is nothing left to skip
191 // past and nothing left to erase, and leaving `consumed` set would make
192 // the loop's `input_.size() - consumed` underflow on the next pass.
193 consumed = taken ? 0 : consumed + full_size;
194
195 if (opcode == kPing) {
196 actions->pongs.push_back(std::move(payload));
197 } else if (opcode == kPong) {
198 continue;
199 } else if (opcode == kClose) {
200 if (payload.size() == 1) {
201 return absl::InvalidArgumentError(
202 "WebSocket close code is truncated");
203 }
204 actions->close = std::move(payload);
205 break;
206 } else if (opcode == kText) {
207 return absl::InvalidArgumentError(
208 "A11 binary channel received a text WebSocket frame");
209 } else if (opcode == kBinary) {
210 if (fragment_opcode_.has_value()) {
211 return absl::InvalidArgumentError(
212 "WebSocket data frame interrupted a fragmented message");
213 }
214 if (final) {
215 actions->messages.push_back(std::move(payload));
216 } else {
217 fragment_opcode_ = opcode;
218 fragmented_ = std::move(payload);
219 }
220 } else if (opcode == kContinuation) {
221 if (!fragment_opcode_.has_value()) {
222 return absl::InvalidArgumentError(
223 "WebSocket continuation has no initial frame");
224 }
225 if (fragmented_.size() + payload.size() > max_message_size_) {
226 return absl::OutOfRangeError(
227 "Fragmented WebSocket message exceeds max_message_size");
228 }
229 fragmented_.append(payload);
230 if (final) {
231 actions->messages.push_back(std::move(fragmented_));
232 fragmented_.clear();
233 fragment_opcode_.reset();
234 }
235 } else {
236 return absl::InvalidArgumentError("WebSocket opcode is unsupported");
237 }
238 }
239 if (consumed != 0) {
240 input_.erase(0, consumed);
241 }
242 return absl::OkStatus();
243 }
244
245 std::string WriteFrame(std::uint8_t opcode, std::string_view payload,
246 std::uint32_t masking_key) {
247 const bool masked = role_ == Role::kClient;
248 std::string frame;
249 frame.reserve(payload.size() + 14);
250 frame.push_back(static_cast<char>(0x80U | opcode));
251 if (const std::uint8_t mask_flag = masked ? 0x80U : 0;
252 payload.size() <= 125) {
253 frame.push_back(static_cast<char>(mask_flag | payload.size()));
254 } else if (payload.size() <= std::numeric_limits<std::uint16_t>::max()) {
255 frame.push_back(static_cast<char>(mask_flag | 126U));
256 AppendBigEndian16(&frame, static_cast<std::uint16_t>(payload.size()));
257 } else {
258 frame.push_back(static_cast<char>(mask_flag | 127U));
259 AppendBigEndian64(&frame, payload.size());
260 }
261 if (masked) {
262 const auto key = masking_key;
263 const char mask[4] = {
264 static_cast<char>((key >> 24U) & 0xffU),
265 static_cast<char>((key >> 16U) & 0xffU),
266 static_cast<char>((key >> 8U) & 0xffU),
267 static_cast<char>(key & 0xffU),
268 };
269 frame.append(mask, sizeof(mask));
270 const size_t body = frame.size();
271 frame.append(payload);
272 MaskInPlace(frame.data() + body, payload.size(), mask);
273 } else {
274 frame.append(payload);
275 }
276 return frame;
277 }
278
279 const Role role_;
280 const size_t max_message_size_;
281 std::string input_;
282 std::optional<std::uint8_t> fragment_opcode_;
283 std::string fragmented_;
284};
285} // namespace symbian::websocket::internal
286#endif
int first
Definition frame.cc:152
int second
Definition frame.cc:153
Definition framing.h:36
constexpr std::uint8_t kBinary
Definition framing.h:39
constexpr std::uint8_t kText
Definition framing.h:38
std::uint64_t ReadBigEndian64(std::string_view input, size_t offset)
Definition framing.h:94
constexpr std::uint8_t kPing
Definition framing.h:41
constexpr std::uint8_t kPong
Definition framing.h:42
void MaskInPlace(char *absl_nonnull data, size_t length, const char(&mask)[4])
XORs length bytes at data with a repeating 4-byte WebSocket mask.
Definition framing.h:70
void AppendBigEndian16(std::string *absl_nonnull output, std::uint16_t value)
Definition framing.h:44
constexpr std::uint8_t kContinuation
Definition framing.h:37
constexpr std::uint8_t kClose
Definition framing.h:40
std::uint16_t ReadBigEndian16(std::string_view input, size_t offset)
Definition framing.h:86
void AppendBigEndian64(std::string *absl_nonnull output, std::uint64_t value)
Definition framing.h:49
Role
Definition websocket.h:20
uint32_t offset
Definition exports.cc:72
std::string_view payload
Definition sis.cc:140
libusb_context *absl_nullable value
Definition usb.cc:37
std::vector< unsigned char > data
Definition usb.cc:296