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
|
// 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 "chromeos/ash/components/disks/disk_mount_manager.h"
#include <fcntl.h>
#include <stddef.h>
#include <stdint.h>
#include <sys/stat.h>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <string_view>
#include <type_traits>
#include <utility>
#include <vector>
#include "base/barrier_closure.h"
#include "base/containers/contains.h"
#include "base/files/file_path.h"
#include "base/files/scoped_file.h"
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/logging.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/metrics/histogram_functions.h"
#include "base/observer_list.h"
#include "base/posix/eintr_wrapper.h"
#include "base/strings/strcat.h"
#include "base/strings/string_util.h"
#include "base/system/sys_info.h"
#include "base/task/thread_pool.h"
#include "base/threading/scoped_blocking_call.h"
#include "chromeos/ash/components/dbus/cros_disks/cros_disks_client.h"
#include "chromeos/ash/components/disks/disk.h"
#include "chromeos/ash/components/disks/suspend_unmount_manager.h"
namespace ash::disks {
namespace {
using base::BindOnce;
std::string Redact(std::string_view s) {
return LOG_IS_ON(INFO) ? base::StrCat({"'", s, "'"}) : "(redacted)";
}
DiskMountManager* g_disk_mount_manager = nullptr;
struct UnmountDeviceRecursivelyCallbackData {
explicit UnmountDeviceRecursivelyCallbackData(
DiskMountManager::UnmountDeviceRecursivelyCallbackType in_callback)
: callback(std::move(in_callback)) {}
DiskMountManager::UnmountDeviceRecursivelyCallbackType callback;
MountError error_code = MountError::kSuccess;
};
void OnAllUnmountDeviceRecursively(
std::unique_ptr<UnmountDeviceRecursivelyCallbackData> cb_data) {
std::move(cb_data->callback).Run(cb_data->error_code);
}
std::string FormatFileSystemTypeToString(FormatFileSystemType filesystem) {
switch (filesystem) {
case FormatFileSystemType::kUnknown:
return "";
case FormatFileSystemType::kVfat:
return "vfat";
case FormatFileSystemType::kExfat:
return "exfat";
case FormatFileSystemType::kNtfs:
return "ntfs";
}
NOTREACHED() << "Unknown filesystem type " << static_cast<int>(filesystem);
}
// Fixes permissions along the given path if it is actually a local file path
// designating a file under ~/MyFiles. Does nothing if the given path is not an
// absolute local path designating a file under ~/MyFiles (like e.g. a URL-like
// string). This is a best effort attempt to ensure that the ChromeOS archive
// mounting daemons can access the archive files to mount.
void FixPermissions(const std::string_view path) {
const base::ScopedBlockingCall guard(FROM_HERE,
base::BlockingType::MAY_BLOCK);
// Is path an absolute local path?
if (!path.starts_with('/')) {
// Not an absolute local path. Might be a URL-like string.
return;
}
// Is path in ~/MyFiles?
std::vector<std::string> parts = base::FilePath(path).GetComponents();
if (!(parts.size() > 5 && parts[0] == "/" && parts[1] == "home" &&
parts[2] == "chronos" && parts[3].starts_with("u-") &&
parts[4] == "MyFiles" && !parts[5].empty())) {
// Not in ~/MyFiles.
return;
}
// Path is in ~/MyFiles. Keep the last part for the end.
const std::string file_name = std::move(parts.back());
parts.pop_back();
// Pre-allocate the bytes of this path to avoid multiple memory allocations.
std::string path_so_far;
path_so_far.reserve(path.size());
// Don't check the permissions on the first 5 levels of directories (that is
// up to ~/MyFiles). Just get a file descriptor to ~/MyFiles. Using openat
// with O_DIRECTORY ensures that the considered item is really a directory and
// that no race condition could possibly affect the next steps.
base::StrAppend(&path_so_far,
{"/", parts[1], "/", parts[2], "/", parts[3], "/", parts[4]});
base::ScopedFD fd(
HANDLE_EINTR(open(path_so_far.c_str(), O_DIRECTORY | O_PATH)));
if (!fd.is_valid()) {
PLOG(ERROR) << "Cannot open " << path_so_far;
return;
}
// GID for `chronos-access`.
const gid_t chronos_access = 1001;
// Check the permissions of all the directories from that point on (i.e. under
// ~/MyFiles).
for (size_t i = 5; i < parts.size(); ++i) {
const std::string& dir_name = parts[i];
if (dir_name.empty() || dir_name == "." || dir_name == "..") {
LOG(ERROR) << "Invalid directory name " << dir_name;
return;
}
// Get a file descriptor to the directory. Using openat with O_DIRECTORY
// ensures that the item is really a directory and that no race condition
// could possibly affect the next steps.
base::StrAppend(&path_so_far, {"/", dir_name});
fd.reset(
HANDLE_EINTR(openat(fd.get(), dir_name.c_str(), O_DIRECTORY | O_PATH)));
if (!fd.is_valid()) {
PLOG(ERROR) << "Cannot open " << path_so_far;
return;
}
// Get the current permissions of the directory.
struct stat z;
if (fstatat(fd.get(), "", &z, AT_EMPTY_PATH) < 0) {
PLOG(ERROR) << "Cannot stat " << path_so_far;
continue;
}
// Since openat was called with O_DIRECTORY, the item should really be a
// directory.
DCHECK(S_ISDIR(z.st_mode)) << " Not a directory: " << path_so_far;
// We want the directory to be traversable by a member of the chronos-access
// group. So, if its GID is chronos-access, then it needs to be at least
// group-traversable (S_IXGRP access bit), otherwise it also needs to be
// world-traversable (S_IXOTH access bit).
const mode_t mode = z.st_mode & 07777;
mode_t want = S_IXUSR | S_IXGRP;
if (z.st_gid != chronos_access) {
want |= S_IXOTH;
}
// Does the directory have the necessary permissions?
if ((mode & want) == want) {
// The directory already has the right permissions.
continue;
}
// Adjust the permissions as necessary.
if (fchmodat(fd.get(), "", mode | want, AT_EMPTY_PATH) < 0) {
PLOG(ERROR) << "Cannot change permissions of " << path_so_far;
continue;
}
VLOG(1) << "Changed permissions of " << path_so_far;
}
// Finished checking the directories.
// Check the last part of the path, which should be a file name.
if (file_name.empty() || file_name == "." || file_name == "..") {
LOG(ERROR) << "Invalid file name " << file_name;
return;
}
// Get a file descriptor to the file. Using openat ensures that no race
// condition could possibly affect the next steps.
base::StrAppend(&path_so_far, {"/", file_name});
fd.reset(HANDLE_EINTR(openat(fd.get(), file_name.c_str(), O_PATH)));
if (!fd.is_valid()) {
PLOG(ERROR) << "Cannot open " << path_so_far;
return;
}
// Get the current permissions of the file.
struct stat z;
if (fstatat(fd.get(), "", &z, AT_EMPTY_PATH) < 0) {
PLOG(ERROR) << "Cannot stat " << path_so_far;
return;
}
// Is the item a regular file?
if (!S_ISREG(z.st_mode)) {
LOG(ERROR) << "Item " << path_so_far << " is not a regular file";
return;
}
// We want the file to be readable by a member of the chronos-access group.
// So, if its GID is chronos-access, then it needs to be at least
// group-readable (S_IRGRP access bit), otherwise it also needs to be
// world-readable (S_IROTH access bit).
const mode_t mode = z.st_mode & 07777;
mode_t want = S_IRUSR | S_IRGRP;
if (z.st_gid != chronos_access) {
want |= S_IROTH;
}
// Does the file have the necessary permissions?
if ((mode & want) == want) {
// The file already has the right permissions.
return;
}
// Adjust the permissions as necessary.
if (fchmodat(fd.get(), "", mode | want, AT_EMPTY_PATH) < 0) {
PLOG(ERROR) << "Cannot change permissions of " << path_so_far;
return;
}
VLOG(1) << "Changed permissions of " << path_so_far;
}
// The DiskMountManager implementation.
class DiskMountManagerImpl : public DiskMountManager,
public CrosDisksClient::Observer {
public:
DiskMountManagerImpl() { cros_disks_client_->AddObserver(this); }
DiskMountManagerImpl(const DiskMountManagerImpl&) = delete;
DiskMountManagerImpl& operator=(const DiskMountManagerImpl&) = delete;
~DiskMountManagerImpl() override { cros_disks_client_->RemoveObserver(this); }
private:
using DiskMountManager::Observer;
// DiskMountManager override.
void AddObserver(Observer* observer) override {
observers_.AddObserver(observer);
}
// DiskMountManager override.
void RemoveObserver(Observer* observer) override {
observers_.RemoveObserver(observer);
}
// DiskMountManager override.
void MountPath(const std::string& source_path,
const std::string& source_format,
const std::string& mount_label,
const std::vector<std::string>& mount_options,
MountType type,
MountAccessMode access_mode,
MountPathCallback callback) override {
if (const auto [_, ok] =
mount_callbacks_.try_emplace(source_path, std::move(callback));
!ok) {
LOG(ERROR) << "Disk '" << source_path << "' is already being mounted";
std::move(callback).Run(MountError::kPathAlreadyMounted,
{source_path, "", type});
return;
}
const Disks::const_iterator it = disks_.find(source_path);
if (it != disks_.end()) {
VLOG(1) << "Disk '" << source_path << "' is already registered";
DCHECK(*it);
DCHECK_EQ((*it)->device_path(), source_path);
} else {
VLOG(1) << "Disk '" << source_path << "' is not registered yet";
}
// Hidden and non-existent devices should not be mounted.
if (type == MountType::kDevice &&
(it == disks_.end() || (*it)->is_hidden())) {
VLOG(1) << "Disk '" << source_path << "' should not be mounted";
OnMountCompleted({source_path, {}, type, MountError::kInternalError});
return;
}
base::ThreadPool::PostTaskAndReply(
FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE},
base::BindOnce(&FixPermissions, source_path),
base::BindOnce(&DiskMountManagerImpl::MountAfterFixingPermissions,
weak_ptr_factory_.GetWeakPtr(), source_path,
source_format, mount_label, mount_options, type,
access_mode));
}
void MountAfterFixingPermissions(
const std::string& source_path,
const std::string& source_format,
const std::string& mount_label,
const std::vector<std::string>& mount_options,
const MountType type,
const MountAccessMode access_mode) {
VLOG(1) << "Mounting '" << source_path << "'...";
cros_disks_client_->Mount(
source_path, source_format, mount_label, mount_options, access_mode,
RemountOption::kMountNewDevice,
BindOnce(&DiskMountManagerImpl::OnMount, weak_ptr_factory_.GetWeakPtr(),
source_path, type));
}
// DiskMountManager override.
void UnmountPath(const std::string& mount_path,
UnmountPathCallback callback) override {
UnmountChildMounts(mount_path);
VLOG(1) << "Unmounting '" << mount_path << "'...";
const base::FilePath mount_file_path(mount_path);
if (arc_delegate_ &&
cros_disks_client_->GetRemovableDiskMountPoint().IsParent(
mount_file_path)) {
VLOG(1) << "Dropping ARC caches for " << Redact(mount_path);
arc_delegate_->DropArcCaches(
mount_file_path, BindOnce(&DiskMountManagerImpl::UnmountPathContinue,
weak_ptr_factory_.GetWeakPtr(), mount_path,
std::move(callback)));
return;
}
UnmountPathContinue(mount_path, std::move(callback), true /* success */);
}
void UnmountPathContinue(const std::string& mount_path,
UnmountPathCallback callback,
bool success) {
if (!success) {
LOG(ERROR) << "Cannot drop ARC caches for " << Redact(mount_path);
}
cros_disks_client_->Unmount(mount_path,
BindOnce(&DiskMountManagerImpl::OnUnmountPath,
weak_ptr_factory_.GetWeakPtr(),
std::move(callback), mount_path));
}
// DiskMountManager override.
void FormatMountedDevice(const std::string& mount_path,
FormatFileSystemType filesystem,
const std::string& label) override {
MountPoints::const_iterator mount_point = mount_points_.find(mount_path);
if (mount_point == mount_points_.end()) {
LOG(ERROR) << "Cannot find mount point " << Redact(mount_path);
// We can't call OnFormatCompleted until |pending_format_changes_| has
// been populated.
NotifyFormatStatusUpdate(FORMAT_COMPLETED, FormatError::kUnknownError,
mount_path, label);
return;
}
std::string device_path = mount_point->source_path;
const std::string filesystem_str = FormatFileSystemTypeToString(filesystem);
pending_format_changes_[device_path] = {filesystem_str, label};
Disks::const_iterator disk = disks_.find(device_path);
if (disk == disks_.end()) {
LOG(ERROR) << "Cannot find device '" << device_path << "'";
OnFormatCompleted(FormatError::kUnknownError, device_path);
return;
}
if (disk->get()->is_read_only()) {
LOG(ERROR) << "Device '" << device_path << "' is read-only";
OnFormatCompleted(FormatError::kDeviceNotAllowed, device_path);
return;
}
if (filesystem == FormatFileSystemType::kUnknown) {
LOG(ERROR) << "Unknown filesystem passed to FormatMountedDevice";
OnFormatCompleted(FormatError::kUnsupportedFilesystem, device_path);
return;
}
UnmountPath(disk->get()->mount_path(),
BindOnce(&DiskMountManagerImpl::OnUnmountPathForFormat,
weak_ptr_factory_.GetWeakPtr(), device_path,
filesystem, label));
}
// DiskMountManager override.
void SinglePartitionFormatDevice(const std::string& device_path,
FormatFileSystemType filesystem,
const std::string& label) override {
Disks::const_iterator disk_iter = disks_.find(device_path);
if (disk_iter == disks_.end()) {
LOG(ERROR) << "Cannot find device '" << device_path << "'";
OnPartitionCompleted(device_path, filesystem, label,
PartitionError::kInvalidDevicePath);
return;
}
UnmountDeviceRecursively(
device_path,
BindOnce(&DiskMountManagerImpl::OnUnmountDeviceForSinglePartitionFormat,
weak_ptr_factory_.GetWeakPtr(), device_path, filesystem,
label));
}
void RenameMountedDevice(const std::string& mount_path,
const std::string& volume_name) override {
MountPoints::const_iterator mount_point = mount_points_.find(mount_path);
if (mount_point == mount_points_.end()) {
LOG(ERROR) << "Cannot find mount point '" << mount_path << "'";
// We can't call OnRenameCompleted until |pending_rename_changes_| has
// been populated.
NotifyRenameStatusUpdate(RENAME_COMPLETED, RenameError::kUnknownError,
mount_path, volume_name);
return;
}
std::string device_path = mount_point->source_path;
pending_rename_changes_[device_path] = volume_name;
Disks::const_iterator iter = disks_.find(device_path);
if (iter == disks_.end()) {
LOG(ERROR) << "Cannot find device '" << device_path << "'";
OnRenameCompleted(RenameError::kUnknownError, device_path);
return;
}
if (iter->get()->is_read_only()) {
LOG(ERROR) << "Device '" << device_path << "' is read-only";
OnRenameCompleted(RenameError::kDeviceNotAllowed, device_path);
return;
}
UnmountPath(
iter->get()->mount_path(),
BindOnce(&DiskMountManagerImpl::OnUnmountPathForRename,
weak_ptr_factory_.GetWeakPtr(), device_path, volume_name));
}
// DiskMountManager override.
void UnmountDeviceRecursively(
const std::string& device_path,
UnmountDeviceRecursivelyCallbackType callback) override {
std::vector<std::string> devices_to_unmount;
// Get list of all devices to unmount.
for (const auto& disk : disks_) {
DCHECK(disk);
if (!disk->mount_path().empty() &&
base::StartsWith(disk->device_path(), device_path)) {
devices_to_unmount.push_back(disk->mount_path());
}
}
// Is there anything to unmount?
if (devices_to_unmount.empty()) {
const auto it = disks_.find(device_path);
if (it == disks_.end()) {
LOG(ERROR) << "Cannot find device '" << device_path << "'";
std::move(callback).Run(MountError::kInvalidDevicePath);
return;
}
// Nothing to unmount.
DCHECK(*it);
DCHECK_EQ((*it)->device_path(), device_path);
DCHECK_EQ((*it)->mount_path(), "");
LOG(WARNING) << "Disk '" << device_path << "' is already unmounted";
std::move(callback).Run(MountError::kSuccess);
return;
}
// There is something to unmount.
std::unique_ptr<UnmountDeviceRecursivelyCallbackData> cb_data =
std::make_unique<UnmountDeviceRecursivelyCallbackData>(
std::move(callback));
UnmountDeviceRecursivelyCallbackData* raw_cb_data = cb_data.get();
base::RepeatingClosure done_callback = base::BarrierClosure(
devices_to_unmount.size(),
BindOnce(&OnAllUnmountDeviceRecursively, std::move(cb_data)));
for (const std::string& device : devices_to_unmount) {
VLOG(1) << "Unmounting '" << device << "'...";
cros_disks_client_->Unmount(
device, BindOnce(&DiskMountManagerImpl::OnUnmountDeviceRecursively,
weak_ptr_factory_.GetWeakPtr(), raw_cb_data, device,
done_callback));
}
}
// DiskMountManager override.
void EnsureMountInfoRefreshed(EnsureMountInfoRefreshedCallback callback,
bool force) override {
if (!force && already_refreshed_) {
std::move(callback).Run(true);
return;
}
refresh_callbacks_.push_back(std::move(callback));
if (refresh_callbacks_.size() == 1) {
// If there's no in-flight refreshing task, start it.
cros_disks_client_->EnumerateDevices(
BindOnce(&DiskMountManagerImpl::RefreshAfterEnumerateDevices,
weak_ptr_factory_.GetWeakPtr()),
BindOnce(&DiskMountManagerImpl::RefreshCompleted,
weak_ptr_factory_.GetWeakPtr(), false));
}
}
// DiskMountManager override.
const Disks& disks() const override { return disks_; }
// DiskMountManager override.
const Disk* FindDiskBySourcePath(
std::string_view source_path) const override {
const Disks::const_iterator it = disks_.find(source_path);
return it == disks_.end() ? nullptr : it->get();
}
// DiskMountManager override.
const MountPoints& mount_points() const override { return mount_points_; }
// DiskMountManager override.
bool AddDiskForTest(std::unique_ptr<Disk> disk) override {
const auto [it, ok] = disks_.insert(std::move(disk));
LOG_IF(ERROR, !ok) << "Cannot add a duplicate disk '"
<< (*it)->device_path() << "'";
return ok;
}
// DiskMountManager override.
// Corresponding disk should be added to the manager before this is called.
bool AddMountPointForTest(const MountPoint& mount_point) override {
if (mount_point.mount_type == MountType::kDevice &&
disks_.count(mount_point.source_path) == 0) {
LOG(ERROR) << "Device mount point '" << mount_point.mount_path
<< "' should have a disk entry '" << mount_point.source_path
<< "'";
return false;
}
const auto [it, ok] = mount_points_.insert(mount_point);
DCHECK_EQ(it->mount_path, mount_point.mount_path);
LOG_IF(ERROR, !ok) << "Cannot add a duplicate mount point '"
<< mount_point.mount_path << "'";
return ok;
}
// A struct to represent information about a format changes.
struct FormatChange {
// new file system type
std::string file_system_type;
// New volume name
std::string volume_name;
};
// Stores new volume name and file system type for a device on which
// formatting is invoked on, so that OnFormatCompleted can set it back to
// |disks_|. The key is a device_path and the value is a FormatChange.
std::map<std::string, FormatChange> pending_format_changes_;
// Stores device path are being partitioning.
// It allows preventing auto-mount of the disks in this set.
std::set<std::string> pending_partitioning_disks_;
// Stores new volume name for a device on which renaming is invoked on, so
// that OnRenameCompleted can set it back to |disks_|. The key is a
// device_path and the value is new volume_name.
std::map<std::string, std::string> pending_rename_changes_;
// Called on D-Bus CrosDisksClient::Mount() is done.
void OnMount(const std::string& source_path, MountType type, bool result) {
// When succeeds, OnMountCompleted will be called by "MountCompleted",
// signal instead. Do nothing now.
if (result) {
return;
}
OnMountCompleted({source_path, {}, type, MountError::kInternalError});
}
void RemountRemovableDrive(const Disk& disk,
MountAccessMode access_mode) override {
// TODO(yamaguchi): Retry for tentative remount failures. crbug.com/661455
if (disk.is_read_only_hardware()) {
// Read-only devices can be mounted in RO mode only. No need to remount.
return;
}
if (!disk.is_mounted()) {
return;
}
const std::string& mount_path = disk.mount_path();
MountPoints::const_iterator mount_point = mount_points_.find(mount_path);
if (mount_point == mount_points_.end()) {
// Not in mount_points_. This happens when the mount_points and disks_ are
// inconsistent.
LOG(ERROR) << "Cannot find mount point " << Redact(mount_path);
OnMountCompleted({disk.device_path(), mount_path, MountType::kDevice,
MountError::kPathNotMounted});
return;
}
cros_disks_client_->Mount(
mount_point->source_path, std::string(), std::string(), {}, access_mode,
RemountOption::kRemountExistingDevice,
BindOnce(&DiskMountManagerImpl::OnMount, weak_ptr_factory_.GetWeakPtr(),
mount_point->source_path, mount_point->mount_type));
}
// Unmounts all mount points whose source path is transitively parented by
// |mount_path|.
void UnmountChildMounts(std::string mount_path) {
DCHECK(!mount_path.empty());
// Let's make sure mount path has trailing slash.
if (mount_path.back() != '/') {
mount_path += '/';
}
// Paths to unmount, indexed by source path.
std::map<std::string, std::string> paths_to_unmount;
// For the already known mount points, use the mount path.
for (const MountPoint& mount_point : mount_points_) {
if (base::StartsWith(mount_point.source_path, mount_path)) {
paths_to_unmount.try_emplace(mount_point.source_path,
mount_point.mount_path);
}
}
// For the mount points that are not registered yet, use the source path.
for (const auto& [source_path, _] : mount_callbacks_) {
if (base::StartsWith(source_path, mount_path)) {
paths_to_unmount.try_emplace(source_path, source_path);
}
}
for (const auto& [_, path_to_unmount] : paths_to_unmount) {
UnmountPath(path_to_unmount, {});
}
}
// Callback for UnmountDeviceRecursively.
void OnUnmountDeviceRecursively(UnmountDeviceRecursivelyCallbackData* cb_data,
const std::string& mount_path,
base::OnceClosure done_callback,
const MountError error) {
if (error == MountError::kPathNotMounted ||
error == MountError::kInvalidPath || error == MountError::kSuccess) {
// Do standard processing for Unmount event.
OnUnmountPath(UnmountPathCallback(), mount_path, error);
} else {
LOG(ERROR) << "Cannot unmount " << Redact(mount_path) << ": " << error;
// This causes the last non-success error to be reported.
cb_data->error_code = error;
}
std::move(done_callback).Run();
}
// CrosDisksClient::Observer override.
void OnMountCompleted(const MountPoint& entry) override {
if (const auto it = deferred_mount_events_.find(entry.source_path);
it != deferred_mount_events_.end()) {
it->second.push_back(entry);
VLOG(1) << "Added mount_path '" << entry.mount_path
<< "' to deferred mount events";
return;
}
bool want_to_keep = entry.mount_error == MountError::kSuccess;
MountError mount_error = MountError::kSuccess;
if (entry.mount_type == MountType::kDevice) {
if (entry.mount_error == MountError::kUnknownFilesystem) {
mount_error = MountError::kUnknownFilesystem;
want_to_keep = true;
} else if (entry.mount_error == MountError::kUnsupportedFilesystem) {
mount_error = MountError::kUnsupportedFilesystem;
want_to_keep = true;
}
}
const MountPoint mount_info{
entry.source_path, entry.mount_path, entry.mount_type, mount_error, 100,
entry.read_only};
// If the device is corrupted but it's still possible to format it, it will
// be fake mounted.
if (want_to_keep) {
VLOG(1) << "Mounted '" << mount_info.source_path << "' as '"
<< mount_info.mount_path << "'";
const auto [it, ok] = mount_points_.insert(mount_info);
if (!ok) {
DCHECK_EQ(it->mount_path, mount_info.mount_path);
// const_cast is Ok since we're not modifying it->mount_path.
const_cast<MountPoint&>(*it) = mount_info;
VLOG(1) << "Updated mount point '" << mount_info.mount_path << "'";
}
} else {
if (base::SysInfo::IsRunningOnChromeOS()) {
LOG(ERROR) << "Cannot mount " << Redact(mount_info.source_path)
<< " as " << Redact(mount_info.mount_path) << ": "
<< entry.mount_error;
}
if (const MountPoints::const_iterator it =
mount_points_.find(mount_info.mount_path);
it != mount_points_.end()) {
VLOG(1) << "Removed mount point '" << mount_info.mount_path << "'";
mount_points_.erase(it);
}
}
const Disks::const_iterator disk_it = disks_.find(mount_info.source_path);
Disk* const disk = disk_it != disks_.end() ? disk_it->get() : nullptr;
if (want_to_keep && mount_info.mount_type == MountType::kDevice &&
!mount_info.source_path.empty() && !mount_info.mount_path.empty() &&
disk) {
DCHECK(disk);
DCHECK_EQ(disk->device_path(), mount_info.source_path);
// Store whether the disk was mounted in read-only mode due to a policy.
disk->set_write_disabled_by_policy(!disk->is_read_only_hardware() &&
entry.read_only);
// Right now, a number of operations (format, rename, unmount) rely on the
// mount path being set even if the disk isn't mounted. cros-disks also
// does some tracking of non-mounted mount paths.
disk->SetMountPath(mount_info.mount_path);
disk->set_mounted(entry.mount_error == MountError::kSuccess);
}
// Observers may read the values of disks_. So notify them after tweaking
// values of disks_.
if (auto it = mount_callbacks_.find(entry.source_path);
it != mount_callbacks_.end()) {
DCHECK_EQ(it->first, entry.source_path);
VLOG(1) << "Calling mount callback for '" << entry.source_path
<< "' with result = " << entry.mount_error;
std::move(it->second).Run(entry.mount_error, mount_info);
mount_callbacks_.erase(std::move(it));
} else {
VLOG(1) << "No mount callback for " << Redact(entry.source_path);
}
NotifyMountStatusUpdate(MOUNTING, entry.mount_error, mount_info);
if (disk) {
DCHECK(disk_it != disks_.end());
disk->set_is_first_mount(false);
if (!want_to_keep) {
VLOG(1) << "Removed Disk '" << disk->device_path() << "'";
disks_.erase(disk_it);
}
}
}
// CrosDisksClient::Observer override.
void OnMountProgress(const MountPoint& entry) override {
DCHECK_EQ(entry.mount_error, MountError::kInProgress);
const auto [it, ok] = mount_points_.insert(
{entry.source_path, entry.mount_path, entry.mount_type,
MountError::kInProgress, entry.progress_percent, entry.read_only});
if (ok) {
DCHECK_EQ(it->mount_path, entry.mount_path);
VLOG(1) << "Added in-progress mount point '" << entry.mount_path
<< "' with " << entry.progress_percent << "%";
return;
}
// const_cast is Ok since we're not modifying it->mount_path.
MountPoint& mount_point = const_cast<MountPoint&>(*it);
DCHECK_EQ(mount_point.mount_path, entry.mount_path);
DCHECK_EQ(mount_point.source_path, entry.source_path);
DCHECK_EQ(mount_point.mount_type, entry.mount_type);
DCHECK_EQ(mount_point.mount_error, MountError::kInProgress);
DCHECK_EQ(mount_point.read_only, entry.read_only);
mount_point.progress_percent = entry.progress_percent;
VLOG(1) << "Updated in-progress mount point '" << entry.mount_path
<< "' to " << entry.progress_percent << "%";
}
// Callback for UnmountPath.
void OnUnmountPath(UnmountPathCallback callback,
const std::string& mount_path,
MountError error) {
if (error == MountError::kSuccess) {
VLOG(1) << "Unmounted '" << mount_path << "'";
} else {
LOG(ERROR) << "Cannot unmount " << Redact(mount_path) << ": " << error;
if (error == MountError::kPathNotMounted ||
error == MountError::kInvalidPath) {
// The path was already unmounted by something else.
error = MountError::kSuccess;
}
}
if (const MountPoints::const_iterator it = mount_points_.find(mount_path);
it != mount_points_.end()) {
if (error == MountError::kSuccess) {
const MountPoints::node_type n = mount_points_.extract(it);
DCHECK(n);
const MountPoint& mount_point = n.value();
if (const Disks::const_iterator disk =
disks_.find(mount_point.source_path);
disk != disks_.end()) {
DCHECK(*disk);
(*disk)->clear_mount_path();
(*disk)->set_mounted(false);
}
NotifyMountStatusUpdate(UNMOUNTING, error, mount_point);
} else {
NotifyMountStatusUpdate(UNMOUNTING, error, *it);
}
}
if (callback) {
std::move(callback).Run(error);
}
}
void OnUnmountPathForFormat(const std::string& device_path,
FormatFileSystemType filesystem,
const std::string& label,
MountError error_code) {
if (error_code == MountError::kSuccess && disks_.count(device_path) != 0) {
FormatUnmountedDevice(device_path, filesystem, label);
} else {
OnFormatCompleted(FormatError::kUnknownError, device_path);
}
}
void OnUnmountDeviceForSinglePartitionFormat(const std::string& device_path,
FormatFileSystemType filesystem,
const std::string& label,
MountError error_code) {
if (error_code != MountError::kSuccess || disks_.count(device_path) == 0) {
OnPartitionCompleted(device_path, filesystem, label,
PartitionError::kUnknownError);
return;
}
SinglePartitionFormatUnmountedDevice(device_path, filesystem, label);
}
// Starts device formatting.
void FormatUnmountedDevice(const std::string& device_path,
FormatFileSystemType filesystem,
const std::string& label) {
Disks::const_iterator disk = disks_.find(device_path);
DCHECK(disk != disks_.end() && disk->get()->mount_path().empty());
base::UmaHistogramEnumeration("FileBrowser.FormatFileSystemType",
filesystem);
cros_disks_client_->Format(
device_path, FormatFileSystemTypeToString(filesystem), label,
BindOnce(&DiskMountManagerImpl::OnFormatStarted,
weak_ptr_factory_.GetWeakPtr(), device_path, label));
}
// Callback for Format.
void OnFormatStarted(const std::string& device_path,
const std::string& device_label,
bool success) {
if (!success) {
OnFormatCompleted(FormatError::kUnknownError, device_path);
return;
}
NotifyFormatStatusUpdate(FORMAT_STARTED, FormatError::kSuccess, device_path,
device_label);
}
// CrosDisksClient::Observer override.
void OnFormatCompleted(FormatError error_code,
const std::string& device_path) override {
std::string device_label;
auto pending_change = pending_format_changes_.find(device_path);
if (pending_change != pending_format_changes_.end()) {
device_label = pending_change->second.volume_name;
}
auto iter = disks_.find(device_path);
// disk might have been removed by now?
if (iter != disks_.end()) {
Disk* const disk = iter->get();
DCHECK(disk);
if (pending_change != pending_format_changes_.end() &&
error_code == FormatError::kSuccess) {
disk->set_device_label(pending_change->second.volume_name);
disk->set_file_system_type(pending_change->second.file_system_type);
}
}
pending_format_changes_.erase(device_path);
EnsureMountInfoRefreshed(base::DoNothing(), true /* force */);
NotifyFormatStatusUpdate(FORMAT_COMPLETED, error_code, device_path,
device_label);
}
void SinglePartitionFormatUnmountedDevice(const std::string& device_path,
FormatFileSystemType filesystem,
const std::string& label) {
Disks::const_iterator disk = disks_.find(device_path);
DCHECK(disk != disks_.end() && disk->get()->mount_path().empty());
pending_partitioning_disks_.insert(disk->get()->device_path());
NotifyPartitionStatusUpdate(PARTITION_STARTED, PartitionError::kSuccess,
device_path, label);
cros_disks_client_->SinglePartitionFormat(
disk->get()->file_path(),
BindOnce(&DiskMountManagerImpl::OnPartitionCompleted,
weak_ptr_factory_.GetWeakPtr(), device_path, filesystem,
label));
}
void OnPartitionCompleted(const std::string& device_path,
FormatFileSystemType filesystem,
const std::string& label,
PartitionError error_code) {
auto iter = disks_.find(device_path);
// disk might have been removed by now?
if (iter != disks_.end()) {
Disk* const disk = iter->get();
DCHECK(disk);
if (error_code == PartitionError::kSuccess) {
EnsureMountInfoRefreshed(
BindOnce(&DiskMountManagerImpl::OnRefreshAfterPartition,
weak_ptr_factory_.GetWeakPtr(), device_path, filesystem,
label),
true /* force */);
}
} else {
// Remove disk from pending partitioning list if disk removed.
pending_partitioning_disks_.erase(device_path);
}
NotifyPartitionStatusUpdate(PARTITION_COMPLETED, error_code, device_path,
label);
}
void OnRefreshAfterPartition(const std::string& device_path,
FormatFileSystemType filesystem,
const std::string& label,
bool success) {
Disks::const_iterator device_disk = disks_.find(device_path);
if (device_disk == disks_.end()) {
LOG(ERROR) << "Device not found, maybe ejected";
pending_partitioning_disks_.erase(device_path);
NotifyPartitionStatusUpdate(PARTITION_COMPLETED,
PartitionError::kInvalidDevicePath,
device_path, label);
return;
}
std::string new_partition_device_path;
// Find new partition using common storage path with parent device.
for (const auto& candidate : disks_) {
if (candidate->storage_device_path() ==
device_disk->get()->storage_device_path() &&
!candidate->is_parent()) {
new_partition_device_path = candidate->device_path();
break;
}
}
if (new_partition_device_path.empty()) {
LOG(ERROR) << "New partition couldn't be found";
pending_partitioning_disks_.erase(device_path);
NotifyPartitionStatusUpdate(PARTITION_COMPLETED,
PartitionError::kInvalidDevicePath,
device_path, label);
return;
}
const std::string filesystem_str = FormatFileSystemTypeToString(filesystem);
pending_format_changes_[new_partition_device_path] = {filesystem_str,
label};
// It's expected the disks (parent device and new partition) are not
// mounted, but try unmounting before starting format if it got
// mounted through another flow.
UnmountDeviceRecursively(
device_path, BindOnce(&DiskMountManagerImpl::OnUnmountPathForFormat,
weak_ptr_factory_.GetWeakPtr(),
new_partition_device_path, filesystem, label));
// It's ok to remove it from pending partitioning as format flow started.
pending_partitioning_disks_.erase(device_path);
}
void OnUnmountPathForRename(const std::string& device_path,
const std::string& volume_name,
MountError error_code) {
if (error_code != MountError::kSuccess || disks_.count(device_path) == 0) {
OnRenameCompleted(RenameError::kUnknownError, device_path);
return;
}
RenameUnmountedDevice(device_path, volume_name);
}
// Start device renaming
void RenameUnmountedDevice(const std::string& device_path,
const std::string& volume_name) {
const Disks::const_iterator disk = disks_.find(device_path);
DCHECK(disk != disks_.end() && disk->get()->mount_path().empty());
cros_disks_client_->Rename(
device_path, volume_name,
BindOnce(&DiskMountManagerImpl::OnRenameStarted,
weak_ptr_factory_.GetWeakPtr(), device_path, volume_name));
}
// Callback for Rename.
void OnRenameStarted(const std::string& device_path,
const std::string& volume_name,
bool success) {
if (!success) {
OnRenameCompleted(RenameError::kUnknownError, device_path);
return;
}
NotifyRenameStatusUpdate(RENAME_STARTED, RenameError::kSuccess, device_path,
volume_name);
}
// CrosDisksClient::Observer override.
void OnRenameCompleted(RenameError error_code,
const std::string& device_path) override {
std::string device_label;
auto pending_change = pending_rename_changes_.find(device_path);
if (pending_change != pending_rename_changes_.end()) {
device_label = pending_change->second;
}
auto iter = disks_.find(device_path);
// disk might have been removed by now?
if (iter != disks_.end()) {
Disk* const disk = iter->get();
DCHECK(disk);
if (pending_change != pending_rename_changes_.end() &&
error_code == RenameError::kSuccess) {
disk->set_device_label(pending_change->second);
}
}
pending_rename_changes_.erase(device_path);
NotifyRenameStatusUpdate(RENAME_COMPLETED, error_code, device_path,
device_label);
}
// Fire observer mount events that were deferred due to an in-progress
// GetDeviceProperties() call.
void RunDeferredMountEvents(const std::string& device_path) {
auto mount_events_iter = deferred_mount_events_.find(device_path);
if (mount_events_iter == deferred_mount_events_.end()) {
return;
}
std::vector<MountPoint> entries = std::move(mount_events_iter->second);
deferred_mount_events_.erase(mount_events_iter);
for (const MountPoint& entry : entries) {
OnMountCompleted(entry);
}
}
// Callback for GetDeviceProperties.
void OnGetDeviceProperties(const DiskInfo& disk_info) {
if (disk_info.is_virtual()) {
RunDeferredMountEvents(disk_info.device_path());
return;
}
VLOG(1) << "Found disk '" << disk_info.device_path() << "'";
// Delete previous disk info for this path:
bool is_new = true;
bool is_first_mount = false;
std::string base_mount_path = std::string();
if (Disks::iterator it = disks_.find(disk_info.device_path());
it != disks_.end()) {
is_first_mount = (*it)->is_first_mount();
base_mount_path = (*it)->base_mount_path();
disks_.erase(std::move(it));
is_new = false;
}
// If the device was mounted by the instance, apply recorded parameter.
// Otherwise, default to false.
// Lookup by |device_path| which we pass to cros-disks when mounting a
// device in |VolumeManager::OnDiskEvent()|.
const MountPoints::const_iterator mount_point =
mount_points_.find(disk_info.mount_path());
const bool write_disabled_by_policy =
mount_point != mount_points_.end() && mount_point->read_only;
std::unique_ptr<Disk> disk = std::make_unique<Disk>(
disk_info, write_disabled_by_policy, base_mount_path);
if (!is_new) {
disk->set_is_first_mount(is_first_mount);
}
const auto [it, ok] = disks_.insert(std::move(disk));
DCHECK(ok);
NotifyDiskStatusUpdate(is_new ? DISK_ADDED : DISK_CHANGED, **it);
RunDeferredMountEvents(disk_info.device_path());
}
// Part of EnsureMountInfoRefreshed(). Called after the list of devices are
// enumerated.
void RefreshAfterEnumerateDevices(const std::vector<std::string>& devices) {
std::set<std::string> current_device_set(devices.begin(), devices.end());
for (Disks::iterator iter = disks_.begin(); iter != disks_.end();) {
if (current_device_set.count(iter->get()->device_path()) == 0) {
iter = disks_.erase(iter);
} else {
++iter;
}
}
RefreshDeviceAtIndex(devices, 0);
}
// Part of EnsureMountInfoRefreshed(). Called for each device to refresh info.
void RefreshDeviceAtIndex(const std::vector<std::string>& devices,
size_t index) {
if (index == devices.size()) {
// All devices info retrieved. Proceed to enumerate mount point info.
cros_disks_client_->EnumerateMountEntries(
BindOnce(&DiskMountManagerImpl::RefreshAfterEnumerateMountEntries,
weak_ptr_factory_.GetWeakPtr()),
BindOnce(&DiskMountManagerImpl::RefreshCompleted,
weak_ptr_factory_.GetWeakPtr(), false));
return;
}
cros_disks_client_->GetDeviceProperties(
devices[index],
BindOnce(&DiskMountManagerImpl::RefreshAfterGetDeviceProperties,
weak_ptr_factory_.GetWeakPtr(), devices, index + 1),
BindOnce(&DiskMountManagerImpl::RefreshDeviceAtIndex,
weak_ptr_factory_.GetWeakPtr(), devices, index + 1));
}
// Part of EnsureMountInfoRefreshed().
void RefreshAfterGetDeviceProperties(const std::vector<std::string>& devices,
size_t next_index,
const DiskInfo& disk_info) {
OnGetDeviceProperties(disk_info);
RefreshDeviceAtIndex(devices, next_index);
}
// Part of EnsureMountInfoRefreshed(). Called after mount entries are listed.
void RefreshAfterEnumerateMountEntries(
const std::vector<MountPoint>& entries) {
for (const MountPoint& entry : entries) {
OnMountCompleted(entry);
}
RefreshCompleted(true);
}
// Part of EnsureMountInfoRefreshed(). Called when the refreshing is done.
void RefreshCompleted(bool success) {
already_refreshed_ = true;
for (auto& callback : refresh_callbacks_) {
std::move(callback).Run(success);
}
refresh_callbacks_.clear();
}
// CrosDisksClient::Observer override.
void OnMountEvent(const MountEventType event,
const std::string& device_path) override {
VLOG(1) << "OnMountEvent: " << event << " for '" << device_path << "'";
switch (event) {
case MountEventType::kDiskAdded:
// Ensure we have an entry indicating we're waiting for
// GetDeviceProperties() to complete.
deferred_mount_events_[device_path];
cros_disks_client_->GetDeviceProperties(
device_path,
BindOnce(&DiskMountManagerImpl::OnGetDeviceProperties,
weak_ptr_factory_.GetWeakPtr()),
base::DoNothing());
return;
case MountEventType::kDiskRemoved:
// Search and remove disks that are no longer present.
if (Disks::const_iterator it = disks_.find(device_path);
it != disks_.end()) {
DCHECK(*it);
NotifyDiskStatusUpdate(DISK_REMOVED, **it);
disks_.erase(std::move(it));
}
return;
case MountEventType::kDeviceAdded:
NotifyDeviceStatusUpdate(DEVICE_ADDED, device_path);
return;
case MountEventType::kDeviceRemoved:
NotifyDeviceStatusUpdate(DEVICE_REMOVED, device_path);
return;
case MountEventType::kDeviceScanned:
NotifyDeviceStatusUpdate(DEVICE_SCANNED, device_path);
return;
case MountEventType::kDiskChanged:
break;
}
LOG(ERROR) << "Unexpected mount event " << event << " for '" << device_path
<< "'";
}
// Notifies all observers about disk status update.
void NotifyDiskStatusUpdate(DiskEvent event, const Disk& disk) {
for (Observer& observer : observers_) {
// Skip mounting of new partitioned disks while waiting for the format.
if (IsPendingPartitioningDisk(disk.device_path())) {
continue;
}
disk.is_auto_mountable() ? observer.OnAutoMountableDiskEvent(event, disk)
: observer.OnBootDeviceDiskEvent(event, disk);
}
}
// Notifies all observers about device status update.
void NotifyDeviceStatusUpdate(DeviceEvent event,
const std::string& device_path) {
for (Observer& observer : observers_) {
observer.OnDeviceEvent(event, device_path);
}
}
// Notifies all observers about mount completion.
void NotifyMountStatusUpdate(MountEvent event,
MountError error_code,
const MountPoint& mount_info) {
for (Observer& observer : observers_) {
observer.OnMountEvent(event, error_code, mount_info);
}
}
void NotifyFormatStatusUpdate(FormatEvent event,
FormatError error_code,
const std::string& device_path,
const std::string& device_label) {
for (Observer& observer : observers_) {
observer.OnFormatEvent(event, error_code, device_path, device_label);
}
}
void NotifyPartitionStatusUpdate(PartitionEvent event,
PartitionError error_code,
const std::string& device_path,
const std::string& device_label) {
for (Observer& observer : observers_) {
observer.OnPartitionEvent(event, error_code, device_path, device_label);
}
}
void NotifyRenameStatusUpdate(RenameEvent event,
RenameError error_code,
const std::string& device_path,
const std::string& device_label) {
for (Observer& observer : observers_) {
observer.OnRenameEvent(event, error_code, device_path, device_label);
}
}
bool IsPendingPartitioningDisk(const std::string& device_path) {
if (base::Contains(pending_partitioning_disks_, device_path)) {
return true;
}
// If device path doesn't match check whether if it's a child path.
for (const auto& disk : pending_partitioning_disks_) {
if (base::StartsWith(device_path, disk, base::CompareCase::SENSITIVE)) {
return true;
}
}
return false;
}
// Mount event change observers.
base::ObserverList<Observer> observers_;
const raw_ptr<CrosDisksClient> cros_disks_client_ = CrosDisksClient::Get();
// The list of disks found.
Disks disks_;
// Callbacks of mount points in the process of being mounted, indexed by
// source path.
using MountCallbacks = std::map<std::string, MountPathCallback>;
MountCallbacks mount_callbacks_;
// Known mount points.
MountPoints mount_points_;
// A map entry with a key of the device path will be created upon calling
// GetDeviceProperties(), for deferring mount events, and removed once it has
// completed. This prevents a race resulting in mount events being fired with
// the corresponding Disk entry unexpectedly missing.
std::map<std::string, std::vector<MountPoint>> deferred_mount_events_;
bool already_refreshed_ = false;
std::vector<EnsureMountInfoRefreshedCallback> refresh_callbacks_;
SuspendUnmountManager suspend_unmount_manager_{this};
base::WeakPtrFactory<DiskMountManagerImpl> weak_ptr_factory_{this};
};
} // namespace
DiskMountManager::Observer::~Observer() {
DCHECK(!IsInObserverList());
}
bool DiskMountManager::AddDiskForTest(std::unique_ptr<Disk> disk) {
return false;
}
bool DiskMountManager::AddMountPointForTest(const MountPoint& mount_point) {
return false;
}
// static
void DiskMountManager::Initialize() {
if (g_disk_mount_manager) {
LOG(WARNING) << "DiskMountManager was already initialized";
return;
}
g_disk_mount_manager = new DiskMountManagerImpl();
VLOG(1) << "DiskMountManager initialized";
}
// static
void DiskMountManager::InitializeForTesting(
DiskMountManager* disk_mount_manager) {
if (g_disk_mount_manager) {
LOG(WARNING) << "DiskMountManager was already initialized";
return;
}
g_disk_mount_manager = disk_mount_manager;
VLOG(1) << "DiskMountManager initialized";
}
// static
void DiskMountManager::Shutdown() {
if (!g_disk_mount_manager) {
LOG(WARNING) << "DiskMountManager::Shutdown() called with NULL manager";
return;
}
delete g_disk_mount_manager;
g_disk_mount_manager = nullptr;
VLOG(1) << "DiskMountManager Shutdown completed";
}
// static
DiskMountManager* DiskMountManager::GetInstance() {
return g_disk_mount_manager;
}
} // namespace ash::disks
|