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