OwnershipTransferService.php 17 KB

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