1
0

OC_Files.php 15 KB

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