embedded_test_server.cc revision 4e180b6a0b4720a9b8e9e959a882386f690f08ff
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(Started()) << "You must start the server first."; 200 DCHECK(StartsWithASCII(relative_url, "/", true /* case_sensitive */)) 201 << relative_url; 202 return base_url_.Resolve(relative_url); 203} 204 205void EmbeddedTestServer::ServeFilesFromDirectory( 206 const base::FilePath& directory) { 207 RegisterRequestHandler(base::Bind(&HandleFileRequest, directory)); 208} 209 210void EmbeddedTestServer::RegisterRequestHandler( 211 const HandleRequestCallback& callback) { 212 request_handlers_.push_back(callback); 213} 214 215void EmbeddedTestServer::DidAccept( 216 StreamListenSocket* server, 217 scoped_ptr<StreamListenSocket> connection) { 218 DCHECK(io_thread_->BelongsToCurrentThread()); 219 220 HttpConnection* http_connection = new HttpConnection( 221 connection.Pass(), 222 base::Bind(&EmbeddedTestServer::HandleRequest, 223 weak_factory_.GetWeakPtr())); 224 // TODO(szym): Make HttpConnection the StreamListenSocket delegate. 225 connections_[http_connection->socket_.get()] = http_connection; 226} 227 228void EmbeddedTestServer::DidRead(StreamListenSocket* connection, 229 const char* data, 230 int length) { 231 DCHECK(io_thread_->BelongsToCurrentThread()); 232 233 HttpConnection* http_connection = FindConnection(connection); 234 if (http_connection == NULL) { 235 LOG(WARNING) << "Unknown connection."; 236 return; 237 } 238 http_connection->ReceiveData(std::string(data, length)); 239} 240 241void EmbeddedTestServer::DidClose(StreamListenSocket* connection) { 242 DCHECK(io_thread_->BelongsToCurrentThread()); 243 244 HttpConnection* http_connection = FindConnection(connection); 245 if (http_connection == NULL) { 246 LOG(WARNING) << "Unknown connection."; 247 return; 248 } 249 delete http_connection; 250 connections_.erase(connection); 251} 252 253HttpConnection* EmbeddedTestServer::FindConnection( 254 StreamListenSocket* socket) { 255 DCHECK(io_thread_->BelongsToCurrentThread()); 256 257 std::map<StreamListenSocket*, HttpConnection*>::iterator it = 258 connections_.find(socket); 259 if (it == connections_.end()) { 260 return NULL; 261 } 262 return it->second; 263} 264 265bool EmbeddedTestServer::PostTaskToIOThreadAndWait( 266 const base::Closure& closure) { 267 // Note that PostTaskAndReply below requires base::MessageLoopProxy::current() 268 // to return a loop for posting the reply task. However, in order to make 269 // EmbeddedTestServer universally usable, it needs to cope with the situation 270 // where it's running on a thread on which a message loop is not (yet) 271 // available or as has been destroyed already. 272 // 273 // To handle this situation, create temporary message loop to support the 274 // PostTaskAndReply operation if the current thread as no message loop. 275 scoped_ptr<base::MessageLoop> temporary_loop; 276 if (!base::MessageLoop::current()) 277 temporary_loop.reset(new base::MessageLoop()); 278 279 base::RunLoop run_loop; 280 if (!io_thread_->PostTaskAndReply(FROM_HERE, closure, run_loop.QuitClosure())) 281 return false; 282 run_loop.Run(); 283 284 return true; 285} 286 287} // namespace test_server 288} // namespace net 289