diff options
author | Zeno Albisser <zeno.albisser@digia.com> | 2013-11-21 14:09:57 +0100 |
---|---|---|
committer | Andras Becsi <andras.becsi@digia.com> | 2013-11-29 15:14:36 +0100 |
commit | eb32ba6f51d0c21d58cd7d89785285ff8fa64624 (patch) | |
tree | 2c7c940e1dbee81b89d935626110816b494aa32c /chromium/net | |
parent | 9427c1a0222ebd67efef1a2c7990a0fa5c9aac84 (diff) | |
download | qtwebengine-chromium-eb32ba6f51d0c21d58cd7d89785285ff8fa64624.tar.gz |
Update chromium to branch 1599.
Change-Id: I04e775a946a208bb4500d3b722bcb05c82b9d7cb
Reviewed-by: Andras Becsi <andras.becsi@digia.com>
Diffstat (limited to 'chromium/net')
132 files changed, 2272 insertions, 4459 deletions
diff --git a/chromium/net/OWNERS b/chromium/net/OWNERS index 87e11faef93..18f14625033 100644 --- a/chromium/net/OWNERS +++ b/chromium/net/OWNERS @@ -1,5 +1,4 @@ agl@chromium.org -akalin@chromium.org asanka@chromium.org cbentzel@chromium.org eroman@chromium.org diff --git a/chromium/net/android/java/src/org/chromium/net/AndroidKeyStore.java b/chromium/net/android/java/src/org/chromium/net/AndroidKeyStore.java index 2edaa895b7e..de5d8f2d5f0 100644 --- a/chromium/net/android/java/src/org/chromium/net/AndroidKeyStore.java +++ b/chromium/net/android/java/src/org/chromium/net/AndroidKeyStore.java @@ -112,20 +112,21 @@ public class AndroidKeyStore { * shall only be used to implement signing in the context of SSL * client certificate support. * - * The message will actually be a hash, computed and padded by OpenSSL, - * itself, depending on the type of the key. The result should match - * exactly what the vanilla implementations of the following OpenSSL - * function calls do: + * The message will actually be a hash, computed by OpenSSL itself, + * depending on the type of the key. The result should match exactly + * what the vanilla implementations of the following OpenSSL function + * calls do: * * - For a RSA private key, this should be equivalent to calling - * RSA_sign(NDI_md5_sha1,....), i.e. it must generate a raw RSA - * signature. The message must a combined, 36-byte MD5+SHA1 message - * digest padded to the length of the modulus using PKCS#1 padding. + * RSA_private_encrypt(..., RSA_PKCS1_PADDING), i.e. it must + * generate a raw RSA signature. The message must be either a + * combined, 36-byte MD5+SHA1 message digest or a DigestInfo + * value wrapping a message digest. * * - For a DSA and ECDSA private keys, this should be equivalent to * calling DSA_sign(0,...) and ECDSA_sign(0,...) respectively. The - * message must be a 20-byte SHA1 hash and the function shall - * compute a direct DSA/ECDSA signature for it. + * message must be a hash and the function shall compute a direct + * DSA/ECDSA signature for it. * * @param privateKey The PrivateKey handle. * @param message The message to sign. diff --git a/chromium/net/android/keystore_openssl.cc b/chromium/net/android/keystore_openssl.cc index cc463f49539..cd55ece3336 100644 --- a/chromium/net/android/keystore_openssl.cc +++ b/chromium/net/android/keystore_openssl.cc @@ -35,7 +35,7 @@ // // Generally speaking, OpenSSL provides many different ways to sign // digests. This code doesn't support all these cases, only the ones that -// are required to sign the MAC during the OpenSSL handshake for TLS < 1.2. +// are required to sign the MAC during the OpenSSL handshake for TLS. // // The OpenSSL EVP_PKEY type is a generic wrapper around key pairs. // Internally, it can hold a pointer to a RSA, DSA or ECDSA structure, @@ -54,8 +54,8 @@ // are used to hold the typical modulus / exponent / parameters for the // key pair). // -// This source file thus defines a custom RSA_METHOD structure, which -// fields points to static methods used to implement the corresponding +// This source file thus defines a custom RSA_METHOD structure whose +// fields point to static methods used to implement the corresponding // RSA operation using platform Android APIs. // // However, the platform APIs require a jobject JNI reference to work. @@ -106,6 +106,7 @@ typedef crypto::ScopedOpenSSL<RSA, RSA_free> ScopedRSA; typedef crypto::ScopedOpenSSL<DSA, DSA_free> ScopedDSA; typedef crypto::ScopedOpenSSL<EC_KEY, EC_KEY_free> ScopedEC_KEY; typedef crypto::ScopedOpenSSL<EC_GROUP, EC_GROUP_free> ScopedEC_GROUP; +typedef crypto::ScopedOpenSSL<X509_SIG, X509_SIG_free> ScopedX509_SIG; // Custom RSA_METHOD that uses the platform APIs. // Note that for now, only signing through RSA_sign() is really supported. @@ -172,28 +173,79 @@ int RsaMethodFinish(RSA* rsa) { return 0; } +// Although these parameters are, per OpenSSL, named |message| and +// |message_len|, RsaMethodSign is actually passed a message digest, +// not the original message. int RsaMethodSign(int type, const unsigned char* message, unsigned int message_len, unsigned char* signature, unsigned int* signature_len, const RSA* rsa) { - // This is only used for client certificate support, which - // will always pass the NID_md5_sha1 |type| value. - DCHECK_EQ(NID_md5_sha1, type); - if (type != NID_md5_sha1) { - RSAerr(RSA_F_RSA_SIGN, RSA_R_UNKNOWN_ALGORITHM_TYPE); - return 0; - } // Retrieve private key JNI reference. jobject private_key = reinterpret_cast<jobject>(RSA_get_app_data(rsa)); if (!private_key) { LOG(WARNING) << "Null JNI reference passed to RsaMethodSign!"; return 0; } - // Sign message with it through JNI. - base::StringPiece message_piece(reinterpret_cast<const char*>(message), - static_cast<size_t>(message_len)); + + // See RSA_sign in third_party/openssl/openssl/crypto/rsa/rsa_sign.c. + base::StringPiece message_piece; + std::vector<uint8> buffer; // To store |message| wrapped in a DigestInfo. + if (type == NID_md5_sha1) { + // For TLS < 1.2, sign just |message|. + message_piece.set(message, static_cast<size_t>(message_len)); + } else { + // For TLS 1.2, wrap |message| in a PKCS #1 DigestInfo before signing. + ScopedX509_SIG sig(X509_SIG_new()); + if (!sig.get()) + return 0; + if (X509_ALGOR_set0(sig.get()->algor, + OBJ_nid2obj(type), V_ASN1_NULL, 0) != 1) { + return 0; + } + if (sig.get()->algor->algorithm == NULL) { + RSAerr(RSA_F_RSA_SIGN, RSA_R_UNKNOWN_ALGORITHM_TYPE); + return 0; + } + if (sig.get()->algor->algorithm->length == 0) { + RSAerr(RSA_F_RSA_SIGN, + RSA_R_THE_ASN1_OBJECT_IDENTIFIER_IS_NOT_KNOWN_FOR_THIS_MD); + return 0; + } + if (ASN1_OCTET_STRING_set(sig.get()->digest, message, message_len) != 1) + return 0; + + int len = i2d_X509_SIG(sig.get(), NULL); + if (len < 0) { + LOG(WARNING) << "Couldn't encode X509_SIG structure"; + return 0; + } + buffer.resize(len); + // OpenSSL takes a pointer to a pointer so it can kindly increment + // it for you. + unsigned char* p = &buffer[0]; + len = i2d_X509_SIG(sig.get(), &p); + if (len < 0) { + LOG(WARNING) << "Couldn't encode X509_SIG structure"; + return 0; + } + + message_piece.set(&buffer[0], static_cast<size_t>(len)); + } + + // Sanity-check the size. + // + // TODO(davidben): Do we need to do this? OpenSSL does, but + // RawSignDigestWithPrivateKey does error on sufficiently large + // input. However, it doesn't take the padding into account. + size_t expected_size = static_cast<size_t>(RSA_size(rsa)); + if (message_piece.size() > expected_size - RSA_PKCS1_PADDING_SIZE) { + RSAerr(RSA_F_RSA_SIGN, RSA_R_DIGEST_TOO_BIG_FOR_RSA_KEY); + return 0; + } + + // Sign |message_piece| with the private key through JNI. std::vector<uint8> result; if (!RawSignDigestWithPrivateKey( @@ -202,7 +254,6 @@ int RsaMethodSign(int type, return 0; } - size_t expected_size = static_cast<size_t>(RSA_size(rsa)); if (result.size() > expected_size) { LOG(ERROR) << "RSA Signature size mismatch, actual: " << result.size() << ", expected <= " << expected_size; diff --git a/chromium/net/base/mime_util.cc b/chromium/net/base/mime_util.cc index da3a4c9aee8..3a0310c53f3 100644 --- a/chromium/net/base/mime_util.cc +++ b/chromium/net/base/mime_util.cc @@ -304,10 +304,11 @@ static const char* const proprietary_media_types[] = { static const char* const common_media_codecs[] = { #if !defined(OS_ANDROID) // Android doesn't support Ogg Theora. "theora", + "vp9", // TODO(tomfinegan): Move vp9 back down with vp8 once VP9 is supported + // on Android. https://crbug.com/285016 #endif "vorbis", "vp8", - "vp9", "1" // WAVE_FORMAT_PCM. }; @@ -413,7 +414,13 @@ struct MediaFormatStrict { }; static const MediaFormatStrict format_codec_mappings[] = { + // TODO(tomfinegan): Remove this if/else when VP9 is supported on Android. + // https://crbug.com/285016 +#if !defined(OS_ANDROID) { "video/webm", "vorbis,vp8,vp8.0,vp9,vp9.0" }, +#else + { "video/webm", "vorbis,vp8,vp8.0" }, +#endif { "audio/webm", "vorbis" }, { "audio/wav", "1" } }; diff --git a/chromium/net/base/net_log_event_type_list.h b/chromium/net/base/net_log_event_type_list.h index b1f0afe096d..01d9bf1e66d 100644 --- a/chromium/net/base/net_log_event_type_list.h +++ b/chromium/net/base/net_log_event_type_list.h @@ -1296,15 +1296,6 @@ EVENT_TYPE(QUIC_SESSION_PACKET_RECEIVED) // as a base-10 string.>, // "size": <The size of the packet in bytes> // } -EVENT_TYPE(QUIC_SESSION_PACKET_RETRANSMITTED) - -// Session retransmitted a QUIC packet. -// { -// "old_packet_sequence_number": <The old packet's full 64-bit sequence -// number, as a base-10 string.>, -// "new_packet_sequence_number": <The new packet's full 64-bit sequence -// number, as a base-10 string.>, -// } EVENT_TYPE(QUIC_SESSION_PACKET_SENT) // Session received a QUIC packet header for a valid packet. @@ -1444,49 +1435,6 @@ EVENT_TYPE(QUIC_SESSION_CONNECTION_CLOSE_FRAME_RECEIVED) // } EVENT_TYPE(QUIC_SESSION_CONNECTION_CLOSE_FRAME_SENT) -// Session received a public reset packet. -// { -// } -EVENT_TYPE(QUIC_SESSION_PUBLIC_RESET_PACKET_RECEIVED) - -// Session received a version negotiation packet. -// { -// "versions": <List of QUIC versions supported by the server>, -// } -EVENT_TYPE(QUIC_SESSION_VERSION_NEGOTIATION_PACKET_RECEIVED) - -// Session revived a QUIC packet packet via FEC. -// { -// "guid": <The 64-bit GUID for this connection, as a base-10 string>, -// "public_flags": <The public flags set for this packet>, -// "packet_sequence_number": <The packet's full 64-bit sequence number, -// as a base-10 string.>, -// "private_flags": <The private flags set for this packet>, -// "fec_group": <The FEC group of this packet>, -// } -EVENT_TYPE(QUIC_SESSION_PACKET_HEADER_REVIVED) - -// Session received a crypto handshake message. -// { -// "quic_crypto_handshake_message": <The human readable dump of the message -// contents> -// } -EVENT_TYPE(QUIC_SESSION_CRYPTO_HANDSHAKE_MESSAGE_RECEIVED) - -// Session sent a crypto handshake message. -// { -// "quic_crypto_handshake_message": <The human readable dump of the message -// contents> -// } -EVENT_TYPE(QUIC_SESSION_CRYPTO_HANDSHAKE_MESSAGE_SENT) - -// Session was closed, either remotely or by the peer. -// { -// "quic_error": <QuicErrorCode which caused the connection to be closed>, -// "from_peer": <True if the peer closed the connection> -// } -EVENT_TYPE(QUIC_SESSION_CLOSED) - // ------------------------------------------------------------------------ // QuicHttpStream // ------------------------------------------------------------------------ diff --git a/chromium/net/cert/x509_cert_types.h b/chromium/net/cert/x509_cert_types.h index f74c82eab7b..b6adb518aa9 100644 --- a/chromium/net/cert/x509_cert_types.h +++ b/chromium/net/cert/x509_cert_types.h @@ -42,7 +42,7 @@ struct NET_EXPORT CertPrincipal { bool ParseDistinguishedName(const void* ber_name_data, size_t length); #endif -#if defined(OS_MACOSX) && !defined(OS_IOS) +#if defined(OS_MACOSX) // Compare this CertPrincipal with |against|, returning true if they're // equal enough to be a possible match. This should NOT be used for any // security relevant decisions. @@ -136,9 +136,9 @@ enum CertDateFormat { // |format|, and writes the result into |*time|. If an invalid date is // specified, or if parsing fails, returns false, and |*time| will not be // updated. -NET_EXPORT_PRIVATE bool ParseCertificateDate(const base::StringPiece& raw_date, - CertDateFormat format, - base::Time* time); +bool ParseCertificateDate(const base::StringPiece& raw_date, + CertDateFormat format, + base::Time* time); } // namespace net #endif // NET_CERT_X509_CERT_TYPES_H_ diff --git a/chromium/net/cert/x509_cert_types_unittest.cc b/chromium/net/cert/x509_cert_types_unittest.cc index 38fd3e95266..e0bcc707dc1 100644 --- a/chromium/net/cert/x509_cert_types_unittest.cc +++ b/chromium/net/cert/x509_cert_types_unittest.cc @@ -2,19 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "net/cert/x509_cert_types.h" - #include "base/basictypes.h" -#include "base/strings/string_piece.h" -#include "base/time/time.h" +#include "net/cert/x509_cert_types.h" #include "net/test/test_certificate_data.h" #include "testing/gtest/include/gtest/gtest.h" namespace net { -namespace { - -#if defined(OS_MACOSX) && !defined(OS_IOS) +#if defined(OS_MACOSX) TEST(X509TypesTest, Matching) { CertPrincipal spamco; spamco.common_name = "SpamCo Dept. Of Certificization"; @@ -53,7 +48,6 @@ TEST(X509TypesTest, Matching) { } #endif -#if (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_WIN) TEST(X509TypesTest, ParseDNVerisign) { CertPrincipal verisign; EXPECT_TRUE(verisign.ParseDistinguishedName(VerisignDN, sizeof(VerisignDN))); @@ -141,103 +135,5 @@ TEST(X509TypesTest, ParseDNEntrust) { EXPECT_EQ("(c) 1999 Entrust.net Limited", entrust.organization_unit_names[1]); } -#endif - -const struct CertDateTestData { - CertDateFormat format; - const char* date_string; - bool is_valid; - base::Time::Exploded expected_result; -} kCertDateTimeData[] = { - { CERT_DATE_FORMAT_UTC_TIME, - "120101000000Z", - true, - { 2012, 1, 0, 1, 0, 0, 0 } }, - { CERT_DATE_FORMAT_GENERALIZED_TIME, - "20120101000000Z", - true, - { 2012, 1, 0, 1, 0, 0, 0 } }, - { CERT_DATE_FORMAT_UTC_TIME, - "490101000000Z", - true, - { 2049, 1, 0, 1, 0, 0, 0 } }, - { CERT_DATE_FORMAT_UTC_TIME, - "500101000000Z", - true, - { 1950, 1, 0, 1, 0, 0, 0 } }, - { CERT_DATE_FORMAT_GENERALIZED_TIME, - "19500101000000Z", - true, - { 1950, 1, 0, 1, 0, 0, 0 } }, - { CERT_DATE_FORMAT_UTC_TIME, - "AB0101000000Z", - false, - { 0 } }, - { CERT_DATE_FORMAT_GENERALIZED_TIME, - "19AB0101000000Z", - false, - { 0 } }, - { CERT_DATE_FORMAT_UTC_TIME, - "", - false, - { 0 } }, - { CERT_DATE_FORMAT_UTC_TIME, - "A", - false, - { 0 } }, - { CERT_DATE_FORMAT_GENERALIZED_TIME, - "20121301000000Z", - false, - { 0 } }, - { CERT_DATE_FORMAT_GENERALIZED_TIME, - "20120101123000Z", - true, - { 2012, 1, 0, 1, 12, 30, 0 } }, -}; - -// GTest pretty printer. -void PrintTo(const CertDateTestData& data, std::ostream* os) { - *os << " format: " << data.format - << "; date string: " << base::StringPiece(data.date_string) - << "; valid: " << data.is_valid - << "; expected date: " - << (data.is_valid ? - base::Time::FromUTCExploded(data.expected_result) - .ToInternalValue() : - 0U); -} - -class X509CertTypesDateTest : public testing::TestWithParam<CertDateTestData> { - public: - virtual ~X509CertTypesDateTest() {} - virtual void SetUp() { - test_data_ = GetParam(); - } - - protected: - CertDateTestData test_data_; -}; - -TEST_P(X509CertTypesDateTest, Parse) { - base::Time parsed_date; - bool parsed = ParseCertificateDate( - test_data_.date_string, test_data_.format, &parsed_date); - EXPECT_EQ(test_data_.is_valid, parsed); - if (!test_data_.is_valid) - return; - // Convert the expected value to a base::Time(). This ensures that systems - // systems that only support 32-bit times will pass the tests, by ensuring at - // least that the times have the same truncating behaviour. - // Note: Compared as internal values so that mismatches can be cleanly - // printed by GTest (eg: without PrintTo overrides). - EXPECT_EQ(base::Time::FromUTCExploded(test_data_.expected_result) - .ToInternalValue(), - parsed_date.ToInternalValue()); -} -INSTANTIATE_TEST_CASE_P(, - X509CertTypesDateTest, - testing::ValuesIn(kCertDateTimeData)); - -} // namespace } // namespace net diff --git a/chromium/net/disk_cache/backend_unittest.cc b/chromium/net/disk_cache/backend_unittest.cc index 7eeeee1fd83..bc48a2eb203 100644 --- a/chromium/net/disk_cache/backend_unittest.cc +++ b/chromium/net/disk_cache/backend_unittest.cc @@ -313,7 +313,7 @@ TEST_F(DiskCacheBackendTest, CreateBackend_MissingFile) { scoped_ptr<disk_cache::BackendImpl> cache(new disk_cache::BackendImpl( cache_path_, cache_thread.message_loop_proxy().get(), NULL)); int rv = cache->Init(cb.callback()); - EXPECT_EQ(net::ERR_FAILED, cb.GetResult(rv)); + ASSERT_EQ(net::ERR_FAILED, cb.GetResult(rv)); base::ThreadRestrictions::SetIOAllowed(prev); cache.reset(); diff --git a/chromium/net/disk_cache/entry_unittest.cc b/chromium/net/disk_cache/entry_unittest.cc index 7addc85e5a0..857e07f1b7b 100644 --- a/chromium/net/disk_cache/entry_unittest.cc +++ b/chromium/net/disk_cache/entry_unittest.cc @@ -392,6 +392,7 @@ void DiskCacheEntryTest::ExternalSyncIOBackground(disk_cache::Entry* entry) { EXPECT_EQ( 25000, entry->ReadData(1, 0, buffer2.get(), kSize2, net::CompletionCallback())); + EXPECT_EQ(0, memcmp(buffer2->data(), buffer2->data(), 10000)); EXPECT_EQ(5000, entry->ReadData( 1, 30000, buffer2.get(), kSize2, net::CompletionCallback())); diff --git a/chromium/net/disk_cache/simple/simple_entry_impl.cc b/chromium/net/disk_cache/simple/simple_entry_impl.cc index 3c3ec7daff6..cbee6048371 100644 --- a/chromium/net/disk_cache/simple/simple_entry_impl.cc +++ b/chromium/net/disk_cache/simple/simple_entry_impl.cc @@ -496,7 +496,7 @@ int SimpleEntryImpl::ReadyForSparseIO(const CompletionCallback& callback) { DCHECK(io_thread_checker_.CalledOnValidThread()); // TODO(gavinp): Determine if the simple backend should support sparse data. NOTIMPLEMENTED(); - return net::ERR_FAILED; + return net::ERR_NOT_IMPLEMENTED; } SimpleEntryImpl::~SimpleEntryImpl() { diff --git a/chromium/net/disk_cache/simple/simple_index_file.cc b/chromium/net/disk_cache/simple/simple_index_file.cc index 7bcea7cdfa8..0136be1c5a0 100644 --- a/chromium/net/disk_cache/simple/simple_index_file.cc +++ b/chromium/net/disk_cache/simple/simple_index_file.cc @@ -7,7 +7,6 @@ #include <vector> #include "base/file_util.h" -#include "base/files/file_enumerator.h" #include "base/files/memory_mapped_file.h" #include "base/hash.h" #include "base/logging.h" @@ -22,11 +21,17 @@ #include "net/disk_cache/simple/simple_util.h" #include "third_party/zlib/zlib.h" - +namespace disk_cache { namespace { +const int kEntryFilesHashLength = 16; +const int kEntryFilesSuffixLength = 2; + const uint64 kMaxEntiresInIndex = 100000000; +const char kIndexFileName[] = "the-real-index"; +const char kTempIndexFileName[] = "temp-index"; + uint32 CalculatePickleCRC(const Pickle& pickle) { return crc32(crc32(0, Z_NULL, 0), reinterpret_cast<const Bytef*>(pickle.payload()), @@ -67,9 +72,54 @@ void WriteToDiskInternal(const base::FilePath& index_filename, } } -} // namespace +// Called for each cache directory traversal iteration. +void ProcessEntryFile(SimpleIndex::EntrySet* entries, + const base::FilePath& file_path) { + static const size_t kEntryFilesLength = + kEntryFilesHashLength + kEntryFilesSuffixLength; + // Converting to std::string is OK since we never use UTF8 wide chars in our + // file names. + const base::FilePath::StringType base_name = file_path.BaseName().value(); + const std::string file_name(base_name.begin(), base_name.end()); + if (file_name.size() != kEntryFilesLength) + return; + const base::StringPiece hash_string( + file_name.begin(), file_name.begin() + kEntryFilesHashLength); + uint64 hash_key = 0; + if (!simple_util::GetEntryHashKeyFromHexString(hash_string, &hash_key)) { + LOG(WARNING) << "Invalid entry hash key filename while restoring index from" + << " disk: " << file_name; + return; + } -namespace disk_cache { + base::PlatformFileInfo file_info; + if (!file_util::GetFileInfo(file_path, &file_info)) { + LOG(ERROR) << "Could not get file info for " << file_path.value(); + return; + } + base::Time last_used_time; +#if defined(OS_POSIX) + // For POSIX systems, a last access time is available. However, it's not + // guaranteed to be more accurate than mtime. It is no worse though. + last_used_time = file_info.last_accessed; +#endif + if (last_used_time.is_null()) + last_used_time = file_info.last_modified; + + int64 file_size = file_info.size; + SimpleIndex::EntrySet::iterator it = entries->find(hash_key); + if (it == entries->end()) { + SimpleIndex::InsertInEntrySet( + hash_key, + EntryMetadata(last_used_time, file_size), + entries); + } else { + // Summing up the total size of the entry through all the *_[0-2] files + it->second.SetEntrySize(it->second.GetEntrySize() + file_size); + } +} + +} // namespace SimpleIndexLoadResult::SimpleIndexLoadResult() : did_load(false), flush_required(false) { @@ -84,11 +134,6 @@ void SimpleIndexLoadResult::Reset() { entries.clear(); } -// static -const char SimpleIndexFile::kIndexFileName[] = "the-real-index"; -// static -const char SimpleIndexFile::kTempIndexFileName[] = "temp-index"; - SimpleIndexFile::IndexMetadata::IndexMetadata() : magic_number_(kSimpleIndexMagicNumber), version_(kSimpleVersion), @@ -350,7 +395,6 @@ void SimpleIndexFile::SyncRestoreFromDisk( const base::FilePath& index_file_path, SimpleIndexLoadResult* out_result) { LOG(INFO) << "Simple Cache Index is being restored from disk."; - base::DeleteFile(index_file_path, /* recursive = */ false); out_result->Reset(); SimpleIndex::EntrySet* entries = &out_result->entries; @@ -359,53 +403,13 @@ void SimpleIndexFile::SyncRestoreFromDisk( COMPILE_ASSERT(kSimpleEntryFileCount == 3, file_pattern_must_match_file_count); - const int kFileSuffixLength = sizeof("_0") - 1; - const base::FilePath::StringType file_pattern = FILE_PATH_LITERAL("*_[0-2]"); - base::FileEnumerator enumerator(cache_directory, - false /* recursive */, - base::FileEnumerator::FILES, - file_pattern); - for (base::FilePath file_path = enumerator.Next(); !file_path.empty(); - file_path = enumerator.Next()) { - const base::FilePath::StringType base_name = file_path.BaseName().value(); - // Converting to std::string is OK since we never use UTF8 wide chars in our - // file names. - const std::string hash_key_string(base_name.begin(), - base_name.end() - kFileSuffixLength); - uint64 hash_key = 0; - if (!simple_util::GetEntryHashKeyFromHexString( - hash_key_string, &hash_key)) { - LOG(WARNING) << "Invalid Entry Hash Key filename while restoring " - << "Simple Index from disk: " << base_name; - // TODO(felipeg): Should we delete the invalid file here ? - continue; - } - - base::FileEnumerator::FileInfo info = enumerator.GetInfo(); - base::Time last_used_time; -#if defined(OS_POSIX) - // For POSIX systems, a last access time is available. However, it's not - // guaranteed to be more accurate than mtime. It is no worse though. - last_used_time = base::Time::FromTimeT(info.stat().st_atime); -#endif - if (last_used_time.is_null()) - last_used_time = info.GetLastModifiedTime(); - - int64 file_size = info.GetSize(); - SimpleIndex::EntrySet::iterator it = entries->find(hash_key); - if (it == entries->end()) { - SimpleIndex::InsertInEntrySet( - hash_key, - EntryMetadata(last_used_time, file_size), - entries); - } else { - // Summing up the total size of the entry through all the *_[0-2] files - it->second.SetEntrySize(it->second.GetEntrySize() + file_size); - } + const bool did_succeed = TraverseCacheDirectory( + cache_directory, base::Bind(&ProcessEntryFile, entries)); + if (!did_succeed) { + LOG(ERROR) << "Could not reconstruct index from disk"; + return; } - out_result->did_load = true; - // When we restore from disk we write the merged index file to disk right // away, this might save us from having to restore again next time. out_result->flush_required = true; diff --git a/chromium/net/disk_cache/simple/simple_index_file.h b/chromium/net/disk_cache/simple/simple_index_file.h index b536df9a1e7..e5fc85d69a2 100644 --- a/chromium/net/disk_cache/simple/simple_index_file.h +++ b/chromium/net/disk_cache/simple/simple_index_file.h @@ -97,6 +97,9 @@ class NET_EXPORT_PRIVATE SimpleIndexFile { private: friend class WrappedSimpleIndexFile; + // Used for cache directory traversal. + typedef base::Callback<void (const base::FilePath&)> EntryFileCallback; + // When loading the entries from disk, add this many extra hash buckets to // prevent reallocation on the IO thread when merging in new live entries. static const int kExtraSizeForMerge = 512; @@ -123,6 +126,15 @@ class NET_EXPORT_PRIVATE SimpleIndexFile { static void Deserialize(const char* data, int data_len, SimpleIndexLoadResult* out_result); + // Implemented either in simple_index_file_posix.cc or + // simple_index_file_win.cc. base::FileEnumerator turned out to be very + // expensive in terms of memory usage therefore it's used only on non-POSIX + // environments for convenience (for now). Returns whether the traversal + // succeeded. + static bool TraverseCacheDirectory( + const base::FilePath& cache_path, + const EntryFileCallback& entry_file_callback); + // Scan the index directory for entries, returning an EntrySet of all entries // found. static void SyncRestoreFromDisk(const base::FilePath& cache_directory, @@ -144,9 +156,6 @@ class NET_EXPORT_PRIVATE SimpleIndexFile { const base::FilePath index_file_; const base::FilePath temp_index_file_; - static const char kIndexFileName[]; - static const char kTempIndexFileName[]; - DISALLOW_COPY_AND_ASSIGN(SimpleIndexFile); }; diff --git a/chromium/net/disk_cache/simple/simple_index_file_posix.cc b/chromium/net/disk_cache/simple/simple_index_file_posix.cc new file mode 100644 index 00000000000..586699d2a8e --- /dev/null +++ b/chromium/net/disk_cache/simple/simple_index_file_posix.cc @@ -0,0 +1,52 @@ +// Copyright (c) 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/disk_cache/simple/simple_index_file.h" + +#include <dirent.h> +#include <sys/stat.h> +#include <sys/types.h> +#include <unistd.h> + +#include <string> + +#include "base/logging.h" +#include "base/memory/scoped_ptr.h" + +namespace disk_cache { +namespace { + +struct DirCloser { + void operator()(DIR* dir) { closedir(dir); } +}; + +typedef scoped_ptr<DIR, DirCloser> ScopedDir; + +} // namespace + +// static +bool SimpleIndexFile::TraverseCacheDirectory( + const base::FilePath& cache_path, + const EntryFileCallback& entry_file_callback) { + const ScopedDir dir(opendir(cache_path.value().c_str())); + if (!dir) { + PLOG(ERROR) << "opendir " << cache_path.value(); + return false; + } + dirent entry, *result; + while (readdir_r(dir.get(), &entry, &result) == 0) { + if (!result) + return true; // The traversal completed successfully. + const std::string file_name(result->d_name); + if (file_name == "." || file_name == "..") + continue; + const base::FilePath file_path = cache_path.Append( + base::FilePath(file_name)); + entry_file_callback.Run(file_path); + } + PLOG(ERROR) << "readdir_r " << cache_path.value(); + return false; +} + +} // namespace disk_cache diff --git a/chromium/net/disk_cache/simple/simple_index_file_win.cc b/chromium/net/disk_cache/simple/simple_index_file_win.cc new file mode 100644 index 00000000000..051d12deaf7 --- /dev/null +++ b/chromium/net/disk_cache/simple/simple_index_file_win.cc @@ -0,0 +1,33 @@ +// Copyright (c) 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/disk_cache/simple/simple_index_file.h" + +#include <string> + +#include "base/files/file_enumerator.h" +#include "base/files/file_path.h" + +namespace disk_cache { + +// static +bool SimpleIndexFile::TraverseCacheDirectory( + const base::FilePath& cache_path, + const EntryFileCallback& entry_file_callback) { + const base::FilePath current_directory(FILE_PATH_LITERAL(".")); + const base::FilePath parent_directory(FILE_PATH_LITERAL("..")); + const base::FilePath::StringType file_pattern = FILE_PATH_LITERAL("*"); + base::FileEnumerator enumerator( + cache_path, false /* recursive */, base::FileEnumerator::FILES, + file_pattern); + for (base::FilePath file_path = enumerator.Next(); !file_path.empty(); + file_path = enumerator.Next()) { + if (file_path == current_directory || file_path == parent_directory) + continue; + entry_file_callback.Run(file_path); + } + return true; +} + +} // namespace disk_cache diff --git a/chromium/net/disk_cache/simple/simple_util.cc b/chromium/net/disk_cache/simple/simple_util.cc index 72a4612271f..e9ec067635a 100644 --- a/chromium/net/disk_cache/simple/simple_util.cc +++ b/chromium/net/disk_cache/simple/simple_util.cc @@ -40,7 +40,7 @@ std::string GetEntryHashKeyAsHexString(const std::string& key) { return hash_key_str; } -bool GetEntryHashKeyFromHexString(const std::string& hash_key, +bool GetEntryHashKeyFromHexString(const base::StringPiece& hash_key, uint64* hash_key_out) { if (hash_key.size() != kEntryHashKeyAsHexStringSize) { return false; diff --git a/chromium/net/disk_cache/simple/simple_util.h b/chromium/net/disk_cache/simple/simple_util.h index 2e92b4a049d..3bb80b95402 100644 --- a/chromium/net/disk_cache/simple/simple_util.h +++ b/chromium/net/disk_cache/simple/simple_util.h @@ -8,6 +8,7 @@ #include <string> #include "base/basictypes.h" +#include "base/strings/string_piece.h" #include "net/base/net_export.h" namespace base { @@ -33,7 +34,7 @@ NET_EXPORT_PRIVATE uint64 GetEntryHashKey(const std::string& key); // Parses the |hash_key| string into a uint64 buffer. // |hash_key| string must be of the form: FFFFFFFFFFFFFFFF . NET_EXPORT_PRIVATE bool GetEntryHashKeyFromHexString( - const std::string& hash_key, + const base::StringPiece& hash_key, uint64* hash_key_out); // Given a |key| for a (potential) entry in the simple backend and the |index| diff --git a/chromium/net/dns/address_sorter_posix_unittest.cc b/chromium/net/dns/address_sorter_posix_unittest.cc index c4517379957..96cbfc6fcb0 100644 --- a/chromium/net/dns/address_sorter_posix_unittest.cc +++ b/chromium/net/dns/address_sorter_posix_unittest.cc @@ -10,8 +10,6 @@ #include "net/base/net_util.h" #include "net/base/test_completion_callback.h" #include "net/socket/client_socket_factory.h" -#include "net/socket/ssl_client_socket.h" -#include "net/socket/stream_socket.h" #include "net/udp/datagram_client_socket.h" #include "testing/gtest/include/gtest/gtest.h" @@ -92,27 +90,27 @@ class TestSocketFactory : public ClientSocketFactory { TestSocketFactory() {} virtual ~TestSocketFactory() {} - virtual scoped_ptr<DatagramClientSocket> CreateDatagramClientSocket( + virtual DatagramClientSocket* CreateDatagramClientSocket( DatagramSocket::BindType, const RandIntCallback&, NetLog*, const NetLog::Source&) OVERRIDE { - return scoped_ptr<DatagramClientSocket>(new TestUDPClientSocket(&mapping_)); + return new TestUDPClientSocket(&mapping_); } - virtual scoped_ptr<StreamSocket> CreateTransportClientSocket( + virtual StreamSocket* CreateTransportClientSocket( const AddressList&, NetLog*, const NetLog::Source&) OVERRIDE { NOTIMPLEMENTED(); - return scoped_ptr<StreamSocket>(); + return NULL; } - virtual scoped_ptr<SSLClientSocket> CreateSSLClientSocket( - scoped_ptr<ClientSocketHandle>, + virtual SSLClientSocket* CreateSSLClientSocket( + ClientSocketHandle*, const HostPortPair&, const SSLConfig&, const SSLClientSocketContext&) OVERRIDE { NOTIMPLEMENTED(); - return scoped_ptr<SSLClientSocket>(); + return NULL; } virtual void ClearSSLSessionCache() OVERRIDE { NOTIMPLEMENTED(); diff --git a/chromium/net/dns/dns_session_unittest.cc b/chromium/net/dns/dns_session_unittest.cc index ed726f23234..46627069f66 100644 --- a/chromium/net/dns/dns_session_unittest.cc +++ b/chromium/net/dns/dns_session_unittest.cc @@ -14,8 +14,6 @@ #include "net/dns/dns_protocol.h" #include "net/dns/dns_socket_pool.h" #include "net/socket/socket_test_util.h" -#include "net/socket/ssl_client_socket.h" -#include "net/socket/stream_socket.h" #include "testing/gtest/include/gtest/gtest.h" namespace net { @@ -26,26 +24,26 @@ class TestClientSocketFactory : public ClientSocketFactory { public: virtual ~TestClientSocketFactory(); - virtual scoped_ptr<DatagramClientSocket> CreateDatagramClientSocket( + virtual DatagramClientSocket* CreateDatagramClientSocket( DatagramSocket::BindType bind_type, const RandIntCallback& rand_int_cb, net::NetLog* net_log, const net::NetLog::Source& source) OVERRIDE; - virtual scoped_ptr<StreamSocket> CreateTransportClientSocket( + virtual StreamSocket* CreateTransportClientSocket( const AddressList& addresses, NetLog*, const NetLog::Source&) OVERRIDE { NOTIMPLEMENTED(); - return scoped_ptr<StreamSocket>(); + return NULL; } - virtual scoped_ptr<SSLClientSocket> CreateSSLClientSocket( - scoped_ptr<ClientSocketHandle> transport_socket, + virtual SSLClientSocket* CreateSSLClientSocket( + ClientSocketHandle* transport_socket, const HostPortPair& host_and_port, const SSLConfig& ssl_config, const SSLClientSocketContext& context) OVERRIDE { NOTIMPLEMENTED(); - return scoped_ptr<SSLClientSocket>(); + return NULL; } virtual void ClearSSLSessionCache() OVERRIDE { @@ -181,8 +179,7 @@ bool DnsSessionTest::ExpectEvent(const PoolEvent& expected) { return true; } -scoped_ptr<DatagramClientSocket> -TestClientSocketFactory::CreateDatagramClientSocket( +DatagramClientSocket* TestClientSocketFactory::CreateDatagramClientSocket( DatagramSocket::BindType bind_type, const RandIntCallback& rand_int_cb, net::NetLog* net_log, @@ -191,10 +188,9 @@ TestClientSocketFactory::CreateDatagramClientSocket( // simplest SocketDataProvider with no data supplied. SocketDataProvider* data_provider = new StaticSocketDataProvider(); data_providers_.push_back(data_provider); - scoped_ptr<MockUDPClientSocket> socket( - new MockUDPClientSocket(data_provider, net_log)); - data_provider->set_socket(socket.get()); - return socket.PassAs<DatagramClientSocket>(); + MockUDPClientSocket* socket = new MockUDPClientSocket(data_provider, net_log); + data_provider->set_socket(socket); + return socket; } TestClientSocketFactory::~TestClientSocketFactory() { diff --git a/chromium/net/dns/dns_socket_pool.cc b/chromium/net/dns/dns_socket_pool.cc index 7a7ecd6ee8f..64570fca8fc 100644 --- a/chromium/net/dns/dns_socket_pool.cc +++ b/chromium/net/dns/dns_socket_pool.cc @@ -76,8 +76,8 @@ scoped_ptr<DatagramClientSocket> DnsSocketPool::CreateConnectedSocket( scoped_ptr<DatagramClientSocket> socket; NetLog::Source no_source; - socket = socket_factory_->CreateDatagramClientSocket( - kBindType, base::Bind(&base::RandInt), net_log_, no_source); + socket.reset(socket_factory_->CreateDatagramClientSocket( + kBindType, base::Bind(&base::RandInt), net_log_, no_source)); if (socket.get()) { int rv = socket->Connect((*nameservers_)[server_index]); diff --git a/chromium/net/dns/dns_transaction_unittest.cc b/chromium/net/dns/dns_transaction_unittest.cc index 7040e44be16..f9667eed5f4 100644 --- a/chromium/net/dns/dns_transaction_unittest.cc +++ b/chromium/net/dns/dns_transaction_unittest.cc @@ -180,21 +180,21 @@ class TestSocketFactory : public MockClientSocketFactory { TestSocketFactory() : fail_next_socket_(false) {} virtual ~TestSocketFactory() {} - virtual scoped_ptr<DatagramClientSocket> CreateDatagramClientSocket( + virtual DatagramClientSocket* CreateDatagramClientSocket( DatagramSocket::BindType bind_type, const RandIntCallback& rand_int_cb, net::NetLog* net_log, const net::NetLog::Source& source) OVERRIDE { if (fail_next_socket_) { fail_next_socket_ = false; - return scoped_ptr<DatagramClientSocket>( - new FailingUDPClientSocket(&empty_data_, net_log)); + return new FailingUDPClientSocket(&empty_data_, net_log); } SocketDataProvider* data_provider = mock_data().GetNext(); - scoped_ptr<TestUDPClientSocket> socket( - new TestUDPClientSocket(this, data_provider, net_log)); - data_provider->set_socket(socket.get()); - return socket.PassAs<DatagramClientSocket>(); + TestUDPClientSocket* socket = new TestUDPClientSocket(this, + data_provider, + net_log); + data_provider->set_socket(socket); + return socket; } void OnConnect(const IPEndPoint& endpoint) { diff --git a/chromium/net/dns/host_resolver_impl.cc b/chromium/net/dns/host_resolver_impl.cc index 10631773291..e656f03955f 100644 --- a/chromium/net/dns/host_resolver_impl.cc +++ b/chromium/net/dns/host_resolver_impl.cc @@ -2023,35 +2023,35 @@ HostResolverImpl::Key HostResolverImpl::GetEffectiveKeyForRequest( AddressFamily effective_address_family = info.address_family(); if (info.address_family() == ADDRESS_FAMILY_UNSPECIFIED) { - if (probe_ipv6_support_) { - base::TimeTicks start_time = base::TimeTicks::Now(); - // Google DNS address. - const uint8 kIPv6Address[] = - { 0x20, 0x01, 0x48, 0x60, 0x48, 0x60, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x88 }; - IPAddressNumber address(kIPv6Address, - kIPv6Address + arraysize(kIPv6Address)); - bool rv6 = IsGloballyReachable(address, net_log); - if (rv6) - net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_IPV6_SUPPORTED); - - UMA_HISTOGRAM_TIMES("Net.IPv6ConnectDuration", - base::TimeTicks::Now() - start_time); - if (rv6) { - UMA_HISTOGRAM_BOOLEAN("Net.IPv6ConnectSuccessMatch", - default_address_family_ == ADDRESS_FAMILY_UNSPECIFIED); - } else { - UMA_HISTOGRAM_BOOLEAN("Net.IPv6ConnectFailureMatch", - default_address_family_ != ADDRESS_FAMILY_UNSPECIFIED); - - effective_address_family = ADDRESS_FAMILY_IPV4; - effective_flags |= HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6; - } + base::TimeTicks start_time = base::TimeTicks::Now(); + // Google DNS address. + const uint8 kIPv6Address[] = + { 0x20, 0x01, 0x48, 0x60, 0x48, 0x60, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x88 }; + IPAddressNumber address(kIPv6Address, + kIPv6Address + arraysize(kIPv6Address)); + bool rv6 = IsGloballyReachable(address, net_log); + if (rv6) + net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_IPV6_SUPPORTED); + + UMA_HISTOGRAM_TIMES("Net.IPv6ConnectDuration", + base::TimeTicks::Now() - start_time); + if (rv6) { + UMA_HISTOGRAM_BOOLEAN("Net.IPv6ConnectSuccessMatch", + default_address_family_ == ADDRESS_FAMILY_UNSPECIFIED); } else { - effective_address_family = default_address_family_; + UMA_HISTOGRAM_BOOLEAN("Net.IPv6ConnectFailureMatch", + default_address_family_ != ADDRESS_FAMILY_UNSPECIFIED); } } + if (effective_address_family == ADDRESS_FAMILY_UNSPECIFIED && + default_address_family_ != ADDRESS_FAMILY_UNSPECIFIED) { + effective_address_family = default_address_family_; + if (probe_ipv6_support_) + effective_flags |= HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6; + } + return Key(info.hostname(), effective_address_family, effective_flags); } diff --git a/chromium/net/ftp/ftp_network_transaction.cc b/chromium/net/ftp/ftp_network_transaction.cc index f9f7b820168..ccd6e2ef3b1 100644 --- a/chromium/net/ftp/ftp_network_transaction.cc +++ b/chromium/net/ftp/ftp_network_transaction.cc @@ -663,8 +663,8 @@ int FtpNetworkTransaction::DoCtrlResolveHostComplete(int result) { int FtpNetworkTransaction::DoCtrlConnect() { next_state_ = STATE_CTRL_CONNECT_COMPLETE; - ctrl_socket_ = socket_factory_->CreateTransportClientSocket( - addresses_, net_log_.net_log(), net_log_.source()); + ctrl_socket_.reset(socket_factory_->CreateTransportClientSocket( + addresses_, net_log_.net_log(), net_log_.source())); net_log_.AddEvent( NetLog::TYPE_FTP_CONTROL_CONNECTION, ctrl_socket_->NetLog().source().ToEventParametersCallback()); @@ -1249,8 +1249,8 @@ int FtpNetworkTransaction::DoDataConnect() { return Stop(rv); data_address = AddressList::CreateFromIPAddress( ip_endpoint.address(), data_connection_port_); - data_socket_ = socket_factory_->CreateTransportClientSocket( - data_address, net_log_.net_log(), net_log_.source()); + data_socket_.reset(socket_factory_->CreateTransportClientSocket( + data_address, net_log_.net_log(), net_log_.source())); net_log_.AddEvent( NetLog::TYPE_FTP_DATA_CONNECTION, data_socket_->NetLog().source().ToEventParametersCallback()); diff --git a/chromium/net/http/http_basic_stream.cc b/chromium/net/http/http_basic_stream.cc index c30e17d6203..d70ac02be74 100644 --- a/chromium/net/http/http_basic_stream.cc +++ b/chromium/net/http/http_basic_stream.cc @@ -127,8 +127,4 @@ void HttpBasicStream::Drain(HttpNetworkSession* session) { // |drainer| will delete itself. } -void HttpBasicStream::SetPriority(RequestPriority priority) { - // TODO(akalin): Plumb this through to |connection_|. -} - } // namespace net diff --git a/chromium/net/http/http_basic_stream.h b/chromium/net/http/http_basic_stream.h index 2057837e9a9..2d4bb65ad32 100644 --- a/chromium/net/http/http_basic_stream.h +++ b/chromium/net/http/http_basic_stream.h @@ -81,8 +81,6 @@ class HttpBasicStream : public HttpStream { virtual void Drain(HttpNetworkSession* session) OVERRIDE; - virtual void SetPriority(RequestPriority priority) OVERRIDE; - private: scoped_refptr<GrowableIOBuffer> read_buf_; diff --git a/chromium/net/http/http_cache_transaction.cc b/chromium/net/http/http_cache_transaction.cc index 8d4a45573b8..d1307012208 100644 --- a/chromium/net/http/http_cache_transaction.cc +++ b/chromium/net/http/http_cache_transaction.cc @@ -1538,6 +1538,20 @@ int HttpCache::Transaction::DoCacheQueryData() { } int HttpCache::Transaction::DoCacheQueryDataComplete(int result) { +#if defined(OS_ANDROID) + if (result == ERR_NOT_IMPLEMENTED) { + // Restart the request overwriting the cache entry. + // + // Note: this would have fixed range requests for debug builds on all OSes, + // not just Android, but karen@ prefers to limit the effect based on OS for + // cherry-picked fixes. + // TODO(pasko): remove the OS_ANDROID limitation as soon as the fix proves + // useful after the cherry-pick. + // TODO(pasko): remove this workaround as soon as the SimpleBackendImpl + // supports Sparse IO. + return DoRestartPartialRequest(); + } +#endif DCHECK_EQ(OK, result); if (!cache_.get()) return ERR_UNEXPECTED; diff --git a/chromium/net/http/http_cache_unittest.cc b/chromium/net/http/http_cache_unittest.cc index 37e53346f42..c2bfde7bce2 100644 --- a/chromium/net/http/http_cache_unittest.cc +++ b/chromium/net/http/http_cache_unittest.cc @@ -3394,6 +3394,82 @@ TEST(HttpCache, RangeGET_OK) { RemoveMockTransaction(&kRangeGET_TransactionOK); } +#if defined(OS_ANDROID) + +// Checks that with a cache backend having Sparse IO unimplementes the cache +// entry would be doomed after a range request. +// TODO(pasko): remove when the SimpleBackendImpl implements Sparse IO. +TEST(HttpCache, RangeGET_SparseNotImplemented) { + MockHttpCache cache; + cache.disk_cache()->set_fail_sparse_requests(); + + // Run a cacheable request to prime the cache. + MockTransaction transaction(kTypicalGET_Transaction); + transaction.url = kRangeGET_TransactionOK.url; + AddMockTransaction(&transaction); + RunTransactionTest(cache.http_cache(), transaction); + EXPECT_EQ(1, cache.network_layer()->transaction_count()); + EXPECT_EQ(0, cache.disk_cache()->open_count()); + EXPECT_EQ(1, cache.disk_cache()->create_count()); + + // Verify that we added the entry. + disk_cache::Entry* entry; + net::TestCompletionCallback cb; + int rv = cache.disk_cache()->OpenEntry(transaction.url, + &entry, + cb.callback()); + ASSERT_EQ(net::OK, cb.GetResult(rv)); + EXPECT_EQ(1, cache.disk_cache()->open_count()); + entry->Close(); + RemoveMockTransaction(&transaction); + + // Request the range with the backend that does not support it. + MockTransaction transaction2(kRangeGET_TransactionOK); + std::string headers; + AddMockTransaction(&transaction2); + RunTransactionTestWithResponse(cache.http_cache(), transaction2, &headers); + EXPECT_EQ(2, cache.network_layer()->transaction_count()); + EXPECT_EQ(2, cache.disk_cache()->open_count()); + EXPECT_EQ(2, cache.disk_cache()->create_count()); + + // Mock cache would return net::ERR_CACHE_OPEN_FAILURE on a doomed entry, even + // if it was re-created later, so this effectively checks that the old data is + // gone. + disk_cache::Entry* entry2; + rv = cache.disk_cache()->OpenEntry(transaction2.url, + &entry2, + cb.callback()); + ASSERT_EQ(net::ERR_CACHE_OPEN_FAILURE, cb.GetResult(rv)); + RemoveMockTransaction(&transaction2); +} + +TEST(HttpCache, RangeGET_SparseNotImplementedOnEmptyCache) { + MockHttpCache cache; + cache.disk_cache()->set_fail_sparse_requests(); + + // Request the range with the backend that does not support it. + MockTransaction transaction(kRangeGET_TransactionOK); + std::string headers; + AddMockTransaction(&transaction); + RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers); + EXPECT_EQ(1, cache.network_layer()->transaction_count()); + EXPECT_EQ(0, cache.disk_cache()->open_count()); + EXPECT_EQ(1, cache.disk_cache()->create_count()); + + // Mock cache would return net::ERR_CACHE_OPEN_FAILURE on a doomed entry, even + // if it was re-created later, so this effectively checks that the old data is + // gone as a result of a failed range write. + disk_cache::Entry* entry; + net::TestCompletionCallback cb; + int rv = cache.disk_cache()->OpenEntry(transaction.url, + &entry, + cb.callback()); + ASSERT_EQ(net::ERR_CACHE_OPEN_FAILURE, cb.GetResult(rv)); + RemoveMockTransaction(&transaction); +} + +#endif // OS_ANDROID + // Tests that we can cache range requests and fetch random blocks from the // cache and the network, with synchronous responses. TEST(HttpCache, RangeGET_SyncOK) { diff --git a/chromium/net/http/http_network_transaction.cc b/chromium/net/http/http_network_transaction.cc index a63a2aa43b9..70292be257f 100644 --- a/chromium/net/http/http_network_transaction.cc +++ b/chromium/net/http/http_network_transaction.cc @@ -419,10 +419,8 @@ bool HttpNetworkTransaction::GetLoadTimingInfo( void HttpNetworkTransaction::SetPriority(RequestPriority priority) { priority_ = priority; - if (stream_request_) - stream_request_->SetPriority(priority); - if (stream_) - stream_->SetPriority(priority); + // TODO(akalin): Plumb this through to |stream_request_| and + // |stream_|. } void HttpNetworkTransaction::OnStreamReady(const SSLConfig& used_ssl_config, diff --git a/chromium/net/http/http_network_transaction_unittest.cc b/chromium/net/http/http_network_transaction_unittest.cc index d89ab546afd..5f8dac2f87d 100644 --- a/chromium/net/http/http_network_transaction_unittest.cc +++ b/chromium/net/http/http_network_transaction_unittest.cc @@ -15,7 +15,6 @@ #include "base/files/file_path.h" #include "base/json/json_writer.h" #include "base/memory/scoped_ptr.h" -#include "base/memory/weak_ptr.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "base/test/test_file_util.h" @@ -46,7 +45,6 @@ #include "net/http/http_stream_factory.h" #include "net/http/http_transaction_unittest.h" #include "net/proxy/proxy_config_service_fixed.h" -#include "net/proxy/proxy_info.h" #include "net/proxy/proxy_resolver.h" #include "net/proxy/proxy_service.h" #include "net/socket/client_socket_factory.h" @@ -60,7 +58,6 @@ #include "net/spdy/spdy_session_pool.h" #include "net/spdy/spdy_test_util_common.h" #include "net/ssl/ssl_cert_request_info.h" -#include "net/ssl/ssl_config_service.h" #include "net/ssl/ssl_config_service_defaults.h" #include "net/ssl/ssl_info.h" #include "net/test/cert_test_util.h" @@ -452,7 +449,7 @@ class CaptureGroupNameSocketPool : public ParentPool { virtual void CancelRequest(const std::string& group_name, ClientSocketHandle* handle) {} virtual void ReleaseSocket(const std::string& group_name, - scoped_ptr<StreamSocket> socket, + StreamSocket* socket, int id) {} virtual void CloseIdleSockets() {} virtual int IdleSocketCount() const { @@ -11683,299 +11680,4 @@ TEST_P(HttpNetworkTransactionTest, GetFullRequestHeadersIncludesExtraHeader) { EXPECT_EQ("bar", foo); } -namespace { - -// Fake HttpStreamBase that simply records calls to SetPriority(). -class FakeStream : public HttpStreamBase, - public base::SupportsWeakPtr<FakeStream> { - public: - explicit FakeStream(RequestPriority priority) : priority_(priority) {} - virtual ~FakeStream() {} - - RequestPriority priority() const { return priority_; } - - virtual int InitializeStream(const HttpRequestInfo* request_info, - RequestPriority priority, - const BoundNetLog& net_log, - const CompletionCallback& callback) OVERRIDE { - return ERR_IO_PENDING; - } - - virtual int SendRequest(const HttpRequestHeaders& request_headers, - HttpResponseInfo* response, - const CompletionCallback& callback) OVERRIDE { - ADD_FAILURE(); - return ERR_UNEXPECTED; - } - - virtual int ReadResponseHeaders(const CompletionCallback& callback) OVERRIDE { - ADD_FAILURE(); - return ERR_UNEXPECTED; - } - - virtual const HttpResponseInfo* GetResponseInfo() const OVERRIDE { - ADD_FAILURE(); - return NULL; - } - - virtual int ReadResponseBody(IOBuffer* buf, int buf_len, - const CompletionCallback& callback) OVERRIDE { - ADD_FAILURE(); - return ERR_UNEXPECTED; - } - - virtual void Close(bool not_reusable) OVERRIDE {} - - virtual bool IsResponseBodyComplete() const OVERRIDE { - ADD_FAILURE(); - return false; - } - - virtual bool CanFindEndOfResponse() const OVERRIDE { - return false; - } - - virtual bool IsConnectionReused() const OVERRIDE { - ADD_FAILURE(); - return false; - } - - virtual void SetConnectionReused() OVERRIDE { - ADD_FAILURE(); - } - - virtual bool IsConnectionReusable() const OVERRIDE { - ADD_FAILURE(); - return false; - } - - virtual bool GetLoadTimingInfo( - LoadTimingInfo* load_timing_info) const OVERRIDE { - ADD_FAILURE(); - return false; - } - - virtual void GetSSLInfo(SSLInfo* ssl_info) OVERRIDE { - ADD_FAILURE(); - } - - virtual void GetSSLCertRequestInfo( - SSLCertRequestInfo* cert_request_info) OVERRIDE { - ADD_FAILURE(); - } - - virtual bool IsSpdyHttpStream() const OVERRIDE { - ADD_FAILURE(); - return false; - } - - virtual void Drain(HttpNetworkSession* session) OVERRIDE { - ADD_FAILURE(); - } - - virtual void SetPriority(RequestPriority priority) OVERRIDE { - priority_ = priority; - } - - private: - RequestPriority priority_; - - DISALLOW_COPY_AND_ASSIGN(FakeStream); -}; - -// Fake HttpStreamRequest that simply records calls to SetPriority() -// and vends FakeStreams with its current priority. -class FakeStreamRequest : public HttpStreamRequest, - public base::SupportsWeakPtr<FakeStreamRequest> { - public: - FakeStreamRequest(RequestPriority priority, - HttpStreamRequest::Delegate* delegate) - : priority_(priority), - delegate_(delegate) {} - - virtual ~FakeStreamRequest() {} - - RequestPriority priority() const { return priority_; } - - // Create a new FakeStream and pass it to the request's - // delegate. Returns a weak pointer to the FakeStream. - base::WeakPtr<FakeStream> FinishStreamRequest() { - FakeStream* fake_stream = new FakeStream(priority_); - // Do this before calling OnStreamReady() as OnStreamReady() may - // immediately delete |fake_stream|. - base::WeakPtr<FakeStream> weak_stream = fake_stream->AsWeakPtr(); - delegate_->OnStreamReady(SSLConfig(), ProxyInfo(), fake_stream); - return weak_stream; - } - - virtual int RestartTunnelWithProxyAuth( - const AuthCredentials& credentials) OVERRIDE { - ADD_FAILURE(); - return ERR_UNEXPECTED; - } - - virtual LoadState GetLoadState() const OVERRIDE { - ADD_FAILURE(); - return LoadState(); - } - - virtual void SetPriority(RequestPriority priority) OVERRIDE { - priority_ = priority; - } - - virtual bool was_npn_negotiated() const OVERRIDE { - return false; - } - - virtual NextProto protocol_negotiated() const OVERRIDE { - return kProtoUnknown; - } - - virtual bool using_spdy() const OVERRIDE { - return false; - } - - private: - RequestPriority priority_; - HttpStreamRequest::Delegate* const delegate_; - - DISALLOW_COPY_AND_ASSIGN(FakeStreamRequest); -}; - -// Fake HttpStreamFactory that vends FakeStreamRequests. -class FakeStreamFactory : public HttpStreamFactory { - public: - FakeStreamFactory() {} - virtual ~FakeStreamFactory() {} - - // Returns a WeakPtr<> to the last HttpStreamRequest returned by - // RequestStream() (which may be NULL if it was destroyed already). - base::WeakPtr<FakeStreamRequest> last_stream_request() { - return last_stream_request_; - } - - virtual HttpStreamRequest* RequestStream( - const HttpRequestInfo& info, - RequestPriority priority, - const SSLConfig& server_ssl_config, - const SSLConfig& proxy_ssl_config, - HttpStreamRequest::Delegate* delegate, - const BoundNetLog& net_log) OVERRIDE { - FakeStreamRequest* fake_request = new FakeStreamRequest(priority, delegate); - last_stream_request_ = fake_request->AsWeakPtr(); - return fake_request; - } - - virtual HttpStreamRequest* RequestWebSocketStream( - const HttpRequestInfo& info, - RequestPriority priority, - const SSLConfig& server_ssl_config, - const SSLConfig& proxy_ssl_config, - HttpStreamRequest::Delegate* delegate, - WebSocketStreamBase::Factory* factory, - const BoundNetLog& net_log) OVERRIDE { - ADD_FAILURE(); - return NULL; - } - - virtual void PreconnectStreams(int num_streams, - const HttpRequestInfo& info, - RequestPriority priority, - const SSLConfig& server_ssl_config, - const SSLConfig& proxy_ssl_config) OVERRIDE { - ADD_FAILURE(); - } - - virtual base::Value* PipelineInfoToValue() const OVERRIDE { - ADD_FAILURE(); - return NULL; - } - - virtual const HostMappingRules* GetHostMappingRules() const OVERRIDE { - ADD_FAILURE(); - return NULL; - } - - private: - base::WeakPtr<FakeStreamRequest> last_stream_request_; - - DISALLOW_COPY_AND_ASSIGN(FakeStreamFactory); -}; - -} // namespace - -// Make sure that HttpNetworkTransaction passes on its priority to its -// stream request on start. -TEST_P(HttpNetworkTransactionTest, SetStreamRequestPriorityOnStart) { - scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_)); - HttpNetworkSessionPeer peer(session); - FakeStreamFactory* fake_factory = new FakeStreamFactory(); - peer.SetHttpStreamFactory(fake_factory); - - HttpNetworkTransaction trans(LOW, session); - - ASSERT_TRUE(fake_factory->last_stream_request() == NULL); - - HttpRequestInfo request; - TestCompletionCallback callback; - EXPECT_EQ(ERR_IO_PENDING, - trans.Start(&request, callback.callback(), BoundNetLog())); - - base::WeakPtr<FakeStreamRequest> fake_request = - fake_factory->last_stream_request(); - ASSERT_TRUE(fake_request != NULL); - EXPECT_EQ(LOW, fake_request->priority()); -} - -// Make sure that HttpNetworkTransaction passes on its priority -// updates to its stream request. -TEST_P(HttpNetworkTransactionTest, SetStreamRequestPriority) { - scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_)); - HttpNetworkSessionPeer peer(session); - FakeStreamFactory* fake_factory = new FakeStreamFactory(); - peer.SetHttpStreamFactory(fake_factory); - - HttpNetworkTransaction trans(LOW, session); - - HttpRequestInfo request; - TestCompletionCallback callback; - EXPECT_EQ(ERR_IO_PENDING, - trans.Start(&request, callback.callback(), BoundNetLog())); - - base::WeakPtr<FakeStreamRequest> fake_request = - fake_factory->last_stream_request(); - ASSERT_TRUE(fake_request != NULL); - EXPECT_EQ(LOW, fake_request->priority()); - - trans.SetPriority(LOWEST); - ASSERT_TRUE(fake_request != NULL); - EXPECT_EQ(LOWEST, fake_request->priority()); -} - -// Make sure that HttpNetworkTransaction passes on its priority -// updates to its stream. -TEST_P(HttpNetworkTransactionTest, SetStreamPriority) { - scoped_refptr<HttpNetworkSession> session(CreateSession(&session_deps_)); - HttpNetworkSessionPeer peer(session); - FakeStreamFactory* fake_factory = new FakeStreamFactory(); - peer.SetHttpStreamFactory(fake_factory); - - HttpNetworkTransaction trans(LOW, session); - - HttpRequestInfo request; - TestCompletionCallback callback; - EXPECT_EQ(ERR_IO_PENDING, - trans.Start(&request, callback.callback(), BoundNetLog())); - - base::WeakPtr<FakeStreamRequest> fake_request = - fake_factory->last_stream_request(); - ASSERT_TRUE(fake_request != NULL); - base::WeakPtr<FakeStream> fake_stream = fake_request->FinishStreamRequest(); - ASSERT_TRUE(fake_stream != NULL); - EXPECT_EQ(LOW, fake_stream->priority()); - - trans.SetPriority(LOWEST); - EXPECT_EQ(LOWEST, fake_stream->priority()); -} - } // namespace net diff --git a/chromium/net/http/http_pipelined_host_forced.cc b/chromium/net/http/http_pipelined_host_forced.cc index 8059d848d73..8179e86f319 100644 --- a/chromium/net/http/http_pipelined_host_forced.cc +++ b/chromium/net/http/http_pipelined_host_forced.cc @@ -36,9 +36,10 @@ HttpPipelinedStream* HttpPipelinedHostForced::CreateStreamOnNewPipeline( bool was_npn_negotiated, NextProto protocol_negotiated) { CHECK(!pipeline_.get()); - scoped_ptr<BufferedWriteStreamSocket> buffered_socket( - new BufferedWriteStreamSocket(connection->PassSocket())); - connection->SetSocket(buffered_socket.PassAs<StreamSocket>()); + StreamSocket* wrapped_socket = connection->release_socket(); + BufferedWriteStreamSocket* buffered_socket = new BufferedWriteStreamSocket( + wrapped_socket); + connection->set_socket(buffered_socket); pipeline_.reset(factory_->CreateNewPipeline( connection, this, key_.origin(), used_ssl_config, used_proxy_info, net_log, was_npn_negotiated, protocol_negotiated)); diff --git a/chromium/net/http/http_pipelined_stream.cc b/chromium/net/http/http_pipelined_stream.cc index df5743556d1..951c2f9afd6 100644 --- a/chromium/net/http/http_pipelined_stream.cc +++ b/chromium/net/http/http_pipelined_stream.cc @@ -121,11 +121,6 @@ void HttpPipelinedStream::Drain(HttpNetworkSession* session) { pipeline_->Drain(this, session); } -void HttpPipelinedStream::SetPriority(RequestPriority priority) { - // TODO(akalin): Plumb this through to |pipeline_| and its - // underlying ClientSocketHandle. -} - const SSLConfig& HttpPipelinedStream::used_ssl_config() const { return pipeline_->used_ssl_config(); } diff --git a/chromium/net/http/http_pipelined_stream.h b/chromium/net/http/http_pipelined_stream.h index d3a7991e5ca..675d8f083a2 100644 --- a/chromium/net/http/http_pipelined_stream.h +++ b/chromium/net/http/http_pipelined_stream.h @@ -81,8 +81,6 @@ class HttpPipelinedStream : public HttpStream { virtual void Drain(HttpNetworkSession* session) OVERRIDE; - virtual void SetPriority(RequestPriority priority) OVERRIDE; - // The SSLConfig used to establish this stream's pipeline. const SSLConfig& used_ssl_config() const; diff --git a/chromium/net/http/http_proxy_client_socket_pool.cc b/chromium/net/http/http_proxy_client_socket_pool.cc index c75df6f0d2f..b80df37b3dd 100644 --- a/chromium/net/http/http_proxy_client_socket_pool.cc +++ b/chromium/net/http/http_proxy_client_socket_pool.cc @@ -289,7 +289,7 @@ int HttpProxyConnectJob::DoHttpProxyConnect() { int HttpProxyConnectJob::DoHttpProxyConnectComplete(int result) { if (result == OK || result == ERR_PROXY_AUTH_REQUESTED || result == ERR_HTTPS_PROXY_TUNNEL_RESPONSE) { - SetSocket(transport_socket_.PassAs<StreamSocket>()); + set_socket(transport_socket_.release()); } return result; @@ -380,19 +380,19 @@ HttpProxyConnectJobFactory::HttpProxyConnectJobFactory( } -scoped_ptr<ConnectJob> +ConnectJob* HttpProxyClientSocketPool::HttpProxyConnectJobFactory::NewConnectJob( const std::string& group_name, const PoolBase::Request& request, ConnectJob::Delegate* delegate) const { - return scoped_ptr<ConnectJob>(new HttpProxyConnectJob(group_name, - request.params(), - ConnectionTimeout(), - transport_pool_, - ssl_pool_, - host_resolver_, - delegate, - net_log_)); + return new HttpProxyConnectJob(group_name, + request.params(), + ConnectionTimeout(), + transport_pool_, + ssl_pool_, + host_resolver_, + delegate, + net_log_); } base::TimeDelta @@ -462,9 +462,8 @@ void HttpProxyClientSocketPool::CancelRequest( } void HttpProxyClientSocketPool::ReleaseSocket(const std::string& group_name, - scoped_ptr<StreamSocket> socket, - int id) { - base_.ReleaseSocket(group_name, socket.Pass(), id); + StreamSocket* socket, int id) { + base_.ReleaseSocket(group_name, socket, id); } void HttpProxyClientSocketPool::FlushWithError(int error) { diff --git a/chromium/net/http/http_proxy_client_socket_pool.h b/chromium/net/http/http_proxy_client_socket_pool.h index b77b5ae3571..a15b8cad809 100644 --- a/chromium/net/http/http_proxy_client_socket_pool.h +++ b/chromium/net/http/http_proxy_client_socket_pool.h @@ -204,7 +204,7 @@ class NET_EXPORT_PRIVATE HttpProxyClientSocketPool ClientSocketHandle* handle) OVERRIDE; virtual void ReleaseSocket(const std::string& group_name, - scoped_ptr<StreamSocket> socket, + StreamSocket* socket, int id) OVERRIDE; virtual void FlushWithError(int error) OVERRIDE; @@ -250,7 +250,7 @@ class NET_EXPORT_PRIVATE HttpProxyClientSocketPool NetLog* net_log); // ClientSocketPoolBase::ConnectJobFactory methods. - virtual scoped_ptr<ConnectJob> NewConnectJob( + virtual ConnectJob* NewConnectJob( const std::string& group_name, const PoolBase::Request& request, ConnectJob::Delegate* delegate) const OVERRIDE; diff --git a/chromium/net/http/http_response_body_drainer_unittest.cc b/chromium/net/http/http_response_body_drainer_unittest.cc index 70134cce1ea..5d9fcc4689e 100644 --- a/chromium/net/http/http_response_body_drainer_unittest.cc +++ b/chromium/net/http/http_response_body_drainer_unittest.cc @@ -127,8 +127,6 @@ class MockHttpStream : public HttpStream { virtual void Drain(HttpNetworkSession*) OVERRIDE {} - virtual void SetPriority(RequestPriority priority) OVERRIDE {} - // Methods to tweak/observer mock behavior: void set_stall_reads_forever() { stall_reads_forever_ = true; } diff --git a/chromium/net/http/http_stream_base.h b/chromium/net/http/http_stream_base.h index 596ed75dff1..6dce6d2a805 100644 --- a/chromium/net/http/http_stream_base.h +++ b/chromium/net/http/http_stream_base.h @@ -141,9 +141,6 @@ class NET_EXPORT_PRIVATE HttpStreamBase { // draining is complete. virtual void Drain(HttpNetworkSession* session) = 0; - // Called when the priority of the parent transaction changes. - virtual void SetPriority(RequestPriority priority) = 0; - private: DISALLOW_COPY_AND_ASSIGN(HttpStreamBase); }; diff --git a/chromium/net/http/http_stream_factory.h b/chromium/net/http/http_stream_factory.h index 0de3b65bc57..6db6905b433 100644 --- a/chromium/net/http/http_stream_factory.h +++ b/chromium/net/http/http_stream_factory.h @@ -157,9 +157,6 @@ class NET_EXPORT_PRIVATE HttpStreamRequest { virtual int RestartTunnelWithProxyAuth( const AuthCredentials& credentials) = 0; - // Called when the priority of the parent transaction changes. - virtual void SetPriority(RequestPriority priority) = 0; - // Returns the LoadState for the request. virtual LoadState GetLoadState() const = 0; diff --git a/chromium/net/http/http_stream_factory_impl.h b/chromium/net/http/http_stream_factory_impl.h index 4339fd350d7..3949f3839ee 100644 --- a/chromium/net/http/http_stream_factory_impl.h +++ b/chromium/net/http/http_stream_factory_impl.h @@ -9,7 +9,6 @@ #include <set> #include <vector> -#include "base/gtest_prod_util.h" #include "base/memory/ref_counted.h" #include "net/base/host_port_pair.h" #include "net/base/net_log.h" @@ -67,10 +66,8 @@ class NET_EXPORT_PRIVATE HttpStreamFactoryImpl : size_t num_orphaned_jobs() const { return orphaned_job_set_.size(); } private: - FRIEND_TEST_ALL_PREFIXES(HttpStreamFactoryImplRequestTest, SetPriority); - - class NET_EXPORT_PRIVATE Request; - class NET_EXPORT_PRIVATE Job; + class Request; + class Job; typedef std::set<Request*> RequestSet; typedef std::vector<Request*> RequestVector; diff --git a/chromium/net/http/http_stream_factory_impl_job.cc b/chromium/net/http/http_stream_factory_impl_job.cc index c0383f4772d..b2eee3b0fbe 100644 --- a/chromium/net/http/http_stream_factory_impl_job.cc +++ b/chromium/net/http/http_stream_factory_impl_job.cc @@ -230,17 +230,12 @@ void HttpStreamFactoryImpl::Job::Orphan(const Request* request) { } } -void HttpStreamFactoryImpl::Job::SetPriority(RequestPriority priority) { - priority_ = priority; - // TODO(akalin): Propagate this to |connection_| and maybe the - // preconnect state. -} - bool HttpStreamFactoryImpl::Job::was_npn_negotiated() const { return was_npn_negotiated_; } -NextProto HttpStreamFactoryImpl::Job::protocol_negotiated() const { +NextProto HttpStreamFactoryImpl::Job::protocol_negotiated() + const { return protocol_negotiated_; } diff --git a/chromium/net/http/http_stream_factory_impl_job.h b/chromium/net/http/http_stream_factory_impl_job.h index 01a794a1bc7..2c2eb349586 100644 --- a/chromium/net/http/http_stream_factory_impl_job.h +++ b/chromium/net/http/http_stream_factory_impl_job.h @@ -74,9 +74,6 @@ class HttpStreamFactoryImpl::Job { // Used to detach the Job from |request|. void Orphan(const Request* request); - void SetPriority(RequestPriority priority); - - RequestPriority priority() const { return priority_; } bool was_npn_negotiated() const; NextProto protocol_negotiated() const; bool using_spdy() const; diff --git a/chromium/net/http/http_stream_factory_impl_request.cc b/chromium/net/http/http_stream_factory_impl_request.cc index 57190ed72e7..e73a897a528 100644 --- a/chromium/net/http/http_stream_factory_impl_request.cc +++ b/chromium/net/http/http_stream_factory_impl_request.cc @@ -215,15 +215,6 @@ int HttpStreamFactoryImpl::Request::RestartTunnelWithProxyAuth( return bound_job_->RestartTunnelWithProxyAuth(credentials); } -void HttpStreamFactoryImpl::Request::SetPriority(RequestPriority priority) { - for (std::set<HttpStreamFactoryImpl::Job*>::const_iterator it = jobs_.begin(); - it != jobs_.end(); ++it) { - (*it)->SetPriority(priority); - } - if (bound_job_) - bound_job_->SetPriority(priority); -} - LoadState HttpStreamFactoryImpl::Request::GetLoadState() const { if (bound_job_.get()) return bound_job_->GetLoadState(); diff --git a/chromium/net/http/http_stream_factory_impl_request.h b/chromium/net/http/http_stream_factory_impl_request.h index d6f9b02cbef..169e1f54ce9 100644 --- a/chromium/net/http/http_stream_factory_impl_request.h +++ b/chromium/net/http/http_stream_factory_impl_request.h @@ -105,7 +105,6 @@ class HttpStreamFactoryImpl::Request : public HttpStreamRequest { virtual int RestartTunnelWithProxyAuth( const AuthCredentials& credentials) OVERRIDE; - virtual void SetPriority(RequestPriority priority) OVERRIDE; virtual LoadState GetLoadState() const OVERRIDE; virtual bool was_npn_negotiated() const OVERRIDE; virtual NextProto protocol_negotiated() const OVERRIDE; diff --git a/chromium/net/http/http_stream_factory_impl_request_unittest.cc b/chromium/net/http/http_stream_factory_impl_request_unittest.cc deleted file mode 100644 index 1f38a2e56f6..00000000000 --- a/chromium/net/http/http_stream_factory_impl_request_unittest.cc +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "net/http/http_stream_factory_impl_request.h" - -#include "net/http/http_stream_factory_impl_job.h" -#include "net/proxy/proxy_info.h" -#include "net/proxy/proxy_service.h" -#include "net/spdy/spdy_test_util_common.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace net { - -class HttpStreamFactoryImplRequestTest - : public ::testing::Test, - public ::testing::WithParamInterface<NextProto> {}; - -INSTANTIATE_TEST_CASE_P( - NextProto, - HttpStreamFactoryImplRequestTest, - testing::Values(kProtoSPDY2, kProtoSPDY3, kProtoSPDY31, kProtoSPDY4a2, - kProtoHTTP2Draft04)); - -namespace { - -class DoNothingRequestDelegate : public HttpStreamRequest::Delegate { - public: - DoNothingRequestDelegate() {} - - virtual ~DoNothingRequestDelegate() {} - - // HttpStreamRequest::Delegate - virtual void OnStreamReady( - const SSLConfig& used_ssl_config, - const ProxyInfo& used_proxy_info, - HttpStreamBase* stream) OVERRIDE {} - virtual void OnWebSocketStreamReady( - const SSLConfig& used_ssl_config, - const ProxyInfo& used_proxy_info, - WebSocketStreamBase* stream) OVERRIDE {} - virtual void OnStreamFailed( - int status, - const SSLConfig& used_ssl_config) OVERRIDE {} - virtual void OnCertificateError( - int status, - const SSLConfig& used_ssl_config, - const SSLInfo& ssl_info) OVERRIDE {} - virtual void OnNeedsProxyAuth(const HttpResponseInfo& proxy_response, - const SSLConfig& used_ssl_config, - const ProxyInfo& used_proxy_info, - HttpAuthController* auth_controller) OVERRIDE {} - virtual void OnNeedsClientAuth(const SSLConfig& used_ssl_config, - SSLCertRequestInfo* cert_info) OVERRIDE {} - virtual void OnHttpsProxyTunnelResponse(const HttpResponseInfo& response_info, - const SSLConfig& used_ssl_config, - const ProxyInfo& used_proxy_info, - HttpStreamBase* stream) OVERRIDE {} -}; - -} // namespace - -// Make sure that Request passes on its priority updates to its jobs. -TEST_P(HttpStreamFactoryImplRequestTest, SetPriority) { - SpdySessionDependencies session_deps(GetParam(), - ProxyService::CreateDirect()); - - scoped_refptr<HttpNetworkSession> - session(SpdySessionDependencies::SpdyCreateSession(&session_deps)); - HttpStreamFactoryImpl* factory = - static_cast<HttpStreamFactoryImpl*>(session->http_stream_factory()); - - DoNothingRequestDelegate request_delegate; - HttpStreamFactoryImpl::Request request( - GURL(), factory, &request_delegate, NULL, BoundNetLog()); - - HttpStreamFactoryImpl::Job* job = - new HttpStreamFactoryImpl::Job(factory, - session, - HttpRequestInfo(), - DEFAULT_PRIORITY, - SSLConfig(), - SSLConfig(), - NULL); - request.AttachJob(job); - EXPECT_EQ(DEFAULT_PRIORITY, job->priority()); - - request.SetPriority(MEDIUM); - EXPECT_EQ(MEDIUM, job->priority()); - - // Make |job| the bound job. - request.OnStreamFailed(job, ERR_FAILED, SSLConfig()); - - request.SetPriority(IDLE); - EXPECT_EQ(IDLE, job->priority()); -} - -} // namespace net diff --git a/chromium/net/http/http_stream_factory_impl_unittest.cc b/chromium/net/http/http_stream_factory_impl_unittest.cc index f378c93ea18..14fbc0338a3 100644 --- a/chromium/net/http/http_stream_factory_impl_unittest.cc +++ b/chromium/net/http/http_stream_factory_impl_unittest.cc @@ -314,7 +314,7 @@ class CapturePreconnectsSocketPool : public ParentPool { ADD_FAILURE(); } virtual void ReleaseSocket(const std::string& group_name, - scoped_ptr<StreamSocket> socket, + StreamSocket* socket, int id) OVERRIDE { ADD_FAILURE(); } diff --git a/chromium/net/http/http_stream_parser_unittest.cc b/chromium/net/http/http_stream_parser_unittest.cc index 84775945ec1..d530c2deab7 100644 --- a/chromium/net/http/http_stream_parser_unittest.cc +++ b/chromium/net/http/http_stream_parser_unittest.cc @@ -220,7 +220,7 @@ TEST(HttpStreamParser, AsyncChunkAndAsyncSocket) { ASSERT_EQ(OK, rv); scoped_ptr<ClientSocketHandle> socket_handle(new ClientSocketHandle); - socket_handle->SetSocket(transport.PassAs<StreamSocket>()); + socket_handle->set_socket(transport.release()); HttpRequestInfo request_info; request_info.method = "GET"; @@ -375,7 +375,7 @@ TEST(HttpStreamParser, TruncatedHeaders) { ASSERT_EQ(OK, rv); scoped_ptr<ClientSocketHandle> socket_handle(new ClientSocketHandle); - socket_handle->SetSocket(transport.PassAs<StreamSocket>()); + socket_handle->set_socket(transport.release()); HttpRequestInfo request_info; request_info.method = "GET"; diff --git a/chromium/net/http/mock_http_cache.cc b/chromium/net/http/mock_http_cache.cc index 85ffa74584e..a3d55b17e6b 100644 --- a/chromium/net/http/mock_http_cache.cc +++ b/chromium/net/http/mock_http_cache.cc @@ -50,14 +50,10 @@ struct MockDiskEntry::CallbackInfo { int result; }; -MockDiskEntry::MockDiskEntry() - : test_mode_(0), doomed_(false), sparse_(false), - fail_requests_(false), busy_(false), delayed_(false) { -} - MockDiskEntry::MockDiskEntry(const std::string& key) : key_(key), doomed_(false), sparse_(false), - fail_requests_(false), busy_(false), delayed_(false) { + fail_requests_(false), fail_sparse_requests_(false), busy_(false), + delayed_(false) { test_mode_ = GetTestModeForEntry(key); } @@ -139,6 +135,8 @@ int MockDiskEntry::WriteData( int MockDiskEntry::ReadSparseData(int64 offset, net::IOBuffer* buf, int buf_len, const net::CompletionCallback& callback) { DCHECK(!callback.is_null()); + if (fail_sparse_requests_) + return net::ERR_NOT_IMPLEMENTED; if (!sparse_ || busy_) return net::ERR_CACHE_OPERATION_NOT_SUPPORTED; if (offset < 0) @@ -169,6 +167,8 @@ int MockDiskEntry::WriteSparseData(int64 offset, net::IOBuffer* buf, int buf_len, const net::CompletionCallback& callback) { DCHECK(!callback.is_null()); + if (fail_sparse_requests_) + return net::ERR_NOT_IMPLEMENTED; if (busy_) return net::ERR_CACHE_OPERATION_NOT_SUPPORTED; if (!sparse_) { @@ -237,6 +237,8 @@ int MockDiskEntry::GetAvailableRange(int64 offset, int len, int64* start, } bool MockDiskEntry::CouldBeSparse() const { + if (fail_sparse_requests_) + return false; return sparse_; } @@ -245,6 +247,8 @@ void MockDiskEntry::CancelSparseIO() { } int MockDiskEntry::ReadyForSparseIO(const net::CompletionCallback& callback) { + if (fail_sparse_requests_) + return net::ERR_NOT_IMPLEMENTED; if (!cancel_) return net::OK; @@ -333,7 +337,8 @@ bool MockDiskEntry::ignore_callbacks_ = false; MockDiskCache::MockDiskCache() : open_count_(0), create_count_(0), fail_requests_(false), - soft_failures_(false), double_create_check_(true) { + soft_failures_(false), double_create_check_(true), + fail_sparse_requests_(false) { } MockDiskCache::~MockDiskCache() { @@ -411,6 +416,9 @@ int MockDiskCache::CreateEntry(const std::string& key, if (soft_failures_) new_entry->set_fail_requests(); + if (fail_sparse_requests_) + new_entry->set_fail_sparse_requests(); + if (GetTestModeForEntry(key) & TEST_MODE_SYNC_CACHE_START) return net::OK; diff --git a/chromium/net/http/mock_http_cache.h b/chromium/net/http/mock_http_cache.h index 6cb0e50f562..90399ec4ff0 100644 --- a/chromium/net/http/mock_http_cache.h +++ b/chromium/net/http/mock_http_cache.h @@ -21,7 +21,6 @@ class MockDiskEntry : public disk_cache::Entry, public base::RefCounted<MockDiskEntry> { public: - MockDiskEntry(); explicit MockDiskEntry(const std::string& key); bool is_doomed() const { return doomed_; } @@ -53,6 +52,8 @@ class MockDiskEntry : public disk_cache::Entry, // Fail most subsequent requests. void set_fail_requests() { fail_requests_ = true; } + void set_fail_sparse_requests() { fail_sparse_requests_ = true; } + // If |value| is true, don't deliver any completion callbacks until called // again with |value| set to false. Caution: remember to enable callbacks // again or all subsequent tests will fail. @@ -85,6 +86,7 @@ class MockDiskEntry : public disk_cache::Entry, bool doomed_; bool sparse_; bool fail_requests_; + bool fail_sparse_requests_; bool busy_; bool delayed_; static bool cancel_; @@ -134,6 +136,9 @@ class MockDiskCache : public disk_cache::Backend { // Makes sure that CreateEntry is not called twice for a given key. void set_double_create_check(bool value) { double_create_check_ = value; } + // Makes all requests for data ranges to fail as not implemented. + void set_fail_sparse_requests() { fail_sparse_requests_ = true; } + void ReleaseAll(); private: @@ -147,6 +152,7 @@ class MockDiskCache : public disk_cache::Backend { bool fail_requests_; bool soft_failures_; bool double_create_check_; + bool fail_sparse_requests_; }; class MockBackendFactory : public net::HttpCache::BackendFactory { diff --git a/chromium/net/http/proxy_connect_redirect_http_stream.cc b/chromium/net/http/proxy_connect_redirect_http_stream.cc index 59bb0146953..f30f33c002c 100644 --- a/chromium/net/http/proxy_connect_redirect_http_stream.cc +++ b/chromium/net/http/proxy_connect_redirect_http_stream.cc @@ -109,10 +109,6 @@ void ProxyConnectRedirectHttpStream::Drain(HttpNetworkSession* session) { NOTREACHED(); } -void ProxyConnectRedirectHttpStream::SetPriority(RequestPriority priority) { - // Nothing to do. -} - UploadProgress ProxyConnectRedirectHttpStream::GetUploadProgress() const { NOTREACHED(); return UploadProgress(); diff --git a/chromium/net/http/proxy_connect_redirect_http_stream.h b/chromium/net/http/proxy_connect_redirect_http_stream.h index c335c218c71..f39ec76b9b9 100644 --- a/chromium/net/http/proxy_connect_redirect_http_stream.h +++ b/chromium/net/http/proxy_connect_redirect_http_stream.h @@ -59,10 +59,6 @@ class ProxyConnectRedirectHttpStream : public HttpStream { SSLCertRequestInfo* cert_request_info) OVERRIDE; virtual bool IsSpdyHttpStream() const OVERRIDE; virtual void Drain(HttpNetworkSession* session) OVERRIDE; - - // This function may be called. - virtual void SetPriority(RequestPriority priority) OVERRIDE; - virtual UploadProgress GetUploadProgress() const OVERRIDE; virtual HttpStream* RenewStreamForAuth() OVERRIDE; diff --git a/chromium/net/net.gyp b/chromium/net/net.gyp index 7086e3d362a..9443da6ac8e 100644 --- a/chromium/net/net.gyp +++ b/chromium/net/net.gyp @@ -399,6 +399,8 @@ 'disk_cache/simple/simple_index.h', 'disk_cache/simple/simple_index_file.cc', 'disk_cache/simple/simple_index_file.h', + 'disk_cache/simple/simple_index_file_posix.cc', + 'disk_cache/simple/simple_index_file_win.cc', 'disk_cache/simple/simple_net_log_parameters.cc', 'disk_cache/simple/simple_net_log_parameters.h', 'disk_cache/simple/simple_synchronous_entry.cc', @@ -1631,7 +1633,6 @@ 'http/http_security_headers_unittest.cc', 'http/http_server_properties_impl_unittest.cc', 'http/http_status_code_unittest.cc', - 'http/http_stream_factory_impl_request_unittest.cc', 'http/http_stream_factory_impl_unittest.cc', 'http/http_stream_parser_unittest.cc', 'http/http_transaction_unittest.cc', @@ -2134,6 +2135,11 @@ '../testing/android/native_test.gyp:native_test_native_code', ] }], + [ 'OS != "win" and OS != "mac"', { + 'sources!': [ + 'cert/x509_cert_types_unittest.cc', + ], + }], ], }, { diff --git a/chromium/net/quic/quic_client_session.cc b/chromium/net/quic/quic_client_session.cc index 67620787307..d7fb0d2675e 100644 --- a/chromium/net/quic/quic_client_session.cc +++ b/chromium/net/quic/quic_client_session.cc @@ -81,7 +81,7 @@ void QuicClientSession::StreamRequest::OnRequestCompleteFailure(int rv) { QuicClientSession::QuicClientSession( QuicConnection* connection, - scoped_ptr<DatagramClientSocket> socket, + DatagramClientSocket* socket, QuicStreamFactory* stream_factory, QuicCryptoClientStreamFactory* crypto_client_stream_factory, const string& server_hostname, @@ -91,7 +91,7 @@ QuicClientSession::QuicClientSession( : QuicSession(connection, config, false), weak_factory_(this), stream_factory_(stream_factory), - socket_(socket.Pass()), + socket_(socket), read_buffer_(new IOBufferWithSize(kMaxPacketSize)), read_pending_(false), num_total_streams_(0), @@ -260,18 +260,7 @@ void QuicClientSession::OnCryptoHandshakeEvent(CryptoHandshakeEvent event) { QuicSession::OnCryptoHandshakeEvent(event); } -void QuicClientSession::OnCryptoHandshakeMessageSent( - const CryptoHandshakeMessage& message) { - logger_.OnCryptoHandshakeMessageSent(message); -} - -void QuicClientSession::OnCryptoHandshakeMessageReceived( - const CryptoHandshakeMessage& message) { - logger_.OnCryptoHandshakeMessageReceived(message); -} - void QuicClientSession::ConnectionClose(QuicErrorCode error, bool from_peer) { - logger_.OnConnectionClose(error, from_peer); UMA_HISTOGRAM_SPARSE_SLOWLY("Net.QuicSession.ConnectionCloseErrorCode", error); UMA_HISTOGRAM_SPARSE_SLOWLY("Net.QuicSession.QuicVersion", diff --git a/chromium/net/quic/quic_client_session.h b/chromium/net/quic/quic_client_session.h index 555837fe9a5..339c40b2ba1 100644 --- a/chromium/net/quic/quic_client_session.h +++ b/chromium/net/quic/quic_client_session.h @@ -13,7 +13,6 @@ #include <string> #include "base/containers/hash_tables.h" -#include "base/memory/scoped_ptr.h" #include "net/base/completion_callback.h" #include "net/quic/quic_connection_logger.h" #include "net/quic/quic_crypto_client_stream.h" @@ -75,7 +74,7 @@ class NET_EXPORT_PRIVATE QuicClientSession : public QuicSession { // not |stream_factory|, which must outlive this session. // TODO(rch): decouple the factory from the session via a Delegate interface. QuicClientSession(QuicConnection* connection, - scoped_ptr<DatagramClientSocket> socket, + DatagramClientSocket* socket, QuicStreamFactory* stream_factory, QuicCryptoClientStreamFactory* crypto_client_stream_factory, const std::string& server_hostname, @@ -103,10 +102,6 @@ class NET_EXPORT_PRIVATE QuicClientSession : public QuicSession { virtual QuicCryptoClientStream* GetCryptoStream() OVERRIDE; virtual void CloseStream(QuicStreamId stream_id) OVERRIDE; virtual void OnCryptoHandshakeEvent(CryptoHandshakeEvent event) OVERRIDE; - virtual void OnCryptoHandshakeMessageSent( - const CryptoHandshakeMessage& message) OVERRIDE; - virtual void OnCryptoHandshakeMessageReceived( - const CryptoHandshakeMessage& message) OVERRIDE; virtual bool GetSSLInfo(SSLInfo* ssl_info) OVERRIDE; // QuicConnectionVisitorInterface methods: diff --git a/chromium/net/quic/quic_client_session_test.cc b/chromium/net/quic/quic_client_session_test.cc index 09e7d210116..6113f4587c1 100644 --- a/chromium/net/quic/quic_client_session_test.cc +++ b/chromium/net/quic/quic_client_session_test.cc @@ -15,7 +15,6 @@ #include "net/quic/test_tools/crypto_test_utils.h" #include "net/quic/test_tools/quic_client_session_peer.h" #include "net/quic/test_tools/quic_test_utils.h" -#include "net/udp/datagram_client_socket.h" using testing::_; @@ -30,9 +29,8 @@ class QuicClientSessionTest : public ::testing::Test { QuicClientSessionTest() : guid_(1), connection_(new PacketSavingConnection(guid_, IPEndPoint(), false)), - session_(connection_, scoped_ptr<DatagramClientSocket>(), NULL, - NULL, kServerHostname, DefaultQuicConfig(), &crypto_config_, - &net_log_) { + session_(connection_, NULL, NULL, NULL, kServerHostname, + DefaultQuicConfig(), &crypto_config_, &net_log_) { session_.config()->SetDefaults(); crypto_config_.SetDefaults(); } diff --git a/chromium/net/quic/quic_connection.cc b/chromium/net/quic/quic_connection.cc index 718b78864c9..fefeba95f2d 100644 --- a/chromium/net/quic/quic_connection.cc +++ b/chromium/net/quic/quic_connection.cc @@ -1035,10 +1035,6 @@ void QuicConnection::RetransmitPacket( unacked)); retransmission_map_.insert(make_pair(serialized_packet.sequence_number, retransmission_info)); - if (debug_visitor_) { - debug_visitor_->OnPacketRetransmitted(sequence_number, - serialized_packet.sequence_number); - } SendOrQueuePacket(unacked->encryption_level(), serialized_packet.sequence_number, serialized_packet.packet, diff --git a/chromium/net/quic/quic_connection.h b/chromium/net/quic/quic_connection.h index 20878d91bc7..41172f7d46d 100644 --- a/chromium/net/quic/quic_connection.h +++ b/chromium/net/quic/quic_connection.h @@ -95,12 +95,6 @@ class NET_EXPORT_PRIVATE QuicConnectionDebugVisitorInterface const QuicEncryptedPacket& packet, int rv) = 0; - // Called when the contents of a packet have been retransmitted as - // a new packet. - virtual void OnPacketRetransmitted( - QuicPacketSequenceNumber old_sequence_number, - QuicPacketSequenceNumber new_sequence_number) = 0; - // Called when a packet has been received, but before it is // validated or parsed. virtual void OnPacketReceived(const IPEndPoint& self_address, diff --git a/chromium/net/quic/quic_connection_logger.cc b/chromium/net/quic/quic_connection_logger.cc index b5dfcd61028..3405cd0c764 100644 --- a/chromium/net/quic/quic_connection_logger.cc +++ b/chromium/net/quic/quic_connection_logger.cc @@ -10,7 +10,6 @@ #include "base/strings/string_number_conversions.h" #include "base/values.h" #include "net/base/net_log.h" -#include "net/quic/crypto/crypto_handshake.h" namespace net { @@ -44,18 +43,6 @@ base::Value* NetLogQuicPacketSentCallback( return dict; } -base::Value* NetLogQuicPacketRetransmittedCallback( - QuicPacketSequenceNumber old_sequence_number, - QuicPacketSequenceNumber new_sequence_number, - NetLog::LogLevel /* log_level */) { - base::DictionaryValue* dict = new base::DictionaryValue(); - dict->SetString("old_packet_sequence_number", - base::Uint64ToString(old_sequence_number)); - dict->SetString("new_packet_sequence_number", - base::Uint64ToString(new_sequence_number)); - return dict; -} - base::Value* NetLogQuicPacketHeaderCallback(const QuicPacketHeader* header, NetLog::LogLevel /* log_level */) { base::DictionaryValue* dict = new base::DictionaryValue(); @@ -99,7 +86,7 @@ base::Value* NetLogQuicAckFrameCallback(const QuicAckFrame* frame, frame->received_info.missing_packets; for (SequenceNumberSet::const_iterator it = missing_packets.begin(); it != missing_packets.end(); ++it) { - missing->AppendString(base::Uint64ToString(*it)); + missing->Append(new base::StringValue(base::Uint64ToString(*it))); } return dict; } @@ -120,7 +107,7 @@ base::Value* NetLogQuicCongestionFeedbackFrameCallback( it != frame->inter_arrival.received_packet_times.end(); ++it) { std::string value = base::Uint64ToString(it->first) + "@" + base::Uint64ToString(it->second.ToDebuggingValue()); - received->AppendString(value); + received->Append(new base::StringValue(value)); } break; } @@ -159,37 +146,6 @@ base::Value* NetLogQuicConnectionCloseFrameCallback( return dict; } -base::Value* NetLogQuicVersionNegotiationPacketCallback( - const QuicVersionNegotiationPacket* packet, - NetLog::LogLevel /* log_level */) { - base::DictionaryValue* dict = new base::DictionaryValue(); - base::ListValue* versions = new base::ListValue(); - dict->Set("versions", versions); - for (QuicVersionVector::const_iterator it = packet->versions.begin(); - it != packet->versions.end(); ++it) { - versions->AppendString(QuicVersionToString(*it)); - } - return dict; -} - -base::Value* NetLogQuicCryptoHandshakeMessageCallback( - const CryptoHandshakeMessage* message, - NetLog::LogLevel /* log_level */) { - base::DictionaryValue* dict = new base::DictionaryValue(); - dict->SetString("quic_crypto_handshake_message", message->DebugString()); - return dict; -} - -base::Value* NetLogQuicConnectionClosedCallback( - QuicErrorCode error, - bool from_peer, - NetLog::LogLevel /* log_level */) { - base::DictionaryValue* dict = new base::DictionaryValue(); - dict->SetInteger("quic_error", error); - dict->SetBoolean("from_peer", from_peer); - return dict; -} - void UpdatePacketGapSentHistogram(size_t num_consecutive_missing_packets) { UMA_HISTOGRAM_COUNTS("Net.QuicSession.PacketGapSent", num_consecutive_missing_packets); @@ -260,15 +216,6 @@ void QuicConnectionLogger::OnPacketSent( packet.length(), rv)); } -void QuicConnectionLogger:: OnPacketRetransmitted( - QuicPacketSequenceNumber old_sequence_number, - QuicPacketSequenceNumber new_sequence_number) { - net_log_.AddEvent( - NetLog::TYPE_QUIC_SESSION_PACKET_RETRANSMITTED, - base::Bind(&NetLogQuicPacketRetransmittedCallback, - old_sequence_number, new_sequence_number)); -} - void QuicConnectionLogger::OnPacketReceived(const IPEndPoint& self_address, const IPEndPoint& peer_address, const QuicEncryptedPacket& packet) { @@ -374,43 +321,15 @@ void QuicConnectionLogger::OnConnectionCloseFrame( void QuicConnectionLogger::OnPublicResetPacket( const QuicPublicResetPacket& packet) { - net_log_.AddEvent(NetLog::TYPE_QUIC_SESSION_PUBLIC_RESET_PACKET_RECEIVED); } void QuicConnectionLogger::OnVersionNegotiationPacket( const QuicVersionNegotiationPacket& packet) { - net_log_.AddEvent( - NetLog::TYPE_QUIC_SESSION_VERSION_NEGOTIATION_PACKET_RECEIVED, - base::Bind(&NetLogQuicVersionNegotiationPacketCallback, &packet)); } void QuicConnectionLogger::OnRevivedPacket( const QuicPacketHeader& revived_header, base::StringPiece payload) { - net_log_.AddEvent( - NetLog::TYPE_QUIC_SESSION_PACKET_HEADER_REVIVED, - base::Bind(&NetLogQuicPacketHeaderCallback, &revived_header)); -} - -void QuicConnectionLogger::OnCryptoHandshakeMessageReceived( - const CryptoHandshakeMessage& message) { - net_log_.AddEvent( - NetLog::TYPE_QUIC_SESSION_CRYPTO_HANDSHAKE_MESSAGE_RECEIVED, - base::Bind(&NetLogQuicCryptoHandshakeMessageCallback, &message)); -} - -void QuicConnectionLogger::OnCryptoHandshakeMessageSent( - const CryptoHandshakeMessage& message) { - net_log_.AddEvent( - NetLog::TYPE_QUIC_SESSION_CRYPTO_HANDSHAKE_MESSAGE_SENT, - base::Bind(&NetLogQuicCryptoHandshakeMessageCallback, &message)); -} - -void QuicConnectionLogger::OnConnectionClose(QuicErrorCode error, - bool from_peer) { - net_log_.AddEvent( - NetLog::TYPE_QUIC_SESSION_CLOSED, - base::Bind(&NetLogQuicConnectionClosedCallback, error, from_peer)); } } // namespace net diff --git a/chromium/net/quic/quic_connection_logger.h b/chromium/net/quic/quic_connection_logger.h index f9080d643e3..1d2bd2df96d 100644 --- a/chromium/net/quic/quic_connection_logger.h +++ b/chromium/net/quic/quic_connection_logger.h @@ -10,7 +10,6 @@ namespace net { class BoundNetLog; -class CryptoHandshakeMessage; // This class is a debug visitor of a QuicConnection which logs // events to |net_log|. @@ -29,9 +28,7 @@ class NET_EXPORT_PRIVATE QuicConnectionLogger EncryptionLevel level, const QuicEncryptedPacket& packet, int rv) OVERRIDE; - virtual void OnPacketRetransmitted( - QuicPacketSequenceNumber old_sequence_number, - QuicPacketSequenceNumber new_sequence_number) OVERRIDE; + virtual void OnPacketReceived(const IPEndPoint& self_address, const IPEndPoint& peer_address, const QuicEncryptedPacket& packet) OVERRIDE; @@ -51,12 +48,6 @@ class NET_EXPORT_PRIVATE QuicConnectionLogger virtual void OnRevivedPacket(const QuicPacketHeader& revived_header, base::StringPiece payload) OVERRIDE; - void OnCryptoHandshakeMessageReceived( - const CryptoHandshakeMessage& message); - void OnCryptoHandshakeMessageSent( - const CryptoHandshakeMessage& message); - void OnConnectionClose(QuicErrorCode error, bool from_peer); - private: BoundNetLog net_log_; // The last packet sequence number received. diff --git a/chromium/net/quic/quic_crypto_client_stream.cc b/chromium/net/quic/quic_crypto_client_stream.cc index 585b293560b..ab1d974b32b 100644 --- a/chromium/net/quic/quic_crypto_client_stream.cc +++ b/chromium/net/quic/quic_crypto_client_stream.cc @@ -85,8 +85,6 @@ QuicCryptoClientStream::~QuicCryptoClientStream() { void QuicCryptoClientStream::OnHandshakeMessage( const CryptoHandshakeMessage& message) { - QuicCryptoStream::OnHandshakeMessage(message); - DoHandshakeLoop(&message); } diff --git a/chromium/net/quic/quic_crypto_server_stream.cc b/chromium/net/quic/quic_crypto_server_stream.cc index a23a34d5b49..f7b67b7c23e 100644 --- a/chromium/net/quic/quic_crypto_server_stream.cc +++ b/chromium/net/quic/quic_crypto_server_stream.cc @@ -27,8 +27,6 @@ QuicCryptoServerStream::~QuicCryptoServerStream() { void QuicCryptoServerStream::OnHandshakeMessage( const CryptoHandshakeMessage& message) { - QuicCryptoStream::OnHandshakeMessage(message); - // Do not process handshake messages after the handshake is confirmed. if (handshake_confirmed_) { CloseConnection(QUIC_CRYPTO_MESSAGE_AFTER_HANDSHAKE_COMPLETE); diff --git a/chromium/net/quic/quic_crypto_stream.cc b/chromium/net/quic/quic_crypto_stream.cc index 569648f1baa..2f06e3ba234 100644 --- a/chromium/net/quic/quic_crypto_stream.cc +++ b/chromium/net/quic/quic_crypto_stream.cc @@ -27,11 +27,6 @@ void QuicCryptoStream::OnError(CryptoFramer* framer) { session()->ConnectionClose(framer->error(), false); } -void QuicCryptoStream::OnHandshakeMessage( - const CryptoHandshakeMessage& message) { - session()->OnCryptoHandshakeMessageReceived(message); -} - uint32 QuicCryptoStream::ProcessData(const char* data, uint32 data_len) { // Do not process handshake messages after the handshake is confirmed. @@ -57,7 +52,6 @@ void QuicCryptoStream::CloseConnectionWithDetails(QuicErrorCode error, void QuicCryptoStream::SendHandshakeMessage( const CryptoHandshakeMessage& message) { - session()->OnCryptoHandshakeMessageSent(message); const QuicData& data = message.GetSerialized(); // TODO(wtc): check the return value. WriteData(string(data.data(), data.length()), false); diff --git a/chromium/net/quic/quic_crypto_stream.h b/chromium/net/quic/quic_crypto_stream.h index c402b0d9b44..bdae59e31f5 100644 --- a/chromium/net/quic/quic_crypto_stream.h +++ b/chromium/net/quic/quic_crypto_stream.h @@ -34,8 +34,7 @@ class NET_EXPORT_PRIVATE QuicCryptoStream // CryptoFramerVisitorInterface implementation virtual void OnError(CryptoFramer* framer) OVERRIDE; - virtual void OnHandshakeMessage( - const CryptoHandshakeMessage& message) OVERRIDE; + virtual void OnHandshakeMessage(const CryptoHandshakeMessage& message) = 0; // ReliableQuicStream implementation virtual uint32 ProcessData(const char* data, uint32 data_len) OVERRIDE; diff --git a/chromium/net/quic/quic_http_stream.cc b/chromium/net/quic/quic_http_stream.cc index 73581248d5b..94d1a2e56ba 100644 --- a/chromium/net/quic/quic_http_stream.cc +++ b/chromium/net/quic/quic_http_stream.cc @@ -257,10 +257,6 @@ void QuicHttpStream::Drain(HttpNetworkSession* session) { delete this; } -void QuicHttpStream::SetPriority(RequestPriority priority) { - // Nothing to do here (yet). -} - int QuicHttpStream::OnSendData() { // TODO(rch): Change QUIC IO to provide notifications to the streams. NOTREACHED(); diff --git a/chromium/net/quic/quic_http_stream.h b/chromium/net/quic/quic_http_stream.h index cc2b973e87f..85dc5537480 100644 --- a/chromium/net/quic/quic_http_stream.h +++ b/chromium/net/quic/quic_http_stream.h @@ -54,7 +54,6 @@ class NET_EXPORT_PRIVATE QuicHttpStream : SSLCertRequestInfo* cert_request_info) OVERRIDE; virtual bool IsSpdyHttpStream() const OVERRIDE; virtual void Drain(HttpNetworkSession* session) OVERRIDE; - virtual void SetPriority(RequestPriority priority) OVERRIDE; // QuicReliableClientStream::Delegate implementation virtual int OnSendData() OVERRIDE; diff --git a/chromium/net/quic/quic_http_stream_test.cc b/chromium/net/quic/quic_http_stream_test.cc index 1e4ac916bbf..b3784168a70 100644 --- a/chromium/net/quic/quic_http_stream_test.cc +++ b/chromium/net/quic/quic_http_stream_test.cc @@ -179,12 +179,10 @@ class QuicHttpStreamTest : public ::testing::TestWithParam<bool> { connection_->SetSendAlgorithm(send_algorithm_); connection_->SetReceiveAlgorithm(receive_algorithm_); crypto_config_.SetDefaults(); - session_.reset( - new QuicClientSession(connection_, - scoped_ptr<DatagramClientSocket>(socket), NULL, - &crypto_client_stream_factory_, - "www.google.com", DefaultQuicConfig(), - &crypto_config_, NULL)); + session_.reset(new QuicClientSession(connection_, socket, NULL, + &crypto_client_stream_factory_, + "www.google.com", DefaultQuicConfig(), + &crypto_config_, NULL)); session_->GetCryptoStream()->CryptoConnect(); EXPECT_TRUE(session_->IsCryptoHandshakeConfirmed()); stream_.reset(use_closing_stream_ ? diff --git a/chromium/net/quic/quic_session.cc b/chromium/net/quic/quic_session.cc index 5abf30593ed..a07f413cbd2 100644 --- a/chromium/net/quic/quic_session.cc +++ b/chromium/net/quic/quic_session.cc @@ -283,14 +283,6 @@ void QuicSession::OnCryptoHandshakeEvent(CryptoHandshakeEvent event) { } } -void QuicSession::OnCryptoHandshakeMessageSent( - const CryptoHandshakeMessage& message) { -} - -void QuicSession::OnCryptoHandshakeMessageReceived( - const CryptoHandshakeMessage& message) { -} - QuicConfig* QuicSession::config() { return &config_; } diff --git a/chromium/net/quic/quic_session.h b/chromium/net/quic/quic_session.h index 24a6deb45d1..9f7aceb7581 100644 --- a/chromium/net/quic/quic_session.h +++ b/chromium/net/quic/quic_session.h @@ -106,14 +106,6 @@ class NET_EXPORT_PRIVATE QuicSession : public QuicConnectionVisitorInterface { // Servers will simply call it once with HANDSHAKE_CONFIRMED. virtual void OnCryptoHandshakeEvent(CryptoHandshakeEvent event); - // Called by the QuicCryptoStream when a handshake message is sent. - virtual void OnCryptoHandshakeMessageSent( - const CryptoHandshakeMessage& message); - - // Called by the QuicCryptoStream when a handshake message is received. - virtual void OnCryptoHandshakeMessageReceived( - const CryptoHandshakeMessage& message); - // Returns mutable config for this session. Returned config is owned // by QuicSession. QuicConfig* config(); diff --git a/chromium/net/quic/quic_stream_factory.cc b/chromium/net/quic/quic_stream_factory.cc index 86bd8a18aaa..fba7f0b7dec 100644 --- a/chromium/net/quic/quic_stream_factory.cc +++ b/chromium/net/quic/quic_stream_factory.cc @@ -408,10 +408,10 @@ QuicClientSession* QuicStreamFactory::CreateSession( const BoundNetLog& net_log) { QuicGuid guid = random_generator_->RandUint64(); IPEndPoint addr = *address_list.begin(); - scoped_ptr<DatagramClientSocket> socket( + DatagramClientSocket* socket = client_socket_factory_->CreateDatagramClientSocket( DatagramSocket::DEFAULT_BIND, base::Bind(&base::RandInt), - net_log.net_log(), net_log.source())); + net_log.net_log(), net_log.source()); socket->Connect(addr); // We should adaptively set this buffer size, but for now, we'll use a size @@ -437,7 +437,7 @@ QuicClientSession* QuicStreamFactory::CreateSession( base::MessageLoop::current()->message_loop_proxy().get(), clock_.get(), random_generator_, - socket.get()); + socket); QuicConnection* connection = new QuicConnection(guid, addr, helper, false, QuicVersionMax()); @@ -447,7 +447,7 @@ QuicClientSession* QuicStreamFactory::CreateSession( DCHECK(crypto_config); QuicClientSession* session = - new QuicClientSession(connection, socket.Pass(), this, + new QuicClientSession(connection, socket, this, quic_crypto_client_stream_factory_, host_port_proxy_pair.first.host(), config_, crypto_config, net_log.net_log()); diff --git a/chromium/net/socket/buffered_write_stream_socket.cc b/chromium/net/socket/buffered_write_stream_socket.cc index cf13c5e439a..36b9df715fd 100644 --- a/chromium/net/socket/buffered_write_stream_socket.cc +++ b/chromium/net/socket/buffered_write_stream_socket.cc @@ -23,8 +23,8 @@ void AppendBuffer(GrowableIOBuffer* dst, IOBuffer* src, int src_len) { } // anonymous namespace BufferedWriteStreamSocket::BufferedWriteStreamSocket( - scoped_ptr<StreamSocket> socket_to_wrap) - : wrapped_socket_(socket_to_wrap.Pass()), + StreamSocket* socket_to_wrap) + : wrapped_socket_(socket_to_wrap), io_buffer_(new GrowableIOBuffer()), backup_buffer_(new GrowableIOBuffer()), weak_factory_(this), diff --git a/chromium/net/socket/buffered_write_stream_socket.h b/chromium/net/socket/buffered_write_stream_socket.h index aad5736d0b0..fcb33a81910 100644 --- a/chromium/net/socket/buffered_write_stream_socket.h +++ b/chromium/net/socket/buffered_write_stream_socket.h @@ -5,8 +5,6 @@ #ifndef NET_SOCKET_BUFFERED_WRITE_STREAM_SOCKET_H_ #define NET_SOCKET_BUFFERED_WRITE_STREAM_SOCKET_H_ -#include "base/basictypes.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "net/base/net_log.h" #include "net/socket/stream_socket.h" @@ -35,7 +33,7 @@ class IPEndPoint; // There are no bounds on the local buffer size. Use carefully. class NET_EXPORT_PRIVATE BufferedWriteStreamSocket : public StreamSocket { public: - explicit BufferedWriteStreamSocket(scoped_ptr<StreamSocket> socket_to_wrap); + BufferedWriteStreamSocket(StreamSocket* socket_to_wrap); virtual ~BufferedWriteStreamSocket(); // Socket interface @@ -73,8 +71,6 @@ class NET_EXPORT_PRIVATE BufferedWriteStreamSocket : public StreamSocket { bool callback_pending_; bool wrapped_write_in_progress_; int error_; - - DISALLOW_COPY_AND_ASSIGN(BufferedWriteStreamSocket); }; } // namespace net diff --git a/chromium/net/socket/buffered_write_stream_socket_unittest.cc b/chromium/net/socket/buffered_write_stream_socket_unittest.cc index 485295f33f6..e579a7f51d2 100644 --- a/chromium/net/socket/buffered_write_stream_socket_unittest.cc +++ b/chromium/net/socket/buffered_write_stream_socket_unittest.cc @@ -30,11 +30,10 @@ class BufferedWriteStreamSocketTest : public testing::Test { if (writes_count) { data_->StopAfter(writes_count); } - scoped_ptr<DeterministicMockTCPClientSocket> wrapped_socket( - new DeterministicMockTCPClientSocket(net_log_.net_log(), data_.get())); + DeterministicMockTCPClientSocket* wrapped_socket = + new DeterministicMockTCPClientSocket(net_log_.net_log(), data_.get()); data_->set_delegate(wrapped_socket->AsWeakPtr()); - socket_.reset(new BufferedWriteStreamSocket( - wrapped_socket.PassAs<StreamSocket>())); + socket_.reset(new BufferedWriteStreamSocket(wrapped_socket)); socket_->Connect(callback_.callback()); } diff --git a/chromium/net/socket/client_socket_factory.cc b/chromium/net/socket/client_socket_factory.cc index a86688e3333..022988aa6a9 100644 --- a/chromium/net/socket/client_socket_factory.cc +++ b/chromium/net/socket/client_socket_factory.cc @@ -67,25 +67,23 @@ class DefaultClientSocketFactory : public ClientSocketFactory, ClearSSLSessionCache(); } - virtual scoped_ptr<DatagramClientSocket> CreateDatagramClientSocket( + virtual DatagramClientSocket* CreateDatagramClientSocket( DatagramSocket::BindType bind_type, const RandIntCallback& rand_int_cb, NetLog* net_log, const NetLog::Source& source) OVERRIDE { - return scoped_ptr<DatagramClientSocket>( - new UDPClientSocket(bind_type, rand_int_cb, net_log, source)); + return new UDPClientSocket(bind_type, rand_int_cb, net_log, source); } - virtual scoped_ptr<StreamSocket> CreateTransportClientSocket( + virtual StreamSocket* CreateTransportClientSocket( const AddressList& addresses, NetLog* net_log, const NetLog::Source& source) OVERRIDE { - return scoped_ptr<StreamSocket>( - new TCPClientSocket(addresses, net_log, source)); + return new TCPClientSocket(addresses, net_log, source); } - virtual scoped_ptr<SSLClientSocket> CreateSSLClientSocket( - scoped_ptr<ClientSocketHandle> transport_socket, + virtual SSLClientSocket* CreateSSLClientSocket( + ClientSocketHandle* transport_socket, const HostPortPair& host_and_port, const SSLConfig& ssl_config, const SSLClientSocketContext& context) OVERRIDE { @@ -104,19 +102,17 @@ class DefaultClientSocketFactory : public ClientSocketFactory, nss_task_runner = base::ThreadTaskRunnerHandle::Get(); #if defined(USE_OPENSSL) - return scoped_ptr<SSLClientSocket>( - new SSLClientSocketOpenSSL(transport_socket.Pass(), host_and_port, - ssl_config, context)); + return new SSLClientSocketOpenSSL(transport_socket, host_and_port, + ssl_config, context); #elif defined(USE_NSS) || defined(OS_MACOSX) || defined(OS_WIN) - return scoped_ptr<SSLClientSocket>( - new SSLClientSocketNSS(nss_task_runner.get(), - transport_socket.Pass(), - host_and_port, - ssl_config, - context)); + return new SSLClientSocketNSS(nss_task_runner.get(), + transport_socket, + host_and_port, + ssl_config, + context); #else NOTIMPLEMENTED(); - return scoped_ptr<SSLClientSocket>(); + return NULL; #endif } @@ -134,6 +130,18 @@ static base::LazyInstance<DefaultClientSocketFactory>::Leaky } // namespace +// Deprecated function (http://crbug.com/37810) that takes a StreamSocket. +SSLClientSocket* ClientSocketFactory::CreateSSLClientSocket( + StreamSocket* transport_socket, + const HostPortPair& host_and_port, + const SSLConfig& ssl_config, + const SSLClientSocketContext& context) { + ClientSocketHandle* socket_handle = new ClientSocketHandle(); + socket_handle->set_socket(transport_socket); + return CreateSSLClientSocket(socket_handle, host_and_port, ssl_config, + context); +} + // static ClientSocketFactory* ClientSocketFactory::GetDefaultFactory() { return g_default_client_socket_factory.Pointer(); diff --git a/chromium/net/socket/client_socket_factory.h b/chromium/net/socket/client_socket_factory.h index 6cb5949f0b3..65022f29234 100644 --- a/chromium/net/socket/client_socket_factory.h +++ b/chromium/net/socket/client_socket_factory.h @@ -8,7 +8,6 @@ #include <string> #include "base/basictypes.h" -#include "base/memory/scoped_ptr.h" #include "net/base/net_export.h" #include "net/base/net_log.h" #include "net/base/rand_callback.h" @@ -33,13 +32,13 @@ class NET_EXPORT ClientSocketFactory { // |source| is the NetLog::Source for the entity trying to create the socket, // if it has one. - virtual scoped_ptr<DatagramClientSocket> CreateDatagramClientSocket( + virtual DatagramClientSocket* CreateDatagramClientSocket( DatagramSocket::BindType bind_type, const RandIntCallback& rand_int_cb, NetLog* net_log, const NetLog::Source& source) = 0; - virtual scoped_ptr<StreamSocket> CreateTransportClientSocket( + virtual StreamSocket* CreateTransportClientSocket( const AddressList& addresses, NetLog* net_log, const NetLog::Source& source) = 0; @@ -47,12 +46,19 @@ class NET_EXPORT ClientSocketFactory { // It is allowed to pass in a |transport_socket| that is not obtained from a // socket pool. The caller could create a ClientSocketHandle directly and call // set_socket() on it to set a valid StreamSocket instance. - virtual scoped_ptr<SSLClientSocket> CreateSSLClientSocket( - scoped_ptr<ClientSocketHandle> transport_socket, + virtual SSLClientSocket* CreateSSLClientSocket( + ClientSocketHandle* transport_socket, const HostPortPair& host_and_port, const SSLConfig& ssl_config, const SSLClientSocketContext& context) = 0; + // Deprecated function (http://crbug.com/37810) that takes a StreamSocket. + virtual SSLClientSocket* CreateSSLClientSocket( + StreamSocket* transport_socket, + const HostPortPair& host_and_port, + const SSLConfig& ssl_config, + const SSLClientSocketContext& context); + // Clears cache used for SSL session resumption. virtual void ClearSSLSessionCache() = 0; diff --git a/chromium/net/socket/client_socket_handle.cc b/chromium/net/socket/client_socket_handle.cc index acb896b36f5..3894fa7aa0e 100644 --- a/chromium/net/socket/client_socket_handle.cc +++ b/chromium/net/socket/client_socket_handle.cc @@ -43,7 +43,7 @@ void ClientSocketHandle::ResetInternal(bool cancel) { if (pool_) // If we've still got a socket, release it back to the ClientSocketPool so // it can be deleted or reused. - pool_->ReleaseSocket(group_name_, PassSocket(), pool_id_); + pool_->ReleaseSocket(group_name_, release_socket(), pool_id_); } else if (cancel) { // If we did not get initialized yet, we've got a socket request pending. // Cancel it. @@ -121,10 +121,6 @@ bool ClientSocketHandle::GetLoadTimingInfo( return true; } -void ClientSocketHandle::SetSocket(scoped_ptr<StreamSocket> s) { - socket_ = s.Pass(); -} - void ClientSocketHandle::OnIOComplete(int result) { CompletionCallback callback = user_callback_; user_callback_.Reset(); @@ -132,10 +128,6 @@ void ClientSocketHandle::OnIOComplete(int result) { callback.Run(result); } -scoped_ptr<StreamSocket> ClientSocketHandle::PassSocket() { - return socket_.Pass(); -} - void ClientSocketHandle::HandleInitCompletion(int result) { CHECK_NE(ERR_IO_PENDING, result); ClientSocketPoolHistograms* histograms = pool_->histograms(); diff --git a/chromium/net/socket/client_socket_handle.h b/chromium/net/socket/client_socket_handle.h index 9651f089a86..7d5588a145b 100644 --- a/chromium/net/socket/client_socket_handle.h +++ b/chromium/net/socket/client_socket_handle.h @@ -116,8 +116,8 @@ class NET_EXPORT ClientSocketHandle { LoadTimingInfo* load_timing_info) const; // Used by ClientSocketPool to initialize the ClientSocketHandle. - void SetSocket(scoped_ptr<StreamSocket> s); void set_is_reused(bool is_reused) { is_reused_ = is_reused; } + void set_socket(StreamSocket* s) { socket_.reset(s); } void set_idle_time(base::TimeDelta idle_time) { idle_time_ = idle_time; } void set_pool_id(int id) { pool_id_ = id; } void set_is_ssl_error(bool is_ssl_error) { is_ssl_error_ = is_ssl_error; } @@ -144,10 +144,10 @@ class NET_EXPORT ClientSocketHandle { } // These may only be used if is_initialized() is true. - scoped_ptr<StreamSocket> PassSocket(); - StreamSocket* socket() { return socket_.get(); } const std::string& group_name() const { return group_name_; } int id() const { return pool_id_; } + StreamSocket* socket() { return socket_.get(); } + StreamSocket* release_socket() { return socket_.release(); } bool is_reused() const { return is_reused_; } base::TimeDelta idle_time() const { return idle_time_; } SocketReuseType reuse_type() const { diff --git a/chromium/net/socket/client_socket_pool.h b/chromium/net/socket/client_socket_pool.h index af184547d6e..7cb9a7ebc2e 100644 --- a/chromium/net/socket/client_socket_pool.h +++ b/chromium/net/socket/client_socket_pool.h @@ -10,7 +10,6 @@ #include "base/basictypes.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/template_util.h" #include "base/time/time.h" #include "net/base/completion_callback.h" @@ -112,7 +111,7 @@ class NET_EXPORT ClientSocketPool { // change when it flushes, so it can use this |id| to discard sockets with // mismatched ids. virtual void ReleaseSocket(const std::string& group_name, - scoped_ptr<StreamSocket> socket, + StreamSocket* socket, int id) = 0; // This flushes all state from the ClientSocketPool. This means that all diff --git a/chromium/net/socket/client_socket_pool_base.cc b/chromium/net/socket/client_socket_pool_base.cc index b1ddd40881c..3332e04a171 100644 --- a/chromium/net/socket/client_socket_pool_base.cc +++ b/chromium/net/socket/client_socket_pool_base.cc @@ -82,10 +82,6 @@ ConnectJob::~ConnectJob() { net_log().EndEvent(NetLog::TYPE_SOCKET_POOL_CONNECT_JOB); } -scoped_ptr<StreamSocket> ConnectJob::PassSocket() { - return socket_.Pass(); -} - int ConnectJob::Connect() { if (timeout_duration_ != base::TimeDelta()) timer_.Start(FROM_HERE, timeout_duration_, this, &ConnectJob::OnTimeout); @@ -104,16 +100,16 @@ int ConnectJob::Connect() { return rv; } -void ConnectJob::SetSocket(scoped_ptr<StreamSocket> socket) { +void ConnectJob::set_socket(StreamSocket* socket) { if (socket) { net_log().AddEvent(NetLog::TYPE_CONNECT_JOB_SET_SOCKET, socket->NetLog().source().ToEventParametersCallback()); } - socket_ = socket.Pass(); + socket_.reset(socket); } void ConnectJob::NotifyDelegateOfCompletion(int rv) { - // The delegate will own |this|. + // The delegate will delete |this|. Delegate* delegate = delegate_; delegate_ = NULL; @@ -139,7 +135,7 @@ void ConnectJob::LogConnectCompletion(int net_error) { void ConnectJob::OnTimeout() { // Make sure the socket is NULL before calling into |delegate|. - SetSocket(scoped_ptr<StreamSocket>()); + set_socket(NULL); net_log_.AddEvent(NetLog::TYPE_SOCKET_POOL_CONNECT_JOB_TIMED_OUT); @@ -396,11 +392,11 @@ int ClientSocketPoolBaseHelper::RequestSocketInternal( if (rv == OK) { LogBoundConnectJobToRequest(connect_job->net_log().source(), request); if (!preconnecting) { - HandOutSocket(connect_job->PassSocket(), false /* not reused */, + HandOutSocket(connect_job->ReleaseSocket(), false /* not reused */, connect_job->connect_timing(), handle, base::TimeDelta(), group, request->net_log()); } else { - AddIdleSocket(connect_job->PassSocket(), group); + AddIdleSocket(connect_job->ReleaseSocket(), group); } } else if (rv == ERR_IO_PENDING) { // If we don't have any sockets in this group, set a timer for potentially @@ -413,17 +409,17 @@ int ClientSocketPoolBaseHelper::RequestSocketInternal( connecting_socket_count_++; - group->AddJob(connect_job.Pass(), preconnecting); + group->AddJob(connect_job.release(), preconnecting); } else { LogBoundConnectJobToRequest(connect_job->net_log().source(), request); - scoped_ptr<StreamSocket> error_socket; + StreamSocket* error_socket = NULL; if (!preconnecting) { DCHECK(handle); connect_job->GetAdditionalErrorState(handle); - error_socket = connect_job->PassSocket(); + error_socket = connect_job->ReleaseSocket(); } if (error_socket) { - HandOutSocket(error_socket.Pass(), false /* not reused */, + HandOutSocket(error_socket, false /* not reused */, connect_job->connect_timing(), handle, base::TimeDelta(), group, request->net_log()); } else if (group->IsEmpty()) { @@ -473,7 +469,7 @@ bool ClientSocketPoolBaseHelper::AssignIdleSocketToRequest( IdleSocket idle_socket = *idle_socket_it; idle_sockets->erase(idle_socket_it); HandOutSocket( - scoped_ptr<StreamSocket>(idle_socket.socket), + idle_socket.socket, idle_socket.socket->WasEverUsed(), LoadTimingInfo::ConnectTiming(), request->handle(), @@ -499,11 +495,11 @@ void ClientSocketPoolBaseHelper::CancelRequest( if (callback_it != pending_callback_map_.end()) { int result = callback_it->second.result; pending_callback_map_.erase(callback_it); - scoped_ptr<StreamSocket> socket = handle->PassSocket(); + StreamSocket* socket = handle->release_socket(); if (socket) { if (result != OK) socket->Disconnect(); - ReleaseSocket(handle->group_name(), socket.Pass(), handle->id()); + ReleaseSocket(handle->group_name(), socket, handle->id()); } return; } @@ -760,7 +756,7 @@ void ClientSocketPoolBaseHelper::StartIdleSocketTimer() { } void ClientSocketPoolBaseHelper::ReleaseSocket(const std::string& group_name, - scoped_ptr<StreamSocket> socket, + StreamSocket* socket, int id) { GroupMap::iterator i = group_map_.find(group_name); CHECK(i != group_map_.end()); @@ -777,10 +773,10 @@ void ClientSocketPoolBaseHelper::ReleaseSocket(const std::string& group_name, id == pool_generation_number_; if (can_reuse) { // Add it to the idle list. - AddIdleSocket(socket.Pass(), group); + AddIdleSocket(socket, group); OnAvailableSocketSlot(group_name, group); } else { - socket.reset(); + delete socket; } CheckForStalledSocketGroups(); @@ -858,16 +854,13 @@ void ClientSocketPoolBaseHelper::OnConnectJobComplete( CHECK(group_it != group_map_.end()); Group* group = group_it->second; - scoped_ptr<StreamSocket> socket = job->PassSocket(); + scoped_ptr<StreamSocket> socket(job->ReleaseSocket()); // Copies of these are needed because |job| may be deleted before they are // accessed. BoundNetLog job_log = job->net_log(); LoadTimingInfo::ConnectTiming connect_timing = job->connect_timing(); - // RemoveConnectJob(job, _) must be called by all branches below; - // otherwise, |job| will be leaked. - if (result == OK) { DCHECK(socket.get()); RemoveConnectJob(job, group); @@ -876,12 +869,12 @@ void ClientSocketPoolBaseHelper::OnConnectJobComplete( group->mutable_pending_requests()->begin(), group)); LogBoundConnectJobToRequest(job_log.source(), r.get()); HandOutSocket( - socket.Pass(), false /* unused socket */, connect_timing, + socket.release(), false /* unused socket */, connect_timing, r->handle(), base::TimeDelta(), group, r->net_log()); r->net_log().EndEvent(NetLog::TYPE_SOCKET_POOL); InvokeUserCallbackLater(r->handle(), r->callback(), result); } else { - AddIdleSocket(socket.Pass(), group); + AddIdleSocket(socket.release(), group); OnAvailableSocketSlot(group_name, group); CheckForStalledSocketGroups(); } @@ -897,7 +890,7 @@ void ClientSocketPoolBaseHelper::OnConnectJobComplete( RemoveConnectJob(job, group); if (socket.get()) { handed_out_socket = true; - HandOutSocket(socket.Pass(), false /* unused socket */, + HandOutSocket(socket.release(), false /* unused socket */, connect_timing, r->handle(), base::TimeDelta(), group, r->net_log()); } @@ -949,12 +942,16 @@ void ClientSocketPoolBaseHelper::RemoveConnectJob(ConnectJob* job, connecting_socket_count_--; DCHECK(group); + DCHECK(ContainsKey(group->jobs(), job)); group->RemoveJob(job); // If we've got no more jobs for this group, then we no longer need a // backup job either. if (group->jobs().empty()) group->CleanupBackupJob(); + + DCHECK(job); + delete job; } void ClientSocketPoolBaseHelper::OnAvailableSocketSlot( @@ -982,7 +979,7 @@ void ClientSocketPoolBaseHelper::ProcessPendingRequest( } void ClientSocketPoolBaseHelper::HandOutSocket( - scoped_ptr<StreamSocket> socket, + StreamSocket* socket, bool reused, const LoadTimingInfo::ConnectTiming& connect_timing, ClientSocketHandle* handle, @@ -990,7 +987,7 @@ void ClientSocketPoolBaseHelper::HandOutSocket( Group* group, const BoundNetLog& net_log) { DCHECK(socket); - handle->SetSocket(socket.Pass()); + handle->set_socket(socket); handle->set_is_reused(reused); handle->set_idle_time(idle_time); handle->set_pool_id(pool_generation_number_); @@ -1003,20 +1000,18 @@ void ClientSocketPoolBaseHelper::HandOutSocket( "idle_ms", static_cast<int>(idle_time.InMilliseconds()))); } - net_log.AddEvent( - NetLog::TYPE_SOCKET_POOL_BOUND_TO_SOCKET, - handle->socket()->NetLog().source().ToEventParametersCallback()); + net_log.AddEvent(NetLog::TYPE_SOCKET_POOL_BOUND_TO_SOCKET, + socket->NetLog().source().ToEventParametersCallback()); handed_out_socket_count_++; group->IncrementActiveSocketCount(); } void ClientSocketPoolBaseHelper::AddIdleSocket( - scoped_ptr<StreamSocket> socket, - Group* group) { + StreamSocket* socket, Group* group) { DCHECK(socket); IdleSocket idle_socket; - idle_socket.socket = socket.release(); + idle_socket.socket = socket; idle_socket.start_time = base::TimeTicks::Now(); group->mutable_idle_sockets()->push_back(idle_socket); @@ -1187,25 +1182,19 @@ bool ClientSocketPoolBaseHelper::Group::TryToUseUnassignedConnectJob() { return true; } -void ClientSocketPoolBaseHelper::Group::AddJob(scoped_ptr<ConnectJob> job, +void ClientSocketPoolBaseHelper::Group::AddJob(ConnectJob* job, bool is_preconnect) { SanityCheck(); if (is_preconnect) ++unassigned_job_count_; - jobs_.insert(job.release()); + jobs_.insert(job); } void ClientSocketPoolBaseHelper::Group::RemoveJob(ConnectJob* job) { - scoped_ptr<ConnectJob> owned_job(job); SanityCheck(); - std::set<ConnectJob*>::iterator it = jobs_.find(job); - if (it != jobs_.end()) { - jobs_.erase(it); - } else { - NOTREACHED(); - } + jobs_.erase(job); size_t job_count = jobs_.size(); if (job_count < unassigned_job_count_) unassigned_job_count_ = job_count; @@ -1233,17 +1222,15 @@ void ClientSocketPoolBaseHelper::Group::OnBackupSocketTimerFired( if (pending_requests_.empty()) return; - scoped_ptr<ConnectJob> backup_job = - pool->connect_job_factory_->NewConnectJob( - group_name, **pending_requests_.begin(), pool); + ConnectJob* backup_job = pool->connect_job_factory_->NewConnectJob( + group_name, **pending_requests_.begin(), pool); backup_job->net_log().AddEvent(NetLog::TYPE_SOCKET_BACKUP_CREATED); SIMPLE_STATS_COUNTER("socket.backup_created"); int rv = backup_job->Connect(); pool->connecting_socket_count_++; - ConnectJob* raw_backup_job = backup_job.get(); - AddJob(backup_job.Pass(), false); + AddJob(backup_job, false); if (rv != ERR_IO_PENDING) - pool->OnConnectJobComplete(rv, raw_backup_job); + pool->OnConnectJobComplete(rv, backup_job); } void ClientSocketPoolBaseHelper::Group::SanityCheck() { diff --git a/chromium/net/socket/client_socket_pool_base.h b/chromium/net/socket/client_socket_pool_base.h index eb642edd730..4bf95d7b04a 100644 --- a/chromium/net/socket/client_socket_pool_base.h +++ b/chromium/net/socket/client_socket_pool_base.h @@ -61,11 +61,8 @@ class NET_EXPORT_PRIVATE ConnectJob { Delegate() {} virtual ~Delegate() {} - // Alerts the delegate that the connection completed. |job| must - // be destroyed by the delegate. A scoped_ptr<> isn't used because - // the caller of this function doesn't own |job|. - virtual void OnConnectJobComplete(int result, - ConnectJob* job) = 0; + // Alerts the delegate that the connection completed. + virtual void OnConnectJobComplete(int result, ConnectJob* job) = 0; private: DISALLOW_COPY_AND_ASSIGN(Delegate); @@ -82,10 +79,9 @@ class NET_EXPORT_PRIVATE ConnectJob { const std::string& group_name() const { return group_name_; } const BoundNetLog& net_log() { return net_log_; } - // Releases ownership of the underlying socket to the caller. - // Returns the released socket, or NULL if there was a connection - // error. - scoped_ptr<StreamSocket> PassSocket(); + // Releases |socket_| to the client. On connection error, this should return + // NULL. + StreamSocket* ReleaseSocket() { return socket_.release(); } // Begins connecting the socket. Returns OK on success, ERR_IO_PENDING if it // cannot complete synchronously without blocking, or another net error code @@ -109,7 +105,7 @@ class NET_EXPORT_PRIVATE ConnectJob { const BoundNetLog& net_log() const { return net_log_; } protected: - void SetSocket(scoped_ptr<StreamSocket> socket); + void set_socket(StreamSocket* socket); StreamSocket* socket() { return socket_.get(); } void NotifyDelegateOfCompletion(int rv); void ResetTimer(base::TimeDelta remainingTime); @@ -192,7 +188,7 @@ class NET_EXPORT_PRIVATE ClientSocketPoolBaseHelper ConnectJobFactory() {} virtual ~ConnectJobFactory() {} - virtual scoped_ptr<ConnectJob> NewConnectJob( + virtual ConnectJob* NewConnectJob( const std::string& group_name, const Request& request, ConnectJob::Delegate* delegate) const = 0; @@ -233,7 +229,7 @@ class NET_EXPORT_PRIVATE ClientSocketPoolBaseHelper // See ClientSocketPool::ReleaseSocket for documentation on this function. void ReleaseSocket(const std::string& group_name, - scoped_ptr<StreamSocket> socket, + StreamSocket* socket, int id); // See ClientSocketPool::FlushWithError for documentation on this function. @@ -390,8 +386,7 @@ class NET_EXPORT_PRIVATE ClientSocketPoolBaseHelper // Otherwise, returns false. bool TryToUseUnassignedConnectJob(); - void AddJob(scoped_ptr<ConnectJob> job, bool is_preconnect); - // Remove |job| from this group, which must already own |job|. + void AddJob(ConnectJob* job, bool is_preconnect); void RemoveJob(ConnectJob* job); void RemoveAllJobs(); @@ -480,7 +475,7 @@ class NET_EXPORT_PRIVATE ClientSocketPoolBaseHelper CleanupIdleSockets(false); } - // Removes |job| from |group|, which must already own |job|. + // Removes |job| from |connect_job_set_|. Also updates |group| if non-NULL. void RemoveConnectJob(ConnectJob* job, Group* group); // Tries to see if we can handle any more requests for |group|. @@ -490,7 +485,7 @@ class NET_EXPORT_PRIVATE ClientSocketPoolBaseHelper void ProcessPendingRequest(const std::string& group_name, Group* group); // Assigns |socket| to |handle| and updates |group|'s counters appropriately. - void HandOutSocket(scoped_ptr<StreamSocket> socket, + void HandOutSocket(StreamSocket* socket, bool reused, const LoadTimingInfo::ConnectTiming& connect_timing, ClientSocketHandle* handle, @@ -499,7 +494,7 @@ class NET_EXPORT_PRIVATE ClientSocketPoolBaseHelper const BoundNetLog& net_log); // Adds |socket| to the list of idle sockets for |group|. - void AddIdleSocket(scoped_ptr<StreamSocket> socket, Group* group); + void AddIdleSocket(StreamSocket* socket, Group* group); // Iterates through |group_map_|, canceling all ConnectJobs and deleting // groups if they are no longer needed. @@ -629,7 +624,7 @@ class ClientSocketPoolBase { ConnectJobFactory() {} virtual ~ConnectJobFactory() {} - virtual scoped_ptr<ConnectJob> NewConnectJob( + virtual ConnectJob* NewConnectJob( const std::string& group_name, const Request& request, ConnectJob::Delegate* delegate) const = 0; @@ -707,10 +702,9 @@ class ClientSocketPoolBase { return helper_.CancelRequest(group_name, handle); } - void ReleaseSocket(const std::string& group_name, - scoped_ptr<StreamSocket> socket, + void ReleaseSocket(const std::string& group_name, StreamSocket* socket, int id) { - return helper_.ReleaseSocket(group_name, socket.Pass(), id); + return helper_.ReleaseSocket(group_name, socket, id); } void FlushWithError(int error) { helper_.FlushWithError(error); } @@ -791,13 +785,13 @@ class ClientSocketPoolBase { : connect_job_factory_(connect_job_factory) {} virtual ~ConnectJobFactoryAdaptor() {} - virtual scoped_ptr<ConnectJob> NewConnectJob( + virtual ConnectJob* NewConnectJob( const std::string& group_name, const internal::ClientSocketPoolBaseHelper::Request& request, - ConnectJob::Delegate* delegate) const OVERRIDE { - const Request& casted_request = static_cast<const Request&>(request); + ConnectJob::Delegate* delegate) const { + const Request* casted_request = static_cast<const Request*>(&request); return connect_job_factory_->NewConnectJob( - group_name, casted_request, delegate); + group_name, *casted_request, delegate); } virtual base::TimeDelta ConnectionTimeout() const { diff --git a/chromium/net/socket/client_socket_pool_base_unittest.cc b/chromium/net/socket/client_socket_pool_base_unittest.cc index 6688e01244d..5eeda972cff 100644 --- a/chromium/net/socket/client_socket_pool_base_unittest.cc +++ b/chromium/net/socket/client_socket_pool_base_unittest.cc @@ -30,9 +30,7 @@ #include "net/socket/client_socket_handle.h" #include "net/socket/client_socket_pool_histograms.h" #include "net/socket/socket_test_util.h" -#include "net/socket/ssl_client_socket.h" #include "net/socket/stream_socket.h" -#include "net/udp/datagram_client_socket.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -191,30 +189,30 @@ class MockClientSocketFactory : public ClientSocketFactory { public: MockClientSocketFactory() : allocation_count_(0) {} - virtual scoped_ptr<DatagramClientSocket> CreateDatagramClientSocket( + virtual DatagramClientSocket* CreateDatagramClientSocket( DatagramSocket::BindType bind_type, const RandIntCallback& rand_int_cb, NetLog* net_log, const NetLog::Source& source) OVERRIDE { NOTREACHED(); - return scoped_ptr<DatagramClientSocket>(); + return NULL; } - virtual scoped_ptr<StreamSocket> CreateTransportClientSocket( + virtual StreamSocket* CreateTransportClientSocket( const AddressList& addresses, NetLog* /* net_log */, const NetLog::Source& /*source*/) OVERRIDE { allocation_count_++; - return scoped_ptr<StreamSocket>(); + return NULL; } - virtual scoped_ptr<SSLClientSocket> CreateSSLClientSocket( - scoped_ptr<ClientSocketHandle> transport_socket, + virtual SSLClientSocket* CreateSSLClientSocket( + ClientSocketHandle* transport_socket, const HostPortPair& host_and_port, const SSLConfig& ssl_config, const SSLClientSocketContext& context) OVERRIDE { NOTIMPLEMENTED(); - return scoped_ptr<SSLClientSocket>(); + return NULL; } virtual void ClearSSLSessionCache() OVERRIDE { @@ -296,8 +294,7 @@ class TestConnectJob : public ConnectJob { AddressList ignored; client_socket_factory_->CreateTransportClientSocket( ignored, NULL, net::NetLog::Source()); - SetSocket( - scoped_ptr<StreamSocket>(new MockClientSocket(net_log().net_log()))); + set_socket(new MockClientSocket(net_log().net_log())); switch (job_type_) { case kMockJob: return DoConnect(true /* successful */, false /* sync */, @@ -376,7 +373,7 @@ class TestConnectJob : public ConnectJob { return ERR_IO_PENDING; default: NOTREACHED(); - SetSocket(scoped_ptr<StreamSocket>()); + set_socket(NULL); return ERR_FAILED; } } @@ -389,7 +386,7 @@ class TestConnectJob : public ConnectJob { result = ERR_PROXY_AUTH_REQUESTED; } else { result = ERR_CONNECTION_FAILED; - SetSocket(scoped_ptr<StreamSocket>()); + set_socket(NULL); } if (was_async) @@ -433,7 +430,7 @@ class TestConnectJobFactory // ConnectJobFactory implementation. - virtual scoped_ptr<ConnectJob> NewConnectJob( + virtual ConnectJob* NewConnectJob( const std::string& group_name, const TestClientSocketPoolBase::Request& request, ConnectJob::Delegate* delegate) const OVERRIDE { @@ -443,13 +440,13 @@ class TestConnectJobFactory job_type = job_types_->front(); job_types_->pop_front(); } - return scoped_ptr<ConnectJob>(new TestConnectJob(job_type, - group_name, - request, - timeout_duration_, - delegate, - client_socket_factory_, - net_log_)); + return new TestConnectJob(job_type, + group_name, + request, + timeout_duration_, + delegate, + client_socket_factory_, + net_log_); } virtual base::TimeDelta ConnectionTimeout() const OVERRIDE { @@ -512,9 +509,9 @@ class TestClientSocketPool : public ClientSocketPool { virtual void ReleaseSocket( const std::string& group_name, - scoped_ptr<StreamSocket> socket, + StreamSocket* socket, int id) OVERRIDE { - base_.ReleaseSocket(group_name, socket.Pass(), id); + base_.ReleaseSocket(group_name, socket, id); } virtual void FlushWithError(int error) OVERRIDE { @@ -633,10 +630,10 @@ class TestConnectJobDelegate : public ConnectJob::Delegate { virtual void OnConnectJobComplete(int result, ConnectJob* job) OVERRIDE { result_ = result; - scoped_ptr<ConnectJob> owned_job(job); - scoped_ptr<StreamSocket> socket = owned_job->PassSocket(); + scoped_ptr<StreamSocket> socket(job->ReleaseSocket()); // socket.get() should be NULL iff result != OK - EXPECT_EQ(socket == NULL, result != OK); + EXPECT_EQ(socket.get() == NULL, result != OK); + delete job; have_result_ = true; if (waiting_for_result_) base::MessageLoop::current()->Quit(); diff --git a/chromium/net/socket/nss_ssl_util.cc b/chromium/net/socket/nss_ssl_util.cc index ae037b17c1e..be33ac5add0 100644 --- a/chromium/net/socket/nss_ssl_util.cc +++ b/chromium/net/socket/nss_ssl_util.cc @@ -58,13 +58,12 @@ class NSSSSLInitSingleton { enabled = false; // Trim the list of cipher suites in order to keep the size of the - // ClientHello down. DSS, ECDH, CAMELLIA, SEED, ECC+3DES, and - // HMAC-SHA256 cipher suites are disabled. + // ClientHello down. DSS, ECDH, CAMELLIA, SEED and ECC+3DES cipher + // suites are disabled. if (info.symCipher == ssl_calg_camellia || info.symCipher == ssl_calg_seed || (info.symCipher == ssl_calg_3des && info.keaType != ssl_kea_rsa) || info.authAlgorithm == ssl_auth_dsa || - info.macAlgorithm == ssl_hmac_sha256 || info.nonStandard || strcmp(info.keaTypeName, "ECDH") == 0) { enabled = false; diff --git a/chromium/net/socket/socket_test_util.cc b/chromium/net/socket/socket_test_util.cc index 159f62e42c6..8b2bdfccba3 100644 --- a/chromium/net/socket/socket_test_util.cc +++ b/chromium/net/socket/socket_test_util.cc @@ -657,39 +657,37 @@ void MockClientSocketFactory::ResetNextMockIndexes() { mock_ssl_data_.ResetNextIndex(); } -scoped_ptr<DatagramClientSocket> -MockClientSocketFactory::CreateDatagramClientSocket( +DatagramClientSocket* MockClientSocketFactory::CreateDatagramClientSocket( DatagramSocket::BindType bind_type, const RandIntCallback& rand_int_cb, net::NetLog* net_log, const net::NetLog::Source& source) { SocketDataProvider* data_provider = mock_data_.GetNext(); - scoped_ptr<MockUDPClientSocket> socket( - new MockUDPClientSocket(data_provider, net_log)); - data_provider->set_socket(socket.get()); - return socket.PassAs<DatagramClientSocket>(); + MockUDPClientSocket* socket = new MockUDPClientSocket(data_provider, net_log); + data_provider->set_socket(socket); + return socket; } -scoped_ptr<StreamSocket> MockClientSocketFactory::CreateTransportClientSocket( +StreamSocket* MockClientSocketFactory::CreateTransportClientSocket( const AddressList& addresses, net::NetLog* net_log, const net::NetLog::Source& source) { SocketDataProvider* data_provider = mock_data_.GetNext(); - scoped_ptr<MockTCPClientSocket> socket( - new MockTCPClientSocket(addresses, net_log, data_provider)); - data_provider->set_socket(socket.get()); - return socket.PassAs<StreamSocket>(); + MockTCPClientSocket* socket = + new MockTCPClientSocket(addresses, net_log, data_provider); + data_provider->set_socket(socket); + return socket; } -scoped_ptr<SSLClientSocket> MockClientSocketFactory::CreateSSLClientSocket( - scoped_ptr<ClientSocketHandle> transport_socket, +SSLClientSocket* MockClientSocketFactory::CreateSSLClientSocket( + ClientSocketHandle* transport_socket, const HostPortPair& host_and_port, const SSLConfig& ssl_config, const SSLClientSocketContext& context) { - return scoped_ptr<SSLClientSocket>( - new MockSSLClientSocket(transport_socket.Pass(), - host_and_port, ssl_config, - mock_ssl_data_.GetNext())); + MockSSLClientSocket* socket = + new MockSSLClientSocket(transport_socket, host_and_port, ssl_config, + mock_ssl_data_.GetNext()); + return socket; } void MockClientSocketFactory::ClearSSLSessionCache() { @@ -1280,7 +1278,7 @@ void DeterministicMockTCPClientSocket::OnConnectComplete( // static void MockSSLClientSocket::ConnectCallback( - MockSSLClientSocket* ssl_client_socket, + MockSSLClientSocket *ssl_client_socket, const CompletionCallback& callback, int rv) { if (rv == OK) @@ -1289,7 +1287,7 @@ void MockSSLClientSocket::ConnectCallback( } MockSSLClientSocket::MockSSLClientSocket( - scoped_ptr<ClientSocketHandle> transport_socket, + ClientSocketHandle* transport_socket, const HostPortPair& host_port_pair, const SSLConfig& ssl_config, SSLSocketDataProvider* data) @@ -1297,7 +1295,7 @@ MockSSLClientSocket::MockSSLClientSocket( // Have to use the right BoundNetLog for LoadTimingInfo regression // tests. transport_socket->socket()->NetLog()), - transport_(transport_socket.Pass()), + transport_(transport_socket), data_(data), is_npn_state_set_(false), new_npn_value_(false), @@ -1666,10 +1664,10 @@ void ClientSocketPoolTest::ReleaseAllConnections(KeepAlive keep_alive) { } MockTransportClientSocketPool::MockConnectJob::MockConnectJob( - scoped_ptr<StreamSocket> socket, + StreamSocket* socket, ClientSocketHandle* handle, const CompletionCallback& callback) - : socket_(socket.Pass()), + : socket_(socket), handle_(handle), user_callback_(callback) { } @@ -1700,7 +1698,7 @@ void MockTransportClientSocketPool::MockConnectJob::OnConnect(int rv) { if (!socket_.get()) return; if (rv == OK) { - handle_->SetSocket(socket_.Pass()); + handle_->set_socket(socket_.release()); // Needed for socket pool tests that layer other sockets on top of mock // sockets. @@ -1742,10 +1740,9 @@ int MockTransportClientSocketPool::RequestSocket( const std::string& group_name, const void* socket_params, RequestPriority priority, ClientSocketHandle* handle, const CompletionCallback& callback, const BoundNetLog& net_log) { - scoped_ptr<StreamSocket> socket = - client_socket_factory_->CreateTransportClientSocket( - AddressList(), net_log.net_log(), net::NetLog::Source()); - MockConnectJob* job = new MockConnectJob(socket.Pass(), handle, callback); + StreamSocket* socket = client_socket_factory_->CreateTransportClientSocket( + AddressList(), net_log.net_log(), net::NetLog::Source()); + MockConnectJob* job = new MockConnectJob(socket, handle, callback); job_list_.push_back(job); handle->set_pool_id(1); return job->Connect(); @@ -1762,12 +1759,11 @@ void MockTransportClientSocketPool::CancelRequest(const std::string& group_name, } } -void MockTransportClientSocketPool::ReleaseSocket( - const std::string& group_name, - scoped_ptr<StreamSocket> socket, - int id) { +void MockTransportClientSocketPool::ReleaseSocket(const std::string& group_name, + StreamSocket* socket, int id) { EXPECT_EQ(1, id); release_count_++; + delete socket; } DeterministicMockClientSocketFactory::DeterministicMockClientSocketFactory() {} @@ -1795,45 +1791,42 @@ MockSSLClientSocket* DeterministicMockClientSocketFactory:: return ssl_client_sockets_[index]; } -scoped_ptr<DatagramClientSocket> +DatagramClientSocket* DeterministicMockClientSocketFactory::CreateDatagramClientSocket( DatagramSocket::BindType bind_type, const RandIntCallback& rand_int_cb, net::NetLog* net_log, const NetLog::Source& source) { DeterministicSocketData* data_provider = mock_data().GetNext(); - scoped_ptr<DeterministicMockUDPClientSocket> socket( - new DeterministicMockUDPClientSocket(net_log, data_provider)); + DeterministicMockUDPClientSocket* socket = + new DeterministicMockUDPClientSocket(net_log, data_provider); data_provider->set_delegate(socket->AsWeakPtr()); - udp_client_sockets().push_back(socket.get()); - return socket.PassAs<DatagramClientSocket>(); + udp_client_sockets().push_back(socket); + return socket; } -scoped_ptr<StreamSocket> -DeterministicMockClientSocketFactory::CreateTransportClientSocket( +StreamSocket* DeterministicMockClientSocketFactory::CreateTransportClientSocket( const AddressList& addresses, net::NetLog* net_log, const net::NetLog::Source& source) { DeterministicSocketData* data_provider = mock_data().GetNext(); - scoped_ptr<DeterministicMockTCPClientSocket> socket( - new DeterministicMockTCPClientSocket(net_log, data_provider)); + DeterministicMockTCPClientSocket* socket = + new DeterministicMockTCPClientSocket(net_log, data_provider); data_provider->set_delegate(socket->AsWeakPtr()); - tcp_client_sockets().push_back(socket.get()); - return socket.PassAs<StreamSocket>(); + tcp_client_sockets().push_back(socket); + return socket; } -scoped_ptr<SSLClientSocket> -DeterministicMockClientSocketFactory::CreateSSLClientSocket( - scoped_ptr<ClientSocketHandle> transport_socket, +SSLClientSocket* DeterministicMockClientSocketFactory::CreateSSLClientSocket( + ClientSocketHandle* transport_socket, const HostPortPair& host_and_port, const SSLConfig& ssl_config, const SSLClientSocketContext& context) { - scoped_ptr<MockSSLClientSocket> socket( - new MockSSLClientSocket(transport_socket.Pass(), - host_and_port, ssl_config, - mock_ssl_data_.GetNext())); - ssl_client_sockets_.push_back(socket.get()); - return socket.PassAs<SSLClientSocket>(); + MockSSLClientSocket* socket = + new MockSSLClientSocket(transport_socket, host_and_port, ssl_config, + mock_ssl_data_.GetNext()); + ssl_client_sockets_.push_back(socket); + return socket; } void DeterministicMockClientSocketFactory::ClearSSLSessionCache() { @@ -1866,9 +1859,8 @@ void MockSOCKSClientSocketPool::CancelRequest( } void MockSOCKSClientSocketPool::ReleaseSocket(const std::string& group_name, - scoped_ptr<StreamSocket> socket, - int id) { - return transport_pool_->ReleaseSocket(group_name, socket.Pass(), id); + StreamSocket* socket, int id) { + return transport_pool_->ReleaseSocket(group_name, socket, id); } const char kSOCKS5GreetRequest[] = { 0x05, 0x01, 0x00 }; diff --git a/chromium/net/socket/socket_test_util.h b/chromium/net/socket/socket_test_util.h index a888249654c..6afe170299e 100644 --- a/chromium/net/socket/socket_test_util.h +++ b/chromium/net/socket/socket_test_util.h @@ -592,17 +592,17 @@ class MockClientSocketFactory : public ClientSocketFactory { } // ClientSocketFactory - virtual scoped_ptr<DatagramClientSocket> CreateDatagramClientSocket( + virtual DatagramClientSocket* CreateDatagramClientSocket( DatagramSocket::BindType bind_type, const RandIntCallback& rand_int_cb, NetLog* net_log, const NetLog::Source& source) OVERRIDE; - virtual scoped_ptr<StreamSocket> CreateTransportClientSocket( + virtual StreamSocket* CreateTransportClientSocket( const AddressList& addresses, NetLog* net_log, const NetLog::Source& source) OVERRIDE; - virtual scoped_ptr<SSLClientSocket> CreateSSLClientSocket( - scoped_ptr<ClientSocketHandle> transport_socket, + virtual SSLClientSocket* CreateSSLClientSocket( + ClientSocketHandle* transport_socket, const HostPortPair& host_and_port, const SSLConfig& ssl_config, const SSLClientSocketContext& context) OVERRIDE; @@ -857,7 +857,7 @@ class DeterministicMockTCPClientSocket class MockSSLClientSocket : public MockClientSocket, public AsyncSocket { public: MockSSLClientSocket( - scoped_ptr<ClientSocketHandle> transport_socket, + ClientSocketHandle* transport_socket, const HostPortPair& host_and_port, const SSLConfig& ssl_config, SSLSocketDataProvider* socket); @@ -1049,7 +1049,7 @@ class MockTransportClientSocketPool : public TransportClientSocketPool { public: class MockConnectJob { public: - MockConnectJob(scoped_ptr<StreamSocket> socket, ClientSocketHandle* handle, + MockConnectJob(StreamSocket* socket, ClientSocketHandle* handle, const CompletionCallback& callback); ~MockConnectJob(); @@ -1088,8 +1088,7 @@ class MockTransportClientSocketPool : public TransportClientSocketPool { virtual void CancelRequest(const std::string& group_name, ClientSocketHandle* handle) OVERRIDE; virtual void ReleaseSocket(const std::string& group_name, - scoped_ptr<StreamSocket> socket, - int id) OVERRIDE; + StreamSocket* socket, int id) OVERRIDE; private: ClientSocketFactory* client_socket_factory_; @@ -1124,17 +1123,17 @@ class DeterministicMockClientSocketFactory : public ClientSocketFactory { } // ClientSocketFactory - virtual scoped_ptr<DatagramClientSocket> CreateDatagramClientSocket( + virtual DatagramClientSocket* CreateDatagramClientSocket( DatagramSocket::BindType bind_type, const RandIntCallback& rand_int_cb, NetLog* net_log, const NetLog::Source& source) OVERRIDE; - virtual scoped_ptr<StreamSocket> CreateTransportClientSocket( + virtual StreamSocket* CreateTransportClientSocket( const AddressList& addresses, NetLog* net_log, const NetLog::Source& source) OVERRIDE; - virtual scoped_ptr<SSLClientSocket> CreateSSLClientSocket( - scoped_ptr<ClientSocketHandle> transport_socket, + virtual SSLClientSocket* CreateSSLClientSocket( + ClientSocketHandle* transport_socket, const HostPortPair& host_and_port, const SSLConfig& ssl_config, const SSLClientSocketContext& context) OVERRIDE; @@ -1171,8 +1170,7 @@ class MockSOCKSClientSocketPool : public SOCKSClientSocketPool { virtual void CancelRequest(const std::string& group_name, ClientSocketHandle* handle) OVERRIDE; virtual void ReleaseSocket(const std::string& group_name, - scoped_ptr<StreamSocket> socket, - int id) OVERRIDE; + StreamSocket* socket, int id) OVERRIDE; private: TransportClientSocketPool* const transport_pool_; diff --git a/chromium/net/socket/socks5_client_socket.cc b/chromium/net/socket/socks5_client_socket.cc index 537b584a932..c9d25bc3dcb 100644 --- a/chromium/net/socket/socks5_client_socket.cc +++ b/chromium/net/socket/socks5_client_socket.cc @@ -28,18 +28,34 @@ COMPILE_ASSERT(sizeof(struct in_addr) == 4, incorrect_system_size_of_IPv4); COMPILE_ASSERT(sizeof(struct in6_addr) == 16, incorrect_system_size_of_IPv6); SOCKS5ClientSocket::SOCKS5ClientSocket( - scoped_ptr<ClientSocketHandle> transport_socket, + ClientSocketHandle* transport_socket, const HostResolver::RequestInfo& req_info) : io_callback_(base::Bind(&SOCKS5ClientSocket::OnIOComplete, base::Unretained(this))), - transport_(transport_socket.Pass()), + transport_(transport_socket), next_state_(STATE_NONE), completed_handshake_(false), bytes_sent_(0), bytes_received_(0), read_header_size(kReadHeaderSize), host_request_info_(req_info), - net_log_(transport_->socket()->NetLog()) { + net_log_(transport_socket->socket()->NetLog()) { +} + +SOCKS5ClientSocket::SOCKS5ClientSocket( + StreamSocket* transport_socket, + const HostResolver::RequestInfo& req_info) + : io_callback_(base::Bind(&SOCKS5ClientSocket::OnIOComplete, + base::Unretained(this))), + transport_(new ClientSocketHandle()), + next_state_(STATE_NONE), + completed_handshake_(false), + bytes_sent_(0), + bytes_received_(0), + read_header_size(kReadHeaderSize), + host_request_info_(req_info), + net_log_(transport_socket->NetLog()) { + transport_->set_socket(transport_socket); } SOCKS5ClientSocket::~SOCKS5ClientSocket() { diff --git a/chromium/net/socket/socks5_client_socket.h b/chromium/net/socket/socks5_client_socket.h index 45216244f10..b955e8f42de 100644 --- a/chromium/net/socket/socks5_client_socket.h +++ b/chromium/net/socket/socks5_client_socket.h @@ -28,13 +28,20 @@ class BoundNetLog; // Currently no SOCKSv5 authentication is supported. class NET_EXPORT_PRIVATE SOCKS5ClientSocket : public StreamSocket { public: + // Takes ownership of the |transport_socket|, which should already be + // connected by the time Connect() is called. + // // |req_info| contains the hostname and port to which the socket above will // communicate to via the SOCKS layer. // // Although SOCKS 5 supports 3 different modes of addressing, we will // always pass it a hostname. This means the DNS resolving is done // proxy side. - SOCKS5ClientSocket(scoped_ptr<ClientSocketHandle> transport_socket, + SOCKS5ClientSocket(ClientSocketHandle* transport_socket, + const HostResolver::RequestInfo& req_info); + + // Deprecated constructor (http://crbug.com/37810) that takes a StreamSocket. + SOCKS5ClientSocket(StreamSocket* transport_socket, const HostResolver::RequestInfo& req_info); // On destruction Disconnect() is called. diff --git a/chromium/net/socket/socks5_client_socket_unittest.cc b/chromium/net/socket/socks5_client_socket_unittest.cc index 4c9240ff5c1..717d858eef8 100644 --- a/chromium/net/socket/socks5_client_socket_unittest.cc +++ b/chromium/net/socket/socks5_client_socket_unittest.cc @@ -32,13 +32,13 @@ class SOCKS5ClientSocketTest : public PlatformTest { public: SOCKS5ClientSocketTest(); // Create a SOCKSClientSocket on top of a MockSocket. - scoped_ptr<SOCKS5ClientSocket> BuildMockSocket(MockRead reads[], - size_t reads_count, - MockWrite writes[], - size_t writes_count, - const std::string& hostname, - int port, - NetLog* net_log); + SOCKS5ClientSocket* BuildMockSocket(MockRead reads[], + size_t reads_count, + MockWrite writes[], + size_t writes_count, + const std::string& hostname, + int port, + NetLog* net_log); virtual void SetUp(); @@ -47,8 +47,6 @@ class SOCKS5ClientSocketTest : public PlatformTest { CapturingNetLog net_log_; scoped_ptr<SOCKS5ClientSocket> user_sock_; AddressList address_list_; - // Filled in by BuildMockSocket() and owned by its return value - // (which |user_sock| is set to). StreamSocket* tcp_sock_; TestCompletionCallback callback_; scoped_ptr<MockHostResolver> host_resolver_; @@ -77,7 +75,7 @@ void SOCKS5ClientSocketTest::SetUp() { ASSERT_EQ(OK, rv); } -scoped_ptr<SOCKS5ClientSocket> SOCKS5ClientSocketTest::BuildMockSocket( +SOCKS5ClientSocket* SOCKS5ClientSocketTest::BuildMockSocket( MockRead reads[], size_t reads_count, MockWrite writes[], @@ -96,13 +94,8 @@ scoped_ptr<SOCKS5ClientSocket> SOCKS5ClientSocketTest::BuildMockSocket( EXPECT_EQ(OK, rv); EXPECT_TRUE(tcp_sock_->IsConnected()); - scoped_ptr<ClientSocketHandle> connection(new ClientSocketHandle); - // |connection| takes ownership of |tcp_sock_|, but keep a - // non-owning pointer to it. - connection->SetSocket(scoped_ptr<StreamSocket>(tcp_sock_)); - return scoped_ptr<SOCKS5ClientSocket>(new SOCKS5ClientSocket( - connection.Pass(), - HostResolver::RequestInfo(HostPortPair(hostname, port)))); + return new SOCKS5ClientSocket(tcp_sock_, + HostResolver::RequestInfo(HostPortPair(hostname, port))); } // Tests a complete SOCKS5 handshake and the disconnection. @@ -130,9 +123,9 @@ TEST_F(SOCKS5ClientSocketTest, CompleteHandshake) { MockRead(ASYNC, kSOCKS5OkResponse, kSOCKS5OkResponseLength), MockRead(ASYNC, payload_read.data(), payload_read.size()) }; - user_sock_ = BuildMockSocket(data_reads, arraysize(data_reads), - data_writes, arraysize(data_writes), - "localhost", 80, &net_log_); + user_sock_.reset(BuildMockSocket(data_reads, arraysize(data_reads), + data_writes, arraysize(data_writes), + "localhost", 80, &net_log_)); // At this state the TCP connection is completed but not the SOCKS handshake. EXPECT_TRUE(tcp_sock_->IsConnected()); @@ -202,9 +195,9 @@ TEST_F(SOCKS5ClientSocketTest, ConnectAndDisconnectTwice) { MockRead(SYNCHRONOUS, kSOCKS5OkResponse, kSOCKS5OkResponseLength) }; - user_sock_ = BuildMockSocket(data_reads, arraysize(data_reads), - data_writes, arraysize(data_writes), - hostname, 80, NULL); + user_sock_.reset(BuildMockSocket(data_reads, arraysize(data_reads), + data_writes, arraysize(data_writes), + hostname, 80, NULL)); int rv = user_sock_->Connect(callback_.callback()); EXPECT_EQ(OK, rv); @@ -224,9 +217,9 @@ TEST_F(SOCKS5ClientSocketTest, LargeHostNameFails) { // Create a SOCKS socket, with mock transport socket. MockWrite data_writes[] = {MockWrite()}; MockRead data_reads[] = {MockRead()}; - user_sock_ = BuildMockSocket(data_reads, arraysize(data_reads), - data_writes, arraysize(data_writes), - large_host_name, 80, NULL); + user_sock_.reset(BuildMockSocket(data_reads, arraysize(data_reads), + data_writes, arraysize(data_writes), + large_host_name, 80, NULL)); // Try to connect -- should fail (without having read/written anything to // the transport socket first) because the hostname is too long. @@ -260,9 +253,9 @@ TEST_F(SOCKS5ClientSocketTest, PartialReadWrites) { MockRead data_reads[] = { MockRead(ASYNC, kSOCKS5GreetResponse, kSOCKS5GreetResponseLength), MockRead(ASYNC, kSOCKS5OkResponse, kSOCKS5OkResponseLength) }; - user_sock_ = BuildMockSocket(data_reads, arraysize(data_reads), - data_writes, arraysize(data_writes), - hostname, 80, &net_log_); + user_sock_.reset(BuildMockSocket(data_reads, arraysize(data_reads), + data_writes, arraysize(data_writes), + hostname, 80, &net_log_)); int rv = user_sock_->Connect(callback_.callback()); EXPECT_EQ(ERR_IO_PENDING, rv); @@ -291,9 +284,9 @@ TEST_F(SOCKS5ClientSocketTest, PartialReadWrites) { MockRead(ASYNC, partial1, arraysize(partial1)), MockRead(ASYNC, partial2, arraysize(partial2)), MockRead(ASYNC, kSOCKS5OkResponse, kSOCKS5OkResponseLength) }; - user_sock_ = BuildMockSocket(data_reads, arraysize(data_reads), - data_writes, arraysize(data_writes), - hostname, 80, &net_log_); + user_sock_.reset(BuildMockSocket(data_reads, arraysize(data_reads), + data_writes, arraysize(data_writes), + hostname, 80, &net_log_)); int rv = user_sock_->Connect(callback_.callback()); EXPECT_EQ(ERR_IO_PENDING, rv); @@ -321,9 +314,9 @@ TEST_F(SOCKS5ClientSocketTest, PartialReadWrites) { MockRead data_reads[] = { MockRead(ASYNC, kSOCKS5GreetResponse, kSOCKS5GreetResponseLength), MockRead(ASYNC, kSOCKS5OkResponse, kSOCKS5OkResponseLength) }; - user_sock_ = BuildMockSocket(data_reads, arraysize(data_reads), - data_writes, arraysize(data_writes), - hostname, 80, &net_log_); + user_sock_.reset(BuildMockSocket(data_reads, arraysize(data_reads), + data_writes, arraysize(data_writes), + hostname, 80, &net_log_)); int rv = user_sock_->Connect(callback_.callback()); EXPECT_EQ(ERR_IO_PENDING, rv); CapturingNetLog::CapturedEntryList net_log_entries; @@ -352,9 +345,9 @@ TEST_F(SOCKS5ClientSocketTest, PartialReadWrites) { kSOCKS5OkResponseLength - kSplitPoint) }; - user_sock_ = BuildMockSocket(data_reads, arraysize(data_reads), - data_writes, arraysize(data_writes), - hostname, 80, &net_log_); + user_sock_.reset(BuildMockSocket(data_reads, arraysize(data_reads), + data_writes, arraysize(data_writes), + hostname, 80, &net_log_)); int rv = user_sock_->Connect(callback_.callback()); EXPECT_EQ(ERR_IO_PENDING, rv); CapturingNetLog::CapturedEntryList net_log_entries; diff --git a/chromium/net/socket/socks_client_socket.cc b/chromium/net/socket/socks_client_socket.cc index 1941fdbfd95..c4bbd28c619 100644 --- a/chromium/net/socket/socks_client_socket.cc +++ b/chromium/net/socket/socks_client_socket.cc @@ -55,18 +55,31 @@ struct SOCKS4ServerResponse { COMPILE_ASSERT(sizeof(SOCKS4ServerResponse) == kReadHeaderSize, socks4_server_response_struct_wrong_size); -SOCKSClientSocket::SOCKSClientSocket( - scoped_ptr<ClientSocketHandle> transport_socket, - const HostResolver::RequestInfo& req_info, - HostResolver* host_resolver) - : transport_(transport_socket.Pass()), +SOCKSClientSocket::SOCKSClientSocket(ClientSocketHandle* transport_socket, + const HostResolver::RequestInfo& req_info, + HostResolver* host_resolver) + : transport_(transport_socket), next_state_(STATE_NONE), completed_handshake_(false), bytes_sent_(0), bytes_received_(0), host_resolver_(host_resolver), host_request_info_(req_info), - net_log_(transport_->socket()->NetLog()) { + net_log_(transport_socket->socket()->NetLog()) { +} + +SOCKSClientSocket::SOCKSClientSocket(StreamSocket* transport_socket, + const HostResolver::RequestInfo& req_info, + HostResolver* host_resolver) + : transport_(new ClientSocketHandle()), + next_state_(STATE_NONE), + completed_handshake_(false), + bytes_sent_(0), + bytes_received_(0), + host_resolver_(host_resolver), + host_request_info_(req_info), + net_log_(transport_socket->NetLog()) { + transport_->set_socket(transport_socket); } SOCKSClientSocket::~SOCKSClientSocket() { diff --git a/chromium/net/socket/socks_client_socket.h b/chromium/net/socket/socks_client_socket.h index 285c75ec295..3d4f9fc2771 100644 --- a/chromium/net/socket/socks_client_socket.h +++ b/chromium/net/socket/socks_client_socket.h @@ -27,9 +27,17 @@ class BoundNetLog; // The SOCKS client socket implementation class NET_EXPORT_PRIVATE SOCKSClientSocket : public StreamSocket { public: + // Takes ownership of the |transport_socket|, which should already be + // connected by the time Connect() is called. + // // |req_info| contains the hostname and port to which the socket above will // communicate to via the socks layer. For testing the referrer is optional. - SOCKSClientSocket(scoped_ptr<ClientSocketHandle> transport_socket, + SOCKSClientSocket(ClientSocketHandle* transport_socket, + const HostResolver::RequestInfo& req_info, + HostResolver* host_resolver); + + // Deprecated constructor (http://crbug.com/37810) that takes a StreamSocket. + SOCKSClientSocket(StreamSocket* transport_socket, const HostResolver::RequestInfo& req_info, HostResolver* host_resolver); diff --git a/chromium/net/socket/socks_client_socket_pool.cc b/chromium/net/socket/socks_client_socket_pool.cc index e49eabaa84c..d740e5b9a0e 100644 --- a/chromium/net/socket/socks_client_socket_pool.cc +++ b/chromium/net/socket/socks_client_socket_pool.cc @@ -140,10 +140,10 @@ int SOCKSConnectJob::DoSOCKSConnect() { // Add a SOCKS connection on top of the tcp socket. if (socks_params_->is_socks_v5()) { - socket_.reset(new SOCKS5ClientSocket(transport_socket_handle_.Pass(), + socket_.reset(new SOCKS5ClientSocket(transport_socket_handle_.release(), socks_params_->destination())); } else { - socket_.reset(new SOCKSClientSocket(transport_socket_handle_.Pass(), + socket_.reset(new SOCKSClientSocket(transport_socket_handle_.release(), socks_params_->destination(), resolver_)); } @@ -157,7 +157,7 @@ int SOCKSConnectJob::DoSOCKSConnectComplete(int result) { return result; } - SetSocket(socket_.Pass()); + set_socket(socket_.release()); return result; } @@ -166,18 +166,17 @@ int SOCKSConnectJob::ConnectInternal() { return DoLoop(OK); } -scoped_ptr<ConnectJob> -SOCKSClientSocketPool::SOCKSConnectJobFactory::NewConnectJob( +ConnectJob* SOCKSClientSocketPool::SOCKSConnectJobFactory::NewConnectJob( const std::string& group_name, const PoolBase::Request& request, ConnectJob::Delegate* delegate) const { - return scoped_ptr<ConnectJob>(new SOCKSConnectJob(group_name, - request.params(), - ConnectionTimeout(), - transport_pool_, - host_resolver_, - delegate, - net_log_)); + return new SOCKSConnectJob(group_name, + request.params(), + ConnectionTimeout(), + transport_pool_, + host_resolver_, + delegate, + net_log_); } base::TimeDelta @@ -239,9 +238,8 @@ void SOCKSClientSocketPool::CancelRequest(const std::string& group_name, } void SOCKSClientSocketPool::ReleaseSocket(const std::string& group_name, - scoped_ptr<StreamSocket> socket, - int id) { - base_.ReleaseSocket(group_name, socket.Pass(), id); + StreamSocket* socket, int id) { + base_.ReleaseSocket(group_name, socket, id); } void SOCKSClientSocketPool::FlushWithError(int error) { diff --git a/chromium/net/socket/socks_client_socket_pool.h b/chromium/net/socket/socks_client_socket_pool.h index fe69a78df69..86609a1a5a0 100644 --- a/chromium/net/socket/socks_client_socket_pool.h +++ b/chromium/net/socket/socks_client_socket_pool.h @@ -134,7 +134,7 @@ class NET_EXPORT_PRIVATE SOCKSClientSocketPool ClientSocketHandle* handle) OVERRIDE; virtual void ReleaseSocket(const std::string& group_name, - scoped_ptr<StreamSocket> socket, + StreamSocket* socket, int id) OVERRIDE; virtual void FlushWithError(int error) OVERRIDE; @@ -183,7 +183,7 @@ class NET_EXPORT_PRIVATE SOCKSClientSocketPool virtual ~SOCKSConnectJobFactory() {} // ClientSocketPoolBase::ConnectJobFactory methods. - virtual scoped_ptr<ConnectJob> NewConnectJob( + virtual ConnectJob* NewConnectJob( const std::string& group_name, const PoolBase::Request& request, ConnectJob::Delegate* delegate) const OVERRIDE; diff --git a/chromium/net/socket/socks_client_socket_unittest.cc b/chromium/net/socket/socks_client_socket_unittest.cc index 8c30838959d..7a8faf69856 100644 --- a/chromium/net/socket/socks_client_socket_unittest.cc +++ b/chromium/net/socket/socks_client_socket_unittest.cc @@ -4,7 +4,6 @@ #include "net/socket/socks_client_socket.h" -#include "base/memory/scoped_ptr.h" #include "net/base/address_list.h" #include "net/base/net_log.h" #include "net/base/net_log_unittest.h" @@ -28,19 +27,16 @@ class SOCKSClientSocketTest : public PlatformTest { public: SOCKSClientSocketTest(); // Create a SOCKSClientSocket on top of a MockSocket. - scoped_ptr<SOCKSClientSocket> BuildMockSocket( - MockRead reads[], size_t reads_count, - MockWrite writes[], size_t writes_count, - HostResolver* host_resolver, - const std::string& hostname, int port, - NetLog* net_log); + SOCKSClientSocket* BuildMockSocket(MockRead reads[], size_t reads_count, + MockWrite writes[], size_t writes_count, + HostResolver* host_resolver, + const std::string& hostname, int port, + NetLog* net_log); virtual void SetUp(); protected: scoped_ptr<SOCKSClientSocket> user_sock_; AddressList address_list_; - // Filled in by BuildMockSocket() and owned by its return value - // (which |user_sock| is set to). StreamSocket* tcp_sock_; TestCompletionCallback callback_; scoped_ptr<MockHostResolver> host_resolver_; @@ -56,7 +52,7 @@ void SOCKSClientSocketTest::SetUp() { PlatformTest::SetUp(); } -scoped_ptr<SOCKSClientSocket> SOCKSClientSocketTest::BuildMockSocket( +SOCKSClientSocket* SOCKSClientSocketTest::BuildMockSocket( MockRead reads[], size_t reads_count, MockWrite writes[], @@ -77,14 +73,9 @@ scoped_ptr<SOCKSClientSocket> SOCKSClientSocketTest::BuildMockSocket( EXPECT_EQ(OK, rv); EXPECT_TRUE(tcp_sock_->IsConnected()); - scoped_ptr<ClientSocketHandle> connection(new ClientSocketHandle); - // |connection| takes ownership of |tcp_sock_|, but keep a - // non-owning pointer to it. - connection->SetSocket(scoped_ptr<StreamSocket>(tcp_sock_)); - return scoped_ptr<SOCKSClientSocket>(new SOCKSClientSocket( - connection.Pass(), + return new SOCKSClientSocket(tcp_sock_, HostResolver::RequestInfo(HostPortPair(hostname, port)), - host_resolver)); + host_resolver); } // Implementation of HostResolver that never completes its resolve request. @@ -143,11 +134,11 @@ TEST_F(SOCKSClientSocketTest, CompleteHandshake) { MockRead(ASYNC, payload_read.data(), payload_read.size()) }; CapturingNetLog log; - user_sock_ = BuildMockSocket(data_reads, arraysize(data_reads), - data_writes, arraysize(data_writes), - host_resolver_.get(), - "localhost", 80, - &log); + user_sock_.reset(BuildMockSocket(data_reads, arraysize(data_reads), + data_writes, arraysize(data_writes), + host_resolver_.get(), + "localhost", 80, + &log)); // At this state the TCP connection is completed but not the SOCKS handshake. EXPECT_TRUE(tcp_sock_->IsConnected()); @@ -219,11 +210,11 @@ TEST_F(SOCKSClientSocketTest, HandshakeFailures) { arraysize(tests[i].fail_reply)) }; CapturingNetLog log; - user_sock_ = BuildMockSocket(data_reads, arraysize(data_reads), - data_writes, arraysize(data_writes), - host_resolver_.get(), - "localhost", 80, - &log); + user_sock_.reset(BuildMockSocket(data_reads, arraysize(data_reads), + data_writes, arraysize(data_writes), + host_resolver_.get(), + "localhost", 80, + &log)); int rv = user_sock_->Connect(callback_.callback()); EXPECT_EQ(ERR_IO_PENDING, rv); @@ -256,11 +247,11 @@ TEST_F(SOCKSClientSocketTest, PartialServerReads) { MockRead(ASYNC, kSOCKSPartialReply2, arraysize(kSOCKSPartialReply2)) }; CapturingNetLog log; - user_sock_ = BuildMockSocket(data_reads, arraysize(data_reads), - data_writes, arraysize(data_writes), - host_resolver_.get(), - "localhost", 80, - &log); + user_sock_.reset(BuildMockSocket(data_reads, arraysize(data_reads), + data_writes, arraysize(data_writes), + host_resolver_.get(), + "localhost", 80, + &log)); int rv = user_sock_->Connect(callback_.callback()); EXPECT_EQ(ERR_IO_PENDING, rv); @@ -294,11 +285,11 @@ TEST_F(SOCKSClientSocketTest, PartialClientWrites) { MockRead(ASYNC, kSOCKSOkReply, arraysize(kSOCKSOkReply)) }; CapturingNetLog log; - user_sock_ = BuildMockSocket(data_reads, arraysize(data_reads), - data_writes, arraysize(data_writes), - host_resolver_.get(), - "localhost", 80, - &log); + user_sock_.reset(BuildMockSocket(data_reads, arraysize(data_reads), + data_writes, arraysize(data_writes), + host_resolver_.get(), + "localhost", 80, + &log)); int rv = user_sock_->Connect(callback_.callback()); EXPECT_EQ(ERR_IO_PENDING, rv); @@ -326,11 +317,11 @@ TEST_F(SOCKSClientSocketTest, FailedSocketRead) { MockRead(SYNCHRONOUS, 0) }; CapturingNetLog log; - user_sock_ = BuildMockSocket(data_reads, arraysize(data_reads), - data_writes, arraysize(data_writes), - host_resolver_.get(), - "localhost", 80, - &log); + user_sock_.reset(BuildMockSocket(data_reads, arraysize(data_reads), + data_writes, arraysize(data_writes), + host_resolver_.get(), + "localhost", 80, + &log)); int rv = user_sock_->Connect(callback_.callback()); EXPECT_EQ(ERR_IO_PENDING, rv); @@ -356,11 +347,11 @@ TEST_F(SOCKSClientSocketTest, FailedDNS) { CapturingNetLog log; - user_sock_ = BuildMockSocket(NULL, 0, - NULL, 0, - host_resolver_.get(), - hostname, 80, - &log); + user_sock_.reset(BuildMockSocket(NULL, 0, + NULL, 0, + host_resolver_.get(), + hostname, 80, + &log)); int rv = user_sock_->Connect(callback_.callback()); EXPECT_EQ(ERR_IO_PENDING, rv); @@ -387,11 +378,11 @@ TEST_F(SOCKSClientSocketTest, DisconnectWhileHostResolveInProgress) { MockWrite data_writes[] = { MockWrite(SYNCHRONOUS, "", 0) }; MockRead data_reads[] = { MockRead(SYNCHRONOUS, "", 0) }; - user_sock_ = BuildMockSocket(data_reads, arraysize(data_reads), - data_writes, arraysize(data_writes), - hanging_resolver.get(), - "foo", 80, - NULL); + user_sock_.reset(BuildMockSocket(data_reads, arraysize(data_reads), + data_writes, arraysize(data_writes), + hanging_resolver.get(), + "foo", 80, + NULL)); // Start connecting (will get stuck waiting for the host to resolve). int rv = user_sock_->Connect(callback_.callback()); diff --git a/chromium/net/socket/ssl_client_socket_nss.cc b/chromium/net/socket/ssl_client_socket_nss.cc index acc1b0dee2e..f374dedcf80 100644 --- a/chromium/net/socket/ssl_client_socket_nss.cc +++ b/chromium/net/socket/ssl_client_socket_nss.cc @@ -2598,7 +2598,7 @@ int SSLClientSocketNSS::Core::DoGetDomainBoundCert(const std::string& host) { weak_net_log_->BeginEvent(NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT); - int rv = server_bound_cert_service_->GetOrCreateDomainBoundCert( + int rv = server_bound_cert_service_->GetDomainBoundCert( host, &domain_bound_private_key_, &domain_bound_cert_, @@ -2751,12 +2751,12 @@ void SSLClientSocketNSS::Core::SetChannelIDProvided() { SSLClientSocketNSS::SSLClientSocketNSS( base::SequencedTaskRunner* nss_task_runner, - scoped_ptr<ClientSocketHandle> transport_socket, + ClientSocketHandle* transport_socket, const HostPortPair& host_and_port, const SSLConfig& ssl_config, const SSLClientSocketContext& context) : nss_task_runner_(nss_task_runner), - transport_(transport_socket.Pass()), + transport_(transport_socket), host_and_port_(host_and_port), ssl_config_(ssl_config), cert_verifier_(context.cert_verifier), @@ -2765,7 +2765,7 @@ SSLClientSocketNSS::SSLClientSocketNSS( completed_handshake_(false), next_handshake_state_(STATE_NONE), nss_fd_(NULL), - net_log_(transport_->socket()->NetLog()), + net_log_(transport_socket->socket()->NetLog()), transport_security_state_(context.transport_security_state), valid_thread_id_(base::kInvalidThreadId) { EnterFunction(""); @@ -3141,8 +3141,7 @@ int SSLClientSocketNSS::InitializeSSLOptions() { net_log_, "SSL_OptionSet", "SSL_ENABLE_SESSION_TICKETS"); } - rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_FALSE_START, - ssl_config_.false_start_enabled); + rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_FALSE_START, PR_FALSE); if (rv != SECSuccess) LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_ENABLE_FALSE_START"); diff --git a/chromium/net/socket/ssl_client_socket_nss.h b/chromium/net/socket/ssl_client_socket_nss.h index b41d28d74a8..fed8ef706b5 100644 --- a/chromium/net/socket/ssl_client_socket_nss.h +++ b/chromium/net/socket/ssl_client_socket_nss.h @@ -59,7 +59,7 @@ class SSLClientSocketNSS : public SSLClientSocket { // behaviour is desired, for performance or compatibility, the current task // runner should be supplied instead. SSLClientSocketNSS(base::SequencedTaskRunner* nss_task_runner, - scoped_ptr<ClientSocketHandle> transport_socket, + ClientSocketHandle* transport_socket, const HostPortPair& host_and_port, const SSLConfig& ssl_config, const SSLClientSocketContext& context); diff --git a/chromium/net/socket/ssl_client_socket_openssl.cc b/chromium/net/socket/ssl_client_socket_openssl.cc index 4591cec5b9d..1431bc61486 100644 --- a/chromium/net/socket/ssl_client_socket_openssl.cc +++ b/chromium/net/socket/ssl_client_socket_openssl.cc @@ -425,7 +425,7 @@ void SSLClientSocket::ClearSessionCache() { } SSLClientSocketOpenSSL::SSLClientSocketOpenSSL( - scoped_ptr<ClientSocketHandle> transport_socket, + ClientSocketHandle* transport_socket, const HostPortPair& host_and_port, const SSLConfig& ssl_config, const SSLClientSocketContext& context) @@ -439,14 +439,14 @@ SSLClientSocketOpenSSL::SSLClientSocketOpenSSL( cert_verifier_(context.cert_verifier), ssl_(NULL), transport_bio_(NULL), - transport_(transport_socket.Pass()), + transport_(transport_socket), host_and_port_(host_and_port), ssl_config_(ssl_config), ssl_session_cache_shard_(context.ssl_session_cache_shard), trying_cached_session_(false), next_handshake_state_(STATE_NONE), npn_status_(kNextProtoUnsupported), - net_log_(transport_->socket()->NetLog()) { + net_log_(transport_socket->socket()->NetLog()) { } SSLClientSocketOpenSSL::~SSLClientSocketOpenSSL() { diff --git a/chromium/net/socket/ssl_client_socket_openssl.h b/chromium/net/socket/ssl_client_socket_openssl.h index f66d95cc69d..520f432b8bc 100644 --- a/chromium/net/socket/ssl_client_socket_openssl.h +++ b/chromium/net/socket/ssl_client_socket_openssl.h @@ -41,7 +41,7 @@ class SSLClientSocketOpenSSL : public SSLClientSocket { // The given hostname will be compared with the name(s) in the server's // certificate during the SSL handshake. ssl_config specifies the SSL // settings. - SSLClientSocketOpenSSL(scoped_ptr<ClientSocketHandle> transport_socket, + SSLClientSocketOpenSSL(ClientSocketHandle* transport_socket, const HostPortPair& host_and_port, const SSLConfig& ssl_config, const SSLClientSocketContext& context); diff --git a/chromium/net/socket/ssl_client_socket_openssl_unittest.cc b/chromium/net/socket/ssl_client_socket_openssl_unittest.cc index 04f899903ac..7a37cdc1187 100644 --- a/chromium/net/socket/ssl_client_socket_openssl_unittest.cc +++ b/chromium/net/socket/ssl_client_socket_openssl_unittest.cc @@ -107,13 +107,11 @@ class SSLClientSocketOpenSSLClientAuthTest : public PlatformTest { } protected: - scoped_ptr<SSLClientSocket> CreateSSLClientSocket( - scoped_ptr<StreamSocket> transport_socket, + SSLClientSocket* CreateSSLClientSocket( + StreamSocket* transport_socket, const HostPortPair& host_and_port, const SSLConfig& ssl_config) { - scoped_ptr<ClientSocketHandle> connection(new ClientSocketHandle); - connection->SetSocket(transport_socket.Pass()); - return socket_factory_->CreateSSLClientSocket(connection.Pass(), + return socket_factory_->CreateSSLClientSocket(transport_socket, host_and_port, ssl_config, context_); @@ -166,9 +164,9 @@ class SSLClientSocketOpenSSLClientAuthTest : public PlatformTest { // itself was a success. bool CreateAndConnectSSLClientSocket(SSLConfig& ssl_config, int* result) { - sock_ = CreateSSLClientSocket(transport_.Pass(), - test_server_->host_port_pair(), - ssl_config); + sock_.reset(CreateSSLClientSocket(transport_.release(), + test_server_->host_port_pair(), + ssl_config)); if (sock_->IsConnected()) { LOG(ERROR) << "SSL Socket prematurely connected"; diff --git a/chromium/net/socket/ssl_client_socket_pool.cc b/chromium/net/socket/ssl_client_socket_pool.cc index d07c76ffb49..fed268d4ee4 100644 --- a/chromium/net/socket/ssl_client_socket_pool.cc +++ b/chromium/net/socket/ssl_client_socket_pool.cc @@ -287,11 +287,11 @@ int SSLConnectJob::DoSSLConnect() { connect_timing_.ssl_start = base::TimeTicks::Now(); - ssl_socket_ = client_socket_factory_->CreateSSLClientSocket( - transport_socket_handle_.Pass(), + ssl_socket_.reset(client_socket_factory_->CreateSSLClientSocket( + transport_socket_handle_.release(), params_->host_and_port(), params_->ssl_config(), - context_); + context_)); return ssl_socket_->Connect(callback_); } @@ -410,7 +410,7 @@ int SSLConnectJob::DoSSLConnectComplete(int result) { } if (result == OK || IsCertificateError(result)) { - SetSocket(ssl_socket_.PassAs<StreamSocket>()); + set_socket(ssl_socket_.release()); } else if (result == ERR_SSL_CLIENT_AUTH_CERT_NEEDED) { error_response_info_.cert_request_info = new SSLCertRequestInfo; ssl_socket_->GetSSLCertRequestInfo( @@ -527,16 +527,14 @@ SSLClientSocketPool::~SSLClientSocketPool() { ssl_config_service_->RemoveObserver(this); } -scoped_ptr<ConnectJob> -SSLClientSocketPool::SSLConnectJobFactory::NewConnectJob( +ConnectJob* SSLClientSocketPool::SSLConnectJobFactory::NewConnectJob( const std::string& group_name, const PoolBase::Request& request, ConnectJob::Delegate* delegate) const { - return scoped_ptr<ConnectJob>( - new SSLConnectJob(group_name, request.params(), ConnectionTimeout(), - transport_pool_, socks_pool_, http_proxy_pool_, - client_socket_factory_, host_resolver_, - context_, delegate, net_log_)); + return new SSLConnectJob(group_name, request.params(), ConnectionTimeout(), + transport_pool_, socks_pool_, http_proxy_pool_, + client_socket_factory_, host_resolver_, + context_, delegate, net_log_); } base::TimeDelta @@ -574,9 +572,8 @@ void SSLClientSocketPool::CancelRequest(const std::string& group_name, } void SSLClientSocketPool::ReleaseSocket(const std::string& group_name, - scoped_ptr<StreamSocket> socket, - int id) { - base_.ReleaseSocket(group_name, socket.Pass(), id); + StreamSocket* socket, int id) { + base_.ReleaseSocket(group_name, socket, id); } void SSLClientSocketPool::FlushWithError(int error) { diff --git a/chromium/net/socket/ssl_client_socket_pool.h b/chromium/net/socket/ssl_client_socket_pool.h index 431a1b7ceea..bc54bc92f9a 100644 --- a/chromium/net/socket/ssl_client_socket_pool.h +++ b/chromium/net/socket/ssl_client_socket_pool.h @@ -204,7 +204,7 @@ class NET_EXPORT_PRIVATE SSLClientSocketPool ClientSocketHandle* handle) OVERRIDE; virtual void ReleaseSocket(const std::string& group_name, - scoped_ptr<StreamSocket> socket, + StreamSocket* socket, int id) OVERRIDE; virtual void FlushWithError(int error) OVERRIDE; @@ -261,7 +261,7 @@ class NET_EXPORT_PRIVATE SSLClientSocketPool virtual ~SSLConnectJobFactory() {} // ClientSocketPoolBase::ConnectJobFactory methods. - virtual scoped_ptr<ConnectJob> NewConnectJob( + virtual ConnectJob* NewConnectJob( const std::string& group_name, const PoolBase::Request& request, ConnectJob::Delegate* delegate) const OVERRIDE; diff --git a/chromium/net/socket/ssl_client_socket_unittest.cc b/chromium/net/socket/ssl_client_socket_unittest.cc index f791928580f..f0e7120a135 100644 --- a/chromium/net/socket/ssl_client_socket_unittest.cc +++ b/chromium/net/socket/ssl_client_socket_unittest.cc @@ -30,11 +30,9 @@ //----------------------------------------------------------------------------- -namespace net { - namespace { -const SSLConfig kDefaultSSLConfig; +const net::SSLConfig kDefaultSSLConfig; // WrappedStreamSocket is a base class that wraps an existing StreamSocket, // forwarding the Socket and StreamSocket interfaces to the underlying @@ -42,30 +40,33 @@ const SSLConfig kDefaultSSLConfig; // This is to provide a common base class for subclasses to override specific // StreamSocket methods for testing, while still communicating with a 'real' // StreamSocket. -class WrappedStreamSocket : public StreamSocket { +class WrappedStreamSocket : public net::StreamSocket { public: - explicit WrappedStreamSocket(scoped_ptr<StreamSocket> transport) - : transport_(transport.Pass()) {} + explicit WrappedStreamSocket(scoped_ptr<net::StreamSocket> transport) + : transport_(transport.Pass()) { + } virtual ~WrappedStreamSocket() {} // StreamSocket implementation: - virtual int Connect(const CompletionCallback& callback) OVERRIDE { + virtual int Connect(const net::CompletionCallback& callback) OVERRIDE { return transport_->Connect(callback); } - virtual void Disconnect() OVERRIDE { transport_->Disconnect(); } + virtual void Disconnect() OVERRIDE { + transport_->Disconnect(); + } virtual bool IsConnected() const OVERRIDE { return transport_->IsConnected(); } virtual bool IsConnectedAndIdle() const OVERRIDE { return transport_->IsConnectedAndIdle(); } - virtual int GetPeerAddress(IPEndPoint* address) const OVERRIDE { + virtual int GetPeerAddress(net::IPEndPoint* address) const OVERRIDE { return transport_->GetPeerAddress(address); } - virtual int GetLocalAddress(IPEndPoint* address) const OVERRIDE { + virtual int GetLocalAddress(net::IPEndPoint* address) const OVERRIDE { return transport_->GetLocalAddress(address); } - virtual const BoundNetLog& NetLog() const OVERRIDE { + virtual const net::BoundNetLog& NetLog() const OVERRIDE { return transport_->NetLog(); } virtual void SetSubresourceSpeculation() OVERRIDE { @@ -83,22 +84,20 @@ class WrappedStreamSocket : public StreamSocket { virtual bool WasNpnNegotiated() const OVERRIDE { return transport_->WasNpnNegotiated(); } - virtual NextProto GetNegotiatedProtocol() const OVERRIDE { + virtual net::NextProto GetNegotiatedProtocol() const OVERRIDE { return transport_->GetNegotiatedProtocol(); } - virtual bool GetSSLInfo(SSLInfo* ssl_info) OVERRIDE { + virtual bool GetSSLInfo(net::SSLInfo* ssl_info) OVERRIDE { return transport_->GetSSLInfo(ssl_info); } // Socket implementation: - virtual int Read(IOBuffer* buf, - int buf_len, - const CompletionCallback& callback) OVERRIDE { + virtual int Read(net::IOBuffer* buf, int buf_len, + const net::CompletionCallback& callback) OVERRIDE { return transport_->Read(buf, buf_len, callback); } - virtual int Write(IOBuffer* buf, - int buf_len, - const CompletionCallback& callback) OVERRIDE { + virtual int Write(net::IOBuffer* buf, int buf_len, + const net::CompletionCallback& callback) OVERRIDE { return transport_->Write(buf, buf_len, callback); } virtual bool SetReceiveBufferSize(int32 size) OVERRIDE { @@ -109,7 +108,7 @@ class WrappedStreamSocket : public StreamSocket { } protected: - scoped_ptr<StreamSocket> transport_; + scoped_ptr<net::StreamSocket> transport_; }; // ReadBufferingStreamSocket is a wrapper for an existing StreamSocket that @@ -120,13 +119,12 @@ class WrappedStreamSocket : public StreamSocket { // them from the TestServer. class ReadBufferingStreamSocket : public WrappedStreamSocket { public: - explicit ReadBufferingStreamSocket(scoped_ptr<StreamSocket> transport); + explicit ReadBufferingStreamSocket(scoped_ptr<net::StreamSocket> transport); virtual ~ReadBufferingStreamSocket() {} // Socket implementation: - virtual int Read(IOBuffer* buf, - int buf_len, - const CompletionCallback& callback) OVERRIDE; + virtual int Read(net::IOBuffer* buf, int buf_len, + const net::CompletionCallback& callback) OVERRIDE; // Sets the internal buffer to |size|. This must not be greater than // the largest value supplied to Read() - that is, it does not handle @@ -150,18 +148,19 @@ class ReadBufferingStreamSocket : public WrappedStreamSocket { void OnReadCompleted(int result); State state_; - scoped_refptr<GrowableIOBuffer> read_buffer_; + scoped_refptr<net::GrowableIOBuffer> read_buffer_; int buffer_size_; - scoped_refptr<IOBuffer> user_read_buf_; - CompletionCallback user_read_callback_; + scoped_refptr<net::IOBuffer> user_read_buf_; + net::CompletionCallback user_read_callback_; }; ReadBufferingStreamSocket::ReadBufferingStreamSocket( - scoped_ptr<StreamSocket> transport) + scoped_ptr<net::StreamSocket> transport) : WrappedStreamSocket(transport.Pass()), - read_buffer_(new GrowableIOBuffer()), - buffer_size_(0) {} + read_buffer_(new net::GrowableIOBuffer()), + buffer_size_(0) { +} void ReadBufferingStreamSocket::SetBufferSize(int size) { DCHECK(!user_read_buf_.get()); @@ -169,19 +168,19 @@ void ReadBufferingStreamSocket::SetBufferSize(int size) { read_buffer_->SetCapacity(size); } -int ReadBufferingStreamSocket::Read(IOBuffer* buf, +int ReadBufferingStreamSocket::Read(net::IOBuffer* buf, int buf_len, - const CompletionCallback& callback) { + const net::CompletionCallback& callback) { if (buffer_size_ == 0) return transport_->Read(buf, buf_len, callback); if (buf_len < buffer_size_) - return ERR_UNEXPECTED; + return net::ERR_UNEXPECTED; state_ = STATE_READ; user_read_buf_ = buf; - int result = DoLoop(OK); - if (result == ERR_IO_PENDING) + int result = DoLoop(net::OK); + if (result == net::ERR_IO_PENDING) user_read_callback_ = callback; else user_read_buf_ = NULL; @@ -203,10 +202,10 @@ int ReadBufferingStreamSocket::DoLoop(int result) { case STATE_NONE: default: NOTREACHED() << "Unexpected state: " << current_state; - rv = ERR_UNEXPECTED; + rv = net::ERR_UNEXPECTED; break; } - } while (rv != ERR_IO_PENDING && state_ != STATE_NONE); + } while (rv != net::ERR_IO_PENDING && state_ != STATE_NONE); return rv; } @@ -228,11 +227,10 @@ int ReadBufferingStreamSocket::DoReadComplete(int result) { read_buffer_->set_offset(read_buffer_->offset() + result); if (read_buffer_->RemainingCapacity() > 0) { state_ = STATE_READ; - return OK; + return net::OK; } - memcpy(user_read_buf_->data(), - read_buffer_->StartOfBuffer(), + memcpy(user_read_buf_->data(), read_buffer_->StartOfBuffer(), read_buffer_->capacity()); read_buffer_->set_offset(0); return read_buffer_->capacity(); @@ -240,7 +238,7 @@ int ReadBufferingStreamSocket::DoReadComplete(int result) { void ReadBufferingStreamSocket::OnReadCompleted(int result) { result = DoLoop(result); - if (result == ERR_IO_PENDING) + if (result == net::ERR_IO_PENDING) return; user_read_buf_ = NULL; @@ -254,18 +252,16 @@ class SynchronousErrorStreamSocket : public WrappedStreamSocket { virtual ~SynchronousErrorStreamSocket() {} // Socket implementation: - virtual int Read(IOBuffer* buf, - int buf_len, - const CompletionCallback& callback) OVERRIDE; - virtual int Write(IOBuffer* buf, - int buf_len, - const CompletionCallback& callback) OVERRIDE; + virtual int Read(net::IOBuffer* buf, int buf_len, + const net::CompletionCallback& callback) OVERRIDE; + virtual int Write(net::IOBuffer* buf, int buf_len, + const net::CompletionCallback& callback) OVERRIDE; // Sets the next Read() call and all future calls to return |error|. // If there is already a pending asynchronous read, the configured error // will not be returned until that asynchronous read has completed and Read() // is called again. - void SetNextReadError(Error error) { + void SetNextReadError(net::Error error) { DCHECK_GE(0, error); have_read_error_ = true; pending_read_error_ = error; @@ -275,7 +271,7 @@ class SynchronousErrorStreamSocket : public WrappedStreamSocket { // If there is already a pending asynchronous write, the configured error // will not be returned until that asynchronous write has completed and // Write() is called again. - void SetNextWriteError(Error error) { + void SetNextWriteError(net::Error error) { DCHECK_GE(0, error); have_write_error_ = true; pending_write_error_ = error; @@ -295,21 +291,24 @@ SynchronousErrorStreamSocket::SynchronousErrorStreamSocket( scoped_ptr<StreamSocket> transport) : WrappedStreamSocket(transport.Pass()), have_read_error_(false), - pending_read_error_(OK), + pending_read_error_(net::OK), have_write_error_(false), - pending_write_error_(OK) {} + pending_write_error_(net::OK) { +} -int SynchronousErrorStreamSocket::Read(IOBuffer* buf, - int buf_len, - const CompletionCallback& callback) { +int SynchronousErrorStreamSocket::Read( + net::IOBuffer* buf, + int buf_len, + const net::CompletionCallback& callback) { if (have_read_error_) return pending_read_error_; return transport_->Read(buf, buf_len, callback); } -int SynchronousErrorStreamSocket::Write(IOBuffer* buf, - int buf_len, - const CompletionCallback& callback) { +int SynchronousErrorStreamSocket::Write( + net::IOBuffer* buf, + int buf_len, + const net::CompletionCallback& callback) { if (have_write_error_) return pending_write_error_; return transport_->Write(buf, buf_len, callback); @@ -325,14 +324,12 @@ class FakeBlockingStreamSocket : public WrappedStreamSocket { virtual ~FakeBlockingStreamSocket() {} // Socket implementation: - virtual int Read(IOBuffer* buf, - int buf_len, - const CompletionCallback& callback) OVERRIDE { + virtual int Read(net::IOBuffer* buf, int buf_len, + const net::CompletionCallback& callback) OVERRIDE { return read_state_.RunWrappedFunction(buf, buf_len, callback); } - virtual int Write(IOBuffer* buf, - int buf_len, - const CompletionCallback& callback) OVERRIDE { + virtual int Write(net::IOBuffer* buf, int buf_len, + const net::CompletionCallback& callback) OVERRIDE { return write_state_.RunWrappedFunction(buf, buf_len, callback); } @@ -353,8 +350,9 @@ class FakeBlockingStreamSocket : public WrappedStreamSocket { class BlockingState { public: // Wrapper for the underlying Socket function to call (ie: Read/Write). - typedef base::Callback<int(IOBuffer*, int, const CompletionCallback&)> - WrappedSocketFunction; + typedef base::Callback< + int(net::IOBuffer*, int, + const net::CompletionCallback&)> WrappedSocketFunction; explicit BlockingState(const WrappedSocketFunction& function); ~BlockingState() {} @@ -373,9 +371,8 @@ class FakeBlockingStreamSocket : public WrappedStreamSocket { // Performs the wrapped socket function on the underlying transport. If // configured to block via SetShouldBlock(), then |user_callback| will not // be invoked until Unblock() has been called. - int RunWrappedFunction(IOBuffer* buf, - int len, - const CompletionCallback& user_callback); + int RunWrappedFunction(net::IOBuffer* buf, int len, + const net::CompletionCallback& user_callback); private: // Handles completion from the underlying wrapped socket function. @@ -385,7 +382,7 @@ class FakeBlockingStreamSocket : public WrappedStreamSocket { bool should_block_; bool have_result_; int pending_result_; - CompletionCallback user_callback_; + net::CompletionCallback user_callback_; }; BlockingState read_state_; @@ -400,14 +397,16 @@ FakeBlockingStreamSocket::FakeBlockingStreamSocket( read_state_(base::Bind(&Socket::Read, base::Unretained(transport_.get()))), write_state_(base::Bind(&Socket::Write, - base::Unretained(transport_.get()))) {} + base::Unretained(transport_.get()))) { +} FakeBlockingStreamSocket::BlockingState::BlockingState( const WrappedSocketFunction& function) : wrapped_function_(function), should_block_(false), have_result_(false), - pending_result_(OK) {} + pending_result_(net::OK) { +} void FakeBlockingStreamSocket::BlockingState::SetShouldBlock() { DCHECK(!should_block_); @@ -430,24 +429,24 @@ void FakeBlockingStreamSocket::BlockingState::Unblock() { } int FakeBlockingStreamSocket::BlockingState::RunWrappedFunction( - IOBuffer* buf, + net::IOBuffer* buf, int len, - const CompletionCallback& callback) { + const net::CompletionCallback& callback) { // The callback to be called by the underlying transport. Either forward // directly to the user's callback if not set to block, or intercept it with // OnCompleted so that the user's callback is not invoked until Unblock() is // called. - CompletionCallback transport_callback = + net::CompletionCallback transport_callback = !should_block_ ? callback : base::Bind(&BlockingState::OnCompleted, base::Unretained(this)); int rv = wrapped_function_.Run(buf, len, transport_callback); if (should_block_) { user_callback_ = callback; // May have completed synchronously. - have_result_ = (rv != ERR_IO_PENDING); + have_result_ = (rv != net::ERR_IO_PENDING); pending_result_ = rv; - return ERR_IO_PENDING; + return net::ERR_IO_PENDING; } return rv; @@ -467,61 +466,64 @@ void FakeBlockingStreamSocket::BlockingState::OnCompleted(int result) { base::ResetAndReturn(&user_callback_).Run(result); } -// CompletionCallback that will delete the associated StreamSocket when +// CompletionCallback that will delete the associated net::StreamSocket when // the callback is invoked. -class DeleteSocketCallback : public TestCompletionCallbackBase { +class DeleteSocketCallback : public net::TestCompletionCallbackBase { public: - explicit DeleteSocketCallback(StreamSocket* socket) + explicit DeleteSocketCallback(net::StreamSocket* socket) : socket_(socket), callback_(base::Bind(&DeleteSocketCallback::OnComplete, - base::Unretained(this))) {} + base::Unretained(this))) { + } virtual ~DeleteSocketCallback() {} - const CompletionCallback& callback() const { return callback_; } + const net::CompletionCallback& callback() const { return callback_; } private: void OnComplete(int result) { - if (socket_) { - delete socket_; - socket_ = NULL; - } else { - ADD_FAILURE() << "Deleting socket twice"; - } - SetResult(result); + if (socket_) { + delete socket_; + socket_ = NULL; + } else { + ADD_FAILURE() << "Deleting socket twice"; + } + SetResult(result); } - StreamSocket* socket_; - CompletionCallback callback_; + net::StreamSocket* socket_; + net::CompletionCallback callback_; DISALLOW_COPY_AND_ASSIGN(DeleteSocketCallback); }; +} // namespace + class SSLClientSocketTest : public PlatformTest { public: SSLClientSocketTest() - : socket_factory_(ClientSocketFactory::GetDefaultFactory()), - cert_verifier_(new MockCertVerifier), - transport_security_state_(new TransportSecurityState) { - cert_verifier_->set_default_result(OK); + : socket_factory_(net::ClientSocketFactory::GetDefaultFactory()), + cert_verifier_(new net::MockCertVerifier), + transport_security_state_(new net::TransportSecurityState) { + cert_verifier_->set_default_result(net::OK); context_.cert_verifier = cert_verifier_.get(); context_.transport_security_state = transport_security_state_.get(); } protected: - scoped_ptr<SSLClientSocket> CreateSSLClientSocket( - scoped_ptr<StreamSocket> transport_socket, - const HostPortPair& host_and_port, - const SSLConfig& ssl_config) { - scoped_ptr<ClientSocketHandle> connection(new ClientSocketHandle); - connection->SetSocket(transport_socket.Pass()); - return socket_factory_->CreateSSLClientSocket( - connection.Pass(), host_and_port, ssl_config, context_); + net::SSLClientSocket* CreateSSLClientSocket( + net::StreamSocket* transport_socket, + const net::HostPortPair& host_and_port, + const net::SSLConfig& ssl_config) { + return socket_factory_->CreateSSLClientSocket(transport_socket, + host_and_port, + ssl_config, + context_); } - ClientSocketFactory* socket_factory_; - scoped_ptr<MockCertVerifier> cert_verifier_; - scoped_ptr<TransportSecurityState> transport_security_state_; - SSLClientSocketContext context_; + net::ClientSocketFactory* socket_factory_; + scoped_ptr<net::MockCertVerifier> cert_verifier_; + scoped_ptr<net::TransportSecurityState> transport_security_state_; + net::SSLClientSocketContext context_; }; //----------------------------------------------------------------------------- @@ -534,45 +536,45 @@ class SSLClientSocketTest : public PlatformTest { // timeout. This means that an SSL connect end event may appear as a socket // write. static bool LogContainsSSLConnectEndEvent( - const CapturingNetLog::CapturedEntryList& log, - int i) { - return LogContainsEndEvent(log, i, NetLog::TYPE_SSL_CONNECT) || - LogContainsEvent( - log, i, NetLog::TYPE_SOCKET_BYTES_SENT, NetLog::PHASE_NONE); -} -; + const net::CapturingNetLog::CapturedEntryList& log, int i) { + return net::LogContainsEndEvent(log, i, net::NetLog::TYPE_SSL_CONNECT) || + net::LogContainsEvent(log, i, net::NetLog::TYPE_SOCKET_BYTES_SENT, + net::NetLog::PHASE_NONE); +}; TEST_F(SSLClientSocketTest, Connect) { - SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS, - SpawnedTestServer::kLocalhost, - base::FilePath()); + net::SpawnedTestServer test_server(net::SpawnedTestServer::TYPE_HTTPS, + net::SpawnedTestServer::kLocalhost, + base::FilePath()); ASSERT_TRUE(test_server.Start()); - AddressList addr; + net::AddressList addr; ASSERT_TRUE(test_server.GetAddressList(&addr)); - TestCompletionCallback callback; - CapturingNetLog log; - scoped_ptr<StreamSocket> transport( - new TCPClientSocket(addr, &log, NetLog::Source())); + net::TestCompletionCallback callback; + net::CapturingNetLog log; + net::StreamSocket* transport = new net::TCPClientSocket( + addr, &log, net::NetLog::Source()); int rv = transport->Connect(callback.callback()); - if (rv == ERR_IO_PENDING) + if (rv == net::ERR_IO_PENDING) rv = callback.WaitForResult(); - EXPECT_EQ(OK, rv); + EXPECT_EQ(net::OK, rv); - scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket( - transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig)); + scoped_ptr<net::SSLClientSocket> sock( + CreateSSLClientSocket(transport, test_server.host_port_pair(), + kDefaultSSLConfig)); EXPECT_FALSE(sock->IsConnected()); rv = sock->Connect(callback.callback()); - CapturingNetLog::CapturedEntryList entries; + net::CapturingNetLog::CapturedEntryList entries; log.GetEntries(&entries); - EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT)); - if (rv == ERR_IO_PENDING) + EXPECT_TRUE(net::LogContainsBeginEvent( + entries, 5, net::NetLog::TYPE_SSL_CONNECT)); + if (rv == net::ERR_IO_PENDING) rv = callback.WaitForResult(); - EXPECT_EQ(OK, rv); + EXPECT_EQ(net::OK, rv); EXPECT_TRUE(sock->IsConnected()); log.GetEntries(&entries); EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1)); @@ -582,40 +584,43 @@ TEST_F(SSLClientSocketTest, Connect) { } TEST_F(SSLClientSocketTest, ConnectExpired) { - SpawnedTestServer::SSLOptions ssl_options( - SpawnedTestServer::SSLOptions::CERT_EXPIRED); - SpawnedTestServer test_server( - SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath()); + net::SpawnedTestServer::SSLOptions ssl_options( + net::SpawnedTestServer::SSLOptions::CERT_EXPIRED); + net::SpawnedTestServer test_server(net::SpawnedTestServer::TYPE_HTTPS, + ssl_options, + base::FilePath()); ASSERT_TRUE(test_server.Start()); - cert_verifier_->set_default_result(ERR_CERT_DATE_INVALID); + cert_verifier_->set_default_result(net::ERR_CERT_DATE_INVALID); - AddressList addr; + net::AddressList addr; ASSERT_TRUE(test_server.GetAddressList(&addr)); - TestCompletionCallback callback; - CapturingNetLog log; - scoped_ptr<StreamSocket> transport( - new TCPClientSocket(addr, &log, NetLog::Source())); + net::TestCompletionCallback callback; + net::CapturingNetLog log; + net::StreamSocket* transport = new net::TCPClientSocket( + addr, &log, net::NetLog::Source()); int rv = transport->Connect(callback.callback()); - if (rv == ERR_IO_PENDING) + if (rv == net::ERR_IO_PENDING) rv = callback.WaitForResult(); - EXPECT_EQ(OK, rv); + EXPECT_EQ(net::OK, rv); - scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket( - transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig)); + scoped_ptr<net::SSLClientSocket> sock( + CreateSSLClientSocket(transport, test_server.host_port_pair(), + kDefaultSSLConfig)); EXPECT_FALSE(sock->IsConnected()); rv = sock->Connect(callback.callback()); - CapturingNetLog::CapturedEntryList entries; + net::CapturingNetLog::CapturedEntryList entries; log.GetEntries(&entries); - EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT)); - if (rv == ERR_IO_PENDING) + EXPECT_TRUE(net::LogContainsBeginEvent( + entries, 5, net::NetLog::TYPE_SSL_CONNECT)); + if (rv == net::ERR_IO_PENDING) rv = callback.WaitForResult(); - EXPECT_EQ(ERR_CERT_DATE_INVALID, rv); + EXPECT_EQ(net::ERR_CERT_DATE_INVALID, rv); // Rather than testing whether or not the underlying socket is connected, // test that the handshake has finished. This is because it may be @@ -626,40 +631,43 @@ TEST_F(SSLClientSocketTest, ConnectExpired) { } TEST_F(SSLClientSocketTest, ConnectMismatched) { - SpawnedTestServer::SSLOptions ssl_options( - SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME); - SpawnedTestServer test_server( - SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath()); + net::SpawnedTestServer::SSLOptions ssl_options( + net::SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME); + net::SpawnedTestServer test_server(net::SpawnedTestServer::TYPE_HTTPS, + ssl_options, + base::FilePath()); ASSERT_TRUE(test_server.Start()); - cert_verifier_->set_default_result(ERR_CERT_COMMON_NAME_INVALID); + cert_verifier_->set_default_result(net::ERR_CERT_COMMON_NAME_INVALID); - AddressList addr; + net::AddressList addr; ASSERT_TRUE(test_server.GetAddressList(&addr)); - TestCompletionCallback callback; - CapturingNetLog log; - scoped_ptr<StreamSocket> transport( - new TCPClientSocket(addr, &log, NetLog::Source())); + net::TestCompletionCallback callback; + net::CapturingNetLog log; + net::StreamSocket* transport = new net::TCPClientSocket( + addr, &log, net::NetLog::Source()); int rv = transport->Connect(callback.callback()); - if (rv == ERR_IO_PENDING) + if (rv == net::ERR_IO_PENDING) rv = callback.WaitForResult(); - EXPECT_EQ(OK, rv); + EXPECT_EQ(net::OK, rv); - scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket( - transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig)); + scoped_ptr<net::SSLClientSocket> sock( + CreateSSLClientSocket(transport, test_server.host_port_pair(), + kDefaultSSLConfig)); EXPECT_FALSE(sock->IsConnected()); rv = sock->Connect(callback.callback()); - CapturingNetLog::CapturedEntryList entries; + net::CapturingNetLog::CapturedEntryList entries; log.GetEntries(&entries); - EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT)); - if (rv == ERR_IO_PENDING) + EXPECT_TRUE(net::LogContainsBeginEvent( + entries, 5, net::NetLog::TYPE_SSL_CONNECT)); + if (rv == net::ERR_IO_PENDING) rv = callback.WaitForResult(); - EXPECT_EQ(ERR_CERT_COMMON_NAME_INVALID, rv); + EXPECT_EQ(net::ERR_CERT_COMMON_NAME_INVALID, rv); // Rather than testing whether or not the underlying socket is connected, // test that the handshake has finished. This is because it may be @@ -672,35 +680,38 @@ TEST_F(SSLClientSocketTest, ConnectMismatched) { // Attempt to connect to a page which requests a client certificate. It should // return an error code on connect. TEST_F(SSLClientSocketTest, ConnectClientAuthCertRequested) { - SpawnedTestServer::SSLOptions ssl_options; + net::SpawnedTestServer::SSLOptions ssl_options; ssl_options.request_client_certificate = true; - SpawnedTestServer test_server( - SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath()); + net::SpawnedTestServer test_server(net::SpawnedTestServer::TYPE_HTTPS, + ssl_options, + base::FilePath()); ASSERT_TRUE(test_server.Start()); - AddressList addr; + net::AddressList addr; ASSERT_TRUE(test_server.GetAddressList(&addr)); - TestCompletionCallback callback; - CapturingNetLog log; - scoped_ptr<StreamSocket> transport( - new TCPClientSocket(addr, &log, NetLog::Source())); + net::TestCompletionCallback callback; + net::CapturingNetLog log; + net::StreamSocket* transport = new net::TCPClientSocket( + addr, &log, net::NetLog::Source()); int rv = transport->Connect(callback.callback()); - if (rv == ERR_IO_PENDING) + if (rv == net::ERR_IO_PENDING) rv = callback.WaitForResult(); - EXPECT_EQ(OK, rv); + EXPECT_EQ(net::OK, rv); - scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket( - transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig)); + scoped_ptr<net::SSLClientSocket> sock( + CreateSSLClientSocket(transport, test_server.host_port_pair(), + kDefaultSSLConfig)); EXPECT_FALSE(sock->IsConnected()); rv = sock->Connect(callback.callback()); - CapturingNetLog::CapturedEntryList entries; + net::CapturingNetLog::CapturedEntryList entries; log.GetEntries(&entries); - EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT)); - if (rv == ERR_IO_PENDING) + EXPECT_TRUE(net::LogContainsBeginEvent( + entries, 5, net::NetLog::TYPE_SSL_CONNECT)); + if (rv == net::ERR_IO_PENDING) rv = callback.WaitForResult(); log.GetEntries(&entries); @@ -720,9 +731,9 @@ TEST_F(SSLClientSocketTest, ConnectClientAuthCertRequested) { // certificate. This test may still be useful as we'll want to close // the socket on a timeout if the user takes a long time to pick a // cert. Related bug: https://bugzilla.mozilla.org/show_bug.cgi?id=542832 - ExpectLogContainsSomewhere( - entries, 0, NetLog::TYPE_SSL_CONNECT, NetLog::PHASE_END); - EXPECT_EQ(ERR_SSL_CLIENT_AUTH_CERT_NEEDED, rv); + net::ExpectLogContainsSomewhere( + entries, 0, net::NetLog::TYPE_SSL_CONNECT, net::NetLog::PHASE_END); + EXPECT_EQ(net::ERR_SSL_CLIENT_AUTH_CERT_NEEDED, rv); EXPECT_FALSE(sock->IsConnected()); } @@ -731,30 +742,32 @@ TEST_F(SSLClientSocketTest, ConnectClientAuthCertRequested) { // // TODO(davidben): Also test providing an actual certificate. TEST_F(SSLClientSocketTest, ConnectClientAuthSendNullCert) { - SpawnedTestServer::SSLOptions ssl_options; + net::SpawnedTestServer::SSLOptions ssl_options; ssl_options.request_client_certificate = true; - SpawnedTestServer test_server( - SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath()); + net::SpawnedTestServer test_server(net::SpawnedTestServer::TYPE_HTTPS, + ssl_options, + base::FilePath()); ASSERT_TRUE(test_server.Start()); - AddressList addr; + net::AddressList addr; ASSERT_TRUE(test_server.GetAddressList(&addr)); - TestCompletionCallback callback; - CapturingNetLog log; - scoped_ptr<StreamSocket> transport( - new TCPClientSocket(addr, &log, NetLog::Source())); + net::TestCompletionCallback callback; + net::CapturingNetLog log; + net::StreamSocket* transport = new net::TCPClientSocket( + addr, &log, net::NetLog::Source()); int rv = transport->Connect(callback.callback()); - if (rv == ERR_IO_PENDING) + if (rv == net::ERR_IO_PENDING) rv = callback.WaitForResult(); - EXPECT_EQ(OK, rv); + EXPECT_EQ(net::OK, rv); - SSLConfig ssl_config = kDefaultSSLConfig; + net::SSLConfig ssl_config = kDefaultSSLConfig; ssl_config.send_client_cert = true; ssl_config.client_cert = NULL; - scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket( - transport.Pass(), test_server.host_port_pair(), ssl_config)); + scoped_ptr<net::SSLClientSocket> sock( + CreateSSLClientSocket(transport, test_server.host_port_pair(), + ssl_config)); EXPECT_FALSE(sock->IsConnected()); @@ -762,13 +775,14 @@ TEST_F(SSLClientSocketTest, ConnectClientAuthSendNullCert) { // TODO(davidben): Add a test which requires them and verify the error. rv = sock->Connect(callback.callback()); - CapturingNetLog::CapturedEntryList entries; + net::CapturingNetLog::CapturedEntryList entries; log.GetEntries(&entries); - EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT)); - if (rv == ERR_IO_PENDING) + EXPECT_TRUE(net::LogContainsBeginEvent( + entries, 5, net::NetLog::TYPE_SSL_CONNECT)); + if (rv == net::ERR_IO_PENDING) rv = callback.WaitForResult(); - EXPECT_EQ(OK, rv); + EXPECT_EQ(net::OK, rv); EXPECT_TRUE(sock->IsConnected()); log.GetEntries(&entries); EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1)); @@ -776,7 +790,7 @@ TEST_F(SSLClientSocketTest, ConnectClientAuthSendNullCert) { // We responded to the server's certificate request with a Certificate // message with no client certificate in it. ssl_info.client_cert_sent // should be false in this case. - SSLInfo ssl_info; + net::SSLInfo ssl_info; sock->GetSSLInfo(&ssl_info); EXPECT_FALSE(ssl_info.client_cert_sent); @@ -790,50 +804,51 @@ TEST_F(SSLClientSocketTest, ConnectClientAuthSendNullCert) { // - Server sends data unexpectedly. TEST_F(SSLClientSocketTest, Read) { - SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS, - SpawnedTestServer::kLocalhost, - base::FilePath()); + net::SpawnedTestServer test_server(net::SpawnedTestServer::TYPE_HTTPS, + net::SpawnedTestServer::kLocalhost, + base::FilePath()); ASSERT_TRUE(test_server.Start()); - AddressList addr; + net::AddressList addr; ASSERT_TRUE(test_server.GetAddressList(&addr)); - TestCompletionCallback callback; - scoped_ptr<StreamSocket> transport( - new TCPClientSocket(addr, NULL, NetLog::Source())); + net::TestCompletionCallback callback; + net::StreamSocket* transport = new net::TCPClientSocket( + addr, NULL, net::NetLog::Source()); int rv = transport->Connect(callback.callback()); - if (rv == ERR_IO_PENDING) + if (rv == net::ERR_IO_PENDING) rv = callback.WaitForResult(); - EXPECT_EQ(OK, rv); + EXPECT_EQ(net::OK, rv); - scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket( - transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig)); + scoped_ptr<net::SSLClientSocket> sock( + CreateSSLClientSocket(transport, test_server.host_port_pair(), + kDefaultSSLConfig)); rv = sock->Connect(callback.callback()); - if (rv == ERR_IO_PENDING) + if (rv == net::ERR_IO_PENDING) rv = callback.WaitForResult(); - EXPECT_EQ(OK, rv); + EXPECT_EQ(net::OK, rv); EXPECT_TRUE(sock->IsConnected()); const char request_text[] = "GET / HTTP/1.0\r\n\r\n"; - scoped_refptr<IOBuffer> request_buffer( - new IOBuffer(arraysize(request_text) - 1)); + scoped_refptr<net::IOBuffer> request_buffer( + new net::IOBuffer(arraysize(request_text) - 1)); memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1); rv = sock->Write( request_buffer.get(), arraysize(request_text) - 1, callback.callback()); - EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING); + EXPECT_TRUE(rv >= 0 || rv == net::ERR_IO_PENDING); - if (rv == ERR_IO_PENDING) + if (rv == net::ERR_IO_PENDING) rv = callback.WaitForResult(); EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv); - scoped_refptr<IOBuffer> buf(new IOBuffer(4096)); + scoped_refptr<net::IOBuffer> buf(new net::IOBuffer(4096)); for (;;) { rv = sock->Read(buf.get(), 4096, callback.callback()); - EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING); + EXPECT_TRUE(rv >= 0 || rv == net::ERR_IO_PENDING); - if (rv == ERR_IO_PENDING) + if (rv == net::ERR_IO_PENDING) rv = callback.WaitForResult(); EXPECT_GE(rv, 0); @@ -847,40 +862,39 @@ TEST_F(SSLClientSocketTest, Read) { // the socket connection uncleanly. // This is a regression test for http://crbug.com/238536 TEST_F(SSLClientSocketTest, Read_WithSynchronousError) { - SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS, - SpawnedTestServer::kLocalhost, - base::FilePath()); + net::SpawnedTestServer test_server(net::SpawnedTestServer::TYPE_HTTPS, + net::SpawnedTestServer::kLocalhost, + base::FilePath()); ASSERT_TRUE(test_server.Start()); - AddressList addr; + net::AddressList addr; ASSERT_TRUE(test_server.GetAddressList(&addr)); - TestCompletionCallback callback; - scoped_ptr<StreamSocket> real_transport( - new TCPClientSocket(addr, NULL, NetLog::Source())); - scoped_ptr<SynchronousErrorStreamSocket> transport( - new SynchronousErrorStreamSocket(real_transport.Pass())); + net::TestCompletionCallback callback; + scoped_ptr<net::StreamSocket> real_transport(new net::TCPClientSocket( + addr, NULL, net::NetLog::Source())); + SynchronousErrorStreamSocket* transport = new SynchronousErrorStreamSocket( + real_transport.Pass()); int rv = callback.GetResult(transport->Connect(callback.callback())); - EXPECT_EQ(OK, rv); + EXPECT_EQ(net::OK, rv); // Disable TLS False Start to avoid handshake non-determinism. - SSLConfig ssl_config; + net::SSLConfig ssl_config; ssl_config.false_start_enabled = false; - SynchronousErrorStreamSocket* raw_transport = transport.get(); - scoped_ptr<SSLClientSocket> sock( - CreateSSLClientSocket(transport.PassAs<StreamSocket>(), - test_server.host_port_pair(), + scoped_ptr<net::SSLClientSocket> sock( + CreateSSLClientSocket(transport, test_server.host_port_pair(), ssl_config)); rv = callback.GetResult(sock->Connect(callback.callback())); - EXPECT_EQ(OK, rv); + EXPECT_EQ(net::OK, rv); EXPECT_TRUE(sock->IsConnected()); const char request_text[] = "GET / HTTP/1.0\r\n\r\n"; static const int kRequestTextSize = static_cast<int>(arraysize(request_text) - 1); - scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize)); + scoped_refptr<net::IOBuffer> request_buffer( + new net::IOBuffer(kRequestTextSize)); memcpy(request_buffer->data(), request_text, kRequestTextSize); rv = callback.GetResult( @@ -888,9 +902,9 @@ TEST_F(SSLClientSocketTest, Read_WithSynchronousError) { EXPECT_EQ(kRequestTextSize, rv); // Simulate an unclean/forcible shutdown. - raw_transport->SetNextReadError(ERR_CONNECTION_RESET); + transport->SetNextReadError(net::ERR_CONNECTION_RESET); - scoped_refptr<IOBuffer> buf(new IOBuffer(4096)); + scoped_refptr<net::IOBuffer> buf(new net::IOBuffer(4096)); // Note: This test will hang if this bug has regressed. Simply checking that // rv != ERR_IO_PENDING is insufficient, as ERR_IO_PENDING is a legitimate @@ -899,7 +913,7 @@ TEST_F(SSLClientSocketTest, Read_WithSynchronousError) { #if !defined(USE_OPENSSL) // SSLClientSocketNSS records the error exactly - EXPECT_EQ(ERR_CONNECTION_RESET, rv); + EXPECT_EQ(net::ERR_CONNECTION_RESET, rv); #else // SSLClientSocketOpenSSL treats any errors as a simple EOF. EXPECT_EQ(0, rv); @@ -911,51 +925,49 @@ TEST_F(SSLClientSocketTest, Read_WithSynchronousError) { // intermediary terminates the socket connection uncleanly. // This is a regression test for http://crbug.com/249848 TEST_F(SSLClientSocketTest, Write_WithSynchronousError) { - SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS, - SpawnedTestServer::kLocalhost, - base::FilePath()); + net::SpawnedTestServer test_server(net::SpawnedTestServer::TYPE_HTTPS, + net::SpawnedTestServer::kLocalhost, + base::FilePath()); ASSERT_TRUE(test_server.Start()); - AddressList addr; + net::AddressList addr; ASSERT_TRUE(test_server.GetAddressList(&addr)); - TestCompletionCallback callback; - scoped_ptr<StreamSocket> real_transport( - new TCPClientSocket(addr, NULL, NetLog::Source())); - // Note: |error_socket|'s ownership is handed to |transport|, but a pointer + net::TestCompletionCallback callback; + scoped_ptr<net::StreamSocket> real_transport(new net::TCPClientSocket( + addr, NULL, net::NetLog::Source())); + // Note: |error_socket|'s ownership is handed to |transport|, but the pointer // is retained in order to configure additional errors. - scoped_ptr<SynchronousErrorStreamSocket> error_socket( - new SynchronousErrorStreamSocket(real_transport.Pass())); - SynchronousErrorStreamSocket* raw_error_socket = error_socket.get(); - scoped_ptr<FakeBlockingStreamSocket> transport( - new FakeBlockingStreamSocket(error_socket.PassAs<StreamSocket>())); - FakeBlockingStreamSocket* raw_transport = transport.get(); + SynchronousErrorStreamSocket* error_socket = new SynchronousErrorStreamSocket( + real_transport.Pass()); + FakeBlockingStreamSocket* transport = new FakeBlockingStreamSocket( + scoped_ptr<net::StreamSocket>(error_socket)); int rv = callback.GetResult(transport->Connect(callback.callback())); - EXPECT_EQ(OK, rv); + EXPECT_EQ(net::OK, rv); // Disable TLS False Start to avoid handshake non-determinism. - SSLConfig ssl_config; + net::SSLConfig ssl_config; ssl_config.false_start_enabled = false; - scoped_ptr<SSLClientSocket> sock( - CreateSSLClientSocket(transport.PassAs<StreamSocket>(), - test_server.host_port_pair(), + scoped_ptr<net::SSLClientSocket> sock( + CreateSSLClientSocket(transport, test_server.host_port_pair(), ssl_config)); rv = callback.GetResult(sock->Connect(callback.callback())); - EXPECT_EQ(OK, rv); + EXPECT_EQ(net::OK, rv); EXPECT_TRUE(sock->IsConnected()); const char request_text[] = "GET / HTTP/1.0\r\n\r\n"; static const int kRequestTextSize = static_cast<int>(arraysize(request_text) - 1); - scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize)); + scoped_refptr<net::IOBuffer> request_buffer( + new net::IOBuffer(kRequestTextSize)); memcpy(request_buffer->data(), request_text, kRequestTextSize); // Simulate an unclean/forcible shutdown on the underlying socket. // However, simulate this error asynchronously. - raw_error_socket->SetNextWriteError(ERR_CONNECTION_RESET); - raw_transport->SetNextWriteShouldBlock(); + error_socket->SetNextWriteError(net::ERR_CONNECTION_RESET); + transport->SetNextWriteShouldBlock(); // This write should complete synchronously, because the TLS ciphertext // can be created and placed into the outgoing buffers independent of the @@ -964,14 +976,14 @@ TEST_F(SSLClientSocketTest, Write_WithSynchronousError) { sock->Write(request_buffer.get(), kRequestTextSize, callback.callback())); EXPECT_EQ(kRequestTextSize, rv); - scoped_refptr<IOBuffer> buf(new IOBuffer(4096)); + scoped_refptr<net::IOBuffer> buf(new net::IOBuffer(4096)); rv = sock->Read(buf.get(), 4096, callback.callback()); - EXPECT_EQ(ERR_IO_PENDING, rv); + EXPECT_EQ(net::ERR_IO_PENDING, rv); // Now unblock the outgoing request, having it fail with the connection // being reset. - raw_transport->UnblockWrite(); + transport->UnblockWrite(); // Note: This will cause an inifite loop if this bug has regressed. Simply // checking that rv != ERR_IO_PENDING is insufficient, as ERR_IO_PENDING @@ -980,7 +992,7 @@ TEST_F(SSLClientSocketTest, Write_WithSynchronousError) { #if !defined(USE_OPENSSL) // SSLClientSocketNSS records the error exactly - EXPECT_EQ(ERR_CONNECTION_RESET, rv); + EXPECT_EQ(net::ERR_CONNECTION_RESET, rv); #else // SSLClientSocketOpenSSL treats any errors as a simple EOF. EXPECT_EQ(0, rv); @@ -990,37 +1002,38 @@ TEST_F(SSLClientSocketTest, Write_WithSynchronousError) { // Test the full duplex mode, with Read and Write pending at the same time. // This test also serves as a regression test for http://crbug.com/29815. TEST_F(SSLClientSocketTest, Read_FullDuplex) { - SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS, - SpawnedTestServer::kLocalhost, - base::FilePath()); + net::SpawnedTestServer test_server(net::SpawnedTestServer::TYPE_HTTPS, + net::SpawnedTestServer::kLocalhost, + base::FilePath()); ASSERT_TRUE(test_server.Start()); - AddressList addr; + net::AddressList addr; ASSERT_TRUE(test_server.GetAddressList(&addr)); - TestCompletionCallback callback; // Used for everything except Write. + net::TestCompletionCallback callback; // Used for everything except Write. - scoped_ptr<StreamSocket> transport( - new TCPClientSocket(addr, NULL, NetLog::Source())); + net::StreamSocket* transport = new net::TCPClientSocket( + addr, NULL, net::NetLog::Source()); int rv = transport->Connect(callback.callback()); - if (rv == ERR_IO_PENDING) + if (rv == net::ERR_IO_PENDING) rv = callback.WaitForResult(); - EXPECT_EQ(OK, rv); + EXPECT_EQ(net::OK, rv); - scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket( - transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig)); + scoped_ptr<net::SSLClientSocket> sock( + CreateSSLClientSocket(transport, test_server.host_port_pair(), + kDefaultSSLConfig)); rv = sock->Connect(callback.callback()); - if (rv == ERR_IO_PENDING) + if (rv == net::ERR_IO_PENDING) rv = callback.WaitForResult(); - EXPECT_EQ(OK, rv); + EXPECT_EQ(net::OK, rv); EXPECT_TRUE(sock->IsConnected()); // Issue a "hanging" Read first. - scoped_refptr<IOBuffer> buf(new IOBuffer(4096)); + scoped_refptr<net::IOBuffer> buf(new net::IOBuffer(4096)); rv = sock->Read(buf.get(), 4096, callback.callback()); // We haven't written the request, so there should be no response yet. - ASSERT_EQ(ERR_IO_PENDING, rv); + ASSERT_EQ(net::ERR_IO_PENDING, rv); // Write the request. // The request is padded with a User-Agent header to a size that causes the @@ -1030,14 +1043,15 @@ TEST_F(SSLClientSocketTest, Read_FullDuplex) { for (int i = 0; i < 3770; ++i) request_text.push_back('*'); request_text.append("\r\n\r\n"); - scoped_refptr<IOBuffer> request_buffer(new StringIOBuffer(request_text)); + scoped_refptr<net::IOBuffer> request_buffer( + new net::StringIOBuffer(request_text)); - TestCompletionCallback callback2; // Used for Write only. + net::TestCompletionCallback callback2; // Used for Write only. rv = sock->Write( request_buffer.get(), request_text.size(), callback2.callback()); - EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING); + EXPECT_TRUE(rv >= 0 || rv == net::ERR_IO_PENDING); - if (rv == ERR_IO_PENDING) + if (rv == net::ERR_IO_PENDING) rv = callback2.WaitForResult(); EXPECT_EQ(static_cast<int>(request_text.size()), rv); @@ -1053,65 +1067,62 @@ TEST_F(SSLClientSocketTest, Read_FullDuplex) { // callback, the Write() callback should not be invoked. // Regression test for http://crbug.com/232633 TEST_F(SSLClientSocketTest, Read_DeleteWhilePendingFullDuplex) { - SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS, - SpawnedTestServer::kLocalhost, - base::FilePath()); + net::SpawnedTestServer test_server(net::SpawnedTestServer::TYPE_HTTPS, + net::SpawnedTestServer::kLocalhost, + base::FilePath()); ASSERT_TRUE(test_server.Start()); - AddressList addr; + net::AddressList addr; ASSERT_TRUE(test_server.GetAddressList(&addr)); - TestCompletionCallback callback; - scoped_ptr<StreamSocket> real_transport( - new TCPClientSocket(addr, NULL, NetLog::Source())); - // Note: |error_socket|'s ownership is handed to |transport|, but a pointer + net::TestCompletionCallback callback; + scoped_ptr<net::StreamSocket> real_transport(new net::TCPClientSocket( + addr, NULL, net::NetLog::Source())); + // Note: |error_socket|'s ownership is handed to |transport|, but the pointer // is retained in order to configure additional errors. - scoped_ptr<SynchronousErrorStreamSocket> error_socket( - new SynchronousErrorStreamSocket(real_transport.Pass())); - SynchronousErrorStreamSocket* raw_error_socket = error_socket.get(); - scoped_ptr<FakeBlockingStreamSocket> transport( - new FakeBlockingStreamSocket(error_socket.PassAs<StreamSocket>())); - FakeBlockingStreamSocket* raw_transport = transport.get(); + SynchronousErrorStreamSocket* error_socket = new SynchronousErrorStreamSocket( + real_transport.Pass()); + FakeBlockingStreamSocket* transport = new FakeBlockingStreamSocket( + scoped_ptr<net::StreamSocket>(error_socket)); int rv = callback.GetResult(transport->Connect(callback.callback())); - EXPECT_EQ(OK, rv); + EXPECT_EQ(net::OK, rv); // Disable TLS False Start to avoid handshake non-determinism. - SSLConfig ssl_config; + net::SSLConfig ssl_config; ssl_config.false_start_enabled = false; - scoped_ptr<SSLClientSocket> sock = - CreateSSLClientSocket(transport.PassAs<StreamSocket>(), - test_server.host_port_pair(), - ssl_config); + net::SSLClientSocket* sock( + CreateSSLClientSocket(transport, test_server.host_port_pair(), + ssl_config)); rv = callback.GetResult(sock->Connect(callback.callback())); - EXPECT_EQ(OK, rv); + EXPECT_EQ(net::OK, rv); EXPECT_TRUE(sock->IsConnected()); std::string request_text = "GET / HTTP/1.1\r\nUser-Agent: long browser name "; request_text.append(20 * 1024, '*'); request_text.append("\r\n\r\n"); - scoped_refptr<DrainableIOBuffer> request_buffer(new DrainableIOBuffer( - new StringIOBuffer(request_text), request_text.size())); + scoped_refptr<net::DrainableIOBuffer> request_buffer( + new net::DrainableIOBuffer(new net::StringIOBuffer(request_text), + request_text.size())); // Simulate errors being returned from the underlying Read() and Write() ... - raw_error_socket->SetNextReadError(ERR_CONNECTION_RESET); - raw_error_socket->SetNextWriteError(ERR_CONNECTION_RESET); + error_socket->SetNextReadError(net::ERR_CONNECTION_RESET); + error_socket->SetNextWriteError(net::ERR_CONNECTION_RESET); // ... but have those errors returned asynchronously. Because the Write() will // return first, this will trigger the error. - raw_transport->SetNextReadShouldBlock(); - raw_transport->SetNextWriteShouldBlock(); + transport->SetNextReadShouldBlock(); + transport->SetNextWriteShouldBlock(); // Enqueue a Read() before calling Write(), which should "hang" due to // the ERR_IO_PENDING caused by SetReadShouldBlock() and thus return. - SSLClientSocket* raw_sock = sock.get(); - DeleteSocketCallback read_callback(sock.release()); - scoped_refptr<IOBuffer> read_buf(new IOBuffer(4096)); - rv = raw_sock->Read(read_buf.get(), 4096, read_callback.callback()); + DeleteSocketCallback read_callback(sock); + scoped_refptr<net::IOBuffer> read_buf(new net::IOBuffer(4096)); + rv = sock->Read(read_buf.get(), 4096, read_callback.callback()); // Ensure things didn't complete synchronously, otherwise |sock| is invalid. - ASSERT_EQ(ERR_IO_PENDING, rv); + ASSERT_EQ(net::ERR_IO_PENDING, rv); ASSERT_FALSE(read_callback.have_result()); #if !defined(USE_OPENSSL) @@ -1131,9 +1142,9 @@ TEST_F(SSLClientSocketTest, Read_DeleteWhilePendingFullDuplex) { // SSLClientSocketOpenSSL::Write() will not return until all of // |request_buffer| has been written to the underlying BIO (although not // necessarily the underlying transport). - rv = callback.GetResult(raw_sock->Write(request_buffer.get(), - request_buffer->BytesRemaining(), - callback.callback())); + rv = callback.GetResult(sock->Write(request_buffer.get(), + request_buffer->BytesRemaining(), + callback.callback())); ASSERT_LT(0, rv); request_buffer->DidConsume(rv); @@ -1146,22 +1157,22 @@ TEST_F(SSLClientSocketTest, Read_DeleteWhilePendingFullDuplex) { // Attempt to write the remaining data. NSS will not be able to consume the // application data because the internal buffers are full, while OpenSSL will // return that its blocked because the underlying transport is blocked. - rv = raw_sock->Write(request_buffer.get(), - request_buffer->BytesRemaining(), - callback.callback()); - ASSERT_EQ(ERR_IO_PENDING, rv); + rv = sock->Write(request_buffer.get(), + request_buffer->BytesRemaining(), + callback.callback()); + ASSERT_EQ(net::ERR_IO_PENDING, rv); ASSERT_FALSE(callback.have_result()); // Now unblock Write(), which will invoke OnSendComplete and (eventually) // call the Read() callback, deleting the socket and thus aborting calling // the Write() callback. - raw_transport->UnblockWrite(); + transport->UnblockWrite(); rv = read_callback.WaitForResult(); #if !defined(USE_OPENSSL) // NSS records the error exactly. - EXPECT_EQ(ERR_CONNECTION_RESET, rv); + EXPECT_EQ(net::ERR_CONNECTION_RESET, rv); #else // OpenSSL treats any errors as a simple EOF. EXPECT_EQ(0, rv); @@ -1172,49 +1183,50 @@ TEST_F(SSLClientSocketTest, Read_DeleteWhilePendingFullDuplex) { } TEST_F(SSLClientSocketTest, Read_SmallChunks) { - SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS, - SpawnedTestServer::kLocalhost, - base::FilePath()); + net::SpawnedTestServer test_server(net::SpawnedTestServer::TYPE_HTTPS, + net::SpawnedTestServer::kLocalhost, + base::FilePath()); ASSERT_TRUE(test_server.Start()); - AddressList addr; + net::AddressList addr; ASSERT_TRUE(test_server.GetAddressList(&addr)); - TestCompletionCallback callback; - scoped_ptr<StreamSocket> transport( - new TCPClientSocket(addr, NULL, NetLog::Source())); + net::TestCompletionCallback callback; + net::StreamSocket* transport = new net::TCPClientSocket( + addr, NULL, net::NetLog::Source()); int rv = transport->Connect(callback.callback()); - if (rv == ERR_IO_PENDING) + if (rv == net::ERR_IO_PENDING) rv = callback.WaitForResult(); - EXPECT_EQ(OK, rv); + EXPECT_EQ(net::OK, rv); - scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket( - transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig)); + scoped_ptr<net::SSLClientSocket> sock( + CreateSSLClientSocket(transport, test_server.host_port_pair(), + kDefaultSSLConfig)); rv = sock->Connect(callback.callback()); - if (rv == ERR_IO_PENDING) + if (rv == net::ERR_IO_PENDING) rv = callback.WaitForResult(); - EXPECT_EQ(OK, rv); + EXPECT_EQ(net::OK, rv); const char request_text[] = "GET / HTTP/1.0\r\n\r\n"; - scoped_refptr<IOBuffer> request_buffer( - new IOBuffer(arraysize(request_text) - 1)); + scoped_refptr<net::IOBuffer> request_buffer( + new net::IOBuffer(arraysize(request_text) - 1)); memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1); rv = sock->Write( request_buffer.get(), arraysize(request_text) - 1, callback.callback()); - EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING); + EXPECT_TRUE(rv >= 0 || rv == net::ERR_IO_PENDING); - if (rv == ERR_IO_PENDING) + if (rv == net::ERR_IO_PENDING) rv = callback.WaitForResult(); EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv); - scoped_refptr<IOBuffer> buf(new IOBuffer(1)); + scoped_refptr<net::IOBuffer> buf(new net::IOBuffer(1)); for (;;) { rv = sock->Read(buf.get(), 1, callback.callback()); - EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING); + EXPECT_TRUE(rv >= 0 || rv == net::ERR_IO_PENDING); - if (rv == ERR_IO_PENDING) + if (rv == net::ERR_IO_PENDING) rv = callback.WaitForResult(); EXPECT_GE(rv, 0); @@ -1224,36 +1236,34 @@ TEST_F(SSLClientSocketTest, Read_SmallChunks) { } TEST_F(SSLClientSocketTest, Read_ManySmallRecords) { - SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS, - SpawnedTestServer::kLocalhost, - base::FilePath()); + net::SpawnedTestServer test_server(net::SpawnedTestServer::TYPE_HTTPS, + net::SpawnedTestServer::kLocalhost, + base::FilePath()); ASSERT_TRUE(test_server.Start()); - AddressList addr; + net::AddressList addr; ASSERT_TRUE(test_server.GetAddressList(&addr)); - TestCompletionCallback callback; + net::TestCompletionCallback callback; - scoped_ptr<StreamSocket> real_transport( - new TCPClientSocket(addr, NULL, NetLog::Source())); - scoped_ptr<ReadBufferingStreamSocket> transport( - new ReadBufferingStreamSocket(real_transport.Pass())); - ReadBufferingStreamSocket* raw_transport = transport.get(); + scoped_ptr<net::StreamSocket> real_transport(new net::TCPClientSocket( + addr, NULL, net::NetLog::Source())); + ReadBufferingStreamSocket* transport = new ReadBufferingStreamSocket( + real_transport.Pass()); int rv = callback.GetResult(transport->Connect(callback.callback())); - ASSERT_EQ(OK, rv); + ASSERT_EQ(net::OK, rv); - scoped_ptr<SSLClientSocket> sock( - CreateSSLClientSocket(transport.PassAs<StreamSocket>(), - test_server.host_port_pair(), + scoped_ptr<net::SSLClientSocket> sock( + CreateSSLClientSocket(transport, test_server.host_port_pair(), kDefaultSSLConfig)); rv = callback.GetResult(sock->Connect(callback.callback())); - ASSERT_EQ(OK, rv); + ASSERT_EQ(net::OK, rv); ASSERT_TRUE(sock->IsConnected()); const char request_text[] = "GET /ssl-many-small-records HTTP/1.0\r\n\r\n"; - scoped_refptr<IOBuffer> request_buffer( - new IOBuffer(arraysize(request_text) - 1)); + scoped_refptr<net::IOBuffer> request_buffer( + new net::IOBuffer(arraysize(request_text) - 1)); memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1); rv = callback.GetResult(sock->Write( @@ -1270,114 +1280,117 @@ TEST_F(SSLClientSocketTest, Read_ManySmallRecords) { // 15K was chosen because 15K is smaller than the 17K (max) read issued by // the SSLClientSocket implementation, and larger than the minimum amount // of ciphertext necessary to contain the 8K of plaintext requested below. - raw_transport->SetBufferSize(15000); + transport->SetBufferSize(15000); - scoped_refptr<IOBuffer> buffer(new IOBuffer(8192)); + scoped_refptr<net::IOBuffer> buffer(new net::IOBuffer(8192)); rv = callback.GetResult(sock->Read(buffer.get(), 8192, callback.callback())); ASSERT_EQ(rv, 8192); } TEST_F(SSLClientSocketTest, Read_Interrupted) { - SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS, - SpawnedTestServer::kLocalhost, - base::FilePath()); + net::SpawnedTestServer test_server(net::SpawnedTestServer::TYPE_HTTPS, + net::SpawnedTestServer::kLocalhost, + base::FilePath()); ASSERT_TRUE(test_server.Start()); - AddressList addr; + net::AddressList addr; ASSERT_TRUE(test_server.GetAddressList(&addr)); - TestCompletionCallback callback; - scoped_ptr<StreamSocket> transport( - new TCPClientSocket(addr, NULL, NetLog::Source())); + net::TestCompletionCallback callback; + net::StreamSocket* transport = new net::TCPClientSocket( + addr, NULL, net::NetLog::Source()); int rv = transport->Connect(callback.callback()); - if (rv == ERR_IO_PENDING) + if (rv == net::ERR_IO_PENDING) rv = callback.WaitForResult(); - EXPECT_EQ(OK, rv); + EXPECT_EQ(net::OK, rv); - scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket( - transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig)); + scoped_ptr<net::SSLClientSocket> sock( + CreateSSLClientSocket(transport, test_server.host_port_pair(), + kDefaultSSLConfig)); rv = sock->Connect(callback.callback()); - if (rv == ERR_IO_PENDING) + if (rv == net::ERR_IO_PENDING) rv = callback.WaitForResult(); - EXPECT_EQ(OK, rv); + EXPECT_EQ(net::OK, rv); const char request_text[] = "GET / HTTP/1.0\r\n\r\n"; - scoped_refptr<IOBuffer> request_buffer( - new IOBuffer(arraysize(request_text) - 1)); + scoped_refptr<net::IOBuffer> request_buffer( + new net::IOBuffer(arraysize(request_text) - 1)); memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1); rv = sock->Write( request_buffer.get(), arraysize(request_text) - 1, callback.callback()); - EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING); + EXPECT_TRUE(rv >= 0 || rv == net::ERR_IO_PENDING); - if (rv == ERR_IO_PENDING) + if (rv == net::ERR_IO_PENDING) rv = callback.WaitForResult(); EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv); // Do a partial read and then exit. This test should not crash! - scoped_refptr<IOBuffer> buf(new IOBuffer(512)); + scoped_refptr<net::IOBuffer> buf(new net::IOBuffer(512)); rv = sock->Read(buf.get(), 512, callback.callback()); - EXPECT_TRUE(rv > 0 || rv == ERR_IO_PENDING); + EXPECT_TRUE(rv > 0 || rv == net::ERR_IO_PENDING); - if (rv == ERR_IO_PENDING) + if (rv == net::ERR_IO_PENDING) rv = callback.WaitForResult(); EXPECT_GT(rv, 0); } TEST_F(SSLClientSocketTest, Read_FullLogging) { - SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS, - SpawnedTestServer::kLocalhost, - base::FilePath()); + net::SpawnedTestServer test_server(net::SpawnedTestServer::TYPE_HTTPS, + net::SpawnedTestServer::kLocalhost, + base::FilePath()); ASSERT_TRUE(test_server.Start()); - AddressList addr; + net::AddressList addr; ASSERT_TRUE(test_server.GetAddressList(&addr)); - TestCompletionCallback callback; - CapturingNetLog log; - log.SetLogLevel(NetLog::LOG_ALL); - scoped_ptr<StreamSocket> transport( - new TCPClientSocket(addr, &log, NetLog::Source())); + net::TestCompletionCallback callback; + net::CapturingNetLog log; + log.SetLogLevel(net::NetLog::LOG_ALL); + net::StreamSocket* transport = new net::TCPClientSocket( + addr, &log, net::NetLog::Source()); int rv = transport->Connect(callback.callback()); - if (rv == ERR_IO_PENDING) + if (rv == net::ERR_IO_PENDING) rv = callback.WaitForResult(); - EXPECT_EQ(OK, rv); + EXPECT_EQ(net::OK, rv); - scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket( - transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig)); + scoped_ptr<net::SSLClientSocket> sock( + CreateSSLClientSocket(transport, test_server.host_port_pair(), + kDefaultSSLConfig)); rv = sock->Connect(callback.callback()); - if (rv == ERR_IO_PENDING) + if (rv == net::ERR_IO_PENDING) rv = callback.WaitForResult(); - EXPECT_EQ(OK, rv); + EXPECT_EQ(net::OK, rv); EXPECT_TRUE(sock->IsConnected()); const char request_text[] = "GET / HTTP/1.0\r\n\r\n"; - scoped_refptr<IOBuffer> request_buffer( - new IOBuffer(arraysize(request_text) - 1)); + scoped_refptr<net::IOBuffer> request_buffer( + new net::IOBuffer(arraysize(request_text) - 1)); memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1); rv = sock->Write( request_buffer.get(), arraysize(request_text) - 1, callback.callback()); - EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING); + EXPECT_TRUE(rv >= 0 || rv == net::ERR_IO_PENDING); - if (rv == ERR_IO_PENDING) + if (rv == net::ERR_IO_PENDING) rv = callback.WaitForResult(); EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv); - CapturingNetLog::CapturedEntryList entries; + net::CapturingNetLog::CapturedEntryList entries; log.GetEntries(&entries); - size_t last_index = ExpectLogContainsSomewhereAfter( - entries, 5, NetLog::TYPE_SSL_SOCKET_BYTES_SENT, NetLog::PHASE_NONE); + size_t last_index = net::ExpectLogContainsSomewhereAfter( + entries, 5, net::NetLog::TYPE_SSL_SOCKET_BYTES_SENT, + net::NetLog::PHASE_NONE); - scoped_refptr<IOBuffer> buf(new IOBuffer(4096)); + scoped_refptr<net::IOBuffer> buf(new net::IOBuffer(4096)); for (;;) { rv = sock->Read(buf.get(), 4096, callback.callback()); - EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING); + EXPECT_TRUE(rv >= 0 || rv == net::ERR_IO_PENDING); - if (rv == ERR_IO_PENDING) + if (rv == net::ERR_IO_PENDING) rv = callback.WaitForResult(); EXPECT_GE(rv, 0); @@ -1385,59 +1398,61 @@ TEST_F(SSLClientSocketTest, Read_FullLogging) { break; log.GetEntries(&entries); - last_index = - ExpectLogContainsSomewhereAfter(entries, - last_index + 1, - NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, - NetLog::PHASE_NONE); + last_index = net::ExpectLogContainsSomewhereAfter( + entries, last_index + 1, net::NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, + net::NetLog::PHASE_NONE); } } // Regression test for http://crbug.com/42538 TEST_F(SSLClientSocketTest, PrematureApplicationData) { - SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS, - SpawnedTestServer::kLocalhost, - base::FilePath()); + net::SpawnedTestServer test_server(net::SpawnedTestServer::TYPE_HTTPS, + net::SpawnedTestServer::kLocalhost, + base::FilePath()); ASSERT_TRUE(test_server.Start()); - AddressList addr; - TestCompletionCallback callback; + net::AddressList addr; + net::TestCompletionCallback callback; static const unsigned char application_data[] = { - 0x17, 0x03, 0x01, 0x00, 0x4a, 0x02, 0x00, 0x00, 0x46, 0x03, 0x01, 0x4b, - 0xc2, 0xf8, 0xb2, 0xc1, 0x56, 0x42, 0xb9, 0x57, 0x7f, 0xde, 0x87, 0x46, - 0xf7, 0xa3, 0x52, 0x42, 0x21, 0xf0, 0x13, 0x1c, 0x9c, 0x83, 0x88, 0xd6, - 0x93, 0x0c, 0xf6, 0x36, 0x30, 0x05, 0x7e, 0x20, 0xb5, 0xb5, 0x73, 0x36, - 0x53, 0x83, 0x0a, 0xfc, 0x17, 0x63, 0xbf, 0xa0, 0xe4, 0x42, 0x90, 0x0d, - 0x2f, 0x18, 0x6d, 0x20, 0xd8, 0x36, 0x3f, 0xfc, 0xe6, 0x01, 0xfa, 0x0f, - 0xa5, 0x75, 0x7f, 0x09, 0x00, 0x04, 0x00, 0x16, 0x03, 0x01, 0x11, 0x57, - 0x0b, 0x00, 0x11, 0x53, 0x00, 0x11, 0x50, 0x00, 0x06, 0x22, 0x30, 0x82, - 0x06, 0x1e, 0x30, 0x82, 0x05, 0x06, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, - 0x0a}; + 0x17, 0x03, 0x01, 0x00, 0x4a, 0x02, 0x00, 0x00, 0x46, 0x03, 0x01, 0x4b, + 0xc2, 0xf8, 0xb2, 0xc1, 0x56, 0x42, 0xb9, 0x57, 0x7f, 0xde, 0x87, 0x46, + 0xf7, 0xa3, 0x52, 0x42, 0x21, 0xf0, 0x13, 0x1c, 0x9c, 0x83, 0x88, 0xd6, + 0x93, 0x0c, 0xf6, 0x36, 0x30, 0x05, 0x7e, 0x20, 0xb5, 0xb5, 0x73, 0x36, + 0x53, 0x83, 0x0a, 0xfc, 0x17, 0x63, 0xbf, 0xa0, 0xe4, 0x42, 0x90, 0x0d, + 0x2f, 0x18, 0x6d, 0x20, 0xd8, 0x36, 0x3f, 0xfc, 0xe6, 0x01, 0xfa, 0x0f, + 0xa5, 0x75, 0x7f, 0x09, 0x00, 0x04, 0x00, 0x16, 0x03, 0x01, 0x11, 0x57, + 0x0b, 0x00, 0x11, 0x53, 0x00, 0x11, 0x50, 0x00, 0x06, 0x22, 0x30, 0x82, + 0x06, 0x1e, 0x30, 0x82, 0x05, 0x06, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, + 0x0a + }; // All reads and writes complete synchronously (async=false). - MockRead data_reads[] = { - MockRead(SYNCHRONOUS, - reinterpret_cast<const char*>(application_data), - arraysize(application_data)), - MockRead(SYNCHRONOUS, OK), }; + net::MockRead data_reads[] = { + net::MockRead(net::SYNCHRONOUS, + reinterpret_cast<const char*>(application_data), + arraysize(application_data)), + net::MockRead(net::SYNCHRONOUS, net::OK), + }; - StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0); + net::StaticSocketDataProvider data(data_reads, arraysize(data_reads), + NULL, 0); - scoped_ptr<StreamSocket> transport( - new MockTCPClientSocket(addr, NULL, &data)); + net::StreamSocket* transport = + new net::MockTCPClientSocket(addr, NULL, &data); int rv = transport->Connect(callback.callback()); - if (rv == ERR_IO_PENDING) + if (rv == net::ERR_IO_PENDING) rv = callback.WaitForResult(); - EXPECT_EQ(OK, rv); + EXPECT_EQ(net::OK, rv); - scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket( - transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig)); + scoped_ptr<net::SSLClientSocket> sock( + CreateSSLClientSocket(transport, test_server.host_port_pair(), + kDefaultSSLConfig)); rv = sock->Connect(callback.callback()); - if (rv == ERR_IO_PENDING) + if (rv == net::ERR_IO_PENDING) rv = callback.WaitForResult(); - EXPECT_EQ(ERR_SSL_PROTOCOL_ERROR, rv); + EXPECT_EQ(net::ERR_SSL_PROTOCOL_ERROR, rv); } TEST_F(SSLClientSocketTest, CipherSuiteDisables) { @@ -1445,41 +1460,46 @@ TEST_F(SSLClientSocketTest, CipherSuiteDisables) { // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml, // only disabling those cipher suites that the test server actually // implements. - const uint16 kCiphersToDisable[] = {0x0005, // TLS_RSA_WITH_RC4_128_SHA + const uint16 kCiphersToDisable[] = { + 0x0005, // TLS_RSA_WITH_RC4_128_SHA }; - SpawnedTestServer::SSLOptions ssl_options; + net::SpawnedTestServer::SSLOptions ssl_options; // Enable only RC4 on the test server. - ssl_options.bulk_ciphers = SpawnedTestServer::SSLOptions::BULK_CIPHER_RC4; - SpawnedTestServer test_server( - SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath()); + ssl_options.bulk_ciphers = + net::SpawnedTestServer::SSLOptions::BULK_CIPHER_RC4; + net::SpawnedTestServer test_server(net::SpawnedTestServer::TYPE_HTTPS, + ssl_options, + base::FilePath()); ASSERT_TRUE(test_server.Start()); - AddressList addr; + net::AddressList addr; ASSERT_TRUE(test_server.GetAddressList(&addr)); - TestCompletionCallback callback; - CapturingNetLog log; - scoped_ptr<StreamSocket> transport( - new TCPClientSocket(addr, &log, NetLog::Source())); + net::TestCompletionCallback callback; + net::CapturingNetLog log; + net::StreamSocket* transport = new net::TCPClientSocket( + addr, &log, net::NetLog::Source()); int rv = transport->Connect(callback.callback()); - if (rv == ERR_IO_PENDING) + if (rv == net::ERR_IO_PENDING) rv = callback.WaitForResult(); - EXPECT_EQ(OK, rv); + EXPECT_EQ(net::OK, rv); - SSLConfig ssl_config; + net::SSLConfig ssl_config; for (size_t i = 0; i < arraysize(kCiphersToDisable); ++i) ssl_config.disabled_cipher_suites.push_back(kCiphersToDisable[i]); - scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket( - transport.Pass(), test_server.host_port_pair(), ssl_config)); + scoped_ptr<net::SSLClientSocket> sock( + CreateSSLClientSocket(transport, test_server.host_port_pair(), + ssl_config)); EXPECT_FALSE(sock->IsConnected()); rv = sock->Connect(callback.callback()); - CapturingNetLog::CapturedEntryList entries; + net::CapturingNetLog::CapturedEntryList entries; log.GetEntries(&entries); - EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT)); + EXPECT_TRUE(net::LogContainsBeginEvent( + entries, 5, net::NetLog::TYPE_SSL_CONNECT)); // NSS has special handling that maps a handshake_failure alert received // immediately after a client_hello to be a mismatched cipher suite error, @@ -1487,16 +1507,17 @@ TEST_F(SSLClientSocketTest, CipherSuiteDisables) { // Secure Transport (OS X), the handshake_failure is bubbled up without any // interpretation, leading to ERR_SSL_PROTOCOL_ERROR. Either way, a failure // indicates that no cipher suite was negotiated with the test server. - if (rv == ERR_IO_PENDING) + if (rv == net::ERR_IO_PENDING) rv = callback.WaitForResult(); - EXPECT_TRUE(rv == ERR_SSL_VERSION_OR_CIPHER_MISMATCH || - rv == ERR_SSL_PROTOCOL_ERROR); + EXPECT_TRUE(rv == net::ERR_SSL_VERSION_OR_CIPHER_MISMATCH || + rv == net::ERR_SSL_PROTOCOL_ERROR); // The exact ordering differs between SSLClientSocketNSS (which issues an // extra read) and SSLClientSocketMac (which does not). Just make sure the // error appears somewhere in the log. log.GetEntries(&entries); - ExpectLogContainsSomewhere( - entries, 0, NetLog::TYPE_SSL_HANDSHAKE_ERROR, NetLog::PHASE_NONE); + net::ExpectLogContainsSomewhere(entries, 0, + net::NetLog::TYPE_SSL_HANDSHAKE_ERROR, + net::NetLog::PHASE_NONE); // We cannot test sock->IsConnected(), as the NSS implementation disconnects // the socket when it encounters an error, whereas other implementations @@ -1518,65 +1539,65 @@ TEST_F(SSLClientSocketTest, CipherSuiteDisables) { // Here we verify that such a simple ClientSocketHandle, not associated with any // client socket pool, can be destroyed safely. TEST_F(SSLClientSocketTest, ClientSocketHandleNotFromPool) { - SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS, - SpawnedTestServer::kLocalhost, - base::FilePath()); + net::SpawnedTestServer test_server(net::SpawnedTestServer::TYPE_HTTPS, + net::SpawnedTestServer::kLocalhost, + base::FilePath()); ASSERT_TRUE(test_server.Start()); - AddressList addr; + net::AddressList addr; ASSERT_TRUE(test_server.GetAddressList(&addr)); - TestCompletionCallback callback; - scoped_ptr<StreamSocket> transport( - new TCPClientSocket(addr, NULL, NetLog::Source())); + net::TestCompletionCallback callback; + net::StreamSocket* transport = new net::TCPClientSocket( + addr, NULL, net::NetLog::Source()); int rv = transport->Connect(callback.callback()); - if (rv == ERR_IO_PENDING) + if (rv == net::ERR_IO_PENDING) rv = callback.WaitForResult(); - EXPECT_EQ(OK, rv); + EXPECT_EQ(net::OK, rv); - scoped_ptr<ClientSocketHandle> socket_handle(new ClientSocketHandle()); - socket_handle->SetSocket(transport.Pass()); + net::ClientSocketHandle* socket_handle = new net::ClientSocketHandle(); + socket_handle->set_socket(transport); - scoped_ptr<SSLClientSocket> sock( - socket_factory_->CreateSSLClientSocket(socket_handle.Pass(), - test_server.host_port_pair(), - kDefaultSSLConfig, - context_)); + scoped_ptr<net::SSLClientSocket> sock( + socket_factory_->CreateSSLClientSocket( + socket_handle, test_server.host_port_pair(), kDefaultSSLConfig, + context_)); EXPECT_FALSE(sock->IsConnected()); rv = sock->Connect(callback.callback()); - if (rv == ERR_IO_PENDING) + if (rv == net::ERR_IO_PENDING) rv = callback.WaitForResult(); - EXPECT_EQ(OK, rv); + EXPECT_EQ(net::OK, rv); } // Verifies that SSLClientSocket::ExportKeyingMaterial return a success // code and different keying label results in different keying material. TEST_F(SSLClientSocketTest, ExportKeyingMaterial) { - SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS, - SpawnedTestServer::kLocalhost, - base::FilePath()); + net::SpawnedTestServer test_server(net::SpawnedTestServer::TYPE_HTTPS, + net::SpawnedTestServer::kLocalhost, + base::FilePath()); ASSERT_TRUE(test_server.Start()); - AddressList addr; + net::AddressList addr; ASSERT_TRUE(test_server.GetAddressList(&addr)); - TestCompletionCallback callback; + net::TestCompletionCallback callback; - scoped_ptr<StreamSocket> transport( - new TCPClientSocket(addr, NULL, NetLog::Source())); + net::StreamSocket* transport = new net::TCPClientSocket( + addr, NULL, net::NetLog::Source()); int rv = transport->Connect(callback.callback()); - if (rv == ERR_IO_PENDING) + if (rv == net::ERR_IO_PENDING) rv = callback.WaitForResult(); - EXPECT_EQ(OK, rv); + EXPECT_EQ(net::OK, rv); - scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket( - transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig)); + scoped_ptr<net::SSLClientSocket> sock( + CreateSSLClientSocket(transport, test_server.host_port_pair(), + kDefaultSSLConfig)); rv = sock->Connect(callback.callback()); - if (rv == ERR_IO_PENDING) + if (rv == net::ERR_IO_PENDING) rv = callback.WaitForResult(); - EXPECT_EQ(OK, rv); + EXPECT_EQ(net::OK, rv); EXPECT_TRUE(sock->IsConnected()); const int kKeyingMaterialSize = 32; @@ -1584,23 +1605,23 @@ TEST_F(SSLClientSocketTest, ExportKeyingMaterial) { const char* kKeyingContext = ""; unsigned char client_out1[kKeyingMaterialSize]; memset(client_out1, 0, sizeof(client_out1)); - rv = sock->ExportKeyingMaterial( - kKeyingLabel1, false, kKeyingContext, client_out1, sizeof(client_out1)); - EXPECT_EQ(rv, OK); + rv = sock->ExportKeyingMaterial(kKeyingLabel1, false, kKeyingContext, + client_out1, sizeof(client_out1)); + EXPECT_EQ(rv, net::OK); const char* kKeyingLabel2 = "client-socket-test-2"; unsigned char client_out2[kKeyingMaterialSize]; memset(client_out2, 0, sizeof(client_out2)); - rv = sock->ExportKeyingMaterial( - kKeyingLabel2, false, kKeyingContext, client_out2, sizeof(client_out2)); - EXPECT_EQ(rv, OK); + rv = sock->ExportKeyingMaterial(kKeyingLabel2, false, kKeyingContext, + client_out2, sizeof(client_out2)); + EXPECT_EQ(rv, net::OK); EXPECT_NE(memcmp(client_out1, client_out2, kKeyingMaterialSize), 0); } // Verifies that SSLClientSocket::ClearSessionCache can be called without // explicit NSS initialization. TEST(SSLClientSocket, ClearSessionCache) { - SSLClientSocket::ClearSessionCache(); + net::SSLClientSocket::ClearSessionCache(); } // This tests that SSLInfo contains a properly re-constructed certificate @@ -1618,84 +1639,86 @@ TEST(SSLClientSocket, ClearSessionCache) { TEST_F(SSLClientSocketTest, VerifyReturnChainProperlyOrdered) { // By default, cause the CertVerifier to treat all certificates as // expired. - cert_verifier_->set_default_result(ERR_CERT_DATE_INVALID); + cert_verifier_->set_default_result(net::ERR_CERT_DATE_INVALID); // We will expect SSLInfo to ultimately contain this chain. - CertificateList certs = - CreateCertificateListFromFile(GetTestCertsDirectory(), - "redundant-validated-chain.pem", - X509Certificate::FORMAT_AUTO); + net::CertificateList certs = CreateCertificateListFromFile( + net::GetTestCertsDirectory(), "redundant-validated-chain.pem", + net::X509Certificate::FORMAT_AUTO); ASSERT_EQ(3U, certs.size()); - X509Certificate::OSCertHandles temp_intermediates; + net::X509Certificate::OSCertHandles temp_intermediates; temp_intermediates.push_back(certs[1]->os_cert_handle()); temp_intermediates.push_back(certs[2]->os_cert_handle()); - CertVerifyResult verify_result; - verify_result.verified_cert = X509Certificate::CreateFromHandle( - certs[0]->os_cert_handle(), temp_intermediates); + net::CertVerifyResult verify_result; + verify_result.verified_cert = + net::X509Certificate::CreateFromHandle(certs[0]->os_cert_handle(), + temp_intermediates); // Add a rule that maps the server cert (A) to the chain of A->B->C2 // rather than A->B->C. - cert_verifier_->AddResultForCert(certs[0].get(), verify_result, OK); + cert_verifier_->AddResultForCert(certs[0].get(), verify_result, net::OK); // Load and install the root for the validated chain. - scoped_refptr<X509Certificate> root_cert = ImportCertFromFile( - GetTestCertsDirectory(), "redundant-validated-chain-root.pem"); - ASSERT_NE(static_cast<X509Certificate*>(NULL), root_cert); - ScopedTestRoot scoped_root(root_cert.get()); + scoped_refptr<net::X509Certificate> root_cert = + net::ImportCertFromFile(net::GetTestCertsDirectory(), + "redundant-validated-chain-root.pem"); + ASSERT_NE(static_cast<net::X509Certificate*>(NULL), root_cert); + net::ScopedTestRoot scoped_root(root_cert.get()); // Set up a test server with CERT_CHAIN_WRONG_ROOT. - SpawnedTestServer::SSLOptions ssl_options( - SpawnedTestServer::SSLOptions::CERT_CHAIN_WRONG_ROOT); - SpawnedTestServer test_server( - SpawnedTestServer::TYPE_HTTPS, - ssl_options, + net::SpawnedTestServer::SSLOptions ssl_options( + net::SpawnedTestServer::SSLOptions::CERT_CHAIN_WRONG_ROOT); + net::SpawnedTestServer test_server( + net::SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))); ASSERT_TRUE(test_server.Start()); - AddressList addr; + net::AddressList addr; ASSERT_TRUE(test_server.GetAddressList(&addr)); - TestCompletionCallback callback; - CapturingNetLog log; - scoped_ptr<StreamSocket> transport( - new TCPClientSocket(addr, &log, NetLog::Source())); + net::TestCompletionCallback callback; + net::CapturingNetLog log; + net::StreamSocket* transport = new net::TCPClientSocket( + addr, &log, net::NetLog::Source()); int rv = transport->Connect(callback.callback()); - if (rv == ERR_IO_PENDING) + if (rv == net::ERR_IO_PENDING) rv = callback.WaitForResult(); - EXPECT_EQ(OK, rv); + EXPECT_EQ(net::OK, rv); - scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket( - transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig)); + scoped_ptr<net::SSLClientSocket> sock( + CreateSSLClientSocket(transport, test_server.host_port_pair(), + kDefaultSSLConfig)); EXPECT_FALSE(sock->IsConnected()); rv = sock->Connect(callback.callback()); - CapturingNetLog::CapturedEntryList entries; + net::CapturingNetLog::CapturedEntryList entries; log.GetEntries(&entries); - EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT)); - if (rv == ERR_IO_PENDING) + EXPECT_TRUE(net::LogContainsBeginEvent( + entries, 5, net::NetLog::TYPE_SSL_CONNECT)); + if (rv == net::ERR_IO_PENDING) rv = callback.WaitForResult(); - EXPECT_EQ(OK, rv); + EXPECT_EQ(net::OK, rv); EXPECT_TRUE(sock->IsConnected()); log.GetEntries(&entries); EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1)); - SSLInfo ssl_info; + net::SSLInfo ssl_info; sock->GetSSLInfo(&ssl_info); // Verify that SSLInfo contains the corrected re-constructed chain A -> B // -> C2. - const X509Certificate::OSCertHandles& intermediates = + const net::X509Certificate::OSCertHandles& intermediates = ssl_info.cert->GetIntermediateCertificates(); ASSERT_EQ(2U, intermediates.size()); - EXPECT_TRUE(X509Certificate::IsSameOSCert(ssl_info.cert->os_cert_handle(), - certs[0]->os_cert_handle())); - EXPECT_TRUE(X509Certificate::IsSameOSCert(intermediates[0], - certs[1]->os_cert_handle())); - EXPECT_TRUE(X509Certificate::IsSameOSCert(intermediates[1], - certs[2]->os_cert_handle())); + EXPECT_TRUE(net::X509Certificate::IsSameOSCert( + ssl_info.cert->os_cert_handle(), certs[0]->os_cert_handle())); + EXPECT_TRUE(net::X509Certificate::IsSameOSCert( + intermediates[0], certs[1]->os_cert_handle())); + EXPECT_TRUE(net::X509Certificate::IsSameOSCert( + intermediates[1], certs[2]->os_cert_handle())); sock->Disconnect(); EXPECT_FALSE(sock->IsConnected()); @@ -1706,34 +1729,37 @@ class SSLClientSocketCertRequestInfoTest : public SSLClientSocketTest { protected: // Creates a test server with the given SSLOptions, connects to it and returns // the SSLCertRequestInfo reported by the socket. - scoped_refptr<SSLCertRequestInfo> GetCertRequest( - SpawnedTestServer::SSLOptions ssl_options) { - SpawnedTestServer test_server( - SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath()); + scoped_refptr<net::SSLCertRequestInfo> GetCertRequest( + net::SpawnedTestServer::SSLOptions ssl_options) { + net::SpawnedTestServer test_server(net::SpawnedTestServer::TYPE_HTTPS, + ssl_options, + base::FilePath()); if (!test_server.Start()) return NULL; - AddressList addr; + net::AddressList addr; if (!test_server.GetAddressList(&addr)) return NULL; - TestCompletionCallback callback; - CapturingNetLog log; - scoped_ptr<StreamSocket> transport( - new TCPClientSocket(addr, &log, NetLog::Source())); + net::TestCompletionCallback callback; + net::CapturingNetLog log; + net::StreamSocket* transport = new net::TCPClientSocket( + addr, &log, net::NetLog::Source()); int rv = transport->Connect(callback.callback()); - if (rv == ERR_IO_PENDING) + if (rv == net::ERR_IO_PENDING) rv = callback.WaitForResult(); - EXPECT_EQ(OK, rv); + EXPECT_EQ(net::OK, rv); - scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket( - transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig)); + scoped_ptr<net::SSLClientSocket> sock( + CreateSSLClientSocket(transport, test_server.host_port_pair(), + kDefaultSSLConfig)); EXPECT_FALSE(sock->IsConnected()); rv = sock->Connect(callback.callback()); - if (rv == ERR_IO_PENDING) + if (rv == net::ERR_IO_PENDING) rv = callback.WaitForResult(); - scoped_refptr<SSLCertRequestInfo> request_info = new SSLCertRequestInfo(); + scoped_refptr<net::SSLCertRequestInfo> request_info = + new net::SSLCertRequestInfo(); sock->GetSSLCertRequestInfo(request_info.get()); sock->Disconnect(); EXPECT_FALSE(sock->IsConnected()); @@ -1743,9 +1769,10 @@ class SSLClientSocketCertRequestInfoTest : public SSLClientSocketTest { }; TEST_F(SSLClientSocketCertRequestInfoTest, NoAuthorities) { - SpawnedTestServer::SSLOptions ssl_options; + net::SpawnedTestServer::SSLOptions ssl_options; ssl_options.request_client_certificate = true; - scoped_refptr<SSLCertRequestInfo> request_info = GetCertRequest(ssl_options); + scoped_refptr<net::SSLCertRequestInfo> request_info = + GetCertRequest(ssl_options); ASSERT_TRUE(request_info.get()); EXPECT_EQ(0u, request_info->cert_authorities.size()); } @@ -1754,36 +1781,39 @@ TEST_F(SSLClientSocketCertRequestInfoTest, TwoAuthorities) { const base::FilePath::CharType kThawteFile[] = FILE_PATH_LITERAL("thawte.single.pem"); const unsigned char kThawteDN[] = { - 0x30, 0x4c, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, - 0x02, 0x5a, 0x41, 0x31, 0x25, 0x30, 0x23, 0x06, 0x03, 0x55, 0x04, 0x0a, - 0x13, 0x1c, 0x54, 0x68, 0x61, 0x77, 0x74, 0x65, 0x20, 0x43, 0x6f, 0x6e, - 0x73, 0x75, 0x6c, 0x74, 0x69, 0x6e, 0x67, 0x20, 0x28, 0x50, 0x74, 0x79, - 0x29, 0x20, 0x4c, 0x74, 0x64, 0x2e, 0x31, 0x16, 0x30, 0x14, 0x06, 0x03, - 0x55, 0x04, 0x03, 0x13, 0x0d, 0x54, 0x68, 0x61, 0x77, 0x74, 0x65, 0x20, - 0x53, 0x47, 0x43, 0x20, 0x43, 0x41}; + 0x30, 0x4c, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, + 0x02, 0x5a, 0x41, 0x31, 0x25, 0x30, 0x23, 0x06, 0x03, 0x55, 0x04, 0x0a, + 0x13, 0x1c, 0x54, 0x68, 0x61, 0x77, 0x74, 0x65, 0x20, 0x43, 0x6f, 0x6e, + 0x73, 0x75, 0x6c, 0x74, 0x69, 0x6e, 0x67, 0x20, 0x28, 0x50, 0x74, 0x79, + 0x29, 0x20, 0x4c, 0x74, 0x64, 0x2e, 0x31, 0x16, 0x30, 0x14, 0x06, 0x03, + 0x55, 0x04, 0x03, 0x13, 0x0d, 0x54, 0x68, 0x61, 0x77, 0x74, 0x65, 0x20, + 0x53, 0x47, 0x43, 0x20, 0x43, 0x41 + }; const size_t kThawteLen = sizeof(kThawteDN); const base::FilePath::CharType kDiginotarFile[] = FILE_PATH_LITERAL("diginotar_root_ca.pem"); const unsigned char kDiginotarDN[] = { - 0x30, 0x5f, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, - 0x02, 0x4e, 0x4c, 0x31, 0x12, 0x30, 0x10, 0x06, 0x03, 0x55, 0x04, 0x0a, - 0x13, 0x09, 0x44, 0x69, 0x67, 0x69, 0x4e, 0x6f, 0x74, 0x61, 0x72, 0x31, - 0x1a, 0x30, 0x18, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x11, 0x44, 0x69, - 0x67, 0x69, 0x4e, 0x6f, 0x74, 0x61, 0x72, 0x20, 0x52, 0x6f, 0x6f, 0x74, - 0x20, 0x43, 0x41, 0x31, 0x20, 0x30, 0x1e, 0x06, 0x09, 0x2a, 0x86, 0x48, - 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x01, 0x16, 0x11, 0x69, 0x6e, 0x66, 0x6f, - 0x40, 0x64, 0x69, 0x67, 0x69, 0x6e, 0x6f, 0x74, 0x61, 0x72, 0x2e, 0x6e, - 0x6c}; + 0x30, 0x5f, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, + 0x02, 0x4e, 0x4c, 0x31, 0x12, 0x30, 0x10, 0x06, 0x03, 0x55, 0x04, 0x0a, + 0x13, 0x09, 0x44, 0x69, 0x67, 0x69, 0x4e, 0x6f, 0x74, 0x61, 0x72, 0x31, + 0x1a, 0x30, 0x18, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x11, 0x44, 0x69, + 0x67, 0x69, 0x4e, 0x6f, 0x74, 0x61, 0x72, 0x20, 0x52, 0x6f, 0x6f, 0x74, + 0x20, 0x43, 0x41, 0x31, 0x20, 0x30, 0x1e, 0x06, 0x09, 0x2a, 0x86, 0x48, + 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x01, 0x16, 0x11, 0x69, 0x6e, 0x66, 0x6f, + 0x40, 0x64, 0x69, 0x67, 0x69, 0x6e, 0x6f, 0x74, 0x61, 0x72, 0x2e, 0x6e, + 0x6c + }; const size_t kDiginotarLen = sizeof(kDiginotarDN); - SpawnedTestServer::SSLOptions ssl_options; + net::SpawnedTestServer::SSLOptions ssl_options; ssl_options.request_client_certificate = true; ssl_options.client_authorities.push_back( - GetTestClientCertsDirectory().Append(kThawteFile)); + net::GetTestClientCertsDirectory().Append(kThawteFile)); ssl_options.client_authorities.push_back( - GetTestClientCertsDirectory().Append(kDiginotarFile)); - scoped_refptr<SSLCertRequestInfo> request_info = GetCertRequest(ssl_options); + net::GetTestClientCertsDirectory().Append(kDiginotarFile)); + scoped_refptr<net::SSLCertRequestInfo> request_info = + GetCertRequest(ssl_options); ASSERT_TRUE(request_info.get()); ASSERT_EQ(2u, request_info->cert_authorities.size()); EXPECT_EQ(std::string(reinterpret_cast<const char*>(kThawteDN), kThawteLen), @@ -1792,7 +1822,3 @@ TEST_F(SSLClientSocketCertRequestInfoTest, TwoAuthorities) { std::string(reinterpret_cast<const char*>(kDiginotarDN), kDiginotarLen), request_info->cert_authorities[1]); } - -} // namespace - -} // namespace net diff --git a/chromium/net/socket/ssl_server_socket.h b/chromium/net/socket/ssl_server_socket.h index 8b607bf80cf..52d53cb19a2 100644 --- a/chromium/net/socket/ssl_server_socket.h +++ b/chromium/net/socket/ssl_server_socket.h @@ -6,7 +6,6 @@ #define NET_SOCKET_SSL_SERVER_SOCKET_H_ #include "base/basictypes.h" -#include "base/memory/scoped_ptr.h" #include "net/base/completion_callback.h" #include "net/base/net_export.h" #include "net/socket/ssl_socket.h" @@ -53,8 +52,8 @@ NET_EXPORT void EnableSSLServerSockets(); // // The caller starts the SSL server handshake by calling Handshake on the // returned socket. -NET_EXPORT scoped_ptr<SSLServerSocket> CreateSSLServerSocket( - scoped_ptr<StreamSocket> socket, +NET_EXPORT SSLServerSocket* CreateSSLServerSocket( + StreamSocket* socket, X509Certificate* certificate, crypto::RSAPrivateKey* key, const SSLConfig& ssl_config); diff --git a/chromium/net/socket/ssl_server_socket_nss.cc b/chromium/net/socket/ssl_server_socket_nss.cc index 7e5d70118ac..c2681d3ee14 100644 --- a/chromium/net/socket/ssl_server_socket_nss.cc +++ b/chromium/net/socket/ssl_server_socket_nss.cc @@ -78,20 +78,19 @@ void EnableSSLServerSockets() { g_nss_ssl_server_init_singleton.Get(); } -scoped_ptr<SSLServerSocket> CreateSSLServerSocket( - scoped_ptr<StreamSocket> socket, +SSLServerSocket* CreateSSLServerSocket( + StreamSocket* socket, X509Certificate* cert, crypto::RSAPrivateKey* key, const SSLConfig& ssl_config) { DCHECK(g_nss_server_sockets_init) << "EnableSSLServerSockets() has not been" << "called yet!"; - return scoped_ptr<SSLServerSocket>( - new SSLServerSocketNSS(socket.Pass(), cert, key, ssl_config)); + return new SSLServerSocketNSS(socket, cert, key, ssl_config); } SSLServerSocketNSS::SSLServerSocketNSS( - scoped_ptr<StreamSocket> transport_socket, + StreamSocket* transport_socket, scoped_refptr<X509Certificate> cert, crypto::RSAPrivateKey* key, const SSLConfig& ssl_config) @@ -101,7 +100,7 @@ SSLServerSocketNSS::SSLServerSocketNSS( user_write_buf_len_(0), nss_fd_(NULL), nss_bufs_(NULL), - transport_socket_(transport_socket.Pass()), + transport_socket_(transport_socket), ssl_config_(ssl_config), cert_(cert), next_handshake_state_(STATE_NONE), diff --git a/chromium/net/socket/ssl_server_socket_nss.h b/chromium/net/socket/ssl_server_socket_nss.h index 8bbb0e338ac..17a1fc38750 100644 --- a/chromium/net/socket/ssl_server_socket_nss.h +++ b/chromium/net/socket/ssl_server_socket_nss.h @@ -24,7 +24,7 @@ class SSLServerSocketNSS : public SSLServerSocket { public: // See comments on CreateSSLServerSocket for details of how these // parameters are used. - SSLServerSocketNSS(scoped_ptr<StreamSocket> socket, + SSLServerSocketNSS(StreamSocket* socket, scoped_refptr<X509Certificate> certificate, crypto::RSAPrivateKey* key, const SSLConfig& ssl_config); diff --git a/chromium/net/socket/ssl_server_socket_openssl.cc b/chromium/net/socket/ssl_server_socket_openssl.cc index c327f2caf10..e0cf8bc0b21 100644 --- a/chromium/net/socket/ssl_server_socket_openssl.cc +++ b/chromium/net/socket/ssl_server_socket_openssl.cc @@ -16,13 +16,13 @@ void EnableSSLServerSockets() { NOTIMPLEMENTED(); } -scoped_ptr<SSLServerSocket> CreateSSLServerSocket( - scoped_ptr<StreamSocket> socket, - X509Certificate* certificate, - crypto::RSAPrivateKey* key, - const SSLConfig& ssl_config) { +SSLServerSocket* CreateSSLServerSocket(StreamSocket* socket, + X509Certificate* certificate, + crypto::RSAPrivateKey* key, + const SSLConfig& ssl_config) { NOTIMPLEMENTED(); - return scoped_ptr<SSLServerSocket>(); + delete socket; + return NULL; } } // namespace net diff --git a/chromium/net/socket/ssl_server_socket_unittest.cc b/chromium/net/socket/ssl_server_socket_unittest.cc index 64c85490b29..f931e2c957e 100644 --- a/chromium/net/socket/ssl_server_socket_unittest.cc +++ b/chromium/net/socket/ssl_server_socket_unittest.cc @@ -304,11 +304,8 @@ class SSLServerSocketTest : public PlatformTest { protected: void Initialize() { - scoped_ptr<ClientSocketHandle> client_connection(new ClientSocketHandle); - client_connection->SetSocket( - scoped_ptr<StreamSocket>(new FakeSocket(&channel_1_, &channel_2_))); - scoped_ptr<StreamSocket> server_socket( - new FakeSocket(&channel_2_, &channel_1_)); + FakeSocket* fake_client_socket = new FakeSocket(&channel_1_, &channel_2_); + FakeSocket* fake_server_socket = new FakeSocket(&channel_2_, &channel_1_); base::FilePath certs_dir(GetTestCertsDirectory()); @@ -347,12 +344,11 @@ class SSLServerSocketTest : public PlatformTest { net::SSLClientSocketContext context; context.cert_verifier = cert_verifier_.get(); context.transport_security_state = transport_security_state_.get(); - client_socket_ = + client_socket_.reset( socket_factory_->CreateSSLClientSocket( - client_connection.Pass(), host_and_pair, ssl_config, context); - server_socket_ = net::CreateSSLServerSocket( - server_socket.Pass(), - cert.get(), private_key.get(), net::SSLConfig()); + fake_client_socket, host_and_pair, ssl_config, context)); + server_socket_.reset(net::CreateSSLServerSocket( + fake_server_socket, cert.get(), private_key.get(), net::SSLConfig())); } FakeDataChannel channel_1_; diff --git a/chromium/net/socket/transport_client_socket_pool.cc b/chromium/net/socket/transport_client_socket_pool.cc index 6d0afac59fb..8255e988fa4 100644 --- a/chromium/net/socket/transport_client_socket_pool.cc +++ b/chromium/net/socket/transport_client_socket_pool.cc @@ -190,8 +190,8 @@ int TransportConnectJob::DoResolveHostComplete(int result) { int TransportConnectJob::DoTransportConnect() { next_state_ = STATE_TRANSPORT_CONNECT_COMPLETE; - transport_socket_ = client_socket_factory_->CreateTransportClientSocket( - addresses_, net_log().net_log(), net_log().source()); + transport_socket_.reset(client_socket_factory_->CreateTransportClientSocket( + addresses_, net_log().net_log(), net_log().source())); int rv = transport_socket_->Connect( base::Bind(&TransportConnectJob::OnIOComplete, base::Unretained(this))); if (rv == ERR_IO_PENDING && @@ -246,7 +246,7 @@ int TransportConnectJob::DoTransportConnectComplete(int result) { 100); } } - SetSocket(transport_socket_.Pass()); + set_socket(transport_socket_.release()); fallback_timer_.Stop(); } else { // Be a bit paranoid and kill off the fallback members to prevent reuse. @@ -270,9 +270,9 @@ void TransportConnectJob::DoIPv6FallbackTransportConnect() { fallback_addresses_.reset(new AddressList(addresses_)); MakeAddressListStartWithIPv4(fallback_addresses_.get()); - fallback_transport_socket_ = + fallback_transport_socket_.reset( client_socket_factory_->CreateTransportClientSocket( - *fallback_addresses_, net_log().net_log(), net_log().source()); + *fallback_addresses_, net_log().net_log(), net_log().source())); fallback_connect_start_time_ = base::TimeTicks::Now(); int rv = fallback_transport_socket_->Connect( base::Bind( @@ -317,7 +317,7 @@ void TransportConnectJob::DoIPv6FallbackTransportConnectComplete(int result) { base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(10), 100); - SetSocket(fallback_transport_socket_.Pass()); + set_socket(fallback_transport_socket_.release()); next_state_ = STATE_NONE; transport_socket_.reset(); } else { @@ -333,19 +333,18 @@ int TransportConnectJob::ConnectInternal() { return DoLoop(OK); } -scoped_ptr<ConnectJob> +ConnectJob* TransportClientSocketPool::TransportConnectJobFactory::NewConnectJob( const std::string& group_name, const PoolBase::Request& request, ConnectJob::Delegate* delegate) const { - return scoped_ptr<ConnectJob>( - new TransportConnectJob(group_name, - request.params(), - ConnectionTimeout(), - client_socket_factory_, - host_resolver_, - delegate, - net_log_)); + return new TransportConnectJob(group_name, + request.params(), + ConnectionTimeout(), + client_socket_factory_, + host_resolver_, + delegate, + net_log_); } base::TimeDelta @@ -420,9 +419,9 @@ void TransportClientSocketPool::CancelRequest( void TransportClientSocketPool::ReleaseSocket( const std::string& group_name, - scoped_ptr<StreamSocket> socket, + StreamSocket* socket, int id) { - base_.ReleaseSocket(group_name, socket.Pass(), id); + base_.ReleaseSocket(group_name, socket, id); } void TransportClientSocketPool::FlushWithError(int error) { diff --git a/chromium/net/socket/transport_client_socket_pool.h b/chromium/net/socket/transport_client_socket_pool.h index f07dc1f5675..bb53b3da301 100644 --- a/chromium/net/socket/transport_client_socket_pool.h +++ b/chromium/net/socket/transport_client_socket_pool.h @@ -156,7 +156,7 @@ class NET_EXPORT_PRIVATE TransportClientSocketPool : public ClientSocketPool { virtual void CancelRequest(const std::string& group_name, ClientSocketHandle* handle) OVERRIDE; virtual void ReleaseSocket(const std::string& group_name, - scoped_ptr<StreamSocket> socket, + StreamSocket* socket, int id) OVERRIDE; virtual void FlushWithError(int error) OVERRIDE; virtual bool IsStalled() const OVERRIDE; @@ -193,7 +193,7 @@ class NET_EXPORT_PRIVATE TransportClientSocketPool : public ClientSocketPool { // ClientSocketPoolBase::ConnectJobFactory methods. - virtual scoped_ptr<ConnectJob> NewConnectJob( + virtual ConnectJob* NewConnectJob( const std::string& group_name, const PoolBase::Request& request, ConnectJob::Delegate* delegate) const OVERRIDE; diff --git a/chromium/net/socket/transport_client_socket_pool_unittest.cc b/chromium/net/socket/transport_client_socket_pool_unittest.cc index c607a38b78a..dfa1151b291 100644 --- a/chromium/net/socket/transport_client_socket_pool_unittest.cc +++ b/chromium/net/socket/transport_client_socket_pool_unittest.cc @@ -23,7 +23,6 @@ #include "net/socket/client_socket_handle.h" #include "net/socket/client_socket_pool_histograms.h" #include "net/socket/socket_test_util.h" -#include "net/socket/ssl_client_socket.h" #include "net/socket/stream_socket.h" #include "testing/gtest/include/gtest/gtest.h" @@ -341,16 +340,16 @@ class MockClientSocketFactory : public ClientSocketFactory { delay_(base::TimeDelta::FromMilliseconds( ClientSocketPool::kMaxConnectRetryIntervalMs)) {} - virtual scoped_ptr<DatagramClientSocket> CreateDatagramClientSocket( + virtual DatagramClientSocket* CreateDatagramClientSocket( DatagramSocket::BindType bind_type, const RandIntCallback& rand_int_cb, NetLog* net_log, const NetLog::Source& source) OVERRIDE { NOTREACHED(); - return scoped_ptr<DatagramClientSocket>(); + return NULL; } - virtual scoped_ptr<StreamSocket> CreateTransportClientSocket( + virtual StreamSocket* CreateTransportClientSocket( const AddressList& addresses, NetLog* /* net_log */, const NetLog::Source& /* source */) OVERRIDE { @@ -364,41 +363,34 @@ class MockClientSocketFactory : public ClientSocketFactory { switch (type) { case MOCK_CLIENT_SOCKET: - return scoped_ptr<StreamSocket>( - new MockClientSocket(addresses, net_log_)); + return new MockClientSocket(addresses, net_log_); case MOCK_FAILING_CLIENT_SOCKET: - return scoped_ptr<StreamSocket>( - new MockFailingClientSocket(addresses, net_log_)); + return new MockFailingClientSocket(addresses, net_log_); case MOCK_PENDING_CLIENT_SOCKET: - return scoped_ptr<StreamSocket>( - new MockPendingClientSocket( - addresses, true, false, base::TimeDelta(), net_log_)); + return new MockPendingClientSocket( + addresses, true, false, base::TimeDelta(), net_log_); case MOCK_PENDING_FAILING_CLIENT_SOCKET: - return scoped_ptr<StreamSocket>( - new MockPendingClientSocket( - addresses, false, false, base::TimeDelta(), net_log_)); + return new MockPendingClientSocket( + addresses, false, false, base::TimeDelta(), net_log_); case MOCK_DELAYED_CLIENT_SOCKET: - return scoped_ptr<StreamSocket>( - new MockPendingClientSocket( - addresses, true, false, delay_, net_log_)); + return new MockPendingClientSocket( + addresses, true, false, delay_, net_log_); case MOCK_STALLED_CLIENT_SOCKET: - return scoped_ptr<StreamSocket>( - new MockPendingClientSocket( - addresses, true, true, base::TimeDelta(), net_log_)); + return new MockPendingClientSocket( + addresses, true, true, base::TimeDelta(), net_log_); default: NOTREACHED(); - return scoped_ptr<StreamSocket>( - new MockClientSocket(addresses, net_log_)); + return new MockClientSocket(addresses, net_log_); } } - virtual scoped_ptr<SSLClientSocket> CreateSSLClientSocket( - scoped_ptr<ClientSocketHandle> transport_socket, + virtual SSLClientSocket* CreateSSLClientSocket( + ClientSocketHandle* transport_socket, const HostPortPair& host_and_port, const SSLConfig& ssl_config, const SSLClientSocketContext& context) OVERRIDE { NOTIMPLEMENTED(); - return scoped_ptr<SSLClientSocket>(); + return NULL; } virtual void ClearSSLSessionCache() OVERRIDE { diff --git a/chromium/net/socket/transport_client_socket_unittest.cc b/chromium/net/socket/transport_client_socket_unittest.cc index 5c5a303b82f..2f75e740067 100644 --- a/chromium/net/socket/transport_client_socket_unittest.cc +++ b/chromium/net/socket/transport_client_socket_unittest.cc @@ -130,10 +130,10 @@ void TransportClientSocketTest::SetUp() { CHECK_EQ(ERR_IO_PENDING, rv); rv = callback.WaitForResult(); CHECK_EQ(rv, OK); - sock_ = + sock_.reset( socket_factory_->CreateTransportClientSocket(addr, &net_log_, - NetLog::Source()); + NetLog::Source())); } int TransportClientSocketTest::DrainClientSocket( diff --git a/chromium/net/socket_stream/socket_stream.cc b/chromium/net/socket_stream/socket_stream.cc index c549fcb9768..dca994cbada 100644 --- a/chromium/net/socket_stream/socket_stream.cc +++ b/chromium/net/socket_stream/socket_stream.cc @@ -33,7 +33,6 @@ #include "net/http/http_transaction_factory.h" #include "net/http/http_util.h" #include "net/socket/client_socket_factory.h" -#include "net/socket/client_socket_handle.h" #include "net/socket/socks5_client_socket.h" #include "net/socket/socks_client_socket.h" #include "net/socket/ssl_client_socket.h" @@ -97,7 +96,6 @@ SocketStream::SocketStream(const GURL& url, Delegate* delegate) proxy_mode_(kDirectConnection), proxy_url_(url), pac_request_(NULL), - connection_(new ClientSocketHandle), privacy_mode_(kPrivacyModeDisabled), // Unretained() is required; without it, Bind() creates a circular // dependency and the SocketStream object will not be freed. @@ -207,10 +205,8 @@ bool SocketStream::SendData(const char* data, int len) { << "The current base::MessageLoop must be TYPE_IO"; DCHECK_GT(len, 0); - if (!connection_->socket() || - !connection_->socket()->IsConnected() || next_state_ == STATE_NONE) { + if (!socket_.get() || !socket_->IsConnected() || next_state_ == STATE_NONE) return false; - } int total_buffered_bytes = len; if (current_write_buf_.get()) { @@ -268,7 +264,7 @@ void SocketStream::RestartWithAuth(const AuthCredentials& credentials) { DCHECK_EQ(base::MessageLoop::TYPE_IO, base::MessageLoop::current()->type()) << "The current base::MessageLoop must be TYPE_IO"; DCHECK(proxy_auth_controller_.get()); - if (!connection_->socket()) { + if (!socket_.get()) { DVLOG(1) << "Socket is closed before restarting with auth."; return; } @@ -373,7 +369,7 @@ void SocketStream::Finish(int result) { } int SocketStream::DidEstablishConnection() { - if (!connection_->socket() || !connection_->socket()->IsConnected()) { + if (!socket_.get() || !socket_->IsConnected()) { next_state_ = STATE_CLOSE; return ERR_CONNECTION_FAILED; } @@ -734,12 +730,11 @@ int SocketStream::DoTcpConnect(int result) { } next_state_ = STATE_TCP_CONNECT_COMPLETE; DCHECK(factory_); - connection_->SetSocket( - factory_->CreateTransportClientSocket(addresses_, - net_log_.net_log(), - net_log_.source())); + socket_.reset(factory_->CreateTransportClientSocket(addresses_, + net_log_.net_log(), + net_log_.source())); metrics_->OnStartConnection(); - return connection_->socket()->Connect(io_callback_); + return socket_->Connect(io_callback_); } int SocketStream::DoTcpConnectComplete(int result) { @@ -824,8 +819,7 @@ int SocketStream::DoWriteTunnelHeaders() { int buf_len = static_cast<int>(tunnel_request_headers_->headers_.size() - tunnel_request_headers_bytes_sent_); DCHECK_GT(buf_len, 0); - return connection_->socket()->Write( - tunnel_request_headers_.get(), buf_len, io_callback_); + return socket_->Write(tunnel_request_headers_.get(), buf_len, io_callback_); } int SocketStream::DoWriteTunnelHeadersComplete(int result) { @@ -868,8 +862,7 @@ int SocketStream::DoReadTunnelHeaders() { tunnel_response_headers_->SetDataOffset(tunnel_response_headers_len_); CHECK(tunnel_response_headers_->data()); - return connection_->socket()->Read( - tunnel_response_headers_.get(), buf_len, io_callback_); + return socket_->Read(tunnel_response_headers_.get(), buf_len, io_callback_); } int SocketStream::DoReadTunnelHeadersComplete(int result) { @@ -960,20 +953,17 @@ int SocketStream::DoSOCKSConnect() { next_state_ = STATE_SOCKS_CONNECT_COMPLETE; + StreamSocket* s = socket_.release(); HostResolver::RequestInfo req_info(HostPortPair::FromURL(url_)); DCHECK(!proxy_info_.is_empty()); - scoped_ptr<StreamSocket> s; - if (proxy_info_.proxy_server().scheme() == ProxyServer::SCHEME_SOCKS5) { - s.reset(new SOCKS5ClientSocket(connection_.Pass(), req_info)); - } else { - s.reset(new SOCKSClientSocket( - connection_.Pass(), req_info, context_->host_resolver())); - } - connection_.reset(new ClientSocketHandle); - connection_->SetSocket(s.Pass()); + if (proxy_info_.proxy_server().scheme() == ProxyServer::SCHEME_SOCKS5) + s = new SOCKS5ClientSocket(s, req_info); + else + s = new SOCKSClientSocket(s, req_info, context_->host_resolver()); + socket_.reset(s); metrics_->OnCountConnectionType(SocketStreamMetrics::SOCKS_CONNECTION); - return connection_->socket()->Connect(io_callback_); + return socket_->Connect(io_callback_); } int SocketStream::DoSOCKSConnectComplete(int result) { @@ -996,16 +986,14 @@ int SocketStream::DoSecureProxyConnect() { ssl_context.cert_verifier = context_->cert_verifier(); ssl_context.transport_security_state = context_->transport_security_state(); ssl_context.server_bound_cert_service = context_->server_bound_cert_service(); - scoped_ptr<StreamSocket> socket(factory_->CreateSSLClientSocket( - connection_.Pass(), + socket_.reset(factory_->CreateSSLClientSocket( + socket_.release(), proxy_info_.proxy_server().host_port_pair(), proxy_ssl_config_, ssl_context)); - connection_.reset(new ClientSocketHandle); - connection_->SetSocket(socket.Pass()); next_state_ = STATE_SECURE_PROXY_CONNECT_COMPLETE; metrics_->OnCountConnectionType(SocketStreamMetrics::SECURE_PROXY_CONNECTION); - return connection_->socket()->Connect(io_callback_); + return socket_->Connect(io_callback_); } int SocketStream::DoSecureProxyConnectComplete(int result) { @@ -1037,7 +1025,7 @@ int SocketStream::DoSecureProxyHandleCertError(int result) { int SocketStream::DoSecureProxyHandleCertErrorComplete(int result) { DCHECK_EQ(STATE_NONE, next_state_); if (result == OK) { - if (!connection_->socket()->IsConnectedAndIdle()) + if (!socket_->IsConnectedAndIdle()) return AllowCertErrorForReconnection(&proxy_ssl_config_); next_state_ = STATE_GENERATE_PROXY_AUTH_TOKEN; } else { @@ -1052,16 +1040,13 @@ int SocketStream::DoSSLConnect() { ssl_context.cert_verifier = context_->cert_verifier(); ssl_context.transport_security_state = context_->transport_security_state(); ssl_context.server_bound_cert_service = context_->server_bound_cert_service(); - scoped_ptr<StreamSocket> socket( - factory_->CreateSSLClientSocket(connection_.Pass(), - HostPortPair::FromURL(url_), - server_ssl_config_, - ssl_context)); - connection_.reset(new ClientSocketHandle); - connection_->SetSocket(socket.Pass()); + socket_.reset(factory_->CreateSSLClientSocket(socket_.release(), + HostPortPair::FromURL(url_), + server_ssl_config_, + ssl_context)); next_state_ = STATE_SSL_CONNECT_COMPLETE; metrics_->OnCountConnectionType(SocketStreamMetrics::SSL_CONNECTION); - return connection_->socket()->Connect(io_callback_); + return socket_->Connect(io_callback_); } int SocketStream::DoSSLConnectComplete(int result) { @@ -1097,7 +1082,7 @@ int SocketStream::DoSSLHandleCertErrorComplete(int result) { // we should take care of TLS NPN extension here. if (result == OK) { - if (!connection_->socket()->IsConnectedAndIdle()) + if (!socket_->IsConnectedAndIdle()) return AllowCertErrorForReconnection(&server_ssl_config_); result = DidEstablishConnection(); } else { @@ -1111,7 +1096,7 @@ int SocketStream::DoReadWrite(int result) { next_state_ = STATE_CLOSE; return result; } - if (!connection_->socket() || !connection_->socket()->IsConnected()) { + if (!socket_.get() || !socket_->IsConnected()) { next_state_ = STATE_CLOSE; return ERR_CONNECTION_CLOSED; } @@ -1120,7 +1105,7 @@ int SocketStream::DoReadWrite(int result) { // let's close the socket. // We don't care about receiving data after the socket is closed. if (closing_ && !current_write_buf_.get() && pending_write_bufs_.empty()) { - connection_->socket()->Disconnect(); + socket_->Disconnect(); next_state_ = STATE_CLOSE; return OK; } @@ -1132,7 +1117,7 @@ int SocketStream::DoReadWrite(int result) { if (!read_buf_.get()) { // No read pending and server didn't close the socket. read_buf_ = new IOBuffer(kReadBufferSize); - result = connection_->socket()->Read( + result = socket_->Read( read_buf_.get(), kReadBufferSize, base::Bind(&SocketStream::OnReadCompleted, base::Unretained(this))); @@ -1171,7 +1156,7 @@ int SocketStream::DoReadWrite(int result) { pending_write_bufs_.pop_front(); } - result = connection_->socket()->Write( + result = socket_->Write( current_write_buf_.get(), current_write_buf_->BytesRemaining(), base::Bind(&SocketStream::OnWriteCompleted, base::Unretained(this))); @@ -1203,10 +1188,10 @@ int SocketStream::HandleCertificateRequest(int result, SSLConfig* ssl_config) { return result; } - DCHECK(connection_->socket()); + DCHECK(socket_.get()); scoped_refptr<SSLCertRequestInfo> cert_request_info = new SSLCertRequestInfo; SSLClientSocket* ssl_socket = - static_cast<SSLClientSocket*>(connection_->socket()); + static_cast<SSLClientSocket*>(socket_.get()); ssl_socket->GetSSLCertRequestInfo(cert_request_info.get()); HttpTransactionFactory* factory = context_->http_transaction_factory(); @@ -1252,8 +1237,7 @@ int SocketStream::AllowCertErrorForReconnection(SSLConfig* ssl_config) { // allowed bad certificates in |ssl_config|. // See also net/http/http_network_transaction.cc HandleCertificateError() and // RestartIgnoringLastError(). - SSLClientSocket* ssl_socket = - static_cast<SSLClientSocket*>(connection_->socket()); + SSLClientSocket* ssl_socket = static_cast<SSLClientSocket*>(socket_.get()); SSLInfo ssl_info; ssl_socket->GetSSLInfo(&ssl_info); if (ssl_info.cert.get() == NULL || @@ -1275,8 +1259,8 @@ int SocketStream::AllowCertErrorForReconnection(SSLConfig* ssl_config) { bad_cert.cert_status = ssl_info.cert_status; ssl_config->allowed_bad_certs.push_back(bad_cert); // Restart connection ignoring the bad certificate. - connection_->socket()->Disconnect(); - connection_->SetSocket(scoped_ptr<StreamSocket>()); + socket_->Disconnect(); + socket_.reset(); next_state_ = STATE_TCP_CONNECT; return OK; } @@ -1302,8 +1286,7 @@ void SocketStream::DoRestartWithAuth() { int SocketStream::HandleCertificateError(int result) { DCHECK(IsCertificateError(result)); - SSLClientSocket* ssl_socket = - static_cast<SSLClientSocket*>(connection_->socket()); + SSLClientSocket* ssl_socket = static_cast<SSLClientSocket*>(socket_.get()); DCHECK(ssl_socket); if (!context_) diff --git a/chromium/net/socket_stream/socket_stream.h b/chromium/net/socket_stream/socket_stream.h index 90aeb8c54b9..5004060df9a 100644 --- a/chromium/net/socket_stream/socket_stream.h +++ b/chromium/net/socket_stream/socket_stream.h @@ -28,13 +28,13 @@ namespace net { class AuthChallengeInfo; class CertVerifier; class ClientSocketFactory; -class ClientSocketHandle; class CookieOptions; class HostResolver; class HttpAuthController; class SSLInfo; class ServerBoundCertService; class SingleRequestHostResolver; +class StreamSocket; class SocketStreamMetrics; class TransportSecurityState; class URLRequestContext; @@ -364,7 +364,7 @@ class NET_EXPORT SocketStream scoped_ptr<SingleRequestHostResolver> resolver_; AddressList addresses_; - scoped_ptr<ClientSocketHandle> connection_; + scoped_ptr<StreamSocket> socket_; SSLConfig server_ssl_config_; SSLConfig proxy_ssl_config_; diff --git a/chromium/net/spdy/spdy_credential_builder_unittest.cc b/chromium/net/spdy/spdy_credential_builder_unittest.cc index f82f2f5860f..bc67cc593ae 100644 --- a/chromium/net/spdy/spdy_credential_builder_unittest.cc +++ b/chromium/net/spdy/spdy_credential_builder_unittest.cc @@ -31,8 +31,9 @@ void CreateCertAndKey(std::string* cert, std::string* key) { TestCompletionCallback callback; ServerBoundCertService::RequestHandle request_handle; - int rv = server_bound_cert_service->GetOrCreateDomainBoundCert( - "www.google.com", key, cert, callback.callback(), &request_handle); + int rv = server_bound_cert_service->GetDomainBoundCert( + "www.google.com", key, cert, + callback.callback(), &request_handle); EXPECT_EQ(ERR_IO_PENDING, rv); EXPECT_EQ(OK, callback.WaitForResult()); diff --git a/chromium/net/spdy/spdy_http_stream.cc b/chromium/net/spdy/spdy_http_stream.cc index 4d9117514ab..08e8b58bf61 100644 --- a/chromium/net/spdy/spdy_http_stream.cc +++ b/chromium/net/spdy/spdy_http_stream.cc @@ -524,9 +524,4 @@ void SpdyHttpStream::Drain(HttpNetworkSession* session) { delete this; } -void SpdyHttpStream::SetPriority(RequestPriority priority) { - // TODO(akalin): Plumb this through to |stream_request_| and - // |stream_|. -} - } // namespace net diff --git a/chromium/net/spdy/spdy_http_stream.h b/chromium/net/spdy/spdy_http_stream.h index f6e39cd102e..65d98784181 100644 --- a/chromium/net/spdy/spdy_http_stream.h +++ b/chromium/net/spdy/spdy_http_stream.h @@ -73,7 +73,6 @@ class NET_EXPORT_PRIVATE SpdyHttpStream : public SpdyStream::Delegate, SSLCertRequestInfo* cert_request_info) OVERRIDE; virtual bool IsSpdyHttpStream() const OVERRIDE; virtual void Drain(HttpNetworkSession* session) OVERRIDE; - virtual void SetPriority(RequestPriority priority) OVERRIDE; // SpdyStream::Delegate implementation. virtual void OnRequestHeadersSent() OVERRIDE; diff --git a/chromium/net/spdy/spdy_http_stream_unittest.cc b/chromium/net/spdy/spdy_http_stream_unittest.cc index d88c963cd9a..55387cf410a 100644 --- a/chromium/net/spdy/spdy_http_stream_unittest.cc +++ b/chromium/net/spdy/spdy_http_stream_unittest.cc @@ -542,7 +542,7 @@ void GetECServerBoundCertAndProof( TestCompletionCallback callback; std::string key; ServerBoundCertService::RequestHandle request_handle; - int rv = server_bound_cert_service->GetOrCreateDomainBoundCert( + int rv = server_bound_cert_service->GetDomainBoundCert( host, &key, cert, callback.callback(), &request_handle); EXPECT_EQ(ERR_IO_PENDING, rv); diff --git a/chromium/net/spdy/spdy_network_transaction_unittest.cc b/chromium/net/spdy/spdy_network_transaction_unittest.cc index f3f9f344995..98c4d134b4a 100644 --- a/chromium/net/spdy/spdy_network_transaction_unittest.cc +++ b/chromium/net/spdy/spdy_network_transaction_unittest.cc @@ -10,7 +10,6 @@ #include "base/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/memory/scoped_vector.h" -#include "base/run_loop.h" #include "base/stl_util.h" #include "net/base/auth.h" #include "net/base/net_log_unittest.h" @@ -81,13 +80,6 @@ class SpdyNetworkTransactionTest SpdyNetworkTransactionTest() : spdy_util_(GetParam().protocol) { } - virtual ~SpdyNetworkTransactionTest() { - // UploadDataStream posts deletion tasks back to the message loop on - // destruction. - upload_data_stream_.reset(); - base::RunLoop().RunUntilIdle(); - } - virtual void SetUp() { google_get_request_initialized_ = false; google_post_request_initialized_ = false; @@ -95,6 +87,11 @@ class SpdyNetworkTransactionTest ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); } + virtual void TearDown() { + // Empty the current queue. + base::MessageLoop::current()->RunUntilIdle(); + } + struct TransactionHelperResult { int rv; std::string status_line; @@ -522,7 +519,7 @@ class SpdyNetworkTransactionTest // reads until we complete our callback. while (!callback.have_result()) { data->CompleteRead(); - base::RunLoop().RunUntilIdle(); + base::MessageLoop::current()->RunUntilIdle(); } rv = callback.WaitForResult(); } else if (rv <= 0) { @@ -576,7 +573,7 @@ class SpdyNetworkTransactionTest rv = trans2->Start( &CreateGetPushRequest(), callback.callback(), BoundNetLog()); EXPECT_EQ(ERR_IO_PENDING, rv); - base::RunLoop().RunUntilIdle(); + base::MessageLoop::current()->RunUntilIdle(); // The data for the pushed path may be coming in more than 1 frame. Compile // the results into a single string. @@ -1883,10 +1880,10 @@ TEST_P(SpdyNetworkTransactionTest, DelayedChunkedPost) { helper.AddData(&data); ASSERT_TRUE(helper.StartDefaultTest()); - base::RunLoop().RunUntilIdle(); + base::MessageLoop::current()->RunUntilIdle(); helper.request().upload_data_stream->AppendChunk( kUploadData, kUploadDataSize, false); - base::RunLoop().RunUntilIdle(); + base::MessageLoop::current()->RunUntilIdle(); helper.request().upload_data_stream->AppendChunk( kUploadData, kUploadDataSize, true); @@ -2255,7 +2252,7 @@ TEST_P(SpdyNetworkTransactionTest, CancelledTransaction) { // Flush the MessageLoop while the SpdySessionDependencies (in particular, the // MockClientSocketFactory) are still alive. - base::RunLoop().RunUntilIdle(); + base::MessageLoop::current()->RunUntilIdle(); helper.VerifyDataNotConsumed(); } @@ -2411,7 +2408,7 @@ TEST_P(SpdyNetworkTransactionTest, DeleteSessionOnReadCallback) { data.CompleteRead(); // Finish running rest of tasks. - base::RunLoop().RunUntilIdle(); + base::MessageLoop::current()->RunUntilIdle(); helper.VerifyDataConsumed(); } @@ -2472,12 +2469,12 @@ TEST_P(SpdyNetworkTransactionTest, RedirectGetRequest) { d.set_quit_on_redirect(true); r.Start(); - base::RunLoop().Run(); + base::MessageLoop::current()->Run(); EXPECT_EQ(1, d.received_redirect_count()); r.FollowDeferredRedirect(); - base::RunLoop().Run(); + base::MessageLoop::current()->Run(); EXPECT_EQ(1, d.response_started_count()); EXPECT_FALSE(d.received_data_before_response()); EXPECT_EQ(net::URLRequestStatus::SUCCESS, r.status().status()); @@ -2562,7 +2559,7 @@ TEST_P(SpdyNetworkTransactionTest, RedirectServerPush) { AddSocketDataProvider(&data); r.Start(); - base::RunLoop().Run(); + base::MessageLoop::current()->Run(); EXPECT_EQ(0, d.received_redirect_count()); std::string contents("hello!"); @@ -2575,11 +2572,11 @@ TEST_P(SpdyNetworkTransactionTest, RedirectServerPush) { d2.set_quit_on_redirect(true); r2.Start(); - base::RunLoop().Run(); + base::MessageLoop::current()->Run(); EXPECT_EQ(1, d2.received_redirect_count()); r2.FollowDeferredRedirect(); - base::RunLoop().Run(); + base::MessageLoop::current()->Run(); EXPECT_EQ(1, d2.response_started_count()); EXPECT_FALSE(d2.received_data_before_response()); EXPECT_EQ(net::URLRequestStatus::SUCCESS, r2.status().status()); @@ -3789,7 +3786,7 @@ TEST_P(SpdyNetworkTransactionTest, BufferFull) { // Flush the MessageLoop while the SpdySessionDependencies (in particular, the // MockClientSocketFactory) are still alive. - base::RunLoop().RunUntilIdle(); + base::MessageLoop::current()->RunUntilIdle(); // Verify that we consumed all test data. helper.VerifyDataConsumed(); @@ -3886,7 +3883,7 @@ TEST_P(SpdyNetworkTransactionTest, Buffering) { // Flush the MessageLoop while the SpdySessionDependencies (in particular, the // MockClientSocketFactory) are still alive. - base::RunLoop().RunUntilIdle(); + base::MessageLoop::current()->RunUntilIdle(); // Verify that we consumed all test data. helper.VerifyDataConsumed(); @@ -3980,7 +3977,7 @@ TEST_P(SpdyNetworkTransactionTest, BufferedAll) { // Flush the MessageLoop while the SpdySessionDependencies (in particular, the // MockClientSocketFactory) are still alive. - base::RunLoop().RunUntilIdle(); + base::MessageLoop::current()->RunUntilIdle(); // Verify that we consumed all test data. helper.VerifyDataConsumed(); @@ -4075,7 +4072,7 @@ TEST_P(SpdyNetworkTransactionTest, BufferedClosed) { // Flush the MessageLoop while the SpdySessionDependencies (in particular, the // MockClientSocketFactory) are still alive. - base::RunLoop().RunUntilIdle(); + base::MessageLoop::current()->RunUntilIdle(); // Verify that we consumed all test data. helper.VerifyDataConsumed(); @@ -4146,7 +4143,7 @@ TEST_P(SpdyNetworkTransactionTest, BufferedCancelled) { // Flush the MessageLoop; this will cause the buffered IO task // to run for the final time. - base::RunLoop().RunUntilIdle(); + base::MessageLoop::current()->RunUntilIdle(); // Verify that we consumed all test data. helper.VerifyDataConsumed(); @@ -4790,7 +4787,7 @@ TEST_P(SpdyNetworkTransactionTest, VerifyRetryOnConnectionReset) { if (variant == VARIANT_RST_DURING_READ_COMPLETION) { // Writes to the socket complete asynchronously on SPDY by running // through the message loop. Complete the write here. - base::RunLoop().RunUntilIdle(); + base::MessageLoop::current()->RunUntilIdle(); } // Now schedule the ERR_CONNECTION_RESET. @@ -5105,7 +5102,7 @@ TEST_P(SpdyNetworkTransactionTest, ServerPushClaimBeforeHeaders) { &CreateGetPushRequest(), callback.callback(), BoundNetLog()); EXPECT_EQ(ERR_IO_PENDING, rv); data.RunFor(3); - base::RunLoop().RunUntilIdle(); + base::MessageLoop::current()->RunUntilIdle(); // Read the server push body. std::string result2; @@ -5241,7 +5238,7 @@ TEST_P(SpdyNetworkTransactionTest, ServerPushWithTwoHeaderFrames) { &CreateGetPushRequest(), callback.callback(), BoundNetLog()); EXPECT_EQ(ERR_IO_PENDING, rv); data.RunFor(3); - base::RunLoop().RunUntilIdle(); + base::MessageLoop::current()->RunUntilIdle(); // Read the server push body. std::string result2; @@ -5374,7 +5371,7 @@ TEST_P(SpdyNetworkTransactionTest, ServerPushWithNoStatusHeaderFrames) { &CreateGetPushRequest(), callback.callback(), BoundNetLog()); EXPECT_EQ(ERR_IO_PENDING, rv); data.RunFor(2); - base::RunLoop().RunUntilIdle(); + base::MessageLoop::current()->RunUntilIdle(); // Read the server push body. std::string result2; @@ -5729,7 +5726,7 @@ TEST_P(SpdyNetworkTransactionTest, OutOfOrderSynStream) { // Run the message loop, but do not allow the write to complete. // This leaves the SpdySession with a write pending, which prevents // SpdySession from attempting subsequent writes until this write completes. - base::RunLoop().RunUntilIdle(); + base::MessageLoop::current()->RunUntilIdle(); // Now, start both new transactions HttpRequestInfo info2 = CreateGetRequest(); @@ -5738,7 +5735,7 @@ TEST_P(SpdyNetworkTransactionTest, OutOfOrderSynStream) { new HttpNetworkTransaction(MEDIUM, helper.session().get())); rv = trans2->Start(&info2, callback2.callback(), BoundNetLog()); EXPECT_EQ(ERR_IO_PENDING, rv); - base::RunLoop().RunUntilIdle(); + base::MessageLoop::current()->RunUntilIdle(); HttpRequestInfo info3 = CreateGetRequest(); TestCompletionCallback callback3; @@ -5746,7 +5743,7 @@ TEST_P(SpdyNetworkTransactionTest, OutOfOrderSynStream) { new HttpNetworkTransaction(HIGHEST, helper.session().get())); rv = trans3->Start(&info3, callback3.callback(), BoundNetLog()); EXPECT_EQ(ERR_IO_PENDING, rv); - base::RunLoop().RunUntilIdle(); + base::MessageLoop::current()->RunUntilIdle(); // We now have two SYN_STREAM frames queued up which will be // dequeued only once the first write completes, which we @@ -5958,7 +5955,7 @@ TEST_P(SpdyNetworkTransactionTest, WindowUpdateSent) { // Force write of WINDOW_UPDATE which was scheduled during the above // read. - base::RunLoop().RunUntilIdle(); + base::MessageLoop::current()->RunUntilIdle(); // Read EOF. data.CompleteRead(); @@ -6142,7 +6139,7 @@ TEST_P(SpdyNetworkTransactionTest, FlowControlStallResume) { int rv = trans->Start(&helper.request(), callback.callback(), BoundNetLog()); EXPECT_EQ(ERR_IO_PENDING, rv); - base::RunLoop().RunUntilIdle(); // Write as much as we can. + base::MessageLoop::current()->RunUntilIdle(); // Write as much as we can. SpdyHttpStream* stream = static_cast<SpdyHttpStream*>(trans->stream_.get()); ASSERT_TRUE(stream != NULL); diff --git a/chromium/net/spdy/spdy_stream.cc b/chromium/net/spdy/spdy_stream.cc index a603a6c93e0..18d20e8d3a4 100644 --- a/chromium/net/spdy/spdy_stream.cc +++ b/chromium/net/spdy/spdy_stream.cc @@ -740,7 +740,7 @@ int SpdyStream::DoGetDomainBoundCert() { io_state_ = STATE_GET_DOMAIN_BOUND_CERT_COMPLETE; ServerBoundCertService* sbc_service = session_->GetServerBoundCertService(); DCHECK(sbc_service != NULL); - int rv = sbc_service->GetOrCreateDomainBoundCert( + int rv = sbc_service->GetDomainBoundCert( url.GetOrigin().host(), &domain_bound_private_key_, &domain_bound_cert_, diff --git a/chromium/net/spdy/spdy_test_util_common.cc b/chromium/net/spdy/spdy_test_util_common.cc index 95466847b93..4383db0860a 100644 --- a/chromium/net/spdy/spdy_test_util_common.cc +++ b/chromium/net/spdy/spdy_test_util_common.cc @@ -649,8 +649,8 @@ base::WeakPtr<SpdySession> CreateFakeSpdySessionHelper( EXPECT_FALSE(HasSpdySession(pool, key)); base::WeakPtr<SpdySession> spdy_session; scoped_ptr<ClientSocketHandle> handle(new ClientSocketHandle()); - handle->SetSocket(scoped_ptr<StreamSocket>(new FakeSpdySessionClientSocket( - expected_status == OK ? ERR_IO_PENDING : expected_status))); + handle->set_socket(new FakeSpdySessionClientSocket( + expected_status == OK ? ERR_IO_PENDING : expected_status)); EXPECT_EQ( expected_status, pool->CreateAvailableSessionFromSocket( diff --git a/chromium/net/ssl/server_bound_cert_service.cc b/chromium/net/ssl/server_bound_cert_service.cc index 2bbcbc79e6b..4bc82ed5d9b 100644 --- a/chromium/net/ssl/server_bound_cert_service.cc +++ b/chromium/net/ssl/server_bound_cert_service.cc @@ -43,8 +43,7 @@ const int kValidityPeriodInDays = 365; const int kSystemTimeValidityBufferInDays = 90; // Used by the GetDomainBoundCertResult histogram to record the final -// outcome of each GetDomainBoundCert or GetOrCreateDomainBoundCert call. -// Do not re-use values. +// outcome of each GetDomainBoundCert call. Do not re-use values. enum GetCertResult { // Synchronously found and returned an existing domain bound cert. SYNC_SUCCESS = 0, @@ -58,8 +57,7 @@ enum GetCertResult { ASYNC_FAILURE_CREATE_CERT = 4, ASYNC_FAILURE_EXPORT_KEY = 5, ASYNC_FAILURE_UNKNOWN = 6, - // GetDomainBoundCert or GetOrCreateDomainBoundCert was called with - // invalid arguments. + // GetDomainBoundCert was called with invalid arguments. INVALID_ARGUMENT = 7, // We don't support any of the cert types the server requested. UNSUPPORTED_TYPE = 8, @@ -279,18 +277,14 @@ class ServerBoundCertServiceWorker { // origin message loop. class ServerBoundCertServiceJob { public: - ServerBoundCertServiceJob(bool create_if_missing) - : create_if_missing_(create_if_missing) { - } + ServerBoundCertServiceJob() { } ~ServerBoundCertServiceJob() { if (!requests_.empty()) DeleteAllCanceled(); } - void AddRequest(ServerBoundCertServiceRequest* request, - bool create_if_missing = false) { - create_if_missing_ |= create_if_missing; + void AddRequest(ServerBoundCertServiceRequest* request) { requests_.push_back(request); } @@ -300,8 +294,6 @@ class ServerBoundCertServiceJob { PostAll(error, private_key, cert); } - bool CreateIfMissing() const { return create_if_missing_; } - private: void PostAll(int error, const std::string& private_key, @@ -328,7 +320,6 @@ class ServerBoundCertServiceJob { } std::vector<ServerBoundCertServiceRequest*> requests_; - bool create_if_missing_; }; // static @@ -397,7 +388,7 @@ std::string ServerBoundCertService::GetDomainForHost(const std::string& host) { return domain; } -int ServerBoundCertService::GetOrCreateDomainBoundCert( +int ServerBoundCertService::GetDomainBoundCert( const std::string& host, std::string* private_key, std::string* cert, @@ -420,15 +411,49 @@ int ServerBoundCertService::GetOrCreateDomainBoundCert( requests_++; - // See if a request for the same domain is currently in flight. - bool create_if_missing = true; - if (JoinToInFlightRequest(request_start, domain, private_key, cert, - create_if_missing, callback, out_req)) { + // See if an identical request is currently in flight. + ServerBoundCertServiceJob* job = NULL; + std::map<std::string, ServerBoundCertServiceJob*>::const_iterator j; + j = inflight_.find(domain); + if (j != inflight_.end()) { + // An identical request is in flight already. We'll just attach our + // callback. + job = j->second; + inflight_joins_++; + + ServerBoundCertServiceRequest* request = new ServerBoundCertServiceRequest( + request_start, + base::Bind(&RequestHandle::OnRequestComplete, + base::Unretained(out_req)), + private_key, cert); + job->AddRequest(request); + out_req->RequestStarted(this, request, callback); return ERR_IO_PENDING; } - int err = LookupDomainBoundCert(request_start, domain, private_key, cert, - create_if_missing, callback, out_req); + // Check if a domain bound cert of an acceptable type already exists for this + // domain. Note that |expiration_time| is ignored, and expired certs are + // considered valid. + base::Time expiration_time; + int err = server_bound_cert_store_->GetServerBoundCert( + domain, + &expiration_time /* ignored */, + private_key, + cert, + base::Bind(&ServerBoundCertService::GotServerBoundCert, + weak_ptr_factory_.GetWeakPtr())); + + if (err == OK) { + // Sync lookup found a valid cert. + DVLOG(1) << "Cert store had valid cert for " << domain; + cert_store_hits_++; + RecordGetDomainBoundCertResult(SYNC_SUCCESS); + base::TimeDelta request_time = base::TimeTicks::Now() - request_start; + UMA_HISTOGRAM_TIMES("DomainBoundCerts.GetCertTimeSync", request_time); + RecordGetCertTime(request_time); + return OK; + } + if (err == ERR_FILE_NOT_FOUND) { // Sync lookup did not find a valid cert. Start generating a new one. workers_created_++; @@ -442,17 +467,19 @@ int ServerBoundCertService::GetOrCreateDomainBoundCert( RecordGetDomainBoundCertResult(WORKER_FAILURE); return ERR_INSUFFICIENT_RESOURCES; } - // We are waiting for cert generation. Create a job & request to track it. - ServerBoundCertServiceJob* job = - new ServerBoundCertServiceJob(create_if_missing); + } + + if (err == ERR_IO_PENDING || err == ERR_FILE_NOT_FOUND) { + // We are either waiting for async DB lookup, or waiting for cert + // generation. Create a job & request to track it. + job = new ServerBoundCertServiceJob(); inflight_[domain] = job; ServerBoundCertServiceRequest* request = new ServerBoundCertServiceRequest( request_start, base::Bind(&RequestHandle::OnRequestComplete, base::Unretained(out_req)), - private_key, - cert); + private_key, cert); job->AddRequest(request); out_req->RequestStarted(this, request, callback); return ERR_IO_PENDING; @@ -461,41 +488,6 @@ int ServerBoundCertService::GetOrCreateDomainBoundCert( return err; } -int ServerBoundCertService::GetDomainBoundCert( - const std::string& host, - std::string* private_key, - std::string* cert, - const CompletionCallback& callback, - RequestHandle* out_req) { - DVLOG(1) << __FUNCTION__ << " " << host; - DCHECK(CalledOnValidThread()); - base::TimeTicks request_start = base::TimeTicks::Now(); - - if (callback.is_null() || !private_key || !cert || host.empty()) { - RecordGetDomainBoundCertResult(INVALID_ARGUMENT); - return ERR_INVALID_ARGUMENT; - } - - std::string domain = GetDomainForHost(host); - if (domain.empty()) { - RecordGetDomainBoundCertResult(INVALID_ARGUMENT); - return ERR_INVALID_ARGUMENT; - } - - requests_++; - - // See if a request for the same domain currently in flight. - bool create_if_missing = false; - if (JoinToInFlightRequest(request_start, domain, private_key, cert, - create_if_missing, callback, out_req)) { - return ERR_IO_PENDING; - } - - int err = LookupDomainBoundCert(request_start, domain, private_key, cert, - create_if_missing, callback, out_req); - return err; -} - void ServerBoundCertService::GotServerBoundCert( int err, const std::string& server_identifier, @@ -519,13 +511,7 @@ void ServerBoundCertService::GotServerBoundCert( HandleResult(OK, server_identifier, key, cert); return; } - // Async lookup did not find a valid cert. If no request asked to create one, - // return the error directly. - if (!j->second->CreateIfMissing()) { - HandleResult(err, server_identifier, key, cert); - return; - } - // At least one request asked to create a cert => start generating a new one. + // Async lookup did not find a valid cert. Start generating a new one. workers_created_++; ServerBoundCertServiceWorker* worker = new ServerBoundCertServiceWorker( server_identifier, @@ -538,6 +524,7 @@ void ServerBoundCertService::GotServerBoundCert( server_identifier, std::string(), std::string()); + return; } } @@ -592,86 +579,6 @@ void ServerBoundCertService::HandleResult( delete job; } -bool ServerBoundCertService::JoinToInFlightRequest( - const base::TimeTicks& request_start, - const std::string& domain, - std::string* private_key, - std::string* cert, - bool create_if_missing, - const CompletionCallback& callback, - RequestHandle* out_req) { - ServerBoundCertServiceJob* job = NULL; - std::map<std::string, ServerBoundCertServiceJob*>::const_iterator j = - inflight_.find(domain); - if (j != inflight_.end()) { - // A request for the same domain is in flight already. We'll attach our - // callback, but we'll also mark it as requiring a cert if one's mising. - job = j->second; - inflight_joins_++; - - ServerBoundCertServiceRequest* request = new ServerBoundCertServiceRequest( - request_start, - base::Bind(&RequestHandle::OnRequestComplete, - base::Unretained(out_req)), - private_key, - cert); - job->AddRequest(request, create_if_missing); - out_req->RequestStarted(this, request, callback); - return true; - } - return false; -} - -int ServerBoundCertService::LookupDomainBoundCert( - const base::TimeTicks& request_start, - const std::string& domain, - std::string* private_key, - std::string* cert, - bool create_if_missing, - const CompletionCallback& callback, - RequestHandle* out_req) { - // Check if a domain bound cert already exists for this domain. Note that - // |expiration_time| is ignored, and expired certs are considered valid. - base::Time expiration_time; - int err = server_bound_cert_store_->GetServerBoundCert( - domain, - &expiration_time /* ignored */, - private_key, - cert, - base::Bind(&ServerBoundCertService::GotServerBoundCert, - weak_ptr_factory_.GetWeakPtr())); - - if (err == OK) { - // Sync lookup found a valid cert. - DVLOG(1) << "Cert store had valid cert for " << domain; - cert_store_hits_++; - RecordGetDomainBoundCertResult(SYNC_SUCCESS); - base::TimeDelta request_time = base::TimeTicks::Now() - request_start; - UMA_HISTOGRAM_TIMES("DomainBoundCerts.GetCertTimeSync", request_time); - RecordGetCertTime(request_time); - return OK; - } - - if (err == ERR_IO_PENDING) { - // We are waiting for async DB lookup. Create a job & request to track it. - ServerBoundCertServiceJob* job = - new ServerBoundCertServiceJob(create_if_missing); - inflight_[domain] = job; - - ServerBoundCertServiceRequest* request = new ServerBoundCertServiceRequest( - request_start, - base::Bind(&RequestHandle::OnRequestComplete, - base::Unretained(out_req)), - private_key, - cert); - job->AddRequest(request); - out_req->RequestStarted(this, request, callback); - return ERR_IO_PENDING; - } - - return err; -} - int ServerBoundCertService::cert_count() { return server_bound_cert_store_->GetCertCount(); } diff --git a/chromium/net/ssl/server_bound_cert_service.h b/chromium/net/ssl/server_bound_cert_service.h index 0dc7f4ae390..d931ec87082 100644 --- a/chromium/net/ssl/server_bound_cert_service.h +++ b/chromium/net/ssl/server_bound_cert_service.h @@ -106,31 +106,6 @@ class NET_EXPORT ServerBoundCertService // |*out_req| will be initialized with a handle to the async request. This // RequestHandle object must be cancelled or destroyed before the // ServerBoundCertService is destroyed. - int GetOrCreateDomainBoundCert( - const std::string& host, - std::string* private_key, - std::string* cert, - const CompletionCallback& callback, - RequestHandle* out_req); - - // Fetches the domain bound cert for the specified host if one exists. - // Returns OK if successful, ERR_FILE_NOT_FOUND if none exists, or an error - // code upon failure. - // - // On successful completion, |private_key| stores a DER-encoded - // PrivateKeyInfo struct, and |cert| stores a DER-encoded certificate. - // The PrivateKeyInfo is always an ECDSA private key. - // - // |callback| must not be null. ERR_IO_PENDING is returned if the operation - // could not be completed immediately, in which case the result code will - // be passed to the callback when available. If an in-flight - // GetDomainBoundCert is pending, and a new GetOrCreateDomainBoundCert - // request arrives for the same domain, the GetDomainBoundCert request will - // not complete until a new cert is created. - // - // |*out_req| will be initialized with a handle to the async request. This - // RequestHandle object must be cancelled or destroyed before the - // ServerBoundCertService is destroyed. int GetDomainBoundCert( const std::string& host, std::string* private_key, @@ -168,29 +143,6 @@ class NET_EXPORT ServerBoundCertService const std::string& private_key, const std::string& cert); - // Searches for an in-flight request for the same domain. If found, - // attaches to the request and returns true. Returns false if no in-flight - // request is found. - bool JoinToInFlightRequest(const base::TimeTicks& request_start, - const std::string& domain, - std::string* private_key, - std::string* cert, - bool create_if_missing, - const CompletionCallback& callback, - RequestHandle* out_req); - - // Looks for the domain bound cert for |domain| in this service's store. - // Returns OK if it can be found synchronously, ERR_IO_PENDING if the - // result cannot be obtained synchronously, or a network error code on - // failure (including failure to find a domain-bound cert of |domain|). - int LookupDomainBoundCert(const base::TimeTicks& request_start, - const std::string& domain, - std::string* private_key, - std::string* cert, - bool create_if_missing, - const CompletionCallback& callback, - RequestHandle* out_req); - scoped_ptr<ServerBoundCertStore> server_bound_cert_store_; scoped_refptr<base::TaskRunner> task_runner_; diff --git a/chromium/net/ssl/server_bound_cert_service_unittest.cc b/chromium/net/ssl/server_bound_cert_service_unittest.cc index b8ca1fa54d0..d7b8553b5ac 100644 --- a/chromium/net/ssl/server_bound_cert_service_unittest.cc +++ b/chromium/net/ssl/server_bound_cert_service_unittest.cc @@ -136,24 +136,6 @@ TEST_F(ServerBoundCertServiceTest, GetDomainForHost) { // See http://crbug.com/91512 - implement OpenSSL version of CreateSelfSigned. #if !defined(USE_OPENSSL) -TEST_F(ServerBoundCertServiceTest, GetCacheMiss) { - std::string host("encrypted.google.com"); - - int error; - TestCompletionCallback callback; - ServerBoundCertService::RequestHandle request_handle; - - // Synchronous completion, because the store is initialized. - std::string private_key, der_cert; - EXPECT_EQ(0, service_->cert_count()); - error = service_->GetDomainBoundCert( - host, &private_key, &der_cert, callback.callback(), &request_handle); - EXPECT_EQ(ERR_FILE_NOT_FOUND, error); - EXPECT_FALSE(request_handle.is_active()); - EXPECT_EQ(0, service_->cert_count()); - EXPECT_TRUE(der_cert.empty()); -} - TEST_F(ServerBoundCertServiceTest, CacheHit) { std::string host("encrypted.google.com"); @@ -164,7 +146,7 @@ TEST_F(ServerBoundCertServiceTest, CacheHit) { // Asynchronous completion. std::string private_key_info1, der_cert1; EXPECT_EQ(0, service_->cert_count()); - error = service_->GetOrCreateDomainBoundCert( + error = service_->GetDomainBoundCert( host, &private_key_info1, &der_cert1, callback.callback(), &request_handle); EXPECT_EQ(ERR_IO_PENDING, error); @@ -178,7 +160,7 @@ TEST_F(ServerBoundCertServiceTest, CacheHit) { // Synchronous completion. std::string private_key_info2, der_cert2; - error = service_->GetOrCreateDomainBoundCert( + error = service_->GetDomainBoundCert( host, &private_key_info2, &der_cert2, callback.callback(), &request_handle); EXPECT_FALSE(request_handle.is_active()); @@ -187,19 +169,8 @@ TEST_F(ServerBoundCertServiceTest, CacheHit) { EXPECT_EQ(private_key_info1, private_key_info2); EXPECT_EQ(der_cert1, der_cert2); - // Synchronous get. - std::string private_key_info3, der_cert3; - error = service_->GetDomainBoundCert( - host, &private_key_info3, &der_cert3, callback.callback(), - &request_handle); - EXPECT_FALSE(request_handle.is_active()); - EXPECT_EQ(OK, error); - EXPECT_EQ(1, service_->cert_count()); - EXPECT_EQ(der_cert1, der_cert3); - EXPECT_EQ(private_key_info1, private_key_info3); - - EXPECT_EQ(3u, service_->requests()); - EXPECT_EQ(2u, service_->cert_store_hits()); + EXPECT_EQ(2u, service_->requests()); + EXPECT_EQ(1u, service_->cert_store_hits()); EXPECT_EQ(0u, service_->inflight_joins()); } @@ -211,7 +182,7 @@ TEST_F(ServerBoundCertServiceTest, StoreCerts) { std::string host1("encrypted.google.com"); std::string private_key_info1, der_cert1; EXPECT_EQ(0, service_->cert_count()); - error = service_->GetOrCreateDomainBoundCert( + error = service_->GetDomainBoundCert( host1, &private_key_info1, &der_cert1, callback.callback(), &request_handle); EXPECT_EQ(ERR_IO_PENDING, error); @@ -222,7 +193,7 @@ TEST_F(ServerBoundCertServiceTest, StoreCerts) { std::string host2("www.verisign.com"); std::string private_key_info2, der_cert2; - error = service_->GetOrCreateDomainBoundCert( + error = service_->GetDomainBoundCert( host2, &private_key_info2, &der_cert2, callback.callback(), &request_handle); EXPECT_EQ(ERR_IO_PENDING, error); @@ -233,7 +204,7 @@ TEST_F(ServerBoundCertServiceTest, StoreCerts) { std::string host3("www.twitter.com"); std::string private_key_info3, der_cert3; - error = service_->GetOrCreateDomainBoundCert( + error = service_->GetDomainBoundCert( host3, &private_key_info3, &der_cert3, callback.callback(), &request_handle); EXPECT_EQ(ERR_IO_PENDING, error); @@ -263,13 +234,13 @@ TEST_F(ServerBoundCertServiceTest, InflightJoin) { TestCompletionCallback callback2; ServerBoundCertService::RequestHandle request_handle2; - error = service_->GetOrCreateDomainBoundCert( + error = service_->GetDomainBoundCert( host, &private_key_info1, &der_cert1, callback1.callback(), &request_handle1); EXPECT_EQ(ERR_IO_PENDING, error); EXPECT_TRUE(request_handle1.is_active()); // Should join with the original request. - error = service_->GetOrCreateDomainBoundCert( + error = service_->GetDomainBoundCert( host, &private_key_info2, &der_cert2, callback2.callback(), &request_handle2); EXPECT_EQ(ERR_IO_PENDING, error); @@ -283,45 +254,6 @@ TEST_F(ServerBoundCertServiceTest, InflightJoin) { EXPECT_EQ(2u, service_->requests()); EXPECT_EQ(0u, service_->cert_store_hits()); EXPECT_EQ(1u, service_->inflight_joins()); - EXPECT_EQ(1u, service_->workers_created()); -} - -// Tests an inflight join of a Get request to a GetOrCreate request. -TEST_F(ServerBoundCertServiceTest, InflightJoinGetOrCreateAndGet) { - std::string host("encrypted.google.com"); - int error; - - std::string private_key_info1, der_cert1; - TestCompletionCallback callback1; - ServerBoundCertService::RequestHandle request_handle1; - - std::string private_key_info2; - std::string der_cert2; - TestCompletionCallback callback2; - ServerBoundCertService::RequestHandle request_handle2; - - error = service_->GetOrCreateDomainBoundCert( - host, &private_key_info1, &der_cert1, - callback1.callback(), &request_handle1); - EXPECT_EQ(ERR_IO_PENDING, error); - EXPECT_TRUE(request_handle1.is_active()); - // Should join with the original request. - error = service_->GetDomainBoundCert( - host, &private_key_info2, &der_cert2, callback2.callback(), - &request_handle2); - EXPECT_EQ(ERR_IO_PENDING, error); - EXPECT_TRUE(request_handle2.is_active()); - - error = callback1.WaitForResult(); - EXPECT_EQ(OK, error); - error = callback2.WaitForResult(); - EXPECT_EQ(OK, error); - EXPECT_EQ(der_cert1, der_cert2); - - EXPECT_EQ(2u, service_->requests()); - EXPECT_EQ(0u, service_->cert_store_hits()); - EXPECT_EQ(1u, service_->inflight_joins()); - EXPECT_EQ(1u, service_->workers_created()); } TEST_F(ServerBoundCertServiceTest, ExtractValuesFromBytesEC) { @@ -331,7 +263,7 @@ TEST_F(ServerBoundCertServiceTest, ExtractValuesFromBytesEC) { TestCompletionCallback callback; ServerBoundCertService::RequestHandle request_handle; - error = service_->GetOrCreateDomainBoundCert( + error = service_->GetDomainBoundCert( host, &private_key_info, &der_cert, callback.callback(), &request_handle); EXPECT_EQ(ERR_IO_PENDING, error); @@ -365,11 +297,11 @@ TEST_F(ServerBoundCertServiceTest, CancelRequest) { int error; ServerBoundCertService::RequestHandle request_handle; - error = service_->GetOrCreateDomainBoundCert(host, - &private_key_info, - &der_cert, - base::Bind(&FailTest), - &request_handle); + error = service_->GetDomainBoundCert(host, + &private_key_info, + &der_cert, + base::Bind(&FailTest), + &request_handle); EXPECT_EQ(ERR_IO_PENDING, error); EXPECT_TRUE(request_handle.is_active()); request_handle.Cancel(); @@ -394,11 +326,11 @@ TEST_F(ServerBoundCertServiceTest, CancelRequestByHandleDestruction) { { ServerBoundCertService::RequestHandle request_handle; - error = service_->GetOrCreateDomainBoundCert(host, - &private_key_info, - &der_cert, - base::Bind(&FailTest), - &request_handle); + error = service_->GetDomainBoundCert(host, + &private_key_info, + &der_cert, + base::Bind(&FailTest), + &request_handle); EXPECT_EQ(ERR_IO_PENDING, error); EXPECT_TRUE(request_handle.is_active()); } @@ -420,11 +352,11 @@ TEST_F(ServerBoundCertServiceTest, DestructionWithPendingRequest) { int error; ServerBoundCertService::RequestHandle request_handle; - error = service_->GetOrCreateDomainBoundCert(host, - &private_key_info, - &der_cert, - base::Bind(&FailTest), - &request_handle); + error = service_->GetDomainBoundCert(host, + &private_key_info, + &der_cert, + base::Bind(&FailTest), + &request_handle); EXPECT_EQ(ERR_IO_PENDING, error); EXPECT_TRUE(request_handle.is_active()); @@ -459,11 +391,11 @@ TEST_F(ServerBoundCertServiceTest, RequestAfterPoolShutdown) { int error; ServerBoundCertService::RequestHandle request_handle; - error = service_->GetOrCreateDomainBoundCert(host, - &private_key_info, - &der_cert, - base::Bind(&FailTest), - &request_handle); + error = service_->GetDomainBoundCert(host, + &private_key_info, + &der_cert, + base::Bind(&FailTest), + &request_handle); // If we got here without crashing or a valgrind error, it worked. ASSERT_EQ(ERR_INSUFFICIENT_RESOURCES, error); EXPECT_FALSE(request_handle.is_active()); @@ -488,27 +420,27 @@ TEST_F(ServerBoundCertServiceTest, SimultaneousCreation) { TestCompletionCallback callback3; ServerBoundCertService::RequestHandle request_handle3; - error = service_->GetOrCreateDomainBoundCert(host1, - &private_key_info1, - &der_cert1, - callback1.callback(), - &request_handle1); + error = service_->GetDomainBoundCert(host1, + &private_key_info1, + &der_cert1, + callback1.callback(), + &request_handle1); EXPECT_EQ(ERR_IO_PENDING, error); EXPECT_TRUE(request_handle1.is_active()); - error = service_->GetOrCreateDomainBoundCert(host2, - &private_key_info2, - &der_cert2, - callback2.callback(), - &request_handle2); + error = service_->GetDomainBoundCert(host2, + &private_key_info2, + &der_cert2, + callback2.callback(), + &request_handle2); EXPECT_EQ(ERR_IO_PENDING, error); EXPECT_TRUE(request_handle2.is_active()); - error = service_->GetOrCreateDomainBoundCert(host3, - &private_key_info3, - &der_cert3, - callback3.callback(), - &request_handle3); + error = service_->GetDomainBoundCert(host3, + &private_key_info3, + &der_cert3, + callback3.callback(), + &request_handle3); EXPECT_EQ(ERR_IO_PENDING, error); EXPECT_TRUE(request_handle3.is_active()); @@ -560,7 +492,7 @@ TEST_F(ServerBoundCertServiceTest, Expiration) { // Cert is valid - synchronous completion. std::string private_key_info1, der_cert1; - error = service_->GetOrCreateDomainBoundCert( + error = service_->GetDomainBoundCert( "good", &private_key_info1, &der_cert1, callback.callback(), &request_handle); EXPECT_EQ(OK, error); @@ -571,7 +503,7 @@ TEST_F(ServerBoundCertServiceTest, Expiration) { // Expired cert is valid as well - synchronous completion. std::string private_key_info2, der_cert2; - error = service_->GetOrCreateDomainBoundCert( + error = service_->GetDomainBoundCert( "expired", &private_key_info2, &der_cert2, callback.callback(), &request_handle); EXPECT_EQ(OK, error); @@ -581,7 +513,7 @@ TEST_F(ServerBoundCertServiceTest, Expiration) { EXPECT_STREQ("d", der_cert2.c_str()); } -TEST_F(ServerBoundCertServiceTest, AsyncStoreGetOrCreateNoCertsInStore) { +TEST_F(ServerBoundCertServiceTest, AsyncStoreGetNoCertsInStore) { MockServerBoundCertStoreWithAsyncGet* mock_store = new MockServerBoundCertStoreWithAsyncGet(); service_ = scoped_ptr<ServerBoundCertService>( @@ -596,7 +528,7 @@ TEST_F(ServerBoundCertServiceTest, AsyncStoreGetOrCreateNoCertsInStore) { // Asynchronous completion with no certs in the store. std::string private_key_info, der_cert; EXPECT_EQ(0, service_->cert_count()); - error = service_->GetOrCreateDomainBoundCert( + error = service_->GetDomainBoundCert( host, &private_key_info, &der_cert, callback.callback(), &request_handle); EXPECT_EQ(ERR_IO_PENDING, error); EXPECT_TRUE(request_handle.is_active()); @@ -612,38 +544,7 @@ TEST_F(ServerBoundCertServiceTest, AsyncStoreGetOrCreateNoCertsInStore) { EXPECT_FALSE(request_handle.is_active()); } -TEST_F(ServerBoundCertServiceTest, AsyncStoreGetNoCertsInStore) { - MockServerBoundCertStoreWithAsyncGet* mock_store = - new MockServerBoundCertStoreWithAsyncGet(); - service_ = scoped_ptr<ServerBoundCertService>( - new ServerBoundCertService(mock_store, sequenced_worker_pool_)); - - std::string host("encrypted.google.com"); - - int error; - TestCompletionCallback callback; - ServerBoundCertService::RequestHandle request_handle; - - // Asynchronous completion with no certs in the store. - std::string private_key, der_cert; - EXPECT_EQ(0, service_->cert_count()); - error = service_->GetDomainBoundCert( - host, &private_key, &der_cert, callback.callback(), &request_handle); - EXPECT_EQ(ERR_IO_PENDING, error); - EXPECT_TRUE(request_handle.is_active()); - - mock_store->CallGetServerBoundCertCallbackWithResult( - ERR_FILE_NOT_FOUND, base::Time(), std::string(), std::string()); - - error = callback.WaitForResult(); - EXPECT_EQ(ERR_FILE_NOT_FOUND, error); - EXPECT_EQ(0, service_->cert_count()); - EXPECT_EQ(0u, service_->workers_created()); - EXPECT_TRUE(der_cert.empty()); - EXPECT_FALSE(request_handle.is_active()); -} - -TEST_F(ServerBoundCertServiceTest, AsyncStoreGetOrCreateOneCertInStore) { +TEST_F(ServerBoundCertServiceTest, AsyncStoreGetOneCertInStore) { MockServerBoundCertStoreWithAsyncGet* mock_store = new MockServerBoundCertStoreWithAsyncGet(); service_ = scoped_ptr<ServerBoundCertService>( @@ -658,7 +559,7 @@ TEST_F(ServerBoundCertServiceTest, AsyncStoreGetOrCreateOneCertInStore) { // Asynchronous completion with a cert in the store. std::string private_key_info, der_cert; EXPECT_EQ(0, service_->cert_count()); - error = service_->GetOrCreateDomainBoundCert( + error = service_->GetDomainBoundCert( host, &private_key_info, &der_cert, callback.callback(), &request_handle); EXPECT_EQ(ERR_IO_PENDING, error); EXPECT_TRUE(request_handle.is_active()); @@ -679,94 +580,6 @@ TEST_F(ServerBoundCertServiceTest, AsyncStoreGetOrCreateOneCertInStore) { EXPECT_FALSE(request_handle.is_active()); } -TEST_F(ServerBoundCertServiceTest, AsyncStoreGetOneCertInStore) { - MockServerBoundCertStoreWithAsyncGet* mock_store = - new MockServerBoundCertStoreWithAsyncGet(); - service_ = scoped_ptr<ServerBoundCertService>( - new ServerBoundCertService(mock_store, sequenced_worker_pool_)); - - std::string host("encrypted.google.com"); - - int error; - TestCompletionCallback callback; - ServerBoundCertService::RequestHandle request_handle; - - // Asynchronous completion with a cert in the store. - std::string private_key, der_cert; - EXPECT_EQ(0, service_->cert_count()); - error = service_->GetDomainBoundCert( - host, &private_key, &der_cert, callback.callback(), &request_handle); - EXPECT_EQ(ERR_IO_PENDING, error); - EXPECT_TRUE(request_handle.is_active()); - - mock_store->CallGetServerBoundCertCallbackWithResult( - OK, base::Time(), "ab", "cd"); - - error = callback.WaitForResult(); - EXPECT_EQ(OK, error); - EXPECT_EQ(1, service_->cert_count()); - EXPECT_EQ(1u, service_->requests()); - EXPECT_EQ(1u, service_->cert_store_hits()); - // Because the cert was found in the store, no new workers should have been - // created. - EXPECT_EQ(0u, service_->workers_created()); - EXPECT_STREQ("cd", der_cert.c_str()); - EXPECT_FALSE(request_handle.is_active()); -} - -TEST_F(ServerBoundCertServiceTest, AsyncStoreGetThenCreateNoCertsInStore) { - MockServerBoundCertStoreWithAsyncGet* mock_store = - new MockServerBoundCertStoreWithAsyncGet(); - service_ = scoped_ptr<ServerBoundCertService>( - new ServerBoundCertService(mock_store, sequenced_worker_pool_)); - - std::string host("encrypted.google.com"); - - int error; - - // Asynchronous get with no certs in the store. - TestCompletionCallback callback1; - ServerBoundCertService::RequestHandle request_handle1; - std::string private_key1, der_cert1; - EXPECT_EQ(0, service_->cert_count()); - error = service_->GetDomainBoundCert( - host, &private_key1, &der_cert1, callback1.callback(), &request_handle1); - EXPECT_EQ(ERR_IO_PENDING, error); - EXPECT_TRUE(request_handle1.is_active()); - - // Asynchronous get/create with no certs in the store. - TestCompletionCallback callback2; - ServerBoundCertService::RequestHandle request_handle2; - std::string private_key2, der_cert2; - EXPECT_EQ(0, service_->cert_count()); - error = service_->GetOrCreateDomainBoundCert( - host, &private_key2, &der_cert2, callback2.callback(), &request_handle2); - EXPECT_EQ(ERR_IO_PENDING, error); - EXPECT_TRUE(request_handle2.is_active()); - - mock_store->CallGetServerBoundCertCallbackWithResult( - ERR_FILE_NOT_FOUND, base::Time(), std::string(), std::string()); - - // Even though the first request didn't ask to create a cert, it gets joined - // by the second, which does, so both succeed. - error = callback1.WaitForResult(); - EXPECT_EQ(OK, error); - error = callback2.WaitForResult(); - EXPECT_EQ(OK, error); - - // One cert is created, one request is joined. - EXPECT_EQ(2U, service_->requests()); - EXPECT_EQ(1, service_->cert_count()); - EXPECT_EQ(1u, service_->workers_created()); - EXPECT_EQ(1u, service_->inflight_joins()); - EXPECT_FALSE(der_cert1.empty()); - EXPECT_EQ(der_cert1, der_cert2); - EXPECT_FALSE(private_key1.empty()); - EXPECT_EQ(private_key1, private_key2); - EXPECT_FALSE(request_handle1.is_active()); - EXPECT_FALSE(request_handle2.is_active()); -} - #endif // !defined(USE_OPENSSL) } // namespace diff --git a/chromium/net/ssl/ssl_config_service.cc b/chromium/net/ssl/ssl_config_service.cc index a2c34a26852..265b43c10e5 100644 --- a/chromium/net/ssl/ssl_config_service.cc +++ b/chromium/net/ssl/ssl_config_service.cc @@ -42,7 +42,7 @@ SSLConfig::SSLConfig() version_max(g_default_version_max), cached_info_enabled(false), channel_id_enabled(true), - false_start_enabled(true), + false_start_enabled(false), unrestricted_ssl3_fallback_enabled(false), send_client_cert(false), verify_ev_cert(false), diff --git a/chromium/net/third_party/nss/README.chromium b/chromium/net/third_party/nss/README.chromium index 11a85102d93..69b7eb77316 100644 --- a/chromium/net/third_party/nss/README.chromium +++ b/chromium/net/third_party/nss/README.chromium @@ -74,8 +74,6 @@ Patches: NSS that doesn't contain the CBC constant-time changes. patches/cbc.patch https://code.google.com/p/chromium/issues/detail?id=172658#c12 - TODO(wtc): remove this patch now that NSS 3.14.3 is the minimum - compile-time and run-time version. * Change ssl3_SuiteBOnly to always return PR_TRUE. The softoken in NSS versions older than 3.15 report an EC key size range of 112 bits to 571 @@ -99,13 +97,10 @@ Patches: https://bugzilla.mozilla.org/show_bug.cgi?id=903565 patches/sslsock_903565.patch - * Implement the AES GCM cipher suites. - https://bugzilla.mozilla.org/show_bug.cgi?id=880543 - patches/aesgcm.patch - - * Add Chromium-specific code to detect AES GCM support in the system NSS - libraries at run time. - patches/aesgcmchromium.patch + * Prefer to generate SHA-1 signatures for TLS 1.2 client authentication if + the client private key is in a CAPI service provider on Windows or if the + client private key is a 1024-bit RSA or DSA key. + patches/tls12backuphash.patch Apply the patches to NSS by running the patches/applypatches.sh script. Read the comments at the top of patches/applypatches.sh for instructions. diff --git a/chromium/net/third_party/nss/patches/aesgcm.patch b/chromium/net/third_party/nss/patches/aesgcm.patch deleted file mode 100644 index 8de0a69d718..00000000000 --- a/chromium/net/third_party/nss/patches/aesgcm.patch +++ /dev/null @@ -1,1179 +0,0 @@ -Index: net/third_party/nss/ssl/sslinfo.c -=================================================================== ---- net/third_party/nss/ssl/sslinfo.c (revision 215189) -+++ net/third_party/nss/ssl/sslinfo.c (working copy) -@@ -109,7 +109,7 @@ - #define K_ECDHE "ECDHE", kt_ecdh - - #define C_SEED "SEED", calg_seed --#define C_CAMELLIA "CAMELLIA", calg_camellia -+#define C_CAMELLIA "CAMELLIA", calg_camellia - #define C_AES "AES", calg_aes - #define C_RC4 "RC4", calg_rc4 - #define C_RC2 "RC2", calg_rc2 -@@ -117,6 +117,7 @@ - #define C_3DES "3DES", calg_3des - #define C_NULL "NULL", calg_null - #define C_SJ "SKIPJACK", calg_sj -+#define C_AESGCM "AES-GCM", calg_aes_gcm - - #define B_256 256, 256, 256 - #define B_128 128, 128, 128 -@@ -130,9 +131,12 @@ - #define M_SHA256 "SHA256", ssl_hmac_sha256, 256 - #define M_SHA "SHA1", ssl_mac_sha, 160 - #define M_MD5 "MD5", ssl_mac_md5, 128 -+#define M_NULL "NULL", ssl_mac_null, 0 - - static const SSLCipherSuiteInfo suiteInfo[] = { - /* <------ Cipher suite --------------------> <auth> <KEA> <bulk cipher> <MAC> <FIPS> */ -+{0,CS(TLS_RSA_WITH_AES_128_GCM_SHA256), S_RSA, K_RSA, C_AESGCM, B_128, M_NULL, 1, 0, 0, }, -+ - {0,CS(TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA), S_RSA, K_DHE, C_CAMELLIA, B_256, M_SHA, 0, 0, 0, }, - {0,CS(TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA), S_DSA, K_DHE, C_CAMELLIA, B_256, M_SHA, 0, 0, 0, }, - {0,CS(TLS_DHE_RSA_WITH_AES_256_CBC_SHA256), S_RSA, K_DHE, C_AES, B_256, M_SHA256, 1, 0, 0, }, -@@ -146,6 +150,7 @@ - {0,CS(TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA), S_DSA, K_DHE, C_CAMELLIA, B_128, M_SHA, 0, 0, 0, }, - {0,CS(TLS_DHE_DSS_WITH_RC4_128_SHA), S_DSA, K_DHE, C_RC4, B_128, M_SHA, 0, 0, 0, }, - {0,CS(TLS_DHE_RSA_WITH_AES_128_CBC_SHA256), S_RSA, K_DHE, C_AES, B_128, M_SHA256, 1, 0, 0, }, -+{0,CS(TLS_DHE_RSA_WITH_AES_128_GCM_SHA256), S_RSA, K_DHE, C_AESGCM, B_128, M_NULL, 1, 0, 0, }, - {0,CS(TLS_DHE_RSA_WITH_AES_128_CBC_SHA), S_RSA, K_DHE, C_AES, B_128, M_SHA, 1, 0, 0, }, - {0,CS(TLS_DHE_DSS_WITH_AES_128_CBC_SHA), S_DSA, K_DHE, C_AES, B_128, M_SHA, 1, 0, 0, }, - {0,CS(TLS_RSA_WITH_SEED_CBC_SHA), S_RSA, K_RSA, C_SEED,B_128, M_SHA, 1, 0, 0, }, -@@ -175,6 +180,9 @@ - - #ifdef NSS_ENABLE_ECC - /* ECC cipher suites */ -+{0,CS(TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256), S_RSA, K_ECDHE, C_AESGCM, B_128, M_NULL, 1, 0, 0, }, -+{0,CS(TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256), S_ECDSA, K_ECDHE, C_AESGCM, B_128, M_NULL, 1, 0, 0, }, -+ - {0,CS(TLS_ECDH_ECDSA_WITH_NULL_SHA), S_ECDSA, K_ECDH, C_NULL, B_0, M_SHA, 0, 0, 0, }, - {0,CS(TLS_ECDH_ECDSA_WITH_RC4_128_SHA), S_ECDSA, K_ECDH, C_RC4, B_128, M_SHA, 0, 0, 0, }, - {0,CS(TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA), S_ECDSA, K_ECDH, C_3DES, B_3DES, M_SHA, 1, 0, 0, }, -Index: net/third_party/nss/ssl/sslimpl.h -=================================================================== ---- net/third_party/nss/ssl/sslimpl.h (revision 215189) -+++ net/third_party/nss/ssl/sslimpl.h (working copy) -@@ -64,6 +64,7 @@ - #define calg_aes ssl_calg_aes - #define calg_camellia ssl_calg_camellia - #define calg_seed ssl_calg_seed -+#define calg_aes_gcm ssl_calg_aes_gcm - - #define mac_null ssl_mac_null - #define mac_md5 ssl_mac_md5 -@@ -290,9 +291,9 @@ - } ssl3CipherSuiteCfg; - - #ifdef NSS_ENABLE_ECC --#define ssl_V3_SUITES_IMPLEMENTED 57 -+#define ssl_V3_SUITES_IMPLEMENTED 61 - #else --#define ssl_V3_SUITES_IMPLEMENTED 35 -+#define ssl_V3_SUITES_IMPLEMENTED 37 - #endif /* NSS_ENABLE_ECC */ - - #define MAX_DTLS_SRTP_CIPHER_SUITES 4 -@@ -440,20 +441,6 @@ - #define GS_DATA 3 - #define GS_PAD 4 - --typedef SECStatus (*SSLCipher)(void * context, -- unsigned char * out, -- int * outlen, -- int maxout, -- const unsigned char *in, -- int inlen); --typedef SECStatus (*SSLCompressor)(void * context, -- unsigned char * out, -- int * outlen, -- int maxout, -- const unsigned char *in, -- int inlen); --typedef SECStatus (*SSLDestroy)(void *context, PRBool freeit); -- - #if defined(NSS_PLATFORM_CLIENT_AUTH) && defined(XP_WIN32) - typedef PCERT_KEY_CONTEXT PlatformKey; - #elif defined(NSS_PLATFORM_CLIENT_AUTH) && defined(XP_MACOSX) -@@ -485,11 +472,12 @@ - cipher_camellia_128, - cipher_camellia_256, - cipher_seed, -+ cipher_aes_128_gcm, - cipher_missing /* reserved for no such supported cipher */ - /* This enum must match ssl3_cipherName[] in ssl3con.c. */ - } SSL3BulkCipher; - --typedef enum { type_stream, type_block } CipherType; -+typedef enum { type_stream, type_block, type_aead } CipherType; - - #define MAX_IV_LENGTH 24 - -@@ -531,6 +519,31 @@ - PRUint64 cipher_context[MAX_CIPHER_CONTEXT_LLONGS]; - } ssl3KeyMaterial; - -+typedef SECStatus (*SSLCipher)(void * context, -+ unsigned char * out, -+ int * outlen, -+ int maxout, -+ const unsigned char *in, -+ int inlen); -+typedef SECStatus (*SSLAEADCipher)( -+ ssl3KeyMaterial * keys, -+ PRBool doDecrypt, -+ unsigned char * out, -+ int * outlen, -+ int maxout, -+ const unsigned char *in, -+ int inlen, -+ SSL3ContentType type, -+ SSL3ProtocolVersion version, -+ SSL3SequenceNumber seqnum); -+typedef SECStatus (*SSLCompressor)(void * context, -+ unsigned char * out, -+ int * outlen, -+ int maxout, -+ const unsigned char *in, -+ int inlen); -+typedef SECStatus (*SSLDestroy)(void *context, PRBool freeit); -+ - /* The DTLS anti-replay window. Defined here because we need it in - * the cipher spec. Note that this is a ring buffer but left and - * right represent the true window, with modular arithmetic used to -@@ -557,6 +570,7 @@ - int mac_size; - SSLCipher encode; - SSLCipher decode; -+ SSLAEADCipher aead; - SSLDestroy destroy; - void * encodeContext; - void * decodeContext; -@@ -706,8 +720,6 @@ - PRBool tls_keygen; - } ssl3KEADef; - --typedef enum { kg_null, kg_strong, kg_export } SSL3KeyGenMode; -- - /* - ** There are tables of these, all const. - */ -@@ -719,7 +731,8 @@ - CipherType type; - int iv_size; - int block_size; -- SSL3KeyGenMode keygen_mode; -+ int tag_size; /* authentication tag size for AEAD ciphers. */ -+ int explicit_nonce_size; /* for AEAD ciphers. */ - }; - - /* -Index: net/third_party/nss/ssl/ssl3ecc.c -=================================================================== ---- net/third_party/nss/ssl/ssl3ecc.c (revision 215189) -+++ net/third_party/nss/ssl/ssl3ecc.c (working copy) -@@ -911,6 +911,7 @@ - TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, - TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, - TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, -+ TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, - TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, - TLS_ECDHE_ECDSA_WITH_NULL_SHA, - TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, -@@ -921,6 +922,7 @@ - TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, - TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, - TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, -+ TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, - TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, - TLS_ECDHE_RSA_WITH_NULL_SHA, - TLS_ECDHE_RSA_WITH_RC4_128_SHA, -@@ -932,12 +934,14 @@ - TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, - TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, - TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, -+ TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, - TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, - TLS_ECDHE_ECDSA_WITH_NULL_SHA, - TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, - TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, - TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, - TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, -+ TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, - TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, - TLS_ECDHE_RSA_WITH_NULL_SHA, - TLS_ECDHE_RSA_WITH_RC4_128_SHA, -Index: net/third_party/nss/ssl/sslsock.c -=================================================================== ---- net/third_party/nss/ssl/sslsock.c (revision 215189) -+++ net/third_party/nss/ssl/sslsock.c (working copy) -@@ -67,8 +67,10 @@ - { TLS_DHE_DSS_WITH_AES_128_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED }, - { TLS_DHE_RSA_WITH_AES_128_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED }, - { TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED }, -+ { TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED }, - { TLS_RSA_WITH_AES_128_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED }, - { TLS_RSA_WITH_AES_128_CBC_SHA256, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED }, -+ { TLS_RSA_WITH_AES_128_GCM_SHA256, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED }, - { TLS_DHE_DSS_WITH_AES_256_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED }, - { TLS_DHE_RSA_WITH_AES_256_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED }, - { TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED }, -@@ -94,6 +96,7 @@ - { TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED }, - { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED }, - { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,SSL_NOT_ALLOWED, SSL_NOT_ALLOWED }, -+ { TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,SSL_NOT_ALLOWED, SSL_NOT_ALLOWED }, - { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED }, - { TLS_ECDH_RSA_WITH_NULL_SHA, SSL_ALLOWED, SSL_ALLOWED }, - { TLS_ECDH_RSA_WITH_RC4_128_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED }, -@@ -105,6 +108,7 @@ - { TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED }, - { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED }, - { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED }, -+ { TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED }, - { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED }, - #endif /* NSS_ENABLE_ECC */ - { 0, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED } -Index: net/third_party/nss/ssl/ssl3con.c -=================================================================== ---- net/third_party/nss/ssl/ssl3con.c (revision 215189) -+++ net/third_party/nss/ssl/ssl3con.c (working copy) -@@ -78,6 +78,14 @@ - static SECStatus Null_Cipher(void *ctx, unsigned char *output, int *outputLen, - int maxOutputLen, const unsigned char *input, - int inputLen); -+#ifndef NO_PKCS11_BYPASS -+static SECStatus ssl3_AESGCMBypass(ssl3KeyMaterial *keys, PRBool doDecrypt, -+ unsigned char *out, int *outlen, int maxout, -+ const unsigned char *in, int inlen, -+ SSL3ContentType type, -+ SSL3ProtocolVersion version, -+ SSL3SequenceNumber seq_num); -+#endif - - #define MAX_SEND_BUF_LENGTH 32000 /* watch for 16-bit integer overflow */ - #define MIN_SEND_BUF_LENGTH 4000 -@@ -90,6 +98,13 @@ - static ssl3CipherSuiteCfg cipherSuites[ssl_V3_SUITES_IMPLEMENTED] = { - /* cipher_suite policy enabled is_present*/ - #ifdef NSS_ENABLE_ECC -+ { TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE}, -+ { TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE}, -+#endif /* NSS_ENABLE_ECC */ -+ { TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE}, -+ { TLS_RSA_WITH_AES_128_GCM_SHA256, SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE}, -+ -+#ifdef NSS_ENABLE_ECC - { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE}, - { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE}, - #endif /* NSS_ENABLE_ECC */ -@@ -233,23 +248,30 @@ - - /* indexed by SSL3BulkCipher */ - static const ssl3BulkCipherDef bulk_cipher_defs[] = { -- /* cipher calg keySz secretSz type ivSz BlkSz keygen */ -- {cipher_null, calg_null, 0, 0, type_stream, 0, 0, kg_null}, -- {cipher_rc4, calg_rc4, 16, 16, type_stream, 0, 0, kg_strong}, -- {cipher_rc4_40, calg_rc4, 16, 5, type_stream, 0, 0, kg_export}, -- {cipher_rc4_56, calg_rc4, 16, 7, type_stream, 0, 0, kg_export}, -- {cipher_rc2, calg_rc2, 16, 16, type_block, 8, 8, kg_strong}, -- {cipher_rc2_40, calg_rc2, 16, 5, type_block, 8, 8, kg_export}, -- {cipher_des, calg_des, 8, 8, type_block, 8, 8, kg_strong}, -- {cipher_3des, calg_3des, 24, 24, type_block, 8, 8, kg_strong}, -- {cipher_des40, calg_des, 8, 5, type_block, 8, 8, kg_export}, -- {cipher_idea, calg_idea, 16, 16, type_block, 8, 8, kg_strong}, -- {cipher_aes_128, calg_aes, 16, 16, type_block, 16,16, kg_strong}, -- {cipher_aes_256, calg_aes, 32, 32, type_block, 16,16, kg_strong}, -- {cipher_camellia_128, calg_camellia,16, 16, type_block, 16,16, kg_strong}, -- {cipher_camellia_256, calg_camellia,32, 32, type_block, 16,16, kg_strong}, -- {cipher_seed, calg_seed, 16, 16, type_block, 16,16, kg_strong}, -- {cipher_missing, calg_null, 0, 0, type_stream, 0, 0, kg_null}, -+ /* |--------- Lengths --------| */ -+ /* cipher calg k s type i b t n */ -+ /* e e v l a o */ -+ /* y c | o g n */ -+ /* | r | c | c */ -+ /* | e | k | e */ -+ /* | t | | | | */ -+ {cipher_null, calg_null, 0, 0, type_stream, 0, 0, 0, 0}, -+ {cipher_rc4, calg_rc4, 16,16, type_stream, 0, 0, 0, 0}, -+ {cipher_rc4_40, calg_rc4, 16, 5, type_stream, 0, 0, 0, 0}, -+ {cipher_rc4_56, calg_rc4, 16, 7, type_stream, 0, 0, 0, 0}, -+ {cipher_rc2, calg_rc2, 16,16, type_block, 8, 8, 0, 0}, -+ {cipher_rc2_40, calg_rc2, 16, 5, type_block, 8, 8, 0, 0}, -+ {cipher_des, calg_des, 8, 8, type_block, 8, 8, 0, 0}, -+ {cipher_3des, calg_3des, 24,24, type_block, 8, 8, 0, 0}, -+ {cipher_des40, calg_des, 8, 5, type_block, 8, 8, 0, 0}, -+ {cipher_idea, calg_idea, 16,16, type_block, 8, 8, 0, 0}, -+ {cipher_aes_128, calg_aes, 16,16, type_block, 16,16, 0, 0}, -+ {cipher_aes_256, calg_aes, 32,32, type_block, 16,16, 0, 0}, -+ {cipher_camellia_128, calg_camellia, 16,16, type_block, 16,16, 0, 0}, -+ {cipher_camellia_256, calg_camellia, 32,32, type_block, 16,16, 0, 0}, -+ {cipher_seed, calg_seed, 16,16, type_block, 16,16, 0, 0}, -+ {cipher_aes_128_gcm, calg_aes_gcm, 16,16, type_aead, 4, 0,16, 8}, -+ {cipher_missing, calg_null, 0, 0, type_stream, 0, 0, 0, 0}, - }; - - static const ssl3KEADef kea_defs[] = -@@ -371,6 +393,11 @@ - {SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_rsa_fips}, - {SSL_RSA_FIPS_WITH_DES_CBC_SHA, cipher_des, mac_sha, kea_rsa_fips}, - -+ {TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_null, kea_dhe_rsa}, -+ {TLS_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_null, kea_rsa}, -+ {TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_null, kea_ecdhe_rsa}, -+ {TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_null, kea_ecdhe_ecdsa}, -+ - #ifdef NSS_ENABLE_ECC - {TLS_ECDH_ECDSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdh_ecdsa}, - {TLS_ECDH_ECDSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdh_ecdsa}, -@@ -434,6 +461,7 @@ - { calg_aes , CKM_AES_CBC }, - { calg_camellia , CKM_CAMELLIA_CBC }, - { calg_seed , CKM_SEED_CBC }, -+ { calg_aes_gcm , CKM_AES_GCM }, - /* { calg_init , (CK_MECHANISM_TYPE)0x7fffffffL } */ - }; - -@@ -472,6 +500,7 @@ - "Camellia-128", - "Camellia-256", - "SEED-CBC", -+ "AES-128-GCM", - "missing" - }; - -@@ -598,9 +627,13 @@ - case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256: - case TLS_RSA_WITH_AES_256_CBC_SHA256: - case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256: -+ case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: - case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256: -+ case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: - case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256: -+ case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256: - case TLS_RSA_WITH_AES_128_CBC_SHA256: -+ case TLS_RSA_WITH_AES_128_GCM_SHA256: - case TLS_RSA_WITH_NULL_SHA256: - return version >= SSL_LIBRARY_VERSION_TLS_1_2; - default: -@@ -1360,7 +1393,7 @@ - cipher = suite_def->bulk_cipher_alg; - kea = suite_def->key_exchange_alg; - mac = suite_def->mac_alg; -- if (mac <= ssl_mac_sha && isTLS) -+ if (mac <= ssl_mac_sha && mac != ssl_mac_null && isTLS) - mac += 2; - - ss->ssl3.hs.suite_def = suite_def; -@@ -1554,7 +1587,6 @@ - unsigned int optArg2 = 0; - PRBool server_encrypts = ss->sec.isServer; - SSLCipherAlgorithm calg; -- SSLCompressionMethod compression_method; - SECStatus rv; - - PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); -@@ -1565,8 +1597,18 @@ - cipher_def = pwSpec->cipher_def; - - calg = cipher_def->calg; -- compression_method = pwSpec->compression_method; - -+ if (calg == calg_aes_gcm) { -+ pwSpec->encode = NULL; -+ pwSpec->decode = NULL; -+ pwSpec->destroy = NULL; -+ pwSpec->encodeContext = NULL; -+ pwSpec->decodeContext = NULL; -+ pwSpec->aead = ssl3_AESGCMBypass; -+ ssl3_InitCompressionContext(pwSpec); -+ return SECSuccess; -+ } -+ - serverContext = pwSpec->server.cipher_context; - clientContext = pwSpec->client.cipher_context; - -@@ -1721,6 +1763,207 @@ - return param; - } - -+/* ssl3_BuildRecordPseudoHeader writes the TLS pseudo-header (the data which -+ * is included in the MAC) to |out| and returns its length. */ -+static unsigned int -+ssl3_BuildRecordPseudoHeader(unsigned char *out, -+ SSL3SequenceNumber seq_num, -+ SSL3ContentType type, -+ PRBool includesVersion, -+ SSL3ProtocolVersion version, -+ PRBool isDTLS, -+ int length) -+{ -+ out[0] = (unsigned char)(seq_num.high >> 24); -+ out[1] = (unsigned char)(seq_num.high >> 16); -+ out[2] = (unsigned char)(seq_num.high >> 8); -+ out[3] = (unsigned char)(seq_num.high >> 0); -+ out[4] = (unsigned char)(seq_num.low >> 24); -+ out[5] = (unsigned char)(seq_num.low >> 16); -+ out[6] = (unsigned char)(seq_num.low >> 8); -+ out[7] = (unsigned char)(seq_num.low >> 0); -+ out[8] = type; -+ -+ /* SSL3 MAC doesn't include the record's version field. */ -+ if (!includesVersion) { -+ out[9] = MSB(length); -+ out[10] = LSB(length); -+ return 11; -+ } -+ -+ /* TLS MAC and AEAD additional data include version. */ -+ if (isDTLS) { -+ SSL3ProtocolVersion dtls_version; -+ -+ dtls_version = dtls_TLSVersionToDTLSVersion(version); -+ out[9] = MSB(dtls_version); -+ out[10] = LSB(dtls_version); -+ } else { -+ out[9] = MSB(version); -+ out[10] = LSB(version); -+ } -+ out[11] = MSB(length); -+ out[12] = LSB(length); -+ return 13; -+} -+ -+static SECStatus -+ssl3_AESGCM(ssl3KeyMaterial *keys, -+ PRBool doDecrypt, -+ unsigned char *out, -+ int *outlen, -+ int maxout, -+ const unsigned char *in, -+ int inlen, -+ SSL3ContentType type, -+ SSL3ProtocolVersion version, -+ SSL3SequenceNumber seq_num) -+{ -+ SECItem param; -+ SECStatus rv = SECFailure; -+ unsigned char nonce[12]; -+ unsigned char additionalData[13]; -+ unsigned int additionalDataLen; -+ unsigned int uOutLen; -+ CK_GCM_PARAMS gcmParams; -+ -+ static const int tagSize = 16; -+ static const int explicitNonceLen = 8; -+ -+ /* See https://tools.ietf.org/html/rfc5246#section-6.2.3.3 for the -+ * definition of the AEAD additional data. */ -+ additionalDataLen = ssl3_BuildRecordPseudoHeader( -+ additionalData, seq_num, type, PR_TRUE /* includes version */, -+ version, PR_FALSE /* not DTLS */, -+ inlen - (doDecrypt ? explicitNonceLen + tagSize : 0)); -+ PORT_Assert(additionalDataLen <= sizeof(additionalData)); -+ -+ /* See https://tools.ietf.org/html/rfc5288#section-3 for details of how the -+ * nonce is formed. */ -+ memcpy(nonce, keys->write_iv, 4); -+ if (doDecrypt) { -+ memcpy(nonce + 4, in, explicitNonceLen); -+ in += explicitNonceLen; -+ inlen -= explicitNonceLen; -+ *outlen = 0; -+ } else { -+ if (maxout < explicitNonceLen) { -+ PORT_SetError(SEC_ERROR_INPUT_LEN); -+ return SECFailure; -+ } -+ /* Use the 64-bit sequence number as the explicit nonce. */ -+ memcpy(nonce + 4, additionalData, explicitNonceLen); -+ memcpy(out, additionalData, explicitNonceLen); -+ out += explicitNonceLen; -+ maxout -= explicitNonceLen; -+ *outlen = explicitNonceLen; -+ } -+ -+ param.type = siBuffer; -+ param.data = (unsigned char *) &gcmParams; -+ param.len = sizeof(gcmParams); -+ gcmParams.pIv = nonce; -+ gcmParams.ulIvLen = sizeof(nonce); -+ gcmParams.pAAD = additionalData; -+ gcmParams.ulAADLen = additionalDataLen; -+ gcmParams.ulTagBits = tagSize * 8; -+ -+ if (doDecrypt) { -+ rv = PK11_Decrypt(keys->write_key, CKM_AES_GCM, ¶m, out, &uOutLen, -+ maxout, in, inlen); -+ } else { -+ rv = PK11_Encrypt(keys->write_key, CKM_AES_GCM, ¶m, out, &uOutLen, -+ maxout, in, inlen); -+ } -+ *outlen += (int) uOutLen; -+ -+ return rv; -+} -+ -+#ifndef NO_PKCS11_BYPASS -+static SECStatus -+ssl3_AESGCMBypass(ssl3KeyMaterial *keys, -+ PRBool doDecrypt, -+ unsigned char *out, -+ int *outlen, -+ int maxout, -+ const unsigned char *in, -+ int inlen, -+ SSL3ContentType type, -+ SSL3ProtocolVersion version, -+ SSL3SequenceNumber seq_num) -+{ -+ SECStatus rv = SECFailure; -+ unsigned char nonce[12]; -+ unsigned char additionalData[13]; -+ unsigned int additionalDataLen; -+ unsigned int uOutLen; -+ AESContext *cx; -+ CK_GCM_PARAMS gcmParams; -+ -+ static const int tagSize = 16; -+ static const int explicitNonceLen = 8; -+ -+ /* See https://tools.ietf.org/html/rfc5246#section-6.2.3.3 for the -+ * definition of the AEAD additional data. */ -+ additionalDataLen = ssl3_BuildRecordPseudoHeader( -+ additionalData, seq_num, type, PR_TRUE /* includes version */, -+ version, PR_FALSE /* not DTLS */, -+ inlen - (doDecrypt ? explicitNonceLen + tagSize : 0)); -+ PORT_Assert(additionalDataLen <= sizeof(additionalData)); -+ -+ /* See https://tools.ietf.org/html/rfc5288#section-3 for details of how the -+ * nonce is formed. */ -+ PORT_Assert(keys->write_iv_item.len == 4); -+ if (keys->write_iv_item.len != 4) { -+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); -+ return SECFailure; -+ } -+ memcpy(nonce, keys->write_iv_item.data, 4); -+ if (doDecrypt) { -+ memcpy(nonce + 4, in, explicitNonceLen); -+ in += explicitNonceLen; -+ inlen -= explicitNonceLen; -+ *outlen = 0; -+ } else { -+ if (maxout < explicitNonceLen) { -+ PORT_SetError(SEC_ERROR_INPUT_LEN); -+ return SECFailure; -+ } -+ /* Use the 64-bit sequence number as the explicit nonce. */ -+ memcpy(nonce + 4, additionalData, explicitNonceLen); -+ memcpy(out, additionalData, explicitNonceLen); -+ out += explicitNonceLen; -+ maxout -= explicitNonceLen; -+ *outlen = explicitNonceLen; -+ } -+ -+ gcmParams.pIv = nonce; -+ gcmParams.ulIvLen = sizeof(nonce); -+ gcmParams.pAAD = additionalData; -+ gcmParams.ulAADLen = additionalDataLen; -+ gcmParams.ulTagBits = tagSize * 8; -+ -+ cx = (AESContext *)keys->cipher_context; -+ rv = AES_InitContext(cx, keys->write_key_item.data, -+ keys->write_key_item.len, -+ (unsigned char *)&gcmParams, NSS_AES_GCM, !doDecrypt, -+ AES_BLOCK_SIZE); -+ if (rv != SECSuccess) { -+ return rv; -+ } -+ if (doDecrypt) { -+ rv = AES_Decrypt(cx, out, &uOutLen, maxout, in, inlen); -+ } else { -+ rv = AES_Encrypt(cx, out, &uOutLen, maxout, in, inlen); -+ } -+ AES_DestroyContext(cx, PR_FALSE); -+ *outlen += (int) uOutLen; -+ -+ return rv; -+} -+#endif -+ - /* Initialize encryption and MAC contexts for pending spec. - * Master Secret already is derived. - * Caller holds Spec write lock. -@@ -1748,14 +1991,27 @@ - pwSpec = ss->ssl3.pwSpec; - cipher_def = pwSpec->cipher_def; - macLength = pwSpec->mac_size; -+ calg = cipher_def->calg; -+ PORT_Assert(alg2Mech[calg].calg == calg); - -+ pwSpec->client.write_mac_context = NULL; -+ pwSpec->server.write_mac_context = NULL; -+ -+ if (calg == calg_aes_gcm) { -+ pwSpec->encode = NULL; -+ pwSpec->decode = NULL; -+ pwSpec->destroy = NULL; -+ pwSpec->encodeContext = NULL; -+ pwSpec->decodeContext = NULL; -+ pwSpec->aead = ssl3_AESGCM; -+ return SECSuccess; -+ } -+ - /* - ** Now setup the MAC contexts, - ** crypto contexts are setup below. - */ - -- pwSpec->client.write_mac_context = NULL; -- pwSpec->server.write_mac_context = NULL; - mac_mech = pwSpec->mac_def->mmech; - mac_param.data = (unsigned char *)&macLength; - mac_param.len = sizeof(macLength); -@@ -1778,9 +2034,6 @@ - ** Now setup the crypto contexts. - */ - -- calg = cipher_def->calg; -- PORT_Assert(alg2Mech[calg].calg == calg); -- - if (calg == calg_null) { - pwSpec->encode = Null_Cipher; - pwSpec->decode = Null_Cipher; -@@ -1999,55 +2252,21 @@ - { - const ssl3MACDef * mac_def; - SECStatus rv; --#ifndef NO_PKCS11_BYPASS - PRBool isTLS; --#endif - unsigned int tempLen; - unsigned char temp[MAX_MAC_LENGTH]; - -- temp[0] = (unsigned char)(seq_num.high >> 24); -- temp[1] = (unsigned char)(seq_num.high >> 16); -- temp[2] = (unsigned char)(seq_num.high >> 8); -- temp[3] = (unsigned char)(seq_num.high >> 0); -- temp[4] = (unsigned char)(seq_num.low >> 24); -- temp[5] = (unsigned char)(seq_num.low >> 16); -- temp[6] = (unsigned char)(seq_num.low >> 8); -- temp[7] = (unsigned char)(seq_num.low >> 0); -- temp[8] = type; -- - /* TLS MAC includes the record's version field, SSL's doesn't. - ** We decide which MAC defintiion to use based on the version of - ** the protocol that was negotiated when the spec became current, - ** NOT based on the version value in the record itself. -- ** But, we use the record'v version value in the computation. -+ ** But, we use the record's version value in the computation. - */ -- if (spec->version <= SSL_LIBRARY_VERSION_3_0) { -- temp[9] = MSB(inputLength); -- temp[10] = LSB(inputLength); -- tempLen = 11; --#ifndef NO_PKCS11_BYPASS -- isTLS = PR_FALSE; --#endif -- } else { -- /* New TLS hash includes version. */ -- if (isDTLS) { -- SSL3ProtocolVersion dtls_version; -+ isTLS = spec->version > SSL_LIBRARY_VERSION_3_0; -+ tempLen = ssl3_BuildRecordPseudoHeader(temp, seq_num, type, isTLS, -+ version, isDTLS, inputLength); -+ PORT_Assert(tempLen <= sizeof(temp)); - -- dtls_version = dtls_TLSVersionToDTLSVersion(version); -- temp[9] = MSB(dtls_version); -- temp[10] = LSB(dtls_version); -- } else { -- temp[9] = MSB(version); -- temp[10] = LSB(version); -- } -- temp[11] = MSB(inputLength); -- temp[12] = LSB(inputLength); -- tempLen = 13; --#ifndef NO_PKCS11_BYPASS -- isTLS = PR_TRUE; --#endif -- } -- - PRINT_BUF(95, (NULL, "frag hash1: temp", temp, tempLen)); - PRINT_BUF(95, (NULL, "frag hash1: input", input, inputLength)); - -@@ -2390,86 +2609,112 @@ - contentLen = outlen; - } - -- /* -- * Add the MAC -- */ -- rv = ssl3_ComputeRecordMAC( cwSpec, isServer, isDTLS, -- type, cwSpec->version, cwSpec->write_seq_num, pIn, contentLen, -- wrBuf->buf + headerLen + ivLen + contentLen, &macLen); -- if (rv != SECSuccess) { -- ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE); -- return SECFailure; -- } -- p1Len = contentLen; -- p2Len = macLen; -- fragLen = contentLen + macLen; /* needs to be encrypted */ -- PORT_Assert(fragLen <= MAX_FRAGMENT_LENGTH + 1024); -+ if (cipher_def->type == type_aead) { -+ const int nonceLen = cipher_def->explicit_nonce_size; -+ const int tagLen = cipher_def->tag_size; - -- /* -- * Pad the text (if we're doing a block cipher) -- * then Encrypt it -- */ -- if (cipher_def->type == type_block) { -- unsigned char * pBuf; -- int padding_length; -- int i; -+ if (headerLen + nonceLen + contentLen + tagLen > wrBuf->space) { -+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); -+ return SECFailure; -+ } - -- oddLen = contentLen % cipher_def->block_size; -- /* Assume blockSize is a power of two */ -- padding_length = cipher_def->block_size - 1 - -- ((fragLen) & (cipher_def->block_size - 1)); -- fragLen += padding_length + 1; -- PORT_Assert((fragLen % cipher_def->block_size) == 0); -- -- /* Pad according to TLS rules (also acceptable to SSL3). */ -- pBuf = &wrBuf->buf[headerLen + ivLen + fragLen - 1]; -- for (i = padding_length + 1; i > 0; --i) { -- *pBuf-- = padding_length; -+ cipherBytes = contentLen; -+ rv = cwSpec->aead( -+ isServer ? &cwSpec->server : &cwSpec->client, -+ PR_FALSE, /* do encrypt */ -+ wrBuf->buf + headerLen, /* output */ -+ &cipherBytes, /* out len */ -+ wrBuf->space - headerLen, /* max out */ -+ pIn, contentLen, /* input */ -+ type, cwSpec->version, cwSpec->write_seq_num); -+ if (rv != SECSuccess) { -+ PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); -+ return SECFailure; - } -- /* now, if contentLen is not a multiple of block size, fix it */ -- p2Len = fragLen - p1Len; -- } -- if (p1Len < 256) { -- oddLen = p1Len; -- p1Len = 0; - } else { -- p1Len -= oddLen; -- } -- if (oddLen) { -- p2Len += oddLen; -- PORT_Assert( (cipher_def->block_size < 2) || \ -- (p2Len % cipher_def->block_size) == 0); -- memmove(wrBuf->buf + headerLen + ivLen + p1Len, pIn + p1Len, oddLen); -- } -- if (p1Len > 0) { -- int cipherBytesPart1 = -1; -- rv = cwSpec->encode( cwSpec->encodeContext, -- wrBuf->buf + headerLen + ivLen, /* output */ -- &cipherBytesPart1, /* actual outlen */ -- p1Len, /* max outlen */ -- pIn, p1Len); /* input, and inputlen */ -- PORT_Assert(rv == SECSuccess && cipherBytesPart1 == (int) p1Len); -- if (rv != SECSuccess || cipherBytesPart1 != (int) p1Len) { -- PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); -+ /* -+ * Add the MAC -+ */ -+ rv = ssl3_ComputeRecordMAC( cwSpec, isServer, isDTLS, -+ type, cwSpec->version, cwSpec->write_seq_num, pIn, contentLen, -+ wrBuf->buf + headerLen + ivLen + contentLen, &macLen); -+ if (rv != SECSuccess) { -+ ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE); - return SECFailure; - } -- cipherBytes += cipherBytesPart1; -+ p1Len = contentLen; -+ p2Len = macLen; -+ fragLen = contentLen + macLen; /* needs to be encrypted */ -+ PORT_Assert(fragLen <= MAX_FRAGMENT_LENGTH + 1024); -+ -+ /* -+ * Pad the text (if we're doing a block cipher) -+ * then Encrypt it -+ */ -+ if (cipher_def->type == type_block) { -+ unsigned char * pBuf; -+ int padding_length; -+ int i; -+ -+ oddLen = contentLen % cipher_def->block_size; -+ /* Assume blockSize is a power of two */ -+ padding_length = cipher_def->block_size - 1 - -+ ((fragLen) & (cipher_def->block_size - 1)); -+ fragLen += padding_length + 1; -+ PORT_Assert((fragLen % cipher_def->block_size) == 0); -+ -+ /* Pad according to TLS rules (also acceptable to SSL3). */ -+ pBuf = &wrBuf->buf[headerLen + ivLen + fragLen - 1]; -+ for (i = padding_length + 1; i > 0; --i) { -+ *pBuf-- = padding_length; -+ } -+ /* now, if contentLen is not a multiple of block size, fix it */ -+ p2Len = fragLen - p1Len; -+ } -+ if (p1Len < 256) { -+ oddLen = p1Len; -+ p1Len = 0; -+ } else { -+ p1Len -= oddLen; -+ } -+ if (oddLen) { -+ p2Len += oddLen; -+ PORT_Assert( (cipher_def->block_size < 2) || \ -+ (p2Len % cipher_def->block_size) == 0); -+ memmove(wrBuf->buf + headerLen + ivLen + p1Len, pIn + p1Len, -+ oddLen); -+ } -+ if (p1Len > 0) { -+ int cipherBytesPart1 = -1; -+ rv = cwSpec->encode( cwSpec->encodeContext, -+ wrBuf->buf + headerLen + ivLen, /* output */ -+ &cipherBytesPart1, /* actual outlen */ -+ p1Len, /* max outlen */ -+ pIn, p1Len); /* input, and inputlen */ -+ PORT_Assert(rv == SECSuccess && cipherBytesPart1 == (int) p1Len); -+ if (rv != SECSuccess || cipherBytesPart1 != (int) p1Len) { -+ PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); -+ return SECFailure; -+ } -+ cipherBytes += cipherBytesPart1; -+ } -+ if (p2Len > 0) { -+ int cipherBytesPart2 = -1; -+ rv = cwSpec->encode( cwSpec->encodeContext, -+ wrBuf->buf + headerLen + ivLen + p1Len, -+ &cipherBytesPart2, /* output and actual outLen */ -+ p2Len, /* max outlen */ -+ wrBuf->buf + headerLen + ivLen + p1Len, -+ p2Len); /* input and inputLen*/ -+ PORT_Assert(rv == SECSuccess && cipherBytesPart2 == (int) p2Len); -+ if (rv != SECSuccess || cipherBytesPart2 != (int) p2Len) { -+ PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); -+ return SECFailure; -+ } -+ cipherBytes += cipherBytesPart2; -+ } - } -- if (p2Len > 0) { -- int cipherBytesPart2 = -1; -- rv = cwSpec->encode( cwSpec->encodeContext, -- wrBuf->buf + headerLen + ivLen + p1Len, -- &cipherBytesPart2, /* output and actual outLen */ -- p2Len, /* max outlen */ -- wrBuf->buf + headerLen + ivLen + p1Len, -- p2Len); /* input and inputLen*/ -- PORT_Assert(rv == SECSuccess && cipherBytesPart2 == (int) p2Len); -- if (rv != SECSuccess || cipherBytesPart2 != (int) p2Len) { -- PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); -- return SECFailure; -- } -- cipherBytes += cipherBytesPart2; -- } -+ - PORT_Assert(cipherBytes <= MAX_FRAGMENT_LENGTH + 1024); - - wrBuf->len = cipherBytes + headerLen; -@@ -3012,9 +3257,6 @@ - static SECStatus - ssl3_IllegalParameter(sslSocket *ss) - { -- PRBool isTLS; -- -- isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0); - (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter); - PORT_SetError(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT - : SSL_ERROR_BAD_SERVER ); -@@ -3538,7 +3780,6 @@ - } - - key_material_params.bIsExport = (CK_BBOOL)(kea_def->is_limited); -- /* was: (CK_BBOOL)(cipher_def->keygen_mode != kg_strong); */ - - key_material_params.RandomInfo.pClientRandom = cr; - key_material_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH; -@@ -9946,7 +10187,6 @@ - static void - ssl3_RecordKeyLog(sslSocket *ss) - { -- sslSessionID *sid; - SECStatus rv; - SECItem *keyData; - char buf[14 /* "CLIENT_RANDOM " */ + -@@ -9958,8 +10198,6 @@ - - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); - -- sid = ss->sec.ci.sid; -- - if (!ssl_keylog_iob) - return; - -@@ -11171,12 +11409,14 @@ - /* With >= TLS 1.1, CBC records have an explicit IV. */ - minLength += cipher_def->iv_size; - } -+ } else if (cipher_def->type == type_aead) { -+ minLength = cipher_def->explicit_nonce_size + cipher_def->tag_size; - } - - /* We can perform this test in variable time because the record's total - * length and the ciphersuite are both public knowledge. */ - if (cText->buf->len < minLength) { -- goto decrypt_loser; -+ goto decrypt_loser; - } - - if (cipher_def->type == type_block && -@@ -11244,78 +11484,95 @@ - return SECFailure; - } - -- if (cipher_def->type == type_block && -- ((cText->buf->len - ivLen) % cipher_def->block_size) != 0) { -- goto decrypt_loser; -- } -+ rType = cText->type; -+ if (cipher_def->type == type_aead) { -+ rv = crSpec->aead( -+ ss->sec.isServer ? &crSpec->client : &crSpec->server, -+ PR_TRUE, /* do decrypt */ -+ plaintext->buf, /* out */ -+ (int*) &plaintext->len, /* outlen */ -+ plaintext->space, /* maxout */ -+ cText->buf->buf, /* in */ -+ cText->buf->len, /* inlen */ -+ rType, /* record type */ -+ cText->version, -+ IS_DTLS(ss) ? cText->seq_num : crSpec->read_seq_num); -+ if (rv != SECSuccess) { -+ good = 0; -+ } -+ } else { -+ if (cipher_def->type == type_block && -+ ((cText->buf->len - ivLen) % cipher_def->block_size) != 0) { -+ goto decrypt_loser; -+ } - -- /* decrypt from cText buf to plaintext. */ -- rv = crSpec->decode( -- crSpec->decodeContext, plaintext->buf, (int *)&plaintext->len, -- plaintext->space, cText->buf->buf + ivLen, cText->buf->len - ivLen); -- if (rv != SECSuccess) { -- goto decrypt_loser; -- } -+ /* decrypt from cText buf to plaintext. */ -+ rv = crSpec->decode( -+ crSpec->decodeContext, plaintext->buf, (int *)&plaintext->len, -+ plaintext->space, cText->buf->buf + ivLen, cText->buf->len - ivLen); -+ if (rv != SECSuccess) { -+ goto decrypt_loser; -+ } - -- PRINT_BUF(80, (ss, "cleartext:", plaintext->buf, plaintext->len)); -+ PRINT_BUF(80, (ss, "cleartext:", plaintext->buf, plaintext->len)); - -- originalLen = plaintext->len; -+ originalLen = plaintext->len; - -- /* If it's a block cipher, check and strip the padding. */ -- if (cipher_def->type == type_block) { -- const unsigned int blockSize = cipher_def->block_size; -- const unsigned int macSize = crSpec->mac_size; -+ /* If it's a block cipher, check and strip the padding. */ -+ if (cipher_def->type == type_block) { -+ const unsigned int blockSize = cipher_def->block_size; -+ const unsigned int macSize = crSpec->mac_size; - -- if (crSpec->version <= SSL_LIBRARY_VERSION_3_0) { -- good &= SECStatusToMask(ssl_RemoveSSLv3CBCPadding( -- plaintext, blockSize, macSize)); -- } else { -- good &= SECStatusToMask(ssl_RemoveTLSCBCPadding( -- plaintext, macSize)); -+ if (crSpec->version <= SSL_LIBRARY_VERSION_3_0) { -+ good &= SECStatusToMask(ssl_RemoveSSLv3CBCPadding( -+ plaintext, blockSize, macSize)); -+ } else { -+ good &= SECStatusToMask(ssl_RemoveTLSCBCPadding( -+ plaintext, macSize)); -+ } - } -- } - -- /* compute the MAC */ -- rType = cText->type; -- if (cipher_def->type == type_block) { -- rv = ssl3_ComputeRecordMACConstantTime( -- crSpec, (PRBool)(!ss->sec.isServer), -- IS_DTLS(ss), rType, cText->version, -- IS_DTLS(ss) ? cText->seq_num : crSpec->read_seq_num, -- plaintext->buf, plaintext->len, originalLen, -- hash, &hashBytes); -+ /* compute the MAC */ -+ if (cipher_def->type == type_block) { -+ rv = ssl3_ComputeRecordMACConstantTime( -+ crSpec, (PRBool)(!ss->sec.isServer), -+ IS_DTLS(ss), rType, cText->version, -+ IS_DTLS(ss) ? cText->seq_num : crSpec->read_seq_num, -+ plaintext->buf, plaintext->len, originalLen, -+ hash, &hashBytes); - -- ssl_CBCExtractMAC(plaintext, originalLen, givenHashBuf, -- crSpec->mac_size); -- givenHash = givenHashBuf; -+ ssl_CBCExtractMAC(plaintext, originalLen, givenHashBuf, -+ crSpec->mac_size); -+ givenHash = givenHashBuf; - -- /* plaintext->len will always have enough space to remove the MAC -- * because in ssl_Remove{SSLv3|TLS}CBCPadding we only adjust -- * plaintext->len if the result has enough space for the MAC and we -- * tested the unadjusted size against minLength, above. */ -- plaintext->len -= crSpec->mac_size; -- } else { -- /* This is safe because we checked the minLength above. */ -- plaintext->len -= crSpec->mac_size; -+ /* plaintext->len will always have enough space to remove the MAC -+ * because in ssl_Remove{SSLv3|TLS}CBCPadding we only adjust -+ * plaintext->len if the result has enough space for the MAC and we -+ * tested the unadjusted size against minLength, above. */ -+ plaintext->len -= crSpec->mac_size; -+ } else { -+ /* This is safe because we checked the minLength above. */ -+ plaintext->len -= crSpec->mac_size; - -- rv = ssl3_ComputeRecordMAC( -- crSpec, (PRBool)(!ss->sec.isServer), -- IS_DTLS(ss), rType, cText->version, -- IS_DTLS(ss) ? cText->seq_num : crSpec->read_seq_num, -- plaintext->buf, plaintext->len, -- hash, &hashBytes); -+ rv = ssl3_ComputeRecordMAC( -+ crSpec, (PRBool)(!ss->sec.isServer), -+ IS_DTLS(ss), rType, cText->version, -+ IS_DTLS(ss) ? cText->seq_num : crSpec->read_seq_num, -+ plaintext->buf, plaintext->len, -+ hash, &hashBytes); - -- /* We can read the MAC directly from the record because its location is -- * public when a stream cipher is used. */ -- givenHash = plaintext->buf + plaintext->len; -- } -+ /* We can read the MAC directly from the record because its location -+ * is public when a stream cipher is used. */ -+ givenHash = plaintext->buf + plaintext->len; -+ } - -- good &= SECStatusToMask(rv); -+ good &= SECStatusToMask(rv); - -- if (hashBytes != (unsigned)crSpec->mac_size || -- NSS_SecureMemcmp(givenHash, hash, crSpec->mac_size) != 0) { -- /* We're allowed to leak whether or not the MAC check was correct */ -- good = 0; -+ if (hashBytes != (unsigned)crSpec->mac_size || -+ NSS_SecureMemcmp(givenHash, hash, crSpec->mac_size) != 0) { -+ /* We're allowed to leak whether or not the MAC check was correct */ -+ good = 0; -+ } - } - - if (good == 0) { -Index: net/third_party/nss/ssl/sslenum.c -=================================================================== ---- net/third_party/nss/ssl/sslenum.c (revision 215189) -+++ net/third_party/nss/ssl/sslenum.c (working copy) -@@ -29,6 +29,14 @@ - * Finally, update the ssl_V3_SUITES_IMPLEMENTED macro in sslimpl.h. - */ - const PRUint16 SSL_ImplementedCiphers[] = { -+ /* AES-GCM */ -+#ifdef NSS_ENABLE_ECC -+ TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, -+ TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, -+#endif /* NSS_ENABLE_ECC */ -+ TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, -+ TLS_RSA_WITH_AES_128_GCM_SHA256, -+ - /* 256-bit */ - #ifdef NSS_ENABLE_ECC - TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, -Index: net/third_party/nss/ssl/sslproto.h -=================================================================== ---- net/third_party/nss/ssl/sslproto.h (revision 215189) -+++ net/third_party/nss/ssl/sslproto.h (working copy) -@@ -162,6 +162,10 @@ - - #define TLS_RSA_WITH_SEED_CBC_SHA 0x0096 - -+#define TLS_RSA_WITH_AES_128_GCM_SHA256 0x009C -+#define TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 0x009E -+#define TLS_DHE_DSS_WITH_AES_128_GCM_SHA256 0x00A2 -+ - /* TLS "Signaling Cipher Suite Value" (SCSV). May be requested by client. - * Must NEVER be chosen by server. SSL 3.0 server acknowledges by sending - * back an empty Renegotiation Info (RI) server hello extension. -@@ -204,6 +208,11 @@ - #define TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 0xC023 - #define TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 0xC027 - -+#define TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 0xC02B -+#define TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 0xC02D -+#define TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 0xC02F -+#define TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 0xC031 -+ - /* Netscape "experimental" cipher suites. */ - #define SSL_RSA_OLDFIPS_WITH_3DES_EDE_CBC_SHA 0xffe0 - #define SSL_RSA_OLDFIPS_WITH_DES_CBC_SHA 0xffe1 -Index: net/third_party/nss/ssl/sslt.h -=================================================================== ---- net/third_party/nss/ssl/sslt.h (revision 215189) -+++ net/third_party/nss/ssl/sslt.h (working copy) -@@ -91,9 +91,10 @@ - ssl_calg_3des = 4, - ssl_calg_idea = 5, - ssl_calg_fortezza = 6, /* deprecated, now unused */ -- ssl_calg_aes = 7, /* coming soon */ -+ ssl_calg_aes = 7, - ssl_calg_camellia = 8, -- ssl_calg_seed = 9 -+ ssl_calg_seed = 9, -+ ssl_calg_aes_gcm = 10 - } SSLCipherAlgorithm; - - typedef enum { -Index: net/third_party/nss/ssl/dtlscon.c -=================================================================== ---- net/third_party/nss/ssl/dtlscon.c (revision 215189) -+++ net/third_party/nss/ssl/dtlscon.c (working copy) -@@ -30,7 +30,14 @@ - - /* List copied from ssl3con.c:cipherSuites */ - static const ssl3CipherSuite nonDTLSSuites[] = { -+ /* XXX Make AES-GCM work with DTLS. */ - #ifdef NSS_ENABLE_ECC -+ TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, -+ TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, -+#endif /* NSS_ENABLE_ECC */ -+ TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, -+ TLS_RSA_WITH_AES_128_GCM_SHA256, -+#ifdef NSS_ENABLE_ECC - TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, - TLS_ECDHE_RSA_WITH_RC4_128_SHA, - #endif /* NSS_ENABLE_ECC */ diff --git a/chromium/net/third_party/nss/patches/aesgcmchromium.patch b/chromium/net/third_party/nss/patches/aesgcmchromium.patch deleted file mode 100644 index 8cd72bb9d9f..00000000000 --- a/chromium/net/third_party/nss/patches/aesgcmchromium.patch +++ /dev/null @@ -1,117 +0,0 @@ ---- net/third_party/nss/ssl/ssl3con.c.orig 2013-08-14 14:22:50.479780305 -0700 -+++ net/third_party/nss/ssl/ssl3con.c 2013-08-14 14:23:57.670788603 -0700 -@@ -44,6 +44,9 @@ - #ifdef NSS_ENABLE_ZLIB - #include "zlib.h" - #endif -+#ifdef LINUX -+#include <dlfcn.h> -+#endif - - #ifndef PK11_SETATTRS - #define PK11_SETATTRS(x,id,v,l) (x)->type = (id); \ -@@ -1807,6 +1810,69 @@ ssl3_BuildRecordPseudoHeader(unsigned ch - return 13; - } - -+typedef SECStatus (*PK11CryptFcn)( -+ PK11SymKey *symKey, CK_MECHANISM_TYPE mechanism, SECItem *param, -+ unsigned char *out, unsigned int *outLen, unsigned int maxLen, -+ const unsigned char *in, unsigned int inLen); -+ -+static PK11CryptFcn pk11_encrypt = NULL; -+static PK11CryptFcn pk11_decrypt = NULL; -+ -+static PRCallOnceType resolvePK11CryptOnce; -+ -+static PRStatus -+ssl3_ResolvePK11CryptFunctions(void) -+{ -+#ifdef LINUX -+ /* On Linux we use the system NSS libraries. Look up the PK11_Encrypt and -+ * PK11_Decrypt functions at run time. */ -+ void *handle = dlopen(NULL, RTLD_LAZY); -+ if (!handle) { -+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); -+ return PR_FAILURE; -+ } -+ pk11_encrypt = (PK11CryptFcn)dlsym(handle, "PK11_Encrypt"); -+ pk11_decrypt = (PK11CryptFcn)dlsym(handle, "PK11_Decrypt"); -+ dlclose(handle); -+ return PR_SUCCESS; -+#else -+ /* On other platforms we use our own copy of NSS. PK11_Encrypt and -+ * PK11_Decrypt are known to be available. */ -+ pk11_encrypt = PK11_Encrypt; -+ pk11_decrypt = PK11_Decrypt; -+ return PR_SUCCESS; -+#endif -+} -+ -+/* -+ * In NSS 3.15, PK11_Encrypt and PK11_Decrypt were added to provide access -+ * to the AES GCM implementation in the NSS softoken. So the presence of -+ * these two functions implies the NSS version supports AES GCM. -+ */ -+static PRBool -+ssl3_HasGCMSupport(void) -+{ -+ (void)PR_CallOnce(&resolvePK11CryptOnce, ssl3_ResolvePK11CryptFunctions); -+ return pk11_encrypt != NULL; -+} -+ -+/* On this socket, disable the GCM cipher suites */ -+SECStatus -+ssl3_DisableGCMSuites(sslSocket * ss) -+{ -+ unsigned int i; -+ -+ for (i = 0; i < PR_ARRAY_SIZE(cipher_suite_defs); i++) { -+ const ssl3CipherSuiteDef *cipher_def = &cipher_suite_defs[i]; -+ if (cipher_def->bulk_cipher_alg == cipher_aes_128_gcm) { -+ SECStatus rv = ssl3_CipherPrefSet(ss, cipher_def->cipher_suite, -+ PR_FALSE); -+ PORT_Assert(rv == SECSuccess); /* else is coding error */ -+ } -+ } -+ return SECSuccess; -+} -+ - static SECStatus - ssl3_AESGCM(ssl3KeyMaterial *keys, - PRBool doDecrypt, -@@ -1869,10 +1935,10 @@ ssl3_AESGCM(ssl3KeyMaterial *keys, - gcmParams.ulTagBits = tagSize * 8; - - if (doDecrypt) { -- rv = PK11_Decrypt(keys->write_key, CKM_AES_GCM, ¶m, out, &uOutLen, -+ rv = pk11_decrypt(keys->write_key, CKM_AES_GCM, ¶m, out, &uOutLen, - maxout, in, inlen); - } else { -- rv = PK11_Encrypt(keys->write_key, CKM_AES_GCM, ¶m, out, &uOutLen, -+ rv = pk11_encrypt(keys->write_key, CKM_AES_GCM, ¶m, out, &uOutLen, - maxout, in, inlen); - } - *outlen += (int) uOutLen; -@@ -5071,6 +5137,10 @@ ssl3_SendClientHello(sslSocket *ss, PRBo - ssl3_DisableNonDTLSSuites(ss); - } - -+ if (!ssl3_HasGCMSupport()) { -+ ssl3_DisableGCMSuites(ss); -+ } -+ - /* how many suites are permitted by policy and user preference? */ - num_suites = count_cipher_suites(ss, ss->ssl3.policy, PR_TRUE); - if (!num_suites) -@@ -7776,6 +7846,10 @@ ssl3_HandleClientHello(sslSocket *ss, SS - ssl3_DisableNonDTLSSuites(ss); - } - -+ if (!ssl3_HasGCMSupport()) { -+ ssl3_DisableGCMSuites(ss); -+ } -+ - #ifdef PARANOID - /* Look for a matching cipher suite. */ - j = ssl3_config_match_init(ss); diff --git a/chromium/net/third_party/nss/patches/applypatches.sh b/chromium/net/third_party/nss/patches/applypatches.sh index 14377acbe46..68798aa6ebb 100755 --- a/chromium/net/third_party/nss/patches/applypatches.sh +++ b/chromium/net/third_party/nss/patches/applypatches.sh @@ -48,6 +48,4 @@ patch -p4 < $patches_dir/alpn.patch patch -p5 < $patches_dir/sslsock_903565.patch -patch -p4 < $patches_dir/aesgcm.patch - -patch -p4 < $patches_dir/aesgcmchromium.patch +patch -p4 < $patches_dir/tls12backuphash.patch diff --git a/chromium/net/third_party/nss/patches/tls12backuphash.patch b/chromium/net/third_party/nss/patches/tls12backuphash.patch new file mode 100644 index 00000000000..92dd9183a07 --- /dev/null +++ b/chromium/net/third_party/nss/patches/tls12backuphash.patch @@ -0,0 +1,220 @@ +Index: net/third_party/nss/ssl/ssl3con.c +=================================================================== +--- net/third_party/nss/ssl/ssl3con.c (revision 220594) ++++ net/third_party/nss/ssl/ssl3con.c (working copy) +@@ -3933,6 +3933,20 @@ + ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); + return SECFailure; + } ++ ++ /* A backup SHA-1 hash for a potential client auth signature. */ ++ if (!ss->sec.isServer) { ++ ss->ssl3.hs.md5 = PK11_CreateDigestContext(SEC_OID_SHA1); ++ if (ss->ssl3.hs.md5 == NULL) { ++ ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); ++ return SECFailure; ++ } ++ ++ if (PK11_DigestBegin(ss->ssl3.hs.md5) != SECSuccess) { ++ ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); ++ return SECFailure; ++ } ++ } + } else { + /* Both ss->ssl3.hs.md5 and ss->ssl3.hs.sha should be NULL or + * created successfully. */ +@@ -4043,6 +4057,13 @@ + ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); + return rv; + } ++ if (ss->ssl3.hs.md5) { ++ rv = PK11_DigestOp(ss->ssl3.hs.md5, b, l); ++ if (rv != SECSuccess) { ++ ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); ++ return rv; ++ } ++ } + } else { + rv = PK11_DigestOp(ss->ssl3.hs.md5, b, l); + if (rv != SECSuccess) { +@@ -4791,6 +4812,30 @@ + return rv; + } + ++static SECStatus ++ssl3_ComputeBackupHandshakeHashes(sslSocket * ss, ++ SSL3Hashes * hashes) /* output goes here. */ ++{ ++ SECStatus rv = SECSuccess; ++ ++ PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); ++ PORT_Assert( ss->ssl3.hs.hashType == handshake_hash_single ); ++ ++ rv = PK11_DigestFinal(ss->ssl3.hs.md5, hashes->u.raw, &hashes->len, ++ sizeof(hashes->u.raw)); ++ if (rv != SECSuccess) { ++ ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); ++ rv = SECFailure; ++ goto loser; ++ } ++ hashes->hashAlg = SEC_OID_SHA1; ++ ++loser: ++ PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE); ++ ss->ssl3.hs.md5 = NULL; ++ return rv; ++} ++ + /* + * SSL 2 based implementations pass in the initial outbound buffer + * so that the handshake hash can contain the included information. +@@ -6044,7 +6089,17 @@ + SSL_GETPID(), ss->fd)); + + ssl_GetSpecReadLock(ss); +- rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.pwSpec, &hashes, 0); ++ /* In TLS 1.2, ssl3_ComputeHandshakeHashes always uses the handshake hash ++ * function (SHA-256). If the server or the client does not support SHA-256 ++ * as a signature hash, we can either maintain a backup SHA-1 handshake ++ * hash or buffer all handshake messages. ++ */ ++ if (ss->ssl3.hs.hashType == handshake_hash_single && ss->ssl3.hs.md5) { ++ rv = ssl3_ComputeBackupHandshakeHashes(ss, &hashes); ++ PORT_Assert(ss->ssl3.hs.md5 == NULL); ++ } else { ++ rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.pwSpec, &hashes, 0); ++ } + ssl_ReleaseSpecReadLock(ss); + if (rv != SECSuccess) { + goto done; /* err code was set by ssl3_ComputeHandshakeHashes */ +@@ -6098,11 +6153,6 @@ + if (rv != SECSuccess) { + goto done; + } +- /* We always sign using the handshake hash function. It's possible that +- * a server could support SHA-256 as the handshake hash but not as a +- * signature hash. In that case we wouldn't be able to do client +- * certificates with it. The alternative is to buffer all handshake +- * messages. */ + sigAndHash.hashAlg = hashes.hashAlg; + + rv = ssl3_AppendSignatureAndHashAlgorithm(ss, &sigAndHash); +@@ -6802,6 +6852,70 @@ + } + + ++/* ++ * Returns true if the client authentication key is an RSA or DSA key that ++ * may be able to sign only SHA-1 hashes. ++ */ ++static PRBool ++ssl3_ClientKeyPrefersSHA1(sslSocket *ss) ++{ ++ SECKEYPublicKey *pubk; ++ PRBool prefer_sha1 = PR_FALSE; ++ ++#if defined(NSS_PLATFORM_CLIENT_AUTH) && defined(_WIN32) ++ /* If the key is in CAPI, assume conservatively that the CAPI service ++ * provider may be unable to sign SHA-256 hashes. ++ */ ++ if (ss->ssl3.platformClientKey->dwKeySpec != CERT_NCRYPT_KEY_SPEC) { ++ /* CAPI only supports RSA and DSA signatures, so we don't need to ++ * check the key type. */ ++ return PR_TRUE; ++ } ++#endif /* NSS_PLATFORM_CLIENT_AUTH && _WIN32 */ ++ ++ /* If the key is a 1024-bit RSA or DSA key, assume conservatively that ++ * it may be unable to sign SHA-256 hashes. This is the case for older ++ * Estonian ID cards that have 1024-bit RSA keys. In FIPS 186-2 and ++ * older, DSA key size is at most 1024 bits and the hash function must ++ * be SHA-1. ++ */ ++ pubk = CERT_ExtractPublicKey(ss->ssl3.clientCertificate); ++ if (pubk == NULL) { ++ return PR_FALSE; ++ } ++ if (pubk->keyType == rsaKey || pubk->keyType == dsaKey) { ++ prefer_sha1 = SECKEY_PublicKeyStrength(pubk) <= 128; ++ } ++ SECKEY_DestroyPublicKey(pubk); ++ return prefer_sha1; ++} ++ ++/* Destroys the backup handshake hash context if we don't need it. */ ++static void ++ssl3_DestroyBackupHandshakeHashIfNotNeeded(sslSocket *ss, ++ const SECItem *algorithms) ++{ ++ PRBool need_backup_hash = PR_FALSE; ++ unsigned int i; ++ ++ PORT_Assert(ss->ssl3.hs.md5); ++ if (ssl3_ClientKeyPrefersSHA1(ss)) { ++ /* Use SHA-1 if the server supports it. */ ++ for (i = 0; i < algorithms->len; i += 2) { ++ if (algorithms->data[i] == tls_hash_sha1 && ++ (algorithms->data[i+1] == tls_sig_rsa || ++ algorithms->data[i+1] == tls_sig_dsa)) { ++ need_backup_hash = PR_TRUE; ++ break; ++ } ++ } ++ } ++ if (!need_backup_hash) { ++ PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE); ++ ss->ssl3.hs.md5 = NULL; ++ } ++} ++ + typedef struct dnameNode { + struct dnameNode *next; + SECItem name; +@@ -6994,6 +7108,9 @@ + } + goto send_no_certificate; + } ++ if (isTLS12) { ++ ssl3_DestroyBackupHandshakeHashIfNotNeeded(ss, &algorithms); ++ } + break; /* not an error */ + } + #endif /* NSS_PLATFORM_CLIENT_AUTH */ +@@ -7029,6 +7146,9 @@ + } + goto send_no_certificate; + } ++ if (isTLS12) { ++ ssl3_DestroyBackupHandshakeHashIfNotNeeded(ss, &algorithms); ++ } + break; /* not an error */ + + case SECFailure: +@@ -7227,6 +7347,13 @@ + (ss->ssl3.platformClientKey || + ss->ssl3.clientPrivateKey != NULL); + ++ if (!sendClientCert && ++ ss->ssl3.hs.hashType == handshake_hash_single && ss->ssl3.hs.md5) { ++ /* Don't need the backup handshake hash. */ ++ PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE); ++ ss->ssl3.hs.md5 = NULL; ++ } ++ + /* We must wait for the server's certificate to be authenticated before + * sending the client certificate in order to disclosing the client + * certificate to an attacker that does not have a valid cert for the +Index: net/third_party/nss/ssl/sslimpl.h +=================================================================== +--- net/third_party/nss/ssl/sslimpl.h (revision 220594) ++++ net/third_party/nss/ssl/sslimpl.h (working copy) +@@ -838,6 +838,9 @@ + * SSL 3.0 - TLS 1.1 use both |md5| and |sha|. |md5| is used for MD5 and + * |sha| for SHA-1. + * TLS 1.2 and later use only |sha|, for SHA-256. */ ++ /* NOTE: On the client side, TLS 1.2 and later use |md5| as a backup ++ * handshake hash for generating client auth signatures. Confusingly, the ++ * backup hash function is SHA-1. */ + PK11Context * md5; + PK11Context * sha; + diff --git a/chromium/net/third_party/nss/ssl/dtlscon.c b/chromium/net/third_party/nss/ssl/dtlscon.c index e86ae01ddbe..78371e62a6c 100644 --- a/chromium/net/third_party/nss/ssl/dtlscon.c +++ b/chromium/net/third_party/nss/ssl/dtlscon.c @@ -30,13 +30,6 @@ static const PRUint16 COMMON_MTU_VALUES[] = { /* List copied from ssl3con.c:cipherSuites */ static const ssl3CipherSuite nonDTLSSuites[] = { - /* XXX Make AES-GCM work with DTLS. */ -#ifdef NSS_ENABLE_ECC - TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, - TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, -#endif /* NSS_ENABLE_ECC */ - TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, - TLS_RSA_WITH_AES_128_GCM_SHA256, #ifdef NSS_ENABLE_ECC TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA, diff --git a/chromium/net/third_party/nss/ssl/ssl3con.c b/chromium/net/third_party/nss/ssl/ssl3con.c index e614eab2bde..bf4ff6b716c 100644 --- a/chromium/net/third_party/nss/ssl/ssl3con.c +++ b/chromium/net/third_party/nss/ssl/ssl3con.c @@ -44,9 +44,6 @@ #ifdef NSS_ENABLE_ZLIB #include "zlib.h" #endif -#ifdef LINUX -#include <dlfcn.h> -#endif #ifndef PK11_SETATTRS #define PK11_SETATTRS(x,id,v,l) (x)->type = (id); \ @@ -81,14 +78,6 @@ static int ssl3_OIDToTLSHashAlgorithm(SECOidTag oid); static SECStatus Null_Cipher(void *ctx, unsigned char *output, int *outputLen, int maxOutputLen, const unsigned char *input, int inputLen); -#ifndef NO_PKCS11_BYPASS -static SECStatus ssl3_AESGCMBypass(ssl3KeyMaterial *keys, PRBool doDecrypt, - unsigned char *out, int *outlen, int maxout, - const unsigned char *in, int inlen, - SSL3ContentType type, - SSL3ProtocolVersion version, - SSL3SequenceNumber seq_num); -#endif #define MAX_SEND_BUF_LENGTH 32000 /* watch for 16-bit integer overflow */ #define MIN_SEND_BUF_LENGTH 4000 @@ -101,13 +90,6 @@ static SECStatus ssl3_AESGCMBypass(ssl3KeyMaterial *keys, PRBool doDecrypt, static ssl3CipherSuiteCfg cipherSuites[ssl_V3_SUITES_IMPLEMENTED] = { /* cipher_suite policy enabled is_present*/ #ifdef NSS_ENABLE_ECC - { TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE}, - { TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE}, -#endif /* NSS_ENABLE_ECC */ - { TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE}, - { TLS_RSA_WITH_AES_128_GCM_SHA256, SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE}, - -#ifdef NSS_ENABLE_ECC { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE}, { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE}, #endif /* NSS_ENABLE_ECC */ @@ -251,30 +233,23 @@ static SSL3Statistics ssl3stats; /* indexed by SSL3BulkCipher */ static const ssl3BulkCipherDef bulk_cipher_defs[] = { - /* |--------- Lengths --------| */ - /* cipher calg k s type i b t n */ - /* e e v l a o */ - /* y c | o g n */ - /* | r | c | c */ - /* | e | k | e */ - /* | t | | | | */ - {cipher_null, calg_null, 0, 0, type_stream, 0, 0, 0, 0}, - {cipher_rc4, calg_rc4, 16,16, type_stream, 0, 0, 0, 0}, - {cipher_rc4_40, calg_rc4, 16, 5, type_stream, 0, 0, 0, 0}, - {cipher_rc4_56, calg_rc4, 16, 7, type_stream, 0, 0, 0, 0}, - {cipher_rc2, calg_rc2, 16,16, type_block, 8, 8, 0, 0}, - {cipher_rc2_40, calg_rc2, 16, 5, type_block, 8, 8, 0, 0}, - {cipher_des, calg_des, 8, 8, type_block, 8, 8, 0, 0}, - {cipher_3des, calg_3des, 24,24, type_block, 8, 8, 0, 0}, - {cipher_des40, calg_des, 8, 5, type_block, 8, 8, 0, 0}, - {cipher_idea, calg_idea, 16,16, type_block, 8, 8, 0, 0}, - {cipher_aes_128, calg_aes, 16,16, type_block, 16,16, 0, 0}, - {cipher_aes_256, calg_aes, 32,32, type_block, 16,16, 0, 0}, - {cipher_camellia_128, calg_camellia, 16,16, type_block, 16,16, 0, 0}, - {cipher_camellia_256, calg_camellia, 32,32, type_block, 16,16, 0, 0}, - {cipher_seed, calg_seed, 16,16, type_block, 16,16, 0, 0}, - {cipher_aes_128_gcm, calg_aes_gcm, 16,16, type_aead, 4, 0,16, 8}, - {cipher_missing, calg_null, 0, 0, type_stream, 0, 0, 0, 0}, + /* cipher calg keySz secretSz type ivSz BlkSz keygen */ + {cipher_null, calg_null, 0, 0, type_stream, 0, 0, kg_null}, + {cipher_rc4, calg_rc4, 16, 16, type_stream, 0, 0, kg_strong}, + {cipher_rc4_40, calg_rc4, 16, 5, type_stream, 0, 0, kg_export}, + {cipher_rc4_56, calg_rc4, 16, 7, type_stream, 0, 0, kg_export}, + {cipher_rc2, calg_rc2, 16, 16, type_block, 8, 8, kg_strong}, + {cipher_rc2_40, calg_rc2, 16, 5, type_block, 8, 8, kg_export}, + {cipher_des, calg_des, 8, 8, type_block, 8, 8, kg_strong}, + {cipher_3des, calg_3des, 24, 24, type_block, 8, 8, kg_strong}, + {cipher_des40, calg_des, 8, 5, type_block, 8, 8, kg_export}, + {cipher_idea, calg_idea, 16, 16, type_block, 8, 8, kg_strong}, + {cipher_aes_128, calg_aes, 16, 16, type_block, 16,16, kg_strong}, + {cipher_aes_256, calg_aes, 32, 32, type_block, 16,16, kg_strong}, + {cipher_camellia_128, calg_camellia,16, 16, type_block, 16,16, kg_strong}, + {cipher_camellia_256, calg_camellia,32, 32, type_block, 16,16, kg_strong}, + {cipher_seed, calg_seed, 16, 16, type_block, 16,16, kg_strong}, + {cipher_missing, calg_null, 0, 0, type_stream, 0, 0, kg_null}, }; static const ssl3KEADef kea_defs[] = @@ -396,11 +371,6 @@ static const ssl3CipherSuiteDef cipher_suite_defs[] = {SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_rsa_fips}, {SSL_RSA_FIPS_WITH_DES_CBC_SHA, cipher_des, mac_sha, kea_rsa_fips}, - {TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_null, kea_dhe_rsa}, - {TLS_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_null, kea_rsa}, - {TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_null, kea_ecdhe_rsa}, - {TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_null, kea_ecdhe_ecdsa}, - #ifdef NSS_ENABLE_ECC {TLS_ECDH_ECDSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdh_ecdsa}, {TLS_ECDH_ECDSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdh_ecdsa}, @@ -464,7 +434,6 @@ static const SSLCipher2Mech alg2Mech[] = { { calg_aes , CKM_AES_CBC }, { calg_camellia , CKM_CAMELLIA_CBC }, { calg_seed , CKM_SEED_CBC }, - { calg_aes_gcm , CKM_AES_GCM }, /* { calg_init , (CK_MECHANISM_TYPE)0x7fffffffL } */ }; @@ -503,7 +472,6 @@ const char * const ssl3_cipherName[] = { "Camellia-128", "Camellia-256", "SEED-CBC", - "AES-128-GCM", "missing" }; @@ -630,13 +598,9 @@ ssl3_CipherSuiteAllowedForVersion(ssl3CipherSuite cipherSuite, case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256: case TLS_RSA_WITH_AES_256_CBC_SHA256: case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256: - case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256: - case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256: - case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256: case TLS_RSA_WITH_AES_128_CBC_SHA256: - case TLS_RSA_WITH_AES_128_GCM_SHA256: case TLS_RSA_WITH_NULL_SHA256: return version >= SSL_LIBRARY_VERSION_TLS_1_2; default: @@ -1396,7 +1360,7 @@ ssl3_SetupPendingCipherSpec(sslSocket *ss) cipher = suite_def->bulk_cipher_alg; kea = suite_def->key_exchange_alg; mac = suite_def->mac_alg; - if (mac <= ssl_mac_sha && mac != ssl_mac_null && isTLS) + if (mac <= ssl_mac_sha && isTLS) mac += 2; ss->ssl3.hs.suite_def = suite_def; @@ -1590,6 +1554,7 @@ ssl3_InitPendingContextsBypass(sslSocket *ss) unsigned int optArg2 = 0; PRBool server_encrypts = ss->sec.isServer; SSLCipherAlgorithm calg; + SSLCompressionMethod compression_method; SECStatus rv; PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); @@ -1600,17 +1565,7 @@ ssl3_InitPendingContextsBypass(sslSocket *ss) cipher_def = pwSpec->cipher_def; calg = cipher_def->calg; - - if (calg == calg_aes_gcm) { - pwSpec->encode = NULL; - pwSpec->decode = NULL; - pwSpec->destroy = NULL; - pwSpec->encodeContext = NULL; - pwSpec->decodeContext = NULL; - pwSpec->aead = ssl3_AESGCMBypass; - ssl3_InitCompressionContext(pwSpec); - return SECSuccess; - } + compression_method = pwSpec->compression_method; serverContext = pwSpec->server.cipher_context; clientContext = pwSpec->client.cipher_context; @@ -1766,270 +1721,6 @@ ssl3_ParamFromIV(CK_MECHANISM_TYPE mtype, SECItem *iv, CK_ULONG ulEffectiveBits) return param; } -/* ssl3_BuildRecordPseudoHeader writes the TLS pseudo-header (the data which - * is included in the MAC) to |out| and returns its length. */ -static unsigned int -ssl3_BuildRecordPseudoHeader(unsigned char *out, - SSL3SequenceNumber seq_num, - SSL3ContentType type, - PRBool includesVersion, - SSL3ProtocolVersion version, - PRBool isDTLS, - int length) -{ - out[0] = (unsigned char)(seq_num.high >> 24); - out[1] = (unsigned char)(seq_num.high >> 16); - out[2] = (unsigned char)(seq_num.high >> 8); - out[3] = (unsigned char)(seq_num.high >> 0); - out[4] = (unsigned char)(seq_num.low >> 24); - out[5] = (unsigned char)(seq_num.low >> 16); - out[6] = (unsigned char)(seq_num.low >> 8); - out[7] = (unsigned char)(seq_num.low >> 0); - out[8] = type; - - /* SSL3 MAC doesn't include the record's version field. */ - if (!includesVersion) { - out[9] = MSB(length); - out[10] = LSB(length); - return 11; - } - - /* TLS MAC and AEAD additional data include version. */ - if (isDTLS) { - SSL3ProtocolVersion dtls_version; - - dtls_version = dtls_TLSVersionToDTLSVersion(version); - out[9] = MSB(dtls_version); - out[10] = LSB(dtls_version); - } else { - out[9] = MSB(version); - out[10] = LSB(version); - } - out[11] = MSB(length); - out[12] = LSB(length); - return 13; -} - -typedef SECStatus (*PK11CryptFcn)( - PK11SymKey *symKey, CK_MECHANISM_TYPE mechanism, SECItem *param, - unsigned char *out, unsigned int *outLen, unsigned int maxLen, - const unsigned char *in, unsigned int inLen); - -static PK11CryptFcn pk11_encrypt = NULL; -static PK11CryptFcn pk11_decrypt = NULL; - -static PRCallOnceType resolvePK11CryptOnce; - -static PRStatus -ssl3_ResolvePK11CryptFunctions(void) -{ -#ifdef LINUX - /* On Linux we use the system NSS libraries. Look up the PK11_Encrypt and - * PK11_Decrypt functions at run time. */ - void *handle = dlopen(NULL, RTLD_LAZY); - if (!handle) { - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - return PR_FAILURE; - } - pk11_encrypt = (PK11CryptFcn)dlsym(handle, "PK11_Encrypt"); - pk11_decrypt = (PK11CryptFcn)dlsym(handle, "PK11_Decrypt"); - dlclose(handle); - return PR_SUCCESS; -#else - /* On other platforms we use our own copy of NSS. PK11_Encrypt and - * PK11_Decrypt are known to be available. */ - pk11_encrypt = PK11_Encrypt; - pk11_decrypt = PK11_Decrypt; - return PR_SUCCESS; -#endif -} - -/* - * In NSS 3.15, PK11_Encrypt and PK11_Decrypt were added to provide access - * to the AES GCM implementation in the NSS softoken. So the presence of - * these two functions implies the NSS version supports AES GCM. - */ -static PRBool -ssl3_HasGCMSupport(void) -{ - (void)PR_CallOnce(&resolvePK11CryptOnce, ssl3_ResolvePK11CryptFunctions); - return pk11_encrypt != NULL; -} - -/* On this socket, disable the GCM cipher suites */ -SECStatus -ssl3_DisableGCMSuites(sslSocket * ss) -{ - unsigned int i; - - for (i = 0; i < PR_ARRAY_SIZE(cipher_suite_defs); i++) { - const ssl3CipherSuiteDef *cipher_def = &cipher_suite_defs[i]; - if (cipher_def->bulk_cipher_alg == cipher_aes_128_gcm) { - SECStatus rv = ssl3_CipherPrefSet(ss, cipher_def->cipher_suite, - PR_FALSE); - PORT_Assert(rv == SECSuccess); /* else is coding error */ - } - } - return SECSuccess; -} - -static SECStatus -ssl3_AESGCM(ssl3KeyMaterial *keys, - PRBool doDecrypt, - unsigned char *out, - int *outlen, - int maxout, - const unsigned char *in, - int inlen, - SSL3ContentType type, - SSL3ProtocolVersion version, - SSL3SequenceNumber seq_num) -{ - SECItem param; - SECStatus rv = SECFailure; - unsigned char nonce[12]; - unsigned char additionalData[13]; - unsigned int additionalDataLen; - unsigned int uOutLen; - CK_GCM_PARAMS gcmParams; - - static const int tagSize = 16; - static const int explicitNonceLen = 8; - - /* See https://tools.ietf.org/html/rfc5246#section-6.2.3.3 for the - * definition of the AEAD additional data. */ - additionalDataLen = ssl3_BuildRecordPseudoHeader( - additionalData, seq_num, type, PR_TRUE /* includes version */, - version, PR_FALSE /* not DTLS */, - inlen - (doDecrypt ? explicitNonceLen + tagSize : 0)); - PORT_Assert(additionalDataLen <= sizeof(additionalData)); - - /* See https://tools.ietf.org/html/rfc5288#section-3 for details of how the - * nonce is formed. */ - memcpy(nonce, keys->write_iv, 4); - if (doDecrypt) { - memcpy(nonce + 4, in, explicitNonceLen); - in += explicitNonceLen; - inlen -= explicitNonceLen; - *outlen = 0; - } else { - if (maxout < explicitNonceLen) { - PORT_SetError(SEC_ERROR_INPUT_LEN); - return SECFailure; - } - /* Use the 64-bit sequence number as the explicit nonce. */ - memcpy(nonce + 4, additionalData, explicitNonceLen); - memcpy(out, additionalData, explicitNonceLen); - out += explicitNonceLen; - maxout -= explicitNonceLen; - *outlen = explicitNonceLen; - } - - param.type = siBuffer; - param.data = (unsigned char *) &gcmParams; - param.len = sizeof(gcmParams); - gcmParams.pIv = nonce; - gcmParams.ulIvLen = sizeof(nonce); - gcmParams.pAAD = additionalData; - gcmParams.ulAADLen = additionalDataLen; - gcmParams.ulTagBits = tagSize * 8; - - if (doDecrypt) { - rv = pk11_decrypt(keys->write_key, CKM_AES_GCM, ¶m, out, &uOutLen, - maxout, in, inlen); - } else { - rv = pk11_encrypt(keys->write_key, CKM_AES_GCM, ¶m, out, &uOutLen, - maxout, in, inlen); - } - *outlen += (int) uOutLen; - - return rv; -} - -#ifndef NO_PKCS11_BYPASS -static SECStatus -ssl3_AESGCMBypass(ssl3KeyMaterial *keys, - PRBool doDecrypt, - unsigned char *out, - int *outlen, - int maxout, - const unsigned char *in, - int inlen, - SSL3ContentType type, - SSL3ProtocolVersion version, - SSL3SequenceNumber seq_num) -{ - SECStatus rv = SECFailure; - unsigned char nonce[12]; - unsigned char additionalData[13]; - unsigned int additionalDataLen; - unsigned int uOutLen; - AESContext *cx; - CK_GCM_PARAMS gcmParams; - - static const int tagSize = 16; - static const int explicitNonceLen = 8; - - /* See https://tools.ietf.org/html/rfc5246#section-6.2.3.3 for the - * definition of the AEAD additional data. */ - additionalDataLen = ssl3_BuildRecordPseudoHeader( - additionalData, seq_num, type, PR_TRUE /* includes version */, - version, PR_FALSE /* not DTLS */, - inlen - (doDecrypt ? explicitNonceLen + tagSize : 0)); - PORT_Assert(additionalDataLen <= sizeof(additionalData)); - - /* See https://tools.ietf.org/html/rfc5288#section-3 for details of how the - * nonce is formed. */ - PORT_Assert(keys->write_iv_item.len == 4); - if (keys->write_iv_item.len != 4) { - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - return SECFailure; - } - memcpy(nonce, keys->write_iv_item.data, 4); - if (doDecrypt) { - memcpy(nonce + 4, in, explicitNonceLen); - in += explicitNonceLen; - inlen -= explicitNonceLen; - *outlen = 0; - } else { - if (maxout < explicitNonceLen) { - PORT_SetError(SEC_ERROR_INPUT_LEN); - return SECFailure; - } - /* Use the 64-bit sequence number as the explicit nonce. */ - memcpy(nonce + 4, additionalData, explicitNonceLen); - memcpy(out, additionalData, explicitNonceLen); - out += explicitNonceLen; - maxout -= explicitNonceLen; - *outlen = explicitNonceLen; - } - - gcmParams.pIv = nonce; - gcmParams.ulIvLen = sizeof(nonce); - gcmParams.pAAD = additionalData; - gcmParams.ulAADLen = additionalDataLen; - gcmParams.ulTagBits = tagSize * 8; - - cx = (AESContext *)keys->cipher_context; - rv = AES_InitContext(cx, keys->write_key_item.data, - keys->write_key_item.len, - (unsigned char *)&gcmParams, NSS_AES_GCM, !doDecrypt, - AES_BLOCK_SIZE); - if (rv != SECSuccess) { - return rv; - } - if (doDecrypt) { - rv = AES_Decrypt(cx, out, &uOutLen, maxout, in, inlen); - } else { - rv = AES_Encrypt(cx, out, &uOutLen, maxout, in, inlen); - } - AES_DestroyContext(cx, PR_FALSE); - *outlen += (int) uOutLen; - - return rv; -} -#endif - /* Initialize encryption and MAC contexts for pending spec. * Master Secret already is derived. * Caller holds Spec write lock. @@ -2057,27 +1748,14 @@ ssl3_InitPendingContextsPKCS11(sslSocket *ss) pwSpec = ss->ssl3.pwSpec; cipher_def = pwSpec->cipher_def; macLength = pwSpec->mac_size; - calg = cipher_def->calg; - PORT_Assert(alg2Mech[calg].calg == calg); - - pwSpec->client.write_mac_context = NULL; - pwSpec->server.write_mac_context = NULL; - - if (calg == calg_aes_gcm) { - pwSpec->encode = NULL; - pwSpec->decode = NULL; - pwSpec->destroy = NULL; - pwSpec->encodeContext = NULL; - pwSpec->decodeContext = NULL; - pwSpec->aead = ssl3_AESGCM; - return SECSuccess; - } /* ** Now setup the MAC contexts, ** crypto contexts are setup below. */ + pwSpec->client.write_mac_context = NULL; + pwSpec->server.write_mac_context = NULL; mac_mech = pwSpec->mac_def->mmech; mac_param.data = (unsigned char *)&macLength; mac_param.len = sizeof(macLength); @@ -2100,6 +1778,9 @@ ssl3_InitPendingContextsPKCS11(sslSocket *ss) ** Now setup the crypto contexts. */ + calg = cipher_def->calg; + PORT_Assert(alg2Mech[calg].calg == calg); + if (calg == calg_null) { pwSpec->encode = Null_Cipher; pwSpec->decode = Null_Cipher; @@ -2318,20 +1999,54 @@ ssl3_ComputeRecordMAC( { const ssl3MACDef * mac_def; SECStatus rv; +#ifndef NO_PKCS11_BYPASS PRBool isTLS; +#endif unsigned int tempLen; unsigned char temp[MAX_MAC_LENGTH]; + temp[0] = (unsigned char)(seq_num.high >> 24); + temp[1] = (unsigned char)(seq_num.high >> 16); + temp[2] = (unsigned char)(seq_num.high >> 8); + temp[3] = (unsigned char)(seq_num.high >> 0); + temp[4] = (unsigned char)(seq_num.low >> 24); + temp[5] = (unsigned char)(seq_num.low >> 16); + temp[6] = (unsigned char)(seq_num.low >> 8); + temp[7] = (unsigned char)(seq_num.low >> 0); + temp[8] = type; + /* TLS MAC includes the record's version field, SSL's doesn't. ** We decide which MAC defintiion to use based on the version of ** the protocol that was negotiated when the spec became current, ** NOT based on the version value in the record itself. - ** But, we use the record's version value in the computation. + ** But, we use the record'v version value in the computation. */ - isTLS = spec->version > SSL_LIBRARY_VERSION_3_0; - tempLen = ssl3_BuildRecordPseudoHeader(temp, seq_num, type, isTLS, - version, isDTLS, inputLength); - PORT_Assert(tempLen <= sizeof(temp)); + if (spec->version <= SSL_LIBRARY_VERSION_3_0) { + temp[9] = MSB(inputLength); + temp[10] = LSB(inputLength); + tempLen = 11; +#ifndef NO_PKCS11_BYPASS + isTLS = PR_FALSE; +#endif + } else { + /* New TLS hash includes version. */ + if (isDTLS) { + SSL3ProtocolVersion dtls_version; + + dtls_version = dtls_TLSVersionToDTLSVersion(version); + temp[9] = MSB(dtls_version); + temp[10] = LSB(dtls_version); + } else { + temp[9] = MSB(version); + temp[10] = LSB(version); + } + temp[11] = MSB(inputLength); + temp[12] = LSB(inputLength); + tempLen = 13; +#ifndef NO_PKCS11_BYPASS + isTLS = PR_TRUE; +#endif + } PRINT_BUF(95, (NULL, "frag hash1: temp", temp, tempLen)); PRINT_BUF(95, (NULL, "frag hash1: input", input, inputLength)); @@ -2675,112 +2390,86 @@ ssl3_CompressMACEncryptRecord(ssl3CipherSpec * cwSpec, contentLen = outlen; } - if (cipher_def->type == type_aead) { - const int nonceLen = cipher_def->explicit_nonce_size; - const int tagLen = cipher_def->tag_size; - - if (headerLen + nonceLen + contentLen + tagLen > wrBuf->space) { - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - return SECFailure; - } + /* + * Add the MAC + */ + rv = ssl3_ComputeRecordMAC( cwSpec, isServer, isDTLS, + type, cwSpec->version, cwSpec->write_seq_num, pIn, contentLen, + wrBuf->buf + headerLen + ivLen + contentLen, &macLen); + if (rv != SECSuccess) { + ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE); + return SECFailure; + } + p1Len = contentLen; + p2Len = macLen; + fragLen = contentLen + macLen; /* needs to be encrypted */ + PORT_Assert(fragLen <= MAX_FRAGMENT_LENGTH + 1024); - cipherBytes = contentLen; - rv = cwSpec->aead( - isServer ? &cwSpec->server : &cwSpec->client, - PR_FALSE, /* do encrypt */ - wrBuf->buf + headerLen, /* output */ - &cipherBytes, /* out len */ - wrBuf->space - headerLen, /* max out */ - pIn, contentLen, /* input */ - type, cwSpec->version, cwSpec->write_seq_num); - if (rv != SECSuccess) { + /* + * Pad the text (if we're doing a block cipher) + * then Encrypt it + */ + if (cipher_def->type == type_block) { + unsigned char * pBuf; + int padding_length; + int i; + + oddLen = contentLen % cipher_def->block_size; + /* Assume blockSize is a power of two */ + padding_length = cipher_def->block_size - 1 - + ((fragLen) & (cipher_def->block_size - 1)); + fragLen += padding_length + 1; + PORT_Assert((fragLen % cipher_def->block_size) == 0); + + /* Pad according to TLS rules (also acceptable to SSL3). */ + pBuf = &wrBuf->buf[headerLen + ivLen + fragLen - 1]; + for (i = padding_length + 1; i > 0; --i) { + *pBuf-- = padding_length; + } + /* now, if contentLen is not a multiple of block size, fix it */ + p2Len = fragLen - p1Len; + } + if (p1Len < 256) { + oddLen = p1Len; + p1Len = 0; + } else { + p1Len -= oddLen; + } + if (oddLen) { + p2Len += oddLen; + PORT_Assert( (cipher_def->block_size < 2) || \ + (p2Len % cipher_def->block_size) == 0); + memmove(wrBuf->buf + headerLen + ivLen + p1Len, pIn + p1Len, oddLen); + } + if (p1Len > 0) { + int cipherBytesPart1 = -1; + rv = cwSpec->encode( cwSpec->encodeContext, + wrBuf->buf + headerLen + ivLen, /* output */ + &cipherBytesPart1, /* actual outlen */ + p1Len, /* max outlen */ + pIn, p1Len); /* input, and inputlen */ + PORT_Assert(rv == SECSuccess && cipherBytesPart1 == (int) p1Len); + if (rv != SECSuccess || cipherBytesPart1 != (int) p1Len) { PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); return SECFailure; } - } else { - /* - * Add the MAC - */ - rv = ssl3_ComputeRecordMAC( cwSpec, isServer, isDTLS, - type, cwSpec->version, cwSpec->write_seq_num, pIn, contentLen, - wrBuf->buf + headerLen + ivLen + contentLen, &macLen); - if (rv != SECSuccess) { - ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE); + cipherBytes += cipherBytesPart1; + } + if (p2Len > 0) { + int cipherBytesPart2 = -1; + rv = cwSpec->encode( cwSpec->encodeContext, + wrBuf->buf + headerLen + ivLen + p1Len, + &cipherBytesPart2, /* output and actual outLen */ + p2Len, /* max outlen */ + wrBuf->buf + headerLen + ivLen + p1Len, + p2Len); /* input and inputLen*/ + PORT_Assert(rv == SECSuccess && cipherBytesPart2 == (int) p2Len); + if (rv != SECSuccess || cipherBytesPart2 != (int) p2Len) { + PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); return SECFailure; } - p1Len = contentLen; - p2Len = macLen; - fragLen = contentLen + macLen; /* needs to be encrypted */ - PORT_Assert(fragLen <= MAX_FRAGMENT_LENGTH + 1024); - - /* - * Pad the text (if we're doing a block cipher) - * then Encrypt it - */ - if (cipher_def->type == type_block) { - unsigned char * pBuf; - int padding_length; - int i; - - oddLen = contentLen % cipher_def->block_size; - /* Assume blockSize is a power of two */ - padding_length = cipher_def->block_size - 1 - - ((fragLen) & (cipher_def->block_size - 1)); - fragLen += padding_length + 1; - PORT_Assert((fragLen % cipher_def->block_size) == 0); - - /* Pad according to TLS rules (also acceptable to SSL3). */ - pBuf = &wrBuf->buf[headerLen + ivLen + fragLen - 1]; - for (i = padding_length + 1; i > 0; --i) { - *pBuf-- = padding_length; - } - /* now, if contentLen is not a multiple of block size, fix it */ - p2Len = fragLen - p1Len; - } - if (p1Len < 256) { - oddLen = p1Len; - p1Len = 0; - } else { - p1Len -= oddLen; - } - if (oddLen) { - p2Len += oddLen; - PORT_Assert( (cipher_def->block_size < 2) || \ - (p2Len % cipher_def->block_size) == 0); - memmove(wrBuf->buf + headerLen + ivLen + p1Len, pIn + p1Len, - oddLen); - } - if (p1Len > 0) { - int cipherBytesPart1 = -1; - rv = cwSpec->encode( cwSpec->encodeContext, - wrBuf->buf + headerLen + ivLen, /* output */ - &cipherBytesPart1, /* actual outlen */ - p1Len, /* max outlen */ - pIn, p1Len); /* input, and inputlen */ - PORT_Assert(rv == SECSuccess && cipherBytesPart1 == (int) p1Len); - if (rv != SECSuccess || cipherBytesPart1 != (int) p1Len) { - PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); - return SECFailure; - } - cipherBytes += cipherBytesPart1; - } - if (p2Len > 0) { - int cipherBytesPart2 = -1; - rv = cwSpec->encode( cwSpec->encodeContext, - wrBuf->buf + headerLen + ivLen + p1Len, - &cipherBytesPart2, /* output and actual outLen */ - p2Len, /* max outlen */ - wrBuf->buf + headerLen + ivLen + p1Len, - p2Len); /* input and inputLen*/ - PORT_Assert(rv == SECSuccess && cipherBytesPart2 == (int) p2Len); - if (rv != SECSuccess || cipherBytesPart2 != (int) p2Len) { - PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); - return SECFailure; - } - cipherBytes += cipherBytesPart2; - } - } - + cipherBytes += cipherBytesPart2; + } PORT_Assert(cipherBytes <= MAX_FRAGMENT_LENGTH + 1024); wrBuf->len = cipherBytes + headerLen; @@ -3323,6 +3012,9 @@ SSL3_SendAlert(sslSocket *ss, SSL3AlertLevel level, SSL3AlertDescription desc) static SECStatus ssl3_IllegalParameter(sslSocket *ss) { + PRBool isTLS; + + isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0); (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter); PORT_SetError(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT : SSL_ERROR_BAD_SERVER ); @@ -3846,6 +3538,7 @@ ssl3_DeriveConnectionKeysPKCS11(sslSocket *ss) } key_material_params.bIsExport = (CK_BBOOL)(kea_def->is_limited); + /* was: (CK_BBOOL)(cipher_def->keygen_mode != kg_strong); */ key_material_params.RandomInfo.pClientRandom = cr; key_material_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH; @@ -3981,6 +3674,20 @@ ssl3_InitHandshakeHashes(sslSocket *ss) ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); return SECFailure; } + + /* A backup SHA-1 hash for a potential client auth signature. */ + if (!ss->sec.isServer) { + ss->ssl3.hs.md5 = PK11_CreateDigestContext(SEC_OID_SHA1); + if (ss->ssl3.hs.md5 == NULL) { + ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); + return SECFailure; + } + + if (PK11_DigestBegin(ss->ssl3.hs.md5) != SECSuccess) { + ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); + return SECFailure; + } + } } else { /* Both ss->ssl3.hs.md5 and ss->ssl3.hs.sha should be NULL or * created successfully. */ @@ -4091,6 +3798,13 @@ ssl3_UpdateHandshakeHashes(sslSocket *ss, const unsigned char *b, ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); return rv; } + if (ss->ssl3.hs.md5) { + rv = PK11_DigestOp(ss->ssl3.hs.md5, b, l); + if (rv != SECSuccess) { + ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); + return rv; + } + } } else { rv = PK11_DigestOp(ss->ssl3.hs.md5, b, l); if (rv != SECSuccess) { @@ -4839,6 +4553,30 @@ tls12_loser: return rv; } +static SECStatus +ssl3_ComputeBackupHandshakeHashes(sslSocket * ss, + SSL3Hashes * hashes) /* output goes here. */ +{ + SECStatus rv = SECSuccess; + + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); + PORT_Assert( ss->ssl3.hs.hashType == handshake_hash_single ); + + rv = PK11_DigestFinal(ss->ssl3.hs.md5, hashes->u.raw, &hashes->len, + sizeof(hashes->u.raw)); + if (rv != SECSuccess) { + ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); + rv = SECFailure; + goto loser; + } + hashes->hashAlg = SEC_OID_SHA1; + +loser: + PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE); + ss->ssl3.hs.md5 = NULL; + return rv; +} + /* * SSL 2 based implementations pass in the initial outbound buffer * so that the handshake hash can contain the included information. @@ -5137,10 +4875,6 @@ ssl3_SendClientHello(sslSocket *ss, PRBool resending) ssl3_DisableNonDTLSSuites(ss); } - if (!ssl3_HasGCMSupport()) { - ssl3_DisableGCMSuites(ss); - } - /* how many suites are permitted by policy and user preference? */ num_suites = count_cipher_suites(ss, ss->ssl3.policy, PR_TRUE); if (!num_suites) @@ -6092,7 +5826,17 @@ ssl3_SendCertificateVerify(sslSocket *ss) SSL_GETPID(), ss->fd)); ssl_GetSpecReadLock(ss); - rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.pwSpec, &hashes, 0); + /* In TLS 1.2, ssl3_ComputeHandshakeHashes always uses the handshake hash + * function (SHA-256). If the server or the client does not support SHA-256 + * as a signature hash, we can either maintain a backup SHA-1 handshake + * hash or buffer all handshake messages. + */ + if (ss->ssl3.hs.hashType == handshake_hash_single && ss->ssl3.hs.md5) { + rv = ssl3_ComputeBackupHandshakeHashes(ss, &hashes); + PORT_Assert(ss->ssl3.hs.md5 == NULL); + } else { + rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.pwSpec, &hashes, 0); + } ssl_ReleaseSpecReadLock(ss); if (rv != SECSuccess) { goto done; /* err code was set by ssl3_ComputeHandshakeHashes */ @@ -6146,11 +5890,6 @@ ssl3_SendCertificateVerify(sslSocket *ss) if (rv != SECSuccess) { goto done; } - /* We always sign using the handshake hash function. It's possible that - * a server could support SHA-256 as the handshake hash but not as a - * signature hash. In that case we wouldn't be able to do client - * certificates with it. The alternative is to buffer all handshake - * messages. */ sigAndHash.hashAlg = hashes.hashAlg; rv = ssl3_AppendSignatureAndHashAlgorithm(ss, &sigAndHash); @@ -6850,6 +6589,70 @@ no_memory: /* no-memory error has already been set. */ } +/* + * Returns true if the client authentication key is an RSA or DSA key that + * may be able to sign only SHA-1 hashes. + */ +static PRBool +ssl3_ClientKeyPrefersSHA1(sslSocket *ss) +{ + SECKEYPublicKey *pubk; + PRBool prefer_sha1 = PR_FALSE; + +#if defined(NSS_PLATFORM_CLIENT_AUTH) && defined(_WIN32) + /* If the key is in CAPI, assume conservatively that the CAPI service + * provider may be unable to sign SHA-256 hashes. + */ + if (ss->ssl3.platformClientKey->dwKeySpec != CERT_NCRYPT_KEY_SPEC) { + /* CAPI only supports RSA and DSA signatures, so we don't need to + * check the key type. */ + return PR_TRUE; + } +#endif /* NSS_PLATFORM_CLIENT_AUTH && _WIN32 */ + + /* If the key is a 1024-bit RSA or DSA key, assume conservatively that + * it may be unable to sign SHA-256 hashes. This is the case for older + * Estonian ID cards that have 1024-bit RSA keys. In FIPS 186-2 and + * older, DSA key size is at most 1024 bits and the hash function must + * be SHA-1. + */ + pubk = CERT_ExtractPublicKey(ss->ssl3.clientCertificate); + if (pubk == NULL) { + return PR_FALSE; + } + if (pubk->keyType == rsaKey || pubk->keyType == dsaKey) { + prefer_sha1 = SECKEY_PublicKeyStrength(pubk) <= 128; + } + SECKEY_DestroyPublicKey(pubk); + return prefer_sha1; +} + +/* Destroys the backup handshake hash context if we don't need it. */ +static void +ssl3_DestroyBackupHandshakeHashIfNotNeeded(sslSocket *ss, + const SECItem *algorithms) +{ + PRBool need_backup_hash = PR_FALSE; + unsigned int i; + + PORT_Assert(ss->ssl3.hs.md5); + if (ssl3_ClientKeyPrefersSHA1(ss)) { + /* Use SHA-1 if the server supports it. */ + for (i = 0; i < algorithms->len; i += 2) { + if (algorithms->data[i] == tls_hash_sha1 && + (algorithms->data[i+1] == tls_sig_rsa || + algorithms->data[i+1] == tls_sig_dsa)) { + need_backup_hash = PR_TRUE; + break; + } + } + } + if (!need_backup_hash) { + PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE); + ss->ssl3.hs.md5 = NULL; + } +} + typedef struct dnameNode { struct dnameNode *next; SECItem name; @@ -7042,6 +6845,9 @@ ssl3_HandleCertificateRequest(sslSocket *ss, SSL3Opaque *b, PRUint32 length) } goto send_no_certificate; } + if (isTLS12) { + ssl3_DestroyBackupHandshakeHashIfNotNeeded(ss, &algorithms); + } break; /* not an error */ } #endif /* NSS_PLATFORM_CLIENT_AUTH */ @@ -7077,6 +6883,9 @@ ssl3_HandleCertificateRequest(sslSocket *ss, SSL3Opaque *b, PRUint32 length) } goto send_no_certificate; } + if (isTLS12) { + ssl3_DestroyBackupHandshakeHashIfNotNeeded(ss, &algorithms); + } break; /* not an error */ case SECFailure: @@ -7275,6 +7084,13 @@ ssl3_SendClientSecondRound(sslSocket *ss) (ss->ssl3.platformClientKey || ss->ssl3.clientPrivateKey != NULL); + if (!sendClientCert && + ss->ssl3.hs.hashType == handshake_hash_single && ss->ssl3.hs.md5) { + /* Don't need the backup handshake hash. */ + PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE); + ss->ssl3.hs.md5 = NULL; + } + /* We must wait for the server's certificate to be authenticated before * sending the client certificate in order to disclosing the client * certificate to an attacker that does not have a valid cert for the @@ -7846,10 +7662,6 @@ ssl3_HandleClientHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length) ssl3_DisableNonDTLSSuites(ss); } - if (!ssl3_HasGCMSupport()) { - ssl3_DisableGCMSuites(ss); - } - #ifdef PARANOID /* Look for a matching cipher suite. */ j = ssl3_config_match_init(ss); @@ -10261,6 +10073,7 @@ ssl3_SendNextProto(sslSocket *ss) static void ssl3_RecordKeyLog(sslSocket *ss) { + sslSessionID *sid; SECStatus rv; SECItem *keyData; char buf[14 /* "CLIENT_RANDOM " */ + @@ -10272,6 +10085,8 @@ ssl3_RecordKeyLog(sslSocket *ss) PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + sid = ss->sec.ci.sid; + if (!ssl_keylog_iob) return; @@ -11483,14 +11298,12 @@ ssl3_HandleRecord(sslSocket *ss, SSL3Ciphertext *cText, sslBuffer *databuf) /* With >= TLS 1.1, CBC records have an explicit IV. */ minLength += cipher_def->iv_size; } - } else if (cipher_def->type == type_aead) { - minLength = cipher_def->explicit_nonce_size + cipher_def->tag_size; } /* We can perform this test in variable time because the record's total * length and the ciphersuite are both public knowledge. */ if (cText->buf->len < minLength) { - goto decrypt_loser; + goto decrypt_loser; } if (cipher_def->type == type_block && @@ -11558,95 +11371,78 @@ ssl3_HandleRecord(sslSocket *ss, SSL3Ciphertext *cText, sslBuffer *databuf) return SECFailure; } - rType = cText->type; - if (cipher_def->type == type_aead) { - rv = crSpec->aead( - ss->sec.isServer ? &crSpec->client : &crSpec->server, - PR_TRUE, /* do decrypt */ - plaintext->buf, /* out */ - (int*) &plaintext->len, /* outlen */ - plaintext->space, /* maxout */ - cText->buf->buf, /* in */ - cText->buf->len, /* inlen */ - rType, /* record type */ - cText->version, - IS_DTLS(ss) ? cText->seq_num : crSpec->read_seq_num); - if (rv != SECSuccess) { - good = 0; - } - } else { - if (cipher_def->type == type_block && - ((cText->buf->len - ivLen) % cipher_def->block_size) != 0) { - goto decrypt_loser; - } + if (cipher_def->type == type_block && + ((cText->buf->len - ivLen) % cipher_def->block_size) != 0) { + goto decrypt_loser; + } - /* decrypt from cText buf to plaintext. */ - rv = crSpec->decode( - crSpec->decodeContext, plaintext->buf, (int *)&plaintext->len, - plaintext->space, cText->buf->buf + ivLen, cText->buf->len - ivLen); - if (rv != SECSuccess) { - goto decrypt_loser; - } + /* decrypt from cText buf to plaintext. */ + rv = crSpec->decode( + crSpec->decodeContext, plaintext->buf, (int *)&plaintext->len, + plaintext->space, cText->buf->buf + ivLen, cText->buf->len - ivLen); + if (rv != SECSuccess) { + goto decrypt_loser; + } - PRINT_BUF(80, (ss, "cleartext:", plaintext->buf, plaintext->len)); + PRINT_BUF(80, (ss, "cleartext:", plaintext->buf, plaintext->len)); - originalLen = plaintext->len; + originalLen = plaintext->len; - /* If it's a block cipher, check and strip the padding. */ - if (cipher_def->type == type_block) { - const unsigned int blockSize = cipher_def->block_size; - const unsigned int macSize = crSpec->mac_size; + /* If it's a block cipher, check and strip the padding. */ + if (cipher_def->type == type_block) { + const unsigned int blockSize = cipher_def->block_size; + const unsigned int macSize = crSpec->mac_size; - if (crSpec->version <= SSL_LIBRARY_VERSION_3_0) { - good &= SECStatusToMask(ssl_RemoveSSLv3CBCPadding( - plaintext, blockSize, macSize)); - } else { - good &= SECStatusToMask(ssl_RemoveTLSCBCPadding( - plaintext, macSize)); - } + if (crSpec->version <= SSL_LIBRARY_VERSION_3_0) { + good &= SECStatusToMask(ssl_RemoveSSLv3CBCPadding( + plaintext, blockSize, macSize)); + } else { + good &= SECStatusToMask(ssl_RemoveTLSCBCPadding( + plaintext, macSize)); } + } - /* compute the MAC */ - if (cipher_def->type == type_block) { - rv = ssl3_ComputeRecordMACConstantTime( - crSpec, (PRBool)(!ss->sec.isServer), - IS_DTLS(ss), rType, cText->version, - IS_DTLS(ss) ? cText->seq_num : crSpec->read_seq_num, - plaintext->buf, plaintext->len, originalLen, - hash, &hashBytes); - - ssl_CBCExtractMAC(plaintext, originalLen, givenHashBuf, - crSpec->mac_size); - givenHash = givenHashBuf; - - /* plaintext->len will always have enough space to remove the MAC - * because in ssl_Remove{SSLv3|TLS}CBCPadding we only adjust - * plaintext->len if the result has enough space for the MAC and we - * tested the unadjusted size against minLength, above. */ - plaintext->len -= crSpec->mac_size; - } else { - /* This is safe because we checked the minLength above. */ - plaintext->len -= crSpec->mac_size; + /* compute the MAC */ + rType = cText->type; + if (cipher_def->type == type_block) { + rv = ssl3_ComputeRecordMACConstantTime( + crSpec, (PRBool)(!ss->sec.isServer), + IS_DTLS(ss), rType, cText->version, + IS_DTLS(ss) ? cText->seq_num : crSpec->read_seq_num, + plaintext->buf, plaintext->len, originalLen, + hash, &hashBytes); + + ssl_CBCExtractMAC(plaintext, originalLen, givenHashBuf, + crSpec->mac_size); + givenHash = givenHashBuf; + + /* plaintext->len will always have enough space to remove the MAC + * because in ssl_Remove{SSLv3|TLS}CBCPadding we only adjust + * plaintext->len if the result has enough space for the MAC and we + * tested the unadjusted size against minLength, above. */ + plaintext->len -= crSpec->mac_size; + } else { + /* This is safe because we checked the minLength above. */ + plaintext->len -= crSpec->mac_size; - rv = ssl3_ComputeRecordMAC( - crSpec, (PRBool)(!ss->sec.isServer), - IS_DTLS(ss), rType, cText->version, - IS_DTLS(ss) ? cText->seq_num : crSpec->read_seq_num, - plaintext->buf, plaintext->len, - hash, &hashBytes); + rv = ssl3_ComputeRecordMAC( + crSpec, (PRBool)(!ss->sec.isServer), + IS_DTLS(ss), rType, cText->version, + IS_DTLS(ss) ? cText->seq_num : crSpec->read_seq_num, + plaintext->buf, plaintext->len, + hash, &hashBytes); - /* We can read the MAC directly from the record because its location - * is public when a stream cipher is used. */ - givenHash = plaintext->buf + plaintext->len; - } + /* We can read the MAC directly from the record because its location is + * public when a stream cipher is used. */ + givenHash = plaintext->buf + plaintext->len; + } - good &= SECStatusToMask(rv); + good &= SECStatusToMask(rv); - if (hashBytes != (unsigned)crSpec->mac_size || - NSS_SecureMemcmp(givenHash, hash, crSpec->mac_size) != 0) { - /* We're allowed to leak whether or not the MAC check was correct */ - good = 0; - } + if (hashBytes != (unsigned)crSpec->mac_size || + NSS_SecureMemcmp(givenHash, hash, crSpec->mac_size) != 0) { + /* We're allowed to leak whether or not the MAC check was correct */ + good = 0; } if (good == 0) { diff --git a/chromium/net/third_party/nss/ssl/ssl3ecc.c b/chromium/net/third_party/nss/ssl/ssl3ecc.c index a3638e75f1c..74995f18321 100644 --- a/chromium/net/third_party/nss/ssl/ssl3ecc.c +++ b/chromium/net/third_party/nss/ssl/ssl3ecc.c @@ -911,7 +911,6 @@ static const ssl3CipherSuite ecdhe_ecdsa_suites[] = { TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, - TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_NULL_SHA, TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, @@ -922,7 +921,6 @@ static const ssl3CipherSuite ecdhe_rsa_suites[] = { TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, - TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_NULL_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA, @@ -934,14 +932,12 @@ static const ssl3CipherSuite ecSuites[] = { TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, - TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_NULL_SHA, TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, - TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_NULL_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA, diff --git a/chromium/net/third_party/nss/ssl/sslenum.c b/chromium/net/third_party/nss/ssl/sslenum.c index 597ec072399..b460f2631dc 100644 --- a/chromium/net/third_party/nss/ssl/sslenum.c +++ b/chromium/net/third_party/nss/ssl/sslenum.c @@ -29,14 +29,6 @@ * Finally, update the ssl_V3_SUITES_IMPLEMENTED macro in sslimpl.h. */ const PRUint16 SSL_ImplementedCiphers[] = { - /* AES-GCM */ -#ifdef NSS_ENABLE_ECC - TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, - TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, -#endif /* NSS_ENABLE_ECC */ - TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, - TLS_RSA_WITH_AES_128_GCM_SHA256, - /* 256-bit */ #ifdef NSS_ENABLE_ECC TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, diff --git a/chromium/net/third_party/nss/ssl/sslimpl.h b/chromium/net/third_party/nss/ssl/sslimpl.h index da302abe57d..40d915616b3 100644 --- a/chromium/net/third_party/nss/ssl/sslimpl.h +++ b/chromium/net/third_party/nss/ssl/sslimpl.h @@ -64,7 +64,6 @@ typedef SSLSignType SSL3SignType; #define calg_aes ssl_calg_aes #define calg_camellia ssl_calg_camellia #define calg_seed ssl_calg_seed -#define calg_aes_gcm ssl_calg_aes_gcm #define mac_null ssl_mac_null #define mac_md5 ssl_mac_md5 @@ -291,9 +290,9 @@ typedef struct { } ssl3CipherSuiteCfg; #ifdef NSS_ENABLE_ECC -#define ssl_V3_SUITES_IMPLEMENTED 61 +#define ssl_V3_SUITES_IMPLEMENTED 57 #else -#define ssl_V3_SUITES_IMPLEMENTED 37 +#define ssl_V3_SUITES_IMPLEMENTED 35 #endif /* NSS_ENABLE_ECC */ #define MAX_DTLS_SRTP_CIPHER_SUITES 4 @@ -441,6 +440,20 @@ struct sslGatherStr { #define GS_DATA 3 #define GS_PAD 4 +typedef SECStatus (*SSLCipher)(void * context, + unsigned char * out, + int * outlen, + int maxout, + const unsigned char *in, + int inlen); +typedef SECStatus (*SSLCompressor)(void * context, + unsigned char * out, + int * outlen, + int maxout, + const unsigned char *in, + int inlen); +typedef SECStatus (*SSLDestroy)(void *context, PRBool freeit); + #if defined(NSS_PLATFORM_CLIENT_AUTH) && defined(XP_WIN32) typedef PCERT_KEY_CONTEXT PlatformKey; #elif defined(NSS_PLATFORM_CLIENT_AUTH) && defined(XP_MACOSX) @@ -472,12 +485,11 @@ typedef enum { cipher_camellia_128, cipher_camellia_256, cipher_seed, - cipher_aes_128_gcm, cipher_missing /* reserved for no such supported cipher */ /* This enum must match ssl3_cipherName[] in ssl3con.c. */ } SSL3BulkCipher; -typedef enum { type_stream, type_block, type_aead } CipherType; +typedef enum { type_stream, type_block } CipherType; #define MAX_IV_LENGTH 24 @@ -519,31 +531,6 @@ typedef struct { PRUint64 cipher_context[MAX_CIPHER_CONTEXT_LLONGS]; } ssl3KeyMaterial; -typedef SECStatus (*SSLCipher)(void * context, - unsigned char * out, - int * outlen, - int maxout, - const unsigned char *in, - int inlen); -typedef SECStatus (*SSLAEADCipher)( - ssl3KeyMaterial * keys, - PRBool doDecrypt, - unsigned char * out, - int * outlen, - int maxout, - const unsigned char *in, - int inlen, - SSL3ContentType type, - SSL3ProtocolVersion version, - SSL3SequenceNumber seqnum); -typedef SECStatus (*SSLCompressor)(void * context, - unsigned char * out, - int * outlen, - int maxout, - const unsigned char *in, - int inlen); -typedef SECStatus (*SSLDestroy)(void *context, PRBool freeit); - /* The DTLS anti-replay window. Defined here because we need it in * the cipher spec. Note that this is a ring buffer but left and * right represent the true window, with modular arithmetic used to @@ -570,7 +557,6 @@ typedef struct { int mac_size; SSLCipher encode; SSLCipher decode; - SSLAEADCipher aead; SSLDestroy destroy; void * encodeContext; void * decodeContext; @@ -720,6 +706,8 @@ typedef struct { PRBool tls_keygen; } ssl3KEADef; +typedef enum { kg_null, kg_strong, kg_export } SSL3KeyGenMode; + /* ** There are tables of these, all const. */ @@ -731,8 +719,7 @@ struct ssl3BulkCipherDefStr { CipherType type; int iv_size; int block_size; - int tag_size; /* authentication tag size for AEAD ciphers. */ - int explicit_nonce_size; /* for AEAD ciphers. */ + SSL3KeyGenMode keygen_mode; }; /* @@ -838,6 +825,9 @@ typedef struct SSL3HandshakeStateStr { * SSL 3.0 - TLS 1.1 use both |md5| and |sha|. |md5| is used for MD5 and * |sha| for SHA-1. * TLS 1.2 and later use only |sha|, for SHA-256. */ + /* NOTE: On the client side, TLS 1.2 and later use |md5| as a backup + * handshake hash for generating client auth signatures. Confusingly, the + * backup hash function is SHA-1. */ PK11Context * md5; PK11Context * sha; diff --git a/chromium/net/third_party/nss/ssl/sslinfo.c b/chromium/net/third_party/nss/ssl/sslinfo.c index 215731e4b02..d29fb0d8f72 100644 --- a/chromium/net/third_party/nss/ssl/sslinfo.c +++ b/chromium/net/third_party/nss/ssl/sslinfo.c @@ -109,7 +109,7 @@ SSL_GetChannelInfo(PRFileDesc *fd, SSLChannelInfo *info, PRUintn len) #define K_ECDHE "ECDHE", kt_ecdh #define C_SEED "SEED", calg_seed -#define C_CAMELLIA "CAMELLIA", calg_camellia +#define C_CAMELLIA "CAMELLIA", calg_camellia #define C_AES "AES", calg_aes #define C_RC4 "RC4", calg_rc4 #define C_RC2 "RC2", calg_rc2 @@ -117,7 +117,6 @@ SSL_GetChannelInfo(PRFileDesc *fd, SSLChannelInfo *info, PRUintn len) #define C_3DES "3DES", calg_3des #define C_NULL "NULL", calg_null #define C_SJ "SKIPJACK", calg_sj -#define C_AESGCM "AES-GCM", calg_aes_gcm #define B_256 256, 256, 256 #define B_128 128, 128, 128 @@ -131,12 +130,9 @@ SSL_GetChannelInfo(PRFileDesc *fd, SSLChannelInfo *info, PRUintn len) #define M_SHA256 "SHA256", ssl_hmac_sha256, 256 #define M_SHA "SHA1", ssl_mac_sha, 160 #define M_MD5 "MD5", ssl_mac_md5, 128 -#define M_NULL "NULL", ssl_mac_null, 0 static const SSLCipherSuiteInfo suiteInfo[] = { /* <------ Cipher suite --------------------> <auth> <KEA> <bulk cipher> <MAC> <FIPS> */ -{0,CS(TLS_RSA_WITH_AES_128_GCM_SHA256), S_RSA, K_RSA, C_AESGCM, B_128, M_NULL, 1, 0, 0, }, - {0,CS(TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA), S_RSA, K_DHE, C_CAMELLIA, B_256, M_SHA, 0, 0, 0, }, {0,CS(TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA), S_DSA, K_DHE, C_CAMELLIA, B_256, M_SHA, 0, 0, 0, }, {0,CS(TLS_DHE_RSA_WITH_AES_256_CBC_SHA256), S_RSA, K_DHE, C_AES, B_256, M_SHA256, 1, 0, 0, }, @@ -150,7 +146,6 @@ static const SSLCipherSuiteInfo suiteInfo[] = { {0,CS(TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA), S_DSA, K_DHE, C_CAMELLIA, B_128, M_SHA, 0, 0, 0, }, {0,CS(TLS_DHE_DSS_WITH_RC4_128_SHA), S_DSA, K_DHE, C_RC4, B_128, M_SHA, 0, 0, 0, }, {0,CS(TLS_DHE_RSA_WITH_AES_128_CBC_SHA256), S_RSA, K_DHE, C_AES, B_128, M_SHA256, 1, 0, 0, }, -{0,CS(TLS_DHE_RSA_WITH_AES_128_GCM_SHA256), S_RSA, K_DHE, C_AESGCM, B_128, M_NULL, 1, 0, 0, }, {0,CS(TLS_DHE_RSA_WITH_AES_128_CBC_SHA), S_RSA, K_DHE, C_AES, B_128, M_SHA, 1, 0, 0, }, {0,CS(TLS_DHE_DSS_WITH_AES_128_CBC_SHA), S_DSA, K_DHE, C_AES, B_128, M_SHA, 1, 0, 0, }, {0,CS(TLS_RSA_WITH_SEED_CBC_SHA), S_RSA, K_RSA, C_SEED,B_128, M_SHA, 1, 0, 0, }, @@ -180,9 +175,6 @@ static const SSLCipherSuiteInfo suiteInfo[] = { #ifdef NSS_ENABLE_ECC /* ECC cipher suites */ -{0,CS(TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256), S_RSA, K_ECDHE, C_AESGCM, B_128, M_NULL, 1, 0, 0, }, -{0,CS(TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256), S_ECDSA, K_ECDHE, C_AESGCM, B_128, M_NULL, 1, 0, 0, }, - {0,CS(TLS_ECDH_ECDSA_WITH_NULL_SHA), S_ECDSA, K_ECDH, C_NULL, B_0, M_SHA, 0, 0, 0, }, {0,CS(TLS_ECDH_ECDSA_WITH_RC4_128_SHA), S_ECDSA, K_ECDH, C_RC4, B_128, M_SHA, 0, 0, 0, }, {0,CS(TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA), S_ECDSA, K_ECDH, C_3DES, B_3DES, M_SHA, 1, 0, 0, }, diff --git a/chromium/net/third_party/nss/ssl/sslproto.h b/chromium/net/third_party/nss/ssl/sslproto.h index 53bba011bb9..b037887acf9 100644 --- a/chromium/net/third_party/nss/ssl/sslproto.h +++ b/chromium/net/third_party/nss/ssl/sslproto.h @@ -162,10 +162,6 @@ #define TLS_RSA_WITH_SEED_CBC_SHA 0x0096 -#define TLS_RSA_WITH_AES_128_GCM_SHA256 0x009C -#define TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 0x009E -#define TLS_DHE_DSS_WITH_AES_128_GCM_SHA256 0x00A2 - /* TLS "Signaling Cipher Suite Value" (SCSV). May be requested by client. * Must NEVER be chosen by server. SSL 3.0 server acknowledges by sending * back an empty Renegotiation Info (RI) server hello extension. @@ -208,11 +204,6 @@ #define TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 0xC023 #define TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 0xC027 -#define TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 0xC02B -#define TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 0xC02D -#define TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 0xC02F -#define TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 0xC031 - /* Netscape "experimental" cipher suites. */ #define SSL_RSA_OLDFIPS_WITH_3DES_EDE_CBC_SHA 0xffe0 #define SSL_RSA_OLDFIPS_WITH_DES_CBC_SHA 0xffe1 diff --git a/chromium/net/third_party/nss/ssl/sslsock.c b/chromium/net/third_party/nss/ssl/sslsock.c index c17c7a3ad03..db0da5f13d1 100644 --- a/chromium/net/third_party/nss/ssl/sslsock.c +++ b/chromium/net/third_party/nss/ssl/sslsock.c @@ -67,10 +67,8 @@ static cipherPolicy ssl_ciphers[] = { /* Export France */ { TLS_DHE_DSS_WITH_AES_128_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED }, { TLS_DHE_RSA_WITH_AES_128_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED }, { TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED }, - { TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED }, { TLS_RSA_WITH_AES_128_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED }, { TLS_RSA_WITH_AES_128_CBC_SHA256, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED }, - { TLS_RSA_WITH_AES_128_GCM_SHA256, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED }, { TLS_DHE_DSS_WITH_AES_256_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED }, { TLS_DHE_RSA_WITH_AES_256_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED }, { TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED }, @@ -96,7 +94,6 @@ static cipherPolicy ssl_ciphers[] = { /* Export France */ { TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED }, { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED }, { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,SSL_NOT_ALLOWED, SSL_NOT_ALLOWED }, - { TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,SSL_NOT_ALLOWED, SSL_NOT_ALLOWED }, { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED }, { TLS_ECDH_RSA_WITH_NULL_SHA, SSL_ALLOWED, SSL_ALLOWED }, { TLS_ECDH_RSA_WITH_RC4_128_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED }, @@ -108,7 +105,6 @@ static cipherPolicy ssl_ciphers[] = { /* Export France */ { TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED }, { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED }, { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED }, - { TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED }, { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED }, #endif /* NSS_ENABLE_ECC */ { 0, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED } diff --git a/chromium/net/third_party/nss/ssl/sslt.h b/chromium/net/third_party/nss/ssl/sslt.h index f4be1743303..41d01130d9e 100644 --- a/chromium/net/third_party/nss/ssl/sslt.h +++ b/chromium/net/third_party/nss/ssl/sslt.h @@ -91,10 +91,9 @@ typedef enum { ssl_calg_3des = 4, ssl_calg_idea = 5, ssl_calg_fortezza = 6, /* deprecated, now unused */ - ssl_calg_aes = 7, + ssl_calg_aes = 7, /* coming soon */ ssl_calg_camellia = 8, - ssl_calg_seed = 9, - ssl_calg_aes_gcm = 10 + ssl_calg_seed = 9 } SSLCipherAlgorithm; typedef enum { |