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