1
0

SharedStorage.php 16 KB

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