1
0

OC_Files.php 13 KB

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