You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

File.php 23KB

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