Home | History | Annotate | Download | only in spawned_test_server
      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 
     26 namespace net {
     27 
     28 namespace {
     29 
     30 std::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 
     43 void 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 
     56 BaseTestServer::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 
     65 BaseTestServer::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 
     75 BaseTestServer::SSLOptions::~SSLOptions() {}
     76 
     77 base::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 
     96 std::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 
    117 const char BaseTestServer::kLocalhost[] = "127.0.0.1";
    118 
    119 BaseTestServer::BaseTestServer(Type type, const std::string& host)
    120     : type_(type),
    121       started_(false),
    122       log_to_console_(false) {
    123   Init(host);
    124 }
    125 
    126 BaseTestServer::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 
    135 BaseTestServer::~BaseTestServer() {}
    136 
    137 const HostPortPair& BaseTestServer::host_port_pair() const {
    138   DCHECK(started_);
    139   return host_port_pair_;
    140 }
    141 
    142 const base::DictionaryValue& BaseTestServer::server_data() const {
    143   DCHECK(started_);
    144   DCHECK(server_data_.get());
    145   return *server_data_;
    146 }
    147 
    148 std::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 
    168 bool 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, address_list, callback.callback(), NULL,
    175                              BoundNetLog());
    176   if (rv == ERR_IO_PENDING)
    177     rv = callback.WaitForResult();
    178   if (rv != net::OK) {
    179     LOG(ERROR) << "Failed to resolve hostname: " << host_port_pair_.host();
    180     return false;
    181   }
    182   return true;
    183 }
    184 
    185 uint16 BaseTestServer::GetPort() {
    186   return host_port_pair_.port();
    187 }
    188 
    189 void BaseTestServer::SetPort(uint16 port) {
    190   host_port_pair_.set_port(port);
    191 }
    192 
    193 GURL BaseTestServer::GetURL(const std::string& path) const {
    194   return GURL(GetScheme() + "://" + host_port_pair_.ToString() + "/" + path);
    195 }
    196 
    197 GURL BaseTestServer::GetURLWithUser(const std::string& path,
    198                                 const std::string& user) const {
    199   return GURL(GetScheme() + "://" + user + "@" + host_port_pair_.ToString() +
    200               "/" + path);
    201 }
    202 
    203 GURL BaseTestServer::GetURLWithUserAndPassword(const std::string& path,
    204                                            const std::string& user,
    205                                            const std::string& password) const {
    206   return GURL(GetScheme() + "://" + user + ":" + password + "@" +
    207               host_port_pair_.ToString() + "/" + path);
    208 }
    209 
    210 // static
    211 bool BaseTestServer::GetFilePathWithReplacements(
    212     const std::string& original_file_path,
    213     const std::vector<StringPair>& text_to_replace,
    214     std::string* replacement_path) {
    215   std::string new_file_path = original_file_path;
    216   bool first_query_parameter = true;
    217   const std::vector<StringPair>::const_iterator end = text_to_replace.end();
    218   for (std::vector<StringPair>::const_iterator it = text_to_replace.begin();
    219        it != end;
    220        ++it) {
    221     const std::string& old_text = it->first;
    222     const std::string& new_text = it->second;
    223     std::string base64_old;
    224     std::string base64_new;
    225     if (!base::Base64Encode(old_text, &base64_old))
    226       return false;
    227     if (!base::Base64Encode(new_text, &base64_new))
    228       return false;
    229     if (first_query_parameter) {
    230       new_file_path += "?";
    231       first_query_parameter = false;
    232     } else {
    233       new_file_path += "&";
    234     }
    235     new_file_path += "replace_text=";
    236     new_file_path += base64_old;
    237     new_file_path += ":";
    238     new_file_path += base64_new;
    239   }
    240 
    241   *replacement_path = new_file_path;
    242   return true;
    243 }
    244 
    245 void BaseTestServer::Init(const std::string& host) {
    246   host_port_pair_ = HostPortPair(host, 0);
    247 
    248   // TODO(battre) Remove this after figuring out why the TestServer is flaky.
    249   // http://crbug.com/96594
    250   log_to_console_ = true;
    251 }
    252 
    253 void BaseTestServer::SetResourcePath(const base::FilePath& document_root,
    254                                      const base::FilePath& certificates_dir) {
    255   // This method shouldn't get called twice.
    256   DCHECK(certificates_dir_.empty());
    257   document_root_ = document_root;
    258   certificates_dir_ = certificates_dir;
    259   DCHECK(!certificates_dir_.empty());
    260 }
    261 
    262 bool BaseTestServer::ParseServerData(const std::string& server_data) {
    263   VLOG(1) << "Server data: " << server_data;
    264   base::JSONReader json_reader;
    265   scoped_ptr<base::Value> value(json_reader.ReadToValue(server_data));
    266   if (!value.get() || !value->IsType(base::Value::TYPE_DICTIONARY)) {
    267     LOG(ERROR) << "Could not parse server data: "
    268                << json_reader.GetErrorMessage();
    269     return false;
    270   }
    271 
    272   server_data_.reset(static_cast<base::DictionaryValue*>(value.release()));
    273   int port = 0;
    274   if (!server_data_->GetInteger("port", &port)) {
    275     LOG(ERROR) << "Could not find port value";
    276     return false;
    277   }
    278   if ((port <= 0) || (port > kuint16max)) {
    279     LOG(ERROR) << "Invalid port value: " << port;
    280     return false;
    281   }
    282   host_port_pair_.set_port(port);
    283 
    284   return true;
    285 }
    286 
    287 bool BaseTestServer::LoadTestRootCert() const {
    288   TestRootCerts* root_certs = TestRootCerts::GetInstance();
    289   if (!root_certs)
    290     return false;
    291 
    292   // Should always use absolute path to load the root certificate.
    293   base::FilePath root_certificate_path = certificates_dir_;
    294   if (!certificates_dir_.IsAbsolute()) {
    295     base::FilePath src_dir;
    296     if (!PathService::Get(base::DIR_SOURCE_ROOT, &src_dir))
    297       return false;
    298     root_certificate_path = src_dir.Append(certificates_dir_);
    299   }
    300 
    301   return root_certs->AddFromFile(
    302       root_certificate_path.AppendASCII("root_ca_cert.pem"));
    303 }
    304 
    305 bool BaseTestServer::SetupWhenServerStarted() {
    306   DCHECK(host_port_pair_.port());
    307 
    308   if (UsingSSL(type_) && !LoadTestRootCert())
    309       return false;
    310 
    311   started_ = true;
    312   allowed_port_.reset(new ScopedPortException(host_port_pair_.port()));
    313   return true;
    314 }
    315 
    316 void BaseTestServer::CleanUpWhenStoppingServer() {
    317   TestRootCerts* root_certs = TestRootCerts::GetInstance();
    318   root_certs->Clear();
    319 
    320   host_port_pair_.set_port(0);
    321   allowed_port_.reset();
    322   started_ = false;
    323 }
    324 
    325 // Generates a dictionary of arguments to pass to the Python test server via
    326 // the test server spawner, in the form of
    327 // { argument-name: argument-value, ... }
    328 // Returns false if an invalid configuration is specified.
    329 bool BaseTestServer::GenerateArguments(base::DictionaryValue* arguments) const {
    330   DCHECK(arguments);
    331 
    332   arguments->SetString("host", host_port_pair_.host());
    333   arguments->SetInteger("port", host_port_pair_.port());
    334   arguments->SetString("data-dir", document_root_.value());
    335 
    336   if (VLOG_IS_ON(1) || log_to_console_)
    337     arguments->Set("log-to-console", base::Value::CreateNullValue());
    338 
    339   if (UsingSSL(type_)) {
    340     // Check the certificate arguments of the HTTPS server.
    341     base::FilePath certificate_path(certificates_dir_);
    342     base::FilePath certificate_file(ssl_options_.GetCertificateFile());
    343     if (!certificate_file.value().empty()) {
    344       certificate_path = certificate_path.Append(certificate_file);
    345       if (certificate_path.IsAbsolute() &&
    346           !base::PathExists(certificate_path)) {
    347         LOG(ERROR) << "Certificate path " << certificate_path.value()
    348                    << " doesn't exist. Can't launch https server.";
    349         return false;
    350       }
    351       arguments->SetString("cert-and-key-file", certificate_path.value());
    352     }
    353 
    354     // Check the client certificate related arguments.
    355     if (ssl_options_.request_client_certificate)
    356       arguments->Set("ssl-client-auth", base::Value::CreateNullValue());
    357     scoped_ptr<base::ListValue> ssl_client_certs(new base::ListValue());
    358 
    359     std::vector<base::FilePath>::const_iterator it;
    360     for (it = ssl_options_.client_authorities.begin();
    361          it != ssl_options_.client_authorities.end(); ++it) {
    362       if (it->IsAbsolute() && !base::PathExists(*it)) {
    363         LOG(ERROR) << "Client authority path " << it->value()
    364                    << " doesn't exist. Can't launch https server.";
    365         return false;
    366       }
    367       ssl_client_certs->Append(new base::StringValue(it->value()));
    368     }
    369 
    370     if (ssl_client_certs->GetSize())
    371       arguments->Set("ssl-client-ca", ssl_client_certs.release());
    372   }
    373 
    374   if (type_ == TYPE_HTTPS) {
    375     arguments->Set("https", base::Value::CreateNullValue());
    376 
    377     std::string ocsp_arg = ssl_options_.GetOCSPArgument();
    378     if (!ocsp_arg.empty())
    379       arguments->SetString("ocsp", ocsp_arg);
    380 
    381     if (ssl_options_.cert_serial != 0) {
    382       arguments->Set("cert-serial",
    383                      base::Value::CreateIntegerValue(ssl_options_.cert_serial));
    384     }
    385 
    386     // Check bulk cipher argument.
    387     scoped_ptr<base::ListValue> bulk_cipher_values(new base::ListValue());
    388     GetCiphersList(ssl_options_.bulk_ciphers, bulk_cipher_values.get());
    389     if (bulk_cipher_values->GetSize())
    390       arguments->Set("ssl-bulk-cipher", bulk_cipher_values.release());
    391     if (ssl_options_.record_resume)
    392       arguments->Set("https-record-resume", base::Value::CreateNullValue());
    393     if (ssl_options_.tls_intolerant != SSLOptions::TLS_INTOLERANT_NONE) {
    394       arguments->Set("tls-intolerant",
    395                      new base::FundamentalValue(ssl_options_.tls_intolerant));
    396     }
    397   }
    398 
    399   return GenerateAdditionalArguments(arguments);
    400 }
    401 
    402 bool BaseTestServer::GenerateAdditionalArguments(
    403     base::DictionaryValue* arguments) const {
    404   return true;
    405 }
    406 
    407 }  // namespace net
    408