blob: 3d80bac15393224b99b70f1931d2d9b8411d9751 [file] [log] [blame]
Max Boguefef332d2016-07-28 22:09:091// Copyright 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.
4
5#include "components/sync/engine_impl/syncer_util.h"
6
Max Boguefef332d2016-07-28 22:09:097#include <algorithm>
Max Boguefef332d2016-07-28 22:09:098
9#include "base/base64.h"
10#include "base/location.h"
11#include "base/metrics/histogram.h"
12#include "base/rand_util.h"
13#include "base/strings/string_number_conversions.h"
14#include "components/sync/base/attachment_id_proto.h"
15#include "components/sync/base/cryptographer.h"
maxbogue2b0bb912016-11-17 20:07:1716#include "components/sync/base/hash_util.h"
Max Boguefef332d2016-07-28 22:09:0917#include "components/sync/base/model_type.h"
18#include "components/sync/base/time.h"
19#include "components/sync/base/unique_position.h"
20#include "components/sync/engine_impl/conflict_resolver.h"
21#include "components/sync/engine_impl/syncer_proto_util.h"
Max Boguefef332d2016-07-28 22:09:0922#include "components/sync/protocol/bookmark_specifics.pb.h"
23#include "components/sync/protocol/password_specifics.pb.h"
24#include "components/sync/protocol/sync.pb.h"
25#include "components/sync/syncable/directory.h"
26#include "components/sync/syncable/entry.h"
27#include "components/sync/syncable/model_neutral_mutable_entry.h"
Max Boguefef332d2016-07-28 22:09:0928#include "components/sync/syncable/syncable_changes_version.h"
29#include "components/sync/syncable/syncable_model_neutral_write_transaction.h"
30#include "components/sync/syncable/syncable_proto_util.h"
31#include "components/sync/syncable/syncable_read_transaction.h"
32#include "components/sync/syncable/syncable_util.h"
33#include "components/sync/syncable/syncable_write_transaction.h"
34
35namespace syncer {
36
37using syncable::CHANGES_VERSION;
38using syncable::Directory;
39using syncable::Entry;
40using syncable::GET_BY_HANDLE;
41using syncable::GET_BY_ID;
42using syncable::ID;
43using syncable::Id;
44
45syncable::Id FindLocalIdToUpdate(syncable::BaseTransaction* trans,
46 const sync_pb::SyncEntity& update) {
47 // Expected entry points of this function:
48 // SyncEntity has NOT been applied to SERVER fields.
49 // SyncEntity has NOT been applied to LOCAL fields.
50 // DB has not yet been modified, no entries created for this update.
51
52 const std::string& client_id = trans->directory()->cache_guid();
53 const syncable::Id& update_id = SyncableIdFromProto(update.id_string());
54
55 if (update.has_client_defined_unique_tag() &&
56 !update.client_defined_unique_tag().empty()) {
57 // When a server sends down a client tag, the following cases can occur:
58 // 1) Client has entry for tag already, ID is server style, matches
59 // 2) Client has entry for tag already, ID is server, doesn't match.
60 // 3) Client has entry for tag already, ID is local, (never matches)
61 // 4) Client has no entry for tag
62
63 // Case 1, we don't have to do anything since the update will
64 // work just fine. Update will end up in the proper entry, via ID lookup.
65 // Case 2 - Happens very rarely due to lax enforcement of client tags
66 // on the server, if two clients commit the same tag at the same time.
67 // When this happens, we pick the lexically-least ID and ignore all other
68 // items.
69 // Case 3 - We need to replace the local ID with the server ID so that
70 // this update gets targeted at the correct local entry; we expect conflict
71 // resolution to occur.
72 // Case 4 - Perfect. Same as case 1.
73
74 syncable::Entry local_entry(trans, syncable::GET_BY_CLIENT_TAG,
75 update.client_defined_unique_tag());
76
77 // The SyncAPI equivalent of this function will return !good if IS_DEL.
78 // The syncable version will return good even if IS_DEL.
79 // TODO(chron): Unit test the case with IS_DEL and make sure.
80 if (local_entry.good()) {
81 if (local_entry.GetId().ServerKnows()) {
82 if (local_entry.GetId() != update_id) {
83 // Case 2.
84 LOG(WARNING) << "Duplicated client tag.";
85 if (local_entry.GetId() < update_id) {
86 // Signal an error; drop this update on the floor. Note that
87 // we don't server delete the item, because we don't allow it to
88 // exist locally at all. So the item will remain orphaned on
89 // the server, and we won't pay attention to it.
90 return syncable::Id();
91 }
92 }
93 // Target this change to the existing local entry; later,
94 // we'll change the ID of the local entry to update_id
95 // if needed.
96 return local_entry.GetId();
97 } else {
98 // Case 3: We have a local entry with the same client tag.
99 // We should change the ID of the local entry to the server entry.
100 // This will result in an server ID with base version == 0, but that's
101 // a legal state for an item with a client tag. By changing the ID,
102 // update will now be applied to local_entry.
103 DCHECK(0 == local_entry.GetBaseVersion() ||
104 CHANGES_VERSION == local_entry.GetBaseVersion());
105 return local_entry.GetId();
106 }
107 }
108 } else if (update.has_originator_cache_guid() &&
109 update.originator_cache_guid() == client_id) {
110 // If a commit succeeds, but the response does not come back fast enough
111 // then the syncer might assume that it was never committed.
112 // The server will track the client that sent up the original commit and
113 // return this in a get updates response. When this matches a local
114 // uncommitted item, we must mutate our local item and version to pick up
115 // the committed version of the same item whose commit response was lost.
116 // There is however still a race condition if the server has not
117 // completed the commit by the time the syncer tries to get updates
118 // again. To mitigate this, we need to have the server time out in
119 // a reasonable span, our commit batches have to be small enough
120 // to process within our HTTP response "assumed alive" time.
121
122 // We need to check if we have an entry that didn't get its server
123 // id updated correctly. The server sends down a client ID
124 // and a local (negative) id. If we have a entry by that
125 // description, we should update the ID and version to the
126 // server side ones to avoid multiple copies of the same thing.
127
128 syncable::Id client_item_id = syncable::Id::CreateFromClientString(
129 update.originator_client_item_id());
130 DCHECK(!client_item_id.ServerKnows());
131 syncable::Entry local_entry(trans, GET_BY_ID, client_item_id);
132
133 // If it exists, then our local client lost a commit response. Use
134 // the local entry.
135 if (local_entry.good() && !local_entry.GetIsDel()) {
136 int64_t old_version = local_entry.GetBaseVersion();
137 int64_t new_version = update.version();
138 DCHECK_LE(old_version, 0);
139 DCHECK_GT(new_version, 0);
140 // Otherwise setting the base version could cause a consistency failure.
141 // An entry should never be version 0 and SYNCED.
142 DCHECK(local_entry.GetIsUnsynced());
143
144 // Just a quick sanity check.
145 DCHECK(!local_entry.GetId().ServerKnows());
146
147 DVLOG(1) << "Reuniting lost commit response IDs. server id: " << update_id
148 << " local id: " << local_entry.GetId()
149 << " new version: " << new_version;
150
151 return local_entry.GetId();
152 }
153 } else if (update.has_server_defined_unique_tag() &&
154 !update.server_defined_unique_tag().empty()) {
155 // The client creates type root folders with a local ID on demand when a
156 // progress marker for the given type is initially set.
157 // The server might also attempt to send a type root folder for the same
158 // type (during the transition period until support for root folders is
159 // removed for new client versions).
160 // TODO(stanisc): crbug.com/438313: remove this once the transition to
161 // implicit root folders on the server is done.
162 syncable::Entry local_entry(trans, syncable::GET_BY_SERVER_TAG,
163 update.server_defined_unique_tag());
164 if (local_entry.good() && !local_entry.GetId().ServerKnows()) {
165 DCHECK(local_entry.GetId() != update_id);
166 return local_entry.GetId();
167 }
168 }
169
170 // Fallback: target an entry having the server ID, creating one if needed.
171 return update_id;
172}
173
174UpdateAttemptResponse AttemptToUpdateEntry(
175 syncable::WriteTransaction* const trans,
176 syncable::MutableEntry* const entry,
177 Cryptographer* cryptographer) {
178 CHECK(entry->good());
179 if (!entry->GetIsUnappliedUpdate())
180 return SUCCESS; // No work to do.
181 syncable::Id id = entry->GetId();
182 const sync_pb::EntitySpecifics& specifics = entry->GetServerSpecifics();
183 ModelType type = GetModelTypeFromSpecifics(specifics);
184
185 // Only apply updates that we can decrypt. If we can't decrypt the update, it
186 // is likely because the passphrase has not arrived yet. Because the
187 // passphrase may not arrive within this GetUpdates, we can't just return
188 // conflict, else we try to perform normal conflict resolution prematurely or
189 // the syncer may get stuck. As such, we return CONFLICT_ENCRYPTION, which is
190 // treated as an unresolvable conflict. See the description in syncer_types.h.
191 // This prevents any unsynced changes from commiting and postpones conflict
192 // resolution until all data can be decrypted.
193 if (specifics.has_encrypted() &&
194 !cryptographer->CanDecrypt(specifics.encrypted())) {
195 // We can't decrypt this node yet.
196 DVLOG(1) << "Received an undecryptable "
197 << ModelTypeToString(entry->GetServerModelType())
198 << " update, returning conflict_encryption.";
199 return CONFLICT_ENCRYPTION;
200 } else if (specifics.has_password() && entry->GetUniqueServerTag().empty()) {
201 // Passwords use their own legacy encryption scheme.
202 const sync_pb::PasswordSpecifics& password = specifics.password();
203 if (!cryptographer->CanDecrypt(password.encrypted())) {
204 DVLOG(1) << "Received an undecryptable password update, returning "
205 << "conflict_encryption.";
206 return CONFLICT_ENCRYPTION;
207 }
208 }
209
210 if (!entry->GetServerIsDel()) {
211 syncable::Id new_parent = entry->GetServerParentId();
212 if (!new_parent.IsNull()) {
213 // Perform this step only if the parent is specified.
214 // The unset parent means that the implicit type root would be used.
215 Entry parent(trans, GET_BY_ID, new_parent);
216 // A note on non-directory parents:
217 // We catch most unfixable tree invariant errors at update receipt time,
218 // however we deal with this case here because we may receive the child
219 // first then the illegal parent. Instead of dealing with it twice in
220 // different ways we deal with it once here to reduce the amount of code
221 // and potential errors.
222 if (!parent.good() || parent.GetIsDel() || !parent.GetIsDir()) {
223 DVLOG(1) << "Entry has bad parent, returning conflict_hierarchy.";
224 return CONFLICT_HIERARCHY;
225 }
226 if (entry->GetParentId() != new_parent) {
227 if (!entry->GetIsDel() && !IsLegalNewParent(trans, id, new_parent)) {
228 DVLOG(1) << "Not updating item " << id
229 << ", illegal new parent (would cause loop).";
230 return CONFLICT_HIERARCHY;
231 }
232 }
233 } else {
234 // new_parent is unset.
235 DCHECK(IsTypeWithClientGeneratedRoot(type));
236 }
237 } else if (entry->GetIsDir()) {
238 Directory::Metahandles handles;
239 trans->directory()->GetChildHandlesById(trans, id, &handles);
240 if (!handles.empty()) {
241 // If we have still-existing children, then we need to deal with
242 // them before we can process this change.
243 DVLOG(1) << "Not deleting directory; it's not empty " << *entry;
244 return CONFLICT_HIERARCHY;
245 }
246 }
247
248 if (entry->GetIsUnsynced()) {
249 DVLOG(1) << "Skipping update, returning conflict for: " << id
250 << " ; it's unsynced.";
251 return CONFLICT_SIMPLE;
252 }
253
254 if (specifics.has_encrypted()) {
255 DVLOG(2) << "Received a decryptable "
256 << ModelTypeToString(entry->GetServerModelType())
257 << " update, applying normally.";
258 } else {
259 DVLOG(2) << "Received an unencrypted "
260 << ModelTypeToString(entry->GetServerModelType())
261 << " update, applying normally.";
262 }
263
264 UpdateLocalDataFromServerData(trans, entry);
265
266 return SUCCESS;
267}
268
269std::string GetUniqueBookmarkTagFromUpdate(const sync_pb::SyncEntity& update) {
270 if (!update.has_originator_cache_guid() ||
271 !update.has_originator_client_item_id()) {
272 LOG(ERROR) << "Update is missing requirements for bookmark position."
273 << " This is a server bug.";
274 return UniquePosition::RandomSuffix();
275 }
276
maxbogue2b0bb912016-11-17 20:07:17277 return GenerateSyncableBookmarkHash(update.originator_cache_guid(),
278 update.originator_client_item_id());
Max Boguefef332d2016-07-28 22:09:09279}
280
281UniquePosition GetUpdatePosition(const sync_pb::SyncEntity& update,
282 const std::string& suffix) {
283 DCHECK(UniquePosition::IsValidSuffix(suffix));
284 if (!(SyncerProtoUtil::ShouldMaintainPosition(update))) {
285 return UniquePosition::CreateInvalid();
286 } else if (update.has_unique_position()) {
287 UniquePosition proto_position =
288 UniquePosition::FromProto(update.unique_position());
289 if (proto_position.IsValid()) {
290 return proto_position;
291 }
292 }
293
294 // Now, there are two cases hit here.
295 // 1. Did not receive unique_position for this update.
296 // 2. Received unique_position, but it is invalid(ex. empty).
297 // And we will create a valid position for this two cases.
298 if (update.has_position_in_parent()) {
299 return UniquePosition::FromInt64(update.position_in_parent(), suffix);
300 } else {
301 LOG(ERROR) << "No position information in update. This is a server bug.";
302 return UniquePosition::FromInt64(0, suffix);
303 }
304}
305
306namespace {
307
308// Helper to synthesize a new-style sync_pb::EntitySpecifics for use locally,
309// when the server speaks only the old sync_pb::SyncEntity_BookmarkData-based
310// protocol.
311void UpdateBookmarkSpecifics(const std::string& singleton_tag,
312 const std::string& url,
313 const std::string& favicon_bytes,
314 syncable::ModelNeutralMutableEntry* local_entry) {
315 // In the new-style protocol, the server no longer sends bookmark info for
316 // the "google_chrome" folder. Mimic that here.
317 if (singleton_tag == "google_chrome")
318 return;
319 sync_pb::EntitySpecifics pb;
320 sync_pb::BookmarkSpecifics* bookmark = pb.mutable_bookmark();
321 if (!url.empty())
322 bookmark->set_url(url);
323 if (!favicon_bytes.empty())
324 bookmark->set_favicon(favicon_bytes);
325 local_entry->PutServerSpecifics(pb);
326}
327
328void UpdateBookmarkPositioning(
329 const sync_pb::SyncEntity& update,
330 syncable::ModelNeutralMutableEntry* local_entry) {
331 // Update our unique bookmark tag. In many cases this will be identical to
332 // the tag we already have. However, clients that have recently upgraded to
333 // versions that support unique positions will have incorrect tags. See the
334 // v86 migration logic in directory_backing_store.cc for more information.
335 //
336 // Both the old and new values are unique to this element. Applying this
337 // update will not risk the creation of conflicting unique tags.
338 std::string bookmark_tag = GetUniqueBookmarkTagFromUpdate(update);
339 if (UniquePosition::IsValidSuffix(bookmark_tag)) {
340 local_entry->PutUniqueBookmarkTag(bookmark_tag);
341 }
342
343 // Update our position.
344 UniquePosition update_pos =
345 GetUpdatePosition(update, local_entry->GetUniqueBookmarkTag());
346 if (update_pos.IsValid()) {
347 local_entry->PutServerUniquePosition(update_pos);
348 }
349}
350
351} // namespace
352
353void UpdateServerFieldsFromUpdate(syncable::ModelNeutralMutableEntry* target,
354 const sync_pb::SyncEntity& update,
355 const std::string& name) {
356 if (update.deleted()) {
357 if (target->GetServerIsDel()) {
358 // If we already think the item is server-deleted, we're done.
359 // Skipping these cases prevents our committed deletions from coming
360 // back and overriding subsequent undeletions. For non-deleted items,
361 // the version number check has a similar effect.
362 return;
363 }
364 // Mark entry as unapplied update first to ensure journaling the deletion.
365 target->PutIsUnappliedUpdate(true);
366 // The server returns very lightweight replies for deletions, so we don't
367 // clobber a bunch of fields on delete.
368 target->PutServerIsDel(true);
369 if (!target->GetUniqueClientTag().empty()) {
370 // Items identified by the client unique tag are undeletable; when
371 // they're deleted, they go back to version 0.
372 target->PutServerVersion(0);
373 } else {
374 // Otherwise, fake a server version by bumping the local number.
375 target->PutServerVersion(
376 std::max(target->GetServerVersion(), target->GetBaseVersion()) + 1);
377 }
378 return;
379 }
380
381 DCHECK_EQ(target->GetId(), SyncableIdFromProto(update.id_string()))
382 << "ID Changing not supported here";
383 if (SyncerProtoUtil::ShouldMaintainHierarchy(update)) {
384 target->PutServerParentId(SyncableIdFromProto(update.parent_id_string()));
385 } else {
386 target->PutServerParentId(syncable::Id());
387 }
388 target->PutServerNonUniqueName(name);
389 target->PutServerVersion(update.version());
390 target->PutServerCtime(ProtoTimeToTime(update.ctime()));
391 target->PutServerMtime(ProtoTimeToTime(update.mtime()));
392 target->PutServerIsDir(IsFolder(update));
393 if (update.has_server_defined_unique_tag()) {
394 const std::string& tag = update.server_defined_unique_tag();
395 target->PutUniqueServerTag(tag);
396 }
397 if (update.has_client_defined_unique_tag()) {
398 const std::string& tag = update.client_defined_unique_tag();
399 target->PutUniqueClientTag(tag);
400 }
401 // Store the datatype-specific part as a protobuf.
402 if (update.has_specifics()) {
403 DCHECK_NE(GetModelType(update), UNSPECIFIED)
404 << "Storing unrecognized datatype in sync database.";
405 target->PutServerSpecifics(update.specifics());
406 } else if (update.has_bookmarkdata()) {
407 // Legacy protocol response for bookmark data.
408 const sync_pb::SyncEntity::BookmarkData& bookmark = update.bookmarkdata();
409 UpdateBookmarkSpecifics(update.server_defined_unique_tag(),
410 bookmark.bookmark_url(),
411 bookmark.bookmark_favicon(), target);
412 }
413 target->PutServerAttachmentMetadata(
414 CreateAttachmentMetadata(update.attachment_id()));
415 if (SyncerProtoUtil::ShouldMaintainPosition(update)) {
416 UpdateBookmarkPositioning(update, target);
417 }
418
419 // We only mark the entry as unapplied if its version is greater than the
420 // local data. If we're processing the update that corresponds to one of our
421 // commit we don't apply it as time differences may occur.
422 if (update.version() > target->GetBaseVersion()) {
423 target->PutIsUnappliedUpdate(true);
424 }
425 DCHECK(!update.deleted());
426 target->PutServerIsDel(false);
427}
428
429// Creates a new Entry iff no Entry exists with the given id.
430void CreateNewEntry(syncable::ModelNeutralWriteTransaction* trans,
431 const syncable::Id& id) {
432 syncable::Entry entry(trans, GET_BY_ID, id);
433 if (!entry.good()) {
434 syncable::ModelNeutralMutableEntry new_entry(
435 trans, syncable::CREATE_NEW_UPDATE_ITEM, id);
436 }
437}
438
439// This function is called on an entry when we can update the user-facing data
440// from the server data.
441void UpdateLocalDataFromServerData(syncable::WriteTransaction* trans,
442 syncable::MutableEntry* entry) {
443 DCHECK(!entry->GetIsUnsynced());
444 DCHECK(entry->GetIsUnappliedUpdate());
445
446 DVLOG(2) << "Updating entry : " << *entry;
447 // Start by setting the properties that determine the model_type.
448 entry->PutSpecifics(entry->GetServerSpecifics());
449 // Clear the previous server specifics now that we're applying successfully.
450 entry->PutBaseServerSpecifics(sync_pb::EntitySpecifics());
451 entry->PutIsDir(entry->GetServerIsDir());
452 // This strange dance around the IS_DEL flag avoids problems when setting
453 // the name.
454 // TODO(chron): Is this still an issue? Unit test this codepath.
455 if (entry->GetServerIsDel()) {
456 entry->PutIsDel(true);
457 } else {
458 entry->PutNonUniqueName(entry->GetServerNonUniqueName());
459 entry->PutParentId(entry->GetServerParentId());
460 entry->PutUniquePosition(entry->GetServerUniquePosition());
461 entry->PutIsDel(false);
462 }
463
464 entry->PutCtime(entry->GetServerCtime());
465 entry->PutMtime(entry->GetServerMtime());
466 entry->PutBaseVersion(entry->GetServerVersion());
467 entry->PutIsDel(entry->GetServerIsDel());
468 entry->PutIsUnappliedUpdate(false);
469 entry->PutAttachmentMetadata(entry->GetServerAttachmentMetadata());
470}
471
472VerifyCommitResult ValidateCommitEntry(syncable::Entry* entry) {
473 syncable::Id id = entry->GetId();
474 if (id == entry->GetParentId()) {
475 CHECK(id.IsRoot()) << "Non-root item is self parenting." << *entry;
476 // If the root becomes unsynced it can cause us problems.
477 LOG(ERROR) << "Root item became unsynced " << *entry;
478 return VERIFY_UNSYNCABLE;
479 }
480 if (entry->IsRoot()) {
481 LOG(ERROR) << "Permanent item became unsynced " << *entry;
482 return VERIFY_UNSYNCABLE;
483 }
484 if (entry->GetIsDel() && !entry->GetId().ServerKnows()) {
485 // Drop deleted uncommitted entries.
486 return VERIFY_UNSYNCABLE;
487 }
488 return VERIFY_OK;
489}
490
491void MarkDeletedChildrenSynced(syncable::Directory* dir,
492 syncable::BaseWriteTransaction* trans,
493 std::set<syncable::Id>* deleted_folders) {
494 // There's two options here.
495 // 1. Scan deleted unsynced entries looking up their pre-delete tree for any
496 // of the deleted folders.
497 // 2. Take each folder and do a tree walk of all entries underneath it.
498 // #2 has a lower big O cost, but writing code to limit the time spent inside
499 // the transaction during each step is simpler with 1. Changing this decision
500 // may be sensible if this code shows up in profiling.
501 if (deleted_folders->empty())
502 return;
503 Directory::Metahandles handles;
504 dir->GetUnsyncedMetaHandles(trans, &handles);
505 if (handles.empty())
506 return;
507 Directory::Metahandles::iterator it;
508 for (it = handles.begin(); it != handles.end(); ++it) {
509 syncable::ModelNeutralMutableEntry entry(trans, GET_BY_HANDLE, *it);
510 if (!entry.GetIsUnsynced() || !entry.GetIsDel())
511 continue;
512 syncable::Id id = entry.GetParentId();
513 while (id != trans->root_id()) {
514 if (deleted_folders->find(id) != deleted_folders->end()) {
515 // We've synced the deletion of this deleted entries parent.
516 entry.PutIsUnsynced(false);
517 break;
518 }
519 Entry parent(trans, GET_BY_ID, id);
520 if (!parent.good() || !parent.GetIsDel())
521 break;
522 id = parent.GetParentId();
523 }
524 }
525}
526
527VerifyResult VerifyNewEntry(const sync_pb::SyncEntity& update,
528 syncable::Entry* target,
529 const bool deleted) {
530 if (target->good()) {
531 // Not a new update.
532 return VERIFY_UNDECIDED;
533 }
534 if (deleted) {
535 // Deletion of an item we've never seen can be ignored.
536 return VERIFY_SKIP;
537 }
538
539 return VERIFY_SUCCESS;
540}
541
542// Assumes we have an existing entry; check here for updates that break
543// consistency rules.
544VerifyResult VerifyUpdateConsistency(
545 syncable::ModelNeutralWriteTransaction* trans,
546 const sync_pb::SyncEntity& update,
547 const bool deleted,
548 const bool is_directory,
549 ModelType model_type,
550 syncable::ModelNeutralMutableEntry* target) {
551 CHECK(target->good());
552 const syncable::Id& update_id = SyncableIdFromProto(update.id_string());
553
554 // If the update is a delete, we don't really need to worry at this stage.
555 if (deleted)
556 return VERIFY_SUCCESS;
557
558 if (model_type == UNSPECIFIED) {
559 // This update is to an item of a datatype we don't recognize. The server
560 // shouldn't have sent it to us. Throw it on the ground.
561 return VERIFY_SKIP;
562 }
563
564 if (target->GetServerVersion() > 0) {
565 // Then we've had an update for this entry before.
566 if (is_directory != target->GetServerIsDir() ||
567 model_type != target->GetServerModelType()) {
568 if (target->GetIsDel()) { // If we've deleted the item, we don't care.
569 return VERIFY_SKIP;
570 } else {
571 LOG(ERROR) << "Server update doesn't agree with previous updates. ";
572 LOG(ERROR) << " Entry: " << *target;
573 LOG(ERROR) << " Update: "
574 << SyncerProtoUtil::SyncEntityDebugString(update);
575 return VERIFY_FAIL;
576 }
577 }
578
579 if (!deleted && (target->GetId() == update_id) &&
580 (target->GetServerIsDel() ||
581 (!target->GetIsUnsynced() && target->GetIsDel() &&
582 target->GetBaseVersion() > 0))) {
583 // An undelete. The latter case in the above condition is for
584 // when the server does not give us an update following the
585 // commit of a delete, before undeleting.
586 // Undeletion is common for items that reuse the client-unique tag.
587 VerifyResult result = VerifyUndelete(trans, update, target);
588 if (VERIFY_UNDECIDED != result)
589 return result;
590 }
591 }
592 if (target->GetBaseVersion() > 0) {
593 // We've committed this update in the past.
594 if (is_directory != target->GetIsDir() ||
595 model_type != target->GetModelType()) {
596 LOG(ERROR) << "Server update doesn't agree with committed item. ";
597 LOG(ERROR) << " Entry: " << *target;
598 LOG(ERROR) << " Update: "
599 << SyncerProtoUtil::SyncEntityDebugString(update);
600 return VERIFY_FAIL;
601 }
602 if (target->GetId() == update_id) {
603 if (target->GetServerVersion() > update.version()) {
604 LOG(WARNING) << "We've already seen a more recent version.";
605 LOG(WARNING) << " Entry: " << *target;
606 LOG(WARNING) << " Update: "
607 << SyncerProtoUtil::SyncEntityDebugString(update);
608 return VERIFY_SKIP;
609 }
610 }
611 }
612 return VERIFY_SUCCESS;
613}
614
615// Assumes we have an existing entry; verify an update that seems to be
616// expressing an 'undelete'
617VerifyResult VerifyUndelete(syncable::ModelNeutralWriteTransaction* trans,
618 const sync_pb::SyncEntity& update,
619 syncable::ModelNeutralMutableEntry* target) {
620 // TODO(nick): We hit this path for items deleted items that the server
621 // tells us to re-create; only deleted items with positive base versions
622 // will hit this path. However, it's not clear how such an undeletion
623 // would actually succeed on the server; in the protocol, a base
624 // version of 0 is required to undelete an object. This codepath
625 // should be deprecated in favor of client-tag style undeletion
626 // (where items go to version 0 when they're deleted), or else
627 // removed entirely (if this type of undeletion is indeed impossible).
628 CHECK(target->good());
629 DVLOG(1) << "Server update is attempting undelete. " << *target
630 << "Update:" << SyncerProtoUtil::SyncEntityDebugString(update);
631 // Move the old one aside and start over. It's too tricky to get the old one
632 // back into a state that would pass CheckTreeInvariants().
633 if (target->GetIsDel()) {
634 if (target->GetUniqueClientTag().empty())
635 LOG(WARNING) << "Doing move-aside undeletion on client-tagged item.";
636 target->PutId(trans->directory()->NextId());
637 target->PutUniqueClientTag(std::string());
638 target->PutBaseVersion(CHANGES_VERSION);
639 target->PutServerVersion(0);
640 return VERIFY_SUCCESS;
641 }
642 if (update.version() < target->GetServerVersion()) {
643 LOG(WARNING) << "Update older than current server version for " << *target
644 << " Update:"
645 << SyncerProtoUtil::SyncEntityDebugString(update);
646 return VERIFY_SUCCESS; // Expected in new sync protocol.
647 }
648 return VERIFY_UNDECIDED;
649}
650
651} // namespace syncer