Re-land: C++ readability review
[chromium-blink-merge.git] / net / server / web_socket_encoder.cc
blob8e1681c8a7233d3878fb0180fc16e5d88e4f3384
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "net/server/web_socket_encoder.h"
7 #include "base/logging.h"
8 #include "base/strings/string_number_conversions.h"
9 #include "base/strings/stringprintf.h"
10 #include "net/base/io_buffer.h"
11 #include "net/websockets/websocket_extension_parser.h"
13 namespace net {
15 const char WebSocketEncoder::kClientExtensions[] =
16 "Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits";
18 namespace {
20 const int kInflaterChunkSize = 16 * 1024;
22 // Constants for hybi-10 frame format.
24 typedef int OpCode;
26 const OpCode kOpCodeContinuation = 0x0;
27 const OpCode kOpCodeText = 0x1;
28 const OpCode kOpCodeBinary = 0x2;
29 const OpCode kOpCodeClose = 0x8;
30 const OpCode kOpCodePing = 0x9;
31 const OpCode kOpCodePong = 0xA;
33 const unsigned char kFinalBit = 0x80;
34 const unsigned char kReserved1Bit = 0x40;
35 const unsigned char kReserved2Bit = 0x20;
36 const unsigned char kReserved3Bit = 0x10;
37 const unsigned char kOpCodeMask = 0xF;
38 const unsigned char kMaskBit = 0x80;
39 const unsigned char kPayloadLengthMask = 0x7F;
41 const size_t kMaxSingleBytePayloadLength = 125;
42 const size_t kTwoBytePayloadLengthField = 126;
43 const size_t kEightBytePayloadLengthField = 127;
44 const size_t kMaskingKeyWidthInBytes = 4;
46 WebSocket::ParseResult DecodeFrameHybi17(const base::StringPiece& frame,
47 bool client_frame,
48 int* bytes_consumed,
49 std::string* output,
50 bool* compressed) {
51 size_t data_length = frame.length();
52 if (data_length < 2)
53 return WebSocket::FRAME_INCOMPLETE;
55 const char* buffer_begin = const_cast<char*>(frame.data());
56 const char* p = buffer_begin;
57 const char* buffer_end = p + data_length;
59 unsigned char first_byte = *p++;
60 unsigned char second_byte = *p++;
62 bool final = (first_byte & kFinalBit) != 0;
63 bool reserved1 = (first_byte & kReserved1Bit) != 0;
64 bool reserved2 = (first_byte & kReserved2Bit) != 0;
65 bool reserved3 = (first_byte & kReserved3Bit) != 0;
66 int op_code = first_byte & kOpCodeMask;
67 bool masked = (second_byte & kMaskBit) != 0;
68 *compressed = reserved1;
69 if (!final || reserved2 || reserved3)
70 return WebSocket::FRAME_ERROR; // Only compression extension is supported.
72 bool closed = false;
73 switch (op_code) {
74 case kOpCodeClose:
75 closed = true;
76 break;
77 case kOpCodeText:
78 break;
79 case kOpCodeBinary: // We don't support binary frames yet.
80 case kOpCodeContinuation: // We don't support binary frames yet.
81 case kOpCodePing: // We don't support binary frames yet.
82 case kOpCodePong: // We don't support binary frames yet.
83 default:
84 return WebSocket::FRAME_ERROR;
87 if (client_frame && !masked) // In Hybi-17 spec client MUST mask his frame.
88 return WebSocket::FRAME_ERROR;
90 uint64 payload_length64 = second_byte & kPayloadLengthMask;
91 if (payload_length64 > kMaxSingleBytePayloadLength) {
92 int extended_payload_length_size;
93 if (payload_length64 == kTwoBytePayloadLengthField)
94 extended_payload_length_size = 2;
95 else {
96 DCHECK(payload_length64 == kEightBytePayloadLengthField);
97 extended_payload_length_size = 8;
99 if (buffer_end - p < extended_payload_length_size)
100 return WebSocket::FRAME_INCOMPLETE;
101 payload_length64 = 0;
102 for (int i = 0; i < extended_payload_length_size; ++i) {
103 payload_length64 <<= 8;
104 payload_length64 |= static_cast<unsigned char>(*p++);
108 size_t actual_masking_key_length = masked ? kMaskingKeyWidthInBytes : 0;
109 static const uint64 max_payload_length = 0x7FFFFFFFFFFFFFFFull;
110 static size_t max_length = std::numeric_limits<size_t>::max();
111 if (payload_length64 > max_payload_length ||
112 payload_length64 + actual_masking_key_length > max_length) {
113 // WebSocket frame length too large.
114 return WebSocket::FRAME_ERROR;
116 size_t payload_length = static_cast<size_t>(payload_length64);
118 size_t total_length = actual_masking_key_length + payload_length;
119 if (static_cast<size_t>(buffer_end - p) < total_length)
120 return WebSocket::FRAME_INCOMPLETE;
122 if (masked) {
123 output->resize(payload_length);
124 const char* masking_key = p;
125 char* payload = const_cast<char*>(p + kMaskingKeyWidthInBytes);
126 for (size_t i = 0; i < payload_length; ++i) // Unmask the payload.
127 (*output)[i] = payload[i] ^ masking_key[i % kMaskingKeyWidthInBytes];
128 } else {
129 output->assign(p, p + payload_length);
132 size_t pos = p + actual_masking_key_length + payload_length - buffer_begin;
133 *bytes_consumed = pos;
134 return closed ? WebSocket::FRAME_CLOSE : WebSocket::FRAME_OK;
137 void EncodeFrameHybi17(const std::string& message,
138 int masking_key,
139 bool compressed,
140 std::string* output) {
141 std::vector<char> frame;
142 OpCode op_code = kOpCodeText;
143 size_t data_length = message.length();
145 int reserved1 = compressed ? kReserved1Bit : 0;
146 frame.push_back(kFinalBit | op_code | reserved1);
147 char mask_key_bit = masking_key != 0 ? kMaskBit : 0;
148 if (data_length <= kMaxSingleBytePayloadLength)
149 frame.push_back(data_length | mask_key_bit);
150 else if (data_length <= 0xFFFF) {
151 frame.push_back(kTwoBytePayloadLengthField | mask_key_bit);
152 frame.push_back((data_length & 0xFF00) >> 8);
153 frame.push_back(data_length & 0xFF);
154 } else {
155 frame.push_back(kEightBytePayloadLengthField | mask_key_bit);
156 char extended_payload_length[8];
157 size_t remaining = data_length;
158 // Fill the length into extended_payload_length in the network byte order.
159 for (int i = 0; i < 8; ++i) {
160 extended_payload_length[7 - i] = remaining & 0xFF;
161 remaining >>= 8;
163 frame.insert(frame.end(), extended_payload_length,
164 extended_payload_length + 8);
165 DCHECK(!remaining);
168 const char* data = const_cast<char*>(message.data());
169 if (masking_key != 0) {
170 const char* mask_bytes = reinterpret_cast<char*>(&masking_key);
171 frame.insert(frame.end(), mask_bytes, mask_bytes + 4);
172 for (size_t i = 0; i < data_length; ++i) // Mask the payload.
173 frame.push_back(data[i] ^ mask_bytes[i % kMaskingKeyWidthInBytes]);
174 } else {
175 frame.insert(frame.end(), data, data + data_length);
177 *output = std::string(&frame[0], frame.size());
180 } // anonymous namespace
182 // static
183 WebSocketEncoder* WebSocketEncoder::CreateServer(
184 const std::string& request_extensions,
185 std::string* response_extensions) {
186 bool deflate;
187 bool has_client_window_bits;
188 int client_window_bits;
189 int server_window_bits;
190 bool client_no_context_takeover;
191 bool server_no_context_takeover;
192 ParseExtensions(request_extensions, &deflate, &has_client_window_bits,
193 &client_window_bits, &server_window_bits,
194 &client_no_context_takeover, &server_no_context_takeover);
196 if (deflate) {
197 *response_extensions = base::StringPrintf(
198 "permessage-deflate; server_max_window_bits=%d%s", server_window_bits,
199 server_no_context_takeover ? "; server_no_context_takeover" : "");
200 if (has_client_window_bits) {
201 base::StringAppendF(response_extensions, "; client_max_window_bits=%d",
202 client_window_bits);
203 } else {
204 DCHECK_EQ(client_window_bits, 15);
206 return new WebSocketEncoder(true /* is_server */, server_window_bits,
207 client_window_bits, server_no_context_takeover);
208 } else {
209 *response_extensions = std::string();
210 return new WebSocketEncoder(true /* is_server */);
214 // static
215 WebSocketEncoder* WebSocketEncoder::CreateClient(
216 const std::string& response_extensions) {
217 bool deflate;
218 bool has_client_window_bits;
219 int client_window_bits;
220 int server_window_bits;
221 bool client_no_context_takeover;
222 bool server_no_context_takeover;
223 ParseExtensions(response_extensions, &deflate, &has_client_window_bits,
224 &client_window_bits, &server_window_bits,
225 &client_no_context_takeover, &server_no_context_takeover);
227 if (deflate) {
228 return new WebSocketEncoder(false /* is_server */, client_window_bits,
229 server_window_bits, client_no_context_takeover);
230 } else {
231 return new WebSocketEncoder(false /* is_server */);
235 // static
236 void WebSocketEncoder::ParseExtensions(const std::string& header_value,
237 bool* deflate,
238 bool* has_client_window_bits,
239 int* client_window_bits,
240 int* server_window_bits,
241 bool* client_no_context_takeover,
242 bool* server_no_context_takeover) {
243 *deflate = false;
244 *has_client_window_bits = false;
245 *client_window_bits = 15;
246 *server_window_bits = 15;
247 *client_no_context_takeover = false;
248 *server_no_context_takeover = false;
250 if (header_value.empty())
251 return;
253 WebSocketExtensionParser parser;
254 parser.Parse(header_value);
255 if (parser.has_error())
256 return;
257 const std::vector<WebSocketExtension>& extensions = parser.extensions();
258 // TODO(tyoshino): Fail if this method is used for parsing a response and
259 // there are multiple permessage-deflate extensions or there are any unknown
260 // extensions.
261 for (const auto& extension : extensions) {
262 if (extension.name() != "permessage-deflate") {
263 continue;
266 const std::vector<WebSocketExtension::Parameter>& parameters =
267 extension.parameters();
268 for (const auto& param : parameters) {
269 const std::string& name = param.name();
270 // TODO(tyoshino): Fail the connection when an invalid value is given.
271 if (name == "client_max_window_bits") {
272 *has_client_window_bits = true;
273 if (param.HasValue()) {
274 int bits = 0;
275 if (base::StringToInt(param.value(), &bits) && bits >= 8 &&
276 bits <= 15) {
277 *client_window_bits = bits;
281 if (name == "server_max_window_bits" && param.HasValue()) {
282 int bits = 0;
283 if (base::StringToInt(param.value(), &bits) && bits >= 8 && bits <= 15)
284 *server_window_bits = bits;
286 if (name == "client_no_context_takeover")
287 *client_no_context_takeover = true;
288 if (name == "server_no_context_takeover")
289 *server_no_context_takeover = true;
291 *deflate = true;
293 break;
297 WebSocketEncoder::WebSocketEncoder(bool is_server) : is_server_(is_server) {
300 WebSocketEncoder::WebSocketEncoder(bool is_server,
301 int deflate_bits,
302 int inflate_bits,
303 bool no_context_takeover)
304 : is_server_(is_server) {
305 deflater_.reset(new WebSocketDeflater(
306 no_context_takeover ? WebSocketDeflater::DO_NOT_TAKE_OVER_CONTEXT
307 : WebSocketDeflater::TAKE_OVER_CONTEXT));
308 inflater_.reset(
309 new WebSocketInflater(kInflaterChunkSize, kInflaterChunkSize));
311 if (!deflater_->Initialize(deflate_bits) ||
312 !inflater_->Initialize(inflate_bits)) {
313 // Disable deflate support.
314 deflater_.reset();
315 inflater_.reset();
319 WebSocketEncoder::~WebSocketEncoder() {
322 WebSocket::ParseResult WebSocketEncoder::DecodeFrame(
323 const base::StringPiece& frame,
324 int* bytes_consumed,
325 std::string* output) {
326 bool compressed;
327 WebSocket::ParseResult result =
328 DecodeFrameHybi17(frame, is_server_, bytes_consumed, output, &compressed);
329 if (result == WebSocket::FRAME_OK && compressed) {
330 if (!Inflate(output))
331 result = WebSocket::FRAME_ERROR;
333 return result;
336 void WebSocketEncoder::EncodeFrame(const std::string& frame,
337 int masking_key,
338 std::string* output) {
339 std::string compressed;
340 if (Deflate(frame, &compressed))
341 EncodeFrameHybi17(compressed, masking_key, true, output);
342 else
343 EncodeFrameHybi17(frame, masking_key, false, output);
346 bool WebSocketEncoder::Inflate(std::string* message) {
347 if (!inflater_)
348 return false;
349 if (!inflater_->AddBytes(message->data(), message->length()))
350 return false;
351 if (!inflater_->Finish())
352 return false;
354 std::vector<char> output;
355 while (inflater_->CurrentOutputSize() > 0) {
356 scoped_refptr<IOBufferWithSize> chunk =
357 inflater_->GetOutput(inflater_->CurrentOutputSize());
358 if (!chunk.get())
359 return false;
360 output.insert(output.end(), chunk->data(), chunk->data() + chunk->size());
363 *message =
364 output.size() ? std::string(&output[0], output.size()) : std::string();
365 return true;
368 bool WebSocketEncoder::Deflate(const std::string& message,
369 std::string* output) {
370 if (!deflater_)
371 return false;
372 if (!deflater_->AddBytes(message.data(), message.length())) {
373 deflater_->Finish();
374 return false;
376 if (!deflater_->Finish())
377 return false;
378 scoped_refptr<IOBufferWithSize> buffer =
379 deflater_->GetOutput(deflater_->CurrentOutputSize());
380 if (!buffer.get())
381 return false;
382 *output = std::string(buffer->data(), buffer->size());
383 return true;
386 } // namespace net