OwnershipTransferService.php 19 KB

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