OC_Files.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  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 Frank Karlitschek <frank@karlitschek.de>
  10. * @author Jakob Sack <mail@jakobsack.de>
  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 Ko- <k.stoffelen@cs.ru.nl>
  15. * @author Michael Gapczynski <GapczynskiM@gmail.com>
  16. * @author Morris Jobke <hey@morrisjobke.de>
  17. * @author Nicolai Ehemann <en@enlightened.de>
  18. * @author Piotr Filiciak <piotr@filiciak.pl>
  19. * @author Robin Appelman <robin@icewind.nl>
  20. * @author Robin McCorkell <robin@mccorkell.me.uk>
  21. * @author Roeland Jago Douma <roeland@famdouma.nl>
  22. * @author Thibaut GRIDEL <tgridel@free.fr>
  23. * @author Thomas Müller <thomas.mueller@tmit.eu>
  24. * @author Valdnet <47037905+Valdnet@users.noreply.github.com>
  25. * @author Victor Dubiniuk <dubiniuk@owncloud.com>
  26. * @author Vincent Petry <vincent@nextcloud.com>
  27. *
  28. * @license AGPL-3.0
  29. *
  30. * This code is free software: you can redistribute it and/or modify
  31. * it under the terms of the GNU Affero General Public License, version 3,
  32. * as published by the Free Software Foundation.
  33. *
  34. * This program is distributed in the hope that it will be useful,
  35. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  36. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  37. * GNU Affero General Public License for more details.
  38. *
  39. * You should have received a copy of the GNU Affero General Public License, version 3,
  40. * along with this program. If not, see <http://www.gnu.org/licenses/>
  41. *
  42. */
  43. use bantu\IniGetWrapper\IniGetWrapper;
  44. use OC\Files\View;
  45. use OC\Streamer;
  46. use OCP\Lock\ILockingProvider;
  47. use OCP\Files\Events\BeforeZipCreatedEvent;
  48. use OCP\Files\Events\BeforeDirectFileDownloadEvent;
  49. use OCP\EventDispatcher\IEventDispatcher;
  50. /**
  51. * Class for file server access
  52. */
  53. class OC_Files {
  54. public const FILE = 1;
  55. public const ZIP_FILES = 2;
  56. public const ZIP_DIR = 3;
  57. public const UPLOAD_MIN_LIMIT_BYTES = 1048576; // 1 MiB
  58. private static string $multipartBoundary = '';
  59. private static function getBoundary(): string {
  60. if (empty(self::$multipartBoundary)) {
  61. self::$multipartBoundary = md5((string)mt_rand());
  62. }
  63. return self::$multipartBoundary;
  64. }
  65. /**
  66. * @param string $filename
  67. * @param string $name
  68. * @param array $rangeArray ('from'=>int,'to'=>int), ...
  69. */
  70. private static function sendHeaders($filename, $name, array $rangeArray): void {
  71. OC_Response::setContentDispositionHeader($name, 'attachment');
  72. header('Content-Transfer-Encoding: binary', true);
  73. header('Pragma: public');// enable caching in IE
  74. header('Expires: 0');
  75. header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  76. $fileSize = \OC\Files\Filesystem::filesize($filename);
  77. $type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename));
  78. if ($fileSize > -1) {
  79. if (!empty($rangeArray)) {
  80. http_response_code(206);
  81. header('Accept-Ranges: bytes', true);
  82. if (count($rangeArray) > 1) {
  83. $type = 'multipart/byteranges; boundary='.self::getBoundary();
  84. // no Content-Length header here
  85. } else {
  86. header(sprintf('Content-Range: bytes %d-%d/%d', $rangeArray[0]['from'], $rangeArray[0]['to'], $fileSize), true);
  87. OC_Response::setContentLengthHeader($rangeArray[0]['to'] - $rangeArray[0]['from'] + 1);
  88. }
  89. } else {
  90. OC_Response::setContentLengthHeader($fileSize);
  91. }
  92. }
  93. header('Content-Type: '.$type, true);
  94. header('X-Accel-Buffering: no');
  95. }
  96. /**
  97. * return the content of a file or return a zip file containing multiple files
  98. *
  99. * @param string $dir
  100. * @param string $files ; separated list of files to download
  101. * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header
  102. */
  103. public static function get($dir, $files, $params = null) {
  104. OC_Util::setupFS();
  105. $view = \OC\Files\Filesystem::getView();
  106. $getType = self::FILE;
  107. $filename = $dir;
  108. try {
  109. if (is_array($files) && count($files) === 1) {
  110. $files = $files[0];
  111. }
  112. if (!is_array($files)) {
  113. $filename = $dir . '/' . $files;
  114. if (!$view->is_dir($filename)) {
  115. self::getSingleFile($view, $dir, $files, is_null($params) ? [] : $params);
  116. return;
  117. }
  118. }
  119. $name = 'download';
  120. if (is_array($files)) {
  121. $getType = self::ZIP_FILES;
  122. $basename = basename($dir);
  123. if ($basename) {
  124. $name = $basename;
  125. }
  126. $filename = $dir . '/' . $name;
  127. } else {
  128. $filename = $dir . '/' . $files;
  129. $getType = self::ZIP_DIR;
  130. // downloading root ?
  131. if ($files !== '') {
  132. $name = $files;
  133. }
  134. }
  135. self::lockFiles($view, $dir, $files);
  136. $numberOfFiles = 0;
  137. $fileSize = 0;
  138. /* Calculate filesize and number of files */
  139. if ($getType === self::ZIP_FILES) {
  140. $fileInfos = [];
  141. foreach ($files as $file) {
  142. $fileInfo = \OC\Files\Filesystem::getFileInfo($dir . '/' . $file);
  143. if ($fileInfo) {
  144. $fileSize += $fileInfo->getSize();
  145. $fileInfos[] = $fileInfo;
  146. }
  147. }
  148. $numberOfFiles = self::getNumberOfFiles($fileInfos);
  149. } elseif ($getType === self::ZIP_DIR) {
  150. $fileInfo = \OC\Files\Filesystem::getFileInfo($dir . '/' . $files);
  151. if ($fileInfo) {
  152. $fileSize = $fileInfo->getSize();
  153. $numberOfFiles = self::getNumberOfFiles([$fileInfo]);
  154. }
  155. }
  156. //Dispatch an event to see if any apps have problem with download
  157. $event = new BeforeZipCreatedEvent($dir, is_array($files) ? $files : [$files]);
  158. $dispatcher = \OCP\Server::get(IEventDispatcher::class);
  159. $dispatcher->dispatchTyped($event);
  160. if ((!$event->isSuccessful()) || $event->getErrorMessage() !== null) {
  161. throw new \OC\ForbiddenException($event->getErrorMessage());
  162. }
  163. $streamer = new Streamer(\OC::$server->getRequest(), $fileSize, $numberOfFiles);
  164. OC_Util::obEnd();
  165. $streamer->sendHeaders($name);
  166. $executionTime = (int)OC::$server->get(IniGetWrapper::class)->getNumeric('max_execution_time');
  167. if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
  168. @set_time_limit(0);
  169. }
  170. ignore_user_abort(true);
  171. if ($getType === self::ZIP_FILES) {
  172. foreach ($files as $file) {
  173. $file = $dir . '/' . $file;
  174. if (\OC\Files\Filesystem::is_file($file)) {
  175. $userFolder = \OC::$server->getRootFolder()->get(\OC\Files\Filesystem::getRoot());
  176. $file = $userFolder->get($file);
  177. if ($file instanceof \OC\Files\Node\File) {
  178. try {
  179. $fh = $file->fopen('r');
  180. } catch (\OCP\Files\NotPermittedException $e) {
  181. continue;
  182. }
  183. $fileSize = $file->getSize();
  184. $fileTime = $file->getMTime();
  185. } else {
  186. // File is not a file? …
  187. \OC::$server->getLogger()->debug(
  188. 'File given, but no Node available. Name {file}',
  189. [ 'app' => 'files', 'file' => $file ]
  190. );
  191. continue;
  192. }
  193. $streamer->addFileFromStream($fh, $file->getName(), $fileSize, $fileTime);
  194. fclose($fh);
  195. } elseif (\OC\Files\Filesystem::is_dir($file)) {
  196. $streamer->addDirRecursive($file);
  197. }
  198. }
  199. } elseif ($getType === self::ZIP_DIR) {
  200. $file = $dir . '/' . $files;
  201. $streamer->addDirRecursive($file);
  202. }
  203. $streamer->finalize();
  204. set_time_limit($executionTime);
  205. self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
  206. } catch (\OCP\Lock\LockedException $ex) {
  207. self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
  208. OC::$server->getLogger()->logException($ex);
  209. $l = \OC::$server->getL10N('lib');
  210. $hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
  211. \OC_Template::printErrorPage($l->t('File is currently busy, please try again later'), $hint, 200);
  212. } catch (\OCP\Files\ForbiddenException $ex) {
  213. self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
  214. OC::$server->getLogger()->logException($ex);
  215. $l = \OC::$server->getL10N('lib');
  216. \OC_Template::printErrorPage($l->t('Cannot download file'), $ex->getMessage(), 200);
  217. } catch (\OCP\Files\ConnectionLostException $ex) {
  218. self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
  219. OC::$server->getLogger()->logException($ex, ['level' => \OCP\ILogger::DEBUG]);
  220. \OC_Template::printErrorPage('Connection lost', $ex->getMessage(), 200);
  221. } catch (\Exception $ex) {
  222. self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
  223. OC::$server->getLogger()->logException($ex);
  224. $l = \OC::$server->getL10N('lib');
  225. $hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
  226. \OC_Template::printErrorPage($l->t('Cannot download file'), $hint, 200);
  227. }
  228. }
  229. /**
  230. * @param string $rangeHeaderPos
  231. * @param int|float $fileSize
  232. * @return array $rangeArray ('from'=>int,'to'=>int), ...
  233. */
  234. private static function parseHttpRangeHeader($rangeHeaderPos, $fileSize): array {
  235. $rArray = explode(',', $rangeHeaderPos);
  236. $minOffset = 0;
  237. $ind = 0;
  238. $rangeArray = [];
  239. foreach ($rArray as $value) {
  240. $ranges = explode('-', $value);
  241. if (is_numeric($ranges[0])) {
  242. if ($ranges[0] < $minOffset) { // case: bytes=500-700,601-999
  243. $ranges[0] = $minOffset;
  244. }
  245. if ($ind > 0 && $rangeArray[$ind - 1]['to'] + 1 == $ranges[0]) { // case: bytes=500-600,601-999
  246. $ind--;
  247. $ranges[0] = $rangeArray[$ind]['from'];
  248. }
  249. }
  250. if (is_numeric($ranges[0]) && is_numeric($ranges[1]) && $ranges[0] < $fileSize && $ranges[0] <= $ranges[1]) {
  251. // case: x-x
  252. if ($ranges[1] >= $fileSize) {
  253. $ranges[1] = $fileSize - 1;
  254. }
  255. $rangeArray[$ind++] = [ 'from' => $ranges[0], 'to' => $ranges[1], 'size' => $fileSize ];
  256. $minOffset = $ranges[1] + 1;
  257. if ($minOffset >= $fileSize) {
  258. break;
  259. }
  260. } elseif (is_numeric($ranges[0]) && $ranges[0] < $fileSize) {
  261. // case: x-
  262. $rangeArray[$ind++] = [ 'from' => $ranges[0], 'to' => $fileSize - 1, 'size' => $fileSize ];
  263. break;
  264. } elseif (is_numeric($ranges[1])) {
  265. // case: -x
  266. if ($ranges[1] > $fileSize) {
  267. $ranges[1] = $fileSize;
  268. }
  269. $rangeArray[$ind++] = [ 'from' => $fileSize - $ranges[1], 'to' => $fileSize - 1, 'size' => $fileSize ];
  270. break;
  271. }
  272. }
  273. return $rangeArray;
  274. }
  275. /**
  276. * @param View $view
  277. * @param string $name
  278. * @param string $dir
  279. * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header
  280. * @throws \OC\ForbiddenException
  281. */
  282. private static function getSingleFile($view, $dir, $name, $params) {
  283. $filename = $dir . '/' . $name;
  284. $file = null;
  285. try {
  286. $userFolder = \OC::$server->getRootFolder()->get(\OC\Files\Filesystem::getRoot());
  287. $file = $userFolder->get($filename);
  288. if (!$file instanceof \OC\Files\Node\File || !$file->isReadable()) {
  289. http_response_code(403);
  290. die('403 Forbidden');
  291. }
  292. $fileSize = $file->getSize();
  293. } catch (\OCP\Files\NotPermittedException $e) {
  294. http_response_code(403);
  295. die('403 Forbidden');
  296. } catch (\OCP\Files\InvalidPathException $e) {
  297. http_response_code(403);
  298. die('403 Forbidden');
  299. } catch (\OCP\Files\NotFoundException $e) {
  300. http_response_code(404);
  301. $tmpl = new OC_Template('', '404', 'guest');
  302. $tmpl->printPage();
  303. exit();
  304. }
  305. OC_Util::obEnd();
  306. $view->lockFile($filename, ILockingProvider::LOCK_SHARED);
  307. $rangeArray = [];
  308. if (isset($params['range']) && substr($params['range'], 0, 6) === 'bytes=') {
  309. $rangeArray = self::parseHttpRangeHeader(substr($params['range'], 6), $fileSize);
  310. }
  311. $dispatcher = \OC::$server->query(IEventDispatcher::class);
  312. $event = new BeforeDirectFileDownloadEvent($filename);
  313. $dispatcher->dispatchTyped($event);
  314. if (!\OC\Files\Filesystem::isReadable($filename) || $event->getErrorMessage()) {
  315. if ($event->getErrorMessage()) {
  316. $msg = $event->getErrorMessage();
  317. } else {
  318. $msg = 'Access denied';
  319. }
  320. throw new \OC\ForbiddenException($msg);
  321. }
  322. self::sendHeaders($filename, $name, $rangeArray);
  323. if (isset($params['head']) && $params['head']) {
  324. return;
  325. }
  326. if (!empty($rangeArray)) {
  327. try {
  328. if (count($rangeArray) == 1) {
  329. $view->readfilePart($filename, $rangeArray[0]['from'], $rangeArray[0]['to']);
  330. } else {
  331. // check if file is seekable (if not throw UnseekableException)
  332. // we have to check it before body contents
  333. $view->readfilePart($filename, $rangeArray[0]['size'], $rangeArray[0]['size']);
  334. $type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename));
  335. foreach ($rangeArray as $range) {
  336. echo "\r\n--".self::getBoundary()."\r\n".
  337. "Content-type: ".$type."\r\n".
  338. "Content-range: bytes ".$range['from']."-".$range['to']."/".$range['size']."\r\n\r\n";
  339. $view->readfilePart($filename, $range['from'], $range['to']);
  340. }
  341. echo "\r\n--".self::getBoundary()."--\r\n";
  342. }
  343. } catch (\OCP\Files\UnseekableException $ex) {
  344. // file is unseekable
  345. header_remove('Accept-Ranges');
  346. header_remove('Content-Range');
  347. http_response_code(200);
  348. self::sendHeaders($filename, $name, []);
  349. $view->readfile($filename);
  350. }
  351. } else {
  352. $view->readfile($filename);
  353. }
  354. }
  355. /**
  356. * Returns the total (recursive) number of files and folders in the given
  357. * FileInfos.
  358. *
  359. * @param \OCP\Files\FileInfo[] $fileInfos the FileInfos to count
  360. * @return int the total number of files and folders
  361. */
  362. private static function getNumberOfFiles($fileInfos) {
  363. $numberOfFiles = 0;
  364. $view = new View();
  365. while ($fileInfo = array_pop($fileInfos)) {
  366. $numberOfFiles++;
  367. if ($fileInfo->getType() === \OCP\Files\FileInfo::TYPE_FOLDER) {
  368. $fileInfos = array_merge($fileInfos, $view->getDirectoryContent($fileInfo->getPath()));
  369. }
  370. }
  371. return $numberOfFiles;
  372. }
  373. /**
  374. * @param View $view
  375. * @param string $dir
  376. * @param string[]|string $files
  377. */
  378. public static function lockFiles($view, $dir, $files) {
  379. if (!is_array($files)) {
  380. $file = $dir . '/' . $files;
  381. $files = [$file];
  382. }
  383. foreach ($files as $file) {
  384. $file = $dir . '/' . $file;
  385. $view->lockFile($file, ILockingProvider::LOCK_SHARED);
  386. if ($view->is_dir($file)) {
  387. $contents = $view->getDirectoryContent($file);
  388. $contents = array_map(function ($fileInfo) use ($file) {
  389. /** @var \OCP\Files\FileInfo $fileInfo */
  390. return $file . '/' . $fileInfo->getName();
  391. }, $contents);
  392. self::lockFiles($view, $dir, $contents);
  393. }
  394. }
  395. }
  396. /**
  397. * @param string $dir
  398. * @param $files
  399. * @param integer $getType
  400. * @param View $view
  401. * @param string $filename
  402. */
  403. private static function unlockAllTheFiles($dir, $files, $getType, $view, $filename) {
  404. if ($getType === self::FILE) {
  405. $view->unlockFile($filename, ILockingProvider::LOCK_SHARED);
  406. }
  407. if ($getType === self::ZIP_FILES) {
  408. foreach ($files as $file) {
  409. $file = $dir . '/' . $file;
  410. $view->unlockFile($file, ILockingProvider::LOCK_SHARED);
  411. }
  412. }
  413. if ($getType === self::ZIP_DIR) {
  414. $file = $dir . '/' . $files;
  415. $view->unlockFile($file, ILockingProvider::LOCK_SHARED);
  416. }
  417. }
  418. }