xref: /aosp_15_r20/external/cronet/net/server/http_server.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "net/server/http_server.h"
6 
7 #include <string_view>
8 #include <utility>
9 
10 #include "base/compiler_specific.h"
11 #include "base/functional/bind.h"
12 #include "base/location.h"
13 #include "base/logging.h"
14 #include "base/strings/string_number_conversions.h"
15 #include "base/strings/string_util.h"
16 #include "base/sys_byteorder.h"
17 #include "base/task/single_thread_task_runner.h"
18 #include "build/build_config.h"
19 #include "net/base/net_errors.h"
20 #include "net/server/http_connection.h"
21 #include "net/server/http_server_request_info.h"
22 #include "net/server/http_server_response_info.h"
23 #include "net/server/web_socket.h"
24 #include "net/socket/server_socket.h"
25 #include "net/socket/stream_socket.h"
26 #include "net/socket/tcp_server_socket.h"
27 
28 namespace net {
29 
30 namespace {
31 
32 constexpr NetworkTrafficAnnotationTag
33     kHttpServerErrorResponseTrafficAnnotation =
34         DefineNetworkTrafficAnnotation("http_server_error_response",
35                                        R"(
36       semantics {
37         sender: "HTTP Server"
38         description: "Error response from the built-in HTTP server."
39         trigger: "Sending a request to the HTTP server that it can't handle."
40         data: "A 500 error code."
41         destination: OTHER
42         destination_other: "Any destination the consumer selects."
43       }
44       policy {
45         cookies_allowed: NO
46         setting:
47           "This request cannot be disabled in settings. However it will never "
48           "be made unless user activates an HTTP server."
49         policy_exception_justification:
50           "Not implemented, not used if HTTP Server is not activated."
51       })");
52 
53 }  // namespace
54 
HttpServer(std::unique_ptr<ServerSocket> server_socket,HttpServer::Delegate * delegate)55 HttpServer::HttpServer(std::unique_ptr<ServerSocket> server_socket,
56                        HttpServer::Delegate* delegate)
57     : server_socket_(std::move(server_socket)), delegate_(delegate) {
58   DCHECK(server_socket_);
59   // Start accepting connections in next run loop in case when delegate is not
60   // ready to get callbacks.
61   base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
62       FROM_HERE, base::BindOnce(&HttpServer::DoAcceptLoop,
63                                 weak_ptr_factory_.GetWeakPtr()));
64 }
65 
66 HttpServer::~HttpServer() = default;
67 
68 void HttpServer::AcceptWebSocket(
69     int connection_id,
70     const HttpServerRequestInfo& request,
71     NetworkTrafficAnnotationTag traffic_annotation) {
72   HttpConnection* connection = FindConnection(connection_id);
73   if (connection == nullptr)
74     return;
75   DCHECK(connection->web_socket());
76   connection->web_socket()->Accept(request, traffic_annotation);
77 }
78 
79 void HttpServer::SendOverWebSocket(
80     int connection_id,
81     std::string_view data,
82     NetworkTrafficAnnotationTag traffic_annotation) {
83   HttpConnection* connection = FindConnection(connection_id);
84   if (connection == nullptr)
85     return;
86   DCHECK(connection->web_socket());
87   connection->web_socket()->Send(
88       data, WebSocketFrameHeader::OpCodeEnum::kOpCodeText, traffic_annotation);
89 }
90 
91 void HttpServer::SendRaw(int connection_id,
92                          const std::string& data,
93                          NetworkTrafficAnnotationTag traffic_annotation) {
94   HttpConnection* connection = FindConnection(connection_id);
95   if (connection == nullptr)
96     return;
97 
98   bool writing_in_progress = !connection->write_buf()->IsEmpty();
99   if (connection->write_buf()->Append(data) && !writing_in_progress)
100     DoWriteLoop(connection, traffic_annotation);
101 }
102 
103 void HttpServer::SendResponse(int connection_id,
104                               const HttpServerResponseInfo& response,
105                               NetworkTrafficAnnotationTag traffic_annotation) {
106   SendRaw(connection_id, response.Serialize(), traffic_annotation);
107 }
108 
109 void HttpServer::Send(int connection_id,
110                       HttpStatusCode status_code,
111                       const std::string& data,
112                       const std::string& content_type,
113                       NetworkTrafficAnnotationTag traffic_annotation) {
114   HttpServerResponseInfo response(status_code);
115   response.SetContentHeaders(data.size(), content_type);
116   SendResponse(connection_id, response, traffic_annotation);
117   SendRaw(connection_id, data, traffic_annotation);
118 }
119 
120 void HttpServer::Send200(int connection_id,
121                          const std::string& data,
122                          const std::string& content_type,
123                          NetworkTrafficAnnotationTag traffic_annotation) {
124   Send(connection_id, HTTP_OK, data, content_type, traffic_annotation);
125 }
126 
127 void HttpServer::Send404(int connection_id,
128                          NetworkTrafficAnnotationTag traffic_annotation) {
129   SendResponse(connection_id, HttpServerResponseInfo::CreateFor404(),
130                traffic_annotation);
131 }
132 
133 void HttpServer::Send500(int connection_id,
134                          const std::string& message,
135                          NetworkTrafficAnnotationTag traffic_annotation) {
136   SendResponse(connection_id, HttpServerResponseInfo::CreateFor500(message),
137                traffic_annotation);
138 }
139 
140 void HttpServer::Close(int connection_id) {
141   auto it = id_to_connection_.find(connection_id);
142   if (it == id_to_connection_.end())
143     return;
144 
145   std::unique_ptr<HttpConnection> connection = std::move(it->second);
146   id_to_connection_.erase(it);
147   delegate_->OnClose(connection_id);
148 
149   // The call stack might have callbacks which still have the pointer of
150   // connection. Instead of referencing connection with ID all the time,
151   // destroys the connection in next run loop to make sure any pending
152   // callbacks in the call stack return.
153   base::SingleThreadTaskRunner::GetCurrentDefault()->DeleteSoon(
154       FROM_HERE, connection.release());
155 }
156 
157 int HttpServer::GetLocalAddress(IPEndPoint* address) {
158   return server_socket_->GetLocalAddress(address);
159 }
160 
161 void HttpServer::SetReceiveBufferSize(int connection_id, int32_t size) {
162   HttpConnection* connection = FindConnection(connection_id);
163   if (connection)
164     connection->read_buf()->set_max_buffer_size(size);
165 }
166 
167 void HttpServer::SetSendBufferSize(int connection_id, int32_t size) {
168   HttpConnection* connection = FindConnection(connection_id);
169   if (connection)
170     connection->write_buf()->set_max_buffer_size(size);
171 }
172 
173 void HttpServer::DoAcceptLoop() {
174   int rv;
175   do {
176     rv = server_socket_->Accept(&accepted_socket_,
177                                 base::BindOnce(&HttpServer::OnAcceptCompleted,
178                                                weak_ptr_factory_.GetWeakPtr()));
179     if (rv == ERR_IO_PENDING)
180       return;
181     rv = HandleAcceptResult(rv);
182   } while (rv == OK);
183 }
184 
185 void HttpServer::OnAcceptCompleted(int rv) {
186   if (HandleAcceptResult(rv) == OK)
187     DoAcceptLoop();
188 }
189 
190 int HttpServer::HandleAcceptResult(int rv) {
191   if (rv < 0) {
192     LOG(ERROR) << "Accept error: rv=" << rv;
193     return rv;
194   }
195 
196   std::unique_ptr<HttpConnection> connection_ptr =
197       std::make_unique<HttpConnection>(++last_id_, std::move(accepted_socket_));
198   HttpConnection* connection = connection_ptr.get();
199   id_to_connection_[connection->id()] = std::move(connection_ptr);
200   delegate_->OnConnect(connection->id());
201   if (!HasClosedConnection(connection))
202     DoReadLoop(connection);
203   return OK;
204 }
205 
206 void HttpServer::DoReadLoop(HttpConnection* connection) {
207   int rv;
208   do {
209     HttpConnection::ReadIOBuffer* read_buf = connection->read_buf();
210     // Increases read buffer size if necessary.
211     if (read_buf->RemainingCapacity() == 0 && !read_buf->IncreaseCapacity()) {
212       Close(connection->id());
213       return;
214     }
215 
216     rv = connection->socket()->Read(
217         read_buf, read_buf->RemainingCapacity(),
218         base::BindOnce(&HttpServer::OnReadCompleted,
219                        weak_ptr_factory_.GetWeakPtr(), connection->id()));
220     if (rv == ERR_IO_PENDING)
221       return;
222     rv = HandleReadResult(connection, rv);
223   } while (rv == OK);
224 }
225 
226 void HttpServer::OnReadCompleted(int connection_id, int rv) {
227   HttpConnection* connection = FindConnection(connection_id);
228   if (!connection)  // It might be closed right before by write error.
229     return;
230 
231   if (HandleReadResult(connection, rv) == OK)
232     DoReadLoop(connection);
233 }
234 
235 int HttpServer::HandleReadResult(HttpConnection* connection, int rv) {
236   if (rv <= 0) {
237     Close(connection->id());
238     return rv == 0 ? ERR_CONNECTION_CLOSED : rv;
239   }
240 
241   HttpConnection::ReadIOBuffer* read_buf = connection->read_buf();
242   read_buf->DidRead(rv);
243 
244   // Handles http requests or websocket messages.
245   while (read_buf->GetSize() > 0) {
246     if (connection->web_socket()) {
247       std::string message;
248       WebSocket::ParseResult result = connection->web_socket()->Read(&message);
249       if (result == WebSocket::FRAME_INCOMPLETE)
250         break;
251 
252       if (result == WebSocket::FRAME_CLOSE ||
253           result == WebSocket::FRAME_ERROR) {
254         Close(connection->id());
255         return ERR_CONNECTION_CLOSED;
256       }
257       if (result == WebSocket::FRAME_OK_FINAL)
258         delegate_->OnWebSocketMessage(connection->id(), std::move(message));
259       if (HasClosedConnection(connection))
260         return ERR_CONNECTION_CLOSED;
261       continue;
262     }
263 
264     HttpServerRequestInfo request;
265     size_t pos = 0;
266     if (!ParseHeaders(read_buf->StartOfBuffer(), read_buf->GetSize(),
267                       &request, &pos)) {
268       // An error has occured. Close the connection.
269       Close(connection->id());
270       return ERR_CONNECTION_CLOSED;
271     } else if (!pos) {
272       // If pos is 0, all the data in read_buf has been consumed, but the
273       // headers have not been fully parsed yet. Continue parsing when more data
274       // rolls in.
275       break;
276     }
277 
278     // Sets peer address if exists.
279     connection->socket()->GetPeerAddress(&request.peer);
280 
281     if (request.HasHeaderValue("connection", "upgrade") &&
282         request.HasHeaderValue("upgrade", "websocket")) {
283       connection->SetWebSocket(std::make_unique<WebSocket>(this, connection));
284       read_buf->DidConsume(pos);
285       delegate_->OnWebSocketRequest(connection->id(), request);
286       if (HasClosedConnection(connection))
287         return ERR_CONNECTION_CLOSED;
288       continue;
289     }
290 
291     const char kContentLength[] = "content-length";
292     if (request.headers.count(kContentLength) > 0) {
293       size_t content_length = 0;
294       const size_t kMaxBodySize = 100 << 20;
295       if (!base::StringToSizeT(request.GetHeaderValue(kContentLength),
296                                &content_length) ||
297           content_length > kMaxBodySize) {
298         SendResponse(connection->id(),
299                      HttpServerResponseInfo::CreateFor500(
300                          "request content-length too big or unknown."),
301                      kHttpServerErrorResponseTrafficAnnotation);
302         Close(connection->id());
303         return ERR_CONNECTION_CLOSED;
304       }
305 
306       if (read_buf->GetSize() - pos < content_length)
307         break;  // Not enough data was received yet.
308       request.data.assign(read_buf->StartOfBuffer() + pos, content_length);
309       pos += content_length;
310     }
311 
312     read_buf->DidConsume(pos);
313     delegate_->OnHttpRequest(connection->id(), request);
314     if (HasClosedConnection(connection))
315       return ERR_CONNECTION_CLOSED;
316   }
317 
318   return OK;
319 }
320 
321 void HttpServer::DoWriteLoop(HttpConnection* connection,
322                              NetworkTrafficAnnotationTag traffic_annotation) {
323   int rv = OK;
324   HttpConnection::QueuedWriteIOBuffer* write_buf = connection->write_buf();
325   while (rv == OK && write_buf->GetSizeToWrite() > 0) {
326     rv = connection->socket()->Write(
327         write_buf, write_buf->GetSizeToWrite(),
328         base::BindOnce(&HttpServer::OnWriteCompleted,
329                        weak_ptr_factory_.GetWeakPtr(), connection->id(),
330                        traffic_annotation),
331         traffic_annotation);
332     if (rv == ERR_IO_PENDING || rv == OK)
333       return;
334     rv = HandleWriteResult(connection, rv);
335   }
336 }
337 
338 void HttpServer::OnWriteCompleted(
339     int connection_id,
340     NetworkTrafficAnnotationTag traffic_annotation,
341     int rv) {
342   HttpConnection* connection = FindConnection(connection_id);
343   if (!connection)  // It might be closed right before by read error.
344     return;
345 
346   if (HandleWriteResult(connection, rv) == OK)
347     DoWriteLoop(connection, traffic_annotation);
348 }
349 
350 int HttpServer::HandleWriteResult(HttpConnection* connection, int rv) {
351   if (rv < 0) {
352     Close(connection->id());
353     return rv;
354   }
355 
356   connection->write_buf()->DidConsume(rv);
357   return OK;
358 }
359 
360 namespace {
361 
362 //
363 // HTTP Request Parser
364 // This HTTP request parser uses a simple state machine to quickly parse
365 // through the headers.  The parser is not 100% complete, as it is designed
366 // for use in this simple test driver.
367 //
368 // Known issues:
369 //   - does not handle whitespace on first HTTP line correctly.  Expects
370 //     a single space between the method/url and url/protocol.
371 
372 // Input character types.
373 enum header_parse_inputs {
374   INPUT_LWS,
375   INPUT_CR,
376   INPUT_LF,
377   INPUT_COLON,
378   INPUT_DEFAULT,
379   MAX_INPUTS,
380 };
381 
382 // Parser states.
383 enum header_parse_states {
384   ST_METHOD,     // Receiving the method
385   ST_URL,        // Receiving the URL
386   ST_PROTO,      // Receiving the protocol
387   ST_HEADER,     // Starting a Request Header
388   ST_NAME,       // Receiving a request header name
389   ST_SEPARATOR,  // Receiving the separator between header name and value
390   ST_VALUE,      // Receiving a request header value
391   ST_DONE,       // Parsing is complete and successful
392   ST_ERR,        // Parsing encountered invalid syntax.
393   MAX_STATES
394 };
395 
396 // State transition table
397 const int parser_state[MAX_STATES][MAX_INPUTS] = {
398     /* METHOD    */ {ST_URL, ST_ERR, ST_ERR, ST_ERR, ST_METHOD},
399     /* URL       */ {ST_PROTO, ST_ERR, ST_ERR, ST_URL, ST_URL},
400     /* PROTOCOL  */ {ST_ERR, ST_HEADER, ST_NAME, ST_ERR, ST_PROTO},
401     /* HEADER    */ {ST_ERR, ST_ERR, ST_NAME, ST_ERR, ST_ERR},
402     /* NAME      */ {ST_SEPARATOR, ST_DONE, ST_ERR, ST_VALUE, ST_NAME},
403     /* SEPARATOR */ {ST_SEPARATOR, ST_ERR, ST_ERR, ST_VALUE, ST_ERR},
404     /* VALUE     */ {ST_VALUE, ST_HEADER, ST_NAME, ST_VALUE, ST_VALUE},
405     /* DONE      */ {ST_DONE, ST_DONE, ST_DONE, ST_DONE, ST_DONE},
406     /* ERR       */ {ST_ERR, ST_ERR, ST_ERR, ST_ERR, ST_ERR}};
407 
408 // Convert an input character to the parser's input token.
409 int charToInput(char ch) {
410   switch (ch) {
411     case ' ':
412     case '\t':
413       return INPUT_LWS;
414     case '\r':
415       return INPUT_CR;
416     case '\n':
417       return INPUT_LF;
418     case ':':
419       return INPUT_COLON;
420   }
421   return INPUT_DEFAULT;
422 }
423 
424 }  // namespace
425 
ParseHeaders(const char * data,size_t data_len,HttpServerRequestInfo * info,size_t * ppos)426 bool HttpServer::ParseHeaders(const char* data,
427                               size_t data_len,
428                               HttpServerRequestInfo* info,
429                               size_t* ppos) {
430   size_t& pos = *ppos;
431   int state = ST_METHOD;
432   std::string buffer;
433   std::string header_name;
434   std::string header_value;
435   while (pos < data_len) {
436     char ch = data[pos++];
437     int input = charToInput(ch);
438     int next_state = parser_state[state][input];
439 
440     bool transition = (next_state != state);
441     HttpServerRequestInfo::HeadersMap::iterator it;
442     if (transition) {
443       // Do any actions based on state transitions.
444       switch (state) {
445         case ST_METHOD:
446           info->method = buffer;
447           buffer.clear();
448           break;
449         case ST_URL:
450           info->path = buffer;
451           buffer.clear();
452           break;
453         case ST_PROTO:
454           if (buffer != "HTTP/1.1") {
455             LOG(ERROR) << "Cannot handle request with protocol: " << buffer;
456             next_state = ST_ERR;
457           }
458           buffer.clear();
459           break;
460         case ST_NAME:
461           header_name = base::ToLowerASCII(buffer);
462           buffer.clear();
463           break;
464         case ST_VALUE:
465           base::TrimWhitespaceASCII(buffer, base::TRIM_LEADING, &header_value);
466           it = info->headers.find(header_name);
467           // See the second paragraph ("A sender MUST NOT generate multiple
468           // header fields...") of tools.ietf.org/html/rfc7230#section-3.2.2.
469           if (it == info->headers.end()) {
470             info->headers[header_name] = header_value;
471           } else {
472             it->second.append(",");
473             it->second.append(header_value);
474           }
475           buffer.clear();
476           break;
477         case ST_SEPARATOR:
478           break;
479       }
480       state = next_state;
481     } else {
482       // Do any actions based on current state
483       switch (state) {
484         case ST_METHOD:
485         case ST_URL:
486         case ST_PROTO:
487         case ST_VALUE:
488         case ST_NAME:
489           buffer.append(&ch, 1);
490           break;
491         case ST_DONE:
492           // We got CR to get this far, also need the LF
493           return (input == INPUT_LF);
494         case ST_ERR:
495           return false;
496       }
497     }
498   }
499   // No more characters, but we haven't finished parsing yet. Signal this to
500   // the caller by setting |pos| to zero.
501   pos = 0;
502   return true;
503 }
504 
FindConnection(int connection_id)505 HttpConnection* HttpServer::FindConnection(int connection_id) {
506   auto it = id_to_connection_.find(connection_id);
507   if (it == id_to_connection_.end())
508     return nullptr;
509   return it->second.get();
510 }
511 
512 // This is called after any delegate callbacks are called to check if Close()
513 // has been called during callback processing. Using the pointer of connection,
514 // |connection| is safe here because Close() deletes the connection in next run
515 // loop.
HasClosedConnection(HttpConnection * connection)516 bool HttpServer::HasClosedConnection(HttpConnection* connection) {
517   return FindConnection(connection->id()) != connection;
518 }
519 
520 }  // namespace net
521