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
3 // found in the LICENSE file.
5 #include "net/test/embedded_test_server/embedded_test_server.h"
8 #include "base/file_util.h"
9 #include "base/files/file_path.h"
10 #include "base/message_loop/message_loop.h"
11 #include "base/path_service.h"
12 #include "base/process/process_metrics.h"
13 #include "base/run_loop.h"
14 #include "base/stl_util.h"
15 #include "base/strings/string_util.h"
16 #include "base/strings/stringprintf.h"
17 #include "base/threading/thread_restrictions.h"
18 #include "net/base/ip_endpoint.h"
19 #include "net/base/net_errors.h"
20 #include "net/test/embedded_test_server/http_connection.h"
21 #include "net/test/embedded_test_server/http_request.h"
22 #include "net/test/embedded_test_server/http_response.h"
25 namespace test_server
{
29 class CustomHttpResponse
: public HttpResponse
{
31 CustomHttpResponse(const std::string
& headers
, const std::string
& contents
)
32 : headers_(headers
), contents_(contents
) {
35 virtual std::string
ToResponseString() const OVERRIDE
{
36 return headers_
+ "\r\n" + contents_
;
41 std::string contents_
;
43 DISALLOW_COPY_AND_ASSIGN(CustomHttpResponse
);
46 // Handles |request| by serving a file from under |server_root|.
47 scoped_ptr
<HttpResponse
> HandleFileRequest(
48 const base::FilePath
& server_root
,
49 const HttpRequest
& request
) {
50 // This is a test-only server. Ignore I/O thread restrictions.
51 base::ThreadRestrictions::ScopedAllowIO allow_io
;
53 // Trim the first byte ('/').
54 std::string
request_path(request
.relative_url
.substr(1));
56 // Remove the query string if present.
57 size_t query_pos
= request_path
.find('?');
58 if (query_pos
!= std::string::npos
)
59 request_path
= request_path
.substr(0, query_pos
);
61 base::FilePath
file_path(server_root
.AppendASCII(request_path
));
62 std::string file_contents
;
63 if (!base::ReadFileToString(file_path
, &file_contents
))
64 return scoped_ptr
<HttpResponse
>();
66 base::FilePath
headers_path(
67 file_path
.AddExtension(FILE_PATH_LITERAL("mock-http-headers")));
69 if (base::PathExists(headers_path
)) {
70 std::string headers_contents
;
71 if (!base::ReadFileToString(headers_path
, &headers_contents
))
72 return scoped_ptr
<HttpResponse
>();
74 scoped_ptr
<CustomHttpResponse
> http_response(
75 new CustomHttpResponse(headers_contents
, file_contents
));
76 return http_response
.PassAs
<HttpResponse
>();
79 scoped_ptr
<BasicHttpResponse
> http_response(new BasicHttpResponse
);
80 http_response
->set_code(HTTP_OK
);
81 http_response
->set_content(file_contents
);
82 return http_response
.PassAs
<HttpResponse
>();
87 HttpListenSocket::HttpListenSocket(const SocketDescriptor socket_descriptor
,
88 StreamListenSocket::Delegate
* delegate
)
89 : TCPListenSocket(socket_descriptor
, delegate
) {
90 DCHECK(thread_checker_
.CalledOnValidThread());
93 void HttpListenSocket::Listen() {
94 DCHECK(thread_checker_
.CalledOnValidThread());
95 TCPListenSocket::Listen();
98 HttpListenSocket::~HttpListenSocket() {
99 DCHECK(thread_checker_
.CalledOnValidThread());
102 void HttpListenSocket::DetachFromThread() {
103 thread_checker_
.DetachFromThread();
106 EmbeddedTestServer::EmbeddedTestServer()
108 weak_factory_(this) {
109 DCHECK(thread_checker_
.CalledOnValidThread());
112 EmbeddedTestServer::~EmbeddedTestServer() {
113 DCHECK(thread_checker_
.CalledOnValidThread());
115 if (Started() && !ShutdownAndWaitUntilComplete()) {
116 LOG(ERROR
) << "EmbeddedTestServer failed to shut down.";
120 bool EmbeddedTestServer::InitializeAndWaitUntilReady() {
122 DCHECK(thread_checker_
.CalledOnValidThread());
123 if (!PostTaskToIOThreadAndWait(base::Bind(
124 &EmbeddedTestServer::InitializeOnIOThread
, base::Unretained(this)))) {
127 return Started() && base_url_
.is_valid();
130 void EmbeddedTestServer::StopThread() {
131 DCHECK(io_thread_
&& io_thread_
->IsRunning());
133 #if defined(OS_LINUX)
134 const int thread_count
=
135 base::GetNumberOfThreads(base::GetCurrentProcessHandle());
140 thread_checker_
.DetachFromThread();
141 listen_socket_
->DetachFromThread();
143 #if defined(OS_LINUX)
144 // Busy loop to wait for thread count to decrease. This is needed because
145 // pthread_join does not guarantee that kernel stat is updated when it
146 // returns. Thus, GetNumberOfThreads does not immediately reflect the stopped
147 // thread and hits the thread number DCHECK in render_sandbox_host_linux.cc
149 while (thread_count
==
150 base::GetNumberOfThreads(base::GetCurrentProcessHandle())) {
151 base::PlatformThread::YieldCurrentThread();
156 void EmbeddedTestServer::RestartThreadAndListen() {
158 CHECK(PostTaskToIOThreadAndWait(base::Bind(
159 &EmbeddedTestServer::ListenOnIOThread
, base::Unretained(this))));
162 bool EmbeddedTestServer::ShutdownAndWaitUntilComplete() {
163 DCHECK(thread_checker_
.CalledOnValidThread());
165 return PostTaskToIOThreadAndWait(base::Bind(
166 &EmbeddedTestServer::ShutdownOnIOThread
, base::Unretained(this)));
169 void EmbeddedTestServer::StartThread() {
170 DCHECK(!io_thread_
.get());
171 base::Thread::Options thread_options
;
172 thread_options
.message_loop_type
= base::MessageLoop::TYPE_IO
;
173 io_thread_
.reset(new base::Thread("EmbeddedTestServer io thread"));
174 CHECK(io_thread_
->StartWithOptions(thread_options
));
177 void EmbeddedTestServer::InitializeOnIOThread() {
178 DCHECK(io_thread_
->message_loop_proxy()->BelongsToCurrentThread());
181 SocketDescriptor socket_descriptor
=
182 TCPListenSocket::CreateAndBindAnyPort("127.0.0.1", &port_
);
183 if (socket_descriptor
== kInvalidSocket
)
186 listen_socket_
.reset(new HttpListenSocket(socket_descriptor
, this));
187 listen_socket_
->Listen();
190 int result
= listen_socket_
->GetLocalAddress(&address
);
192 base_url_
= GURL(std::string("http://") + address
.ToString());
194 LOG(ERROR
) << "GetLocalAddress failed: " << ErrorToString(result
);
198 void EmbeddedTestServer::ListenOnIOThread() {
199 DCHECK(io_thread_
->message_loop_proxy()->BelongsToCurrentThread());
201 listen_socket_
->Listen();
204 void EmbeddedTestServer::ShutdownOnIOThread() {
205 DCHECK(io_thread_
->message_loop_proxy()->BelongsToCurrentThread());
207 listen_socket_
.reset();
208 STLDeleteContainerPairSecondPointers(connections_
.begin(),
210 connections_
.clear();
213 void EmbeddedTestServer::HandleRequest(HttpConnection
* connection
,
214 scoped_ptr
<HttpRequest
> request
) {
215 DCHECK(io_thread_
->message_loop_proxy()->BelongsToCurrentThread());
217 bool request_handled
= false;
219 for (size_t i
= 0; i
< request_handlers_
.size(); ++i
) {
220 scoped_ptr
<HttpResponse
> response
=
221 request_handlers_
[i
].Run(*request
.get());
222 if (response
.get()) {
223 connection
->SendResponse(response
.Pass());
224 request_handled
= true;
229 if (!request_handled
) {
230 LOG(WARNING
) << "Request not handled. Returning 404: "
231 << request
->relative_url
;
232 scoped_ptr
<BasicHttpResponse
> not_found_response(new BasicHttpResponse
);
233 not_found_response
->set_code(HTTP_NOT_FOUND
);
234 connection
->SendResponse(
235 not_found_response
.PassAs
<HttpResponse
>());
238 // Drop the connection, since we do not support multiple requests per
240 connections_
.erase(connection
->socket_
.get());
244 GURL
EmbeddedTestServer::GetURL(const std::string
& relative_url
) const {
245 DCHECK(Started()) << "You must start the server first.";
246 DCHECK(StartsWithASCII(relative_url
, "/", true /* case_sensitive */))
248 return base_url_
.Resolve(relative_url
);
251 void EmbeddedTestServer::ServeFilesFromDirectory(
252 const base::FilePath
& directory
) {
253 RegisterRequestHandler(base::Bind(&HandleFileRequest
, directory
));
256 void EmbeddedTestServer::RegisterRequestHandler(
257 const HandleRequestCallback
& callback
) {
258 request_handlers_
.push_back(callback
);
261 void EmbeddedTestServer::DidAccept(
262 StreamListenSocket
* server
,
263 scoped_ptr
<StreamListenSocket
> connection
) {
264 DCHECK(io_thread_
->message_loop_proxy()->BelongsToCurrentThread());
266 HttpConnection
* http_connection
= new HttpConnection(
268 base::Bind(&EmbeddedTestServer::HandleRequest
,
269 weak_factory_
.GetWeakPtr()));
270 // TODO(szym): Make HttpConnection the StreamListenSocket delegate.
271 connections_
[http_connection
->socket_
.get()] = http_connection
;
274 void EmbeddedTestServer::DidRead(StreamListenSocket
* connection
,
277 DCHECK(io_thread_
->message_loop_proxy()->BelongsToCurrentThread());
279 HttpConnection
* http_connection
= FindConnection(connection
);
280 if (http_connection
== NULL
) {
281 LOG(WARNING
) << "Unknown connection.";
284 http_connection
->ReceiveData(std::string(data
, length
));
287 void EmbeddedTestServer::DidClose(StreamListenSocket
* connection
) {
288 DCHECK(io_thread_
->message_loop_proxy()->BelongsToCurrentThread());
290 HttpConnection
* http_connection
= FindConnection(connection
);
291 if (http_connection
== NULL
) {
292 LOG(WARNING
) << "Unknown connection.";
295 delete http_connection
;
296 connections_
.erase(connection
);
299 HttpConnection
* EmbeddedTestServer::FindConnection(
300 StreamListenSocket
* socket
) {
301 DCHECK(io_thread_
->message_loop_proxy()->BelongsToCurrentThread());
303 std::map
<StreamListenSocket
*, HttpConnection
*>::iterator it
=
304 connections_
.find(socket
);
305 if (it
== connections_
.end()) {
311 bool EmbeddedTestServer::PostTaskToIOThreadAndWait(
312 const base::Closure
& closure
) {
313 // Note that PostTaskAndReply below requires base::MessageLoopProxy::current()
314 // to return a loop for posting the reply task. However, in order to make
315 // EmbeddedTestServer universally usable, it needs to cope with the situation
316 // where it's running on a thread on which a message loop is not (yet)
317 // available or as has been destroyed already.
319 // To handle this situation, create temporary message loop to support the
320 // PostTaskAndReply operation if the current thread as no message loop.
321 scoped_ptr
<base::MessageLoop
> temporary_loop
;
322 if (!base::MessageLoop::current())
323 temporary_loop
.reset(new base::MessageLoop());
325 base::RunLoop run_loop
;
326 if (!io_thread_
->message_loop_proxy()->PostTaskAndReply(
327 FROM_HERE
, closure
, run_loop
.QuitClosure())) {
335 } // namespace test_server