OwnershipTransferService.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2019 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OCA\Files\Service;
  8. use Closure;
  9. use OC\Encryption\Manager as EncryptionManager;
  10. use OC\Files\Filesystem;
  11. use OC\Files\View;
  12. use OCA\Files\Exception\TransferOwnershipException;
  13. use OCP\Encryption\IManager as IEncryptionManager;
  14. use OCP\Files\Config\IUserMountCache;
  15. use OCP\Files\FileInfo;
  16. use OCP\Files\IHomeStorage;
  17. use OCP\Files\InvalidPathException;
  18. use OCP\Files\IRootFolder;
  19. use OCP\Files\Mount\IMountManager;
  20. use OCP\IUser;
  21. use OCP\IUserManager;
  22. use OCP\L10N\IFactory;
  23. use OCP\Share\IManager as IShareManager;
  24. use OCP\Share\IShare;
  25. use Symfony\Component\Console\Helper\ProgressBar;
  26. use Symfony\Component\Console\Output\NullOutput;
  27. use Symfony\Component\Console\Output\OutputInterface;
  28. use function array_merge;
  29. use function basename;
  30. use function count;
  31. use function date;
  32. use function is_dir;
  33. use function rtrim;
  34. class OwnershipTransferService {
  35. private IEncryptionManager|EncryptionManager $encryptionManager;
  36. public function __construct(
  37. IEncryptionManager $encryptionManager,
  38. private IShareManager $shareManager,
  39. private IMountManager $mountManager,
  40. private IUserMountCache $userMountCache,
  41. private IUserManager $userManager,
  42. private IFactory $l10nFactory,
  43. ) {
  44. $this->encryptionManager = $encryptionManager;
  45. }
  46. /**
  47. * @param IUser $sourceUser
  48. * @param IUser $destinationUser
  49. * @param string $path
  50. *
  51. * @param OutputInterface|null $output
  52. * @param bool $move
  53. * @throws TransferOwnershipException
  54. * @throws \OC\User\NoUserException
  55. */
  56. public function transfer(
  57. IUser $sourceUser,
  58. IUser $destinationUser,
  59. string $path,
  60. ?OutputInterface $output = null,
  61. bool $move = false,
  62. bool $firstLogin = false,
  63. bool $transferIncomingShares = false,
  64. ): void {
  65. $output = $output ?? new NullOutput();
  66. $sourceUid = $sourceUser->getUID();
  67. $destinationUid = $destinationUser->getUID();
  68. $sourcePath = rtrim($sourceUid . '/files/' . $path, '/');
  69. // If encryption is on we have to ensure the user has logged in before and that all encryption modules are ready
  70. if (($this->encryptionManager->isEnabled() && $destinationUser->getLastLogin() === 0)
  71. || !$this->encryptionManager->isReadyForUser($destinationUid)) {
  72. throw new TransferOwnershipException("The target user is not ready to accept files. The user has at least to have logged in once.", 2);
  73. }
  74. // setup filesystem
  75. // Requesting the user folder will set it up if the user hasn't logged in before
  76. // We need a setupFS for the full filesystem setup before as otherwise we will just return
  77. // a lazy root folder which does not create the destination users folder
  78. \OC_Util::setupFS($destinationUser->getUID());
  79. \OC::$server->getUserFolder($destinationUser->getUID());
  80. Filesystem::initMountPoints($sourceUid);
  81. Filesystem::initMountPoints($destinationUid);
  82. $view = new View();
  83. if ($move) {
  84. $finalTarget = "$destinationUid/files/";
  85. } else {
  86. $l = $this->l10nFactory->get('files', $this->l10nFactory->getUserLanguage($destinationUser));
  87. $date = date('Y-m-d H-i-s');
  88. $cleanUserName = $this->sanitizeFolderName($sourceUser->getDisplayName()) ?: $sourceUid;
  89. $finalTarget = "$destinationUid/files/" . $this->sanitizeFolderName($l->t('Transferred from %1$s on %2$s', [$cleanUserName, $date]));
  90. try {
  91. $view->verifyPath(dirname($finalTarget), basename($finalTarget));
  92. } catch (InvalidPathException $e) {
  93. $finalTarget = "$destinationUid/files/" . $this->sanitizeFolderName($l->t('Transferred from %1$s on %2$s', [$sourceUid, $date]));
  94. }
  95. }
  96. if (!($view->is_dir($sourcePath) || $view->is_file($sourcePath))) {
  97. throw new TransferOwnershipException("Unknown path provided: $path", 1);
  98. }
  99. if ($move && !$view->is_dir($finalTarget)) {
  100. // Initialize storage
  101. \OC_Util::setupFS($destinationUser->getUID());
  102. }
  103. if ($move && !$firstLogin && count($view->getDirectoryContent($finalTarget)) > 0) {
  104. throw new TransferOwnershipException("Destination path does not exists or is not empty", 1);
  105. }
  106. // analyse source folder
  107. $this->analyse(
  108. $sourceUid,
  109. $destinationUid,
  110. $sourcePath,
  111. $view,
  112. $output
  113. );
  114. // collect all the shares
  115. $shares = $this->collectUsersShares(
  116. $sourceUid,
  117. $output,
  118. $view,
  119. $sourcePath
  120. );
  121. // transfer the files
  122. $this->transferFiles(
  123. $sourceUid,
  124. $sourcePath,
  125. $finalTarget,
  126. $view,
  127. $output
  128. );
  129. $destinationPath = $finalTarget . '/' . $path;
  130. // restore the shares
  131. $this->restoreShares(
  132. $sourceUid,
  133. $destinationUid,
  134. $destinationPath,
  135. $shares,
  136. $output
  137. );
  138. // transfer the incoming shares
  139. if ($transferIncomingShares === true) {
  140. $sourceShares = $this->collectIncomingShares(
  141. $sourceUid,
  142. $output,
  143. $view
  144. );
  145. $destinationShares = $this->collectIncomingShares(
  146. $destinationUid,
  147. $output,
  148. $view,
  149. true
  150. );
  151. $this->transferIncomingShares(
  152. $sourceUid,
  153. $destinationUid,
  154. $sourceShares,
  155. $destinationShares,
  156. $output,
  157. $path,
  158. $finalTarget,
  159. $move
  160. );
  161. }
  162. }
  163. private function sanitizeFolderName(string $name): string {
  164. // Remove some characters which are prone to cause errors
  165. $name = str_replace(['\\', '/', ':', '.', '?', '#', '\'', '"'], '-', $name);
  166. // Replace multiple dashes with one dash
  167. return preg_replace('/-{2,}/s', '-', $name);
  168. }
  169. private function walkFiles(View $view, $path, Closure $callBack) {
  170. foreach ($view->getDirectoryContent($path) as $fileInfo) {
  171. if (!$callBack($fileInfo)) {
  172. return;
  173. }
  174. if ($fileInfo->getType() === FileInfo::TYPE_FOLDER) {
  175. $this->walkFiles($view, $fileInfo->getPath(), $callBack);
  176. }
  177. }
  178. }
  179. /**
  180. * @param OutputInterface $output
  181. *
  182. * @throws \Exception
  183. */
  184. protected function analyse(string $sourceUid,
  185. string $destinationUid,
  186. string $sourcePath,
  187. View $view,
  188. OutputInterface $output): void {
  189. $output->writeln('Validating quota');
  190. $size = $view->getFileInfo($sourcePath, false)->getSize(false);
  191. $freeSpace = $view->free_space($destinationUid . '/files/');
  192. if ($size > $freeSpace && $freeSpace !== FileInfo::SPACE_UNKNOWN) {
  193. $output->writeln('<error>Target user does not have enough free space available.</error>');
  194. throw new \Exception('Execution terminated.');
  195. }
  196. $output->writeln("Analysing files of $sourceUid ...");
  197. $progress = new ProgressBar($output);
  198. $progress->start();
  199. $encryptedFiles = [];
  200. $this->walkFiles($view, $sourcePath,
  201. function (FileInfo $fileInfo) use ($progress, &$encryptedFiles) {
  202. if ($fileInfo->getType() === FileInfo::TYPE_FOLDER) {
  203. // only analyze into folders from main storage,
  204. if (!$fileInfo->getStorage()->instanceOfStorage(IHomeStorage::class)) {
  205. return false;
  206. }
  207. return true;
  208. }
  209. $progress->advance();
  210. if ($fileInfo->isEncrypted()) {
  211. $encryptedFiles[] = $fileInfo;
  212. }
  213. return true;
  214. });
  215. $progress->finish();
  216. $output->writeln('');
  217. // no file is allowed to be encrypted
  218. if (!empty($encryptedFiles)) {
  219. $output->writeln("<error>Some files are encrypted - please decrypt them first.</error>");
  220. foreach ($encryptedFiles as $encryptedFile) {
  221. /** @var FileInfo $encryptedFile */
  222. $output->writeln(" " . $encryptedFile->getPath());
  223. }
  224. throw new \Exception('Execution terminated.');
  225. }
  226. }
  227. /**
  228. * @return array<array{share: IShare, suffix: string}>
  229. */
  230. private function collectUsersShares(
  231. string $sourceUid,
  232. OutputInterface $output,
  233. View $view,
  234. string $path,
  235. ): array {
  236. $output->writeln("Collecting all share information for files and folders of $sourceUid ...");
  237. $shares = [];
  238. $progress = new ProgressBar($output);
  239. $normalizedPath = Filesystem::normalizePath($path);
  240. $supportedShareTypes = [
  241. IShare::TYPE_GROUP,
  242. IShare::TYPE_USER,
  243. IShare::TYPE_LINK,
  244. IShare::TYPE_REMOTE,
  245. IShare::TYPE_ROOM,
  246. IShare::TYPE_EMAIL,
  247. IShare::TYPE_CIRCLE,
  248. IShare::TYPE_DECK,
  249. IShare::TYPE_SCIENCEMESH,
  250. ];
  251. foreach ($supportedShareTypes as $shareType) {
  252. $offset = 0;
  253. while (true) {
  254. $sharePage = $this->shareManager->getSharesBy($sourceUid, $shareType, null, true, 50, $offset);
  255. $progress->advance(count($sharePage));
  256. if (empty($sharePage)) {
  257. break;
  258. }
  259. if ($path !== "$sourceUid/files") {
  260. $sharePage = array_filter($sharePage, function (IShare $share) use ($view, $normalizedPath) {
  261. try {
  262. $relativePath = $view->getPath($share->getNodeId());
  263. $singleFileTranfer = $view->is_file($normalizedPath);
  264. if ($singleFileTranfer) {
  265. return Filesystem::normalizePath($relativePath) === $normalizedPath;
  266. }
  267. return mb_strpos(
  268. Filesystem::normalizePath($relativePath . '/', false),
  269. $normalizedPath . '/') === 0;
  270. } catch (\Exception $e) {
  271. return false;
  272. }
  273. });
  274. }
  275. $shares = array_merge($shares, $sharePage);
  276. $offset += 50;
  277. }
  278. }
  279. $progress->finish();
  280. $output->writeln('');
  281. return array_map(fn (IShare $share) => [
  282. 'share' => $share,
  283. 'suffix' => substr(Filesystem::normalizePath($view->getPath($share->getNodeId())), strlen($normalizedPath)),
  284. ], $shares);
  285. }
  286. private function collectIncomingShares(string $sourceUid,
  287. OutputInterface $output,
  288. View $view,
  289. bool $addKeys = false): array {
  290. $output->writeln("Collecting all incoming share information for files and folders of $sourceUid ...");
  291. $shares = [];
  292. $progress = new ProgressBar($output);
  293. $offset = 0;
  294. while (true) {
  295. $sharePage = $this->shareManager->getSharedWith($sourceUid, IShare::TYPE_USER, null, 50, $offset);
  296. $progress->advance(count($sharePage));
  297. if (empty($sharePage)) {
  298. break;
  299. }
  300. if ($addKeys) {
  301. foreach ($sharePage as $singleShare) {
  302. $shares[$singleShare->getNodeId()] = $singleShare;
  303. }
  304. } else {
  305. foreach ($sharePage as $singleShare) {
  306. $shares[] = $singleShare;
  307. }
  308. }
  309. $offset += 50;
  310. }
  311. $progress->finish();
  312. $output->writeln('');
  313. return $shares;
  314. }
  315. /**
  316. * @throws TransferOwnershipException
  317. */
  318. protected function transferFiles(string $sourceUid,
  319. string $sourcePath,
  320. string $finalTarget,
  321. View $view,
  322. OutputInterface $output): void {
  323. $output->writeln("Transferring files to $finalTarget ...");
  324. // This change will help user to transfer the folder specified using --path option.
  325. // Else only the content inside folder is transferred which is not correct.
  326. if ($sourcePath !== "$sourceUid/files") {
  327. $view->mkdir($finalTarget);
  328. $finalTarget = $finalTarget . '/' . basename($sourcePath);
  329. }
  330. if ($view->rename($sourcePath, $finalTarget) === false) {
  331. throw new TransferOwnershipException("Could not transfer files.", 1);
  332. }
  333. if (!is_dir("$sourceUid/files")) {
  334. // because the files folder is moved away we need to recreate it
  335. $view->mkdir("$sourceUid/files");
  336. }
  337. }
  338. /**
  339. * @param string $targetLocation New location of the transfered node
  340. * @param array<array{share: IShare, suffix: string}> $shares previously collected share information
  341. */
  342. private function restoreShares(
  343. string $sourceUid,
  344. string $destinationUid,
  345. string $targetLocation,
  346. array $shares,
  347. OutputInterface $output,
  348. ):void {
  349. $output->writeln("Restoring shares ...");
  350. $progress = new ProgressBar($output, count($shares));
  351. $rootFolder = \OCP\Server::get(IRootFolder::class);
  352. foreach ($shares as ['share' => $share, 'suffix' => $suffix]) {
  353. try {
  354. if ($share->getShareType() === IShare::TYPE_USER &&
  355. $share->getSharedWith() === $destinationUid) {
  356. // Unmount the shares before deleting, so we don't try to get the storage later on.
  357. $shareMountPoint = $this->mountManager->find('/' . $destinationUid . '/files' . $share->getTarget());
  358. if ($shareMountPoint) {
  359. $this->mountManager->removeMount($shareMountPoint->getMountPoint());
  360. }
  361. $this->shareManager->deleteShare($share);
  362. } else {
  363. if ($share->getShareOwner() === $sourceUid) {
  364. $share->setShareOwner($destinationUid);
  365. }
  366. if ($share->getSharedBy() === $sourceUid) {
  367. $share->setSharedBy($destinationUid);
  368. }
  369. if ($share->getShareType() === IShare::TYPE_USER &&
  370. !$this->userManager->userExists($share->getSharedWith())) {
  371. // stray share with deleted user
  372. $output->writeln('<error>Share with id ' . $share->getId() . ' points at deleted user "' . $share->getSharedWith() . '", deleting</error>');
  373. $this->shareManager->deleteShare($share);
  374. continue;
  375. } else {
  376. // trigger refetching of the node so that the new owner and mountpoint are taken into account
  377. // otherwise the checks on the share update will fail due to the original node not being available in the new user scope
  378. $this->userMountCache->clear();
  379. try {
  380. // Try to get the "old" id.
  381. // Normally the ID is preserved,
  382. // but for transferes between different storages the ID might change
  383. $newNodeId = $share->getNode()->getId();
  384. } catch (\OCP\Files\NotFoundException) {
  385. // ID has changed due to transfer between different storages
  386. // Try to get the new ID from the target path and suffix of the share
  387. $node = $rootFolder->get(Filesystem::normalizePath($targetLocation . '/' . $suffix));
  388. $newNodeId = $node->getId();
  389. }
  390. $share->setNodeId($newNodeId);
  391. $this->shareManager->updateShare($share);
  392. }
  393. }
  394. } catch (\OCP\Files\NotFoundException $e) {
  395. $output->writeln('<error>Share with id ' . $share->getId() . ' points at deleted file, skipping</error>');
  396. } catch (\Throwable $e) {
  397. $output->writeln('<error>Could not restore share with id ' . $share->getId() . ':' . $e->getMessage() . ' : ' . $e->getTraceAsString() . '</error>');
  398. }
  399. $progress->advance();
  400. }
  401. $progress->finish();
  402. $output->writeln('');
  403. }
  404. private function transferIncomingShares(string $sourceUid,
  405. string $destinationUid,
  406. array $sourceShares,
  407. array $destinationShares,
  408. OutputInterface $output,
  409. string $path,
  410. string $finalTarget,
  411. bool $move): void {
  412. $output->writeln("Restoring incoming shares ...");
  413. $progress = new ProgressBar($output, count($sourceShares));
  414. $prefix = "$destinationUid/files";
  415. $finalShareTarget = '';
  416. if (str_starts_with($finalTarget, $prefix)) {
  417. $finalShareTarget = substr($finalTarget, strlen($prefix));
  418. }
  419. foreach ($sourceShares as $share) {
  420. try {
  421. // Only restore if share is in given path.
  422. $pathToCheck = '/';
  423. if (trim($path, '/') !== '') {
  424. $pathToCheck = '/' . trim($path) . '/';
  425. }
  426. if (!str_starts_with($share->getTarget(), $pathToCheck)) {
  427. continue;
  428. }
  429. $shareTarget = $share->getTarget();
  430. $shareTarget = $finalShareTarget . $shareTarget;
  431. if ($share->getShareType() === IShare::TYPE_USER &&
  432. $share->getSharedBy() === $destinationUid) {
  433. $this->shareManager->deleteShare($share);
  434. } elseif (isset($destinationShares[$share->getNodeId()])) {
  435. $destinationShare = $destinationShares[$share->getNodeId()];
  436. // Keep the share which has the most permissions and discard the other one.
  437. if ($destinationShare->getPermissions() < $share->getPermissions()) {
  438. $this->shareManager->deleteShare($destinationShare);
  439. $share->setSharedWith($destinationUid);
  440. // trigger refetching of the node so that the new owner and mountpoint are taken into account
  441. // otherwise the checks on the share update will fail due to the original node not being available in the new user scope
  442. $this->userMountCache->clear();
  443. $share->setNodeId($share->getNode()->getId());
  444. $this->shareManager->updateShare($share);
  445. // The share is already transferred.
  446. $progress->advance();
  447. if ($move) {
  448. continue;
  449. }
  450. $share->setTarget($shareTarget);
  451. $this->shareManager->moveShare($share, $destinationUid);
  452. continue;
  453. }
  454. $this->shareManager->deleteShare($share);
  455. } elseif ($share->getShareOwner() === $destinationUid) {
  456. $this->shareManager->deleteShare($share);
  457. } else {
  458. $share->setSharedWith($destinationUid);
  459. $share->setNodeId($share->getNode()->getId());
  460. $this->shareManager->updateShare($share);
  461. // trigger refetching of the node so that the new owner and mountpoint are taken into account
  462. // otherwise the checks on the share update will fail due to the original node not being available in the new user scope
  463. $this->userMountCache->clear();
  464. // The share is already transferred.
  465. $progress->advance();
  466. if ($move) {
  467. continue;
  468. }
  469. $share->setTarget($shareTarget);
  470. $this->shareManager->moveShare($share, $destinationUid);
  471. continue;
  472. }
  473. } catch (\OCP\Files\NotFoundException $e) {
  474. $output->writeln('<error>Share with id ' . $share->getId() . ' points at deleted file, skipping</error>');
  475. } catch (\Throwable $e) {
  476. $output->writeln('<error>Could not restore share with id ' . $share->getId() . ':' . $e->getTraceAsString() . '</error>');
  477. }
  478. $progress->advance();
  479. }
  480. $progress->finish();
  481. $output->writeln('');
  482. }
  483. }