Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(256)

Side by Side Diff: net/server/http_server.cc

Issue 296053012: Replace StreamListenSocket with StreamSocket in HttpServer. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Redo changes reverted with unknown reason. Created 6 years, 4 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
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 HttpServer::HttpServer(scoped_ptr<ServerSocket> server_socket,
25 HttpServer::Delegate* delegate) 27 HttpServer::Delegate* delegate)
26 : delegate_(delegate), 28 : server_socket_(server_socket.Pass()),
27 server_(factory.CreateAndListen(this)) { 29 delegate_(delegate),
30 last_id_(0) {
31 DCHECK(server_socket_);
32 DoAcceptLoop();
33 }
34
35 HttpServer::~HttpServer() {
36 STLDeleteContainerPairSecondPointers(
37 id_to_connection_.begin(), id_to_connection_.end());
28 } 38 }
29 39
30 void HttpServer::AcceptWebSocket( 40 void HttpServer::AcceptWebSocket(
31 int connection_id, 41 int connection_id,
32 const HttpServerRequestInfo& request) { 42 const HttpServerRequestInfo& request) {
33 HttpConnection* connection = FindConnection(connection_id); 43 HttpConnection* connection = FindConnection(connection_id);
34 if (connection == NULL) 44 if (connection == NULL)
35 return; 45 return;
36 46 DCHECK(connection->web_socket());
37 DCHECK(connection->web_socket_.get()); 47 connection->web_socket()->Accept(request);
38 connection->web_socket_->Accept(request);
39 } 48 }
40 49
41 void HttpServer::SendOverWebSocket(int connection_id, 50 void HttpServer::SendOverWebSocket(int connection_id,
42 const std::string& data) { 51 const std::string& data) {
43 HttpConnection* connection = FindConnection(connection_id); 52 HttpConnection* connection = FindConnection(connection_id);
44 if (connection == NULL) 53 if (connection == NULL)
45 return; 54 return;
46 DCHECK(connection->web_socket_.get()); 55 DCHECK(connection->web_socket());
47 connection->web_socket_->Send(data); 56 connection->web_socket()->Send(data);
48 } 57 }
49 58
50 void HttpServer::SendRaw(int connection_id, const std::string& data) { 59 void HttpServer::SendRaw(int connection_id, const std::string& data) {
51 HttpConnection* connection = FindConnection(connection_id); 60 HttpConnection* connection = FindConnection(connection_id);
52 if (connection == NULL) 61 if (connection == NULL)
53 return; 62 return;
54 connection->Send(data); 63
64 bool writing_in_progress = !connection->write_buf()->IsEmpty();
65 if (connection->write_buf()->Append(data) && !writing_in_progress)
66 DoWriteLoop(connection);
55 } 67 }
56 68
57 void HttpServer::SendResponse(int connection_id, 69 void HttpServer::SendResponse(int connection_id,
58 const HttpServerResponseInfo& response) { 70 const HttpServerResponseInfo& response) {
59 HttpConnection* connection = FindConnection(connection_id); 71 SendRaw(connection_id, response.Serialize());
60 if (connection == NULL)
61 return;
62 connection->Send(response);
63 } 72 }
64 73
65 void HttpServer::Send(int connection_id, 74 void HttpServer::Send(int connection_id,
66 HttpStatusCode status_code, 75 HttpStatusCode status_code,
67 const std::string& data, 76 const std::string& data,
68 const std::string& content_type) { 77 const std::string& content_type) {
69 HttpServerResponseInfo response(status_code); 78 HttpServerResponseInfo response(status_code);
70 response.SetBody(data, content_type); 79 response.SetContentHeaders(data.size(), content_type);
71 SendResponse(connection_id, response); 80 SendResponse(connection_id, response);
81 SendRaw(connection_id, data);
72 } 82 }
73 83
74 void HttpServer::Send200(int connection_id, 84 void HttpServer::Send200(int connection_id,
75 const std::string& data, 85 const std::string& data,
76 const std::string& content_type) { 86 const std::string& content_type) {
77 Send(connection_id, HTTP_OK, data, content_type); 87 Send(connection_id, HTTP_OK, data, content_type);
78 } 88 }
79 89
80 void HttpServer::Send404(int connection_id) { 90 void HttpServer::Send404(int connection_id) {
81 SendResponse(connection_id, HttpServerResponseInfo::CreateFor404()); 91 SendResponse(connection_id, HttpServerResponseInfo::CreateFor404());
82 } 92 }
83 93
84 void HttpServer::Send500(int connection_id, const std::string& message) { 94 void HttpServer::Send500(int connection_id, const std::string& message) {
85 SendResponse(connection_id, HttpServerResponseInfo::CreateFor500(message)); 95 SendResponse(connection_id, HttpServerResponseInfo::CreateFor500(message));
86 } 96 }
87 97
88 void HttpServer::Close(int connection_id) { 98 void HttpServer::Close(int connection_id) {
89 HttpConnection* connection = FindConnection(connection_id); 99 HttpConnection* connection = FindConnection(connection_id);
90 if (connection == NULL) 100 if (connection == NULL)
91 return; 101 return;
92 102
93 // Initiating close from server-side does not lead to the DidClose call. 103 id_to_connection_.erase(connection->id());
94 // Do it manually here. 104 delegate_->OnClose(connection_id);
95 DidClose(connection->socket_.get()); 105
106 // The call stack might have callbacks which still have the pointer of
107 // connection. Instead of referencing connection with ID all the time,
108 // destroys the connection in next run loop to make sure any pending
109 // callbacks in the call stack return.
110 base::MessageLoopProxy::current()->DeleteSoon(FROM_HERE, connection);
96 } 111 }
97 112
98 int HttpServer::GetLocalAddress(IPEndPoint* address) { 113 int HttpServer::GetLocalAddress(IPEndPoint* address) {
99 if (!server_) 114 return server_socket_->GetLocalAddress(address);
100 return ERR_SOCKET_NOT_CONNECTED;
101 return server_->GetLocalAddress(address);
102 } 115 }
103 116
104 void HttpServer::DidAccept(StreamListenSocket* server, 117 void HttpServer::SetReceiveBufferSize(int connection_id, int32 size) {
105 scoped_ptr<StreamListenSocket> socket) { 118 HttpConnection* connection = FindConnection(connection_id);
106 HttpConnection* connection = new HttpConnection(this, socket.Pass()); 119 DCHECK(connection);
107 id_to_connection_[connection->id()] = connection; 120 connection->read_buf()->set_capacity_limit(size);
108 // TODO(szym): Fix socket access. Make HttpConnection the Delegate.
109 socket_to_connection_[connection->socket_.get()] = connection;
110 } 121 }
111 122
112 void HttpServer::DidRead(StreamListenSocket* socket, 123 void HttpServer::SetSendBufferSize(int connection_id, int32 size) {
113 const char* data, 124 HttpConnection* connection = FindConnection(connection_id);
114 int len) { 125 DCHECK(connection);
115 HttpConnection* connection = FindConnection(socket); 126 connection->write_buf()->set_total_size_limit(size);
116 DCHECK(connection != NULL); 127 }
117 if (connection == NULL) 128
129 void HttpServer::DoAcceptLoop() {
130 int rv;
131 do {
132 rv = server_socket_->Accept(&accepted_socket_,
133 base::Bind(&HttpServer::OnAcceptCompleted,
134 base::Unretained(this)));
135 if (rv == ERR_IO_PENDING)
136 return;
137 rv = HandleAcceptResult(rv);
138 } while (rv == OK);
139 }
140
141 void HttpServer::OnAcceptCompleted(int rv) {
142 if (HandleAcceptResult(rv) == OK)
143 DoAcceptLoop();
144 }
145
146 int HttpServer::HandleAcceptResult(int rv) {
147 if (rv < 0) {
148 LOG(ERROR) << "Accept error: rv=" << rv;
149 return rv;
150 }
151
152 HttpConnection* connection =
153 new HttpConnection(++last_id_, accepted_socket_.Pass());
154 id_to_connection_[connection->id()] = connection;
155 DoReadLoop(connection);
156 return OK;
157 }
158
159 void HttpServer::DoReadLoop(HttpConnection* connection) {
160 int rv;
161 do {
162 HttpConnection::ReadIOBuffer* read_buf = connection->read_buf();
163 // Increases read buffer size if necessary.
164 if (read_buf->RemainingCapacity() == 0 && !read_buf->IncreaseCapacity()) {
165 Close(connection->id());
166 return;
167 }
168
169 rv = connection->socket()->Read(
170 read_buf,
171 read_buf->RemainingCapacity(),
172 base::Bind(&HttpServer::OnReadCompleted,
173 base::Unretained(this), connection->id()));
174 if (rv == ERR_IO_PENDING)
175 return;
176 rv = HandleReadResult(connection, rv);
177 } while (rv == OK);
178 }
179
180 void HttpServer::OnReadCompleted(int connection_id, int rv) {
181 HttpConnection* connection = FindConnection(connection_id);
182 if (!connection) // It might be closed right before by write error.
mmenke 2014/08/08 18:35:44 The connection does have a pointer, actually. Or
byungchul 2014/08/12 21:36:55 Changed to weak ptr.
118 return; 183 return;
119 184
120 connection->recv_data_.append(data, len); 185 if (HandleReadResult(connection, rv) == OK)
121 while (connection->recv_data_.length()) { 186 DoReadLoop(connection);
122 if (connection->web_socket_.get()) { 187 }
188
189 int HttpServer::HandleReadResult(HttpConnection* connection, int rv) {
190 if (rv <= 0) {
191 Close(connection->id());
192 return rv == 0 ? ERR_CONNECTION_CLOSED : rv;
193 }
194
195 HttpConnection::ReadIOBuffer* read_buf = connection->read_buf();
196 read_buf->DidRead(rv);
197
198 // Handles http requests or websocket messages.
199 while (read_buf->GetSize() > 0) {
200 if (connection->web_socket()) {
123 std::string message; 201 std::string message;
124 WebSocket::ParseResult result = connection->web_socket_->Read(&message); 202 WebSocket::ParseResult result = connection->web_socket()->Read(&message);
125 if (result == WebSocket::FRAME_INCOMPLETE) 203 if (result == WebSocket::FRAME_INCOMPLETE)
126 break; 204 break;
127 205
128 if (result == WebSocket::FRAME_CLOSE || 206 if (result == WebSocket::FRAME_CLOSE ||
129 result == WebSocket::FRAME_ERROR) { 207 result == WebSocket::FRAME_ERROR) {
130 Close(connection->id()); 208 Close(connection->id());
131 break; 209 break;
132 } 210 }
133 delegate_->OnWebSocketMessage(connection->id(), message); 211 delegate_->OnWebSocketMessage(connection->id(), message);
134 continue; 212 continue;
135 } 213 }
136 214
137 HttpServerRequestInfo request; 215 HttpServerRequestInfo request;
138 size_t pos = 0; 216 size_t pos = 0;
139 if (!ParseHeaders(connection, &request, &pos)) 217 if (!ParseHeaders(read_buf->StartOfBuffer(), read_buf->GetSize(),
218 &request, &pos))
140 break; 219 break;
141 220
142 // Sets peer address if exists. 221 // Sets peer address if exists.
143 socket->GetPeerAddress(&request.peer); 222 connection->socket()->GetPeerAddress(&request.peer);
144 223
145 if (request.HasHeaderValue("connection", "upgrade")) { 224 if (request.HasHeaderValue("connection", "upgrade")) {
146 connection->web_socket_.reset(WebSocket::CreateWebSocket(connection, 225 scoped_ptr<WebSocket> websocket(
147 request, 226 WebSocket::CreateWebSocket(this, connection, request, &pos));
148 &pos)); 227 if (!websocket) // Not enough data was received.
149
150 if (!connection->web_socket_.get()) // Not enough data was received.
151 break; 228 break;
229 connection->SetWebSocket(websocket.Pass());
230 read_buf->DidConsume(pos);
152 delegate_->OnWebSocketRequest(connection->id(), request); 231 delegate_->OnWebSocketRequest(connection->id(), request);
153 connection->Shift(pos);
154 continue; 232 continue;
155 } 233 }
156 234
157 const char kContentLength[] = "content-length"; 235 const char kContentLength[] = "content-length";
158 if (request.headers.count(kContentLength)) { 236 if (request.headers.count(kContentLength) > 0) {
159 size_t content_length = 0; 237 size_t content_length = 0;
160 const size_t kMaxBodySize = 100 << 20; 238 const size_t kMaxBodySize = 100 << 20;
161 if (!base::StringToSizeT(request.GetHeaderValue(kContentLength), 239 if (!base::StringToSizeT(request.GetHeaderValue(kContentLength),
162 &content_length) || 240 &content_length) ||
163 content_length > kMaxBodySize) { 241 content_length > kMaxBodySize) {
164 connection->Send(HttpServerResponseInfo::CreateFor500( 242 SendResponse(connection->id(),
165 "request content-length too big or unknown: " + 243 HttpServerResponseInfo::CreateFor500(
166 request.GetHeaderValue(kContentLength))); 244 "request content-length too big or unknown: " +
167 DidClose(socket); 245 request.GetHeaderValue(kContentLength)));
246 Close(connection->id());
168 break; 247 break;
169 } 248 }
170 249
171 if (connection->recv_data_.length() - pos < content_length) 250 if (read_buf->GetSize() - pos < content_length)
172 break; // Not enough data was received yet. 251 break; // Not enough data was received yet.
173 request.data = connection->recv_data_.substr(pos, content_length); 252 request.data.assign(read_buf->StartOfBuffer() + pos, content_length);
174 pos += content_length; 253 pos += content_length;
175 } 254 }
176 255
256 read_buf->DidConsume(pos);
177 delegate_->OnHttpRequest(connection->id(), request); 257 delegate_->OnHttpRequest(connection->id(), request);
178 connection->Shift(pos); 258 }
259
260 return OK;
261 }
262
263 void HttpServer::DoWriteLoop(HttpConnection* connection) {
264 int rv = OK;
265 HttpConnection::PendingWriteIOBuffer* write_buf = connection->write_buf();
266 while (rv == OK && write_buf->GetSizeToWrite() > 0) {
267 rv = connection->socket()->Write(
268 write_buf,
269 write_buf->GetSizeToWrite(),
270 base::Bind(&HttpServer::OnWriteCompleted,
271 base::Unretained(this), connection->id()));
272 if (rv == ERR_IO_PENDING || rv == OK)
273 return;
274 rv = HandleWriteResult(connection, rv);
179 } 275 }
180 } 276 }
181 277
182 void HttpServer::DidClose(StreamListenSocket* socket) { 278 void HttpServer::OnWriteCompleted(int connection_id, int rv) {
183 HttpConnection* connection = FindConnection(socket); 279 HttpConnection* connection = FindConnection(connection_id);
184 DCHECK(connection != NULL); 280 if (!connection) // It might be closed right before by read error.
185 id_to_connection_.erase(connection->id()); 281 return;
186 socket_to_connection_.erase(connection->socket_.get()); 282
187 delete connection; 283 if (HandleWriteResult(connection, rv) == OK)
284 DoWriteLoop(connection);
188 } 285 }
189 286
190 HttpServer::~HttpServer() { 287 int HttpServer::HandleWriteResult(HttpConnection* connection, int rv) {
191 STLDeleteContainerPairSecondPointers( 288 if (rv < 0) {
192 id_to_connection_.begin(), id_to_connection_.end()); 289 Close(connection->id());
290 return rv;
291 }
292
293 connection->write_buf()->DidConsume(rv);
294 return OK;
193 } 295 }
194 296
297 namespace {
298
195 // 299 //
196 // HTTP Request Parser 300 // HTTP Request Parser
197 // This HTTP request parser uses a simple state machine to quickly parse 301 // 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 302 // through the headers. The parser is not 100% complete, as it is designed
199 // for use in this simple test driver. 303 // for use in this simple test driver.
200 // 304 //
201 // Known issues: 305 // Known issues:
202 // - does not handle whitespace on first HTTP line correctly. Expects 306 // - does not handle whitespace on first HTTP line correctly. Expects
203 // a single space between the method/url and url/protocol. 307 // a single space between the method/url and url/protocol.
204 308
(...skipping 43 matching lines...) Expand 10 before | Expand all | Expand 10 after
248 case '\r': 352 case '\r':
249 return INPUT_CR; 353 return INPUT_CR;
250 case '\n': 354 case '\n':
251 return INPUT_LF; 355 return INPUT_LF;
252 case ':': 356 case ':':
253 return INPUT_COLON; 357 return INPUT_COLON;
254 } 358 }
255 return INPUT_DEFAULT; 359 return INPUT_DEFAULT;
256 } 360 }
257 361
258 bool HttpServer::ParseHeaders(HttpConnection* connection, 362 } // namespace
363
364 bool HttpServer::ParseHeaders(const char* data,
365 size_t data_len,
259 HttpServerRequestInfo* info, 366 HttpServerRequestInfo* info,
260 size_t* ppos) { 367 size_t* ppos) {
261 size_t& pos = *ppos; 368 size_t& pos = *ppos;
262 size_t data_len = connection->recv_data_.length();
263 int state = ST_METHOD; 369 int state = ST_METHOD;
264 std::string buffer; 370 std::string buffer;
265 std::string header_name; 371 std::string header_name;
266 std::string header_value; 372 std::string header_value;
267 while (pos < data_len) { 373 while (pos < data_len) {
268 char ch = connection->recv_data_[pos++]; 374 char ch = data[pos++];
269 int input = charToInput(ch); 375 int input = charToInput(ch);
270 int next_state = parser_state[state][input]; 376 int next_state = parser_state[state][input];
271 377
272 bool transition = (next_state != state); 378 bool transition = (next_state != state);
273 HttpServerRequestInfo::HeadersMap::iterator it; 379 HttpServerRequestInfo::HeadersMap::iterator it;
274 if (transition) { 380 if (transition) {
275 // Do any actions based on state transitions. 381 // Do any actions based on state transitions.
276 switch (state) { 382 switch (state) {
277 case ST_METHOD: 383 case ST_METHOD:
278 info->method = buffer; 384 info->method = buffer;
(...skipping 51 matching lines...) Expand 10 before | Expand all | Expand 10 after
330 return false; 436 return false;
331 } 437 }
332 438
333 HttpConnection* HttpServer::FindConnection(int connection_id) { 439 HttpConnection* HttpServer::FindConnection(int connection_id) {
334 IdToConnectionMap::iterator it = id_to_connection_.find(connection_id); 440 IdToConnectionMap::iterator it = id_to_connection_.find(connection_id);
335 if (it == id_to_connection_.end()) 441 if (it == id_to_connection_.end())
336 return NULL; 442 return NULL;
337 return it->second; 443 return it->second;
338 } 444 }
339 445
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 446 } // namespace net
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698