File.php 27 KB

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