1 // Copyright (c) 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.
5 #include "base/prefs/json_pref_store.h"
10 #include "base/callback.h"
11 #include "base/file_util.h"
12 #include "base/json/json_file_value_serializer.h"
13 #include "base/json/json_string_value_serializer.h"
14 #include "base/memory/ref_counted.h"
15 #include "base/message_loop/message_loop_proxy.h"
16 #include "base/prefs/pref_filter.h"
17 #include "base/sequenced_task_runner.h"
18 #include "base/threading/sequenced_worker_pool.h"
19 #include "base/values.h"
23 // Some extensions we'll tack on to copies of the Preferences files.
24 const base::FilePath::CharType
* kBadExtension
= FILE_PATH_LITERAL("bad");
26 // Differentiates file loading between origin thread and passed
28 class FileThreadDeserializer
29 : public base::RefCountedThreadSafe
<FileThreadDeserializer
> {
31 FileThreadDeserializer(JsonPrefStore
* delegate
,
32 base::SequencedTaskRunner
* sequenced_task_runner
)
34 error_(PersistentPrefStore::PREF_READ_ERROR_NONE
),
36 sequenced_task_runner_(sequenced_task_runner
),
37 origin_loop_proxy_(base::MessageLoopProxy::current()) {
40 void Start(const base::FilePath
& path
) {
41 DCHECK(origin_loop_proxy_
->BelongsToCurrentThread());
42 sequenced_task_runner_
->PostTask(
44 base::Bind(&FileThreadDeserializer::ReadFileAndReport
,
48 // Deserializes JSON on the sequenced task runner.
49 void ReadFileAndReport(const base::FilePath
& path
) {
50 DCHECK(sequenced_task_runner_
->RunsTasksOnCurrentThread());
52 value_
.reset(DoReading(path
, &error_
, &no_dir_
));
54 origin_loop_proxy_
->PostTask(
56 base::Bind(&FileThreadDeserializer::ReportOnOriginThread
, this));
59 // Reports deserialization result on the origin thread.
60 void ReportOnOriginThread() {
61 DCHECK(origin_loop_proxy_
->BelongsToCurrentThread());
62 delegate_
->OnFileRead(value_
.release(), error_
, no_dir_
);
65 static base::Value
* DoReading(const base::FilePath
& path
,
66 PersistentPrefStore::PrefReadError
* error
,
69 std::string error_msg
;
70 JSONFileValueSerializer
serializer(path
);
71 base::Value
* value
= serializer
.Deserialize(&error_code
, &error_msg
);
72 HandleErrors(value
, path
, error_code
, error_msg
, error
);
73 *no_dir
= !base::PathExists(path
.DirName());
77 static void HandleErrors(const base::Value
* value
,
78 const base::FilePath
& path
,
80 const std::string
& error_msg
,
81 PersistentPrefStore::PrefReadError
* error
);
84 friend class base::RefCountedThreadSafe
<FileThreadDeserializer
>;
85 ~FileThreadDeserializer() {}
88 PersistentPrefStore::PrefReadError error_
;
89 scoped_ptr
<base::Value
> value_
;
90 const scoped_refptr
<JsonPrefStore
> delegate_
;
91 const scoped_refptr
<base::SequencedTaskRunner
> sequenced_task_runner_
;
92 const scoped_refptr
<base::MessageLoopProxy
> origin_loop_proxy_
;
96 void FileThreadDeserializer::HandleErrors(
97 const base::Value
* value
,
98 const base::FilePath
& path
,
100 const std::string
& error_msg
,
101 PersistentPrefStore::PrefReadError
* error
) {
102 *error
= PersistentPrefStore::PREF_READ_ERROR_NONE
;
104 DVLOG(1) << "Error while loading JSON file: " << error_msg
105 << ", file: " << path
.value();
106 switch (error_code
) {
107 case JSONFileValueSerializer::JSON_ACCESS_DENIED
:
108 *error
= PersistentPrefStore::PREF_READ_ERROR_ACCESS_DENIED
;
110 case JSONFileValueSerializer::JSON_CANNOT_READ_FILE
:
111 *error
= PersistentPrefStore::PREF_READ_ERROR_FILE_OTHER
;
113 case JSONFileValueSerializer::JSON_FILE_LOCKED
:
114 *error
= PersistentPrefStore::PREF_READ_ERROR_FILE_LOCKED
;
116 case JSONFileValueSerializer::JSON_NO_SUCH_FILE
:
117 *error
= PersistentPrefStore::PREF_READ_ERROR_NO_FILE
;
120 *error
= PersistentPrefStore::PREF_READ_ERROR_JSON_PARSE
;
121 // JSON errors indicate file corruption of some sort.
122 // Since the file is corrupt, move it to the side and continue with
123 // empty preferences. This will result in them losing their settings.
124 // We keep the old file for possible support and debugging assistance
125 // as well as to detect if they're seeing these errors repeatedly.
126 // TODO(erikkay) Instead, use the last known good file.
127 base::FilePath bad
= path
.ReplaceExtension(kBadExtension
);
129 // If they've ever had a parse error before, put them in another bucket.
130 // TODO(erikkay) if we keep this error checking for very long, we may
131 // want to differentiate between recent and long ago errors.
132 if (base::PathExists(bad
))
133 *error
= PersistentPrefStore::PREF_READ_ERROR_JSON_REPEAT
;
134 base::Move(path
, bad
);
137 } else if (!value
->IsType(base::Value::TYPE_DICTIONARY
)) {
138 *error
= PersistentPrefStore::PREF_READ_ERROR_JSON_TYPE
;
144 scoped_refptr
<base::SequencedTaskRunner
> JsonPrefStore::GetTaskRunnerForFile(
145 const base::FilePath
& filename
,
146 base::SequencedWorkerPool
* worker_pool
) {
147 std::string
token("json_pref_store-");
148 token
.append(filename
.AsUTF8Unsafe());
149 return worker_pool
->GetSequencedTaskRunnerWithShutdownBehavior(
150 worker_pool
->GetNamedSequenceToken(token
),
151 base::SequencedWorkerPool::BLOCK_SHUTDOWN
);
154 JsonPrefStore::JsonPrefStore(const base::FilePath
& filename
,
155 base::SequencedTaskRunner
* sequenced_task_runner
,
156 scoped_ptr
<PrefFilter
> pref_filter
)
158 sequenced_task_runner_(sequenced_task_runner
),
159 prefs_(new base::DictionaryValue()),
161 writer_(filename
, sequenced_task_runner
),
162 pref_filter_(pref_filter
.Pass()),
164 read_error_(PREF_READ_ERROR_OTHER
) {}
166 bool JsonPrefStore::GetValue(const std::string
& key
,
167 const base::Value
** result
) const {
168 base::Value
* tmp
= NULL
;
169 if (!prefs_
->Get(key
, &tmp
))
177 void JsonPrefStore::AddObserver(PrefStore::Observer
* observer
) {
178 observers_
.AddObserver(observer
);
181 void JsonPrefStore::RemoveObserver(PrefStore::Observer
* observer
) {
182 observers_
.RemoveObserver(observer
);
185 bool JsonPrefStore::HasObservers() const {
186 return observers_
.might_have_observers();
189 bool JsonPrefStore::IsInitializationComplete() const {
193 bool JsonPrefStore::GetMutableValue(const std::string
& key
,
194 base::Value
** result
) {
195 return prefs_
->Get(key
, result
);
198 void JsonPrefStore::SetValue(const std::string
& key
, base::Value
* value
) {
200 scoped_ptr
<base::Value
> new_value(value
);
201 base::Value
* old_value
= NULL
;
202 prefs_
->Get(key
, &old_value
);
203 if (!old_value
|| !value
->Equals(old_value
)) {
204 prefs_
->Set(key
, new_value
.release());
205 ReportValueChanged(key
);
209 void JsonPrefStore::SetValueSilently(const std::string
& key
,
210 base::Value
* value
) {
212 scoped_ptr
<base::Value
> new_value(value
);
213 base::Value
* old_value
= NULL
;
214 prefs_
->Get(key
, &old_value
);
215 if (!old_value
|| !value
->Equals(old_value
)) {
216 prefs_
->Set(key
, new_value
.release());
218 writer_
.ScheduleWrite(this);
222 void JsonPrefStore::RemoveValue(const std::string
& key
) {
223 if (prefs_
->RemovePath(key
, NULL
))
224 ReportValueChanged(key
);
227 bool JsonPrefStore::ReadOnly() const {
231 PersistentPrefStore::PrefReadError
JsonPrefStore::GetReadError() const {
235 PersistentPrefStore::PrefReadError
JsonPrefStore::ReadPrefs() {
237 OnFileRead(NULL
, PREF_READ_ERROR_FILE_NOT_SPECIFIED
, false);
238 return PREF_READ_ERROR_FILE_NOT_SPECIFIED
;
244 FileThreadDeserializer::DoReading(path_
, &error
, &no_dir
);
245 OnFileRead(value
, error
, no_dir
);
249 void JsonPrefStore::ReadPrefsAsync(ReadErrorDelegate
*error_delegate
) {
250 initialized_
= false;
251 error_delegate_
.reset(error_delegate
);
253 OnFileRead(NULL
, PREF_READ_ERROR_FILE_NOT_SPECIFIED
, false);
257 // Start async reading of the preferences file. It will delete itself
259 scoped_refptr
<FileThreadDeserializer
> deserializer(
260 new FileThreadDeserializer(this, sequenced_task_runner_
.get()));
261 deserializer
->Start(path_
);
264 void JsonPrefStore::CommitPendingWrite() {
265 if (writer_
.HasPendingWrite() && !read_only_
)
266 writer_
.DoScheduledWrite();
269 void JsonPrefStore::ReportValueChanged(const std::string
& key
) {
271 pref_filter_
->FilterUpdate(key
);
273 FOR_EACH_OBSERVER(PrefStore::Observer
, observers_
, OnPrefValueChanged(key
));
276 writer_
.ScheduleWrite(this);
279 void JsonPrefStore::OnFileRead(base::Value
* value_owned
,
280 PersistentPrefStore::PrefReadError error
,
282 scoped_ptr
<base::Value
> value(value_owned
);
286 FOR_EACH_OBSERVER(PrefStore::Observer
,
288 OnInitializationCompleted(false));
295 case PREF_READ_ERROR_ACCESS_DENIED
:
296 case PREF_READ_ERROR_FILE_OTHER
:
297 case PREF_READ_ERROR_FILE_LOCKED
:
298 case PREF_READ_ERROR_JSON_TYPE
:
299 case PREF_READ_ERROR_FILE_NOT_SPECIFIED
:
302 case PREF_READ_ERROR_NONE
:
304 prefs_
.reset(static_cast<base::DictionaryValue
*>(value
.release()));
306 case PREF_READ_ERROR_NO_FILE
:
307 // If the file just doesn't exist, maybe this is first run. In any case
308 // there's no harm in writing out default prefs in this case.
310 case PREF_READ_ERROR_JSON_PARSE
:
311 case PREF_READ_ERROR_JSON_REPEAT
:
314 NOTREACHED() << "Unknown error: " << error
;
317 if (pref_filter_
&& pref_filter_
->FilterOnLoad(prefs_
.get()))
318 writer_
.ScheduleWrite(this);
320 if (error_delegate_
.get() && error
!= PREF_READ_ERROR_NONE
)
321 error_delegate_
->OnError(error
);
323 FOR_EACH_OBSERVER(PrefStore::Observer
,
325 OnInitializationCompleted(true));
328 JsonPrefStore::~JsonPrefStore() {
329 CommitPendingWrite();
332 bool JsonPrefStore::SerializeData(std::string
* output
) {
334 pref_filter_
->FilterSerializeData(prefs_
.get());
336 JSONStringValueSerializer
serializer(output
);
337 serializer
.set_pretty_print(true);
338 return serializer
.Serialize(*prefs_
);