OC_Files.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. use bantu\IniGetWrapper\IniGetWrapper;
  8. use OC\Files\View;
  9. use OC\Streamer;
  10. use OCP\EventDispatcher\IEventDispatcher;
  11. use OCP\Files\Events\BeforeDirectFileDownloadEvent;
  12. use OCP\Files\Events\BeforeZipCreatedEvent;
  13. use OCP\Files\IRootFolder;
  14. use OCP\Lock\ILockingProvider;
  15. /**
  16. * Class for file server access
  17. */
  18. class OC_Files {
  19. public const FILE = 1;
  20. public const ZIP_FILES = 2;
  21. public const ZIP_DIR = 3;
  22. public const UPLOAD_MIN_LIMIT_BYTES = 1048576; // 1 MiB
  23. private static string $multipartBoundary = '';
  24. private static function getBoundary(): string {
  25. if (empty(self::$multipartBoundary)) {
  26. self::$multipartBoundary = md5((string)mt_rand());
  27. }
  28. return self::$multipartBoundary;
  29. }
  30. /**
  31. * @param string $filename
  32. * @param string $name
  33. * @param array $rangeArray ('from'=>int,'to'=>int), ...
  34. */
  35. private static function sendHeaders($filename, $name, array $rangeArray): void {
  36. OC_Response::setContentDispositionHeader($name, 'attachment');
  37. header('Content-Transfer-Encoding: binary', true);
  38. header('Expires: 0');
  39. header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  40. $fileSize = \OC\Files\Filesystem::filesize($filename);
  41. $type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename));
  42. if ($fileSize > -1) {
  43. if (!empty($rangeArray)) {
  44. http_response_code(206);
  45. header('Accept-Ranges: bytes', true);
  46. if (count($rangeArray) > 1) {
  47. $type = 'multipart/byteranges; boundary='.self::getBoundary();
  48. // no Content-Length header here
  49. } else {
  50. header(sprintf('Content-Range: bytes %d-%d/%d', $rangeArray[0]['from'], $rangeArray[0]['to'], $fileSize), true);
  51. OC_Response::setContentLengthHeader($rangeArray[0]['to'] - $rangeArray[0]['from'] + 1);
  52. }
  53. } else {
  54. OC_Response::setContentLengthHeader($fileSize);
  55. }
  56. }
  57. header('Content-Type: '.$type, true);
  58. header('X-Accel-Buffering: no');
  59. }
  60. /**
  61. * return the content of a file or return a zip file containing multiple files
  62. *
  63. * @param string $dir
  64. * @param string|array $files ; separated list of files to download
  65. * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header
  66. */
  67. public static function get($dir, $files, $params = null) {
  68. OC_Util::setupFS();
  69. $view = \OC\Files\Filesystem::getView();
  70. $getType = self::FILE;
  71. $filename = $dir;
  72. try {
  73. if (is_array($files) && count($files) === 1) {
  74. $files = $files[0];
  75. }
  76. if (!is_array($files)) {
  77. $filename = $dir . '/' . $files;
  78. if (!$view->is_dir($filename)) {
  79. self::getSingleFile($view, $dir, $files, is_null($params) ? [] : $params);
  80. return;
  81. }
  82. }
  83. $name = 'download';
  84. if (is_array($files)) {
  85. $getType = self::ZIP_FILES;
  86. $basename = basename($dir);
  87. if ($basename) {
  88. $name = $basename;
  89. }
  90. $filename = $dir . '/' . $name;
  91. } else {
  92. $filename = $dir . '/' . $files;
  93. $getType = self::ZIP_DIR;
  94. // downloading root ?
  95. if ($files !== '') {
  96. $name = $files;
  97. }
  98. }
  99. self::lockFiles($view, $dir, $files);
  100. $numberOfFiles = 0;
  101. $fileSize = 0;
  102. /* Calculate filesize and number of files */
  103. if ($getType === self::ZIP_FILES) {
  104. $fileInfos = [];
  105. foreach ($files as $file) {
  106. $fileInfo = \OC\Files\Filesystem::getFileInfo($dir . '/' . $file);
  107. if ($fileInfo) {
  108. $fileSize += $fileInfo->getSize();
  109. $fileInfos[] = $fileInfo;
  110. }
  111. }
  112. $numberOfFiles = self::getNumberOfFiles($fileInfos);
  113. } elseif ($getType === self::ZIP_DIR) {
  114. $fileInfo = \OC\Files\Filesystem::getFileInfo($dir . '/' . $files);
  115. if ($fileInfo) {
  116. $fileSize = $fileInfo->getSize();
  117. $numberOfFiles = self::getNumberOfFiles([$fileInfo]);
  118. }
  119. }
  120. //Dispatch an event to see if any apps have problem with download
  121. $event = new BeforeZipCreatedEvent($dir, is_array($files) ? $files : [$files]);
  122. $dispatcher = \OCP\Server::get(IEventDispatcher::class);
  123. $dispatcher->dispatchTyped($event);
  124. if ((!$event->isSuccessful()) || $event->getErrorMessage() !== null) {
  125. throw new \OC\ForbiddenException($event->getErrorMessage());
  126. }
  127. $streamer = new Streamer(\OC::$server->getRequest(), $fileSize, $numberOfFiles);
  128. OC_Util::obEnd();
  129. $streamer->sendHeaders($name);
  130. $executionTime = (int)OC::$server->get(IniGetWrapper::class)->getNumeric('max_execution_time');
  131. if (!str_contains(@ini_get('disable_functions'), 'set_time_limit')) {
  132. @set_time_limit(0);
  133. }
  134. ignore_user_abort(true);
  135. if ($getType === self::ZIP_FILES) {
  136. foreach ($files as $file) {
  137. $file = $dir . '/' . $file;
  138. if (\OC\Files\Filesystem::is_file($file)) {
  139. $userFolder = \OC::$server->get(IRootFolder::class)->get(\OC\Files\Filesystem::getRoot());
  140. $file = $userFolder->get($file);
  141. if ($file instanceof \OC\Files\Node\File) {
  142. try {
  143. $fh = $file->fopen('r');
  144. } catch (\OCP\Files\NotPermittedException $e) {
  145. continue;
  146. }
  147. $fileSize = $file->getSize();
  148. $fileTime = $file->getMTime();
  149. } else {
  150. // File is not a file? …
  151. \OC::$server->getLogger()->debug(
  152. 'File given, but no Node available. Name {file}',
  153. [ 'app' => 'files', 'file' => $file ]
  154. );
  155. continue;
  156. }
  157. $streamer->addFileFromStream($fh, $file->getName(), $fileSize, $fileTime);
  158. fclose($fh);
  159. } elseif (\OC\Files\Filesystem::is_dir($file)) {
  160. $streamer->addDirRecursive($file);
  161. }
  162. }
  163. } elseif ($getType === self::ZIP_DIR) {
  164. $file = $dir . '/' . $files;
  165. $streamer->addDirRecursive($file);
  166. }
  167. $streamer->finalize();
  168. set_time_limit($executionTime);
  169. self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
  170. } catch (\OCP\Lock\LockedException $ex) {
  171. self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
  172. OC::$server->getLogger()->logException($ex);
  173. $l = \OC::$server->getL10N('lib');
  174. $hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
  175. \OC_Template::printErrorPage($l->t('File is currently busy, please try again later'), $hint, 200);
  176. } catch (\OCP\Files\ForbiddenException $ex) {
  177. self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
  178. OC::$server->getLogger()->logException($ex);
  179. $l = \OC::$server->getL10N('lib');
  180. \OC_Template::printErrorPage($l->t('Cannot download file'), $ex->getMessage(), 200);
  181. } catch (\OCP\Files\ConnectionLostException $ex) {
  182. self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
  183. OC::$server->getLogger()->logException($ex, ['level' => \OCP\ILogger::DEBUG]);
  184. \OC_Template::printErrorPage('Connection lost', $ex->getMessage(), 200);
  185. } catch (\Exception $ex) {
  186. self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
  187. OC::$server->getLogger()->logException($ex);
  188. $l = \OC::$server->getL10N('lib');
  189. $hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
  190. if ($event && $event->getErrorMessage() !== null) {
  191. $hint .= ' ' . $event->getErrorMessage();
  192. }
  193. \OC_Template::printErrorPage($l->t('Cannot download file'), $hint, 200);
  194. }
  195. }
  196. /**
  197. * @param string $rangeHeaderPos
  198. * @param int|float $fileSize
  199. * @return array $rangeArray ('from'=>int,'to'=>int), ...
  200. */
  201. private static function parseHttpRangeHeader($rangeHeaderPos, $fileSize): array {
  202. $rArray = explode(',', $rangeHeaderPos);
  203. $minOffset = 0;
  204. $ind = 0;
  205. $rangeArray = [];
  206. foreach ($rArray as $value) {
  207. $ranges = explode('-', $value);
  208. if (is_numeric($ranges[0])) {
  209. if ($ranges[0] < $minOffset) { // case: bytes=500-700,601-999
  210. $ranges[0] = $minOffset;
  211. }
  212. if ($ind > 0 && $rangeArray[$ind - 1]['to'] + 1 == $ranges[0]) { // case: bytes=500-600,601-999
  213. $ind--;
  214. $ranges[0] = $rangeArray[$ind]['from'];
  215. }
  216. }
  217. if (is_numeric($ranges[0]) && is_numeric($ranges[1]) && $ranges[0] < $fileSize && $ranges[0] <= $ranges[1]) {
  218. // case: x-x
  219. if ($ranges[1] >= $fileSize) {
  220. $ranges[1] = $fileSize - 1;
  221. }
  222. $rangeArray[$ind++] = [ 'from' => $ranges[0], 'to' => $ranges[1], 'size' => $fileSize ];
  223. $minOffset = $ranges[1] + 1;
  224. if ($minOffset >= $fileSize) {
  225. break;
  226. }
  227. } elseif (is_numeric($ranges[0]) && $ranges[0] < $fileSize) {
  228. // case: x-
  229. $rangeArray[$ind++] = [ 'from' => $ranges[0], 'to' => $fileSize - 1, 'size' => $fileSize ];
  230. break;
  231. } elseif (is_numeric($ranges[1])) {
  232. // case: -x
  233. if ($ranges[1] > $fileSize) {
  234. $ranges[1] = $fileSize;
  235. }
  236. $rangeArray[$ind++] = [ 'from' => $fileSize - $ranges[1], 'to' => $fileSize - 1, 'size' => $fileSize ];
  237. break;
  238. }
  239. }
  240. return $rangeArray;
  241. }
  242. /**
  243. * @param View $view
  244. * @param string $name
  245. * @param string $dir
  246. * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header
  247. * @throws \OC\ForbiddenException
  248. */
  249. private static function getSingleFile($view, $dir, $name, $params) {
  250. $filename = $dir . '/' . $name;
  251. $file = null;
  252. try {
  253. $userFolder = \OC::$server->get(IRootFolder::class)->get(\OC\Files\Filesystem::getRoot());
  254. $file = $userFolder->get($filename);
  255. if (!$file instanceof \OC\Files\Node\File || !$file->isReadable()) {
  256. http_response_code(403);
  257. die('403 Forbidden');
  258. }
  259. $fileSize = $file->getSize();
  260. } catch (\OCP\Files\NotPermittedException $e) {
  261. http_response_code(403);
  262. die('403 Forbidden');
  263. } catch (\OCP\Files\InvalidPathException $e) {
  264. http_response_code(403);
  265. die('403 Forbidden');
  266. } catch (\OCP\Files\NotFoundException $e) {
  267. http_response_code(404);
  268. $tmpl = new OC_Template('', '404', 'guest');
  269. $tmpl->printPage();
  270. exit();
  271. }
  272. OC_Util::obEnd();
  273. $view->lockFile($filename, ILockingProvider::LOCK_SHARED);
  274. $rangeArray = [];
  275. if (isset($params['range']) && substr($params['range'], 0, 6) === 'bytes=') {
  276. $rangeArray = self::parseHttpRangeHeader(substr($params['range'], 6), $fileSize);
  277. }
  278. $dispatcher = \OCP\Server::get(IEventDispatcher::class);
  279. $event = new BeforeDirectFileDownloadEvent($filename);
  280. $dispatcher->dispatchTyped($event);
  281. if (!\OC\Files\Filesystem::isReadable($filename) || $event->getErrorMessage()) {
  282. if ($event->getErrorMessage()) {
  283. $msg = $event->getErrorMessage();
  284. } else {
  285. $msg = 'Access denied';
  286. }
  287. throw new \OC\ForbiddenException($msg);
  288. }
  289. self::sendHeaders($filename, $name, $rangeArray);
  290. if (isset($params['head']) && $params['head']) {
  291. return;
  292. }
  293. if (!empty($rangeArray)) {
  294. try {
  295. if (count($rangeArray) == 1) {
  296. $view->readfilePart($filename, $rangeArray[0]['from'], $rangeArray[0]['to']);
  297. } else {
  298. // check if file is seekable (if not throw UnseekableException)
  299. // we have to check it before body contents
  300. $view->readfilePart($filename, $rangeArray[0]['size'], $rangeArray[0]['size']);
  301. $type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename));
  302. foreach ($rangeArray as $range) {
  303. echo "\r\n--".self::getBoundary()."\r\n".
  304. "Content-type: ".$type."\r\n".
  305. "Content-range: bytes ".$range['from']."-".$range['to']."/".$range['size']."\r\n\r\n";
  306. $view->readfilePart($filename, $range['from'], $range['to']);
  307. }
  308. echo "\r\n--".self::getBoundary()."--\r\n";
  309. }
  310. } catch (\OCP\Files\UnseekableException $ex) {
  311. // file is unseekable
  312. header_remove('Accept-Ranges');
  313. header_remove('Content-Range');
  314. http_response_code(200);
  315. self::sendHeaders($filename, $name, []);
  316. $view->readfile($filename);
  317. }
  318. } else {
  319. $view->readfile($filename);
  320. }
  321. }
  322. /**
  323. * Returns the total (recursive) number of files and folders in the given
  324. * FileInfos.
  325. *
  326. * @param \OCP\Files\FileInfo[] $fileInfos the FileInfos to count
  327. * @return int the total number of files and folders
  328. */
  329. private static function getNumberOfFiles($fileInfos) {
  330. $numberOfFiles = 0;
  331. $view = new View();
  332. while ($fileInfo = array_pop($fileInfos)) {
  333. $numberOfFiles++;
  334. if ($fileInfo->getType() === \OCP\Files\FileInfo::TYPE_FOLDER) {
  335. $fileInfos = array_merge($fileInfos, $view->getDirectoryContent($fileInfo->getPath()));
  336. }
  337. }
  338. return $numberOfFiles;
  339. }
  340. /**
  341. * @param View $view
  342. * @param string $dir
  343. * @param string[]|string $files
  344. */
  345. public static function lockFiles($view, $dir, $files) {
  346. if (!is_array($files)) {
  347. $file = $dir . '/' . $files;
  348. $files = [$file];
  349. }
  350. foreach ($files as $file) {
  351. $file = $dir . '/' . $file;
  352. $view->lockFile($file, ILockingProvider::LOCK_SHARED);
  353. if ($view->is_dir($file)) {
  354. $contents = $view->getDirectoryContent($file);
  355. $contents = array_map(function ($fileInfo) use ($file) {
  356. /** @var \OCP\Files\FileInfo $fileInfo */
  357. return $file . '/' . $fileInfo->getName();
  358. }, $contents);
  359. self::lockFiles($view, $dir, $contents);
  360. }
  361. }
  362. }
  363. /**
  364. * @param string $dir
  365. * @param $files
  366. * @param integer $getType
  367. * @param View $view
  368. * @param string $filename
  369. */
  370. private static function unlockAllTheFiles($dir, $files, $getType, $view, $filename) {
  371. if ($getType === self::FILE) {
  372. $view->unlockFile($filename, ILockingProvider::LOCK_SHARED);
  373. }
  374. if ($getType === self::ZIP_FILES) {
  375. foreach ($files as $file) {
  376. $file = $dir . '/' . $file;
  377. $view->unlockFile($file, ILockingProvider::LOCK_SHARED);
  378. }
  379. }
  380. if ($getType === self::ZIP_DIR) {
  381. $file = $dir . '/' . $files;
  382. $view->unlockFile($file, ILockingProvider::LOCK_SHARED);
  383. }
  384. }
  385. }