File.php 23 KB

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