chromeos: Fix StartupBrowserCreatorImpl::Launch crash.
[chromium-blink-merge.git] / sync / internal_api / base_node.cc
blobfc0dfb216e46ca2e7cf29adbabf2f1a2c970fd55
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "sync/internal_api/public/base_node.h"
7 #include "base/base64.h"
8 #include "base/sha1.h"
9 #include "base/string_number_conversions.h"
10 #include "base/utf_string_conversions.h"
11 #include "base/values.h"
12 #include "sync/internal_api/public/base_transaction.h"
13 #include "sync/internal_api/syncapi_internal.h"
14 #include "sync/protocol/app_specifics.pb.h"
15 #include "sync/protocol/autofill_specifics.pb.h"
16 #include "sync/protocol/bookmark_specifics.pb.h"
17 #include "sync/protocol/extension_specifics.pb.h"
18 #include "sync/protocol/nigori_specifics.pb.h"
19 #include "sync/protocol/password_specifics.pb.h"
20 #include "sync/protocol/session_specifics.pb.h"
21 #include "sync/protocol/theme_specifics.pb.h"
22 #include "sync/protocol/typed_url_specifics.pb.h"
23 #include "sync/syncable/directory.h"
24 #include "sync/syncable/entry.h"
25 #include "sync/syncable/syncable_id.h"
26 #include "sync/util/time.h"
28 using sync_pb::AutofillProfileSpecifics;
30 namespace syncer {
32 using syncable::SPECIFICS;
34 // Helper function to look up the int64 metahandle of an object given the ID
35 // string.
36 static int64 IdToMetahandle(syncable::BaseTransaction* trans,
37 const syncable::Id& id) {
38 syncable::Entry entry(trans, syncable::GET_BY_ID, id);
39 if (!entry.good())
40 return kInvalidId;
41 return entry.Get(syncable::META_HANDLE);
44 static bool EndsWithSpace(const std::string& string) {
45 return !string.empty() && *string.rbegin() == ' ';
48 // In the reverse direction, if a server name matches the pattern of a
49 // server-illegal name followed by one or more spaces, remove the trailing
50 // space.
51 static void ServerNameToSyncAPIName(const std::string& server_name,
52 std::string* out) {
53 CHECK(out);
54 int length_to_copy = server_name.length();
55 if (IsNameServerIllegalAfterTrimming(server_name) &&
56 EndsWithSpace(server_name)) {
57 --length_to_copy;
59 *out = std::string(server_name.c_str(), length_to_copy);
62 BaseNode::BaseNode() : password_data_(new sync_pb::PasswordSpecificsData) {}
64 BaseNode::~BaseNode() {}
66 std::string BaseNode::GenerateSyncableHash(
67 syncer::ModelType model_type, const std::string& client_tag) {
68 // Blank PB with just the field in it has termination symbol,
69 // handy for delimiter.
70 sync_pb::EntitySpecifics serialized_type;
71 syncer::AddDefaultFieldValue(model_type, &serialized_type);
72 std::string hash_input;
73 serialized_type.AppendToString(&hash_input);
74 hash_input.append(client_tag);
76 std::string encode_output;
77 CHECK(base::Base64Encode(base::SHA1HashString(hash_input), &encode_output));
78 return encode_output;
81 bool BaseNode::DecryptIfNecessary() {
82 if (!GetEntry()->Get(syncable::UNIQUE_SERVER_TAG).empty())
83 return true; // Ignore unique folders.
84 const sync_pb::EntitySpecifics& specifics =
85 GetEntry()->Get(syncable::SPECIFICS);
86 if (specifics.has_password()) {
87 // Passwords have their own legacy encryption structure.
88 scoped_ptr<sync_pb::PasswordSpecificsData> data(DecryptPasswordSpecifics(
89 specifics, GetTransaction()->GetCryptographer()));
90 if (!data.get()) {
91 LOG(ERROR) << "Failed to decrypt password specifics.";
92 return false;
94 password_data_.swap(data);
95 return true;
98 // We assume any node with the encrypted field set has encrypted data and if
99 // not we have no work to do, with the exception of bookmarks. For bookmarks
100 // we must make sure the bookmarks data has the title field supplied. If not,
101 // we fill the unencrypted_data_ with a copy of the bookmark specifics that
102 // follows the new bookmarks format.
103 if (!specifics.has_encrypted()) {
104 if (GetModelType() == syncer::BOOKMARKS &&
105 !specifics.bookmark().has_title() &&
106 !GetTitle().empty()) { // Last check ensures this isn't a new node.
107 // We need to fill in the title.
108 std::string title = GetTitle();
109 std::string server_legal_title;
110 SyncAPINameToServerName(title, &server_legal_title);
111 DVLOG(1) << "Reading from legacy bookmark, manually returning title "
112 << title;
113 unencrypted_data_.CopyFrom(specifics);
114 unencrypted_data_.mutable_bookmark()->set_title(
115 server_legal_title);
117 return true;
120 const sync_pb::EncryptedData& encrypted = specifics.encrypted();
121 std::string plaintext_data = GetTransaction()->GetCryptographer()->
122 DecryptToString(encrypted);
123 if (plaintext_data.length() == 0) {
124 LOG(ERROR) << "Failed to decrypt encrypted node of type " <<
125 syncer::ModelTypeToString(GetModelType()) << ".";
126 // Debugging for crbug.com/123223. We failed to decrypt the data, which
127 // means we applied an update without having the key or lost the key at a
128 // later point.
129 CHECK(false);
130 return false;
131 } else if (!unencrypted_data_.ParseFromString(plaintext_data)) {
132 // Debugging for crbug.com/123223. We should never succeed in decrypting
133 // but fail to parse into a protobuf.
134 CHECK(false);
135 return false;
137 DVLOG(2) << "Decrypted specifics of type "
138 << syncer::ModelTypeToString(GetModelType())
139 << " with content: " << plaintext_data;
140 return true;
143 const sync_pb::EntitySpecifics& BaseNode::GetUnencryptedSpecifics(
144 const syncable::Entry* entry) const {
145 const sync_pb::EntitySpecifics& specifics = entry->Get(SPECIFICS);
146 if (specifics.has_encrypted()) {
147 DCHECK_NE(syncer::GetModelTypeFromSpecifics(unencrypted_data_),
148 syncer::UNSPECIFIED);
149 return unencrypted_data_;
150 } else {
151 // Due to the change in bookmarks format, we need to check to see if this is
152 // a legacy bookmarks (and has no title field in the proto). If it is, we
153 // return the unencrypted_data_, which was filled in with the title by
154 // DecryptIfNecessary().
155 if (GetModelType() == syncer::BOOKMARKS) {
156 const sync_pb::BookmarkSpecifics& bookmark_specifics =
157 specifics.bookmark();
158 if (bookmark_specifics.has_title() ||
159 GetTitle().empty() || // For the empty node case
160 !GetEntry()->Get(syncable::UNIQUE_SERVER_TAG).empty()) {
161 // It's possible we previously had to convert and set
162 // |unencrypted_data_| but then wrote our own data, so we allow
163 // |unencrypted_data_| to be non-empty.
164 return specifics;
165 } else {
166 DCHECK_EQ(syncer::GetModelTypeFromSpecifics(unencrypted_data_),
167 syncer::BOOKMARKS);
168 return unencrypted_data_;
170 } else {
171 DCHECK_EQ(syncer::GetModelTypeFromSpecifics(unencrypted_data_),
172 syncer::UNSPECIFIED);
173 return specifics;
178 int64 BaseNode::GetParentId() const {
179 return IdToMetahandle(GetTransaction()->GetWrappedTrans(),
180 GetEntry()->Get(syncable::PARENT_ID));
183 int64 BaseNode::GetId() const {
184 return GetEntry()->Get(syncable::META_HANDLE);
187 const base::Time& BaseNode::GetModificationTime() const {
188 return GetEntry()->Get(syncable::MTIME);
191 bool BaseNode::GetIsFolder() const {
192 return GetEntry()->Get(syncable::IS_DIR);
195 std::string BaseNode::GetTitle() const {
196 std::string result;
197 // TODO(zea): refactor bookmarks to not need this functionality.
198 if (syncer::BOOKMARKS == GetModelType() &&
199 GetEntry()->Get(syncable::SPECIFICS).has_encrypted()) {
200 // Special case for legacy bookmarks dealing with encryption.
201 ServerNameToSyncAPIName(GetBookmarkSpecifics().title(), &result);
202 } else {
203 ServerNameToSyncAPIName(GetEntry()->Get(syncable::NON_UNIQUE_NAME),
204 &result);
206 return result;
209 GURL BaseNode::GetURL() const {
210 return GURL(GetBookmarkSpecifics().url());
213 bool BaseNode::HasChildren() const {
214 syncable::Directory* dir = GetTransaction()->GetDirectory();
215 syncable::BaseTransaction* trans = GetTransaction()->GetWrappedTrans();
216 return dir->HasChildren(trans, GetEntry()->Get(syncable::ID));
219 int64 BaseNode::GetPredecessorId() const {
220 syncable::Id id_string = GetEntry()->Get(syncable::PREV_ID);
221 if (id_string.IsRoot())
222 return kInvalidId;
223 return IdToMetahandle(GetTransaction()->GetWrappedTrans(), id_string);
226 int64 BaseNode::GetSuccessorId() const {
227 syncable::Id id_string = GetEntry()->Get(syncable::NEXT_ID);
228 if (id_string.IsRoot())
229 return kInvalidId;
230 return IdToMetahandle(GetTransaction()->GetWrappedTrans(), id_string);
233 int64 BaseNode::GetFirstChildId() const {
234 syncable::Directory* dir = GetTransaction()->GetDirectory();
235 syncable::BaseTransaction* trans = GetTransaction()->GetWrappedTrans();
236 syncable::Id id_string;
237 // TODO(akalin): Propagate up the error further (see
238 // http://crbug.com/100907).
239 CHECK(dir->GetFirstChildId(trans,
240 GetEntry()->Get(syncable::ID), &id_string));
241 if (id_string.IsRoot())
242 return kInvalidId;
243 return IdToMetahandle(GetTransaction()->GetWrappedTrans(), id_string);
246 DictionaryValue* BaseNode::GetSummaryAsValue() const {
247 DictionaryValue* node_info = new DictionaryValue();
248 node_info->SetString("id", base::Int64ToString(GetId()));
249 node_info->SetBoolean("isFolder", GetIsFolder());
250 node_info->SetString("title", GetTitle());
251 node_info->Set("type", ModelTypeToValue(GetModelType()));
252 return node_info;
255 DictionaryValue* BaseNode::GetDetailsAsValue() const {
256 DictionaryValue* node_info = GetSummaryAsValue();
257 node_info->SetString(
258 "modificationTime",
259 syncer::GetTimeDebugString(GetModificationTime()));
260 node_info->SetString("parentId", base::Int64ToString(GetParentId()));
261 // Specifics are already in the Entry value, so no need to duplicate
262 // it here.
263 node_info->SetString("externalId",
264 base::Int64ToString(GetExternalId()));
265 node_info->SetString("predecessorId",
266 base::Int64ToString(GetPredecessorId()));
267 node_info->SetString("successorId",
268 base::Int64ToString(GetSuccessorId()));
269 node_info->SetString("firstChildId",
270 base::Int64ToString(GetFirstChildId()));
271 node_info->Set("entry", GetEntry()->ToValue());
272 return node_info;
275 void BaseNode::GetFaviconBytes(std::vector<unsigned char>* output) const {
276 if (!output)
277 return;
278 const std::string& favicon = GetBookmarkSpecifics().favicon();
279 output->assign(reinterpret_cast<const unsigned char*>(favicon.data()),
280 reinterpret_cast<const unsigned char*>(favicon.data() +
281 favicon.length()));
284 int64 BaseNode::GetExternalId() const {
285 return GetEntry()->Get(syncable::LOCAL_EXTERNAL_ID);
288 const sync_pb::AppSpecifics& BaseNode::GetAppSpecifics() const {
289 DCHECK_EQ(syncer::APPS, GetModelType());
290 return GetEntitySpecifics().app();
293 const sync_pb::AutofillSpecifics& BaseNode::GetAutofillSpecifics() const {
294 DCHECK_EQ(syncer::AUTOFILL, GetModelType());
295 return GetEntitySpecifics().autofill();
298 const AutofillProfileSpecifics& BaseNode::GetAutofillProfileSpecifics() const {
299 DCHECK_EQ(GetModelType(), syncer::AUTOFILL_PROFILE);
300 return GetEntitySpecifics().autofill_profile();
303 const sync_pb::BookmarkSpecifics& BaseNode::GetBookmarkSpecifics() const {
304 DCHECK_EQ(syncer::BOOKMARKS, GetModelType());
305 return GetEntitySpecifics().bookmark();
308 const sync_pb::NigoriSpecifics& BaseNode::GetNigoriSpecifics() const {
309 DCHECK_EQ(syncer::NIGORI, GetModelType());
310 return GetEntitySpecifics().nigori();
313 const sync_pb::PasswordSpecificsData& BaseNode::GetPasswordSpecifics() const {
314 DCHECK_EQ(syncer::PASSWORDS, GetModelType());
315 return *password_data_;
318 const sync_pb::ThemeSpecifics& BaseNode::GetThemeSpecifics() const {
319 DCHECK_EQ(syncer::THEMES, GetModelType());
320 return GetEntitySpecifics().theme();
323 const sync_pb::TypedUrlSpecifics& BaseNode::GetTypedUrlSpecifics() const {
324 DCHECK_EQ(syncer::TYPED_URLS, GetModelType());
325 return GetEntitySpecifics().typed_url();
328 const sync_pb::ExtensionSpecifics& BaseNode::GetExtensionSpecifics() const {
329 DCHECK_EQ(syncer::EXTENSIONS, GetModelType());
330 return GetEntitySpecifics().extension();
333 const sync_pb::SessionSpecifics& BaseNode::GetSessionSpecifics() const {
334 DCHECK_EQ(syncer::SESSIONS, GetModelType());
335 return GetEntitySpecifics().session();
338 const sync_pb::EntitySpecifics& BaseNode::GetEntitySpecifics() const {
339 return GetUnencryptedSpecifics(GetEntry());
342 syncer::ModelType BaseNode::GetModelType() const {
343 return GetEntry()->GetModelType();
346 void BaseNode::SetUnencryptedSpecifics(
347 const sync_pb::EntitySpecifics& specifics) {
348 syncer::ModelType type = syncer::GetModelTypeFromSpecifics(specifics);
349 DCHECK_NE(syncer::UNSPECIFIED, type);
350 if (GetModelType() != syncer::UNSPECIFIED) {
351 DCHECK_EQ(GetModelType(), type);
353 unencrypted_data_.CopyFrom(specifics);
356 } // namespace syncer