File.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795
  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 Christoph Wurst <christoph@winzerhof-wurst.at>
  8. * @author Daniel Calviño Sánchez <danxuliu@gmail.com>
  9. * @author Jakob Sack <mail@jakobsack.de>
  10. * @author Jan-Philipp Litza <jplitza@users.noreply.github.com>
  11. * @author Joas Schilling <coding@schilljs.com>
  12. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  13. * @author Julius Härtl <jus@bitgrid.net>
  14. * @author Lukas Reschke <lukas@statuscode.ch>
  15. * @author Morris Jobke <hey@morrisjobke.de>
  16. * @author Owen Winkler <a_github@midnightcircus.com>
  17. * @author Robin Appelman <robin@icewind.nl>
  18. * @author Roeland Jago Douma <roeland@famdouma.nl>
  19. * @author Semih Serhat Karakaya <karakayasemi@itu.edu.tr>
  20. * @author Stefan Schneider <stefan.schneider@squareweave.com.au>
  21. * @author Thomas Müller <thomas.mueller@tmit.eu>
  22. * @author Vincent Petry <vincent@nextcloud.com>
  23. *
  24. * @license AGPL-3.0
  25. *
  26. * This code is free software: you can redistribute it and/or modify
  27. * it under the terms of the GNU Affero General Public License, version 3,
  28. * as published by the Free Software Foundation.
  29. *
  30. * This program is distributed in the hope that it will be useful,
  31. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  32. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  33. * GNU Affero General Public License for more details.
  34. *
  35. * You should have received a copy of the GNU Affero General Public License, version 3,
  36. * along with this program. If not, see <http://www.gnu.org/licenses/>
  37. *
  38. */
  39. namespace OCA\DAV\Connector\Sabre;
  40. use Icewind\Streams\CallbackWrapper;
  41. use OC\AppFramework\Http\Request;
  42. use OC\Files\Filesystem;
  43. use OC\Files\Stream\HashWrapper;
  44. use OC\Files\View;
  45. use OCA\DAV\AppInfo\Application;
  46. use OCA\DAV\Connector\Sabre\Exception\BadGateway;
  47. use OCA\DAV\Connector\Sabre\Exception\EntityTooLarge;
  48. use OCA\DAV\Connector\Sabre\Exception\FileLocked;
  49. use OCA\DAV\Connector\Sabre\Exception\Forbidden as DAVForbiddenException;
  50. use OCA\DAV\Connector\Sabre\Exception\UnsupportedMediaType;
  51. use OCP\Encryption\Exceptions\GenericEncryptionException;
  52. use OCP\Files\EntityTooLargeException;
  53. use OCP\Files\FileInfo;
  54. use OCP\Files\ForbiddenException;
  55. use OCP\Files\GenericFileException;
  56. use OCP\Files\InvalidContentException;
  57. use OCP\Files\InvalidPathException;
  58. use OCP\Files\LockNotAcquiredException;
  59. use OCP\Files\NotFoundException;
  60. use OCP\Files\NotPermittedException;
  61. use OCP\Files\Storage;
  62. use OCP\Files\StorageNotAvailableException;
  63. use OCP\IL10N;
  64. use OCP\IRequest;
  65. use OCP\L10N\IFactory as IL10NFactory;
  66. use OCP\Lock\ILockingProvider;
  67. use OCP\Lock\LockedException;
  68. use OCP\Share\IManager;
  69. use Psr\Log\LoggerInterface;
  70. use Sabre\DAV\Exception;
  71. use Sabre\DAV\Exception\BadRequest;
  72. use Sabre\DAV\Exception\Forbidden;
  73. use Sabre\DAV\Exception\NotFound;
  74. use Sabre\DAV\Exception\NotImplemented;
  75. use Sabre\DAV\Exception\ServiceUnavailable;
  76. use Sabre\DAV\IFile;
  77. class File extends Node implements IFile {
  78. protected IRequest $request;
  79. protected IL10N $l10n;
  80. /**
  81. * Sets up the node, expects a full path name
  82. *
  83. * @param \OC\Files\View $view
  84. * @param \OCP\Files\FileInfo $info
  85. * @param ?\OCP\Share\IManager $shareManager
  86. * @param ?IRequest $request
  87. * @param ?IL10N $l10n
  88. */
  89. public function __construct(View $view, FileInfo $info, IManager $shareManager = null, IRequest $request = null, IL10N $l10n = null) {
  90. parent::__construct($view, $info, $shareManager);
  91. if ($l10n) {
  92. $this->l10n = $l10n;
  93. } else {
  94. // Querying IL10N directly results in a dependency loop
  95. /** @var IL10NFactory $l10nFactory */
  96. $l10nFactory = \OC::$server->get(IL10NFactory::class);
  97. $this->l10n = $l10nFactory->get(Application::APP_ID);
  98. }
  99. if (isset($request)) {
  100. $this->request = $request;
  101. } else {
  102. $this->request = \OC::$server->get(IRequest::class);
  103. }
  104. }
  105. /**
  106. * Updates the data
  107. *
  108. * The data argument is a readable stream resource.
  109. *
  110. * After a successful put operation, you may choose to return an ETag. The
  111. * etag must always be surrounded by double-quotes. These quotes must
  112. * appear in the actual string you're returning.
  113. *
  114. * Clients may use the ETag from a PUT request to later on make sure that
  115. * when they update the file, the contents haven't changed in the mean
  116. * time.
  117. *
  118. * If you don't plan to store the file byte-by-byte, and you return a
  119. * different object on a subsequent GET you are strongly recommended to not
  120. * return an ETag, and just return null.
  121. *
  122. * @param resource $data
  123. *
  124. * @throws Forbidden
  125. * @throws UnsupportedMediaType
  126. * @throws BadRequest
  127. * @throws Exception
  128. * @throws EntityTooLarge
  129. * @throws ServiceUnavailable
  130. * @throws FileLocked
  131. * @return string|null
  132. */
  133. public function put($data) {
  134. try {
  135. $exists = $this->fileView->file_exists($this->path);
  136. if ($exists && !$this->info->isUpdateable()) {
  137. throw new Forbidden();
  138. }
  139. } catch (StorageNotAvailableException $e) {
  140. throw new ServiceUnavailable($this->l10n->t('File is not updatable: %1$s', [$e->getMessage()]));
  141. }
  142. // verify path of the target
  143. $this->verifyPath();
  144. // chunked handling
  145. $chunkedHeader = $this->request->getHeader('oc-chunked');
  146. if ($chunkedHeader) {
  147. try {
  148. return $this->createFileChunked($data);
  149. } catch (\Exception $e) {
  150. $this->convertToSabreException($e);
  151. }
  152. }
  153. /** @var Storage $partStorage */
  154. [$partStorage] = $this->fileView->resolvePath($this->path);
  155. $needsPartFile = $partStorage->needsPartFile() && (strlen($this->path) > 1);
  156. $view = \OC\Files\Filesystem::getView();
  157. if ($needsPartFile) {
  158. // mark file as partial while uploading (ignored by the scanner)
  159. $partFilePath = $this->getPartFileBasePath($this->path) . '.ocTransferId' . rand() . '.part';
  160. if (!$view->isCreatable($partFilePath) && $view->isUpdatable($this->path)) {
  161. $needsPartFile = false;
  162. }
  163. }
  164. if (!$needsPartFile) {
  165. // upload file directly as the final path
  166. $partFilePath = $this->path;
  167. if ($view && !$this->emitPreHooks($exists)) {
  168. throw new Exception($this->l10n->t('Could not write to final file, canceled by hook'));
  169. }
  170. }
  171. // the part file and target file might be on a different storage in case of a single file storage (e.g. single file share)
  172. /** @var \OC\Files\Storage\Storage $partStorage */
  173. [$partStorage, $internalPartPath] = $this->fileView->resolvePath($partFilePath);
  174. /** @var \OC\Files\Storage\Storage $storage */
  175. [$storage, $internalPath] = $this->fileView->resolvePath($this->path);
  176. try {
  177. if (!$needsPartFile) {
  178. try {
  179. $this->changeLock(ILockingProvider::LOCK_EXCLUSIVE);
  180. } catch (LockedException $e) {
  181. // during very large uploads, the shared lock we got at the start might have been expired
  182. // meaning that the above lock can fail not just only because somebody else got a shared lock
  183. // or because there is no existing shared lock to make exclusive
  184. //
  185. // Thus we try to get a new exclusive lock, if the original lock failed because of a different shared
  186. // lock this will still fail, if our original shared lock expired the new lock will be successful and
  187. // the entire operation will be safe
  188. try {
  189. $this->acquireLock(ILockingProvider::LOCK_EXCLUSIVE);
  190. } catch (LockedException $ex) {
  191. throw new FileLocked($e->getMessage(), $e->getCode(), $e);
  192. }
  193. }
  194. }
  195. if (!is_resource($data)) {
  196. $tmpData = fopen('php://temp', 'r+');
  197. if ($data !== null) {
  198. fwrite($tmpData, $data);
  199. rewind($tmpData);
  200. }
  201. $data = $tmpData;
  202. }
  203. if ($this->request->getHeader('X-HASH') !== '') {
  204. $hash = $this->request->getHeader('X-HASH');
  205. if ($hash === 'all' || $hash === 'md5') {
  206. $data = HashWrapper::wrap($data, 'md5', function ($hash) {
  207. $this->header('X-Hash-MD5: ' . $hash);
  208. });
  209. }
  210. if ($hash === 'all' || $hash === 'sha1') {
  211. $data = HashWrapper::wrap($data, 'sha1', function ($hash) {
  212. $this->header('X-Hash-SHA1: ' . $hash);
  213. });
  214. }
  215. if ($hash === 'all' || $hash === 'sha256') {
  216. $data = HashWrapper::wrap($data, 'sha256', function ($hash) {
  217. $this->header('X-Hash-SHA256: ' . $hash);
  218. });
  219. }
  220. }
  221. if ($partStorage->instanceOfStorage(Storage\IWriteStreamStorage::class)) {
  222. $isEOF = false;
  223. $wrappedData = CallbackWrapper::wrap($data, null, null, null, null, function ($stream) use (&$isEOF) {
  224. $isEOF = feof($stream);
  225. });
  226. $result = true;
  227. $count = -1;
  228. try {
  229. $count = $partStorage->writeStream($internalPartPath, $wrappedData);
  230. } catch (GenericFileException $e) {
  231. $result = false;
  232. } catch (BadGateway $e) {
  233. throw $e;
  234. }
  235. if ($result === false) {
  236. $result = $isEOF;
  237. if (is_resource($wrappedData)) {
  238. $result = feof($wrappedData);
  239. }
  240. }
  241. } else {
  242. $target = $partStorage->fopen($internalPartPath, 'wb');
  243. if ($target === false) {
  244. \OC::$server->get(LoggerInterface::class)->error('\OC\Files\Filesystem::fopen() failed', ['app' => 'webdav']);
  245. // because we have no clue about the cause we can only throw back a 500/Internal Server Error
  246. throw new Exception($this->l10n->t('Could not write file contents'));
  247. }
  248. [$count, $result] = \OC_Helper::streamCopy($data, $target);
  249. fclose($target);
  250. }
  251. if ($result === false) {
  252. $expected = -1;
  253. $lengthHeader = $this->request->getHeader('content-length');
  254. if ($lengthHeader) {
  255. $expected = (int)$lengthHeader;
  256. }
  257. if ($expected !== 0) {
  258. throw new Exception(
  259. $this->l10n->t(
  260. 'Error while copying file to target location (copied: %1$s, expected filesize: %2$s)',
  261. [
  262. $this->l10n->n('%n byte', '%n bytes', $count),
  263. $this->l10n->n('%n byte', '%n bytes', $expected),
  264. ],
  265. )
  266. );
  267. }
  268. }
  269. // if content length is sent by client:
  270. // double check if the file was fully received
  271. // compare expected and actual size
  272. $lengthHeader = $this->request->getHeader('content-length');
  273. if ($lengthHeader && $this->request->getMethod() === 'PUT') {
  274. $expected = (int)$lengthHeader;
  275. if ($count !== $expected) {
  276. throw new BadRequest(
  277. $this->l10n->t(
  278. 'Expected filesize of %1$s but read (from Nextcloud client) and wrote (to Nextcloud storage) %2$s. Could either be a network problem on the sending side or a problem writing to the storage on the server side.',
  279. [
  280. $this->l10n->n('%n byte', '%n bytes', $expected),
  281. $this->l10n->n('%n byte', '%n bytes', $count),
  282. ],
  283. )
  284. );
  285. }
  286. }
  287. } catch (\Exception $e) {
  288. if ($e instanceof LockedException) {
  289. \OC::$server->get(LoggerInterface::class)->debug($e->getMessage(), ['exception' => $e]);
  290. } else {
  291. \OC::$server->get(LoggerInterface::class)->error($e->getMessage(), ['exception' => $e]);
  292. }
  293. if ($needsPartFile) {
  294. $partStorage->unlink($internalPartPath);
  295. }
  296. $this->convertToSabreException($e);
  297. }
  298. try {
  299. if ($needsPartFile) {
  300. if ($view && !$this->emitPreHooks($exists)) {
  301. $partStorage->unlink($internalPartPath);
  302. throw new Exception($this->l10n->t('Could not rename part file to final file, canceled by hook'));
  303. }
  304. try {
  305. $this->changeLock(ILockingProvider::LOCK_EXCLUSIVE);
  306. } catch (LockedException $e) {
  307. // during very large uploads, the shared lock we got at the start might have been expired
  308. // meaning that the above lock can fail not just only because somebody else got a shared lock
  309. // or because there is no existing shared lock to make exclusive
  310. //
  311. // Thus we try to get a new exclusive lock, if the original lock failed because of a different shared
  312. // lock this will still fail, if our original shared lock expired the new lock will be successful and
  313. // the entire operation will be safe
  314. try {
  315. $this->acquireLock(ILockingProvider::LOCK_EXCLUSIVE);
  316. } catch (LockedException $ex) {
  317. if ($needsPartFile) {
  318. $partStorage->unlink($internalPartPath);
  319. }
  320. throw new FileLocked($e->getMessage(), $e->getCode(), $e);
  321. }
  322. }
  323. // rename to correct path
  324. try {
  325. $renameOkay = $storage->moveFromStorage($partStorage, $internalPartPath, $internalPath);
  326. $fileExists = $storage->file_exists($internalPath);
  327. if ($renameOkay === false || $fileExists === false) {
  328. \OC::$server->get(LoggerInterface::class)->error('renaming part file to final file failed $renameOkay: ' . ($renameOkay ? 'true' : 'false') . ', $fileExists: ' . ($fileExists ? 'true' : 'false') . ')', ['app' => 'webdav']);
  329. throw new Exception($this->l10n->t('Could not rename part file to final file'));
  330. }
  331. } catch (ForbiddenException $ex) {
  332. if (!$ex->getRetry()) {
  333. $partStorage->unlink($internalPartPath);
  334. }
  335. throw new DAVForbiddenException($ex->getMessage(), $ex->getRetry());
  336. } catch (\Exception $e) {
  337. $partStorage->unlink($internalPartPath);
  338. $this->convertToSabreException($e);
  339. }
  340. }
  341. // since we skipped the view we need to scan and emit the hooks ourselves
  342. $storage->getUpdater()->update($internalPath);
  343. try {
  344. $this->changeLock(ILockingProvider::LOCK_SHARED);
  345. } catch (LockedException $e) {
  346. throw new FileLocked($e->getMessage(), $e->getCode(), $e);
  347. }
  348. // allow sync clients to send the mtime along in a header
  349. $mtimeHeader = $this->request->getHeader('x-oc-mtime');
  350. if ($mtimeHeader !== '') {
  351. $mtime = $this->sanitizeMtime($mtimeHeader);
  352. if ($this->fileView->touch($this->path, $mtime)) {
  353. $this->header('X-OC-MTime: accepted');
  354. }
  355. }
  356. $fileInfoUpdate = [
  357. 'upload_time' => time()
  358. ];
  359. // allow sync clients to send the creation time along in a header
  360. $ctimeHeader = $this->request->getHeader('x-oc-ctime');
  361. if ($ctimeHeader) {
  362. $ctime = $this->sanitizeMtime($ctimeHeader);
  363. $fileInfoUpdate['creation_time'] = $ctime;
  364. $this->header('X-OC-CTime: accepted');
  365. }
  366. $this->fileView->putFileInfo($this->path, $fileInfoUpdate);
  367. if ($view) {
  368. $this->emitPostHooks($exists);
  369. }
  370. $this->refreshInfo();
  371. $checksumHeader = $this->request->getHeader('oc-checksum');
  372. if ($checksumHeader) {
  373. $checksum = trim($checksumHeader);
  374. $this->setChecksum($checksum);
  375. } elseif ($this->getChecksum() !== null && $this->getChecksum() !== '') {
  376. $this->setChecksum('');
  377. }
  378. } catch (StorageNotAvailableException $e) {
  379. throw new ServiceUnavailable($this->l10n->t('Failed to check file size: %1$s', [$e->getMessage()]), 0, $e);
  380. }
  381. return '"' . $this->info->getEtag() . '"';
  382. }
  383. private function getPartFileBasePath($path) {
  384. $partFileInStorage = \OC::$server->getConfig()->getSystemValue('part_file_in_storage', true);
  385. if ($partFileInStorage) {
  386. return $path;
  387. } else {
  388. return md5($path); // will place it in the root of the view with a unique name
  389. }
  390. }
  391. private function emitPreHooks(bool $exists, ?string $path = null): bool {
  392. if (is_null($path)) {
  393. $path = $this->path;
  394. }
  395. $hookPath = Filesystem::getView()->getRelativePath($this->fileView->getAbsolutePath($path));
  396. if ($hookPath === null) {
  397. // We only trigger hooks from inside default view
  398. return true;
  399. }
  400. $run = true;
  401. if (!$exists) {
  402. \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_create, [
  403. \OC\Files\Filesystem::signal_param_path => $hookPath,
  404. \OC\Files\Filesystem::signal_param_run => &$run,
  405. ]);
  406. } else {
  407. \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_update, [
  408. \OC\Files\Filesystem::signal_param_path => $hookPath,
  409. \OC\Files\Filesystem::signal_param_run => &$run,
  410. ]);
  411. }
  412. \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_write, [
  413. \OC\Files\Filesystem::signal_param_path => $hookPath,
  414. \OC\Files\Filesystem::signal_param_run => &$run,
  415. ]);
  416. return $run;
  417. }
  418. private function emitPostHooks(bool $exists, ?string $path = null): void {
  419. if (is_null($path)) {
  420. $path = $this->path;
  421. }
  422. $hookPath = Filesystem::getView()->getRelativePath($this->fileView->getAbsolutePath($path));
  423. if ($hookPath === null) {
  424. // We only trigger hooks from inside default view
  425. return;
  426. }
  427. if (!$exists) {
  428. \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_post_create, [
  429. \OC\Files\Filesystem::signal_param_path => $hookPath
  430. ]);
  431. } else {
  432. \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_post_update, [
  433. \OC\Files\Filesystem::signal_param_path => $hookPath
  434. ]);
  435. }
  436. \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_post_write, [
  437. \OC\Files\Filesystem::signal_param_path => $hookPath
  438. ]);
  439. }
  440. /**
  441. * Returns the data
  442. *
  443. * @return resource
  444. * @throws Forbidden
  445. * @throws ServiceUnavailable
  446. */
  447. public function get() {
  448. //throw exception if encryption is disabled but files are still encrypted
  449. try {
  450. if (!$this->info->isReadable()) {
  451. // do a if the file did not exist
  452. throw new NotFound();
  453. }
  454. try {
  455. $res = $this->fileView->fopen(ltrim($this->path, '/'), 'rb');
  456. } catch (\Exception $e) {
  457. $this->convertToSabreException($e);
  458. }
  459. if ($res === false) {
  460. throw new ServiceUnavailable($this->l10n->t('Could not open file'));
  461. }
  462. // comparing current file size with the one in DB
  463. // if different, fix DB and refresh cache.
  464. if ($this->getSize() !== $this->fileView->filesize($this->getPath())) {
  465. $logger = \OC::$server->get(LoggerInterface::class);
  466. $logger->warning('fixing cached size of file id=' . $this->getId());
  467. $this->getFileInfo()->getStorage()->getUpdater()->update($this->getFileInfo()->getInternalPath());
  468. $this->refreshInfo();
  469. }
  470. return $res;
  471. } catch (GenericEncryptionException $e) {
  472. // returning 503 will allow retry of the operation at a later point in time
  473. throw new ServiceUnavailable($this->l10n->t('Encryption not ready: %1$s', [$e->getMessage()]));
  474. } catch (StorageNotAvailableException $e) {
  475. throw new ServiceUnavailable($this->l10n->t('Failed to open file: %1$s', [$e->getMessage()]));
  476. } catch (ForbiddenException $ex) {
  477. throw new DAVForbiddenException($ex->getMessage(), $ex->getRetry());
  478. } catch (LockedException $e) {
  479. throw new FileLocked($e->getMessage(), $e->getCode(), $e);
  480. }
  481. }
  482. /**
  483. * Delete the current file
  484. *
  485. * @throws Forbidden
  486. * @throws ServiceUnavailable
  487. */
  488. public function delete() {
  489. if (!$this->info->isDeletable()) {
  490. throw new Forbidden();
  491. }
  492. try {
  493. if (!$this->fileView->unlink($this->path)) {
  494. // assume it wasn't possible to delete due to permissions
  495. throw new Forbidden();
  496. }
  497. } catch (StorageNotAvailableException $e) {
  498. throw new ServiceUnavailable($this->l10n->t('Failed to unlink: %1$s', [$e->getMessage()]));
  499. } catch (ForbiddenException $ex) {
  500. throw new DAVForbiddenException($ex->getMessage(), $ex->getRetry());
  501. } catch (LockedException $e) {
  502. throw new FileLocked($e->getMessage(), $e->getCode(), $e);
  503. }
  504. }
  505. /**
  506. * Returns the mime-type for a file
  507. *
  508. * If null is returned, we'll assume application/octet-stream
  509. *
  510. * @return string
  511. */
  512. public function getContentType() {
  513. $mimeType = $this->info->getMimetype();
  514. // PROPFIND needs to return the correct mime type, for consistency with the web UI
  515. if ($this->request->getMethod() === 'PROPFIND') {
  516. return $mimeType;
  517. }
  518. return \OC::$server->getMimeTypeDetector()->getSecureMimeType($mimeType);
  519. }
  520. /**
  521. * @return array|bool
  522. */
  523. public function getDirectDownload() {
  524. if (\OCP\Server::get(\OCP\App\IAppManager::class)->isEnabledForUser('encryption')) {
  525. return [];
  526. }
  527. /** @var \OCP\Files\Storage $storage */
  528. [$storage, $internalPath] = $this->fileView->resolvePath($this->path);
  529. if (is_null($storage)) {
  530. return [];
  531. }
  532. return $storage->getDirectDownload($internalPath);
  533. }
  534. /**
  535. * @param resource $data
  536. * @return null|string
  537. * @throws Exception
  538. * @throws BadRequest
  539. * @throws NotImplemented
  540. * @throws ServiceUnavailable
  541. */
  542. private function createFileChunked($data) {
  543. [$path, $name] = \Sabre\Uri\split($this->path);
  544. $info = \OC_FileChunking::decodeName($name);
  545. if (empty($info)) {
  546. throw new NotImplemented($this->l10n->t('Invalid chunk name'));
  547. }
  548. $chunk_handler = new \OC_FileChunking($info);
  549. $bytesWritten = $chunk_handler->store($info['index'], $data);
  550. //detect aborted upload
  551. if ($this->request->getMethod() === 'PUT') {
  552. $lengthHeader = $this->request->getHeader('content-length');
  553. if ($lengthHeader) {
  554. $expected = (int)$lengthHeader;
  555. if ($bytesWritten !== $expected) {
  556. $chunk_handler->remove($info['index']);
  557. throw new BadRequest(
  558. $this->l10n->t(
  559. 'Expected filesize of %1$s but read (from Nextcloud client) and wrote (to Nextcloud storage) %2$s. Could either be a network problem on the sending side or a problem writing to the storage on the server side.',
  560. [
  561. $this->l10n->n('%n byte', '%n bytes', $expected),
  562. $this->l10n->n('%n byte', '%n bytes', $bytesWritten),
  563. ],
  564. )
  565. );
  566. }
  567. }
  568. }
  569. if ($chunk_handler->isComplete()) {
  570. /** @var Storage $storage */
  571. [$storage,] = $this->fileView->resolvePath($path);
  572. $needsPartFile = $storage->needsPartFile();
  573. $partFile = null;
  574. $targetPath = $path . '/' . $info['name'];
  575. /** @var \OC\Files\Storage\Storage $targetStorage */
  576. [$targetStorage, $targetInternalPath] = $this->fileView->resolvePath($targetPath);
  577. $exists = $this->fileView->file_exists($targetPath);
  578. try {
  579. $this->fileView->lockFile($targetPath, ILockingProvider::LOCK_SHARED);
  580. $this->emitPreHooks($exists, $targetPath);
  581. $this->fileView->changeLock($targetPath, ILockingProvider::LOCK_EXCLUSIVE);
  582. /** @var \OC\Files\Storage\Storage $targetStorage */
  583. [$targetStorage, $targetInternalPath] = $this->fileView->resolvePath($targetPath);
  584. if ($needsPartFile) {
  585. // we first assembly the target file as a part file
  586. $partFile = $this->getPartFileBasePath($path . '/' . $info['name']) . '.ocTransferId' . $info['transferid'] . '.part';
  587. /** @var \OC\Files\Storage\Storage $targetStorage */
  588. [$partStorage, $partInternalPath] = $this->fileView->resolvePath($partFile);
  589. $chunk_handler->file_assemble($partStorage, $partInternalPath);
  590. // here is the final atomic rename
  591. $renameOkay = $targetStorage->moveFromStorage($partStorage, $partInternalPath, $targetInternalPath);
  592. $fileExists = $targetStorage->file_exists($targetInternalPath);
  593. if ($renameOkay === false || $fileExists === false) {
  594. \OC::$server->get(LoggerInterface::class)->error('\OC\Files\Filesystem::rename() failed', ['app' => 'webdav']);
  595. // only delete if an error occurred and the target file was already created
  596. if ($fileExists) {
  597. // set to null to avoid double-deletion when handling exception
  598. // stray part file
  599. $partFile = null;
  600. $targetStorage->unlink($targetInternalPath);
  601. }
  602. $this->fileView->changeLock($targetPath, ILockingProvider::LOCK_SHARED);
  603. throw new Exception($this->l10n->t('Could not rename part file assembled from chunks'));
  604. }
  605. } else {
  606. // assemble directly into the final file
  607. $chunk_handler->file_assemble($targetStorage, $targetInternalPath);
  608. }
  609. // allow sync clients to send the mtime along in a header
  610. $mtimeHeader = $this->request->getHeader('x-oc-mtime');
  611. if ($mtimeHeader !== '') {
  612. $mtime = $this->sanitizeMtime($mtimeHeader);
  613. if ($targetStorage->touch($targetInternalPath, $mtime)) {
  614. $this->header('X-OC-MTime: accepted');
  615. }
  616. }
  617. // since we skipped the view we need to scan and emit the hooks ourselves
  618. $targetStorage->getUpdater()->update($targetInternalPath);
  619. $this->fileView->changeLock($targetPath, ILockingProvider::LOCK_SHARED);
  620. $this->emitPostHooks($exists, $targetPath);
  621. // FIXME: should call refreshInfo but can't because $this->path is not the of the final file
  622. $info = $this->fileView->getFileInfo($targetPath);
  623. $checksumHeader = $this->request->getHeader('oc-checksum');
  624. if ($checksumHeader) {
  625. $checksum = trim($checksumHeader);
  626. $this->fileView->putFileInfo($targetPath, ['checksum' => $checksum]);
  627. } elseif ($info->getChecksum() !== null && $info->getChecksum() !== '') {
  628. $this->fileView->putFileInfo($this->path, ['checksum' => '']);
  629. }
  630. $this->fileView->unlockFile($targetPath, ILockingProvider::LOCK_SHARED);
  631. return $info->getEtag();
  632. } catch (\Exception $e) {
  633. if ($partFile !== null) {
  634. $targetStorage->unlink($targetInternalPath);
  635. }
  636. $this->convertToSabreException($e);
  637. }
  638. }
  639. return null;
  640. }
  641. /**
  642. * Convert the given exception to a SabreException instance
  643. *
  644. * @param \Exception $e
  645. *
  646. * @throws \Sabre\DAV\Exception
  647. */
  648. private function convertToSabreException(\Exception $e) {
  649. if ($e instanceof \Sabre\DAV\Exception) {
  650. throw $e;
  651. }
  652. if ($e instanceof NotPermittedException) {
  653. // a more general case - due to whatever reason the content could not be written
  654. throw new Forbidden($e->getMessage(), 0, $e);
  655. }
  656. if ($e instanceof ForbiddenException) {
  657. // the path for the file was forbidden
  658. throw new DAVForbiddenException($e->getMessage(), $e->getRetry(), $e);
  659. }
  660. if ($e instanceof EntityTooLargeException) {
  661. // the file is too big to be stored
  662. throw new EntityTooLarge($e->getMessage(), 0, $e);
  663. }
  664. if ($e instanceof InvalidContentException) {
  665. // the file content is not permitted
  666. throw new UnsupportedMediaType($e->getMessage(), 0, $e);
  667. }
  668. if ($e instanceof InvalidPathException) {
  669. // the path for the file was not valid
  670. // TODO: find proper http status code for this case
  671. throw new Forbidden($e->getMessage(), 0, $e);
  672. }
  673. if ($e instanceof LockedException || $e instanceof LockNotAcquiredException) {
  674. // the file is currently being written to by another process
  675. throw new FileLocked($e->getMessage(), $e->getCode(), $e);
  676. }
  677. if ($e instanceof GenericEncryptionException) {
  678. // returning 503 will allow retry of the operation at a later point in time
  679. throw new ServiceUnavailable($this->l10n->t('Encryption not ready: %1$s', [$e->getMessage()]), 0, $e);
  680. }
  681. if ($e instanceof StorageNotAvailableException) {
  682. throw new ServiceUnavailable($this->l10n->t('Failed to write file contents: %1$s', [$e->getMessage()]), 0, $e);
  683. }
  684. if ($e instanceof NotFoundException) {
  685. throw new NotFound($this->l10n->t('File not found: %1$s', [$e->getMessage()]), 0, $e);
  686. }
  687. throw new \Sabre\DAV\Exception($e->getMessage(), 0, $e);
  688. }
  689. /**
  690. * Get the checksum for this file
  691. *
  692. * @return string|null
  693. */
  694. public function getChecksum() {
  695. return $this->info->getChecksum();
  696. }
  697. public function setChecksum(string $checksum) {
  698. $this->fileView->putFileInfo($this->path, ['checksum' => $checksum]);
  699. $this->refreshInfo();
  700. }
  701. protected function header($string) {
  702. if (!\OC::$CLI) {
  703. \header($string);
  704. }
  705. }
  706. public function hash(string $type) {
  707. return $this->fileView->hash($type, $this->path);
  708. }
  709. public function getNode(): \OCP\Files\File {
  710. return $this->node;
  711. }
  712. }