SharedStorage.php 17 KB

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