1 // Copyright 2013 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 "chrome/browser/policy/cloud/cloud_external_data_store.h" 6 7 #include <set> 8 9 #include "base/logging.h" 10 #include "base/sha1.h" 11 #include "base/strings/string_number_conversions.h" 12 #include "chrome/browser/policy/cloud/resource_cache.h" 13 14 namespace policy { 15 16 namespace { 17 18 // Encodes (policy, hash) into a single string. 19 std::string GetSubkey(const std::string& policy, const std::string& hash) { 20 DCHECK(!policy.empty()); 21 DCHECK(!hash.empty()); 22 return base::IntToString(policy.size()) + ":" + 23 base::IntToString(hash.size()) + ":" + 24 policy + hash; 25 } 26 27 } // namespace 28 29 CloudExternalDataStore::CloudExternalDataStore(const std::string& cache_key, 30 ResourceCache* cache) 31 : cache_key_(cache_key), 32 cache_(cache) { 33 DetachFromThread(); 34 } 35 36 CloudExternalDataStore::~CloudExternalDataStore() { 37 DCHECK(CalledOnValidThread()); 38 } 39 40 void CloudExternalDataStore::Prune( 41 const CloudExternalDataManager::Metadata& metadata) { 42 std::set<std::string> subkeys_to_keep; 43 for (CloudExternalDataManager::Metadata::const_iterator it = metadata.begin(); 44 it != metadata.end(); ++it) { 45 subkeys_to_keep.insert(GetSubkey(it->first, it->second.hash)); 46 } 47 cache_->PurgeOtherSubkeys(cache_key_, subkeys_to_keep); 48 } 49 50 bool CloudExternalDataStore::Store(const std::string& policy, 51 const std::string& hash, 52 const std::string& data) { 53 DCHECK(CalledOnValidThread()); 54 return cache_->Store(cache_key_, GetSubkey(policy, hash), data); 55 } 56 57 bool CloudExternalDataStore::Load(const std::string& policy, 58 const std::string& hash, 59 size_t max_size, 60 std::string* data) { 61 DCHECK(CalledOnValidThread()); 62 const std::string subkey = GetSubkey(policy, hash); 63 if (cache_->Load(cache_key_, subkey, data)) { 64 if (data->size() <= max_size && base::SHA1HashString(*data) == hash) 65 return true; 66 // If the data is larger than allowed or does not match the expected hash, 67 // delete the entry. 68 cache_->Delete(cache_key_, subkey); 69 data->clear(); 70 } 71 return false; 72 } 73 74 } // namespace policy 75