OLD | NEW |
---|---|
(Empty) | |
1 // Copyright 2013 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. | |
4 | |
5 #include "net/websockets/websocket_basic_stream.h" | |
6 | |
7 #include <algorithm> | |
8 #include <limits> | |
9 #include <string> | |
10 #include <vector> | |
11 | |
12 #include "base/base64.h" | |
13 #include "base/basictypes.h" | |
14 #include "base/bind.h" | |
15 #include "base/rand_util.h" | |
16 #include "base/safe_numerics.h" | |
17 #include "base/sha1.h" | |
18 #include "base/strings/string_util.h" | |
19 #include "base/strings/stringprintf.h" | |
20 #include "googleurl/src/url_canon.h" | |
21 #include "net/base/io_buffer.h" | |
22 #include "net/base/load_flags.h" | |
23 #include "net/http/http_request_headers.h" | |
24 #include "net/http/http_request_info.h" | |
25 #include "net/http/http_response_headers.h" | |
26 #include "net/http/http_stream_parser.h" | |
27 #include "net/http/http_util.h" | |
28 #include "net/socket/client_socket_handle.h" | |
29 #include "net/websockets/websocket_errors.h" | |
30 #include "net/websockets/websocket_frame.h" | |
31 #include "net/websockets/websocket_frame_parser.h" | |
32 | |
33 namespace net { | |
34 | |
35 namespace { | |
36 | |
37 // The number of bytes to attempt to read at a time. | |
38 // TODO(ricea): See if there is a better number. Should it start small, and get | |
39 // bigger if needed? | |
40 const int kReadAtATime = 32 * 1024; | |
41 | |
42 // RFC6455 only requires HTTP/1.1 "or better" but in practice an HTTP version | |
43 // other than 1.1 should not occur in a WebSocket handshake. | |
44 const char kWebSocketUpgradeOkStatusLineStartsWith[] = "HTTP/1.1 101 "; | |
45 | |
46 // The Sec-WebSockey-Key challenge is 16 random bytes, base64 encoded. | |
47 const size_t kRawChallengeLength = 16; | |
48 | |
49 // TODO(ricea): Define all these constants in one central place | |
tyoshino (SeeGerritForStatus)
2013/08/01 04:47:52
yes. you can split this into a cl adding a file co
| |
50 const char kSecWebSocketProtocol[] = "Sec-WebSocket-Protocol"; | |
51 const char kSecWebSocketExtensions[] = "Sec-WebSocket-Extensions"; | |
52 const char kSecWebSocketKey[] = "Sec-WebSocket-Key"; | |
53 const char kSecWebSocketAccept[] = "Sec-WebSocket-Accept"; | |
54 const char kUpgrade[] = "Upgrade"; | |
55 const char kConnection[] = "Connection"; | |
56 const char kWebSocketToken[] = "websocket"; | |
57 const char kWebSocketGuid[] = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; | |
58 | |
59 inline bool CaseInsensitiveLessASCII(char lhs, char rhs) { | |
60 return base::ToLowerASCII(lhs) < base::ToLowerASCII(rhs); | |
61 } | |
62 | |
63 } // namespace | |
64 | |
65 struct WebSocketBasicStream::HandshakeData { | |
66 public: | |
67 HandshakeData() : http_response_info(NULL) {} | |
68 ~HandshakeData() {} | |
69 | |
70 // HTTP implementation, used for the handshake. | |
71 scoped_ptr<HttpStreamParser> http_parser; | |
72 | |
73 // Only used during handshake | |
74 scoped_ptr<HttpRequestInfo> http_request_info; | |
75 | |
76 // Owned by the caller of SendHandshakeRequest. | |
77 HttpResponseInfo* http_response_info; | |
78 | |
79 // The expected value for the Sec-WebSocket-Accept header, extracted from the | |
80 // request headers. | |
81 std::string handshake_response; | |
82 | |
83 // The extensions that were requested. | |
84 std::vector<std::string> requested_extensions; | |
85 | |
86 // The sub-protocols that were requested. | |
87 std::vector<std::string> requested_sub_protocols; | |
88 | |
89 private: | |
90 DISALLOW_COPY_AND_ASSIGN(HandshakeData); | |
91 }; | |
92 | |
93 struct WebSocketBasicStream::ParseRequestHeadersArg { | |
94 std::string key; | |
95 std::vector<std::string>* tokens; | |
96 bool operator<(const ParseRequestHeadersArg& rhs) const; | |
97 }; | |
98 | |
99 WebSocketBasicStream::WebSocketBasicStream( | |
100 scoped_ptr<ClientSocketHandle> connection) | |
101 : read_buffer_(new IOBufferWithSize(kReadAtATime)), | |
102 connection_(connection.Pass()) {} | |
103 | |
104 WebSocketBasicStream::~WebSocketBasicStream() { | |
105 connection_->socket()->Disconnect(); | |
106 } | |
107 | |
108 int WebSocketBasicStream::ReadFrames( | |
109 ScopedVector<WebSocketFrameChunk>* frame_chunks, | |
110 const CompletionCallback& callback) { | |
111 DCHECK(frame_chunks->empty()); | |
112 // If there is data left over after parsing the HTTP headers, attempt to parse | |
113 // it as WebSocket frames. | |
114 if (http_read_buffer_) { | |
115 DCHECK_GE(http_read_buffer_->offset(), 0); | |
116 if (!parser_.Decode(http_read_buffer_->data(), | |
117 http_read_buffer_->offset(), | |
118 frame_chunks)) { | |
119 http_read_buffer_ = NULL; | |
120 return WebSocketErrorToNetError(parser_.websocket_error()); | |
121 } | |
122 http_read_buffer_ = NULL; | |
123 } | |
124 // Loop until we either have at least one chunk to return, or we get | |
125 // ERR_IO_PENDING, or something goes wrong. | |
126 while (frame_chunks->empty()) { | |
127 // This use of base::Unretained() is safe because WebSocketChannel will | |
128 // delete us before deleting frame_chunks. | |
129 int result = | |
130 connection_->socket()->Read(read_buffer_.get(), | |
131 read_buffer_->size(), | |
132 base::Bind(&WebSocketBasicStream::ReadDone, | |
133 base::Unretained(this), | |
134 base::Unretained(frame_chunks), | |
135 callback)); | |
136 if (result > 0) { | |
137 if (!parser_.Decode(read_buffer_->data(), result, frame_chunks)) { | |
138 return WebSocketErrorToNetError(parser_.websocket_error()); | |
139 } | |
140 } else if (result == 0 && frame_chunks->empty()) { | |
141 return ERR_CONNECTION_CLOSED; | |
142 } else { | |
143 return result; | |
144 } | |
145 } | |
146 return OK; | |
147 } | |
148 | |
149 void WebSocketBasicStream::ReadDone( | |
150 ScopedVector<WebSocketFrameChunk>* frame_chunks, | |
151 const CompletionCallback& callback, | |
152 int result) { | |
153 if (result > 0) { | |
154 if (parser_.Decode(read_buffer_->data(), result, frame_chunks)) { | |
155 if (!frame_chunks->empty()) { | |
156 callback.Run(OK); | |
157 } else { | |
158 result = ReadFrames(frame_chunks, callback); | |
159 if (result == ERR_IO_PENDING) { | |
160 // We will be called back again. | |
161 return; | |
162 } | |
163 } | |
164 } else { | |
165 result = WebSocketErrorToNetError(parser_.websocket_error()); | |
166 } | |
167 } | |
168 if (result == 0 && frame_chunks->empty()) { | |
169 result = ERR_CONNECTION_CLOSED; | |
170 } | |
171 DCHECK_NE(ERR_IO_PENDING, result); | |
172 callback.Run(result); | |
173 } | |
174 | |
175 int WebSocketBasicStream::WriteFrames( | |
176 ScopedVector<WebSocketFrameChunk>* frame_chunks, | |
177 const CompletionCallback& callback) { | |
178 // This function always concatenates all frames into a single buffer. | |
179 // TODO(ricea): Investigate whether it would be better in some cases to | |
180 // perform multiple writes with smaller buffers. | |
181 // | |
182 // First calculate the size of the buffer we need to allocate. | |
183 typedef ScopedVector<WebSocketFrameChunk>::const_iterator Iterator; | |
184 int total_size = 0; | |
185 for (Iterator it = frame_chunks->begin(); it != frame_chunks->end(); ++it) { | |
186 WebSocketFrameChunk* chunk = *it; | |
187 DCHECK(chunk->header && chunk->final_chunk) | |
188 << "Only complete frames are supported by WebSocketBasicStream"; | |
189 // Force the masked bit on. | |
190 chunk->header->masked = true; | |
191 // We enforce flow control so the renderer should never be able to force us | |
192 // to cache anywhere near 2GB of frames. | |
193 int chunk_size = | |
194 chunk->data->size() + GetWebSocketFrameHeaderSize(*(chunk->header)); | |
195 CHECK_GE(std::numeric_limits<int>::max() - total_size, chunk_size) | |
196 << "Aborting to prevent overflow"; | |
197 total_size += chunk_size; | |
198 } | |
199 scoped_refptr<IOBufferWithSize> total(new IOBufferWithSize(total_size)); | |
200 char* data = total->data(); | |
201 int remaining_size = total_size; | |
202 for (Iterator it = frame_chunks->begin(); it != frame_chunks->end(); ++it) { | |
203 WebSocketFrameChunk* chunk = *it; | |
204 WebSocketMaskingKey mask = GenerateWebSocketMaskingKey(); | |
205 int result = WriteWebSocketFrameHeader( | |
206 *(chunk->header), &mask, data, remaining_size); | |
207 DCHECK(result != ERR_INVALID_ARGUMENT) | |
208 << "WriteWebSocketFrameHeader() says that " << remaining_size | |
209 << " is not enough to write the header in. This should not happen."; | |
210 CHECK_GE(result, 0) << "Potentially security-critical check failed"; | |
211 data += result; | |
212 remaining_size -= result; | |
213 const char* const frame_data = chunk->data->data(); | |
214 const int frame_size = chunk->data->size(); | |
215 CHECK_GE(remaining_size, frame_size); | |
216 std::copy(frame_data, frame_data + frame_size, data); | |
217 MaskWebSocketFramePayload(mask, 0, data, frame_size); | |
218 data += frame_size; | |
219 remaining_size -= frame_size; | |
220 } | |
221 DCHECK_EQ(0, remaining_size) << "Buffer size calculation was wrong; " | |
222 << remaining_size << " bytes left over."; | |
223 scoped_refptr<DrainableIOBuffer> drainable_buffer( | |
224 new DrainableIOBuffer(total, total_size)); | |
225 return WriteEverything(drainable_buffer, callback); | |
226 } | |
227 | |
228 int WebSocketBasicStream::WriteEverything( | |
229 const scoped_refptr<DrainableIOBuffer>& buffer, | |
230 const CompletionCallback& callback) { | |
231 while (buffer->BytesRemaining() > 0) { | |
232 // The use of base::Unretained() here is safe because on destruction we | |
233 // disconnect the socket, preventing any further callbacks. | |
234 int result = connection_->socket() | |
235 ->Write(buffer.get(), | |
236 buffer->BytesRemaining(), | |
237 base::Bind(&WebSocketBasicStream::WriteDone, | |
238 base::Unretained(this), | |
239 buffer, | |
240 callback)); | |
241 if (result > 0) { | |
242 buffer->DidConsume(result); | |
243 } else { | |
244 return result; | |
245 } | |
246 } | |
247 return OK; | |
248 } | |
249 | |
250 void WebSocketBasicStream::WriteDone( | |
251 const scoped_refptr<DrainableIOBuffer>& buffer, | |
252 const CompletionCallback& callback, | |
253 int result) { | |
254 if (result > 0) { | |
255 buffer->DidConsume(result); | |
256 if (buffer->BytesRemaining() > 0) { | |
257 int result = WriteEverything(buffer, callback); | |
258 if (result != ERR_IO_PENDING) { | |
259 callback.Run(result); | |
260 } | |
261 } | |
262 } | |
263 } | |
264 | |
265 void WebSocketBasicStream::Close() { connection_->socket()->Disconnect(); } | |
266 | |
267 std::string WebSocketBasicStream::GetSubProtocol() const { | |
268 return sub_protocol_; | |
269 } | |
270 | |
271 std::string WebSocketBasicStream::GetExtensions() const { return extensions_; } | |
272 | |
273 std::string GenerateHandshakeChallenge() { | |
274 std::string raw_challenge = base::RandBytesAsString(kRawChallengeLength); | |
275 std::string encoded_challenge; | |
276 bool encode_success = base::Base64Encode(raw_challenge, &encoded_challenge); | |
277 DCHECK(encode_success); | |
278 return encoded_challenge; | |
279 } | |
280 | |
281 // TODO(ricea): Factor this and the implementation in | |
282 // websocket_handshake_handler.cc (and maybe the one in net/server as well) out | |
283 // into a single utility class. | |
284 std::string GenerateHandshakeResponse(std::string challenge) { | |
285 challenge += kWebSocketGuid; | |
286 std::string hash = base::SHA1HashString(challenge); | |
287 std::string websocket_accept; | |
288 bool encode_success = base::Base64Encode(hash, &websocket_accept); | |
289 DCHECK(encode_success); | |
290 return websocket_accept; | |
291 } | |
292 | |
293 int WebSocketBasicStream::SendHandshakeRequest( | |
294 const GURL& url, | |
295 const HttpRequestHeaders& headers, | |
296 HttpResponseInfo* response_info, | |
297 const CompletionCallback& callback) { | |
298 DCHECK(!headers.HasHeader(kSecWebSocketKey)) | |
299 << "The caller of SendHandshakeRequest included a Sec-WebSocket-Key " | |
300 << "header. They are not supposed to do that."; | |
301 http_read_buffer_ = new GrowableIOBuffer; | |
302 scoped_ptr<HttpRequestInfo> info(new HttpRequestInfo); | |
303 info->url = url; | |
304 // TODO(ricea): WTF does using_proxy come from? | |
305 bool using_proxy = false; | |
306 // TODO(ricea): See comment below. | |
307 info->method = using_proxy ? "CONNECT" : HttpRequestHeaders::kGetMethod; | |
308 // TODO(ricea): Double-check these flags | |
309 info->load_flags = LOAD_VERIFY_EV_CERT | LOAD_DISABLE_CACHE; | |
310 info->motivation = HttpRequestInfo::NORMAL_MOTIVATION; | |
311 bool enable_privacy_mode = true; | |
312 // TODO(ricea): Somehow make this work | |
313 // if (context_ && context_->network_delegate()) { | |
314 // enable_privacy_mode = | |
315 // context_->network_delegate()->CanEnablePrivacyMode(url_, url_); | |
316 // } | |
317 info->privacy_mode = | |
318 enable_privacy_mode ? kPrivacyModeEnabled : kPrivacyModeDisabled; | |
319 handshake_data_->http_request_info = info.Pass(); | |
320 ParseRequestHeadersArg args[] = { | |
321 {kSecWebSocketProtocol, &(handshake_data_->requested_sub_protocols)}, | |
322 {kSecWebSocketExtensions, &(handshake_data_->requested_extensions)}, | |
323 }; | |
324 ParseRequestHeaders(headers, args, arraysize(args)); | |
325 | |
326 // TODO(ricea): Where is this supposed to come from? | |
327 BoundNetLog net_log; | |
328 | |
329 handshake_data_->http_parser | |
330 .reset(new HttpStreamParser(connection_.get(), | |
331 handshake_data_->http_request_info.get(), | |
332 http_read_buffer_.get(), | |
333 net_log)); | |
334 // Create a new URL which is identical except that the scheme is changed from | |
335 // ws: or wss: to http: or https:. For some reason this takes 6 lines of | |
336 // code. This is literally one of the most insane APIs I have ever used. | |
337 std::string new_scheme = url.SchemeIsSecure() ? "https" : "http"; | |
338 url_canon::Replacements<char> replacements; | |
339 url_parse::Component comp; | |
340 comp.len = base::checked_numeric_cast<int>(new_scheme.length()); | |
341 replacements.SetScheme(new_scheme.c_str(), comp); | |
342 GURL httpified_url = url.ReplaceComponents(replacements); | |
343 // TODO(ricea): The proxy case. In this case we need to send two sets of | |
344 // headers, eg. | |
345 // | |
346 // CONNECT www.google.com:80 HTTP/1.1 | |
347 // Host: www.google.com:80 | |
348 // Proxy-Authorization: basic aGVsbG86d29ybGQ | |
349 // | |
350 // GET /ws_endpoint?type=text HTTP/1.1 | |
351 // Host: www.google.com:80 | |
352 // Cookie: ... | |
353 // | |
354 // Or maybe we won't be called until the proxy tunnel has already been | |
355 // established and we just send headers as normal. | |
356 const std::string path = HttpUtil::PathForRequest(httpified_url); | |
357 std::string request_line = | |
358 base::StringPrintf("%s %s HTTP/1.1\r\n", | |
359 handshake_data_->http_request_info->method.c_str(), | |
360 path.c_str()); | |
361 handshake_data_->http_response_info = response_info; | |
362 | |
363 // Create a new header object, so that we can add the Sec-WebSockey-Key | |
364 // header. | |
365 HttpRequestHeaders enriched_headers; | |
366 enriched_headers.CopyFrom(headers); | |
367 std::string handshake_challenge = GenerateHandshakeChallenge(); | |
368 enriched_headers.SetHeader(kSecWebSocketKey, handshake_challenge); | |
369 handshake_data_->handshake_response = | |
370 GenerateHandshakeResponse(handshake_challenge); | |
371 return handshake_data_->http_parser | |
372 ->SendRequest(request_line, headers, response_info, callback); | |
373 } | |
374 | |
375 int WebSocketBasicStream::ReadHandshakeResponse( | |
376 const CompletionCallback& callback) { | |
377 // TODO(ricea): Find a justification for this use of base::Unretained. | |
378 int result = handshake_data_->http_parser->ReadResponseHeaders(base::Bind( | |
379 &WebSocketBasicStream::HandshakeDone, base::Unretained(this), callback)); | |
380 if (result == OK) { | |
381 result = ProcessHandshake(); | |
382 } | |
383 return result; | |
384 } | |
385 | |
386 bool WebSocketBasicStream::ParseRequestHeadersArg::operator<( | |
387 const ParseRequestHeadersArg& rhs) const { | |
388 return std::lexicographical_compare(key.begin(), | |
389 key.end(), | |
390 rhs.key.begin(), | |
391 rhs.key.end(), | |
392 CaseInsensitiveLessASCII); | |
393 } | |
394 | |
395 void WebSocketBasicStream::ParseRequestHeaders( | |
396 const HttpRequestHeaders& headers, | |
397 ParseRequestHeadersArg args[], | |
398 size_t count) { | |
399 ParseRequestHeadersArg* begin = args; | |
400 ParseRequestHeadersArg* end = args + count; | |
401 std::sort(begin, end); // Sort so we can do binary search. | |
402 HttpRequestHeaders::Iterator it(headers); | |
403 while (it.GetNext()) { | |
404 ParseRequestHeadersArg needle = {std::string(it.name()), NULL}; | |
405 ParseRequestHeadersArg* answer = std::lower_bound(begin, end, needle); | |
406 if (answer != end) { | |
407 DCHECK(!HttpUtil::IsNonCoalescingHeader(it.name())); | |
408 const std::string& value = it.value(); | |
409 HttpUtil::ValuesIterator value_it(value.begin(), value.end(), ','); | |
410 while (value_it.GetNext()) { | |
411 answer->tokens->push_back(value_it.value()); | |
412 } | |
413 } | |
414 } | |
415 } | |
416 | |
417 void WebSocketBasicStream::HandshakeDone(const CompletionCallback& callback, | |
418 int result) { | |
419 if (result == OK) { | |
420 result = ProcessHandshake(); | |
421 } | |
422 callback.Run(result); | |
423 } | |
424 | |
425 bool WebSocketBasicStream::ValidateSingleTokenHeader( | |
426 const scoped_refptr<HttpResponseHeaders>& headers, | |
427 const base::StringPiece& name, | |
428 const std::string& value) { | |
429 void* state = NULL; | |
430 std::string token; | |
431 int tokens = 0; | |
432 bool has_value = false; | |
433 while (headers->EnumerateHeader(&state, name, &token)) { | |
434 if (++tokens > 1) { | |
435 return false; | |
436 } | |
437 has_value = LowerCaseEqualsASCII(value, token.c_str()); | |
438 } | |
439 return has_value; | |
440 } | |
441 | |
442 bool WebSocketBasicStream::ValidateUpgradeResponseHeader( | |
443 const scoped_refptr<HttpResponseHeaders>& headers) { | |
444 return ValidateSingleTokenHeader(headers, kUpgrade, kWebSocketToken); | |
445 } | |
446 | |
447 bool WebSocketBasicStream::ValidateSecWebSocketAcceptResponseHeader( | |
448 const scoped_refptr<HttpResponseHeaders>& headers) { | |
449 return ValidateSingleTokenHeader( | |
450 headers, kSecWebSocketAccept, handshake_data_->handshake_response); | |
451 } | |
452 | |
453 int WebSocketBasicStream::ProcessHandshake() { | |
tyoshino (SeeGerritForStatus)
2013/08/01 04:47:52
consider splitting handshake processing code or st
| |
454 DCHECK(handshake_data_); | |
455 DCHECK(handshake_data_->http_request_info); | |
456 DCHECK(handshake_data_->http_response_info); | |
457 DCHECK(handshake_data_->http_response_info->headers); | |
458 const scoped_refptr<HttpResponseHeaders>& headers = | |
459 handshake_data_->http_response_info->headers; | |
460 if (!StartsWithASCII(headers->GetStatusLine(), | |
461 kWebSocketUpgradeOkStatusLineStartsWith, | |
462 true)) { | |
463 // TODO(ricea): Would a more specific error be better? | |
464 return ERR_INVALID_RESPONSE; | |
465 } | |
466 // There must be an exact case-insensitive match for "Upgrade: websocket" | |
467 // Look at the tokenised Upgrade: header, ensure it has exactly one token and | |
468 // that token is "websocket" | |
469 if (!ValidateUpgradeResponseHeader(headers)) { | |
470 return ERR_INVALID_RESPONSE; | |
471 } | |
472 // The Connection header field must contain a an "upgrade" token. | |
473 if (!headers->HasHeaderValue(HttpRequestHeaders::kConnection, kUpgrade)) { | |
474 return ERR_INVALID_RESPONSE; | |
475 } | |
476 // Sec-WebSocket-Accept contains the correct challenge response. | |
477 if (!ValidateSecWebSocketAcceptResponseHeader(headers)) { | |
478 return ERR_INVALID_RESPONSE; | |
479 } | |
480 | |
481 handshake_data_.reset(); | |
482 if (http_read_buffer_->offset() == 0) { | |
483 http_read_buffer_ = NULL; | |
484 } | |
485 return OK; | |
486 } | |
487 | |
488 } // namespace net | |
OLD | NEW |