blob: 0d3d42eee333d138f7bd0c9cffb613be7a4e7894 [file] [log] [blame]
[email protected]d3b05ea2012-01-24 22:57:051// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]277404c22010-04-22 13:09:452// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
[email protected]03b9b4e2012-10-22 20:01:525#include "base/prefs/json_pref_store.h"
[email protected]277404c22010-04-22 13:09:456
7#include <algorithm>
8
[email protected]844a1002011-04-19 11:37:219#include "base/bind.h"
10#include "base/callback.h"
[email protected]277404c22010-04-22 13:09:4511#include "base/file_util.h"
[email protected]ffbec692012-02-26 20:26:4212#include "base/json/json_file_value_serializer.h"
13#include "base/json/json_string_value_serializer.h"
[email protected]844a1002011-04-19 11:37:2114#include "base/memory/ref_counted.h"
[email protected]845b43a82011-05-11 10:14:4315#include "base/message_loop_proxy.h"
[email protected]0de615a2012-11-08 04:40:5916#include "base/sequenced_task_runner.h"
17#include "base/threading/sequenced_worker_pool.h"
[email protected]277404c22010-04-22 13:09:4518#include "base/values.h"
[email protected]277404c22010-04-22 13:09:4519
20namespace {
21
22// Some extensions we'll tack on to copies of the Preferences files.
[email protected]023ad6ab2013-02-17 05:07:2323const base::FilePath::CharType* kBadExtension = FILE_PATH_LITERAL("bad");
[email protected]277404c22010-04-22 13:09:4524
[email protected]845b43a82011-05-11 10:14:4325// Differentiates file loading between origin thread and passed
26// (aka file) thread.
[email protected]844a1002011-04-19 11:37:2127class FileThreadDeserializer
28 : public base::RefCountedThreadSafe<FileThreadDeserializer> {
29 public:
[email protected]e7e38032011-07-26 17:25:2530 FileThreadDeserializer(JsonPrefStore* delegate,
[email protected]0de615a2012-11-08 04:40:5931 base::SequencedTaskRunner* sequenced_task_runner)
[email protected]68e83602011-06-14 13:09:2832 : no_dir_(false),
33 error_(PersistentPrefStore::PREF_READ_ERROR_NONE),
34 delegate_(delegate),
[email protected]0de615a2012-11-08 04:40:5935 sequenced_task_runner_(sequenced_task_runner),
[email protected]edd685f2011-08-15 20:33:4636 origin_loop_proxy_(base::MessageLoopProxy::current()) {
[email protected]844a1002011-04-19 11:37:2137 }
38
[email protected]023ad6ab2013-02-17 05:07:2339 void Start(const base::FilePath& path) {
[email protected]845b43a82011-05-11 10:14:4340 DCHECK(origin_loop_proxy_->BelongsToCurrentThread());
[email protected]0de615a2012-11-08 04:40:5941 sequenced_task_runner_->PostTask(
[email protected]844a1002011-04-19 11:37:2142 FROM_HERE,
[email protected]3a1a4052011-10-17 18:04:4143 base::Bind(&FileThreadDeserializer::ReadFileAndReport,
44 this, path));
[email protected]844a1002011-04-19 11:37:2145 }
46
[email protected]0de615a2012-11-08 04:40:5947 // Deserializes JSON on the sequenced task runner.
[email protected]023ad6ab2013-02-17 05:07:2348 void ReadFileAndReport(const base::FilePath& path) {
[email protected]0de615a2012-11-08 04:40:5949 DCHECK(sequenced_task_runner_->RunsTasksOnCurrentThread());
[email protected]370bc732012-05-07 21:25:2050
[email protected]845b43a82011-05-11 10:14:4351 value_.reset(DoReading(path, &error_, &no_dir_));
52
53 origin_loop_proxy_->PostTask(
54 FROM_HERE,
[email protected]3a1a4052011-10-17 18:04:4155 base::Bind(&FileThreadDeserializer::ReportOnOriginThread, this));
[email protected]845b43a82011-05-11 10:14:4356 }
57
58 // Reports deserialization result on the origin thread.
59 void ReportOnOriginThread() {
60 DCHECK(origin_loop_proxy_->BelongsToCurrentThread());
61 delegate_->OnFileRead(value_.release(), error_, no_dir_);
62 }
63
[email protected]023ad6ab2013-02-17 05:07:2364 static Value* DoReading(const base::FilePath& path,
[email protected]845b43a82011-05-11 10:14:4365 PersistentPrefStore::PrefReadError* error,
66 bool* no_dir) {
[email protected]844a1002011-04-19 11:37:2167 int error_code;
68 std::string error_msg;
69 JSONFileValueSerializer serializer(path);
[email protected]845b43a82011-05-11 10:14:4370 Value* value = serializer.Deserialize(&error_code, &error_msg);
71 HandleErrors(value, path, error_code, error_msg, error);
72 *no_dir = !file_util::PathExists(path.DirName());
73 return value;
[email protected]844a1002011-04-19 11:37:2174 }
75
76 static void HandleErrors(const Value* value,
[email protected]023ad6ab2013-02-17 05:07:2377 const base::FilePath& path,
[email protected]844a1002011-04-19 11:37:2178 int error_code,
79 const std::string& error_msg,
80 PersistentPrefStore::PrefReadError* error);
81
82 private:
83 friend class base::RefCountedThreadSafe<FileThreadDeserializer>;
[email protected]7b2720b2012-04-25 16:59:1184 ~FileThreadDeserializer() {}
[email protected]844a1002011-04-19 11:37:2185
86 bool no_dir_;
87 PersistentPrefStore::PrefReadError error_;
88 scoped_ptr<Value> value_;
[email protected]0de615a2012-11-08 04:40:5989 const scoped_refptr<JsonPrefStore> delegate_;
90 const scoped_refptr<base::SequencedTaskRunner> sequenced_task_runner_;
91 const scoped_refptr<base::MessageLoopProxy> origin_loop_proxy_;
[email protected]844a1002011-04-19 11:37:2192};
93
94// static
95void FileThreadDeserializer::HandleErrors(
96 const Value* value,
[email protected]023ad6ab2013-02-17 05:07:2397 const base::FilePath& path,
[email protected]844a1002011-04-19 11:37:2198 int error_code,
99 const std::string& error_msg,
100 PersistentPrefStore::PrefReadError* error) {
101 *error = PersistentPrefStore::PREF_READ_ERROR_NONE;
102 if (!value) {
[email protected]0de615a2012-11-08 04:40:59103 DVLOG(1) << "Error while loading JSON file: " << error_msg
104 << ", file: " << path.value();
[email protected]844a1002011-04-19 11:37:21105 switch (error_code) {
106 case JSONFileValueSerializer::JSON_ACCESS_DENIED:
107 *error = PersistentPrefStore::PREF_READ_ERROR_ACCESS_DENIED;
108 break;
109 case JSONFileValueSerializer::JSON_CANNOT_READ_FILE:
110 *error = PersistentPrefStore::PREF_READ_ERROR_FILE_OTHER;
111 break;
112 case JSONFileValueSerializer::JSON_FILE_LOCKED:
113 *error = PersistentPrefStore::PREF_READ_ERROR_FILE_LOCKED;
114 break;
115 case JSONFileValueSerializer::JSON_NO_SUCH_FILE:
116 *error = PersistentPrefStore::PREF_READ_ERROR_NO_FILE;
117 break;
118 default:
119 *error = PersistentPrefStore::PREF_READ_ERROR_JSON_PARSE;
120 // JSON errors indicate file corruption of some sort.
121 // Since the file is corrupt, move it to the side and continue with
122 // empty preferences. This will result in them losing their settings.
123 // We keep the old file for possible support and debugging assistance
124 // as well as to detect if they're seeing these errors repeatedly.
125 // TODO(erikkay) Instead, use the last known good file.
[email protected]023ad6ab2013-02-17 05:07:23126 base::FilePath bad = path.ReplaceExtension(kBadExtension);
[email protected]844a1002011-04-19 11:37:21127
128 // If they've ever had a parse error before, put them in another bucket.
129 // TODO(erikkay) if we keep this error checking for very long, we may
130 // want to differentiate between recent and long ago errors.
131 if (file_util::PathExists(bad))
132 *error = PersistentPrefStore::PREF_READ_ERROR_JSON_REPEAT;
133 file_util::Move(path, bad);
134 break;
135 }
136 } else if (!value->IsType(Value::TYPE_DICTIONARY)) {
137 *error = PersistentPrefStore::PREF_READ_ERROR_JSON_TYPE;
138 }
139}
140
[email protected]277404c22010-04-22 13:09:45141} // namespace
142
[email protected]0de615a2012-11-08 04:40:59143scoped_refptr<base::SequencedTaskRunner> JsonPrefStore::GetTaskRunnerForFile(
[email protected]023ad6ab2013-02-17 05:07:23144 const base::FilePath& filename,
[email protected]0de615a2012-11-08 04:40:59145 base::SequencedWorkerPool* worker_pool) {
146 std::string token("json_pref_store-");
147 token.append(filename.AsUTF8Unsafe());
148 return worker_pool->GetSequencedTaskRunnerWithShutdownBehavior(
149 worker_pool->GetNamedSequenceToken(token),
150 base::SequencedWorkerPool::BLOCK_SHUTDOWN);
151}
152
[email protected]023ad6ab2013-02-17 05:07:23153JsonPrefStore::JsonPrefStore(const base::FilePath& filename,
[email protected]0de615a2012-11-08 04:40:59154 base::SequencedTaskRunner* sequenced_task_runner)
[email protected]277404c22010-04-22 13:09:45155 : path_(filename),
[email protected]0de615a2012-11-08 04:40:59156 sequenced_task_runner_(sequenced_task_runner),
[email protected]277404c22010-04-22 13:09:45157 prefs_(new DictionaryValue()),
158 read_only_(false),
[email protected]0de615a2012-11-08 04:40:59159 writer_(filename, sequenced_task_runner),
[email protected]845b43a82011-05-11 10:14:43160 error_delegate_(NULL),
[email protected]59c10712012-03-13 02:10:34161 initialized_(false),
162 read_error_(PREF_READ_ERROR_OTHER) {
[email protected]6658ca82010-05-20 18:20:29163}
[email protected]277404c22010-04-22 13:09:45164
[email protected]892f1d62012-11-08 18:24:34165bool JsonPrefStore::GetValue(const std::string& key,
166 const Value** result) const {
[email protected]68bf41a2011-03-25 16:38:31167 Value* tmp = NULL;
[email protected]892f1d62012-11-08 18:24:34168 if (!prefs_->Get(key, &tmp))
169 return false;
170
171 if (result)
172 *result = tmp;
173 return true;
[email protected]f2d1f612010-12-09 15:10:17174}
175
176void JsonPrefStore::AddObserver(PrefStore::Observer* observer) {
177 observers_.AddObserver(observer);
178}
179
180void JsonPrefStore::RemoveObserver(PrefStore::Observer* observer) {
181 observers_.RemoveObserver(observer);
182}
183
[email protected]d3b05ea2012-01-24 22:57:05184size_t JsonPrefStore::NumberOfObservers() const {
185 return observers_.size();
186}
187
[email protected]845b43a82011-05-11 10:14:43188bool JsonPrefStore::IsInitializationComplete() const {
189 return initialized_;
190}
191
[email protected]892f1d62012-11-08 18:24:34192bool JsonPrefStore::GetMutableValue(const std::string& key,
193 Value** result) {
194 return prefs_->Get(key, result);
[email protected]68bf41a2011-03-25 16:38:31195}
196
[email protected]f2d1f612010-12-09 15:10:17197void JsonPrefStore::SetValue(const std::string& key, Value* value) {
[email protected]9b5f56b42011-08-24 21:17:59198 DCHECK(value);
199 scoped_ptr<Value> new_value(value);
200 Value* old_value = NULL;
201 prefs_->Get(key, &old_value);
202 if (!old_value || !value->Equals(old_value)) {
203 prefs_->Set(key, new_value.release());
[email protected]25308672011-10-10 17:22:50204 ReportValueChanged(key);
[email protected]9b5f56b42011-08-24 21:17:59205 }
[email protected]f2d1f612010-12-09 15:10:17206}
207
208void JsonPrefStore::SetValueSilently(const std::string& key, Value* value) {
[email protected]9b5f56b42011-08-24 21:17:59209 DCHECK(value);
210 scoped_ptr<Value> new_value(value);
211 Value* old_value = NULL;
212 prefs_->Get(key, &old_value);
[email protected]25308672011-10-10 17:22:50213 if (!old_value || !value->Equals(old_value)) {
[email protected]9b5f56b42011-08-24 21:17:59214 prefs_->Set(key, new_value.release());
[email protected]25308672011-10-10 17:22:50215 if (!read_only_)
216 writer_.ScheduleWrite(this);
217 }
[email protected]f2d1f612010-12-09 15:10:17218}
219
220void JsonPrefStore::RemoveValue(const std::string& key) {
[email protected]25308672011-10-10 17:22:50221 if (prefs_->Remove(key, NULL))
222 ReportValueChanged(key);
[email protected]f2d1f612010-12-09 15:10:17223}
224
[email protected]ea3e4972012-04-12 03:41:37225void JsonPrefStore::MarkNeedsEmptyValue(const std::string& key) {
226 keys_need_empty_value_.insert(key);
227}
228
[email protected]ddb1e5a2010-12-13 20:10:45229bool JsonPrefStore::ReadOnly() const {
230 return read_only_;
231}
232
[email protected]59c10712012-03-13 02:10:34233PersistentPrefStore::PrefReadError JsonPrefStore::GetReadError() const {
234 return read_error_;
235}
236
[email protected]7b2720b2012-04-25 16:59:11237PersistentPrefStore::PrefReadError JsonPrefStore::ReadPrefs() {
238 if (path_.empty()) {
239 OnFileRead(NULL, PREF_READ_ERROR_FILE_NOT_SPECIFIED, false);
240 return PREF_READ_ERROR_FILE_NOT_SPECIFIED;
241 }
242
243 PrefReadError error;
244 bool no_dir;
245 Value* value = FileThreadDeserializer::DoReading(path_, &error, &no_dir);
246 OnFileRead(value, error, no_dir);
247 return error;
248}
249
250void JsonPrefStore::ReadPrefsAsync(ReadErrorDelegate *error_delegate) {
251 initialized_ = false;
252 error_delegate_.reset(error_delegate);
253 if (path_.empty()) {
254 OnFileRead(NULL, PREF_READ_ERROR_FILE_NOT_SPECIFIED, false);
255 return;
256 }
257
258 // Start async reading of the preferences file. It will delete itself
259 // in the end.
260 scoped_refptr<FileThreadDeserializer> deserializer(
[email protected]0de615a2012-11-08 04:40:59261 new FileThreadDeserializer(this, sequenced_task_runner_.get()));
[email protected]7b2720b2012-04-25 16:59:11262 deserializer->Start(path_);
263}
264
265void JsonPrefStore::CommitPendingWrite() {
266 if (writer_.HasPendingWrite() && !read_only_)
267 writer_.DoScheduledWrite();
268}
269
270void JsonPrefStore::ReportValueChanged(const std::string& key) {
271 FOR_EACH_OBSERVER(PrefStore::Observer, observers_, OnPrefValueChanged(key));
272 if (!read_only_)
273 writer_.ScheduleWrite(this);
274}
275
[email protected]844a1002011-04-19 11:37:21276void JsonPrefStore::OnFileRead(Value* value_owned,
277 PersistentPrefStore::PrefReadError error,
278 bool no_dir) {
279 scoped_ptr<Value> value(value_owned);
[email protected]59c10712012-03-13 02:10:34280 read_error_ = error;
[email protected]845b43a82011-05-11 10:14:43281
282 if (no_dir) {
283 FOR_EACH_OBSERVER(PrefStore::Observer,
284 observers_,
285 OnInitializationCompleted(false));
286 return;
287 }
288
[email protected]32a7a022012-05-10 23:36:39289 initialized_ = true;
290
[email protected]844a1002011-04-19 11:37:21291 switch (error) {
292 case PREF_READ_ERROR_ACCESS_DENIED:
293 case PREF_READ_ERROR_FILE_OTHER:
294 case PREF_READ_ERROR_FILE_LOCKED:
295 case PREF_READ_ERROR_JSON_TYPE:
[email protected]845b43a82011-05-11 10:14:43296 case PREF_READ_ERROR_FILE_NOT_SPECIFIED:
[email protected]844a1002011-04-19 11:37:21297 read_only_ = true;
298 break;
299 case PREF_READ_ERROR_NONE:
300 DCHECK(value.get());
301 prefs_.reset(static_cast<DictionaryValue*>(value.release()));
302 break;
303 case PREF_READ_ERROR_NO_FILE:
304 // If the file just doesn't exist, maybe this is first run. In any case
305 // there's no harm in writing out default prefs in this case.
306 break;
307 case PREF_READ_ERROR_JSON_PARSE:
308 case PREF_READ_ERROR_JSON_REPEAT:
309 break;
310 default:
311 NOTREACHED() << "Unknown error: " << error;
312 }
313
[email protected]845b43a82011-05-11 10:14:43314 if (error_delegate_.get() && error != PREF_READ_ERROR_NONE)
315 error_delegate_->OnError(error);
316
317 FOR_EACH_OBSERVER(PrefStore::Observer,
318 observers_,
319 OnInitializationCompleted(true));
[email protected]844a1002011-04-19 11:37:21320}
321
[email protected]7b2720b2012-04-25 16:59:11322JsonPrefStore::~JsonPrefStore() {
323 CommitPendingWrite();
[email protected]f89ee342011-03-07 09:28:27324}
325
[email protected]277404c22010-04-22 13:09:45326bool JsonPrefStore::SerializeData(std::string* output) {
327 // TODO(tc): Do we want to prune webkit preferences that match the default
328 // value?
329 JSONStringValueSerializer serializer(output);
330 serializer.set_pretty_print(true);
331 scoped_ptr<DictionaryValue> copy(prefs_->DeepCopyWithoutEmptyChildren());
[email protected]ea3e4972012-04-12 03:41:37332
333 // Iterates |keys_need_empty_value_| and if the key exists in |prefs_|,
334 // ensure its empty ListValue or DictonaryValue is preserved.
335 for (std::set<std::string>::const_iterator
336 it = keys_need_empty_value_.begin();
337 it != keys_need_empty_value_.end();
338 ++it) {
339 const std::string& key = *it;
340
341 base::Value* value = NULL;
342 if (!prefs_->Get(key, &value))
343 continue;
344
345 if (value->IsType(base::Value::TYPE_LIST)) {
346 const base::ListValue* list = NULL;
347 if (value->GetAsList(&list) && list->empty())
348 copy->Set(key, new base::ListValue);
349 } else if (value->IsType(base::Value::TYPE_DICTIONARY)) {
350 const base::DictionaryValue* dict = NULL;
351 if (value->GetAsDictionary(&dict) && dict->empty())
352 copy->Set(key, new base::DictionaryValue);
353 }
354 }
355
[email protected]277404c22010-04-22 13:09:45356 return serializer.Serialize(*(copy.get()));
357}