SharedStorage.php 16 KB

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