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/files/file_path.h"
9 #include "base/files/file_util.h"
10 #include "base/message_loop/message_loop.h"
11 #include "base/process/process_metrics.h"
12 #include "base/run_loop.h"
13 #include "base/stl_util.h"
14 #include "base/strings/string_util.h"
15 #include "base/strings/stringprintf.h"
16 #include "base/threading/thread_restrictions.h"
17 #include "net/base/ip_endpoint.h"
18 #include "net/base/net_errors.h"
19 #include "net/test/embedded_test_server/http_connection.h"
20 #include "net/test/embedded_test_server/http_request.h"
21 #include "net/test/embedded_test_server/http_response.h"
24 namespace test_server
{
28 class CustomHttpResponse
: public HttpResponse
{
30 CustomHttpResponse(const std::string
& headers
, const std::string
& contents
)
31 : headers_(headers
), contents_(contents
) {
34 std::string
ToResponseString() const override
{
35 return headers_
+ "\r\n" + contents_
;
40 std::string contents_
;
42 DISALLOW_COPY_AND_ASSIGN(CustomHttpResponse
);
45 // Handles |request| by serving a file from under |server_root|.
46 scoped_ptr
<HttpResponse
> HandleFileRequest(
47 const base::FilePath
& server_root
,
48 const HttpRequest
& request
) {
49 // This is a test-only server. Ignore I/O thread restrictions.
50 base::ThreadRestrictions::ScopedAllowIO allow_io
;
52 std::string
relative_url(request
.relative_url
);
53 // A proxy request will have an absolute path. Simulate the proxy by stripping
54 // the scheme, host, and port.
55 GURL
relative_gurl(relative_url
);
56 if (relative_gurl
.is_valid())
57 relative_url
= relative_gurl
.PathForRequest();
59 // Trim the first byte ('/').
60 std::string request_path
= relative_url
.substr(1);
62 // Remove the query string if present.
63 size_t query_pos
= request_path
.find('?');
64 if (query_pos
!= std::string::npos
)
65 request_path
= request_path
.substr(0, query_pos
);
67 base::FilePath
file_path(server_root
.AppendASCII(request_path
));
68 std::string file_contents
;
69 if (!base::ReadFileToString(file_path
, &file_contents
))
70 return scoped_ptr
<HttpResponse
>();
72 base::FilePath
headers_path(
73 file_path
.AddExtension(FILE_PATH_LITERAL("mock-http-headers")));
75 if (base::PathExists(headers_path
)) {
76 std::string headers_contents
;
77 if (!base::ReadFileToString(headers_path
, &headers_contents
))
78 return scoped_ptr
<HttpResponse
>();
80 scoped_ptr
<CustomHttpResponse
> http_response(
81 new CustomHttpResponse(headers_contents
, file_contents
));
82 return http_response
.Pass();
85 scoped_ptr
<BasicHttpResponse
> http_response(new BasicHttpResponse
);
86 http_response
->set_code(HTTP_OK
);
87 http_response
->set_content(file_contents
);
88 return http_response
.Pass();
93 HttpListenSocket::HttpListenSocket(const SocketDescriptor socket_descriptor
,
94 StreamListenSocket::Delegate
* delegate
)
95 : TCPListenSocket(socket_descriptor
, delegate
) {
96 DCHECK(thread_checker_
.CalledOnValidThread());
99 void HttpListenSocket::Listen() {
100 DCHECK(thread_checker_
.CalledOnValidThread());
101 TCPListenSocket::Listen();
104 void HttpListenSocket::ListenOnIOThread() {
105 DCHECK(thread_checker_
.CalledOnValidThread());
106 #if !defined(OS_POSIX)
107 // This method may be called after the IO thread is changed, thus we need to
108 // call |WatchSocket| again to make sure it listens on the current IO thread.
109 // Only needed for non POSIX platforms, since on POSIX platforms
110 // StreamListenSocket::Listen already calls WatchSocket inside the function.
111 WatchSocket(WAITING_ACCEPT
);
116 HttpListenSocket::~HttpListenSocket() {
117 DCHECK(thread_checker_
.CalledOnValidThread());
120 void HttpListenSocket::DetachFromThread() {
121 thread_checker_
.DetachFromThread();
124 EmbeddedTestServer::EmbeddedTestServer()
126 weak_factory_(this) {
127 DCHECK(thread_checker_
.CalledOnValidThread());
130 EmbeddedTestServer::~EmbeddedTestServer() {
131 DCHECK(thread_checker_
.CalledOnValidThread());
133 if (Started() && !ShutdownAndWaitUntilComplete()) {
134 LOG(ERROR
) << "EmbeddedTestServer failed to shut down.";
138 bool EmbeddedTestServer::InitializeAndWaitUntilReady() {
140 DCHECK(thread_checker_
.CalledOnValidThread());
141 if (!PostTaskToIOThreadAndWait(base::Bind(
142 &EmbeddedTestServer::InitializeOnIOThread
, base::Unretained(this)))) {
145 return Started() && base_url_
.is_valid();
148 void EmbeddedTestServer::StopThread() {
149 DCHECK(io_thread_
&& io_thread_
->IsRunning());
151 #if defined(OS_LINUX)
152 const int thread_count
=
153 base::GetNumberOfThreads(base::GetCurrentProcessHandle());
158 thread_checker_
.DetachFromThread();
159 listen_socket_
->DetachFromThread();
161 #if defined(OS_LINUX)
162 // Busy loop to wait for thread count to decrease. This is needed because
163 // pthread_join does not guarantee that kernel stat is updated when it
164 // returns. Thus, GetNumberOfThreads does not immediately reflect the stopped
165 // thread and hits the thread number DCHECK in render_sandbox_host_linux.cc
167 while (thread_count
==
168 base::GetNumberOfThreads(base::GetCurrentProcessHandle())) {
169 base::PlatformThread::YieldCurrentThread();
174 void EmbeddedTestServer::RestartThreadAndListen() {
176 CHECK(PostTaskToIOThreadAndWait(base::Bind(
177 &EmbeddedTestServer::ListenOnIOThread
, base::Unretained(this))));
180 bool EmbeddedTestServer::ShutdownAndWaitUntilComplete() {
181 DCHECK(thread_checker_
.CalledOnValidThread());
183 return PostTaskToIOThreadAndWait(base::Bind(
184 &EmbeddedTestServer::ShutdownOnIOThread
, base::Unretained(this)));
187 void EmbeddedTestServer::StartThread() {
188 DCHECK(!io_thread_
.get());
189 base::Thread::Options thread_options
;
190 thread_options
.message_loop_type
= base::MessageLoop::TYPE_IO
;
191 io_thread_
.reset(new base::Thread("EmbeddedTestServer io thread"));
192 CHECK(io_thread_
->StartWithOptions(thread_options
));
195 void EmbeddedTestServer::InitializeOnIOThread() {
196 DCHECK(io_thread_
->message_loop_proxy()->BelongsToCurrentThread());
199 SocketDescriptor socket_descriptor
=
200 TCPListenSocket::CreateAndBindAnyPort("127.0.0.1", &port_
);
201 if (socket_descriptor
== kInvalidSocket
)
204 listen_socket_
.reset(new HttpListenSocket(socket_descriptor
, this));
205 listen_socket_
->Listen();
208 int result
= listen_socket_
->GetLocalAddress(&address
);
210 base_url_
= GURL(std::string("http://") + address
.ToString());
212 LOG(ERROR
) << "GetLocalAddress failed: " << ErrorToString(result
);
216 void EmbeddedTestServer::ListenOnIOThread() {
217 DCHECK(io_thread_
->message_loop_proxy()->BelongsToCurrentThread());
219 listen_socket_
->ListenOnIOThread();
222 void EmbeddedTestServer::ShutdownOnIOThread() {
223 DCHECK(io_thread_
->message_loop_proxy()->BelongsToCurrentThread());
225 listen_socket_
.reset();
226 STLDeleteContainerPairSecondPointers(connections_
.begin(),
228 connections_
.clear();
231 void EmbeddedTestServer::HandleRequest(HttpConnection
* connection
,
232 scoped_ptr
<HttpRequest
> request
) {
233 DCHECK(io_thread_
->message_loop_proxy()->BelongsToCurrentThread());
235 bool request_handled
= false;
237 for (size_t i
= 0; i
< request_handlers_
.size(); ++i
) {
238 scoped_ptr
<HttpResponse
> response
=
239 request_handlers_
[i
].Run(*request
.get());
240 if (response
.get()) {
241 connection
->SendResponse(response
.Pass());
242 request_handled
= true;
247 if (!request_handled
) {
248 LOG(WARNING
) << "Request not handled. Returning 404: "
249 << request
->relative_url
;
250 scoped_ptr
<BasicHttpResponse
> not_found_response(new BasicHttpResponse
);
251 not_found_response
->set_code(HTTP_NOT_FOUND
);
252 connection
->SendResponse(not_found_response
.Pass());
255 // Drop the connection, since we do not support multiple requests per
257 connections_
.erase(connection
->socket_
.get());
261 GURL
EmbeddedTestServer::GetURL(const std::string
& relative_url
) const {
262 DCHECK(Started()) << "You must start the server first.";
263 DCHECK(StartsWithASCII(relative_url
, "/", true /* case_sensitive */))
265 return base_url_
.Resolve(relative_url
);
268 GURL
EmbeddedTestServer::GetURL(
269 const std::string
& hostname
,
270 const std::string
& relative_url
) const {
271 GURL local_url
= GetURL(relative_url
);
272 GURL::Replacements replace_host
;
273 replace_host
.SetHostStr(hostname
);
274 return local_url
.ReplaceComponents(replace_host
);
277 void EmbeddedTestServer::ServeFilesFromDirectory(
278 const base::FilePath
& directory
) {
279 RegisterRequestHandler(base::Bind(&HandleFileRequest
, directory
));
282 void EmbeddedTestServer::RegisterRequestHandler(
283 const HandleRequestCallback
& callback
) {
284 request_handlers_
.push_back(callback
);
287 void EmbeddedTestServer::DidAccept(
288 StreamListenSocket
* server
,
289 scoped_ptr
<StreamListenSocket
> connection
) {
290 DCHECK(io_thread_
->message_loop_proxy()->BelongsToCurrentThread());
292 HttpConnection
* http_connection
= new HttpConnection(
294 base::Bind(&EmbeddedTestServer::HandleRequest
,
295 weak_factory_
.GetWeakPtr()));
296 // TODO(szym): Make HttpConnection the StreamListenSocket delegate.
297 connections_
[http_connection
->socket_
.get()] = http_connection
;
300 void EmbeddedTestServer::DidRead(StreamListenSocket
* connection
,
303 DCHECK(io_thread_
->message_loop_proxy()->BelongsToCurrentThread());
305 HttpConnection
* http_connection
= FindConnection(connection
);
306 if (http_connection
== NULL
) {
307 LOG(WARNING
) << "Unknown connection.";
310 http_connection
->ReceiveData(std::string(data
, length
));
313 void EmbeddedTestServer::DidClose(StreamListenSocket
* connection
) {
314 DCHECK(io_thread_
->message_loop_proxy()->BelongsToCurrentThread());
316 HttpConnection
* http_connection
= FindConnection(connection
);
317 if (http_connection
== NULL
) {
318 LOG(WARNING
) << "Unknown connection.";
321 delete http_connection
;
322 connections_
.erase(connection
);
325 HttpConnection
* EmbeddedTestServer::FindConnection(
326 StreamListenSocket
* socket
) {
327 DCHECK(io_thread_
->message_loop_proxy()->BelongsToCurrentThread());
329 std::map
<StreamListenSocket
*, HttpConnection
*>::iterator it
=
330 connections_
.find(socket
);
331 if (it
== connections_
.end()) {
337 bool EmbeddedTestServer::PostTaskToIOThreadAndWait(
338 const base::Closure
& closure
) {
339 // Note that PostTaskAndReply below requires base::MessageLoopProxy::current()
340 // to return a loop for posting the reply task. However, in order to make
341 // EmbeddedTestServer universally usable, it needs to cope with the situation
342 // where it's running on a thread on which a message loop is not (yet)
343 // available or as has been destroyed already.
345 // To handle this situation, create temporary message loop to support the
346 // PostTaskAndReply operation if the current thread as no message loop.
347 scoped_ptr
<base::MessageLoop
> temporary_loop
;
348 if (!base::MessageLoop::current())
349 temporary_loop
.reset(new base::MessageLoop());
351 base::RunLoop run_loop
;
352 if (!io_thread_
->message_loop_proxy()->PostTaskAndReply(
353 FROM_HERE
, closure
, run_loop
.QuitClosure())) {
361 } // namespace test_server