diff options
| author | zea@chromium.org <zea@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2011-08-17 23:38:30 +0000 |
|---|---|---|
| committer | zea@chromium.org <zea@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2011-08-17 23:38:30 +0000 |
| commit | 67192b4b7800af69dda3168877db3d9d4f1f202d (patch) | |
| tree | c5c173386b56d1cbf4e5cc809761a5d463e5eee1 /chrome/browser/sync/internal_api | |
| parent | d3540c23e13dc77e8c89054bcadc7d56eeb497de (diff) | |
| download | chromium_src-67192b4b7800af69dda3168877db3d9d4f1f202d.zip chromium_src-67192b4b7800af69dda3168877db3d9d4f1f202d.tar.gz chromium_src-67192b4b7800af69dda3168877db3d9d4f1f202d.tar.bz2 | |
Original patch by rlarocque@chromium.org at http://codereview.chromium.org/7633077/
Fragment syncapi.h into sync/internal_api/*
This commit splits syncapi.cc and syncapi.h into many files. Most of these files have been moved to the newly created chrome/browser/sync/internal_api.
Each of the following classes now have their own .cc and .h files:
- BaseNode
- ReadNode
- WriteNode
- BaseTransaction
- ReadTransaction
- WriteTransaction
- UserShare
- SyncManager
Functions formerly declared at file-scope in syncapi.cc and shared among several classes are now declared in engine/syncapi_internal.h. We intend to use DEPS rules to prevent these functions from being included in non-syncapi classes.
Test classes closely related to syncapi.h classes have been moved from engine to internal_api.
This change necessarily touches the #include lists for lots of files and some of the sources lists in .gyp.
This change should have no effect on program behaviour.
BUG=19878
TEST=
Review URL: http://codereview.chromium.org/7624009
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97238 0039d316-1c4b-4281-b951-d872f2087c98
Diffstat (limited to 'chrome/browser/sync/internal_api')
22 files changed, 5880 insertions, 0 deletions
diff --git a/chrome/browser/sync/internal_api/DEPS b/chrome/browser/sync/internal_api/DEPS new file mode 100644 index 0000000..ff4b760 --- /dev/null +++ b/chrome/browser/sync/internal_api/DEPS @@ -0,0 +1,14 @@ +include_rules = [ + "-chrome", + "+chrome/test/base", + "+chrome/test/sync", + + "+chrome/browser/sync", + "-chrome/browser/sync/api", + "-chrome/browser/sync/glue", + + # unittests need this for mac osx keychain overriding + "+chrome/browser/password_manager/encryptor.h", + + "+chrome/common/net/gaia/google_service_auth_error.h", +] diff --git a/chrome/browser/sync/internal_api/README b/chrome/browser/sync/internal_api/README new file mode 100644 index 0000000..32987bb --- /dev/null +++ b/chrome/browser/sync/internal_api/README @@ -0,0 +1,32 @@ +This file defines the "sync API", an interface to the syncer +backend that exposes (1) the core functionality of maintaining a consistent +local snapshot of a hierarchical object set; (2) a means to transactionally +access and modify those objects; (3) a means to control client/server +synchronization tasks, namely: pushing local object modifications to a +server, pulling nonlocal object modifications from a server to this client, +and resolving conflicts that may arise between the two; and (4) an +abstraction of some external functionality that is to be provided by the +host environment. + +This interface is used as the entry point into the syncer backend +when the backend is compiled as a library and embedded in another +application. A goal for this interface layer is to depend on very few +external types, so that an application can use the sync backend +without introducing a dependency on specific types. A non-goal is to +have binary compatibility across versions or compilers; this allows the +interface to use C++ classes. An application wishing to use the sync API +should ideally compile the syncer backend and this API as part of the +application's own build, to avoid e.g. mismatches in calling convention, +structure padding, or name mangling that could arise if there were a +compiler mismatch. + +The schema of the objects in the sync domain is based on the model, which +is essentially a hierarchy of items and folders similar to a filesystem, +but with a few important differences. The sync API contains fields +such as URL to easily allow the embedding application to store web +browser bookmarks. Also, the sync API allows duplicate titles in a parent. +Consequently, it does not support looking up an object by title +and parent, since such a lookup is not uniquely determined. Lastly, +unlike a filesystem model, objects in the Sync API model have a strict +ordering within a parent; the position is manipulable by callers, and +children of a node can be enumerated in the order of their position. diff --git a/chrome/browser/sync/internal_api/base_node.cc b/chrome/browser/sync/internal_api/base_node.cc new file mode 100644 index 0000000..002006c --- /dev/null +++ b/chrome/browser/sync/internal_api/base_node.cc @@ -0,0 +1,298 @@ +// 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/internal_api/base_node.h" + +#include "base/base64.h" +#include "base/sha1.h" +#include "base/string_number_conversions.h" +#include "base/values.h" +#include "chrome/browser/sync/engine/syncapi_internal.h" +#include "chrome/browser/sync/internal_api/base_transaction.h" +#include "chrome/browser/sync/protocol/app_specifics.pb.h" +#include "chrome/browser/sync/protocol/autofill_specifics.pb.h" +#include "chrome/browser/sync/protocol/bookmark_specifics.pb.h" +#include "chrome/browser/sync/protocol/extension_specifics.pb.h" +#include "chrome/browser/sync/protocol/nigori_specifics.pb.h" +#include "chrome/browser/sync/protocol/password_specifics.pb.h" +#include "chrome/browser/sync/protocol/session_specifics.pb.h" +#include "chrome/browser/sync/protocol/theme_specifics.pb.h" +#include "chrome/browser/sync/protocol/typed_url_specifics.pb.h" +#include "chrome/browser/sync/syncable/directory_manager.h" +#include "chrome/browser/sync/syncable/syncable.h" +#include "chrome/browser/sync/syncable/syncable_id.h" + +using syncable::SPECIFICS; +using sync_pb::AutofillProfileSpecifics; + +namespace sync_api { + +// Helper function to look up the int64 metahandle of an object given the ID +// string. +static int64 IdToMetahandle(syncable::BaseTransaction* trans, + const syncable::Id& id) { + syncable::Entry entry(trans, syncable::GET_BY_ID, id); + if (!entry.good()) + return kInvalidId; + return entry.Get(syncable::META_HANDLE); +} + +static bool EndsWithSpace(const std::string& string) { + return !string.empty() && *string.rbegin() == ' '; +} + +// In the reverse direction, if a server name matches the pattern of a +// server-illegal name followed by one or more spaces, remove the trailing +// space. +static void ServerNameToSyncAPIName(const std::string& server_name, + std::string* out) { + CHECK(out); + int length_to_copy = server_name.length(); + if (IsNameServerIllegalAfterTrimming(server_name) && + EndsWithSpace(server_name)) { + --length_to_copy; + } + *out = std::string(server_name.c_str(), length_to_copy); +} + +BaseNode::BaseNode() : password_data_(new sync_pb::PasswordSpecificsData) {} + +BaseNode::~BaseNode() {} + +std::string BaseNode::GenerateSyncableHash( + syncable::ModelType model_type, const std::string& client_tag) { + // blank PB with just the extension in it has termination symbol, + // handy for delimiter + sync_pb::EntitySpecifics serialized_type; + syncable::AddDefaultExtensionValue(model_type, &serialized_type); + std::string hash_input; + serialized_type.AppendToString(&hash_input); + hash_input.append(client_tag); + + std::string encode_output; + CHECK(base::Base64Encode(base::SHA1HashString(hash_input), &encode_output)); + return encode_output; +} + +bool BaseNode::DecryptIfNecessary() { + if (!GetEntry()->Get(syncable::UNIQUE_SERVER_TAG).empty()) + return true; // Ignore unique folders. + const sync_pb::EntitySpecifics& specifics = + GetEntry()->Get(syncable::SPECIFICS); + if (specifics.HasExtension(sync_pb::password)) { + // Passwords have their own legacy encryption structure. + scoped_ptr<sync_pb::PasswordSpecificsData> data(DecryptPasswordSpecifics( + specifics, GetTransaction()->GetCryptographer())); + if (!data.get()) { + LOG(ERROR) << "Failed to decrypt password specifics."; + return false; + } + password_data_.swap(data); + return true; + } + + // We assume any node with the encrypted field set has encrypted data. + if (!specifics.has_encrypted()) + return true; + + const sync_pb::EncryptedData& encrypted = + specifics.encrypted(); + std::string plaintext_data = GetTransaction()->GetCryptographer()-> + DecryptToString(encrypted); + if (plaintext_data.length() == 0 || + !unencrypted_data_.ParseFromString(plaintext_data)) { + LOG(ERROR) << "Failed to decrypt encrypted node of type " << + syncable::ModelTypeToString(GetModelType()) << "."; + return false; + } + VLOG(2) << "Decrypted specifics of type " + << syncable::ModelTypeToString(GetModelType()) + << " with content: " << plaintext_data; + return true; +} + +const sync_pb::EntitySpecifics& BaseNode::GetUnencryptedSpecifics( + const syncable::Entry* entry) const { + const sync_pb::EntitySpecifics& specifics = entry->Get(SPECIFICS); + if (specifics.has_encrypted()) { + DCHECK(syncable::GetModelTypeFromSpecifics(unencrypted_data_) != + syncable::UNSPECIFIED); + return unencrypted_data_; + } else { + DCHECK(syncable::GetModelTypeFromSpecifics(unencrypted_data_) == + syncable::UNSPECIFIED); + return specifics; + } +} + +int64 BaseNode::GetParentId() const { + return IdToMetahandle(GetTransaction()->GetWrappedTrans(), + GetEntry()->Get(syncable::PARENT_ID)); +} + +int64 BaseNode::GetId() const { + return GetEntry()->Get(syncable::META_HANDLE); +} + +int64 BaseNode::GetModificationTime() const { + return GetEntry()->Get(syncable::MTIME); +} + +bool BaseNode::GetIsFolder() const { + return GetEntry()->Get(syncable::IS_DIR); +} + +std::string BaseNode::GetTitle() const { + std::string result; + // TODO(zea): refactor bookmarks to not need this functionality. + if (syncable::BOOKMARKS == GetModelType() && + GetEntry()->Get(syncable::SPECIFICS).has_encrypted()) { + // Special case for legacy bookmarks dealing with encryption. + ServerNameToSyncAPIName(GetBookmarkSpecifics().title(), &result); + } else { + ServerNameToSyncAPIName(GetEntry()->Get(syncable::NON_UNIQUE_NAME), + &result); + } + return result; +} + +GURL BaseNode::GetURL() const { + return GURL(GetBookmarkSpecifics().url()); +} + +int64 BaseNode::GetPredecessorId() const { + syncable::Id id_string = GetEntry()->Get(syncable::PREV_ID); + if (id_string.IsRoot()) + return kInvalidId; + return IdToMetahandle(GetTransaction()->GetWrappedTrans(), id_string); +} + +int64 BaseNode::GetSuccessorId() const { + syncable::Id id_string = GetEntry()->Get(syncable::NEXT_ID); + if (id_string.IsRoot()) + return kInvalidId; + return IdToMetahandle(GetTransaction()->GetWrappedTrans(), id_string); +} + +int64 BaseNode::GetFirstChildId() const { + syncable::Directory* dir = GetTransaction()->GetLookup(); + syncable::BaseTransaction* trans = GetTransaction()->GetWrappedTrans(); + syncable::Id id_string = + dir->GetFirstChildId(trans, GetEntry()->Get(syncable::ID)); + if (id_string.IsRoot()) + return kInvalidId; + return IdToMetahandle(GetTransaction()->GetWrappedTrans(), id_string); +} + +DictionaryValue* BaseNode::GetSummaryAsValue() const { + DictionaryValue* node_info = new DictionaryValue(); + node_info->SetString("id", base::Int64ToString(GetId())); + node_info->SetBoolean("isFolder", GetIsFolder()); + node_info->SetString("title", GetTitle()); + node_info->Set("type", ModelTypeToValue(GetModelType())); + return node_info; +} + +DictionaryValue* BaseNode::GetDetailsAsValue() const { + DictionaryValue* node_info = GetSummaryAsValue(); + // TODO(akalin): Return time in a better format. + node_info->SetString("modificationTime", + base::Int64ToString(GetModificationTime())); + node_info->SetString("parentId", base::Int64ToString(GetParentId())); + // Specifics are already in the Entry value, so no need to duplicate + // it here. + node_info->SetString("externalId", + base::Int64ToString(GetExternalId())); + node_info->SetString("predecessorId", + base::Int64ToString(GetPredecessorId())); + node_info->SetString("successorId", + base::Int64ToString(GetSuccessorId())); + node_info->SetString("firstChildId", + base::Int64ToString(GetFirstChildId())); + node_info->Set("entry", GetEntry()->ToValue()); + return node_info; +} + +void BaseNode::GetFaviconBytes(std::vector<unsigned char>* output) const { + if (!output) + return; + const std::string& favicon = GetBookmarkSpecifics().favicon(); + output->assign(reinterpret_cast<const unsigned char*>(favicon.data()), + reinterpret_cast<const unsigned char*>(favicon.data() + + favicon.length())); +} + +int64 BaseNode::GetExternalId() const { + return GetEntry()->Get(syncable::LOCAL_EXTERNAL_ID); +} + +const sync_pb::AppSpecifics& BaseNode::GetAppSpecifics() const { + DCHECK_EQ(syncable::APPS, GetModelType()); + return GetEntitySpecifics().GetExtension(sync_pb::app); +} + +const sync_pb::AutofillSpecifics& BaseNode::GetAutofillSpecifics() const { + DCHECK_EQ(syncable::AUTOFILL, GetModelType()); + return GetEntitySpecifics().GetExtension(sync_pb::autofill); +} + +const AutofillProfileSpecifics& BaseNode::GetAutofillProfileSpecifics() const { + DCHECK_EQ(GetModelType(), syncable::AUTOFILL_PROFILE); + return GetEntitySpecifics().GetExtension(sync_pb::autofill_profile); +} + +const sync_pb::BookmarkSpecifics& BaseNode::GetBookmarkSpecifics() const { + DCHECK_EQ(syncable::BOOKMARKS, GetModelType()); + return GetEntitySpecifics().GetExtension(sync_pb::bookmark); +} + +const sync_pb::NigoriSpecifics& BaseNode::GetNigoriSpecifics() const { + DCHECK_EQ(syncable::NIGORI, GetModelType()); + return GetEntitySpecifics().GetExtension(sync_pb::nigori); +} + +const sync_pb::PasswordSpecificsData& BaseNode::GetPasswordSpecifics() const { + DCHECK_EQ(syncable::PASSWORDS, GetModelType()); + return *password_data_; +} + +const sync_pb::ThemeSpecifics& BaseNode::GetThemeSpecifics() const { + DCHECK_EQ(syncable::THEMES, GetModelType()); + return GetEntitySpecifics().GetExtension(sync_pb::theme); +} + +const sync_pb::TypedUrlSpecifics& BaseNode::GetTypedUrlSpecifics() const { + DCHECK_EQ(syncable::TYPED_URLS, GetModelType()); + return GetEntitySpecifics().GetExtension(sync_pb::typed_url); +} + +const sync_pb::ExtensionSpecifics& BaseNode::GetExtensionSpecifics() const { + DCHECK_EQ(syncable::EXTENSIONS, GetModelType()); + return GetEntitySpecifics().GetExtension(sync_pb::extension); +} + +const sync_pb::SessionSpecifics& BaseNode::GetSessionSpecifics() const { + DCHECK_EQ(syncable::SESSIONS, GetModelType()); + return GetEntitySpecifics().GetExtension(sync_pb::session); +} + +const sync_pb::EntitySpecifics& BaseNode::GetEntitySpecifics() const { + return GetUnencryptedSpecifics(GetEntry()); +} + +syncable::ModelType BaseNode::GetModelType() const { + return GetEntry()->GetModelType(); +} + +void BaseNode::SetUnencryptedSpecifics( + const sync_pb::EntitySpecifics& specifics) { + syncable::ModelType type = syncable::GetModelTypeFromSpecifics(specifics); + DCHECK_NE(syncable::UNSPECIFIED, type); + if (GetModelType() != syncable::UNSPECIFIED) { + DCHECK_EQ(GetModelType(), type); + } + unencrypted_data_.CopyFrom(specifics); +} + +} // namespace sync_api diff --git a/chrome/browser/sync/internal_api/base_node.h b/chrome/browser/sync/internal_api/base_node.h new file mode 100644 index 0000000..8759966 --- /dev/null +++ b/chrome/browser/sync/internal_api/base_node.h @@ -0,0 +1,224 @@ +// 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_INTERNAL_API_BASE_NODE_H_ +#define CHROME_BROWSER_SYNC_INTERNAL_API_BASE_NODE_H_ +#pragma once + +#include <string> +#include <vector> + +#include "base/basictypes.h" +#include "base/gtest_prod_util.h" +#include "base/memory/scoped_ptr.h" +#include "chrome/browser/sync/protocol/sync.pb.h" +#include "chrome/browser/sync/syncable/model_type.h" +#include "googleurl/src/gurl.h" + +// Forward declarations of internal class types so that sync API objects +// may have opaque pointers to these types. +namespace base { +class DictionaryValue; +} + +namespace syncable { +class BaseTransaction; +class Entry; +} + +namespace sync_pb { +class AppSpecifics; +class AutofillSpecifics; +class AutofillProfileSpecifics; +class BookmarkSpecifics; +class EntitySpecifics; +class ExtensionSpecifics; +class SessionSpecifics; +class NigoriSpecifics; +class PreferenceSpecifics; +class PasswordSpecificsData; +class ThemeSpecifics; +class TypedUrlSpecifics; +} + +namespace sync_api { + +class BaseTransaction; + +// A valid BaseNode will never have an ID of zero. +static const int64 kInvalidId = 0; + +// BaseNode wraps syncable::Entry, and corresponds to a single object's state. +// This, like syncable::Entry, is intended for use on the stack. A valid +// transaction is necessary to create a BaseNode or any of its children. +// Unlike syncable::Entry, a sync API BaseNode is identified primarily by its +// int64 metahandle, which we call an ID here. +class BaseNode { + public: + // All subclasses of BaseNode must provide a way to initialize themselves by + // doing an ID lookup. Returns false on failure. An invalid or deleted + // ID will result in failure. + virtual bool InitByIdLookup(int64 id) = 0; + + // All subclasses of BaseNode must also provide a way to initialize themselves + // by doing a client tag lookup. Returns false on failure. A deleted node + // will return FALSE. + virtual bool InitByClientTagLookup(syncable::ModelType model_type, + const std::string& tag) = 0; + + // Each object is identified by a 64-bit id (internally, the syncable + // metahandle). These ids are strictly local handles. They will persist + // on this client, but the same object on a different client may have a + // different ID value. + virtual int64 GetId() const; + + // Returns the modification time of the object (in TimeTicks internal format). + int64 GetModificationTime() const; + + // Nodes are hierarchically arranged into a single-rooted tree. + // InitByRootLookup on ReadNode allows access to the root. GetParentId is + // how you find a node's parent. + int64 GetParentId() const; + + // Nodes are either folders or not. This corresponds to the IS_DIR property + // of syncable::Entry. + bool GetIsFolder() const; + + // Returns the title of the object. + // Uniqueness of the title is not enforced on siblings -- it is not an error + // for two children to share a title. + std::string GetTitle() const; + + // Returns the model type of this object. The model type is set at node + // creation time and is expected never to change. + syncable::ModelType GetModelType() const; + + // Getter specific to the BOOKMARK datatype. Returns protobuf + // data. Can only be called if GetModelType() == BOOKMARK. + const sync_pb::BookmarkSpecifics& GetBookmarkSpecifics() const; + + // Legacy, bookmark-specific getter that wraps GetBookmarkSpecifics() above. + // Returns the URL of a bookmark object. + // TODO(ncarter): Remove this datatype-specific accessor. + GURL GetURL() const; + + // Legacy, bookmark-specific getter that wraps GetBookmarkSpecifics() above. + // Fill in a vector with the byte data of this node's favicon. Assumes + // that the node is a bookmark. + // Favicons are expected to be PNG images, and though no verification is + // done on the syncapi client of this, the server may reject favicon updates + // that are invalid for whatever reason. + // TODO(ncarter): Remove this datatype-specific accessor. + void GetFaviconBytes(std::vector<unsigned char>* output) const; + + // Getter specific to the APPS datatype. Returns protobuf + // data. Can only be called if GetModelType() == APPS. + const sync_pb::AppSpecifics& GetAppSpecifics() const; + + // Getter specific to the AUTOFILL datatype. Returns protobuf + // data. Can only be called if GetModelType() == AUTOFILL. + const sync_pb::AutofillSpecifics& GetAutofillSpecifics() const; + + virtual const sync_pb::AutofillProfileSpecifics& + GetAutofillProfileSpecifics() const; + + // Getter specific to the NIGORI datatype. Returns protobuf + // data. Can only be called if GetModelType() == NIGORI. + const sync_pb::NigoriSpecifics& GetNigoriSpecifics() const; + + // Getter specific to the PASSWORD datatype. Returns protobuf + // data. Can only be called if GetModelType() == PASSWORD. + const sync_pb::PasswordSpecificsData& GetPasswordSpecifics() const; + + // Getter specific to the PREFERENCE datatype. Returns protobuf + // data. Can only be called if GetModelType() == PREFERENCE. + const sync_pb::PreferenceSpecifics& GetPreferenceSpecifics() const; + + // Getter specific to the THEME datatype. Returns protobuf + // data. Can only be called if GetModelType() == THEME. + const sync_pb::ThemeSpecifics& GetThemeSpecifics() const; + + // Getter specific to the TYPED_URLS datatype. Returns protobuf + // data. Can only be called if GetModelType() == TYPED_URLS. + const sync_pb::TypedUrlSpecifics& GetTypedUrlSpecifics() const; + + // Getter specific to the EXTENSIONS datatype. Returns protobuf + // data. Can only be called if GetModelType() == EXTENSIONS. + const sync_pb::ExtensionSpecifics& GetExtensionSpecifics() const; + + // Getter specific to the SESSIONS datatype. Returns protobuf + // data. Can only be called if GetModelType() == SESSIONS. + const sync_pb::SessionSpecifics& GetSessionSpecifics() const; + + const sync_pb::EntitySpecifics& GetEntitySpecifics() const; + + // Returns the local external ID associated with the node. + int64 GetExternalId() const; + + // Return the ID of the node immediately before this in the sibling order. + // For the first node in the ordering, return 0. + int64 GetPredecessorId() const; + + // Return the ID of the node immediately after this in the sibling order. + // For the last node in the ordering, return 0. + virtual int64 GetSuccessorId() const; + + // Return the ID of the first child of this node. If this node has no + // children, return 0. + virtual int64 GetFirstChildId() const; + + // These virtual accessors provide access to data members of derived classes. + virtual const syncable::Entry* GetEntry() const = 0; + virtual const BaseTransaction* GetTransaction() const = 0; + + // Dumps a summary of node info into a DictionaryValue and returns it. + // Transfers ownership of the DictionaryValue to the caller. + base::DictionaryValue* GetSummaryAsValue() const; + + // Dumps all node details into a DictionaryValue and returns it. + // Transfers ownership of the DictionaryValue to the caller. + base::DictionaryValue* GetDetailsAsValue() const; + + protected: + BaseNode(); + virtual ~BaseNode(); + // The server has a size limit on client tags, so we generate a fixed length + // hash locally. This also ensures that ModelTypes have unique namespaces. + static std::string GenerateSyncableHash(syncable::ModelType model_type, + const std::string& client_tag); + + // Determines whether part of the entry is encrypted, and if so attempts to + // decrypt it. Unless decryption is necessary and fails, this will always + // return |true|. If the contents are encrypted, the decrypted data will be + // stored in |unencrypted_data_|. + // This method is invoked once when the BaseNode is initialized. + bool DecryptIfNecessary(); + + // Returns the unencrypted specifics associated with |entry|. If |entry| was + // not encrypted, it directly returns |entry|'s EntitySpecifics. Otherwise, + // returns |unencrypted_data_|. + const sync_pb::EntitySpecifics& GetUnencryptedSpecifics( + const syncable::Entry* entry) const; + + // Copy |specifics| into |unencrypted_data_|. + void SetUnencryptedSpecifics(const sync_pb::EntitySpecifics& specifics); + + private: + void* operator new(size_t size); // Node is meant for stack use only. + + // A holder for the unencrypted data stored in an encrypted node. + sync_pb::EntitySpecifics unencrypted_data_; + + // Same as |unencrypted_data_|, but for legacy password encryption. + scoped_ptr<sync_pb::PasswordSpecificsData> password_data_; + + friend class SyncApiTest; + FRIEND_TEST_ALL_PREFIXES(SyncApiTest, GenerateSyncableHash); + + DISALLOW_COPY_AND_ASSIGN(BaseNode); +}; + +} // namespace sync_api + +#endif // CHROME_BROWSER_SYNC_INTERNAL_API_BASE_NODE_H_ diff --git a/chrome/browser/sync/internal_api/base_transaction.cc b/chrome/browser/sync/internal_api/base_transaction.cc new file mode 100644 index 0000000..8d26702 --- /dev/null +++ b/chrome/browser/sync/internal_api/base_transaction.cc @@ -0,0 +1,35 @@ +// 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 "base_transaction.h" + +#include "chrome/browser/sync/syncable/directory_manager.h" +#include "chrome/browser/sync/util/cryptographer.h" + +using browser_sync::Cryptographer; + +namespace sync_api { + +////////////////////////////////////////////////////////////////////////// +// BaseTransaction member definitions +BaseTransaction::BaseTransaction(UserShare* share) + : lookup_(NULL) { + DCHECK(share && share->dir_manager.get()); + lookup_ = new syncable::ScopedDirLookup(share->dir_manager.get(), + share->name); + cryptographer_ = share->dir_manager->GetCryptographer(this); + if (!(lookup_->good())) + DCHECK(false) << "ScopedDirLookup failed on valid DirManager."; +} +BaseTransaction::~BaseTransaction() { + delete lookup_; +} + +syncable::ModelTypeSet GetEncryptedTypes( + const sync_api::BaseTransaction* trans) { + Cryptographer* cryptographer = trans->GetCryptographer(); + return cryptographer->GetEncryptedTypes(); +} + +} // namespace sync_api diff --git a/chrome/browser/sync/internal_api/base_transaction.h b/chrome/browser/sync/internal_api/base_transaction.h new file mode 100644 index 0000000..9bf2fb3 --- /dev/null +++ b/chrome/browser/sync/internal_api/base_transaction.h @@ -0,0 +1,59 @@ +// 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_INTERNAL_API_BASE_TRANSACTION_H_ +#define CHROME_BROWSER_SYNC_INTERNAL_API_BASE_TRANSACTION_H_ +#pragma once + +#include "chrome/browser/sync/internal_api/user_share.h" + +#include "chrome/browser/sync/util/cryptographer.h" + +namespace syncable { +class BaseTransaction; +class ScopedDirLookup; +} + +namespace sync_api { + +// Sync API's BaseTransaction, ReadTransaction, and WriteTransaction allow for +// batching of several read and/or write operations. The read and write +// operations are performed by creating ReadNode and WriteNode instances using +// the transaction. These transaction classes wrap identically named classes in +// syncable, and are used in a similar way. Unlike syncable::BaseTransaction, +// whose construction requires an explicit syncable::ScopedDirLookup, a sync +// API BaseTransaction creates its own ScopedDirLookup implicitly. +class BaseTransaction { + public: + // Provide access to the underlying syncable.h objects from BaseNode. + virtual syncable::BaseTransaction* GetWrappedTrans() const = 0; + const syncable::ScopedDirLookup& GetLookup() const { return *lookup_; } + browser_sync::Cryptographer* GetCryptographer() const { + return cryptographer_; + } + + protected: + // The ScopedDirLookup is created in the constructor and destroyed + // in the destructor. Creation of the ScopedDirLookup is not expected + // to fail. + explicit BaseTransaction(UserShare* share); + virtual ~BaseTransaction(); + + BaseTransaction() { lookup_= NULL; } + + private: + // A syncable ScopedDirLookup, which is the parent of syncable transactions. + syncable::ScopedDirLookup* lookup_; + + browser_sync::Cryptographer* cryptographer_; + + DISALLOW_COPY_AND_ASSIGN(BaseTransaction); +}; + +syncable::ModelTypeSet GetEncryptedTypes( + const sync_api::BaseTransaction* trans); + +} // namespace sync_api + +#endif // CHROME_BROWSER_SYNC_INTERNAL_API_BASE_TRANSACTION_H_ diff --git a/chrome/browser/sync/internal_api/read_node.cc b/chrome/browser/sync/internal_api/read_node.cc new file mode 100644 index 0000000..73e0b29 --- /dev/null +++ b/chrome/browser/sync/internal_api/read_node.cc @@ -0,0 +1,92 @@ +// 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/internal_api/read_node.h" + +#include "base/logging.h" +#include "chrome/browser/sync/internal_api/base_transaction.h" +#include "chrome/browser/sync/syncable/syncable.h" + +namespace sync_api { + +////////////////////////////////////////////////////////////////////////// +// ReadNode member definitions +ReadNode::ReadNode(const BaseTransaction* transaction) + : entry_(NULL), transaction_(transaction) { + DCHECK(transaction); +} + +ReadNode::ReadNode() { + entry_ = NULL; + transaction_ = NULL; +} + +ReadNode::~ReadNode() { + delete entry_; +} + +void ReadNode::InitByRootLookup() { + DCHECK(!entry_) << "Init called twice"; + syncable::BaseTransaction* trans = transaction_->GetWrappedTrans(); + entry_ = new syncable::Entry(trans, syncable::GET_BY_ID, trans->root_id()); + if (!entry_->good()) + DCHECK(false) << "Could not lookup root node for reading."; +} + +bool ReadNode::InitByIdLookup(int64 id) { + DCHECK(!entry_) << "Init called twice"; + DCHECK_NE(id, kInvalidId); + syncable::BaseTransaction* trans = transaction_->GetWrappedTrans(); + entry_ = new syncable::Entry(trans, syncable::GET_BY_HANDLE, id); + if (!entry_->good()) + return false; + if (entry_->Get(syncable::IS_DEL)) + return false; + syncable::ModelType model_type = GetModelType(); + LOG_IF(WARNING, model_type == syncable::UNSPECIFIED || + model_type == syncable::TOP_LEVEL_FOLDER) + << "SyncAPI InitByIdLookup referencing unusual object."; + return DecryptIfNecessary(); +} + +bool ReadNode::InitByClientTagLookup(syncable::ModelType model_type, + const std::string& tag) { + DCHECK(!entry_) << "Init called twice"; + if (tag.empty()) + return false; + + const std::string hash = GenerateSyncableHash(model_type, tag); + + entry_ = new syncable::Entry(transaction_->GetWrappedTrans(), + syncable::GET_BY_CLIENT_TAG, hash); + return (entry_->good() && !entry_->Get(syncable::IS_DEL) && + DecryptIfNecessary()); +} + +const syncable::Entry* ReadNode::GetEntry() const { + return entry_; +} + +const BaseTransaction* ReadNode::GetTransaction() const { + return transaction_; +} + +bool ReadNode::InitByTagLookup(const std::string& tag) { + DCHECK(!entry_) << "Init called twice"; + if (tag.empty()) + return false; + syncable::BaseTransaction* trans = transaction_->GetWrappedTrans(); + entry_ = new syncable::Entry(trans, syncable::GET_BY_SERVER_TAG, tag); + if (!entry_->good()) + return false; + if (entry_->Get(syncable::IS_DEL)) + return false; + syncable::ModelType model_type = GetModelType(); + LOG_IF(WARNING, model_type == syncable::UNSPECIFIED || + model_type == syncable::TOP_LEVEL_FOLDER) + << "SyncAPI InitByTagLookup referencing unusually typed object."; + return DecryptIfNecessary(); +} + +} // namespace sync_api diff --git a/chrome/browser/sync/internal_api/read_node.h b/chrome/browser/sync/internal_api/read_node.h new file mode 100644 index 0000000..9ad9715 --- /dev/null +++ b/chrome/browser/sync/internal_api/read_node.h @@ -0,0 +1,79 @@ +// 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_INTERNAL_API_READ_NODE_H_ +#define CHROME_BROWSER_SYNC_INTERNAL_API_READ_NODE_H_ +#pragma once + +#include <string> + +#include "base/basictypes.h" +#include "chrome/browser/sync/internal_api/base_node.h" +#include "chrome/browser/sync/syncable/model_type.h" + +namespace sync_pb { +class AppSpecifics; +class AutofillSpecifics; +class AutofillProfileSpecifics; +class BookmarkSpecifics; +class EntitySpecifics; +class ExtensionSpecifics; +class SessionSpecifics; +class NigoriSpecifics; +class PreferenceSpecifics; +class PasswordSpecificsData; +class ThemeSpecifics; +class TypedUrlSpecifics; +} + +namespace sync_api { + +// ReadNode wraps a syncable::Entry to provide the functionality of a +// read-only BaseNode. +class ReadNode : public BaseNode { + public: + // Create an unpopulated ReadNode on the given transaction. Call some flavor + // of Init to populate the ReadNode with a database entry. + explicit ReadNode(const BaseTransaction* transaction); + virtual ~ReadNode(); + + // A client must use one (and only one) of the following Init variants to + // populate the node. + + // BaseNode implementation. + virtual bool InitByIdLookup(int64 id); + virtual bool InitByClientTagLookup(syncable::ModelType model_type, + const std::string& tag); + + // There is always a root node, so this can't fail. The root node is + // never mutable, so root lookup is only possible on a ReadNode. + void InitByRootLookup(); + + // Each server-created permanent node is tagged with a unique string. + // Look up the node with the particular tag. If it does not exist, + // return false. + bool InitByTagLookup(const std::string& tag); + + // Implementation of BaseNode's abstract virtual accessors. + virtual const syncable::Entry* GetEntry() const; + virtual const BaseTransaction* GetTransaction() const; + + protected: + ReadNode(); + + private: + void* operator new(size_t size); // Node is meant for stack use only. + + // The underlying syncable object which this class wraps. + syncable::Entry* entry_; + + // The sync API transaction that is the parent of this node. + const BaseTransaction* transaction_; + + DISALLOW_COPY_AND_ASSIGN(ReadNode); +}; + +} // namespace sync_api + +#endif // CHROME_BROWSER_SYNC_INTERNAL_API_READ_NODE_H_ diff --git a/chrome/browser/sync/internal_api/read_node_mock.cc b/chrome/browser/sync/internal_api/read_node_mock.cc new file mode 100644 index 0000000..64007b5 --- /dev/null +++ b/chrome/browser/sync/internal_api/read_node_mock.cc @@ -0,0 +1,11 @@ +// 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/internal_api/read_node_mock.h" + +#include "chrome/browser/sync/protocol/autofill_specifics.pb.h" + +ReadNodeMock::ReadNodeMock() {} + +ReadNodeMock::~ReadNodeMock() {} diff --git a/chrome/browser/sync/internal_api/read_node_mock.h b/chrome/browser/sync/internal_api/read_node_mock.h new file mode 100644 index 0000000..598d4e2 --- /dev/null +++ b/chrome/browser/sync/internal_api/read_node_mock.h @@ -0,0 +1,30 @@ +// 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_INTERNAL_API_READ_NODE_MOCK_H_
+#define CHROME_BROWSER_SYNC_INTERNAL_API_READ_NODE_MOCK_H_
+#pragma once
+
+#include <string>
+
+#include "chrome/browser/sync/internal_api/read_node.h"
+#include "testing/gmock/include/gmock/gmock.h"
+
+class ReadNodeMock : public sync_api::ReadNode {
+ public:
+ ReadNodeMock();
+ virtual ~ReadNodeMock();
+
+ MOCK_METHOD2(InitByClientTagLookup,
+ bool(syncable::ModelType model_type, const std::string& tag));
+ MOCK_CONST_METHOD0(GetAutofillProfileSpecifics,
+ const sync_pb::AutofillProfileSpecifics&());
+ MOCK_CONST_METHOD0(GetId, int64());
+ MOCK_CONST_METHOD0(GetFirstChildId, int64());
+ MOCK_CONST_METHOD0(GetFirstChild, int64());
+ MOCK_CONST_METHOD0(GetSuccessorId, int64());
+ MOCK_METHOD1(InitByIdLookup, bool(int64 id));
+};
+
+#endif // CHROME_BROWSER_SYNC_INTERNAL_API_READ_NODE_MOCK_H_
diff --git a/chrome/browser/sync/internal_api/read_transaction.cc b/chrome/browser/sync/internal_api/read_transaction.cc new file mode 100644 index 0000000..40691dd --- /dev/null +++ b/chrome/browser/sync/internal_api/read_transaction.cc @@ -0,0 +1,37 @@ +// 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/internal_api/read_transaction.h" + +#include "chrome/browser/sync/syncable/syncable.h" + +namespace sync_api { + +////////////////////////////////////////////////////////////////////////// +// ReadTransaction member definitions +ReadTransaction::ReadTransaction(const tracked_objects::Location& from_here, + UserShare* share) + : BaseTransaction(share), + transaction_(NULL), + close_transaction_(true) { + transaction_ = new syncable::ReadTransaction(from_here, GetLookup()); +} + +ReadTransaction::ReadTransaction(UserShare* share, + syncable::BaseTransaction* trans) + : BaseTransaction(share), + transaction_(trans), + close_transaction_(false) {} + +ReadTransaction::~ReadTransaction() { + if (close_transaction_) { + delete transaction_; + } +} + +syncable::BaseTransaction* ReadTransaction::GetWrappedTrans() const { + return transaction_; +} + +} // namespace sync_api diff --git a/chrome/browser/sync/internal_api/read_transaction.h b/chrome/browser/sync/internal_api/read_transaction.h new file mode 100644 index 0000000..c1b97d9 --- /dev/null +++ b/chrome/browser/sync/internal_api/read_transaction.h @@ -0,0 +1,45 @@ +// 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_INTERNAL_API_READ_TRANSACTION_H_ +#define CHROME_BROWSER_SYNC_INTERNAL_API_READ_TRANSACTION_H_ + +#include "chrome/browser/sync/internal_api/base_transaction.h" + +namespace tracked_objects { +class Location; +} // namespace tracked_objects + +namespace sync_api { + +struct UserShare; + +// Sync API's ReadTransaction is a read-only BaseTransaction. It wraps +// a syncable::ReadTransaction. +class ReadTransaction : public BaseTransaction { + public: + // Start a new read-only transaction on the specified repository. + ReadTransaction(const tracked_objects::Location& from_here, + UserShare* share); + + // Resume the middle of a transaction. Will not close transaction. + ReadTransaction(UserShare* share, syncable::BaseTransaction* trans); + + virtual ~ReadTransaction(); + + // BaseTransaction override. + virtual syncable::BaseTransaction* GetWrappedTrans() const; + private: + void* operator new(size_t size); // Transaction is meant for stack use only. + + // The underlying syncable object which this class wraps. + syncable::BaseTransaction* transaction_; + bool close_transaction_; + + DISALLOW_COPY_AND_ASSIGN(ReadTransaction); +}; + +} // namespace sync_api + +#endif // CHROME_BROWSER_SYNC_INTERNAL_API_READ_TRANSACTION_H_ diff --git a/chrome/browser/sync/internal_api/sync_manager.cc b/chrome/browser/sync/internal_api/sync_manager.cc new file mode 100644 index 0000000..40ebdd5 --- /dev/null +++ b/chrome/browser/sync/internal_api/sync_manager.cc @@ -0,0 +1,2047 @@ +// 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/internal_api/sync_manager.h" + +#include <string> +#include <vector> + +#include "base/base64.h" +#include "base/json/json_writer.h" +#include "base/string_number_conversions.h" +#include "base/values.h" +#include "chrome/browser/sync/engine/all_status.h" +#include "chrome/browser/sync/engine/change_reorder_buffer.h" +#include "chrome/browser/sync/engine/net/server_connection_manager.h" +#include "chrome/browser/sync/engine/net/syncapi_server_connection_manager.h" +#include "chrome/browser/sync/engine/nigori_util.h" +#include "chrome/browser/sync/engine/syncapi_internal.h" +#include "chrome/browser/sync/engine/syncer_types.h" +#include "chrome/browser/sync/engine/sync_scheduler.h" +#include "chrome/browser/sync/internal_api/base_node.h" +#include "chrome/browser/sync/internal_api/read_node.h" +#include "chrome/browser/sync/internal_api/read_transaction.h" +#include "chrome/browser/sync/internal_api/user_share.h" +#include "chrome/browser/sync/internal_api/write_node.h" +#include "chrome/browser/sync/internal_api/write_transaction.h" +#include "chrome/browser/sync/js/js_arg_list.h" +#include "chrome/browser/sync/js/js_backend.h" +#include "chrome/browser/sync/js/js_event_details.h" +#include "chrome/browser/sync/js/js_event_handler.h" +#include "chrome/browser/sync/js/js_reply_handler.h" +#include "chrome/browser/sync/js/js_sync_manager_observer.h" +#include "chrome/browser/sync/js/js_transaction_observer.h" +#include "chrome/browser/sync/notifier/sync_notifier.h" +#include "chrome/browser/sync/notifier/sync_notifier_observer.h" +#include "chrome/browser/sync/protocol/proto_value_conversions.h" +#include "chrome/browser/sync/syncable/directory_change_delegate.h" +#include "chrome/browser/sync/syncable/directory_manager.h" +#include "chrome/browser/sync/syncable/model_type.h" +#include "chrome/browser/sync/syncable/syncable.h" +#include "chrome/browser/sync/util/cryptographer.h" +#include "chrome/browser/sync/weak_handle.h" +#include "net/base/network_change_notifier.h" + +using std::string; +using std::vector; + +using base::TimeDelta; +using browser_sync::AllStatus; +using browser_sync::Cryptographer; +using browser_sync::JsArgList; +using browser_sync::JsBackend; +using browser_sync::JsEventDetails; +using browser_sync::JsEventHandler; +using browser_sync::JsEventHandler; +using browser_sync::JsReplyHandler; +using browser_sync::JsSyncManagerObserver; +using browser_sync::JsTransactionObserver; +using browser_sync::ModelSafeWorkerRegistrar; +using browser_sync::kNigoriTag; +using browser_sync::KeyParams; +using browser_sync::ModelSafeRoutingInfo; +using browser_sync::ServerConnectionEvent; +using browser_sync::ServerConnectionEventListener; +using browser_sync::SyncEngineEvent; +using browser_sync::SyncEngineEventListener; +using browser_sync::SyncScheduler; +using browser_sync::Syncer; +using browser_sync::WeakHandle; +using browser_sync::sessions::SyncSessionContext; +using syncable::DirectoryManager; +using syncable::EntryKernelMutationSet; +using syncable::ModelType; +using syncable::ModelTypeBitSet; +using syncable::SPECIFICS; + +typedef GoogleServiceAuthError AuthError; + +namespace { + +static const int kSyncSchedulerDelayMsec = 250; + +#if defined(OS_CHROMEOS) +static const int kChromeOSNetworkChangeReactionDelayHackMsec = 5000; +#endif // OS_CHROMEOS + +} // namespace + +namespace sync_api { + +SyncManager::ChangeRecord::ChangeRecord() + : id(kInvalidId), action(ACTION_ADD) {} + +SyncManager::ChangeRecord::~ChangeRecord() {} + +DictionaryValue* SyncManager::ChangeRecord::ToValue( + const BaseTransaction* trans) const { + DictionaryValue* value = new DictionaryValue(); + std::string action_str; + switch (action) { + case ACTION_ADD: + action_str = "Add"; + break; + case ACTION_DELETE: + action_str = "Delete"; + break; + case ACTION_UPDATE: + action_str = "Update"; + break; + default: + NOTREACHED(); + action_str = "Unknown"; + break; + } + value->SetString("action", action_str); + Value* node_value = NULL; + if (action == ACTION_DELETE) { + DictionaryValue* node_dict = new DictionaryValue(); + node_dict->SetString("id", base::Int64ToString(id)); + node_dict->Set("specifics", + browser_sync::EntitySpecificsToValue(specifics)); + if (extra.get()) { + node_dict->Set("extra", extra->ToValue()); + } + node_value = node_dict; + } else { + ReadNode node(trans); + if (node.InitByIdLookup(id)) { + node_value = node.GetDetailsAsValue(); + } + } + if (!node_value) { + NOTREACHED(); + node_value = Value::CreateNullValue(); + } + value->Set("node", node_value); + return value; +} + +SyncManager::ExtraPasswordChangeRecordData::ExtraPasswordChangeRecordData() {} + +SyncManager::ExtraPasswordChangeRecordData::ExtraPasswordChangeRecordData( + const sync_pb::PasswordSpecificsData& data) + : unencrypted_(data) { +} + +SyncManager::ExtraPasswordChangeRecordData::~ExtraPasswordChangeRecordData() {} + +DictionaryValue* SyncManager::ExtraPasswordChangeRecordData::ToValue() const { + return browser_sync::PasswordSpecificsDataToValue(unencrypted_); +} + +const sync_pb::PasswordSpecificsData& + SyncManager::ExtraPasswordChangeRecordData::unencrypted() const { + return unencrypted_; +} + +////////////////////////////////////////////////////////////////////////// +// SyncManager's implementation: SyncManager::SyncInternal +class SyncManager::SyncInternal + : public net::NetworkChangeNotifier::IPAddressObserver, + public sync_notifier::SyncNotifierObserver, + public JsBackend, + public SyncEngineEventListener, + public ServerConnectionEventListener, + public syncable::DirectoryChangeDelegate { + static const int kDefaultNudgeDelayMilliseconds; + static const int kPreferencesNudgeDelayMilliseconds; + public: + explicit SyncInternal(const std::string& name) + : weak_ptr_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)), + registrar_(NULL), + initialized_(false), + setup_for_test_mode_(false), + observing_ip_address_changes_(false) { + // Pre-fill |notification_info_map_|. + for (int i = syncable::FIRST_REAL_MODEL_TYPE; + i < syncable::MODEL_TYPE_COUNT; ++i) { + notification_info_map_.insert( + std::make_pair(syncable::ModelTypeFromInt(i), NotificationInfo())); + } + + // Bind message handlers. + BindJsMessageHandler( + "getNotificationState", + &SyncManager::SyncInternal::GetNotificationState); + BindJsMessageHandler( + "getNotificationInfo", + &SyncManager::SyncInternal::GetNotificationInfo); + BindJsMessageHandler( + "getRootNodeDetails", + &SyncManager::SyncInternal::GetRootNodeDetails); + BindJsMessageHandler( + "getNodeSummariesById", + &SyncManager::SyncInternal::GetNodeSummariesById); + BindJsMessageHandler( + "getNodeDetailsById", + &SyncManager::SyncInternal::GetNodeDetailsById); + BindJsMessageHandler( + "getChildNodeIds", + &SyncManager::SyncInternal::GetChildNodeIds); + BindJsMessageHandler( + "findNodesContainingString", + &SyncManager::SyncInternal::FindNodesContainingString); + } + + virtual ~SyncInternal() { + CHECK(!initialized_); + } + + bool Init(const FilePath& database_location, + const WeakHandle<JsEventHandler>& event_handler, + const std::string& sync_server_and_path, + int port, + bool use_ssl, + HttpPostProviderFactory* post_factory, + ModelSafeWorkerRegistrar* model_safe_worker_registrar, + const std::string& user_agent, + const SyncCredentials& credentials, + sync_notifier::SyncNotifier* sync_notifier, + const std::string& restored_key_for_bootstrapping, + bool setup_for_test_mode); + + // Sign into sync with given credentials. + // We do not verify the tokens given. After this call, the tokens are set + // and the sync DB is open. True if successful, false if something + // went wrong. + bool SignIn(const SyncCredentials& credentials); + + // Update tokens that we're using in Sync. Email must stay the same. + void UpdateCredentials(const SyncCredentials& credentials); + + // Called when the user disables or enables a sync type. + void UpdateEnabledTypes(); + + // Tell the sync engine to start the syncing process. + void StartSyncingNormally(); + + // Whether or not the Nigori node is encrypted using an explicit passphrase. + bool IsUsingExplicitPassphrase(); + + // Update the Cryptographer from the current nigori node. + // Note: opens a transaction and can trigger an ON_PASSPHRASE_REQUIRED, so + // should only be called after syncapi is fully initialized. + // Returns true if cryptographer is ready, false otherwise. + bool UpdateCryptographerFromNigori(); + + // Set the datatypes we want to encrypt and encrypt any nodes as necessary. + // Note: |encrypted_types| will be unioned with the current set of encrypted + // types, as we do not currently support decrypting datatypes. + void EncryptDataTypes(const syncable::ModelTypeSet& encrypted_types); + + // Try to set the current passphrase to |passphrase|, and record whether + // it is an explicit passphrase or implicitly using gaia in the Nigori + // node. + void SetPassphrase(const std::string& passphrase, bool is_explicit); + + // Call periodically from a database-safe thread to persist recent changes + // to the syncapi model. + void SaveChanges(); + + // DirectoryChangeDelegate implementation. + // This listener is called upon completion of a syncable transaction, and + // builds the list of sync-engine initiated changes that will be forwarded to + // the SyncManager's Observers. + virtual void HandleTransactionCompleteChangeEvent( + const ModelTypeBitSet& models_with_changes); + virtual ModelTypeBitSet HandleTransactionEndingChangeEvent( + syncable::BaseTransaction* trans); + virtual void HandleCalculateChangesChangeEventFromSyncApi( + const EntryKernelMutationSet& mutations, + syncable::BaseTransaction* trans); + virtual void HandleCalculateChangesChangeEventFromSyncer( + const EntryKernelMutationSet& mutations, + syncable::BaseTransaction* trans); + + // Listens for notifications from the ServerConnectionManager + void HandleServerConnectionEvent(const ServerConnectionEvent& event); + + // Open the directory named with username_for_share + bool OpenDirectory(); + + // SyncNotifierObserver implementation. + virtual void OnNotificationStateChange( + bool notifications_enabled); + + virtual void OnIncomingNotification( + const syncable::ModelTypePayloadMap& type_payloads); + + virtual void StoreState(const std::string& cookie); + + // Thread-safe observers_ accessors. + void CopyObservers(ObserverList<SyncManager::Observer>* observers_copy); + bool HaveObservers() const; + void AddObserver(SyncManager::Observer* observer); + void RemoveObserver(SyncManager::Observer* observer); + + // Accessors for the private members. + DirectoryManager* dir_manager() { return share_.dir_manager.get(); } + SyncAPIServerConnectionManager* connection_manager() { + return connection_manager_.get(); + } + SyncScheduler* scheduler() { return scheduler_.get(); } + UserShare* GetUserShare() { + DCHECK(initialized_); + return &share_; + } + + // Return the currently active (validated) username for use with syncable + // types. + const std::string& username_for_share() const { + return share_.name; + } + + Status GetStatus(); + + void RequestNudge(const tracked_objects::Location& nudge_location); + + void RequestNudgeForDataType( + const tracked_objects::Location& nudge_location, + const ModelType& type); + + void RequestEarlyExit(); + + // See SyncManager::Shutdown for information. + void Shutdown(); + + // If this is a deletion for a password, sets the legacy + // ExtraPasswordChangeRecordData field of |buffer|. Otherwise sets + // |buffer|'s specifics field to contain the unencrypted data. + void SetExtraChangeRecordData(int64 id, + syncable::ModelType type, + ChangeReorderBuffer* buffer, + Cryptographer* cryptographer, + const syncable::EntryKernel& original, + bool existed_before, + bool exists_now); + + // Called only by our NetworkChangeNotifier. + virtual void OnIPAddressChanged(); + + bool InitialSyncEndedForAllEnabledTypes() { + syncable::ModelTypeSet types; + ModelSafeRoutingInfo enabled_types; + registrar_->GetModelSafeRoutingInfo(&enabled_types); + for (ModelSafeRoutingInfo::const_iterator i = enabled_types.begin(); + i != enabled_types.end(); ++i) { + types.insert(i->first); + } + + return InitialSyncEndedForTypes(types, &share_); + } + + // SyncEngineEventListener implementation. + virtual void OnSyncEngineEvent(const SyncEngineEvent& event); + + // ServerConnectionEventListener implementation. + virtual void OnServerConnectionEvent(const ServerConnectionEvent& event); + + // JsBackend implementation. + virtual void SetJsEventHandler( + const WeakHandle<JsEventHandler>& event_handler) OVERRIDE; + virtual void ProcessJsMessage( + const std::string& name, const JsArgList& args, + const WeakHandle<JsReplyHandler>& reply_handler) OVERRIDE; + + private: + struct NotificationInfo { + int total_count; + std::string payload; + + NotificationInfo() : total_count(0) {} + + ~NotificationInfo() {} + + // Returned pointer owned by the caller. + DictionaryValue* ToValue() const { + DictionaryValue* value = new DictionaryValue(); + value->SetInteger("totalCount", total_count); + value->SetString("payload", payload); + return value; + } + }; + + typedef std::map<syncable::ModelType, NotificationInfo> NotificationInfoMap; + typedef JsArgList + (SyncManager::SyncInternal::*UnboundJsMessageHandler)(const JsArgList&); + typedef base::Callback<JsArgList(JsArgList)> JsMessageHandler; + typedef std::map<std::string, JsMessageHandler> JsMessageHandlerMap; + + // Helper to call OnAuthError when no authentication credentials are + // available. + void RaiseAuthNeededEvent(); + + // Determine if the parents or predecessors differ between the old and new + // versions of an entry stored in |a| and |b|. Note that a node's index may + // change without its NEXT_ID changing if the node at NEXT_ID also moved (but + // the relative order is unchanged). To handle such cases, we rely on the + // caller to treat a position update on any sibling as updating the positions + // of all siblings. + static bool VisiblePositionsDiffer( + const syncable::EntryKernelMutation& mutation) { + const syncable::EntryKernel& a = mutation.original; + const syncable::EntryKernel& b = mutation.mutated; + // If the datatype isn't one where the browser model cares about position, + // don't bother notifying that data model of position-only changes. + if (!ShouldMaintainPosition( + syncable::GetModelTypeFromSpecifics(b.ref(SPECIFICS)))) + return false; + if (a.ref(syncable::NEXT_ID) != b.ref(syncable::NEXT_ID)) + return true; + if (a.ref(syncable::PARENT_ID) != b.ref(syncable::PARENT_ID)) + return true; + return false; + } + + // Determine if any of the fields made visible to clients of the Sync API + // differ between the versions of an entry stored in |a| and |b|. A return + // value of false means that it should be OK to ignore this change. + static bool VisiblePropertiesDiffer( + const syncable::EntryKernelMutation& mutation, + Cryptographer* cryptographer) { + const syncable::EntryKernel& a = mutation.original; + const syncable::EntryKernel& b = mutation.mutated; + const sync_pb::EntitySpecifics& a_specifics = a.ref(SPECIFICS); + const sync_pb::EntitySpecifics& b_specifics = b.ref(SPECIFICS); + DCHECK_EQ(syncable::GetModelTypeFromSpecifics(a_specifics), + syncable::GetModelTypeFromSpecifics(b_specifics)); + syncable::ModelType model_type = + syncable::GetModelTypeFromSpecifics(b_specifics); + // Suppress updates to items that aren't tracked by any browser model. + if (model_type < syncable::FIRST_REAL_MODEL_TYPE || + !a.ref(syncable::UNIQUE_SERVER_TAG).empty()) { + return false; + } + if (a.ref(syncable::IS_DIR) != b.ref(syncable::IS_DIR)) + return true; + if (!AreSpecificsEqual(cryptographer, + a.ref(syncable::SPECIFICS), + b.ref(syncable::SPECIFICS))) { + return true; + } + // We only care if the name has changed if neither specifics is encrypted + // (encrypted nodes blow away the NON_UNIQUE_NAME). + if (!a_specifics.has_encrypted() && !b_specifics.has_encrypted() && + a.ref(syncable::NON_UNIQUE_NAME) != b.ref(syncable::NON_UNIQUE_NAME)) + return true; + if (VisiblePositionsDiffer(mutation)) + return true; + return false; + } + + bool ChangeBuffersAreEmpty() { + for (int i = 0; i < syncable::MODEL_TYPE_COUNT; ++i) { + if (!change_buffers_[i].IsEmpty()) + return false; + } + return true; + } + + void CheckServerReachable() { + if (connection_manager()) { + connection_manager()->CheckServerReachable(); + } else { + NOTREACHED() << "Should be valid connection manager!"; + } + } + + void ReEncryptEverything(WriteTransaction* trans); + + // Initializes (bootstraps) the Cryptographer if NIGORI has finished + // initial sync so that it can immediately start encrypting / decrypting. + // If the restored key is incompatible with the current version of the NIGORI + // node (which could happen if a restart occurred just after an update to + // NIGORI was downloaded and the user must enter a new passphrase to decrypt) + // then we will raise OnPassphraseRequired and set pending keys for + // decryption. Otherwise, the cryptographer is made ready (is_ready()). + void BootstrapEncryption(const std::string& restored_key_for_bootstrapping); + + // Called for every notification. This updates the notification statistics + // to be displayed in about:sync. + void UpdateNotificationInfo( + const syncable::ModelTypePayloadMap& type_payloads); + + // Checks for server reachabilty and requests a nudge. + void OnIPAddressChangedImpl(); + + // Helper function used only by the constructor. + void BindJsMessageHandler( + const std::string& name, UnboundJsMessageHandler unbound_message_handler); + + // Returned pointer is owned by the caller. + static DictionaryValue* NotificationInfoToValue( + const NotificationInfoMap& notification_info); + + // JS message handlers. + JsArgList GetNotificationState(const JsArgList& args); + JsArgList GetNotificationInfo(const JsArgList& args); + JsArgList GetRootNodeDetails(const JsArgList& args); + JsArgList GetNodeSummariesById(const JsArgList& args); + JsArgList GetNodeDetailsById(const JsArgList& args); + JsArgList GetChildNodeIds(const JsArgList& args); + JsArgList FindNodesContainingString(const JsArgList& args); + + const std::string name_; + + base::ThreadChecker thread_checker_; + + base::WeakPtrFactory<SyncInternal> weak_ptr_factory_; + + // Thread-safe handle used by + // HandleCalculateChangesChangeEventFromSyncApi(), which can be + // called from any thread. Valid only between between calls to + // Init() and Shutdown(). + // + // TODO(akalin): Ideally, we wouldn't need to store this; instead, + // we'd have another worker class which implements + // HandleCalculateChangesChangeEventFromSyncApi() and we'd pass it a + // WeakHandle when we construct it. + WeakHandle<SyncInternal> weak_handle_this_; + + // We couple the DirectoryManager and username together in a UserShare member + // so we can return a handle to share_ to clients of the API for use when + // constructing any transaction type. + UserShare share_; + + // We have to lock around every observers_ access because it can get accessed + // from any thread and added to/removed from on the core thread. + mutable base::Lock observers_lock_; + ObserverList<SyncManager::Observer> observers_; + + // The ServerConnectionManager used to abstract communication between the + // client (the Syncer) and the sync server. + scoped_ptr<SyncAPIServerConnectionManager> connection_manager_; + + // The scheduler that runs the Syncer. Needs to be explicitly + // Start()ed. + scoped_ptr<SyncScheduler> scheduler_; + + // The SyncNotifier which notifies us when updates need to be downloaded. + scoped_ptr<sync_notifier::SyncNotifier> sync_notifier_; + + // A multi-purpose status watch object that aggregates stats from various + // sync components. + AllStatus allstatus_; + + // Each element of this array is a store of change records produced by + // HandleChangeEvent during the CALCULATE_CHANGES step. The changes are + // segregated by model type, and are stored here to be processed and + // forwarded to the observer slightly later, at the TRANSACTION_ENDING + // step by HandleTransactionEndingChangeEvent. The list is cleared in the + // TRANSACTION_COMPLETE step by HandleTransactionCompleteChangeEvent. + ChangeReorderBuffer change_buffers_[syncable::MODEL_TYPE_COUNT]; + + // The entity that provides us with information about which types to sync. + // The instance is shared between the SyncManager and the Syncer. + ModelSafeWorkerRegistrar* registrar_; + + // Set to true once Init has been called. + bool initialized_; + + // True if the SyncManager should be running in test mode (no sync + // scheduler actually communicating with the server). + bool setup_for_test_mode_; + + // Whether we should respond to an IP address change notification. + bool observing_ip_address_changes_; + + // Map used to store the notification info to be displayed in + // about:sync page. + NotificationInfoMap notification_info_map_; + + // These are for interacting with chrome://sync-internals. + JsMessageHandlerMap js_message_handlers_; + WeakHandle<JsEventHandler> js_event_handler_; + JsSyncManagerObserver js_sync_manager_observer_; + JsTransactionObserver js_transaction_observer_; +}; +const int SyncManager::SyncInternal::kDefaultNudgeDelayMilliseconds = 200; +const int SyncManager::SyncInternal::kPreferencesNudgeDelayMilliseconds = 2000; + +SyncManager::Observer::~Observer() {} + +SyncManager::SyncManager(const std::string& name) + : data_(new SyncInternal(name)) {} + +SyncManager::Status::Status() + : summary(INVALID), + authenticated(false), + server_up(false), + server_reachable(false), + server_broken(false), + notifications_enabled(false), + notifications_received(0), + notifiable_commits(0), + max_consecutive_errors(0), + unsynced_count(0), + conflicting_count(0), + syncing(false), + initial_sync_ended(false), + syncer_stuck(false), + updates_available(0), + updates_received(0), + tombstone_updates_received(0), + disk_full(false), + num_local_overwrites_total(0), + num_server_overwrites_total(0), + nonempty_get_updates(0), + empty_get_updates(0), + useless_sync_cycles(0), + useful_sync_cycles(0), + cryptographer_ready(false), + crypto_has_pending_keys(false) { +} + +SyncManager::Status::~Status() { +} + +bool SyncManager::Init( + const FilePath& database_location, + const WeakHandle<JsEventHandler>& event_handler, + const std::string& sync_server_and_path, + int sync_server_port, + bool use_ssl, + HttpPostProviderFactory* post_factory, + ModelSafeWorkerRegistrar* registrar, + const std::string& user_agent, + const SyncCredentials& credentials, + sync_notifier::SyncNotifier* sync_notifier, + const std::string& restored_key_for_bootstrapping, + bool setup_for_test_mode) { + DCHECK(post_factory); + VLOG(1) << "SyncManager starting Init..."; + string server_string(sync_server_and_path); + return data_->Init(database_location, + event_handler, + server_string, + sync_server_port, + use_ssl, + post_factory, + registrar, + user_agent, + credentials, + sync_notifier, + restored_key_for_bootstrapping, + setup_for_test_mode); +} + +void SyncManager::UpdateCredentials(const SyncCredentials& credentials) { + data_->UpdateCredentials(credentials); +} + +void SyncManager::UpdateEnabledTypes() { + data_->UpdateEnabledTypes(); +} + +bool SyncManager::InitialSyncEndedForAllEnabledTypes() { + return data_->InitialSyncEndedForAllEnabledTypes(); +} + +void SyncManager::StartSyncingNormally() { + data_->StartSyncingNormally(); +} + +void SyncManager::SetPassphrase(const std::string& passphrase, + bool is_explicit) { + data_->SetPassphrase(passphrase, is_explicit); +} + +void SyncManager::EncryptDataTypes( + const syncable::ModelTypeSet& encrypted_types) { + data_->EncryptDataTypes(encrypted_types); +} + +bool SyncManager::IsUsingExplicitPassphrase() { + return data_ && data_->IsUsingExplicitPassphrase(); +} + +void SyncManager::RequestCleanupDisabledTypes() { + if (data_->scheduler()) + data_->scheduler()->ScheduleCleanupDisabledTypes(); +} + +void SyncManager::RequestClearServerData() { + if (data_->scheduler()) + data_->scheduler()->ScheduleClearUserData(); +} + +void SyncManager::RequestConfig(const syncable::ModelTypeBitSet& types, + ConfigureReason reason) { + if (!data_->scheduler()) { + LOG(INFO) + << "SyncManager::RequestConfig: bailing out because scheduler is " + << "null"; + return; + } + StartConfigurationMode(NULL); + data_->scheduler()->ScheduleConfig(types, reason); +} + +void SyncManager::StartConfigurationMode(ModeChangeCallback* callback) { + if (!data_->scheduler()) { + LOG(INFO) + << "SyncManager::StartConfigurationMode: could not start " + << "configuration mode because because scheduler is null"; + return; + } + data_->scheduler()->Start( + browser_sync::SyncScheduler::CONFIGURATION_MODE, callback); +} + +const std::string& SyncManager::GetAuthenticatedUsername() { + DCHECK(data_); + return data_->username_for_share(); +} + +bool SyncManager::SyncInternal::Init( + const FilePath& database_location, + const WeakHandle<JsEventHandler>& event_handler, + const std::string& sync_server_and_path, + int port, + bool use_ssl, + HttpPostProviderFactory* post_factory, + ModelSafeWorkerRegistrar* model_safe_worker_registrar, + const std::string& user_agent, + const SyncCredentials& credentials, + sync_notifier::SyncNotifier* sync_notifier, + const std::string& restored_key_for_bootstrapping, + bool setup_for_test_mode) { + CHECK(!initialized_); + + DCHECK(thread_checker_.CalledOnValidThread()); + + VLOG(1) << "Starting SyncInternal initialization."; + + weak_handle_this_ = MakeWeakHandle(weak_ptr_factory_.GetWeakPtr()); + + registrar_ = model_safe_worker_registrar; + setup_for_test_mode_ = setup_for_test_mode; + + sync_notifier_.reset(sync_notifier); + + AddObserver(&js_sync_manager_observer_); + SetJsEventHandler(event_handler); + + share_.dir_manager.reset(new DirectoryManager(database_location)); + + connection_manager_.reset(new SyncAPIServerConnectionManager( + sync_server_and_path, port, use_ssl, user_agent, post_factory)); + + net::NetworkChangeNotifier::AddIPAddressObserver(this); + observing_ip_address_changes_ = true; + + connection_manager()->AddListener(this); + + // TODO(akalin): CheckServerReachable() can block, which may cause jank if we + // try to shut down sync. Fix this. + MessageLoop::current()->PostTask( + FROM_HERE, base::Bind(&SyncInternal::CheckServerReachable, + weak_ptr_factory_.GetWeakPtr())); + + // Test mode does not use a syncer context or syncer thread. + if (!setup_for_test_mode_) { + // Build a SyncSessionContext and store the worker in it. + VLOG(1) << "Sync is bringing up SyncSessionContext."; + std::vector<SyncEngineEventListener*> listeners; + listeners.push_back(&allstatus_); + listeners.push_back(this); + SyncSessionContext* context = new SyncSessionContext( + connection_manager_.get(), + dir_manager(), + model_safe_worker_registrar, + listeners); + context->set_account_name(credentials.email); + // The SyncScheduler takes ownership of |context|. + scheduler_.reset(new SyncScheduler(name_, context, new Syncer())); + } + + bool signed_in = SignIn(credentials); + + if (signed_in && scheduler()) { + scheduler()->Start( + browser_sync::SyncScheduler::CONFIGURATION_MODE, NULL); + } + + initialized_ = true; + + // Notify that initialization is complete. + ObserverList<SyncManager::Observer> temp_obs_list; + CopyObservers(&temp_obs_list); + FOR_EACH_OBSERVER(SyncManager::Observer, temp_obs_list, + OnInitializationComplete( + WeakHandle<JsBackend>(weak_ptr_factory_.GetWeakPtr()))); + + // The following calls check that initialized_ is true. + + BootstrapEncryption(restored_key_for_bootstrapping); + + sync_notifier_->AddObserver(this); + + return signed_in; +} + +void SyncManager::SyncInternal::BootstrapEncryption( + const std::string& restored_key_for_bootstrapping) { + // Cryptographer should only be accessed while holding a transaction. + ReadTransaction trans(FROM_HERE, GetUserShare()); + Cryptographer* cryptographer = trans.GetCryptographer(); + + // Set the bootstrap token before bailing out if nigori node is not there. + // This could happen if server asked us to migrate nigri. + cryptographer->Bootstrap(restored_key_for_bootstrapping); +} + +bool SyncManager::SyncInternal::UpdateCryptographerFromNigori() { + DCHECK(initialized_); + syncable::ScopedDirLookup lookup(dir_manager(), username_for_share()); + if (!lookup.good()) { + NOTREACHED() << "BootstrapEncryption: lookup not good so bailing out"; + return false; + } + if (!lookup->initial_sync_ended_for_type(syncable::NIGORI)) + return false; // Should only happen during first time sync. + + ReadTransaction trans(FROM_HERE, GetUserShare()); + Cryptographer* cryptographer = trans.GetCryptographer(); + + ReadNode node(&trans); + if (!node.InitByTagLookup(kNigoriTag)) { + NOTREACHED(); + return false; + } + Cryptographer::UpdateResult result = + cryptographer->Update(node.GetNigoriSpecifics()); + if (result == Cryptographer::NEEDS_PASSPHRASE) { + ObserverList<SyncManager::Observer> temp_obs_list; + CopyObservers(&temp_obs_list); + FOR_EACH_OBSERVER(SyncManager::Observer, temp_obs_list, + OnPassphraseRequired(sync_api::REASON_DECRYPTION)); + } + + allstatus_.SetCryptographerReady(cryptographer->is_ready()); + allstatus_.SetCryptoHasPendingKeys(cryptographer->has_pending_keys()); + + return cryptographer->is_ready(); +} + +void SyncManager::SyncInternal::StartSyncingNormally() { + // Start the sync scheduler. This won't actually result in any + // syncing until at least the DirectoryManager broadcasts the OPENED + // event, and a valid server connection is detected. + if (scheduler()) // NULL during certain unittests. + scheduler()->Start(SyncScheduler::NORMAL_MODE, NULL); +} + +bool SyncManager::SyncInternal::OpenDirectory() { + DCHECK(!initialized_) << "Should only happen once"; + + bool share_opened = dir_manager()->Open(username_for_share(), this); + DCHECK(share_opened); + if (!share_opened) { + ObserverList<SyncManager::Observer> temp_obs_list; + CopyObservers(&temp_obs_list); + FOR_EACH_OBSERVER(SyncManager::Observer, temp_obs_list, + OnStopSyncingPermanently()); + + LOG(ERROR) << "Could not open share for:" << username_for_share(); + return false; + } + + // Database has to be initialized for the guid to be available. + syncable::ScopedDirLookup lookup(dir_manager(), username_for_share()); + if (!lookup.good()) { + NOTREACHED(); + return false; + } + + connection_manager()->set_client_id(lookup->cache_guid()); + lookup->AddTransactionObserver(&js_transaction_observer_); + return true; +} + +bool SyncManager::SyncInternal::SignIn(const SyncCredentials& credentials) { + DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK(share_.name.empty()); + share_.name = credentials.email; + + VLOG(1) << "Signing in user: " << username_for_share(); + if (!OpenDirectory()) + return false; + + // Retrieve and set the sync notifier state. This should be done + // only after OpenDirectory is called. + syncable::ScopedDirLookup lookup(dir_manager(), username_for_share()); + std::string unique_id; + std::string state; + if (lookup.good()) { + unique_id = lookup->cache_guid(); + state = lookup->GetNotificationState(); + VLOG(1) << "Read notification unique ID: " << unique_id; + if (VLOG_IS_ON(1)) { + std::string encoded_state; + base::Base64Encode(state, &encoded_state); + VLOG(1) << "Read notification state: " << encoded_state; + } + } else { + LOG(ERROR) << "Could not read notification unique ID/state"; + } + sync_notifier_->SetUniqueId(unique_id); + sync_notifier_->SetState(state); + + UpdateCredentials(credentials); + UpdateEnabledTypes(); + return true; +} + +void SyncManager::SyncInternal::UpdateCredentials( + const SyncCredentials& credentials) { + DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_EQ(credentials.email, share_.name); + DCHECK(!credentials.email.empty()); + DCHECK(!credentials.sync_token.empty()); + + observing_ip_address_changes_ = true; + if (connection_manager()->set_auth_token(credentials.sync_token)) { + sync_notifier_->UpdateCredentials( + credentials.email, credentials.sync_token); + if (!setup_for_test_mode_) { + CheckServerReachable(); + } + } +} + +void SyncManager::SyncInternal::UpdateEnabledTypes() { + DCHECK(thread_checker_.CalledOnValidThread()); + ModelSafeRoutingInfo routes; + registrar_->GetModelSafeRoutingInfo(&routes); + syncable::ModelTypeSet enabled_types; + for (ModelSafeRoutingInfo::const_iterator it = routes.begin(); + it != routes.end(); ++it) { + enabled_types.insert(it->first); + } + sync_notifier_->UpdateEnabledTypes(enabled_types); +} + +void SyncManager::SyncInternal::RaiseAuthNeededEvent() { + ObserverList<SyncManager::Observer> temp_obs_list; + CopyObservers(&temp_obs_list); + FOR_EACH_OBSERVER(SyncManager::Observer, temp_obs_list, + OnAuthError(AuthError(AuthError::INVALID_GAIA_CREDENTIALS))); +} + +void SyncManager::SyncInternal::SetPassphrase( + const std::string& passphrase, bool is_explicit) { + // We do not accept empty passphrases. + if (passphrase.empty()) { + VLOG(1) << "Rejecting empty passphrase."; + ObserverList<SyncManager::Observer> temp_obs_list; + CopyObservers(&temp_obs_list); + FOR_EACH_OBSERVER(SyncManager::Observer, temp_obs_list, + OnPassphraseRequired(sync_api::REASON_SET_PASSPHRASE_FAILED)); + return; + } + + // All accesses to the cryptographer are protected by a transaction. + WriteTransaction trans(FROM_HERE, GetUserShare()); + Cryptographer* cryptographer = trans.GetCryptographer(); + KeyParams params = {"localhost", "dummy", passphrase}; + + WriteNode node(&trans); + if (!node.InitByTagLookup(kNigoriTag)) { + // TODO(albertb): Plumb an UnrecoverableError all the way back to the PSS. + NOTREACHED(); + return; + } + + if (cryptographer->has_pending_keys()) { + bool suceeded = false; + + // See if the explicit flag matches what is set in nigori. If not we dont + // even try the passphrase. Note: This could mean that we wont try setting + // the gaia password as passphrase if custom is elected by the user. Which + // is fine because nigori node has all the old passwords in it. + if (node.GetNigoriSpecifics().using_explicit_passphrase() == is_explicit) { + if (cryptographer->DecryptPendingKeys(params)) { + suceeded = true; + } else { + VLOG(1) << "Passphrase failed to decrypt pending keys."; + } + } else { + VLOG(1) << "Not trying the passphrase because the explicit flags dont " + << "match. Nigori node's explicit flag is " + << node.GetNigoriSpecifics().using_explicit_passphrase(); + } + + if (!suceeded) { + ObserverList<SyncManager::Observer> temp_obs_list; + CopyObservers(&temp_obs_list); + FOR_EACH_OBSERVER(SyncManager::Observer, temp_obs_list, + OnPassphraseRequired(sync_api::REASON_SET_PASSPHRASE_FAILED)); + return; + } + + // Nudge the syncer so that encrypted datatype updates that were waiting for + // this passphrase get applied as soon as possible. + RequestNudge(FROM_HERE); + } else { + VLOG(1) << "No pending keys, adding provided passphrase."; + + // Prevent an implicit SetPassphrase request from changing an explicitly + // set passphrase. + if (!is_explicit && node.GetNigoriSpecifics().using_explicit_passphrase()) + return; + + cryptographer->AddKey(params); + + // TODO(tim): Bug 58231. It would be nice if SetPassphrase didn't require + // messing with the Nigori node, because we can't call SetPassphrase until + // download conditions are met vs Cryptographer init. It seems like it's + // safe to defer this work. + sync_pb::NigoriSpecifics specifics(node.GetNigoriSpecifics()); + specifics.clear_encrypted(); + cryptographer->GetKeys(specifics.mutable_encrypted()); + specifics.set_using_explicit_passphrase(is_explicit); + node.SetNigoriSpecifics(specifics); + ReEncryptEverything(&trans); + } + + VLOG(1) << "Passphrase accepted, bootstrapping encryption."; + std::string bootstrap_token; + cryptographer->GetBootstrapToken(&bootstrap_token); + ObserverList<SyncManager::Observer> temp_obs_list; + CopyObservers(&temp_obs_list); + FOR_EACH_OBSERVER(SyncManager::Observer, temp_obs_list, + OnPassphraseAccepted(bootstrap_token)); +} + +bool SyncManager::SyncInternal::IsUsingExplicitPassphrase() { + ReadTransaction trans(FROM_HERE, &share_); + ReadNode node(&trans); + if (!node.InitByTagLookup(kNigoriTag)) { + // TODO(albertb): Plumb an UnrecoverableError all the way back to the PSS. + NOTREACHED(); + return false; + } + + return node.GetNigoriSpecifics().using_explicit_passphrase(); +} + +void SyncManager::SyncInternal::EncryptDataTypes( + const syncable::ModelTypeSet& encrypted_types) { + DCHECK(initialized_); + VLOG(1) << "Attempting to encrypt datatypes " + << syncable::ModelTypeSetToString(encrypted_types); + + WriteTransaction trans(FROM_HERE, GetUserShare()); + WriteNode node(&trans); + if (!node.InitByTagLookup(kNigoriTag)) { + NOTREACHED() << "Unable to set encrypted datatypes because Nigori node not " + << "found."; + return; + } + + Cryptographer* cryptographer = trans.GetCryptographer(); + + if (!cryptographer->is_initialized()) { + VLOG(1) << "Attempting to encrypt datatypes when cryptographer not " + << "initialized, prompting for passphrase."; + ObserverList<SyncManager::Observer> temp_obs_list; + CopyObservers(&temp_obs_list); + // TODO(zea): this isn't really decryption, but that's the only way we have + // to prompt the user for a passsphrase. See http://crbug.com/91379. + FOR_EACH_OBSERVER(SyncManager::Observer, temp_obs_list, + OnPassphraseRequired(sync_api::REASON_DECRYPTION)); + return; + } + + // Update the Nigori node's set of encrypted datatypes. + // Note, we merge the current encrypted types with those requested. Once a + // datatypes is marked as needing encryption, it is never unmarked. + sync_pb::NigoriSpecifics nigori; + nigori.CopyFrom(node.GetNigoriSpecifics()); + syncable::ModelTypeSet current_encrypted_types = GetEncryptedTypes(&trans); + syncable::ModelTypeSet newly_encrypted_types; + std::set_union(current_encrypted_types.begin(), current_encrypted_types.end(), + encrypted_types.begin(), encrypted_types.end(), + std::inserter(newly_encrypted_types, + newly_encrypted_types.begin())); + allstatus_.SetEncryptedTypes(newly_encrypted_types); + if (newly_encrypted_types == current_encrypted_types) { + // Set of encrypted types has not changed, just notify and return. + ObserverList<SyncManager::Observer> temp_obs_list; + CopyObservers(&temp_obs_list); + FOR_EACH_OBSERVER(SyncManager::Observer, temp_obs_list, + OnEncryptionComplete(current_encrypted_types)); + return; + } + syncable::FillNigoriEncryptedTypes(newly_encrypted_types, &nigori); + node.SetNigoriSpecifics(nigori); + + cryptographer->SetEncryptedTypes(nigori); + + // TODO(zea): only reencrypt this datatype? ReEncrypting everything is a + // safer approach, and should not impact anything that is already encrypted + // (redundant changes are ignored). + ReEncryptEverything(&trans); + return; +} + +// TODO(zea): Add unit tests that ensure no sync changes are made when not +// needed. +void SyncManager::SyncInternal::ReEncryptEverything(WriteTransaction* trans) { + syncable::ModelTypeSet encrypted_types = + GetEncryptedTypes(trans); + ModelSafeRoutingInfo routes; + registrar_->GetModelSafeRoutingInfo(&routes); + std::string tag; + for (syncable::ModelTypeSet::iterator iter = encrypted_types.begin(); + iter != encrypted_types.end(); ++iter) { + if (*iter == syncable::PASSWORDS || routes.count(*iter) == 0) + continue; + ReadNode type_root(trans); + tag = syncable::ModelTypeToRootTag(*iter); + if (!type_root.InitByTagLookup(tag)) { + NOTREACHED(); + return; + } + + // Iterate through all children of this datatype. + std::queue<int64> to_visit; + int64 child_id = type_root.GetFirstChildId(); + to_visit.push(child_id); + while (!to_visit.empty()) { + child_id = to_visit.front(); + to_visit.pop(); + if (child_id == kInvalidId) + continue; + + WriteNode child(trans); + if (!child.InitByIdLookup(child_id)) { + NOTREACHED(); + continue; + } + if (child.GetIsFolder()) { + to_visit.push(child.GetFirstChildId()); + } + if (child.GetEntry()->Get(syncable::UNIQUE_SERVER_TAG).empty()) { + // Rewrite the specifics of the node with encrypted data if necessary + // (only rewrite the non-unique folders). + child.ResetFromSpecifics(); + } + to_visit.push(child.GetSuccessorId()); + } + } + + if (routes.count(syncable::PASSWORDS) > 0) { + // Passwords are encrypted with their own legacy scheme. + ReadNode passwords_root(trans); + std::string passwords_tag = + syncable::ModelTypeToRootTag(syncable::PASSWORDS); + // It's possible we'll have the password routing info and not the password + // root if we attempted to SetPassphrase before passwords was enabled. + if (passwords_root.InitByTagLookup(passwords_tag)) { + int64 child_id = passwords_root.GetFirstChildId(); + while (child_id != kInvalidId) { + WriteNode child(trans); + if (!child.InitByIdLookup(child_id)) { + NOTREACHED(); + return; + } + child.SetPasswordSpecifics(child.GetPasswordSpecifics()); + child_id = child.GetSuccessorId(); + } + } + } + + ObserverList<SyncManager::Observer> temp_obs_list; + CopyObservers(&temp_obs_list); + FOR_EACH_OBSERVER(SyncManager::Observer, temp_obs_list, + OnEncryptionComplete(encrypted_types)); +} + +SyncManager::~SyncManager() { + delete data_; +} + +void SyncManager::AddObserver(Observer* observer) { + data_->AddObserver(observer); +} + +void SyncManager::RemoveObserver(Observer* observer) { + data_->RemoveObserver(observer); +} + +void SyncManager::RequestEarlyExit() { + data_->RequestEarlyExit(); +} + +void SyncManager::SyncInternal::RequestEarlyExit() { + if (scheduler()) { + scheduler()->RequestEarlyExit(); + } +} + +void SyncManager::Shutdown() { + data_->Shutdown(); +} + +void SyncManager::SyncInternal::Shutdown() { + DCHECK(thread_checker_.CalledOnValidThread()); + + // Prevent any in-flight method calls from running. Also + // invalidates |weak_handle_this_|. + weak_ptr_factory_.InvalidateWeakPtrs(); + + // Automatically stops the scheduler. + scheduler_.reset(); + + SetJsEventHandler(WeakHandle<JsEventHandler>()); + RemoveObserver(&js_sync_manager_observer_); + + if (sync_notifier_.get()) { + sync_notifier_->RemoveObserver(this); + } + sync_notifier_.reset(); + + if (connection_manager_.get()) { + connection_manager_->RemoveListener(this); + } + connection_manager_.reset(); + + net::NetworkChangeNotifier::RemoveIPAddressObserver(this); + observing_ip_address_changes_ = false; + + if (dir_manager()) { + syncable::ScopedDirLookup lookup(dir_manager(), username_for_share()); + if (lookup.good()) { + lookup->RemoveTransactionObserver(&js_transaction_observer_); + } else { + NOTREACHED(); + } + dir_manager()->FinalSaveChangesForAll(); + dir_manager()->Close(username_for_share()); + } + + // Reset the DirectoryManager and UserSettings so they relinquish sqlite + // handles to backing files. + share_.dir_manager.reset(); + + setup_for_test_mode_ = false; + registrar_ = NULL; + + initialized_ = false; + + // We reset this here, since only now we know it will not be + // accessed from other threads (since we shut down everything). + weak_handle_this_.Reset(); +} + +void SyncManager::SyncInternal::OnIPAddressChanged() { + VLOG(1) << "IP address change detected"; + if (!observing_ip_address_changes_) { + VLOG(1) << "IP address change dropped."; + return; + } + +#if defined (OS_CHROMEOS) + // TODO(tim): This is a hack to intentionally lose a race with flimflam at + // shutdown, so we don't cause shutdown to wait for our http request. + // http://crosbug.com/8429 + MessageLoop::current()->PostDelayedTask( + FROM_HERE, + base::Bind(&SyncInternal::OnIPAddressChangedImpl, + weak_ptr_factory_.GetWeakPtr()), + kChromeOSNetworkChangeReactionDelayHackMsec); +#else + OnIPAddressChangedImpl(); +#endif // defined(OS_CHROMEOS) +} + +void SyncManager::SyncInternal::OnIPAddressChangedImpl() { + // TODO(akalin): CheckServerReachable() can block, which may cause + // jank if we try to shut down sync. Fix this. + connection_manager()->CheckServerReachable(); +} + +void SyncManager::SyncInternal::OnServerConnectionEvent( + const ServerConnectionEvent& event) { + allstatus_.HandleServerConnectionEvent(event); + if (event.connection_code == + browser_sync::HttpResponse::SERVER_CONNECTION_OK) { + ObserverList<SyncManager::Observer> temp_obs_list; + CopyObservers(&temp_obs_list); + FOR_EACH_OBSERVER(SyncManager::Observer, temp_obs_list, + OnAuthError(AuthError::None())); + } + + if (event.connection_code == browser_sync::HttpResponse::SYNC_AUTH_ERROR) { + observing_ip_address_changes_ = false; + ObserverList<SyncManager::Observer> temp_obs_list; + CopyObservers(&temp_obs_list); + FOR_EACH_OBSERVER(SyncManager::Observer, temp_obs_list, + OnAuthError(AuthError(AuthError::INVALID_GAIA_CREDENTIALS))); + } + + if (event.connection_code == + browser_sync::HttpResponse::SYNC_SERVER_ERROR) { + ObserverList<SyncManager::Observer> temp_obs_list; + CopyObservers(&temp_obs_list); + FOR_EACH_OBSERVER(SyncManager::Observer, temp_obs_list, + OnAuthError(AuthError(AuthError::CONNECTION_FAILED))); + } +} + +void SyncManager::SyncInternal::HandleTransactionCompleteChangeEvent( + const syncable::ModelTypeBitSet& models_with_changes) { + // This notification happens immediately after the transaction mutex is + // released. This allows work to be performed without blocking other threads + // from acquiring a transaction. + if (!HaveObservers()) + return; + + // Call commit. + for (int i = 0; i < syncable::MODEL_TYPE_COUNT; ++i) { + if (models_with_changes.test(i)) { + ObserverList<SyncManager::Observer> temp_obs_list; + CopyObservers(&temp_obs_list); + FOR_EACH_OBSERVER(SyncManager::Observer, temp_obs_list, + OnChangesComplete(syncable::ModelTypeFromInt(i))); + } + } +} + +ModelTypeBitSet SyncManager::SyncInternal::HandleTransactionEndingChangeEvent( + syncable::BaseTransaction* trans) { + // This notification happens immediately before a syncable WriteTransaction + // falls out of scope. It happens while the channel mutex is still held, + // and while the transaction mutex is held, so it cannot be re-entrant. + if (!HaveObservers() || ChangeBuffersAreEmpty()) + return ModelTypeBitSet(); + + // This will continue the WriteTransaction using a read only wrapper. + // This is the last chance for read to occur in the WriteTransaction + // that's closing. This special ReadTransaction will not close the + // underlying transaction. + ReadTransaction read_trans(GetUserShare(), trans); + + syncable::ModelTypeBitSet models_with_changes; + for (int i = 0; i < syncable::MODEL_TYPE_COUNT; ++i) { + if (change_buffers_[i].IsEmpty()) + continue; + + vector<ChangeRecord> ordered_changes; + change_buffers_[i].GetAllChangesInTreeOrder(&read_trans, &ordered_changes); + if (!ordered_changes.empty()) { + ObserverList<SyncManager::Observer> temp_obs_list; + CopyObservers(&temp_obs_list); + FOR_EACH_OBSERVER(SyncManager::Observer, temp_obs_list, + OnChangesApplied(syncable::ModelTypeFromInt(i), &read_trans, + &ordered_changes[0], ordered_changes.size())); + models_with_changes.set(i, true); + } + change_buffers_[i].Clear(); + } + return models_with_changes; +} + +void SyncManager::SyncInternal::HandleCalculateChangesChangeEventFromSyncApi( + const EntryKernelMutationSet& mutations, + syncable::BaseTransaction* trans) { + if (!scheduler()) { + return; + } + + // We have been notified about a user action changing a sync model. + LOG_IF(WARNING, !ChangeBuffersAreEmpty()) << + "CALCULATE_CHANGES called with unapplied old changes."; + + // The mutated model type, or UNSPECIFIED if nothing was mutated. + syncable::ModelType mutated_model_type = syncable::UNSPECIFIED; + + // Find the first real mutation. We assume that only a single model + // type is mutated per transaction. + for (syncable::EntryKernelMutationSet::const_iterator it = + mutations.begin(); it != mutations.end(); ++it) { + if (!it->mutated.ref(syncable::IS_UNSYNCED)) { + continue; + } + + syncable::ModelType model_type = + syncable::GetModelTypeFromSpecifics(it->mutated.ref(SPECIFICS)); + if (model_type < syncable::FIRST_REAL_MODEL_TYPE) { + NOTREACHED() << "Permanent or underspecified item changed via syncapi."; + continue; + } + + // Found real mutation. + if (mutated_model_type == syncable::UNSPECIFIED) { + mutated_model_type = model_type; + break; + } + } + + // Nudge if necessary. + if (mutated_model_type != syncable::UNSPECIFIED) { + if (weak_handle_this_.IsInitialized()) { + weak_handle_this_.Call(FROM_HERE, + &SyncInternal::RequestNudgeForDataType, + FROM_HERE, + mutated_model_type); + } else { + NOTREACHED(); + } + } +} + +void SyncManager::SyncInternal::SetExtraChangeRecordData(int64 id, + syncable::ModelType type, ChangeReorderBuffer* buffer, + Cryptographer* cryptographer, const syncable::EntryKernel& original, + bool existed_before, bool exists_now) { + // If this is a deletion and the datatype was encrypted, we need to decrypt it + // and attach it to the buffer. + if (!exists_now && existed_before) { + sync_pb::EntitySpecifics original_specifics(original.ref(SPECIFICS)); + if (type == syncable::PASSWORDS) { + // Passwords must use their own legacy ExtraPasswordChangeRecordData. + scoped_ptr<sync_pb::PasswordSpecificsData> data( + DecryptPasswordSpecifics(original_specifics, cryptographer)); + if (!data.get()) { + NOTREACHED(); + return; + } + buffer->SetExtraDataForId(id, new ExtraPasswordChangeRecordData(*data)); + } else if (original_specifics.has_encrypted()) { + // All other datatypes can just create a new unencrypted specifics and + // attach it. + const sync_pb::EncryptedData& encrypted = original_specifics.encrypted(); + if (!cryptographer->Decrypt(encrypted, &original_specifics)) { + NOTREACHED(); + return; + } + } + buffer->SetSpecificsForId(id, original_specifics); + } +} + +void SyncManager::SyncInternal::HandleCalculateChangesChangeEventFromSyncer( + const EntryKernelMutationSet& mutations, + syncable::BaseTransaction* trans) { + // We only expect one notification per sync step, so change_buffers_ should + // contain no pending entries. + LOG_IF(WARNING, !ChangeBuffersAreEmpty()) << + "CALCULATE_CHANGES called with unapplied old changes."; + + Cryptographer* crypto = dir_manager()->GetCryptographer(trans); + for (syncable::EntryKernelMutationSet::const_iterator it = + mutations.begin(); it != mutations.end(); ++it) { + bool existed_before = !it->original.ref(syncable::IS_DEL); + bool exists_now = !it->mutated.ref(syncable::IS_DEL); + + // Omit items that aren't associated with a model. + syncable::ModelType type = + syncable::GetModelTypeFromSpecifics(it->mutated.ref(SPECIFICS)); + if (type < syncable::FIRST_REAL_MODEL_TYPE) + continue; + + int64 id = it->original.ref(syncable::META_HANDLE); + if (exists_now && !existed_before) + change_buffers_[type].PushAddedItem(id); + else if (!exists_now && existed_before) + change_buffers_[type].PushDeletedItem(id); + else if (exists_now && existed_before && + VisiblePropertiesDiffer(*it, crypto)) { + change_buffers_[type].PushUpdatedItem( + id, VisiblePositionsDiffer(*it)); + } + + SetExtraChangeRecordData(id, type, &change_buffers_[type], crypto, + it->original, existed_before, exists_now); + } +} + +SyncManager::Status SyncManager::SyncInternal::GetStatus() { + return allstatus_.status(); +} + +void SyncManager::SyncInternal::RequestNudge( + const tracked_objects::Location& location) { + if (scheduler()) + scheduler()->ScheduleNudge( + TimeDelta::FromMilliseconds(0), browser_sync::NUDGE_SOURCE_LOCAL, + ModelTypeBitSet(), location); +} + +void SyncManager::SyncInternal::RequestNudgeForDataType( + const tracked_objects::Location& nudge_location, + const ModelType& type) { + if (!scheduler()) { + NOTREACHED(); + return; + } + base::TimeDelta nudge_delay; + switch (type) { + case syncable::PREFERENCES: + nudge_delay = + TimeDelta::FromMilliseconds(kPreferencesNudgeDelayMilliseconds); + break; + case syncable::SESSIONS: + nudge_delay = scheduler()->sessions_commit_delay(); + break; + default: + nudge_delay = + TimeDelta::FromMilliseconds(kDefaultNudgeDelayMilliseconds); + break; + } + syncable::ModelTypeBitSet types; + types.set(type); + scheduler()->ScheduleNudge(nudge_delay, + browser_sync::NUDGE_SOURCE_LOCAL, + types, + nudge_location); +} + +void SyncManager::SyncInternal::OnSyncEngineEvent( + const SyncEngineEvent& event) { + DCHECK(thread_checker_.CalledOnValidThread()); + if (!HaveObservers()) { + LOG(INFO) + << "OnSyncEngineEvent returning because observers_.size() is zero"; + return; + } + + // Only send an event if this is due to a cycle ending and this cycle + // concludes a canonical "sync" process; that is, based on what is known + // locally we are "all happy" and up-to-date. There may be new changes on + // the server, but we'll get them on a subsequent sync. + // + // Notifications are sent at the end of every sync cycle, regardless of + // whether we should sync again. + if (event.what_happened == SyncEngineEvent::SYNC_CYCLE_ENDED) { + ModelSafeRoutingInfo enabled_types; + registrar_->GetModelSafeRoutingInfo(&enabled_types); + { + // Check to see if we need to notify the frontend that we have newly + // encrypted types or that we require a passphrase. + sync_api::ReadTransaction trans(FROM_HERE, GetUserShare()); + Cryptographer* cryptographer = trans.GetCryptographer(); + // If we've completed a sync cycle and the cryptographer isn't ready + // yet, prompt the user for a passphrase. + if (cryptographer->has_pending_keys()) { + VLOG(1) << "OnPassPhraseRequired Sent"; + ObserverList<SyncManager::Observer> temp_obs_list; + CopyObservers(&temp_obs_list); + FOR_EACH_OBSERVER(SyncManager::Observer, temp_obs_list, + OnPassphraseRequired(sync_api::REASON_DECRYPTION)); + } else if (!cryptographer->is_ready() && + event.snapshot->initial_sync_ended.test(syncable::NIGORI)) { + VLOG(1) << "OnPassphraseRequired sent because cryptographer is not " + << "ready"; + ObserverList<SyncManager::Observer> temp_obs_list; + CopyObservers(&temp_obs_list); + FOR_EACH_OBSERVER(SyncManager::Observer, temp_obs_list, + OnPassphraseRequired(sync_api::REASON_ENCRYPTION)); + } + + allstatus_.SetCryptographerReady(cryptographer->is_ready()); + allstatus_.SetCryptoHasPendingKeys(cryptographer->has_pending_keys()); + allstatus_.SetEncryptedTypes(cryptographer->GetEncryptedTypes()); + + // If everything is in order(we have the passphrase) then there is no + // need to inform the listeners. They will just wait for sync + // completion event and if no errors have been raised it means + // encryption was succesful. + } + + if (!initialized_) { + LOG(INFO) << "OnSyncCycleCompleted not sent because sync api is not " + << "initialized"; + return; + } + + if (!event.snapshot->has_more_to_sync) { + VLOG(1) << "OnSyncCycleCompleted sent"; + ObserverList<SyncManager::Observer> temp_obs_list; + CopyObservers(&temp_obs_list); + FOR_EACH_OBSERVER(SyncManager::Observer, temp_obs_list, + OnSyncCycleCompleted(event.snapshot)); + } + + // This is here for tests, which are still using p2p notifications. + // + // TODO(chron): Consider changing this back to track has_more_to_sync + // only notify peers if a successful commit has occurred. + bool is_notifiable_commit = + (event.snapshot->syncer_status.num_successful_commits > 0); + if (is_notifiable_commit) { + allstatus_.IncrementNotifiableCommits(); + if (sync_notifier_.get()) { + sync_notifier_->SendNotification(); + } else { + VLOG(1) << "Not sending notification: sync_notifier_ is NULL"; + } + } + } + + if (event.what_happened == SyncEngineEvent::STOP_SYNCING_PERMANENTLY) { + ObserverList<SyncManager::Observer> temp_obs_list; + CopyObservers(&temp_obs_list); + FOR_EACH_OBSERVER(SyncManager::Observer, temp_obs_list, + OnStopSyncingPermanently()); + return; + } + + if (event.what_happened == SyncEngineEvent::CLEAR_SERVER_DATA_SUCCEEDED) { + ObserverList<SyncManager::Observer> temp_obs_list; + CopyObservers(&temp_obs_list); + FOR_EACH_OBSERVER(SyncManager::Observer, temp_obs_list, + OnClearServerDataSucceeded()); + return; + } + + if (event.what_happened == SyncEngineEvent::CLEAR_SERVER_DATA_FAILED) { + ObserverList<SyncManager::Observer> temp_obs_list; + CopyObservers(&temp_obs_list); + FOR_EACH_OBSERVER(SyncManager::Observer, temp_obs_list, + OnClearServerDataFailed()); + return; + } + + if (event.what_happened == SyncEngineEvent::UPDATED_TOKEN) { + ObserverList<SyncManager::Observer> temp_obs_list; + CopyObservers(&temp_obs_list); + FOR_EACH_OBSERVER(SyncManager::Observer, temp_obs_list, + OnUpdatedToken(event.updated_token)); + return; + } +} + +void SyncManager::SyncInternal::SetJsEventHandler( + const WeakHandle<JsEventHandler>& event_handler) { + js_event_handler_ = event_handler; + js_sync_manager_observer_.SetJsEventHandler(js_event_handler_); + js_transaction_observer_.SetJsEventHandler(js_event_handler_); +} + +void SyncManager::SyncInternal::ProcessJsMessage( + const std::string& name, const JsArgList& args, + const WeakHandle<JsReplyHandler>& reply_handler) { + if (!initialized_) { + NOTREACHED(); + return; + } + + if (!reply_handler.IsInitialized()) { + VLOG(1) << "Uninitialized reply handler; dropping unknown message " + << name << " with args " << args.ToString(); + return; + } + + JsMessageHandler js_message_handler = js_message_handlers_[name]; + if (js_message_handler.is_null()) { + VLOG(1) << "Dropping unknown message " << name + << " with args " << args.ToString(); + return; + } + + reply_handler.Call(FROM_HERE, + &JsReplyHandler::HandleJsReply, + name, js_message_handler.Run(args)); +} + +void SyncManager::SyncInternal::BindJsMessageHandler( + const std::string& name, + UnboundJsMessageHandler unbound_message_handler) { + js_message_handlers_[name] = + base::Bind(unbound_message_handler, base::Unretained(this)); +} + +DictionaryValue* SyncManager::SyncInternal::NotificationInfoToValue( + const NotificationInfoMap& notification_info) { + DictionaryValue* value = new DictionaryValue(); + + for (NotificationInfoMap::const_iterator it = notification_info.begin(); + it != notification_info.end(); ++it) { + const std::string& model_type_str = + syncable::ModelTypeToString(it->first); + value->Set(model_type_str, it->second.ToValue()); + } + + return value; +} + +JsArgList SyncManager::SyncInternal::GetNotificationState( + const JsArgList& args) { + bool notifications_enabled = allstatus_.status().notifications_enabled; + ListValue return_args; + return_args.Append(Value::CreateBooleanValue(notifications_enabled)); + return JsArgList(&return_args); +} + +JsArgList SyncManager::SyncInternal::GetNotificationInfo( + const JsArgList& args) { + ListValue return_args; + return_args.Append(NotificationInfoToValue(notification_info_map_)); + return JsArgList(&return_args); +} + +JsArgList SyncManager::SyncInternal::GetRootNodeDetails( + const JsArgList& args) { + ReadTransaction trans(FROM_HERE, GetUserShare()); + ReadNode root(&trans); + root.InitByRootLookup(); + ListValue return_args; + return_args.Append(root.GetDetailsAsValue()); + return JsArgList(&return_args); +} + +namespace { + +int64 GetId(const ListValue& ids, int i) { + std::string id_str; + if (!ids.GetString(i, &id_str)) { + return kInvalidId; + } + int64 id = kInvalidId; + if (!base::StringToInt64(id_str, &id)) { + return kInvalidId; + } + return id; +} + +JsArgList GetNodeInfoById(const JsArgList& args, + UserShare* user_share, + DictionaryValue* (BaseNode::*info_getter)() const) { + CHECK(info_getter); + ListValue return_args; + ListValue* node_summaries = new ListValue(); + return_args.Append(node_summaries); + ListValue* id_list = NULL; + ReadTransaction trans(FROM_HERE, user_share); + if (args.Get().GetList(0, &id_list)) { + CHECK(id_list); + for (size_t i = 0; i < id_list->GetSize(); ++i) { + int64 id = GetId(*id_list, i); + if (id == kInvalidId) { + continue; + } + ReadNode node(&trans); + if (!node.InitByIdLookup(id)) { + continue; + } + node_summaries->Append((node.*info_getter)()); + } + } + return JsArgList(&return_args); +} + +} // namespace + +JsArgList SyncManager::SyncInternal::GetNodeSummariesById( + const JsArgList& args) { + return GetNodeInfoById(args, GetUserShare(), &BaseNode::GetSummaryAsValue); +} + +JsArgList SyncManager::SyncInternal::GetNodeDetailsById( + const JsArgList& args) { + return GetNodeInfoById(args, GetUserShare(), &BaseNode::GetDetailsAsValue); +} + +JsArgList SyncManager::SyncInternal::GetChildNodeIds( + const JsArgList& args) { + ListValue return_args; + ListValue* child_ids = new ListValue(); + return_args.Append(child_ids); + int64 id = GetId(args.Get(), 0); + if (id != kInvalidId) { + ReadTransaction trans(FROM_HERE, GetUserShare()); + syncable::Directory::ChildHandles child_handles; + trans.GetLookup()->GetChildHandlesByHandle(trans.GetWrappedTrans(), + id, &child_handles); + for (syncable::Directory::ChildHandles::const_iterator it = + child_handles.begin(); it != child_handles.end(); ++it) { + child_ids->Append(Value::CreateStringValue( + base::Int64ToString(*it))); + } + } + return JsArgList(&return_args); +} + +JsArgList SyncManager::SyncInternal::FindNodesContainingString( + const JsArgList& args) { + std::string query; + ListValue return_args; + if (!args.Get().GetString(0, &query)) { + return_args.Append(new ListValue()); + return JsArgList(&return_args); + } + + // Convert the query string to lower case to perform case insensitive + // searches. + std::string lowercase_query = query; + StringToLowerASCII(&lowercase_query); + + ListValue* result = new ListValue(); + return_args.Append(result); + + ReadTransaction trans(FROM_HERE, GetUserShare()); + std::vector<const syncable::EntryKernel*> entry_kernels; + trans.GetLookup()->GetAllEntryKernels(trans.GetWrappedTrans(), + &entry_kernels); + + for (std::vector<const syncable::EntryKernel*>::const_iterator it = + entry_kernels.begin(); it != entry_kernels.end(); ++it) { + if ((*it)->ContainsString(lowercase_query)) { + result->Append(new StringValue(base::Int64ToString( + (*it)->ref(syncable::META_HANDLE)))); + } + } + + return JsArgList(&return_args); +} + +void SyncManager::SyncInternal::OnNotificationStateChange( + bool notifications_enabled) { + VLOG(1) << "P2P: Notifications enabled = " + << (notifications_enabled ? "true" : "false"); + allstatus_.SetNotificationsEnabled(notifications_enabled); + if (scheduler()) { + scheduler()->set_notifications_enabled(notifications_enabled); + } + if (js_event_handler_.IsInitialized()) { + DictionaryValue details; + details.Set("enabled", Value::CreateBooleanValue(notifications_enabled)); + js_event_handler_.Call(FROM_HERE, + &JsEventHandler::HandleJsEvent, + "onNotificationStateChange", + JsEventDetails(&details)); + } +} + +void SyncManager::SyncInternal::UpdateNotificationInfo( + const syncable::ModelTypePayloadMap& type_payloads) { + for (syncable::ModelTypePayloadMap::const_iterator it = type_payloads.begin(); + it != type_payloads.end(); ++it) { + NotificationInfo* info = ¬ification_info_map_[it->first]; + info->total_count++; + info->payload = it->second; + } +} + +void SyncManager::SyncInternal::OnIncomingNotification( + const syncable::ModelTypePayloadMap& type_payloads) { + if (!type_payloads.empty()) { + if (scheduler()) { + scheduler()->ScheduleNudgeWithPayloads( + TimeDelta::FromMilliseconds(kSyncSchedulerDelayMsec), + browser_sync::NUDGE_SOURCE_NOTIFICATION, + type_payloads, FROM_HERE); + } + allstatus_.IncrementNotificationsReceived(); + UpdateNotificationInfo(type_payloads); + } else { + LOG(WARNING) << "Sync received notification without any type information."; + } + + if (js_event_handler_.IsInitialized()) { + DictionaryValue details; + ListValue* changed_types = new ListValue(); + details.Set("changedTypes", changed_types); + for (syncable::ModelTypePayloadMap::const_iterator + it = type_payloads.begin(); + it != type_payloads.end(); ++it) { + const std::string& model_type_str = + syncable::ModelTypeToString(it->first); + changed_types->Append(Value::CreateStringValue(model_type_str)); + } + js_event_handler_.Call(FROM_HERE, + &JsEventHandler::HandleJsEvent, + "onIncomingNotification", + JsEventDetails(&details)); + } +} + +void SyncManager::SyncInternal::StoreState( + const std::string& state) { + syncable::ScopedDirLookup lookup(dir_manager(), username_for_share()); + if (!lookup.good()) { + LOG(ERROR) << "Could not write notification state"; + // TODO(akalin): Propagate result callback all the way to this + // function and call it with "false" to signal failure. + return; + } + if (VLOG_IS_ON(1)) { + std::string encoded_state; + base::Base64Encode(state, &encoded_state); + VLOG(1) << "Writing notification state: " << encoded_state; + } + lookup->SetNotificationState(state); + lookup->SaveChanges(); +} + +// Note: it is possible that an observer will remove itself after we have made +// a copy, but before the copy is consumed. This could theoretically result +// in accessing a garbage pointer, but can only occur when an about:sync window +// is closed in the middle of a notification. +// See crbug.com/85481. +void SyncManager::SyncInternal::CopyObservers( + ObserverList<SyncManager::Observer>* observers_copy) { + DCHECK_EQ(0U, observers_copy->size()); + base::AutoLock lock(observers_lock_); + if (observers_.size() == 0) + return; + ObserverListBase<SyncManager::Observer>::Iterator it(observers_); + SyncManager::Observer* obs; + while ((obs = it.GetNext()) != NULL) + observers_copy->AddObserver(obs); +} + +bool SyncManager::SyncInternal::HaveObservers() const { + base::AutoLock lock(observers_lock_); + return observers_.size() > 0; +} + +void SyncManager::SyncInternal::AddObserver( + SyncManager::Observer* observer) { + base::AutoLock lock(observers_lock_); + observers_.AddObserver(observer); +} + +void SyncManager::SyncInternal::RemoveObserver( + SyncManager::Observer* observer) { + base::AutoLock lock(observers_lock_); + observers_.RemoveObserver(observer); +} + +SyncManager::Status::Summary SyncManager::GetStatusSummary() const { + return data_->GetStatus().summary; +} + +SyncManager::Status SyncManager::GetDetailedStatus() const { + return data_->GetStatus(); +} + +SyncManager::SyncInternal* SyncManager::GetImpl() const { return data_; } + +void SyncManager::SaveChanges() { + data_->SaveChanges(); +} + +void SyncManager::SyncInternal::SaveChanges() { + syncable::ScopedDirLookup lookup(dir_manager(), username_for_share()); + if (!lookup.good()) { + DCHECK(false) << "ScopedDirLookup creation failed; Unable to SaveChanges"; + return; + } + lookup->SaveChanges(); +} + +UserShare* SyncManager::GetUserShare() const { + return data_->GetUserShare(); +} + +void SyncManager::RefreshEncryption() { + if (data_->UpdateCryptographerFromNigori()) + data_->EncryptDataTypes(syncable::ModelTypeSet()); +} + +syncable::ModelTypeSet SyncManager::GetEncryptedDataTypes() const { + sync_api::ReadTransaction trans(FROM_HERE, GetUserShare()); + return GetEncryptedTypes(&trans); +} + +bool SyncManager::HasUnsyncedItems() const { + sync_api::ReadTransaction trans(FROM_HERE, GetUserShare()); + return (trans.GetWrappedTrans()->directory()->unsynced_entity_count() != 0); +} + +void SyncManager::LogUnsyncedItems(int level) const { + std::vector<int64> unsynced_handles; + sync_api::ReadTransaction trans(FROM_HERE, GetUserShare()); + trans.GetWrappedTrans()->directory()->GetUnsyncedMetaHandles( + trans.GetWrappedTrans(), &unsynced_handles); + + for (std::vector<int64>::const_iterator it = unsynced_handles.begin(); + it != unsynced_handles.end(); ++it) { + ReadNode node(&trans); + if (node.InitByIdLookup(*it)) { + scoped_ptr<DictionaryValue> value(node.GetDetailsAsValue()); + std::string info; + base::JSONWriter::Write(value.get(), true, &info); + VLOG(level) << info; + } + } +} + +void SyncManager::TriggerOnNotificationStateChangeForTest( + bool notifications_enabled) { + data_->OnNotificationStateChange(notifications_enabled); +} + +void SyncManager::TriggerOnIncomingNotificationForTest( + const syncable::ModelTypeBitSet& model_types) { + syncable::ModelTypePayloadMap model_types_with_payloads = + syncable::ModelTypePayloadMapFromBitSet(model_types, + std::string()); + + data_->OnIncomingNotification(model_types_with_payloads); +} + +// Helper function that converts a PassphraseRequiredReason value to a string. +std::string PassphraseRequiredReasonToString( + PassphraseRequiredReason reason) { + switch (reason) { + case REASON_PASSPHRASE_NOT_REQUIRED: + return "REASON_PASSPHRASE_NOT_REQUIRED"; + case REASON_ENCRYPTION: + return "REASON_ENCRYPTION"; + case REASON_DECRYPTION: + return "REASON_DECRYPTION"; + case REASON_SET_PASSPHRASE_FAILED: + return "REASON_SET_PASSPHRASE_FAILED"; + default: + NOTREACHED(); + return "INVALID_REASON"; + } +} + +// Helper function to determine if initial sync had ended for types. +bool InitialSyncEndedForTypes(syncable::ModelTypeSet types, + sync_api::UserShare* share) { + syncable::ScopedDirLookup lookup(share->dir_manager.get(), + share->name); + if (!lookup.good()) { + DCHECK(false) << "ScopedDirLookup failed when checking initial sync"; + return false; + } + + for (syncable::ModelTypeSet::const_iterator i = types.begin(); + i != types.end(); ++i) { + if (!lookup->initial_sync_ended_for_type(*i)) + return false; + } + return true; +} + +} // namespace sync_api diff --git a/chrome/browser/sync/internal_api/sync_manager.h b/chrome/browser/sync/internal_api/sync_manager.h new file mode 100644 index 0000000..14350a4 --- /dev/null +++ b/chrome/browser/sync/internal_api/sync_manager.h @@ -0,0 +1,546 @@ +// 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_INTERNAL_API_SYNC_MANAGER_H_ +#define CHROME_BROWSER_SYNC_INTERNAL_API_SYNC_MANAGER_H_ + +#include <string> + +#include "base/basictypes.h" +#include "base/callback_old.h" +#include "base/memory/linked_ptr.h" +#include "chrome/browser/sync/engine/configure_reason.h" +#include "chrome/browser/sync/protocol/password_specifics.pb.h" +#include "chrome/browser/sync/syncable/model_type.h" +#include "chrome/browser/sync/weak_handle.h" +#include "chrome/common/net/gaia/google_service_auth_error.h" + +class FilePath; + +namespace base { +class DictionaryValue; +} // namespace base + +namespace browser_sync { +class JsBackend; +class JsEventHandler; +class ModelSafeWorkerRegistrar; + +namespace sessions { +struct SyncSessionSnapshot; +} // namespace sessions +} // namespace browser_sync + +namespace sync_notifier { +class SyncNotifier; +} // namespace sync_notifier + +namespace sync_pb { +class PasswordSpecificsData; +} // namespace sync_pb + +namespace sync_api { + +class BaseTransaction; +class HttpPostProviderFactory; +struct UserShare; + +// Reasons due to which browser_sync::Cryptographer might require a passphrase. +enum PassphraseRequiredReason { + REASON_PASSPHRASE_NOT_REQUIRED = 0, // Initial value. + REASON_ENCRYPTION = 1, // The cryptographer requires a + // passphrase for its first attempt at + // encryption. Happens only during + // migration or upgrade. + REASON_DECRYPTION = 2, // The cryptographer requires a + // passphrase for its first attempt at + // decryption. + REASON_SET_PASSPHRASE_FAILED = 3, // The cryptographer requires a new + // passphrase because its attempt at + // decryption with the cached passphrase + // was unsuccessful. +}; + +// Contains everything needed to talk to and identify a user account. +struct SyncCredentials { + std::string email; + std::string sync_token; +}; + +// SyncManager encapsulates syncable::DirectoryManager and serves as the parent +// of all other objects in the sync API. SyncManager is thread-safe. If +// multiple threads interact with the same local sync repository (i.e. the +// same sqlite database), they should share a single SyncManager instance. The +// caller should typically create one SyncManager for the lifetime of a user +// session. +class SyncManager { + public: + // SyncInternal contains the implementation of SyncManager, while abstracting + // internal types from clients of the interface. + class SyncInternal; + + // TODO(zea): One day get passwords playing nicely with the rest of encryption + // and get rid of this. + class ExtraPasswordChangeRecordData { + public: + ExtraPasswordChangeRecordData(); + explicit ExtraPasswordChangeRecordData( + const sync_pb::PasswordSpecificsData& data); + virtual ~ExtraPasswordChangeRecordData(); + + // Transfers ownership of the DictionaryValue to the caller. + virtual base::DictionaryValue* ToValue() const; + + const sync_pb::PasswordSpecificsData& unencrypted() const; + private: + sync_pb::PasswordSpecificsData unencrypted_; + }; + + // ChangeRecord indicates a single item that changed as a result of a sync + // operation. This gives the sync id of the node that changed, and the type + // of change. To get the actual property values after an ADD or UPDATE, the + // client should get the node with InitByIdLookup(), using the provided id. + struct ChangeRecord { + enum Action { + ACTION_ADD, + ACTION_DELETE, + ACTION_UPDATE, + }; + ChangeRecord(); + ~ChangeRecord(); + + // Transfers ownership of the DictionaryValue to the caller. + base::DictionaryValue* ToValue(const BaseTransaction* trans) const; + + int64 id; + Action action; + sync_pb::EntitySpecifics specifics; + linked_ptr<ExtraPasswordChangeRecordData> extra; + }; + + // Status encapsulates detailed state about the internals of the SyncManager. + struct Status { + // Summary is a distilled set of important information that the end-user may + // wish to be informed about (through UI, for example). Note that if a + // summary state requires user interaction (such as auth failures), more + // detailed information may be contained in additional status fields. + enum Summary { + // The internal instance is in an unrecognizable state. This should not + // happen. + INVALID = 0, + // Can't connect to server, but there are no pending changes in + // our local cache. + OFFLINE, + // Can't connect to server, and there are pending changes in our + // local cache. + OFFLINE_UNSYNCED, + // Connected and syncing. + SYNCING, + // Connected, no pending changes. + READY, + // Internal sync error. + CONFLICT, + // Can't connect to server, and we haven't completed the initial + // sync yet. So there's nothing we can do but wait for the server. + OFFLINE_UNUSABLE, + + SUMMARY_STATUS_COUNT, + }; + + Status(); + ~Status(); + + Summary summary; + bool authenticated; // Successfully authenticated via GAIA. + bool server_up; // True if we have received at least one good + // reply from the server. + bool server_reachable; // True if we received any reply from the server. + bool server_broken; // True of the syncer is stopped because of server + // issues. + bool notifications_enabled; // True only if subscribed for notifications. + + // Notifications counters updated by the actions in synapi. + int notifications_received; + int notifiable_commits; + + // The max number of consecutive errors from any component. + int max_consecutive_errors; + + int unsynced_count; + + int conflicting_count; + bool syncing; + // True after a client has done a first sync. + bool initial_sync_ended; + // True if any syncer is stuck. + bool syncer_stuck; + + // Total updates available. If zero, nothing left to download. + int64 updates_available; + // Total updates received by the syncer since browser start. + int updates_received; + + // Of updates_received, how many were tombstones. + int tombstone_updates_received; + bool disk_full; + + // Total number of overwrites due to conflict resolver since browser start. + int num_local_overwrites_total; + int num_server_overwrites_total; + + // Count of empty and non empty getupdates; + int nonempty_get_updates; + int empty_get_updates; + + // Count of useless and useful syncs we perform. + int useless_sync_cycles; + int useful_sync_cycles; + + // Encryption related. + syncable::ModelTypeSet encrypted_types; + bool cryptographer_ready; + bool crypto_has_pending_keys; + }; + + // An interface the embedding application implements to receive notifications + // from the SyncManager. Register an observer via SyncManager::AddObserver. + // This observer is an event driven model as the events may be raised from + // different internal threads, and simply providing an "OnStatusChanged" type + // notification complicates things such as trying to determine "what changed", + // if different members of the Status object are modified from different + // threads. This way, the event is explicit, and it is safe for the Observer + // to dispatch to a native thread or synchronize accordingly. + class Observer { + public: + // Notify the observer that changes have been applied to the sync model. + // + // This will be invoked on the same thread as on which ApplyChanges was + // called. |changes| is an array of size |change_count|, and contains the + // ID of each individual item that was changed. |changes| exists only for + // the duration of the call. If items of multiple data types change at + // the same time, this method is invoked once per data type and |changes| + // is restricted to items of the ModelType indicated by |model_type|. + // Because the observer is passed a |trans|, the observer can assume a + // read lock on the sync model that will be released after the function + // returns. + // + // The SyncManager constructs |changes| in the following guaranteed order: + // + // 1. Deletions, from leaves up to parents. + // 2. Updates to existing items with synced parents & predecessors. + // 3. New items with synced parents & predecessors. + // 4. Items with parents & predecessors in |changes|. + // 5. Repeat #4 until all items are in |changes|. + // + // Thus, an implementation of OnChangesApplied should be able to + // process the change records in the order without having to worry about + // forward dependencies. But since deletions come before reparent + // operations, a delete may temporarily orphan a node that is + // updated later in the list. + virtual void OnChangesApplied(syncable::ModelType model_type, + const BaseTransaction* trans, + const ChangeRecord* changes, + int change_count) = 0; + + // OnChangesComplete gets called when the TransactionComplete event is + // posted (after OnChangesApplied finishes), after the transaction lock + // and the change channel mutex are released. + // + // The purpose of this function is to support processors that require + // split-transactions changes. For example, if a model processor wants to + // perform blocking I/O due to a change, it should calculate the changes + // while holding the transaction lock (from within OnChangesApplied), buffer + // those changes, let the transaction fall out of scope, and then commit + // those changes from within OnChangesComplete (postponing the blocking + // I/O to when it no longer holds any lock). + virtual void OnChangesComplete(syncable::ModelType model_type) = 0; + + // A round-trip sync-cycle took place and the syncer has resolved any + // conflicts that may have arisen. + virtual void OnSyncCycleCompleted( + const browser_sync::sessions::SyncSessionSnapshot* snapshot) = 0; + + // Called when user interaction may be required due to an auth problem. + virtual void OnAuthError(const GoogleServiceAuthError& auth_error) = 0; + + // Called when a new auth token is provided by the sync server. + virtual void OnUpdatedToken(const std::string& token) = 0; + + // Called when user interaction is required to obtain a valid passphrase. + // - If the passphrase is required for encryption, |reason| will be + // REASON_ENCRYPTION. + // - If the passphrase is required for the decryption of data that has + // already been encrypted, |reason| will be REASON_DECRYPTION. + // - If the passphrase is required because decryption failed, and a new + // passphrase is required, |reason| will be REASON_SET_PASSPHRASE_FAILED. + virtual void OnPassphraseRequired(PassphraseRequiredReason reason) = 0; + + // Called when the passphrase provided by the user has been accepted and is + // now used to encrypt sync data. |bootstrap_token| is an opaque base64 + // encoded representation of the key generated by the accepted passphrase, + // and is provided to the observer for persistence purposes and use in a + // future initialization of sync (e.g. after restart). + virtual void OnPassphraseAccepted(const std::string& bootstrap_token) = 0; + + // Called when initialization is complete to the point that SyncManager can + // process changes. This does not necessarily mean authentication succeeded + // or that the SyncManager is online. + // IMPORTANT: Creating any type of transaction before receiving this + // notification is illegal! + // WARNING: Calling methods on the SyncManager before receiving this + // message, unless otherwise specified, produces undefined behavior. + // + // |js_backend| is what about:sync interacts with. It can emit + // the following events: + + /** + * @param {{ enabled: boolean }} details A dictionary containing: + * - enabled: whether or not notifications are enabled. + */ + // function onNotificationStateChange(details); + + /** + * @param {{ changedTypes: Array.<string> }} details A dictionary + * containing: + * - changedTypes: a list of types (as strings) for which there + are new updates. + */ + // function onIncomingNotification(details); + + // Also, it responds to the following messages (all other messages + // are ignored): + + /** + * Gets the current notification state. + * + * @param {function(boolean)} callback Called with whether or not + * notifications are enabled. + */ + // function getNotificationState(callback); + + /** + * Gets details about the root node. + * + * @param {function(!Object)} callback Called with details about the + * root node. + */ + // TODO(akalin): Change this to getRootNodeId or eliminate it + // entirely. + // function getRootNodeDetails(callback); + + /** + * Gets summary information for a list of ids. + * + * @param {Array.<string>} idList List of 64-bit ids in decimal + * string form. + * @param {Array.<{id: string, title: string, isFolder: boolean}>} + * callback Called with summaries for the nodes in idList that + * exist. + */ + // function getNodeSummariesById(idList, callback); + + /** + * Gets detailed information for a list of ids. + * + * @param {Array.<string>} idList List of 64-bit ids in decimal + * string form. + * @param {Array.<!Object>} callback Called with detailed + * information for the nodes in idList that exist. + */ + // function getNodeDetailsById(idList, callback); + + /** + * Gets child ids for a given id. + * + * @param {string} id 64-bit id in decimal string form of the parent + * node. + * @param {Array.<string>} callback Called with the (possibly empty) + * list of child ids. + */ + // function getChildNodeIds(id); + + virtual void OnInitializationComplete( + const browser_sync::WeakHandle<browser_sync::JsBackend>& + js_backend) = 0; + + // We are no longer permitted to communicate with the server. Sync should + // be disabled and state cleaned up at once. This can happen for a number + // of reasons, e.g. swapping from a test instance to production, or a + // global stop syncing operation has wiped the store. + virtual void OnStopSyncingPermanently() = 0; + + // After a request to clear server data, these callbacks are invoked to + // indicate success or failure. + virtual void OnClearServerDataSucceeded() = 0; + virtual void OnClearServerDataFailed() = 0; + + // Called after we finish encrypting all appropriate datatypes. + virtual void OnEncryptionComplete( + const syncable::ModelTypeSet& encrypted_types) = 0; + + protected: + virtual ~Observer(); + }; + + typedef Callback0::Type ModeChangeCallback; + + // Create an uninitialized SyncManager. Callers must Init() before using. + explicit SyncManager(const std::string& name); + virtual ~SyncManager(); + + // Initialize the sync manager. |database_location| specifies the path of + // the directory in which to locate a sqlite repository storing the syncer + // backend state. Initialization will open the database, or create it if it + // does not already exist. Returns false on failure. + // |event_handler| is the JsEventHandler used to propagate events to + // chrome://sync-internals. |event_handler| may be uninitialized. + // |sync_server_and_path| and |sync_server_port| represent the Chrome sync + // server to use, and |use_ssl| specifies whether to communicate securely; + // the default is false. + // |post_factory| will be owned internally and used to create + // instances of an HttpPostProvider. + // |model_safe_worker| ownership is given to the SyncManager. + // |user_agent| is a 7-bit ASCII string suitable for use as the User-Agent + // HTTP header. Used internally when collecting stats to classify clients. + // |sync_notifier| is owned and used to listen for notifications. + bool Init(const FilePath& database_location, + const browser_sync::WeakHandle<browser_sync::JsEventHandler>& + event_handler, + const std::string& sync_server_and_path, + int sync_server_port, + bool use_ssl, + HttpPostProviderFactory* post_factory, + browser_sync::ModelSafeWorkerRegistrar* registrar, + const std::string& user_agent, + const SyncCredentials& credentials, + sync_notifier::SyncNotifier* sync_notifier, + const std::string& restored_key_for_bootstrapping, + bool setup_for_test_mode); + + // Returns the username last used for a successful authentication. + // Returns empty if there is no such username. + const std::string& GetAuthenticatedUsername(); + + // Check if the database has been populated with a full "initial" download of + // sync items for each data type currently present in the routing info. + // Prerequisite for calling this is that OnInitializationComplete has been + // called. + bool InitialSyncEndedForAllEnabledTypes(); + + // Update tokens that we're using in Sync. Email must stay the same. + void UpdateCredentials(const SyncCredentials& credentials); + + // Called when the user disables or enables a sync type. + void UpdateEnabledTypes(); + + // Put the syncer in normal mode ready to perform nudges and polls. + void StartSyncingNormally(); + + // Attempt to set the passphrase. If the passphrase is valid, + // OnPassphraseAccepted will be fired to notify the ProfileSyncService and the + // syncer will be nudged so that any update that was waiting for this + // passphrase gets applied as soon as possible. + // If the passphrase in invalid, OnPassphraseRequired will be fired. + // Calling this metdod again is the appropriate course of action to "retry" + // with a new passphrase. + // |is_explicit| is true if the call is in response to the user explicitly + // setting a passphrase as opposed to implicitly (from the users' perspective) + // using their Google Account password. An implicit SetPassphrase will *not* + // *not* override an explicit passphrase set previously. + void SetPassphrase(const std::string& passphrase, bool is_explicit); + + // Set the datatypes we want to encrypt and encrypt any nodes as necessary. + // Note: |encrypted_types| will be unioned with the current set of encrypted + // types, as we do not currently support decrypting datatypes. + void EncryptDataTypes(const syncable::ModelTypeSet& encrypted_types); + + // Puts the SyncScheduler into a mode where no normal nudge or poll traffic + // will occur, but calls to RequestConfig will be supported. If |callback| + // is provided, it will be invoked (from the internal SyncScheduler) when + // the thread has changed to configuration mode. + void StartConfigurationMode(ModeChangeCallback* callback); + + // Switches the mode of operation to CONFIGURATION_MODE and + // schedules a config task to fetch updates for |types|. + void RequestConfig(const syncable::ModelTypeBitSet& types, + sync_api::ConfigureReason reason); + + void RequestCleanupDisabledTypes(); + + // Request a clearing of all data on the server + void RequestClearServerData(); + + // Adds a listener to be notified of sync events. + // NOTE: It is OK (in fact, it's probably a good idea) to call this before + // having received OnInitializationCompleted. + void AddObserver(Observer* observer); + + // Remove the given observer. Make sure to call this if the + // Observer is being destroyed so the SyncManager doesn't + // potentially dereference garbage. + void RemoveObserver(Observer* observer); + + // Status-related getters. Typically GetStatusSummary will suffice, but + // GetDetailedSyncStatus can be useful for gathering debug-level details of + // the internals of the sync engine. + Status::Summary GetStatusSummary() const; + Status GetDetailedStatus() const; + + // Whether or not the Nigori node is encrypted using an explicit passphrase. + bool IsUsingExplicitPassphrase(); + + // Get the internal implementation for use by BaseTransaction, etc. + SyncInternal* GetImpl() const; + + // Call periodically from a database-safe thread to persist recent changes + // to the syncapi model. + void SaveChanges(); + + void RequestEarlyExit(); + + // Issue a final SaveChanges, close sqlite handles, and stop running threads. + // Must be called from the same thread that called Init(). + void Shutdown(); + + UserShare* GetUserShare() const; + + // Inform the cryptographer of the most recent passphrase and set of encrypted + // types (from nigori node), then ensure all data that needs encryption is + // encrypted with the appropriate passphrase. + // Note: opens a transaction and can trigger ON_PASSPHRASE_REQUIRED, so must + // only be called after syncapi has been initialized. + void RefreshEncryption(); + + syncable::ModelTypeSet GetEncryptedDataTypes() const; + + // Uses a read-only transaction to determine if the directory being synced has + // any remaining unsynced items. + bool HasUnsyncedItems() const; + + // Logs the list of unsynced meta handles. + void LogUnsyncedItems(int level) const; + + // Functions used for testing. + + void TriggerOnNotificationStateChangeForTest( + bool notifications_enabled); + + void TriggerOnIncomingNotificationForTest( + const syncable::ModelTypeBitSet& model_types); + + private: + // An opaque pointer to the nested private class. + SyncInternal* data_; + + DISALLOW_COPY_AND_ASSIGN(SyncManager); +}; + +bool InitialSyncEndedForTypes(syncable::ModelTypeSet types, UserShare* share); + +// Returns the string representation of a PassphraseRequiredReason value. +std::string PassphraseRequiredReasonToString(PassphraseRequiredReason reason); + +} // namespace sync_api + +#endif // CHROME_BROWSER_SYNC_INTERNAL_API_SYNC_MANAGER_H_ diff --git a/chrome/browser/sync/internal_api/syncapi_mock.h b/chrome/browser/sync/internal_api/syncapi_mock.h new file mode 100644 index 0000000..dd56d7a --- /dev/null +++ b/chrome/browser/sync/internal_api/syncapi_mock.h @@ -0,0 +1,27 @@ +// 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_INTERNAL_API_SYNCAPI_MOCK_H_ +#define CHROME_BROWSER_SYNC_INTERNAL_API_SYNCAPI_MOCK_H_ +#pragma once + +#include "chrome/browser/sync/internal_api/write_transaction.h" +#include "chrome/browser/sync/syncable/syncable.h" +#include "chrome/browser/sync/syncable/syncable_mock.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +using sync_api::WriteTransaction; + +class MockWriteTransaction : public sync_api::WriteTransaction { + public: + MockWriteTransaction(const tracked_objects::Location& from_here, + Directory* directory) + : sync_api::WriteTransaction() { + SetTransaction(new MockSyncableWriteTransaction(from_here, directory)); + } +}; + +#endif // CHROME_BROWSER_SYNC_INTERNAL_API_SYNCAPI_MOCK_H_ + diff --git a/chrome/browser/sync/internal_api/syncapi_unittest.cc b/chrome/browser/sync/internal_api/syncapi_unittest.cc new file mode 100644 index 0000000..17f77e9 --- /dev/null +++ b/chrome/browser/sync/internal_api/syncapi_unittest.cc @@ -0,0 +1,1436 @@ +// 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. + +// Unit tests for the SyncApi. Note that a lot of the underlying +// functionality is provided by the Syncable layer, which has its own +// unit tests. We'll test SyncApi specific things in this harness. + +#include <cstddef> +#include <map> + +#include "base/basictypes.h" +#include "base/compiler_specific.h" +#include "base/format_macros.h" +#include "base/memory/scoped_ptr.h" +#include "base/message_loop.h" +#include "base/scoped_temp_dir.h" +#include "base/string_number_conversions.h" +#include "base/stringprintf.h" +#include "base/tracked.h" +#include "base/utf_string_conversions.h" +#include "base/values.h" +#include "chrome/browser/password_manager/encryptor.h" +#include "chrome/browser/sync/engine/http_post_provider_factory.h" +#include "chrome/browser/sync/engine/http_post_provider_interface.h" +#include "chrome/browser/sync/engine/model_safe_worker.h" +#include "chrome/browser/sync/engine/nigori_util.h" +#include "chrome/browser/sync/internal_api/read_node.h" +#include "chrome/browser/sync/internal_api/read_transaction.h" +#include "chrome/browser/sync/internal_api/sync_manager.h" +#include "chrome/browser/sync/internal_api/write_node.h" +#include "chrome/browser/sync/internal_api/write_transaction.h" +#include "chrome/browser/sync/js/js_arg_list.h" +#include "chrome/browser/sync/js/js_backend.h" +#include "chrome/browser/sync/js/js_event_handler.h" +#include "chrome/browser/sync/js/js_reply_handler.h" +#include "chrome/browser/sync/js/js_test_util.h" +#include "chrome/browser/sync/notifier/sync_notifier.h" +#include "chrome/browser/sync/notifier/sync_notifier_observer.h" +#include "chrome/browser/sync/protocol/bookmark_specifics.pb.h" +#include "chrome/browser/sync/protocol/password_specifics.pb.h" +#include "chrome/browser/sync/protocol/proto_value_conversions.h" +#include "chrome/browser/sync/protocol/sync.pb.h" +#include "chrome/browser/sync/sessions/sync_session.h" +#include "chrome/browser/sync/syncable/directory_manager.h" +#include "chrome/browser/sync/syncable/syncable.h" +#include "chrome/browser/sync/syncable/syncable_id.h" +#include "chrome/browser/sync/util/cryptographer.h" +#include "chrome/test/base/values_test_util.h" +#include "chrome/test/sync/engine/test_user_share.h" +#include "content/browser/browser_thread.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +using browser_sync::Cryptographer; +using browser_sync::HasArgsAsList; +using browser_sync::HasDetailsAsDictionary; +using browser_sync::KeyParams; +using browser_sync::JsArgList; +using browser_sync::JsBackend; +using browser_sync::JsEventHandler; +using browser_sync::JsReplyHandler; +using browser_sync::MockJsEventHandler; +using browser_sync::MockJsReplyHandler; +using browser_sync::ModelSafeRoutingInfo; +using browser_sync::ModelSafeWorker; +using browser_sync::ModelSafeWorkerRegistrar; +using browser_sync::sessions::SyncSessionSnapshot; +using browser_sync::WeakHandle; +using syncable::ModelType; +using syncable::ModelTypeSet; +using test::ExpectDictDictionaryValue; +using test::ExpectDictStringValue; +using testing::_; +using testing::AnyNumber; +using testing::AtLeast; +using testing::InSequence; +using testing::Invoke; +using testing::SaveArg; +using testing::StrictMock; + +namespace sync_api { + +namespace { + +void ExpectInt64Value(int64 expected_value, + const DictionaryValue& value, const std::string& key) { + std::string int64_str; + EXPECT_TRUE(value.GetString(key, &int64_str)); + int64 val = 0; + EXPECT_TRUE(base::StringToInt64(int64_str, &val)); + EXPECT_EQ(expected_value, val); +} + +// Makes a non-folder child of the root node. Returns the id of the +// newly-created node. +int64 MakeNode(UserShare* share, + ModelType model_type, + const std::string& client_tag) { + WriteTransaction trans(FROM_HERE, share); + ReadNode root_node(&trans); + root_node.InitByRootLookup(); + WriteNode node(&trans); + EXPECT_TRUE(node.InitUniqueByCreation(model_type, root_node, client_tag)); + node.SetIsFolder(false); + return node.GetId(); +} + +// Makes a non-folder child of a non-root node. Returns the id of the +// newly-created node. +int64 MakeNodeWithParent(UserShare* share, + ModelType model_type, + const std::string& client_tag, + int64 parent_id) { + WriteTransaction trans(FROM_HERE, share); + ReadNode parent_node(&trans); + EXPECT_TRUE(parent_node.InitByIdLookup(parent_id)); + WriteNode node(&trans); + EXPECT_TRUE(node.InitUniqueByCreation(model_type, parent_node, client_tag)); + node.SetIsFolder(false); + return node.GetId(); +} + +// Makes a folder child of a non-root node. Returns the id of the +// newly-created node. +int64 MakeFolderWithParent(UserShare* share, + ModelType model_type, + int64 parent_id, + BaseNode* predecessor) { + WriteTransaction trans(FROM_HERE, share); + ReadNode parent_node(&trans); + EXPECT_TRUE(parent_node.InitByIdLookup(parent_id)); + WriteNode node(&trans); + EXPECT_TRUE(node.InitByCreation(model_type, parent_node, predecessor)); + node.SetIsFolder(true); + return node.GetId(); +} + +// Creates the "synced" root node for a particular datatype. We use the syncable +// methods here so that the syncer treats these nodes as if they were already +// received from the server. +int64 MakeServerNodeForType(UserShare* share, + ModelType model_type) { + sync_pb::EntitySpecifics specifics; + syncable::AddDefaultExtensionValue(model_type, &specifics); + syncable::ScopedDirLookup dir(share->dir_manager.get(), share->name); + EXPECT_TRUE(dir.good()); + syncable::WriteTransaction trans(FROM_HERE, syncable::UNITTEST, dir); + // Attempt to lookup by nigori tag. + std::string type_tag = syncable::ModelTypeToRootTag(model_type); + syncable::Id node_id = syncable::Id::CreateFromServerId(type_tag); + syncable::MutableEntry entry(&trans, syncable::CREATE_NEW_UPDATE_ITEM, + node_id); + EXPECT_TRUE(entry.good()); + entry.Put(syncable::BASE_VERSION, 1); + entry.Put(syncable::SERVER_VERSION, 1); + entry.Put(syncable::IS_UNAPPLIED_UPDATE, false); + entry.Put(syncable::SERVER_PARENT_ID, syncable::kNullId); + entry.Put(syncable::SERVER_IS_DIR, true); + entry.Put(syncable::IS_DIR, true); + entry.Put(syncable::SERVER_SPECIFICS, specifics); + entry.Put(syncable::UNIQUE_SERVER_TAG, type_tag); + entry.Put(syncable::NON_UNIQUE_NAME, type_tag); + entry.Put(syncable::IS_DEL, false); + entry.Put(syncable::SPECIFICS, specifics); + return entry.Get(syncable::META_HANDLE); +} + +} // namespace + +class SyncApiTest : public testing::Test { + public: + virtual void SetUp() { + test_user_share_.SetUp(); + } + + virtual void TearDown() { + test_user_share_.TearDown(); + } + + protected: + browser_sync::TestUserShare test_user_share_; +}; + +TEST_F(SyncApiTest, SanityCheckTest) { + { + ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); + EXPECT_TRUE(trans.GetWrappedTrans() != NULL); + } + { + WriteTransaction trans(FROM_HERE, test_user_share_.user_share()); + EXPECT_TRUE(trans.GetWrappedTrans() != NULL); + } + { + // No entries but root should exist + ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); + ReadNode node(&trans); + // Metahandle 1 can be root, sanity check 2 + EXPECT_FALSE(node.InitByIdLookup(2)); + } +} + +TEST_F(SyncApiTest, BasicTagWrite) { + { + ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); + ReadNode root_node(&trans); + root_node.InitByRootLookup(); + EXPECT_EQ(root_node.GetFirstChildId(), 0); + } + + ignore_result(MakeNode(test_user_share_.user_share(), + syncable::BOOKMARKS, "testtag")); + + { + ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); + ReadNode node(&trans); + EXPECT_TRUE(node.InitByClientTagLookup(syncable::BOOKMARKS, + "testtag")); + + ReadNode root_node(&trans); + root_node.InitByRootLookup(); + EXPECT_NE(node.GetId(), 0); + EXPECT_EQ(node.GetId(), root_node.GetFirstChildId()); + } +} + +TEST_F(SyncApiTest, GenerateSyncableHash) { + EXPECT_EQ("OyaXV5mEzrPS4wbogmtKvRfekAI=", + BaseNode::GenerateSyncableHash(syncable::BOOKMARKS, "tag1")); + EXPECT_EQ("iNFQtRFQb+IZcn1kKUJEZDDkLs4=", + BaseNode::GenerateSyncableHash(syncable::PREFERENCES, "tag1")); + EXPECT_EQ("gO1cPZQXaM73sHOvSA+tKCKFs58=", + BaseNode::GenerateSyncableHash(syncable::AUTOFILL, "tag1")); + + EXPECT_EQ("A0eYIHXM1/jVwKDDp12Up20IkKY=", + BaseNode::GenerateSyncableHash(syncable::BOOKMARKS, "tag2")); + EXPECT_EQ("XYxkF7bhS4eItStFgiOIAU23swI=", + BaseNode::GenerateSyncableHash(syncable::PREFERENCES, "tag2")); + EXPECT_EQ("GFiWzo5NGhjLlN+OyCfhy28DJTQ=", + BaseNode::GenerateSyncableHash(syncable::AUTOFILL, "tag2")); +} + +TEST_F(SyncApiTest, ModelTypesSiloed) { + { + WriteTransaction trans(FROM_HERE, test_user_share_.user_share()); + ReadNode root_node(&trans); + root_node.InitByRootLookup(); + EXPECT_EQ(root_node.GetFirstChildId(), 0); + } + + ignore_result(MakeNode(test_user_share_.user_share(), + syncable::BOOKMARKS, "collideme")); + ignore_result(MakeNode(test_user_share_.user_share(), + syncable::PREFERENCES, "collideme")); + ignore_result(MakeNode(test_user_share_.user_share(), + syncable::AUTOFILL, "collideme")); + + { + ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); + + ReadNode bookmarknode(&trans); + EXPECT_TRUE(bookmarknode.InitByClientTagLookup(syncable::BOOKMARKS, + "collideme")); + + ReadNode prefnode(&trans); + EXPECT_TRUE(prefnode.InitByClientTagLookup(syncable::PREFERENCES, + "collideme")); + + ReadNode autofillnode(&trans); + EXPECT_TRUE(autofillnode.InitByClientTagLookup(syncable::AUTOFILL, + "collideme")); + + EXPECT_NE(bookmarknode.GetId(), prefnode.GetId()); + EXPECT_NE(autofillnode.GetId(), prefnode.GetId()); + EXPECT_NE(bookmarknode.GetId(), autofillnode.GetId()); + } +} + +TEST_F(SyncApiTest, ReadMissingTagsFails) { + { + ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); + ReadNode node(&trans); + EXPECT_FALSE(node.InitByClientTagLookup(syncable::BOOKMARKS, + "testtag")); + } + { + WriteTransaction trans(FROM_HERE, test_user_share_.user_share()); + WriteNode node(&trans); + EXPECT_FALSE(node.InitByClientTagLookup(syncable::BOOKMARKS, + "testtag")); + } +} + +// TODO(chron): Hook this all up to the server and write full integration tests +// for update->undelete behavior. +TEST_F(SyncApiTest, TestDeleteBehavior) { + int64 node_id; + int64 folder_id; + std::string test_title("test1"); + + { + WriteTransaction trans(FROM_HERE, test_user_share_.user_share()); + ReadNode root_node(&trans); + root_node.InitByRootLookup(); + + // we'll use this spare folder later + WriteNode folder_node(&trans); + EXPECT_TRUE(folder_node.InitByCreation(syncable::BOOKMARKS, + root_node, NULL)); + folder_id = folder_node.GetId(); + + WriteNode wnode(&trans); + EXPECT_TRUE(wnode.InitUniqueByCreation(syncable::BOOKMARKS, + root_node, "testtag")); + wnode.SetIsFolder(false); + wnode.SetTitle(UTF8ToWide(test_title)); + + node_id = wnode.GetId(); + } + + // Ensure we can delete something with a tag. + { + WriteTransaction trans(FROM_HERE, test_user_share_.user_share()); + WriteNode wnode(&trans); + EXPECT_TRUE(wnode.InitByClientTagLookup(syncable::BOOKMARKS, + "testtag")); + EXPECT_FALSE(wnode.GetIsFolder()); + EXPECT_EQ(wnode.GetTitle(), test_title); + + wnode.Remove(); + } + + // Lookup of a node which was deleted should return failure, + // but have found some data about the node. + { + ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); + ReadNode node(&trans); + EXPECT_FALSE(node.InitByClientTagLookup(syncable::BOOKMARKS, + "testtag")); + // Note that for proper function of this API this doesn't need to be + // filled, we're checking just to make sure the DB worked in this test. + EXPECT_EQ(node.GetTitle(), test_title); + } + + { + WriteTransaction trans(FROM_HERE, test_user_share_.user_share()); + ReadNode folder_node(&trans); + EXPECT_TRUE(folder_node.InitByIdLookup(folder_id)); + + WriteNode wnode(&trans); + // This will undelete the tag. + EXPECT_TRUE(wnode.InitUniqueByCreation(syncable::BOOKMARKS, + folder_node, "testtag")); + EXPECT_EQ(wnode.GetIsFolder(), false); + EXPECT_EQ(wnode.GetParentId(), folder_node.GetId()); + EXPECT_EQ(wnode.GetId(), node_id); + EXPECT_NE(wnode.GetTitle(), test_title); // Title should be cleared + wnode.SetTitle(UTF8ToWide(test_title)); + } + + // Now look up should work. + { + ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); + ReadNode node(&trans); + EXPECT_TRUE(node.InitByClientTagLookup(syncable::BOOKMARKS, + "testtag")); + EXPECT_EQ(node.GetTitle(), test_title); + EXPECT_EQ(node.GetModelType(), syncable::BOOKMARKS); + } +} + +TEST_F(SyncApiTest, WriteAndReadPassword) { + KeyParams params = {"localhost", "username", "passphrase"}; + { + ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); + trans.GetCryptographer()->AddKey(params); + } + { + WriteTransaction trans(FROM_HERE, test_user_share_.user_share()); + ReadNode root_node(&trans); + root_node.InitByRootLookup(); + + WriteNode password_node(&trans); + EXPECT_TRUE(password_node.InitUniqueByCreation(syncable::PASSWORDS, + root_node, "foo")); + sync_pb::PasswordSpecificsData data; + data.set_password_value("secret"); + password_node.SetPasswordSpecifics(data); + } + { + ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); + ReadNode root_node(&trans); + root_node.InitByRootLookup(); + + ReadNode password_node(&trans); + EXPECT_TRUE(password_node.InitByClientTagLookup(syncable::PASSWORDS, + "foo")); + const sync_pb::PasswordSpecificsData& data = + password_node.GetPasswordSpecifics(); + EXPECT_EQ("secret", data.password_value()); + } +} + +TEST_F(SyncApiTest, BaseNodeSetSpecifics) { + int64 child_id = MakeNode(test_user_share_.user_share(), + syncable::BOOKMARKS, "testtag"); + WriteTransaction trans(FROM_HERE, test_user_share_.user_share()); + WriteNode node(&trans); + EXPECT_TRUE(node.InitByIdLookup(child_id)); + + sync_pb::EntitySpecifics entity_specifics; + entity_specifics.MutableExtension(sync_pb::bookmark)-> + set_url("http://www.google.com"); + + EXPECT_NE(entity_specifics.SerializeAsString(), + node.GetEntitySpecifics().SerializeAsString()); + node.SetEntitySpecifics(entity_specifics); + EXPECT_EQ(entity_specifics.SerializeAsString(), + node.GetEntitySpecifics().SerializeAsString()); +} + +TEST_F(SyncApiTest, BaseNodeSetSpecificsPreservesUnknownFields) { + int64 child_id = MakeNode(test_user_share_.user_share(), + syncable::BOOKMARKS, "testtag"); + WriteTransaction trans(FROM_HERE, test_user_share_.user_share()); + WriteNode node(&trans); + EXPECT_TRUE(node.InitByIdLookup(child_id)); + EXPECT_TRUE(node.GetEntitySpecifics().unknown_fields().empty()); + + sync_pb::EntitySpecifics entity_specifics; + entity_specifics.MutableExtension(sync_pb::bookmark)-> + set_url("http://www.google.com"); + entity_specifics.mutable_unknown_fields()->AddFixed32(5, 100); + node.SetEntitySpecifics(entity_specifics); + EXPECT_FALSE(node.GetEntitySpecifics().unknown_fields().empty()); + + entity_specifics.mutable_unknown_fields()->Clear(); + node.SetEntitySpecifics(entity_specifics); + EXPECT_FALSE(node.GetEntitySpecifics().unknown_fields().empty()); +} + +namespace { + +void CheckNodeValue(const BaseNode& node, const DictionaryValue& value, + bool is_detailed) { + ExpectInt64Value(node.GetId(), value, "id"); + { + bool is_folder = false; + EXPECT_TRUE(value.GetBoolean("isFolder", &is_folder)); + EXPECT_EQ(node.GetIsFolder(), is_folder); + } + ExpectDictStringValue(node.GetTitle(), value, "title"); + { + ModelType expected_model_type = node.GetModelType(); + std::string type_str; + EXPECT_TRUE(value.GetString("type", &type_str)); + if (expected_model_type >= syncable::FIRST_REAL_MODEL_TYPE) { + ModelType model_type = + syncable::ModelTypeFromString(type_str); + EXPECT_EQ(expected_model_type, model_type); + } else if (expected_model_type == syncable::TOP_LEVEL_FOLDER) { + EXPECT_EQ("Top-level folder", type_str); + } else if (expected_model_type == syncable::UNSPECIFIED) { + EXPECT_EQ("Unspecified", type_str); + } else { + ADD_FAILURE(); + } + } + if (is_detailed) { + ExpectInt64Value(node.GetParentId(), value, "parentId"); + ExpectInt64Value(node.GetModificationTime(), value, "modificationTime"); + ExpectInt64Value(node.GetExternalId(), value, "externalId"); + ExpectInt64Value(node.GetPredecessorId(), value, "predecessorId"); + ExpectInt64Value(node.GetSuccessorId(), value, "successorId"); + ExpectInt64Value(node.GetFirstChildId(), value, "firstChildId"); + { + scoped_ptr<DictionaryValue> expected_entry(node.GetEntry()->ToValue()); + Value* entry = NULL; + EXPECT_TRUE(value.Get("entry", &entry)); + EXPECT_TRUE(Value::Equals(entry, expected_entry.get())); + } + EXPECT_EQ(11u, value.size()); + } else { + EXPECT_EQ(4u, value.size()); + } +} + +} // namespace + +TEST_F(SyncApiTest, BaseNodeGetSummaryAsValue) { + ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); + ReadNode node(&trans); + node.InitByRootLookup(); + scoped_ptr<DictionaryValue> details(node.GetSummaryAsValue()); + if (details.get()) { + CheckNodeValue(node, *details, false); + } else { + ADD_FAILURE(); + } +} + +TEST_F(SyncApiTest, BaseNodeGetDetailsAsValue) { + ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); + ReadNode node(&trans); + node.InitByRootLookup(); + scoped_ptr<DictionaryValue> details(node.GetDetailsAsValue()); + if (details.get()) { + CheckNodeValue(node, *details, true); + } else { + ADD_FAILURE(); + } +} + +namespace { + +void ExpectChangeRecordActionValue(SyncManager::ChangeRecord::Action + expected_value, + const DictionaryValue& value, + const std::string& key) { + std::string str_value; + EXPECT_TRUE(value.GetString(key, &str_value)); + switch (expected_value) { + case SyncManager::ChangeRecord::ACTION_ADD: + EXPECT_EQ("Add", str_value); + break; + case SyncManager::ChangeRecord::ACTION_UPDATE: + EXPECT_EQ("Update", str_value); + break; + case SyncManager::ChangeRecord::ACTION_DELETE: + EXPECT_EQ("Delete", str_value); + break; + default: + NOTREACHED(); + break; + } +} + +void CheckNonDeleteChangeRecordValue(const SyncManager::ChangeRecord& record, + const DictionaryValue& value, + BaseTransaction* trans) { + EXPECT_NE(SyncManager::ChangeRecord::ACTION_DELETE, record.action); + ExpectChangeRecordActionValue(record.action, value, "action"); + { + ReadNode node(trans); + EXPECT_TRUE(node.InitByIdLookup(record.id)); + scoped_ptr<DictionaryValue> expected_details(node.GetDetailsAsValue()); + ExpectDictDictionaryValue(*expected_details, value, "node"); + } +} + +void CheckDeleteChangeRecordValue(const SyncManager::ChangeRecord& record, + const DictionaryValue& value) { + EXPECT_EQ(SyncManager::ChangeRecord::ACTION_DELETE, record.action); + ExpectChangeRecordActionValue(record.action, value, "action"); + DictionaryValue* node_value = NULL; + EXPECT_TRUE(value.GetDictionary("node", &node_value)); + if (node_value) { + ExpectInt64Value(record.id, *node_value, "id"); + scoped_ptr<DictionaryValue> expected_specifics_value( + browser_sync::EntitySpecificsToValue(record.specifics)); + ExpectDictDictionaryValue(*expected_specifics_value, + *node_value, "specifics"); + scoped_ptr<DictionaryValue> expected_extra_value; + if (record.extra.get()) { + expected_extra_value.reset(record.extra->ToValue()); + } + Value* extra_value = NULL; + EXPECT_EQ(record.extra.get() != NULL, + node_value->Get("extra", &extra_value)); + EXPECT_TRUE(Value::Equals(extra_value, expected_extra_value.get())); + } +} + +class MockExtraChangeRecordData + : public SyncManager::ExtraPasswordChangeRecordData { + public: + MOCK_CONST_METHOD0(ToValue, DictionaryValue*()); +}; + +} // namespace + +TEST_F(SyncApiTest, ChangeRecordToValue) { + int64 child_id = MakeNode(test_user_share_.user_share(), + syncable::BOOKMARKS, "testtag"); + sync_pb::EntitySpecifics child_specifics; + { + ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); + ReadNode node(&trans); + EXPECT_TRUE(node.InitByIdLookup(child_id)); + child_specifics = node.GetEntry()->Get(syncable::SPECIFICS); + } + + // Add + { + ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); + SyncManager::ChangeRecord record; + record.action = SyncManager::ChangeRecord::ACTION_ADD; + record.id = 1; + record.specifics = child_specifics; + record.extra.reset(new StrictMock<MockExtraChangeRecordData>()); + scoped_ptr<DictionaryValue> value(record.ToValue(&trans)); + CheckNonDeleteChangeRecordValue(record, *value, &trans); + } + + // Update + { + ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); + SyncManager::ChangeRecord record; + record.action = SyncManager::ChangeRecord::ACTION_UPDATE; + record.id = child_id; + record.specifics = child_specifics; + record.extra.reset(new StrictMock<MockExtraChangeRecordData>()); + scoped_ptr<DictionaryValue> value(record.ToValue(&trans)); + CheckNonDeleteChangeRecordValue(record, *value, &trans); + } + + // Delete (no extra) + { + ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); + SyncManager::ChangeRecord record; + record.action = SyncManager::ChangeRecord::ACTION_DELETE; + record.id = child_id + 1; + record.specifics = child_specifics; + scoped_ptr<DictionaryValue> value(record.ToValue(&trans)); + CheckDeleteChangeRecordValue(record, *value); + } + + // Delete (with extra) + { + ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); + SyncManager::ChangeRecord record; + record.action = SyncManager::ChangeRecord::ACTION_DELETE; + record.id = child_id + 1; + record.specifics = child_specifics; + + DictionaryValue extra_value; + extra_value.SetString("foo", "bar"); + scoped_ptr<StrictMock<MockExtraChangeRecordData> > extra( + new StrictMock<MockExtraChangeRecordData>()); + EXPECT_CALL(*extra, ToValue()).Times(2).WillRepeatedly( + Invoke(&extra_value, &DictionaryValue::DeepCopy)); + + record.extra.reset(extra.release()); + scoped_ptr<DictionaryValue> value(record.ToValue(&trans)); + CheckDeleteChangeRecordValue(record, *value); + } +} + +namespace { + +class TestHttpPostProviderInterface : public HttpPostProviderInterface { + public: + virtual ~TestHttpPostProviderInterface() {} + + virtual void SetUserAgent(const char* user_agent) OVERRIDE {} + virtual void SetExtraRequestHeaders(const char* headers) OVERRIDE {} + virtual void SetURL(const char* url, int port) OVERRIDE {} + virtual void SetPostPayload(const char* content_type, + int content_length, + const char* content) OVERRIDE {} + virtual bool MakeSynchronousPost(int* os_error_code, int* response_code) + OVERRIDE { + return false; + } + virtual int GetResponseContentLength() const OVERRIDE { + return 0; + } + virtual const char* GetResponseContent() const OVERRIDE { + return ""; + } + virtual const std::string GetResponseHeaderValue( + const std::string& name) const OVERRIDE { + return ""; + } + virtual void Abort() OVERRIDE {} +}; + +class TestHttpPostProviderFactory : public HttpPostProviderFactory { + public: + virtual ~TestHttpPostProviderFactory() {} + virtual HttpPostProviderInterface* Create() OVERRIDE { + return new TestHttpPostProviderInterface(); + } + virtual void Destroy(HttpPostProviderInterface* http) OVERRIDE { + delete http; + } +}; + +class SyncManagerObserverMock : public SyncManager::Observer { + public: + MOCK_METHOD4(OnChangesApplied, + void(ModelType, + const BaseTransaction*, + const SyncManager::ChangeRecord*, + int)); // NOLINT + MOCK_METHOD1(OnChangesComplete, void(ModelType)); // NOLINT + MOCK_METHOD1(OnSyncCycleCompleted, + void(const SyncSessionSnapshot*)); // NOLINT + MOCK_METHOD1(OnInitializationComplete, + void(const WeakHandle<JsBackend>&)); // NOLINT + MOCK_METHOD1(OnAuthError, void(const GoogleServiceAuthError&)); // NOLINT + MOCK_METHOD1(OnPassphraseRequired, + void(sync_api::PassphraseRequiredReason)); // NOLINT + MOCK_METHOD1(OnPassphraseAccepted, void(const std::string&)); // NOLINT + MOCK_METHOD0(OnStopSyncingPermanently, void()); // NOLINT + MOCK_METHOD1(OnUpdatedToken, void(const std::string&)); // NOLINT + MOCK_METHOD1(OnMigrationNeededForTypes, void(const ModelTypeSet&)); + MOCK_METHOD0(OnClearServerDataFailed, void()); // NOLINT + MOCK_METHOD0(OnClearServerDataSucceeded, void()); // NOLINT + MOCK_METHOD1(OnEncryptionComplete, void(const ModelTypeSet&)); // NOLINT +}; + +class SyncNotifierMock : public sync_notifier::SyncNotifier { + public: + MOCK_METHOD1(AddObserver, void(sync_notifier::SyncNotifierObserver*)); + MOCK_METHOD1(RemoveObserver, void(sync_notifier::SyncNotifierObserver*)); + MOCK_METHOD1(SetUniqueId, void(const std::string&)); + MOCK_METHOD1(SetState, void(const std::string&)); + MOCK_METHOD2(UpdateCredentials, + void(const std::string&, const std::string&)); + MOCK_METHOD1(UpdateEnabledTypes, + void(const syncable::ModelTypeSet&)); + MOCK_METHOD0(SendNotification, void()); +}; + +class SyncManagerTest : public testing::Test, + public ModelSafeWorkerRegistrar { + protected: + SyncManagerTest() + : ui_thread_(BrowserThread::UI, &ui_loop_), + sync_notifier_mock_(NULL), + sync_manager_("Test sync manager"), + sync_notifier_observer_(NULL), + update_enabled_types_call_count_(0) {} + + virtual ~SyncManagerTest() { + EXPECT_FALSE(sync_notifier_mock_); + } + + // Test implementation. + void SetUp() { + ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); + + SyncCredentials credentials; + credentials.email = "foo@bar.com"; + credentials.sync_token = "sometoken"; + + sync_notifier_mock_ = new StrictMock<SyncNotifierMock>(); + EXPECT_CALL(*sync_notifier_mock_, AddObserver(_)). + WillOnce(Invoke(this, &SyncManagerTest::SyncNotifierAddObserver)); + EXPECT_CALL(*sync_notifier_mock_, SetUniqueId(_)); + EXPECT_CALL(*sync_notifier_mock_, SetState("")); + EXPECT_CALL(*sync_notifier_mock_, + UpdateCredentials(credentials.email, credentials.sync_token)); + EXPECT_CALL(*sync_notifier_mock_, UpdateEnabledTypes(_)). + Times(AtLeast(1)). + WillRepeatedly( + Invoke(this, &SyncManagerTest::SyncNotifierUpdateEnabledTypes)); + EXPECT_CALL(*sync_notifier_mock_, RemoveObserver(_)). + WillOnce(Invoke(this, &SyncManagerTest::SyncNotifierRemoveObserver)); + + sync_manager_.AddObserver(&observer_); + EXPECT_CALL(observer_, OnInitializationComplete(_)). + WillOnce(SaveArg<0>(&js_backend_)); + + EXPECT_FALSE(sync_notifier_observer_); + EXPECT_FALSE(js_backend_.IsInitialized()); + + // Takes ownership of |sync_notifier_mock_|. + sync_manager_.Init(temp_dir_.path(), + WeakHandle<JsEventHandler>(), + "bogus", 0, false, + new TestHttpPostProviderFactory(), this, "bogus", + credentials, sync_notifier_mock_, "", + true /* setup_for_test_mode */); + + EXPECT_TRUE(sync_notifier_observer_); + EXPECT_TRUE(js_backend_.IsInitialized()); + + EXPECT_EQ(1, update_enabled_types_call_count_); + + ModelSafeRoutingInfo routes; + GetModelSafeRoutingInfo(&routes); + for (ModelSafeRoutingInfo::iterator i = routes.begin(); i != routes.end(); + ++i) { + EXPECT_CALL(observer_, OnChangesApplied(i->first, _, _, 1)) + .RetiresOnSaturation(); + EXPECT_CALL(observer_, OnChangesComplete(i->first)) + .RetiresOnSaturation(); + type_roots_[i->first] = MakeServerNodeForType( + sync_manager_.GetUserShare(), i->first); + } + PumpLoop(); + } + + void TearDown() { + sync_manager_.RemoveObserver(&observer_); + sync_manager_.Shutdown(); + sync_notifier_mock_ = NULL; + EXPECT_FALSE(sync_notifier_observer_); + PumpLoop(); + } + + // ModelSafeWorkerRegistrar implementation. + virtual void GetWorkers(std::vector<ModelSafeWorker*>* out) { + NOTIMPLEMENTED(); + out->clear(); + } + virtual void GetModelSafeRoutingInfo(ModelSafeRoutingInfo* out) { + (*out)[syncable::NIGORI] = browser_sync::GROUP_PASSIVE; + (*out)[syncable::BOOKMARKS] = browser_sync::GROUP_PASSIVE; + (*out)[syncable::THEMES] = browser_sync::GROUP_PASSIVE; + (*out)[syncable::SESSIONS] = browser_sync::GROUP_PASSIVE; + (*out)[syncable::PASSWORDS] = browser_sync::GROUP_PASSIVE; + } + + // Helper methods. + bool SetUpEncryption() { + // Mock the Mac Keychain service. The real Keychain can block on user input. + #if defined(OS_MACOSX) + Encryptor::UseMockKeychain(true); + #endif + + // We need to create the nigori node as if it were an applied server update. + UserShare* share = sync_manager_.GetUserShare(); + int64 nigori_id = GetIdForDataType(syncable::NIGORI); + if (nigori_id == kInvalidId) + return false; + + // Set the nigori cryptographer information. + WriteTransaction trans(FROM_HERE, share); + Cryptographer* cryptographer = trans.GetCryptographer(); + if (!cryptographer) + return false; + KeyParams params = {"localhost", "dummy", "foobar"}; + cryptographer->AddKey(params); + sync_pb::NigoriSpecifics nigori; + cryptographer->GetKeys(nigori.mutable_encrypted()); + WriteNode node(&trans); + EXPECT_TRUE(node.InitByIdLookup(nigori_id)); + node.SetNigoriSpecifics(nigori); + return cryptographer->is_ready(); + } + + int64 GetIdForDataType(ModelType type) { + if (type_roots_.count(type) == 0) + return 0; + return type_roots_[type]; + } + + void SyncNotifierAddObserver( + sync_notifier::SyncNotifierObserver* sync_notifier_observer) { + EXPECT_EQ(NULL, sync_notifier_observer_); + sync_notifier_observer_ = sync_notifier_observer; + } + + void SyncNotifierRemoveObserver( + sync_notifier::SyncNotifierObserver* sync_notifier_observer) { + EXPECT_EQ(sync_notifier_observer_, sync_notifier_observer); + sync_notifier_observer_ = NULL; + } + + void SyncNotifierUpdateEnabledTypes( + const syncable::ModelTypeSet& types) { + ModelSafeRoutingInfo routes; + GetModelSafeRoutingInfo(&routes); + syncable::ModelTypeSet expected_types; + for (ModelSafeRoutingInfo::const_iterator it = routes.begin(); + it != routes.end(); ++it) { + expected_types.insert(it->first); + } + EXPECT_EQ(expected_types, types); + ++update_enabled_types_call_count_; + } + + void PumpLoop() { + ui_loop_.RunAllPending(); + } + + void SendJsMessage(const std::string& name, const JsArgList& args, + const WeakHandle<JsReplyHandler>& reply_handler) { + js_backend_.Call(FROM_HERE, &JsBackend::ProcessJsMessage, + name, args, reply_handler); + PumpLoop(); + } + + void SetJsEventHandler(const WeakHandle<JsEventHandler>& event_handler) { + js_backend_.Call(FROM_HERE, &JsBackend::SetJsEventHandler, + event_handler); + PumpLoop(); + } + + private: + // Needed by |ui_thread_|. + MessageLoopForUI ui_loop_; + // Needed by |sync_manager_|. + BrowserThread ui_thread_; + // Needed by |sync_manager_|. + ScopedTempDir temp_dir_; + // Sync Id's for the roots of the enabled datatypes. + std::map<ModelType, int64> type_roots_; + StrictMock<SyncNotifierMock>* sync_notifier_mock_; + + protected: + SyncManager sync_manager_; + WeakHandle<JsBackend> js_backend_; + StrictMock<SyncManagerObserverMock> observer_; + sync_notifier::SyncNotifierObserver* sync_notifier_observer_; + int update_enabled_types_call_count_; +}; + +TEST_F(SyncManagerTest, UpdateEnabledTypes) { + EXPECT_EQ(1, update_enabled_types_call_count_); + // Triggers SyncNotifierUpdateEnabledTypes. + sync_manager_.UpdateEnabledTypes(); + EXPECT_EQ(2, update_enabled_types_call_count_); +} + +TEST_F(SyncManagerTest, ProcessJsMessage) { + const JsArgList kNoArgs; + + StrictMock<MockJsReplyHandler> reply_handler; + + ListValue false_args; + false_args.Append(Value::CreateBooleanValue(false)); + + EXPECT_CALL(reply_handler, + HandleJsReply("getNotificationState", + HasArgsAsList(false_args))); + + // This message should be dropped. + SendJsMessage("unknownMessage", kNoArgs, reply_handler.AsWeakHandle()); + + SendJsMessage("getNotificationState", kNoArgs, reply_handler.AsWeakHandle()); +} + +TEST_F(SyncManagerTest, ProcessJsMessageGetRootNodeDetails) { + const JsArgList kNoArgs; + + StrictMock<MockJsReplyHandler> reply_handler; + + JsArgList return_args; + + EXPECT_CALL(reply_handler, + HandleJsReply("getRootNodeDetails", _)) + .WillOnce(SaveArg<1>(&return_args)); + + SendJsMessage("getRootNodeDetails", kNoArgs, reply_handler.AsWeakHandle()); + + EXPECT_EQ(1u, return_args.Get().GetSize()); + DictionaryValue* node_info = NULL; + EXPECT_TRUE(return_args.Get().GetDictionary(0, &node_info)); + if (node_info) { + ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); + ReadNode node(&trans); + node.InitByRootLookup(); + CheckNodeValue(node, *node_info, true); + } else { + ADD_FAILURE(); + } +} + +void CheckGetNodesByIdReturnArgs(const SyncManager& sync_manager, + const JsArgList& return_args, + int64 id, + bool is_detailed) { + EXPECT_EQ(1u, return_args.Get().GetSize()); + ListValue* nodes = NULL; + ASSERT_TRUE(return_args.Get().GetList(0, &nodes)); + ASSERT_TRUE(nodes); + EXPECT_EQ(1u, nodes->GetSize()); + DictionaryValue* node_info = NULL; + EXPECT_TRUE(nodes->GetDictionary(0, &node_info)); + ASSERT_TRUE(node_info); + ReadTransaction trans(FROM_HERE, sync_manager.GetUserShare()); + ReadNode node(&trans); + EXPECT_TRUE(node.InitByIdLookup(id)); + CheckNodeValue(node, *node_info, is_detailed); +} + +class SyncManagerGetNodesByIdTest : public SyncManagerTest { + protected: + virtual ~SyncManagerGetNodesByIdTest() {} + + void RunGetNodesByIdTest(const char* message_name, bool is_detailed) { + int64 root_id = kInvalidId; + { + ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); + ReadNode root_node(&trans); + root_node.InitByRootLookup(); + root_id = root_node.GetId(); + } + + int64 child_id = + MakeNode(sync_manager_.GetUserShare(), + syncable::BOOKMARKS, "testtag"); + + StrictMock<MockJsReplyHandler> reply_handler; + + JsArgList return_args; + + const int64 ids[] = { root_id, child_id }; + + EXPECT_CALL(reply_handler, + HandleJsReply(message_name, _)) + .Times(arraysize(ids)).WillRepeatedly(SaveArg<1>(&return_args)); + + for (size_t i = 0; i < arraysize(ids); ++i) { + ListValue args; + ListValue* id_values = new ListValue(); + args.Append(id_values); + id_values->Append(Value::CreateStringValue(base::Int64ToString(ids[i]))); + SendJsMessage(message_name, + JsArgList(&args), reply_handler.AsWeakHandle()); + + CheckGetNodesByIdReturnArgs(sync_manager_, return_args, + ids[i], is_detailed); + } + } + + void RunGetNodesByIdFailureTest(const char* message_name) { + StrictMock<MockJsReplyHandler> reply_handler; + + ListValue empty_list_args; + empty_list_args.Append(new ListValue()); + + EXPECT_CALL(reply_handler, + HandleJsReply(message_name, + HasArgsAsList(empty_list_args))) + .Times(6); + + { + ListValue args; + SendJsMessage(message_name, + JsArgList(&args), reply_handler.AsWeakHandle()); + } + + { + ListValue args; + args.Append(new ListValue()); + SendJsMessage(message_name, + JsArgList(&args), reply_handler.AsWeakHandle()); + } + + { + ListValue args; + ListValue* ids = new ListValue(); + args.Append(ids); + ids->Append(Value::CreateStringValue("")); + SendJsMessage(message_name, + JsArgList(&args), reply_handler.AsWeakHandle()); + } + + { + ListValue args; + ListValue* ids = new ListValue(); + args.Append(ids); + ids->Append(Value::CreateStringValue("nonsense")); + SendJsMessage(message_name, + JsArgList(&args), reply_handler.AsWeakHandle()); + } + + { + ListValue args; + ListValue* ids = new ListValue(); + args.Append(ids); + ids->Append(Value::CreateStringValue("0")); + SendJsMessage(message_name, + JsArgList(&args), reply_handler.AsWeakHandle()); + } + + { + ListValue args; + ListValue* ids = new ListValue(); + args.Append(ids); + ids->Append(Value::CreateStringValue("9999")); + SendJsMessage(message_name, + JsArgList(&args), reply_handler.AsWeakHandle()); + } + } +}; + +TEST_F(SyncManagerGetNodesByIdTest, GetNodeSummariesById) { + RunGetNodesByIdTest("getNodeSummariesById", false); +} + +TEST_F(SyncManagerGetNodesByIdTest, GetNodeDetailsById) { + RunGetNodesByIdTest("getNodeDetailsById", true); +} + +TEST_F(SyncManagerGetNodesByIdTest, GetNodeSummariesByIdFailure) { + RunGetNodesByIdFailureTest("getNodeSummariesById"); +} + +TEST_F(SyncManagerGetNodesByIdTest, GetNodeDetailsByIdFailure) { + RunGetNodesByIdFailureTest("getNodeDetailsById"); +} + +TEST_F(SyncManagerTest, GetChildNodeIds) { + StrictMock<MockJsReplyHandler> reply_handler; + + JsArgList return_args; + + EXPECT_CALL(reply_handler, + HandleJsReply("getChildNodeIds", _)) + .Times(1).WillRepeatedly(SaveArg<1>(&return_args)); + + { + ListValue args; + args.Append(Value::CreateStringValue("1")); + SendJsMessage("getChildNodeIds", + JsArgList(&args), reply_handler.AsWeakHandle()); + } + + EXPECT_EQ(1u, return_args.Get().GetSize()); + ListValue* nodes = NULL; + ASSERT_TRUE(return_args.Get().GetList(0, &nodes)); + ASSERT_TRUE(nodes); + EXPECT_EQ(5u, nodes->GetSize()); +} + +TEST_F(SyncManagerTest, GetChildNodeIdsFailure) { + StrictMock<MockJsReplyHandler> reply_handler; + + ListValue empty_list_args; + empty_list_args.Append(new ListValue()); + + EXPECT_CALL(reply_handler, + HandleJsReply("getChildNodeIds", + HasArgsAsList(empty_list_args))) + .Times(5); + + { + ListValue args; + SendJsMessage("getChildNodeIds", + JsArgList(&args), reply_handler.AsWeakHandle()); + } + + { + ListValue args; + args.Append(Value::CreateStringValue("")); + SendJsMessage("getChildNodeIds", + JsArgList(&args), reply_handler.AsWeakHandle()); + } + + { + ListValue args; + args.Append(Value::CreateStringValue("nonsense")); + SendJsMessage("getChildNodeIds", + JsArgList(&args), reply_handler.AsWeakHandle()); + } + + { + ListValue args; + args.Append(Value::CreateStringValue("0")); + SendJsMessage("getChildNodeIds", + JsArgList(&args), reply_handler.AsWeakHandle()); + } + + { + ListValue args; + args.Append(Value::CreateStringValue("9999")); + SendJsMessage("getChildNodeIds", + JsArgList(&args), reply_handler.AsWeakHandle()); + } +} + +// TODO(akalin): Add unit tests for findNodesContainingString message. + +TEST_F(SyncManagerTest, OnNotificationStateChange) { + InSequence dummy; + StrictMock<MockJsEventHandler> event_handler; + + DictionaryValue true_details; + true_details.SetBoolean("enabled", true); + DictionaryValue false_details; + false_details.SetBoolean("enabled", false); + + EXPECT_CALL(event_handler, + HandleJsEvent("onNotificationStateChange", + HasDetailsAsDictionary(true_details))); + EXPECT_CALL(event_handler, + HandleJsEvent("onNotificationStateChange", + HasDetailsAsDictionary(false_details))); + + sync_manager_.TriggerOnNotificationStateChangeForTest(true); + sync_manager_.TriggerOnNotificationStateChangeForTest(false); + + SetJsEventHandler(event_handler.AsWeakHandle()); + sync_manager_.TriggerOnNotificationStateChangeForTest(true); + sync_manager_.TriggerOnNotificationStateChangeForTest(false); + SetJsEventHandler(WeakHandle<JsEventHandler>()); + + sync_manager_.TriggerOnNotificationStateChangeForTest(true); + sync_manager_.TriggerOnNotificationStateChangeForTest(false); + + // Should trigger the replies. + PumpLoop(); +} + +TEST_F(SyncManagerTest, OnIncomingNotification) { + StrictMock<MockJsEventHandler> event_handler; + + const syncable::ModelTypeBitSet empty_model_types; + syncable::ModelTypeBitSet model_types; + model_types.set(syncable::BOOKMARKS); + model_types.set(syncable::THEMES); + + // Build expected_args to have a single argument with the string + // equivalents of model_types. + DictionaryValue expected_details; + { + ListValue* model_type_list = new ListValue(); + expected_details.Set("changedTypes", model_type_list); + for (int i = syncable::FIRST_REAL_MODEL_TYPE; + i < syncable::MODEL_TYPE_COUNT; ++i) { + if (model_types[i]) { + model_type_list->Append( + Value::CreateStringValue( + syncable::ModelTypeToString( + syncable::ModelTypeFromInt(i)))); + } + } + } + + EXPECT_CALL(event_handler, + HandleJsEvent("onIncomingNotification", + HasDetailsAsDictionary(expected_details))); + + sync_manager_.TriggerOnIncomingNotificationForTest(empty_model_types); + sync_manager_.TriggerOnIncomingNotificationForTest(model_types); + + SetJsEventHandler(event_handler.AsWeakHandle()); + sync_manager_.TriggerOnIncomingNotificationForTest(model_types); + SetJsEventHandler(WeakHandle<JsEventHandler>()); + + sync_manager_.TriggerOnIncomingNotificationForTest(empty_model_types); + sync_manager_.TriggerOnIncomingNotificationForTest(model_types); + + // Should trigger the replies. + PumpLoop(); +} + +TEST_F(SyncManagerTest, RefreshEncryptionReady) { + EXPECT_TRUE(SetUpEncryption()); + sync_manager_.RefreshEncryption(); + syncable::ModelTypeSet encrypted_types = + sync_manager_.GetEncryptedDataTypes(); + EXPECT_EQ(1U, encrypted_types.count(syncable::PASSWORDS)); +} + +// Attempt to refresh encryption when nigori not downloaded. +TEST_F(SyncManagerTest, RefreshEncryptionNotReady) { + // Don't set up encryption (no nigori node created). + sync_manager_.RefreshEncryption(); // Should fail. + syncable::ModelTypeSet encrypted_types = + sync_manager_.GetEncryptedDataTypes(); + EXPECT_EQ(1U, encrypted_types.count(syncable::PASSWORDS)); // Hardcoded. +} + +TEST_F(SyncManagerTest, EncryptDataTypesWithNoData) { + EXPECT_TRUE(SetUpEncryption()); + ModelTypeSet encrypted_types; + encrypted_types.insert(syncable::BOOKMARKS); + // Even though Passwords isn't marked for encryption, it's enabled, so it + // should automatically be added to the response of OnEncryptionComplete. + ModelTypeSet expected_types = encrypted_types; + expected_types.insert(syncable::PASSWORDS); + EXPECT_CALL(observer_, OnEncryptionComplete(expected_types)); + sync_manager_.EncryptDataTypes(encrypted_types); + { + ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); + EXPECT_EQ(expected_types, + GetEncryptedTypes(&trans)); + } +} + +TEST_F(SyncManagerTest, EncryptDataTypesWithData) { + size_t batch_size = 5; + EXPECT_TRUE(SetUpEncryption()); + + // Create some unencrypted unsynced data. + int64 folder = MakeFolderWithParent(sync_manager_.GetUserShare(), + syncable::BOOKMARKS, + GetIdForDataType(syncable::BOOKMARKS), + NULL); + // First batch_size nodes are children of folder. + size_t i; + for (i = 0; i < batch_size; ++i) { + MakeNodeWithParent(sync_manager_.GetUserShare(), syncable::BOOKMARKS, + base::StringPrintf("%"PRIuS"", i), folder); + } + // Next batch_size nodes are a different type and on their own. + for (; i < 2*batch_size; ++i) { + MakeNodeWithParent(sync_manager_.GetUserShare(), syncable::SESSIONS, + base::StringPrintf("%"PRIuS"", i), + GetIdForDataType(syncable::SESSIONS)); + } + // Last batch_size nodes are a third type that will not need encryption. + for (; i < 3*batch_size; ++i) { + MakeNodeWithParent(sync_manager_.GetUserShare(), syncable::THEMES, + base::StringPrintf("%"PRIuS"", i), + GetIdForDataType(syncable::THEMES)); + } + + { + ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); + EXPECT_TRUE(syncable::VerifyDataTypeEncryption(trans.GetWrappedTrans(), + trans.GetCryptographer(), + syncable::BOOKMARKS, + false /* not encrypted */)); + EXPECT_TRUE(syncable::VerifyDataTypeEncryption(trans.GetWrappedTrans(), + trans.GetCryptographer(), + syncable::SESSIONS, + false /* not encrypted */)); + EXPECT_TRUE(syncable::VerifyDataTypeEncryption(trans.GetWrappedTrans(), + trans.GetCryptographer(), + syncable::THEMES, + false /* not encrypted */)); + } + + ModelTypeSet encrypted_types; + encrypted_types.insert(syncable::BOOKMARKS); + encrypted_types.insert(syncable::SESSIONS); + encrypted_types.insert(syncable::PASSWORDS); + EXPECT_CALL(observer_, OnEncryptionComplete(encrypted_types)); + sync_manager_.EncryptDataTypes(encrypted_types); + + { + ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); + EXPECT_EQ(encrypted_types, GetEncryptedTypes(&trans)); + EXPECT_TRUE(syncable::VerifyDataTypeEncryption(trans.GetWrappedTrans(), + trans.GetCryptographer(), + syncable::BOOKMARKS, + true /* is encrypted */)); + EXPECT_TRUE(syncable::VerifyDataTypeEncryption(trans.GetWrappedTrans(), + trans.GetCryptographer(), + syncable::SESSIONS, + true /* is encrypted */)); + EXPECT_TRUE(syncable::VerifyDataTypeEncryption(trans.GetWrappedTrans(), + trans.GetCryptographer(), + syncable::THEMES, + false /* not encrypted */)); + } + + // Trigger's a ReEncryptEverything with new passphrase. + testing::Mock::VerifyAndClearExpectations(&observer_); + EXPECT_CALL(observer_, OnPassphraseAccepted(_)).Times(1); + EXPECT_CALL(observer_, OnEncryptionComplete(encrypted_types)).Times(1); + sync_manager_.SetPassphrase("new_passphrase", true); + { + ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); + EXPECT_EQ(encrypted_types, GetEncryptedTypes(&trans)); + EXPECT_TRUE(syncable::VerifyDataTypeEncryption(trans.GetWrappedTrans(), + trans.GetCryptographer(), + syncable::BOOKMARKS, + true /* is encrypted */)); + EXPECT_TRUE(syncable::VerifyDataTypeEncryption(trans.GetWrappedTrans(), + trans.GetCryptographer(), + syncable::SESSIONS, + true /* is encrypted */)); + EXPECT_TRUE(syncable::VerifyDataTypeEncryption(trans.GetWrappedTrans(), + trans.GetCryptographer(), + syncable::THEMES, + false /* not encrypted */)); + } + // Calling EncryptDataTypes with an empty encrypted types should not trigger + // a reencryption and should just notify immediately. + // TODO(zea): add logic to ensure nothing was written. + testing::Mock::VerifyAndClearExpectations(&observer_); + EXPECT_CALL(observer_, OnPassphraseAccepted(_)).Times(0); + EXPECT_CALL(observer_, OnEncryptionComplete(encrypted_types)).Times(1); + sync_manager_.EncryptDataTypes(encrypted_types); +} + +TEST_F(SyncManagerTest, SetPassphraseWithPassword) { + EXPECT_TRUE(SetUpEncryption()); + { + WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); + ReadNode root_node(&trans); + root_node.InitByRootLookup(); + + WriteNode password_node(&trans); + EXPECT_TRUE(password_node.InitUniqueByCreation(syncable::PASSWORDS, + root_node, "foo")); + sync_pb::PasswordSpecificsData data; + data.set_password_value("secret"); + password_node.SetPasswordSpecifics(data); + } + EXPECT_CALL(observer_, OnPassphraseAccepted(_)); + EXPECT_CALL(observer_, OnEncryptionComplete(_)); + sync_manager_.SetPassphrase("new_passphrase", true); + { + ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); + ReadNode password_node(&trans); + EXPECT_TRUE(password_node.InitByClientTagLookup(syncable::PASSWORDS, + "foo")); + const sync_pb::PasswordSpecificsData& data = + password_node.GetPasswordSpecifics(); + EXPECT_EQ("secret", data.password_value()); + } +} + +TEST_F(SyncManagerTest, SetPassphraseWithEmptyPasswordNode) { + EXPECT_TRUE(SetUpEncryption()); + int64 node_id = 0; + std::string tag = "foo"; + { + WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); + ReadNode root_node(&trans); + root_node.InitByRootLookup(); + + WriteNode password_node(&trans); + EXPECT_TRUE(password_node.InitUniqueByCreation(syncable::PASSWORDS, + root_node, tag)); + node_id = password_node.GetId(); + } + EXPECT_CALL(observer_, OnPassphraseAccepted(_)); + EXPECT_CALL(observer_, OnEncryptionComplete(_)); + sync_manager_.SetPassphrase("new_passphrase", true); + { + ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); + ReadNode password_node(&trans); + EXPECT_FALSE(password_node.InitByClientTagLookup(syncable::PASSWORDS, + tag)); + } + { + ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); + ReadNode password_node(&trans); + EXPECT_FALSE(password_node.InitByIdLookup(node_id)); + } +} + +} // namespace + +} // namespace browser_sync diff --git a/chrome/browser/sync/internal_api/user_share.cc b/chrome/browser/sync/internal_api/user_share.cc new file mode 100644 index 0000000..3cb70a0 --- /dev/null +++ b/chrome/browser/sync/internal_api/user_share.cc @@ -0,0 +1,15 @@ +// 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/internal_api/user_share.h" + +#include "chrome/browser/sync/syncable/directory_manager.h" + +namespace sync_api { + +UserShare::UserShare() {} + +UserShare::~UserShare() {} + +} diff --git a/chrome/browser/sync/internal_api/user_share.h b/chrome/browser/sync/internal_api/user_share.h new file mode 100644 index 0000000..edc0932 --- /dev/null +++ b/chrome/browser/sync/internal_api/user_share.h @@ -0,0 +1,37 @@ +// 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_INTERNAL_API_USER_SHARE_H_ +#define CHROME_BROWSER_SYNC_INTERNAL_API_USER_SHARE_H_ +#pragma once + +#include <string> + +#include "base/memory/scoped_ptr.h" + +namespace syncable { +class DirectoryManager; +} + +namespace sync_api { + +// A UserShare encapsulates the syncable pieces that represent an authenticated +// user and their data (share). +// This encompasses all pieces required to build transaction objects on the +// syncable share. +struct UserShare { + UserShare(); + ~UserShare(); + + // The DirectoryManager itself, which is the parent of Transactions and can + // be shared across multiple threads (unlike Directory). + scoped_ptr<syncable::DirectoryManager> dir_manager; + + // The username of the sync user. + std::string name; +}; + +} + +#endif // CHROME_BROWSER_SYNC_INTERNAL_API_USER_SHARE_H_ diff --git a/chrome/browser/sync/internal_api/write_node.cc b/chrome/browser/sync/internal_api/write_node.cc new file mode 100644 index 0000000..875d644 --- /dev/null +++ b/chrome/browser/sync/internal_api/write_node.cc @@ -0,0 +1,538 @@ +// 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/internal_api/write_node.h" + +#include "base/json/json_writer.h" +#include "base/utf_string_conversions.h" +#include "base/values.h" +#include "chrome/browser/sync/engine/nigori_util.h" +#include "chrome/browser/sync/engine/syncapi_internal.h" +#include "chrome/browser/sync/internal_api/base_transaction.h" +#include "chrome/browser/sync/internal_api/write_transaction.h" +#include "chrome/browser/sync/protocol/app_specifics.pb.h" +#include "chrome/browser/sync/protocol/autofill_specifics.pb.h" +#include "chrome/browser/sync/protocol/bookmark_specifics.pb.h" +#include "chrome/browser/sync/protocol/extension_specifics.pb.h" +#include "chrome/browser/sync/protocol/password_specifics.pb.h" +#include "chrome/browser/sync/protocol/session_specifics.pb.h" +#include "chrome/browser/sync/protocol/theme_specifics.pb.h" +#include "chrome/browser/sync/protocol/typed_url_specifics.pb.h" +#include "chrome/browser/sync/syncable/syncable.h" +#include "chrome/browser/sync/util/cryptographer.h" + +using browser_sync::Cryptographer; +using std::string; +using std::vector; +using syncable::kEncryptedString; +using syncable::SPECIFICS; + +namespace sync_api { + +static const char kDefaultNameForNewNodes[] = " "; + +////////////////////////////////////////////////////////////////////////// +// Static helper functions. + +// When taking a name from the syncapi, append a space if it matches the +// pattern of a server-illegal name followed by zero or more spaces. +static void SyncAPINameToServerName(const std::wstring& sync_api_name, + std::string* out) { + *out = WideToUTF8(sync_api_name); + if (IsNameServerIllegalAfterTrimming(*out)) + out->append(" "); +} + +bool WriteNode::UpdateEntryWithEncryption( + browser_sync::Cryptographer* cryptographer, + const sync_pb::EntitySpecifics& new_specifics, + syncable::MutableEntry* entry) { + syncable::ModelType type = syncable::GetModelTypeFromSpecifics(new_specifics); + DCHECK_GE(type, syncable::FIRST_REAL_MODEL_TYPE); + syncable::ModelTypeSet encrypted_types = cryptographer->GetEncryptedTypes(); + + sync_pb::EntitySpecifics generated_specifics; + if (type == syncable::PASSWORDS || // Has own encryption scheme. + type == syncable::NIGORI || // Encrypted separately. + encrypted_types.count(type) == 0 || + new_specifics.has_encrypted()) { + // No encryption required. + generated_specifics.CopyFrom(new_specifics); + } else { + // Encrypt new_specifics into generated_specifics. + if (VLOG_IS_ON(2)) { + scoped_ptr<DictionaryValue> value(entry->ToValue()); + std::string info; + base::JSONWriter::Write(value.get(), true, &info); + VLOG(2) << "Encrypting specifics of type " + << syncable::ModelTypeToString(type) + << " with content: " + << info; + } + if (!cryptographer->is_initialized()) + return false; + syncable::AddDefaultExtensionValue(type, &generated_specifics); + if (!cryptographer->Encrypt(new_specifics, + generated_specifics.mutable_encrypted())) { + NOTREACHED() << "Could not encrypt data for node of type " + << syncable::ModelTypeToString(type); + return false; + } + } + + const sync_pb::EntitySpecifics& old_specifics = entry->Get(SPECIFICS); + if (AreSpecificsEqual(cryptographer, old_specifics, generated_specifics)) { + // Even if the data is the same but the old specifics are encrypted with an + // old key, we should go ahead and re-encrypt with the new key. + if ((!old_specifics.has_encrypted() && + !generated_specifics.has_encrypted()) || + cryptographer->CanDecryptUsingDefaultKey(old_specifics.encrypted())) { + VLOG(2) << "Specifics of type " << syncable::ModelTypeToString(type) + << " already match, dropping change."; + return true; + } + // TODO(zea): Add some way to keep track of how often we're reencrypting + // because of a passphrase change. + } + + if (generated_specifics.has_encrypted()) { + // Overwrite the possibly sensitive non-specifics data. + entry->Put(syncable::NON_UNIQUE_NAME, kEncryptedString); + // For bookmarks we actually put bogus data into the unencrypted specifics, + // else the server will try to do it for us. + if (type == syncable::BOOKMARKS) { + sync_pb::BookmarkSpecifics* bookmark_specifics = + generated_specifics.MutableExtension(sync_pb::bookmark); + if (!entry->Get(syncable::IS_DIR)) + bookmark_specifics->set_url(kEncryptedString); + bookmark_specifics->set_title(kEncryptedString); + } + } + entry->Put(syncable::SPECIFICS, generated_specifics); + syncable::MarkForSyncing(entry); + return true; +} + +void WriteNode::SetIsFolder(bool folder) { + if (entry_->Get(syncable::IS_DIR) == folder) + return; // Skip redundant changes. + + entry_->Put(syncable::IS_DIR, folder); + MarkForSyncing(); +} + +void WriteNode::SetTitle(const std::wstring& title) { + std::string server_legal_name; + SyncAPINameToServerName(title, &server_legal_name); + + string old_name = entry_->Get(syncable::NON_UNIQUE_NAME); + + if (server_legal_name == old_name) + return; // Skip redundant changes. + + // Only set NON_UNIQUE_NAME to the title if we're not encrypted. + if (GetEntitySpecifics().has_encrypted()) + entry_->Put(syncable::NON_UNIQUE_NAME, kEncryptedString); + else + entry_->Put(syncable::NON_UNIQUE_NAME, server_legal_name); + + // For bookmarks, we also set the title field in the specifics. + // TODO(zea): refactor bookmarks to not need this functionality. + if (GetModelType() == syncable::BOOKMARKS) { + sync_pb::BookmarkSpecifics new_value = GetBookmarkSpecifics(); + new_value.set_title(server_legal_name); + SetBookmarkSpecifics(new_value); // Does it's own encryption checking. + } + + MarkForSyncing(); +} + +void WriteNode::SetURL(const GURL& url) { + sync_pb::BookmarkSpecifics new_value = GetBookmarkSpecifics(); + new_value.set_url(url.spec()); + SetBookmarkSpecifics(new_value); +} + +void WriteNode::SetAppSpecifics( + const sync_pb::AppSpecifics& new_value) { + sync_pb::EntitySpecifics entity_specifics; + entity_specifics.MutableExtension(sync_pb::app)->CopyFrom(new_value); + SetEntitySpecifics(entity_specifics); +} + +void WriteNode::SetAutofillSpecifics( + const sync_pb::AutofillSpecifics& new_value) { + sync_pb::EntitySpecifics entity_specifics; + entity_specifics.MutableExtension(sync_pb::autofill)->CopyFrom(new_value); + SetEntitySpecifics(entity_specifics); +} + +void WriteNode::SetAutofillProfileSpecifics( + const sync_pb::AutofillProfileSpecifics& new_value) { + sync_pb::EntitySpecifics entity_specifics; + entity_specifics.MutableExtension(sync_pb::autofill_profile)-> + CopyFrom(new_value); + SetEntitySpecifics(entity_specifics); +} + +void WriteNode::SetBookmarkSpecifics( + const sync_pb::BookmarkSpecifics& new_value) { + sync_pb::EntitySpecifics entity_specifics; + entity_specifics.MutableExtension(sync_pb::bookmark)->CopyFrom(new_value); + SetEntitySpecifics(entity_specifics); +} + +void WriteNode::SetNigoriSpecifics( + const sync_pb::NigoriSpecifics& new_value) { + sync_pb::EntitySpecifics entity_specifics; + entity_specifics.MutableExtension(sync_pb::nigori)->CopyFrom(new_value); + SetEntitySpecifics(entity_specifics); +} + +void WriteNode::SetPasswordSpecifics( + const sync_pb::PasswordSpecificsData& data) { + DCHECK_EQ(syncable::PASSWORDS, GetModelType()); + + Cryptographer* cryptographer = GetTransaction()->GetCryptographer(); + + // Idempotency check to prevent unnecessary syncing: if the plaintexts match + // and the old ciphertext is encrypted with the most current key, there's + // nothing to do here. Because each encryption is seeded with a different + // random value, checking for equivalence post-encryption doesn't suffice. + const sync_pb::EncryptedData& old_ciphertext = + GetEntry()->Get(SPECIFICS).GetExtension(sync_pb::password).encrypted(); + scoped_ptr<sync_pb::PasswordSpecificsData> old_plaintext( + DecryptPasswordSpecifics(GetEntry()->Get(SPECIFICS), cryptographer)); + if (old_plaintext.get() && + old_plaintext->SerializeAsString() == data.SerializeAsString() && + cryptographer->CanDecryptUsingDefaultKey(old_ciphertext)) { + return; + } + + sync_pb::PasswordSpecifics new_value; + if (!cryptographer->Encrypt(data, new_value.mutable_encrypted())) { + NOTREACHED() << "Failed to encrypt password, possibly due to sync node " + << "corruption"; + return; + } + + sync_pb::EntitySpecifics entity_specifics; + entity_specifics.MutableExtension(sync_pb::password)->CopyFrom(new_value); + SetEntitySpecifics(entity_specifics); +} + +void WriteNode::SetThemeSpecifics( + const sync_pb::ThemeSpecifics& new_value) { + sync_pb::EntitySpecifics entity_specifics; + entity_specifics.MutableExtension(sync_pb::theme)->CopyFrom(new_value); + SetEntitySpecifics(entity_specifics); +} + +void WriteNode::SetSessionSpecifics( + const sync_pb::SessionSpecifics& new_value) { + sync_pb::EntitySpecifics entity_specifics; + entity_specifics.MutableExtension(sync_pb::session)->CopyFrom(new_value); + SetEntitySpecifics(entity_specifics); +} + +void WriteNode::SetEntitySpecifics( + const sync_pb::EntitySpecifics& new_value) { + syncable::ModelType new_specifics_type = + syncable::GetModelTypeFromSpecifics(new_value); + DCHECK_NE(new_specifics_type, syncable::UNSPECIFIED); + VLOG(1) << "Writing entity specifics of type " + << syncable::ModelTypeToString(new_specifics_type); + // GetModelType() can be unspecified if this is the first time this + // node is being initialized (see PutModelType()). Otherwise, it + // should match |new_specifics_type|. + if (GetModelType() != syncable::UNSPECIFIED) { + DCHECK_EQ(new_specifics_type, GetModelType()); + } + browser_sync::Cryptographer* cryptographer = + GetTransaction()->GetCryptographer(); + + // Preserve unknown fields. + const sync_pb::EntitySpecifics& old_specifics = entry_->Get(SPECIFICS); + sync_pb::EntitySpecifics new_specifics; + new_specifics.CopyFrom(new_value); + new_specifics.mutable_unknown_fields()->MergeFrom( + old_specifics.unknown_fields()); + + // Will update the entry if encryption was necessary. + if (!UpdateEntryWithEncryption(cryptographer, new_specifics, entry_)) { + return; + } + if (entry_->Get(SPECIFICS).has_encrypted()) { + // EncryptIfNecessary already updated the entry for us and marked for + // syncing if it was needed. Now we just make a copy of the unencrypted + // specifics so that if this node is updated, we do not have to decrypt the + // old data. Note that this only modifies the node's local data, not the + // entry itself. + SetUnencryptedSpecifics(new_value); + } + + DCHECK_EQ(new_specifics_type, GetModelType()); +} + +void WriteNode::ResetFromSpecifics() { + SetEntitySpecifics(GetEntitySpecifics()); +} + +void WriteNode::SetTypedUrlSpecifics( + const sync_pb::TypedUrlSpecifics& new_value) { + sync_pb::EntitySpecifics entity_specifics; + entity_specifics.MutableExtension(sync_pb::typed_url)->CopyFrom(new_value); + SetEntitySpecifics(entity_specifics); +} + +void WriteNode::SetExtensionSpecifics( + const sync_pb::ExtensionSpecifics& new_value) { + sync_pb::EntitySpecifics entity_specifics; + entity_specifics.MutableExtension(sync_pb::extension)->CopyFrom(new_value); + SetEntitySpecifics(entity_specifics); +} + +void WriteNode::SetExternalId(int64 id) { + if (GetExternalId() != id) + entry_->Put(syncable::LOCAL_EXTERNAL_ID, id); +} + +WriteNode::WriteNode(WriteTransaction* transaction) + : entry_(NULL), transaction_(transaction) { + DCHECK(transaction); +} + +WriteNode::~WriteNode() { + delete entry_; +} + +// Find an existing node matching the ID |id|, and bind this WriteNode to it. +// Return true on success. +bool WriteNode::InitByIdLookup(int64 id) { + DCHECK(!entry_) << "Init called twice"; + DCHECK_NE(id, kInvalidId); + entry_ = new syncable::MutableEntry(transaction_->GetWrappedWriteTrans(), + syncable::GET_BY_HANDLE, id); + return (entry_->good() && !entry_->Get(syncable::IS_DEL) && + DecryptIfNecessary()); +} + +// Find a node by client tag, and bind this WriteNode to it. +// Return true if the write node was found, and was not deleted. +// Undeleting a deleted node is possible by ClientTag. +bool WriteNode::InitByClientTagLookup(syncable::ModelType model_type, + const std::string& tag) { + DCHECK(!entry_) << "Init called twice"; + if (tag.empty()) + return false; + + const std::string hash = GenerateSyncableHash(model_type, tag); + + entry_ = new syncable::MutableEntry(transaction_->GetWrappedWriteTrans(), + syncable::GET_BY_CLIENT_TAG, hash); + return (entry_->good() && !entry_->Get(syncable::IS_DEL) && + DecryptIfNecessary()); +} + +bool WriteNode::InitByTagLookup(const std::string& tag) { + DCHECK(!entry_) << "Init called twice"; + if (tag.empty()) + return false; + entry_ = new syncable::MutableEntry(transaction_->GetWrappedWriteTrans(), + syncable::GET_BY_SERVER_TAG, tag); + if (!entry_->good()) + return false; + if (entry_->Get(syncable::IS_DEL)) + return false; + syncable::ModelType model_type = GetModelType(); + DCHECK_EQ(syncable::NIGORI, model_type); + return true; +} + +void WriteNode::PutModelType(syncable::ModelType model_type) { + // Set an empty specifics of the appropriate datatype. The presence + // of the specific extension will identify the model type. + DCHECK(GetModelType() == model_type || + GetModelType() == syncable::UNSPECIFIED); // Immutable once set. + + sync_pb::EntitySpecifics specifics; + syncable::AddDefaultExtensionValue(model_type, &specifics); + SetEntitySpecifics(specifics); +} + +// Create a new node with default properties, and bind this WriteNode to it. +// Return true on success. +bool WriteNode::InitByCreation(syncable::ModelType model_type, + const BaseNode& parent, + const BaseNode* predecessor) { + DCHECK(!entry_) << "Init called twice"; + // |predecessor| must be a child of |parent| or NULL. + if (predecessor && predecessor->GetParentId() != parent.GetId()) { + DCHECK(false); + return false; + } + + syncable::Id parent_id = parent.GetEntry()->Get(syncable::ID); + + // Start out with a dummy name. We expect + // the caller to set a meaningful name after creation. + string dummy(kDefaultNameForNewNodes); + + entry_ = new syncable::MutableEntry(transaction_->GetWrappedWriteTrans(), + syncable::CREATE, parent_id, dummy); + + if (!entry_->good()) + return false; + + // Entries are untitled folders by default. + entry_->Put(syncable::IS_DIR, true); + + PutModelType(model_type); + + // Now set the predecessor, which sets IS_UNSYNCED as necessary. + PutPredecessor(predecessor); + + return true; +} + +// Create a new node with default properties and a client defined unique tag, +// and bind this WriteNode to it. +// Return true on success. If the tag exists in the database, then +// we will attempt to undelete the node. +// TODO(chron): Code datatype into hash tag. +// TODO(chron): Is model type ever lost? +bool WriteNode::InitUniqueByCreation(syncable::ModelType model_type, + const BaseNode& parent, + const std::string& tag) { + DCHECK(!entry_) << "Init called twice"; + + const std::string hash = GenerateSyncableHash(model_type, tag); + + syncable::Id parent_id = parent.GetEntry()->Get(syncable::ID); + + // Start out with a dummy name. We expect + // the caller to set a meaningful name after creation. + string dummy(kDefaultNameForNewNodes); + + // Check if we have this locally and need to undelete it. + scoped_ptr<syncable::MutableEntry> existing_entry( + new syncable::MutableEntry(transaction_->GetWrappedWriteTrans(), + syncable::GET_BY_CLIENT_TAG, hash)); + + if (existing_entry->good()) { + if (existing_entry->Get(syncable::IS_DEL)) { + // Rules for undelete: + // BASE_VERSION: Must keep the same. + // ID: Essential to keep the same. + // META_HANDLE: Must be the same, so we can't "split" the entry. + // IS_DEL: Must be set to false, will cause reindexing. + // This one is weird because IS_DEL is true for "update only" + // items. It should be OK to undelete an update only. + // MTIME/CTIME: Seems reasonable to just leave them alone. + // IS_UNSYNCED: Must set this to true or face database insurrection. + // We do this below this block. + // IS_UNAPPLIED_UPDATE: Either keep it the same or also set BASE_VERSION + // to SERVER_VERSION. We keep it the same here. + // IS_DIR: We'll leave it the same. + // SPECIFICS: Reset it. + + existing_entry->Put(syncable::IS_DEL, false); + + // Client tags are immutable and must be paired with the ID. + // If a server update comes down with an ID and client tag combo, + // and it already exists, always overwrite it and store only one copy. + // We have to undelete entries because we can't disassociate IDs from + // tags and updates. + + existing_entry->Put(syncable::NON_UNIQUE_NAME, dummy); + existing_entry->Put(syncable::PARENT_ID, parent_id); + entry_ = existing_entry.release(); + } else { + return false; + } + } else { + entry_ = new syncable::MutableEntry(transaction_->GetWrappedWriteTrans(), + syncable::CREATE, parent_id, dummy); + if (!entry_->good()) { + return false; + } + + // Only set IS_DIR for new entries. Don't bitflip undeleted ones. + entry_->Put(syncable::UNIQUE_CLIENT_TAG, hash); + } + + // We don't support directory and tag combinations. + entry_->Put(syncable::IS_DIR, false); + + // Will clear specifics data. + PutModelType(model_type); + + // Now set the predecessor, which sets IS_UNSYNCED as necessary. + PutPredecessor(NULL); + + return true; +} + +bool WriteNode::SetPosition(const BaseNode& new_parent, + const BaseNode* predecessor) { + // |predecessor| must be a child of |new_parent| or NULL. + if (predecessor && predecessor->GetParentId() != new_parent.GetId()) { + DCHECK(false); + return false; + } + + syncable::Id new_parent_id = new_parent.GetEntry()->Get(syncable::ID); + + // Filter out redundant changes if both the parent and the predecessor match. + if (new_parent_id == entry_->Get(syncable::PARENT_ID)) { + const syncable::Id& old = entry_->Get(syncable::PREV_ID); + if ((!predecessor && old.IsRoot()) || + (predecessor && (old == predecessor->GetEntry()->Get(syncable::ID)))) { + return true; + } + } + + // Atomically change the parent. This will fail if it would + // introduce a cycle in the hierarchy. + if (!entry_->Put(syncable::PARENT_ID, new_parent_id)) + return false; + + // Now set the predecessor, which sets IS_UNSYNCED as necessary. + PutPredecessor(predecessor); + + return true; +} + +const syncable::Entry* WriteNode::GetEntry() const { + return entry_; +} + +const BaseTransaction* WriteNode::GetTransaction() const { + return transaction_; +} + +void WriteNode::Remove() { + entry_->Put(syncable::IS_DEL, true); + MarkForSyncing(); +} + +void WriteNode::PutPredecessor(const BaseNode* predecessor) { + syncable::Id predecessor_id = predecessor ? + predecessor->GetEntry()->Get(syncable::ID) : syncable::Id(); + entry_->PutPredecessor(predecessor_id); + // Mark this entry as unsynced, to wake up the syncer. + MarkForSyncing(); +} + +void WriteNode::SetFaviconBytes(const vector<unsigned char>& bytes) { + sync_pb::BookmarkSpecifics new_value = GetBookmarkSpecifics(); + new_value.set_favicon(bytes.empty() ? NULL : &bytes[0], bytes.size()); + SetBookmarkSpecifics(new_value); +} + +void WriteNode::MarkForSyncing() { + syncable::MarkForSyncing(entry_); +} + +} // namespace sync_api diff --git a/chrome/browser/sync/internal_api/write_node.h b/chrome/browser/sync/internal_api/write_node.h new file mode 100644 index 0000000..75e4f21 --- /dev/null +++ b/chrome/browser/sync/internal_api/write_node.h @@ -0,0 +1,193 @@ +// 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_INTERNAL_API_WRITE_NODE_H_ +#define CHROME_BROWSER_SYNC_INTERNAL_API_WRITE_NODE_H_ +#pragma once + +#include <string> +#include <vector> + +#include "base/basictypes.h" +#include "chrome/browser/sync/internal_api/base_node.h" +#include "chrome/browser/sync/syncable/model_type.h" + +namespace browser_sync { +class Cryptographer; +} + +namespace syncable { +class Entry; +class MutableEntry; +} + +namespace sync_pb { +class AppSpecifics; +class AutofillSpecifics; +class AutofillProfileSpecifics; +class BookmarkSpecifics; +class EntitySpecifics; +class ExtensionSpecifics; +class SessionSpecifics; +class NigoriSpecifics; +class PreferenceSpecifics; +class PasswordSpecificsData; +class ThemeSpecifics; +class TypedUrlSpecifics; +} + +namespace sync_api { + +class WriteTransaction; + +// WriteNode extends BaseNode to add mutation, and wraps +// syncable::MutableEntry. A WriteTransaction is needed to create a WriteNode. +class WriteNode : public BaseNode { + public: + // Create a WriteNode using the given transaction. + explicit WriteNode(WriteTransaction* transaction); + virtual ~WriteNode(); + + // A client must use one (and only one) of the following Init variants to + // populate the node. + + // BaseNode implementation. + virtual bool InitByIdLookup(int64 id); + virtual bool InitByClientTagLookup(syncable::ModelType model_type, + const std::string& tag); + + // Create a new node with the specified parent and predecessor. |model_type| + // dictates the type of the item, and controls which EntitySpecifics proto + // extension can be used with this item. Use a NULL |predecessor| + // to indicate that this is to be the first child. + // |predecessor| must be a child of |new_parent| or NULL. Returns false on + // failure. + bool InitByCreation(syncable::ModelType model_type, + const BaseNode& parent, + const BaseNode* predecessor); + + // Create nodes using this function if they're unique items that + // you want to fetch using client_tag. Note that the behavior of these + // items is slightly different than that of normal items. + // Most importantly, if it exists locally, this function will + // actually undelete it + // Client unique tagged nodes must NOT be folders. + bool InitUniqueByCreation(syncable::ModelType model_type, + const BaseNode& parent, + const std::string& client_tag); + + // Each server-created permanent node is tagged with a unique string. + // Look up the node with the particular tag. If it does not exist, + // return false. + bool InitByTagLookup(const std::string& tag); + + // These Set() functions correspond to the Get() functions of BaseNode. + void SetIsFolder(bool folder); + void SetTitle(const std::wstring& title); + + // External ID is a client-only field, so setting it doesn't cause the item to + // be synced again. + void SetExternalId(int64 external_id); + + // Remove this node and its children. + void Remove(); + + // Set a new parent and position. Position is specified by |predecessor|; if + // it is NULL, the node is moved to the first position. |predecessor| must + // be a child of |new_parent| or NULL. Returns false on failure.. + bool SetPosition(const BaseNode& new_parent, const BaseNode* predecessor); + + // Set the bookmark specifics (url and favicon). + // Should only be called if GetModelType() == BOOKMARK. + void SetBookmarkSpecifics(const sync_pb::BookmarkSpecifics& specifics); + + // Legacy, bookmark-specific setters that wrap SetBookmarkSpecifics() above. + // Should only be called if GetModelType() == BOOKMARK. + // TODO(ncarter): Remove these two datatype-specific accessors. + void SetURL(const GURL& url); + void SetFaviconBytes(const std::vector<unsigned char>& bytes); + + // Generic set specifics method. Will extract the model type from |specifics|. + void SetEntitySpecifics(const sync_pb::EntitySpecifics& specifics); + + // Resets the EntitySpecifics for this node based on the unencrypted data. + // Will encrypt if necessary. + void ResetFromSpecifics(); + + // TODO(sync): Remove the setters below when the corresponding data + // types are ported to the new sync service API. + + // Set the app specifics (id, update url, enabled state, etc). + // Should only be called if GetModelType() == APPS. + void SetAppSpecifics(const sync_pb::AppSpecifics& specifics); + + // Set the autofill specifics (name and value). + // Should only be called if GetModelType() == AUTOFILL. + void SetAutofillSpecifics(const sync_pb::AutofillSpecifics& specifics); + + void SetAutofillProfileSpecifics( + const sync_pb::AutofillProfileSpecifics& specifics); + + // Set the nigori specifics. + // Should only be called if GetModelType() == NIGORI. + void SetNigoriSpecifics(const sync_pb::NigoriSpecifics& specifics); + + // Set the password specifics. + // Should only be called if GetModelType() == PASSWORD. + void SetPasswordSpecifics(const sync_pb::PasswordSpecificsData& specifics); + + // Set the theme specifics (name and value). + // Should only be called if GetModelType() == THEME. + void SetThemeSpecifics(const sync_pb::ThemeSpecifics& specifics); + + // Set the typed_url specifics (url, title, typed_count, etc). + // Should only be called if GetModelType() == TYPED_URLS. + void SetTypedUrlSpecifics(const sync_pb::TypedUrlSpecifics& specifics); + + // Set the extension specifics (id, update url, enabled state, etc). + // Should only be called if GetModelType() == EXTENSIONS. + void SetExtensionSpecifics(const sync_pb::ExtensionSpecifics& specifics); + + // Set the session specifics (windows, tabs, navigations etc.). + // Should only be called if GetModelType() == SESSIONS. + void SetSessionSpecifics(const sync_pb::SessionSpecifics& specifics); + + // Stores |new_specifics| into |entry|, encrypting if necessary. + // Returns false if an error encrypting occurred (does not modify |entry|). + // Note: gracefully handles new_specifics aliasing with entry->Get(SPECIFICS). + static bool UpdateEntryWithEncryption( + browser_sync::Cryptographer* cryptographer, + const sync_pb::EntitySpecifics& new_specifics, + syncable::MutableEntry* entry); + + // Implementation of BaseNode's abstract virtual accessors. + virtual const syncable::Entry* GetEntry() const; + + virtual const BaseTransaction* GetTransaction() const; + + private: + void* operator new(size_t size); // Node is meant for stack use only. + + // Helper to set model type. This will clear any specifics data. + void PutModelType(syncable::ModelType model_type); + + // Helper to set the previous node. + void PutPredecessor(const BaseNode* predecessor); + + // Sets IS_UNSYNCED and SYNCING to ensure this entry is considered in an + // upcoming commit pass. + void MarkForSyncing(); + + // The underlying syncable object which this class wraps. + syncable::MutableEntry* entry_; + + // The sync API transaction that is the parent of this node. + WriteTransaction* transaction_; + + DISALLOW_COPY_AND_ASSIGN(WriteNode); +}; + +} // namespace sync_api + +#endif // CHROME_BROWSER_SYNC_INTERNAL_API_WRITE_NODE_H_ diff --git a/chrome/browser/sync/internal_api/write_transaction.cc b/chrome/browser/sync/internal_api/write_transaction.cc new file mode 100644 index 0000000..1bed02b --- /dev/null +++ b/chrome/browser/sync/internal_api/write_transaction.cc @@ -0,0 +1,29 @@ +// 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/internal_api/write_transaction.h" + +#include "chrome/browser/sync/syncable/syncable.h" + +namespace sync_api { + +////////////////////////////////////////////////////////////////////////// +// WriteTransaction member definitions +WriteTransaction::WriteTransaction(const tracked_objects::Location& from_here, + UserShare* share) + : BaseTransaction(share), + transaction_(NULL) { + transaction_ = new syncable::WriteTransaction(from_here, syncable::SYNCAPI, + GetLookup()); +} + +WriteTransaction::~WriteTransaction() { + delete transaction_; +} + +syncable::BaseTransaction* WriteTransaction::GetWrappedTrans() const { + return transaction_; +} + +} // namespace sync_api diff --git a/chrome/browser/sync/internal_api/write_transaction.h b/chrome/browser/sync/internal_api/write_transaction.h new file mode 100644 index 0000000..e90abc7 --- /dev/null +++ b/chrome/browser/sync/internal_api/write_transaction.h @@ -0,0 +1,56 @@ +// 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_INTERNAL_API_WRITE_TRANSACTION_H_ +#define CHROME_BROWSER_SYNC_INTERNAL_API_WRITE_TRANSACTION_H_ + +#include "base/basictypes.h" +#include "chrome/browser/sync/internal_api/base_transaction.h" + +namespace syncable { +class BaseTransaction; +class WriteTransaction; +} // namespace syncable + +namespace tracked_objects { +class Location; +} // namespace tracked_objects + +namespace sync_api { + +// Sync API's WriteTransaction is a read/write BaseTransaction. It wraps +// a syncable::WriteTransaction. +// +// NOTE: Only a single model type can be mutated for a given +// WriteTransaction. +class WriteTransaction : public BaseTransaction { + public: + // Start a new read/write transaction. + WriteTransaction(const tracked_objects::Location& from_here, + UserShare* share); + virtual ~WriteTransaction(); + + // Provide access to the syncable.h transaction from the API WriteNode. + virtual syncable::BaseTransaction* GetWrappedTrans() const; + syncable::WriteTransaction* GetWrappedWriteTrans() { return transaction_; } + + protected: + WriteTransaction() {} + + void SetTransaction(syncable::WriteTransaction* trans) { + transaction_ = trans; + } + + private: + void* operator new(size_t size); // Transaction is meant for stack use only. + + // The underlying syncable object which this class wraps. + syncable::WriteTransaction* transaction_; + + DISALLOW_COPY_AND_ASSIGN(WriteTransaction); +}; + +} // namespace sync_api + +#endif // CHROME_BROWSER_SYNC_INTERNAL_API_WRITE_TRANSACTION_H_ |
