diff options
Diffstat (limited to 'chrome/browser/sync/util')
37 files changed, 0 insertions, 4290 deletions
diff --git a/chrome/browser/sync/util/DEPS b/chrome/browser/sync/util/DEPS deleted file mode 100644 index c45c30e..0000000 --- a/chrome/browser/sync/util/DEPS +++ /dev/null @@ -1,12 +0,0 @@ -include_rules = [ - "-chrome", - - "+chrome/browser/sync/protocol", - "+chrome/browser/sync/sessions", - "+chrome/browser/sync/syncable", - "+chrome/browser/sync/test", - "+chrome/browser/sync/util", - - # this file is weird. - "+chrome/browser/sync/engine/syncproto.h", -] diff --git a/chrome/browser/sync/util/cryptographer.cc b/chrome/browser/sync/util/cryptographer.cc deleted file mode 100644 index 30d0e91..0000000 --- a/chrome/browser/sync/util/cryptographer.cc +++ /dev/null @@ -1,446 +0,0 @@ -// Copyright (c) 2012 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 <algorithm> - -#include "base/base64.h" -#include "base/logging.h" -#include "chrome/browser/sync/util/cryptographer.h" -#include "chrome/browser/sync/util/encryptor.h" - -namespace browser_sync { - -const char kNigoriTag[] = "google_chrome_nigori"; - -// We name a particular Nigori instance (ie. a triplet consisting of a hostname, -// a username, and a password) by calling Permute on this string. Since the -// output of Permute is always the same for a given triplet, clients will always -// assign the same name to a particular triplet. -const char kNigoriKeyName[] = "nigori-key"; - -Cryptographer::Observer::~Observer() {} - -Cryptographer::Cryptographer(Encryptor* encryptor) - : encryptor_(encryptor), - default_nigori_(NULL), - encrypted_types_(SensitiveTypes()), - encrypt_everything_(false) { - DCHECK(encryptor); -} - -Cryptographer::~Cryptographer() {} - -void Cryptographer::AddObserver(Observer* observer) { - observers_.AddObserver(observer); -} - -void Cryptographer::RemoveObserver(Observer* observer) { - observers_.RemoveObserver(observer); -} - -void Cryptographer::Bootstrap(const std::string& restored_bootstrap_token) { - if (is_initialized()) { - NOTREACHED(); - return; - } - - scoped_ptr<Nigori> nigori(UnpackBootstrapToken(restored_bootstrap_token)); - if (nigori.get()) - AddKeyImpl(nigori.release()); -} - -bool Cryptographer::CanDecrypt(const sync_pb::EncryptedData& data) const { - return nigoris_.end() != nigoris_.find(data.key_name()); -} - -bool Cryptographer::CanDecryptUsingDefaultKey( - const sync_pb::EncryptedData& data) const { - return default_nigori_ && (data.key_name() == default_nigori_->first); -} - -bool Cryptographer::Encrypt( - const ::google::protobuf::MessageLite& message, - sync_pb::EncryptedData* encrypted) const { - DCHECK(encrypted); - if (!default_nigori_) { - LOG(ERROR) << "Cryptographer not ready, failed to encrypt."; - return false; - } - - std::string serialized; - if (!message.SerializeToString(&serialized)) { - LOG(ERROR) << "Message is invalid/missing a required field."; - return false; - } - - if (CanDecryptUsingDefaultKey(*encrypted)) { - const std::string& original_serialized = DecryptToString(*encrypted); - if (original_serialized == serialized) { - DVLOG(2) << "Re-encryption unnecessary, encrypted data already matches."; - return true; - } - } - - encrypted->set_key_name(default_nigori_->first); - if (!default_nigori_->second->Encrypt(serialized, - encrypted->mutable_blob())) { - LOG(ERROR) << "Failed to encrypt data."; - return false; - } - return true; -} - -bool Cryptographer::Decrypt(const sync_pb::EncryptedData& encrypted, - ::google::protobuf::MessageLite* message) const { - DCHECK(message); - std::string plaintext = DecryptToString(encrypted); - return message->ParseFromString(plaintext); -} - -std::string Cryptographer::DecryptToString( - const sync_pb::EncryptedData& encrypted) const { - NigoriMap::const_iterator it = nigoris_.find(encrypted.key_name()); - if (nigoris_.end() == it) { - NOTREACHED() << "Cannot decrypt message"; - return std::string(""); // Caller should have called CanDecrypt(encrypt). - } - - std::string plaintext; - if (!it->second->Decrypt(encrypted.blob(), &plaintext)) { - return std::string(""); - } - - return plaintext; -} - -bool Cryptographer::GetKeys(sync_pb::EncryptedData* encrypted) const { - DCHECK(encrypted); - DCHECK(!nigoris_.empty()); - - // Create a bag of all the Nigori parameters we know about. - sync_pb::NigoriKeyBag bag; - for (NigoriMap::const_iterator it = nigoris_.begin(); it != nigoris_.end(); - ++it) { - const Nigori& nigori = *it->second; - sync_pb::NigoriKey* key = bag.add_key(); - key->set_name(it->first); - nigori.ExportKeys(key->mutable_user_key(), - key->mutable_encryption_key(), - key->mutable_mac_key()); - } - - // Encrypt the bag with the default Nigori. - return Encrypt(bag, encrypted); -} - -bool Cryptographer::AddKey(const KeyParams& params) { - // Create the new Nigori and make it the default encryptor. - scoped_ptr<Nigori> nigori(new Nigori); - if (!nigori->InitByDerivation(params.hostname, - params.username, - params.password)) { - NOTREACHED(); // Invalid username or password. - return false; - } - return AddKeyImpl(nigori.release()); -} - -bool Cryptographer::AddKeyFromBootstrapToken( - const std::string restored_bootstrap_token) { - // Create the new Nigori and make it the default encryptor. - scoped_ptr<Nigori> nigori(UnpackBootstrapToken(restored_bootstrap_token)); - if (!nigori.get()) - return false; - return AddKeyImpl(nigori.release()); -} - -bool Cryptographer::AddKeyImpl(Nigori* initialized_nigori) { - scoped_ptr<Nigori> nigori(initialized_nigori); - std::string name; - if (!nigori->Permute(Nigori::Password, kNigoriKeyName, &name)) { - NOTREACHED(); - return false; - } - nigoris_[name] = make_linked_ptr(nigori.release()); - default_nigori_ = &*nigoris_.find(name); - return true; -} - -bool Cryptographer::SetKeys(const sync_pb::EncryptedData& encrypted) { - DCHECK(CanDecrypt(encrypted)); - - sync_pb::NigoriKeyBag bag; - if (!Decrypt(encrypted, &bag)) { - return false; - } - InstallKeys(encrypted.key_name(), bag); - return true; -} - -void Cryptographer::SetPendingKeys(const sync_pb::EncryptedData& encrypted) { - DCHECK(!CanDecrypt(encrypted)); - pending_keys_.reset(new sync_pb::EncryptedData(encrypted)); -} - -const sync_pb::EncryptedData& Cryptographer::GetPendingKeys() const { - DCHECK(has_pending_keys()); - return *(pending_keys_.get()); -} - -bool Cryptographer::DecryptPendingKeys(const KeyParams& params) { - Nigori nigori; - if (!nigori.InitByDerivation(params.hostname, - params.username, - params.password)) { - NOTREACHED(); - return false; - } - - std::string plaintext; - if (!nigori.Decrypt(pending_keys_->blob(), &plaintext)) - return false; - - sync_pb::NigoriKeyBag bag; - if (!bag.ParseFromString(plaintext)) { - NOTREACHED(); - return false; - } - InstallKeys(pending_keys_->key_name(), bag); - pending_keys_.reset(); - return true; -} - -bool Cryptographer::GetBootstrapToken(std::string* token) const { - DCHECK(token); - if (!is_initialized()) - return false; - - return PackBootstrapToken(default_nigori_->second.get(), token); -} - -bool Cryptographer::PackBootstrapToken(const Nigori* nigori, - std::string* pack_into) const { - DCHECK(pack_into); - DCHECK(nigori); - - sync_pb::NigoriKey key; - if (!nigori->ExportKeys(key.mutable_user_key(), - key.mutable_encryption_key(), - key.mutable_mac_key())) { - NOTREACHED(); - return false; - } - - std::string unencrypted_token; - if (!key.SerializeToString(&unencrypted_token)) { - NOTREACHED(); - return false; - } - - std::string encrypted_token; - if (!encryptor_->EncryptString(unencrypted_token, &encrypted_token)) { - NOTREACHED(); - return false; - } - - if (!base::Base64Encode(encrypted_token, pack_into)) { - NOTREACHED(); - return false; - } - return true; -} - -Nigori* Cryptographer::UnpackBootstrapToken(const std::string& token) const { - if (token.empty()) - return NULL; - - std::string encrypted_data; - if (!base::Base64Decode(token, &encrypted_data)) { - DLOG(WARNING) << "Could not decode token."; - return NULL; - } - - std::string unencrypted_token; - if (!encryptor_->DecryptString(encrypted_data, &unencrypted_token)) { - DLOG(WARNING) << "Decryption of bootstrap token failed."; - return NULL; - } - - sync_pb::NigoriKey key; - if (!key.ParseFromString(unencrypted_token)) { - DLOG(WARNING) << "Parsing of bootstrap token failed."; - return NULL; - } - - scoped_ptr<Nigori> nigori(new Nigori); - if (!nigori->InitByImport(key.user_key(), key.encryption_key(), - key.mac_key())) { - NOTREACHED(); - return NULL; - } - - return nigori.release(); -} - -Cryptographer::UpdateResult Cryptographer::Update( - const sync_pb::NigoriSpecifics& nigori) { - UpdateEncryptedTypesFromNigori(nigori); - if (!nigori.encrypted().blob().empty()) { - if (CanDecrypt(nigori.encrypted())) { - SetKeys(nigori.encrypted()); - return Cryptographer::SUCCESS; - } else { - SetPendingKeys(nigori.encrypted()); - return Cryptographer::NEEDS_PASSPHRASE; - } - } - return Cryptographer::SUCCESS; -} - -// Static -syncable::ModelTypeSet Cryptographer::SensitiveTypes() { - // Both of these have their own encryption schemes, but we include them - // anyways. - syncable::ModelTypeSet types; - types.Put(syncable::PASSWORDS); - types.Put(syncable::NIGORI); - return types; -} - -void Cryptographer::UpdateEncryptedTypesFromNigori( - const sync_pb::NigoriSpecifics& nigori) { - if (nigori.encrypt_everything()) { - set_encrypt_everything(); - return; - } - - syncable::ModelTypeSet encrypted_types(SensitiveTypes()); - if (nigori.encrypt_bookmarks()) - encrypted_types.Put(syncable::BOOKMARKS); - if (nigori.encrypt_preferences()) - encrypted_types.Put(syncable::PREFERENCES); - if (nigori.encrypt_autofill_profile()) - encrypted_types.Put(syncable::AUTOFILL_PROFILE); - if (nigori.encrypt_autofill()) - encrypted_types.Put(syncable::AUTOFILL); - if (nigori.encrypt_themes()) - encrypted_types.Put(syncable::THEMES); - if (nigori.encrypt_typed_urls()) - encrypted_types.Put(syncable::TYPED_URLS); - if (nigori.encrypt_extension_settings()) - encrypted_types.Put(syncable::EXTENSION_SETTINGS); - if (nigori.encrypt_extensions()) - encrypted_types.Put(syncable::EXTENSIONS); - if (nigori.encrypt_search_engines()) - encrypted_types.Put(syncable::SEARCH_ENGINES); - if (nigori.encrypt_sessions()) - encrypted_types.Put(syncable::SESSIONS); - if (nigori.encrypt_app_settings()) - encrypted_types.Put(syncable::APP_SETTINGS); - if (nigori.encrypt_apps()) - encrypted_types.Put(syncable::APPS); - if (nigori.encrypt_app_notifications()) - encrypted_types.Put(syncable::APP_NOTIFICATIONS); - - // Note: the initial version with encryption did not support the - // encrypt_everything field. If anything more than the sensitive types were - // encrypted, it meant we were encrypting everything. - if (!nigori.has_encrypt_everything() && - !Difference(encrypted_types, SensitiveTypes()).Empty()) { - set_encrypt_everything(); - return; - } - - MergeEncryptedTypes(encrypted_types); -} - -void Cryptographer::UpdateNigoriFromEncryptedTypes( - sync_pb::NigoriSpecifics* nigori) const { - nigori->set_encrypt_everything(encrypt_everything_); - nigori->set_encrypt_bookmarks( - encrypted_types_.Has(syncable::BOOKMARKS)); - nigori->set_encrypt_preferences( - encrypted_types_.Has(syncable::PREFERENCES)); - nigori->set_encrypt_autofill_profile( - encrypted_types_.Has(syncable::AUTOFILL_PROFILE)); - nigori->set_encrypt_autofill(encrypted_types_.Has(syncable::AUTOFILL)); - nigori->set_encrypt_themes(encrypted_types_.Has(syncable::THEMES)); - nigori->set_encrypt_typed_urls( - encrypted_types_.Has(syncable::TYPED_URLS)); - nigori->set_encrypt_extension_settings( - encrypted_types_.Has(syncable::EXTENSION_SETTINGS)); - nigori->set_encrypt_extensions( - encrypted_types_.Has(syncable::EXTENSIONS)); - nigori->set_encrypt_search_engines( - encrypted_types_.Has(syncable::SEARCH_ENGINES)); - nigori->set_encrypt_sessions(encrypted_types_.Has(syncable::SESSIONS)); - nigori->set_encrypt_app_settings( - encrypted_types_.Has(syncable::APP_SETTINGS)); - nigori->set_encrypt_apps(encrypted_types_.Has(syncable::APPS)); - nigori->set_encrypt_app_notifications( - encrypted_types_.Has(syncable::APP_NOTIFICATIONS)); -} - -void Cryptographer::set_encrypt_everything() { - if (encrypt_everything_) { - DCHECK(encrypted_types_.Equals(syncable::ModelTypeSet::All())); - return; - } - encrypt_everything_ = true; - // Change |encrypted_types_| directly to avoid sending more than one - // notification. - encrypted_types_ = syncable::ModelTypeSet::All(); - EmitEncryptedTypesChangedNotification(); -} - -bool Cryptographer::encrypt_everything() const { - return encrypt_everything_; -} - -syncable::ModelTypeSet Cryptographer::GetEncryptedTypes() const { - return encrypted_types_; -} - -void Cryptographer::MergeEncryptedTypesForTest( - syncable::ModelTypeSet encrypted_types) { - MergeEncryptedTypes(encrypted_types); -} - -void Cryptographer::MergeEncryptedTypes( - syncable::ModelTypeSet encrypted_types) { - if (encrypted_types_.HasAll(encrypted_types)) { - return; - } - encrypted_types_ = encrypted_types; - EmitEncryptedTypesChangedNotification(); -} - -void Cryptographer::EmitEncryptedTypesChangedNotification() { - FOR_EACH_OBSERVER( - Observer, observers_, - OnEncryptedTypesChanged(encrypted_types_, encrypt_everything_)); -} - -void Cryptographer::InstallKeys(const std::string& default_key_name, - const sync_pb::NigoriKeyBag& bag) { - int key_size = bag.key_size(); - for (int i = 0; i < key_size; ++i) { - const sync_pb::NigoriKey key = bag.key(i); - // Only use this key if we don't already know about it. - if (nigoris_.end() == nigoris_.find(key.name())) { - scoped_ptr<Nigori> new_nigori(new Nigori); - if (!new_nigori->InitByImport(key.user_key(), - key.encryption_key(), - key.mac_key())) { - NOTREACHED(); - continue; - } - nigoris_[key.name()] = make_linked_ptr(new_nigori.release()); - } - } - DCHECK(nigoris_.end() != nigoris_.find(default_key_name)); - default_nigori_ = &*nigoris_.find(default_key_name); -} - -} // namespace browser_sync diff --git a/chrome/browser/sync/util/cryptographer.h b/chrome/browser/sync/util/cryptographer.h deleted file mode 100644 index ede5153..0000000 --- a/chrome/browser/sync/util/cryptographer.h +++ /dev/null @@ -1,247 +0,0 @@ -// Copyright (c) 2012 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. - -#ifndef CHROME_BROWSER_SYNC_UTIL_CRYPTOGRAPHER_H_ -#define CHROME_BROWSER_SYNC_UTIL_CRYPTOGRAPHER_H_ -#pragma once - -#include <map> -#include <string> - -#include "base/gtest_prod_util.h" -#include "base/memory/linked_ptr.h" -#include "base/memory/scoped_ptr.h" -#include "base/observer_list.h" -#include "chrome/browser/sync/syncable/model_type.h" -#include "chrome/browser/sync/util/nigori.h" -#include "sync/protocol/encryption.pb.h" -#include "sync/protocol/nigori_specifics.pb.h" - -namespace browser_sync { - -class Encryptor; - -extern const char kNigoriTag[]; - -// The parameters used to initialize a Nigori instance. -struct KeyParams { - std::string hostname; - std::string username; - std::string password; -}; - -// This class manages the Nigori objects used to encrypt and decrypt sensitive -// sync data (eg. passwords). Each Nigori object knows how to handle data -// protected with a particular passphrase. -// -// Whenever an update to the Nigori sync node is received from the server, -// SetPendingKeys should be called with the encrypted contents of that node. -// Most likely, an updated Nigori node means that a new passphrase has been set -// and that future node updates won't be decryptable. To remedy this, the user -// should be prompted for the new passphrase and DecryptPendingKeys be called. -// -// Whenever a update to an encrypted node is received from the server, -// CanDecrypt should be used to verify whether the Cryptographer can decrypt -// that node. If it cannot, then the application of that update should be -// delayed until after it can be decrypted. -class Cryptographer { - public: - // All Observer methods are done synchronously, so they're called - // under a transaction (since all Cryptographer operations are done - // under a transaction). - class Observer { - public: - // Called when the set of encrypted types or the encrypt - // everything flag has been changed. Note that this doesn't - // necessarily mean that encryption has completed for the given - // types. - // - // |encrypted_types| will always be a superset of - // SensitiveTypes(). If |encrypt_everything| is true, - // |encrypted_types| will be the set of all known types. - // - // Until this function is called, observers can assume that the - // set of encrypted types is SensitiveTypes() and that the encrypt - // everything flag is false. - virtual void OnEncryptedTypesChanged( - syncable::ModelTypeSet encrypted_types, - bool encrypt_everything) = 0; - - protected: - virtual ~Observer(); - }; - - // Does not take ownership of |encryptor|. - explicit Cryptographer(Encryptor* encryptor); - ~Cryptographer(); - - // When update on cryptographer is called this enum tells if the - // cryptographer was succesfully able to update using the nigori node or if - // it needs a key to decrypt the nigori node. - enum UpdateResult { - SUCCESS, - NEEDS_PASSPHRASE - }; - - // Manage observers. - void AddObserver(Observer* observer); - void RemoveObserver(Observer* observer); - - // |restored_bootstrap_token| can be provided via this method to bootstrap - // Cryptographer instance into the ready state (is_ready will be true). - // It must be a string that was previously built by the - // GetSerializedBootstrapToken function. It is possible that the token is no - // longer valid (due to server key change), in which case the normal - // decryption code paths will fail and the user will need to provide a new - // passphrase. - // It is an error to call this if is_ready() == true, though it is fair to - // never call Bootstrap at all. - void Bootstrap(const std::string& restored_bootstrap_token); - - // Returns whether we can decrypt |encrypted| using the keys we currently know - // about. - bool CanDecrypt(const sync_pb::EncryptedData& encrypted) const; - - // Returns whether |encrypted| can be decrypted using the default encryption - // key. - bool CanDecryptUsingDefaultKey(const sync_pb::EncryptedData& encrypted) const; - - // Encrypts |message| into |encrypted|. Does not overwrite |encrypted| if - // |message| already matches the decrypted data within |encrypted| and - // |encrypted| was encrypted with the current default key. This avoids - // unnecessarily modifying |encrypted| if the change had no practical effect. - // Returns true unless encryption fails or |message| isn't valid (e.g. a - // required field isn't set). - bool Encrypt(const ::google::protobuf::MessageLite& message, - sync_pb::EncryptedData* encrypted) const; - - // Decrypts |encrypted| into |message|. Returns true unless decryption fails, - // or |message| fails to parse the decrypted data. - bool Decrypt(const sync_pb::EncryptedData& encrypted, - ::google::protobuf::MessageLite* message) const; - - // Decrypts |encrypted| and returns plaintext decrypted data. If decryption - // fails, returns empty string. - std::string DecryptToString(const sync_pb::EncryptedData& encrypted) const; - - // Encrypts the set of currently known keys into |encrypted|. Returns true if - // successful. - bool GetKeys(sync_pb::EncryptedData* encrypted) const; - - // Creates a new Nigori instance using |params|. If successful, |params| will - // become the default encryption key and be used for all future calls to - // Encrypt. - bool AddKey(const KeyParams& params); - - // Same as AddKey(..), but builds the new Nigori from a previously persisted - // bootstrap token. This can be useful when consuming a bootstrap token - // with a cryptographer that has already been initialized. - bool AddKeyFromBootstrapToken(const std::string restored_bootstrap_token); - - // Decrypts |encrypted| and uses its contents to initialize Nigori instances. - // Returns true unless decryption of |encrypted| fails. The caller is - // responsible for checking that CanDecrypt(encrypted) == true. - bool SetKeys(const sync_pb::EncryptedData& encrypted); - - // Makes a local copy of |encrypted| to later be decrypted by - // DecryptPendingKeys. This should only be used if CanDecrypt(encrypted) == - // false. - void SetPendingKeys(const sync_pb::EncryptedData& encrypted); - - // Makes |pending_keys_| available to callers that may want to cache its - // value for later use on the UI thread. It is illegal to call this if the - // cryptographer has no pending keys. Like other calls that access the - // cryptographer, this method must be called from within a transaction. - const sync_pb::EncryptedData& GetPendingKeys() const; - - // Attempts to decrypt the set of keys that was copied in the previous call to - // SetPendingKeys using |params|. Returns true if the pending keys were - // successfully decrypted and installed. - bool DecryptPendingKeys(const KeyParams& params); - - bool is_initialized() const { return !nigoris_.empty() && default_nigori_; } - - // Returns whether this Cryptographer is ready to encrypt and decrypt data. - bool is_ready() const { return is_initialized() && - has_pending_keys() == false; } - - // Returns whether there is a pending set of keys that needs to be decrypted. - bool has_pending_keys() const { return NULL != pending_keys_.get(); } - - // Obtain a token that can be provided on construction to a future - // Cryptographer instance to bootstrap itself. Returns false if such a token - // can't be created (i.e. if this Cryptograhper doesn't have valid keys). - bool GetBootstrapToken(std::string* token) const; - - // Update the cryptographer based on the contents of the nigori specifics. - // This updates both the encryption keys and the set of encrypted types. - // Returns NEEDS_PASSPHRASE if was unable to decrypt the pending keys, - // SUCCESS otherwise. - UpdateResult Update(const sync_pb::NigoriSpecifics& nigori); - - // The set of types that are always encrypted. - static syncable::ModelTypeSet SensitiveTypes(); - - // Reset our set of encrypted types based on the contents of the nigori - // specifics. - void UpdateEncryptedTypesFromNigori(const sync_pb::NigoriSpecifics& nigori); - - // Update the nigori to reflect the current set of encrypted types. - void UpdateNigoriFromEncryptedTypes(sync_pb::NigoriSpecifics* nigori) const; - - // Setter/getter for whether all current and future datatypes should - // be encrypted. Once set you cannot unset without reading from a - // new nigori node. set_encrypt_everything() emits a notification - // the first time it's called. - void set_encrypt_everything(); - bool encrypt_everything() const; - - // Return the set of encrypted types. - syncable::ModelTypeSet GetEncryptedTypes() const; - - // Forwards to MergeEncryptedTypes. - void MergeEncryptedTypesForTest( - syncable::ModelTypeSet encrypted_types); - - private: - FRIEND_TEST_ALL_PREFIXES(SyncCryptographerTest, PackUnpack); - typedef std::map<std::string, linked_ptr<const Nigori> > NigoriMap; - - // Merges the given set of encrypted types with the existing set and emits a - // notification if necessary. - void MergeEncryptedTypes(syncable::ModelTypeSet encrypted_types); - - void EmitEncryptedTypesChangedNotification(); - - // Helper method to instantiate Nigori instances for each set of key - // parameters in |bag| and setting the default encryption key to - // |default_key_name|. - void InstallKeys(const std::string& default_key_name, - const sync_pb::NigoriKeyBag& bag); - - bool AddKeyImpl(Nigori* nigori); - - // Functions to serialize + encrypt a Nigori object in an opaque format for - // persistence by sync infrastructure. - bool PackBootstrapToken(const Nigori* nigori, std::string* pack_into) const; - Nigori* UnpackBootstrapToken(const std::string& token) const; - - Encryptor* const encryptor_; - - ObserverList<Observer> observers_; - - NigoriMap nigoris_; // The Nigoris we know about, mapped by key name. - NigoriMap::value_type* default_nigori_; // The Nigori used for encryption. - - scoped_ptr<sync_pb::EncryptedData> pending_keys_; - - syncable::ModelTypeSet encrypted_types_; - bool encrypt_everything_; - - DISALLOW_COPY_AND_ASSIGN(Cryptographer); -}; - -} // namespace browser_sync - -#endif // CHROME_BROWSER_SYNC_UTIL_CRYPTOGRAPHER_H_ diff --git a/chrome/browser/sync/util/cryptographer_unittest.cc b/chrome/browser/sync/util/cryptographer_unittest.cc deleted file mode 100644 index 99e676d..0000000 --- a/chrome/browser/sync/util/cryptographer_unittest.cc +++ /dev/null @@ -1,391 +0,0 @@ -// Copyright (c) 2012 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 "chrome/browser/sync/util/cryptographer.h" - -#include <string> - -#include "base/memory/scoped_ptr.h" -#include "base/string_util.h" -#include "chrome/browser/sync/syncable/model_type_test_util.h" -#include "chrome/browser/sync/test/fake_encryptor.h" -#include "sync/protocol/nigori_specifics.pb.h" -#include "sync/protocol/password_specifics.pb.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace browser_sync { - -namespace { - -using ::testing::_; -using ::testing::Mock; -using ::testing::StrictMock; -using syncable::ModelTypeSet; - -class MockObserver : public Cryptographer::Observer { - public: - MOCK_METHOD2(OnEncryptedTypesChanged, - void(syncable::ModelTypeSet, bool)); -}; - -} // namespace - -class SyncCryptographerTest : public ::testing::Test { - protected: - SyncCryptographerTest() : cryptographer_(&encryptor_) {} - - FakeEncryptor encryptor_; - Cryptographer cryptographer_; -}; - -TEST_F(SyncCryptographerTest, EmptyCantDecrypt) { - EXPECT_FALSE(cryptographer_.is_ready()); - - sync_pb::EncryptedData encrypted; - encrypted.set_key_name("foo"); - encrypted.set_blob("bar"); - - EXPECT_FALSE(cryptographer_.CanDecrypt(encrypted)); -} - -TEST_F(SyncCryptographerTest, EmptyCantEncrypt) { - EXPECT_FALSE(cryptographer_.is_ready()); - - sync_pb::EncryptedData encrypted; - sync_pb::PasswordSpecificsData original; - EXPECT_FALSE(cryptographer_.Encrypt(original, &encrypted)); -} - -TEST_F(SyncCryptographerTest, MissingCantDecrypt) { - KeyParams params = {"localhost", "dummy", "dummy"}; - cryptographer_.AddKey(params); - EXPECT_TRUE(cryptographer_.is_ready()); - - sync_pb::EncryptedData encrypted; - encrypted.set_key_name("foo"); - encrypted.set_blob("bar"); - - EXPECT_FALSE(cryptographer_.CanDecrypt(encrypted)); -} - -TEST_F(SyncCryptographerTest, CanEncryptAndDecrypt) { - KeyParams params = {"localhost", "dummy", "dummy"}; - EXPECT_TRUE(cryptographer_.AddKey(params)); - EXPECT_TRUE(cryptographer_.is_ready()); - - sync_pb::PasswordSpecificsData original; - original.set_origin("http://example.com"); - original.set_username_value("azure"); - original.set_password_value("hunter2"); - - sync_pb::EncryptedData encrypted; - EXPECT_TRUE(cryptographer_.Encrypt(original, &encrypted)); - - sync_pb::PasswordSpecificsData decrypted; - EXPECT_TRUE(cryptographer_.Decrypt(encrypted, &decrypted)); - - EXPECT_EQ(original.SerializeAsString(), decrypted.SerializeAsString()); -} - -TEST_F(SyncCryptographerTest, EncryptOnlyIfDifferent) { - KeyParams params = {"localhost", "dummy", "dummy"}; - EXPECT_TRUE(cryptographer_.AddKey(params)); - EXPECT_TRUE(cryptographer_.is_ready()); - - sync_pb::PasswordSpecificsData original; - original.set_origin("http://example.com"); - original.set_username_value("azure"); - original.set_password_value("hunter2"); - - sync_pb::EncryptedData encrypted; - EXPECT_TRUE(cryptographer_.Encrypt(original, &encrypted)); - - sync_pb::EncryptedData encrypted2, encrypted3; - encrypted2.CopyFrom(encrypted); - encrypted3.CopyFrom(encrypted); - EXPECT_TRUE(cryptographer_.Encrypt(original, &encrypted2)); - - // Now encrypt with a new default key. Should overwrite the old data. - KeyParams params_new = {"localhost", "dummy", "dummy2"}; - cryptographer_.AddKey(params_new); - EXPECT_TRUE(cryptographer_.Encrypt(original, &encrypted3)); - - sync_pb::PasswordSpecificsData decrypted; - EXPECT_TRUE(cryptographer_.Decrypt(encrypted2, &decrypted)); - // encrypted2 should match encrypted, encrypted3 should not (due to salting). - EXPECT_EQ(encrypted.SerializeAsString(), encrypted2.SerializeAsString()); - EXPECT_NE(encrypted.SerializeAsString(), encrypted3.SerializeAsString()); - EXPECT_EQ(original.SerializeAsString(), decrypted.SerializeAsString()); -} - -TEST_F(SyncCryptographerTest, AddKeySetsDefault) { - KeyParams params1 = {"localhost", "dummy", "dummy1"}; - EXPECT_TRUE(cryptographer_.AddKey(params1)); - EXPECT_TRUE(cryptographer_.is_ready()); - - sync_pb::PasswordSpecificsData original; - original.set_origin("http://example.com"); - original.set_username_value("azure"); - original.set_password_value("hunter2"); - - sync_pb::EncryptedData encrypted1; - EXPECT_TRUE(cryptographer_.Encrypt(original, &encrypted1)); - sync_pb::EncryptedData encrypted2; - EXPECT_TRUE(cryptographer_.Encrypt(original, &encrypted2)); - - KeyParams params2 = {"localhost", "dummy", "dummy2"}; - EXPECT_TRUE(cryptographer_.AddKey(params2)); - EXPECT_TRUE(cryptographer_.is_ready()); - - sync_pb::EncryptedData encrypted3; - EXPECT_TRUE(cryptographer_.Encrypt(original, &encrypted3)); - sync_pb::EncryptedData encrypted4; - EXPECT_TRUE(cryptographer_.Encrypt(original, &encrypted4)); - - EXPECT_EQ(encrypted1.key_name(), encrypted2.key_name()); - EXPECT_NE(encrypted1.key_name(), encrypted3.key_name()); - EXPECT_EQ(encrypted3.key_name(), encrypted4.key_name()); -} - -// Crashes, Bug 55178. -#if defined(OS_WIN) -#define MAYBE_EncryptExportDecrypt DISABLED_EncryptExportDecrypt -#else -#define MAYBE_EncryptExportDecrypt EncryptExportDecrypt -#endif -TEST_F(SyncCryptographerTest, MAYBE_EncryptExportDecrypt) { - sync_pb::EncryptedData nigori; - sync_pb::EncryptedData encrypted; - - sync_pb::PasswordSpecificsData original; - original.set_origin("http://example.com"); - original.set_username_value("azure"); - original.set_password_value("hunter2"); - - { - Cryptographer cryptographer(&encryptor_); - - KeyParams params = {"localhost", "dummy", "dummy"}; - cryptographer.AddKey(params); - EXPECT_TRUE(cryptographer.is_ready()); - - EXPECT_TRUE(cryptographer.Encrypt(original, &encrypted)); - EXPECT_TRUE(cryptographer.GetKeys(&nigori)); - } - - { - Cryptographer cryptographer(&encryptor_); - EXPECT_FALSE(cryptographer.CanDecrypt(nigori)); - - cryptographer.SetPendingKeys(nigori); - EXPECT_FALSE(cryptographer.is_ready()); - EXPECT_TRUE(cryptographer.has_pending_keys()); - - KeyParams params = {"localhost", "dummy", "dummy"}; - EXPECT_TRUE(cryptographer.DecryptPendingKeys(params)); - EXPECT_TRUE(cryptographer.is_ready()); - EXPECT_FALSE(cryptographer.has_pending_keys()); - - sync_pb::PasswordSpecificsData decrypted; - EXPECT_TRUE(cryptographer.Decrypt(encrypted, &decrypted)); - EXPECT_EQ(original.SerializeAsString(), decrypted.SerializeAsString()); - } -} - -// Crashes, Bug 55178. -#if defined(OS_WIN) -#define MAYBE_PackUnpack DISABLED_PackUnpack -#else -#define MAYBE_PackUnpack PackUnpack -#endif -TEST_F(SyncCryptographerTest, MAYBE_PackUnpack) { - Nigori nigori; - ASSERT_TRUE(nigori.InitByDerivation("example.com", "username", "password")); - std::string expected_user, expected_encryption, expected_mac; - ASSERT_TRUE(nigori.ExportKeys(&expected_user, &expected_encryption, - &expected_mac)); - - std::string token; - EXPECT_TRUE(cryptographer_.PackBootstrapToken(&nigori, &token)); - EXPECT_TRUE(IsStringUTF8(token)); - - scoped_ptr<Nigori> unpacked(cryptographer_.UnpackBootstrapToken(token)); - EXPECT_NE(static_cast<Nigori*>(NULL), unpacked.get()); - - std::string user_key, encryption_key, mac_key; - ASSERT_TRUE(unpacked->ExportKeys(&user_key, &encryption_key, &mac_key)); - - EXPECT_EQ(expected_user, user_key); - EXPECT_EQ(expected_encryption, encryption_key); - EXPECT_EQ(expected_mac, mac_key); -} - -TEST_F(SyncCryptographerTest, NigoriEncryptionTypes) { - Cryptographer cryptographer2(&encryptor_); - sync_pb::NigoriSpecifics nigori; - - StrictMock<MockObserver> observer; - cryptographer_.AddObserver(&observer); - StrictMock<MockObserver> observer2; - cryptographer2.AddObserver(&observer2); - - // Just set the sensitive types (shouldn't trigger any - // notifications). - ModelTypeSet encrypted_types(Cryptographer::SensitiveTypes()); - cryptographer_.MergeEncryptedTypesForTest(encrypted_types); - cryptographer_.UpdateNigoriFromEncryptedTypes(&nigori); - cryptographer2.UpdateEncryptedTypesFromNigori(nigori); - EXPECT_TRUE(encrypted_types.Equals(cryptographer_.GetEncryptedTypes())); - EXPECT_TRUE(encrypted_types.Equals(cryptographer2.GetEncryptedTypes())); - - Mock::VerifyAndClearExpectations(&observer); - Mock::VerifyAndClearExpectations(&observer2); - - EXPECT_CALL(observer, - OnEncryptedTypesChanged( - HasModelTypes(syncable::ModelTypeSet::All()), - false)); - EXPECT_CALL(observer2, - OnEncryptedTypesChanged( - HasModelTypes(syncable::ModelTypeSet::All()), - false)); - - // Set all encrypted types - encrypted_types = syncable::ModelTypeSet::All(); - cryptographer_.MergeEncryptedTypesForTest(encrypted_types); - cryptographer_.UpdateNigoriFromEncryptedTypes(&nigori); - cryptographer2.UpdateEncryptedTypesFromNigori(nigori); - EXPECT_TRUE(encrypted_types.Equals(cryptographer_.GetEncryptedTypes())); - EXPECT_TRUE(encrypted_types.Equals(cryptographer2.GetEncryptedTypes())); - - // Receiving an empty nigori should not reset any encrypted types or trigger - // an observer notification. - Mock::VerifyAndClearExpectations(&observer); - nigori = sync_pb::NigoriSpecifics(); - cryptographer_.UpdateEncryptedTypesFromNigori(nigori); - EXPECT_TRUE(encrypted_types.Equals(cryptographer_.GetEncryptedTypes())); -} - -TEST_F(SyncCryptographerTest, EncryptEverythingExplicit) { - ModelTypeSet real_types = syncable::ModelTypeSet::All(); - sync_pb::NigoriSpecifics specifics; - specifics.set_encrypt_everything(true); - - StrictMock<MockObserver> observer; - cryptographer_.AddObserver(&observer); - - EXPECT_CALL(observer, - OnEncryptedTypesChanged( - HasModelTypes(syncable::ModelTypeSet::All()), true)); - - EXPECT_FALSE(cryptographer_.encrypt_everything()); - ModelTypeSet encrypted_types = cryptographer_.GetEncryptedTypes(); - for (ModelTypeSet::Iterator iter = real_types.First(); - iter.Good(); iter.Inc()) { - if (iter.Get() == syncable::PASSWORDS || iter.Get() == syncable::NIGORI) - EXPECT_TRUE(encrypted_types.Has(iter.Get())); - else - EXPECT_FALSE(encrypted_types.Has(iter.Get())); - } - - cryptographer_.UpdateEncryptedTypesFromNigori(specifics); - - EXPECT_TRUE(cryptographer_.encrypt_everything()); - encrypted_types = cryptographer_.GetEncryptedTypes(); - for (ModelTypeSet::Iterator iter = real_types.First(); - iter.Good(); iter.Inc()) { - EXPECT_TRUE(encrypted_types.Has(iter.Get())); - } - - // Shouldn't trigger another notification. - specifics.set_encrypt_everything(true); - - cryptographer_.RemoveObserver(&observer); -} - -TEST_F(SyncCryptographerTest, EncryptEverythingImplicit) { - ModelTypeSet real_types = syncable::ModelTypeSet::All(); - sync_pb::NigoriSpecifics specifics; - specifics.set_encrypt_bookmarks(true); // Non-passwords = encrypt everything - - StrictMock<MockObserver> observer; - cryptographer_.AddObserver(&observer); - - EXPECT_CALL(observer, - OnEncryptedTypesChanged( - HasModelTypes(syncable::ModelTypeSet::All()), true)); - - EXPECT_FALSE(cryptographer_.encrypt_everything()); - ModelTypeSet encrypted_types = cryptographer_.GetEncryptedTypes(); - for (ModelTypeSet::Iterator iter = real_types.First(); - iter.Good(); iter.Inc()) { - if (iter.Get() == syncable::PASSWORDS || iter.Get() == syncable::NIGORI) - EXPECT_TRUE(encrypted_types.Has(iter.Get())); - else - EXPECT_FALSE(encrypted_types.Has(iter.Get())); - } - - cryptographer_.UpdateEncryptedTypesFromNigori(specifics); - - EXPECT_TRUE(cryptographer_.encrypt_everything()); - encrypted_types = cryptographer_.GetEncryptedTypes(); - for (ModelTypeSet::Iterator iter = real_types.First(); - iter.Good(); iter.Inc()) { - EXPECT_TRUE(encrypted_types.Has(iter.Get())); - } - - // Shouldn't trigger another notification. - specifics.set_encrypt_everything(true); - - cryptographer_.RemoveObserver(&observer); -} - -TEST_F(SyncCryptographerTest, UnknownSensitiveTypes) { - ModelTypeSet real_types = syncable::ModelTypeSet::All(); - sync_pb::NigoriSpecifics specifics; - // Explicitly setting encrypt everything should override logic for implicit - // encrypt everything. - specifics.set_encrypt_everything(false); - specifics.set_encrypt_bookmarks(true); - - StrictMock<MockObserver> observer; - cryptographer_.AddObserver(&observer); - - syncable::ModelTypeSet expected_encrypted_types = - Cryptographer::SensitiveTypes(); - expected_encrypted_types.Put(syncable::BOOKMARKS); - - EXPECT_CALL(observer, - OnEncryptedTypesChanged( - HasModelTypes(expected_encrypted_types), false)); - - EXPECT_FALSE(cryptographer_.encrypt_everything()); - ModelTypeSet encrypted_types = cryptographer_.GetEncryptedTypes(); - for (ModelTypeSet::Iterator iter = real_types.First(); - iter.Good(); iter.Inc()) { - if (iter.Get() == syncable::PASSWORDS || iter.Get() == syncable::NIGORI) - EXPECT_TRUE(encrypted_types.Has(iter.Get())); - else - EXPECT_FALSE(encrypted_types.Has(iter.Get())); - } - - cryptographer_.UpdateEncryptedTypesFromNigori(specifics); - - EXPECT_FALSE(cryptographer_.encrypt_everything()); - encrypted_types = cryptographer_.GetEncryptedTypes(); - for (ModelTypeSet::Iterator iter = real_types.First(); - iter.Good(); iter.Inc()) { - if (iter.Get() == syncable::PASSWORDS || - iter.Get() == syncable::NIGORI || - iter.Get() == syncable::BOOKMARKS) - EXPECT_TRUE(encrypted_types.Has(iter.Get())); - else - EXPECT_FALSE(encrypted_types.Has(iter.Get())); - } - - cryptographer_.RemoveObserver(&observer); -} - -} // namespace browser_sync diff --git a/chrome/browser/sync/util/data_encryption.cc b/chrome/browser/sync/util/data_encryption.cc deleted file mode 100644 index 10f19ec..0000000 --- a/chrome/browser/sync/util/data_encryption.cc +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) 2010 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. -// -// NOTE: this file is Winodws specific. - -#include "chrome/browser/sync/util/data_encryption.h" - -#include <windows.h> -#include <wincrypt.h> - -#include <cstddef> -#include <string> -#include <vector> - -#include "base/logging.h" - -using std::string; -using std::vector; - -vector<uint8> EncryptData(const string& data) { - DATA_BLOB unencrypted_data = { 0 }; - unencrypted_data.pbData = (BYTE*)(data.data()); - unencrypted_data.cbData = data.size(); - DATA_BLOB encrypted_data = { 0 }; - - if (!CryptProtectData(&unencrypted_data, L"", NULL, NULL, NULL, 0, - &encrypted_data)) - LOG(ERROR) << "Encryption fails: " << data; - - vector<uint8> result(encrypted_data.pbData, - encrypted_data.pbData + encrypted_data.cbData); - LocalFree(encrypted_data.pbData); - return result; -} - -bool DecryptData(const vector<uint8>& in_data, string* out_data) { - DATA_BLOB encrypted_data, decrypted_data; - encrypted_data.pbData = - (in_data.empty() ? NULL : const_cast<BYTE*>(&in_data[0])); - encrypted_data.cbData = in_data.size(); - LPWSTR descrip = L""; - - if (!CryptUnprotectData(&encrypted_data, &descrip, NULL, NULL, NULL, 0, - &decrypted_data)) { - LOG(ERROR) << "Decryption fails: "; - return false; - } else { - out_data->assign(reinterpret_cast<const char*>(decrypted_data.pbData), - decrypted_data.cbData); - LocalFree(decrypted_data.pbData); - return true; - } -} diff --git a/chrome/browser/sync/util/data_encryption.h b/chrome/browser/sync/util/data_encryption.h deleted file mode 100644 index 1f48afd..0000000 --- a/chrome/browser/sync/util/data_encryption.h +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) 2010 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. - -#ifndef CHROME_BROWSER_SYNC_UTIL_DATA_ENCRYPTION_H_ -#define CHROME_BROWSER_SYNC_UTIL_DATA_ENCRYPTION_H_ -#pragma once - -#include <string> -#include <vector> - -#include "base/basictypes.h" - -using std::string; -using std::vector; - -vector<uint8> EncryptData(const string& data); -bool DecryptData(const vector<uint8>& in_data, string* out_data); - -#endif // CHROME_BROWSER_SYNC_UTIL_DATA_ENCRYPTION_H_ diff --git a/chrome/browser/sync/util/data_encryption_unittest.cc b/chrome/browser/sync/util/data_encryption_unittest.cc deleted file mode 100644 index 6a8091c..0000000 --- a/chrome/browser/sync/util/data_encryption_unittest.cc +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) 2012 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 "chrome/browser/sync/util/data_encryption.h" - -#include <string> -#include <vector> - -#include "testing/gtest/include/gtest/gtest.h" - -using std::string; -using std::vector; - -namespace { - -TEST(SyncDataEncryption, TestEncryptDecryptOfSampleString) { - vector<uint8> example(EncryptData("example")); - ASSERT_FALSE(example.empty()); - string result; - ASSERT_TRUE(DecryptData(example, &result)); - ASSERT_TRUE(result == "example"); -} - -TEST(SyncDataEncryption, TestDecryptFailure) { - vector<uint8> example(0, 0); - string result; - ASSERT_FALSE(DecryptData(example, &result)); -} - -} // namespace diff --git a/chrome/browser/sync/util/data_type_histogram.h b/chrome/browser/sync/util/data_type_histogram.h deleted file mode 100644 index 00478222..0000000 --- a/chrome/browser/sync/util/data_type_histogram.h +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright (c) 2012 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. - -#ifndef CHROME_BROWSER_SYNC_UTIL_DATA_TYPE_HISTOGRAM_H_ -#define CHROME_BROWSER_SYNC_UTIL_DATA_TYPE_HISTOGRAM_H_ -#pragma once - -#include "base/metrics/histogram.h" -#include "base/time.h" -#include "chrome/browser/sync/syncable/model_type.h" - -// For now, this just implements UMA_HISTOGRAM_LONG_TIMES. This can be adjusted -// if we feel the min, max, or bucket count amount are not appropriate. -#define SYNC_FREQ_HISTOGRAM(name, time) UMA_HISTOGRAM_CUSTOM_TIMES( \ - name, time, base::TimeDelta::FromMilliseconds(1), \ - base::TimeDelta::FromHours(1), 50) - -// Helper macro for datatype specific histograms. For each datatype, invokes -// a pre-defined PER_DATA_TYPE_MACRO(type_str), where |type_str| is the string -// version of the datatype. -// -// Example usage (ignoring newlines necessary for multiline macro): -// std::vector<syncable::ModelType> types = GetEntryTypes(); -// for (int i = 0; i < types.size(); ++i) { -// #define PER_DATA_TYPE_MACRO(type_str) -// UMA_HISTOGRAM_ENUMERATION("Sync." type_str "StartFailures", -// error, max_error); -// SYNC_DATA_TYPE_HISTOGRAM(types[i]); -// #undef PER_DATA_TYPE_MACRO -// } -// -// TODO(zea): Once visual studio supports proper variadic argument replacement -// in macros, pass in the histogram method directly as a parameter. -// See http://connect.microsoft.com/VisualStudio/feedback/details/380090/ -// variadic-macro-replacement#details -#define SYNC_DATA_TYPE_HISTOGRAM(datatype) \ - do { \ - switch (datatype) { \ - case syncable::BOOKMARKS: \ - PER_DATA_TYPE_MACRO("Bookmarks"); \ - break; \ - case syncable::PREFERENCES: \ - PER_DATA_TYPE_MACRO("Preferences"); \ - break; \ - case syncable::PASSWORDS: \ - PER_DATA_TYPE_MACRO("Passwords"); \ - break; \ - case syncable::AUTOFILL: \ - PER_DATA_TYPE_MACRO("Autofill"); \ - break; \ - case syncable::AUTOFILL_PROFILE: \ - PER_DATA_TYPE_MACRO("AutofillProfiles"); \ - break; \ - case syncable::THEMES: \ - PER_DATA_TYPE_MACRO("Themes"); \ - break; \ - case syncable::TYPED_URLS: \ - PER_DATA_TYPE_MACRO("TypedUrls"); \ - break; \ - case syncable::EXTENSIONS: \ - PER_DATA_TYPE_MACRO("Extensions"); \ - break; \ - case syncable::NIGORI: \ - PER_DATA_TYPE_MACRO("Nigori"); \ - break; \ - case syncable::SEARCH_ENGINES: \ - PER_DATA_TYPE_MACRO("SearchEngines"); \ - break; \ - case syncable::SESSIONS: \ - PER_DATA_TYPE_MACRO("Sessions"); \ - break; \ - case syncable::APPS: \ - PER_DATA_TYPE_MACRO("Apps"); \ - break; \ - case syncable::APP_SETTINGS: \ - PER_DATA_TYPE_MACRO("AppSettings"); \ - break; \ - case syncable::EXTENSION_SETTINGS: \ - PER_DATA_TYPE_MACRO("ExtensionSettings"); \ - break; \ - case syncable::APP_NOTIFICATIONS: \ - PER_DATA_TYPE_MACRO("AppNotifications"); \ - break; \ - default: \ - NOTREACHED() << "Unknown datatype " \ - << syncable::ModelTypeToString(datatype); \ - } \ - } while (0) - -#endif // CHROME_BROWSER_SYNC_UTIL_DATA_TYPE_HISTOGRAM_H_ diff --git a/chrome/browser/sync/util/data_type_histogram_unittest.cc b/chrome/browser/sync/util/data_type_histogram_unittest.cc deleted file mode 100644 index 6b7547e..0000000 --- a/chrome/browser/sync/util/data_type_histogram_unittest.cc +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright (c) 2012 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 "chrome/browser/sync/util/data_type_histogram.h" - -#include "base/time.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace browser_sync { -namespace { - -class DataTypeHistogramTest : public testing::Test { -}; - -// Create a histogram of type HISTOGRAM_COUNTS for each model type. Nothing -// should break. -TEST(DataTypeHistogramTest, BasicCount) { - for (int i = syncable::FIRST_REAL_MODEL_TYPE; - i <= syncable::LAST_REAL_MODEL_TYPE; ++i) { - syncable::ModelType type = syncable::ModelTypeFromInt(i); -#define PER_DATA_TYPE_MACRO(type_str) \ - HISTOGRAM_COUNTS("Prefix" type_str "Suffix", 1); - SYNC_DATA_TYPE_HISTOGRAM(type); -#undef PER_DATA_TYPE_MACRO - } -} - -// Create a histogram of type SYNC_FREQ_HISTOGRAM for each model type. Nothing -// should break. -TEST(DataTypeHistogramTest, BasicFreq) { - for (int i = syncable::FIRST_REAL_MODEL_TYPE; - i <= syncable::LAST_REAL_MODEL_TYPE; ++i) { - syncable::ModelType type = syncable::ModelTypeFromInt(i); -#define PER_DATA_TYPE_MACRO(type_str) \ - SYNC_FREQ_HISTOGRAM("Prefix" type_str "Suffix", \ - base::TimeDelta::FromSeconds(1)); - SYNC_DATA_TYPE_HISTOGRAM(type); -#undef PER_DATA_TYPE_MACRO - } -} - -// Create a histogram of type UMA_HISTOGRAM_ENUMERATION for each model type. -// Nothing should break. -TEST(DataTypeHistogramTest, BasicEnum) { - enum HistTypes { - TYPE_1, - TYPE_2, - TYPE_COUNT, - }; - for (int i = syncable::FIRST_REAL_MODEL_TYPE; - i <= syncable::LAST_REAL_MODEL_TYPE; ++i) { - syncable::ModelType type = syncable::ModelTypeFromInt(i); -#define PER_DATA_TYPE_MACRO(type_str) \ - UMA_HISTOGRAM_ENUMERATION("Prefix" type_str "Suffix", \ - (i % 2 ? TYPE_1 : TYPE_2), TYPE_COUNT); - SYNC_DATA_TYPE_HISTOGRAM(type); -#undef PER_DATA_TYPE_MACRO - } -} - -} // namespace -} // namespace browser_sync diff --git a/chrome/browser/sync/util/encryptor.h b/chrome/browser/sync/util/encryptor.h deleted file mode 100644 index 1c9eab9..0000000 --- a/chrome/browser/sync/util/encryptor.h +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) 2012 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. - -#ifndef CHROME_BROWSER_SYNC_UTIL_ENCRYPTOR_H_ -#define CHROME_BROWSER_SYNC_UTIL_ENCRYPTOR_H_ -#pragma once - -#include <string> - -namespace browser_sync { - -class Encryptor { - public: - // All methods below should be thread-safe. - virtual bool EncryptString(const std::string& plaintext, - std::string* ciphertext) = 0; - - virtual bool DecryptString(const std::string& ciphertext, - std::string* plaintext) = 0; - - protected: - virtual ~Encryptor() {} -}; - -} // namespace browser_sync - -#endif // CHROME_BROWSER_SYNC_UTIL_ENCRYPTOR_H_ diff --git a/chrome/browser/sync/util/enum_set.h b/chrome/browser/sync/util/enum_set.h deleted file mode 100644 index 51d3afe..0000000 --- a/chrome/browser/sync/util/enum_set.h +++ /dev/null @@ -1,286 +0,0 @@ -// Copyright (c) 2011 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. - -#ifndef CHROME_BROWSER_SYNC_UTIL_ENUM_SET_H_ -#define CHROME_BROWSER_SYNC_UTIL_ENUM_SET_H_ -#pragma once - -#include <bitset> -#include <cstddef> -#include <string> - -#include "base/basictypes.h" -#include "base/logging.h" - -namespace browser_sync { - -// Forward declarations needed for friend declarations. -template <typename E, E MinEnumValue, E MaxEnumValue> -class EnumSet; - -template <typename E, E Min, E Max> -EnumSet<E, Min, Max> Union(EnumSet<E, Min, Max> set1, - EnumSet<E, Min, Max> set2); - -template <typename E, E Min, E Max> -EnumSet<E, Min, Max> Intersection(EnumSet<E, Min, Max> set1, - EnumSet<E, Min, Max> set2); - -template <typename E, E Min, E Max> -EnumSet<E, Min, Max> Difference(EnumSet<E, Min, Max> set1, - EnumSet<E, Min, Max> set2); - -// An EnumSet is a set that can hold enum values between a min and a -// max value (inclusive of both). It's essentially a wrapper around -// std::bitset<> with stronger type enforcement, more descriptive -// member function names, and an iterator interface. -// -// If you're working with enums with a small number of possible values -// (say, fewer than 64), you can efficiently pass around an EnumSet -// for that enum around by value. - -template <typename E, E MinEnumValue, E MaxEnumValue> -class EnumSet { - public: - typedef E EnumType; - static const E kMinValue = MinEnumValue; - static const E kMaxValue = MaxEnumValue; - static const size_t kValueCount = kMaxValue - kMinValue + 1; - COMPILE_ASSERT(kMinValue < kMaxValue, - min_value_must_be_less_than_max_value); - - private: - // Declaration needed by Iterator. - typedef std::bitset<kValueCount> EnumBitSet; - - public: - // Iterator is a forward-only read-only iterator for EnumSet. Its - // interface is deliberately distinct from an STL iterator as its - // semantics are substantially different. - // - // Example usage: - // - // for (EnumSet<...>::Iterator it = enums.First(); it.Good(); it.Inc()) { - // Process(it.Get()); - // } - // - // The iterator must not be outlived by the set. In particular, the - // following is an error: - // - // EnumSet<...> SomeFn() { ... } - // - // /* ERROR */ - // for (EnumSet<...>::Iterator it = SomeFun().First(); ... - // - // Also, there are no guarantees as to what will happen if you - // modify an EnumSet while traversing it with an iterator. - class Iterator { - public: - // A default-constructed iterator can't do anything except check - // Good(). You need to call First() on an EnumSet to get a usable - // iterator. - Iterator() : enums_(NULL), i_(kValueCount) {} - ~Iterator() {} - - // Copy constructor and assignment welcome. - - // Returns true iff the iterator points to an EnumSet and it - // hasn't yet traversed the EnumSet entirely. - bool Good() const { - return enums_ && i_ < kValueCount && enums_->test(i_); - } - - // Returns the value the iterator currently points to. Good() - // must hold. - E Get() const { - CHECK(Good()); - return FromIndex(i_); - } - - // Moves the iterator to the next value in the EnumSet. Good() - // must hold. Takes linear time. - void Inc() { - CHECK(Good()); - i_ = FindNext(i_ + 1); - } - - private: - friend Iterator EnumSet::First() const; - - explicit Iterator(const EnumBitSet& enums) - : enums_(&enums), i_(FindNext(0)) {} - - size_t FindNext(size_t i) { - while ((i < kValueCount) && !enums_->test(i)) { - ++i; - } - return i; - } - - const EnumBitSet* enums_; - size_t i_; - }; - - // You can construct an EnumSet with 0, 1, 2, or 3 initial values. - - EnumSet() {} - - explicit EnumSet(E value) { - Put(value); - } - - EnumSet(E value1, E value2) { - Put(value1); - Put(value2); - } - - EnumSet(E value1, E value2, E value3) { - Put(value1); - Put(value2); - Put(value3); - } - - // Returns an EnumSet with all possible values. - static EnumSet All() { - EnumBitSet enums; - enums.set(); - return EnumSet(enums); - } - - ~EnumSet() {} - - // Copy constructor and assignment welcome. - - // Set operations. Put, Retain, and Remove are basically - // self-mutating versions of Union, Intersection, and Difference - // (defined below). - - // Adds the given value (which must be in range) to our set. - void Put(E value) { - enums_.set(ToIndex(value)); - } - - // Adds all values in the given set to our set. - void PutAll(EnumSet other) { - enums_ |= other.enums_; - } - - // There's no real need for a Retain(E) member function. - - // Removes all values not in the given set from our set. - void RetainAll(EnumSet other) { - enums_ &= other.enums_; - } - - // If the given value is in range, removes it from our set. - void Remove(E value) { - if (InRange(value)) { - enums_.reset(ToIndex(value)); - } - } - - // Removes all values in the given set from our set. - void RemoveAll(EnumSet other) { - enums_ &= ~other.enums_; - } - - // Removes all values from our set. - void Clear() { - enums_.reset(); - } - - // Returns true iff the given value is in range and a member of our - // set. - bool Has(E value) const { - return InRange(value) && enums_.test(ToIndex(value)); - } - - // Returns true iff the given set is a subset of our set. - bool HasAll(EnumSet other) const { - return (enums_ & other.enums_) == other.enums_; - } - - // Returns true iff our set and the given set contain exactly the - // same values. - bool Equals(const EnumSet& other) const { - return enums_ == other.enums_; - } - - // Returns true iff our set is empty. - bool Empty() const { - return !enums_.any(); - } - - // Returns how many values our set has. - size_t Size() const { - return enums_.count(); - } - - // Returns an iterator pointing to the first element (if any). - Iterator First() const { - return Iterator(enums_); - } - - private: - friend EnumSet Union<E, MinEnumValue, MaxEnumValue>( - EnumSet set1, EnumSet set2); - friend EnumSet Intersection<E, MinEnumValue, MaxEnumValue>( - EnumSet set1, EnumSet set2); - friend EnumSet Difference<E, MinEnumValue, MaxEnumValue>( - EnumSet set1, EnumSet set2); - - explicit EnumSet(EnumBitSet enums) : enums_(enums) {} - - static bool InRange(E value) { - return (value >= MinEnumValue) && (value <= MaxEnumValue); - } - - // Converts a value to/from an index into |enums_|. - - static size_t ToIndex(E value) { - DCHECK_GE(value, MinEnumValue); - DCHECK_LE(value, MaxEnumValue); - return value - MinEnumValue; - } - - static E FromIndex(size_t i) { - DCHECK_LT(i, kValueCount); - return static_cast<E>(MinEnumValue + i); - } - - EnumBitSet enums_; -}; - -template <typename E, E MinEnumValue, E MaxEnumValue> -const E EnumSet<E, MinEnumValue, MaxEnumValue>::kMinValue; - -template <typename E, E MinEnumValue, E MaxEnumValue> -const E EnumSet<E, MinEnumValue, MaxEnumValue>::kMaxValue; - -template <typename E, E MinEnumValue, E MaxEnumValue> -const size_t EnumSet<E, MinEnumValue, MaxEnumValue>::kValueCount; - -// The usual set operations. - -template <typename E, E Min, E Max> -EnumSet<E, Min, Max> Union(EnumSet<E, Min, Max> set1, - EnumSet<E, Min, Max> set2) { - return EnumSet<E, Min, Max>(set1.enums_ | set2.enums_); -} - -template <typename E, E Min, E Max> -EnumSet<E, Min, Max> Intersection(EnumSet<E, Min, Max> set1, - EnumSet<E, Min, Max> set2) { - return EnumSet<E, Min, Max>(set1.enums_ & set2.enums_); -} - -template <typename E, E Min, E Max> -EnumSet<E, Min, Max> Difference(EnumSet<E, Min, Max> set1, - EnumSet<E, Min, Max> set2) { - return EnumSet<E, Min, Max>(set1.enums_ & ~set2.enums_); -} - -} // namespace browser_sync - -#endif // CHROME_BROWSER_SYNC_UTIL_ENUM_SET_H_ diff --git a/chrome/browser/sync/util/enum_set_unittest.cc b/chrome/browser/sync/util/enum_set_unittest.cc deleted file mode 100644 index 6a8eecc..0000000 --- a/chrome/browser/sync/util/enum_set_unittest.cc +++ /dev/null @@ -1,195 +0,0 @@ -// Copyright (c) 2011 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 "chrome/browser/sync/util/enum_set.h" - -#include "base/basictypes.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace browser_sync { -namespace { - -enum TestEnum { - TEST_0, - TEST_MIN = TEST_0, - TEST_1, - TEST_2, - TEST_3, - TEST_4, - TEST_MAX = TEST_4, - TEST_5 -}; - -typedef EnumSet<TestEnum, TEST_MIN, TEST_MAX> TestEnumSet; - -class EnumSetTest : public ::testing::Test {}; - -TEST_F(EnumSetTest, ClassConstants) { - TestEnumSet enums; - EXPECT_EQ(TEST_MIN, TestEnumSet::kMinValue); - EXPECT_EQ(TEST_MAX, TestEnumSet::kMaxValue); - EXPECT_EQ(static_cast<size_t>(5), TestEnumSet::kValueCount); -} - -TEST_F(EnumSetTest, DefaultConstructor) { - const TestEnumSet enums; - EXPECT_TRUE(enums.Empty()); - EXPECT_EQ(static_cast<size_t>(0), enums.Size()); - EXPECT_FALSE(enums.Has(TEST_0)); - EXPECT_FALSE(enums.Has(TEST_1)); - EXPECT_FALSE(enums.Has(TEST_2)); - EXPECT_FALSE(enums.Has(TEST_3)); - EXPECT_FALSE(enums.Has(TEST_4)); -} - -TEST_F(EnumSetTest, OneArgConstructor) { - const TestEnumSet enums(TEST_3); - EXPECT_FALSE(enums.Empty()); - EXPECT_EQ(static_cast<size_t>(1), enums.Size()); - EXPECT_FALSE(enums.Has(TEST_0)); - EXPECT_FALSE(enums.Has(TEST_1)); - EXPECT_FALSE(enums.Has(TEST_2)); - EXPECT_TRUE(enums.Has(TEST_3)); - EXPECT_FALSE(enums.Has(TEST_4)); -} - -TEST_F(EnumSetTest, TwoArgConstructor) { - const TestEnumSet enums(TEST_3, TEST_1); - EXPECT_FALSE(enums.Empty()); - EXPECT_EQ(static_cast<size_t>(2), enums.Size()); - EXPECT_FALSE(enums.Has(TEST_0)); - EXPECT_TRUE(enums.Has(TEST_1)); - EXPECT_FALSE(enums.Has(TEST_2)); - EXPECT_TRUE(enums.Has(TEST_3)); - EXPECT_FALSE(enums.Has(TEST_4)); -} - -TEST_F(EnumSetTest, ThreeArgConstructor) { - const TestEnumSet enums(TEST_3, TEST_1, TEST_0); - EXPECT_FALSE(enums.Empty()); - EXPECT_EQ(static_cast<size_t>(3), enums.Size()); - EXPECT_TRUE(enums.Has(TEST_0)); - EXPECT_TRUE(enums.Has(TEST_1)); - EXPECT_FALSE(enums.Has(TEST_2)); - EXPECT_TRUE(enums.Has(TEST_3)); - EXPECT_FALSE(enums.Has(TEST_4)); -} - -TEST_F(EnumSetTest, All) { - const TestEnumSet enums(TestEnumSet::All()); - EXPECT_FALSE(enums.Empty()); - EXPECT_EQ(static_cast<size_t>(5), enums.Size()); - EXPECT_TRUE(enums.Has(TEST_0)); - EXPECT_TRUE(enums.Has(TEST_1)); - EXPECT_TRUE(enums.Has(TEST_2)); - EXPECT_TRUE(enums.Has(TEST_3)); - EXPECT_TRUE(enums.Has(TEST_4)); -} - -TEST_F(EnumSetTest, Put) { - TestEnumSet enums(TEST_3); - enums.Put(TEST_2); - EXPECT_TRUE(enums.Equals(TestEnumSet(TEST_2, TEST_3))); - enums.Put(TEST_4); - EXPECT_TRUE(enums.Equals(TestEnumSet(TEST_2, TEST_3, TEST_4))); -} - -TEST_F(EnumSetTest, PutAll) { - TestEnumSet enums(TEST_3, TEST_4); - enums.PutAll(TestEnumSet(TEST_2, TEST_3)); - EXPECT_TRUE(enums.Equals(TestEnumSet(TEST_2, TEST_3, TEST_4))); -} - -TEST_F(EnumSetTest, RetainAll) { - TestEnumSet enums(TEST_3, TEST_4); - enums.RetainAll(TestEnumSet(TEST_2, TEST_3)); - EXPECT_TRUE(enums.Equals(TestEnumSet(TEST_3))); -} - -TEST_F(EnumSetTest, Remove) { - TestEnumSet enums(TEST_3, TEST_4); - enums.Remove(TEST_0); - enums.Remove(TEST_2); - EXPECT_TRUE(enums.Equals(TestEnumSet(TEST_3, TEST_4))); - enums.Remove(TEST_3); - EXPECT_TRUE(enums.Equals(TestEnumSet(TEST_4))); - enums.Remove(TEST_4); - enums.Remove(TEST_5); - EXPECT_TRUE(enums.Empty()); -} - -TEST_F(EnumSetTest, RemoveAll) { - TestEnumSet enums(TEST_3, TEST_4); - enums.RemoveAll(TestEnumSet(TEST_2, TEST_3)); - EXPECT_TRUE(enums.Equals(TestEnumSet(TEST_4))); -} - -TEST_F(EnumSetTest, Clear) { - TestEnumSet enums(TEST_3, TEST_4); - enums.Clear(); - EXPECT_TRUE(enums.Empty()); -} - -TEST_F(EnumSetTest, Has) { - const TestEnumSet enums(TEST_3, TEST_4); - EXPECT_FALSE(enums.Has(TEST_0)); - EXPECT_FALSE(enums.Has(TEST_1)); - EXPECT_FALSE(enums.Has(TEST_2)); - EXPECT_TRUE(enums.Has(TEST_3)); - EXPECT_TRUE(enums.Has(TEST_4)); - EXPECT_FALSE(enums.Has(TEST_5)); -} - -TEST_F(EnumSetTest, HasAll) { - const TestEnumSet enums1(TEST_3, TEST_4); - const TestEnumSet enums2(TEST_2, TEST_3); - const TestEnumSet enums3 = Union(enums1, enums2); - EXPECT_TRUE(enums1.HasAll(enums1)); - EXPECT_FALSE(enums1.HasAll(enums2)); - EXPECT_FALSE(enums1.HasAll(enums3)); - - EXPECT_FALSE(enums2.HasAll(enums1)); - EXPECT_TRUE(enums2.HasAll(enums2)); - EXPECT_FALSE(enums2.HasAll(enums3)); - - EXPECT_TRUE(enums3.HasAll(enums1)); - EXPECT_TRUE(enums3.HasAll(enums2)); - EXPECT_TRUE(enums3.HasAll(enums3)); -} - -TEST_F(EnumSetTest, Iterators) { - const TestEnumSet enums1(TEST_3, TEST_4); - TestEnumSet enums2; - for (TestEnumSet::Iterator it = enums1.First(); it.Good(); it.Inc()) { - enums2.Put(it.Get()); - } - EXPECT_TRUE(enums1.Equals(enums2)); -} - -TEST_F(EnumSetTest, Union) { - const TestEnumSet enums1(TEST_3, TEST_4); - const TestEnumSet enums2(TEST_2, TEST_3); - const TestEnumSet enums3 = Union(enums1, enums2); - - EXPECT_TRUE(enums3.Equals(TestEnumSet(TEST_2, TEST_3, TEST_4))); -} - -TEST_F(EnumSetTest, Intersection) { - const TestEnumSet enums1(TEST_3, TEST_4); - const TestEnumSet enums2(TEST_2, TEST_3); - const TestEnumSet enums3 = Intersection(enums1, enums2); - - EXPECT_TRUE(enums3.Equals(TestEnumSet(TEST_3))); -} - -TEST_F(EnumSetTest, Difference) { - const TestEnumSet enums1(TEST_3, TEST_4); - const TestEnumSet enums2(TEST_2, TEST_3); - const TestEnumSet enums3 = Difference(enums1, enums2); - - EXPECT_TRUE(enums3.Equals(TestEnumSet(TEST_4))); -} - -} // namespace -} // namespace browser_sync diff --git a/chrome/browser/sync/util/extensions_activity_monitor.cc b/chrome/browser/sync/util/extensions_activity_monitor.cc deleted file mode 100644 index 967385f..0000000 --- a/chrome/browser/sync/util/extensions_activity_monitor.cc +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (c) 2012 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 "chrome/browser/sync/util/extensions_activity_monitor.h" - -namespace browser_sync { - -ExtensionsActivityMonitor::Record::Record() - : bookmark_write_count(0U) {} - -ExtensionsActivityMonitor::Record::~Record() {} - -ExtensionsActivityMonitor::~ExtensionsActivityMonitor() {} - -} // namespace browser_sync diff --git a/chrome/browser/sync/util/extensions_activity_monitor.h b/chrome/browser/sync/util/extensions_activity_monitor.h deleted file mode 100644 index 2a1d666..0000000 --- a/chrome/browser/sync/util/extensions_activity_monitor.h +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright (c) 2012 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. - -#ifndef CHROME_BROWSER_SYNC_UTIL_EXTENSIONS_ACTIVITY_MONITOR_H_ -#define CHROME_BROWSER_SYNC_UTIL_EXTENSIONS_ACTIVITY_MONITOR_H_ -#pragma once - -#include <map> -#include <string> - -#include "base/basictypes.h" - -namespace browser_sync { - -// An interface to monitor usage of extensions APIs to send to sync -// servers, with the ability to purge data once sync servers have -// acknowledged it (successful commit response). -// -// All abstract methods are called from the sync thread. -class ExtensionsActivityMonitor { - public: - // A data record of activity performed by extension |extension_id|. - struct Record { - Record(); - ~Record(); - - // The human-readable ID identifying the extension responsible - // for the activity reported in this Record. - std::string extension_id; - - // How many times the extension successfully invoked a write - // operation through the bookmarks API since the last CommitMessage. - uint32 bookmark_write_count; - }; - - typedef std::map<std::string, Record> Records; - - // Fill |buffer| with all current records and then clear the - // internal records. - virtual void GetAndClearRecords(Records* buffer) = 0; - - // Merge |records| with the current set of records, adding the - // bookmark write counts for common Records. - virtual void PutRecords(const Records& records) = 0; - - protected: - virtual ~ExtensionsActivityMonitor(); -}; - -} // namespace browser_sync - -#endif // CHROME_BROWSER_SYNC_UTIL_EXTENSIONS_ACTIVITY_MONITOR_H_ diff --git a/chrome/browser/sync/util/get_session_name.cc b/chrome/browser/sync/util/get_session_name.cc deleted file mode 100644 index e861042..0000000 --- a/chrome/browser/sync/util/get_session_name.cc +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (c) 2012 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 "chrome/browser/sync/util/get_session_name.h" - -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/callback.h" -#include "base/location.h" -#include "base/sys_info.h" -#include "base/task_runner.h" - -#if defined(OS_LINUX) -#include "base/linux_util.h" -#elif defined(OS_MACOSX) -#include "chrome/browser/sync/util/get_session_name_mac.h" -#elif defined(OS_WIN) -#include "chrome/browser/sync/util/get_session_name_win.h" -#endif - -namespace browser_sync { - -namespace { - -std::string GetSessionNameSynchronously() { - std::string session_name; -#if defined(OS_CHROMEOS) - session_name = "Chromebook"; -#elif defined(OS_LINUX) - session_name = base::GetLinuxDistro(); -#elif defined(OS_MACOSX) - session_name = internal::GetHardwareModelName(); -#elif defined(OS_WIN) - session_name = internal::GetComputerName(); -#endif - - if (session_name == "Unknown" || session_name.empty()) - session_name = base::SysInfo::OperatingSystemName(); - - return session_name; -} - -void FillSessionName(std::string* session_name) { - *session_name = GetSessionNameSynchronously(); -} - -void OnSessionNameFilled( - const base::Callback<void(const std::string&)>& done_callback, - std::string* session_name) { - done_callback.Run(*session_name); -} - -} // namespace - -void GetSessionName( - const scoped_refptr<base::TaskRunner>& task_runner, - const base::Callback<void(const std::string&)>& done_callback) { - std::string* session_name = new std::string(); - task_runner->PostTaskAndReply( - FROM_HERE, - base::Bind(&FillSessionName, - base::Unretained(session_name)), - base::Bind(&OnSessionNameFilled, - done_callback, - base::Owned(session_name))); -} - -std::string GetSessionNameSynchronouslyForTesting() { - return GetSessionNameSynchronously(); -} - -} // namespace browser_sync diff --git a/chrome/browser/sync/util/get_session_name.h b/chrome/browser/sync/util/get_session_name.h deleted file mode 100644 index a4df65d..0000000 --- a/chrome/browser/sync/util/get_session_name.h +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) 2012 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. - -#ifndef CHROME_BROWSER_SYNC_UTIL_GET_SESSION_NAME_H_ -#define CHROME_BROWSER_SYNC_UTIL_GET_SESSION_NAME_H_ -#pragma once - -#include <string> - -#include "base/callback_forward.h" -#include "base/memory/ref_counted.h" - -namespace base { -class TaskRunner; -} // namespace base - -namespace browser_sync { - -void GetSessionName( - const scoped_refptr<base::TaskRunner>& task_runner, - const base::Callback<void(const std::string&)>& done_callback); - -std::string GetSessionNameSynchronouslyForTesting(); - -} // namespace browser_sync - -#endif // CHROME_BROWSER_SYNC_UTIL_GET_SESSION_NAME_H_ diff --git a/chrome/browser/sync/util/get_session_name_mac.h b/chrome/browser/sync/util/get_session_name_mac.h deleted file mode 100644 index 4b784de..0000000 --- a/chrome/browser/sync/util/get_session_name_mac.h +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) 2012 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. - -#ifndef CHROME_BROWSER_SYNC_UTIL_GET_SESSION_NAME_MAC_H_ -#define CHROME_BROWSER_SYNC_UTIL_GET_SESSION_NAME_MAC_H_ -#pragma once - -#include <string> - -namespace browser_sync { -namespace internal { - -// Returns the Hardware model name, without trailing numbers, if -// possible. See http://www.cocoadev.com/index.pl?MacintoshModels for -// an example list of models. If an error occurs trying to read the -// model, this simply returns "Unknown". -std::string GetHardwareModelName(); - -} // namespace internal -} // namespace browser_sync - -#endif // CHROME_BROWSER_SYNC_UTIL_GET_SESSION_NAME_MAC_H_ diff --git a/chrome/browser/sync/util/get_session_name_mac.mm b/chrome/browser/sync/util/get_session_name_mac.mm deleted file mode 100644 index 379ce3b..0000000 --- a/chrome/browser/sync/util/get_session_name_mac.mm +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) 2012 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 "chrome/browser/sync/util/get_session_name_mac.h" - -#import <Foundation/Foundation.h> -#import <SystemConfiguration/SCDynamicStoreCopySpecific.h> -#include <sys/sysctl.h> // sysctlbyname() - -#include "base/mac/foundation_util.h" -#include "base/mac/mac_util.h" -#include "base/memory/scoped_nsobject.h" -#include "base/string_util.h" -#include "base/sys_info.h" -#include "base/sys_string_conversions.h" - -@interface NSHost(SnowLeopardAPI) -- (NSString*)localizedName; -@end - -namespace browser_sync { -namespace internal { - -std::string GetHardwareModelName() { - NSHost* myHost = [NSHost currentHost]; - if ([myHost respondsToSelector:@selector(localizedName)]) - return base::SysNSStringToUTF8([myHost localizedName]); - - // Fallback for 10.5 - scoped_nsobject<NSString> computerName(base::mac::CFToNSCast( - SCDynamicStoreCopyComputerName(NULL, NULL))); - if (computerName.get() != NULL) - return base::SysNSStringToUTF8(computerName.get()); - - // If all else fails, return to using a slightly nicer version of the - // hardware model. - char modelBuffer[256]; - size_t length = sizeof(modelBuffer); - if (!sysctlbyname("hw.model", modelBuffer, &length, NULL, 0)) { - for (size_t i = 0; i < length; i++) { - if (IsAsciiDigit(modelBuffer[i])) - return std::string(modelBuffer, 0, i); - } - return std::string(modelBuffer, 0, length); - } - return "Unknown"; -} - -} // namespace internal -} // namespace browser_sync diff --git a/chrome/browser/sync/util/get_session_name_unittest.cc b/chrome/browser/sync/util/get_session_name_unittest.cc deleted file mode 100644 index a0bfe76..0000000 --- a/chrome/browser/sync/util/get_session_name_unittest.cc +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) 2012 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 <string> - -#include "base/bind.h" -#include "base/message_loop.h" -#include "chrome/browser/sync/util/get_session_name.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace browser_sync { - -namespace { - -class GetSessionNameTest : public ::testing::Test { - public: - void SetSessionNameAndQuit(const std::string& session_name) { - session_name_ = session_name; - message_loop_.Quit(); - } - - protected: - MessageLoop message_loop_; - std::string session_name_; -}; - -// Call GetSessionNameSynchronouslyForTesting and make sure its return -// value looks sane. -TEST_F(GetSessionNameTest, GetSessionNameSynchronously) { - const std::string& session_name = GetSessionNameSynchronouslyForTesting(); - EXPECT_FALSE(session_name.empty()); -} - -// Calls GetSessionName and runs the message loop until it comes back -// with a session name. Makes sure the returned session name is equal -// to the return value of GetSessionNameSynchronouslyForTesting(). -TEST_F(GetSessionNameTest, GetSessionName) { - GetSessionName(message_loop_.message_loop_proxy(), - base::Bind(&GetSessionNameTest::SetSessionNameAndQuit, - base::Unretained(this))); - message_loop_.Run(); - EXPECT_EQ(session_name_, GetSessionNameSynchronouslyForTesting()); -} - -} // namespace - -} // namespace browser_sync diff --git a/chrome/browser/sync/util/get_session_name_win.cc b/chrome/browser/sync/util/get_session_name_win.cc deleted file mode 100644 index f4012a2..0000000 --- a/chrome/browser/sync/util/get_session_name_win.cc +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) 2012 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 "chrome/browser/sync/util/get_session_name_win.h" - -#include <windows.h> - -namespace browser_sync { -namespace internal { - -std::string GetComputerName() { - char computer_name[MAX_COMPUTERNAME_LENGTH + 1]; - DWORD size = sizeof(computer_name); - if (GetComputerNameA(computer_name, &size)) - return computer_name; - return std::string(); -} - -} // namespace internal -} // namespace browser_sync diff --git a/chrome/browser/sync/util/get_session_name_win.h b/chrome/browser/sync/util/get_session_name_win.h deleted file mode 100644 index 45dc44b..0000000 --- a/chrome/browser/sync/util/get_session_name_win.h +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) 2012 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. - -#ifndef CHROME_BROWSER_SYNC_UTIL_GET_SESSION_NAME_WIN_H_ -#define CHROME_BROWSER_SYNC_UTIL_GET_SESSION_NAME_WIN_H_ -#pragma once - -#include <string> - -namespace browser_sync { -namespace internal { - -std::string GetComputerName(); - -} // namespace internal -} // namespace browser_sync - -#endif // CHROME_BROWSER_SYNC_UTIL_GET_SESSION_NAME_WIN_H_ diff --git a/chrome/browser/sync/util/immutable.h b/chrome/browser/sync/util/immutable.h deleted file mode 100644 index 8bb03c7..0000000 --- a/chrome/browser/sync/util/immutable.h +++ /dev/null @@ -1,262 +0,0 @@ -// Copyright (c) 2011 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. - -// Immutable<T> provides an easy, cheap, and thread-safe way to pass -// large immutable data around. -// -// For example, consider the following code: -// -// typedef std::vector<LargeObject> LargeObjectList; -// -// void ProcessStuff(const LargeObjectList& stuff) { -// for (LargeObjectList::const_iterator it = stuff.begin(); -// it != stuff.end(); ++it) { -// ... process it ... -// } -// } -// -// ... -// -// LargeObjectList my_stuff; -// ... fill my_stuff with lots of LargeObjects ... -// some_loop->PostTask(FROM_HERE, base::Bind(&ProcessStuff, my_stuff)); -// -// The last line incurs the cost of copying my_stuff, which is -// undesirable. Here's the above code re-written using Immutable<T>: -// -// void ProcessStuff( -// const browser_sync::Immutable<LargeObjectList>& stuff) { -// for (LargeObjectList::const_iterator it = stuff.Get().begin(); -// it != stuff.Get().end(); ++it) { -// ... process it ... -// } -// } -// -// ... -// -// LargeObjectList my_stuff; -// ... fill my_stuff with lots of LargeObjects ... -// some_loop->PostTask( -// FROM_HERE, base::Bind(&ProcessStuff, MakeImmutable(&my_stuff))); -// -// The last line, which resets my_stuff to a default-initialized -// state, incurs only the cost of a swap of LargeObjectLists, which is -// O(1) for most STL container implementations. The data in my_stuff -// is ref-counted (thread-safely), so it is freed as soon as -// ProcessStuff is finished. -// -// NOTE: By default, Immutable<T> relies on ADL -// (http://en.wikipedia.org/wiki/Argument-dependent_name_lookup) to -// find a swap() function for T, falling back to std::swap() when -// necessary. If you overload swap() for your type in its namespace, -// or if you specialize std::swap() for your type, (see -// http://stackoverflow.com/questions/11562/how-to-overload-stdswap -// for discussion) Immutable<T> should be able to find it. -// -// Alternatively, you could explicitly control which swap function is -// used by providing your own traits class or using one of the -// pre-defined ones below. See comments on traits below for details. -// -// NOTE: Some complexity is necessary in order to use Immutable<T> -// with forward-declared types. See comments on traits below for -// details. - -#ifndef CHROME_BROWSER_SYNC_UTIL_IMMUTABLE_H_ -#define CHROME_BROWSER_SYNC_UTIL_IMMUTABLE_H_ -#pragma once - -// For std::swap(). -#include <algorithm> - -#include "base/basictypes.h" -#include "base/memory/ref_counted.h" - -namespace browser_sync { - -namespace internal { -// This class is part of the Immutable implementation. DO NOT USE -// THIS CLASS DIRECTLY YOURSELF. - -template <typename T, typename Traits> -class ImmutableCore - : public base::RefCountedThreadSafe<ImmutableCore<T, Traits> > { - public: - // wrapper_ is always explicitly default-initialized to handle - // primitive types and the case where Traits::Wrapper == T. - - ImmutableCore() : wrapper_() { - Traits::InitializeWrapper(&wrapper_); - } - - explicit ImmutableCore(T* t) : wrapper_() { - Traits::InitializeWrapper(&wrapper_); - Traits::Swap(Traits::UnwrapMutable(&wrapper_), t); - } - - const T& Get() const { - return Traits::Unwrap(wrapper_); - } - - private: - ~ImmutableCore() { - Traits::DestroyWrapper(&wrapper_); - } - friend class base::RefCountedThreadSafe<ImmutableCore<T, Traits> >; - - // This is semantically const, but we can't mark it a such as we - // modify it in the constructor. - typename Traits::Wrapper wrapper_; - - DISALLOW_COPY_AND_ASSIGN(ImmutableCore); -}; - -} // namespace internal - -// Traits usage notes -// ------------------ -// The most common reason to use your own traits class is to provide -// your own swap method. First, consider the pre-defined traits -// classes HasSwapMemFn{ByRef,ByPtr} below. If neither of those work, -// then define your own traits class inheriting from -// DefaultImmutableTraits<YourType> (to pick up the defaults for -// everything else) and provide your own Swap() method. -// -// Another reason to use your own traits class is to be able to use -// Immutable<T> with a forward-declared type (important for protobuf -// classes, when you want to avoid headers pulling in generated -// headers). (This is why the Traits::Wrapper type exists; normally, -// Traits::Wrapper is just T itself, but that needs to be changed for -// forward-declared types.) -// -// For example, if you want to do this: -// -// my_class.h -// ---------- -// #include ".../immutable.h" -// -// // Forward declaration. -// class SomeOtherType; -// -// class MyClass { -// ... -// private: -// // Doesn't work, as defaults traits class needs SomeOtherType's -// // definition to be visible. -// Immutable<SomeOtherType> foo_; -// }; -// -// You'll have to do this: -// -// my_class.h -// ---------- -// #include ".../immutable.h" -// -// // Forward declaration. -// class SomeOtherType; -// -// class MyClass { -// ... -// private: -// struct ImmutableSomeOtherTypeTraits { -// // scoped_ptr<SomeOtherType> won't work here, either. -// typedef SomeOtherType* Wrapper; -// -// static void InitializeWrapper(Wrapper* wrapper); -// -// static void DestroyWrapper(Wrapper* wrapper); -// ... -// }; -// -// typedef Immutable<SomeOtherType, ImmutableSomeOtherTypeTraits> -// ImmutableSomeOtherType; -// -// ImmutableSomeOtherType foo_; -// }; -// -// my_class.cc -// ----------- -// #include ".../some_other_type.h" -// -// void MyClass::ImmutableSomeOtherTypeTraits::InitializeWrapper( -// Wrapper* wrapper) { -// *wrapper = new SomeOtherType(); -// } -// -// void MyClass::ImmutableSomeOtherTypeTraits::DestroyWrapper( -// Wrapper* wrapper) { -// delete *wrapper; -// } -// -// ... -// -// Also note that this incurs an additional memory allocation when you -// create an Immutable<SomeOtherType>. - -template <typename T> -struct DefaultImmutableTraits { - typedef T Wrapper; - - static void InitializeWrapper(Wrapper* wrapper) {} - - static void DestroyWrapper(Wrapper* wrapper) {} - - static const T& Unwrap(const Wrapper& wrapper) { return wrapper; } - - static T* UnwrapMutable(Wrapper* wrapper) { return wrapper; } - - static void Swap(T* t1, T* t2) { - // Uses ADL (see - // http://en.wikipedia.org/wiki/Argument-dependent_name_lookup). - using std::swap; - swap(*t1, *t2); - } -}; - -// Most STL containers have by-reference swap() member functions, -// although they usually already overload std::swap() to use those. -template <typename T> -struct HasSwapMemFnByRef : public DefaultImmutableTraits<T> { - static void Swap(T* t1, T* t2) { - t1->swap(*t2); - } -}; - -// Most Google-style objects have by-pointer Swap() member functions -// (for example, generated protocol buffer classes). -template <typename T> -struct HasSwapMemFnByPtr : public DefaultImmutableTraits<T> { - static void Swap(T* t1, T* t2) { - t1->Swap(t2); - } -}; - -template <typename T, typename Traits = DefaultImmutableTraits<T> > -class Immutable { - public: - // Puts the underlying object in a default-initialized state. - Immutable() : core_(new internal::ImmutableCore<T, Traits>()) {} - - // Copy constructor and assignment welcome. - - // Resets |t| to a default-initialized state. - explicit Immutable(T* t) - : core_(new internal::ImmutableCore<T, Traits>(t)) {} - - const T& Get() const { - return core_->Get(); - } - - private: - scoped_refptr<const internal::ImmutableCore<T, Traits> > core_; -}; - -// Helper function to avoid having to write out template arguments. -template <typename T> -Immutable<T> MakeImmutable(T* t) { - return Immutable<T>(t); -} - -} // namespace browser_sync - -#endif // CHROME_BROWSER_SYNC_UTIL_IMMUTABLE_H_ diff --git a/chrome/browser/sync/util/immutable_unittest.cc b/chrome/browser/sync/util/immutable_unittest.cc deleted file mode 100644 index dc6553b..0000000 --- a/chrome/browser/sync/util/immutable_unittest.cc +++ /dev/null @@ -1,244 +0,0 @@ -// Copyright (c) 2011 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 "chrome/browser/sync/util/immutable.h" - -#include <algorithm> -#include <cstddef> -#include <deque> -#include <list> -#include <set> -#include <string> -#include <vector> - -#include "base/basictypes.h" -#include "base/memory/ref_counted.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace browser_sync { - -// Helper class that keeps track of the token passed in at -// construction and how many times that token is copied. -class TokenCore : public base::RefCounted<TokenCore> { - public: - explicit TokenCore(const char* token) : token_(token), copy_count_(0) {} - - const char* GetToken() const { return token_; } - - void RecordCopy() { ++copy_count_; } - - int GetCopyCount() const { return copy_count_; } - - private: - friend class base::RefCounted<TokenCore>; - - ~TokenCore() {} - - const char* const token_; - int copy_count_; -}; - -enum SwapBehavior { - USE_DEFAULT_SWAP, - USE_FAST_SWAP_VIA_ADL, - USE_FAST_SWAP_VIA_SPECIALIZATION -}; - -const char kEmptyToken[] = "<empty token>"; - -// Base class for various token classes, differing in swap behavior. -template <SwapBehavior> -class TokenBase { - public: - TokenBase() : core_(new TokenCore(kEmptyToken)) {} - - explicit TokenBase(const char* token) : core_(new TokenCore(token)) {} - - TokenBase(const TokenBase& other) : core_(other.core_) { - core_->RecordCopy(); - } - - TokenBase& operator=(const TokenBase& other) { - core_ = other.core_; - core_->RecordCopy(); - return *this; - } - - const char* GetToken() const { - return core_->GetToken(); - } - - int GetCopyCount() const { - return core_->GetCopyCount(); - } - - // For associative containers. - bool operator<(const TokenBase& other) const { - return std::string(GetToken()) < std::string(other.GetToken()); - } - - // STL-style swap. - void swap(TokenBase& other) { - using std::swap; - swap(other.core_, core_); - } - - // Google-style swap. - void Swap(TokenBase* other) { - using std::swap; - swap(other->core_, core_); - } - - private: - scoped_refptr<TokenCore> core_; -}; - -typedef TokenBase<USE_DEFAULT_SWAP> Token; -typedef TokenBase<USE_FAST_SWAP_VIA_ADL> ADLToken; -typedef TokenBase<USE_FAST_SWAP_VIA_SPECIALIZATION> SpecializationToken; - -void swap(ADLToken& t1, ADLToken& t2) { - t1.Swap(&t2); -} - -} // namespace browser_sync - -// Allowed by the standard (17.4.3.1/1). -namespace std { - -template <> -void swap(browser_sync::SpecializationToken& t1, - browser_sync::SpecializationToken& t2) { - t1.Swap(&t2); -} - -} // namespace - -namespace browser_sync { -namespace { - -class ImmutableTest : public ::testing::Test {}; - -TEST_F(ImmutableTest, Int) { - int x = 5; - Immutable<int> ix(&x); - EXPECT_EQ(5, ix.Get()); - EXPECT_EQ(0, x); -} - -TEST_F(ImmutableTest, IntCopy) { - int x = 5; - Immutable<int> ix = Immutable<int>(&x); - EXPECT_EQ(5, ix.Get()); - EXPECT_EQ(0, x); -} - -TEST_F(ImmutableTest, IntAssign) { - int x = 5; - Immutable<int> ix; - EXPECT_EQ(0, ix.Get()); - ix = Immutable<int>(&x); - EXPECT_EQ(5, ix.Get()); - EXPECT_EQ(0, x); -} - -TEST_F(ImmutableTest, IntMakeImmutable) { - int x = 5; - Immutable<int> ix = MakeImmutable(&x); - EXPECT_EQ(5, ix.Get()); - EXPECT_EQ(0, x); -} - -template <typename T, typename ImmutableT> -void RunTokenTest(const char* token, bool expect_copies) { - SCOPED_TRACE(token); - T t(token); - EXPECT_EQ(token, t.GetToken()); - EXPECT_EQ(0, t.GetCopyCount()); - - ImmutableT immutable_t(&t); - EXPECT_EQ(token, immutable_t.Get().GetToken()); - EXPECT_EQ(kEmptyToken, t.GetToken()); - EXPECT_EQ(expect_copies, immutable_t.Get().GetCopyCount() > 0); - EXPECT_EQ(expect_copies, t.GetCopyCount() > 0); -} - -TEST_F(ImmutableTest, Token) { - RunTokenTest<Token, Immutable<Token> >("Token", true /* expect_copies */); -} - -TEST_F(ImmutableTest, TokenSwapMemFnByRef) { - RunTokenTest<Token, Immutable<Token, HasSwapMemFnByRef<Token> > >( - "TokenSwapMemFnByRef", false /* expect_copies */); -} - -TEST_F(ImmutableTest, TokenSwapMemFnByPtr) { - RunTokenTest<Token, Immutable<Token, HasSwapMemFnByPtr<Token> > >( - "TokenSwapMemFnByPtr", false /* expect_copies */); -} - -TEST_F(ImmutableTest, ADLToken) { - RunTokenTest<ADLToken, Immutable<ADLToken> >( - "ADLToken", false /* expect_copies */); -} - -TEST_F(ImmutableTest, SpecializationToken) { - RunTokenTest<SpecializationToken, Immutable<SpecializationToken> >( - "SpecializationToken", false /* expect_copies */); -} - -template <typename C, typename ImmutableC> -void RunTokenContainerTest(const char* token) { - SCOPED_TRACE(token); - const Token tokens[] = { Token(), Token(token) }; - const size_t token_count = arraysize(tokens); - C c(tokens, tokens + token_count); - const int copy_count = c.begin()->GetCopyCount(); - EXPECT_GT(copy_count, 0); - for (typename C::const_iterator it = c.begin(); it != c.end(); ++it) { - EXPECT_EQ(copy_count, it->GetCopyCount()); - } - - // Make sure that making the container immutable doesn't incur any - // copies of the tokens. - ImmutableC immutable_c(&c); - EXPECT_TRUE(c.empty()); - ASSERT_EQ(token_count, immutable_c.Get().size()); - int i = 0; - for (typename C::const_iterator it = c.begin(); it != c.end(); ++it) { - EXPECT_EQ(tokens[i].GetToken(), it->GetToken()); - EXPECT_EQ(copy_count, it->GetCopyCount()); - ++i; - } -} - -TEST_F(ImmutableTest, Vector) { - RunTokenContainerTest<std::vector<Token>, Immutable<std::vector<Token> > >( - "Vector"); -} - -TEST_F(ImmutableTest, VectorSwapMemFnByRef) { - RunTokenContainerTest< - std::vector<Token>, - Immutable<std::vector<Token>, HasSwapMemFnByRef<std::vector<Token> > > >( - "VectorSwapMemFnByRef"); -} - -TEST_F(ImmutableTest, Deque) { - RunTokenContainerTest<std::deque<Token>, Immutable<std::deque<Token> > >( - "Deque"); -} - -TEST_F(ImmutableTest, List) { - RunTokenContainerTest<std::list<Token>, Immutable<std::list<Token> > >( - "List"); -} - -TEST_F(ImmutableTest, Set) { - RunTokenContainerTest<std::set<Token>, Immutable<std::set<Token> > >( - "Set"); -} - -} // namespace -} // namespace browser_sync diff --git a/chrome/browser/sync/util/logging.cc b/chrome/browser/sync/util/logging.cc deleted file mode 100644 index 9601f58..0000000 --- a/chrome/browser/sync/util/logging.cc +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) 2011 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 "chrome/browser/sync/util/logging.h" - -#include "base/location.h" - -namespace browser_sync { - -bool VlogIsOnForLocation(const tracked_objects::Location& from_here, - int verbose_level) { - return (verbose_level <= - logging::GetVlogLevelHelper( - from_here.file_name(), ::strlen(from_here.file_name()))); -} - -} // namespace browser_sync diff --git a/chrome/browser/sync/util/logging.h b/chrome/browser/sync/util/logging.h deleted file mode 100644 index e14ac49..0000000 --- a/chrome/browser/sync/util/logging.h +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) 2011 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. - -#ifndef CHROME_BROWSER_SYNC_UTIL_LOGGING_H_ -#define CHROME_BROWSER_SYNC_UTIL_LOGGING_H_ -#pragma once - -#include "base/logging.h" - -// TODO(akalin): This probably belongs in base/ somewhere. - -namespace tracked_objects { -class Location; -} // namespace tracked_objects - -namespace browser_sync { - -bool VlogIsOnForLocation(const tracked_objects::Location& from_here, - int verbose_level); - -} // namespace browser_sync - -#define VLOG_LOC_STREAM(from_here, verbose_level) \ - logging::LogMessage(from_here.file_name(), from_here.line_number(), \ - -verbose_level).stream() - -#define DVLOG_LOC(from_here, verbose_level) \ - LAZY_STREAM( \ - VLOG_LOC_STREAM(from_here, verbose_level), \ - ::logging::DEBUG_MODE && \ - (VLOG_IS_ON(verbose_level) || \ - ::browser_sync::VlogIsOnForLocation(from_here, verbose_level))) \ - -#endif // CHROME_BROWSER_SYNC_UTIL_LOGGING_H_ diff --git a/chrome/browser/sync/util/nigori.cc b/chrome/browser/sync/util/nigori.cc deleted file mode 100644 index 799a3f4..0000000 --- a/chrome/browser/sync/util/nigori.cc +++ /dev/null @@ -1,256 +0,0 @@ -// Copyright (c) 2011 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 "chrome/browser/sync/util/nigori.h" - -#include <sstream> -#include <vector> - -#include "base/base64.h" -#include "base/logging.h" -#include "base/rand_util.h" -#include "base/string_util.h" -#include "base/sys_byteorder.h" -#include "crypto/encryptor.h" -#include "crypto/hmac.h" - -using base::Base64Encode; -using base::Base64Decode; -using base::RandInt; -using crypto::Encryptor; -using crypto::HMAC; -using crypto::SymmetricKey; - -namespace browser_sync { - -// NigoriStream simplifies the concatenation operation of the Nigori protocol. -class NigoriStream { - public: - // Append the big-endian representation of the length of |value| with 32 bits, - // followed by |value| itself to the stream. - NigoriStream& operator<<(const std::string& value) { - uint32 size = htonl(value.size()); - stream_.write((char *) &size, sizeof(uint32)); - stream_ << value; - return *this; - } - - // Append the big-endian representation of the length of |type| with 32 bits, - // followed by the big-endian representation of the value of |type|, with 32 - // bits, to the stream. - NigoriStream& operator<<(const Nigori::Type type) { - uint32 size = htonl(sizeof(uint32)); - stream_.write((char *) &size, sizeof(uint32)); - uint32 value = htonl(type); - stream_.write((char *) &value, sizeof(uint32)); - return *this; - } - - std::string str() { - return stream_.str(); - } - - private: - std::ostringstream stream_; -}; - -// static -const char Nigori::kSaltSalt[] = "saltsalt"; - -Nigori::Nigori() { -} - -Nigori::~Nigori() { -} - -bool Nigori::InitByDerivation(const std::string& hostname, - const std::string& username, - const std::string& password) { - NigoriStream salt_password; - salt_password << username << hostname; - - // Suser = PBKDF2(Username || Servername, "saltsalt", Nsalt, 8) - scoped_ptr<SymmetricKey> user_salt(SymmetricKey::DeriveKeyFromPassword( - SymmetricKey::HMAC_SHA1, salt_password.str(), - kSaltSalt, - kSaltIterations, - kSaltKeySizeInBits)); - DCHECK(user_salt.get()); - - std::string raw_user_salt; - if (!user_salt->GetRawKey(&raw_user_salt)) - return false; - - // Kuser = PBKDF2(P, Suser, Nuser, 16) - user_key_.reset(SymmetricKey::DeriveKeyFromPassword(SymmetricKey::AES, - password, raw_user_salt, kUserIterations, kDerivedKeySizeInBits)); - DCHECK(user_key_.get()); - - // Kenc = PBKDF2(P, Suser, Nenc, 16) - encryption_key_.reset(SymmetricKey::DeriveKeyFromPassword(SymmetricKey::AES, - password, raw_user_salt, kEncryptionIterations, kDerivedKeySizeInBits)); - DCHECK(encryption_key_.get()); - - // Kmac = PBKDF2(P, Suser, Nmac, 16) - mac_key_.reset(SymmetricKey::DeriveKeyFromPassword( - SymmetricKey::HMAC_SHA1, password, raw_user_salt, kSigningIterations, - kDerivedKeySizeInBits)); - DCHECK(mac_key_.get()); - - return user_key_.get() && encryption_key_.get() && mac_key_.get(); -} - -bool Nigori::InitByImport(const std::string& user_key, - const std::string& encryption_key, - const std::string& mac_key) { - user_key_.reset(SymmetricKey::Import(SymmetricKey::AES, user_key)); - DCHECK(user_key_.get()); - - encryption_key_.reset(SymmetricKey::Import(SymmetricKey::AES, - encryption_key)); - DCHECK(encryption_key_.get()); - - mac_key_.reset(SymmetricKey::Import(SymmetricKey::HMAC_SHA1, mac_key)); - DCHECK(mac_key_.get()); - - return user_key_.get() && encryption_key_.get() && mac_key_.get(); -} - -// Permute[Kenc,Kmac](type || name) -bool Nigori::Permute(Type type, const std::string& name, - std::string* permuted) const { - DCHECK_LT(0U, name.size()); - - NigoriStream plaintext; - plaintext << type << name; - - Encryptor encryptor; - if (!encryptor.Init(encryption_key_.get(), Encryptor::CBC, - std::string(kIvSize, 0))) - return false; - - std::string ciphertext; - if (!encryptor.Encrypt(plaintext.str(), &ciphertext)) - return false; - - std::string raw_mac_key; - if (!mac_key_->GetRawKey(&raw_mac_key)) - return false; - - HMAC hmac(HMAC::SHA256); - if (!hmac.Init(raw_mac_key)) - return false; - - std::vector<unsigned char> hash(kHashSize); - if (!hmac.Sign(ciphertext, &hash[0], hash.size())) - return false; - - std::string output; - output.assign(ciphertext); - output.append(hash.begin(), hash.end()); - - return Base64Encode(output, permuted); -} - -std::string GenerateRandomString(size_t size) { - // TODO(albertb): Use a secure random function. - std::string random(size, 0); - for (size_t i = 0; i < size; ++i) - random[i] = RandInt(0, 0xff); - return random; -} - -// Enc[Kenc,Kmac](value) -bool Nigori::Encrypt(const std::string& value, std::string* encrypted) const { - if (0U >= value.size()) - return false; - - std::string iv = GenerateRandomString(kIvSize); - - Encryptor encryptor; - if (!encryptor.Init(encryption_key_.get(), Encryptor::CBC, iv)) - return false; - - std::string ciphertext; - if (!encryptor.Encrypt(value, &ciphertext)) - return false; - - std::string raw_mac_key; - if (!mac_key_->GetRawKey(&raw_mac_key)) - return false; - - HMAC hmac(HMAC::SHA256); - if (!hmac.Init(raw_mac_key)) - return false; - - std::vector<unsigned char> hash(kHashSize); - if (!hmac.Sign(ciphertext, &hash[0], hash.size())) - return false; - - std::string output; - output.assign(iv); - output.append(ciphertext); - output.append(hash.begin(), hash.end()); - - return Base64Encode(output, encrypted); -} - -bool Nigori::Decrypt(const std::string& encrypted, std::string* value) const { - std::string input; - if (!Base64Decode(encrypted, &input)) - return false; - - if (input.size() < kIvSize * 2 + kHashSize) - return false; - - // The input is: - // * iv (16 bytes) - // * ciphertext (multiple of 16 bytes) - // * hash (32 bytes) - std::string iv(input.substr(0, kIvSize)); - std::string ciphertext(input.substr(kIvSize, - input.size() - (kIvSize + kHashSize))); - std::string hash(input.substr(input.size() - kHashSize, kHashSize)); - - std::string raw_mac_key; - if (!mac_key_->GetRawKey(&raw_mac_key)) - return false; - - HMAC hmac(HMAC::SHA256); - if (!hmac.Init(raw_mac_key)) - return false; - - std::vector<unsigned char> expected(kHashSize); - if (!hmac.Sign(ciphertext, &expected[0], expected.size())) - return false; - - if (hash.compare(0, hash.size(), - reinterpret_cast<char *>(&expected[0]), - expected.size())) - return false; - - Encryptor encryptor; - if (!encryptor.Init(encryption_key_.get(), Encryptor::CBC, iv)) - return false; - - std::string plaintext; - if (!encryptor.Decrypt(ciphertext, value)) - return false; - - return true; -} - -bool Nigori::ExportKeys(std::string* user_key, - std::string* encryption_key, - std::string* mac_key) const { - DCHECK(user_key); - DCHECK(encryption_key); - DCHECK(mac_key); - - return user_key_->GetRawKey(user_key) && - encryption_key_->GetRawKey(encryption_key) && - mac_key_->GetRawKey(mac_key); -} - -} // namespace browser_sync diff --git a/chrome/browser/sync/util/nigori.h b/chrome/browser/sync/util/nigori.h deleted file mode 100644 index 74fd6ec..0000000 --- a/chrome/browser/sync/util/nigori.h +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright (c) 2011 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. - -#ifndef CHROME_BROWSER_SYNC_UTIL_NIGORI_H_ -#define CHROME_BROWSER_SYNC_UTIL_NIGORI_H_ -#pragma once - -#include <string> - -#include "base/memory/scoped_ptr.h" -#include "crypto/symmetric_key.h" - -namespace browser_sync { - -// A (partial) implementation of Nigori, a protocol to securely store secrets in -// the cloud. This implementation does not support server authentication or -// assisted key derivation. -// -// To store secrets securely, use the |Permute| method to derive a lookup name -// for your secret (basically a map key), and |Encrypt| and |Decrypt| to store -// and retrieve the secret. -// -// TODO: Link to doc. -class Nigori { - public: - enum Type { - Password = 1, - }; - - Nigori(); - virtual ~Nigori(); - - // Initialize the client with the given |hostname|, |username| and |password|. - bool InitByDerivation(const std::string& hostname, - const std::string& username, - const std::string& password); - - // Initialize the client by importing the given keys instead of deriving new - // ones. - bool InitByImport(const std::string& user_key, - const std::string& encryption_key, - const std::string& mac_key); - - // Derives a secure lookup name from |type| and |name|. If |hostname|, - // |username| and |password| are kept constant, a given |type| and |name| pair - // always yields the same |permuted| value. Note that |permuted| will be - // Base64 encoded. - bool Permute(Type type, const std::string& name, std::string* permuted) const; - - // Encrypts |value|. Note that on success, |encrypted| will be Base64 - // encoded. - bool Encrypt(const std::string& value, std::string* encrypted) const; - - // Decrypts |value| into |decrypted|. It is assumed that |value| is Base64 - // encoded. - bool Decrypt(const std::string& value, std::string* decrypted) const; - - // Exports the raw derived keys. - bool ExportKeys(std::string* user_key, - std::string* encryption_key, - std::string* mac_key) const; - - static const char kSaltSalt[]; // The salt used to derive the user salt. - static const size_t kSaltKeySizeInBits = 128; - static const size_t kDerivedKeySizeInBits = 128; - static const size_t kIvSize = 16; - static const size_t kHashSize = 32; - - static const size_t kSaltIterations = 1001; - static const size_t kUserIterations = 1002; - static const size_t kEncryptionIterations = 1003; - static const size_t kSigningIterations = 1004; - - private: - scoped_ptr<crypto::SymmetricKey> user_key_; - scoped_ptr<crypto::SymmetricKey> encryption_key_; - scoped_ptr<crypto::SymmetricKey> mac_key_; -}; - -} // namespace browser_sync - -#endif // CHROME_BROWSER_SYNC_UTIL_NIGORI_H_ diff --git a/chrome/browser/sync/util/nigori_unittest.cc b/chrome/browser/sync/util/nigori_unittest.cc deleted file mode 100644 index 95afafe..0000000 --- a/chrome/browser/sync/util/nigori_unittest.cc +++ /dev/null @@ -1,170 +0,0 @@ -// Copyright (c) 2012 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 "chrome/browser/sync/util/nigori.h" - -#include <string> - -#include "base/memory/scoped_ptr.h" -#include "base/string_util.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace browser_sync { -namespace { - -TEST(SyncNigoriTest, Permute) { - Nigori nigori; - EXPECT_TRUE(nigori.InitByDerivation("example.com", "username", "password")); - - std::string permuted; - EXPECT_TRUE(nigori.Permute(Nigori::Password, "test name", - &permuted)); - - std::string expected = - "prewwdJj2PrGDczvmsHJEE5ndcCyVze8sY9kD5hjY/Tm" - "c5kOjXFK7zB3Ss4LlHjEDirMu+vh85JwHOnGrMVe+g=="; - EXPECT_EQ(expected, permuted); -} - -TEST(SyncNigoriTest, PermuteIsConstant) { - Nigori nigori1; - EXPECT_TRUE(nigori1.InitByDerivation("example.com", "username", "password")); - - std::string permuted1; - EXPECT_TRUE(nigori1.Permute(Nigori::Password, - "name", - &permuted1)); - - Nigori nigori2; - EXPECT_TRUE(nigori2.InitByDerivation("example.com", "username", "password")); - - std::string permuted2; - EXPECT_TRUE(nigori2.Permute(Nigori::Password, - "name", - &permuted2)); - - EXPECT_LT(0U, permuted1.size()); - EXPECT_EQ(permuted1, permuted2); -} - -TEST(SyncNigoriTest, EncryptDifferentIv) { - Nigori nigori; - EXPECT_TRUE(nigori.InitByDerivation("example.com", "username", "password")); - - std::string plaintext("value"); - - std::string encrypted1; - EXPECT_TRUE(nigori.Encrypt(plaintext, &encrypted1)); - - std::string encrypted2; - EXPECT_TRUE(nigori.Encrypt(plaintext, &encrypted2)); - - EXPECT_NE(encrypted1, encrypted2); -} - -TEST(SyncNigoriTest, Decrypt) { - Nigori nigori; - EXPECT_TRUE(nigori.InitByDerivation("example.com", "username", "password")); - - std::string encrypted = - "e7+JyS6ibj6F5qqvpseukNRTZ+oBpu5iuv2VYjOfrH1dNiFLNf7Ov0" - "kx/zicKFn0lJcbG1UmkNWqIuR4x+quDNVuLaZGbrJPhrJuj7cokCM="; - - std::string plaintext; - EXPECT_TRUE(nigori.Decrypt(encrypted, &plaintext)); - - std::string expected("test, test, 1, 2, 3"); - EXPECT_EQ(expected, plaintext); -} - -TEST(SyncNigoriTest, EncryptDecrypt) { - Nigori nigori; - EXPECT_TRUE(nigori.InitByDerivation("example.com", "username", "password")); - - std::string plaintext("value"); - - std::string encrypted; - EXPECT_TRUE(nigori.Encrypt(plaintext, &encrypted)); - - std::string decrypted; - EXPECT_TRUE(nigori.Decrypt(encrypted, &decrypted)); - - EXPECT_EQ(plaintext, decrypted); -} - -TEST(SyncNigoriTest, CorruptedIv) { - Nigori nigori; - EXPECT_TRUE(nigori.InitByDerivation("example.com", "username", "password")); - - std::string plaintext("test"); - - std::string encrypted; - EXPECT_TRUE(nigori.Encrypt(plaintext, &encrypted)); - - // Corrupt the IV by changing one of its byte. - encrypted[0] = (encrypted[0] == 'a' ? 'b' : 'a'); - - std::string decrypted; - EXPECT_TRUE(nigori.Decrypt(encrypted, &decrypted)); - - EXPECT_NE(plaintext, decrypted); -} - -TEST(SyncNigoriTest, CorruptedCiphertext) { - Nigori nigori; - EXPECT_TRUE(nigori.InitByDerivation("example.com", "username", "password")); - - std::string plaintext("test"); - - std::string encrypted; - EXPECT_TRUE(nigori.Encrypt(plaintext, &encrypted)); - - // Corrput the ciphertext by changing one of its bytes. - encrypted[Nigori::kIvSize + 10] = - (encrypted[Nigori::kIvSize + 10] == 'a' ? 'b' : 'a'); - - std::string decrypted; - EXPECT_FALSE(nigori.Decrypt(encrypted, &decrypted)); - - EXPECT_NE(plaintext, decrypted); -} - -// Crashes, Bug 55180. -#if defined(OS_WIN) -#define MAYBE_ExportImport DISABLED_ExportImport -#else -#define MAYBE_ExportImport ExportImport -#endif -TEST(SyncNigoriTest, MAYBE_ExportImport) { - Nigori nigori1; - EXPECT_TRUE(nigori1.InitByDerivation("example.com", "username", "password")); - - std::string user_key; - std::string encryption_key; - std::string mac_key; - EXPECT_TRUE(nigori1.ExportKeys(&user_key, &encryption_key, &mac_key)); - - Nigori nigori2; - EXPECT_TRUE(nigori2.InitByImport(user_key, encryption_key, mac_key)); - - std::string original("test"); - std::string plaintext; - std::string ciphertext; - - EXPECT_TRUE(nigori1.Encrypt(original, &ciphertext)); - EXPECT_TRUE(nigori2.Decrypt(ciphertext, &plaintext)); - EXPECT_EQ(original, plaintext); - - EXPECT_TRUE(nigori2.Encrypt(original, &ciphertext)); - EXPECT_TRUE(nigori1.Decrypt(ciphertext, &plaintext)); - EXPECT_EQ(original, plaintext); - - std::string permuted1, permuted2; - EXPECT_TRUE(nigori1.Permute(Nigori::Password, original, &permuted1)); - EXPECT_TRUE(nigori2.Permute(Nigori::Password, original, &permuted2)); - EXPECT_EQ(permuted1, permuted2); -} - -} // anonymous namespace -} // namespace browser_sync diff --git a/chrome/browser/sync/util/protobuf_unittest.cc b/chrome/browser/sync/util/protobuf_unittest.cc deleted file mode 100644 index 4f654d5..0000000 --- a/chrome/browser/sync/util/protobuf_unittest.cc +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) 2012 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 <string> -#include <vector> - -#include "sync/protocol/test.pb.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace { - -TEST(SyncProtobufTest, TestUnknownFields) { - // This tests ensures that we retain unknown fields in protocol buffers by - // serialising UnknownFieldsTestB, which is a superset of UnknownFieldsTestA, - // and checking we get back to the same message after parsing/serialising via - // UnknownFieldsTestA. - sync_pb::UnknownFieldsTestA a; - sync_pb::UnknownFieldsTestB b; - sync_pb::UnknownFieldsTestB b2; - - b.set_foo(true); - b.set_bar(true); - std::string serialized; - ASSERT_TRUE(b.SerializeToString(&serialized)); - ASSERT_TRUE(a.ParseFromString(serialized)); - ASSERT_TRUE(a.foo()); - std::string serialized2; - ASSERT_TRUE(a.SerializeToString(&serialized2)); - ASSERT_TRUE(b2.ParseFromString(serialized2)); - ASSERT_TRUE(b2.foo()); - ASSERT_TRUE(b2.bar()); -} - -} // namespace diff --git a/chrome/browser/sync/util/time.cc b/chrome/browser/sync/util/time.cc deleted file mode 100644 index ad309d0..0000000 --- a/chrome/browser/sync/util/time.cc +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) 2011 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 "chrome/browser/sync/util/time.h" - -#include "base/i18n/time_formatting.h" -#include "base/utf_string_conversions.h" - -namespace browser_sync { - -int64 TimeToProtoTime(const base::Time& t) { - return (t - base::Time::UnixEpoch()).InMilliseconds(); -} - -base::Time ProtoTimeToTime(int64 proto_t) { - return base::Time::UnixEpoch() + base::TimeDelta::FromMilliseconds(proto_t); -} - -std::string GetTimeDebugString(const base::Time& t) { - return UTF16ToUTF8(base::TimeFormatFriendlyDateAndTime(t)); -} - -} // namespace browser_sync diff --git a/chrome/browser/sync/util/time.h b/chrome/browser/sync/util/time.h deleted file mode 100644 index 473f7e2..0000000 --- a/chrome/browser/sync/util/time.h +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2011 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. -// -// Time-related sync functions. - -#ifndef CHROME_BROWSER_SYNC_UTIL_TIME_H_ -#define CHROME_BROWSER_SYNC_UTIL_TIME_H_ -#pragma once - -#include <string> - -#include "base/basictypes.h" -#include "base/time.h" - -namespace browser_sync { - -// Converts a time object to the format used in sync protobufs (ms -// since the Unix epoch). -int64 TimeToProtoTime(const base::Time& t); - -// Converts a time field from sync protobufs to a time object. -base::Time ProtoTimeToTime(int64 proto_t); - -std::string GetTimeDebugString(const base::Time& t); - -} // namespace browser_sync - -#endif // CHROME_BROWSER_SYNC_UTIL_TIME_H_ diff --git a/chrome/browser/sync/util/unrecoverable_error_info.cc b/chrome/browser/sync/util/unrecoverable_error_info.cc deleted file mode 100644 index 579eb38..0000000 --- a/chrome/browser/sync/util/unrecoverable_error_info.cc +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) 2011 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 "chrome/browser/sync/util/unrecoverable_error_info.h" - -namespace browser_sync { - -UnrecoverableErrorInfo::UnrecoverableErrorInfo() - : is_set_(false) { -} - -UnrecoverableErrorInfo::UnrecoverableErrorInfo( - const tracked_objects::Location& location, - const std::string& message) - : location_(location), - message_(message), - is_set_(true) { -} - -UnrecoverableErrorInfo::~UnrecoverableErrorInfo() { -} - -void UnrecoverableErrorInfo::Reset( - const tracked_objects::Location& location, - const std::string& message) { - location_ = location; - message_ = message; - is_set_ = true; -} - -bool UnrecoverableErrorInfo::IsSet() const { - return is_set_; -} - -const tracked_objects::Location& UnrecoverableErrorInfo::location() const { - return location_; -} - -const std::string& UnrecoverableErrorInfo::message() const { - return message_; -} - -} // namespace browser_sync diff --git a/chrome/browser/sync/util/unrecoverable_error_info.h b/chrome/browser/sync/util/unrecoverable_error_info.h deleted file mode 100644 index dd62c30..0000000 --- a/chrome/browser/sync/util/unrecoverable_error_info.h +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (c) 2011 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. - -#ifndef CHROME_BROWSER_SYNC_UTIL_UNRECOVERABLE_ERROR_INFO_H_ -#define CHROME_BROWSER_SYNC_UTIL_UNRECOVERABLE_ERROR_INFO_H_ -// TODO(lipalani): Figure out the right location for this class so it is -// accessible outside of sync engine as well. -#pragma once - -#include <string> - -#include "base/location.h" - -namespace browser_sync { - -class UnrecoverableErrorInfo { - public: - UnrecoverableErrorInfo(); - UnrecoverableErrorInfo( - const tracked_objects::Location& location, - const std::string& message); - ~UnrecoverableErrorInfo(); - - void Reset(const tracked_objects::Location& location, - const std::string& message); - - bool IsSet() const; - - const tracked_objects::Location& location() const; - const std::string& message() const; - - private: - tracked_objects::Location location_; - std::string message_; - bool is_set_; -}; - -} // namespace browser_sync - -#endif // CHROME_BROWSER_SYNC_UTIL_UNRECOVERABLE_ERROR_INFO_H_ diff --git a/chrome/browser/sync/util/user_settings.h b/chrome/browser/sync/util/user_settings.h deleted file mode 100644 index 546c8b0..0000000 --- a/chrome/browser/sync/util/user_settings.h +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright (c) 2010 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. - -#ifndef CHROME_BROWSER_SYNC_UTIL_USER_SETTINGS_H_ -#define CHROME_BROWSER_SYNC_UTIL_USER_SETTINGS_H_ -#pragma once - -#include <map> -#include <string> - -#include "base/synchronization/lock.h" -#include "build/build_config.h" - -extern "C" struct sqlite3; - -class FilePath; - -namespace browser_sync { - -void ExecOrDie(sqlite3* dbhandle, const char *query); -std::string APEncode(const std::string& in); -std::string APDecode(const std::string& in); - -class URLFactory; - -class UserSettings { - public: - // db_path is used for the main user settings. - // passwords_file contains hashes of passwords. - UserSettings(); - ~UserSettings(); - // Returns false (failure) if the db is a newer version. - bool Init(const FilePath& settings_path); - void StoreHashedPassword(const std::string& email, - const std::string& password); - bool VerifyAgainstStoredHash(const std::string& email, - const std::string& password); - - // Set the username. - void SwitchUser(const std::string& email); - - // Saves the email address and the named service token for the given user. - // Call this multiple times with the same email parameter to save multiple - // service tokens. - void SetAuthTokenForService(const std::string& email, - const std::string& service_name, - const std::string& long_lived_service_token); - // Erases all saved service tokens. - void ClearAllServiceTokens(); - - // Returns the user name whose credentials have been persisted. - bool GetLastUser(std::string* username); - - // Returns the user name whose credentials have been persisted as well as a - // service token for the named service - bool GetLastUserAndServiceToken(const std::string& service_name, - std::string* username, - std::string* service_token); - - void RemoveAllGuestSettings(); - - void StoreEmailForSignin(const std::string& signin, - const std::string& primary_email); - - // Multiple email addresses can map to the same Google Account. This method - // returns the primary Google Account email associated with |signin|, which - // is used as both input and output. - bool GetEmailForSignin(std::string* signin); - - std::string email() const; - - // Get a unique ID suitable for use as the client ID. This ID has the - // lifetime of the user settings database. You may use this ID if your - // operating environment does not provide its own unique client ID. - std::string GetClientId(); - - protected: - struct ScopedDBHandle { - explicit ScopedDBHandle(UserSettings* settings); - inline sqlite3* get() const { return *handle_; } - base::AutoLock mutex_lock_; - sqlite3** const handle_; - }; - - friend struct ScopedDBHandle; - friend class URLFactory; - - void MigrateOldVersionsAsNeeded(sqlite3* const handle, int current_version); - - private: - std::string email_; - mutable base::Lock mutex_; // protects email_. - - // We keep a single dbhandle. - sqlite3* dbhandle_; - base::Lock dbhandle_mutex_; - - // TODO(sync): Use in-memory cache for service auth tokens on posix. - // Have someone competent in Windows switch it over to not use Sqlite in the - // future. -#ifndef OS_WIN - typedef std::map<std::string, std::string> ServiceTokenMap; - ServiceTokenMap service_tokens_; -#endif // OS_WIN - - DISALLOW_COPY_AND_ASSIGN(UserSettings); -}; - -} // namespace browser_sync - -#endif // CHROME_BROWSER_SYNC_UTIL_USER_SETTINGS_H_ diff --git a/chrome/browser/sync/util/weak_handle.cc b/chrome/browser/sync/util/weak_handle.cc deleted file mode 100644 index 040841f..0000000 --- a/chrome/browser/sync/util/weak_handle.cc +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) 2011 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 "chrome/browser/sync/util/weak_handle.h" - -#include <sstream> - -#include "base/callback.h" -#include "base/location.h" -#include "base/message_loop_proxy.h" - -namespace browser_sync { - -namespace internal { - -WeakHandleCoreBase::WeakHandleCoreBase() - : owner_loop_proxy_(base::MessageLoopProxy::current()) {} - -bool WeakHandleCoreBase::IsOnOwnerThread() const { - return owner_loop_proxy_->BelongsToCurrentThread(); -} - -WeakHandleCoreBase::~WeakHandleCoreBase() {} - -void WeakHandleCoreBase::PostToOwnerThread( - const tracked_objects::Location& from_here, - const base::Closure& fn) const { - if (!owner_loop_proxy_->PostTask(from_here, fn)) { - DVLOG(1) << "Could not post task from " << from_here.ToString(); - } -} - -} // namespace internal - -} // namespace base diff --git a/chrome/browser/sync/util/weak_handle.h b/chrome/browser/sync/util/weak_handle.h deleted file mode 100644 index 28bfeda..0000000 --- a/chrome/browser/sync/util/weak_handle.h +++ /dev/null @@ -1,379 +0,0 @@ -// Copyright (c) 2011 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. - -// Weak handles provides a way to refer to weak pointers from another -// thread. This is useful because it is not safe to reference a weak -// pointer from a thread other than the thread on which it was -// created. -// -// Weak handles can be passed across threads, so for example, you can -// use them to do the "real" work on one thread and get notified on -// another thread: -// -// class FooIOWorker { -// public: -// FooIOWorker(const WeakHandle<Foo>& foo) : foo_(foo) {} -// -// void OnIOStart() { -// foo_.Call(FROM_HERE, &Foo::OnIOStart); -// } -// -// void OnIOEvent(IOEvent e) { -// foo_.Call(FROM_HERE, &Foo::OnIOEvent, e); -// } -// -// void OnIOError(IOError err) { -// foo_.Call(FROM_HERE, &Foo::OnIOError, err); -// } -// -// private: -// const WeakHandle<Foo> foo_; -// }; -// -// class Foo : public SupportsWeakPtr<Foo>, public NonThreadSafe { -// public: -// Foo() { -// SpawnFooIOWorkerOnIOThread(base::MakeWeakHandle(AsWeakPtr())); -// } -// -// /* Will always be called on the correct thread, and only if this -// object hasn't been destroyed. */ -// void OnIOStart() { DCHECK(CalledOnValidThread(); ... } -// void OnIOEvent(IOEvent e) { DCHECK(CalledOnValidThread(); ... } -// void OnIOError(IOError err) { DCHECK(CalledOnValidThread(); ... } -// }; - -#ifndef CHROME_BROWSER_SYNC_UTIL_WEAK_HANDLE_H_ -#define CHROME_BROWSER_SYNC_UTIL_WEAK_HANDLE_H_ -#pragma once - -#include <cstddef> - -#include "base/basictypes.h" -#include "base/bind.h" -#include "base/callback_forward.h" -#include "base/compiler_specific.h" -#include "base/gtest_prod_util.h" -#include "base/location.h" -#include "base/logging.h" -#include "base/memory/ref_counted.h" -#include "base/memory/weak_ptr.h" - -namespace base { -class MessageLoopProxy; -} // namespace base - -namespace tracked_objects { -class Location; -} // namespace tracked_objects - -namespace browser_sync { - -template <typename T> class WeakHandle; - -namespace internal { -// These classes are part of the WeakHandle implementation. DO NOT -// USE THESE CLASSES DIRECTLY YOURSELF. - -// Adapted from base/callback_internal.h. - -template <typename T> -struct ParamTraits { - typedef const T& ForwardType; -}; - -template <typename T> -struct ParamTraits<T&> { - typedef T& ForwardType; -}; - -template <typename T, size_t n> -struct ParamTraits<T[n]> { - typedef const T* ForwardType; -}; - -template <typename T> -struct ParamTraits<T[]> { - typedef const T* ForwardType; -}; - -// Base class for WeakHandleCore<T> to avoid template bloat. Handles -// the interaction with the owner thread and its message loop. -class WeakHandleCoreBase { - public: - // Assumes the current thread is the owner thread. - WeakHandleCoreBase(); - - // May be called on any thread. - bool IsOnOwnerThread() const; - - protected: - // May be destroyed on any thread. - ~WeakHandleCoreBase(); - - // May be called on any thread. - void PostToOwnerThread(const tracked_objects::Location& from_here, - const base::Closure& fn) const; - - private: - // May be used on any thread. - const scoped_refptr<base::MessageLoopProxy> owner_loop_proxy_; - - DISALLOW_COPY_AND_ASSIGN(WeakHandleCoreBase); -}; - -// WeakHandleCore<T> contains all the logic for WeakHandle<T>. -template <typename T> -class WeakHandleCore - : public WeakHandleCoreBase, - public base::RefCountedThreadSafe<WeakHandleCore<T> > { - public: - // Must be called on |ptr|'s owner thread, which is assumed to be - // the current thread. - explicit WeakHandleCore(const base::WeakPtr<T>& ptr) : ptr_(ptr) {} - - // Must be called on |ptr_|'s owner thread. - base::WeakPtr<T> Get() const { - CHECK(IsOnOwnerThread()); - return ptr_; - } - - // Call(...) may be called on any thread, but all its arguments - // should be safe to be bound and copied across threads. - - template <typename U> - void Call(const tracked_objects::Location& from_here, - void (U::*fn)(void)) const { - PostToOwnerThread( - from_here, - Bind(&WeakHandleCore::template DoCall0<U>, this, fn)); - } - - template <typename U, typename A1> - void Call(const tracked_objects::Location& from_here, - void (U::*fn)(A1), - typename ParamTraits<A1>::ForwardType a1) const { - PostToOwnerThread( - from_here, - Bind(&WeakHandleCore::template DoCall1<U, A1>, - this, fn, a1)); - } - - template <typename U, typename A1, typename A2> - void Call(const tracked_objects::Location& from_here, - void (U::*fn)(A1, A2), - typename ParamTraits<A1>::ForwardType a1, - typename ParamTraits<A2>::ForwardType a2) const { - PostToOwnerThread( - from_here, - Bind(&WeakHandleCore::template DoCall2<U, A1, A2>, - this, fn, a1, a2)); - } - - template <typename U, typename A1, typename A2, typename A3> - void Call(const tracked_objects::Location& from_here, - void (U::*fn)(A1, A2, A3), - typename ParamTraits<A1>::ForwardType a1, - typename ParamTraits<A2>::ForwardType a2, - typename ParamTraits<A3>::ForwardType a3) const { - PostToOwnerThread( - from_here, - Bind(&WeakHandleCore::template DoCall3<U, A1, A2, A3>, - this, fn, a1, a2, a3)); - } - - template <typename U, typename A1, typename A2, typename A3, typename A4> - void Call(const tracked_objects::Location& from_here, - void (U::*fn)(A1, A2, A3, A4), - typename ParamTraits<A1>::ForwardType a1, - typename ParamTraits<A2>::ForwardType a2, - typename ParamTraits<A3>::ForwardType a3, - typename ParamTraits<A4>::ForwardType a4) const { - PostToOwnerThread( - from_here, - Bind(&WeakHandleCore::template DoCall4<U, A1, A2, A3, A4>, - this, fn, a1, a2, a3, a4)); - } - - private: - friend class base::RefCountedThreadSafe<WeakHandleCore<T> >; - - // May be destroyed on any thread. - ~WeakHandleCore() {} - - // GCC 4.2.1 on OS X gets confused if all the DoCall functions are - // named the same, so we distinguish them. - - template <typename U> - void DoCall0(void (U::*fn)(void)) const { - CHECK(IsOnOwnerThread()); - if (!Get()) { - return; - } - (Get()->*fn)(); - } - - template <typename U, typename A1> - void DoCall1(void (U::*fn)(A1), - typename ParamTraits<A1>::ForwardType a1) const { - CHECK(IsOnOwnerThread()); - if (!Get()) { - return; - } - (Get()->*fn)(a1); - } - - template <typename U, typename A1, typename A2> - void DoCall2(void (U::*fn)(A1, A2), - typename ParamTraits<A1>::ForwardType a1, - typename ParamTraits<A2>::ForwardType a2) const { - CHECK(IsOnOwnerThread()); - if (!Get()) { - return; - } - (Get()->*fn)(a1, a2); - } - - template <typename U, typename A1, typename A2, typename A3> - void DoCall3(void (U::*fn)(A1, A2, A3), - typename ParamTraits<A1>::ForwardType a1, - typename ParamTraits<A2>::ForwardType a2, - typename ParamTraits<A3>::ForwardType a3) const { - CHECK(IsOnOwnerThread()); - if (!Get()) { - return; - } - (Get()->*fn)(a1, a2, a3); - } - - template <typename U, typename A1, typename A2, typename A3, typename A4> - void DoCall4(void (U::*fn)(A1, A2, A3, A4), - typename ParamTraits<A1>::ForwardType a1, - typename ParamTraits<A2>::ForwardType a2, - typename ParamTraits<A3>::ForwardType a3, - typename ParamTraits<A4>::ForwardType a4) const { - CHECK(IsOnOwnerThread()); - if (!Get()) { - return; - } - (Get()->*fn)(a1, a2, a3, a4); - } - - // Must be dereferenced only on the owner thread. May be destroyed - // from any thread. - base::WeakPtr<T> ptr_; - - DISALLOW_COPY_AND_ASSIGN(WeakHandleCore); -}; - -} // namespace internal - -// May be destroyed on any thread. -// Copying and assignment are welcome. -template <typename T> -class WeakHandle { - public: - // Creates an uninitialized WeakHandle. - WeakHandle() {} - - // Creates an initialized WeakHandle from |ptr|. - explicit WeakHandle(const base::WeakPtr<T>& ptr) - : core_(new internal::WeakHandleCore<T>(ptr)) {} - - // Allow conversion from WeakHandle<U> to WeakHandle<T> if U is - // convertible to T, but we *must* be on |other|'s owner thread. - // Note that this doesn't override the regular copy constructor, so - // that one can be called on any thread. - template <typename U> - WeakHandle(const browser_sync::WeakHandle<U>& other) // NOLINT - : core_( - other.IsInitialized() ? - new internal::WeakHandleCore<T>(other.Get()) : - NULL) {} - - // Returns true iff this WeakHandle is initialized. Note that being - // initialized isn't a guarantee that the underlying object is still - // alive. - bool IsInitialized() const { - return core_.get() != NULL; - } - - // Resets to an uninitialized WeakHandle. - void Reset() { - core_ = NULL; - } - - // Must be called only on the underlying object's owner thread. - base::WeakPtr<T> Get() const { - CHECK(IsInitialized()); - CHECK(core_->IsOnOwnerThread()); - return core_->Get(); - } - - // Call(...) may be called on any thread, but all its arguments - // should be safe to be bound and copied across threads. - - template <typename U> - void Call(const tracked_objects::Location& from_here, - void (U::*fn)(void)) const { - CHECK(IsInitialized()); - core_->Call(from_here, fn); - } - - template <typename U, typename A1> - void Call(const tracked_objects::Location& from_here, - void (U::*fn)(A1), - typename internal::ParamTraits<A1>::ForwardType a1) const { - CHECK(IsInitialized()); - core_->Call(from_here, fn, a1); - } - - template <typename U, typename A1, typename A2> - void Call(const tracked_objects::Location& from_here, - void (U::*fn)(A1, A2), - typename internal::ParamTraits<A1>::ForwardType a1, - typename internal::ParamTraits<A2>::ForwardType a2) const { - CHECK(IsInitialized()); - core_->Call(from_here, fn, a1, a2); - } - - template <typename U, typename A1, typename A2, typename A3> - void Call(const tracked_objects::Location& from_here, - void (U::*fn)(A1, A2, A3), - typename internal::ParamTraits<A1>::ForwardType a1, - typename internal::ParamTraits<A2>::ForwardType a2, - typename internal::ParamTraits<A3>::ForwardType a3) const { - CHECK(IsInitialized()); - core_->Call(from_here, fn, a1, a2, a3); - } - - template <typename U, typename A1, typename A2, typename A3, typename A4> - void Call(const tracked_objects::Location& from_here, - void (U::*fn)(A1, A2, A3, A4), - typename internal::ParamTraits<A1>::ForwardType a1, - typename internal::ParamTraits<A2>::ForwardType a2, - typename internal::ParamTraits<A3>::ForwardType a3, - typename internal::ParamTraits<A4>::ForwardType a4) const { - CHECK(IsInitialized()); - core_->Call(from_here, fn, a1, a2, a3, a4); - } - - private: - FRIEND_TEST_ALL_PREFIXES(WeakHandleTest, - TypeConversionConstructor); - FRIEND_TEST_ALL_PREFIXES(WeakHandleTest, - TypeConversionConstructorAssignment); - - scoped_refptr<internal::WeakHandleCore<T> > core_; -}; - -// Makes a WeakHandle from a WeakPtr. -template <typename T> -WeakHandle<T> MakeWeakHandle(const base::WeakPtr<T>& ptr) { - return WeakHandle<T>(ptr); -} - -} // namespace browser_sync - -#endif // CHROME_BROWSER_SYNC_UTIL_WEAK_HANDLE_H_ diff --git a/chrome/browser/sync/util/weak_handle_unittest.cc b/chrome/browser/sync/util/weak_handle_unittest.cc deleted file mode 100644 index 4a56f9e..0000000 --- a/chrome/browser/sync/util/weak_handle_unittest.cc +++ /dev/null @@ -1,326 +0,0 @@ -// Copyright (c) 2011 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 "chrome/browser/sync/util/weak_handle.h" - -#include "base/bind.h" -#include "base/compiler_specific.h" -#include "base/location.h" -#include "base/memory/weak_ptr.h" -#include "base/message_loop.h" -#include "base/threading/thread.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace browser_sync { - -using ::testing::_; -using ::testing::SaveArg; -using ::testing::StrictMock; - -class Base { - public: - Base() : weak_ptr_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) {} - - WeakHandle<Base> AsWeakHandle() { - return MakeWeakHandle(weak_ptr_factory_.GetWeakPtr()); - } - - void Kill() { - weak_ptr_factory_.InvalidateWeakPtrs(); - } - - MOCK_METHOD0(Test, void()); - MOCK_METHOD1(Test1, void(const int&)); - MOCK_METHOD2(Test2, void(const int&, Base*)); - MOCK_METHOD3(Test3, void(const int&, Base*, float)); - MOCK_METHOD4(Test4, void(const int&, Base*, float, const char*)); - - MOCK_METHOD1(TestWithSelf, void(const WeakHandle<Base>&)); - - private: - base::WeakPtrFactory<Base> weak_ptr_factory_; -}; - -class Derived : public Base, public base::SupportsWeakPtr<Derived> {}; - -class WeakHandleTest : public ::testing::Test { - protected: - virtual void TearDown() { - // Process any last-minute posted tasks. - PumpLoop(); - } - - void PumpLoop() { - message_loop_.RunAllPending(); - } - - static void CallTestFromOtherThread(tracked_objects::Location from_here, - const WeakHandle<Base>& h) { - base::Thread t("Test thread"); - ASSERT_TRUE(t.Start()); - t.message_loop()->PostTask( - from_here, base::Bind(&WeakHandleTest::CallTest, from_here, h)); - } - - private: - static void CallTest(tracked_objects::Location from_here, - const WeakHandle<Base>& h) { - h.Call(from_here, &Base::Test); - } - - MessageLoop message_loop_; -}; - -TEST_F(WeakHandleTest, Uninitialized) { - // Default. - WeakHandle<int> h; - EXPECT_FALSE(h.IsInitialized()); - // Copy. - { - WeakHandle<int> h2(h); - EXPECT_FALSE(h2.IsInitialized()); - } - // Assign. - { - WeakHandle<int> h2; - h2 = h; - EXPECT_FALSE(h.IsInitialized()); - } -} - -TEST_F(WeakHandleTest, InitializedAfterDestroy) { - WeakHandle<Base> h; - { - StrictMock<Base> b; - h = b.AsWeakHandle(); - } - EXPECT_TRUE(h.IsInitialized()); - EXPECT_FALSE(h.Get()); -} - -TEST_F(WeakHandleTest, InitializedAfterInvalidate) { - StrictMock<Base> b; - WeakHandle<Base> h = b.AsWeakHandle(); - b.Kill(); - EXPECT_TRUE(h.IsInitialized()); - EXPECT_FALSE(h.Get()); -} - -TEST_F(WeakHandleTest, Call) { - StrictMock<Base> b; - const char test_str[] = "test"; - EXPECT_CALL(b, Test()); - EXPECT_CALL(b, Test1(5)); - EXPECT_CALL(b, Test2(5, &b)); - EXPECT_CALL(b, Test3(5, &b, 5)); - EXPECT_CALL(b, Test4(5, &b, 5, test_str)); - - WeakHandle<Base> h = b.AsWeakHandle(); - EXPECT_TRUE(h.IsInitialized()); - - // Should run. - h.Call(FROM_HERE, &Base::Test); - h.Call(FROM_HERE, &Base::Test1, 5); - h.Call(FROM_HERE, &Base::Test2, 5, &b); - h.Call(FROM_HERE, &Base::Test3, 5, &b, 5); - h.Call(FROM_HERE, &Base::Test4, 5, &b, 5, test_str); - PumpLoop(); -} - -TEST_F(WeakHandleTest, CallAfterDestroy) { - { - StrictMock<Base> b; - EXPECT_CALL(b, Test()).Times(0); - - WeakHandle<Base> h = b.AsWeakHandle(); - EXPECT_TRUE(h.IsInitialized()); - - // Should not run. - h.Call(FROM_HERE, &Base::Test); - } - PumpLoop(); -} - -TEST_F(WeakHandleTest, CallAfterInvalidate) { - StrictMock<Base> b; - EXPECT_CALL(b, Test()).Times(0); - - WeakHandle<Base> h = b.AsWeakHandle(); - EXPECT_TRUE(h.IsInitialized()); - - // Should not run. - h.Call(FROM_HERE, &Base::Test); - - b.Kill(); - PumpLoop(); -} - -TEST_F(WeakHandleTest, CallThreaded) { - StrictMock<Base> b; - EXPECT_CALL(b, Test()); - - WeakHandle<Base> h = b.AsWeakHandle(); - // Should run. - CallTestFromOtherThread(FROM_HERE, h); - PumpLoop(); -} - -TEST_F(WeakHandleTest, CallAfterDestroyThreaded) { - WeakHandle<Base> h; - { - StrictMock<Base> b; - EXPECT_CALL(b, Test()).Times(0); - h = b.AsWeakHandle(); - } - - // Should not run. - CallTestFromOtherThread(FROM_HERE, h); - PumpLoop(); -} - -TEST_F(WeakHandleTest, CallAfterInvalidateThreaded) { - StrictMock<Base> b; - EXPECT_CALL(b, Test()).Times(0); - - WeakHandle<Base> h = b.AsWeakHandle(); - b.Kill(); - // Should not run. - CallTestFromOtherThread(FROM_HERE, h); - PumpLoop(); -} - -TEST_F(WeakHandleTest, DeleteOnOtherThread) { - StrictMock<Base> b; - EXPECT_CALL(b, Test()).Times(0); - - WeakHandle<Base>* h = new WeakHandle<Base>(b.AsWeakHandle()); - - { - base::Thread t("Test thread"); - ASSERT_TRUE(t.Start()); - t.message_loop()->DeleteSoon(FROM_HERE, h); - } - - PumpLoop(); -} - -void CallTestWithSelf(const WeakHandle<Base>& b1) { - StrictMock<Base> b2; - b1.Call(FROM_HERE, &Base::TestWithSelf, b2.AsWeakHandle()); -} - -TEST_F(WeakHandleTest, WithDestroyedThread) { - StrictMock<Base> b1; - WeakHandle<Base> b2; - EXPECT_CALL(b1, TestWithSelf(_)).WillOnce(SaveArg<0>(&b2)); - - { - base::Thread t("Test thread"); - ASSERT_TRUE(t.Start()); - t.message_loop()->PostTask(FROM_HERE, - base::Bind(&CallTestWithSelf, - b1.AsWeakHandle())); - } - - // Calls b1.TestWithSelf(). - PumpLoop(); - - // Shouldn't do anything, since the thread is gone. - b2.Call(FROM_HERE, &Base::Test); - - // |b2| shouldn't leak when it's destroyed, even if the original - // thread is gone. -} - -TEST_F(WeakHandleTest, InitializedAcrossCopyAssign) { - StrictMock<Base> b; - EXPECT_CALL(b, Test()).Times(3); - - EXPECT_TRUE(b.AsWeakHandle().IsInitialized()); - b.AsWeakHandle().Call(FROM_HERE, &Base::Test); - - { - WeakHandle<Base> h(b.AsWeakHandle()); - EXPECT_TRUE(h.IsInitialized()); - h.Call(FROM_HERE, &Base::Test); - h.Reset(); - EXPECT_FALSE(h.IsInitialized()); - } - - { - WeakHandle<Base> h; - h = b.AsWeakHandle(); - EXPECT_TRUE(h.IsInitialized()); - h.Call(FROM_HERE, &Base::Test); - h.Reset(); - EXPECT_FALSE(h.IsInitialized()); - } - - PumpLoop(); -} - -TEST_F(WeakHandleTest, TypeConversionConstructor) { - StrictMock<Derived> d; - EXPECT_CALL(d, Test()).Times(2); - - const WeakHandle<Derived> weak_handle = MakeWeakHandle(d.AsWeakPtr()); - - // Should trigger type conversion constructor. - const WeakHandle<Base> base_weak_handle(weak_handle); - // Should trigger regular copy constructor. - const WeakHandle<Derived> derived_weak_handle(weak_handle); - - EXPECT_TRUE(base_weak_handle.IsInitialized()); - base_weak_handle.Call(FROM_HERE, &Base::Test); - - EXPECT_TRUE(derived_weak_handle.IsInitialized()); - // Copy constructor shouldn't construct a new |core_|. - EXPECT_EQ(weak_handle.core_.get(), derived_weak_handle.core_.get()); - derived_weak_handle.Call(FROM_HERE, &Base::Test); - - PumpLoop(); -} - -TEST_F(WeakHandleTest, TypeConversionConstructorMakeWeakHandle) { - const base::WeakPtr<Derived> weak_ptr; - - // Should trigger type conversion constructor after MakeWeakHandle. - WeakHandle<Base> base_weak_handle(MakeWeakHandle(weak_ptr)); - // Should trigger regular copy constructor after MakeWeakHandle. - const WeakHandle<Derived> derived_weak_handle(MakeWeakHandle(weak_ptr)); - - EXPECT_TRUE(base_weak_handle.IsInitialized()); - EXPECT_TRUE(derived_weak_handle.IsInitialized()); -} - -TEST_F(WeakHandleTest, TypeConversionConstructorAssignment) { - const WeakHandle<Derived> weak_handle = - MakeWeakHandle(Derived().AsWeakPtr()); - - // Should trigger type conversion constructor before the assignment. - WeakHandle<Base> base_weak_handle; - base_weak_handle = weak_handle; - // Should trigger regular copy constructor before the assignment. - WeakHandle<Derived> derived_weak_handle; - derived_weak_handle = weak_handle; - - EXPECT_TRUE(base_weak_handle.IsInitialized()); - EXPECT_TRUE(derived_weak_handle.IsInitialized()); - // Copy constructor shouldn't construct a new |core_|. - EXPECT_EQ(weak_handle.core_.get(), derived_weak_handle.core_.get()); -} - -TEST_F(WeakHandleTest, TypeConversionConstructorUninitialized) { - const WeakHandle<Base> base_weak_handle = WeakHandle<Derived>(); - EXPECT_FALSE(base_weak_handle.IsInitialized()); -} - -TEST_F(WeakHandleTest, TypeConversionConstructorUninitializedAssignment) { - WeakHandle<Base> base_weak_handle; - base_weak_handle = WeakHandle<Derived>(); - EXPECT_FALSE(base_weak_handle.IsInitialized()); -} - -} // namespace browser_sync |