- add sources.
[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/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
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 EmbeddedTestServer::EmbeddedTestServer()
103     : io_thread_("EmbeddedTestServer io thread"),
104       port_(-1),
105       weak_factory_(this) {
106   DCHECK(thread_checker_.CalledOnValidThread());
107
108   base::Thread::Options thread_options;
109   thread_options.message_loop_type = base::MessageLoop::TYPE_IO;
110   CHECK(io_thread_.StartWithOptions(thread_options));
111 }
112
113 EmbeddedTestServer::~EmbeddedTestServer() {
114   DCHECK(thread_checker_.CalledOnValidThread());
115
116   if (Started() && !ShutdownAndWaitUntilComplete()) {
117     LOG(ERROR) << "EmbeddedTestServer failed to shut down.";
118   }
119 }
120
121 bool EmbeddedTestServer::InitializeAndWaitUntilReady() {
122   DCHECK(thread_checker_.CalledOnValidThread());
123
124   if (!PostTaskToIOThreadAndWait(base::Bind(
125           &EmbeddedTestServer::InitializeOnIOThread, base::Unretained(this)))) {
126     return false;
127   }
128
129   return Started() && base_url_.is_valid();
130 }
131
132 bool EmbeddedTestServer::ShutdownAndWaitUntilComplete() {
133   DCHECK(thread_checker_.CalledOnValidThread());
134
135   return PostTaskToIOThreadAndWait(base::Bind(
136       &EmbeddedTestServer::ShutdownOnIOThread, base::Unretained(this)));
137 }
138
139 void EmbeddedTestServer::InitializeOnIOThread() {
140   DCHECK(io_thread_.message_loop_proxy()->BelongsToCurrentThread());
141   DCHECK(!Started());
142
143   SocketDescriptor socket_descriptor =
144       TCPListenSocket::CreateAndBindAnyPort("127.0.0.1", &port_);
145   if (socket_descriptor == kInvalidSocket)
146     return;
147
148   listen_socket_.reset(new HttpListenSocket(socket_descriptor, this));
149   listen_socket_->Listen();
150
151   IPEndPoint address;
152   int result = listen_socket_->GetLocalAddress(&address);
153   if (result == OK) {
154     base_url_ = GURL(std::string("http://") + address.ToString());
155   } else {
156     LOG(ERROR) << "GetLocalAddress failed: " << ErrorToString(result);
157   }
158 }
159
160 void EmbeddedTestServer::ShutdownOnIOThread() {
161   DCHECK(io_thread_.message_loop_proxy()->BelongsToCurrentThread());
162
163   listen_socket_.reset();
164   STLDeleteContainerPairSecondPointers(connections_.begin(),
165                                        connections_.end());
166   connections_.clear();
167 }
168
169 void EmbeddedTestServer::HandleRequest(HttpConnection* connection,
170                                scoped_ptr<HttpRequest> request) {
171   DCHECK(io_thread_.message_loop_proxy()->BelongsToCurrentThread());
172
173   bool request_handled = false;
174
175   for (size_t i = 0; i < request_handlers_.size(); ++i) {
176     scoped_ptr<HttpResponse> response =
177         request_handlers_[i].Run(*request.get());
178     if (response.get()) {
179       connection->SendResponse(response.Pass());
180       request_handled = true;
181       break;
182     }
183   }
184
185   if (!request_handled) {
186     LOG(WARNING) << "Request not handled. Returning 404: "
187                  << request->relative_url;
188     scoped_ptr<BasicHttpResponse> not_found_response(new BasicHttpResponse);
189     not_found_response->set_code(HTTP_NOT_FOUND);
190     connection->SendResponse(
191         not_found_response.PassAs<HttpResponse>());
192   }
193
194   // Drop the connection, since we do not support multiple requests per
195   // connection.
196   connections_.erase(connection->socket_.get());
197   delete connection;
198 }
199
200 GURL EmbeddedTestServer::GetURL(const std::string& relative_url) const {
201   DCHECK(Started()) << "You must start the server first.";
202   DCHECK(StartsWithASCII(relative_url, "/", true /* case_sensitive */))
203       << relative_url;
204   return base_url_.Resolve(relative_url);
205 }
206
207 void EmbeddedTestServer::ServeFilesFromDirectory(
208     const base::FilePath& directory) {
209   RegisterRequestHandler(base::Bind(&HandleFileRequest, directory));
210 }
211
212 void EmbeddedTestServer::RegisterRequestHandler(
213     const HandleRequestCallback& callback) {
214   request_handlers_.push_back(callback);
215 }
216
217 void EmbeddedTestServer::DidAccept(
218     StreamListenSocket* server,
219     scoped_ptr<StreamListenSocket> connection) {
220   DCHECK(io_thread_.message_loop_proxy()->BelongsToCurrentThread());
221
222   HttpConnection* http_connection = new HttpConnection(
223       connection.Pass(),
224       base::Bind(&EmbeddedTestServer::HandleRequest,
225                  weak_factory_.GetWeakPtr()));
226   // TODO(szym): Make HttpConnection the StreamListenSocket delegate.
227   connections_[http_connection->socket_.get()] = http_connection;
228 }
229
230 void EmbeddedTestServer::DidRead(StreamListenSocket* connection,
231                          const char* data,
232                          int length) {
233   DCHECK(io_thread_.message_loop_proxy()->BelongsToCurrentThread());
234
235   HttpConnection* http_connection = FindConnection(connection);
236   if (http_connection == NULL) {
237     LOG(WARNING) << "Unknown connection.";
238     return;
239   }
240   http_connection->ReceiveData(std::string(data, length));
241 }
242
243 void EmbeddedTestServer::DidClose(StreamListenSocket* connection) {
244   DCHECK(io_thread_.message_loop_proxy()->BelongsToCurrentThread());
245
246   HttpConnection* http_connection = FindConnection(connection);
247   if (http_connection == NULL) {
248     LOG(WARNING) << "Unknown connection.";
249     return;
250   }
251   delete http_connection;
252   connections_.erase(connection);
253 }
254
255 HttpConnection* EmbeddedTestServer::FindConnection(
256     StreamListenSocket* socket) {
257   DCHECK(io_thread_.message_loop_proxy()->BelongsToCurrentThread());
258
259   std::map<StreamListenSocket*, HttpConnection*>::iterator it =
260       connections_.find(socket);
261   if (it == connections_.end()) {
262     return NULL;
263   }
264   return it->second;
265 }
266
267 bool EmbeddedTestServer::PostTaskToIOThreadAndWait(
268     const base::Closure& closure) {
269   // Note that PostTaskAndReply below requires base::MessageLoopProxy::current()
270   // to return a loop for posting the reply task. However, in order to make
271   // EmbeddedTestServer universally usable, it needs to cope with the situation
272   // where it's running on a thread on which a message loop is not (yet)
273   // available or as has been destroyed already.
274   //
275   // To handle this situation, create temporary message loop to support the
276   // PostTaskAndReply operation if the current thread as no message loop.
277   scoped_ptr<base::MessageLoop> temporary_loop;
278   if (!base::MessageLoop::current())
279     temporary_loop.reset(new base::MessageLoop());
280
281   base::RunLoop run_loop;
282   if (!io_thread_.message_loop_proxy()->PostTaskAndReply(
283           FROM_HERE, closure, run_loop.QuitClosure())) {
284     return false;
285   }
286   run_loop.Run();
287
288   return true;
289 }
290
291 }  // namespace test_server
292 }  // namespace net