OC_Files.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  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 (\Exception $ex) {
  218. self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
  219. OC::$server->getLogger()->logException($ex);
  220. $l = \OC::$server->getL10N('lib');
  221. $hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
  222. if ($event && $event->getErrorMessage() !== null) {
  223. $hint .= ' ' . $event->getErrorMessage();
  224. }
  225. \OC_Template::printErrorPage($l->t('Cannot download file'), $hint, 200);
  226. }
  227. }
  228. /**
  229. * @param string $rangeHeaderPos
  230. * @param int|float $fileSize
  231. * @return array $rangeArray ('from'=>int,'to'=>int), ...
  232. */
  233. private static function parseHttpRangeHeader($rangeHeaderPos, $fileSize): array {
  234. $rArray = explode(',', $rangeHeaderPos);
  235. $minOffset = 0;
  236. $ind = 0;
  237. $rangeArray = [];
  238. foreach ($rArray as $value) {
  239. $ranges = explode('-', $value);
  240. if (is_numeric($ranges[0])) {
  241. if ($ranges[0] < $minOffset) { // case: bytes=500-700,601-999
  242. $ranges[0] = $minOffset;
  243. }
  244. if ($ind > 0 && $rangeArray[$ind - 1]['to'] + 1 == $ranges[0]) { // case: bytes=500-600,601-999
  245. $ind--;
  246. $ranges[0] = $rangeArray[$ind]['from'];
  247. }
  248. }
  249. if (is_numeric($ranges[0]) && is_numeric($ranges[1]) && $ranges[0] < $fileSize && $ranges[0] <= $ranges[1]) {
  250. // case: x-x
  251. if ($ranges[1] >= $fileSize) {
  252. $ranges[1] = $fileSize - 1;
  253. }
  254. $rangeArray[$ind++] = [ 'from' => $ranges[0], 'to' => $ranges[1], 'size' => $fileSize ];
  255. $minOffset = $ranges[1] + 1;
  256. if ($minOffset >= $fileSize) {
  257. break;
  258. }
  259. } elseif (is_numeric($ranges[0]) && $ranges[0] < $fileSize) {
  260. // case: x-
  261. $rangeArray[$ind++] = [ 'from' => $ranges[0], 'to' => $fileSize - 1, 'size' => $fileSize ];
  262. break;
  263. } elseif (is_numeric($ranges[1])) {
  264. // case: -x
  265. if ($ranges[1] > $fileSize) {
  266. $ranges[1] = $fileSize;
  267. }
  268. $rangeArray[$ind++] = [ 'from' => $fileSize - $ranges[1], 'to' => $fileSize - 1, 'size' => $fileSize ];
  269. break;
  270. }
  271. }
  272. return $rangeArray;
  273. }
  274. /**
  275. * @param View $view
  276. * @param string $name
  277. * @param string $dir
  278. * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header
  279. * @throws \OC\ForbiddenException
  280. */
  281. private static function getSingleFile($view, $dir, $name, $params) {
  282. $filename = $dir . '/' . $name;
  283. $file = null;
  284. try {
  285. $userFolder = \OC::$server->getRootFolder()->get(\OC\Files\Filesystem::getRoot());
  286. $file = $userFolder->get($filename);
  287. if (!$file instanceof \OC\Files\Node\File || !$file->isReadable()) {
  288. http_response_code(403);
  289. die('403 Forbidden');
  290. }
  291. $fileSize = $file->getSize();
  292. } catch (\OCP\Files\NotPermittedException $e) {
  293. http_response_code(403);
  294. die('403 Forbidden');
  295. } catch (\OCP\Files\InvalidPathException $e) {
  296. http_response_code(403);
  297. die('403 Forbidden');
  298. } catch (\OCP\Files\NotFoundException $e) {
  299. http_response_code(404);
  300. $tmpl = new OC_Template('', '404', 'guest');
  301. $tmpl->printPage();
  302. exit();
  303. }
  304. OC_Util::obEnd();
  305. $view->lockFile($filename, ILockingProvider::LOCK_SHARED);
  306. $rangeArray = [];
  307. if (isset($params['range']) && substr($params['range'], 0, 6) === 'bytes=') {
  308. $rangeArray = self::parseHttpRangeHeader(substr($params['range'], 6), $fileSize);
  309. }
  310. $dispatcher = \OC::$server->query(IEventDispatcher::class);
  311. $event = new BeforeDirectFileDownloadEvent($filename);
  312. $dispatcher->dispatchTyped($event);
  313. if (!\OC\Files\Filesystem::isReadable($filename) || $event->getErrorMessage()) {
  314. if ($event->getErrorMessage()) {
  315. $msg = $event->getErrorMessage();
  316. } else {
  317. $msg = 'Access denied';
  318. }
  319. throw new \OC\ForbiddenException($msg);
  320. }
  321. self::sendHeaders($filename, $name, $rangeArray);
  322. if (isset($params['head']) && $params['head']) {
  323. return;
  324. }
  325. if (!empty($rangeArray)) {
  326. try {
  327. if (count($rangeArray) == 1) {
  328. $view->readfilePart($filename, $rangeArray[0]['from'], $rangeArray[0]['to']);
  329. } else {
  330. // check if file is seekable (if not throw UnseekableException)
  331. // we have to check it before body contents
  332. $view->readfilePart($filename, $rangeArray[0]['size'], $rangeArray[0]['size']);
  333. $type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename));
  334. foreach ($rangeArray as $range) {
  335. echo "\r\n--".self::getBoundary()."\r\n".
  336. "Content-type: ".$type."\r\n".
  337. "Content-range: bytes ".$range['from']."-".$range['to']."/".$range['size']."\r\n\r\n";
  338. $view->readfilePart($filename, $range['from'], $range['to']);
  339. }
  340. echo "\r\n--".self::getBoundary()."--\r\n";
  341. }
  342. } catch (\OCP\Files\UnseekableException $ex) {
  343. // file is unseekable
  344. header_remove('Accept-Ranges');
  345. header_remove('Content-Range');
  346. http_response_code(200);
  347. self::sendHeaders($filename, $name, []);
  348. $view->readfile($filename);
  349. }
  350. } else {
  351. $view->readfile($filename);
  352. }
  353. }
  354. /**
  355. * Returns the total (recursive) number of files and folders in the given
  356. * FileInfos.
  357. *
  358. * @param \OCP\Files\FileInfo[] $fileInfos the FileInfos to count
  359. * @return int the total number of files and folders
  360. */
  361. private static function getNumberOfFiles($fileInfos) {
  362. $numberOfFiles = 0;
  363. $view = new View();
  364. while ($fileInfo = array_pop($fileInfos)) {
  365. $numberOfFiles++;
  366. if ($fileInfo->getType() === \OCP\Files\FileInfo::TYPE_FOLDER) {
  367. $fileInfos = array_merge($fileInfos, $view->getDirectoryContent($fileInfo->getPath()));
  368. }
  369. }
  370. return $numberOfFiles;
  371. }
  372. /**
  373. * @param View $view
  374. * @param string $dir
  375. * @param string[]|string $files
  376. */
  377. public static function lockFiles($view, $dir, $files) {
  378. if (!is_array($files)) {
  379. $file = $dir . '/' . $files;
  380. $files = [$file];
  381. }
  382. foreach ($files as $file) {
  383. $file = $dir . '/' . $file;
  384. $view->lockFile($file, ILockingProvider::LOCK_SHARED);
  385. if ($view->is_dir($file)) {
  386. $contents = $view->getDirectoryContent($file);
  387. $contents = array_map(function ($fileInfo) use ($file) {
  388. /** @var \OCP\Files\FileInfo $fileInfo */
  389. return $file . '/' . $fileInfo->getName();
  390. }, $contents);
  391. self::lockFiles($view, $dir, $contents);
  392. }
  393. }
  394. }
  395. /**
  396. * @param string $dir
  397. * @param $files
  398. * @param integer $getType
  399. * @param View $view
  400. * @param string $filename
  401. */
  402. private static function unlockAllTheFiles($dir, $files, $getType, $view, $filename) {
  403. if ($getType === self::FILE) {
  404. $view->unlockFile($filename, ILockingProvider::LOCK_SHARED);
  405. }
  406. if ($getType === self::ZIP_FILES) {
  407. foreach ($files as $file) {
  408. $file = $dir . '/' . $file;
  409. $view->unlockFile($file, ILockingProvider::LOCK_SHARED);
  410. }
  411. }
  412. if ($getType === self::ZIP_DIR) {
  413. $file = $dir . '/' . $files;
  414. $view->unlockFile($file, ILockingProvider::LOCK_SHARED);
  415. }
  416. }
  417. }