base_test_server.cc revision 7dbb3d5cf0c15f500944d211057644d6a2f37371
1// Copyright 2013 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/spawned_test_server/base_test_server.h"
6
7#include <string>
8#include <vector>
9
10#include "base/base64.h"
11#include "base/file_util.h"
12#include "base/json/json_reader.h"
13#include "base/logging.h"
14#include "base/path_service.h"
15#include "base/values.h"
16#include "net/base/address_list.h"
17#include "net/base/host_port_pair.h"
18#include "net/base/net_errors.h"
19#include "net/base/net_log.h"
20#include "net/base/net_util.h"
21#include "net/base/test_completion_callback.h"
22#include "net/cert/test_root_certs.h"
23#include "net/dns/host_resolver.h"
24#include "url/gurl.h"
25
26namespace net {
27
28namespace {
29
30std::string GetHostname(BaseTestServer::Type type,
31                        const BaseTestServer::SSLOptions& options) {
32  if (BaseTestServer::UsingSSL(type) &&
33      options.server_certificate ==
34          BaseTestServer::SSLOptions::CERT_MISMATCHED_NAME) {
35    // Return a different hostname string that resolves to the same hostname.
36    return "localhost";
37  }
38
39  // Use the 127.0.0.1 as default.
40  return BaseTestServer::kLocalhost;
41}
42
43void GetCiphersList(int cipher, base::ListValue* values) {
44  if (cipher & BaseTestServer::SSLOptions::BULK_CIPHER_RC4)
45    values->Append(new base::StringValue("rc4"));
46  if (cipher & BaseTestServer::SSLOptions::BULK_CIPHER_AES128)
47    values->Append(new base::StringValue("aes128"));
48  if (cipher & BaseTestServer::SSLOptions::BULK_CIPHER_AES256)
49    values->Append(new base::StringValue("aes256"));
50  if (cipher & BaseTestServer::SSLOptions::BULK_CIPHER_3DES)
51    values->Append(new base::StringValue("3des"));
52}
53
54}  // namespace
55
56BaseTestServer::SSLOptions::SSLOptions()
57    : server_certificate(CERT_OK),
58      ocsp_status(OCSP_OK),
59      request_client_certificate(false),
60      bulk_ciphers(SSLOptions::BULK_CIPHER_ANY),
61      record_resume(false),
62      tls_intolerant(TLS_INTOLERANT_NONE) {}
63
64BaseTestServer::SSLOptions::SSLOptions(
65    BaseTestServer::SSLOptions::ServerCertificate cert)
66    : server_certificate(cert),
67      request_client_certificate(false),
68      bulk_ciphers(SSLOptions::BULK_CIPHER_ANY),
69      record_resume(false),
70      tls_intolerant(TLS_INTOLERANT_NONE) {}
71
72BaseTestServer::SSLOptions::~SSLOptions() {}
73
74base::FilePath BaseTestServer::SSLOptions::GetCertificateFile() const {
75  switch (server_certificate) {
76    case CERT_OK:
77    case CERT_MISMATCHED_NAME:
78      return base::FilePath(FILE_PATH_LITERAL("ok_cert.pem"));
79    case CERT_EXPIRED:
80      return base::FilePath(FILE_PATH_LITERAL("expired_cert.pem"));
81    case CERT_CHAIN_WRONG_ROOT:
82      // This chain uses its own dedicated test root certificate to avoid
83      // side-effects that may affect testing.
84      return base::FilePath(FILE_PATH_LITERAL("redundant-server-chain.pem"));
85    case CERT_AUTO:
86      return base::FilePath();
87    default:
88      NOTREACHED();
89  }
90  return base::FilePath();
91}
92
93std::string BaseTestServer::SSLOptions::GetOCSPArgument() const {
94  if (server_certificate != CERT_AUTO)
95    return std::string();
96
97  switch (ocsp_status) {
98    case OCSP_OK:
99      return "ok";
100    case OCSP_REVOKED:
101      return "revoked";
102    case OCSP_INVALID:
103      return "invalid";
104    case OCSP_UNAUTHORIZED:
105      return "unauthorized";
106    case OCSP_UNKNOWN:
107      return "unknown";
108    default:
109      NOTREACHED();
110      return std::string();
111  }
112}
113
114const char BaseTestServer::kLocalhost[] = "127.0.0.1";
115
116BaseTestServer::BaseTestServer(Type type, const std::string& host)
117    : type_(type),
118      started_(false),
119      log_to_console_(false) {
120  Init(host);
121}
122
123BaseTestServer::BaseTestServer(Type type, const SSLOptions& ssl_options)
124    : ssl_options_(ssl_options),
125      type_(type),
126      started_(false),
127      log_to_console_(false) {
128  DCHECK(UsingSSL(type));
129  Init(GetHostname(type, ssl_options));
130}
131
132BaseTestServer::~BaseTestServer() {}
133
134const HostPortPair& BaseTestServer::host_port_pair() const {
135  DCHECK(started_);
136  return host_port_pair_;
137}
138
139const base::DictionaryValue& BaseTestServer::server_data() const {
140  DCHECK(started_);
141  DCHECK(server_data_.get());
142  return *server_data_;
143}
144
145std::string BaseTestServer::GetScheme() const {
146  switch (type_) {
147    case TYPE_FTP:
148      return "ftp";
149    case TYPE_HTTP:
150      return "http";
151    case TYPE_HTTPS:
152      return "https";
153    case TYPE_WS:
154      return "ws";
155    case TYPE_WSS:
156      return "wss";
157    case TYPE_TCP_ECHO:
158    case TYPE_UDP_ECHO:
159    default:
160      NOTREACHED();
161  }
162  return std::string();
163}
164
165bool BaseTestServer::GetAddressList(AddressList* address_list) const {
166  DCHECK(address_list);
167
168  scoped_ptr<HostResolver> resolver(HostResolver::CreateDefaultResolver(NULL));
169  HostResolver::RequestInfo info(host_port_pair_);
170  TestCompletionCallback callback;
171  int rv = resolver->Resolve(info, address_list, callback.callback(), NULL,
172                             BoundNetLog());
173  if (rv == ERR_IO_PENDING)
174    rv = callback.WaitForResult();
175  if (rv != net::OK) {
176    LOG(ERROR) << "Failed to resolve hostname: " << host_port_pair_.host();
177    return false;
178  }
179  return true;
180}
181
182uint16 BaseTestServer::GetPort() {
183  return host_port_pair_.port();
184}
185
186void BaseTestServer::SetPort(uint16 port) {
187  host_port_pair_.set_port(port);
188}
189
190GURL BaseTestServer::GetURL(const std::string& path) const {
191  return GURL(GetScheme() + "://" + host_port_pair_.ToString() + "/" + path);
192}
193
194GURL BaseTestServer::GetURLWithUser(const std::string& path,
195                                const std::string& user) const {
196  return GURL(GetScheme() + "://" + user + "@" + host_port_pair_.ToString() +
197              "/" + path);
198}
199
200GURL BaseTestServer::GetURLWithUserAndPassword(const std::string& path,
201                                           const std::string& user,
202                                           const std::string& password) const {
203  return GURL(GetScheme() + "://" + user + ":" + password + "@" +
204              host_port_pair_.ToString() + "/" + path);
205}
206
207// static
208bool BaseTestServer::GetFilePathWithReplacements(
209    const std::string& original_file_path,
210    const std::vector<StringPair>& text_to_replace,
211    std::string* replacement_path) {
212  std::string new_file_path = original_file_path;
213  bool first_query_parameter = true;
214  const std::vector<StringPair>::const_iterator end = text_to_replace.end();
215  for (std::vector<StringPair>::const_iterator it = text_to_replace.begin();
216       it != end;
217       ++it) {
218    const std::string& old_text = it->first;
219    const std::string& new_text = it->second;
220    std::string base64_old;
221    std::string base64_new;
222    if (!base::Base64Encode(old_text, &base64_old))
223      return false;
224    if (!base::Base64Encode(new_text, &base64_new))
225      return false;
226    if (first_query_parameter) {
227      new_file_path += "?";
228      first_query_parameter = false;
229    } else {
230      new_file_path += "&";
231    }
232    new_file_path += "replace_text=";
233    new_file_path += base64_old;
234    new_file_path += ":";
235    new_file_path += base64_new;
236  }
237
238  *replacement_path = new_file_path;
239  return true;
240}
241
242void BaseTestServer::Init(const std::string& host) {
243  host_port_pair_ = HostPortPair(host, 0);
244
245  // TODO(battre) Remove this after figuring out why the TestServer is flaky.
246  // http://crbug.com/96594
247  log_to_console_ = true;
248}
249
250void BaseTestServer::SetResourcePath(const base::FilePath& document_root,
251                                     const base::FilePath& certificates_dir) {
252  // This method shouldn't get called twice.
253  DCHECK(certificates_dir_.empty());
254  document_root_ = document_root;
255  certificates_dir_ = certificates_dir;
256  DCHECK(!certificates_dir_.empty());
257}
258
259bool BaseTestServer::ParseServerData(const std::string& server_data) {
260  VLOG(1) << "Server data: " << server_data;
261  base::JSONReader json_reader;
262  scoped_ptr<base::Value> value(json_reader.ReadToValue(server_data));
263  if (!value.get() || !value->IsType(base::Value::TYPE_DICTIONARY)) {
264    LOG(ERROR) << "Could not parse server data: "
265               << json_reader.GetErrorMessage();
266    return false;
267  }
268
269  server_data_.reset(static_cast<base::DictionaryValue*>(value.release()));
270  int port = 0;
271  if (!server_data_->GetInteger("port", &port)) {
272    LOG(ERROR) << "Could not find port value";
273    return false;
274  }
275  if ((port <= 0) || (port > kuint16max)) {
276    LOG(ERROR) << "Invalid port value: " << port;
277    return false;
278  }
279  host_port_pair_.set_port(port);
280
281  return true;
282}
283
284bool BaseTestServer::LoadTestRootCert() const {
285  TestRootCerts* root_certs = TestRootCerts::GetInstance();
286  if (!root_certs)
287    return false;
288
289  // Should always use absolute path to load the root certificate.
290  base::FilePath root_certificate_path = certificates_dir_;
291  if (!certificates_dir_.IsAbsolute()) {
292    base::FilePath src_dir;
293    if (!PathService::Get(base::DIR_SOURCE_ROOT, &src_dir))
294      return false;
295    root_certificate_path = src_dir.Append(certificates_dir_);
296  }
297
298  return root_certs->AddFromFile(
299      root_certificate_path.AppendASCII("root_ca_cert.pem"));
300}
301
302bool BaseTestServer::SetupWhenServerStarted() {
303  DCHECK(host_port_pair_.port());
304
305  if (UsingSSL(type_) && !LoadTestRootCert())
306      return false;
307
308  started_ = true;
309  allowed_port_.reset(new ScopedPortException(host_port_pair_.port()));
310  return true;
311}
312
313void BaseTestServer::CleanUpWhenStoppingServer() {
314  TestRootCerts* root_certs = TestRootCerts::GetInstance();
315  root_certs->Clear();
316
317  host_port_pair_.set_port(0);
318  allowed_port_.reset();
319  started_ = false;
320}
321
322// Generates a dictionary of arguments to pass to the Python test server via
323// the test server spawner, in the form of
324// { argument-name: argument-value, ... }
325// Returns false if an invalid configuration is specified.
326bool BaseTestServer::GenerateArguments(base::DictionaryValue* arguments) const {
327  DCHECK(arguments);
328
329  arguments->SetString("host", host_port_pair_.host());
330  arguments->SetInteger("port", host_port_pair_.port());
331  arguments->SetString("data-dir", document_root_.value());
332
333  if (VLOG_IS_ON(1) || log_to_console_)
334    arguments->Set("log-to-console", base::Value::CreateNullValue());
335
336  if (UsingSSL(type_)) {
337    // Check the certificate arguments of the HTTPS server.
338    base::FilePath certificate_path(certificates_dir_);
339    base::FilePath certificate_file(ssl_options_.GetCertificateFile());
340    if (!certificate_file.value().empty()) {
341      certificate_path = certificate_path.Append(certificate_file);
342      if (certificate_path.IsAbsolute() &&
343          !base::PathExists(certificate_path)) {
344        LOG(ERROR) << "Certificate path " << certificate_path.value()
345                   << " doesn't exist. Can't launch https server.";
346        return false;
347      }
348      arguments->SetString("cert-and-key-file", certificate_path.value());
349    }
350
351    // Check the client certificate related arguments.
352    if (ssl_options_.request_client_certificate)
353      arguments->Set("ssl-client-auth", base::Value::CreateNullValue());
354    scoped_ptr<base::ListValue> ssl_client_certs(new base::ListValue());
355
356    std::vector<base::FilePath>::const_iterator it;
357    for (it = ssl_options_.client_authorities.begin();
358         it != ssl_options_.client_authorities.end(); ++it) {
359      if (it->IsAbsolute() && !base::PathExists(*it)) {
360        LOG(ERROR) << "Client authority path " << it->value()
361                   << " doesn't exist. Can't launch https server.";
362        return false;
363      }
364      ssl_client_certs->Append(new base::StringValue(it->value()));
365    }
366
367    if (ssl_client_certs->GetSize())
368      arguments->Set("ssl-client-ca", ssl_client_certs.release());
369  }
370
371  if (type_ == TYPE_HTTPS) {
372    arguments->Set("https", base::Value::CreateNullValue());
373
374    std::string ocsp_arg = ssl_options_.GetOCSPArgument();
375    if (!ocsp_arg.empty())
376      arguments->SetString("ocsp", ocsp_arg);
377
378    // Check bulk cipher argument.
379    scoped_ptr<base::ListValue> bulk_cipher_values(new base::ListValue());
380    GetCiphersList(ssl_options_.bulk_ciphers, bulk_cipher_values.get());
381    if (bulk_cipher_values->GetSize())
382      arguments->Set("ssl-bulk-cipher", bulk_cipher_values.release());
383    if (ssl_options_.record_resume)
384      arguments->Set("https-record-resume", base::Value::CreateNullValue());
385    if (ssl_options_.tls_intolerant != SSLOptions::TLS_INTOLERANT_NONE) {
386      arguments->Set("tls-intolerant",
387                     new base::FundamentalValue(ssl_options_.tls_intolerant));
388    }
389  }
390
391  return GenerateAdditionalArguments(arguments);
392}
393
394bool BaseTestServer::GenerateAdditionalArguments(
395    base::DictionaryValue* arguments) const {
396  return true;
397}
398
399}  // namespace net
400