Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(86)

Side by Side Diff: webkit/fileapi/obfuscated_file_util.cc

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

Powered by Google App Engine
This is Rietveld 408576698