SharedStorage.php 17 KB

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