| OLD | NEW |
| (Empty) |
| 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/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" | |
| 22 | |
| 23 namespace net { | |
| 24 namespace test_server { | |
| 25 | |
| 26 namespace { | |
| 27 | |
| 28 class CustomHttpResponse : public HttpResponse { | |
| 29 public: | |
| 30 CustomHttpResponse(const std::string& headers, const std::string& contents) | |
| 31 : headers_(headers), contents_(contents) { | |
| 32 } | |
| 33 | |
| 34 std::string ToResponseString() const override { | |
| 35 return headers_ + "\r\n" + contents_; | |
| 36 } | |
| 37 | |
| 38 private: | |
| 39 std::string headers_; | |
| 40 std::string contents_; | |
| 41 | |
| 42 DISALLOW_COPY_AND_ASSIGN(CustomHttpResponse); | |
| 43 }; | |
| 44 | |
| 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; | |
| 51 | |
| 52 std::string relative_url(request.relative_url); | |
| 53 // A proxy request will have an absolute path. Simulate the proxy by stripping | |
| 54 // the scheme, host, and port. | |
| 55 GURL relative_gurl(relative_url); | |
| 56 if (relative_gurl.is_valid()) | |
| 57 relative_url = relative_gurl.PathForRequest(); | |
| 58 | |
| 59 // Trim the first byte ('/'). | |
| 60 std::string request_path = relative_url.substr(1); | |
| 61 | |
| 62 // Remove the query string if present. | |
| 63 size_t query_pos = request_path.find('?'); | |
| 64 if (query_pos != std::string::npos) | |
| 65 request_path = request_path.substr(0, query_pos); | |
| 66 | |
| 67 base::FilePath file_path(server_root.AppendASCII(request_path)); | |
| 68 std::string file_contents; | |
| 69 if (!base::ReadFileToString(file_path, &file_contents)) | |
| 70 return scoped_ptr<HttpResponse>(); | |
| 71 | |
| 72 base::FilePath headers_path( | |
| 73 file_path.AddExtension(FILE_PATH_LITERAL("mock-http-headers"))); | |
| 74 | |
| 75 if (base::PathExists(headers_path)) { | |
| 76 std::string headers_contents; | |
| 77 if (!base::ReadFileToString(headers_path, &headers_contents)) | |
| 78 return scoped_ptr<HttpResponse>(); | |
| 79 | |
| 80 scoped_ptr<CustomHttpResponse> http_response( | |
| 81 new CustomHttpResponse(headers_contents, file_contents)); | |
| 82 return http_response.Pass(); | |
| 83 } | |
| 84 | |
| 85 scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); | |
| 86 http_response->set_code(HTTP_OK); | |
| 87 http_response->set_content(file_contents); | |
| 88 return http_response.Pass(); | |
| 89 } | |
| 90 | |
| 91 } // namespace | |
| 92 | |
| 93 HttpListenSocket::HttpListenSocket(const SocketDescriptor socket_descriptor, | |
| 94 StreamListenSocket::Delegate* delegate) | |
| 95 : TCPListenSocket(socket_descriptor, delegate) { | |
| 96 DCHECK(thread_checker_.CalledOnValidThread()); | |
| 97 } | |
| 98 | |
| 99 void HttpListenSocket::Listen() { | |
| 100 DCHECK(thread_checker_.CalledOnValidThread()); | |
| 101 TCPListenSocket::Listen(); | |
| 102 } | |
| 103 | |
| 104 void HttpListenSocket::ListenOnIOThread() { | |
| 105 DCHECK(thread_checker_.CalledOnValidThread()); | |
| 106 #if !defined(OS_POSIX) | |
| 107 // This method may be called after the IO thread is changed, thus we need to | |
| 108 // call |WatchSocket| again to make sure it listens on the current IO thread. | |
| 109 // Only needed for non POSIX platforms, since on POSIX platforms | |
| 110 // StreamListenSocket::Listen already calls WatchSocket inside the function. | |
| 111 WatchSocket(WAITING_ACCEPT); | |
| 112 #endif | |
| 113 Listen(); | |
| 114 } | |
| 115 | |
| 116 HttpListenSocket::~HttpListenSocket() { | |
| 117 DCHECK(thread_checker_.CalledOnValidThread()); | |
| 118 } | |
| 119 | |
| 120 void HttpListenSocket::DetachFromThread() { | |
| 121 thread_checker_.DetachFromThread(); | |
| 122 } | |
| 123 | |
| 124 EmbeddedTestServer::EmbeddedTestServer() | |
| 125 : port_(0), | |
| 126 weak_factory_(this) { | |
| 127 DCHECK(thread_checker_.CalledOnValidThread()); | |
| 128 } | |
| 129 | |
| 130 EmbeddedTestServer::~EmbeddedTestServer() { | |
| 131 DCHECK(thread_checker_.CalledOnValidThread()); | |
| 132 | |
| 133 if (Started() && !ShutdownAndWaitUntilComplete()) { | |
| 134 LOG(ERROR) << "EmbeddedTestServer failed to shut down."; | |
| 135 } | |
| 136 } | |
| 137 | |
| 138 bool EmbeddedTestServer::InitializeAndWaitUntilReady() { | |
| 139 StartThread(); | |
| 140 DCHECK(thread_checker_.CalledOnValidThread()); | |
| 141 if (!PostTaskToIOThreadAndWait(base::Bind( | |
| 142 &EmbeddedTestServer::InitializeOnIOThread, base::Unretained(this)))) { | |
| 143 return false; | |
| 144 } | |
| 145 return Started() && base_url_.is_valid(); | |
| 146 } | |
| 147 | |
| 148 void EmbeddedTestServer::StopThread() { | |
| 149 DCHECK(io_thread_ && io_thread_->IsRunning()); | |
| 150 | |
| 151 #if defined(OS_LINUX) | |
| 152 const int thread_count = | |
| 153 base::GetNumberOfThreads(base::GetCurrentProcessHandle()); | |
| 154 #endif | |
| 155 | |
| 156 io_thread_->Stop(); | |
| 157 io_thread_.reset(); | |
| 158 thread_checker_.DetachFromThread(); | |
| 159 listen_socket_->DetachFromThread(); | |
| 160 | |
| 161 #if defined(OS_LINUX) | |
| 162 // Busy loop to wait for thread count to decrease. This is needed because | |
| 163 // pthread_join does not guarantee that kernel stat is updated when it | |
| 164 // returns. Thus, GetNumberOfThreads does not immediately reflect the stopped | |
| 165 // thread and hits the thread number DCHECK in render_sandbox_host_linux.cc | |
| 166 // in browser_tests. | |
| 167 while (thread_count == | |
| 168 base::GetNumberOfThreads(base::GetCurrentProcessHandle())) { | |
| 169 base::PlatformThread::YieldCurrentThread(); | |
| 170 } | |
| 171 #endif | |
| 172 } | |
| 173 | |
| 174 void EmbeddedTestServer::RestartThreadAndListen() { | |
| 175 StartThread(); | |
| 176 CHECK(PostTaskToIOThreadAndWait(base::Bind( | |
| 177 &EmbeddedTestServer::ListenOnIOThread, base::Unretained(this)))); | |
| 178 } | |
| 179 | |
| 180 bool EmbeddedTestServer::ShutdownAndWaitUntilComplete() { | |
| 181 DCHECK(thread_checker_.CalledOnValidThread()); | |
| 182 | |
| 183 return PostTaskToIOThreadAndWait(base::Bind( | |
| 184 &EmbeddedTestServer::ShutdownOnIOThread, base::Unretained(this))); | |
| 185 } | |
| 186 | |
| 187 void EmbeddedTestServer::StartThread() { | |
| 188 DCHECK(!io_thread_.get()); | |
| 189 base::Thread::Options thread_options; | |
| 190 thread_options.message_loop_type = base::MessageLoop::TYPE_IO; | |
| 191 io_thread_.reset(new base::Thread("EmbeddedTestServer io thread")); | |
| 192 CHECK(io_thread_->StartWithOptions(thread_options)); | |
| 193 } | |
| 194 | |
| 195 void EmbeddedTestServer::InitializeOnIOThread() { | |
| 196 DCHECK(io_thread_->message_loop_proxy()->BelongsToCurrentThread()); | |
| 197 DCHECK(!Started()); | |
| 198 | |
| 199 SocketDescriptor socket_descriptor = | |
| 200 TCPListenSocket::CreateAndBindAnyPort("127.0.0.1", &port_); | |
| 201 if (socket_descriptor == kInvalidSocket) | |
| 202 return; | |
| 203 | |
| 204 listen_socket_.reset(new HttpListenSocket(socket_descriptor, this)); | |
| 205 listen_socket_->Listen(); | |
| 206 | |
| 207 IPEndPoint address; | |
| 208 int result = listen_socket_->GetLocalAddress(&address); | |
| 209 if (result == OK) { | |
| 210 base_url_ = GURL(std::string("http://") + address.ToString()); | |
| 211 } else { | |
| 212 LOG(ERROR) << "GetLocalAddress failed: " << ErrorToString(result); | |
| 213 } | |
| 214 } | |
| 215 | |
| 216 void EmbeddedTestServer::ListenOnIOThread() { | |
| 217 DCHECK(io_thread_->message_loop_proxy()->BelongsToCurrentThread()); | |
| 218 DCHECK(Started()); | |
| 219 listen_socket_->ListenOnIOThread(); | |
| 220 } | |
| 221 | |
| 222 void EmbeddedTestServer::ShutdownOnIOThread() { | |
| 223 DCHECK(io_thread_->message_loop_proxy()->BelongsToCurrentThread()); | |
| 224 | |
| 225 listen_socket_.reset(); | |
| 226 STLDeleteContainerPairSecondPointers(connections_.begin(), | |
| 227 connections_.end()); | |
| 228 connections_.clear(); | |
| 229 } | |
| 230 | |
| 231 void EmbeddedTestServer::HandleRequest(HttpConnection* connection, | |
| 232 scoped_ptr<HttpRequest> request) { | |
| 233 DCHECK(io_thread_->message_loop_proxy()->BelongsToCurrentThread()); | |
| 234 | |
| 235 bool request_handled = false; | |
| 236 | |
| 237 for (size_t i = 0; i < request_handlers_.size(); ++i) { | |
| 238 scoped_ptr<HttpResponse> response = | |
| 239 request_handlers_[i].Run(*request.get()); | |
| 240 if (response.get()) { | |
| 241 connection->SendResponse(response.Pass()); | |
| 242 request_handled = true; | |
| 243 break; | |
| 244 } | |
| 245 } | |
| 246 | |
| 247 if (!request_handled) { | |
| 248 LOG(WARNING) << "Request not handled. Returning 404: " | |
| 249 << request->relative_url; | |
| 250 scoped_ptr<BasicHttpResponse> not_found_response(new BasicHttpResponse); | |
| 251 not_found_response->set_code(HTTP_NOT_FOUND); | |
| 252 connection->SendResponse(not_found_response.Pass()); | |
| 253 } | |
| 254 | |
| 255 // Drop the connection, since we do not support multiple requests per | |
| 256 // connection. | |
| 257 connections_.erase(connection->socket_.get()); | |
| 258 delete connection; | |
| 259 } | |
| 260 | |
| 261 GURL EmbeddedTestServer::GetURL(const std::string& relative_url) const { | |
| 262 DCHECK(Started()) << "You must start the server first."; | |
| 263 DCHECK(StartsWithASCII(relative_url, "/", true /* case_sensitive */)) | |
| 264 << relative_url; | |
| 265 return base_url_.Resolve(relative_url); | |
| 266 } | |
| 267 | |
| 268 GURL EmbeddedTestServer::GetURL( | |
| 269 const std::string& hostname, | |
| 270 const std::string& relative_url) const { | |
| 271 GURL local_url = GetURL(relative_url); | |
| 272 GURL::Replacements replace_host; | |
| 273 replace_host.SetHostStr(hostname); | |
| 274 return local_url.ReplaceComponents(replace_host); | |
| 275 } | |
| 276 | |
| 277 void EmbeddedTestServer::ServeFilesFromDirectory( | |
| 278 const base::FilePath& directory) { | |
| 279 RegisterRequestHandler(base::Bind(&HandleFileRequest, directory)); | |
| 280 } | |
| 281 | |
| 282 void EmbeddedTestServer::RegisterRequestHandler( | |
| 283 const HandleRequestCallback& callback) { | |
| 284 request_handlers_.push_back(callback); | |
| 285 } | |
| 286 | |
| 287 void EmbeddedTestServer::DidAccept( | |
| 288 StreamListenSocket* server, | |
| 289 scoped_ptr<StreamListenSocket> connection) { | |
| 290 DCHECK(io_thread_->message_loop_proxy()->BelongsToCurrentThread()); | |
| 291 | |
| 292 HttpConnection* http_connection = new HttpConnection( | |
| 293 connection.Pass(), | |
| 294 base::Bind(&EmbeddedTestServer::HandleRequest, | |
| 295 weak_factory_.GetWeakPtr())); | |
| 296 // TODO(szym): Make HttpConnection the StreamListenSocket delegate. | |
| 297 connections_[http_connection->socket_.get()] = http_connection; | |
| 298 } | |
| 299 | |
| 300 void EmbeddedTestServer::DidRead(StreamListenSocket* connection, | |
| 301 const char* data, | |
| 302 int length) { | |
| 303 DCHECK(io_thread_->message_loop_proxy()->BelongsToCurrentThread()); | |
| 304 | |
| 305 HttpConnection* http_connection = FindConnection(connection); | |
| 306 if (http_connection == NULL) { | |
| 307 LOG(WARNING) << "Unknown connection."; | |
| 308 return; | |
| 309 } | |
| 310 http_connection->ReceiveData(std::string(data, length)); | |
| 311 } | |
| 312 | |
| 313 void EmbeddedTestServer::DidClose(StreamListenSocket* connection) { | |
| 314 DCHECK(io_thread_->message_loop_proxy()->BelongsToCurrentThread()); | |
| 315 | |
| 316 HttpConnection* http_connection = FindConnection(connection); | |
| 317 if (http_connection == NULL) { | |
| 318 LOG(WARNING) << "Unknown connection."; | |
| 319 return; | |
| 320 } | |
| 321 delete http_connection; | |
| 322 connections_.erase(connection); | |
| 323 } | |
| 324 | |
| 325 HttpConnection* EmbeddedTestServer::FindConnection( | |
| 326 StreamListenSocket* socket) { | |
| 327 DCHECK(io_thread_->message_loop_proxy()->BelongsToCurrentThread()); | |
| 328 | |
| 329 std::map<StreamListenSocket*, HttpConnection*>::iterator it = | |
| 330 connections_.find(socket); | |
| 331 if (it == connections_.end()) { | |
| 332 return NULL; | |
| 333 } | |
| 334 return it->second; | |
| 335 } | |
| 336 | |
| 337 bool EmbeddedTestServer::PostTaskToIOThreadAndWait( | |
| 338 const base::Closure& closure) { | |
| 339 // Note that PostTaskAndReply below requires base::MessageLoopProxy::current() | |
| 340 // to return a loop for posting the reply task. However, in order to make | |
| 341 // EmbeddedTestServer universally usable, it needs to cope with the situation | |
| 342 // where it's running on a thread on which a message loop is not (yet) | |
| 343 // available or as has been destroyed already. | |
| 344 // | |
| 345 // To handle this situation, create temporary message loop to support the | |
| 346 // PostTaskAndReply operation if the current thread as no message loop. | |
| 347 scoped_ptr<base::MessageLoop> temporary_loop; | |
| 348 if (!base::MessageLoop::current()) | |
| 349 temporary_loop.reset(new base::MessageLoop()); | |
| 350 | |
| 351 base::RunLoop run_loop; | |
| 352 if (!io_thread_->message_loop_proxy()->PostTaskAndReply( | |
| 353 FROM_HERE, closure, run_loop.QuitClosure())) { | |
| 354 return false; | |
| 355 } | |
| 356 run_loop.Run(); | |
| 357 | |
| 358 return true; | |
| 359 } | |
| 360 | |
| 361 } // namespace test_server | |
| 362 } // namespace net | |
| OLD | NEW |