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