1
0

OC_Files.php 15 KB

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