Home | History | Annotate | Download | only in engine
      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/apply_control_data_updates.h"
      6 
      7 #include "base/metrics/histogram.h"
      8 #include "sync/engine/conflict_resolver.h"
      9 #include "sync/engine/conflict_util.h"
     10 #include "sync/engine/syncer_util.h"
     11 #include "sync/syncable/directory.h"
     12 #include "sync/syncable/mutable_entry.h"
     13 #include "sync/syncable/nigori_handler.h"
     14 #include "sync/syncable/nigori_util.h"
     15 #include "sync/syncable/syncable_write_transaction.h"
     16 #include "sync/util/cryptographer.h"
     17 
     18 namespace syncer {
     19 
     20 using syncable::GET_BY_SERVER_TAG;
     21 using syncable::IS_UNAPPLIED_UPDATE;
     22 using syncable::IS_UNSYNCED;
     23 using syncable::SERVER_SPECIFICS;
     24 using syncable::SPECIFICS;
     25 using syncable::SYNCER;
     26 
     27 void ApplyControlDataUpdates(sessions::SyncSession* session) {
     28   syncable::Directory* dir = session->context()->directory();
     29   syncable::WriteTransaction trans(FROM_HERE, SYNCER, dir);
     30 
     31   std::vector<int64> handles;
     32   dir->GetUnappliedUpdateMetaHandles(
     33       &trans, ToFullModelTypeSet(ControlTypes()), &handles);
     34 
     35   // First, go through and manually apply any new top level datatype nodes (so
     36   // that we don't have to worry about hitting a CONFLICT_HIERARCHY with an
     37   // entry because we haven't applied its parent yet).
     38   // TODO(sync): if at some point we support control datatypes with actual
     39   // hierarchies we'll need to revisit this logic.
     40   ModelTypeSet control_types = ControlTypes();
     41   for (ModelTypeSet::Iterator iter = control_types.First(); iter.Good();
     42        iter.Inc()) {
     43     syncable::MutableEntry entry(&trans,
     44                                  syncable::GET_BY_SERVER_TAG,
     45                                  ModelTypeToRootTag(iter.Get()));
     46     if (!entry.good())
     47       continue;
     48     if (!entry.Get(syncable::IS_UNAPPLIED_UPDATE))
     49       continue;
     50 
     51     ModelType type = entry.GetServerModelType();
     52     if (type == NIGORI) {
     53       // Nigori node applications never fail.
     54       ApplyNigoriUpdate(&trans,
     55                         &entry,
     56                         dir->GetCryptographer(&trans));
     57     } else {
     58       ApplyControlUpdate(&trans,
     59                          &entry,
     60                          dir->GetCryptographer(&trans));
     61     }
     62   }
     63 
     64   // Go through the rest of the unapplied control updates, skipping over any
     65   // top level folders.
     66   for (std::vector<int64>::const_iterator iter = handles.begin();
     67        iter != handles.end(); ++iter) {
     68     syncable::MutableEntry entry(&trans, syncable::GET_BY_HANDLE, *iter);
     69     CHECK(entry.good());
     70     ModelType type = entry.GetServerModelType();
     71     CHECK(ControlTypes().Has(type));
     72     if (!entry.Get(syncable::UNIQUE_SERVER_TAG).empty()) {
     73       // We should have already applied all top level control nodes.
     74       DCHECK(!entry.Get(syncable::IS_UNAPPLIED_UPDATE));
     75       continue;
     76     }
     77 
     78     ApplyControlUpdate(&trans,
     79                        &entry,
     80                        dir->GetCryptographer(&trans));
     81   }
     82 }
     83 
     84 // Update the nigori handler with the server's nigori node.
     85 //
     86 // If we have a locally modified nigori node, we merge them manually. This
     87 // handles the case where two clients both set a different passphrase. The
     88 // second client to attempt to commit will go into a state of having pending
     89 // keys, unioned the set of encrypted types, and eventually re-encrypt
     90 // everything with the passphrase of the first client and commit the set of
     91 // merged encryption keys. Until the second client provides the pending
     92 // passphrase, the cryptographer will preserve the encryption keys based on the
     93 // local passphrase, while the nigori node will preserve the server encryption
     94 // keys.
     95 void ApplyNigoriUpdate(syncable::WriteTransaction* const trans,
     96                        syncable::MutableEntry* const entry,
     97                        Cryptographer* cryptographer) {
     98   DCHECK(entry->Get(IS_UNAPPLIED_UPDATE));
     99 
    100   // We apply the nigori update regardless of whether there's a conflict or
    101   // not in order to preserve any new encrypted types or encryption keys.
    102   // TODO(zea): consider having this return a bool reflecting whether it was a
    103   // valid update or not, and in the case of invalid updates not overwrite the
    104   // local data.
    105   const sync_pb::NigoriSpecifics& nigori =
    106       entry->Get(SERVER_SPECIFICS).nigori();
    107   trans->directory()->GetNigoriHandler()->ApplyNigoriUpdate(nigori, trans);
    108 
    109   // Make sure any unsynced changes are properly encrypted as necessary.
    110   // We only perform this if the cryptographer is ready. If not, these are
    111   // re-encrypted at SetDecryptionPassphrase time (via ReEncryptEverything).
    112   // This logic covers the case where the nigori update marked new datatypes
    113   // for encryption, but didn't change the passphrase.
    114   if (cryptographer->is_ready()) {
    115     // Note that we don't bother to encrypt any data for which IS_UNSYNCED
    116     // == false here. The machine that turned on encryption should know about
    117     // and re-encrypt all synced data. It's possible it could get interrupted
    118     // during this process, but we currently reencrypt everything at startup
    119     // as well, so as soon as a client is restarted with this datatype marked
    120     // for encryption, all the data should be updated as necessary.
    121 
    122     // If this fails, something is wrong with the cryptographer, but there's
    123     // nothing we can do about it here.
    124     DVLOG(1) << "Received new nigori, encrypting unsynced changes.";
    125     syncable::ProcessUnsyncedChangesForEncryption(trans);
    126   }
    127 
    128   if (!entry->Get(IS_UNSYNCED)) {  // Update only.
    129     UpdateLocalDataFromServerData(trans, entry);
    130   } else {  // Conflict.
    131     const sync_pb::EntitySpecifics& server_specifics =
    132         entry->Get(SERVER_SPECIFICS);
    133     const sync_pb::NigoriSpecifics& server_nigori = server_specifics.nigori();
    134     const sync_pb::EntitySpecifics& local_specifics =
    135         entry->Get(SPECIFICS);
    136     const sync_pb::NigoriSpecifics& local_nigori = local_specifics.nigori();
    137 
    138     // We initialize the new nigori with the server state, and will override
    139     // it as necessary below.
    140     sync_pb::EntitySpecifics new_specifics = entry->Get(SERVER_SPECIFICS);
    141     sync_pb::NigoriSpecifics* new_nigori = new_specifics.mutable_nigori();
    142 
    143     // If the cryptographer is not ready, another client set a new encryption
    144     // passphrase. If we had migrated locally, we will re-migrate when the
    145     // pending keys are provided. If we had set a new custom passphrase locally
    146     // the user will have another chance to set a custom passphrase later
    147     // (assuming they hadn't set a custom passphrase on the other client).
    148     // Therefore, we only attempt to merge the nigori nodes if the cryptographer
    149     // is ready.
    150     // Note: we only update the encryption keybag if we're sure that we aren't
    151     // invalidating the keystore_decryptor_token (i.e. we're either
    152     // not migrated or we copying over all local state).
    153     if (cryptographer->is_ready()) {
    154       if (local_nigori.has_passphrase_type() &&
    155           server_nigori.has_passphrase_type()) {
    156         // They're both migrated, preserve the local nigori if the passphrase
    157         // type is more conservative.
    158         if (server_nigori.passphrase_type() ==
    159                 sync_pb::NigoriSpecifics::KEYSTORE_PASSPHRASE &&
    160             local_nigori.passphrase_type() !=
    161                 sync_pb::NigoriSpecifics::KEYSTORE_PASSPHRASE) {
    162           DCHECK(local_nigori.passphrase_type() ==
    163                      sync_pb::NigoriSpecifics::FROZEN_IMPLICIT_PASSPHRASE ||
    164                  local_nigori.passphrase_type() ==
    165                      sync_pb::NigoriSpecifics::CUSTOM_PASSPHRASE);
    166           new_nigori->CopyFrom(local_nigori);
    167           cryptographer->GetKeys(new_nigori->mutable_encryption_keybag());
    168         }
    169       } else if (!local_nigori.has_passphrase_type() &&
    170                  !server_nigori.has_passphrase_type()) {
    171         // Set the explicit passphrase based on the local state. If the server
    172         // had set an explict passphrase, we should have pending keys, so
    173         // should not reach this code.
    174         // Because neither side is migrated, we don't have to worry about the
    175         // keystore decryptor token.
    176         new_nigori->set_keybag_is_frozen(local_nigori.keybag_is_frozen());
    177         cryptographer->GetKeys(new_nigori->mutable_encryption_keybag());
    178       } else if (local_nigori.has_passphrase_type()) {
    179         // Local is migrated but server is not. Copy over the local migrated
    180         // data.
    181         new_nigori->CopyFrom(local_nigori);
    182         cryptographer->GetKeys(new_nigori->mutable_encryption_keybag());
    183       }  // else leave the new nigori with the server state.
    184     }
    185 
    186     // Always update to the safest set of encrypted types.
    187     trans->directory()->GetNigoriHandler()->UpdateNigoriFromEncryptedTypes(
    188         new_nigori,
    189         trans);
    190 
    191     entry->Put(SPECIFICS, new_specifics);
    192     DVLOG(1) << "Resolving simple conflict, merging nigori nodes: "
    193              << entry;
    194 
    195     conflict_util::OverwriteServerChanges(entry);
    196 
    197     UMA_HISTOGRAM_ENUMERATION("Sync.ResolveSimpleConflict",
    198                               ConflictResolver::NIGORI_MERGE,
    199                               ConflictResolver::CONFLICT_RESOLUTION_SIZE);
    200   }
    201 }
    202 
    203 void ApplyControlUpdate(syncable::WriteTransaction* const trans,
    204                         syncable::MutableEntry* const entry,
    205                         Cryptographer* cryptographer) {
    206   DCHECK_NE(entry->GetServerModelType(), NIGORI);
    207   DCHECK(entry->Get(IS_UNAPPLIED_UPDATE));
    208   if (entry->Get(IS_UNSYNCED)) {
    209       // We just let the server win all conflicts with control types.
    210     DVLOG(1) << "Ignoring local changes for control update.";
    211     conflict_util::IgnoreLocalChanges(entry);
    212     UMA_HISTOGRAM_ENUMERATION("Sync.ResolveSimpleConflict",
    213                               ConflictResolver::OVERWRITE_LOCAL,
    214                               ConflictResolver::CONFLICT_RESOLUTION_SIZE);
    215   }
    216 
    217   UpdateAttemptResponse response = AttemptToUpdateEntry(
    218       trans, entry, cryptographer);
    219   DCHECK_EQ(SUCCESS, response);
    220 }
    221 
    222 }  // namespace syncer
    223