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
|
// Copyright (c) 2009 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_throttle.h"
#if defined(OS_WIN)
#include <ws2tcpip.h>
#else
#include <netdb.h>
#endif
#include <string>
#include "base/message_loop.h"
#include "base/ref_counted.h"
#include "base/singleton.h"
#include "base/string_util.h"
#include "net/base/io_buffer.h"
#include "net/socket_stream/socket_stream.h"
namespace net {
static std::string AddrinfoToHashkey(const struct addrinfo* addrinfo) {
switch (addrinfo->ai_family) {
case AF_INET: {
const struct sockaddr_in* const addr =
reinterpret_cast<const sockaddr_in*>(addrinfo->ai_addr);
return StringPrintf("%d:%s",
addrinfo->ai_family,
HexEncode(&addr->sin_addr, 4).c_str());
}
case AF_INET6: {
const struct sockaddr_in6* const addr6 =
reinterpret_cast<const sockaddr_in6*>(addrinfo->ai_addr);
return StringPrintf("%d:%s",
addrinfo->ai_family,
HexEncode(&addr6->sin6_addr,
sizeof(addr6->sin6_addr)).c_str());
}
default:
return StringPrintf("%d:%s",
addrinfo->ai_family,
HexEncode(addrinfo->ai_addr,
addrinfo->ai_addrlen).c_str());
}
}
// State for WebSocket protocol on each SocketStream.
// This is owned in SocketStream as UserData keyed by WebSocketState::kKeyName.
// This is alive between connection starts and handshake is finished.
// In this class, it doesn't check actual handshake finishes, but only checks
// end of header is found in read data.
class WebSocketThrottle::WebSocketState : public SocketStream::UserData {
public:
explicit WebSocketState(const AddressList& addrs)
: address_list_(addrs),
callback_(NULL),
waiting_(false),
handshake_finished_(false),
buffer_(NULL) {
}
~WebSocketState() {}
int OnStartOpenConnection(CompletionCallback* callback) {
DCHECK(!callback_);
if (!waiting_)
return OK;
callback_ = callback;
return ERR_IO_PENDING;
}
int OnRead(const char* data, int len, CompletionCallback* callback) {
DCHECK(!waiting_);
DCHECK(!callback_);
DCHECK(!handshake_finished_);
static const int kBufferSize = 8129;
if (!buffer_) {
// Fast path.
int eoh = HttpUtil::LocateEndOfHeaders(data, len, 0);
if (eoh > 0) {
handshake_finished_ = true;
return OK;
}
buffer_ = new GrowableIOBuffer();
buffer_->SetCapacity(kBufferSize);
} else {
if (buffer_->RemainingCapacity() < len) {
if (!buffer_->SetCapacity(buffer_->capacity() + kBufferSize)) {
// TODO(ukai): Check more correctly.
// Seek to the last CR or LF and reduce memory usage.
LOG(ERROR) << "Too large headers? capacity=" << buffer_->capacity();
handshake_finished_ = true;
return OK;
}
}
}
memcpy(buffer_->data(), data, len);
buffer_->set_offset(buffer_->offset() + len);
int eoh = HttpUtil::LocateEndOfHeaders(buffer_->StartOfBuffer(),
buffer_->offset(), 0);
handshake_finished_ = (eoh > 0);
return OK;
}
const AddressList& address_list() const { return address_list_; }
void SetWaiting() { waiting_ = true; }
bool IsWaiting() const { return waiting_; }
bool HandshakeFinished() const { return handshake_finished_; }
void Wakeup() {
waiting_ = false;
// We wrap |callback_| to keep this alive while this is released.
scoped_refptr<CompletionCallbackRunner> runner =
new CompletionCallbackRunner(callback_);
callback_ = NULL;
MessageLoopForIO::current()->PostTask(
FROM_HERE,
NewRunnableMethod(runner.get(),
&CompletionCallbackRunner::Run));
}
static const char* kKeyName;
private:
class CompletionCallbackRunner
: public base::RefCountedThreadSafe<CompletionCallbackRunner> {
public:
explicit CompletionCallbackRunner(CompletionCallback* callback)
: callback_(callback) {
DCHECK(callback_);
}
virtual ~CompletionCallbackRunner() {}
void Run() {
callback_->Run(OK);
}
private:
CompletionCallback* callback_;
DISALLOW_COPY_AND_ASSIGN(CompletionCallbackRunner);
};
const AddressList& address_list_;
CompletionCallback* callback_;
// True if waiting another websocket connection is established.
// False if the websocket is performing handshaking.
bool waiting_;
// True if the websocket handshake is completed.
// If true, it will be removed from queue and deleted from the SocketStream
// UserData soon.
bool handshake_finished_;
// Buffer for read data to check handshake response message.
scoped_refptr<GrowableIOBuffer> buffer_;
DISALLOW_COPY_AND_ASSIGN(WebSocketState);
};
const char* WebSocketThrottle::WebSocketState::kKeyName = "WebSocketState";
WebSocketThrottle::WebSocketThrottle() {
SocketStreamThrottle::RegisterSocketStreamThrottle("ws", this);
SocketStreamThrottle::RegisterSocketStreamThrottle("wss", this);
}
WebSocketThrottle::~WebSocketThrottle() {
DCHECK(queue_.empty());
DCHECK(addr_map_.empty());
}
int WebSocketThrottle::OnStartOpenConnection(
SocketStream* socket, CompletionCallback* callback) {
WebSocketState* state = new WebSocketState(socket->address_list());
PutInQueue(socket, state);
return state->OnStartOpenConnection(callback);
}
int WebSocketThrottle::OnRead(SocketStream* socket,
const char* data, int len,
CompletionCallback* callback) {
WebSocketState* state = static_cast<WebSocketState*>(
socket->GetUserData(WebSocketState::kKeyName));
// If no state, handshake was already completed. Do nothing.
if (!state)
return OK;
int result = state->OnRead(data, len, callback);
if (state->HandshakeFinished()) {
RemoveFromQueue(socket, state);
WakeupSocketIfNecessary();
}
return result;
}
int WebSocketThrottle::OnWrite(SocketStream* socket,
const char* data, int len,
CompletionCallback* callback) {
// Do nothing.
return OK;
}
void WebSocketThrottle::OnClose(SocketStream* socket) {
WebSocketState* state = static_cast<WebSocketState*>(
socket->GetUserData(WebSocketState::kKeyName));
if (!state)
return;
RemoveFromQueue(socket, state);
WakeupSocketIfNecessary();
}
void WebSocketThrottle::PutInQueue(SocketStream* socket,
WebSocketState* state) {
socket->SetUserData(WebSocketState::kKeyName, state);
queue_.push_back(state);
const AddressList& address_list = socket->address_list();
for (const struct addrinfo* addrinfo = address_list.head();
addrinfo != NULL;
addrinfo = addrinfo->ai_next) {
std::string addrkey = AddrinfoToHashkey(addrinfo);
ConnectingAddressMap::iterator iter = addr_map_.find(addrkey);
if (iter == addr_map_.end()) {
ConnectingQueue* queue = new ConnectingQueue();
queue->push_back(state);
addr_map_[addrkey] = queue;
} else {
iter->second->push_back(state);
state->SetWaiting();
}
}
}
void WebSocketThrottle::RemoveFromQueue(SocketStream* socket,
WebSocketState* state) {
const AddressList& address_list = socket->address_list();
for (const struct addrinfo* addrinfo = address_list.head();
addrinfo != NULL;
addrinfo = addrinfo->ai_next) {
std::string addrkey = AddrinfoToHashkey(addrinfo);
ConnectingAddressMap::iterator iter = addr_map_.find(addrkey);
DCHECK(iter != addr_map_.end());
ConnectingQueue* queue = iter->second;
DCHECK(state == queue->front());
queue->pop_front();
if (queue->empty())
addr_map_.erase(iter);
}
for (ConnectingQueue::iterator iter = queue_.begin();
iter != queue_.end();
++iter) {
if (*iter == state) {
queue_.erase(iter);
break;
}
}
socket->SetUserData(WebSocketState::kKeyName, NULL);
}
void WebSocketThrottle::WakeupSocketIfNecessary() {
for (ConnectingQueue::iterator iter = queue_.begin();
iter != queue_.end();
++iter) {
WebSocketState* state = *iter;
if (!state->IsWaiting())
continue;
bool should_wakeup = true;
const AddressList& address_list = state->address_list();
for (const struct addrinfo* addrinfo = address_list.head();
addrinfo != NULL;
addrinfo = addrinfo->ai_next) {
std::string addrkey = AddrinfoToHashkey(addrinfo);
ConnectingAddressMap::iterator iter = addr_map_.find(addrkey);
DCHECK(iter != addr_map_.end());
ConnectingQueue* queue = iter->second;
if (state != queue->front()) {
should_wakeup = false;
break;
}
}
if (should_wakeup)
state->Wakeup();
}
}
/* static */
void WebSocketThrottle::Init() {
Singleton<WebSocketThrottle>::get();
}
} // namespace net
|