joi@chromium.org | 026cee4 | 2012-10-23 05:01:52 +0900 | [diff] [blame] | 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. |
| 4 | |
| 5 | #include "base/prefs/json_pref_store.h" |
| 6 | |
| 7 | #include <algorithm> |
| 8 | |
| 9 | #include "base/bind.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_proxy.h" |
zelidrag@chromium.org | 011ad40 | 2012-11-08 13:40:59 +0900 | [diff] [blame^] | 16 | #include "base/sequenced_task_runner.h" |
| 17 | #include "base/threading/sequenced_worker_pool.h" |
joi@chromium.org | 026cee4 | 2012-10-23 05:01:52 +0900 | [diff] [blame] | 18 | #include "base/values.h" |
| 19 | |
| 20 | namespace { |
| 21 | |
| 22 | // Some extensions we'll tack on to copies of the Preferences files. |
| 23 | const FilePath::CharType* kBadExtension = FILE_PATH_LITERAL("bad"); |
| 24 | |
| 25 | // Differentiates file loading between origin thread and passed |
| 26 | // (aka file) thread. |
| 27 | class FileThreadDeserializer |
| 28 | : public base::RefCountedThreadSafe<FileThreadDeserializer> { |
| 29 | public: |
| 30 | FileThreadDeserializer(JsonPrefStore* delegate, |
zelidrag@chromium.org | 011ad40 | 2012-11-08 13:40:59 +0900 | [diff] [blame^] | 31 | base::SequencedTaskRunner* sequenced_task_runner) |
joi@chromium.org | 026cee4 | 2012-10-23 05:01:52 +0900 | [diff] [blame] | 32 | : no_dir_(false), |
| 33 | error_(PersistentPrefStore::PREF_READ_ERROR_NONE), |
| 34 | delegate_(delegate), |
zelidrag@chromium.org | 011ad40 | 2012-11-08 13:40:59 +0900 | [diff] [blame^] | 35 | sequenced_task_runner_(sequenced_task_runner), |
joi@chromium.org | 026cee4 | 2012-10-23 05:01:52 +0900 | [diff] [blame] | 36 | origin_loop_proxy_(base::MessageLoopProxy::current()) { |
| 37 | } |
| 38 | |
| 39 | void Start(const FilePath& path) { |
| 40 | DCHECK(origin_loop_proxy_->BelongsToCurrentThread()); |
zelidrag@chromium.org | 011ad40 | 2012-11-08 13:40:59 +0900 | [diff] [blame^] | 41 | sequenced_task_runner_->PostTask( |
joi@chromium.org | 026cee4 | 2012-10-23 05:01:52 +0900 | [diff] [blame] | 42 | FROM_HERE, |
| 43 | base::Bind(&FileThreadDeserializer::ReadFileAndReport, |
| 44 | this, path)); |
| 45 | } |
| 46 | |
zelidrag@chromium.org | 011ad40 | 2012-11-08 13:40:59 +0900 | [diff] [blame^] | 47 | // Deserializes JSON on the sequenced task runner. |
joi@chromium.org | 026cee4 | 2012-10-23 05:01:52 +0900 | [diff] [blame] | 48 | void ReadFileAndReport(const FilePath& path) { |
zelidrag@chromium.org | 011ad40 | 2012-11-08 13:40:59 +0900 | [diff] [blame^] | 49 | DCHECK(sequenced_task_runner_->RunsTasksOnCurrentThread()); |
joi@chromium.org | 026cee4 | 2012-10-23 05:01:52 +0900 | [diff] [blame] | 50 | |
| 51 | value_.reset(DoReading(path, &error_, &no_dir_)); |
| 52 | |
| 53 | origin_loop_proxy_->PostTask( |
| 54 | FROM_HERE, |
| 55 | base::Bind(&FileThreadDeserializer::ReportOnOriginThread, this)); |
| 56 | } |
| 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 | |
| 64 | static Value* DoReading(const FilePath& path, |
| 65 | PersistentPrefStore::PrefReadError* error, |
| 66 | bool* no_dir) { |
| 67 | int error_code; |
| 68 | std::string error_msg; |
| 69 | JSONFileValueSerializer serializer(path); |
| 70 | 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; |
| 74 | } |
| 75 | |
| 76 | static void HandleErrors(const Value* value, |
| 77 | const FilePath& path, |
| 78 | int error_code, |
| 79 | const std::string& error_msg, |
| 80 | PersistentPrefStore::PrefReadError* error); |
| 81 | |
| 82 | private: |
| 83 | friend class base::RefCountedThreadSafe<FileThreadDeserializer>; |
| 84 | ~FileThreadDeserializer() {} |
| 85 | |
| 86 | bool no_dir_; |
| 87 | PersistentPrefStore::PrefReadError error_; |
| 88 | scoped_ptr<Value> value_; |
zelidrag@chromium.org | 011ad40 | 2012-11-08 13:40:59 +0900 | [diff] [blame^] | 89 | const scoped_refptr<JsonPrefStore> delegate_; |
| 90 | const scoped_refptr<base::SequencedTaskRunner> sequenced_task_runner_; |
| 91 | const scoped_refptr<base::MessageLoopProxy> origin_loop_proxy_; |
joi@chromium.org | 026cee4 | 2012-10-23 05:01:52 +0900 | [diff] [blame] | 92 | }; |
| 93 | |
| 94 | // static |
| 95 | void FileThreadDeserializer::HandleErrors( |
| 96 | const Value* value, |
| 97 | const FilePath& path, |
| 98 | int error_code, |
| 99 | const std::string& error_msg, |
| 100 | PersistentPrefStore::PrefReadError* error) { |
| 101 | *error = PersistentPrefStore::PREF_READ_ERROR_NONE; |
| 102 | if (!value) { |
zelidrag@chromium.org | 011ad40 | 2012-11-08 13:40:59 +0900 | [diff] [blame^] | 103 | DVLOG(1) << "Error while loading JSON file: " << error_msg |
| 104 | << ", file: " << path.value(); |
joi@chromium.org | 026cee4 | 2012-10-23 05:01:52 +0900 | [diff] [blame] | 105 | 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. |
| 126 | FilePath bad = path.ReplaceExtension(kBadExtension); |
| 127 | |
| 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 | |
| 141 | } // namespace |
| 142 | |
zelidrag@chromium.org | 011ad40 | 2012-11-08 13:40:59 +0900 | [diff] [blame^] | 143 | scoped_refptr<base::SequencedTaskRunner> JsonPrefStore::GetTaskRunnerForFile( |
| 144 | const FilePath& filename, |
| 145 | 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 | |
joi@chromium.org | 026cee4 | 2012-10-23 05:01:52 +0900 | [diff] [blame] | 153 | JsonPrefStore::JsonPrefStore(const FilePath& filename, |
zelidrag@chromium.org | 011ad40 | 2012-11-08 13:40:59 +0900 | [diff] [blame^] | 154 | base::SequencedTaskRunner* sequenced_task_runner) |
joi@chromium.org | 026cee4 | 2012-10-23 05:01:52 +0900 | [diff] [blame] | 155 | : path_(filename), |
zelidrag@chromium.org | 011ad40 | 2012-11-08 13:40:59 +0900 | [diff] [blame^] | 156 | sequenced_task_runner_(sequenced_task_runner), |
joi@chromium.org | 026cee4 | 2012-10-23 05:01:52 +0900 | [diff] [blame] | 157 | prefs_(new DictionaryValue()), |
| 158 | read_only_(false), |
zelidrag@chromium.org | 011ad40 | 2012-11-08 13:40:59 +0900 | [diff] [blame^] | 159 | writer_(filename, sequenced_task_runner), |
joi@chromium.org | 026cee4 | 2012-10-23 05:01:52 +0900 | [diff] [blame] | 160 | error_delegate_(NULL), |
| 161 | initialized_(false), |
| 162 | read_error_(PREF_READ_ERROR_OTHER) { |
| 163 | } |
| 164 | |
| 165 | PrefStore::ReadResult JsonPrefStore::GetValue(const std::string& key, |
| 166 | const Value** result) const { |
| 167 | Value* tmp = NULL; |
| 168 | if (prefs_->Get(key, &tmp)) { |
| 169 | if (result) |
| 170 | *result = tmp; |
| 171 | return READ_OK; |
| 172 | } |
| 173 | return READ_NO_VALUE; |
| 174 | } |
| 175 | |
| 176 | void JsonPrefStore::AddObserver(PrefStore::Observer* observer) { |
| 177 | observers_.AddObserver(observer); |
| 178 | } |
| 179 | |
| 180 | void JsonPrefStore::RemoveObserver(PrefStore::Observer* observer) { |
| 181 | observers_.RemoveObserver(observer); |
| 182 | } |
| 183 | |
| 184 | size_t JsonPrefStore::NumberOfObservers() const { |
| 185 | return observers_.size(); |
| 186 | } |
| 187 | |
| 188 | bool JsonPrefStore::IsInitializationComplete() const { |
| 189 | return initialized_; |
| 190 | } |
| 191 | |
| 192 | PrefStore::ReadResult JsonPrefStore::GetMutableValue(const std::string& key, |
| 193 | Value** result) { |
| 194 | return prefs_->Get(key, result) ? READ_OK : READ_NO_VALUE; |
| 195 | } |
| 196 | |
| 197 | void JsonPrefStore::SetValue(const std::string& key, Value* value) { |
| 198 | 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()); |
| 204 | ReportValueChanged(key); |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | void JsonPrefStore::SetValueSilently(const std::string& key, Value* value) { |
| 209 | DCHECK(value); |
| 210 | scoped_ptr<Value> new_value(value); |
| 211 | Value* old_value = NULL; |
| 212 | prefs_->Get(key, &old_value); |
| 213 | if (!old_value || !value->Equals(old_value)) { |
| 214 | prefs_->Set(key, new_value.release()); |
| 215 | if (!read_only_) |
| 216 | writer_.ScheduleWrite(this); |
| 217 | } |
| 218 | } |
| 219 | |
| 220 | void JsonPrefStore::RemoveValue(const std::string& key) { |
| 221 | if (prefs_->Remove(key, NULL)) |
| 222 | ReportValueChanged(key); |
| 223 | } |
| 224 | |
| 225 | void JsonPrefStore::MarkNeedsEmptyValue(const std::string& key) { |
| 226 | keys_need_empty_value_.insert(key); |
| 227 | } |
| 228 | |
| 229 | bool JsonPrefStore::ReadOnly() const { |
| 230 | return read_only_; |
| 231 | } |
| 232 | |
| 233 | PersistentPrefStore::PrefReadError JsonPrefStore::GetReadError() const { |
| 234 | return read_error_; |
| 235 | } |
| 236 | |
| 237 | PersistentPrefStore::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 | |
| 250 | void 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( |
zelidrag@chromium.org | 011ad40 | 2012-11-08 13:40:59 +0900 | [diff] [blame^] | 261 | new FileThreadDeserializer(this, sequenced_task_runner_.get())); |
joi@chromium.org | 026cee4 | 2012-10-23 05:01:52 +0900 | [diff] [blame] | 262 | deserializer->Start(path_); |
| 263 | } |
| 264 | |
| 265 | void JsonPrefStore::CommitPendingWrite() { |
| 266 | if (writer_.HasPendingWrite() && !read_only_) |
| 267 | writer_.DoScheduledWrite(); |
| 268 | } |
| 269 | |
| 270 | void 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 | |
| 276 | void JsonPrefStore::OnFileRead(Value* value_owned, |
| 277 | PersistentPrefStore::PrefReadError error, |
| 278 | bool no_dir) { |
| 279 | scoped_ptr<Value> value(value_owned); |
| 280 | read_error_ = error; |
| 281 | |
| 282 | if (no_dir) { |
| 283 | FOR_EACH_OBSERVER(PrefStore::Observer, |
| 284 | observers_, |
| 285 | OnInitializationCompleted(false)); |
| 286 | return; |
| 287 | } |
| 288 | |
| 289 | initialized_ = true; |
| 290 | |
| 291 | 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: |
| 296 | case PREF_READ_ERROR_FILE_NOT_SPECIFIED: |
| 297 | 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 | |
| 314 | 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)); |
| 320 | } |
| 321 | |
| 322 | JsonPrefStore::~JsonPrefStore() { |
| 323 | CommitPendingWrite(); |
| 324 | } |
| 325 | |
| 326 | bool 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()); |
| 332 | |
| 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 | |
| 356 | return serializer.Serialize(*(copy.get())); |
| 357 | } |