base_test_server.cc revision a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7
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 base::Base64Encode(old_text, &base64_old); 230 base::Base64Encode(new_text, &base64_new); 231 if (first_query_parameter) { 232 new_file_path += "?"; 233 first_query_parameter = false; 234 } else { 235 new_file_path += "&"; 236 } 237 new_file_path += "replace_text="; 238 new_file_path += base64_old; 239 new_file_path += ":"; 240 new_file_path += base64_new; 241 } 242 243 *replacement_path = new_file_path; 244 return true; 245} 246 247void BaseTestServer::Init(const std::string& host) { 248 host_port_pair_ = HostPortPair(host, 0); 249 250 // TODO(battre) Remove this after figuring out why the TestServer is flaky. 251 // http://crbug.com/96594 252 log_to_console_ = true; 253} 254 255void BaseTestServer::SetResourcePath(const base::FilePath& document_root, 256 const base::FilePath& certificates_dir) { 257 // This method shouldn't get called twice. 258 DCHECK(certificates_dir_.empty()); 259 document_root_ = document_root; 260 certificates_dir_ = certificates_dir; 261 DCHECK(!certificates_dir_.empty()); 262} 263 264bool BaseTestServer::ParseServerData(const std::string& server_data) { 265 VLOG(1) << "Server data: " << server_data; 266 base::JSONReader json_reader; 267 scoped_ptr<base::Value> value(json_reader.ReadToValue(server_data)); 268 if (!value.get() || !value->IsType(base::Value::TYPE_DICTIONARY)) { 269 LOG(ERROR) << "Could not parse server data: " 270 << json_reader.GetErrorMessage(); 271 return false; 272 } 273 274 server_data_.reset(static_cast<base::DictionaryValue*>(value.release())); 275 int port = 0; 276 if (!server_data_->GetInteger("port", &port)) { 277 LOG(ERROR) << "Could not find port value"; 278 return false; 279 } 280 if ((port <= 0) || (port > kuint16max)) { 281 LOG(ERROR) << "Invalid port value: " << port; 282 return false; 283 } 284 host_port_pair_.set_port(port); 285 286 return true; 287} 288 289bool BaseTestServer::LoadTestRootCert() const { 290 TestRootCerts* root_certs = TestRootCerts::GetInstance(); 291 if (!root_certs) 292 return false; 293 294 // Should always use absolute path to load the root certificate. 295 base::FilePath root_certificate_path = certificates_dir_; 296 if (!certificates_dir_.IsAbsolute()) { 297 base::FilePath src_dir; 298 if (!PathService::Get(base::DIR_SOURCE_ROOT, &src_dir)) 299 return false; 300 root_certificate_path = src_dir.Append(certificates_dir_); 301 } 302 303 return root_certs->AddFromFile( 304 root_certificate_path.AppendASCII("root_ca_cert.pem")); 305} 306 307bool BaseTestServer::SetupWhenServerStarted() { 308 DCHECK(host_port_pair_.port()); 309 310 if (UsingSSL(type_) && !LoadTestRootCert()) 311 return false; 312 313 started_ = true; 314 allowed_port_.reset(new ScopedPortException(host_port_pair_.port())); 315 return true; 316} 317 318void BaseTestServer::CleanUpWhenStoppingServer() { 319 TestRootCerts* root_certs = TestRootCerts::GetInstance(); 320 root_certs->Clear(); 321 322 host_port_pair_.set_port(0); 323 allowed_port_.reset(); 324 started_ = false; 325} 326 327// Generates a dictionary of arguments to pass to the Python test server via 328// the test server spawner, in the form of 329// { argument-name: argument-value, ... } 330// Returns false if an invalid configuration is specified. 331bool BaseTestServer::GenerateArguments(base::DictionaryValue* arguments) const { 332 DCHECK(arguments); 333 334 arguments->SetString("host", host_port_pair_.host()); 335 arguments->SetInteger("port", host_port_pair_.port()); 336 arguments->SetString("data-dir", document_root_.value()); 337 338 if (VLOG_IS_ON(1) || log_to_console_) 339 arguments->Set("log-to-console", base::Value::CreateNullValue()); 340 341 if (UsingSSL(type_)) { 342 // Check the certificate arguments of the HTTPS server. 343 base::FilePath certificate_path(certificates_dir_); 344 base::FilePath certificate_file(ssl_options_.GetCertificateFile()); 345 if (!certificate_file.value().empty()) { 346 certificate_path = certificate_path.Append(certificate_file); 347 if (certificate_path.IsAbsolute() && 348 !base::PathExists(certificate_path)) { 349 LOG(ERROR) << "Certificate path " << certificate_path.value() 350 << " doesn't exist. Can't launch https server."; 351 return false; 352 } 353 arguments->SetString("cert-and-key-file", certificate_path.value()); 354 } 355 356 // Check the client certificate related arguments. 357 if (ssl_options_.request_client_certificate) 358 arguments->Set("ssl-client-auth", base::Value::CreateNullValue()); 359 scoped_ptr<base::ListValue> ssl_client_certs(new base::ListValue()); 360 361 std::vector<base::FilePath>::const_iterator it; 362 for (it = ssl_options_.client_authorities.begin(); 363 it != ssl_options_.client_authorities.end(); ++it) { 364 if (it->IsAbsolute() && !base::PathExists(*it)) { 365 LOG(ERROR) << "Client authority path " << it->value() 366 << " doesn't exist. Can't launch https server."; 367 return false; 368 } 369 ssl_client_certs->Append(new base::StringValue(it->value())); 370 } 371 372 if (ssl_client_certs->GetSize()) 373 arguments->Set("ssl-client-ca", ssl_client_certs.release()); 374 } 375 376 if (type_ == TYPE_HTTPS) { 377 arguments->Set("https", base::Value::CreateNullValue()); 378 379 std::string ocsp_arg = ssl_options_.GetOCSPArgument(); 380 if (!ocsp_arg.empty()) 381 arguments->SetString("ocsp", ocsp_arg); 382 383 if (ssl_options_.cert_serial != 0) { 384 arguments->Set("cert-serial", 385 base::Value::CreateIntegerValue(ssl_options_.cert_serial)); 386 } 387 388 // Check bulk cipher argument. 389 scoped_ptr<base::ListValue> bulk_cipher_values(new base::ListValue()); 390 GetCiphersList(ssl_options_.bulk_ciphers, bulk_cipher_values.get()); 391 if (bulk_cipher_values->GetSize()) 392 arguments->Set("ssl-bulk-cipher", bulk_cipher_values.release()); 393 if (ssl_options_.record_resume) 394 arguments->Set("https-record-resume", base::Value::CreateNullValue()); 395 if (ssl_options_.tls_intolerant != SSLOptions::TLS_INTOLERANT_NONE) { 396 arguments->Set("tls-intolerant", 397 new base::FundamentalValue(ssl_options_.tls_intolerant)); 398 } 399 if (!ssl_options_.signed_cert_timestamps.empty()) { 400 std::string b64_scts; 401 base::Base64Encode(ssl_options_.signed_cert_timestamps, &b64_scts); 402 arguments->SetString("signed-cert-timestamps", b64_scts); 403 } 404 } 405 406 return GenerateAdditionalArguments(arguments); 407} 408 409bool BaseTestServer::GenerateAdditionalArguments( 410 base::DictionaryValue* arguments) const { 411 return true; 412} 413 414} // namespace net 415