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 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050
|
// 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 "chrome/browser/media_galleries/chromeos/mtp_device_delegate_impl_chromeos.h"
#include <errno.h>
#include <fcntl.h>
#include <stddef.h>
#include <algorithm>
#include <limits>
#include <ostream>
#include <string_view>
#include <unordered_map>
#include <utility>
#include <vector>
#include "base/containers/circular_deque.h"
#include "base/containers/contains.h"
#include "base/files/file_util.h"
#include "base/files/safe_base_name.h"
#include "base/functional/bind.h"
#include "base/logging.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/raw_ref.h"
#include "base/not_fatal_until.h"
#include "base/notreached.h"
#include "base/numerics/safe_conversions.h"
#include "base/posix/eintr_wrapper.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/task/task_traits.h"
#include "base/task/thread_pool.h"
#include "base/threading/scoped_blocking_call.h"
#include "chrome/browser/media_galleries/chromeos/mtp_device_task_helper_map_service.h"
#include "chrome/browser/media_galleries/chromeos/snapshot_file_details.h"
#include "components/services/filesystem/public/mojom/types.mojom.h"
#include "content/public/browser/browser_thread.h"
#include "net/base/io_buffer.h"
#include "third_party/cros_system_api/dbus/service_constants.h"
namespace {
// File path separator constant.
const char kRootPath[] = "/";
// Helper function to create |MTPDeviceDelegateImplLinux::storage_name_|.
std::string CreateStorageName(const std::string& device_location) {
std::string storage_name;
base::RemoveChars(device_location, kRootPath, &storage_name);
return storage_name;
}
// Returns the device relative file path given |file_path|.
// E.g.: If the |file_path| is "/usb:2,2:12345/DCIM" and |registered_dev_path|
// is "/usb:2,2:12345", this function returns the device relative path which is
// "DCIM".
// In the special case when |registered_dev_path| and |file_path| are the same,
// return |kRootPath|.
std::string GetDeviceRelativePath(const base::FilePath& registered_dev_path,
const base::FilePath& file_path) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
DCHECK(!registered_dev_path.empty());
DCHECK(!file_path.empty());
std::string result;
if (registered_dev_path == file_path) {
result = kRootPath;
} else {
base::FilePath relative_path;
if (registered_dev_path.AppendRelativePath(file_path, &relative_path)) {
DCHECK(!relative_path.empty());
result = relative_path.value();
}
}
return result;
}
// Returns the MTPDeviceTaskHelper object associated with the MTP device
// storage.
//
// |storage_name| specifies the name of the storage device.
// |read_only| specifies the mode of the storage device.
// Returns NULL if the |storage_name| is no longer valid (e.g. because the
// corresponding storage device is detached, etc).
MTPDeviceTaskHelper* GetDeviceTaskHelperForStorage(
const std::string& storage_name,
const bool read_only) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
return MTPDeviceTaskHelperMapService::GetInstance()->GetDeviceTaskHelper(
storage_name, read_only);
}
// Opens the storage device for communication.
//
// Called on the UI thread to dispatch the request to the MTPDeviceTaskHelper.
//
// |storage_name| specifies the name of the storage device.
// |read_only| specifies the mode of the storage device.
// |reply_callback| is called when the OpenStorage request completes.
// |reply_callback| runs on the IO thread.
void OpenStorageOnUIThread(
const std::string& storage_name,
const bool read_only,
MTPDeviceTaskHelper::OpenStorageCallback reply_callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
MTPDeviceTaskHelper* task_helper =
GetDeviceTaskHelperForStorage(storage_name, read_only);
if (!task_helper) {
task_helper =
MTPDeviceTaskHelperMapService::GetInstance()->CreateDeviceTaskHelper(
storage_name, read_only);
}
task_helper->OpenStorage(storage_name, read_only, std::move(reply_callback));
}
// Creates |directory_name| on |parent_id|.
//
// |storage_name| specifies the name of the storage device.
// |read_only| specifies the mode of the storage device.
// |parent_id| is an object id of the parent directory.
// |directory_name| is name of the new directory.
// |success_callback| is called when the directory is created successfully.
// |error_callback| is called when it fails to create a directory.
// |success_callback| and |error_callback| runs on the IO thread.
void CreateDirectoryOnUIThread(
const std::string& storage_name,
const bool read_only,
const uint32_t parent_id,
const std::string& directory_name,
MTPDeviceTaskHelper::CreateDirectorySuccessCallback success_callback,
MTPDeviceTaskHelper::ErrorCallback error_callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
MTPDeviceTaskHelper* task_helper =
GetDeviceTaskHelperForStorage(storage_name, read_only);
if (!task_helper) {
return;
}
task_helper->CreateDirectory(parent_id, directory_name,
std::move(success_callback),
std::move(error_callback));
}
// Enumerates the |directory_id| directory file entries.
//
// Called on the UI thread to dispatch the request to the MTPDeviceTaskHelper.
//
// |storage_name| specifies the name of the storage device.
// |read_only| specifies the mode of the storage device.
// |directory_id| is an id of a directory to read.
// |success_callback| is called when the ReadDirectory request succeeds.
// |error_callback| is called when the ReadDirectory request fails.
// |success_callback| and |error_callback| runs on the IO thread.
void ReadDirectoryOnUIThread(
const std::string& storage_name,
const bool read_only,
const uint32_t directory_id,
MTPDeviceTaskHelper::ReadDirectorySuccessCallback success_callback,
MTPDeviceTaskHelper::ErrorCallback error_callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
MTPDeviceTaskHelper* task_helper =
GetDeviceTaskHelperForStorage(storage_name, read_only);
if (!task_helper) {
return;
}
task_helper->ReadDirectory(directory_id, success_callback,
std::move(error_callback));
}
// Checks if the |directory_id| directory is empty.
//
// Called on the UI thread to dispatch the request to the MTPDeviceTaskHelper.
//
// |storage_name| specifies the name of the storage device.
// |read_only| specifies the mode of the storage device.
// |directory_id| is an id of a directory to check.
// |success_callback| is called when the CheckDirectoryEmpty request succeeds.
// |error_callback| is called when the CheckDirectoryEmpty request fails.
// |success_callback| and |error_callback| runs on the IO thread.
void CheckDirectoryEmptyOnUIThread(
const std::string& storage_name,
bool read_only,
uint32_t directory_id,
MTPDeviceTaskHelper::CheckDirectoryEmptySuccessCallback success_callback,
MTPDeviceTaskHelper::ErrorCallback error_callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
MTPDeviceTaskHelper* task_helper =
GetDeviceTaskHelperForStorage(storage_name, read_only);
if (!task_helper) {
return;
}
task_helper->CheckDirectoryEmpty(directory_id, std::move(success_callback),
std::move(error_callback));
}
// Gets the |file_path| details.
//
// Called on the UI thread to dispatch the request to the MTPDeviceTaskHelper.
//
// |storage_name| specifies the name of the storage device.
// |read_only| specifies the mode of the storage device.
// |success_callback| is called when the GetFileInfo request succeeds.
// |error_callback| is called when the GetFileInfo request fails.
// |success_callback| and |error_callback| runs on the IO thread.
void GetFileInfoOnUIThread(
const std::string& storage_name,
const bool read_only,
uint32_t file_id,
MTPDeviceTaskHelper::GetFileInfoSuccessCallback success_callback,
MTPDeviceTaskHelper::ErrorCallback error_callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
MTPDeviceTaskHelper* task_helper =
GetDeviceTaskHelperForStorage(storage_name, read_only);
if (!task_helper) {
return;
}
task_helper->GetFileInfo(file_id, std::move(success_callback),
std::move(error_callback));
}
// Copies the contents of |device_file_path| to |snapshot_file_path|.
//
// Called on the UI thread to dispatch the request to the MTPDeviceTaskHelper.
//
// |storage_name| specifies the name of the storage device.
// |read_only| specifies the mode of the storage device.
// |device_file_path| specifies the media device file path.
// |snapshot_file_path| specifies the platform path of the snapshot file.
// |file_size| specifies the number of bytes that will be written to the
// snapshot file.
// |success_callback| is called when the copy operation succeeds.
// |error_callback| is called when the copy operation fails.
// |success_callback| and |error_callback| runs on the IO thread.
void WriteDataIntoSnapshotFileOnUIThread(
const std::string& storage_name,
const bool read_only,
SnapshotRequestInfo request_info,
const base::File::Info& snapshot_file_info) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
MTPDeviceTaskHelper* task_helper =
GetDeviceTaskHelperForStorage(storage_name, read_only);
if (!task_helper) {
return;
}
task_helper->WriteDataIntoSnapshotFile(std::move(request_info),
snapshot_file_info);
}
// Copies the contents of |device_file_path| to |snapshot_file_path|.
//
// Called on the UI thread to dispatch the request to the MTPDeviceTaskHelper.
//
// |storage_name| specifies the name of the storage device.
// |read_only| specifies the mode of the storage device.
// |request| is a struct containing details about the byte read request.
void ReadBytesOnUIThread(const std::string& storage_name,
const bool read_only,
MTPDeviceAsyncDelegate::ReadBytesRequest request) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
MTPDeviceTaskHelper* task_helper =
GetDeviceTaskHelperForStorage(storage_name, read_only);
if (!task_helper) {
return;
}
task_helper->ReadBytes(std::move(request));
}
// Renames |object_id| to |new_name|.
//
// |storage_name| specifies the name of the storage device.
// |read_only| specifies the mode of the storage device.
// |object_id| is an id of object to be renamed.
// |new_name| is new name of the object.
// |success_callback| is called when the object is renamed successfully.
// |error_callback| is called when it fails to rename the object.
// |success_callback| and |error_callback| runs on the IO thread.
void RenameObjectOnUIThread(
const std::string& storage_name,
const bool read_only,
const uint32_t object_id,
const std::string& new_name,
MTPDeviceTaskHelper::RenameObjectSuccessCallback success_callback,
MTPDeviceTaskHelper::ErrorCallback error_callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
MTPDeviceTaskHelper* task_helper =
GetDeviceTaskHelperForStorage(storage_name, read_only);
if (!task_helper) {
return;
}
task_helper->RenameObject(object_id, new_name, std::move(success_callback),
std::move(error_callback));
}
// Copies the file |source_file_descriptor| to |file_name| in |parent_id|.
//
// |storage_name| specifies the name of the storage device.
// |read_only| specifies the mode of the storage device.
// |source_file_descriptor| file descriptor of source file.
// |parent_id| object id of a target directory.
// |file_name| file name of a target file.
// |success_callback| is called when the file is copied successfully.
// |error_callback| is called when it fails to copy file.
// Since this method does not close the file descriptor, callbacks are
// responsible for closing it.
void CopyFileFromLocalOnUIThread(
const std::string& storage_name,
const bool read_only,
const int source_file_descriptor,
const uint32_t parent_id,
const std::string& file_name,
MTPDeviceTaskHelper::CopyFileFromLocalSuccessCallback success_callback,
MTPDeviceTaskHelper::ErrorCallback error_callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
MTPDeviceTaskHelper* task_helper =
GetDeviceTaskHelperForStorage(storage_name, read_only);
if (!task_helper) {
return;
}
task_helper->CopyFileFromLocal(
storage_name, source_file_descriptor, parent_id, file_name,
std::move(success_callback), std::move(error_callback));
}
// Deletes |object_id|.
//
// Called on the UI thread to dispatch the request to the MTPDeviceTaskHelper.
//
// |storage_name| specifies the name of the storage device.
// |read_only| specifies the mode of the storage device.
// |object_id| is the object to be deleted.
// |success_callback| is called when the object is deleted successfully.
// |error_callback| is called when it fails to delete the object.
// |success_callback| and |error_callback| runs on the IO thread.
void DeleteObjectOnUIThread(
const std::string storage_name,
const bool read_only,
const uint32_t object_id,
MTPDeviceTaskHelper::DeleteObjectSuccessCallback success_callback,
MTPDeviceTaskHelper::ErrorCallback error_callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
MTPDeviceTaskHelper* task_helper =
GetDeviceTaskHelperForStorage(storage_name, read_only);
if (!task_helper) {
return;
}
task_helper->DeleteObject(object_id, std::move(success_callback),
std::move(error_callback));
}
// Closes the device storage specified by the |storage_name| and destroys the
// MTPDeviceTaskHelper object associated with the device storage.
//
// Called on the UI thread to dispatch the request to the MTPDeviceTaskHelper.
void CloseStorageAndDestroyTaskHelperOnUIThread(const std::string& storage_name,
const bool read_only) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
MTPDeviceTaskHelper* task_helper =
GetDeviceTaskHelperForStorage(storage_name, read_only);
if (!task_helper) {
return;
}
task_helper->CloseStorage();
MTPDeviceTaskHelperMapService::GetInstance()->DestroyDeviceTaskHelper(
storage_name, read_only);
}
// Opens |file_path| with |flags|. Returns the result as a pair.
// first is file descriptor.
// second is base::File::Error. This value is set as following.
// - When it succeeds to open a file descriptor, base::File::FILE_OK is set.
// - When |file_path| is a directory, base::File::FILE_ERROR_NOT_A_FILE is set.
// - When |file_path| does not exist, base::File::FILE_ERROR_NOT_FOUND is set.
// - For other error cases, base::File::FILE_ERROR_FAILED is set.
std::pair<int, base::File::Error> OpenFileDescriptor(
const base::FilePath& file_path,
const int flags) {
base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
base::BlockingType::MAY_BLOCK);
if (base::DirectoryExists(file_path)) {
return std::make_pair(-1, base::File::FILE_ERROR_NOT_A_FILE);
}
int file_descriptor = open(file_path.value().c_str(), flags);
if (file_descriptor >= 0) {
return std::make_pair(file_descriptor, base::File::FILE_OK);
}
if (errno == ENOENT) {
return std::make_pair(file_descriptor, base::File::FILE_ERROR_NOT_FOUND);
}
return std::make_pair(file_descriptor, base::File::FILE_ERROR_FAILED);
}
// Closes |file_descriptor| on a background task runner.
void CloseFileDescriptor(const int file_descriptor) {
base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
base::BlockingType::MAY_BLOCK);
IGNORE_EINTR(close(file_descriptor));
}
// Deletes a temporary file |file_path|.
void DeleteTemporaryFile(const base::FilePath& file_path) {
base::ThreadPool::PostTask(
FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT},
base::GetDeleteFileCallback(file_path));
}
// A fake callback to be passed as CopyFileProgressCallback.
void FakeCopyFileProgressCallback(int64_t size) {}
} // namespace
MTPDeviceDelegateImplLinux::PendingTaskInfo::PendingTaskInfo(
const base::FilePath& path,
content::BrowserThread::ID thread_id,
const base::Location& location,
base::OnceClosure task)
: path(path),
thread_id(thread_id),
location(location),
task(std::move(task)) {}
MTPDeviceDelegateImplLinux::PendingTaskInfo::PendingTaskInfo(
PendingTaskInfo&& other) = default;
MTPDeviceDelegateImplLinux::PendingTaskInfo::~PendingTaskInfo() = default;
// Represents a file on the MTP device.
// Lives on the IO thread.
class MTPDeviceDelegateImplLinux::MTPFileNode {
public:
MTPFileNode(uint32_t file_id,
const std::string& file_name,
MTPFileNode* parent,
MTPFileNodesById& nodes_by_id);
MTPFileNode(const MTPFileNode&) = delete;
MTPFileNode& operator=(const MTPFileNode&) = delete;
~MTPFileNode();
const MTPFileNode* GetChild(const std::string& name) const;
void EnsureChildExists(const std::string& name, uint32_t id);
// Clears all the children, except those in |children_to_keep|.
void ClearNonexistentChildren(const std::set<std::string>& children_to_keep);
bool DeleteChild(uint32_t file_id);
bool HasChildren() const;
uint32_t file_id() const { return file_id_; }
const std::string& file_name() const { return file_name_; }
MTPFileNode* parent() { return parent_; }
private:
// Container for holding a node's children.
using ChildNodes =
std::unordered_map<std::string, std::unique_ptr<MTPFileNode>>;
friend std::ostream& operator<<(std::ostream& out, const ChildNodes& nodes) {
if (nodes.empty()) {
return out << "no children";
}
out << nodes.size() << " children: ";
for (std::string_view sep; const ChildNodes::value_type& v : nodes) {
out << sep << "'" << v.first << "'";
sep = ", ";
}
return out;
}
const uint32_t file_id_;
const std::string file_name_;
ChildNodes children_;
const raw_ptr<MTPFileNode> parent_;
const raw_ref<MTPFileNodesById> nodes_by_id_;
};
MTPDeviceDelegateImplLinux::MTPFileNode::MTPFileNode(
uint32_t file_id,
const std::string& file_name,
MTPFileNode* parent,
MTPFileNodesById& nodes_by_id)
: file_id_(file_id),
file_name_(file_name),
parent_(parent),
nodes_by_id_(nodes_by_id) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
const bool ok = nodes_by_id_->try_emplace(file_id_, this).second;
DCHECK(ok);
}
MTPDeviceDelegateImplLinux::MTPFileNode::~MTPFileNode() {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
const size_t erased = nodes_by_id_->erase(file_id_);
DCHECK_EQ(1U, erased);
}
const MTPDeviceDelegateImplLinux::MTPFileNode*
MTPDeviceDelegateImplLinux::MTPFileNode::GetChild(
const std::string& name) const {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
const ChildNodes::const_iterator it = children_.find(name);
return it != children_.cend() ? it->second.get() : nullptr;
}
void MTPDeviceDelegateImplLinux::MTPFileNode::EnsureChildExists(
const std::string& name,
uint32_t id) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
std::unique_ptr<MTPFileNode>& child = children_[name];
if (!child || child->file_id() != id) {
child = std::make_unique<MTPFileNode>(id, name, this, *nodes_by_id_);
}
}
void MTPDeviceDelegateImplLinux::MTPFileNode::ClearNonexistentChildren(
const std::set<std::string>& children_to_keep) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
std::erase_if(children_,
[&children_to_keep](const ChildNodes::value_type& child) {
return !children_to_keep.contains(child.first);
});
}
bool MTPDeviceDelegateImplLinux::MTPFileNode::DeleteChild(uint32_t file_id) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
const ChildNodes::const_iterator it = std::ranges::find_if(
children_, [file_id](const ChildNodes::value_type& child) {
return child.second->file_id() == file_id;
});
if (it == children_.cend()) {
LOG(ERROR) << "Cannot find MTP node with ID " << file_id;
return false;
}
VLOG_IF(1, !it->second->children_.empty())
<< "Deleting MTP node '" << it->first << "' which has "
<< it->second->children_;
children_.erase(it);
return true;
}
bool MTPDeviceDelegateImplLinux::MTPFileNode::HasChildren() const {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
return !children_.empty();
}
MTPDeviceDelegateImplLinux::MTPDeviceDelegateImplLinux(
const std::string& device_location,
const bool read_only)
: device_path_(device_location),
storage_name_(CreateStorageName(device_location)),
read_only_(read_only),
root_node_(std::make_unique<MTPFileNode>(mtpd::kRootFileId,
"", // Root node has no name.
nullptr, // And no parent node.
nodes_by_id_)) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
DCHECK(!device_path_.empty());
DCHECK(!storage_name_.empty());
}
MTPDeviceDelegateImplLinux::~MTPDeviceDelegateImplLinux() {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
}
void MTPDeviceDelegateImplLinux::CreateDirectory(
const base::FilePath& directory_path,
const bool exclusive,
const bool recursive,
CreateDirectorySuccessCallback success_callback,
ErrorCallback error_callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
DCHECK(!directory_path.empty());
// If |directory_path| is not the path in this device, fails with error.
if (!device_path_.IsParent(directory_path)) {
std::move(error_callback).Run(base::File::FILE_ERROR_FAILED);
return;
}
// Decomposes |directory_path| to components. CreateDirectoryInternal creates
// directories by reading |components| from back.
std::vector<base::FilePath> components;
if (recursive) {
for (base::FilePath path = directory_path; path != device_path_;
path = path.DirName()) {
components.push_back(path);
}
} else {
components.push_back(directory_path);
}
base::OnceClosure closure =
base::BindOnce(&MTPDeviceDelegateImplLinux::CreateDirectoryInternal,
weak_ptr_factory_.GetWeakPtr(), components, exclusive,
std::move(success_callback), std::move(error_callback));
EnsureInitAndRunTask(PendingTaskInfo(directory_path,
content::BrowserThread::IO, FROM_HERE,
std::move(closure)));
}
void MTPDeviceDelegateImplLinux::GetFileInfo(
const base::FilePath& file_path,
GetFileInfoSuccessCallback success_callback,
ErrorCallback error_callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
DCHECK(!file_path.empty());
// If a ReadDirectory operation is in progress, the file info may already be
// cached.
FileInfoCache::const_iterator it = file_info_cache_.find(file_path);
if (it != file_info_cache_.end()) {
// TODO(thestig): This code is repeated in several places. Combine them.
// e.g. c/b/media_galleries/win/mtp_device_operations_util.cc
const MTPDeviceTaskHelper::MTPEntry& cached_file_entry = it->second;
std::move(success_callback).Run(cached_file_entry.file_info);
return;
}
base::OnceClosure closure =
base::BindOnce(&MTPDeviceDelegateImplLinux::GetFileInfoInternal,
weak_ptr_factory_.GetWeakPtr(), file_path,
std::move(success_callback), std::move(error_callback));
EnsureInitAndRunTask(PendingTaskInfo(file_path, content::BrowserThread::IO,
FROM_HERE, std::move(closure)));
}
void MTPDeviceDelegateImplLinux::ReadDirectory(
const base::FilePath& root,
ReadDirectorySuccessCallback success_callback,
ErrorCallback error_callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
DCHECK(!root.empty());
base::OnceClosure closure =
base::BindOnce(&MTPDeviceDelegateImplLinux::ReadDirectoryInternal,
weak_ptr_factory_.GetWeakPtr(), root, success_callback,
std::move(error_callback));
EnsureInitAndRunTask(PendingTaskInfo(root, content::BrowserThread::IO,
FROM_HERE, std::move(closure)));
}
void MTPDeviceDelegateImplLinux::CreateSnapshotFile(
const base::FilePath& device_file_path,
const base::FilePath& local_path,
CreateSnapshotFileSuccessCallback success_callback,
ErrorCallback error_callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
DCHECK(!device_file_path.empty());
DCHECK(!local_path.empty());
base::OnceClosure closure = base::BindOnce(
&MTPDeviceDelegateImplLinux::CreateSnapshotFileInternal,
weak_ptr_factory_.GetWeakPtr(), device_file_path, local_path,
std::move(success_callback), std::move(error_callback));
EnsureInitAndRunTask(PendingTaskInfo(device_file_path,
content::BrowserThread::IO, FROM_HERE,
std::move(closure)));
}
bool MTPDeviceDelegateImplLinux::IsStreaming() {
return true;
}
void MTPDeviceDelegateImplLinux::ReadBytes(
const base::FilePath& device_file_path,
const scoped_refptr<net::IOBuffer>& buf,
int64_t offset,
int buf_len,
ReadBytesSuccessCallback success_callback,
ErrorCallback error_callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
DCHECK(!device_file_path.empty());
base::OnceClosure closure = base::BindOnce(
&MTPDeviceDelegateImplLinux::ReadBytesInternal,
weak_ptr_factory_.GetWeakPtr(), device_file_path, base::RetainedRef(buf),
offset, buf_len, std::move(success_callback), std::move(error_callback));
EnsureInitAndRunTask(PendingTaskInfo(device_file_path,
content::BrowserThread::IO, FROM_HERE,
std::move(closure)));
}
bool MTPDeviceDelegateImplLinux::IsReadOnly() const {
return read_only_;
}
void MTPDeviceDelegateImplLinux::CopyFileLocal(
const base::FilePath& source_file_path,
const base::FilePath& device_file_path,
CreateTemporaryFileCallback create_temporary_file_callback,
CopyFileProgressCallback progress_callback,
CopyFileLocalSuccessCallback success_callback,
ErrorCallback error_callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
DCHECK(!source_file_path.empty());
DCHECK(!device_file_path.empty());
// Create a temporary file for creating a copy of source file on local.
base::ThreadPool::PostTaskAndReplyWithResult(
FROM_HERE,
{base::MayBlock(), base::TaskPriority::BEST_EFFORT,
base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
std::move(create_temporary_file_callback),
base::BindOnce(
&MTPDeviceDelegateImplLinux::OnDidCreateTemporaryFileToCopyFileLocal,
weak_ptr_factory_.GetWeakPtr(), source_file_path, device_file_path,
progress_callback, std::move(success_callback),
std::move(error_callback)));
}
void MTPDeviceDelegateImplLinux::MoveFileLocal(
const base::FilePath& source_file_path,
const base::FilePath& device_file_path,
CreateTemporaryFileCallback create_temporary_file_callback,
MoveFileLocalSuccessCallback success_callback,
ErrorCallback error_callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
DCHECK(!source_file_path.empty());
DCHECK(!device_file_path.empty());
// In case of error, only one callback will be called.
auto split_error_callback =
base::SplitOnceCallback(std::move(error_callback));
// Get file info to move file on local.
GetFileInfoSuccessCallback success_callback_wrapper = base::BindOnce(
&MTPDeviceDelegateImplLinux::MoveFileLocalInternal,
weak_ptr_factory_.GetWeakPtr(), source_file_path, device_file_path,
std::move(create_temporary_file_callback), std::move(success_callback),
std::move(split_error_callback.first));
base::OnceClosure closure =
base::BindOnce(&MTPDeviceDelegateImplLinux::GetFileInfoInternal,
weak_ptr_factory_.GetWeakPtr(), source_file_path,
std::move(success_callback_wrapper),
std::move(split_error_callback.second));
EnsureInitAndRunTask(PendingTaskInfo(source_file_path,
content::BrowserThread::IO, FROM_HERE,
std::move(closure)));
}
void MTPDeviceDelegateImplLinux::CopyFileFromLocal(
const base::FilePath& source_file_path,
const base::FilePath& device_file_path,
CopyFileFromLocalSuccessCallback success_callback,
ErrorCallback error_callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
DCHECK(!source_file_path.empty());
DCHECK(!device_file_path.empty());
// In case of error, only one callback will be called.
auto split_error_callback =
base::SplitOnceCallback(std::move(error_callback));
// Get file info of destination file path.
GetFileInfoSuccessCallback success_callback_wrapper = base::BindOnce(
&MTPDeviceDelegateImplLinux::OnDidGetDestFileInfoToCopyFileFromLocal,
weak_ptr_factory_.GetWeakPtr(), std::move(split_error_callback.first));
ErrorCallback error_callback_wrapper = base::BindOnce(
&MTPDeviceDelegateImplLinux::OnGetDestFileInfoErrorToCopyFileFromLocal,
weak_ptr_factory_.GetWeakPtr(), source_file_path, device_file_path,
std::move(success_callback), std::move(split_error_callback.second));
base::OnceClosure closure = base::BindOnce(
&MTPDeviceDelegateImplLinux::GetFileInfoInternal,
weak_ptr_factory_.GetWeakPtr(), device_file_path,
std::move(success_callback_wrapper), std::move(error_callback_wrapper));
EnsureInitAndRunTask(PendingTaskInfo(device_file_path,
content::BrowserThread::IO, FROM_HERE,
std::move(closure)));
}
void MTPDeviceDelegateImplLinux::DeleteFile(
const base::FilePath& file_path,
DeleteFileSuccessCallback success_callback,
ErrorCallback error_callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
DCHECK(!file_path.empty());
// In case of error, only one callback will be called.
auto split_error_callback =
base::SplitOnceCallback(std::move(error_callback));
GetFileInfoSuccessCallback success_callback_wrapper = base::BindOnce(
&MTPDeviceDelegateImplLinux::DeleteFileInternal,
weak_ptr_factory_.GetWeakPtr(), file_path, std::move(success_callback),
std::move(split_error_callback.first));
base::OnceClosure closure =
base::BindOnce(&MTPDeviceDelegateImplLinux::GetFileInfoInternal,
weak_ptr_factory_.GetWeakPtr(), file_path,
std::move(success_callback_wrapper),
std::move(split_error_callback.second));
EnsureInitAndRunTask(PendingTaskInfo(file_path, content::BrowserThread::IO,
FROM_HERE, std::move(closure)));
}
void MTPDeviceDelegateImplLinux::DeleteDirectory(
const base::FilePath& file_path,
DeleteDirectorySuccessCallback success_callback,
ErrorCallback error_callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
DCHECK(!file_path.empty());
// In case of error, only one callback will be called.
auto split_error_callback =
base::SplitOnceCallback(std::move(error_callback));
GetFileInfoSuccessCallback success_callback_wrapper = base::BindOnce(
&MTPDeviceDelegateImplLinux::DeleteDirectoryInternal,
weak_ptr_factory_.GetWeakPtr(), file_path, std::move(success_callback),
std::move(split_error_callback.first));
base::OnceClosure closure =
base::BindOnce(&MTPDeviceDelegateImplLinux::GetFileInfoInternal,
weak_ptr_factory_.GetWeakPtr(), file_path,
std::move(success_callback_wrapper),
std::move(split_error_callback.second));
EnsureInitAndRunTask(PendingTaskInfo(file_path, content::BrowserThread::IO,
FROM_HERE, std::move(closure)));
}
void MTPDeviceDelegateImplLinux::AddWatcher(
const GURL& origin,
const base::FilePath& file_path,
const bool recursive,
storage::WatcherManager::StatusCallback callback,
storage::WatcherManager::NotificationCallback notification_callback) {
if (recursive) {
std::move(callback).Run(base::File::FILE_ERROR_INVALID_OPERATION);
return;
}
const auto it = subscribers_.find(file_path);
if (it != subscribers_.end()) {
// Adds to existing origin callback map.
if (base::Contains(it->second, origin)) {
std::move(callback).Run(base::File::FILE_ERROR_EXISTS);
return;
}
it->second.insert(std::make_pair(origin, std::move(notification_callback)));
} else {
// Creates new origin callback map.
OriginNotificationCallbackMap callback_map;
callback_map.insert(
std::make_pair(origin, std::move(notification_callback)));
subscribers_.insert(std::make_pair(file_path, callback_map));
}
std::move(callback).Run(base::File::FILE_OK);
}
void MTPDeviceDelegateImplLinux::RemoveWatcher(
const GURL& origin,
const base::FilePath& file_path,
const bool recursive,
storage::WatcherManager::StatusCallback callback) {
if (recursive) {
std::move(callback).Run(base::File::FILE_ERROR_INVALID_OPERATION);
return;
}
const auto it = subscribers_.find(file_path);
if (it == subscribers_.end()) {
std::move(callback).Run(base::File::FILE_ERROR_NOT_FOUND);
return;
}
if (it->second.erase(origin) == 0) {
std::move(callback).Run(base::File::FILE_ERROR_NOT_FOUND);
return;
}
if (it->second.empty()) {
subscribers_.erase(it);
}
std::move(callback).Run(base::File::FILE_OK);
}
void MTPDeviceDelegateImplLinux::NotifyFileChange(
const base::FilePath& file_path,
const storage::WatcherManager::ChangeType change_type) {
const auto it = subscribers_.find(file_path);
if (it != subscribers_.end()) {
for (const auto& origin_callback : it->second) {
origin_callback.second.Run(change_type);
}
}
}
void MTPDeviceDelegateImplLinux::CancelPendingTasksAndDeleteDelegate() {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
// To cancel all the pending tasks, destroy the MTPDeviceTaskHelper object.
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE, base::BindOnce(&CloseStorageAndDestroyTaskHelperOnUIThread,
storage_name_, read_only_));
delete this;
}
void MTPDeviceDelegateImplLinux::GetFileInfoInternal(
const base::FilePath& file_path,
GetFileInfoSuccessCallback success_callback,
ErrorCallback error_callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
std::optional<uint32_t> file_id = CachedPathToId(file_path);
if (file_id) {
GetFileInfoSuccessCallback success_callback_wrapper = base::BindOnce(
&MTPDeviceDelegateImplLinux::OnDidGetFileInfo,
weak_ptr_factory_.GetWeakPtr(), std::move(success_callback));
ErrorCallback error_callback_wrapper = base::BindOnce(
&MTPDeviceDelegateImplLinux::HandleDeviceFileError,
weak_ptr_factory_.GetWeakPtr(), std::move(error_callback), *file_id);
base::OnceClosure closure = base::BindOnce(
&GetFileInfoOnUIThread, storage_name_, read_only_, *file_id,
std::move(success_callback_wrapper), std::move(error_callback_wrapper));
EnsureInitAndRunTask(PendingTaskInfo(base::FilePath(),
content::BrowserThread::UI, FROM_HERE,
std::move(closure)));
} else {
std::move(error_callback).Run(base::File::FILE_ERROR_NOT_FOUND);
}
PendingRequestDone();
}
void MTPDeviceDelegateImplLinux::CreateDirectoryInternal(
const std::vector<base::FilePath>& components,
const bool exclusive,
CreateDirectorySuccessCallback success_callback,
ErrorCallback error_callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
const base::FilePath current_component = components.back();
std::vector<base::FilePath> other_components = components;
other_components.pop_back();
if (other_components.empty()) {
// Either we reached the last component in the recursive case, or this is
// the non-recursive case.
std::optional<uint32_t> parent_id =
CachedPathToId(current_component.DirName());
if (parent_id) {
base::OnceClosure closure = base::BindOnce(
&MTPDeviceDelegateImplLinux::CreateSingleDirectory,
weak_ptr_factory_.GetWeakPtr(), current_component, exclusive,
std::move(success_callback), std::move(error_callback));
EnsureInitAndRunTask(PendingTaskInfo(base::FilePath(),
content::BrowserThread::IO,
FROM_HERE, std::move(closure)));
} else {
std::move(error_callback).Run(base::File::FILE_ERROR_NOT_FOUND);
}
} else {
// Ensures that parent directories are created for recursive case.
std::optional<uint32_t> directory_id = CachedPathToId(current_component);
if (directory_id) {
// Parent directory |current_component| already exists, continue creating
// directories.
base::OnceClosure closure = base::BindOnce(
&MTPDeviceDelegateImplLinux::CreateDirectoryInternal,
weak_ptr_factory_.GetWeakPtr(), other_components, exclusive,
std::move(success_callback), std::move(error_callback));
EnsureInitAndRunTask(PendingTaskInfo(base::FilePath(),
content::BrowserThread::IO,
FROM_HERE, std::move(closure)));
} else {
// In case of error, only one callback will be called.
auto split_error_callback =
base::SplitOnceCallback(std::move(error_callback));
// If parent directory |current_component| does not exist, create it.
CreateDirectorySuccessCallback success_callback_wrapper = base::BindOnce(
&MTPDeviceDelegateImplLinux::
OnDidCreateParentDirectoryToCreateDirectory,
weak_ptr_factory_.GetWeakPtr(), current_component, other_components,
exclusive, std::move(success_callback),
std::move(split_error_callback.first));
// Wraps error callback to return all errors of creating parent
// directories as FILE_ERROR_FAILED.
ErrorCallback error_callback_wrapper =
base::BindOnce(&MTPDeviceDelegateImplLinux::
OnCreateParentDirectoryErrorToCreateDirectory,
weak_ptr_factory_.GetWeakPtr(),
std::move(split_error_callback.second));
base::OnceClosure closure = base::BindOnce(
&MTPDeviceDelegateImplLinux::CreateSingleDirectory,
weak_ptr_factory_.GetWeakPtr(), current_component,
false /* not exclusive */, std::move(success_callback_wrapper),
std::move(error_callback_wrapper));
EnsureInitAndRunTask(PendingTaskInfo(base::FilePath(),
content::BrowserThread::IO,
FROM_HERE, std::move(closure)));
}
}
PendingRequestDone();
}
void MTPDeviceDelegateImplLinux::ReadDirectoryInternal(
const base::FilePath& root,
ReadDirectorySuccessCallback success_callback,
ErrorCallback error_callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
DCHECK(task_in_progress_);
std::optional<uint32_t> dir_id = CachedPathToId(root);
if (!dir_id) {
std::move(error_callback).Run(base::File::FILE_ERROR_NOT_FOUND);
PendingRequestDone();
return;
}
// In case of error, only one callback will be called.
auto split_error_callback =
base::SplitOnceCallback(std::move(error_callback));
GetFileInfoSuccessCallback success_callback_wrapper = base::BindOnce(
&MTPDeviceDelegateImplLinux::OnDidGetFileInfoToReadDirectory,
weak_ptr_factory_.GetWeakPtr(), *dir_id, success_callback,
std::move(split_error_callback.first));
ErrorCallback error_callback_wrapper =
base::BindOnce(&MTPDeviceDelegateImplLinux::HandleDeviceFileError,
weak_ptr_factory_.GetWeakPtr(),
std::move(split_error_callback.second), *dir_id);
base::OnceClosure closure = base::BindOnce(
&GetFileInfoOnUIThread, storage_name_, read_only_, *dir_id,
std::move(success_callback_wrapper), std::move(error_callback_wrapper));
content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE, std::move(closure));
}
void MTPDeviceDelegateImplLinux::CreateSnapshotFileInternal(
const base::FilePath& device_file_path,
const base::FilePath& local_path,
CreateSnapshotFileSuccessCallback success_callback,
ErrorCallback error_callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
std::optional<uint32_t> file_id = CachedPathToId(device_file_path);
if (file_id) {
// In case of error, only one callback will be called.
auto split_error_callback =
base::SplitOnceCallback(std::move(error_callback));
auto request_info = std::make_unique<SnapshotRequestInfo>(
*file_id, local_path, std::move(success_callback),
std::move(split_error_callback.first));
GetFileInfoSuccessCallback success_callback_wrapper = base::BindOnce(
&MTPDeviceDelegateImplLinux::OnDidGetFileInfoToCreateSnapshotFile,
weak_ptr_factory_.GetWeakPtr(), std::move(request_info));
ErrorCallback error_callback_wrapper =
base::BindOnce(&MTPDeviceDelegateImplLinux::HandleDeviceFileError,
weak_ptr_factory_.GetWeakPtr(),
std::move(split_error_callback.second), *file_id);
base::OnceClosure closure = base::BindOnce(
&GetFileInfoOnUIThread, storage_name_, read_only_, *file_id,
std::move(success_callback_wrapper), std::move(error_callback_wrapper));
EnsureInitAndRunTask(PendingTaskInfo(base::FilePath(),
content::BrowserThread::UI, FROM_HERE,
std::move(closure)));
} else {
std::move(error_callback).Run(base::File::FILE_ERROR_NOT_FOUND);
}
PendingRequestDone();
}
void MTPDeviceDelegateImplLinux::ReadBytesInternal(
const base::FilePath& device_file_path,
net::IOBuffer* buf,
int64_t offset,
int buf_len,
ReadBytesSuccessCallback success_callback,
ErrorCallback error_callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
std::optional<uint32_t> file_id = CachedPathToId(device_file_path);
if (file_id) {
ReadBytesRequest request(
*file_id, buf, offset, buf_len,
base::BindOnce(&MTPDeviceDelegateImplLinux::OnDidReadBytes,
weak_ptr_factory_.GetWeakPtr(),
std::move(success_callback)),
base::BindOnce(&MTPDeviceDelegateImplLinux::HandleDeviceFileError,
weak_ptr_factory_.GetWeakPtr(),
std::move(error_callback), *file_id));
base::OnceClosure closure = base::BindOnce(
&ReadBytesOnUIThread, storage_name_, read_only_, std::move(request));
EnsureInitAndRunTask(PendingTaskInfo(base::FilePath(),
content::BrowserThread::UI, FROM_HERE,
std::move(closure)));
} else {
std::move(error_callback).Run(base::File::FILE_ERROR_NOT_FOUND);
}
PendingRequestDone();
}
void MTPDeviceDelegateImplLinux::MoveFileLocalInternal(
const base::FilePath& source_file_path,
const base::FilePath& device_file_path,
CreateTemporaryFileCallback create_temporary_file_callback,
MoveFileLocalSuccessCallback success_callback,
ErrorCallback error_callback,
const base::File::Info& source_file_info) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
if (source_file_path.DirName() == device_file_path.DirName()) {
// If a file or directory is moved in a same directory, rename it.
std::optional<uint32_t> file_id = CachedPathToId(source_file_path);
if (file_id) {
MTPDeviceTaskHelper::RenameObjectSuccessCallback
success_callback_wrapper = base::BindOnce(
&MTPDeviceDelegateImplLinux::OnDidMoveFileLocalWithRename,
weak_ptr_factory_.GetWeakPtr(), std::move(success_callback),
source_file_path, *file_id);
MTPDeviceTaskHelper::ErrorCallback error_callback_wrapper =
base::BindOnce(&MTPDeviceDelegateImplLinux::HandleDeviceFileError,
weak_ptr_factory_.GetWeakPtr(),
std::move(error_callback), *file_id);
base::OnceClosure closure =
base::BindOnce(&RenameObjectOnUIThread, storage_name_, read_only_,
*file_id, device_file_path.BaseName().value(),
std::move(success_callback_wrapper),
std::move(error_callback_wrapper));
EnsureInitAndRunTask(PendingTaskInfo(base::FilePath(),
content::BrowserThread::UI,
FROM_HERE, std::move(closure)));
} else {
std::move(error_callback)
.Run(source_file_info.is_directory
? base::File::FILE_ERROR_NOT_A_FILE
: base::File::FILE_ERROR_NOT_FOUND);
}
return;
}
if (source_file_info.is_directory) {
std::move(error_callback).Run(base::File::FILE_ERROR_NOT_A_FILE);
return;
}
// In case of error, only one callback will be called.
auto split_error_callback =
base::SplitOnceCallback(std::move(error_callback));
// If a file is moved to a different directory, create a copy to the
// destination path, and remove source file.
CopyFileLocalSuccessCallback success_callback_wrapper =
base::BindOnce(&MTPDeviceDelegateImplLinux::DeleteFileInternal,
weak_ptr_factory_.GetWeakPtr(), source_file_path,
std::move(success_callback),
std::move(split_error_callback.first), source_file_info);
// TODO(yawano): Avoid to call external method from internal code.
CopyFileLocal(source_file_path, device_file_path,
std::move(create_temporary_file_callback),
base::BindRepeating(&FakeCopyFileProgressCallback),
std::move(success_callback_wrapper),
std::move(split_error_callback.second));
}
void MTPDeviceDelegateImplLinux::OnDidOpenFDToCopyFileFromLocal(
const base::FilePath& device_file_path,
CopyFileFromLocalSuccessCallback success_callback,
ErrorCallback error_callback,
const std::pair<int, base::File::Error>& open_fd_result) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
if (open_fd_result.second != base::File::FILE_OK) {
std::move(error_callback).Run(open_fd_result.second);
return;
}
const int source_file_descriptor = open_fd_result.first;
std::optional<uint32_t> parent_id =
CachedPathToId(device_file_path.DirName());
if (!parent_id) {
HandleCopyFileFromLocalError(std::move(error_callback),
source_file_descriptor,
base::File::FILE_ERROR_NOT_FOUND);
return;
}
MTPDeviceTaskHelper::CopyFileFromLocalSuccessCallback
success_callback_wrapper = base::BindOnce(
&MTPDeviceDelegateImplLinux::OnDidCopyFileFromLocal,
weak_ptr_factory_.GetWeakPtr(), std::move(success_callback),
device_file_path, source_file_descriptor);
ErrorCallback error_callback_wrapper =
base::BindOnce(&MTPDeviceDelegateImplLinux::HandleCopyFileFromLocalError,
weak_ptr_factory_.GetWeakPtr(), std::move(error_callback),
source_file_descriptor);
base::OnceClosure closure = base::BindOnce(
&CopyFileFromLocalOnUIThread, storage_name_, read_only_,
source_file_descriptor, *parent_id, device_file_path.BaseName().value(),
std::move(success_callback_wrapper), std::move(error_callback_wrapper));
EnsureInitAndRunTask(PendingTaskInfo(base::FilePath(),
content::BrowserThread::UI, FROM_HERE,
std::move(closure)));
}
void MTPDeviceDelegateImplLinux::DeleteFileInternal(
const base::FilePath& file_path,
DeleteFileSuccessCallback success_callback,
ErrorCallback error_callback,
const base::File::Info& file_info) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
if (file_info.is_directory) {
std::move(error_callback).Run(base::File::FILE_ERROR_NOT_A_FILE);
return;
}
std::optional<uint32_t> file_id = CachedPathToId(file_path);
if (!file_id) {
std::move(error_callback).Run(base::File::FILE_ERROR_NOT_FOUND);
return;
}
RunDeleteObjectOnUIThread(file_path, *file_id, std::move(success_callback),
std::move(error_callback));
}
void MTPDeviceDelegateImplLinux::DeleteDirectoryInternal(
const base::FilePath& file_path,
DeleteDirectorySuccessCallback success_callback,
ErrorCallback error_callback,
const base::File::Info& file_info) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
if (!file_info.is_directory) {
std::move(error_callback).Run(base::File::FILE_ERROR_NOT_A_DIRECTORY);
return;
}
std::optional<uint32_t> directory_id = CachedPathToId(file_path);
if (!directory_id) {
std::move(error_callback).Run(base::File::FILE_ERROR_NOT_FOUND);
return;
}
// Checks the cache first. If it has children in cache, the directory cannot
// be empty.
const MTPFileNodesById::const_iterator it = nodes_by_id_.find(*directory_id);
if (it != nodes_by_id_.end() && it->second->HasChildren()) {
std::move(error_callback).Run(base::File::FILE_ERROR_NOT_EMPTY);
return;
}
// In case of error, only one callback will be called.
auto split_error_callback =
base::SplitOnceCallback(std::move(error_callback));
// Since the directory can contain a file even if the cache returns it as
// empty, explicitly check the directory and confirm it is actually empty.
MTPDeviceTaskHelper::CheckDirectoryEmptySuccessCallback
success_callback_wrapper = base::BindOnce(
&MTPDeviceDelegateImplLinux::
OnDidCheckDirectoryEmptyToDeleteDirectory,
weak_ptr_factory_.GetWeakPtr(), file_path, *directory_id,
std::move(success_callback), std::move(split_error_callback.first));
MTPDeviceTaskHelper::ErrorCallback error_callback_wrapper =
base::BindOnce(&MTPDeviceDelegateImplLinux::HandleDeviceFileError,
weak_ptr_factory_.GetWeakPtr(),
std::move(split_error_callback.second), *directory_id);
base::OnceClosure closure = base::BindOnce(
&CheckDirectoryEmptyOnUIThread, storage_name_, read_only_, *directory_id,
std::move(success_callback_wrapper), std::move(error_callback_wrapper));
EnsureInitAndRunTask(PendingTaskInfo(base::FilePath(),
content::BrowserThread::UI, FROM_HERE,
std::move(closure)));
}
void MTPDeviceDelegateImplLinux::CreateSingleDirectory(
const base::FilePath& directory_path,
const bool exclusive,
CreateDirectorySuccessCallback success_callback,
ErrorCallback error_callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
// In case of error, only one callback will be called.
auto split_error_callback =
base::SplitOnceCallback(std::move(error_callback));
// Only one of the callbacks will be called in either path below.
auto split_success_callback =
base::SplitOnceCallback(std::move(success_callback));
GetFileInfoSuccessCallback success_callback_wrapper = base::BindOnce(
&MTPDeviceDelegateImplLinux::OnPathAlreadyExistsForCreateSingleDirectory,
weak_ptr_factory_.GetWeakPtr(), exclusive,
std::move(split_success_callback.first),
std::move(split_error_callback.first));
ErrorCallback error_callback_wrapper = base::BindOnce(
&MTPDeviceDelegateImplLinux::OnPathDoesNotExistForCreateSingleDirectory,
weak_ptr_factory_.GetWeakPtr(), directory_path,
std::move(split_success_callback.second),
std::move(split_error_callback.second));
base::OnceClosure closure = base::BindOnce(
&MTPDeviceDelegateImplLinux::GetFileInfoInternal,
weak_ptr_factory_.GetWeakPtr(), directory_path,
std::move(success_callback_wrapper), std::move(error_callback_wrapper));
EnsureInitAndRunTask(PendingTaskInfo(base::FilePath(),
content::BrowserThread::IO, FROM_HERE,
std::move(closure)));
PendingRequestDone();
}
void MTPDeviceDelegateImplLinux::OnDidReadDirectoryToCreateDirectory(
const std::vector<base::FilePath>& components,
const bool exclusive,
CreateDirectorySuccessCallback success_callback,
ErrorCallback error_callback,
storage::AsyncFileUtil::EntryList /* entries */,
const bool has_more) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
if (has_more) {
return; // Wait until all entries have been read.
}
base::OnceClosure closure =
base::BindOnce(&MTPDeviceDelegateImplLinux::CreateDirectoryInternal,
weak_ptr_factory_.GetWeakPtr(), components, exclusive,
std::move(success_callback), std::move(error_callback));
EnsureInitAndRunTask(PendingTaskInfo(base::FilePath(),
content::BrowserThread::IO, FROM_HERE,
std::move(closure)));
}
void MTPDeviceDelegateImplLinux::OnDidCheckDirectoryEmptyToDeleteDirectory(
const base::FilePath& directory_path,
uint32_t directory_id,
DeleteDirectorySuccessCallback success_callback,
ErrorCallback error_callback,
bool is_empty) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
if (is_empty) {
RunDeleteObjectOnUIThread(directory_path, directory_id,
std::move(success_callback),
std::move(error_callback));
} else {
std::move(error_callback).Run(base::File::FILE_ERROR_NOT_EMPTY);
}
PendingRequestDone();
}
void MTPDeviceDelegateImplLinux::RunDeleteObjectOnUIThread(
const base::FilePath& object_path,
const uint32_t object_id,
DeleteObjectSuccessCallback success_callback,
ErrorCallback error_callback) {
MTPDeviceTaskHelper::DeleteObjectSuccessCallback success_callback_wrapper =
base::BindOnce(&MTPDeviceDelegateImplLinux::OnDidDeleteObject,
weak_ptr_factory_.GetWeakPtr(), object_path, object_id,
std::move(success_callback));
MTPDeviceTaskHelper::ErrorCallback error_callback_wrapper = base::BindOnce(
&MTPDeviceDelegateImplLinux::HandleDeleteFileOrDirectoryError,
weak_ptr_factory_.GetWeakPtr(), std::move(error_callback));
base::OnceClosure closure = base::BindOnce(
&DeleteObjectOnUIThread, storage_name_, read_only_, object_id,
std::move(success_callback_wrapper), std::move(error_callback_wrapper));
EnsureInitAndRunTask(PendingTaskInfo(base::FilePath(),
content::BrowserThread::UI, FROM_HERE,
std::move(closure)));
}
void MTPDeviceDelegateImplLinux::EnsureInitAndRunTask(
PendingTaskInfo task_info) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
if ((init_state_ == INITIALIZED) && !task_in_progress_) {
RunTask(std::move(task_info));
return;
}
// Only *Internal functions have empty paths. Since they are the continuation
// of the current running task, they get to cut in line.
if (task_info.path.empty()) {
pending_tasks_.push_front(std::move(task_info));
} else {
pending_tasks_.push_back(std::move(task_info));
}
if (init_state_ == UNINITIALIZED) {
init_state_ = PENDING_INIT;
task_in_progress_ = true;
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(
&OpenStorageOnUIThread, storage_name_, read_only_,
base::BindOnce(&MTPDeviceDelegateImplLinux::OnInitCompleted,
weak_ptr_factory_.GetWeakPtr())));
}
}
void MTPDeviceDelegateImplLinux::RunTask(PendingTaskInfo task_info) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
DCHECK_EQ(INITIALIZED, init_state_);
DCHECK(!task_in_progress_);
task_in_progress_ = true;
bool need_to_check_cache = !task_info.path.empty();
if (need_to_check_cache) {
base::FilePath uncached_path =
NextUncachedPathComponent(task_info.path, task_info.cached_path);
if (!uncached_path.empty()) {
// Save the current task and do a cache lookup first.
pending_tasks_.push_front(std::move(task_info));
FillFileCache(uncached_path);
return;
}
}
switch (task_info.thread_id) {
case content::BrowserThread::UI:
content::GetUIThreadTaskRunner({})->PostTask(task_info.location,
std::move(task_info.task));
break;
case content::BrowserThread::IO:
content::GetIOThreadTaskRunner({})->PostTask(task_info.location,
std::move(task_info.task));
break;
case content::BrowserThread::ID_COUNT:
NOTREACHED();
}
}
void MTPDeviceDelegateImplLinux::WriteDataIntoSnapshotFile(
const base::File::Info& file_info) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
DCHECK(current_snapshot_request_info_.get());
DCHECK_GT(file_info.size, 0);
DCHECK(task_in_progress_);
SnapshotRequestInfo request_info(
current_snapshot_request_info_->file_id,
current_snapshot_request_info_->snapshot_file_path,
base::BindOnce(
&MTPDeviceDelegateImplLinux::OnDidWriteDataIntoSnapshotFile,
weak_ptr_factory_.GetWeakPtr()),
base::BindOnce(
&MTPDeviceDelegateImplLinux::OnWriteDataIntoSnapshotFileError,
weak_ptr_factory_.GetWeakPtr()));
base::OnceClosure task_closure =
base::BindOnce(&WriteDataIntoSnapshotFileOnUIThread, storage_name_,
read_only_, std::move(request_info), file_info);
content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE,
std::move(task_closure));
}
void MTPDeviceDelegateImplLinux::PendingRequestDone() {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
DCHECK(task_in_progress_);
task_in_progress_ = false;
ProcessNextPendingRequest();
}
void MTPDeviceDelegateImplLinux::ProcessNextPendingRequest() {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
DCHECK(!task_in_progress_);
if (pending_tasks_.empty()) {
return;
}
PendingTaskInfo task_info = std::move(pending_tasks_.front());
pending_tasks_.pop_front();
RunTask(std::move(task_info));
}
void MTPDeviceDelegateImplLinux::OnInitCompleted(bool succeeded) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
init_state_ = succeeded ? INITIALIZED : UNINITIALIZED;
PendingRequestDone();
}
void MTPDeviceDelegateImplLinux::OnDidGetFileInfo(
GetFileInfoSuccessCallback success_callback,
const base::File::Info& file_info) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
std::move(success_callback).Run(file_info);
PendingRequestDone();
}
void MTPDeviceDelegateImplLinux::OnPathAlreadyExistsForCreateSingleDirectory(
const bool exclusive,
CreateDirectorySuccessCallback success_callback,
ErrorCallback error_callback,
const base::File::Info& file_info) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
if (!file_info.is_directory || exclusive) {
std::move(error_callback).Run(base::File::FILE_ERROR_EXISTS);
} else {
std::move(success_callback).Run();
}
}
void MTPDeviceDelegateImplLinux::OnPathDoesNotExistForCreateSingleDirectory(
const base::FilePath& directory_path,
CreateDirectorySuccessCallback success_callback,
ErrorCallback error_callback,
const base::File::Error error) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
if (error != base::File::FILE_ERROR_NOT_FOUND) {
std::move(error_callback).Run(base::File::FILE_ERROR_NOT_FOUND);
return;
}
std::optional<uint32_t> parent_id = CachedPathToId(directory_path.DirName());
if (!parent_id) {
std::move(error_callback).Run(base::File::FILE_ERROR_NOT_FOUND);
return;
}
MTPDeviceTaskHelper::CreateDirectorySuccessCallback success_callback_wrapper =
base::BindOnce(&MTPDeviceDelegateImplLinux::OnDidCreateSingleDirectory,
weak_ptr_factory_.GetWeakPtr(), directory_path,
std::move(success_callback));
MTPDeviceTaskHelper::ErrorCallback error_callback_wrapper = base::BindOnce(
&MTPDeviceDelegateImplLinux::HandleDeviceFileError,
weak_ptr_factory_.GetWeakPtr(), std::move(error_callback), *parent_id);
base::OnceClosure closure = base::BindOnce(
&CreateDirectoryOnUIThread, storage_name_, read_only_, *parent_id,
directory_path.BaseName().value(), std::move(success_callback_wrapper),
std::move(error_callback_wrapper));
EnsureInitAndRunTask(PendingTaskInfo(base::FilePath(),
content::BrowserThread::UI, FROM_HERE,
std::move(closure)));
}
void MTPDeviceDelegateImplLinux::OnDidGetFileInfoToReadDirectory(
uint32_t dir_id,
ReadDirectorySuccessCallback success_callback,
ErrorCallback error_callback,
const base::File::Info& file_info) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
DCHECK(task_in_progress_);
if (!file_info.is_directory) {
return HandleDeviceFileError(std::move(error_callback), dir_id,
base::File::FILE_ERROR_NOT_A_DIRECTORY);
}
base::OnceClosure task_closure = base::BindOnce(
&ReadDirectoryOnUIThread, storage_name_, read_only_, dir_id,
base::BindRepeating(&MTPDeviceDelegateImplLinux::OnDidReadDirectory,
weak_ptr_factory_.GetWeakPtr(), dir_id,
success_callback),
base::BindOnce(&MTPDeviceDelegateImplLinux::HandleDeviceFileError,
weak_ptr_factory_.GetWeakPtr(), std::move(error_callback),
dir_id));
content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE,
std::move(task_closure));
}
void MTPDeviceDelegateImplLinux::OnDidGetFileInfoToCreateSnapshotFile(
std::unique_ptr<SnapshotRequestInfo> snapshot_request_info,
const base::File::Info& file_info) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
DCHECK(!current_snapshot_request_info_.get());
DCHECK(snapshot_request_info.get());
DCHECK(task_in_progress_);
base::File::Error error = base::File::FILE_OK;
if (file_info.is_directory) {
error = base::File::FILE_ERROR_NOT_A_FILE;
} else if (file_info.size < 0 ||
file_info.size > std::numeric_limits<uint32_t>::max()) {
error = base::File::FILE_ERROR_FAILED;
}
if (error != base::File::FILE_OK) {
return HandleDeviceFileError(
std::move(snapshot_request_info->error_callback),
snapshot_request_info->file_id, error);
}
base::File::Info snapshot_file_info(file_info);
// Modify the last modified time to null. This prevents the time stamp
// verfication in LocalFileStreamReader.
snapshot_file_info.last_modified = base::Time();
current_snapshot_request_info_ = std::move(snapshot_request_info);
if (file_info.size == 0) {
// Empty snapshot file.
return OnDidWriteDataIntoSnapshotFile(
snapshot_file_info, current_snapshot_request_info_->snapshot_file_path);
}
WriteDataIntoSnapshotFile(snapshot_file_info);
}
void MTPDeviceDelegateImplLinux::OnDidGetDestFileInfoToCopyFileFromLocal(
ErrorCallback error_callback,
const base::File::Info& file_info) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
if (file_info.is_directory) {
std::move(error_callback).Run(base::File::FILE_ERROR_INVALID_OPERATION);
} else {
std::move(error_callback).Run(base::File::FILE_ERROR_FAILED);
}
}
void MTPDeviceDelegateImplLinux::OnGetDestFileInfoErrorToCopyFileFromLocal(
const base::FilePath& source_file_path,
const base::FilePath& device_file_path,
CopyFileFromLocalSuccessCallback success_callback,
ErrorCallback error_callback,
const base::File::Error error) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
if (error != base::File::FILE_ERROR_NOT_FOUND) {
std::move(error_callback).Run(error);
return;
}
base::ThreadPool::PostTaskAndReplyWithResult(
FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT},
base::BindOnce(&OpenFileDescriptor, source_file_path, O_RDONLY),
base::BindOnce(
&MTPDeviceDelegateImplLinux::OnDidOpenFDToCopyFileFromLocal,
weak_ptr_factory_.GetWeakPtr(), device_file_path,
std::move(success_callback), std::move(error_callback)));
}
void MTPDeviceDelegateImplLinux::OnDidCreateSingleDirectory(
const base::FilePath& directory_path,
CreateDirectorySuccessCallback success_callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
std::move(success_callback).Run();
NotifyFileChange(directory_path.DirName(),
storage::WatcherManager::ChangeType::CHANGED);
PendingRequestDone();
}
void MTPDeviceDelegateImplLinux::OnDidCreateParentDirectoryToCreateDirectory(
const base::FilePath& created_directory,
const std::vector<base::FilePath>& components,
const bool exclusive,
CreateDirectorySuccessCallback success_callback,
ErrorCallback error_callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
// In case of error, only one callback will be called.
auto split_error_callback =
base::SplitOnceCallback(std::move(error_callback));
// Calls ReadDirectoryInternal to fill the cache for created directory.
// Calls ReadDirectoryInternal in this method to call it via
// EnsureInitAndRunTask.
ReadDirectorySuccessCallback success_callback_wrapper = base::BindRepeating(
&MTPDeviceDelegateImplLinux::OnDidReadDirectoryToCreateDirectory,
weak_ptr_factory_.GetWeakPtr(), components, exclusive,
base::Passed(&success_callback),
base::Passed(&split_error_callback.first));
base::OnceClosure closure = base::BindOnce(
&MTPDeviceDelegateImplLinux::ReadDirectoryInternal,
weak_ptr_factory_.GetWeakPtr(), created_directory.DirName(),
success_callback_wrapper, std::move(split_error_callback.second));
EnsureInitAndRunTask(PendingTaskInfo(base::FilePath(),
content::BrowserThread::IO, FROM_HERE,
std::move(closure)));
}
void MTPDeviceDelegateImplLinux::OnCreateParentDirectoryErrorToCreateDirectory(
ErrorCallback callback,
const base::File::Error error) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
std::move(callback).Run(base::File::FILE_ERROR_FAILED);
}
void MTPDeviceDelegateImplLinux::OnDidReadDirectory(
uint32_t dir_id,
ReadDirectorySuccessCallback success_callback,
const MTPDeviceTaskHelper::MTPEntries& mtp_entries,
bool has_more) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
storage::AsyncFileUtil::EntryList file_list;
MTPFileNode* dir_node = nullptr;
if (const MTPFileNodesById::const_iterator it = nodes_by_id_.find(dir_id);
it != nodes_by_id_.cend()) {
dir_node = it->second;
// Traverse the MTPFileNode tree to reconstruct the full path for |dir_id|.
base::circular_deque<std::string> dir_path_parts;
MTPFileNode* parent_node = dir_node;
while (parent_node->parent()) {
dir_path_parts.push_front(parent_node->file_name());
parent_node = parent_node->parent();
}
base::FilePath dir_path = device_path_;
for (const auto& dir_path_part : dir_path_parts) {
dir_path = dir_path.Append(dir_path_part);
}
for (const auto& mtp_entry : mtp_entries) {
filesystem::mojom::DirectoryEntry entry;
auto name = base::SafeBaseName::Create(mtp_entry.name);
CHECK(name) << mtp_entry.name;
entry.name = *name;
entry.type = mtp_entry.file_info.is_directory
? filesystem::mojom::FsFileType::DIRECTORY
: filesystem::mojom::FsFileType::REGULAR_FILE;
file_list.push_back(entry);
// Refresh the in memory tree.
dir_node->EnsureChildExists(entry.name.value(), mtp_entry.file_id);
child_nodes_seen_.insert(entry.name.value());
// Add to |file_info_cache_|.
file_info_cache_[dir_path.Append(entry.name)] = mtp_entry;
}
} else {
LOG(ERROR) << "Cannot find MTP node with ID " << dir_id;
}
success_callback.Run(file_list, has_more);
if (has_more) {
return; // Wait to be called again.
}
// Last call, finish book keeping and continue with the next request.
if (dir_node) {
dir_node->ClearNonexistentChildren(child_nodes_seen_);
}
child_nodes_seen_.clear();
file_info_cache_.clear();
PendingRequestDone();
}
void MTPDeviceDelegateImplLinux::OnDidWriteDataIntoSnapshotFile(
const base::File::Info& file_info,
const base::FilePath& snapshot_file_path) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
DCHECK(current_snapshot_request_info_.get());
std::move(current_snapshot_request_info_->success_callback)
.Run(file_info, snapshot_file_path);
current_snapshot_request_info_.reset();
PendingRequestDone();
}
void MTPDeviceDelegateImplLinux::OnWriteDataIntoSnapshotFileError(
base::File::Error error) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
DCHECK(current_snapshot_request_info_.get());
std::move(current_snapshot_request_info_->error_callback).Run(error);
current_snapshot_request_info_.reset();
PendingRequestDone();
}
void MTPDeviceDelegateImplLinux::OnDidReadBytes(
ReadBytesSuccessCallback success_callback,
const base::File::Info& file_info,
int bytes_read) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
std::move(success_callback).Run(file_info, bytes_read);
PendingRequestDone();
}
void MTPDeviceDelegateImplLinux::OnDidFillFileCache(
const base::FilePath& path,
storage::AsyncFileUtil::EntryList /* entries */,
bool has_more) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
if (pending_tasks_.empty()) {
return;
}
DCHECK(path.IsParent(pending_tasks_.front().path));
if (has_more) {
return; // Wait until all entries have been read.
}
pending_tasks_.front().cached_path = path;
}
void MTPDeviceDelegateImplLinux::OnFillFileCacheFailed(
base::File::Error /* error */) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
if (pending_tasks_.empty()) {
return;
}
// When filling the cache fails for the task at the front of the queue, clear
// the path of the task so it will not try to do any more caching. Instead,
// the task will just run and fail the CachedPathToId() lookup.
pending_tasks_.front().path.clear();
}
void MTPDeviceDelegateImplLinux::OnDidCreateTemporaryFileToCopyFileLocal(
const base::FilePath& source_file_path,
const base::FilePath& device_file_path,
CopyFileProgressCallback progress_callback,
CopyFileLocalSuccessCallback success_callback,
ErrorCallback error_callback,
const base::FilePath& temporary_file_path) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
if (temporary_file_path.empty()) {
std::move(error_callback).Run(base::File::FILE_ERROR_FAILED);
return;
}
// In case of error, only one callback will be called.
auto split_error_callback =
base::SplitOnceCallback(std::move(error_callback));
CreateSnapshotFile(
source_file_path, temporary_file_path,
base::BindOnce(
&MTPDeviceDelegateImplLinux::OnDidCreateSnapshotFileOfCopyFileLocal,
weak_ptr_factory_.GetWeakPtr(), device_file_path, progress_callback,
std::move(success_callback), std::move(split_error_callback.first)),
base::BindOnce(&MTPDeviceDelegateImplLinux::HandleCopyFileLocalError,
weak_ptr_factory_.GetWeakPtr(),
std::move(split_error_callback.second),
temporary_file_path));
}
void MTPDeviceDelegateImplLinux::OnDidCreateSnapshotFileOfCopyFileLocal(
const base::FilePath& device_file_path,
CopyFileProgressCallback progress_callback,
CopyFileLocalSuccessCallback success_callback,
ErrorCallback error_callback,
const base::File::Info& file_info,
const base::FilePath& temporary_file_path) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
// Consider that half of copy is completed by creating a temporary file.
progress_callback.Run(file_info.size / 2);
// TODO(yawano): Avoid to call external method from internal code.
CopyFileFromLocal(
temporary_file_path, device_file_path,
base::BindOnce(
&MTPDeviceDelegateImplLinux::OnDidCopyFileFromLocalOfCopyFileLocal,
weak_ptr_factory_.GetWeakPtr(), std::move(success_callback),
temporary_file_path),
base::BindOnce(&MTPDeviceDelegateImplLinux::HandleCopyFileLocalError,
weak_ptr_factory_.GetWeakPtr(), std::move(error_callback),
temporary_file_path));
}
void MTPDeviceDelegateImplLinux::OnDidCopyFileFromLocalOfCopyFileLocal(
CopyFileFromLocalSuccessCallback success_callback,
const base::FilePath& temporary_file_path) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
DeleteTemporaryFile(temporary_file_path);
std::move(success_callback).Run();
}
void MTPDeviceDelegateImplLinux::OnDidMoveFileLocalWithRename(
MoveFileLocalSuccessCallback success_callback,
const base::FilePath& source_file_path,
const uint32_t file_id) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
EvictCachedPathToId(file_id);
std::move(success_callback).Run();
NotifyFileChange(source_file_path,
storage::WatcherManager::ChangeType::DELETED);
NotifyFileChange(source_file_path.DirName(),
storage::WatcherManager::ChangeType::CHANGED);
PendingRequestDone();
}
void MTPDeviceDelegateImplLinux::OnDidCopyFileFromLocal(
CopyFileFromLocalSuccessCallback success_callback,
const base::FilePath& file_path,
const int source_file_descriptor) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
base::ThreadPool::PostTask(
FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT},
base::BindOnce(&CloseFileDescriptor, source_file_descriptor));
std::move(success_callback).Run();
NotifyFileChange(file_path.DirName(),
storage::WatcherManager::ChangeType::CHANGED);
PendingRequestDone();
}
void MTPDeviceDelegateImplLinux::HandleCopyFileLocalError(
ErrorCallback error_callback,
const base::FilePath& temporary_file_path,
const base::File::Error error) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
DeleteTemporaryFile(temporary_file_path);
std::move(error_callback).Run(error);
}
void MTPDeviceDelegateImplLinux::HandleCopyFileFromLocalError(
ErrorCallback error_callback,
const int source_file_descriptor,
base::File::Error error) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
base::ThreadPool::PostTask(
FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT},
base::BindOnce(&CloseFileDescriptor, source_file_descriptor));
std::move(error_callback).Run(error);
PendingRequestDone();
}
void MTPDeviceDelegateImplLinux::OnDidDeleteObject(
const base::FilePath& object_path,
const uint32_t object_id,
DeleteObjectSuccessCallback success_callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
EvictCachedPathToId(object_id);
std::move(success_callback).Run();
NotifyFileChange(object_path, storage::WatcherManager::ChangeType::DELETED);
NotifyFileChange(object_path.DirName(),
storage::WatcherManager::ChangeType::CHANGED);
PendingRequestDone();
}
void MTPDeviceDelegateImplLinux::HandleDeleteFileOrDirectoryError(
ErrorCallback error_callback,
base::File::Error error) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
std::move(error_callback).Run(error);
PendingRequestDone();
}
void MTPDeviceDelegateImplLinux::HandleDeviceFileError(
ErrorCallback error_callback,
uint32_t file_id,
base::File::Error error) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
EvictCachedPathToId(file_id);
std::move(error_callback).Run(error);
PendingRequestDone();
}
base::FilePath MTPDeviceDelegateImplLinux::NextUncachedPathComponent(
const base::FilePath& path,
const base::FilePath& cached_path) const {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
DCHECK(cached_path.empty() || cached_path.IsParent(path));
base::FilePath uncached_path;
std::string device_relpath = GetDeviceRelativePath(device_path_, path);
if (!device_relpath.empty() && device_relpath != kRootPath) {
uncached_path = device_path_;
std::vector<std::string> device_relpath_components = base::SplitString(
device_relpath, "/", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
DCHECK(!device_relpath_components.empty());
bool all_components_cached = true;
const MTPFileNode* current_node = root_node_.get();
for (const std::string& component : device_relpath_components) {
current_node = current_node->GetChild(component);
if (!current_node) {
// With a cache miss, check if it is a genuine failure. If so, pretend
// the entire |path| is cached, so there is no further attempt to do
// more caching. The actual operation will then fail.
all_components_cached =
!cached_path.empty() && (uncached_path == cached_path);
break;
}
uncached_path = uncached_path.Append(component);
}
if (all_components_cached) {
uncached_path.clear();
}
}
return uncached_path;
}
void MTPDeviceDelegateImplLinux::FillFileCache(
const base::FilePath& uncached_path) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
DCHECK(task_in_progress_);
ReadDirectorySuccessCallback success_callback =
base::BindRepeating(&MTPDeviceDelegateImplLinux::OnDidFillFileCache,
weak_ptr_factory_.GetWeakPtr(), uncached_path);
ErrorCallback error_callback =
base::BindOnce(&MTPDeviceDelegateImplLinux::OnFillFileCacheFailed,
weak_ptr_factory_.GetWeakPtr());
ReadDirectoryInternal(uncached_path, success_callback,
std::move(error_callback));
}
std::optional<uint32_t> MTPDeviceDelegateImplLinux::CachedPathToId(
const base::FilePath& path) const {
std::string device_relpath = GetDeviceRelativePath(device_path_, path);
if (device_relpath.empty()) {
return {};
}
std::vector<std::string> device_relpath_components;
if (device_relpath != kRootPath) {
device_relpath_components = base::SplitString(
device_relpath, "/", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
}
const MTPFileNode* current_node = root_node_.get();
for (const std::string& component : device_relpath_components) {
current_node = current_node->GetChild(component);
if (!current_node) {
return {};
}
}
return current_node->file_id();
}
void MTPDeviceDelegateImplLinux::EvictCachedPathToId(uint32_t id) {
const MTPFileNodesById::const_iterator it = nodes_by_id_.find(id);
if (it == nodes_by_id_.cend()) {
LOG(ERROR) << "Cannot find MTP node with ID " << id;
return;
}
if (MTPFileNode* const parent = it->second->parent()) {
const bool ok = parent->DeleteChild(id);
DCHECK(ok);
}
}
void CreateMTPDeviceAsyncDelegate(
const std::string& device_location,
const bool read_only,
CreateMTPDeviceAsyncDelegateCallback callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
std::move(callback).Run(
new MTPDeviceDelegateImplLinux(device_location, read_only));
}
|