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 // Trim the first byte ('/').
53 std::string request_path(request.relative_url.substr(1));
55 // Remove the query string if present.
56 size_t query_pos = request_path.find('?');
57 if (query_pos != std::string::npos)
58 request_path = request_path.substr(0, query_pos);
60 base::FilePath file_path(server_root.AppendASCII(request_path));
61 std::string file_contents;
62 if (!base::ReadFileToString(file_path, &file_contents))
63 return scoped_ptr<HttpResponse>();
65 base::FilePath headers_path(
66 file_path.AddExtension(FILE_PATH_LITERAL("mock-http-headers")));
68 if (base::PathExists(headers_path)) {
69 std::string headers_contents;
70 if (!base::ReadFileToString(headers_path, &headers_contents))
71 return scoped_ptr<HttpResponse>();
73 scoped_ptr<CustomHttpResponse> http_response(
74 new CustomHttpResponse(headers_contents, file_contents));
75 return http_response.Pass();
78 scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse);
79 http_response->set_code(HTTP_OK);
80 http_response->set_content(file_contents);
81 return http_response.Pass();
86 HttpListenSocket::HttpListenSocket(const SocketDescriptor socket_descriptor,
87 StreamListenSocket::Delegate* delegate)
88 : TCPListenSocket(socket_descriptor, delegate) {
89 DCHECK(thread_checker_.CalledOnValidThread());
92 void HttpListenSocket::Listen() {
93 DCHECK(thread_checker_.CalledOnValidThread());
94 TCPListenSocket::Listen();
97 void HttpListenSocket::ListenOnIOThread() {
98 DCHECK(thread_checker_.CalledOnValidThread());
99 #if !defined(OS_POSIX)
100 // This method may be called after the IO thread is changed, thus we need to
101 // call |WatchSocket| again to make sure it listens on the current IO thread.
102 // Only needed for non POSIX platforms, since on POSIX platforms
103 // StreamListenSocket::Listen already calls WatchSocket inside the function.
104 WatchSocket(WAITING_ACCEPT);
109 HttpListenSocket::~HttpListenSocket() {
110 DCHECK(thread_checker_.CalledOnValidThread());
113 void HttpListenSocket::DetachFromThread() {
114 thread_checker_.DetachFromThread();
117 EmbeddedTestServer::EmbeddedTestServer()
119 weak_factory_(this) {
120 DCHECK(thread_checker_.CalledOnValidThread());
123 EmbeddedTestServer::~EmbeddedTestServer() {
124 DCHECK(thread_checker_.CalledOnValidThread());
126 if (Started() && !ShutdownAndWaitUntilComplete()) {
127 LOG(ERROR) << "EmbeddedTestServer failed to shut down.";
131 bool EmbeddedTestServer::InitializeAndWaitUntilReady() {
133 DCHECK(thread_checker_.CalledOnValidThread());
134 if (!PostTaskToIOThreadAndWait(base::Bind(
135 &EmbeddedTestServer::InitializeOnIOThread, base::Unretained(this)))) {
138 return Started() && base_url_.is_valid();
141 void EmbeddedTestServer::StopThread() {
142 DCHECK(io_thread_ && io_thread_->IsRunning());
144 #if defined(OS_LINUX)
145 const int thread_count =
146 base::GetNumberOfThreads(base::GetCurrentProcessHandle());
151 thread_checker_.DetachFromThread();
152 listen_socket_->DetachFromThread();
154 #if defined(OS_LINUX)
155 // Busy loop to wait for thread count to decrease. This is needed because
156 // pthread_join does not guarantee that kernel stat is updated when it
157 // returns. Thus, GetNumberOfThreads does not immediately reflect the stopped
158 // thread and hits the thread number DCHECK in render_sandbox_host_linux.cc
160 while (thread_count ==
161 base::GetNumberOfThreads(base::GetCurrentProcessHandle())) {
162 base::PlatformThread::YieldCurrentThread();
167 void EmbeddedTestServer::RestartThreadAndListen() {
169 CHECK(PostTaskToIOThreadAndWait(base::Bind(
170 &EmbeddedTestServer::ListenOnIOThread, base::Unretained(this))));
173 bool EmbeddedTestServer::ShutdownAndWaitUntilComplete() {
174 DCHECK(thread_checker_.CalledOnValidThread());
176 return PostTaskToIOThreadAndWait(base::Bind(
177 &EmbeddedTestServer::ShutdownOnIOThread, base::Unretained(this)));
180 void EmbeddedTestServer::StartThread() {
181 DCHECK(!io_thread_.get());
182 base::Thread::Options thread_options;
183 thread_options.message_loop_type = base::MessageLoop::TYPE_IO;
184 io_thread_.reset(new base::Thread("EmbeddedTestServer io thread"));
185 CHECK(io_thread_->StartWithOptions(thread_options));
188 void EmbeddedTestServer::InitializeOnIOThread() {
189 DCHECK(io_thread_->message_loop_proxy()->BelongsToCurrentThread());
192 SocketDescriptor socket_descriptor =
193 TCPListenSocket::CreateAndBindAnyPort("127.0.0.1", &port_);
194 if (socket_descriptor == kInvalidSocket)
197 listen_socket_.reset(new HttpListenSocket(socket_descriptor, this));
198 listen_socket_->Listen();
201 int result = listen_socket_->GetLocalAddress(&address);
203 base_url_ = GURL(std::string("http://") + address.ToString());
205 LOG(ERROR) << "GetLocalAddress failed: " << ErrorToString(result);
209 void EmbeddedTestServer::ListenOnIOThread() {
210 DCHECK(io_thread_->message_loop_proxy()->BelongsToCurrentThread());
212 listen_socket_->ListenOnIOThread();
215 void EmbeddedTestServer::ShutdownOnIOThread() {
216 DCHECK(io_thread_->message_loop_proxy()->BelongsToCurrentThread());
218 listen_socket_.reset();
219 STLDeleteContainerPairSecondPointers(connections_.begin(),
221 connections_.clear();
224 void EmbeddedTestServer::HandleRequest(HttpConnection* connection,
225 scoped_ptr<HttpRequest> request) {
226 DCHECK(io_thread_->message_loop_proxy()->BelongsToCurrentThread());
228 bool request_handled = false;
230 for (size_t i = 0; i < request_handlers_.size(); ++i) {
231 scoped_ptr<HttpResponse> response =
232 request_handlers_[i].Run(*request.get());
233 if (response.get()) {
234 connection->SendResponse(response.Pass());
235 request_handled = true;
240 if (!request_handled) {
241 LOG(WARNING) << "Request not handled. Returning 404: "
242 << request->relative_url;
243 scoped_ptr<BasicHttpResponse> not_found_response(new BasicHttpResponse);
244 not_found_response->set_code(HTTP_NOT_FOUND);
245 connection->SendResponse(not_found_response.Pass());
248 // Drop the connection, since we do not support multiple requests per
250 connections_.erase(connection->socket_.get());
254 GURL EmbeddedTestServer::GetURL(const std::string& relative_url) const {
255 DCHECK(Started()) << "You must start the server first.";
256 DCHECK(StartsWithASCII(relative_url, "/", true /* case_sensitive */))
258 return base_url_.Resolve(relative_url);
261 GURL EmbeddedTestServer::GetURL(
262 const std::string& hostname,
263 const std::string& relative_url) const {
264 GURL local_url = GetURL(relative_url);
265 GURL::Replacements replace_host;
266 replace_host.SetHostStr(hostname);
267 return local_url.ReplaceComponents(replace_host);
270 void EmbeddedTestServer::ServeFilesFromDirectory(
271 const base::FilePath& directory) {
272 RegisterRequestHandler(base::Bind(&HandleFileRequest, directory));
275 void EmbeddedTestServer::RegisterRequestHandler(
276 const HandleRequestCallback& callback) {
277 request_handlers_.push_back(callback);
280 void EmbeddedTestServer::DidAccept(
281 StreamListenSocket* server,
282 scoped_ptr<StreamListenSocket> connection) {
283 DCHECK(io_thread_->message_loop_proxy()->BelongsToCurrentThread());
285 HttpConnection* http_connection = new HttpConnection(
287 base::Bind(&EmbeddedTestServer::HandleRequest,
288 weak_factory_.GetWeakPtr()));
289 // TODO(szym): Make HttpConnection the StreamListenSocket delegate.
290 connections_[http_connection->socket_.get()] = http_connection;
293 void EmbeddedTestServer::DidRead(StreamListenSocket* connection,
296 DCHECK(io_thread_->message_loop_proxy()->BelongsToCurrentThread());
298 HttpConnection* http_connection = FindConnection(connection);
299 if (http_connection == NULL) {
300 LOG(WARNING) << "Unknown connection.";
303 http_connection->ReceiveData(std::string(data, length));
306 void EmbeddedTestServer::DidClose(StreamListenSocket* connection) {
307 DCHECK(io_thread_->message_loop_proxy()->BelongsToCurrentThread());
309 HttpConnection* http_connection = FindConnection(connection);
310 if (http_connection == NULL) {
311 LOG(WARNING) << "Unknown connection.";
314 delete http_connection;
315 connections_.erase(connection);
318 HttpConnection* EmbeddedTestServer::FindConnection(
319 StreamListenSocket* socket) {
320 DCHECK(io_thread_->message_loop_proxy()->BelongsToCurrentThread());
322 std::map<StreamListenSocket*, HttpConnection*>::iterator it =
323 connections_.find(socket);
324 if (it == connections_.end()) {
330 bool EmbeddedTestServer::PostTaskToIOThreadAndWait(
331 const base::Closure& closure) {
332 // Note that PostTaskAndReply below requires base::MessageLoopProxy::current()
333 // to return a loop for posting the reply task. However, in order to make
334 // EmbeddedTestServer universally usable, it needs to cope with the situation
335 // where it's running on a thread on which a message loop is not (yet)
336 // available or as has been destroyed already.
338 // To handle this situation, create temporary message loop to support the
339 // PostTaskAndReply operation if the current thread as no message loop.
340 scoped_ptr<base::MessageLoop> temporary_loop;
341 if (!base::MessageLoop::current())
342 temporary_loop.reset(new base::MessageLoop());
344 base::RunLoop run_loop;
345 if (!io_thread_->message_loop_proxy()->PostTaskAndReply(
346 FROM_HERE, closure, run_loop.QuitClosure())) {
354 } // namespace test_server