You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Directory.php 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  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 OCA\DAV\AppInfo\Application;
  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 OCP\Files\FileInfo;
  41. use OCP\Files\Folder;
  42. use OCP\Files\ForbiddenException;
  43. use OCP\Files\InvalidPathException;
  44. use OCP\Files\NotPermittedException;
  45. use OCP\Files\StorageNotAvailableException;
  46. use OCP\IL10N;
  47. use OCP\IRequest;
  48. use OCP\L10N\IFactory;
  49. use OCP\Lock\ILockingProvider;
  50. use OCP\Lock\LockedException;
  51. use OCP\Share\IManager as IShareManager;
  52. use Psr\Log\LoggerInterface;
  53. use Sabre\DAV\Exception\BadRequest;
  54. use Sabre\DAV\Exception\Locked;
  55. use Sabre\DAV\Exception\NotFound;
  56. use Sabre\DAV\Exception\ServiceUnavailable;
  57. use Sabre\DAV\IFile;
  58. use Sabre\DAV\INode;
  59. class Directory extends \OCA\DAV\Connector\Sabre\Node implements \Sabre\DAV\ICollection, \Sabre\DAV\IQuota, \Sabre\DAV\IMoveTarget, \Sabre\DAV\ICopyTarget {
  60. /**
  61. * Cached directory content
  62. * @var \OCP\Files\FileInfo[]
  63. */
  64. private ?array $dirContent = null;
  65. /** Cached quota info */
  66. private ?array $quotaInfo = null;
  67. private ?CachingTree $tree = null;
  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, IRequest $request = null, IL10N $l10n = 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, $request, $l10n);
  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. $request = \OC::$server->get(IRequest::class);
  250. $l10nFactory = \OC::$server->get(IFactory::class);
  251. $l10n = $l10nFactory->get(Application::APP_ID);
  252. foreach ($folderContent as $info) {
  253. $node = $this->getChild($info->getName(), $info, $request, $l10n);
  254. $nodes[] = $node;
  255. }
  256. $this->dirContent = $nodes;
  257. return $this->dirContent;
  258. }
  259. /**
  260. * Checks if a child exists.
  261. *
  262. * @param string $name
  263. * @return bool
  264. */
  265. public function childExists($name) {
  266. // note: here we do NOT resolve the chunk file name to the real file name
  267. // to make sure we return false when checking for file existence with a chunk
  268. // file name.
  269. // This is to make sure that "createFile" is still triggered
  270. // (required old code) instead of "updateFile".
  271. //
  272. // TODO: resolve chunk file name here and implement "updateFile"
  273. $path = $this->path . '/' . $name;
  274. return $this->fileView->file_exists($path);
  275. }
  276. /**
  277. * Deletes all files in this directory, and then itself
  278. *
  279. * @return void
  280. * @throws FileLocked
  281. * @throws \Sabre\DAV\Exception\Forbidden
  282. */
  283. public function delete() {
  284. if ($this->path === '' || $this->path === '/' || !$this->info->isDeletable()) {
  285. throw new \Sabre\DAV\Exception\Forbidden();
  286. }
  287. try {
  288. if (!$this->fileView->rmdir($this->path)) {
  289. // assume it wasn't possible to remove due to permission issue
  290. throw new \Sabre\DAV\Exception\Forbidden();
  291. }
  292. } catch (ForbiddenException $ex) {
  293. throw new Forbidden($ex->getMessage(), $ex->getRetry());
  294. } catch (LockedException $e) {
  295. throw new FileLocked($e->getMessage(), $e->getCode(), $e);
  296. }
  297. }
  298. private function getLogger(): LoggerInterface {
  299. return \OC::$server->get(LoggerInterface::class);
  300. }
  301. /**
  302. * Returns available diskspace information
  303. *
  304. * @return array
  305. */
  306. public function getQuotaInfo() {
  307. if ($this->quotaInfo) {
  308. return $this->quotaInfo;
  309. }
  310. $relativePath = $this->fileView->getRelativePath($this->info->getPath());
  311. if ($relativePath === null) {
  312. $this->getLogger()->warning("error while getting quota as the relative path cannot be found");
  313. return [0, 0];
  314. }
  315. try {
  316. $storageInfo = \OC_Helper::getStorageInfo($relativePath, $this->info, false);
  317. if ($storageInfo['quota'] === \OCP\Files\FileInfo::SPACE_UNLIMITED) {
  318. $free = \OCP\Files\FileInfo::SPACE_UNLIMITED;
  319. } else {
  320. $free = $storageInfo['free'];
  321. }
  322. $this->quotaInfo = [
  323. $storageInfo['used'],
  324. $free
  325. ];
  326. return $this->quotaInfo;
  327. } catch (\OCP\Files\NotFoundException $e) {
  328. $this->getLogger()->warning("error while getting quota into", ['exception' => $e]);
  329. return [0, 0];
  330. } catch (\OCP\Files\StorageNotAvailableException $e) {
  331. $this->getLogger()->warning("error while getting quota into", ['exception' => $e]);
  332. return [0, 0];
  333. } catch (NotPermittedException $e) {
  334. $this->getLogger()->warning("error while getting quota into", ['exception' => $e]);
  335. return [0, 0];
  336. }
  337. }
  338. /**
  339. * Moves a node into this collection.
  340. *
  341. * It is up to the implementors to:
  342. * 1. Create the new resource.
  343. * 2. Remove the old resource.
  344. * 3. Transfer any properties or other data.
  345. *
  346. * Generally you should make very sure that your collection can easily move
  347. * the move.
  348. *
  349. * If you don't, just return false, which will trigger sabre/dav to handle
  350. * the move itself. If you return true from this function, the assumption
  351. * is that the move was successful.
  352. *
  353. * @param string $targetName New local file/collection name.
  354. * @param string $fullSourcePath Full path to source node
  355. * @param INode $sourceNode Source node itself
  356. * @return bool
  357. * @throws BadRequest
  358. * @throws ServiceUnavailable
  359. * @throws Forbidden
  360. * @throws FileLocked
  361. * @throws \Sabre\DAV\Exception\Forbidden
  362. */
  363. public function moveInto($targetName, $fullSourcePath, INode $sourceNode) {
  364. if (!$sourceNode instanceof Node) {
  365. // it's a file of another kind, like FutureFile
  366. if ($sourceNode instanceof IFile) {
  367. // fallback to default copy+delete handling
  368. return false;
  369. }
  370. throw new BadRequest('Incompatible node types');
  371. }
  372. if (!$this->fileView) {
  373. throw new ServiceUnavailable('filesystem not setup');
  374. }
  375. $destinationPath = $this->getPath() . '/' . $targetName;
  376. $targetNodeExists = $this->childExists($targetName);
  377. // at getNodeForPath we also check the path for isForbiddenFileOrDir
  378. // with that we have covered both source and destination
  379. if ($sourceNode instanceof Directory && $targetNodeExists) {
  380. throw new \Sabre\DAV\Exception\Forbidden('Could not copy directory ' . $sourceNode->getName() . ', target exists');
  381. }
  382. [$sourceDir,] = \Sabre\Uri\split($sourceNode->getPath());
  383. $destinationDir = $this->getPath();
  384. $sourcePath = $sourceNode->getPath();
  385. $isMovableMount = false;
  386. $sourceMount = \OC::$server->getMountManager()->find($this->fileView->getAbsolutePath($sourcePath));
  387. $internalPath = $sourceMount->getInternalPath($this->fileView->getAbsolutePath($sourcePath));
  388. if ($sourceMount instanceof MoveableMount && $internalPath === '') {
  389. $isMovableMount = true;
  390. }
  391. try {
  392. $sameFolder = ($sourceDir === $destinationDir);
  393. // if we're overwriting or same folder
  394. if ($targetNodeExists || $sameFolder) {
  395. // note that renaming a share mount point is always allowed
  396. if (!$this->fileView->isUpdatable($destinationDir) && !$isMovableMount) {
  397. throw new \Sabre\DAV\Exception\Forbidden();
  398. }
  399. } else {
  400. if (!$this->fileView->isCreatable($destinationDir)) {
  401. throw new \Sabre\DAV\Exception\Forbidden();
  402. }
  403. }
  404. if (!$sameFolder) {
  405. // moving to a different folder, source will be gone, like a deletion
  406. // note that moving a share mount point is always allowed
  407. if (!$this->fileView->isDeletable($sourcePath) && !$isMovableMount) {
  408. throw new \Sabre\DAV\Exception\Forbidden();
  409. }
  410. }
  411. $fileName = basename($destinationPath);
  412. try {
  413. $this->fileView->verifyPath($destinationDir, $fileName);
  414. } catch (InvalidPathException $ex) {
  415. throw new InvalidPath($ex->getMessage());
  416. }
  417. $renameOkay = $this->fileView->rename($sourcePath, $destinationPath);
  418. if (!$renameOkay) {
  419. throw new \Sabre\DAV\Exception\Forbidden('');
  420. }
  421. } catch (StorageNotAvailableException $e) {
  422. throw new ServiceUnavailable($e->getMessage());
  423. } catch (ForbiddenException $ex) {
  424. throw new Forbidden($ex->getMessage(), $ex->getRetry());
  425. } catch (LockedException $e) {
  426. throw new FileLocked($e->getMessage(), $e->getCode(), $e);
  427. }
  428. return true;
  429. }
  430. public function copyInto($targetName, $sourcePath, INode $sourceNode) {
  431. if ($sourceNode instanceof File || $sourceNode instanceof Directory) {
  432. $destinationPath = $this->getPath() . '/' . $targetName;
  433. $sourcePath = $sourceNode->getPath();
  434. if (!$this->fileView->isCreatable($this->getPath())) {
  435. throw new \Sabre\DAV\Exception\Forbidden();
  436. }
  437. try {
  438. $this->fileView->verifyPath($this->getPath(), $targetName);
  439. } catch (InvalidPathException $ex) {
  440. throw new InvalidPath($ex->getMessage());
  441. }
  442. return $this->fileView->copy($sourcePath, $destinationPath);
  443. }
  444. return false;
  445. }
  446. public function getNode(): Folder {
  447. return $this->node;
  448. }
  449. }