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