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/process/process_metrics.h" 13 #include "base/run_loop.h" 14 #include "base/stl_util.h" 15 #include "base/strings/string_util.h" 16 #include "base/strings/stringprintf.h" 17 #include "base/threading/thread_restrictions.h" 18 #include "net/base/ip_endpoint.h" 19 #include "net/base/net_errors.h" 20 #include "net/test/embedded_test_server/http_connection.h" 21 #include "net/test/embedded_test_server/http_request.h" 22 #include "net/test/embedded_test_server/http_response.h" 23 24 namespace net { 25 namespace test_server { 26 27 namespace { 28 29 class 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|. 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; 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 87 HttpListenSocket::HttpListenSocket(const SocketDescriptor socket_descriptor, 88 StreamListenSocket::Delegate* delegate) 89 : TCPListenSocket(socket_descriptor, delegate) { 90 DCHECK(thread_checker_.CalledOnValidThread()); 91 } 92 93 void HttpListenSocket::Listen() { 94 DCHECK(thread_checker_.CalledOnValidThread()); 95 TCPListenSocket::Listen(); 96 } 97 98 HttpListenSocket::~HttpListenSocket() { 99 DCHECK(thread_checker_.CalledOnValidThread()); 100 } 101 102 void HttpListenSocket::DetachFromThread() { 103 thread_checker_.DetachFromThread(); 104 } 105 106 EmbeddedTestServer::EmbeddedTestServer() 107 : port_(-1), 108 weak_factory_(this) { 109 DCHECK(thread_checker_.CalledOnValidThread()); 110 } 111 112 EmbeddedTestServer::~EmbeddedTestServer() { 113 DCHECK(thread_checker_.CalledOnValidThread()); 114 115 if (Started() && !ShutdownAndWaitUntilComplete()) { 116 LOG(ERROR) << "EmbeddedTestServer failed to shut down."; 117 } 118 } 119 120 bool EmbeddedTestServer::InitializeAndWaitUntilReady() { 121 StartThread(); 122 DCHECK(thread_checker_.CalledOnValidThread()); 123 if (!PostTaskToIOThreadAndWait(base::Bind( 124 &EmbeddedTestServer::InitializeOnIOThread, base::Unretained(this)))) { 125 return false; 126 } 127 return Started() && base_url_.is_valid(); 128 } 129 130 void EmbeddedTestServer::StopThread() { 131 DCHECK(io_thread_ && io_thread_->IsRunning()); 132 133 #if defined(OS_LINUX) 134 const int thread_count = 135 base::GetNumberOfThreads(base::GetCurrentProcessHandle()); 136 #endif 137 138 io_thread_->Stop(); 139 io_thread_.reset(); 140 thread_checker_.DetachFromThread(); 141 listen_socket_->DetachFromThread(); 142 143 #if defined(OS_LINUX) 144 // Busy loop to wait for thread count to decrease. This is needed because 145 // pthread_join does not guarantee that kernel stat is updated when it 146 // returns. Thus, GetNumberOfThreads does not immediately reflect the stopped 147 // thread and hits the thread number DCHECK in render_sandbox_host_linux.cc 148 // in browser_tests. 149 while (thread_count == 150 base::GetNumberOfThreads(base::GetCurrentProcessHandle())) { 151 base::PlatformThread::YieldCurrentThread(); 152 } 153 #endif 154 } 155 156 void EmbeddedTestServer::RestartThreadAndListen() { 157 StartThread(); 158 CHECK(PostTaskToIOThreadAndWait(base::Bind( 159 &EmbeddedTestServer::ListenOnIOThread, base::Unretained(this)))); 160 } 161 162 bool EmbeddedTestServer::ShutdownAndWaitUntilComplete() { 163 DCHECK(thread_checker_.CalledOnValidThread()); 164 165 return PostTaskToIOThreadAndWait(base::Bind( 166 &EmbeddedTestServer::ShutdownOnIOThread, base::Unretained(this))); 167 } 168 169 void EmbeddedTestServer::StartThread() { 170 DCHECK(!io_thread_.get()); 171 base::Thread::Options thread_options; 172 thread_options.message_loop_type = base::MessageLoop::TYPE_IO; 173 io_thread_.reset(new base::Thread("EmbeddedTestServer io thread")); 174 CHECK(io_thread_->StartWithOptions(thread_options)); 175 } 176 177 void EmbeddedTestServer::InitializeOnIOThread() { 178 DCHECK(io_thread_->message_loop_proxy()->BelongsToCurrentThread()); 179 DCHECK(!Started()); 180 181 SocketDescriptor socket_descriptor = 182 TCPListenSocket::CreateAndBindAnyPort("127.0.0.1", &port_); 183 if (socket_descriptor == kInvalidSocket) 184 return; 185 186 listen_socket_.reset(new HttpListenSocket(socket_descriptor, this)); 187 listen_socket_->Listen(); 188 189 IPEndPoint address; 190 int result = listen_socket_->GetLocalAddress(&address); 191 if (result == OK) { 192 base_url_ = GURL(std::string("http://") + address.ToString()); 193 } else { 194 LOG(ERROR) << "GetLocalAddress failed: " << ErrorToString(result); 195 } 196 } 197 198 void EmbeddedTestServer::ListenOnIOThread() { 199 DCHECK(io_thread_->message_loop_proxy()->BelongsToCurrentThread()); 200 DCHECK(Started()); 201 listen_socket_->Listen(); 202 } 203 204 void EmbeddedTestServer::ShutdownOnIOThread() { 205 DCHECK(io_thread_->message_loop_proxy()->BelongsToCurrentThread()); 206 207 listen_socket_.reset(); 208 STLDeleteContainerPairSecondPointers(connections_.begin(), 209 connections_.end()); 210 connections_.clear(); 211 } 212 213 void EmbeddedTestServer::HandleRequest(HttpConnection* connection, 214 scoped_ptr<HttpRequest> request) { 215 DCHECK(io_thread_->message_loop_proxy()->BelongsToCurrentThread()); 216 217 bool request_handled = false; 218 219 for (size_t i = 0; i < request_handlers_.size(); ++i) { 220 scoped_ptr<HttpResponse> response = 221 request_handlers_[i].Run(*request.get()); 222 if (response.get()) { 223 connection->SendResponse(response.Pass()); 224 request_handled = true; 225 break; 226 } 227 } 228 229 if (!request_handled) { 230 LOG(WARNING) << "Request not handled. Returning 404: " 231 << request->relative_url; 232 scoped_ptr<BasicHttpResponse> not_found_response(new BasicHttpResponse); 233 not_found_response->set_code(HTTP_NOT_FOUND); 234 connection->SendResponse( 235 not_found_response.PassAs<HttpResponse>()); 236 } 237 238 // Drop the connection, since we do not support multiple requests per 239 // connection. 240 connections_.erase(connection->socket_.get()); 241 delete connection; 242 } 243 244 GURL EmbeddedTestServer::GetURL(const std::string& relative_url) const { 245 DCHECK(Started()) << "You must start the server first."; 246 DCHECK(StartsWithASCII(relative_url, "/", true /* case_sensitive */)) 247 << relative_url; 248 return base_url_.Resolve(relative_url); 249 } 250 251 void EmbeddedTestServer::ServeFilesFromDirectory( 252 const base::FilePath& directory) { 253 RegisterRequestHandler(base::Bind(&HandleFileRequest, directory)); 254 } 255 256 void EmbeddedTestServer::RegisterRequestHandler( 257 const HandleRequestCallback& callback) { 258 request_handlers_.push_back(callback); 259 } 260 261 void EmbeddedTestServer::DidAccept( 262 StreamListenSocket* server, 263 scoped_ptr<StreamListenSocket> connection) { 264 DCHECK(io_thread_->message_loop_proxy()->BelongsToCurrentThread()); 265 266 HttpConnection* http_connection = new HttpConnection( 267 connection.Pass(), 268 base::Bind(&EmbeddedTestServer::HandleRequest, 269 weak_factory_.GetWeakPtr())); 270 // TODO(szym): Make HttpConnection the StreamListenSocket delegate. 271 connections_[http_connection->socket_.get()] = http_connection; 272 } 273 274 void EmbeddedTestServer::DidRead(StreamListenSocket* connection, 275 const char* data, 276 int length) { 277 DCHECK(io_thread_->message_loop_proxy()->BelongsToCurrentThread()); 278 279 HttpConnection* http_connection = FindConnection(connection); 280 if (http_connection == NULL) { 281 LOG(WARNING) << "Unknown connection."; 282 return; 283 } 284 http_connection->ReceiveData(std::string(data, length)); 285 } 286 287 void EmbeddedTestServer::DidClose(StreamListenSocket* connection) { 288 DCHECK(io_thread_->message_loop_proxy()->BelongsToCurrentThread()); 289 290 HttpConnection* http_connection = FindConnection(connection); 291 if (http_connection == NULL) { 292 LOG(WARNING) << "Unknown connection."; 293 return; 294 } 295 delete http_connection; 296 connections_.erase(connection); 297 } 298 299 HttpConnection* EmbeddedTestServer::FindConnection( 300 StreamListenSocket* socket) { 301 DCHECK(io_thread_->message_loop_proxy()->BelongsToCurrentThread()); 302 303 std::map<StreamListenSocket*, HttpConnection*>::iterator it = 304 connections_.find(socket); 305 if (it == connections_.end()) { 306 return NULL; 307 } 308 return it->second; 309 } 310 311 bool EmbeddedTestServer::PostTaskToIOThreadAndWait( 312 const base::Closure& closure) { 313 // Note that PostTaskAndReply below requires base::MessageLoopProxy::current() 314 // to return a loop for posting the reply task. However, in order to make 315 // EmbeddedTestServer universally usable, it needs to cope with the situation 316 // where it's running on a thread on which a message loop is not (yet) 317 // available or as has been destroyed already. 318 // 319 // To handle this situation, create temporary message loop to support the 320 // PostTaskAndReply operation if the current thread as no message loop. 321 scoped_ptr<base::MessageLoop> temporary_loop; 322 if (!base::MessageLoop::current()) 323 temporary_loop.reset(new base::MessageLoop()); 324 325 base::RunLoop run_loop; 326 if (!io_thread_->message_loop_proxy()->PostTaskAndReply( 327 FROM_HERE, closure, run_loop.QuitClosure())) { 328 return false; 329 } 330 run_loop.Run(); 331 332 return true; 333 } 334 335 } // namespace test_server 336 } // namespace net 337