1
0

SharedStorage.php 17 KB

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