Root.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Bernhard Posselt <dev@bernhard-posselt.com>
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author Joas Schilling <coding@schilljs.com>
  8. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  9. * @author Julius Härtl <jus@bitgrid.net>
  10. * @author Lukas Reschke <lukas@statuscode.ch>
  11. * @author Morris Jobke <hey@morrisjobke.de>
  12. * @author Robin Appelman <robin@icewind.nl>
  13. * @author Roeland Jago Douma <roeland@famdouma.nl>
  14. * @author Stefan Weil <sw@weilnetz.de>
  15. * @author Vincent Petry <vincent@nextcloud.com>
  16. *
  17. * @license AGPL-3.0
  18. *
  19. * This code is free software: you can redistribute it and/or modify
  20. * it under the terms of the GNU Affero General Public License, version 3,
  21. * as published by the Free Software Foundation.
  22. *
  23. * This program is distributed in the hope that it will be useful,
  24. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  25. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  26. * GNU Affero General Public License for more details.
  27. *
  28. * You should have received a copy of the GNU Affero General Public License, version 3,
  29. * along with this program. If not, see <http://www.gnu.org/licenses/>
  30. *
  31. */
  32. namespace OC\Files\Node;
  33. use OC\Files\FileInfo;
  34. use OC\Files\Mount\Manager;
  35. use OC\Files\Mount\MountPoint;
  36. use OC\Files\Utils\PathHelper;
  37. use OC\Files\View;
  38. use OC\Hooks\PublicEmitter;
  39. use OC\User\NoUserException;
  40. use OCP\Cache\CappedMemoryCache;
  41. use OCP\EventDispatcher\IEventDispatcher;
  42. use OCP\Files\Cache\ICacheEntry;
  43. use OCP\Files\Config\IUserMountCache;
  44. use OCP\Files\Events\Node\FilesystemTornDownEvent;
  45. use OCP\Files\IRootFolder;
  46. use OCP\Files\Mount\IMountPoint;
  47. use OCP\Files\Node as INode;
  48. use OCP\Files\NotFoundException;
  49. use OCP\Files\NotPermittedException;
  50. use OCP\ICache;
  51. use OCP\ICacheFactory;
  52. use OCP\IUser;
  53. use OCP\IUserManager;
  54. use Psr\Log\LoggerInterface;
  55. /**
  56. * Class Root
  57. *
  58. * Hooks available in scope \OC\Files
  59. * - preWrite(\OCP\Files\Node $node)
  60. * - postWrite(\OCP\Files\Node $node)
  61. * - preCreate(\OCP\Files\Node $node)
  62. * - postCreate(\OCP\Files\Node $node)
  63. * - preDelete(\OCP\Files\Node $node)
  64. * - postDelete(\OCP\Files\Node $node)
  65. * - preTouch(\OC\FilesP\Node $node, int $mtime)
  66. * - postTouch(\OCP\Files\Node $node)
  67. * - preCopy(\OCP\Files\Node $source, \OCP\Files\Node $target)
  68. * - postCopy(\OCP\Files\Node $source, \OCP\Files\Node $target)
  69. * - preRename(\OCP\Files\Node $source, \OCP\Files\Node $target)
  70. * - postRename(\OCP\Files\Node $source, \OCP\Files\Node $target)
  71. *
  72. * @package OC\Files\Node
  73. */
  74. class Root extends Folder implements IRootFolder {
  75. private Manager $mountManager;
  76. private PublicEmitter $emitter;
  77. private ?IUser $user;
  78. private CappedMemoryCache $userFolderCache;
  79. private IUserMountCache $userMountCache;
  80. private LoggerInterface $logger;
  81. private IUserManager $userManager;
  82. private IEventDispatcher $eventDispatcher;
  83. private ICache $pathByIdCache;
  84. /**
  85. * @param Manager $manager
  86. * @param View $view
  87. * @param IUser|null $user
  88. */
  89. public function __construct(
  90. $manager,
  91. $view,
  92. $user,
  93. IUserMountCache $userMountCache,
  94. LoggerInterface $logger,
  95. IUserManager $userManager,
  96. IEventDispatcher $eventDispatcher,
  97. ICacheFactory $cacheFactory,
  98. ) {
  99. parent::__construct($this, $view, '');
  100. $this->mountManager = $manager;
  101. $this->user = $user;
  102. $this->emitter = new PublicEmitter();
  103. $this->userFolderCache = new CappedMemoryCache();
  104. $this->userMountCache = $userMountCache;
  105. $this->logger = $logger;
  106. $this->userManager = $userManager;
  107. $eventDispatcher->addListener(FilesystemTornDownEvent::class, function () {
  108. $this->userFolderCache = new CappedMemoryCache();
  109. });
  110. $this->pathByIdCache = $cacheFactory->createLocal('path-by-id');
  111. }
  112. /**
  113. * Get the user for which the filesystem is setup
  114. *
  115. * @return \OC\User\User
  116. */
  117. public function getUser() {
  118. return $this->user;
  119. }
  120. /**
  121. * @param string $scope
  122. * @param string $method
  123. * @param callable $callback
  124. */
  125. public function listen($scope, $method, callable $callback) {
  126. $this->emitter->listen($scope, $method, $callback);
  127. }
  128. /**
  129. * @param string $scope optional
  130. * @param string $method optional
  131. * @param callable $callback optional
  132. */
  133. public function removeListener($scope = null, $method = null, callable $callback = null) {
  134. $this->emitter->removeListener($scope, $method, $callback);
  135. }
  136. /**
  137. * @param string $scope
  138. * @param string $method
  139. * @param Node[] $arguments
  140. */
  141. public function emit($scope, $method, $arguments = []) {
  142. $this->emitter->emit($scope, $method, $arguments);
  143. }
  144. /**
  145. * @param \OC\Files\Storage\Storage $storage
  146. * @param string $mountPoint
  147. * @param array $arguments
  148. */
  149. public function mount($storage, $mountPoint, $arguments = []) {
  150. $mount = new MountPoint($storage, $mountPoint, $arguments);
  151. $this->mountManager->addMount($mount);
  152. }
  153. public function getMount(string $mountPoint): IMountPoint {
  154. return $this->mountManager->find($mountPoint);
  155. }
  156. /**
  157. * @param string $mountPoint
  158. * @return \OC\Files\Mount\MountPoint[]
  159. */
  160. public function getMountsIn(string $mountPoint): array {
  161. return $this->mountManager->findIn($mountPoint);
  162. }
  163. /**
  164. * @param string $storageId
  165. * @return \OC\Files\Mount\MountPoint[]
  166. */
  167. public function getMountByStorageId($storageId) {
  168. return $this->mountManager->findByStorageId($storageId);
  169. }
  170. /**
  171. * @param int $numericId
  172. * @return MountPoint[]
  173. */
  174. public function getMountByNumericStorageId($numericId) {
  175. return $this->mountManager->findByNumericId($numericId);
  176. }
  177. /**
  178. * @param \OC\Files\Mount\MountPoint $mount
  179. */
  180. public function unMount($mount) {
  181. $this->mountManager->remove($mount);
  182. }
  183. /**
  184. * @param string $path
  185. * @return Node
  186. * @throws \OCP\Files\NotPermittedException
  187. * @throws \OCP\Files\NotFoundException
  188. */
  189. public function get($path) {
  190. $path = $this->normalizePath($path);
  191. if ($this->isValidPath($path)) {
  192. $fullPath = $this->getFullPath($path);
  193. $fileInfo = $this->view->getFileInfo($fullPath, false);
  194. if ($fileInfo) {
  195. return $this->createNode($fullPath, $fileInfo, false);
  196. } else {
  197. throw new NotFoundException($path);
  198. }
  199. } else {
  200. throw new NotPermittedException();
  201. }
  202. }
  203. //most operations can't be done on the root
  204. /**
  205. * @param string $targetPath
  206. * @return Node
  207. * @throws \OCP\Files\NotPermittedException
  208. */
  209. public function rename($targetPath) {
  210. throw new NotPermittedException();
  211. }
  212. public function delete() {
  213. throw new NotPermittedException();
  214. }
  215. /**
  216. * @param string $targetPath
  217. * @return Node
  218. * @throws \OCP\Files\NotPermittedException
  219. */
  220. public function copy($targetPath) {
  221. throw new NotPermittedException();
  222. }
  223. /**
  224. * @param int $mtime
  225. * @throws \OCP\Files\NotPermittedException
  226. */
  227. public function touch($mtime = null) {
  228. throw new NotPermittedException();
  229. }
  230. /**
  231. * @return \OC\Files\Storage\Storage
  232. * @throws \OCP\Files\NotFoundException
  233. */
  234. public function getStorage() {
  235. throw new NotFoundException();
  236. }
  237. /**
  238. * @return string
  239. */
  240. public function getPath() {
  241. return '/';
  242. }
  243. /**
  244. * @return string
  245. */
  246. public function getInternalPath() {
  247. return '';
  248. }
  249. /**
  250. * @return int
  251. */
  252. public function getId() {
  253. return 0;
  254. }
  255. /**
  256. * @return array
  257. */
  258. public function stat() {
  259. return [];
  260. }
  261. /**
  262. * @return int
  263. */
  264. public function getMTime() {
  265. return 0;
  266. }
  267. /**
  268. * @param bool $includeMounts
  269. * @return int|float
  270. */
  271. public function getSize($includeMounts = true): int|float {
  272. return 0;
  273. }
  274. /**
  275. * @return string
  276. */
  277. public function getEtag() {
  278. return '';
  279. }
  280. /**
  281. * @return int
  282. */
  283. public function getPermissions() {
  284. return \OCP\Constants::PERMISSION_CREATE;
  285. }
  286. /**
  287. * @return bool
  288. */
  289. public function isReadable() {
  290. return false;
  291. }
  292. /**
  293. * @return bool
  294. */
  295. public function isUpdateable() {
  296. return false;
  297. }
  298. /**
  299. * @return bool
  300. */
  301. public function isDeletable() {
  302. return false;
  303. }
  304. /**
  305. * @return bool
  306. */
  307. public function isShareable() {
  308. return false;
  309. }
  310. /**
  311. * @throws \OCP\Files\NotFoundException
  312. */
  313. public function getParent(): INode|IRootFolder {
  314. throw new NotFoundException();
  315. }
  316. /**
  317. * @return string
  318. */
  319. public function getName() {
  320. return '';
  321. }
  322. /**
  323. * Returns a view to user's files folder
  324. *
  325. * @param string $userId user ID
  326. * @return \OCP\Files\Folder
  327. * @throws NoUserException
  328. * @throws NotPermittedException
  329. */
  330. public function getUserFolder($userId) {
  331. $userObject = $this->userManager->get($userId);
  332. if (is_null($userObject)) {
  333. $e = new NoUserException('Backends provided no user object');
  334. $this->logger->error(
  335. sprintf(
  336. 'Backends provided no user object for %s',
  337. $userId
  338. ),
  339. [
  340. 'app' => 'files',
  341. 'exception' => $e,
  342. ]
  343. );
  344. throw $e;
  345. }
  346. $userId = $userObject->getUID();
  347. if (!$this->userFolderCache->hasKey($userId)) {
  348. if ($this->mountManager->getSetupManager()->isSetupComplete($userObject)) {
  349. try {
  350. $folder = $this->get('/' . $userId . '/files');
  351. if (!$folder instanceof \OCP\Files\Folder) {
  352. throw new \Exception("Account folder for \"$userId\" exists as a file");
  353. }
  354. } catch (NotFoundException $e) {
  355. if (!$this->nodeExists('/' . $userId)) {
  356. $this->newFolder('/' . $userId);
  357. }
  358. $folder = $this->newFolder('/' . $userId . '/files');
  359. }
  360. } else {
  361. $folder = new LazyUserFolder($this, $userObject, $this->mountManager);
  362. }
  363. $this->userFolderCache->set($userId, $folder);
  364. }
  365. return $this->userFolderCache->get($userId);
  366. }
  367. public function getUserMountCache() {
  368. return $this->userMountCache;
  369. }
  370. public function getFirstNodeByIdInPath(int $id, string $path): ?INode {
  371. // scope the cache by user, so we don't return nodes for different users
  372. if ($this->user) {
  373. $cachedPath = $this->pathByIdCache->get($this->user->getUID() . '::' . $id);
  374. if ($cachedPath && str_starts_with($path, $cachedPath)) {
  375. // getting the node by path is significantly cheaper than finding it by id
  376. $node = $this->get($cachedPath);
  377. // by validating that the cached path still has the requested fileid we can work around the need to invalidate the cached path
  378. // if the cached path is invalid or a different file now we fall back to the uncached logic
  379. if ($node && $node->getId() === $id) {
  380. return $node;
  381. }
  382. }
  383. }
  384. $node = current($this->getByIdInPath($id, $path));
  385. if (!$node) {
  386. return null;
  387. }
  388. if ($this->user) {
  389. $this->pathByIdCache->set($this->user->getUID() . '::' . $id, $node->getPath());
  390. }
  391. return $node;
  392. }
  393. /**
  394. * @param int $id
  395. * @return Node[]
  396. */
  397. public function getByIdInPath(int $id, string $path): array {
  398. $mountCache = $this->getUserMountCache();
  399. if (strpos($path, '/', 1) > 0) {
  400. [, $user] = explode('/', $path);
  401. } else {
  402. $user = null;
  403. }
  404. $mountsContainingFile = $mountCache->getMountsForFileId($id, $user);
  405. // if the mount isn't in the cache yet, perform a setup first, then try again
  406. if (count($mountsContainingFile) === 0) {
  407. $this->mountManager->getSetupManager()->setupForPath($path, true);
  408. $mountsContainingFile = $mountCache->getMountsForFileId($id, $user);
  409. }
  410. // when a user has access through the same storage through multiple paths
  411. // (such as an external storage that is both mounted for a user and shared to the user)
  412. // the mount cache will only hold a single entry for the storage
  413. // this can lead to issues as the different ways the user has access to a storage can have different permissions
  414. //
  415. // so instead of using the cached entries directly, we instead filter the current mounts by the rootid of the cache entry
  416. $mountRootIds = array_map(function ($mount) {
  417. return $mount->getRootId();
  418. }, $mountsContainingFile);
  419. $mountRootPaths = array_map(function ($mount) {
  420. return $mount->getRootInternalPath();
  421. }, $mountsContainingFile);
  422. $mountProviders = array_unique(array_map(function ($mount) {
  423. return $mount->getMountProvider();
  424. }, $mountsContainingFile));
  425. $mountRoots = array_combine($mountRootIds, $mountRootPaths);
  426. $mounts = $this->mountManager->getMountsByMountProvider($path, $mountProviders);
  427. $mountsContainingFile = array_filter($mounts, function ($mount) use ($mountRoots) {
  428. return isset($mountRoots[$mount->getStorageRootId()]);
  429. });
  430. if (count($mountsContainingFile) === 0) {
  431. if ($user === $this->getAppDataDirectoryName()) {
  432. $folder = $this->get($path);
  433. if ($folder instanceof Folder) {
  434. return $folder->getByIdInRootMount($id);
  435. } else {
  436. throw new \Exception("getByIdInPath with non folder");
  437. }
  438. }
  439. return [];
  440. }
  441. $nodes = array_map(function (IMountPoint $mount) use ($id, $mountRoots) {
  442. $rootInternalPath = $mountRoots[$mount->getStorageRootId()];
  443. $cacheEntry = $mount->getStorage()->getCache()->get($id);
  444. if (!$cacheEntry) {
  445. return null;
  446. }
  447. // cache jails will hide the "true" internal path
  448. $internalPath = ltrim($rootInternalPath . '/' . $cacheEntry->getPath(), '/');
  449. $pathRelativeToMount = substr($internalPath, strlen($rootInternalPath));
  450. $pathRelativeToMount = ltrim($pathRelativeToMount, '/');
  451. $absolutePath = rtrim($mount->getMountPoint() . $pathRelativeToMount, '/');
  452. return $this->createNode($absolutePath, new FileInfo(
  453. $absolutePath, $mount->getStorage(), $cacheEntry->getPath(), $cacheEntry, $mount,
  454. \OC::$server->getUserManager()->get($mount->getStorage()->getOwner($pathRelativeToMount))
  455. ));
  456. }, $mountsContainingFile);
  457. $nodes = array_filter($nodes);
  458. $folders = array_filter($nodes, function (Node $node) use ($path) {
  459. return PathHelper::getRelativePath($path, $node->getPath()) !== null;
  460. });
  461. usort($folders, function ($a, $b) {
  462. return $b->getPath() <=> $a->getPath();
  463. });
  464. return $folders;
  465. }
  466. public function getNodeFromCacheEntryAndMount(ICacheEntry $cacheEntry, IMountPoint $mountPoint): INode {
  467. $path = $cacheEntry->getPath();
  468. $fullPath = $mountPoint->getMountPoint() . $path;
  469. // todo: LazyNode?
  470. $info = new FileInfo($fullPath, $mountPoint->getStorage(), $path, $cacheEntry, $mountPoint);
  471. $parentPath = dirname($fullPath);
  472. $parent = new LazyFolder($this, function () use ($parentPath) {
  473. $parent = $this->get($parentPath);
  474. if ($parent instanceof \OCP\Files\Folder) {
  475. return $parent;
  476. } else {
  477. throw new \Exception("parent $parentPath is not a folder");
  478. }
  479. }, [
  480. 'path' => $parentPath,
  481. ]);
  482. $isDir = $info->getType() === FileInfo::TYPE_FOLDER;
  483. $view = new View('');
  484. if ($isDir) {
  485. return new Folder($this, $view, $path, $info, $parent);
  486. } else {
  487. return new File($this, $view, $path, $info, $parent);
  488. }
  489. }
  490. }