1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587
|
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "storage/browser/file_system/obfuscated_file_util.h"
#include <stddef.h>
#include <stdint.h>
#include <memory>
#include <tuple>
#include <utility>
#include "base/containers/queue.h"
#include "base/files/file_error_or.h"
#include "base/files/file_util.h"
#include "base/format_macros.h"
#include "base/functional/bind.h"
#include "base/logging.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/metrics/histogram.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/threading/thread_restrictions.h"
#include "base/time/time.h"
#include "base/types/expected_macros.h"
#include "components/services/storage/public/cpp/buckets/bucket_init_params.h"
#include "storage/browser/file_system/file_observers.h"
#include "storage/browser/file_system/file_system_context.h"
#include "storage/browser/file_system/file_system_operation_context.h"
#include "storage/browser/file_system/obfuscated_file_util_disk_delegate.h"
#include "storage/browser/file_system/obfuscated_file_util_memory_delegate.h"
#include "storage/browser/file_system/quota/quota_limit_type.h"
#include "storage/browser/file_system/sandbox_file_system_backend.h"
#include "storage/browser/file_system/sandbox_origin_database.h"
#include "storage/browser/quota/quota_manager.h"
#include "storage/common/database/database_identifier.h"
#include "storage/common/file_system/file_system_types.h"
#include "storage/common/file_system/file_system_util.h"
#include "third_party/blink/public/common/storage_key/storage_key.h"
#include "third_party/leveldatabase/leveldb_chrome.h"
#include "url/gurl.h"
// Example of various paths:
// void ObfuscatedFileUtil::DoSomething(const FileSystemURL& url) {
// base::FilePath virtual_path = url.path();
// base::FilePath local_path = GetLocalFilePath(url);
//
// NativeFileUtil::DoSomething(local_path);
// file_util::DoAnother(local_path);
// }
namespace storage {
namespace {
using FileId = SandboxDirectoryDatabase::FileId;
using FileInfo = SandboxDirectoryDatabase::FileInfo;
void InitFileInfo(SandboxDirectoryDatabase::FileInfo* file_info,
SandboxDirectoryDatabase::FileId parent_id,
const base::FilePath::StringType& file_name) {
DCHECK(file_info);
file_info->parent_id = parent_id;
file_info->name = file_name;
}
// Costs computed as per crbug.com/86114, based on the LevelDB implementation of
// path storage under Linux. It's not clear if that will differ on Windows, on
// which base::FilePath uses wide chars [since they're converted to UTF-8 for
// storage anyway], but as long as the cost is high enough that one can't cheat
// on quota by storing data in paths, it doesn't need to be all that accurate.
const int64_t kPathCreationQuotaCost = 146; // Bytes per inode, basically.
const int64_t kPathByteQuotaCost =
2; // Bytes per byte of path length in UTF-8.
int64_t UsageForPath(size_t length) {
return kPathCreationQuotaCost +
static_cast<int64_t>(length) * kPathByteQuotaCost;
}
bool AllocateQuota(FileSystemOperationContext* context, int64_t growth) {
if (context->allowed_bytes_growth() == QuotaManager::kNoLimit)
return true;
int64_t new_quota = context->allowed_bytes_growth() - growth;
if (growth > 0 && new_quota < 0)
return false;
context->set_allowed_bytes_growth(new_quota);
return true;
}
void UpdateUsage(FileSystemOperationContext* context,
const FileSystemURL& url,
int64_t growth) {
context->update_observers()->Notify(&FileUpdateObserver::OnUpdate, url,
growth);
}
void TouchDirectory(SandboxDirectoryDatabase* db, FileId dir_id) {
DCHECK(db);
if (!db->UpdateModificationTime(dir_id, base::Time::Now()))
NOTREACHED();
}
enum IsolatedOriginStatus {
kIsolatedOriginMatch,
kIsolatedOriginDontMatch,
kIsolatedOriginStatusMax,
};
} // namespace
// Implementing the DatabaseKey for the directories_ map.
DatabaseKey::DatabaseKey() = default;
DatabaseKey::~DatabaseKey() = default;
// Copyable and moveable
DatabaseKey::DatabaseKey(const DatabaseKey& other) = default;
DatabaseKey& DatabaseKey::operator=(const DatabaseKey& other) = default;
DatabaseKey::DatabaseKey(DatabaseKey&& other) = default;
DatabaseKey& DatabaseKey::operator=(DatabaseKey&& other) = default;
DatabaseKey::DatabaseKey(const blink::StorageKey& storage_key,
const std::optional<BucketLocator>& bucket,
const std::string& type) {
storage_key_ = storage_key;
bucket_ = bucket;
type_ = type;
}
bool DatabaseKey::operator==(const DatabaseKey& other) const {
return std::tie(storage_key_, bucket_, type_) ==
std::tie(other.storage_key_, other.bucket_, other.type_);
}
bool DatabaseKey::operator!=(const DatabaseKey& other) const {
return std::tie(storage_key_, bucket_, type_) !=
std::tie(other.storage_key_, other.bucket_, other.type_);
}
bool DatabaseKey::operator<(const DatabaseKey& other) const {
return std::tie(storage_key_, bucket_, type_) <
std::tie(other.storage_key_, other.bucket_, other.type_);
}
// end DatabaseKey implementation.
class ObfuscatedFileEnumerator final
: public FileSystemFileUtil::AbstractFileEnumerator {
public:
ObfuscatedFileEnumerator(SandboxDirectoryDatabase* db,
FileSystemOperationContext* context,
ObfuscatedFileUtil* obfuscated_file_util,
const FileSystemURL& root_url,
bool recursive)
: db_(db),
context_(context),
obfuscated_file_util_(obfuscated_file_util),
root_url_(root_url),
recursive_(recursive),
current_file_id_(0) {
base::FilePath root_virtual_path = root_url.path();
FileId file_id;
if (!db_->GetFileWithPath(root_virtual_path, &file_id))
return;
FileRecord record = {file_id, root_virtual_path};
recurse_queue_.push(record);
}
~ObfuscatedFileEnumerator() override = default;
base::FilePath Next() override {
FileInfo file_info;
base::File::Error error;
do {
ProcessRecurseQueue();
if (display_stack_.empty())
return base::FilePath();
current_file_id_ = display_stack_.back();
display_stack_.pop_back();
base::FilePath platform_file_path;
error = obfuscated_file_util_->GetFileInfoInternal(
db_, context_, root_url_, current_file_id_, &file_info,
¤t_platform_file_info_, &platform_file_path);
} while (error != base::File::FILE_OK);
base::FilePath virtual_path =
current_parent_virtual_path_.Append(file_info.name);
if (recursive_ && file_info.is_directory()) {
FileRecord record = {current_file_id_, virtual_path};
recurse_queue_.push(record);
}
return virtual_path;
}
int64_t Size() override { return current_platform_file_info_.size; }
base::FilePath GetName() override { return base::FilePath(); }
base::Time LastModifiedTime() override {
return current_platform_file_info_.last_modified;
}
bool IsDirectory() override {
return current_platform_file_info_.is_directory;
}
private:
using FileId = SandboxDirectoryDatabase::FileId;
using FileInfo = SandboxDirectoryDatabase::FileInfo;
struct FileRecord {
FileId file_id;
base::FilePath virtual_path;
};
void ProcessRecurseQueue() {
while (display_stack_.empty() && !recurse_queue_.empty()) {
FileRecord entry = recurse_queue_.front();
recurse_queue_.pop();
if (!db_->ListChildren(entry.file_id, &display_stack_)) {
display_stack_.clear();
return;
}
current_parent_virtual_path_ = entry.virtual_path;
}
}
raw_ptr<SandboxDirectoryDatabase> db_;
raw_ptr<FileSystemOperationContext, DanglingUntriaged> context_;
raw_ptr<ObfuscatedFileUtil> obfuscated_file_util_;
FileSystemURL root_url_;
bool recursive_;
base::queue<FileRecord> recurse_queue_;
std::vector<FileId> display_stack_;
base::FilePath current_parent_virtual_path_;
FileId current_file_id_;
base::File::Info current_platform_file_info_;
};
// NOTE: currently, ObfuscatedFileUtil still relies on SandboxOriginDatabases
// for first-party StorageKeys/default buckets. The AbstractStorageKeyEnumerator
// class is only used in these cases. While this class stores and iterates
// through StorageKeys types, it works by retrieving OriginRecords from the
// SandboxOriginDatabase and converting those origins into first-party
// StorageKey values (e.g. blink::StorageKey(origin)). The goal is to eventually
// deprecate SandboxOriginDatabases and AbstractStorageKeyEnumerators and rely
// entirely on Storage Buckets.
class ObfuscatedStorageKeyEnumerator
: public ObfuscatedFileUtil::AbstractStorageKeyEnumerator {
public:
using OriginRecord = SandboxOriginDatabase::OriginRecord;
ObfuscatedStorageKeyEnumerator(
SandboxOriginDatabaseInterface* origin_database,
base::WeakPtr<ObfuscatedFileUtilMemoryDelegate> memory_file_util,
const base::FilePath& base_file_path)
: base_file_path_(base_file_path),
memory_file_util_(std::move(memory_file_util)) {
if (origin_database)
origin_database->ListAllOrigins(&origin_records_);
}
~ObfuscatedStorageKeyEnumerator() override = default;
// Returns the next StorageKey. Returns empty if there are no more
// StorageKeys.
std::optional<blink::StorageKey> Next() override {
OriginRecord record;
if (origin_records_.empty()) {
current_ = record;
return std::nullopt;
}
record = origin_records_.back();
origin_records_.pop_back();
current_ = record;
return blink::StorageKey::CreateFirstParty(
GetOriginFromIdentifier(record.origin));
}
// Returns the current StorageKey.origin()'s information.
bool HasTypeDirectory(const std::string& type_string) const override {
if (current_.path.empty())
return false;
if (type_string.empty()) {
NOTREACHED();
}
base::FilePath path =
base_file_path_.Append(current_.path).AppendASCII(type_string);
if (memory_file_util_)
return memory_file_util_->DirectoryExists(path);
else
return base::DirectoryExists(path);
}
private:
std::vector<OriginRecord> origin_records_;
OriginRecord current_;
base::FilePath base_file_path_;
base::WeakPtr<ObfuscatedFileUtilMemoryDelegate> memory_file_util_;
};
const base::FilePath::CharType ObfuscatedFileUtil::kFileSystemDirectory[] =
FILE_PATH_LITERAL("File System");
ObfuscatedFileUtil::ObfuscatedFileUtil(
scoped_refptr<SpecialStoragePolicy> special_storage_policy,
const base::FilePath& profile_path,
leveldb::Env* env_override,
const std::set<std::string>& known_type_strings,
SandboxFileSystemBackendDelegate* sandbox_delegate,
bool is_incognito)
: special_storage_policy_(std::move(special_storage_policy)),
env_override_(env_override),
is_incognito_(is_incognito),
db_flush_delay_seconds_(10 * 60), // 10 mins.
known_type_strings_(known_type_strings),
sandbox_delegate_(sandbox_delegate) {
DETACH_FROM_SEQUENCE(sequence_checker_);
DCHECK(!is_incognito_ ||
(env_override && leveldb_chrome::IsMemEnv(env_override)));
file_system_directory_ = profile_path.Append(kFileSystemDirectory);
if (is_incognito_) {
// profile_path is passed here, so that the delegate is able to accommodate
// both codepaths of {{profile_path}}/File System (first-party) and
// {{profile_path}}/WebStorage (buckets-based).
// See https://crrev.com/c/3817542 for more context.
delegate_ =
std::make_unique<ObfuscatedFileUtilMemoryDelegate>(profile_path);
} else {
delegate_ = std::make_unique<ObfuscatedFileUtilDiskDelegate>();
}
}
ObfuscatedFileUtil::~ObfuscatedFileUtil() {
DropDatabases();
}
base::File ObfuscatedFileUtil::CreateOrOpen(FileSystemOperationContext* context,
const FileSystemURL& url,
int file_flags) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
base::File file = CreateOrOpenInternal(context, url, file_flags);
if (file.IsValid() && file_flags & base::File::FLAG_WRITE &&
context->quota_limit_type() == QuotaLimitType::kUnlimited &&
sandbox_delegate_) {
sandbox_delegate_->StickyInvalidateUsageCache(url.storage_key(),
url.type());
}
return file;
}
base::File::Error ObfuscatedFileUtil::EnsureFileExists(
FileSystemOperationContext* context,
const FileSystemURL& url,
bool* created) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
SandboxDirectoryDatabase* db = GetDirectoryDatabase(url, true);
if (!db)
return base::File::FILE_ERROR_FAILED;
FileId file_id;
if (db->GetFileWithPath(url.path(), &file_id)) {
FileInfo file_info;
if (!db->GetFileInfo(file_id, &file_info)) {
return base::File::FILE_ERROR_FAILED;
}
if (file_info.is_directory())
return base::File::FILE_ERROR_NOT_A_FILE;
if (created)
*created = false;
return base::File::FILE_OK;
}
FileId parent_id;
if (!db->GetFileWithPath(VirtualPath::DirName(url.path()), &parent_id))
return base::File::FILE_ERROR_NOT_FOUND;
FileInfo file_info;
InitFileInfo(&file_info, parent_id,
VirtualPath::BaseName(url.path()).value());
int64_t growth = UsageForPath(file_info.name.size());
if (!AllocateQuota(context, growth))
return base::File::FILE_ERROR_NO_SPACE;
base::File::Error error = CreateFile(
context, base::FilePath(), false /* foreign_source */, url, &file_info);
if (created && base::File::FILE_OK == error) {
*created = true;
UpdateUsage(context, url, growth);
context->change_observers()->Notify(&FileChangeObserver::OnCreateFile, url);
}
return error;
}
base::File::Error ObfuscatedFileUtil::CreateDirectory(
FileSystemOperationContext* context,
const FileSystemURL& url,
bool exclusive,
bool recursive) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
SandboxDirectoryDatabase* db = GetDirectoryDatabase(url, true);
if (!db)
return base::File::FILE_ERROR_FAILED;
FileId file_id;
if (db->GetFileWithPath(url.path(), &file_id)) {
FileInfo file_info;
if (exclusive)
return base::File::FILE_ERROR_EXISTS;
if (!db->GetFileInfo(file_id, &file_info)) {
return base::File::FILE_ERROR_FAILED;
}
if (!file_info.is_directory())
return base::File::FILE_ERROR_NOT_A_DIRECTORY;
return base::File::FILE_OK;
}
std::vector<base::FilePath::StringType> components =
VirtualPath::GetComponents(url.path());
FileId parent_id = 0;
size_t index;
for (index = 0; index < components.size(); ++index) {
base::FilePath::StringType name = components[index];
if (name == FILE_PATH_LITERAL("/"))
continue;
if (!db->GetChildWithName(parent_id, name, &parent_id))
break;
}
if (!db->IsDirectory(parent_id))
return base::File::FILE_ERROR_NOT_A_DIRECTORY;
if (!recursive && components.size() - index > 1)
return base::File::FILE_ERROR_NOT_FOUND;
bool first = true;
for (; index < components.size(); ++index) {
FileInfo file_info;
file_info.name = components[index];
if (file_info.name == FILE_PATH_LITERAL("/"))
continue;
file_info.modification_time = base::Time::Now();
file_info.parent_id = parent_id;
int64_t growth = UsageForPath(file_info.name.size());
if (!AllocateQuota(context, growth))
return base::File::FILE_ERROR_NO_SPACE;
base::File::Error error = db->AddFileInfo(file_info, &parent_id);
if (error != base::File::FILE_OK)
return error;
UpdateUsage(context, url, growth);
// Appropriately report changes when recursively creating a directory by
// constructing the FileSystemURL of created intermediate directories.
base::FilePath changed_path = url.virtual_path();
for (size_t i = components.size() - 1; i > index; --i) {
changed_path = VirtualPath::DirName(changed_path);
}
auto created_directory_url =
context->file_system_context()->CreateCrackedFileSystemURL(
url.storage_key(), url.mount_type(), changed_path);
if (url.bucket().has_value()) {
created_directory_url.SetBucket(url.bucket().value());
}
context->change_observers()->Notify(&FileChangeObserver::OnCreateDirectory,
created_directory_url);
if (first) {
first = false;
TouchDirectory(db, file_info.parent_id);
}
}
return base::File::FILE_OK;
}
base::File::Error ObfuscatedFileUtil::GetFileInfo(
FileSystemOperationContext* context,
const FileSystemURL& url,
base::File::Info* file_info,
base::FilePath* platform_file_path) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
SandboxDirectoryDatabase* db = GetDirectoryDatabase(url, false);
if (!db)
return base::File::FILE_ERROR_NOT_FOUND;
FileId file_id;
if (!db->GetFileWithPath(url.path(), &file_id))
return base::File::FILE_ERROR_NOT_FOUND;
FileInfo local_info;
return GetFileInfoInternal(db, context, url, file_id, &local_info, file_info,
platform_file_path);
}
base::File::Error ObfuscatedFileUtil::GetLocalFilePath(
FileSystemOperationContext* context,
const FileSystemURL& url,
base::FilePath* local_path) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
SandboxDirectoryDatabase* db = GetDirectoryDatabase(url, false);
if (!db)
return base::File::FILE_ERROR_NOT_FOUND;
FileId file_id;
if (!db->GetFileWithPath(url.path(), &file_id))
return base::File::FILE_ERROR_NOT_FOUND;
FileInfo file_info;
if (!db->GetFileInfo(file_id, &file_info) || file_info.is_directory()) {
// Directories have no local file path.
return base::File::FILE_ERROR_NOT_FOUND;
}
*local_path = DataPathToLocalPath(url, file_info.data_path);
if (local_path->empty())
return base::File::FILE_ERROR_NOT_FOUND;
return base::File::FILE_OK;
}
base::File::Error ObfuscatedFileUtil::Touch(
FileSystemOperationContext* context,
const FileSystemURL& url,
const base::Time& last_access_time,
const base::Time& last_modified_time) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
SandboxDirectoryDatabase* db = GetDirectoryDatabase(url, false);
if (!db)
return base::File::FILE_ERROR_NOT_FOUND;
FileId file_id;
if (!db->GetFileWithPath(url.path(), &file_id))
return base::File::FILE_ERROR_NOT_FOUND;
FileInfo file_info;
if (!db->GetFileInfo(file_id, &file_info)) {
return base::File::FILE_ERROR_FAILED;
}
if (file_info.is_directory()) {
if (!db->UpdateModificationTime(file_id, last_modified_time))
return base::File::FILE_ERROR_FAILED;
return base::File::FILE_OK;
}
return delegate_->Touch(DataPathToLocalPath(url, file_info.data_path),
last_access_time, last_modified_time);
}
base::File::Error ObfuscatedFileUtil::Truncate(
FileSystemOperationContext* context,
const FileSystemURL& url,
int64_t length) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
base::File::Info file_info;
base::FilePath local_path;
base::File::Error error = GetFileInfo(context, url, &file_info, &local_path);
if (error != base::File::FILE_OK)
return error;
int64_t growth = length - file_info.size;
if (!AllocateQuota(context, growth))
return base::File::FILE_ERROR_NO_SPACE;
error = delegate_->Truncate(local_path, length);
if (error == base::File::FILE_OK) {
UpdateUsage(context, url, growth);
context->change_observers()->Notify(&FileChangeObserver::OnModifyFile, url);
}
return error;
}
base::File::Error ObfuscatedFileUtil::CopyOrMoveFile(
FileSystemOperationContext* context,
const FileSystemURL& src_url,
const FileSystemURL& dest_url,
CopyOrMoveOptionSet options,
bool copy) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// Cross-filesystem copies and moves should be handled via CopyInForeignFile.
DCHECK(src_url.origin() == dest_url.origin());
DCHECK(src_url.type() == dest_url.type());
SandboxDirectoryDatabase* db = GetDirectoryDatabase(src_url, true);
if (!db)
return base::File::FILE_ERROR_FAILED;
FileId src_file_id;
if (!db->GetFileWithPath(src_url.path(), &src_file_id))
return base::File::FILE_ERROR_NOT_FOUND;
FileId dest_file_id;
bool overwrite = db->GetFileWithPath(dest_url.path(), &dest_file_id);
FileInfo src_file_info;
base::File::Info src_platform_file_info;
base::FilePath src_local_path;
base::File::Error error =
GetFileInfoInternal(db, context, src_url, src_file_id, &src_file_info,
&src_platform_file_info, &src_local_path);
if (error != base::File::FILE_OK)
return error;
if (src_file_info.is_directory())
return base::File::FILE_ERROR_NOT_A_FILE;
FileInfo dest_file_info;
base::File::Info dest_platform_file_info; // overwrite case only
base::FilePath dest_local_path; // overwrite case only
if (overwrite) {
error = GetFileInfoInternal(db, context, dest_url, dest_file_id,
&dest_file_info, &dest_platform_file_info,
&dest_local_path);
if (error == base::File::FILE_ERROR_NOT_FOUND)
overwrite = false; // fallback to non-overwrite case
else if (error != base::File::FILE_OK)
return error;
else if (dest_file_info.is_directory())
return base::File::FILE_ERROR_INVALID_OPERATION;
}
if (!overwrite) {
FileId dest_parent_id;
if (!db->GetFileWithPath(VirtualPath::DirName(dest_url.path()),
&dest_parent_id)) {
return base::File::FILE_ERROR_NOT_FOUND;
}
dest_file_info = src_file_info;
dest_file_info.parent_id = dest_parent_id;
dest_file_info.name = VirtualPath::BaseName(dest_url.path()).value();
}
int64_t growth = 0;
if (copy)
growth += src_platform_file_info.size;
else
growth -= UsageForPath(src_file_info.name.size());
if (overwrite)
growth -= dest_platform_file_info.size;
else
growth += UsageForPath(dest_file_info.name.size());
if (!AllocateQuota(context, growth))
return base::File::FILE_ERROR_NO_SPACE;
/*
* Copy-with-overwrite
* Just overwrite data file
* Copy-without-overwrite
* Copy backing file
* Create new metadata pointing to new backing file.
* Move-with-overwrite
* transaction:
* Remove source entry.
* Point target entry to source entry's backing file.
* Delete target entry's old backing file
* Move-without-overwrite
* Just update metadata
*/
error = base::File::FILE_ERROR_FAILED;
if (copy) {
if (overwrite) {
error = delegate_->CopyOrMoveFile(
src_local_path, dest_local_path, options,
delegate_->CopyOrMoveModeForDestination(dest_url, true /* copy */));
} else { // non-overwrite
error = CreateFile(context, src_local_path, false /* foreign_source */,
dest_url, &dest_file_info);
}
} else {
if (overwrite) {
if (db->OverwritingMoveFile(src_file_id, dest_file_id)) {
if (base::File::FILE_OK != delegate_->DeleteFile(dest_local_path))
LOG(WARNING) << "Leaked a backing file.";
error = base::File::FILE_OK;
} else {
error = base::File::FILE_ERROR_FAILED;
}
} else { // non-overwrite
if (db->UpdateFileInfo(src_file_id, dest_file_info))
error = base::File::FILE_OK;
else
error = base::File::FILE_ERROR_FAILED;
}
}
if (error != base::File::FILE_OK)
return error;
if (copy) {
context->change_observers()->Notify(&FileChangeObserver::OnCreateFileFrom,
dest_url, src_url);
} else {
context->change_observers()->Notify(&FileChangeObserver::OnMoveFileFrom,
dest_url, src_url);
TouchDirectory(db, src_file_info.parent_id);
}
TouchDirectory(db, dest_file_info.parent_id);
UpdateUsage(context, dest_url, growth);
return error;
}
base::File::Error ObfuscatedFileUtil::CopyInForeignFile(
FileSystemOperationContext* context,
const base::FilePath& src_file_path,
const FileSystemURL& dest_url) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
SandboxDirectoryDatabase* db = GetDirectoryDatabase(dest_url, true);
if (!db)
return base::File::FILE_ERROR_FAILED;
base::File::Info src_platform_file_info;
// Foreign files are from another on-disk file system and don't require path
// conversion.
if (ObfuscatedFileUtilDiskDelegate().GetFileInfo(
src_file_path, &src_platform_file_info) != base::File::FILE_OK)
return base::File::FILE_ERROR_NOT_FOUND;
FileId dest_file_id;
bool overwrite = db->GetFileWithPath(dest_url.path(), &dest_file_id);
FileInfo dest_file_info;
base::File::Info dest_platform_file_info; // overwrite case only
if (overwrite) {
base::FilePath dest_local_path;
base::File::Error error = GetFileInfoInternal(
db, context, dest_url, dest_file_id, &dest_file_info,
&dest_platform_file_info, &dest_local_path);
if (error == base::File::FILE_ERROR_NOT_FOUND)
overwrite = false; // fallback to non-overwrite case
else if (error != base::File::FILE_OK)
return error;
else if (dest_file_info.is_directory())
return base::File::FILE_ERROR_INVALID_OPERATION;
}
if (!overwrite) {
FileId dest_parent_id;
if (!db->GetFileWithPath(VirtualPath::DirName(dest_url.path()),
&dest_parent_id)) {
return base::File::FILE_ERROR_NOT_FOUND;
}
if (!dest_file_info.is_directory())
return base::File::FILE_ERROR_FAILED;
InitFileInfo(&dest_file_info, dest_parent_id,
VirtualPath::BaseName(dest_url.path()).value());
}
int64_t growth = src_platform_file_info.size;
if (overwrite)
growth -= dest_platform_file_info.size;
else
growth += UsageForPath(dest_file_info.name.size());
if (!AllocateQuota(context, growth))
return base::File::FILE_ERROR_NO_SPACE;
base::File::Error error;
if (overwrite) {
base::FilePath dest_local_path =
DataPathToLocalPath(dest_url, dest_file_info.data_path);
error = delegate_->CopyInForeignFile(
src_file_path, dest_local_path,
FileSystemOperation::CopyOrMoveOptionSet(),
delegate_->CopyOrMoveModeForDestination(dest_url, true /* copy */));
} else {
error = CreateFile(context, src_file_path, true /* foreign_source */,
dest_url, &dest_file_info);
}
if (error != base::File::FILE_OK)
return error;
if (overwrite) {
context->change_observers()->Notify(&FileChangeObserver::OnModifyFile,
dest_url);
} else {
context->change_observers()->Notify(&FileChangeObserver::OnCreateFile,
dest_url);
}
UpdateUsage(context, dest_url, growth);
TouchDirectory(db, dest_file_info.parent_id);
return base::File::FILE_OK;
}
base::File::Error ObfuscatedFileUtil::DeleteFile(
FileSystemOperationContext* context,
const FileSystemURL& url) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
SandboxDirectoryDatabase* db = GetDirectoryDatabase(url, true);
if (!db)
return base::File::FILE_ERROR_FAILED;
FileId file_id;
if (!db->GetFileWithPath(url.path(), &file_id))
return base::File::FILE_ERROR_NOT_FOUND;
FileInfo file_info;
base::File::Info platform_file_info;
base::FilePath local_path;
base::File::Error error = GetFileInfoInternal(
db, context, url, file_id, &file_info, &platform_file_info, &local_path);
if (error != base::File::FILE_ERROR_NOT_FOUND && error != base::File::FILE_OK)
return error;
if (file_info.is_directory())
return base::File::FILE_ERROR_NOT_A_FILE;
int64_t growth =
-UsageForPath(file_info.name.size()) - platform_file_info.size;
AllocateQuota(context, growth);
if (!db->RemoveFileInfo(file_id)) {
DUMP_WILL_BE_NOTREACHED();
return base::File::FILE_ERROR_FAILED;
}
UpdateUsage(context, url, growth);
TouchDirectory(db, file_info.parent_id);
context->change_observers()->Notify(&FileChangeObserver::OnRemoveFile, url);
if (error == base::File::FILE_ERROR_NOT_FOUND)
return base::File::FILE_OK;
error = delegate_->DeleteFile(local_path);
if (base::File::FILE_OK != error)
LOG(WARNING) << "Leaked a backing file.";
return base::File::FILE_OK;
}
base::File::Error ObfuscatedFileUtil::DeleteDirectory(
FileSystemOperationContext* context,
const FileSystemURL& url) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
SandboxDirectoryDatabase* db = GetDirectoryDatabase(url, true);
if (!db)
return base::File::FILE_ERROR_FAILED;
FileId file_id;
if (!db->GetFileWithPath(url.path(), &file_id))
return base::File::FILE_ERROR_NOT_FOUND;
if (!file_id) {
// Attempting to remove the root directory. Delete the whole file system.
// This code should only be reached by the File System Access API when
// deleting the root of an Origin Private File System. All sandboxed URLs
// coming from that API are guaranteed to include bucket information.
DCHECK(url.bucket().has_value());
DCHECK(url.type() == kFileSystemTypeTemporary);
DeleteDirectoryForBucketAndType(url.bucket().value(), url.type());
context->change_observers()->Notify(&FileChangeObserver::OnRemoveDirectory,
url);
return base::File::FILE_OK;
}
FileInfo file_info;
if (!db->GetFileInfo(file_id, &file_info)) {
return base::File::FILE_ERROR_FAILED;
}
if (!file_info.is_directory())
return base::File::FILE_ERROR_NOT_A_DIRECTORY;
if (!db->RemoveFileInfo(file_id))
return base::File::FILE_ERROR_NOT_EMPTY;
int64_t growth = -UsageForPath(file_info.name.size());
AllocateQuota(context, growth);
UpdateUsage(context, url, growth);
TouchDirectory(db, file_info.parent_id);
context->change_observers()->Notify(&FileChangeObserver::OnRemoveDirectory,
url);
return base::File::FILE_OK;
}
ScopedFile ObfuscatedFileUtil::CreateSnapshotFile(
FileSystemOperationContext* context,
const FileSystemURL& url,
base::File::Error* error,
base::File::Info* file_info,
base::FilePath* platform_path) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// We're just returning the local file information.
*error = GetFileInfo(context, url, file_info, platform_path);
if (*error == base::File::FILE_OK && file_info->is_directory) {
*file_info = base::File::Info();
*error = base::File::FILE_ERROR_NOT_A_FILE;
}
// An empty ScopedFile does not have any on-disk operation, therefore it can
// be handled the same way by on-disk and in-memory implementations.
return ScopedFile();
}
std::unique_ptr<FileSystemFileUtil::AbstractFileEnumerator>
ObfuscatedFileUtil::CreateFileEnumerator(FileSystemOperationContext* context,
const FileSystemURL& root_url,
bool recursive) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
SandboxDirectoryDatabase* db = GetDirectoryDatabase(root_url, false);
if (!db) {
return std::make_unique<EmptyFileEnumerator>();
}
return std::make_unique<ObfuscatedFileEnumerator>(
db, context, this, root_url, recursive);
}
bool ObfuscatedFileUtil::IsDirectoryEmpty(FileSystemOperationContext* context,
const FileSystemURL& url) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
SandboxDirectoryDatabase* db = GetDirectoryDatabase(url, false);
if (!db)
return true; // Not a great answer, but it's what others do.
FileId file_id;
if (!db->GetFileWithPath(url.path(), &file_id))
return true; // Ditto.
FileInfo file_info;
if (!db->GetFileInfo(file_id, &file_info)) {
// It's the root directory and the database hasn't been initialized yet.
return true;
}
if (!file_info.is_directory())
return true;
std::vector<FileId> children;
// TODO(ericu): This could easily be made faster with help from the database.
if (!db->ListChildren(file_id, &children))
return true;
return children.empty();
}
base::FileErrorOr<base::FilePath>
ObfuscatedFileUtil::GetDirectoryForBucketAndType(
const BucketLocator& bucket,
const std::optional<FileSystemType>& type,
bool create) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// A default bucket in a first-party context uses
// GetDirectoryForStorageKeyAndType() to determine its file path.
// In tests, `sandbox_delegate_->quota_manager_proxy()` may be null.
if ((bucket.storage_key.IsFirstPartyContext() && bucket.is_default) ||
!sandbox_delegate_->quota_manager_proxy()) {
return GetDirectoryForStorageKeyAndType(bucket.storage_key, type, create);
}
// All other contexts use the provided bucket information to construct the
// file path.
base::FilePath path =
sandbox_delegate_->quota_manager_proxy()->GetClientBucketPath(
bucket, QuotaClientType::kFileSystem);
// Append the file system type and verify the path is valid.
if (type) {
path = path.AppendASCII(
SandboxFileSystemBackendDelegate::GetTypeString(type.value()));
}
base::File::Error error = GetDirectoryHelper(path, create);
if (error != base::File::FILE_OK)
return base::unexpected(error);
return path;
}
base::FileErrorOr<base::FilePath>
ObfuscatedFileUtil::GetDirectoryForStorageKeyAndType(
const blink::StorageKey& storage_key,
const std::optional<FileSystemType>& type,
bool create) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
ASSIGN_OR_RETURN(base::FilePath path,
GetDirectoryForStorageKey(storage_key, create));
DCHECK(!path.empty());
if (!type) {
return path;
}
// Append the file system type and verify the path is valid.
path = path.AppendASCII(
SandboxFileSystemBackendDelegate::GetTypeString(type.value()));
base::File::Error error = GetDirectoryHelper(path, create);
if (error != base::File::FILE_OK)
return base::unexpected(error);
return path;
}
bool ObfuscatedFileUtil::DeleteDirectoryForBucketAndType(
const BucketLocator& bucket_locator,
const std::optional<FileSystemType>& type) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DestroyDirectoryDatabaseForBucket(bucket_locator, type);
// Get the base path for the bucket without the type string appended.
base::FileErrorOr<base::FilePath> path_without_type =
GetDirectoryForBucketAndType(bucket_locator, /*type=*/std::nullopt,
/*create=*/false);
if (!path_without_type.has_value() || path_without_type->empty()) {
return true;
}
if (type) {
// Delete the filesystem type directory.
ASSIGN_OR_RETURN(const base::FilePath path_with_type,
GetDirectoryForBucketAndType(bucket_locator, type.value(),
/*create=*/false),
[](base::File::Error error) {
return error == base::File::FILE_ERROR_NOT_FOUND;
});
if (!path_with_type.empty() && !delegate_->DeleteFileOrDirectory(
path_with_type, true /* recursive */)) {
return false;
}
// At this point we are sure we had successfully deleted the bucket/type
// directory. Now we need to see if we have other sub-type-directories under
// the higher-level `path_without_type` directory. If so, we need to return
// early to avoid deleting the higher-level `path_without_type` directory
const std::string type_string =
SandboxFileSystemBackendDelegate::GetTypeString(type.value());
for (const std::string& known_type : known_type_strings_) {
if (known_type == type_string) {
continue;
}
if (delegate_->DirectoryExists(
path_without_type->AppendASCII(known_type))) {
// Other type's directory exists; return to avoid deleting the higher
// level directory.
return true;
}
}
}
// No other directories seem to exist. If we have a first-party default
// bucket, try deleting the entire origin directory.
if (bucket_locator.is_default &&
bucket_locator.storage_key.IsFirstPartyContext()) {
InitOriginDatabase(bucket_locator.storage_key.origin(), false);
if (origin_database_) {
origin_database_->RemovePathForOrigin(
GetIdentifierFromOrigin(bucket_locator.storage_key.origin()));
}
}
// Delete the higher-level directory.
return delegate_->DeleteFileOrDirectory(path_without_type.value(),
true /* recursive */);
}
std::unique_ptr<ObfuscatedFileUtil::AbstractStorageKeyEnumerator>
ObfuscatedFileUtil::CreateStorageKeyEnumerator() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
InitOriginDatabase(url::Origin(), false);
base::WeakPtr<ObfuscatedFileUtilMemoryDelegate> file_util_delegate;
if (is_incognito()) {
file_util_delegate =
static_cast<ObfuscatedFileUtilMemoryDelegate*>(delegate())
->GetWeakPtr();
}
return std::make_unique<ObfuscatedStorageKeyEnumerator>(
origin_database_.get(), file_util_delegate, file_system_directory_);
}
void ObfuscatedFileUtil::DestroyDirectoryDatabaseForBucket(
const BucketLocator& bucket_locator,
const std::optional<FileSystemType>& type) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
const std::string type_string =
type ? SandboxFileSystemBackendDelegate::GetTypeString(type.value())
: std::string();
DatabaseKey key_prefix =
DatabaseKey(bucket_locator.storage_key, bucket_locator, type_string);
// If `type` is empty, delete all filesystem types under `storage_key`.
for (auto iter = directories_.lower_bound(key_prefix);
iter != directories_.end();) {
// If the key matches exactly or `type` is std::nullopt and just the
// StorageKey and BucketLocator match exactly, delete the database.
if (iter->first == key_prefix ||
(type == std::nullopt &&
iter->first.storage_key() == key_prefix.storage_key() &&
iter->first.bucket() == key_prefix.bucket())) {
std::unique_ptr<SandboxDirectoryDatabase> database =
std::move(iter->second);
directories_.erase(iter++);
database->DestroyDatabase();
} else {
break;
}
}
}
// static
int64_t ObfuscatedFileUtil::ComputeFilePathCost(const base::FilePath& path) {
return UsageForPath(VirtualPath::BaseName(path).value().size());
}
base::FileErrorOr<base::FilePath> ObfuscatedFileUtil::GetDirectoryForURL(
const FileSystemURL& url,
bool create) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (!url.bucket().has_value()) {
// Access the SandboxDirectoryDatabase to construct the file path.
return GetDirectoryForStorageKeyAndType(url.storage_key(), url.type(),
create);
}
// Construct the file path using the provided bucket information.
return GetDirectoryForBucketAndType(url.bucket().value(), url.type(), create);
}
QuotaErrorOr<BucketLocator> ObfuscatedFileUtil::GetOrCreateDefaultBucket(
const blink::StorageKey& storage_key) {
// If we have already looked up this default bucket for this StorageKey,
// return the cached value.
auto iter = default_buckets_.find(storage_key);
if (iter != default_buckets_.end()) {
return iter->second;
}
// GetOrCreateBucketSync() called below requires the use of the
// base::WaitableEvent sync primitive. We must explicitly declare the usage
// of this primitive to avoid thread restriction errors.
base::ScopedAllowBaseSyncPrimitives allow_wait;
// Instead of crashing, return a QuotaError if the proxy is a nullptr.
if (!sandbox_delegate_->quota_manager_proxy()) {
LOG(WARNING) << "Failed to GetOrCreateBucket: QuotaManagerProxy is null";
return base::unexpected(QuotaError::kUnknownError);
}
// Retrieve or create the default bucket for this StorageKey.
ASSIGN_OR_RETURN(
BucketInfo bucket,
sandbox_delegate_->quota_manager_proxy()->GetOrCreateBucketSync(
BucketInitParams::ForDefaultBucket(storage_key)));
default_buckets_[storage_key] = bucket.ToBucketLocator();
return bucket.ToBucketLocator();
}
base::File::Error ObfuscatedFileUtil::GetFileInfoInternal(
SandboxDirectoryDatabase* db,
FileSystemOperationContext* context,
const FileSystemURL& url,
FileId file_id,
FileInfo* local_info,
base::File::Info* file_info,
base::FilePath* platform_file_path) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(db);
DCHECK(context);
DCHECK(file_info);
DCHECK(platform_file_path);
if (!db->GetFileInfo(file_id, local_info)) {
return base::File::FILE_ERROR_FAILED;
}
if (local_info->is_directory()) {
file_info->size = 0;
file_info->is_directory = true;
file_info->is_symbolic_link = false;
file_info->last_modified = local_info->modification_time;
*platform_file_path = base::FilePath();
// We don't fill in ctime or atime.
return base::File::FILE_OK;
}
if (local_info->data_path.empty())
return base::File::FILE_ERROR_INVALID_OPERATION;
base::FilePath local_path = DataPathToLocalPath(url, local_info->data_path);
base::File::Error error = delegate_->GetFileInfo(local_path, file_info);
// We should not follow symbolic links in sandboxed file system.
if (delegate_->IsLink(local_path)) {
LOG(WARNING) << "Found a symbolic file.";
error = base::File::FILE_ERROR_NOT_FOUND;
}
if (error == base::File::FILE_OK) {
*platform_file_path = local_path;
} else if (error == base::File::FILE_ERROR_NOT_FOUND) {
LOG(WARNING) << "Lost a backing file.";
InvalidateUsageCache(context, url.storage_key(), url.type());
if (!db->RemoveFileInfo(file_id))
return base::File::FILE_ERROR_FAILED;
}
return error;
}
base::File ObfuscatedFileUtil::CreateAndOpenFile(
FileSystemOperationContext* context,
const FileSystemURL& dest_url,
FileInfo* dest_file_info,
int file_flags) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
SandboxDirectoryDatabase* db = GetDirectoryDatabase(dest_url, true);
base::FilePath root, dest_local_path;
base::File::Error error =
GenerateNewLocalPath(db, context, dest_url, &root, &dest_local_path);
if (error != base::File::FILE_OK)
return base::File(error);
if (delegate_->PathExists(dest_local_path)) {
if (!delegate_->DeleteFileOrDirectory(dest_local_path,
false /* recursive */))
return base::File(base::File::FILE_ERROR_FAILED);
LOG(WARNING) << "A stray file detected";
InvalidateUsageCache(context, dest_url.storage_key(), dest_url.type());
}
base::File file = delegate_->CreateOrOpen(dest_local_path, file_flags);
if (!file.IsValid())
return file;
if (!file.created()) {
file.Close();
delegate_->DeleteFile(dest_local_path);
return base::File(base::File::FILE_ERROR_FAILED);
}
error = CommitCreateFile(root, dest_local_path, db, dest_file_info);
if (error != base::File::FILE_OK) {
file.Close();
delegate_->DeleteFile(dest_local_path);
return base::File(error);
}
return file;
}
base::File::Error ObfuscatedFileUtil::CreateFile(
FileSystemOperationContext* context,
const base::FilePath& src_file_path,
bool foreign_source,
const FileSystemURL& dest_url,
FileInfo* dest_file_info) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
SandboxDirectoryDatabase* db = GetDirectoryDatabase(dest_url, true);
base::FilePath root, dest_local_path;
base::File::Error error =
GenerateNewLocalPath(db, context, dest_url, &root, &dest_local_path);
if (error != base::File::FILE_OK)
return error;
bool created = false;
if (src_file_path.empty()) {
if (delegate_->PathExists(dest_local_path)) {
if (!delegate_->DeleteFileOrDirectory(dest_local_path,
false /* recursive */))
return base::File::FILE_ERROR_FAILED;
LOG(WARNING) << "A stray file detected";
InvalidateUsageCache(context, dest_url.storage_key(), dest_url.type());
}
error = delegate_->EnsureFileExists(dest_local_path, &created);
} else {
if (foreign_source) {
error = delegate_->CopyInForeignFile(
src_file_path, dest_local_path,
FileSystemOperation::CopyOrMoveOptionSet(),
delegate_->CopyOrMoveModeForDestination(dest_url, true /* copy */));
} else {
error = delegate_->CopyOrMoveFile(
src_file_path, dest_local_path,
FileSystemOperation::CopyOrMoveOptionSet(),
delegate_->CopyOrMoveModeForDestination(dest_url, true /* copy */));
}
created = true;
}
if (error != base::File::FILE_OK)
return error;
if (!created)
return base::File::FILE_ERROR_FAILED;
return CommitCreateFile(root, dest_local_path, db, dest_file_info);
}
base::File::Error ObfuscatedFileUtil::CommitCreateFile(
const base::FilePath& root,
const base::FilePath& local_path,
SandboxDirectoryDatabase* db,
FileInfo* dest_file_info) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// This removes the root, including the trailing slash, leaving a relative
// path.
dest_file_info->data_path =
base::FilePath(local_path.value().substr(root.value().length() + 1));
FileId file_id;
base::File::Error error = db->AddFileInfo(*dest_file_info, &file_id);
if (error != base::File::FILE_OK)
return error;
TouchDirectory(db, dest_file_info->parent_id);
return base::File::FILE_OK;
}
base::FilePath ObfuscatedFileUtil::DataPathToLocalPath(
const FileSystemURL& url,
const base::FilePath& data_path) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
ASSIGN_OR_RETURN(base::FilePath root, GetDirectoryForURL(url, false),
[](auto) { return base::FilePath(); });
return root.Append(data_path);
}
// TODO(ericu): How to do the whole validation-without-creation thing?
// We may not have quota even to create the database.
// Ah, in that case don't even get here?
// Still doesn't answer the quota issue, though.
SandboxDirectoryDatabase* ObfuscatedFileUtil::GetDirectoryDatabase(
const FileSystemURL& url,
bool create) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DatabaseKey key;
const std::string type_string =
SandboxFileSystemBackendDelegate::GetTypeString(url.type());
if (url.bucket().has_value()) {
key = DatabaseKey(url.storage_key(), url.bucket().value(), type_string);
} else {
// If we are not provided a custom bucket value we must find the default
// bucket corresponding to the url's StorageKey.
ASSIGN_OR_RETURN(BucketLocator default_bucket,
GetOrCreateDefaultBucket(url.storage_key()),
[](auto) { return nullptr; });
key =
DatabaseKey(url.storage_key(), std::move(default_bucket), type_string);
}
auto iter = directories_.find(key);
if (iter != directories_.end()) {
MarkUsed();
return iter->second.get();
}
ASSIGN_OR_RETURN(base::FilePath path, GetDirectoryForURL(url, create),
[&](base::File::Error error) {
LOG(WARNING) << "Failed to get origin+type directory: "
<< url.DebugString() << " error:" << error;
return nullptr;
});
MarkUsed();
directories_[key] = std::make_unique<SandboxDirectoryDatabase>(
std::move(path), env_override_);
return directories_[key].get();
}
base::FileErrorOr<base::FilePath> ObfuscatedFileUtil::GetDirectoryForStorageKey(
const blink::StorageKey& storage_key,
bool create) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (storage_key.IsThirdPartyContext()) {
// Retrieve the default bucket value for `storage_key`.
ASSIGN_OR_RETURN(BucketLocator bucket,
GetOrCreateDefaultBucket(storage_key),
[](auto) { return base::File::FILE_ERROR_FAILED; });
// Get the path and verify it is valid.
base::FilePath path =
sandbox_delegate_->quota_manager_proxy()->GetClientBucketPath(
std::move(bucket), QuotaClientType::kFileSystem);
base::File::Error error = GetDirectoryHelper(path, create);
if (error != base::File::FILE_OK)
return base::unexpected(error);
return path;
}
if (!InitOriginDatabase(storage_key.origin(), create)) {
return base::FileErrorOr<base::FilePath>(
base::unexpected(create ? base::File::FILE_ERROR_FAILED
: base::File::FILE_ERROR_NOT_FOUND));
}
base::FilePath directory_name;
std::string id = GetIdentifierFromOrigin(storage_key.origin());
bool exists_in_db = origin_database_->HasOriginPath(id);
if (!exists_in_db && !create) {
return base::unexpected(base::File::FILE_ERROR_NOT_FOUND);
}
if (!origin_database_->GetPathForOrigin(id, &directory_name)) {
return base::unexpected(base::File::FILE_ERROR_FAILED);
}
base::FilePath path = file_system_directory_.Append(directory_name);
bool exists_in_fs = delegate_->DirectoryExists(path);
if (!exists_in_db && exists_in_fs) {
if (!delegate_->DeleteFileOrDirectory(path, true)) {
return base::unexpected(base::File::FILE_ERROR_FAILED);
}
exists_in_fs = false;
}
if (!exists_in_fs) {
if (!create || delegate_->CreateDirectory(path, false /* exclusive */,
true /* recursive */) !=
base::File::FILE_OK) {
return base::unexpected(create ? base::File::FILE_ERROR_FAILED
: base::File::FILE_ERROR_NOT_FOUND);
}
}
return path;
}
base::File::Error ObfuscatedFileUtil::GetDirectoryHelper(
const base::FilePath& path,
bool create) {
if (!delegate_->DirectoryExists(path) &&
(!create ||
delegate_->CreateDirectory(path, /*exclusive=*/false,
/*recursive=*/true) != base::File::FILE_OK)) {
return create ? base::File::FILE_ERROR_FAILED
: base::File::FILE_ERROR_NOT_FOUND;
}
return base::File::FILE_OK;
}
void ObfuscatedFileUtil::InvalidateUsageCache(
FileSystemOperationContext* context,
const blink::StorageKey& storage_key,
FileSystemType type) {
if (sandbox_delegate_)
sandbox_delegate_->InvalidateUsageCache(storage_key, type);
}
void ObfuscatedFileUtil::MarkUsed() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
timer_.Start(FROM_HERE, base::Seconds(db_flush_delay_seconds_), this,
&ObfuscatedFileUtil::DropDatabases);
}
void ObfuscatedFileUtil::DropDatabases() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
origin_database_.reset();
directories_.clear();
timer_.Stop();
}
void ObfuscatedFileUtil::RewriteDatabases() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (origin_database_)
origin_database_->RewriteDatabase();
}
void ObfuscatedFileUtil::DeleteDefaultBucketForStorageKey(
const blink::StorageKey& storage_key) {
auto default_bucket_iter = default_buckets_.find(storage_key);
// If we are not already caching the bucket for that StorageKey, it does not
// need to be deleted.
if (default_bucket_iter == default_buckets_.end())
return;
BucketLocator default_bucket = default_buckets_[storage_key];
// Ensure that all directories with that StorageKey and bucket have been
// erased.
DCHECK(directories_.find(
DatabaseKey(storage_key, default_bucket,
SandboxFileSystemBackendDelegate::GetTypeString(
FileSystemType::kFileSystemTypeTemporary))) ==
directories_.end());
default_buckets_.erase(default_bucket_iter);
}
bool ObfuscatedFileUtil::InitOriginDatabase(const url::Origin& origin_hint,
bool create) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (origin_database_)
return true;
if (!delegate_->DirectoryExists(file_system_directory_)) {
if (!create)
return false;
if (delegate_->CreateDirectory(
file_system_directory_, false /* exclusive */,
true /* recursive */) != base::File::FILE_OK) {
LOG(WARNING) << "Failed to create FileSystem directory: "
<< file_system_directory_.value();
return false;
}
}
origin_database_ = std::make_unique<SandboxOriginDatabase>(
file_system_directory_, env_override_);
return true;
}
base::File::Error ObfuscatedFileUtil::GenerateNewLocalPath(
SandboxDirectoryDatabase* db,
FileSystemOperationContext* context,
const FileSystemURL& url,
base::FilePath* root,
base::FilePath* local_path) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(local_path);
int64_t number;
if (!db || !db->GetNextInteger(&number))
return base::File::FILE_ERROR_FAILED;
ASSIGN_OR_RETURN(*root, GetDirectoryForURL(url, false));
// We use the third- and fourth-to-last digits as the directory.
int64_t directory_number = number % 10000 / 100;
base::FilePath new_local_path =
root->AppendASCII(base::StringPrintf("%02" PRId64, directory_number));
base::File::Error error = base::File::FILE_OK;
error = delegate_->CreateDirectory(new_local_path, false /* exclusive */,
false /* recursive */);
if (error != base::File::FILE_OK)
return error;
*local_path =
new_local_path.AppendASCII(base::StringPrintf("%08" PRId64, number));
return base::File::FILE_OK;
}
base::File ObfuscatedFileUtil::CreateOrOpenInternal(
FileSystemOperationContext* context,
const FileSystemURL& url,
int file_flags) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(!(file_flags &
(base::File::FLAG_DELETE_ON_CLOSE | base::File::FLAG_WIN_HIDDEN |
base::File::FLAG_WIN_EXCLUSIVE_READ |
base::File::FLAG_WIN_EXCLUSIVE_WRITE)));
SandboxDirectoryDatabase* db = GetDirectoryDatabase(url, true);
if (!db)
return base::File(base::File::FILE_ERROR_FAILED);
FileId file_id;
if (!db->GetFileWithPath(url.path(), &file_id)) {
// The file doesn't exist.
if (!(file_flags &
(base::File::FLAG_CREATE | base::File::FLAG_CREATE_ALWAYS |
base::File::FLAG_OPEN_ALWAYS))) {
return base::File(base::File::FILE_ERROR_NOT_FOUND);
}
FileId parent_id;
if (!db->GetFileWithPath(VirtualPath::DirName(url.path()), &parent_id))
return base::File(base::File::FILE_ERROR_NOT_FOUND);
FileInfo file_info;
InitFileInfo(&file_info, parent_id,
VirtualPath::BaseName(url.path()).value());
int64_t growth = UsageForPath(file_info.name.size());
if (!AllocateQuota(context, growth))
return base::File(base::File::FILE_ERROR_NO_SPACE);
base::File file = CreateAndOpenFile(context, url, &file_info, file_flags);
if (file.IsValid()) {
UpdateUsage(context, url, growth);
context->change_observers()->Notify(&FileChangeObserver::OnCreateFile,
url);
}
return file;
}
if (file_flags & base::File::FLAG_CREATE)
return base::File(base::File::FILE_ERROR_EXISTS);
base::File::Info platform_file_info;
base::FilePath local_path;
FileInfo file_info;
base::File::Error error = GetFileInfoInternal(
db, context, url, file_id, &file_info, &platform_file_info, &local_path);
if (error != base::File::FILE_OK)
return base::File(error);
if (file_info.is_directory())
return base::File(base::File::FILE_ERROR_NOT_A_FILE);
int64_t delta = 0;
if (file_flags &
(base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_OPEN_TRUNCATED)) {
// The file exists and we're truncating.
delta = -platform_file_info.size;
AllocateQuota(context, delta);
}
base::File file = delegate_->CreateOrOpen(local_path, file_flags);
if (!file.IsValid()) {
error = file.error_details();
if (error == base::File::FILE_ERROR_NOT_FOUND) {
// TODO(tzik): Also invalidate on-memory usage cache in UsageTracker.
// TODO(tzik): Delete database entry after ensuring the file lost.
InvalidateUsageCache(context, url.storage_key(), url.type());
LOG(WARNING) << "Lost a backing file.";
return base::File(base::File::FILE_ERROR_FAILED);
}
return file;
}
// If truncating we need to update the usage.
if (delta) {
UpdateUsage(context, url, delta);
context->change_observers()->Notify(&FileChangeObserver::OnModifyFile, url);
}
return file;
}
bool ObfuscatedFileUtil::HasIsolatedStorage(
const blink::StorageKey& storage_key) {
return special_storage_policy_.get() &&
special_storage_policy_->HasIsolatedStorage(
storage_key.origin().GetURL());
}
} // namespace storage
|