Directory.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OCA\DAV\Connector\Sabre;
  8. use OC\Files\Mount\MoveableMount;
  9. use OC\Files\View;
  10. use OCA\DAV\AppInfo\Application;
  11. use OCA\DAV\Connector\Sabre\Exception\FileLocked;
  12. use OCA\DAV\Connector\Sabre\Exception\Forbidden;
  13. use OCA\DAV\Connector\Sabre\Exception\InvalidPath;
  14. use OCP\Files\FileInfo;
  15. use OCP\Files\Folder;
  16. use OCP\Files\ForbiddenException;
  17. use OCP\Files\InvalidPathException;
  18. use OCP\Files\NotPermittedException;
  19. use OCP\Files\StorageNotAvailableException;
  20. use OCP\IL10N;
  21. use OCP\IRequest;
  22. use OCP\L10N\IFactory;
  23. use OCP\Lock\ILockingProvider;
  24. use OCP\Lock\LockedException;
  25. use OCP\Share\IManager as IShareManager;
  26. use Psr\Log\LoggerInterface;
  27. use Sabre\DAV\Exception\BadRequest;
  28. use Sabre\DAV\Exception\Locked;
  29. use Sabre\DAV\Exception\NotFound;
  30. use Sabre\DAV\Exception\ServiceUnavailable;
  31. use Sabre\DAV\IFile;
  32. use Sabre\DAV\INode;
  33. class Directory extends \OCA\DAV\Connector\Sabre\Node implements \Sabre\DAV\ICollection, \Sabre\DAV\IQuota, \Sabre\DAV\IMoveTarget, \Sabre\DAV\ICopyTarget {
  34. /**
  35. * Cached directory content
  36. * @var \OCP\Files\FileInfo[]
  37. */
  38. private ?array $dirContent = null;
  39. /** Cached quota info */
  40. private ?array $quotaInfo = null;
  41. private ?CachingTree $tree = null;
  42. /**
  43. * Sets up the node, expects a full path name
  44. */
  45. public function __construct(View $view, FileInfo $info, ?CachingTree $tree = null, ?IShareManager $shareManager = null) {
  46. parent::__construct($view, $info, $shareManager);
  47. $this->tree = $tree;
  48. }
  49. /**
  50. * Creates a new file in the directory
  51. *
  52. * Data will either be supplied as a stream resource, or in certain cases
  53. * as a string. Keep in mind that you may have to support either.
  54. *
  55. * After successful creation of the file, you may choose to return the ETag
  56. * of the new file here.
  57. *
  58. * The returned ETag must be surrounded by double-quotes (The quotes should
  59. * be part of the actual string).
  60. *
  61. * If you cannot accurately determine the ETag, you should not return it.
  62. * If you don't store the file exactly as-is (you're transforming it
  63. * somehow) you should also not return an ETag.
  64. *
  65. * This means that if a subsequent GET to this new file does not exactly
  66. * return the same contents of what was submitted here, you are strongly
  67. * recommended to omit the ETag.
  68. *
  69. * @param string $name Name of the file
  70. * @param resource|string $data Initial payload
  71. * @return null|string
  72. * @throws Exception\EntityTooLarge
  73. * @throws Exception\UnsupportedMediaType
  74. * @throws FileLocked
  75. * @throws InvalidPath
  76. * @throws \Sabre\DAV\Exception
  77. * @throws \Sabre\DAV\Exception\BadRequest
  78. * @throws \Sabre\DAV\Exception\Forbidden
  79. * @throws \Sabre\DAV\Exception\ServiceUnavailable
  80. */
  81. public function createFile($name, $data = null) {
  82. try {
  83. if (!$this->fileView->isCreatable($this->path)) {
  84. throw new \Sabre\DAV\Exception\Forbidden();
  85. }
  86. $this->fileView->verifyPath($this->path, $name);
  87. $path = $this->fileView->getAbsolutePath($this->path) . '/' . $name;
  88. // in case the file already exists/overwriting
  89. $info = $this->fileView->getFileInfo($this->path . '/' . $name);
  90. if (!$info) {
  91. // use a dummy FileInfo which is acceptable here since it will be refreshed after the put is complete
  92. $info = new \OC\Files\FileInfo($path, null, null, [
  93. 'type' => FileInfo::TYPE_FILE
  94. ], null);
  95. }
  96. $node = new \OCA\DAV\Connector\Sabre\File($this->fileView, $info);
  97. // only allow 1 process to upload a file at once but still allow reading the file while writing the part file
  98. $node->acquireLock(ILockingProvider::LOCK_SHARED);
  99. $this->fileView->lockFile($path . '.upload.part', ILockingProvider::LOCK_EXCLUSIVE);
  100. $result = $node->put($data);
  101. $this->fileView->unlockFile($path . '.upload.part', ILockingProvider::LOCK_EXCLUSIVE);
  102. $node->releaseLock(ILockingProvider::LOCK_SHARED);
  103. return $result;
  104. } catch (\OCP\Files\StorageNotAvailableException $e) {
  105. throw new \Sabre\DAV\Exception\ServiceUnavailable($e->getMessage(), $e->getCode(), $e);
  106. } catch (InvalidPathException $ex) {
  107. throw new InvalidPath($ex->getMessage(), false, $ex);
  108. } catch (ForbiddenException $ex) {
  109. throw new Forbidden($ex->getMessage(), $ex->getRetry(), $ex);
  110. } catch (LockedException $e) {
  111. throw new FileLocked($e->getMessage(), $e->getCode(), $e);
  112. }
  113. }
  114. /**
  115. * Creates a new subdirectory
  116. *
  117. * @param string $name
  118. * @throws FileLocked
  119. * @throws InvalidPath
  120. * @throws \Sabre\DAV\Exception\Forbidden
  121. * @throws \Sabre\DAV\Exception\ServiceUnavailable
  122. */
  123. public function createDirectory($name) {
  124. try {
  125. if (!$this->info->isCreatable()) {
  126. throw new \Sabre\DAV\Exception\Forbidden();
  127. }
  128. $this->fileView->verifyPath($this->path, $name);
  129. $newPath = $this->path . '/' . $name;
  130. if (!$this->fileView->mkdir($newPath)) {
  131. throw new \Sabre\DAV\Exception\Forbidden('Could not create directory ' . $newPath);
  132. }
  133. } catch (\OCP\Files\StorageNotAvailableException $e) {
  134. throw new \Sabre\DAV\Exception\ServiceUnavailable($e->getMessage(), 0, $e);
  135. } catch (InvalidPathException $ex) {
  136. throw new InvalidPath($ex->getMessage(), false, $ex);
  137. } catch (ForbiddenException $ex) {
  138. throw new Forbidden($ex->getMessage(), $ex->getRetry(), $ex);
  139. } catch (LockedException $e) {
  140. throw new FileLocked($e->getMessage(), $e->getCode(), $e);
  141. }
  142. }
  143. /**
  144. * Returns a specific child node, referenced by its name
  145. *
  146. * @param string $name
  147. * @param \OCP\Files\FileInfo $info
  148. * @return \Sabre\DAV\INode
  149. * @throws InvalidPath
  150. * @throws \Sabre\DAV\Exception\NotFound
  151. * @throws \Sabre\DAV\Exception\ServiceUnavailable
  152. */
  153. public function getChild($name, $info = null, ?IRequest $request = null, ?IL10N $l10n = null) {
  154. if (!$this->info->isReadable()) {
  155. // avoid detecting files through this way
  156. throw new NotFound();
  157. }
  158. $path = $this->path . '/' . $name;
  159. if (is_null($info)) {
  160. try {
  161. $this->fileView->verifyPath($this->path, $name, true);
  162. $info = $this->fileView->getFileInfo($path);
  163. } catch (\OCP\Files\StorageNotAvailableException $e) {
  164. throw new \Sabre\DAV\Exception\ServiceUnavailable($e->getMessage(), 0, $e);
  165. } catch (InvalidPathException $ex) {
  166. throw new InvalidPath($ex->getMessage(), false, $ex);
  167. } catch (ForbiddenException $e) {
  168. throw new \Sabre\DAV\Exception\Forbidden($e->getMessage(), $e->getCode(), $e);
  169. }
  170. }
  171. if (!$info) {
  172. throw new \Sabre\DAV\Exception\NotFound('File with name ' . $path . ' could not be located');
  173. }
  174. if ($info->getMimeType() === FileInfo::MIMETYPE_FOLDER) {
  175. $node = new \OCA\DAV\Connector\Sabre\Directory($this->fileView, $info, $this->tree, $this->shareManager);
  176. } else {
  177. $node = new \OCA\DAV\Connector\Sabre\File($this->fileView, $info, $this->shareManager, $request, $l10n);
  178. }
  179. if ($this->tree) {
  180. $this->tree->cacheNode($node);
  181. }
  182. return $node;
  183. }
  184. /**
  185. * Returns an array with all the child nodes
  186. *
  187. * @return \Sabre\DAV\INode[]
  188. * @throws \Sabre\DAV\Exception\Locked
  189. * @throws \OCA\DAV\Connector\Sabre\Exception\Forbidden
  190. */
  191. public function getChildren() {
  192. if (!is_null($this->dirContent)) {
  193. return $this->dirContent;
  194. }
  195. try {
  196. if (!$this->info->isReadable()) {
  197. // return 403 instead of 404 because a 404 would make
  198. // the caller believe that the collection itself does not exist
  199. if (\OCP\Server::get(\OCP\App\IAppManager::class)->isInstalled('files_accesscontrol')) {
  200. throw new Forbidden('No read permissions. This might be caused by files_accesscontrol, check your configured rules');
  201. } else {
  202. throw new Forbidden('No read permissions');
  203. }
  204. }
  205. $folderContent = $this->getNode()->getDirectoryListing();
  206. } catch (LockedException $e) {
  207. throw new Locked();
  208. }
  209. $nodes = [];
  210. $request = \OC::$server->get(IRequest::class);
  211. $l10nFactory = \OC::$server->get(IFactory::class);
  212. $l10n = $l10nFactory->get(Application::APP_ID);
  213. foreach ($folderContent as $info) {
  214. $node = $this->getChild($info->getName(), $info, $request, $l10n);
  215. $nodes[] = $node;
  216. }
  217. $this->dirContent = $nodes;
  218. return $this->dirContent;
  219. }
  220. /**
  221. * Checks if a child exists.
  222. *
  223. * @param string $name
  224. * @return bool
  225. */
  226. public function childExists($name) {
  227. // note: here we do NOT resolve the chunk file name to the real file name
  228. // to make sure we return false when checking for file existence with a chunk
  229. // file name.
  230. // This is to make sure that "createFile" is still triggered
  231. // (required old code) instead of "updateFile".
  232. //
  233. // TODO: resolve chunk file name here and implement "updateFile"
  234. $path = $this->path . '/' . $name;
  235. return $this->fileView->file_exists($path);
  236. }
  237. /**
  238. * Deletes all files in this directory, and then itself
  239. *
  240. * @return void
  241. * @throws FileLocked
  242. * @throws \Sabre\DAV\Exception\Forbidden
  243. */
  244. public function delete() {
  245. if ($this->path === '' || $this->path === '/' || !$this->info->isDeletable()) {
  246. throw new \Sabre\DAV\Exception\Forbidden();
  247. }
  248. try {
  249. if (!$this->fileView->rmdir($this->path)) {
  250. // assume it wasn't possible to remove due to permission issue
  251. throw new \Sabre\DAV\Exception\Forbidden();
  252. }
  253. } catch (ForbiddenException $ex) {
  254. throw new Forbidden($ex->getMessage(), $ex->getRetry());
  255. } catch (LockedException $e) {
  256. throw new FileLocked($e->getMessage(), $e->getCode(), $e);
  257. }
  258. }
  259. private function getLogger(): LoggerInterface {
  260. return \OC::$server->get(LoggerInterface::class);
  261. }
  262. /**
  263. * Returns available diskspace information
  264. *
  265. * @return array
  266. */
  267. public function getQuotaInfo() {
  268. if ($this->quotaInfo) {
  269. return $this->quotaInfo;
  270. }
  271. $relativePath = $this->fileView->getRelativePath($this->info->getPath());
  272. if ($relativePath === null) {
  273. $this->getLogger()->warning('error while getting quota as the relative path cannot be found');
  274. return [0, 0];
  275. }
  276. try {
  277. $storageInfo = \OC_Helper::getStorageInfo($relativePath, $this->info, false);
  278. if ($storageInfo['quota'] === \OCP\Files\FileInfo::SPACE_UNLIMITED) {
  279. $free = \OCP\Files\FileInfo::SPACE_UNLIMITED;
  280. } else {
  281. $free = $storageInfo['free'];
  282. }
  283. $this->quotaInfo = [
  284. $storageInfo['used'],
  285. $free
  286. ];
  287. return $this->quotaInfo;
  288. } catch (\OCP\Files\NotFoundException $e) {
  289. $this->getLogger()->warning('error while getting quota into', ['exception' => $e]);
  290. return [0, 0];
  291. } catch (\OCP\Files\StorageNotAvailableException $e) {
  292. $this->getLogger()->warning('error while getting quota into', ['exception' => $e]);
  293. return [0, 0];
  294. } catch (NotPermittedException $e) {
  295. $this->getLogger()->warning('error while getting quota into', ['exception' => $e]);
  296. return [0, 0];
  297. }
  298. }
  299. /**
  300. * Moves a node into this collection.
  301. *
  302. * It is up to the implementors to:
  303. * 1. Create the new resource.
  304. * 2. Remove the old resource.
  305. * 3. Transfer any properties or other data.
  306. *
  307. * Generally you should make very sure that your collection can easily move
  308. * the move.
  309. *
  310. * If you don't, just return false, which will trigger sabre/dav to handle
  311. * the move itself. If you return true from this function, the assumption
  312. * is that the move was successful.
  313. *
  314. * @param string $targetName New local file/collection name.
  315. * @param string $fullSourcePath Full path to source node
  316. * @param INode $sourceNode Source node itself
  317. * @return bool
  318. * @throws BadRequest
  319. * @throws ServiceUnavailable
  320. * @throws Forbidden
  321. * @throws FileLocked
  322. * @throws \Sabre\DAV\Exception\Forbidden
  323. */
  324. public function moveInto($targetName, $fullSourcePath, INode $sourceNode) {
  325. if (!$sourceNode instanceof Node) {
  326. // it's a file of another kind, like FutureFile
  327. if ($sourceNode instanceof IFile) {
  328. // fallback to default copy+delete handling
  329. return false;
  330. }
  331. throw new BadRequest('Incompatible node types');
  332. }
  333. if (!$this->fileView) {
  334. throw new ServiceUnavailable('filesystem not setup');
  335. }
  336. $destinationPath = $this->getPath() . '/' . $targetName;
  337. $targetNodeExists = $this->childExists($targetName);
  338. // at getNodeForPath we also check the path for isForbiddenFileOrDir
  339. // with that we have covered both source and destination
  340. if ($sourceNode instanceof Directory && $targetNodeExists) {
  341. throw new \Sabre\DAV\Exception\Forbidden('Could not copy directory ' . $sourceNode->getName() . ', target exists');
  342. }
  343. [$sourceDir,] = \Sabre\Uri\split($sourceNode->getPath());
  344. $destinationDir = $this->getPath();
  345. $sourcePath = $sourceNode->getPath();
  346. $isMovableMount = false;
  347. $sourceMount = \OC::$server->getMountManager()->find($this->fileView->getAbsolutePath($sourcePath));
  348. $internalPath = $sourceMount->getInternalPath($this->fileView->getAbsolutePath($sourcePath));
  349. if ($sourceMount instanceof MoveableMount && $internalPath === '') {
  350. $isMovableMount = true;
  351. }
  352. try {
  353. $sameFolder = ($sourceDir === $destinationDir);
  354. // if we're overwriting or same folder
  355. if ($targetNodeExists || $sameFolder) {
  356. // note that renaming a share mount point is always allowed
  357. if (!$this->fileView->isUpdatable($destinationDir) && !$isMovableMount) {
  358. throw new \Sabre\DAV\Exception\Forbidden();
  359. }
  360. } else {
  361. if (!$this->fileView->isCreatable($destinationDir)) {
  362. throw new \Sabre\DAV\Exception\Forbidden();
  363. }
  364. }
  365. if (!$sameFolder) {
  366. // moving to a different folder, source will be gone, like a deletion
  367. // note that moving a share mount point is always allowed
  368. if (!$this->fileView->isDeletable($sourcePath) && !$isMovableMount) {
  369. throw new \Sabre\DAV\Exception\Forbidden();
  370. }
  371. }
  372. $fileName = basename($destinationPath);
  373. try {
  374. $this->fileView->verifyPath($destinationDir, $fileName);
  375. } catch (InvalidPathException $ex) {
  376. throw new InvalidPath($ex->getMessage());
  377. }
  378. $renameOkay = $this->fileView->rename($sourcePath, $destinationPath);
  379. if (!$renameOkay) {
  380. throw new \Sabre\DAV\Exception\Forbidden('');
  381. }
  382. } catch (StorageNotAvailableException $e) {
  383. throw new ServiceUnavailable($e->getMessage(), $e->getCode(), $e);
  384. } catch (ForbiddenException $ex) {
  385. throw new Forbidden($ex->getMessage(), $ex->getRetry(), $ex);
  386. } catch (LockedException $e) {
  387. throw new FileLocked($e->getMessage(), $e->getCode(), $e);
  388. }
  389. return true;
  390. }
  391. public function copyInto($targetName, $sourcePath, INode $sourceNode) {
  392. if ($sourceNode instanceof File || $sourceNode instanceof Directory) {
  393. try {
  394. $destinationPath = $this->getPath() . '/' . $targetName;
  395. $sourcePath = $sourceNode->getPath();
  396. if (!$this->fileView->isCreatable($this->getPath())) {
  397. throw new \Sabre\DAV\Exception\Forbidden();
  398. }
  399. try {
  400. $this->fileView->verifyPath($this->getPath(), $targetName);
  401. } catch (InvalidPathException $ex) {
  402. throw new InvalidPath($ex->getMessage());
  403. }
  404. return $this->fileView->copy($sourcePath, $destinationPath);
  405. } catch (StorageNotAvailableException $e) {
  406. throw new ServiceUnavailable($e->getMessage(), $e->getCode(), $e);
  407. } catch (ForbiddenException $ex) {
  408. throw new Forbidden($ex->getMessage(), $ex->getRetry(), $ex);
  409. } catch (LockedException $e) {
  410. throw new FileLocked($e->getMessage(), $e->getCode(), $e);
  411. }
  412. }
  413. return false;
  414. }
  415. public function getNode(): Folder {
  416. return $this->node;
  417. }
  418. }