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