SharedStorage.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  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\User\NoUserException;
  44. use OCA\Files_External\Config\ConfigAdapter;
  45. use OCP\Constants;
  46. use OCP\Files\Cache\ICacheEntry;
  47. use OCP\Files\Config\IUserMountCache;
  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. public function __construct($arguments) {
  87. $this->ownerView = $arguments['ownerView'];
  88. $this->logger = \OC::$server->get(LoggerInterface::class);
  89. $this->superShare = $arguments['superShare'];
  90. $this->groupedShares = $arguments['groupedShares'];
  91. $this->user = $arguments['user'];
  92. if (isset($arguments['sharingDisabledForUser'])) {
  93. $this->sharingDisabledForUser = $arguments['sharingDisabledForUser'];
  94. } else {
  95. $this->sharingDisabledForUser = false;
  96. }
  97. parent::__construct([
  98. 'storage' => null,
  99. 'root' => null,
  100. ]);
  101. }
  102. /**
  103. * @return ICacheEntry
  104. */
  105. private function getSourceRootInfo() {
  106. if (is_null($this->sourceRootInfo)) {
  107. if (is_null($this->superShare->getNodeCacheEntry())) {
  108. $this->init();
  109. $this->sourceRootInfo = $this->nonMaskedStorage->getCache()->get($this->rootPath);
  110. } else {
  111. $this->sourceRootInfo = $this->superShare->getNodeCacheEntry();
  112. }
  113. }
  114. return $this->sourceRootInfo;
  115. }
  116. private function init() {
  117. if ($this->initialized) {
  118. return;
  119. }
  120. $this->initialized = true;
  121. try {
  122. /** @var IRootFolder $rootFolder */
  123. $rootFolder = \OC::$server->get(IRootFolder::class);
  124. $this->ownerUserFolder = $rootFolder->getUserFolder($this->superShare->getShareOwner());
  125. $sourceId = $this->superShare->getNodeId();
  126. $ownerNodes = $this->ownerUserFolder->getById($sourceId);
  127. /** @var Node|false $ownerNode */
  128. $ownerNode = current($ownerNodes);
  129. if (!$ownerNode) {
  130. $this->storage = new FailedStorage(['exception' => new NotFoundException("File by id $sourceId not found")]);
  131. $this->cache = new FailedCache();
  132. $this->rootPath = '';
  133. } else {
  134. $this->nonMaskedStorage = $ownerNode->getStorage();
  135. $this->sourcePath = $ownerNode->getPath();
  136. $this->rootPath = $ownerNode->getInternalPath();
  137. $this->storage = new PermissionsMask([
  138. 'storage' => $this->nonMaskedStorage,
  139. 'mask' => $this->superShare->getPermissions(),
  140. ]);
  141. }
  142. } catch (NotFoundException $e) {
  143. // original file not accessible or deleted, set FailedStorage
  144. $this->storage = new FailedStorage(['exception' => $e]);
  145. $this->cache = new FailedCache();
  146. $this->rootPath = '';
  147. } catch (NoUserException $e) {
  148. // sharer user deleted, set FailedStorage
  149. $this->storage = new FailedStorage(['exception' => $e]);
  150. $this->cache = new FailedCache();
  151. $this->rootPath = '';
  152. } catch (\Exception $e) {
  153. $this->storage = new FailedStorage(['exception' => $e]);
  154. $this->cache = new FailedCache();
  155. $this->rootPath = '';
  156. $this->logger->error($e->getMessage(), ['exception' => $e]);
  157. }
  158. if (!$this->nonMaskedStorage) {
  159. $this->nonMaskedStorage = $this->storage;
  160. }
  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 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. return $this->storage;
  481. }
  482. public function file_get_contents($path) {
  483. $info = [
  484. 'target' => $this->getMountPoint() . '/' . $path,
  485. 'source' => $this->getUnjailedPath($path),
  486. ];
  487. \OCP\Util::emitHook('\OC\Files\Storage\Shared', 'file_get_contents', $info);
  488. return parent::file_get_contents($path);
  489. }
  490. public function file_put_contents($path, $data) {
  491. $info = [
  492. 'target' => $this->getMountPoint() . '/' . $path,
  493. 'source' => $this->getUnjailedPath($path),
  494. ];
  495. \OCP\Util::emitHook('\OC\Files\Storage\Shared', 'file_put_contents', $info);
  496. return parent::file_put_contents($path, $data);
  497. }
  498. /**
  499. * @return void
  500. */
  501. public function setMountOptions(array $options) {
  502. /* Note: This value is never read */
  503. $this->mountOptions = $options;
  504. }
  505. public function getUnjailedPath($path) {
  506. $this->init();
  507. return parent::getUnjailedPath($path);
  508. }
  509. }