file.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. <?php
  2. /**
  3. * @author Bart Visscher <bartv@thisnet.nl>
  4. * @author Björn Schießle <schiessle@owncloud.com>
  5. * @author Jakob Sack <mail@jakobsack.de>
  6. * @author Joas Schilling <nickvergessen@owncloud.com>
  7. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  8. * @author Lukas Reschke <lukas@owncloud.com>
  9. * @author Morris Jobke <hey@morrisjobke.de>
  10. * @author Owen Winkler <a_github@midnightcircus.com>
  11. * @author Robin Appelman <icewind@owncloud.com>
  12. * @author Roeland Jago Douma <rullzer@owncloud.com>
  13. * @author Scrutinizer Auto-Fixer <auto-fixer@scrutinizer-ci.com>
  14. * @author Thomas Müller <thomas.mueller@tmit.eu>
  15. * @author Vincent Petry <pvince81@owncloud.com>
  16. *
  17. * @copyright Copyright (c) 2016, ownCloud, Inc.
  18. * @license AGPL-3.0
  19. *
  20. * This code is free software: you can redistribute it and/or modify
  21. * it under the terms of the GNU Affero General Public License, version 3,
  22. * as published by the Free Software Foundation.
  23. *
  24. * This program is distributed in the hope that it will be useful,
  25. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  26. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  27. * GNU Affero General Public License for more details.
  28. *
  29. * You should have received a copy of the GNU Affero General Public License, version 3,
  30. * along with this program. If not, see <http://www.gnu.org/licenses/>
  31. *
  32. */
  33. namespace OCA\DAV\Connector\Sabre;
  34. use OC\Files\Filesystem;
  35. use OCA\DAV\Connector\Sabre\Exception\EntityTooLarge;
  36. use OCA\DAV\Connector\Sabre\Exception\FileLocked;
  37. use OCA\DAV\Connector\Sabre\Exception\Forbidden as DAVForbiddenException;
  38. use OCA\DAV\Connector\Sabre\Exception\UnsupportedMediaType;
  39. use OCP\Encryption\Exceptions\GenericEncryptionException;
  40. use OCP\Files\EntityTooLargeException;
  41. use OCP\Files\ForbiddenException;
  42. use OCP\Files\InvalidContentException;
  43. use OCP\Files\InvalidPathException;
  44. use OCP\Files\LockNotAcquiredException;
  45. use OCP\Files\NotPermittedException;
  46. use OCP\Files\StorageNotAvailableException;
  47. use OCP\Lock\ILockingProvider;
  48. use OCP\Lock\LockedException;
  49. use Sabre\DAV\Exception;
  50. use Sabre\DAV\Exception\BadRequest;
  51. use Sabre\DAV\Exception\Forbidden;
  52. use Sabre\DAV\Exception\NotImplemented;
  53. use Sabre\DAV\Exception\ServiceUnavailable;
  54. use Sabre\DAV\IFile;
  55. class File extends Node implements IFile {
  56. /**
  57. * Updates the data
  58. *
  59. * The data argument is a readable stream resource.
  60. *
  61. * After a successful put operation, you may choose to return an ETag. The
  62. * etag must always be surrounded by double-quotes. These quotes must
  63. * appear in the actual string you're returning.
  64. *
  65. * Clients may use the ETag from a PUT request to later on make sure that
  66. * when they update the file, the contents haven't changed in the mean
  67. * time.
  68. *
  69. * If you don't plan to store the file byte-by-byte, and you return a
  70. * different object on a subsequent GET you are strongly recommended to not
  71. * return an ETag, and just return null.
  72. *
  73. * @param resource $data
  74. *
  75. * @throws Forbidden
  76. * @throws UnsupportedMediaType
  77. * @throws BadRequest
  78. * @throws Exception
  79. * @throws EntityTooLarge
  80. * @throws ServiceUnavailable
  81. * @throws FileLocked
  82. * @return string|null
  83. */
  84. public function put($data) {
  85. try {
  86. $exists = $this->fileView->file_exists($this->path);
  87. if ($this->info && $exists && !$this->info->isUpdateable()) {
  88. throw new Forbidden();
  89. }
  90. } catch (StorageNotAvailableException $e) {
  91. throw new ServiceUnavailable("File is not updatable: " . $e->getMessage());
  92. }
  93. // verify path of the target
  94. $this->verifyPath();
  95. // chunked handling
  96. if (isset($_SERVER['HTTP_OC_CHUNKED'])) {
  97. try {
  98. return $this->createFileChunked($data);
  99. } catch (\Exception $e) {
  100. $this->convertToSabreException($e);
  101. }
  102. }
  103. list($partStorage) = $this->fileView->resolvePath($this->path);
  104. $needsPartFile = $this->needsPartFile($partStorage) && (strlen($this->path) > 1);
  105. if ($needsPartFile) {
  106. // mark file as partial while uploading (ignored by the scanner)
  107. $partFilePath = $this->path . '.ocTransferId' . rand() . '.part';
  108. } else {
  109. // upload file directly as the final path
  110. $partFilePath = $this->path;
  111. }
  112. // the part file and target file might be on a different storage in case of a single file storage (e.g. single file share)
  113. /** @var \OC\Files\Storage\Storage $partStorage */
  114. list($partStorage, $internalPartPath) = $this->fileView->resolvePath($partFilePath);
  115. /** @var \OC\Files\Storage\Storage $storage */
  116. list($storage, $internalPath) = $this->fileView->resolvePath($this->path);
  117. try {
  118. $target = $partStorage->fopen($internalPartPath, 'wb');
  119. if ($target === false) {
  120. \OCP\Util::writeLog('webdav', '\OC\Files\Filesystem::fopen() failed', \OCP\Util::ERROR);
  121. // because we have no clue about the cause we can only throw back a 500/Internal Server Error
  122. throw new Exception('Could not write file contents');
  123. }
  124. list($count, $result) = \OC_Helper::streamCopy($data, $target);
  125. fclose($target);
  126. if($result === false) {
  127. $expected = -1;
  128. if (isset($_SERVER['CONTENT_LENGTH'])) {
  129. $expected = $_SERVER['CONTENT_LENGTH'];
  130. }
  131. throw new Exception('Error while copying file to target location (copied bytes: ' . $count . ', expected filesize: '. $expected .' )');
  132. }
  133. // if content length is sent by client:
  134. // double check if the file was fully received
  135. // compare expected and actual size
  136. if (isset($_SERVER['CONTENT_LENGTH']) && $_SERVER['REQUEST_METHOD'] !== 'LOCK') {
  137. $expected = $_SERVER['CONTENT_LENGTH'];
  138. if ($count != $expected) {
  139. throw new BadRequest('expected filesize ' . $expected . ' got ' . $count);
  140. }
  141. }
  142. } catch (\Exception $e) {
  143. if ($needsPartFile) {
  144. $partStorage->unlink($internalPartPath);
  145. }
  146. $this->convertToSabreException($e);
  147. }
  148. try {
  149. $view = \OC\Files\Filesystem::getView();
  150. if ($view) {
  151. $run = $this->emitPreHooks($exists);
  152. } else {
  153. $run = true;
  154. }
  155. try {
  156. $this->changeLock(ILockingProvider::LOCK_EXCLUSIVE);
  157. } catch (LockedException $e) {
  158. if ($needsPartFile) {
  159. $partStorage->unlink($internalPartPath);
  160. }
  161. throw new FileLocked($e->getMessage(), $e->getCode(), $e);
  162. }
  163. if ($needsPartFile) {
  164. // rename to correct path
  165. try {
  166. if ($run) {
  167. $renameOkay = $storage->moveFromStorage($partStorage, $internalPartPath, $internalPath);
  168. $fileExists = $storage->file_exists($internalPath);
  169. }
  170. if (!$run || $renameOkay === false || $fileExists === false) {
  171. \OCP\Util::writeLog('webdav', 'renaming part file to final file failed', \OCP\Util::ERROR);
  172. throw new Exception('Could not rename part file to final file');
  173. }
  174. } catch (ForbiddenException $ex) {
  175. throw new DAVForbiddenException($ex->getMessage(), $ex->getRetry());
  176. } catch (\Exception $e) {
  177. $partStorage->unlink($internalPartPath);
  178. $this->convertToSabreException($e);
  179. }
  180. }
  181. // since we skipped the view we need to scan and emit the hooks ourselves
  182. $storage->getUpdater()->update($internalPath);
  183. try {
  184. $this->changeLock(ILockingProvider::LOCK_SHARED);
  185. } catch (LockedException $e) {
  186. throw new FileLocked($e->getMessage(), $e->getCode(), $e);
  187. }
  188. if ($view) {
  189. $this->emitPostHooks($exists);
  190. }
  191. // allow sync clients to send the mtime along in a header
  192. $request = \OC::$server->getRequest();
  193. if (isset($request->server['HTTP_X_OC_MTIME'])) {
  194. if ($this->fileView->touch($this->path, $request->server['HTTP_X_OC_MTIME'])) {
  195. header('X-OC-MTime: accepted');
  196. }
  197. }
  198. if (isset($request->server['HTTP_OC_CHECKSUM'])) {
  199. $checksum = trim($request->server['HTTP_OC_CHECKSUM']);
  200. $this->fileView->putFileInfo($this->path, ['checksum' => $checksum]);
  201. }
  202. $this->refreshInfo();
  203. } catch (StorageNotAvailableException $e) {
  204. throw new ServiceUnavailable("Failed to check file size: " . $e->getMessage());
  205. }
  206. return '"' . $this->info->getEtag() . '"';
  207. }
  208. /**
  209. * @param string $path
  210. */
  211. private function emitPreHooks($exists, $path = null) {
  212. if (is_null($path)) {
  213. $path = $this->path;
  214. }
  215. $hookPath = Filesystem::getView()->getRelativePath($this->fileView->getAbsolutePath($path));
  216. $run = true;
  217. if (!$exists) {
  218. \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_create, array(
  219. \OC\Files\Filesystem::signal_param_path => $hookPath,
  220. \OC\Files\Filesystem::signal_param_run => &$run,
  221. ));
  222. } else {
  223. \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_update, array(
  224. \OC\Files\Filesystem::signal_param_path => $hookPath,
  225. \OC\Files\Filesystem::signal_param_run => &$run,
  226. ));
  227. }
  228. \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_write, array(
  229. \OC\Files\Filesystem::signal_param_path => $hookPath,
  230. \OC\Files\Filesystem::signal_param_run => &$run,
  231. ));
  232. return $run;
  233. }
  234. /**
  235. * @param string $path
  236. */
  237. private function emitPostHooks($exists, $path = null) {
  238. if (is_null($path)) {
  239. $path = $this->path;
  240. }
  241. $hookPath = Filesystem::getView()->getRelativePath($this->fileView->getAbsolutePath($path));
  242. if (!$exists) {
  243. \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_post_create, array(
  244. \OC\Files\Filesystem::signal_param_path => $hookPath
  245. ));
  246. } else {
  247. \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_post_update, array(
  248. \OC\Files\Filesystem::signal_param_path => $hookPath
  249. ));
  250. }
  251. \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_post_write, array(
  252. \OC\Files\Filesystem::signal_param_path => $hookPath
  253. ));
  254. }
  255. /**
  256. * Returns the data
  257. *
  258. * @return resource
  259. * @throws Forbidden
  260. * @throws ServiceUnavailable
  261. */
  262. public function get() {
  263. //throw exception if encryption is disabled but files are still encrypted
  264. try {
  265. $res = $this->fileView->fopen(ltrim($this->path, '/'), 'rb');
  266. if ($res === false) {
  267. throw new ServiceUnavailable("Could not open file");
  268. }
  269. return $res;
  270. } catch (GenericEncryptionException $e) {
  271. // returning 503 will allow retry of the operation at a later point in time
  272. throw new ServiceUnavailable("Encryption not ready: " . $e->getMessage());
  273. } catch (StorageNotAvailableException $e) {
  274. throw new ServiceUnavailable("Failed to open file: " . $e->getMessage());
  275. } catch (ForbiddenException $ex) {
  276. throw new DAVForbiddenException($ex->getMessage(), $ex->getRetry());
  277. } catch (LockedException $e) {
  278. throw new FileLocked($e->getMessage(), $e->getCode(), $e);
  279. }
  280. }
  281. /**
  282. * Delete the current file
  283. *
  284. * @throws Forbidden
  285. * @throws ServiceUnavailable
  286. */
  287. public function delete() {
  288. if (!$this->info->isDeletable()) {
  289. throw new Forbidden();
  290. }
  291. try {
  292. if (!$this->fileView->unlink($this->path)) {
  293. // assume it wasn't possible to delete due to permissions
  294. throw new Forbidden();
  295. }
  296. } catch (StorageNotAvailableException $e) {
  297. throw new ServiceUnavailable("Failed to unlink: " . $e->getMessage());
  298. } catch (ForbiddenException $ex) {
  299. throw new DAVForbiddenException($ex->getMessage(), $ex->getRetry());
  300. } catch (LockedException $e) {
  301. throw new FileLocked($e->getMessage(), $e->getCode(), $e);
  302. }
  303. }
  304. /**
  305. * Returns the mime-type for a file
  306. *
  307. * If null is returned, we'll assume application/octet-stream
  308. *
  309. * @return string
  310. */
  311. public function getContentType() {
  312. $mimeType = $this->info->getMimetype();
  313. // PROPFIND needs to return the correct mime type, for consistency with the web UI
  314. if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
  315. return $mimeType;
  316. }
  317. return \OC::$server->getMimeTypeDetector()->getSecureMimeType($mimeType);
  318. }
  319. /**
  320. * @return array|false
  321. */
  322. public function getDirectDownload() {
  323. if (\OCP\App::isEnabled('encryption')) {
  324. return [];
  325. }
  326. /** @var \OCP\Files\Storage $storage */
  327. list($storage, $internalPath) = $this->fileView->resolvePath($this->path);
  328. if (is_null($storage)) {
  329. return [];
  330. }
  331. return $storage->getDirectDownload($internalPath);
  332. }
  333. /**
  334. * @param resource $data
  335. * @return null|string
  336. * @throws Exception
  337. * @throws BadRequest
  338. * @throws NotImplemented
  339. * @throws ServiceUnavailable
  340. */
  341. private function createFileChunked($data) {
  342. list($path, $name) = \Sabre\HTTP\URLUtil::splitPath($this->path);
  343. $info = \OC_FileChunking::decodeName($name);
  344. if (empty($info)) {
  345. throw new NotImplemented('Invalid chunk name');
  346. }
  347. $chunk_handler = new \OC_FileChunking($info);
  348. $bytesWritten = $chunk_handler->store($info['index'], $data);
  349. //detect aborted upload
  350. if (isset ($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PUT') {
  351. if (isset($_SERVER['CONTENT_LENGTH'])) {
  352. $expected = $_SERVER['CONTENT_LENGTH'];
  353. if ($bytesWritten != $expected) {
  354. $chunk_handler->remove($info['index']);
  355. throw new BadRequest(
  356. 'expected filesize ' . $expected . ' got ' . $bytesWritten);
  357. }
  358. }
  359. }
  360. if ($chunk_handler->isComplete()) {
  361. list($storage,) = $this->fileView->resolvePath($path);
  362. $needsPartFile = $this->needsPartFile($storage);
  363. $partFile = null;
  364. $targetPath = $path . '/' . $info['name'];
  365. /** @var \OC\Files\Storage\Storage $targetStorage */
  366. list($targetStorage, $targetInternalPath) = $this->fileView->resolvePath($targetPath);
  367. $exists = $this->fileView->file_exists($targetPath);
  368. try {
  369. $this->fileView->lockFile($targetPath, ILockingProvider::LOCK_SHARED);
  370. $this->emitPreHooks($exists, $targetPath);
  371. $this->fileView->changeLock($targetPath, ILockingProvider::LOCK_EXCLUSIVE);
  372. /** @var \OC\Files\Storage\Storage $targetStorage */
  373. list($targetStorage, $targetInternalPath) = $this->fileView->resolvePath($targetPath);
  374. if ($needsPartFile) {
  375. // we first assembly the target file as a part file
  376. $partFile = $path . '/' . $info['name'] . '.ocTransferId' . $info['transferid'] . '.part';
  377. /** @var \OC\Files\Storage\Storage $targetStorage */
  378. list($partStorage, $partInternalPath) = $this->fileView->resolvePath($partFile);
  379. $chunk_handler->file_assemble($partStorage, $partInternalPath, $this->fileView->getAbsolutePath($targetPath));
  380. // here is the final atomic rename
  381. $renameOkay = $targetStorage->moveFromStorage($partStorage, $partInternalPath, $targetInternalPath);
  382. $fileExists = $targetStorage->file_exists($targetInternalPath);
  383. if ($renameOkay === false || $fileExists === false) {
  384. \OCP\Util::writeLog('webdav', '\OC\Files\Filesystem::rename() failed', \OCP\Util::ERROR);
  385. // only delete if an error occurred and the target file was already created
  386. if ($fileExists) {
  387. // set to null to avoid double-deletion when handling exception
  388. // stray part file
  389. $partFile = null;
  390. $targetStorage->unlink($targetInternalPath);
  391. }
  392. $this->fileView->changeLock($targetPath, ILockingProvider::LOCK_SHARED);
  393. throw new Exception('Could not rename part file assembled from chunks');
  394. }
  395. } else {
  396. // assemble directly into the final file
  397. $chunk_handler->file_assemble($targetStorage, $targetInternalPath, $this->fileView->getAbsolutePath($targetPath));
  398. }
  399. // allow sync clients to send the mtime along in a header
  400. $request = \OC::$server->getRequest();
  401. if (isset($request->server['HTTP_X_OC_MTIME'])) {
  402. if ($targetStorage->touch($targetInternalPath, $request->server['HTTP_X_OC_MTIME'])) {
  403. header('X-OC-MTime: accepted');
  404. }
  405. }
  406. // since we skipped the view we need to scan and emit the hooks ourselves
  407. $targetStorage->getUpdater()->update($targetInternalPath);
  408. $this->fileView->changeLock($targetPath, ILockingProvider::LOCK_SHARED);
  409. $this->emitPostHooks($exists, $targetPath);
  410. $info = $this->fileView->getFileInfo($targetPath);
  411. $this->fileView->unlockFile($targetPath, ILockingProvider::LOCK_SHARED);
  412. return $info->getEtag();
  413. } catch (\Exception $e) {
  414. if ($partFile !== null) {
  415. $targetStorage->unlink($targetInternalPath);
  416. }
  417. $this->convertToSabreException($e);
  418. }
  419. }
  420. return null;
  421. }
  422. /**
  423. * Returns whether a part file is needed for the given storage
  424. * or whether the file can be assembled/uploaded directly on the
  425. * target storage.
  426. *
  427. * @param \OCP\Files\Storage $storage
  428. * @return bool true if the storage needs part file handling
  429. */
  430. private function needsPartFile($storage) {
  431. // TODO: in the future use ChunkHandler provided by storage
  432. // and/or add method on Storage called "needsPartFile()"
  433. return !$storage->instanceOfStorage('OCA\Files_Sharing\External\Storage') &&
  434. !$storage->instanceOfStorage('OC\Files\Storage\OwnCloud');
  435. }
  436. /**
  437. * Convert the given exception to a SabreException instance
  438. *
  439. * @param \Exception $e
  440. *
  441. * @throws \Sabre\DAV\Exception
  442. */
  443. private function convertToSabreException(\Exception $e) {
  444. if ($e instanceof \Sabre\DAV\Exception) {
  445. throw $e;
  446. }
  447. if ($e instanceof NotPermittedException) {
  448. // a more general case - due to whatever reason the content could not be written
  449. throw new Forbidden($e->getMessage(), 0, $e);
  450. }
  451. if ($e instanceof ForbiddenException) {
  452. // the path for the file was forbidden
  453. throw new DAVForbiddenException($e->getMessage(), $e->getRetry(), $e);
  454. }
  455. if ($e instanceof EntityTooLargeException) {
  456. // the file is too big to be stored
  457. throw new EntityTooLarge($e->getMessage(), 0, $e);
  458. }
  459. if ($e instanceof InvalidContentException) {
  460. // the file content is not permitted
  461. throw new UnsupportedMediaType($e->getMessage(), 0, $e);
  462. }
  463. if ($e instanceof InvalidPathException) {
  464. // the path for the file was not valid
  465. // TODO: find proper http status code for this case
  466. throw new Forbidden($e->getMessage(), 0, $e);
  467. }
  468. if ($e instanceof LockedException || $e instanceof LockNotAcquiredException) {
  469. // the file is currently being written to by another process
  470. throw new FileLocked($e->getMessage(), $e->getCode(), $e);
  471. }
  472. if ($e instanceof GenericEncryptionException) {
  473. // returning 503 will allow retry of the operation at a later point in time
  474. throw new ServiceUnavailable('Encryption not ready: ' . $e->getMessage(), 0, $e);
  475. }
  476. if ($e instanceof StorageNotAvailableException) {
  477. throw new ServiceUnavailable('Failed to write file contents: ' . $e->getMessage(), 0, $e);
  478. }
  479. throw new \Sabre\DAV\Exception($e->getMessage(), 0, $e);
  480. }
  481. /**
  482. * Get the checksum for this file
  483. *
  484. * @return string
  485. */
  486. public function getChecksum() {
  487. return $this->info->getChecksum();
  488. }
  489. }