ShareController.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Bjoern Schiessle <bjoern@schiessle.org>
  7. * @author Björn Schießle <bjoern@schiessle.org>
  8. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  9. * @author Daniel Calviño Sánchez <danxuliu@gmail.com>
  10. * @author Georg Ehrke <oc.list@georgehrke.com>
  11. * @author j3l11234 <297259024@qq.com>
  12. * @author Joas Schilling <coding@schilljs.com>
  13. * @author John Molakvoæ <skjnldsv@protonmail.com>
  14. * @author Jonas Sulzer <jonas@violoncello.ch>
  15. * @author Julius Härtl <jus@bitgrid.net>
  16. * @author Lukas Reschke <lukas@statuscode.ch>
  17. * @author MartB <mart.b@outlook.de>
  18. * @author Maxence Lange <maxence@pontapreta.net>
  19. * @author Michael Weimann <mail@michael-weimann.eu>
  20. * @author Morris Jobke <hey@morrisjobke.de>
  21. * @author Piotr Filiciak <piotr@filiciak.pl>
  22. * @author Robin Appelman <robin@icewind.nl>
  23. * @author Roeland Jago Douma <roeland@famdouma.nl>
  24. * @author Sascha Sambale <mastixmc@gmail.com>
  25. * @author Thomas Müller <thomas.mueller@tmit.eu>
  26. * @author Vincent Petry <vincent@nextcloud.com>
  27. * @author Kate Döen <kate.doeen@nextcloud.com>
  28. *
  29. * @license AGPL-3.0
  30. *
  31. * This code is free software: you can redistribute it and/or modify
  32. * it under the terms of the GNU Affero General Public License, version 3,
  33. * as published by the Free Software Foundation.
  34. *
  35. * This program is distributed in the hope that it will be useful,
  36. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  37. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  38. * GNU Affero General Public License for more details.
  39. *
  40. * You should have received a copy of the GNU Affero General Public License, version 3,
  41. * along with this program. If not, see <http://www.gnu.org/licenses/>
  42. *
  43. */
  44. namespace OCA\Files_Sharing\Controller;
  45. use OC\Security\CSP\ContentSecurityPolicy;
  46. use OC_Files;
  47. use OC_Util;
  48. use OCA\FederatedFileSharing\FederatedShareProvider;
  49. use OCA\Files_Sharing\Activity\Providers\Downloads;
  50. use OCA\Files_Sharing\Event\BeforeTemplateRenderedEvent;
  51. use OCA\Files_Sharing\Event\ShareLinkAccessedEvent;
  52. use OCP\Accounts\IAccountManager;
  53. use OCP\AppFramework\AuthPublicShareController;
  54. use OCP\AppFramework\Http\Attribute\OpenAPI;
  55. use OCP\AppFramework\Http\NotFoundResponse;
  56. use OCP\AppFramework\Http\TemplateResponse;
  57. use OCP\Defaults;
  58. use OCP\EventDispatcher\IEventDispatcher;
  59. use OCP\Files\Folder;
  60. use OCP\Files\IRootFolder;
  61. use OCP\Files\NotFoundException;
  62. use OCP\IConfig;
  63. use OCP\IL10N;
  64. use OCP\IPreview;
  65. use OCP\IRequest;
  66. use OCP\ISession;
  67. use OCP\IURLGenerator;
  68. use OCP\IUserManager;
  69. use OCP\Security\ISecureRandom;
  70. use OCP\Share;
  71. use OCP\Share\Exceptions\ShareNotFound;
  72. use OCP\Share\IManager as ShareManager;
  73. use OCP\Share\IPublicShareTemplateFactory;
  74. use OCP\Share\IShare;
  75. use OCP\Template;
  76. /**
  77. * @package OCA\Files_Sharing\Controllers
  78. */
  79. #[OpenAPI(scope: OpenAPI::SCOPE_IGNORE)]
  80. class ShareController extends AuthPublicShareController {
  81. protected ?Share\IShare $share = null;
  82. public const SHARE_ACCESS = 'access';
  83. public const SHARE_AUTH = 'auth';
  84. public const SHARE_DOWNLOAD = 'download';
  85. public function __construct(
  86. string $appName,
  87. IRequest $request,
  88. protected IConfig $config,
  89. IURLGenerator $urlGenerator,
  90. protected IUserManager $userManager,
  91. protected \OCP\Activity\IManager $activityManager,
  92. protected ShareManager $shareManager,
  93. ISession $session,
  94. protected IPreview $previewManager,
  95. protected IRootFolder $rootFolder,
  96. protected FederatedShareProvider $federatedShareProvider,
  97. protected IAccountManager $accountManager,
  98. protected IEventDispatcher $eventDispatcher,
  99. protected IL10N $l10n,
  100. protected ISecureRandom $secureRandom,
  101. protected Defaults $defaults,
  102. private IPublicShareTemplateFactory $publicShareTemplateFactory,
  103. ) {
  104. parent::__construct($appName, $request, $session, $urlGenerator);
  105. }
  106. /**
  107. * @PublicPage
  108. * @NoCSRFRequired
  109. *
  110. * Show the authentication page
  111. * The form has to submit to the authenticate method route
  112. */
  113. public function showAuthenticate(): TemplateResponse {
  114. $templateParameters = ['share' => $this->share];
  115. $this->eventDispatcher->dispatchTyped(new BeforeTemplateRenderedEvent($this->share, BeforeTemplateRenderedEvent::SCOPE_PUBLIC_SHARE_AUTH));
  116. $response = new TemplateResponse('core', 'publicshareauth', $templateParameters, 'guest');
  117. if ($this->share->getSendPasswordByTalk()) {
  118. $csp = new ContentSecurityPolicy();
  119. $csp->addAllowedConnectDomain('*');
  120. $csp->addAllowedMediaDomain('blob:');
  121. $response->setContentSecurityPolicy($csp);
  122. }
  123. return $response;
  124. }
  125. /**
  126. * The template to show when authentication failed
  127. */
  128. protected function showAuthFailed(): TemplateResponse {
  129. $templateParameters = ['share' => $this->share, 'wrongpw' => true];
  130. $this->eventDispatcher->dispatchTyped(new BeforeTemplateRenderedEvent($this->share, BeforeTemplateRenderedEvent::SCOPE_PUBLIC_SHARE_AUTH));
  131. $response = new TemplateResponse('core', 'publicshareauth', $templateParameters, 'guest');
  132. if ($this->share->getSendPasswordByTalk()) {
  133. $csp = new ContentSecurityPolicy();
  134. $csp->addAllowedConnectDomain('*');
  135. $csp->addAllowedMediaDomain('blob:');
  136. $response->setContentSecurityPolicy($csp);
  137. }
  138. return $response;
  139. }
  140. /**
  141. * The template to show after user identification
  142. */
  143. protected function showIdentificationResult(bool $success = false): TemplateResponse {
  144. $templateParameters = ['share' => $this->share, 'identityOk' => $success];
  145. $this->eventDispatcher->dispatchTyped(new BeforeTemplateRenderedEvent($this->share, BeforeTemplateRenderedEvent::SCOPE_PUBLIC_SHARE_AUTH));
  146. $response = new TemplateResponse('core', 'publicshareauth', $templateParameters, 'guest');
  147. if ($this->share->getSendPasswordByTalk()) {
  148. $csp = new ContentSecurityPolicy();
  149. $csp->addAllowedConnectDomain('*');
  150. $csp->addAllowedMediaDomain('blob:');
  151. $response->setContentSecurityPolicy($csp);
  152. }
  153. return $response;
  154. }
  155. /**
  156. * Validate the identity token of a public share
  157. *
  158. * @param ?string $identityToken
  159. * @return bool
  160. */
  161. protected function validateIdentity(?string $identityToken = null): bool {
  162. if ($this->share->getShareType() !== IShare::TYPE_EMAIL) {
  163. return false;
  164. }
  165. if ($identityToken === null || $this->share->getSharedWith() === null) {
  166. return false;
  167. }
  168. return $identityToken === $this->share->getSharedWith();
  169. }
  170. /**
  171. * Generates a password for the share, respecting any password policy defined
  172. */
  173. protected function generatePassword(): void {
  174. $event = new \OCP\Security\Events\GenerateSecurePasswordEvent();
  175. $this->eventDispatcher->dispatchTyped($event);
  176. $password = $event->getPassword() ?? $this->secureRandom->generate(20);
  177. $this->share->setPassword($password);
  178. $this->shareManager->updateShare($this->share);
  179. }
  180. protected function verifyPassword(string $password): bool {
  181. return $this->shareManager->checkPassword($this->share, $password);
  182. }
  183. protected function getPasswordHash(): string {
  184. return $this->share->getPassword();
  185. }
  186. public function isValidToken(): bool {
  187. try {
  188. $this->share = $this->shareManager->getShareByToken($this->getToken());
  189. } catch (ShareNotFound $e) {
  190. return false;
  191. }
  192. return true;
  193. }
  194. protected function isPasswordProtected(): bool {
  195. return $this->share->getPassword() !== null;
  196. }
  197. protected function authSucceeded() {
  198. // For share this was always set so it is still used in other apps
  199. $this->session->set('public_link_authenticated', (string)$this->share->getId());
  200. }
  201. protected function authFailed() {
  202. $this->emitAccessShareHook($this->share, 403, 'Wrong password');
  203. $this->emitShareAccessEvent($this->share, self::SHARE_AUTH, 403, 'Wrong password');
  204. }
  205. /**
  206. * throws hooks when a share is attempted to be accessed
  207. *
  208. * @param \OCP\Share\IShare|string $share the Share instance if available,
  209. * otherwise token
  210. * @param int $errorCode
  211. * @param string $errorMessage
  212. *
  213. * @throws \OCP\HintException
  214. * @throws \OC\ServerNotAvailableException
  215. *
  216. * @deprecated use OCP\Files_Sharing\Event\ShareLinkAccessedEvent
  217. */
  218. protected function emitAccessShareHook($share, int $errorCode = 200, string $errorMessage = '') {
  219. $itemType = $itemSource = $uidOwner = '';
  220. $token = $share;
  221. $exception = null;
  222. if ($share instanceof \OCP\Share\IShare) {
  223. try {
  224. $token = $share->getToken();
  225. $uidOwner = $share->getSharedBy();
  226. $itemType = $share->getNodeType();
  227. $itemSource = $share->getNodeId();
  228. } catch (\Exception $e) {
  229. // we log what we know and pass on the exception afterwards
  230. $exception = $e;
  231. }
  232. }
  233. \OC_Hook::emit(Share::class, 'share_link_access', [
  234. 'itemType' => $itemType,
  235. 'itemSource' => $itemSource,
  236. 'uidOwner' => $uidOwner,
  237. 'token' => $token,
  238. 'errorCode' => $errorCode,
  239. 'errorMessage' => $errorMessage
  240. ]);
  241. if (!is_null($exception)) {
  242. throw $exception;
  243. }
  244. }
  245. /**
  246. * Emit a ShareLinkAccessedEvent event when a share is accessed, downloaded, auth...
  247. */
  248. protected function emitShareAccessEvent(IShare $share, string $step = '', int $errorCode = 200, string $errorMessage = ''): void {
  249. if ($step !== self::SHARE_ACCESS &&
  250. $step !== self::SHARE_AUTH &&
  251. $step !== self::SHARE_DOWNLOAD) {
  252. return;
  253. }
  254. $this->eventDispatcher->dispatchTyped(new ShareLinkAccessedEvent($share, $step, $errorCode, $errorMessage));
  255. }
  256. /**
  257. * Validate the permissions of the share
  258. *
  259. * @param Share\IShare $share
  260. * @return bool
  261. */
  262. private function validateShare(\OCP\Share\IShare $share) {
  263. // If the owner is disabled no access to the link is granted
  264. $owner = $this->userManager->get($share->getShareOwner());
  265. if ($owner === null || !$owner->isEnabled()) {
  266. return false;
  267. }
  268. // If the initiator of the share is disabled no access is granted
  269. $initiator = $this->userManager->get($share->getSharedBy());
  270. if ($initiator === null || !$initiator->isEnabled()) {
  271. return false;
  272. }
  273. return $share->getNode()->isReadable() && $share->getNode()->isShareable();
  274. }
  275. /**
  276. * @PublicPage
  277. * @NoCSRFRequired
  278. *
  279. *
  280. * @param string $path
  281. * @return TemplateResponse
  282. * @throws NotFoundException
  283. * @throws \Exception
  284. */
  285. public function showShare($path = ''): TemplateResponse {
  286. \OC_User::setIncognitoMode(true);
  287. // Check whether share exists
  288. try {
  289. $share = $this->shareManager->getShareByToken($this->getToken());
  290. } catch (ShareNotFound $e) {
  291. // The share does not exists, we do not emit an ShareLinkAccessedEvent
  292. $this->emitAccessShareHook($this->getToken(), 404, 'Share not found');
  293. throw new NotFoundException();
  294. }
  295. if (!$this->validateShare($share)) {
  296. throw new NotFoundException();
  297. }
  298. $shareNode = $share->getNode();
  299. try {
  300. $templateProvider = $this->publicShareTemplateFactory->getProvider($share);
  301. $response = $templateProvider->renderPage($share, $this->getToken(), $path);
  302. } catch (NotFoundException $e) {
  303. $this->emitAccessShareHook($share, 404, 'Share not found');
  304. $this->emitShareAccessEvent($share, ShareController::SHARE_ACCESS, 404, 'Share not found');
  305. throw new NotFoundException();
  306. }
  307. // We can't get the path of a file share
  308. try {
  309. if ($shareNode instanceof \OCP\Files\File && $path !== '') {
  310. $this->emitAccessShareHook($share, 404, 'Share not found');
  311. $this->emitShareAccessEvent($share, self::SHARE_ACCESS, 404, 'Share not found');
  312. throw new NotFoundException();
  313. }
  314. } catch (\Exception $e) {
  315. $this->emitAccessShareHook($share, 404, 'Share not found');
  316. $this->emitShareAccessEvent($share, self::SHARE_ACCESS, 404, 'Share not found');
  317. throw $e;
  318. }
  319. $this->emitAccessShareHook($share);
  320. $this->emitShareAccessEvent($share, self::SHARE_ACCESS);
  321. return $response;
  322. }
  323. /**
  324. * @PublicPage
  325. * @NoCSRFRequired
  326. * @NoSameSiteCookieRequired
  327. *
  328. * @param string $token
  329. * @param string $files
  330. * @param string $path
  331. * @param string $downloadStartSecret
  332. * @return void|\OCP\AppFramework\Http\Response
  333. * @throws NotFoundException
  334. */
  335. public function downloadShare($token, $files = null, $path = '', $downloadStartSecret = '') {
  336. \OC_User::setIncognitoMode(true);
  337. $share = $this->shareManager->getShareByToken($token);
  338. if (!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) {
  339. return new \OCP\AppFramework\Http\DataResponse('Share has no read permission');
  340. }
  341. $files_list = null;
  342. if (!is_null($files)) { // download selected files
  343. $files_list = json_decode($files);
  344. // in case we get only a single file
  345. if ($files_list === null) {
  346. $files_list = [$files];
  347. }
  348. // Just in case $files is a single int like '1234'
  349. if (!is_array($files_list)) {
  350. $files_list = [$files_list];
  351. }
  352. }
  353. if (!$this->validateShare($share)) {
  354. throw new NotFoundException();
  355. }
  356. $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
  357. $originalSharePath = $userFolder->getRelativePath($share->getNode()->getPath());
  358. // Single file share
  359. if ($share->getNode() instanceof \OCP\Files\File) {
  360. // Single file download
  361. $this->singleFileDownloaded($share, $share->getNode());
  362. }
  363. // Directory share
  364. else {
  365. /** @var \OCP\Files\Folder $node */
  366. $node = $share->getNode();
  367. // Try to get the path
  368. if ($path !== '') {
  369. try {
  370. $node = $node->get($path);
  371. } catch (NotFoundException $e) {
  372. $this->emitAccessShareHook($share, 404, 'Share not found');
  373. $this->emitShareAccessEvent($share, self::SHARE_DOWNLOAD, 404, 'Share not found');
  374. return new NotFoundResponse();
  375. }
  376. }
  377. $originalSharePath = $userFolder->getRelativePath($node->getPath());
  378. if ($node instanceof \OCP\Files\File) {
  379. // Single file download
  380. $this->singleFileDownloaded($share, $share->getNode());
  381. } else {
  382. try {
  383. if (!empty($files_list)) {
  384. $this->fileListDownloaded($share, $files_list, $node);
  385. } else {
  386. // The folder is downloaded
  387. $this->singleFileDownloaded($share, $share->getNode());
  388. }
  389. } catch (NotFoundException $e) {
  390. return new NotFoundResponse();
  391. }
  392. }
  393. }
  394. /* FIXME: We should do this all nicely in OCP */
  395. OC_Util::tearDownFS();
  396. OC_Util::setupFS($share->getShareOwner());
  397. /**
  398. * this sets a cookie to be able to recognize the start of the download
  399. * the content must not be longer than 32 characters and must only contain
  400. * alphanumeric characters
  401. */
  402. if (!empty($downloadStartSecret)
  403. && !isset($downloadStartSecret[32])
  404. && preg_match('!^[a-zA-Z0-9]+$!', $downloadStartSecret) === 1) {
  405. // FIXME: set on the response once we use an actual app framework response
  406. setcookie('ocDownloadStarted', $downloadStartSecret, time() + 20, '/');
  407. }
  408. $this->emitAccessShareHook($share);
  409. $this->emitShareAccessEvent($share, self::SHARE_DOWNLOAD);
  410. $server_params = [ 'head' => $this->request->getMethod() === 'HEAD' ];
  411. /**
  412. * Http range requests support
  413. */
  414. if (isset($_SERVER['HTTP_RANGE'])) {
  415. $server_params['range'] = $this->request->getHeader('Range');
  416. }
  417. // download selected files
  418. if (!is_null($files) && $files !== '') {
  419. // FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
  420. // after dispatching the request which results in a "Cannot modify header information" notice.
  421. OC_Files::get($originalSharePath, $files_list, $server_params);
  422. exit();
  423. } else {
  424. // FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
  425. // after dispatching the request which results in a "Cannot modify header information" notice.
  426. OC_Files::get(dirname($originalSharePath), basename($originalSharePath), $server_params);
  427. exit();
  428. }
  429. }
  430. /**
  431. * create activity for every downloaded file
  432. *
  433. * @param Share\IShare $share
  434. * @param array $files_list
  435. * @param \OCP\Files\Folder $node
  436. * @throws NotFoundException when trying to download a folder or multiple files of a "hide download" share
  437. */
  438. protected function fileListDownloaded(Share\IShare $share, array $files_list, \OCP\Files\Folder $node) {
  439. if ($share->getHideDownload() && count($files_list) > 1) {
  440. throw new NotFoundException('Downloading more than 1 file');
  441. }
  442. foreach ($files_list as $file) {
  443. $subNode = $node->get($file);
  444. $this->singleFileDownloaded($share, $subNode);
  445. }
  446. }
  447. /**
  448. * create activity if a single file was downloaded from a link share
  449. *
  450. * @param Share\IShare $share
  451. * @throws NotFoundException when trying to download a folder of a "hide download" share
  452. */
  453. protected function singleFileDownloaded(Share\IShare $share, \OCP\Files\Node $node) {
  454. if ($share->getHideDownload() && $node instanceof Folder) {
  455. throw new NotFoundException('Downloading a folder');
  456. }
  457. $fileId = $node->getId();
  458. $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
  459. $userNodeList = $userFolder->getById($fileId);
  460. $userNode = $userNodeList[0];
  461. $ownerFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
  462. $userPath = $userFolder->getRelativePath($userNode->getPath());
  463. $ownerPath = $ownerFolder->getRelativePath($node->getPath());
  464. $remoteAddress = $this->request->getRemoteAddress();
  465. $dateTime = new \DateTime();
  466. $dateTime = $dateTime->format('Y-m-d H');
  467. $remoteAddressHash = md5($dateTime . '-' . $remoteAddress);
  468. $parameters = [$userPath];
  469. if ($share->getShareType() === IShare::TYPE_EMAIL) {
  470. if ($node instanceof \OCP\Files\File) {
  471. $subject = Downloads::SUBJECT_SHARED_FILE_BY_EMAIL_DOWNLOADED;
  472. } else {
  473. $subject = Downloads::SUBJECT_SHARED_FOLDER_BY_EMAIL_DOWNLOADED;
  474. }
  475. $parameters[] = $share->getSharedWith();
  476. } else {
  477. if ($node instanceof \OCP\Files\File) {
  478. $subject = Downloads::SUBJECT_PUBLIC_SHARED_FILE_DOWNLOADED;
  479. $parameters[] = $remoteAddressHash;
  480. } else {
  481. $subject = Downloads::SUBJECT_PUBLIC_SHARED_FOLDER_DOWNLOADED;
  482. $parameters[] = $remoteAddressHash;
  483. }
  484. }
  485. $this->publishActivity($subject, $parameters, $share->getSharedBy(), $fileId, $userPath);
  486. if ($share->getShareOwner() !== $share->getSharedBy()) {
  487. $parameters[0] = $ownerPath;
  488. $this->publishActivity($subject, $parameters, $share->getShareOwner(), $fileId, $ownerPath);
  489. }
  490. }
  491. /**
  492. * publish activity
  493. *
  494. * @param string $subject
  495. * @param array $parameters
  496. * @param string $affectedUser
  497. * @param int $fileId
  498. * @param string $filePath
  499. */
  500. protected function publishActivity($subject,
  501. array $parameters,
  502. $affectedUser,
  503. $fileId,
  504. $filePath) {
  505. $event = $this->activityManager->generateEvent();
  506. $event->setApp('files_sharing')
  507. ->setType('public_links')
  508. ->setSubject($subject, $parameters)
  509. ->setAffectedUser($affectedUser)
  510. ->setObject('files', $fileId, $filePath);
  511. $this->activityManager->publish($event);
  512. }
  513. }