1
0

SharedStorage.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Bart Visscher <bartv@thisnet.nl>
  6. * @author Björn Schießle <bjoern@schiessle.org>
  7. * @author J0WI <J0WI@users.noreply.github.com>
  8. * @author Joas Schilling <coding@schilljs.com>
  9. * @author Michael Gapczynski <GapczynskiM@gmail.com>
  10. * @author Morris Jobke <hey@morrisjobke.de>
  11. * @author Robin Appelman <robin@icewind.nl>
  12. * @author Robin McCorkell <robin@mccorkell.me.uk>
  13. * @author Roeland Jago Douma <roeland@famdouma.nl>
  14. * @author scambra <sergio@entrecables.com>
  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\Files_Sharing;
  34. use OC\Files\Cache\FailedCache;
  35. use OC\Files\Cache\NullWatcher;
  36. use OC\Files\Cache\Watcher;
  37. use OC\Files\ObjectStore\HomeObjectStoreStorage;
  38. use OC\Files\Storage\Common;
  39. use OC\Files\Storage\Home;
  40. use OC\User\DisplayNameCache;
  41. use OCP\Files\Folder;
  42. use OCP\Files\IHomeStorage;
  43. use OCP\Files\Node;
  44. use OC\Files\Storage\FailedStorage;
  45. use OC\Files\Storage\Wrapper\PermissionsMask;
  46. use OC\Files\Storage\Wrapper\Wrapper;
  47. use OC\User\NoUserException;
  48. use OCA\Files_External\Config\ExternalMountPoint;
  49. use OCP\Constants;
  50. use OCP\Files\Cache\ICacheEntry;
  51. use OCP\Files\IRootFolder;
  52. use OCP\Files\NotFoundException;
  53. use OCP\Files\Storage\IDisableEncryptionStorage;
  54. use OCP\Files\Storage\IStorage;
  55. use OCP\Lock\ILockingProvider;
  56. use OCP\Share\IShare;
  57. /**
  58. * Convert target path to source path and pass the function call to the correct storage provider
  59. */
  60. class SharedStorage extends \OC\Files\Storage\Wrapper\Jail implements ISharedStorage, IDisableEncryptionStorage {
  61. /** @var \OCP\Share\IShare */
  62. private $superShare;
  63. /** @var \OCP\Share\IShare[] */
  64. private $groupedShares;
  65. /**
  66. * @var \OC\Files\View
  67. */
  68. private $ownerView;
  69. private $initialized = false;
  70. /**
  71. * @var ICacheEntry
  72. */
  73. private $sourceRootInfo;
  74. /** @var string */
  75. private $user;
  76. /**
  77. * @var \OCP\ILogger
  78. */
  79. private $logger;
  80. /** @var IStorage */
  81. private $nonMaskedStorage;
  82. private array $mountOptions = [];
  83. /** @var boolean */
  84. private $sharingDisabledForUser;
  85. /** @var ?Folder $ownerUserFolder */
  86. private $ownerUserFolder = null;
  87. private string $sourcePath = '';
  88. private static int $initDepth = 0;
  89. /**
  90. * @psalm-suppress NonInvariantDocblockPropertyType
  91. * @var ?\OC\Files\Storage\Storage $storage
  92. */
  93. protected $storage;
  94. public function __construct($arguments) {
  95. $this->ownerView = $arguments['ownerView'];
  96. $this->logger = \OC::$server->getLogger();
  97. $this->superShare = $arguments['superShare'];
  98. $this->groupedShares = $arguments['groupedShares'];
  99. $this->user = $arguments['user'];
  100. if (isset($arguments['sharingDisabledForUser'])) {
  101. $this->sharingDisabledForUser = $arguments['sharingDisabledForUser'];
  102. } else {
  103. $this->sharingDisabledForUser = false;
  104. }
  105. parent::__construct([
  106. 'storage' => null,
  107. 'root' => null,
  108. ]);
  109. }
  110. /**
  111. * @return ICacheEntry
  112. */
  113. private function getSourceRootInfo() {
  114. if (is_null($this->sourceRootInfo)) {
  115. if (is_null($this->superShare->getNodeCacheEntry())) {
  116. $this->init();
  117. $this->sourceRootInfo = $this->nonMaskedStorage->getCache()->get($this->rootPath);
  118. } else {
  119. $this->sourceRootInfo = $this->superShare->getNodeCacheEntry();
  120. }
  121. }
  122. return $this->sourceRootInfo;
  123. }
  124. /**
  125. * @psalm-assert \OC\Files\Storage\Storage $this->storage
  126. */
  127. private function init() {
  128. if ($this->initialized) {
  129. if (!$this->storage) {
  130. // marked as initialized but no storage set
  131. // this is probably because some code path has caused recursion during the share setup
  132. // we setup a "failed storage" so `getWrapperStorage` doesn't return null.
  133. // If the share setup completes after this the "failed storage" will be overwritten by the correct one
  134. $this->logger->warning('Possible share setup recursion detected');
  135. $this->storage = new FailedStorage(['exception' => new \Exception('Possible share setup recursion detected')]);
  136. $this->cache = new FailedCache();
  137. $this->rootPath = '';
  138. }
  139. return;
  140. }
  141. $this->initialized = true;
  142. self::$initDepth++;
  143. try {
  144. if (self::$initDepth > 10) {
  145. throw new \Exception("Maximum share depth reached");
  146. }
  147. /** @var IRootFolder $rootFolder */
  148. $rootFolder = \OC::$server->get(IRootFolder::class);
  149. $this->ownerUserFolder = $rootFolder->getUserFolder($this->superShare->getShareOwner());
  150. $sourceId = $this->superShare->getNodeId();
  151. $ownerNodes = $this->ownerUserFolder->getById($sourceId);
  152. /** @var Node|false $ownerNode */
  153. $ownerNode = current($ownerNodes);
  154. if (!$ownerNode) {
  155. $this->storage = new FailedStorage(['exception' => new NotFoundException("File by id $sourceId not found")]);
  156. $this->cache = new FailedCache();
  157. $this->rootPath = '';
  158. } else {
  159. if ($this->nonMaskedStorage instanceof Wrapper && $this->nonMaskedStorage->isWrapperOf($this)) {
  160. throw new \Exception('recursive share detected');
  161. }
  162. $this->nonMaskedStorage = $ownerNode->getStorage();
  163. $this->sourcePath = $ownerNode->getPath();
  164. $this->rootPath = $ownerNode->getInternalPath();
  165. $this->storage = new PermissionsMask([
  166. 'storage' => $this->nonMaskedStorage,
  167. 'mask' => $this->superShare->getPermissions(),
  168. ]);
  169. }
  170. } catch (NotFoundException $e) {
  171. // original file not accessible or deleted, set FailedStorage
  172. $this->storage = new FailedStorage(['exception' => $e]);
  173. $this->cache = new FailedCache();
  174. $this->rootPath = '';
  175. } catch (NoUserException $e) {
  176. // sharer user deleted, set FailedStorage
  177. $this->storage = new FailedStorage(['exception' => $e]);
  178. $this->cache = new FailedCache();
  179. $this->rootPath = '';
  180. } catch (\Exception $e) {
  181. $this->storage = new FailedStorage(['exception' => $e]);
  182. $this->cache = new FailedCache();
  183. $this->rootPath = '';
  184. $this->logger->logException($e);
  185. }
  186. if (!$this->nonMaskedStorage) {
  187. $this->nonMaskedStorage = $this->storage;
  188. }
  189. self::$initDepth--;
  190. }
  191. /**
  192. * @inheritdoc
  193. */
  194. public function instanceOfStorage($class): bool {
  195. if ($class === '\OC\Files\Storage\Common' || $class == Common::class) {
  196. return true;
  197. }
  198. if (in_array($class, [
  199. '\OC\Files\Storage\Home',
  200. '\OC\Files\ObjectStore\HomeObjectStoreStorage',
  201. '\OCP\Files\IHomeStorage',
  202. Home::class,
  203. HomeObjectStoreStorage::class,
  204. IHomeStorage::class
  205. ])) {
  206. return false;
  207. }
  208. return parent::instanceOfStorage($class);
  209. }
  210. /**
  211. * @return string
  212. */
  213. public function getShareId() {
  214. return $this->superShare->getId();
  215. }
  216. private function isValid(): bool {
  217. return $this->getSourceRootInfo() && ($this->getSourceRootInfo()->getPermissions() & Constants::PERMISSION_SHARE) === Constants::PERMISSION_SHARE;
  218. }
  219. /**
  220. * get id of the mount point
  221. *
  222. * @return string
  223. */
  224. public function getId(): string {
  225. return 'shared::' . $this->getMountPoint();
  226. }
  227. /**
  228. * Get the permissions granted for a shared file
  229. *
  230. * @param string $path Shared target file path
  231. * @return int CRUDS permissions granted
  232. */
  233. public function getPermissions($path = ''): int {
  234. if (!$this->isValid()) {
  235. return 0;
  236. }
  237. $permissions = parent::getPermissions($path) & $this->superShare->getPermissions();
  238. // part files and the mount point always have delete permissions
  239. if ($path === '' || pathinfo($path, PATHINFO_EXTENSION) === 'part') {
  240. $permissions |= \OCP\Constants::PERMISSION_DELETE;
  241. }
  242. if ($this->sharingDisabledForUser) {
  243. $permissions &= ~\OCP\Constants::PERMISSION_SHARE;
  244. }
  245. return $permissions;
  246. }
  247. public function isCreatable($path): bool {
  248. return (bool)($this->getPermissions($path) & \OCP\Constants::PERMISSION_CREATE);
  249. }
  250. public function isReadable($path): bool {
  251. if (!$this->isValid()) {
  252. return false;
  253. }
  254. if (!$this->file_exists($path)) {
  255. return false;
  256. }
  257. /** @var IStorage $storage */
  258. /** @var string $internalPath */
  259. [$storage, $internalPath] = $this->resolvePath($path);
  260. return $storage->isReadable($internalPath);
  261. }
  262. public function isUpdatable($path): bool {
  263. return (bool)($this->getPermissions($path) & \OCP\Constants::PERMISSION_UPDATE);
  264. }
  265. public function isDeletable($path): bool {
  266. return (bool)($this->getPermissions($path) & \OCP\Constants::PERMISSION_DELETE);
  267. }
  268. public function isSharable($path): bool {
  269. if (\OCP\Util::isSharingDisabledForUser() || !\OC\Share\Share::isResharingAllowed()) {
  270. return false;
  271. }
  272. return (bool)($this->getPermissions($path) & \OCP\Constants::PERMISSION_SHARE);
  273. }
  274. public function fopen($path, $mode) {
  275. $source = $this->getUnjailedPath($path);
  276. switch ($mode) {
  277. case 'r+':
  278. case 'rb+':
  279. case 'w+':
  280. case 'wb+':
  281. case 'x+':
  282. case 'xb+':
  283. case 'a+':
  284. case 'ab+':
  285. case 'w':
  286. case 'wb':
  287. case 'x':
  288. case 'xb':
  289. case 'a':
  290. case 'ab':
  291. $creatable = $this->isCreatable(dirname($path));
  292. $updatable = $this->isUpdatable($path);
  293. // if neither permissions given, no need to continue
  294. if (!$creatable && !$updatable) {
  295. if (pathinfo($path, PATHINFO_EXTENSION) === 'part') {
  296. $updatable = $this->isUpdatable(dirname($path));
  297. }
  298. if (!$updatable) {
  299. return false;
  300. }
  301. }
  302. $exists = $this->file_exists($path);
  303. // if a file exists, updatable permissions are required
  304. if ($exists && !$updatable) {
  305. return false;
  306. }
  307. // part file is allowed if !$creatable but the final file is $updatable
  308. if (pathinfo($path, PATHINFO_EXTENSION) !== 'part') {
  309. if (!$exists && !$creatable) {
  310. return false;
  311. }
  312. }
  313. }
  314. $info = [
  315. 'target' => $this->getMountPoint() . '/' . $path,
  316. 'source' => $source,
  317. 'mode' => $mode,
  318. ];
  319. \OCP\Util::emitHook('\OC\Files\Storage\Shared', 'fopen', $info);
  320. return $this->nonMaskedStorage->fopen($this->getUnjailedPath($path), $mode);
  321. }
  322. /**
  323. * see https://www.php.net/manual/en/function.rename.php
  324. *
  325. * @param string $source
  326. * @param string $target
  327. * @return bool
  328. */
  329. public function rename($source, $target): bool {
  330. $this->init();
  331. $isPartFile = pathinfo($source, PATHINFO_EXTENSION) === 'part';
  332. $targetExists = $this->file_exists($target);
  333. $sameFolder = dirname($source) === dirname($target);
  334. if ($targetExists || ($sameFolder && !$isPartFile)) {
  335. if (!$this->isUpdatable('')) {
  336. return false;
  337. }
  338. } else {
  339. if (!$this->isCreatable('')) {
  340. return false;
  341. }
  342. }
  343. return $this->nonMaskedStorage->rename($this->getUnjailedPath($source), $this->getUnjailedPath($target));
  344. }
  345. /**
  346. * return mount point of share, relative to data/user/files
  347. *
  348. * @return string
  349. */
  350. public function getMountPoint(): string {
  351. return $this->superShare->getTarget();
  352. }
  353. /**
  354. * @param string $path
  355. */
  356. public function setMountPoint($path): void {
  357. $this->superShare->setTarget($path);
  358. foreach ($this->groupedShares as $share) {
  359. $share->setTarget($path);
  360. }
  361. }
  362. /**
  363. * get the user who shared the file
  364. *
  365. * @return string
  366. */
  367. public function getSharedFrom(): string {
  368. return $this->superShare->getShareOwner();
  369. }
  370. /**
  371. * @return \OCP\Share\IShare
  372. */
  373. public function getShare(): IShare {
  374. return $this->superShare;
  375. }
  376. /**
  377. * return share type, can be "file" or "folder"
  378. *
  379. * @return string
  380. */
  381. public function getItemType(): string {
  382. return $this->superShare->getNodeType();
  383. }
  384. public function getCache($path = '', $storage = null) {
  385. if ($this->cache) {
  386. return $this->cache;
  387. }
  388. if (!$storage) {
  389. $storage = $this;
  390. }
  391. $sourceRoot = $this->getSourceRootInfo();
  392. if ($this->storage instanceof FailedStorage) {
  393. return new FailedCache();
  394. }
  395. $this->cache = new \OCA\Files_Sharing\Cache(
  396. $storage,
  397. $sourceRoot,
  398. \OC::$server->get(DisplayNameCache::class),
  399. $this->getShare()
  400. );
  401. return $this->cache;
  402. }
  403. public function getScanner($path = '', $storage = null) {
  404. if (!$storage) {
  405. $storage = $this;
  406. }
  407. return new \OCA\Files_Sharing\Scanner($storage);
  408. }
  409. public function getOwner($path): string {
  410. return $this->superShare->getShareOwner();
  411. }
  412. public function getWatcher($path = '', $storage = null): Watcher {
  413. $mountManager = \OC::$server->getMountManager();
  414. // Get node information
  415. $node = $this->getShare()->getNodeCacheEntry();
  416. if ($node) {
  417. $mount = $mountManager->findByNumericId($node->getStorageId());
  418. // If the share is originating from an external storage
  419. if (count($mount) > 0 && $mount[0] instanceof ExternalMountPoint) {
  420. // Propagate original storage scan
  421. return parent::getWatcher($path, $storage);
  422. }
  423. }
  424. // cache updating is handled by the share source
  425. return new NullWatcher();
  426. }
  427. /**
  428. * unshare complete storage, also the grouped shares
  429. *
  430. * @return bool
  431. */
  432. public function unshareStorage(): bool {
  433. foreach ($this->groupedShares as $share) {
  434. \OC::$server->getShareManager()->deleteFromSelf($share, $this->user);
  435. }
  436. return true;
  437. }
  438. /**
  439. * @param string $path
  440. * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
  441. * @param \OCP\Lock\ILockingProvider $provider
  442. * @throws \OCP\Lock\LockedException
  443. */
  444. public function acquireLock($path, $type, ILockingProvider $provider) {
  445. /** @var \OCP\Files\Storage $targetStorage */
  446. [$targetStorage, $targetInternalPath] = $this->resolvePath($path);
  447. $targetStorage->acquireLock($targetInternalPath, $type, $provider);
  448. // lock the parent folders of the owner when locking the share as recipient
  449. if ($path === '') {
  450. $sourcePath = $this->ownerUserFolder->getRelativePath($this->sourcePath);
  451. $this->ownerView->lockFile(dirname($sourcePath), ILockingProvider::LOCK_SHARED, true);
  452. }
  453. }
  454. /**
  455. * @param string $path
  456. * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
  457. * @param \OCP\Lock\ILockingProvider $provider
  458. */
  459. public function releaseLock($path, $type, ILockingProvider $provider) {
  460. /** @var \OCP\Files\Storage $targetStorage */
  461. [$targetStorage, $targetInternalPath] = $this->resolvePath($path);
  462. $targetStorage->releaseLock($targetInternalPath, $type, $provider);
  463. // unlock the parent folders of the owner when unlocking the share as recipient
  464. if ($path === '') {
  465. $sourcePath = $this->ownerUserFolder->getRelativePath($this->sourcePath);
  466. $this->ownerView->unlockFile(dirname($sourcePath), ILockingProvider::LOCK_SHARED, true);
  467. }
  468. }
  469. /**
  470. * @param string $path
  471. * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
  472. * @param \OCP\Lock\ILockingProvider $provider
  473. */
  474. public function changeLock($path, $type, ILockingProvider $provider) {
  475. /** @var \OCP\Files\Storage $targetStorage */
  476. [$targetStorage, $targetInternalPath] = $this->resolvePath($path);
  477. $targetStorage->changeLock($targetInternalPath, $type, $provider);
  478. }
  479. /**
  480. * @return array [ available, last_checked ]
  481. */
  482. public function getAvailability() {
  483. // shares do not participate in availability logic
  484. return [
  485. 'available' => true,
  486. 'last_checked' => 0,
  487. ];
  488. }
  489. /**
  490. * @param bool $isAvailable
  491. */
  492. public function setAvailability($isAvailable) {
  493. // shares do not participate in availability logic
  494. }
  495. public function getSourceStorage() {
  496. $this->init();
  497. return $this->nonMaskedStorage;
  498. }
  499. public function getWrapperStorage() {
  500. $this->init();
  501. /**
  502. * @psalm-suppress DocblockTypeContradiction
  503. */
  504. if (!$this->storage) {
  505. $message = "no storage set after init for share " . $this->getShareId();
  506. $this->logger->error($message);
  507. $this->storage = new FailedStorage(['exception' => new \Exception($message)]);
  508. }
  509. return $this->storage;
  510. }
  511. public function file_get_contents($path) {
  512. $info = [
  513. 'target' => $this->getMountPoint() . '/' . $path,
  514. 'source' => $this->getUnjailedPath($path),
  515. ];
  516. \OCP\Util::emitHook('\OC\Files\Storage\Shared', 'file_get_contents', $info);
  517. return parent::file_get_contents($path);
  518. }
  519. public function file_put_contents($path, $data) {
  520. $info = [
  521. 'target' => $this->getMountPoint() . '/' . $path,
  522. 'source' => $this->getUnjailedPath($path),
  523. ];
  524. \OCP\Util::emitHook('\OC\Files\Storage\Shared', 'file_put_contents', $info);
  525. return parent::file_put_contents($path, $data);
  526. }
  527. /**
  528. * @return void
  529. */
  530. public function setMountOptions(array $options) {
  531. /* Note: This value is never read */
  532. $this->mountOptions = $options;
  533. }
  534. public function getUnjailedPath($path) {
  535. $this->init();
  536. return parent::getUnjailedPath($path);
  537. }
  538. }