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/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"
22 #include "net/tools/fetch/http_listen_socket.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 EmbeddedTestServer::EmbeddedTestServer()
103 : io_thread_("EmbeddedTestServer io thread"),
105 weak_factory_(this) {
106 DCHECK(thread_checker_.CalledOnValidThread());
108 base::Thread::Options thread_options;
109 thread_options.message_loop_type = base::MessageLoop::TYPE_IO;
110 CHECK(io_thread_.StartWithOptions(thread_options));
113 EmbeddedTestServer::~EmbeddedTestServer() {
114 DCHECK(thread_checker_.CalledOnValidThread());
116 if (Started() && !ShutdownAndWaitUntilComplete()) {
117 LOG(ERROR) << "EmbeddedTestServer failed to shut down.";
121 bool EmbeddedTestServer::InitializeAndWaitUntilReady() {
122 DCHECK(thread_checker_.CalledOnValidThread());
124 if (!PostTaskToIOThreadAndWait(base::Bind(
125 &EmbeddedTestServer::InitializeOnIOThread, base::Unretained(this)))) {
129 return Started() && base_url_.is_valid();
132 bool EmbeddedTestServer::ShutdownAndWaitUntilComplete() {
133 DCHECK(thread_checker_.CalledOnValidThread());
135 return PostTaskToIOThreadAndWait(base::Bind(
136 &EmbeddedTestServer::ShutdownOnIOThread, base::Unretained(this)));
139 void EmbeddedTestServer::InitializeOnIOThread() {
140 DCHECK(io_thread_.message_loop_proxy()->BelongsToCurrentThread());
143 SocketDescriptor socket_descriptor =
144 TCPListenSocket::CreateAndBindAnyPort("127.0.0.1", &port_);
145 if (socket_descriptor == kInvalidSocket)
148 listen_socket_.reset(new HttpListenSocket(socket_descriptor, this));
149 listen_socket_->Listen();
152 int result = listen_socket_->GetLocalAddress(&address);
154 base_url_ = GURL(std::string("http://") + address.ToString());
156 LOG(ERROR) << "GetLocalAddress failed: " << ErrorToString(result);
160 void EmbeddedTestServer::ShutdownOnIOThread() {
161 DCHECK(io_thread_.message_loop_proxy()->BelongsToCurrentThread());
163 listen_socket_.reset();
164 STLDeleteContainerPairSecondPointers(connections_.begin(),
166 connections_.clear();
169 void EmbeddedTestServer::HandleRequest(HttpConnection* connection,
170 scoped_ptr<HttpRequest> request) {
171 DCHECK(io_thread_.message_loop_proxy()->BelongsToCurrentThread());
173 bool request_handled = false;
175 for (size_t i = 0; i < request_handlers_.size(); ++i) {
176 scoped_ptr<HttpResponse> response =
177 request_handlers_[i].Run(*request.get());
178 if (response.get()) {
179 connection->SendResponse(response.Pass());
180 request_handled = true;
185 if (!request_handled) {
186 LOG(WARNING) << "Request not handled. Returning 404: "
187 << request->relative_url;
188 scoped_ptr<BasicHttpResponse> not_found_response(new BasicHttpResponse);
189 not_found_response->set_code(HTTP_NOT_FOUND);
190 connection->SendResponse(
191 not_found_response.PassAs<HttpResponse>());
194 // Drop the connection, since we do not support multiple requests per
196 connections_.erase(connection->socket_.get());
200 GURL EmbeddedTestServer::GetURL(const std::string& relative_url) const {
201 DCHECK(Started()) << "You must start the server first.";
202 DCHECK(StartsWithASCII(relative_url, "/", true /* case_sensitive */))
204 return base_url_.Resolve(relative_url);
207 void EmbeddedTestServer::ServeFilesFromDirectory(
208 const base::FilePath& directory) {
209 RegisterRequestHandler(base::Bind(&HandleFileRequest, directory));
212 void EmbeddedTestServer::RegisterRequestHandler(
213 const HandleRequestCallback& callback) {
214 request_handlers_.push_back(callback);
217 void EmbeddedTestServer::DidAccept(
218 StreamListenSocket* server,
219 scoped_ptr<StreamListenSocket> connection) {
220 DCHECK(io_thread_.message_loop_proxy()->BelongsToCurrentThread());
222 HttpConnection* http_connection = new HttpConnection(
224 base::Bind(&EmbeddedTestServer::HandleRequest,
225 weak_factory_.GetWeakPtr()));
226 // TODO(szym): Make HttpConnection the StreamListenSocket delegate.
227 connections_[http_connection->socket_.get()] = http_connection;
230 void EmbeddedTestServer::DidRead(StreamListenSocket* connection,
233 DCHECK(io_thread_.message_loop_proxy()->BelongsToCurrentThread());
235 HttpConnection* http_connection = FindConnection(connection);
236 if (http_connection == NULL) {
237 LOG(WARNING) << "Unknown connection.";
240 http_connection->ReceiveData(std::string(data, length));
243 void EmbeddedTestServer::DidClose(StreamListenSocket* connection) {
244 DCHECK(io_thread_.message_loop_proxy()->BelongsToCurrentThread());
246 HttpConnection* http_connection = FindConnection(connection);
247 if (http_connection == NULL) {
248 LOG(WARNING) << "Unknown connection.";
251 delete http_connection;
252 connections_.erase(connection);
255 HttpConnection* EmbeddedTestServer::FindConnection(
256 StreamListenSocket* socket) {
257 DCHECK(io_thread_.message_loop_proxy()->BelongsToCurrentThread());
259 std::map<StreamListenSocket*, HttpConnection*>::iterator it =
260 connections_.find(socket);
261 if (it == connections_.end()) {
267 bool EmbeddedTestServer::PostTaskToIOThreadAndWait(
268 const base::Closure& closure) {
269 // Note that PostTaskAndReply below requires base::MessageLoopProxy::current()
270 // to return a loop for posting the reply task. However, in order to make
271 // EmbeddedTestServer universally usable, it needs to cope with the situation
272 // where it's running on a thread on which a message loop is not (yet)
273 // available or as has been destroyed already.
275 // To handle this situation, create temporary message loop to support the
276 // PostTaskAndReply operation if the current thread as no message loop.
277 scoped_ptr<base::MessageLoop> temporary_loop;
278 if (!base::MessageLoop::current())
279 temporary_loop.reset(new base::MessageLoop());
281 base::RunLoop run_loop;
282 if (!io_thread_.message_loop_proxy()->PostTaskAndReply(
283 FROM_HERE, closure, run_loop.QuitClosure())) {
291 } // namespace test_server