Directory.php 15 KB

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