1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
|
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/websockets/websocket_handshake_handler.h"
#include "base/md5.h"
#include "base/string_piece.h"
#include "base/string_util.h"
#include "googleurl/src/gurl.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_util.h"
namespace {
const size_t kRequestKey3Size = 8U;
const size_t kResponseKeySize = 16U;
void ParseHandshakeHeader(
const char* handshake_message, int len,
std::string* status_line,
std::string* headers) {
size_t i = base::StringPiece(handshake_message, len).find_first_of("\r\n");
if (i == base::StringPiece::npos) {
*status_line = std::string(handshake_message, len);
*headers = "";
return;
}
// |status_line| includes \r\n.
*status_line = std::string(handshake_message, i + 2);
int header_len = len - (i + 2) - 2;
if (header_len > 0) {
// |handshake_message| includes tailing \r\n\r\n.
// |headers| doesn't include 2nd \r\n.
*headers = std::string(handshake_message + i + 2, header_len);
} else {
*headers = "";
}
}
void FetchHeaders(const std::string& headers,
const char* const headers_to_get[],
size_t headers_to_get_len,
std::vector<std::string>* values) {
net::HttpUtil::HeadersIterator iter(headers.begin(), headers.end(), "\r\n");
while (iter.GetNext()) {
for (size_t i = 0; i < headers_to_get_len; i++) {
if (LowerCaseEqualsASCII(iter.name_begin(), iter.name_end(),
headers_to_get[i])) {
values->push_back(iter.values());
}
}
}
}
bool GetHeaderName(std::string::const_iterator line_begin,
std::string::const_iterator line_end,
std::string::const_iterator* name_begin,
std::string::const_iterator* name_end) {
std::string::const_iterator colon = std::find(line_begin, line_end, ':');
if (colon == line_end) {
return false;
}
*name_begin = line_begin;
*name_end = colon;
if (*name_begin == *name_end || net::HttpUtil::IsLWS(**name_begin))
return false;
net::HttpUtil::TrimLWS(name_begin, name_end);
return true;
}
// Similar to HttpUtil::StripHeaders, but it preserves malformed headers, that
// is, lines that are not formatted as "<name>: <value>\r\n".
std::string FilterHeaders(
const std::string& headers,
const char* const headers_to_remove[],
size_t headers_to_remove_len) {
std::string filtered_headers;
StringTokenizer lines(headers.begin(), headers.end(), "\r\n");
while (lines.GetNext()) {
std::string::const_iterator line_begin = lines.token_begin();
std::string::const_iterator line_end = lines.token_end();
std::string::const_iterator name_begin;
std::string::const_iterator name_end;
bool should_remove = false;
if (GetHeaderName(line_begin, line_end, &name_begin, &name_end)) {
for (size_t i = 0; i < headers_to_remove_len; ++i) {
if (LowerCaseEqualsASCII(name_begin, name_end, headers_to_remove[i])) {
should_remove = true;
break;
}
}
}
if (!should_remove) {
filtered_headers.append(line_begin, line_end);
filtered_headers.append("\r\n");
}
}
return filtered_headers;
}
// Gets a key number from |key| and appends the number to |challenge|.
// The key number (/part_N/) is extracted as step 4.-8. in
// 5.2. Sending the server's opening handshake of
// http://www.ietf.org/id/draft-ietf-hybi-thewebsocketprotocol-00.txt
void GetKeyNumber(const std::string& key, std::string* challenge) {
uint32 key_number = 0;
uint32 spaces = 0;
for (size_t i = 0; i < key.size(); ++i) {
if (isdigit(key[i])) {
// key_number should not overflow. (it comes from
// WebCore/websockets/WebSocketHandshake.cpp).
key_number = key_number * 10 + key[i] - '0';
} else if (key[i] == ' ') {
++spaces;
}
}
// spaces should not be zero in valid handshake request.
if (spaces == 0)
return;
key_number /= spaces;
char part[4];
for (int i = 0; i < 4; i++) {
part[3 - i] = key_number & 0xFF;
key_number >>= 8;
}
challenge->append(part, 4);
}
} // anonymous namespace
namespace net {
WebSocketHandshakeRequestHandler::WebSocketHandshakeRequestHandler()
: original_length_(0),
raw_length_(0) {}
bool WebSocketHandshakeRequestHandler::ParseRequest(
const char* data, int length) {
DCHECK_GT(length, 0);
std::string input(data, length);
int input_header_length =
HttpUtil::LocateEndOfHeaders(input.data(), input.size(), 0);
if (input_header_length <= 0 ||
input_header_length + kRequestKey3Size > input.size())
return false;
ParseHandshakeHeader(input.data(),
input_header_length,
&status_line_,
&headers_);
// draft-hixie-thewebsocketprotocol-76 or later will send /key3/
// after handshake request header.
// Assumes WebKit doesn't send any data after handshake request message
// until handshake is finished.
// Thus, |key3_| is part of handshake message, and not in part
// of WebSocket frame stream.
DCHECK_EQ(kRequestKey3Size,
input.size() -
input_header_length);
key3_ = std::string(input.data() + input_header_length,
input.size() - input_header_length);
original_length_ = input.size();
return true;
}
size_t WebSocketHandshakeRequestHandler::original_length() const {
return original_length_;
}
void WebSocketHandshakeRequestHandler::AppendHeaderIfMissing(
const std::string& name, const std::string& value) {
DCHECK(headers_.size() > 0);
HttpUtil::AppendHeaderIfMissing(name.c_str(), value, &headers_);
}
void WebSocketHandshakeRequestHandler::RemoveHeaders(
const char* const headers_to_remove[],
size_t headers_to_remove_len) {
DCHECK(headers_.size() > 0);
headers_ = FilterHeaders(
headers_, headers_to_remove, headers_to_remove_len);
}
HttpRequestInfo WebSocketHandshakeRequestHandler::GetRequestInfo(
const GURL& url, std::string* challenge) {
HttpRequestInfo request_info;
request_info.url = url;
base::StringPiece method = status_line_.data();
size_t method_end = base::StringPiece(
status_line_.data(), status_line_.size()).find_first_of(" ");
if (method_end != base::StringPiece::npos)
request_info.method = std::string(status_line_.data(), method_end);
request_info.extra_headers.Clear();
request_info.extra_headers.AddHeadersFromString(headers_);
request_info.extra_headers.RemoveHeader("Upgrade");
request_info.extra_headers.RemoveHeader("Connection");
challenge->clear();
std::string key;
request_info.extra_headers.GetHeader("Sec-WebSocket-Key1", &key);
request_info.extra_headers.RemoveHeader("Sec-WebSocket-Key1");
GetKeyNumber(key, challenge);
request_info.extra_headers.GetHeader("Sec-WebSocket-Key2", &key);
request_info.extra_headers.RemoveHeader("Sec-WebSocket-Key2");
GetKeyNumber(key, challenge);
challenge->append(key3_);
return request_info;
}
bool WebSocketHandshakeRequestHandler::GetRequestHeaderBlock(
const GURL& url, spdy::SpdyHeaderBlock* headers, std::string* challenge) {
// We don't set "method" and "version". These are fixed value in WebSocket
// protocol.
(*headers)["url"] = url.spec();
std::string key1;
std::string key2;
HttpUtil::HeadersIterator iter(headers_.begin(), headers_.end(), "\r\n");
while (iter.GetNext()) {
if (LowerCaseEqualsASCII(iter.name_begin(), iter.name_end(),
"connection")) {
// Ignore "Connection" header.
continue;
} else if (LowerCaseEqualsASCII(iter.name_begin(), iter.name_end(),
"upgrade")) {
// Ignore "Upgrade" header.
continue;
} else if (LowerCaseEqualsASCII(iter.name_begin(), iter.name_end(),
"sec-websocket-key1")) {
// Use only for generating challenge.
key1 = iter.values();
continue;
} else if (LowerCaseEqualsASCII(iter.name_begin(), iter.name_end(),
"sec-websocket-key2")) {
// Use only for generating challenge.
key2 = iter.values();
continue;
}
// Others should be sent out to |headers|.
std::string name = StringToLowerASCII(iter.name());
spdy::SpdyHeaderBlock::iterator found = headers->find(name);
if (found == headers->end()) {
(*headers)[name] = iter.values();
} else {
// For now, websocket doesn't use multiple headers, but follows to http.
found->second.append(1, '\0'); // +=() doesn't append 0's
found->second.append(iter.values());
}
}
challenge->clear();
GetKeyNumber(key1, challenge);
GetKeyNumber(key2, challenge);
challenge->append(key3_);
return true;
}
std::string WebSocketHandshakeRequestHandler::GetRawRequest() {
DCHECK(status_line_.size() > 0);
DCHECK(headers_.size() > 0);
DCHECK_EQ(kRequestKey3Size, key3_.size());
std::string raw_request = status_line_ + headers_ + "\r\n" + key3_;
raw_length_ = raw_request.size();
return raw_request;
}
size_t WebSocketHandshakeRequestHandler::raw_length() const {
DCHECK_GT(raw_length_, 0);
return raw_length_;
}
WebSocketHandshakeResponseHandler::WebSocketHandshakeResponseHandler()
: original_header_length_(0) {
}
WebSocketHandshakeResponseHandler::~WebSocketHandshakeResponseHandler() {}
size_t WebSocketHandshakeResponseHandler::ParseRawResponse(
const char* data, int length) {
DCHECK_GT(length, 0);
if (HasResponse()) {
DCHECK(status_line_.size() > 0);
DCHECK(headers_.size() > 0);
DCHECK_EQ(kResponseKeySize, key_.size());
return 0;
}
size_t old_original_length = original_.size();
original_.append(data, length);
// TODO(ukai): fail fast when response gives wrong status code.
original_header_length_ = HttpUtil::LocateEndOfHeaders(
original_.data(), original_.size(), 0);
if (!HasResponse())
return length;
ParseHandshakeHeader(original_.data(),
original_header_length_,
&status_line_,
&headers_);
int header_size = status_line_.size() + headers_.size();
DCHECK_GE(original_header_length_, header_size);
header_separator_ = std::string(original_.data() + header_size,
original_header_length_ - header_size);
key_ = std::string(original_.data() + original_header_length_,
kResponseKeySize);
return original_header_length_ + kResponseKeySize - old_original_length;
}
bool WebSocketHandshakeResponseHandler::HasResponse() const {
return original_header_length_ > 0 &&
original_header_length_ + kResponseKeySize <= original_.size();
}
bool WebSocketHandshakeResponseHandler::ParseResponseInfo(
const HttpResponseInfo& response_info,
const std::string& challenge) {
if (!response_info.headers.get())
return false;
std::string response_message;
response_message = response_info.headers->GetStatusLine();
response_message += "\r\n";
response_message += "Upgrade: WebSocket\r\n";
response_message += "Connection: Upgrade\r\n";
void* iter = NULL;
std::string name;
std::string value;
while (response_info.headers->EnumerateHeaderLines(&iter, &name, &value)) {
response_message += name + ": " + value + "\r\n";
}
response_message += "\r\n";
MD5Digest digest;
MD5Sum(challenge.data(), challenge.size(), &digest);
const char* digest_data = reinterpret_cast<char*>(digest.a);
response_message.append(digest_data, sizeof(digest.a));
return ParseRawResponse(response_message.data(),
response_message.size()) == response_message.size();
}
bool WebSocketHandshakeResponseHandler::ParseResponseHeaderBlock(
const spdy::SpdyHeaderBlock& headers,
const std::string& challenge) {
std::string response_message;
response_message = "HTTP/1.1 101 WebSocket Protocol Handshake\r\n";
response_message += "Upgrade: WebSocket\r\n";
response_message += "Connection: Upgrade\r\n";
for (spdy::SpdyHeaderBlock::const_iterator iter = headers.begin();
iter != headers.end();
++iter) {
// For each value, if the server sends a NUL-separated list of values,
// we separate that back out into individual headers for each value
// in the list.
const std::string& value = iter->second;
size_t start = 0;
size_t end = 0;
do {
end = value.find('\0', start);
std::string tval;
if (end != std::string::npos)
tval = value.substr(start, (end - start));
else
tval = value.substr(start);
response_message += iter->first + ": " + tval + "\r\n";
start = end + 1;
} while (end != std::string::npos);
}
response_message += "\r\n";
MD5Digest digest;
MD5Sum(challenge.data(), challenge.size(), &digest);
const char* digest_data = reinterpret_cast<char*>(digest.a);
response_message.append(digest_data, sizeof(digest.a));
return ParseRawResponse(response_message.data(),
response_message.size()) == response_message.size();
}
void WebSocketHandshakeResponseHandler::GetHeaders(
const char* const headers_to_get[],
size_t headers_to_get_len,
std::vector<std::string>* values) {
DCHECK(HasResponse());
DCHECK(status_line_.size() > 0);
DCHECK(headers_.size() > 0);
DCHECK_EQ(kResponseKeySize, key_.size());
FetchHeaders(headers_, headers_to_get, headers_to_get_len, values);
}
void WebSocketHandshakeResponseHandler::RemoveHeaders(
const char* const headers_to_remove[],
size_t headers_to_remove_len) {
DCHECK(HasResponse());
DCHECK(status_line_.size() > 0);
DCHECK(headers_.size() > 0);
DCHECK_EQ(kResponseKeySize, key_.size());
headers_ = FilterHeaders(headers_, headers_to_remove, headers_to_remove_len);
}
std::string WebSocketHandshakeResponseHandler::GetRawResponse() const {
DCHECK(HasResponse());
return std::string(original_.data(),
original_header_length_ + kResponseKeySize);
}
std::string WebSocketHandshakeResponseHandler::GetResponse() {
DCHECK(HasResponse());
DCHECK(status_line_.size() > 0);
// headers_ might be empty for wrong response from server.
DCHECK_EQ(kResponseKeySize, key_.size());
return status_line_ + headers_ + header_separator_ + key_;
}
} // namespace net
|