Directory.php 16 KB

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