2
* Copyright (C) 2011 Google Inc. All rights reserved.
3
* Copyright (C) Research In Motion Limited 2011. All rights reserved.
5
* Redistribution and use in source and binary forms, with or without
6
* modification, are permitted provided that the following conditions are
9
* * Redistributions of source code must retain the above copyright
10
* notice, this list of conditions and the following disclaimer.
11
* * Redistributions in binary form must reproduce the above
12
* copyright notice, this list of conditions and the following disclaimer
13
* in the documentation and/or other materials provided with the
15
* * Neither the name of Google Inc. nor the names of its
16
* contributors may be used to endorse or promote products derived from
17
* this software without specific prior written permission.
19
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34
#if ENABLE(WEB_SOCKETS)
36
#include "WebSocketHandshake.h"
37
#include "WebSocket.h"
40
#include "CookieJar.h"
42
#include "HTTPHeaderMap.h"
43
#include "HTTPParsers.h"
46
#include "ScriptCallStack.h"
47
#include "ScriptExecutionContext.h"
48
#include "SecurityOrigin.h"
49
#include <wtf/CryptographicallyRandomNumber.h>
52
#include <wtf/StdLibExtras.h>
53
#include <wtf/StringExtras.h>
54
#include <wtf/Vector.h>
55
#include <wtf/text/Base64.h>
56
#include <wtf/text/CString.h>
57
#include <wtf/text/StringBuilder.h>
58
#include <wtf/text/WTFString.h>
59
#include <wtf/unicode/CharacterNames.h>
63
static const char randomCharacterInSecWebSocketKey[] = "!\"#$%&'()*+,-./:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
65
static String resourceName(const KURL& url)
68
name.append(url.path());
71
if (!url.query().isNull()) {
73
name.append(url.query());
75
String result = name.toString();
76
ASSERT(!result.isEmpty());
77
ASSERT(!result.contains(' '));
81
static String hostName(const KURL& url, bool secure)
83
ASSERT(url.protocolIs("wss") == secure);
84
StringBuilder builder;
85
builder.append(url.host().lower());
86
if (url.port() && ((!secure && url.port() != 80) || (secure && url.port() != 443))) {
88
builder.appendNumber(url.port());
90
return builder.toString();
93
static const size_t maxInputSampleSize = 128;
94
static String trimInputSample(const char* p, size_t len)
96
String s = String(p, std::min<size_t>(len, maxInputSampleSize));
97
if (len > maxInputSampleSize)
98
s.append(horizontalEllipsis);
102
static String generateSecWebSocketKey()
104
static const size_t nonceSize = 16;
105
unsigned char key[nonceSize];
106
cryptographicallyRandomValues(key, nonceSize);
107
return base64Encode(reinterpret_cast<char*>(key), nonceSize);
110
String WebSocketHandshake::getExpectedWebSocketAccept(const String& secWebSocketKey)
112
static const char* const webSocketKeyGUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
113
static const size_t sha1HashSize = 20; // FIXME: This should be defined in SHA1.h.
115
CString keyData = secWebSocketKey.ascii();
116
sha1.addBytes(reinterpret_cast<const uint8_t*>(keyData.data()), keyData.length());
117
sha1.addBytes(reinterpret_cast<const uint8_t*>(webSocketKeyGUID), strlen(webSocketKeyGUID));
118
Vector<uint8_t, sha1HashSize> hash;
119
sha1.computeHash(hash);
120
return base64Encode(reinterpret_cast<const char*>(hash.data()), sha1HashSize);
123
WebSocketHandshake::WebSocketHandshake(const KURL& url, const String& protocol, ScriptExecutionContext* context)
125
, m_clientProtocol(protocol)
126
, m_secure(m_url.protocolIs("wss"))
130
m_secWebSocketKey = generateSecWebSocketKey();
131
m_expectedAccept = getExpectedWebSocketAccept(m_secWebSocketKey);
134
WebSocketHandshake::~WebSocketHandshake()
138
const KURL& WebSocketHandshake::url() const
143
void WebSocketHandshake::setURL(const KURL& url)
148
const String WebSocketHandshake::host() const
150
return m_url.host().lower();
153
const String& WebSocketHandshake::clientProtocol() const
155
return m_clientProtocol;
158
void WebSocketHandshake::setClientProtocol(const String& protocol)
160
m_clientProtocol = protocol;
163
bool WebSocketHandshake::secure() const
168
String WebSocketHandshake::clientOrigin() const
170
return m_context->securityOrigin()->toString();
173
String WebSocketHandshake::clientLocation() const
175
StringBuilder builder;
176
builder.append(m_secure ? "wss" : "ws");
177
builder.append("://");
178
builder.append(hostName(m_url, m_secure));
179
builder.append(resourceName(m_url));
180
return builder.toString();
183
CString WebSocketHandshake::clientHandshakeMessage() const
185
// Keep the following consistent with clientHandshakeRequest().
186
StringBuilder builder;
188
builder.append("GET ");
189
builder.append(resourceName(m_url));
190
builder.append(" HTTP/1.1\r\n");
192
Vector<String> fields;
193
fields.append("Upgrade: websocket");
194
fields.append("Connection: Upgrade");
195
fields.append("Host: " + hostName(m_url, m_secure));
196
fields.append("Origin: " + clientOrigin());
197
if (!m_clientProtocol.isEmpty())
198
fields.append("Sec-WebSocket-Protocol: " + m_clientProtocol);
200
KURL url = httpURLForAuthenticationAndCookies();
201
if (m_context->isDocument()) {
202
Document* document = static_cast<Document*>(m_context);
203
String cookie = cookieRequestHeaderFieldValue(document, url);
204
if (!cookie.isEmpty())
205
fields.append("Cookie: " + cookie);
206
// Set "Cookie2: <cookie>" if cookies 2 exists for url?
209
// Add no-cache headers to avoid compatibility issue.
210
// There are some proxies that rewrite "Connection: upgrade"
211
// to "Connection: close" in the response if a request doesn't contain
213
fields.append("Pragma: no-cache");
214
fields.append("Cache-Control: no-cache");
216
fields.append("Sec-WebSocket-Key: " + m_secWebSocketKey);
217
fields.append("Sec-WebSocket-Version: 13");
218
const String extensionValue = m_extensionDispatcher.createHeaderValue();
219
if (extensionValue.length())
220
fields.append("Sec-WebSocket-Extensions: " + extensionValue);
222
// Fields in the handshake are sent by the client in a random order; the
223
// order is not meaningful. Thus, it's ok to send the order we constructed
226
for (size_t i = 0; i < fields.size(); i++) {
227
builder.append(fields[i]);
228
builder.append("\r\n");
231
builder.append("\r\n");
233
return builder.toString().utf8();
236
PassRefPtr<WebSocketHandshakeRequest> WebSocketHandshake::clientHandshakeRequest() const
238
// Keep the following consistent with clientHandshakeMessage().
239
// FIXME: do we need to store m_secWebSocketKey1, m_secWebSocketKey2 and
240
// m_key3 in WebSocketHandshakeRequest?
241
RefPtr<WebSocketHandshakeRequest> request = WebSocketHandshakeRequest::create("GET", m_url);
242
request->addHeaderField("Upgrade", "websocket");
243
request->addHeaderField("Connection", "Upgrade");
244
request->addHeaderField("Host", hostName(m_url, m_secure));
245
request->addHeaderField("Origin", clientOrigin());
246
if (!m_clientProtocol.isEmpty())
247
request->addHeaderField("Sec-WebSocket-Protocol", m_clientProtocol);
249
KURL url = httpURLForAuthenticationAndCookies();
250
if (m_context->isDocument()) {
251
Document* document = static_cast<Document*>(m_context);
252
String cookie = cookieRequestHeaderFieldValue(document, url);
253
if (!cookie.isEmpty())
254
request->addHeaderField("Cookie", cookie);
255
// Set "Cookie2: <cookie>" if cookies 2 exists for url?
258
request->addHeaderField("Pragma", "no-cache");
259
request->addHeaderField("Cache-Control", "no-cache");
261
request->addHeaderField("Sec-WebSocket-Key", m_secWebSocketKey);
262
request->addHeaderField("Sec-WebSocket-Version", "13");
263
const String extensionValue = m_extensionDispatcher.createHeaderValue();
264
if (extensionValue.length())
265
request->addHeaderField("Sec-WebSocket-Extensions", extensionValue);
267
return request.release();
270
void WebSocketHandshake::reset()
273
m_extensionDispatcher.reset();
276
void WebSocketHandshake::clearScriptExecutionContext()
281
int WebSocketHandshake::readServerHandshake(const char* header, size_t len)
286
int lineLength = readStatusLine(header, len, statusCode, statusText);
287
if (lineLength == -1)
289
if (statusCode == -1) {
290
m_mode = Failed; // m_failureReason is set inside readStatusLine().
293
LOG(Network, "response code: %d", statusCode);
294
m_response.setStatusCode(statusCode);
295
m_response.setStatusText(statusText);
296
if (statusCode != 101) {
298
m_failureReason = "Unexpected response code: " + String::number(statusCode);
302
if (!strnstr(header, "\r\n\r\n", len)) {
303
// Just hasn't been received fully yet.
307
const char* p = readHTTPHeaders(header + lineLength, header + len);
309
LOG(Network, "readHTTPHeaders failed");
310
m_mode = Failed; // m_failureReason is set inside readHTTPHeaders().
313
if (!checkResponseHeaders()) {
314
LOG(Network, "header process failed");
323
WebSocketHandshake::Mode WebSocketHandshake::mode() const
328
String WebSocketHandshake::failureReason() const
330
return m_failureReason;
333
String WebSocketHandshake::serverWebSocketProtocol() const
335
return m_response.headerFields().get("sec-websocket-protocol");
338
String WebSocketHandshake::serverSetCookie() const
340
return m_response.headerFields().get("set-cookie");
343
String WebSocketHandshake::serverSetCookie2() const
345
return m_response.headerFields().get("set-cookie2");
348
String WebSocketHandshake::serverUpgrade() const
350
return m_response.headerFields().get("upgrade");
353
String WebSocketHandshake::serverConnection() const
355
return m_response.headerFields().get("connection");
358
String WebSocketHandshake::serverWebSocketAccept() const
360
return m_response.headerFields().get("sec-websocket-accept");
363
String WebSocketHandshake::acceptedExtensions() const
365
return m_extensionDispatcher.acceptedExtensions();
368
const WebSocketHandshakeResponse& WebSocketHandshake::serverHandshakeResponse() const
373
void WebSocketHandshake::addExtensionProcessor(PassOwnPtr<WebSocketExtensionProcessor> processor)
375
m_extensionDispatcher.addProcessor(processor);
378
KURL WebSocketHandshake::httpURLForAuthenticationAndCookies() const
380
KURL url = m_url.copy();
381
bool couldSetProtocol = url.setProtocol(m_secure ? "https" : "http");
382
ASSERT_UNUSED(couldSetProtocol, couldSetProtocol);
386
// Returns the header length (including "\r\n"), or -1 if we have not received enough data yet.
387
// If the line is malformed or the status code is not a 3-digit number,
388
// statusCode and statusText will be set to -1 and a null string, respectively.
389
int WebSocketHandshake::readStatusLine(const char* header, size_t headerLength, int& statusCode, String& statusText)
391
// Arbitrary size limit to prevent the server from sending an unbounded
392
// amount of data with no newlines and forcing us to buffer it all.
393
static const int maximumLength = 1024;
396
statusText = String();
398
const char* space1 = 0;
399
const char* space2 = 0;
401
size_t consumedLength;
403
for (p = header, consumedLength = 0; consumedLength < headerLength; p++, consumedLength++) {
409
} else if (*p == '\0') {
410
// The caller isn't prepared to deal with null bytes in status
411
// line. WebSockets specification doesn't prohibit this, but HTTP
412
// does, so we'll just treat this as an error.
413
m_failureReason = "Status line contains embedded null";
414
return p + 1 - header;
415
} else if (*p == '\n')
418
if (consumedLength == headerLength)
419
return -1; // We have not received '\n' yet.
421
const char* end = p + 1;
422
int lineLength = end - header;
423
if (lineLength > maximumLength) {
424
m_failureReason = "Status line is too long";
425
return maximumLength;
428
// The line must end with "\r\n".
429
if (lineLength < 2 || *(end - 2) != '\r') {
430
m_failureReason = "Status line does not end with CRLF";
434
if (!space1 || !space2) {
435
m_failureReason = "No response code found: " + trimInputSample(header, lineLength - 2);
439
String statusCodeString(space1 + 1, space2 - space1 - 1);
440
if (statusCodeString.length() != 3) // Status code must consist of three digits.
442
for (int i = 0; i < 3; ++i)
443
if (statusCodeString[i] < '0' || statusCodeString[i] > '9') {
444
m_failureReason = "Invalid status code: " + statusCodeString;
449
statusCode = statusCodeString.toInt(&ok);
452
statusText = String(space2 + 1, end - space2 - 3); // Exclude "\r\n".
456
const char* WebSocketHandshake::readHTTPHeaders(const char* start, const char* end)
458
m_response.clearHeaderFields();
462
bool sawSecWebSocketAcceptHeaderField = false;
463
bool sawSecWebSocketProtocolHeaderField = false;
464
const char* p = start;
465
for (; p < end; p++) {
466
size_t consumedLength = parseHTTPHeader(p, end - p, m_failureReason, name, value);
471
// Stop once we consumed an empty line.
475
// Sec-WebSocket-Extensions may be split. We parse and check the
476
// header value every time the header appears.
477
if (equalIgnoringCase("sec-websocket-extensions", name)) {
478
if (!m_extensionDispatcher.processHeaderValue(value)) {
479
m_failureReason = m_extensionDispatcher.failureReason();
482
} else if (equalIgnoringCase("Sec-WebSocket-Accept", name)) {
483
if (sawSecWebSocketAcceptHeaderField) {
484
m_failureReason = "The Sec-WebSocket-Accept header MUST NOT appear more than once in an HTTP response";
487
m_response.addHeaderField(name, value);
488
sawSecWebSocketAcceptHeaderField = true;
489
} else if (equalIgnoringCase("Sec-WebSocket-Protocol", name)) {
490
if (sawSecWebSocketProtocolHeaderField) {
491
m_failureReason = "The Sec-WebSocket-Protocol header MUST NOT appear more than once in an HTTP response";
494
m_response.addHeaderField(name, value);
495
sawSecWebSocketProtocolHeaderField = true;
497
m_response.addHeaderField(name, value);
502
bool WebSocketHandshake::checkResponseHeaders()
504
const String& serverWebSocketProtocol = this->serverWebSocketProtocol();
505
const String& serverUpgrade = this->serverUpgrade();
506
const String& serverConnection = this->serverConnection();
507
const String& serverWebSocketAccept = this->serverWebSocketAccept();
509
if (serverUpgrade.isNull()) {
510
m_failureReason = "Error during WebSocket handshake: 'Upgrade' header is missing";
513
if (serverConnection.isNull()) {
514
m_failureReason = "Error during WebSocket handshake: 'Connection' header is missing";
517
if (serverWebSocketAccept.isNull()) {
518
m_failureReason = "Error during WebSocket handshake: 'Sec-WebSocket-Accept' header is missing";
522
if (!equalIgnoringCase(serverUpgrade, "websocket")) {
523
m_failureReason = "Error during WebSocket handshake: 'Upgrade' header value is not 'WebSocket'";
526
if (!equalIgnoringCase(serverConnection, "upgrade")) {
527
m_failureReason = "Error during WebSocket handshake: 'Connection' header value is not 'Upgrade'";
531
if (serverWebSocketAccept != m_expectedAccept) {
532
m_failureReason = "Error during WebSocket handshake: Sec-WebSocket-Accept mismatch";
535
if (!serverWebSocketProtocol.isNull()) {
536
if (m_clientProtocol.isEmpty()) {
537
m_failureReason = "Error during WebSocket handshake: Sec-WebSocket-Protocol mismatch";
540
Vector<String> result;
541
m_clientProtocol.split(String(WebSocket::subProtocolSeperator()), result);
542
if (!result.contains(serverWebSocketProtocol)) {
543
m_failureReason = "Error during WebSocket handshake: Sec-WebSocket-Protocol mismatch";
550
} // namespace WebCore
552
#endif // ENABLE(WEB_SOCKETS)