embedded_test_server.cc revision 58537e28ecd584eab876aee8be7156509866d23a
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.
4
5#include "net/test/embedded_test_server/embedded_test_server.h"
6
7#include "base/bind.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"
23
24namespace net {
25namespace test_server {
26
27namespace {
28
29class CustomHttpResponse : public HttpResponse {
30 public:
31  CustomHttpResponse(const std::string& headers, const std::string& contents)
32      : headers_(headers), contents_(contents) {
33  }
34
35  virtual std::string ToResponseString() const OVERRIDE {
36    return headers_ + "\r\n" + contents_;
37  }
38
39 private:
40  std::string headers_;
41  std::string contents_;
42
43  DISALLOW_COPY_AND_ASSIGN(CustomHttpResponse);
44};
45
46// Handles |request| by serving a file from under |server_root|.
47scoped_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;
52
53  // Trim the first byte ('/').
54  std::string request_path(request.relative_url.substr(1));
55
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);
60
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>();
65
66  base::FilePath headers_path(
67      file_path.AddExtension(FILE_PATH_LITERAL("mock-http-headers")));
68
69  if (base::PathExists(headers_path)) {
70    std::string headers_contents;
71    if (!base::ReadFileToString(headers_path, &headers_contents))
72      return scoped_ptr<HttpResponse>();
73
74    scoped_ptr<CustomHttpResponse> http_response(
75        new CustomHttpResponse(headers_contents, file_contents));
76    return http_response.PassAs<HttpResponse>();
77  }
78
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>();
83}
84
85}  // namespace
86
87HttpListenSocket::HttpListenSocket(const SocketDescriptor socket_descriptor,
88                                   StreamListenSocket::Delegate* delegate)
89    : TCPListenSocket(socket_descriptor, delegate) {
90  DCHECK(thread_checker_.CalledOnValidThread());
91}
92
93void HttpListenSocket::Listen() {
94  DCHECK(thread_checker_.CalledOnValidThread());
95  TCPListenSocket::Listen();
96}
97
98HttpListenSocket::~HttpListenSocket() {
99  DCHECK(thread_checker_.CalledOnValidThread());
100}
101
102EmbeddedTestServer::EmbeddedTestServer(
103    const scoped_refptr<base::SingleThreadTaskRunner>& io_thread)
104    : io_thread_(io_thread),
105      port_(-1),
106      weak_factory_(this) {
107  DCHECK(io_thread_.get());
108  DCHECK(thread_checker_.CalledOnValidThread());
109}
110
111EmbeddedTestServer::~EmbeddedTestServer() {
112  DCHECK(thread_checker_.CalledOnValidThread());
113
114  if (Started() && !ShutdownAndWaitUntilComplete()) {
115    LOG(ERROR) << "EmbeddedTestServer failed to shut down.";
116  }
117}
118
119bool EmbeddedTestServer::InitializeAndWaitUntilReady() {
120  DCHECK(thread_checker_.CalledOnValidThread());
121
122  if (!PostTaskToIOThreadAndWait(base::Bind(
123          &EmbeddedTestServer::InitializeOnIOThread, base::Unretained(this)))) {
124    return false;
125  }
126
127  return Started() && base_url_.is_valid();
128}
129
130bool EmbeddedTestServer::ShutdownAndWaitUntilComplete() {
131  DCHECK(thread_checker_.CalledOnValidThread());
132
133  return PostTaskToIOThreadAndWait(base::Bind(
134      &EmbeddedTestServer::ShutdownOnIOThread, base::Unretained(this)));
135}
136
137void EmbeddedTestServer::InitializeOnIOThread() {
138  DCHECK(io_thread_->BelongsToCurrentThread());
139  DCHECK(!Started());
140
141  SocketDescriptor socket_descriptor =
142      TCPListenSocket::CreateAndBindAnyPort("127.0.0.1", &port_);
143  if (socket_descriptor == kInvalidSocket)
144    return;
145
146  listen_socket_.reset(new HttpListenSocket(socket_descriptor, this));
147  listen_socket_->Listen();
148
149  IPEndPoint address;
150  int result = listen_socket_->GetLocalAddress(&address);
151  if (result == OK) {
152    base_url_ = GURL(std::string("http://") + address.ToString());
153  } else {
154    LOG(ERROR) << "GetLocalAddress failed: " << ErrorToString(result);
155  }
156}
157
158void EmbeddedTestServer::ShutdownOnIOThread() {
159  DCHECK(io_thread_->BelongsToCurrentThread());
160
161  listen_socket_.reset();
162  STLDeleteContainerPairSecondPointers(connections_.begin(),
163                                       connections_.end());
164  connections_.clear();
165}
166
167void EmbeddedTestServer::HandleRequest(HttpConnection* connection,
168                               scoped_ptr<HttpRequest> request) {
169  DCHECK(io_thread_->BelongsToCurrentThread());
170
171  bool request_handled = false;
172
173  for (size_t i = 0; i < request_handlers_.size(); ++i) {
174    scoped_ptr<HttpResponse> response =
175        request_handlers_[i].Run(*request.get());
176    if (response.get()) {
177      connection->SendResponse(response.Pass());
178      request_handled = true;
179      break;
180    }
181  }
182
183  if (!request_handled) {
184    LOG(WARNING) << "Request not handled. Returning 404: "
185                 << request->relative_url;
186    scoped_ptr<BasicHttpResponse> not_found_response(new BasicHttpResponse);
187    not_found_response->set_code(HTTP_NOT_FOUND);
188    connection->SendResponse(
189        not_found_response.PassAs<HttpResponse>());
190  }
191
192  // Drop the connection, since we do not support multiple requests per
193  // connection.
194  connections_.erase(connection->socket_.get());
195  delete connection;
196}
197
198GURL EmbeddedTestServer::GetURL(const std::string& relative_url) const {
199  DCHECK(StartsWithASCII(relative_url, "/", true /* case_sensitive */))
200      << relative_url;
201  return base_url_.Resolve(relative_url);
202}
203
204void EmbeddedTestServer::ServeFilesFromDirectory(
205    const base::FilePath& directory) {
206  RegisterRequestHandler(base::Bind(&HandleFileRequest, directory));
207}
208
209void EmbeddedTestServer::RegisterRequestHandler(
210    const HandleRequestCallback& callback) {
211  request_handlers_.push_back(callback);
212}
213
214void EmbeddedTestServer::DidAccept(
215    StreamListenSocket* server,
216    scoped_ptr<StreamListenSocket> connection) {
217  DCHECK(io_thread_->BelongsToCurrentThread());
218
219  HttpConnection* http_connection = new HttpConnection(
220      connection.Pass(),
221      base::Bind(&EmbeddedTestServer::HandleRequest,
222                 weak_factory_.GetWeakPtr()));
223  // TODO(szym): Make HttpConnection the StreamListenSocket delegate.
224  connections_[http_connection->socket_.get()] = http_connection;
225}
226
227void EmbeddedTestServer::DidRead(StreamListenSocket* connection,
228                         const char* data,
229                         int length) {
230  DCHECK(io_thread_->BelongsToCurrentThread());
231
232  HttpConnection* http_connection = FindConnection(connection);
233  if (http_connection == NULL) {
234    LOG(WARNING) << "Unknown connection.";
235    return;
236  }
237  http_connection->ReceiveData(std::string(data, length));
238}
239
240void EmbeddedTestServer::DidClose(StreamListenSocket* connection) {
241  DCHECK(io_thread_->BelongsToCurrentThread());
242
243  HttpConnection* http_connection = FindConnection(connection);
244  if (http_connection == NULL) {
245    LOG(WARNING) << "Unknown connection.";
246    return;
247  }
248  delete http_connection;
249  connections_.erase(connection);
250}
251
252HttpConnection* EmbeddedTestServer::FindConnection(
253    StreamListenSocket* socket) {
254  DCHECK(io_thread_->BelongsToCurrentThread());
255
256  std::map<StreamListenSocket*, HttpConnection*>::iterator it =
257      connections_.find(socket);
258  if (it == connections_.end()) {
259    return NULL;
260  }
261  return it->second;
262}
263
264bool EmbeddedTestServer::PostTaskToIOThreadAndWait(
265    const base::Closure& closure) {
266  // Note that PostTaskAndReply below requires base::MessageLoopProxy::current()
267  // to return a loop for posting the reply task. However, in order to make
268  // EmbeddedTestServer universally usable, it needs to cope with the situation
269  // where it's running on a thread on which a message loop is not (yet)
270  // available or as has been destroyed already.
271  //
272  // To handle this situation, create temporary message loop to support the
273  // PostTaskAndReply operation if the current thread as no message loop.
274  scoped_ptr<base::MessageLoop> temporary_loop;
275  if (!base::MessageLoop::current())
276    temporary_loop.reset(new base::MessageLoop());
277
278  base::RunLoop run_loop;
279  if (!io_thread_->PostTaskAndReply(FROM_HERE, closure, run_loop.QuitClosure()))
280    return false;
281  run_loop.Run();
282
283  return true;
284}
285
286}  // namespace test_server
287}  // namespace net
288