nigori_storage_impl.cc 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright 2019 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. #include "components/sync/nigori/nigori_storage_impl.h"
  5. #include <string>
  6. #include "base/files/file_util.h"
  7. #include "base/files/important_file_writer.h"
  8. #include "base/logging.h"
  9. #include "components/os_crypt/os_crypt.h"
  10. namespace syncer {
  11. NigoriStorageImpl::NigoriStorageImpl(const base::FilePath& path)
  12. : path_(path) {}
  13. NigoriStorageImpl::~NigoriStorageImpl() {
  14. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  15. }
  16. void NigoriStorageImpl::StoreData(const sync_pb::NigoriLocalData& data) {
  17. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  18. std::string serialized_data = data.SerializeAsString();
  19. if (serialized_data.empty()) {
  20. DLOG(ERROR) << "Failed to serialize NigoriLocalData.";
  21. return;
  22. }
  23. std::string encrypted_data;
  24. if (!OSCrypt::EncryptString(serialized_data, &encrypted_data)) {
  25. DLOG(ERROR) << "Failed to encrypt NigoriLocalData.";
  26. return;
  27. }
  28. if (!base::ImportantFileWriter::WriteFileAtomically(path_, encrypted_data)) {
  29. DLOG(ERROR) << "Failed to write NigoriLocalData into file.";
  30. }
  31. }
  32. absl::optional<sync_pb::NigoriLocalData> NigoriStorageImpl::RestoreData() {
  33. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  34. if (!base::PathExists(path_)) {
  35. return absl::nullopt;
  36. }
  37. std::string encrypted_data;
  38. if (!base::ReadFileToString(path_, &encrypted_data)) {
  39. DLOG(ERROR) << "Failed to read NigoriLocalData from file.";
  40. return absl::nullopt;
  41. }
  42. std::string serialized_data;
  43. if (!OSCrypt::DecryptString(encrypted_data, &serialized_data)) {
  44. DLOG(ERROR) << "Failed to decrypt NigoriLocalData.";
  45. return absl::nullopt;
  46. }
  47. sync_pb::NigoriLocalData data;
  48. if (!data.ParseFromString(serialized_data)) {
  49. DLOG(ERROR) << "Failed to parse NigoriLocalData.";
  50. return absl::nullopt;
  51. }
  52. return data;
  53. }
  54. void NigoriStorageImpl::ClearData() {
  55. base::DeleteFile(path_);
  56. }
  57. } // namespace syncer