SharedStorage.php 16 KB

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