blob: 585408cefcb032e4e217a7a547afb4241e0650b6 [file] [log] [blame]
Darin Petkov30030592010-07-27 13:53:20 -07001// Copyright (c) 2010 The Chromium OS 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 "update_engine/prefs.h"
6
Darin Petkov36275772010-10-01 11:40:57 -07007#include <base/file_util.h>
8#include <base/logging.h>
9#include <base/string_number_conversions.h>
10#include <base/string_util.h>
11
Darin Petkov30030592010-07-27 13:53:20 -070012#include "update_engine/utils.h"
13
14using std::string;
15
16namespace chromeos_update_engine {
17
Darin Petkov36275772010-10-01 11:40:57 -070018const char kPrefsDeltaUpdateFailures[] = "delta-update-failures";
Darin Petkov1cbd78f2010-07-29 12:38:34 -070019const char kPrefsLastActivePingDay[] = "last-active-ping-day";
20const char kPrefsLastRollCallPingDay[] = "last-roll-call-ping-day";
21
Darin Petkov30030592010-07-27 13:53:20 -070022bool Prefs::Init(const FilePath& prefs_dir) {
23 prefs_dir_ = prefs_dir;
24 return true;
25}
26
27bool Prefs::GetString(const string& key, string* value) {
28 LOG(INFO) << "Getting key \"" << key << "\"";
29 FilePath filename;
30 TEST_AND_RETURN_FALSE(GetFileNameForKey(key, &filename));
31 TEST_AND_RETURN_FALSE(file_util::ReadFileToString(filename, value));
32 LOG(INFO) << "Key \"" << key << "\" value \"" << *value << "\"";
33 return true;
34}
35
36bool Prefs::SetString(const std::string& key, const std::string& value) {
37 LOG(INFO) << "Setting key \"" << key << "\" value \"" << value << "\"";
38 FilePath filename;
39 TEST_AND_RETURN_FALSE(GetFileNameForKey(key, &filename));
40 TEST_AND_RETURN_FALSE(file_util::CreateDirectory(filename.DirName()));
41 TEST_AND_RETURN_FALSE(
42 file_util::WriteFile(filename, value.data(), value.size()) ==
43 static_cast<int>(value.size()));
44 return true;
45}
46
47bool Prefs::GetInt64(const string& key, int64_t* value) {
48 string str_value;
49 TEST_AND_RETURN_FALSE(GetString(key, &str_value));
50 TrimWhitespaceASCII(str_value, TRIM_ALL, &str_value);
Chris Masone790e62e2010-08-12 10:41:18 -070051 TEST_AND_RETURN_FALSE(base::StringToInt64(str_value, value));
Darin Petkov30030592010-07-27 13:53:20 -070052 return true;
53}
54
55bool Prefs::SetInt64(const string& key, const int64_t value) {
Chris Masone790e62e2010-08-12 10:41:18 -070056 return SetString(key, base::Int64ToString(value));
Darin Petkov30030592010-07-27 13:53:20 -070057}
58
59bool Prefs::GetFileNameForKey(const std::string& key, FilePath* filename) {
60 // Allows only non-empty keys containing [A-Za-z0-9_-].
61 TEST_AND_RETURN_FALSE(!key.empty());
62 for (size_t i = 0; i < key.size(); ++i) {
63 char c = key.at(i);
64 TEST_AND_RETURN_FALSE(IsAsciiAlpha(c) || IsAsciiDigit(c) ||
65 c == '_' || c == '-');
66 }
67 *filename = prefs_dir_.Append(key);
68 return true;
69}
70
71} // namespace chromeos_update_engine