Directory.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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 OC\Metadata\MetadataGroup;
  38. use OCA\DAV\Connector\Sabre\Exception\FileLocked;
  39. use OCA\DAV\Connector\Sabre\Exception\Forbidden;
  40. use OCA\DAV\Connector\Sabre\Exception\InvalidPath;
  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. try {
  307. $storageInfo = \OC_Helper::getStorageInfo($this->info->getPath(), $this->info, false);
  308. if ($storageInfo['quota'] === \OCP\Files\FileInfo::SPACE_UNLIMITED) {
  309. $free = \OCP\Files\FileInfo::SPACE_UNLIMITED;
  310. } else {
  311. $free = $storageInfo['free'];
  312. }
  313. $this->quotaInfo = [
  314. $storageInfo['used'],
  315. $free
  316. ];
  317. return $this->quotaInfo;
  318. } catch (\OCP\Files\NotFoundException $e) {
  319. $logger->warning("error while getting quota into", ['exception' => $e]);
  320. return [0, 0];
  321. } catch (\OCP\Files\StorageNotAvailableException $e) {
  322. $logger->warning("error while getting quota into", ['exception' => $e]);
  323. return [0, 0];
  324. } catch (NotPermittedException $e) {
  325. $logger->warning("error while getting quota into", ['exception' => $e]);
  326. return [0, 0];
  327. }
  328. }
  329. /**
  330. * Moves a node into this collection.
  331. *
  332. * It is up to the implementors to:
  333. * 1. Create the new resource.
  334. * 2. Remove the old resource.
  335. * 3. Transfer any properties or other data.
  336. *
  337. * Generally you should make very sure that your collection can easily move
  338. * the move.
  339. *
  340. * If you don't, just return false, which will trigger sabre/dav to handle
  341. * the move itself. If you return true from this function, the assumption
  342. * is that the move was successful.
  343. *
  344. * @param string $targetName New local file/collection name.
  345. * @param string $fullSourcePath Full path to source node
  346. * @param INode $sourceNode Source node itself
  347. * @return bool
  348. * @throws BadRequest
  349. * @throws ServiceUnavailable
  350. * @throws Forbidden
  351. * @throws FileLocked
  352. * @throws \Sabre\DAV\Exception\Forbidden
  353. */
  354. public function moveInto($targetName, $fullSourcePath, INode $sourceNode) {
  355. if (!$sourceNode instanceof Node) {
  356. // it's a file of another kind, like FutureFile
  357. if ($sourceNode instanceof IFile) {
  358. // fallback to default copy+delete handling
  359. return false;
  360. }
  361. throw new BadRequest('Incompatible node types');
  362. }
  363. if (!$this->fileView) {
  364. throw new ServiceUnavailable('filesystem not setup');
  365. }
  366. $destinationPath = $this->getPath() . '/' . $targetName;
  367. $targetNodeExists = $this->childExists($targetName);
  368. // at getNodeForPath we also check the path for isForbiddenFileOrDir
  369. // with that we have covered both source and destination
  370. if ($sourceNode instanceof Directory && $targetNodeExists) {
  371. throw new \Sabre\DAV\Exception\Forbidden('Could not copy directory ' . $sourceNode->getName() . ', target exists');
  372. }
  373. [$sourceDir,] = \Sabre\Uri\split($sourceNode->getPath());
  374. $destinationDir = $this->getPath();
  375. $sourcePath = $sourceNode->getPath();
  376. $isMovableMount = false;
  377. $sourceMount = \OC::$server->getMountManager()->find($this->fileView->getAbsolutePath($sourcePath));
  378. $internalPath = $sourceMount->getInternalPath($this->fileView->getAbsolutePath($sourcePath));
  379. if ($sourceMount instanceof MoveableMount && $internalPath === '') {
  380. $isMovableMount = true;
  381. }
  382. try {
  383. $sameFolder = ($sourceDir === $destinationDir);
  384. // if we're overwriting or same folder
  385. if ($targetNodeExists || $sameFolder) {
  386. // note that renaming a share mount point is always allowed
  387. if (!$this->fileView->isUpdatable($destinationDir) && !$isMovableMount) {
  388. throw new \Sabre\DAV\Exception\Forbidden();
  389. }
  390. } else {
  391. if (!$this->fileView->isCreatable($destinationDir)) {
  392. throw new \Sabre\DAV\Exception\Forbidden();
  393. }
  394. }
  395. if (!$sameFolder) {
  396. // moving to a different folder, source will be gone, like a deletion
  397. // note that moving a share mount point is always allowed
  398. if (!$this->fileView->isDeletable($sourcePath) && !$isMovableMount) {
  399. throw new \Sabre\DAV\Exception\Forbidden();
  400. }
  401. }
  402. $fileName = basename($destinationPath);
  403. try {
  404. $this->fileView->verifyPath($destinationDir, $fileName);
  405. } catch (InvalidPathException $ex) {
  406. throw new InvalidPath($ex->getMessage());
  407. }
  408. $renameOkay = $this->fileView->rename($sourcePath, $destinationPath);
  409. if (!$renameOkay) {
  410. throw new \Sabre\DAV\Exception\Forbidden('');
  411. }
  412. } catch (StorageNotAvailableException $e) {
  413. throw new ServiceUnavailable($e->getMessage());
  414. } catch (ForbiddenException $ex) {
  415. throw new Forbidden($ex->getMessage(), $ex->getRetry());
  416. } catch (LockedException $e) {
  417. throw new FileLocked($e->getMessage(), $e->getCode(), $e);
  418. }
  419. return true;
  420. }
  421. public function copyInto($targetName, $sourcePath, INode $sourceNode) {
  422. if ($sourceNode instanceof File || $sourceNode instanceof Directory) {
  423. $destinationPath = $this->getPath() . '/' . $targetName;
  424. $sourcePath = $sourceNode->getPath();
  425. if (!$this->fileView->isCreatable($this->getPath())) {
  426. throw new \Sabre\DAV\Exception\Forbidden();
  427. }
  428. try {
  429. $this->fileView->verifyPath($this->getPath(), $targetName);
  430. } catch (InvalidPathException $ex) {
  431. throw new InvalidPath($ex->getMessage());
  432. }
  433. return $this->fileView->copy($sourcePath, $destinationPath);
  434. }
  435. return false;
  436. }
  437. public function getNode(): Folder {
  438. return $this->node;
  439. }
  440. }