We started redesigning GpuMemoryBuffer interface to handle multiple buffers [0].
[chromium-blink-merge.git] / storage / browser / fileapi / obfuscated_file_util.cc
blobaf1406637ea5f1e94ab6d96b2e46336b35ffdfc6
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 "storage/browser/fileapi/obfuscated_file_util.h"
7 #include <queue>
8 #include <string>
9 #include <vector>
11 #include "base/files/file_util.h"
12 #include "base/format_macros.h"
13 #include "base/logging.h"
14 #include "base/message_loop/message_loop.h"
15 #include "base/metrics/histogram.h"
16 #include "base/stl_util.h"
17 #include "base/strings/string_number_conversions.h"
18 #include "base/strings/string_util.h"
19 #include "base/strings/stringprintf.h"
20 #include "base/strings/sys_string_conversions.h"
21 #include "base/strings/utf_string_conversions.h"
22 #include "base/time/time.h"
23 #include "storage/browser/fileapi/file_observers.h"
24 #include "storage/browser/fileapi/file_system_context.h"
25 #include "storage/browser/fileapi/file_system_operation_context.h"
26 #include "storage/browser/fileapi/file_system_url.h"
27 #include "storage/browser/fileapi/native_file_util.h"
28 #include "storage/browser/fileapi/sandbox_file_system_backend.h"
29 #include "storage/browser/fileapi/sandbox_isolated_origin_database.h"
30 #include "storage/browser/fileapi/sandbox_origin_database.h"
31 #include "storage/browser/fileapi/sandbox_prioritized_origin_database.h"
32 #include "storage/browser/fileapi/timed_task_helper.h"
33 #include "storage/browser/quota/quota_manager.h"
34 #include "storage/common/database/database_identifier.h"
35 #include "storage/common/fileapi/file_system_util.h"
36 #include "url/gurl.h"
38 // Example of various paths:
39 // void ObfuscatedFileUtil::DoSomething(const FileSystemURL& url) {
40 // base::FilePath virtual_path = url.path();
41 // base::FilePath local_path = GetLocalFilePath(url);
43 // NativeFileUtil::DoSomething(local_path);
44 // file_util::DoAnother(local_path);
45 // }
47 namespace storage {
49 namespace {
51 typedef SandboxDirectoryDatabase::FileId FileId;
52 typedef SandboxDirectoryDatabase::FileInfo FileInfo;
54 void InitFileInfo(
55 SandboxDirectoryDatabase::FileInfo* file_info,
56 SandboxDirectoryDatabase::FileId parent_id,
57 const base::FilePath::StringType& file_name) {
58 DCHECK(file_info);
59 file_info->parent_id = parent_id;
60 file_info->name = file_name;
63 // Costs computed as per crbug.com/86114, based on the LevelDB implementation of
64 // path storage under Linux. It's not clear if that will differ on Windows, on
65 // which base::FilePath uses wide chars [since they're converted to UTF-8 for
66 // storage anyway], but as long as the cost is high enough that one can't cheat
67 // on quota by storing data in paths, it doesn't need to be all that accurate.
68 const int64 kPathCreationQuotaCost = 146; // Bytes per inode, basically.
69 const int64 kPathByteQuotaCost = 2; // Bytes per byte of path length in UTF-8.
71 const char kDirectoryDatabaseKeySeparator = ' ';
73 int64 UsageForPath(size_t length) {
74 return kPathCreationQuotaCost +
75 static_cast<int64>(length) * kPathByteQuotaCost;
78 bool AllocateQuota(FileSystemOperationContext* context, int64 growth) {
79 if (context->allowed_bytes_growth() == storage::QuotaManager::kNoLimit)
80 return true;
82 int64 new_quota = context->allowed_bytes_growth() - growth;
83 if (growth > 0 && new_quota < 0)
84 return false;
85 context->set_allowed_bytes_growth(new_quota);
86 return true;
89 void UpdateUsage(
90 FileSystemOperationContext* context,
91 const FileSystemURL& url,
92 int64 growth) {
93 context->update_observers()->Notify(
94 &FileUpdateObserver::OnUpdate, MakeTuple(url, growth));
97 void TouchDirectory(SandboxDirectoryDatabase* db, FileId dir_id) {
98 DCHECK(db);
99 if (!db->UpdateModificationTime(dir_id, base::Time::Now()))
100 NOTREACHED();
103 enum IsolatedOriginStatus {
104 kIsolatedOriginMatch,
105 kIsolatedOriginDontMatch,
106 kIsolatedOriginStatusMax,
109 } // namespace
111 class ObfuscatedFileEnumerator
112 : public FileSystemFileUtil::AbstractFileEnumerator {
113 public:
114 ObfuscatedFileEnumerator(
115 SandboxDirectoryDatabase* db,
116 FileSystemOperationContext* context,
117 ObfuscatedFileUtil* obfuscated_file_util,
118 const FileSystemURL& root_url,
119 bool recursive)
120 : db_(db),
121 context_(context),
122 obfuscated_file_util_(obfuscated_file_util),
123 root_url_(root_url),
124 recursive_(recursive),
125 current_file_id_(0) {
126 base::FilePath root_virtual_path = root_url.path();
127 FileId file_id;
129 if (!db_->GetFileWithPath(root_virtual_path, &file_id))
130 return;
132 FileRecord record = { file_id, root_virtual_path };
133 recurse_queue_.push(record);
136 ~ObfuscatedFileEnumerator() override {}
138 base::FilePath Next() override {
139 ProcessRecurseQueue();
140 if (display_stack_.empty())
141 return base::FilePath();
143 current_file_id_ = display_stack_.back();
144 display_stack_.pop_back();
146 FileInfo file_info;
147 base::FilePath platform_file_path;
148 base::File::Error error =
149 obfuscated_file_util_->GetFileInfoInternal(
150 db_, context_, root_url_, current_file_id_,
151 &file_info, &current_platform_file_info_, &platform_file_path);
152 if (error != base::File::FILE_OK)
153 return Next();
155 base::FilePath virtual_path =
156 current_parent_virtual_path_.Append(file_info.name);
157 if (recursive_ && file_info.is_directory()) {
158 FileRecord record = { current_file_id_, virtual_path };
159 recurse_queue_.push(record);
161 return virtual_path;
164 int64 Size() override { return current_platform_file_info_.size; }
166 base::Time LastModifiedTime() override {
167 return current_platform_file_info_.last_modified;
170 bool IsDirectory() override {
171 return current_platform_file_info_.is_directory;
174 private:
175 typedef SandboxDirectoryDatabase::FileId FileId;
176 typedef SandboxDirectoryDatabase::FileInfo FileInfo;
178 struct FileRecord {
179 FileId file_id;
180 base::FilePath virtual_path;
183 void ProcessRecurseQueue() {
184 while (display_stack_.empty() && !recurse_queue_.empty()) {
185 FileRecord entry = recurse_queue_.front();
186 recurse_queue_.pop();
187 if (!db_->ListChildren(entry.file_id, &display_stack_)) {
188 display_stack_.clear();
189 return;
191 current_parent_virtual_path_ = entry.virtual_path;
195 SandboxDirectoryDatabase* db_;
196 FileSystemOperationContext* context_;
197 ObfuscatedFileUtil* obfuscated_file_util_;
198 FileSystemURL root_url_;
199 bool recursive_;
201 std::queue<FileRecord> recurse_queue_;
202 std::vector<FileId> display_stack_;
203 base::FilePath current_parent_virtual_path_;
205 FileId current_file_id_;
206 base::File::Info current_platform_file_info_;
209 class ObfuscatedOriginEnumerator
210 : public ObfuscatedFileUtil::AbstractOriginEnumerator {
211 public:
212 typedef SandboxOriginDatabase::OriginRecord OriginRecord;
213 ObfuscatedOriginEnumerator(
214 SandboxOriginDatabaseInterface* origin_database,
215 const base::FilePath& base_file_path)
216 : base_file_path_(base_file_path) {
217 if (origin_database)
218 origin_database->ListAllOrigins(&origins_);
221 ~ObfuscatedOriginEnumerator() override {}
223 // Returns the next origin. Returns empty if there are no more origins.
224 GURL Next() override {
225 OriginRecord record;
226 if (!origins_.empty()) {
227 record = origins_.back();
228 origins_.pop_back();
230 current_ = record;
231 return storage::GetOriginFromIdentifier(record.origin);
234 // Returns the current origin's information.
235 bool HasTypeDirectory(const std::string& type_string) const override {
236 if (current_.path.empty())
237 return false;
238 if (type_string.empty()) {
239 NOTREACHED();
240 return false;
242 base::FilePath path =
243 base_file_path_.Append(current_.path).AppendASCII(type_string);
244 return base::DirectoryExists(path);
247 private:
248 std::vector<OriginRecord> origins_;
249 OriginRecord current_;
250 base::FilePath base_file_path_;
253 ObfuscatedFileUtil::ObfuscatedFileUtil(
254 storage::SpecialStoragePolicy* special_storage_policy,
255 const base::FilePath& file_system_directory,
256 leveldb::Env* env_override,
257 base::SequencedTaskRunner* file_task_runner,
258 const GetTypeStringForURLCallback& get_type_string_for_url,
259 const std::set<std::string>& known_type_strings,
260 SandboxFileSystemBackendDelegate* sandbox_delegate)
261 : special_storage_policy_(special_storage_policy),
262 file_system_directory_(file_system_directory),
263 env_override_(env_override),
264 db_flush_delay_seconds_(10 * 60), // 10 mins.
265 file_task_runner_(file_task_runner),
266 get_type_string_for_url_(get_type_string_for_url),
267 known_type_strings_(known_type_strings),
268 sandbox_delegate_(sandbox_delegate) {
271 ObfuscatedFileUtil::~ObfuscatedFileUtil() {
272 DropDatabases();
275 base::File ObfuscatedFileUtil::CreateOrOpen(
276 FileSystemOperationContext* context,
277 const FileSystemURL& url, int file_flags) {
278 base::File file = CreateOrOpenInternal(context, url, file_flags);
279 if (file.IsValid() && file_flags & base::File::FLAG_WRITE &&
280 context->quota_limit_type() == storage::kQuotaLimitTypeUnlimited &&
281 sandbox_delegate_) {
282 sandbox_delegate_->StickyInvalidateUsageCache(url.origin(), url.type());
284 return file.Pass();
287 base::File::Error ObfuscatedFileUtil::EnsureFileExists(
288 FileSystemOperationContext* context,
289 const FileSystemURL& url,
290 bool* created) {
291 SandboxDirectoryDatabase* db = GetDirectoryDatabase(url, true);
292 if (!db)
293 return base::File::FILE_ERROR_FAILED;
295 FileId file_id;
296 if (db->GetFileWithPath(url.path(), &file_id)) {
297 FileInfo file_info;
298 if (!db->GetFileInfo(file_id, &file_info)) {
299 NOTREACHED();
300 return base::File::FILE_ERROR_FAILED;
302 if (file_info.is_directory())
303 return base::File::FILE_ERROR_NOT_A_FILE;
304 if (created)
305 *created = false;
306 return base::File::FILE_OK;
308 FileId parent_id;
309 if (!db->GetFileWithPath(VirtualPath::DirName(url.path()), &parent_id))
310 return base::File::FILE_ERROR_NOT_FOUND;
312 FileInfo file_info;
313 InitFileInfo(&file_info, parent_id,
314 VirtualPath::BaseName(url.path()).value());
316 int64 growth = UsageForPath(file_info.name.size());
317 if (!AllocateQuota(context, growth))
318 return base::File::FILE_ERROR_NO_SPACE;
319 base::File::Error error = CreateFile(context, base::FilePath(), url,
320 &file_info);
321 if (created && base::File::FILE_OK == error) {
322 *created = true;
323 UpdateUsage(context, url, growth);
324 context->change_observers()->Notify(
325 &FileChangeObserver::OnCreateFile, MakeTuple(url));
327 return error;
330 base::File::Error ObfuscatedFileUtil::CreateDirectory(
331 FileSystemOperationContext* context,
332 const FileSystemURL& url,
333 bool exclusive,
334 bool recursive) {
335 SandboxDirectoryDatabase* db = GetDirectoryDatabase(url, true);
336 if (!db)
337 return base::File::FILE_ERROR_FAILED;
339 FileId file_id;
340 if (db->GetFileWithPath(url.path(), &file_id)) {
341 FileInfo file_info;
342 if (exclusive)
343 return base::File::FILE_ERROR_EXISTS;
344 if (!db->GetFileInfo(file_id, &file_info)) {
345 NOTREACHED();
346 return base::File::FILE_ERROR_FAILED;
348 if (!file_info.is_directory())
349 return base::File::FILE_ERROR_NOT_A_DIRECTORY;
350 return base::File::FILE_OK;
353 std::vector<base::FilePath::StringType> components;
354 VirtualPath::GetComponents(url.path(), &components);
355 FileId parent_id = 0;
356 size_t index;
357 for (index = 0; index < components.size(); ++index) {
358 base::FilePath::StringType name = components[index];
359 if (name == FILE_PATH_LITERAL("/"))
360 continue;
361 if (!db->GetChildWithName(parent_id, name, &parent_id))
362 break;
364 if (!db->IsDirectory(parent_id))
365 return base::File::FILE_ERROR_NOT_A_DIRECTORY;
366 if (!recursive && components.size() - index > 1)
367 return base::File::FILE_ERROR_NOT_FOUND;
368 bool first = true;
369 for (; index < components.size(); ++index) {
370 FileInfo file_info;
371 file_info.name = components[index];
372 if (file_info.name == FILE_PATH_LITERAL("/"))
373 continue;
374 file_info.modification_time = base::Time::Now();
375 file_info.parent_id = parent_id;
376 int64 growth = UsageForPath(file_info.name.size());
377 if (!AllocateQuota(context, growth))
378 return base::File::FILE_ERROR_NO_SPACE;
379 base::File::Error error = db->AddFileInfo(file_info, &parent_id);
380 if (error != base::File::FILE_OK)
381 return error;
382 UpdateUsage(context, url, growth);
383 context->change_observers()->Notify(
384 &FileChangeObserver::OnCreateDirectory, MakeTuple(url));
385 if (first) {
386 first = false;
387 TouchDirectory(db, file_info.parent_id);
390 return base::File::FILE_OK;
393 base::File::Error ObfuscatedFileUtil::GetFileInfo(
394 FileSystemOperationContext* context,
395 const FileSystemURL& url,
396 base::File::Info* file_info,
397 base::FilePath* platform_file_path) {
398 SandboxDirectoryDatabase* db = GetDirectoryDatabase(url, false);
399 if (!db)
400 return base::File::FILE_ERROR_NOT_FOUND;
401 FileId file_id;
402 if (!db->GetFileWithPath(url.path(), &file_id))
403 return base::File::FILE_ERROR_NOT_FOUND;
404 FileInfo local_info;
405 return GetFileInfoInternal(db, context, url,
406 file_id, &local_info,
407 file_info, platform_file_path);
410 scoped_ptr<FileSystemFileUtil::AbstractFileEnumerator>
411 ObfuscatedFileUtil::CreateFileEnumerator(
412 FileSystemOperationContext* context,
413 const FileSystemURL& root_url) {
414 return CreateFileEnumerator(context, root_url, false /* recursive */);
417 base::File::Error ObfuscatedFileUtil::GetLocalFilePath(
418 FileSystemOperationContext* context,
419 const FileSystemURL& url,
420 base::FilePath* local_path) {
421 SandboxDirectoryDatabase* db = GetDirectoryDatabase(url, false);
422 if (!db)
423 return base::File::FILE_ERROR_NOT_FOUND;
424 FileId file_id;
425 if (!db->GetFileWithPath(url.path(), &file_id))
426 return base::File::FILE_ERROR_NOT_FOUND;
427 FileInfo file_info;
428 if (!db->GetFileInfo(file_id, &file_info) || file_info.is_directory()) {
429 NOTREACHED();
430 // Directories have no local file path.
431 return base::File::FILE_ERROR_NOT_FOUND;
433 *local_path = DataPathToLocalPath(url, file_info.data_path);
435 if (local_path->empty())
436 return base::File::FILE_ERROR_NOT_FOUND;
437 return base::File::FILE_OK;
440 base::File::Error ObfuscatedFileUtil::Touch(
441 FileSystemOperationContext* context,
442 const FileSystemURL& url,
443 const base::Time& last_access_time,
444 const base::Time& last_modified_time) {
445 SandboxDirectoryDatabase* db = GetDirectoryDatabase(url, false);
446 if (!db)
447 return base::File::FILE_ERROR_NOT_FOUND;
448 FileId file_id;
449 if (!db->GetFileWithPath(url.path(), &file_id))
450 return base::File::FILE_ERROR_NOT_FOUND;
452 FileInfo file_info;
453 if (!db->GetFileInfo(file_id, &file_info)) {
454 NOTREACHED();
455 return base::File::FILE_ERROR_FAILED;
457 if (file_info.is_directory()) {
458 if (!db->UpdateModificationTime(file_id, last_modified_time))
459 return base::File::FILE_ERROR_FAILED;
460 return base::File::FILE_OK;
462 return NativeFileUtil::Touch(
463 DataPathToLocalPath(url, file_info.data_path),
464 last_access_time, last_modified_time);
467 base::File::Error ObfuscatedFileUtil::Truncate(
468 FileSystemOperationContext* context,
469 const FileSystemURL& url,
470 int64 length) {
471 base::File::Info file_info;
472 base::FilePath local_path;
473 base::File::Error error =
474 GetFileInfo(context, url, &file_info, &local_path);
475 if (error != base::File::FILE_OK)
476 return error;
478 int64 growth = length - file_info.size;
479 if (!AllocateQuota(context, growth))
480 return base::File::FILE_ERROR_NO_SPACE;
481 error = NativeFileUtil::Truncate(local_path, length);
482 if (error == base::File::FILE_OK) {
483 UpdateUsage(context, url, growth);
484 context->change_observers()->Notify(
485 &FileChangeObserver::OnModifyFile, MakeTuple(url));
487 return error;
490 base::File::Error ObfuscatedFileUtil::CopyOrMoveFile(
491 FileSystemOperationContext* context,
492 const FileSystemURL& src_url,
493 const FileSystemURL& dest_url,
494 CopyOrMoveOption option,
495 bool copy) {
496 // Cross-filesystem copies and moves should be handled via CopyInForeignFile.
497 DCHECK(src_url.origin() == dest_url.origin());
498 DCHECK(src_url.type() == dest_url.type());
500 SandboxDirectoryDatabase* db = GetDirectoryDatabase(src_url, true);
501 if (!db)
502 return base::File::FILE_ERROR_FAILED;
504 FileId src_file_id;
505 if (!db->GetFileWithPath(src_url.path(), &src_file_id))
506 return base::File::FILE_ERROR_NOT_FOUND;
508 FileId dest_file_id;
509 bool overwrite = db->GetFileWithPath(dest_url.path(),
510 &dest_file_id);
512 FileInfo src_file_info;
513 base::File::Info src_platform_file_info;
514 base::FilePath src_local_path;
515 base::File::Error error = GetFileInfoInternal(
516 db, context, src_url, src_file_id,
517 &src_file_info, &src_platform_file_info, &src_local_path);
518 if (error != base::File::FILE_OK)
519 return error;
520 if (src_file_info.is_directory())
521 return base::File::FILE_ERROR_NOT_A_FILE;
523 FileInfo dest_file_info;
524 base::File::Info dest_platform_file_info; // overwrite case only
525 base::FilePath dest_local_path; // overwrite case only
526 if (overwrite) {
527 base::File::Error error = GetFileInfoInternal(
528 db, context, dest_url, dest_file_id,
529 &dest_file_info, &dest_platform_file_info, &dest_local_path);
530 if (error == base::File::FILE_ERROR_NOT_FOUND)
531 overwrite = false; // fallback to non-overwrite case
532 else if (error != base::File::FILE_OK)
533 return error;
534 else if (dest_file_info.is_directory())
535 return base::File::FILE_ERROR_INVALID_OPERATION;
537 if (!overwrite) {
538 FileId dest_parent_id;
539 if (!db->GetFileWithPath(VirtualPath::DirName(dest_url.path()),
540 &dest_parent_id)) {
541 return base::File::FILE_ERROR_NOT_FOUND;
544 dest_file_info = src_file_info;
545 dest_file_info.parent_id = dest_parent_id;
546 dest_file_info.name =
547 VirtualPath::BaseName(dest_url.path()).value();
550 int64 growth = 0;
551 if (copy)
552 growth += src_platform_file_info.size;
553 else
554 growth -= UsageForPath(src_file_info.name.size());
555 if (overwrite)
556 growth -= dest_platform_file_info.size;
557 else
558 growth += UsageForPath(dest_file_info.name.size());
559 if (!AllocateQuota(context, growth))
560 return base::File::FILE_ERROR_NO_SPACE;
563 * Copy-with-overwrite
564 * Just overwrite data file
565 * Copy-without-overwrite
566 * Copy backing file
567 * Create new metadata pointing to new backing file.
568 * Move-with-overwrite
569 * transaction:
570 * Remove source entry.
571 * Point target entry to source entry's backing file.
572 * Delete target entry's old backing file
573 * Move-without-overwrite
574 * Just update metadata
576 error = base::File::FILE_ERROR_FAILED;
577 if (copy) {
578 if (overwrite) {
579 error = NativeFileUtil::CopyOrMoveFile(
580 src_local_path,
581 dest_local_path,
582 option,
583 storage::NativeFileUtil::CopyOrMoveModeForDestination(
584 dest_url, true /* copy */));
585 } else { // non-overwrite
586 error = CreateFile(context, src_local_path, dest_url, &dest_file_info);
588 } else {
589 if (overwrite) {
590 if (db->OverwritingMoveFile(src_file_id, dest_file_id)) {
591 if (base::File::FILE_OK !=
592 NativeFileUtil::DeleteFile(dest_local_path))
593 LOG(WARNING) << "Leaked a backing file.";
594 error = base::File::FILE_OK;
595 } else {
596 error = base::File::FILE_ERROR_FAILED;
598 } else { // non-overwrite
599 if (db->UpdateFileInfo(src_file_id, dest_file_info))
600 error = base::File::FILE_OK;
601 else
602 error = base::File::FILE_ERROR_FAILED;
606 if (error != base::File::FILE_OK)
607 return error;
609 if (overwrite) {
610 context->change_observers()->Notify(
611 &FileChangeObserver::OnModifyFile,
612 MakeTuple(dest_url));
613 } else {
614 context->change_observers()->Notify(
615 &FileChangeObserver::OnCreateFileFrom,
616 MakeTuple(dest_url, src_url));
619 if (!copy) {
620 context->change_observers()->Notify(
621 &FileChangeObserver::OnRemoveFile, MakeTuple(src_url));
622 TouchDirectory(db, src_file_info.parent_id);
625 TouchDirectory(db, dest_file_info.parent_id);
627 UpdateUsage(context, dest_url, growth);
628 return error;
631 base::File::Error ObfuscatedFileUtil::CopyInForeignFile(
632 FileSystemOperationContext* context,
633 const base::FilePath& src_file_path,
634 const FileSystemURL& dest_url) {
635 SandboxDirectoryDatabase* db = GetDirectoryDatabase(dest_url, true);
636 if (!db)
637 return base::File::FILE_ERROR_FAILED;
639 base::File::Info src_platform_file_info;
640 if (!base::GetFileInfo(src_file_path, &src_platform_file_info))
641 return base::File::FILE_ERROR_NOT_FOUND;
643 FileId dest_file_id;
644 bool overwrite = db->GetFileWithPath(dest_url.path(),
645 &dest_file_id);
647 FileInfo dest_file_info;
648 base::File::Info dest_platform_file_info; // overwrite case only
649 if (overwrite) {
650 base::FilePath dest_local_path;
651 base::File::Error error = GetFileInfoInternal(
652 db, context, dest_url, dest_file_id,
653 &dest_file_info, &dest_platform_file_info, &dest_local_path);
654 if (error == base::File::FILE_ERROR_NOT_FOUND)
655 overwrite = false; // fallback to non-overwrite case
656 else if (error != base::File::FILE_OK)
657 return error;
658 else if (dest_file_info.is_directory())
659 return base::File::FILE_ERROR_INVALID_OPERATION;
661 if (!overwrite) {
662 FileId dest_parent_id;
663 if (!db->GetFileWithPath(VirtualPath::DirName(dest_url.path()),
664 &dest_parent_id)) {
665 return base::File::FILE_ERROR_NOT_FOUND;
667 if (!dest_file_info.is_directory())
668 return base::File::FILE_ERROR_FAILED;
669 InitFileInfo(&dest_file_info, dest_parent_id,
670 VirtualPath::BaseName(dest_url.path()).value());
673 int64 growth = src_platform_file_info.size;
674 if (overwrite)
675 growth -= dest_platform_file_info.size;
676 else
677 growth += UsageForPath(dest_file_info.name.size());
678 if (!AllocateQuota(context, growth))
679 return base::File::FILE_ERROR_NO_SPACE;
681 base::File::Error error;
682 if (overwrite) {
683 base::FilePath dest_local_path =
684 DataPathToLocalPath(dest_url, dest_file_info.data_path);
685 error = NativeFileUtil::CopyOrMoveFile(
686 src_file_path,
687 dest_local_path,
688 FileSystemOperation::OPTION_NONE,
689 storage::NativeFileUtil::CopyOrMoveModeForDestination(dest_url,
690 true /* copy */));
691 } else {
692 error = CreateFile(context, src_file_path, dest_url, &dest_file_info);
695 if (error != base::File::FILE_OK)
696 return error;
698 if (overwrite) {
699 context->change_observers()->Notify(
700 &FileChangeObserver::OnModifyFile, MakeTuple(dest_url));
701 } else {
702 context->change_observers()->Notify(
703 &FileChangeObserver::OnCreateFile, MakeTuple(dest_url));
706 UpdateUsage(context, dest_url, growth);
707 TouchDirectory(db, dest_file_info.parent_id);
708 return base::File::FILE_OK;
711 base::File::Error ObfuscatedFileUtil::DeleteFile(
712 FileSystemOperationContext* context,
713 const FileSystemURL& url) {
714 SandboxDirectoryDatabase* db = GetDirectoryDatabase(url, true);
715 if (!db)
716 return base::File::FILE_ERROR_FAILED;
717 FileId file_id;
718 if (!db->GetFileWithPath(url.path(), &file_id))
719 return base::File::FILE_ERROR_NOT_FOUND;
721 FileInfo file_info;
722 base::File::Info platform_file_info;
723 base::FilePath local_path;
724 base::File::Error error = GetFileInfoInternal(
725 db, context, url, file_id, &file_info, &platform_file_info, &local_path);
726 if (error != base::File::FILE_ERROR_NOT_FOUND &&
727 error != base::File::FILE_OK)
728 return error;
730 if (file_info.is_directory())
731 return base::File::FILE_ERROR_NOT_A_FILE;
733 int64 growth = -UsageForPath(file_info.name.size()) - platform_file_info.size;
734 AllocateQuota(context, growth);
735 if (!db->RemoveFileInfo(file_id)) {
736 NOTREACHED();
737 return base::File::FILE_ERROR_FAILED;
739 UpdateUsage(context, url, growth);
740 TouchDirectory(db, file_info.parent_id);
742 context->change_observers()->Notify(
743 &FileChangeObserver::OnRemoveFile, MakeTuple(url));
745 if (error == base::File::FILE_ERROR_NOT_FOUND)
746 return base::File::FILE_OK;
748 error = NativeFileUtil::DeleteFile(local_path);
749 if (base::File::FILE_OK != error)
750 LOG(WARNING) << "Leaked a backing file.";
751 return base::File::FILE_OK;
754 base::File::Error ObfuscatedFileUtil::DeleteDirectory(
755 FileSystemOperationContext* context,
756 const FileSystemURL& url) {
757 SandboxDirectoryDatabase* db = GetDirectoryDatabase(url, true);
758 if (!db)
759 return base::File::FILE_ERROR_FAILED;
761 FileId file_id;
762 if (!db->GetFileWithPath(url.path(), &file_id))
763 return base::File::FILE_ERROR_NOT_FOUND;
764 FileInfo file_info;
765 if (!db->GetFileInfo(file_id, &file_info)) {
766 NOTREACHED();
767 return base::File::FILE_ERROR_FAILED;
769 if (!file_info.is_directory())
770 return base::File::FILE_ERROR_NOT_A_DIRECTORY;
771 if (!db->RemoveFileInfo(file_id))
772 return base::File::FILE_ERROR_NOT_EMPTY;
773 int64 growth = -UsageForPath(file_info.name.size());
774 AllocateQuota(context, growth);
775 UpdateUsage(context, url, growth);
776 TouchDirectory(db, file_info.parent_id);
777 context->change_observers()->Notify(
778 &FileChangeObserver::OnRemoveDirectory, MakeTuple(url));
779 return base::File::FILE_OK;
782 storage::ScopedFile ObfuscatedFileUtil::CreateSnapshotFile(
783 FileSystemOperationContext* context,
784 const FileSystemURL& url,
785 base::File::Error* error,
786 base::File::Info* file_info,
787 base::FilePath* platform_path) {
788 // We're just returning the local file information.
789 *error = GetFileInfo(context, url, file_info, platform_path);
790 if (*error == base::File::FILE_OK && file_info->is_directory) {
791 *file_info = base::File::Info();
792 *error = base::File::FILE_ERROR_NOT_A_FILE;
794 return storage::ScopedFile();
797 scoped_ptr<FileSystemFileUtil::AbstractFileEnumerator>
798 ObfuscatedFileUtil::CreateFileEnumerator(
799 FileSystemOperationContext* context,
800 const FileSystemURL& root_url,
801 bool recursive) {
802 SandboxDirectoryDatabase* db = GetDirectoryDatabase(root_url, false);
803 if (!db) {
804 return scoped_ptr<AbstractFileEnumerator>(new EmptyFileEnumerator());
806 return scoped_ptr<AbstractFileEnumerator>(
807 new ObfuscatedFileEnumerator(db, context, this, root_url, recursive));
810 bool ObfuscatedFileUtil::IsDirectoryEmpty(
811 FileSystemOperationContext* context,
812 const FileSystemURL& url) {
813 SandboxDirectoryDatabase* db = GetDirectoryDatabase(url, false);
814 if (!db)
815 return true; // Not a great answer, but it's what others do.
816 FileId file_id;
817 if (!db->GetFileWithPath(url.path(), &file_id))
818 return true; // Ditto.
819 FileInfo file_info;
820 if (!db->GetFileInfo(file_id, &file_info)) {
821 DCHECK(!file_id);
822 // It's the root directory and the database hasn't been initialized yet.
823 return true;
825 if (!file_info.is_directory())
826 return true;
827 std::vector<FileId> children;
828 // TODO(ericu): This could easily be made faster with help from the database.
829 if (!db->ListChildren(file_id, &children))
830 return true;
831 return children.empty();
834 base::FilePath ObfuscatedFileUtil::GetDirectoryForOriginAndType(
835 const GURL& origin,
836 const std::string& type_string,
837 bool create,
838 base::File::Error* error_code) {
839 base::FilePath origin_dir = GetDirectoryForOrigin(origin, create, error_code);
840 if (origin_dir.empty())
841 return base::FilePath();
842 if (type_string.empty())
843 return origin_dir;
844 base::FilePath path = origin_dir.AppendASCII(type_string);
845 base::File::Error error = base::File::FILE_OK;
846 if (!base::DirectoryExists(path) &&
847 (!create || !base::CreateDirectory(path))) {
848 error = create ?
849 base::File::FILE_ERROR_FAILED :
850 base::File::FILE_ERROR_NOT_FOUND;
853 if (error_code)
854 *error_code = error;
855 return path;
858 bool ObfuscatedFileUtil::DeleteDirectoryForOriginAndType(
859 const GURL& origin,
860 const std::string& type_string) {
861 DestroyDirectoryDatabase(origin, type_string);
863 const base::FilePath origin_path = GetDirectoryForOrigin(origin, false, NULL);
864 if (!type_string.empty()) {
865 // Delete the filesystem type directory.
866 base::File::Error error = base::File::FILE_OK;
867 const base::FilePath origin_type_path =
868 GetDirectoryForOriginAndType(origin, type_string, false, &error);
869 if (error == base::File::FILE_ERROR_FAILED)
870 return false;
871 if (error == base::File::FILE_OK &&
872 !origin_type_path.empty() &&
873 !base::DeleteFile(origin_type_path, true /* recursive */)) {
874 return false;
877 // At this point we are sure we had successfully deleted the origin/type
878 // directory (i.e. we're ready to just return true).
879 // See if we have other directories in this origin directory.
880 for (std::set<std::string>::iterator iter = known_type_strings_.begin();
881 iter != known_type_strings_.end();
882 ++iter) {
883 if (*iter == type_string)
884 continue;
885 if (base::DirectoryExists(origin_path.AppendASCII(*iter))) {
886 // Other type's directory exists; just return true here.
887 return true;
892 // No other directories seem exist. Try deleting the entire origin directory.
893 InitOriginDatabase(origin, false);
894 if (origin_database_) {
895 origin_database_->RemovePathForOrigin(
896 storage::GetIdentifierFromOrigin(origin));
898 return base::DeleteFile(origin_path, true /* recursive */);
901 void ObfuscatedFileUtil::CloseFileSystemForOriginAndType(
902 const GURL& origin,
903 const std::string& type_string) {
904 const std::string key_prefix = GetDirectoryDatabaseKey(origin, type_string);
905 for (DirectoryMap::iterator iter = directories_.lower_bound(key_prefix);
906 iter != directories_.end();) {
907 if (!StartsWithASCII(iter->first, key_prefix, true))
908 break;
909 DCHECK(type_string.empty() || iter->first == key_prefix);
910 scoped_ptr<SandboxDirectoryDatabase> database(iter->second);
911 directories_.erase(iter++);
915 ObfuscatedFileUtil::AbstractOriginEnumerator*
916 ObfuscatedFileUtil::CreateOriginEnumerator() {
917 std::vector<SandboxOriginDatabase::OriginRecord> origins;
919 InitOriginDatabase(GURL(), false);
920 return new ObfuscatedOriginEnumerator(
921 origin_database_.get(), file_system_directory_);
924 void ObfuscatedFileUtil::DestroyDirectoryDatabase(
925 const GURL& origin,
926 const std::string& type_string) {
927 // If |type_string| is empty, delete all filesystem types under |origin|.
928 const std::string key_prefix = GetDirectoryDatabaseKey(origin, type_string);
929 for (DirectoryMap::iterator iter = directories_.lower_bound(key_prefix);
930 iter != directories_.end();) {
931 if (!StartsWithASCII(iter->first, key_prefix, true))
932 break;
933 DCHECK(type_string.empty() || iter->first == key_prefix);
934 scoped_ptr<SandboxDirectoryDatabase> database(iter->second);
935 directories_.erase(iter++);
937 // Continue to destroy databases even if it failed because it doesn't affect
938 // the final result.
939 database->DestroyDatabase();
943 // static
944 int64 ObfuscatedFileUtil::ComputeFilePathCost(const base::FilePath& path) {
945 return UsageForPath(VirtualPath::BaseName(path).value().size());
948 void ObfuscatedFileUtil::MaybePrepopulateDatabase(
949 const std::vector<std::string>& type_strings_to_prepopulate) {
950 SandboxPrioritizedOriginDatabase database(file_system_directory_,
951 env_override_);
952 std::string origin_string = database.GetPrimaryOrigin();
953 if (origin_string.empty() || !database.HasOriginPath(origin_string))
954 return;
955 const GURL origin = storage::GetOriginFromIdentifier(origin_string);
957 // Prepopulate the directory database(s) if and only if this instance
958 // has primary origin and the directory database is already there.
959 for (size_t i = 0; i < type_strings_to_prepopulate.size(); ++i) {
960 const std::string type_string = type_strings_to_prepopulate[i];
961 // Only handles known types.
962 if (!ContainsKey(known_type_strings_, type_string))
963 continue;
964 base::File::Error error = base::File::FILE_ERROR_FAILED;
965 base::FilePath path = GetDirectoryForOriginAndType(
966 origin, type_string, false, &error);
967 if (error != base::File::FILE_OK)
968 continue;
969 scoped_ptr<SandboxDirectoryDatabase> db(
970 new SandboxDirectoryDatabase(path, env_override_));
971 if (db->Init(SandboxDirectoryDatabase::FAIL_ON_CORRUPTION)) {
972 directories_[GetDirectoryDatabaseKey(origin, type_string)] = db.release();
973 MarkUsed();
974 // Don't populate more than one database, as it may rather hurt
975 // performance.
976 break;
981 base::FilePath ObfuscatedFileUtil::GetDirectoryForURL(
982 const FileSystemURL& url,
983 bool create,
984 base::File::Error* error_code) {
985 return GetDirectoryForOriginAndType(
986 url.origin(), CallGetTypeStringForURL(url), create, error_code);
989 std::string ObfuscatedFileUtil::CallGetTypeStringForURL(
990 const FileSystemURL& url) {
991 DCHECK(!get_type_string_for_url_.is_null());
992 return get_type_string_for_url_.Run(url);
995 base::File::Error ObfuscatedFileUtil::GetFileInfoInternal(
996 SandboxDirectoryDatabase* db,
997 FileSystemOperationContext* context,
998 const FileSystemURL& url,
999 FileId file_id,
1000 FileInfo* local_info,
1001 base::File::Info* file_info,
1002 base::FilePath* platform_file_path) {
1003 DCHECK(db);
1004 DCHECK(context);
1005 DCHECK(file_info);
1006 DCHECK(platform_file_path);
1008 if (!db->GetFileInfo(file_id, local_info)) {
1009 NOTREACHED();
1010 return base::File::FILE_ERROR_FAILED;
1013 if (local_info->is_directory()) {
1014 file_info->size = 0;
1015 file_info->is_directory = true;
1016 file_info->is_symbolic_link = false;
1017 file_info->last_modified = local_info->modification_time;
1018 *platform_file_path = base::FilePath();
1019 // We don't fill in ctime or atime.
1020 return base::File::FILE_OK;
1022 if (local_info->data_path.empty())
1023 return base::File::FILE_ERROR_INVALID_OPERATION;
1024 base::FilePath local_path = DataPathToLocalPath(url, local_info->data_path);
1025 base::File::Error error = NativeFileUtil::GetFileInfo(
1026 local_path, file_info);
1027 // We should not follow symbolic links in sandboxed file system.
1028 if (base::IsLink(local_path)) {
1029 LOG(WARNING) << "Found a symbolic file.";
1030 error = base::File::FILE_ERROR_NOT_FOUND;
1032 if (error == base::File::FILE_OK) {
1033 *platform_file_path = local_path;
1034 } else if (error == base::File::FILE_ERROR_NOT_FOUND) {
1035 LOG(WARNING) << "Lost a backing file.";
1036 InvalidateUsageCache(context, url.origin(), url.type());
1037 if (!db->RemoveFileInfo(file_id))
1038 return base::File::FILE_ERROR_FAILED;
1040 return error;
1043 base::File ObfuscatedFileUtil::CreateAndOpenFile(
1044 FileSystemOperationContext* context,
1045 const FileSystemURL& dest_url,
1046 FileInfo* dest_file_info, int file_flags) {
1047 SandboxDirectoryDatabase* db = GetDirectoryDatabase(dest_url, true);
1049 base::FilePath root, dest_local_path;
1050 base::File::Error error = GenerateNewLocalPath(db, context, dest_url, &root,
1051 &dest_local_path);
1052 if (error != base::File::FILE_OK)
1053 return base::File(error);
1055 if (base::PathExists(dest_local_path)) {
1056 if (!base::DeleteFile(dest_local_path, true /* recursive */))
1057 return base::File(base::File::FILE_ERROR_FAILED);
1058 LOG(WARNING) << "A stray file detected";
1059 InvalidateUsageCache(context, dest_url.origin(), dest_url.type());
1062 base::File file = NativeFileUtil::CreateOrOpen(dest_local_path, file_flags);
1063 if (!file.IsValid())
1064 return file.Pass();
1066 if (!file.created()) {
1067 file.Close();
1068 base::DeleteFile(dest_local_path, false /* recursive */);
1069 return base::File(base::File::FILE_ERROR_FAILED);
1072 error = CommitCreateFile(root, dest_local_path, db, dest_file_info);
1073 if (error != base::File::FILE_OK) {
1074 file.Close();
1075 base::DeleteFile(dest_local_path, false /* recursive */);
1076 return base::File(error);
1079 return file.Pass();
1082 base::File::Error ObfuscatedFileUtil::CreateFile(
1083 FileSystemOperationContext* context,
1084 const base::FilePath& src_file_path,
1085 const FileSystemURL& dest_url,
1086 FileInfo* dest_file_info) {
1087 SandboxDirectoryDatabase* db = GetDirectoryDatabase(dest_url, true);
1089 base::FilePath root, dest_local_path;
1090 base::File::Error error = GenerateNewLocalPath(db, context, dest_url, &root,
1091 &dest_local_path);
1092 if (error != base::File::FILE_OK)
1093 return error;
1095 bool created = false;
1096 if (src_file_path.empty()) {
1097 if (base::PathExists(dest_local_path)) {
1098 if (!base::DeleteFile(dest_local_path, true /* recursive */))
1099 return base::File::FILE_ERROR_FAILED;
1100 LOG(WARNING) << "A stray file detected";
1101 InvalidateUsageCache(context, dest_url.origin(), dest_url.type());
1104 error = NativeFileUtil::EnsureFileExists(dest_local_path, &created);
1105 } else {
1106 error = NativeFileUtil::CopyOrMoveFile(
1107 src_file_path,
1108 dest_local_path,
1109 FileSystemOperation::OPTION_NONE,
1110 storage::NativeFileUtil::CopyOrMoveModeForDestination(dest_url,
1111 true /* copy */));
1112 created = true;
1114 if (error != base::File::FILE_OK)
1115 return error;
1116 if (!created)
1117 return base::File::FILE_ERROR_FAILED;
1119 return CommitCreateFile(root, dest_local_path, db, dest_file_info);
1122 base::File::Error ObfuscatedFileUtil::CommitCreateFile(
1123 const base::FilePath& root,
1124 const base::FilePath& local_path,
1125 SandboxDirectoryDatabase* db,
1126 FileInfo* dest_file_info) {
1127 // This removes the root, including the trailing slash, leaving a relative
1128 // path.
1129 dest_file_info->data_path = base::FilePath(
1130 local_path.value().substr(root.value().length() + 1));
1132 FileId file_id;
1133 base::File::Error error = db->AddFileInfo(*dest_file_info, &file_id);
1134 if (error != base::File::FILE_OK)
1135 return error;
1137 TouchDirectory(db, dest_file_info->parent_id);
1138 return base::File::FILE_OK;
1141 base::FilePath ObfuscatedFileUtil::DataPathToLocalPath(
1142 const FileSystemURL& url, const base::FilePath& data_path) {
1143 base::File::Error error = base::File::FILE_OK;
1144 base::FilePath root = GetDirectoryForURL(url, false, &error);
1145 if (error != base::File::FILE_OK)
1146 return base::FilePath();
1147 return root.Append(data_path);
1150 std::string ObfuscatedFileUtil::GetDirectoryDatabaseKey(
1151 const GURL& origin, const std::string& type_string) {
1152 // For isolated origin we just use a type string as a key.
1153 return storage::GetIdentifierFromOrigin(origin) +
1154 kDirectoryDatabaseKeySeparator + type_string;
1157 // TODO(ericu): How to do the whole validation-without-creation thing?
1158 // We may not have quota even to create the database.
1159 // Ah, in that case don't even get here?
1160 // Still doesn't answer the quota issue, though.
1161 SandboxDirectoryDatabase* ObfuscatedFileUtil::GetDirectoryDatabase(
1162 const FileSystemURL& url, bool create) {
1163 std::string key = GetDirectoryDatabaseKey(
1164 url.origin(), CallGetTypeStringForURL(url));
1165 if (key.empty())
1166 return NULL;
1168 DirectoryMap::iterator iter = directories_.find(key);
1169 if (iter != directories_.end()) {
1170 MarkUsed();
1171 return iter->second;
1174 base::File::Error error = base::File::FILE_OK;
1175 base::FilePath path = GetDirectoryForURL(url, create, &error);
1176 if (error != base::File::FILE_OK) {
1177 LOG(WARNING) << "Failed to get origin+type directory: "
1178 << url.DebugString() << " error:" << error;
1179 return NULL;
1181 MarkUsed();
1182 SandboxDirectoryDatabase* database =
1183 new SandboxDirectoryDatabase(path, env_override_);
1184 directories_[key] = database;
1185 return database;
1188 base::FilePath ObfuscatedFileUtil::GetDirectoryForOrigin(
1189 const GURL& origin, bool create, base::File::Error* error_code) {
1190 if (!InitOriginDatabase(origin, create)) {
1191 if (error_code) {
1192 *error_code = create ?
1193 base::File::FILE_ERROR_FAILED :
1194 base::File::FILE_ERROR_NOT_FOUND;
1196 return base::FilePath();
1198 base::FilePath directory_name;
1199 std::string id = storage::GetIdentifierFromOrigin(origin);
1201 bool exists_in_db = origin_database_->HasOriginPath(id);
1202 if (!exists_in_db && !create) {
1203 if (error_code)
1204 *error_code = base::File::FILE_ERROR_NOT_FOUND;
1205 return base::FilePath();
1207 if (!origin_database_->GetPathForOrigin(id, &directory_name)) {
1208 if (error_code)
1209 *error_code = base::File::FILE_ERROR_FAILED;
1210 return base::FilePath();
1213 base::FilePath path = file_system_directory_.Append(directory_name);
1214 bool exists_in_fs = base::DirectoryExists(path);
1215 if (!exists_in_db && exists_in_fs) {
1216 if (!base::DeleteFile(path, true)) {
1217 if (error_code)
1218 *error_code = base::File::FILE_ERROR_FAILED;
1219 return base::FilePath();
1221 exists_in_fs = false;
1224 if (!exists_in_fs) {
1225 if (!create || !base::CreateDirectory(path)) {
1226 if (error_code)
1227 *error_code = create ?
1228 base::File::FILE_ERROR_FAILED :
1229 base::File::FILE_ERROR_NOT_FOUND;
1230 return base::FilePath();
1234 if (error_code)
1235 *error_code = base::File::FILE_OK;
1237 return path;
1240 void ObfuscatedFileUtil::InvalidateUsageCache(
1241 FileSystemOperationContext* context,
1242 const GURL& origin,
1243 FileSystemType type) {
1244 if (sandbox_delegate_)
1245 sandbox_delegate_->InvalidateUsageCache(origin, type);
1248 void ObfuscatedFileUtil::MarkUsed() {
1249 if (!timer_)
1250 timer_.reset(new TimedTaskHelper(file_task_runner_.get()));
1252 if (timer_->IsRunning()) {
1253 timer_->Reset();
1254 } else {
1255 timer_->Start(FROM_HERE,
1256 base::TimeDelta::FromSeconds(db_flush_delay_seconds_),
1257 base::Bind(&ObfuscatedFileUtil::DropDatabases,
1258 base::Unretained(this)));
1262 void ObfuscatedFileUtil::DropDatabases() {
1263 origin_database_.reset();
1264 STLDeleteContainerPairSecondPointers(
1265 directories_.begin(), directories_.end());
1266 directories_.clear();
1267 timer_.reset();
1270 bool ObfuscatedFileUtil::InitOriginDatabase(const GURL& origin_hint,
1271 bool create) {
1272 if (origin_database_)
1273 return true;
1275 if (!create && !base::DirectoryExists(file_system_directory_))
1276 return false;
1277 if (!base::CreateDirectory(file_system_directory_)) {
1278 LOG(WARNING) << "Failed to create FileSystem directory: " <<
1279 file_system_directory_.value();
1280 return false;
1283 SandboxPrioritizedOriginDatabase* prioritized_origin_database =
1284 new SandboxPrioritizedOriginDatabase(file_system_directory_,
1285 env_override_);
1286 origin_database_.reset(prioritized_origin_database);
1288 if (origin_hint.is_empty() || !HasIsolatedStorage(origin_hint))
1289 return true;
1291 const std::string isolated_origin_string =
1292 storage::GetIdentifierFromOrigin(origin_hint);
1294 // TODO(kinuko): Deprecate this after a few release cycles, e.g. around M33.
1295 base::FilePath isolated_origin_dir = file_system_directory_.Append(
1296 SandboxIsolatedOriginDatabase::kObsoleteOriginDirectory);
1297 if (base::DirectoryExists(isolated_origin_dir) &&
1298 prioritized_origin_database->GetSandboxOriginDatabase()) {
1299 SandboxIsolatedOriginDatabase::MigrateBackFromObsoleteOriginDatabase(
1300 isolated_origin_string,
1301 file_system_directory_,
1302 prioritized_origin_database->GetSandboxOriginDatabase());
1305 prioritized_origin_database->InitializePrimaryOrigin(
1306 isolated_origin_string);
1308 return true;
1311 base::File::Error ObfuscatedFileUtil::GenerateNewLocalPath(
1312 SandboxDirectoryDatabase* db,
1313 FileSystemOperationContext* context,
1314 const FileSystemURL& url,
1315 base::FilePath* root,
1316 base::FilePath* local_path) {
1317 DCHECK(local_path);
1318 int64 number;
1319 if (!db || !db->GetNextInteger(&number))
1320 return base::File::FILE_ERROR_FAILED;
1322 base::File::Error error = base::File::FILE_OK;
1323 *root = GetDirectoryForURL(url, false, &error);
1324 if (error != base::File::FILE_OK)
1325 return error;
1327 // We use the third- and fourth-to-last digits as the directory.
1328 int64 directory_number = number % 10000 / 100;
1329 base::FilePath new_local_path = root->AppendASCII(
1330 base::StringPrintf("%02" PRId64, directory_number));
1332 error = NativeFileUtil::CreateDirectory(
1333 new_local_path, false /* exclusive */, false /* recursive */);
1334 if (error != base::File::FILE_OK)
1335 return error;
1337 *local_path =
1338 new_local_path.AppendASCII(base::StringPrintf("%08" PRId64, number));
1339 return base::File::FILE_OK;
1342 base::File ObfuscatedFileUtil::CreateOrOpenInternal(
1343 FileSystemOperationContext* context,
1344 const FileSystemURL& url, int file_flags) {
1345 DCHECK(!(file_flags & (base::File::FLAG_DELETE_ON_CLOSE |
1346 base::File::FLAG_HIDDEN | base::File::FLAG_EXCLUSIVE_READ |
1347 base::File::FLAG_EXCLUSIVE_WRITE)));
1348 SandboxDirectoryDatabase* db = GetDirectoryDatabase(url, true);
1349 if (!db)
1350 return base::File(base::File::FILE_ERROR_FAILED);
1351 FileId file_id;
1352 if (!db->GetFileWithPath(url.path(), &file_id)) {
1353 // The file doesn't exist.
1354 if (!(file_flags & (base::File::FLAG_CREATE |
1355 base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_OPEN_ALWAYS))) {
1356 return base::File(base::File::FILE_ERROR_NOT_FOUND);
1358 FileId parent_id;
1359 if (!db->GetFileWithPath(VirtualPath::DirName(url.path()), &parent_id))
1360 return base::File(base::File::FILE_ERROR_NOT_FOUND);
1361 FileInfo file_info;
1362 InitFileInfo(&file_info, parent_id,
1363 VirtualPath::BaseName(url.path()).value());
1365 int64 growth = UsageForPath(file_info.name.size());
1366 if (!AllocateQuota(context, growth))
1367 return base::File(base::File::FILE_ERROR_NO_SPACE);
1368 base::File file = CreateAndOpenFile(context, url, &file_info, file_flags);
1369 if (file.IsValid()) {
1370 UpdateUsage(context, url, growth);
1371 context->change_observers()->Notify(
1372 &FileChangeObserver::OnCreateFile, MakeTuple(url));
1374 return file.Pass();
1377 if (file_flags & base::File::FLAG_CREATE)
1378 return base::File(base::File::FILE_ERROR_EXISTS);
1380 base::File::Info platform_file_info;
1381 base::FilePath local_path;
1382 FileInfo file_info;
1383 base::File::Error error = GetFileInfoInternal(
1384 db, context, url, file_id, &file_info, &platform_file_info, &local_path);
1385 if (error != base::File::FILE_OK)
1386 return base::File(error);
1387 if (file_info.is_directory())
1388 return base::File(base::File::FILE_ERROR_NOT_A_FILE);
1390 int64 delta = 0;
1391 if (file_flags & (base::File::FLAG_CREATE_ALWAYS |
1392 base::File::FLAG_OPEN_TRUNCATED)) {
1393 // The file exists and we're truncating.
1394 delta = -platform_file_info.size;
1395 AllocateQuota(context, delta);
1398 base::File file = NativeFileUtil::CreateOrOpen(local_path, file_flags);
1399 if (!file.IsValid()) {
1400 error = file.error_details();
1401 if (error == base::File::FILE_ERROR_NOT_FOUND) {
1402 // TODO(tzik): Also invalidate on-memory usage cache in UsageTracker.
1403 // TODO(tzik): Delete database entry after ensuring the file lost.
1404 InvalidateUsageCache(context, url.origin(), url.type());
1405 LOG(WARNING) << "Lost a backing file.";
1406 return base::File(base::File::FILE_ERROR_FAILED);
1408 return file.Pass();
1411 // If truncating we need to update the usage.
1412 if (delta) {
1413 UpdateUsage(context, url, delta);
1414 context->change_observers()->Notify(
1415 &FileChangeObserver::OnModifyFile, MakeTuple(url));
1417 return file.Pass();
1420 bool ObfuscatedFileUtil::HasIsolatedStorage(const GURL& origin) {
1421 return special_storage_policy_.get() &&
1422 special_storage_policy_->HasIsolatedStorage(origin);
1425 } // namespace storage