Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(224)

Side by Side Diff: net/server/web_socket.cc

Issue 812543002: Update from https://crrev.com/308331 (Closed) Base URL: git@github.com:domokit/mojo.git@master
Patch Set: Created 6 years ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « net/server/web_socket.h ('k') | net/server/web_socket_encoder.h » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "net/server/web_socket.h" 5 #include "net/server/web_socket.h"
6 6
7 #include <limits>
8
9 #include "base/base64.h" 7 #include "base/base64.h"
10 #include "base/rand_util.h"
11 #include "base/logging.h" 8 #include "base/logging.h"
12 #include "base/md5.h" 9 #include "base/md5.h"
13 #include "base/sha1.h" 10 #include "base/sha1.h"
14 #include "base/strings/string_number_conversions.h" 11 #include "base/strings/string_number_conversions.h"
15 #include "base/strings/stringprintf.h" 12 #include "base/strings/stringprintf.h"
16 #include "base/sys_byteorder.h" 13 #include "base/sys_byteorder.h"
17 #include "net/server/http_connection.h" 14 #include "net/server/http_connection.h"
18 #include "net/server/http_server.h" 15 #include "net/server/http_server.h"
19 #include "net/server/http_server_request_info.h" 16 #include "net/server/http_server_request_info.h"
20 #include "net/server/http_server_response_info.h" 17 #include "net/server/http_server_response_info.h"
18 #include "net/server/web_socket_encoder.h"
21 19
22 namespace net { 20 namespace net {
23 21
24 namespace { 22 namespace {
25 23
26 static uint32 WebSocketKeyFingerprint(const std::string& str) { 24 static uint32 WebSocketKeyFingerprint(const std::string& str) {
27 std::string result; 25 std::string result;
28 const char* p_char = str.c_str(); 26 const char* p_char = str.c_str();
29 int length = str.length(); 27 int length = str.length();
30 int spaces = 0; 28 int spaces = 0;
(...skipping 114 matching lines...) Expand 10 before | Expand all | Expand 10 after
145 *pos += kWebSocketHandshakeBodyLen; 143 *pos += kWebSocketHandshakeBodyLen;
146 } 144 }
147 145
148 std::string key3_; 146 std::string key3_;
149 147
150 DISALLOW_COPY_AND_ASSIGN(WebSocketHixie76); 148 DISALLOW_COPY_AND_ASSIGN(WebSocketHixie76);
151 }; 149 };
152 150
153 const int WebSocketHixie76::kWebSocketHandshakeBodyLen = 8; 151 const int WebSocketHixie76::kWebSocketHandshakeBodyLen = 8;
154 152
155
156 // Constants for hybi-10 frame format.
157
158 typedef int OpCode;
159
160 const OpCode kOpCodeContinuation = 0x0;
161 const OpCode kOpCodeText = 0x1;
162 const OpCode kOpCodeBinary = 0x2;
163 const OpCode kOpCodeClose = 0x8;
164 const OpCode kOpCodePing = 0x9;
165 const OpCode kOpCodePong = 0xA;
166
167 const unsigned char kFinalBit = 0x80;
168 const unsigned char kReserved1Bit = 0x40;
169 const unsigned char kReserved2Bit = 0x20;
170 const unsigned char kReserved3Bit = 0x10;
171 const unsigned char kOpCodeMask = 0xF;
172 const unsigned char kMaskBit = 0x80;
173 const unsigned char kPayloadLengthMask = 0x7F;
174
175 const size_t kMaxSingleBytePayloadLength = 125;
176 const size_t kTwoBytePayloadLengthField = 126;
177 const size_t kEightBytePayloadLengthField = 127;
178 const size_t kMaskingKeyWidthInBytes = 4;
179
180 class WebSocketHybi17 : public WebSocket { 153 class WebSocketHybi17 : public WebSocket {
181 public: 154 public:
182 static WebSocket* Create(HttpServer* server, 155 static WebSocket* Create(HttpServer* server,
183 HttpConnection* connection, 156 HttpConnection* connection,
184 const HttpServerRequestInfo& request, 157 const HttpServerRequestInfo& request,
185 size_t* pos) { 158 size_t* pos) {
186 std::string version = request.GetHeaderValue("sec-websocket-version"); 159 std::string version = request.GetHeaderValue("sec-websocket-version");
187 if (version != "8" && version != "13") 160 if (version != "8" && version != "13")
188 return NULL; 161 return NULL;
189 162
(...skipping 10 matching lines...) Expand all
200 } 173 }
201 174
202 void Accept(const HttpServerRequestInfo& request) override { 175 void Accept(const HttpServerRequestInfo& request) override {
203 static const char* const kWebSocketGuid = 176 static const char* const kWebSocketGuid =
204 "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; 177 "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
205 std::string key = request.GetHeaderValue("sec-websocket-key"); 178 std::string key = request.GetHeaderValue("sec-websocket-key");
206 std::string data = base::StringPrintf("%s%s", key.c_str(), kWebSocketGuid); 179 std::string data = base::StringPrintf("%s%s", key.c_str(), kWebSocketGuid);
207 std::string encoded_hash; 180 std::string encoded_hash;
208 base::Base64Encode(base::SHA1HashString(data), &encoded_hash); 181 base::Base64Encode(base::SHA1HashString(data), &encoded_hash);
209 182
210 server_->SendRaw( 183 server_->SendRaw(connection_->id(),
211 connection_->id(), 184 base::StringPrintf(
212 base::StringPrintf("HTTP/1.1 101 WebSocket Protocol Handshake\r\n" 185 "HTTP/1.1 101 WebSocket Protocol Handshake\r\n"
213 "Upgrade: WebSocket\r\n" 186 "Upgrade: WebSocket\r\n"
214 "Connection: Upgrade\r\n" 187 "Connection: Upgrade\r\n"
215 "Sec-WebSocket-Accept: %s\r\n" 188 "Sec-WebSocket-Accept: %s\r\n"
216 "\r\n", 189 "%s"
217 encoded_hash.c_str())); 190 "\r\n",
191 encoded_hash.c_str(), response_extensions_.c_str()));
218 } 192 }
219 193
220 ParseResult Read(std::string* message) override { 194 ParseResult Read(std::string* message) override {
221 HttpConnection::ReadIOBuffer* read_buf = connection_->read_buf(); 195 HttpConnection::ReadIOBuffer* read_buf = connection_->read_buf();
222 base::StringPiece frame(read_buf->StartOfBuffer(), read_buf->GetSize()); 196 base::StringPiece frame(read_buf->StartOfBuffer(), read_buf->GetSize());
223 int bytes_consumed = 0; 197 int bytes_consumed = 0;
224 ParseResult result = 198 ParseResult result = encoder_->DecodeFrame(frame, &bytes_consumed, message);
225 WebSocket::DecodeFrameHybi17(frame, true, &bytes_consumed, message);
226 if (result == FRAME_OK) 199 if (result == FRAME_OK)
227 read_buf->DidConsume(bytes_consumed); 200 read_buf->DidConsume(bytes_consumed);
228 if (result == FRAME_CLOSE) 201 if (result == FRAME_CLOSE)
229 closed_ = true; 202 closed_ = true;
230 return result; 203 return result;
231 } 204 }
232 205
233 void Send(const std::string& message) override { 206 void Send(const std::string& message) override {
234 if (closed_) 207 if (closed_)
235 return; 208 return;
236 server_->SendRaw(connection_->id(), 209 std::string encoded;
237 WebSocket::EncodeFrameHybi17(message, 0)); 210 encoder_->EncodeFrame(message, 0, &encoded);
211 server_->SendRaw(connection_->id(), encoded);
238 } 212 }
239 213
240 private: 214 private:
241 WebSocketHybi17(HttpServer* server, 215 WebSocketHybi17(HttpServer* server,
242 HttpConnection* connection, 216 HttpConnection* connection,
243 const HttpServerRequestInfo& request, 217 const HttpServerRequestInfo& request,
244 size_t* pos) 218 size_t* pos)
245 : WebSocket(server, connection), 219 : WebSocket(server, connection),
246 op_code_(0),
247 final_(false),
248 reserved1_(false),
249 reserved2_(false),
250 reserved3_(false),
251 masked_(false),
252 payload_(0),
253 payload_length_(0),
254 frame_end_(0),
255 closed_(false) { 220 closed_(false) {
221 std::string request_extensions =
222 request.GetHeaderValue("sec-websocket-extensions");
223 encoder_.reset(WebSocketEncoder::CreateServer(request_extensions,
224 &response_extensions_));
225 if (!response_extensions_.empty()) {
226 response_extensions_ =
227 "Sec-WebSocket-Extensions: " + response_extensions_ + "\r\n";
228 }
256 } 229 }
257 230
258 OpCode op_code_; 231 scoped_ptr<WebSocketEncoder> encoder_;
259 bool final_; 232 std::string response_extensions_;
260 bool reserved1_;
261 bool reserved2_;
262 bool reserved3_;
263 bool masked_;
264 const char* payload_;
265 size_t payload_length_;
266 const char* frame_end_;
267 bool closed_; 233 bool closed_;
268 234
269 DISALLOW_COPY_AND_ASSIGN(WebSocketHybi17); 235 DISALLOW_COPY_AND_ASSIGN(WebSocketHybi17);
270 }; 236 };
271 237
272 } // anonymous namespace 238 } // anonymous namespace
273 239
274 WebSocket* WebSocket::CreateWebSocket(HttpServer* server, 240 WebSocket* WebSocket::CreateWebSocket(HttpServer* server,
275 HttpConnection* connection, 241 HttpConnection* connection,
276 const HttpServerRequestInfo& request, 242 const HttpServerRequestInfo& request,
277 size_t* pos) { 243 size_t* pos) {
278 WebSocket* socket = WebSocketHybi17::Create(server, connection, request, pos); 244 WebSocket* socket = WebSocketHybi17::Create(server, connection, request, pos);
279 if (socket) 245 if (socket)
280 return socket; 246 return socket;
281 247
282 return WebSocketHixie76::Create(server, connection, request, pos); 248 return WebSocketHixie76::Create(server, connection, request, pos);
283 } 249 }
284 250
285 // static
286 WebSocket::ParseResult WebSocket::DecodeFrameHybi17(
287 const base::StringPiece& frame,
288 bool client_frame,
289 int* bytes_consumed,
290 std::string* output) {
291 size_t data_length = frame.length();
292 if (data_length < 2)
293 return FRAME_INCOMPLETE;
294
295 const char* buffer_begin = const_cast<char*>(frame.data());
296 const char* p = buffer_begin;
297 const char* buffer_end = p + data_length;
298
299 unsigned char first_byte = *p++;
300 unsigned char second_byte = *p++;
301
302 bool final = (first_byte & kFinalBit) != 0;
303 bool reserved1 = (first_byte & kReserved1Bit) != 0;
304 bool reserved2 = (first_byte & kReserved2Bit) != 0;
305 bool reserved3 = (first_byte & kReserved3Bit) != 0;
306 int op_code = first_byte & kOpCodeMask;
307 bool masked = (second_byte & kMaskBit) != 0;
308 if (!final || reserved1 || reserved2 || reserved3)
309 return FRAME_ERROR; // Extensions and not supported.
310
311 bool closed = false;
312 switch (op_code) {
313 case kOpCodeClose:
314 closed = true;
315 break;
316 case kOpCodeText:
317 break;
318 case kOpCodeBinary: // We don't support binary frames yet.
319 case kOpCodeContinuation: // We don't support binary frames yet.
320 case kOpCodePing: // We don't support binary frames yet.
321 case kOpCodePong: // We don't support binary frames yet.
322 default:
323 return FRAME_ERROR;
324 }
325
326 if (client_frame && !masked) // In Hybi-17 spec client MUST mask his frame.
327 return FRAME_ERROR;
328
329 uint64 payload_length64 = second_byte & kPayloadLengthMask;
330 if (payload_length64 > kMaxSingleBytePayloadLength) {
331 int extended_payload_length_size;
332 if (payload_length64 == kTwoBytePayloadLengthField)
333 extended_payload_length_size = 2;
334 else {
335 DCHECK(payload_length64 == kEightBytePayloadLengthField);
336 extended_payload_length_size = 8;
337 }
338 if (buffer_end - p < extended_payload_length_size)
339 return FRAME_INCOMPLETE;
340 payload_length64 = 0;
341 for (int i = 0; i < extended_payload_length_size; ++i) {
342 payload_length64 <<= 8;
343 payload_length64 |= static_cast<unsigned char>(*p++);
344 }
345 }
346
347 size_t actual_masking_key_length = masked ? kMaskingKeyWidthInBytes : 0;
348 static const uint64 max_payload_length = 0x7FFFFFFFFFFFFFFFull;
349 static size_t max_length = std::numeric_limits<size_t>::max();
350 if (payload_length64 > max_payload_length ||
351 payload_length64 + actual_masking_key_length > max_length) {
352 // WebSocket frame length too large.
353 return FRAME_ERROR;
354 }
355 size_t payload_length = static_cast<size_t>(payload_length64);
356
357 size_t total_length = actual_masking_key_length + payload_length;
358 if (static_cast<size_t>(buffer_end - p) < total_length)
359 return FRAME_INCOMPLETE;
360
361 if (masked) {
362 output->resize(payload_length);
363 const char* masking_key = p;
364 char* payload = const_cast<char*>(p + kMaskingKeyWidthInBytes);
365 for (size_t i = 0; i < payload_length; ++i) // Unmask the payload.
366 (*output)[i] = payload[i] ^ masking_key[i % kMaskingKeyWidthInBytes];
367 } else {
368 output->assign(p, p + payload_length);
369 }
370
371 size_t pos = p + actual_masking_key_length + payload_length - buffer_begin;
372 *bytes_consumed = pos;
373 return closed ? FRAME_CLOSE : FRAME_OK;
374 }
375
376 // static
377 std::string WebSocket::EncodeFrameHybi17(const std::string& message,
378 int masking_key) {
379 std::vector<char> frame;
380 OpCode op_code = kOpCodeText;
381 size_t data_length = message.length();
382
383 frame.push_back(kFinalBit | op_code);
384 char mask_key_bit = masking_key != 0 ? kMaskBit : 0;
385 if (data_length <= kMaxSingleBytePayloadLength)
386 frame.push_back(data_length | mask_key_bit);
387 else if (data_length <= 0xFFFF) {
388 frame.push_back(kTwoBytePayloadLengthField | mask_key_bit);
389 frame.push_back((data_length & 0xFF00) >> 8);
390 frame.push_back(data_length & 0xFF);
391 } else {
392 frame.push_back(kEightBytePayloadLengthField | mask_key_bit);
393 char extended_payload_length[8];
394 size_t remaining = data_length;
395 // Fill the length into extended_payload_length in the network byte order.
396 for (int i = 0; i < 8; ++i) {
397 extended_payload_length[7 - i] = remaining & 0xFF;
398 remaining >>= 8;
399 }
400 frame.insert(frame.end(),
401 extended_payload_length,
402 extended_payload_length + 8);
403 DCHECK(!remaining);
404 }
405
406 const char* data = const_cast<char*>(message.data());
407 if (masking_key != 0) {
408 const char* mask_bytes = reinterpret_cast<char*>(&masking_key);
409 frame.insert(frame.end(), mask_bytes, mask_bytes + 4);
410 for (size_t i = 0; i < data_length; ++i) // Mask the payload.
411 frame.push_back(data[i] ^ mask_bytes[i % kMaskingKeyWidthInBytes]);
412 } else {
413 frame.insert(frame.end(), data, data + data_length);
414 }
415 return std::string(&frame[0], frame.size());
416 }
417
418 WebSocket::WebSocket(HttpServer* server, HttpConnection* connection) 251 WebSocket::WebSocket(HttpServer* server, HttpConnection* connection)
419 : server_(server), 252 : server_(server),
420 connection_(connection) { 253 connection_(connection) {
421 } 254 }
422 255
256 WebSocket::~WebSocket() {
257 }
258
423 } // namespace net 259 } // namespace net
OLDNEW
« no previous file with comments | « net/server/web_socket.h ('k') | net/server/web_socket_encoder.h » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698