OLD | NEW |
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/http_server.h" | 5 #include "net/server/http_server.h" |
6 | 6 |
7 #include "base/compiler_specific.h" | 7 #include "base/compiler_specific.h" |
8 #include "base/logging.h" | 8 #include "base/logging.h" |
9 #include "base/stl_util.h" | 9 #include "base/stl_util.h" |
10 #include "base/strings/string_number_conversions.h" | 10 #include "base/strings/string_number_conversions.h" |
11 #include "base/strings/string_util.h" | 11 #include "base/strings/string_util.h" |
12 #include "base/strings/stringprintf.h" | 12 #include "base/strings/stringprintf.h" |
13 #include "base/sys_byteorder.h" | 13 #include "base/sys_byteorder.h" |
14 #include "build/build_config.h" | 14 #include "build/build_config.h" |
15 #include "net/base/net_errors.h" | 15 #include "net/base/net_errors.h" |
16 #include "net/server/http_connection.h" | 16 #include "net/server/http_connection.h" |
17 #include "net/server/http_server_request_info.h" | 17 #include "net/server/http_server_request_info.h" |
18 #include "net/server/http_server_response_info.h" | 18 #include "net/server/http_server_response_info.h" |
19 #include "net/server/web_socket.h" | 19 #include "net/server/web_socket.h" |
20 #include "net/socket/tcp_listen_socket.h" | 20 #include "net/socket/server_socket.h" |
| 21 #include "net/socket/stream_socket.h" |
| 22 #include "net/socket/tcp_server_socket.h" |
21 | 23 |
22 namespace net { | 24 namespace net { |
23 | 25 |
24 HttpServer::HttpServer(const StreamListenSocketFactory& factory, | 26 namespace { |
| 27 |
| 28 // A helper function to delete connection in next run loop. |
| 29 void DeleteConnection(HttpConnection* connection) { |
| 30 delete connection; |
| 31 } |
| 32 |
| 33 } // namespace |
| 34 |
| 35 HttpServer::HttpServer(scoped_ptr<ServerSocket> server_socket, |
25 HttpServer::Delegate* delegate) | 36 HttpServer::Delegate* delegate) |
26 : delegate_(delegate), | 37 : server_socket_(server_socket.Pass()), |
27 server_(factory.CreateAndListen(this)) { | 38 delegate_(delegate), |
| 39 last_id_(0), |
| 40 weak_ptr_factory_(this) { |
| 41 DCHECK(server_socket_); |
| 42 DoAcceptLoop(); |
| 43 } |
| 44 |
| 45 HttpServer::~HttpServer() { |
| 46 STLDeleteContainerPairSecondPointers( |
| 47 id_to_connection_.begin(), id_to_connection_.end()); |
| 48 } |
| 49 |
| 50 base::WeakPtr<HttpServer> HttpServer::GetWeakPtr() { |
| 51 return weak_ptr_factory_.GetWeakPtr(); |
28 } | 52 } |
29 | 53 |
30 void HttpServer::AcceptWebSocket( | 54 void HttpServer::AcceptWebSocket( |
31 int connection_id, | 55 int connection_id, |
32 const HttpServerRequestInfo& request) { | 56 const HttpServerRequestInfo& request) { |
33 HttpConnection* connection = FindConnection(connection_id); | 57 HttpConnection* connection = FindConnection(connection_id); |
34 if (connection == NULL) | 58 if (connection == NULL) |
35 return; | 59 return; |
36 | 60 DCHECK(connection->web_socket()); |
37 DCHECK(connection->web_socket_.get()); | 61 connection->web_socket()->Accept(request); |
38 connection->web_socket_->Accept(request); | |
39 } | 62 } |
40 | 63 |
41 void HttpServer::SendOverWebSocket(int connection_id, | 64 void HttpServer::SendOverWebSocket(int connection_id, |
42 const std::string& data) { | 65 const std::string& data) { |
43 HttpConnection* connection = FindConnection(connection_id); | 66 HttpConnection* connection = FindConnection(connection_id); |
44 if (connection == NULL) | 67 if (connection == NULL) |
45 return; | 68 return; |
46 DCHECK(connection->web_socket_.get()); | 69 DCHECK(connection->web_socket()); |
47 connection->web_socket_->Send(data); | 70 connection->web_socket()->Send(data); |
48 } | 71 } |
49 | 72 |
50 void HttpServer::SendRaw(int connection_id, const std::string& data) { | 73 void HttpServer::SendRaw(int connection_id, const std::string& data) { |
51 HttpConnection* connection = FindConnection(connection_id); | 74 HttpConnection* connection = FindConnection(connection_id); |
52 if (connection == NULL) | 75 if (connection == NULL) |
53 return; | 76 return; |
54 connection->Send(data); | 77 |
| 78 bool writing_in_progress = !connection->write_buf()->IsEmpty(); |
| 79 if (connection->write_buf()->Append(data) && !writing_in_progress) |
| 80 DoWriteLoop(connection); |
55 } | 81 } |
56 | 82 |
57 void HttpServer::SendResponse(int connection_id, | 83 void HttpServer::SendResponse(int connection_id, |
58 const HttpServerResponseInfo& response) { | 84 const HttpServerResponseInfo& response) { |
59 HttpConnection* connection = FindConnection(connection_id); | 85 SendRaw(connection_id, response.Serialize()); |
60 if (connection == NULL) | |
61 return; | |
62 connection->Send(response); | |
63 } | 86 } |
64 | 87 |
65 void HttpServer::Send(int connection_id, | 88 void HttpServer::Send(int connection_id, |
66 HttpStatusCode status_code, | 89 HttpStatusCode status_code, |
67 const std::string& data, | 90 const std::string& data, |
68 const std::string& content_type) { | 91 const std::string& content_type) { |
69 HttpServerResponseInfo response(status_code); | 92 HttpServerResponseInfo response(status_code); |
70 response.SetBody(data, content_type); | 93 response.SetBody(data, content_type); |
71 SendResponse(connection_id, response); | 94 SendResponse(connection_id, response); |
72 } | 95 } |
(...skipping 10 matching lines...) Expand all Loading... |
83 | 106 |
84 void HttpServer::Send500(int connection_id, const std::string& message) { | 107 void HttpServer::Send500(int connection_id, const std::string& message) { |
85 SendResponse(connection_id, HttpServerResponseInfo::CreateFor500(message)); | 108 SendResponse(connection_id, HttpServerResponseInfo::CreateFor500(message)); |
86 } | 109 } |
87 | 110 |
88 void HttpServer::Close(int connection_id) { | 111 void HttpServer::Close(int connection_id) { |
89 HttpConnection* connection = FindConnection(connection_id); | 112 HttpConnection* connection = FindConnection(connection_id); |
90 if (connection == NULL) | 113 if (connection == NULL) |
91 return; | 114 return; |
92 | 115 |
93 // Initiating close from server-side does not lead to the DidClose call. | 116 id_to_connection_.erase(connection->id()); |
94 // Do it manually here. | 117 delegate_->OnClose(connection_id); |
95 DidClose(connection->socket_.get()); | 118 |
| 119 // The call stack might have callbacks which still have the pointer of |
| 120 // connection. Instead of referencing connection with ID all the time, |
| 121 // destroys the connection in next run loop to make sure any pending |
| 122 // callbacks in the call stack return. |
| 123 base::MessageLoopProxy::current()->PostTask( |
| 124 FROM_HERE, |
| 125 base::Bind(&DeleteConnection, base::Unretained(connection))); |
96 } | 126 } |
97 | 127 |
98 int HttpServer::GetLocalAddress(IPEndPoint* address) { | 128 int HttpServer::GetLocalAddress(IPEndPoint* address) { |
99 if (!server_) | 129 return server_socket_->GetLocalAddress(address); |
100 return ERR_SOCKET_NOT_CONNECTED; | |
101 return server_->GetLocalAddress(address); | |
102 } | 130 } |
103 | 131 |
104 void HttpServer::DidAccept(StreamListenSocket* server, | 132 void HttpServer::SetReceiveBufferSize(int connection_id, int32 size) { |
105 scoped_ptr<StreamListenSocket> socket) { | 133 HttpConnection* connection = FindConnection(connection_id); |
106 HttpConnection* connection = new HttpConnection(this, socket.Pass()); | 134 if (connection == NULL) |
107 id_to_connection_[connection->id()] = connection; | 135 return; |
108 // TODO(szym): Fix socket access. Make HttpConnection the Delegate. | 136 connection->read_buf()->set_capacity_limit(size); |
109 socket_to_connection_[connection->socket_.get()] = connection; | |
110 } | 137 } |
111 | 138 |
112 void HttpServer::DidRead(StreamListenSocket* socket, | 139 void HttpServer::SetSendBufferSize(int connection_id, int32 size) { |
113 const char* data, | 140 HttpConnection* connection = FindConnection(connection_id); |
114 int len) { | |
115 HttpConnection* connection = FindConnection(socket); | |
116 DCHECK(connection != NULL); | |
117 if (connection == NULL) | 141 if (connection == NULL) |
118 return; | 142 return; |
| 143 connection->write_buf()->set_total_size_limit(size); |
| 144 } |
119 | 145 |
120 connection->recv_data_.append(data, len); | 146 void HttpServer::DoAcceptLoop() { |
121 while (connection->recv_data_.length()) { | 147 int rv; |
122 if (connection->web_socket_.get()) { | 148 do { |
| 149 rv = server_socket_->Accept(&accepted_socket_, |
| 150 base::Bind(&HttpServer::OnAcceptCompleted, |
| 151 base::Unretained(this))); |
| 152 if (rv == ERR_IO_PENDING) |
| 153 return; |
| 154 rv = DidAccept(rv); |
| 155 } while (rv == OK); |
| 156 } |
| 157 |
| 158 void HttpServer::OnAcceptCompleted(int rv) { |
| 159 if (DidAccept(rv) == OK) |
| 160 DoAcceptLoop(); |
| 161 } |
| 162 |
| 163 int HttpServer::DidAccept(int rv) { |
| 164 if (rv < 0) { |
| 165 LOG(ERROR) << "Accept error: rv=" << rv; |
| 166 return rv; |
| 167 } |
| 168 |
| 169 HttpConnection* connection = |
| 170 new HttpConnection(++last_id_, accepted_socket_.Pass()); |
| 171 id_to_connection_[connection->id()] = connection; |
| 172 DoReadLoop(connection); |
| 173 return OK; |
| 174 } |
| 175 |
| 176 void HttpServer::DoReadLoop(HttpConnection* connection) { |
| 177 int rv; |
| 178 do { |
| 179 HttpConnection::ReadIOBuffer* read_buf = connection->read_buf(); |
| 180 // Increases read buffer size if necessary. |
| 181 if (read_buf->GetUnusedCapacity() == 0 && !read_buf->IncreaseCapacity()) { |
| 182 Close(connection->id()); |
| 183 return; |
| 184 } |
| 185 |
| 186 rv = connection->socket()->Read( |
| 187 read_buf->GetUnusedIOBuffer(), |
| 188 read_buf->GetUnusedCapacity(), |
| 189 base::Bind(&HttpServer::OnReadCompleted, |
| 190 base::Unretained(this), connection->id())); |
| 191 if (rv == ERR_IO_PENDING) |
| 192 return; |
| 193 rv = DidRead(connection, rv); |
| 194 } while (rv == OK); |
| 195 } |
| 196 |
| 197 void HttpServer::OnReadCompleted(int connection_id, int rv) { |
| 198 HttpConnection* connection = FindConnection(connection_id); |
| 199 if (!connection) // It might be closed right before by write error. |
| 200 return; |
| 201 |
| 202 if (DidRead(connection, rv) == OK) |
| 203 DoReadLoop(connection); |
| 204 } |
| 205 |
| 206 int HttpServer::DidRead(HttpConnection* connection, int rv) { |
| 207 if (rv <= 0) { |
| 208 Close(connection->id()); |
| 209 return rv == 0 ? ERR_CONNECTION_CLOSED : rv; |
| 210 } |
| 211 |
| 212 HttpConnection::ReadIOBuffer* read_buf = connection->read_buf(); |
| 213 read_buf->DidRead(rv); |
| 214 |
| 215 // Handles http requests or websocket messages. |
| 216 while (read_buf->GetUnconsumedSize() > 0) { |
| 217 if (connection->web_socket()) { |
123 std::string message; | 218 std::string message; |
124 WebSocket::ParseResult result = connection->web_socket_->Read(&message); | 219 WebSocket::ParseResult result = connection->web_socket()->Read(&message); |
125 if (result == WebSocket::FRAME_INCOMPLETE) | 220 if (result == WebSocket::FRAME_INCOMPLETE) |
126 break; | 221 break; |
127 | 222 |
128 if (result == WebSocket::FRAME_CLOSE || | 223 if (result == WebSocket::FRAME_CLOSE || |
129 result == WebSocket::FRAME_ERROR) { | 224 result == WebSocket::FRAME_ERROR) { |
130 Close(connection->id()); | 225 Close(connection->id()); |
131 break; | 226 break; |
132 } | 227 } |
133 delegate_->OnWebSocketMessage(connection->id(), message); | 228 delegate_->OnWebSocketMessage(connection->id(), message); |
134 continue; | 229 continue; |
135 } | 230 } |
136 | 231 |
137 HttpServerRequestInfo request; | 232 HttpServerRequestInfo request; |
138 size_t pos = 0; | 233 size_t pos = 0; |
139 if (!ParseHeaders(connection, &request, &pos)) | 234 if (!ParseHeaders(read_buf->data(), read_buf->GetUnconsumedSize(), |
| 235 &request, &pos)) |
140 break; | 236 break; |
141 | 237 |
142 // Sets peer address if exists. | 238 // Sets peer address if exists. |
143 socket->GetPeerAddress(&request.peer); | 239 connection->socket()->GetPeerAddress(&request.peer); |
144 | 240 |
145 if (request.HasHeaderValue("connection", "upgrade")) { | 241 if (request.HasHeaderValue("connection", "upgrade")) { |
146 connection->web_socket_.reset(WebSocket::CreateWebSocket(connection, | 242 scoped_ptr<WebSocket> websocket( |
147 request, | 243 WebSocket::CreateWebSocket(this, connection, request, &pos)); |
148 &pos)); | 244 if (!websocket) // Not enough data was received. |
149 | |
150 if (!connection->web_socket_.get()) // Not enough data was received. | |
151 break; | 245 break; |
| 246 connection->SetWebSocket(websocket.Pass()); |
| 247 read_buf->DidConsume(pos); |
152 delegate_->OnWebSocketRequest(connection->id(), request); | 248 delegate_->OnWebSocketRequest(connection->id(), request); |
153 connection->Shift(pos); | |
154 continue; | 249 continue; |
155 } | 250 } |
156 | 251 |
157 const char kContentLength[] = "content-length"; | 252 const char kContentLength[] = "content-length"; |
158 if (request.headers.count(kContentLength)) { | 253 if (request.headers.count(kContentLength) > 0) { |
159 size_t content_length = 0; | 254 size_t content_length = 0; |
160 const size_t kMaxBodySize = 100 << 20; | 255 const size_t kMaxBodySize = 100 << 20; |
161 if (!base::StringToSizeT(request.GetHeaderValue(kContentLength), | 256 if (!base::StringToSizeT(request.GetHeaderValue(kContentLength), |
162 &content_length) || | 257 &content_length) || |
163 content_length > kMaxBodySize) { | 258 content_length > kMaxBodySize) { |
164 connection->Send(HttpServerResponseInfo::CreateFor500( | 259 SendResponse(connection->id(), |
165 "request content-length too big or unknown: " + | 260 HttpServerResponseInfo::CreateFor500( |
166 request.GetHeaderValue(kContentLength))); | 261 "request content-length too big or unknown: " + |
167 DidClose(socket); | 262 request.GetHeaderValue(kContentLength))); |
| 263 Close(connection->id()); |
168 break; | 264 break; |
169 } | 265 } |
170 | 266 |
171 if (connection->recv_data_.length() - pos < content_length) | 267 if (read_buf->GetUnconsumedSize() - pos < content_length) |
172 break; // Not enough data was received yet. | 268 break; // Not enough data was received yet. |
173 request.data = connection->recv_data_.substr(pos, content_length); | 269 request.data.assign(read_buf->data() + pos, content_length); |
174 pos += content_length; | 270 pos += content_length; |
175 } | 271 } |
176 | 272 |
| 273 read_buf->DidConsume(pos); |
177 delegate_->OnHttpRequest(connection->id(), request); | 274 delegate_->OnHttpRequest(connection->id(), request); |
178 connection->Shift(pos); | 275 } |
| 276 |
| 277 return OK; |
| 278 } |
| 279 |
| 280 void HttpServer::DoWriteLoop(HttpConnection* connection) { |
| 281 int rv = OK; |
| 282 HttpConnection::PendingWriteIOBuffer* write_buf = connection->write_buf(); |
| 283 while (rv == OK && write_buf->GetSizeToWrite() > 0) { |
| 284 rv = connection->socket()->Write( |
| 285 write_buf, |
| 286 write_buf->GetSizeToWrite(), |
| 287 base::Bind(&HttpServer::OnWriteCompleted, |
| 288 base::Unretained(this), connection->id())); |
| 289 if (rv == ERR_IO_PENDING || rv == OK) |
| 290 return; |
| 291 rv = DidWrite(connection, rv); |
179 } | 292 } |
180 } | 293 } |
181 | 294 |
182 void HttpServer::DidClose(StreamListenSocket* socket) { | 295 void HttpServer::OnWriteCompleted(int connection_id, int rv) { |
183 HttpConnection* connection = FindConnection(socket); | 296 HttpConnection* connection = FindConnection(connection_id); |
184 DCHECK(connection != NULL); | 297 if (!connection) // It might be closed right before by read error. |
185 id_to_connection_.erase(connection->id()); | 298 return; |
186 socket_to_connection_.erase(connection->socket_.get()); | 299 |
187 delete connection; | 300 if (DidWrite(connection, rv) == OK) |
| 301 DoWriteLoop(connection); |
188 } | 302 } |
189 | 303 |
190 HttpServer::~HttpServer() { | 304 int HttpServer::DidWrite(HttpConnection* connection, int rv) { |
191 STLDeleteContainerPairSecondPointers( | 305 if (rv < 0) { |
192 id_to_connection_.begin(), id_to_connection_.end()); | 306 Close(connection->id()); |
| 307 return rv; |
| 308 } |
| 309 |
| 310 connection->write_buf()->DidConsume(rv); |
| 311 return OK; |
193 } | 312 } |
194 | 313 |
| 314 namespace { |
| 315 |
195 // | 316 // |
196 // HTTP Request Parser | 317 // HTTP Request Parser |
197 // This HTTP request parser uses a simple state machine to quickly parse | 318 // This HTTP request parser uses a simple state machine to quickly parse |
198 // through the headers. The parser is not 100% complete, as it is designed | 319 // through the headers. The parser is not 100% complete, as it is designed |
199 // for use in this simple test driver. | 320 // for use in this simple test driver. |
200 // | 321 // |
201 // Known issues: | 322 // Known issues: |
202 // - does not handle whitespace on first HTTP line correctly. Expects | 323 // - does not handle whitespace on first HTTP line correctly. Expects |
203 // a single space between the method/url and url/protocol. | 324 // a single space between the method/url and url/protocol. |
204 | 325 |
(...skipping 43 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
248 case '\r': | 369 case '\r': |
249 return INPUT_CR; | 370 return INPUT_CR; |
250 case '\n': | 371 case '\n': |
251 return INPUT_LF; | 372 return INPUT_LF; |
252 case ':': | 373 case ':': |
253 return INPUT_COLON; | 374 return INPUT_COLON; |
254 } | 375 } |
255 return INPUT_DEFAULT; | 376 return INPUT_DEFAULT; |
256 } | 377 } |
257 | 378 |
258 bool HttpServer::ParseHeaders(HttpConnection* connection, | 379 } // namespace |
| 380 |
| 381 bool HttpServer::ParseHeaders(const char* data, |
| 382 size_t data_len, |
259 HttpServerRequestInfo* info, | 383 HttpServerRequestInfo* info, |
260 size_t* ppos) { | 384 size_t* ppos) { |
261 size_t& pos = *ppos; | 385 size_t& pos = *ppos; |
262 size_t data_len = connection->recv_data_.length(); | |
263 int state = ST_METHOD; | 386 int state = ST_METHOD; |
264 std::string buffer; | 387 std::string buffer; |
265 std::string header_name; | 388 std::string header_name; |
266 std::string header_value; | 389 std::string header_value; |
267 while (pos < data_len) { | 390 while (pos < data_len) { |
268 char ch = connection->recv_data_[pos++]; | 391 char ch = data[pos++]; |
269 int input = charToInput(ch); | 392 int input = charToInput(ch); |
270 int next_state = parser_state[state][input]; | 393 int next_state = parser_state[state][input]; |
271 | 394 |
272 bool transition = (next_state != state); | 395 bool transition = (next_state != state); |
273 HttpServerRequestInfo::HeadersMap::iterator it; | 396 HttpServerRequestInfo::HeadersMap::iterator it; |
274 if (transition) { | 397 if (transition) { |
275 // Do any actions based on state transitions. | 398 // Do any actions based on state transitions. |
276 switch (state) { | 399 switch (state) { |
277 case ST_METHOD: | 400 case ST_METHOD: |
278 info->method = buffer; | 401 info->method = buffer; |
(...skipping 51 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
330 return false; | 453 return false; |
331 } | 454 } |
332 | 455 |
333 HttpConnection* HttpServer::FindConnection(int connection_id) { | 456 HttpConnection* HttpServer::FindConnection(int connection_id) { |
334 IdToConnectionMap::iterator it = id_to_connection_.find(connection_id); | 457 IdToConnectionMap::iterator it = id_to_connection_.find(connection_id); |
335 if (it == id_to_connection_.end()) | 458 if (it == id_to_connection_.end()) |
336 return NULL; | 459 return NULL; |
337 return it->second; | 460 return it->second; |
338 } | 461 } |
339 | 462 |
340 HttpConnection* HttpServer::FindConnection(StreamListenSocket* socket) { | |
341 SocketToConnectionMap::iterator it = socket_to_connection_.find(socket); | |
342 if (it == socket_to_connection_.end()) | |
343 return NULL; | |
344 return it->second; | |
345 } | |
346 | |
347 } // namespace net | 463 } // namespace net |
OLD | NEW |