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/files/file_path.h"
13 #include "base/json/json_file_value_serializer.h"
14 #include "base/json/json_string_value_serializer.h"
15 #include "base/memory/ref_counted.h"
16 #include "base/metrics/histogram.h"
17 #include "base/prefs/pref_filter.h"
18 #include "base/sequenced_task_runner.h"
19 #include "base/strings/string_util.h"
20 #include "base/task_runner_util.h"
21 #include "base/threading/sequenced_worker_pool.h"
22 #include "base/values.h"
24 // Result returned from internal read tasks.
25 struct JsonPrefStore::ReadResult
{
30 scoped_ptr
<base::Value
> value
;
35 DISALLOW_COPY_AND_ASSIGN(ReadResult
);
38 JsonPrefStore::ReadResult::ReadResult()
39 : error(PersistentPrefStore::PREF_READ_ERROR_NONE
), no_dir(false) {
42 JsonPrefStore::ReadResult::~ReadResult() {
47 // Some extensions we'll tack on to copies of the Preferences files.
48 const base::FilePath::CharType kBadExtension
[] = FILE_PATH_LITERAL("bad");
50 PersistentPrefStore::PrefReadError
HandleReadErrors(
51 const base::Value
* value
,
52 const base::FilePath
& path
,
54 const std::string
& error_msg
) {
56 DVLOG(1) << "Error while loading JSON file: " << error_msg
57 << ", file: " << path
.value();
59 case JSONFileValueSerializer::JSON_ACCESS_DENIED
:
60 return PersistentPrefStore::PREF_READ_ERROR_ACCESS_DENIED
;
62 case JSONFileValueSerializer::JSON_CANNOT_READ_FILE
:
63 return PersistentPrefStore::PREF_READ_ERROR_FILE_OTHER
;
65 case JSONFileValueSerializer::JSON_FILE_LOCKED
:
66 return PersistentPrefStore::PREF_READ_ERROR_FILE_LOCKED
;
68 case JSONFileValueSerializer::JSON_NO_SUCH_FILE
:
69 return PersistentPrefStore::PREF_READ_ERROR_NO_FILE
;
72 // JSON errors indicate file corruption of some sort.
73 // Since the file is corrupt, move it to the side and continue with
74 // empty preferences. This will result in them losing their settings.
75 // We keep the old file for possible support and debugging assistance
76 // as well as to detect if they're seeing these errors repeatedly.
77 // TODO(erikkay) Instead, use the last known good file.
78 base::FilePath bad
= path
.ReplaceExtension(kBadExtension
);
80 // If they've ever had a parse error before, put them in another bucket.
81 // TODO(erikkay) if we keep this error checking for very long, we may
82 // want to differentiate between recent and long ago errors.
83 bool bad_existed
= base::PathExists(bad
);
84 base::Move(path
, bad
);
85 return bad_existed
? PersistentPrefStore::PREF_READ_ERROR_JSON_REPEAT
86 : PersistentPrefStore::PREF_READ_ERROR_JSON_PARSE
;
88 } else if (!value
->IsType(base::Value::TYPE_DICTIONARY
)) {
89 return PersistentPrefStore::PREF_READ_ERROR_JSON_TYPE
;
91 return PersistentPrefStore::PREF_READ_ERROR_NONE
;
94 scoped_ptr
<JsonPrefStore::ReadResult
> ReadPrefsFromDisk(
95 const base::FilePath
& path
,
96 const base::FilePath
& alternate_path
) {
97 if (!base::PathExists(path
) && !alternate_path
.empty() &&
98 base::PathExists(alternate_path
)) {
99 base::Move(alternate_path
, path
);
103 std::string error_msg
;
104 scoped_ptr
<JsonPrefStore::ReadResult
> read_result(
105 new JsonPrefStore::ReadResult
);
106 JSONFileValueSerializer
serializer(path
);
107 read_result
->value
.reset(serializer
.Deserialize(&error_code
, &error_msg
));
109 HandleReadErrors(read_result
->value
.get(), path
, error_code
, error_msg
);
110 read_result
->no_dir
= !base::PathExists(path
.DirName());
111 return read_result
.Pass();
117 scoped_refptr
<base::SequencedTaskRunner
> JsonPrefStore::GetTaskRunnerForFile(
118 const base::FilePath
& filename
,
119 base::SequencedWorkerPool
* worker_pool
) {
120 std::string
token("json_pref_store-");
121 token
.append(filename
.AsUTF8Unsafe());
122 return worker_pool
->GetSequencedTaskRunnerWithShutdownBehavior(
123 worker_pool
->GetNamedSequenceToken(token
),
124 base::SequencedWorkerPool::BLOCK_SHUTDOWN
);
127 JsonPrefStore::JsonPrefStore(const base::FilePath
& filename
,
128 base::SequencedTaskRunner
* sequenced_task_runner
,
129 scoped_ptr
<PrefFilter
> pref_filter
)
131 sequenced_task_runner_(sequenced_task_runner
),
132 prefs_(new base::DictionaryValue()),
134 writer_(filename
, sequenced_task_runner
),
135 pref_filter_(pref_filter
.Pass()),
137 filtering_in_progress_(false),
138 read_error_(PREF_READ_ERROR_NONE
) {
141 JsonPrefStore::JsonPrefStore(const base::FilePath
& filename
,
142 const base::FilePath
& alternate_filename
,
143 base::SequencedTaskRunner
* sequenced_task_runner
,
144 scoped_ptr
<PrefFilter
> pref_filter
)
146 alternate_path_(alternate_filename
),
147 sequenced_task_runner_(sequenced_task_runner
),
148 prefs_(new base::DictionaryValue()),
150 writer_(filename
, sequenced_task_runner
),
151 pref_filter_(pref_filter
.Pass()),
153 filtering_in_progress_(false),
154 read_error_(PREF_READ_ERROR_NONE
) {
157 bool JsonPrefStore::GetValue(const std::string
& key
,
158 const base::Value
** result
) const {
159 DCHECK(CalledOnValidThread());
161 base::Value
* tmp
= NULL
;
162 if (!prefs_
->Get(key
, &tmp
))
170 void JsonPrefStore::AddObserver(PrefStore::Observer
* observer
) {
171 DCHECK(CalledOnValidThread());
173 observers_
.AddObserver(observer
);
176 void JsonPrefStore::RemoveObserver(PrefStore::Observer
* observer
) {
177 DCHECK(CalledOnValidThread());
179 observers_
.RemoveObserver(observer
);
182 bool JsonPrefStore::HasObservers() const {
183 DCHECK(CalledOnValidThread());
185 return observers_
.might_have_observers();
188 bool JsonPrefStore::IsInitializationComplete() const {
189 DCHECK(CalledOnValidThread());
194 bool JsonPrefStore::GetMutableValue(const std::string
& key
,
195 base::Value
** result
) {
196 DCHECK(CalledOnValidThread());
198 return prefs_
->Get(key
, result
);
201 void JsonPrefStore::SetValue(const std::string
& key
, base::Value
* value
) {
202 DCHECK(CalledOnValidThread());
205 scoped_ptr
<base::Value
> new_value(value
);
206 base::Value
* old_value
= NULL
;
207 prefs_
->Get(key
, &old_value
);
208 if (!old_value
|| !value
->Equals(old_value
)) {
209 prefs_
->Set(key
, new_value
.release());
210 ReportValueChanged(key
);
214 void JsonPrefStore::SetValueSilently(const std::string
& key
,
215 base::Value
* value
) {
216 DCHECK(CalledOnValidThread());
219 scoped_ptr
<base::Value
> new_value(value
);
220 base::Value
* old_value
= NULL
;
221 prefs_
->Get(key
, &old_value
);
222 if (!old_value
|| !value
->Equals(old_value
)) {
223 prefs_
->Set(key
, new_value
.release());
225 writer_
.ScheduleWrite(this);
229 void JsonPrefStore::RemoveValue(const std::string
& key
) {
230 DCHECK(CalledOnValidThread());
232 if (prefs_
->RemovePath(key
, NULL
))
233 ReportValueChanged(key
);
236 void JsonPrefStore::RemoveValueSilently(const std::string
& key
) {
237 DCHECK(CalledOnValidThread());
239 prefs_
->RemovePath(key
, NULL
);
241 writer_
.ScheduleWrite(this);
244 bool JsonPrefStore::ReadOnly() const {
245 DCHECK(CalledOnValidThread());
250 PersistentPrefStore::PrefReadError
JsonPrefStore::GetReadError() const {
251 DCHECK(CalledOnValidThread());
256 PersistentPrefStore::PrefReadError
JsonPrefStore::ReadPrefs() {
257 DCHECK(CalledOnValidThread());
260 scoped_ptr
<ReadResult
> no_file_result
;
261 no_file_result
->error
= PREF_READ_ERROR_FILE_NOT_SPECIFIED
;
262 OnFileRead(no_file_result
.Pass());
263 return PREF_READ_ERROR_FILE_NOT_SPECIFIED
;
266 OnFileRead(ReadPrefsFromDisk(path_
, alternate_path_
));
267 return filtering_in_progress_
? PREF_READ_ERROR_ASYNCHRONOUS_TASK_INCOMPLETE
271 void JsonPrefStore::ReadPrefsAsync(ReadErrorDelegate
* error_delegate
) {
272 DCHECK(CalledOnValidThread());
274 initialized_
= false;
275 error_delegate_
.reset(error_delegate
);
277 scoped_ptr
<ReadResult
> no_file_result
;
278 no_file_result
->error
= PREF_READ_ERROR_FILE_NOT_SPECIFIED
;
279 OnFileRead(no_file_result
.Pass());
283 // Weakly binds the read task so that it doesn't kick in during shutdown.
284 base::PostTaskAndReplyWithResult(
285 sequenced_task_runner_
,
287 base::Bind(&ReadPrefsFromDisk
, path_
, alternate_path_
),
288 base::Bind(&JsonPrefStore::OnFileRead
, AsWeakPtr()));
291 void JsonPrefStore::CommitPendingWrite() {
292 DCHECK(CalledOnValidThread());
294 if (writer_
.HasPendingWrite() && !read_only_
)
295 writer_
.DoScheduledWrite();
298 void JsonPrefStore::ReportValueChanged(const std::string
& key
) {
299 DCHECK(CalledOnValidThread());
302 pref_filter_
->FilterUpdate(key
);
304 FOR_EACH_OBSERVER(PrefStore::Observer
, observers_
, OnPrefValueChanged(key
));
307 writer_
.ScheduleWrite(this);
310 void JsonPrefStore::RegisterOnNextSuccessfulWriteCallback(
311 const base::Closure
& on_next_successful_write
) {
312 DCHECK(CalledOnValidThread());
314 writer_
.RegisterOnNextSuccessfulWriteCallback(on_next_successful_write
);
317 void JsonPrefStore::OnFileRead(scoped_ptr
<ReadResult
> read_result
) {
318 DCHECK(CalledOnValidThread());
322 scoped_ptr
<base::DictionaryValue
> unfiltered_prefs(new base::DictionaryValue
);
324 read_error_
= read_result
->error
;
326 bool initialization_successful
= !read_result
->no_dir
;
328 if (initialization_successful
) {
329 switch (read_error_
) {
330 case PREF_READ_ERROR_ACCESS_DENIED
:
331 case PREF_READ_ERROR_FILE_OTHER
:
332 case PREF_READ_ERROR_FILE_LOCKED
:
333 case PREF_READ_ERROR_JSON_TYPE
:
334 case PREF_READ_ERROR_FILE_NOT_SPECIFIED
:
337 case PREF_READ_ERROR_NONE
:
338 DCHECK(read_result
->value
.get());
339 unfiltered_prefs
.reset(
340 static_cast<base::DictionaryValue
*>(read_result
->value
.release()));
342 case PREF_READ_ERROR_NO_FILE
:
343 // If the file just doesn't exist, maybe this is first run. In any case
344 // there's no harm in writing out default prefs in this case.
346 case PREF_READ_ERROR_JSON_PARSE
:
347 case PREF_READ_ERROR_JSON_REPEAT
:
349 case PREF_READ_ERROR_ASYNCHRONOUS_TASK_INCOMPLETE
:
350 // This is a special error code to be returned by ReadPrefs when it
351 // can't complete synchronously, it should never be returned by the read
355 case PREF_READ_ERROR_LEVELDB_IO
:
356 case PREF_READ_ERROR_LEVELDB_CORRUPTION_READ_ONLY
:
357 case PREF_READ_ERROR_LEVELDB_CORRUPTION
:
358 // These are specific to LevelDBPrefStore.
360 case PREF_READ_ERROR_MAX_ENUM
:
367 filtering_in_progress_
= true;
368 const PrefFilter::PostFilterOnLoadCallback
post_filter_on_load_callback(
370 &JsonPrefStore::FinalizeFileRead
, AsWeakPtr(),
371 initialization_successful
));
372 pref_filter_
->FilterOnLoad(post_filter_on_load_callback
,
373 unfiltered_prefs
.Pass());
375 FinalizeFileRead(initialization_successful
, unfiltered_prefs
.Pass(), false);
379 JsonPrefStore::~JsonPrefStore() {
380 CommitPendingWrite();
383 bool JsonPrefStore::SerializeData(std::string
* output
) {
384 DCHECK(CalledOnValidThread());
387 pref_filter_
->FilterSerializeData(prefs_
.get());
389 JSONStringValueSerializer
serializer(output
);
390 serializer
.set_pretty_print(true);
391 bool result
= serializer
.Serialize(*prefs_
);
394 std::string spaceless_basename
;
395 base::ReplaceChars(path_
.BaseName().MaybeAsASCII(), " ", "_",
396 &spaceless_basename
);
398 // The histogram below is an expansion of the UMA_HISTOGRAM_COUNTS_10000
399 // macro adapted to allow for a dynamically suffixed histogram name.
400 // Note: The factory creates and owns the histogram.
401 base::HistogramBase
* histogram
=
402 base::LinearHistogram::FactoryGet(
403 "Settings.JsonDataSizeKilobytes." + spaceless_basename
,
407 base::HistogramBase::kUmaTargetedHistogramFlag
);
408 histogram
->Add(static_cast<int>(output
->size()) / 1024);
414 void JsonPrefStore::FinalizeFileRead(bool initialization_successful
,
415 scoped_ptr
<base::DictionaryValue
> prefs
,
416 bool schedule_write
) {
417 DCHECK(CalledOnValidThread());
419 filtering_in_progress_
= false;
421 if (!initialization_successful
) {
422 FOR_EACH_OBSERVER(PrefStore::Observer
,
424 OnInitializationCompleted(false));
428 prefs_
= prefs
.Pass();
432 if (schedule_write
&& !read_only_
)
433 writer_
.ScheduleWrite(this);
435 if (error_delegate_
&& read_error_
!= PREF_READ_ERROR_NONE
)
436 error_delegate_
->OnError(read_error_
);
438 FOR_EACH_OBSERVER(PrefStore::Observer
,
440 OnInitializationCompleted(true));