You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

426 lines
13 KiB

3 years ago
  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 Lukas Reschke <lukas@statuscode.ch>
  16. * @author Michael Gapczynski <GapczynskiM@gmail.com>
  17. * @author Morris Jobke <hey@morrisjobke.de>
  18. * @author Nicolai Ehemann <en@enlightened.de>
  19. * @author Piotr Filiciak <piotr@filiciak.pl>
  20. * @author Robin Appelman <robin@icewind.nl>
  21. * @author Robin McCorkell <robin@mccorkell.me.uk>
  22. * @author Roeland Jago Douma <roeland@famdouma.nl>
  23. * @author Thibaut GRIDEL <tgridel@free.fr>
  24. * @author Thomas Müller <thomas.mueller@tmit.eu>
  25. * @author Victor Dubiniuk <dubiniuk@owncloud.com>
  26. * @author Vincent Petry <pvince81@owncloud.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. /**
  48. * Class for file server access
  49. *
  50. */
  51. class OC_Files {
  52. public const FILE = 1;
  53. public const ZIP_FILES = 2;
  54. public const ZIP_DIR = 3;
  55. public const UPLOAD_MIN_LIMIT_BYTES = 1048576; // 1 MiB
  56. private static $multipartBoundary = '';
  57. /**
  58. * @return string
  59. */
  60. private static function getBoundary() {
  61. if (empty(self::$multipartBoundary)) {
  62. self::$multipartBoundary = md5(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) {
  72. OC_Response::setContentDispositionHeader($name, 'attachment');
  73. header('Content-Transfer-Encoding: binary', true);
  74. header('Pragma: public');// enable caching in IE
  75. header('Expires: 0');
  76. header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  77. $fileSize = \OC\Files\Filesystem::filesize($filename);
  78. $type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename));
  79. if ($fileSize > -1) {
  80. if (!empty($rangeArray)) {
  81. http_response_code(206);
  82. header('Accept-Ranges: bytes', true);
  83. if (count($rangeArray) > 1) {
  84. $type = 'multipart/byteranges; boundary='.self::getBoundary();
  85. // no Content-Length header here
  86. } else {
  87. header(sprintf('Content-Range: bytes %d-%d/%d', $rangeArray[0]['from'], $rangeArray[0]['to'], $fileSize), true);
  88. OC_Response::setContentLengthHeader($rangeArray[0]['to'] - $rangeArray[0]['from'] + 1);
  89. }
  90. } else {
  91. OC_Response::setContentLengthHeader($fileSize);
  92. }
  93. }
  94. header('Content-Type: '.$type, true);
  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. $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. /* Calculate filesize and number of files */
  136. if ($getType === self::ZIP_FILES) {
  137. $fileInfos = [];
  138. $fileSize = 0;
  139. foreach ($files as $file) {
  140. $fileInfo = \OC\Files\Filesystem::getFileInfo($dir . '/' . $file);
  141. $fileSize += $fileInfo->getSize();
  142. $fileInfos[] = $fileInfo;
  143. }
  144. $numberOfFiles = self::getNumberOfFiles($fileInfos);
  145. } elseif ($getType === self::ZIP_DIR) {
  146. $fileInfo = \OC\Files\Filesystem::getFileInfo($dir . '/' . $files);
  147. $fileSize = $fileInfo->getSize();
  148. $numberOfFiles = self::getNumberOfFiles([$fileInfo]);
  149. }
  150. $streamer = new Streamer(\OC::$server->getRequest(), $fileSize, $numberOfFiles);
  151. OC_Util::obEnd();
  152. $streamer->sendHeaders($name);
  153. $executionTime = (int)OC::$server->get(IniGetWrapper::class)->getNumeric('max_execution_time');
  154. if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
  155. @set_time_limit(0);
  156. }
  157. ignore_user_abort(true);
  158. if ($getType === self::ZIP_FILES) {
  159. foreach ($files as $file) {
  160. $file = $dir . '/' . $file;
  161. if (\OC\Files\Filesystem::is_file($file)) {
  162. $userFolder = \OC::$server->getRootFolder()->get(\OC\Files\Filesystem::getRoot());
  163. $file = $userFolder->get($file);
  164. if ($file instanceof \OC\Files\Node\File) {
  165. try {
  166. $fh = $file->fopen('r');
  167. } catch (\OCP\Files\NotPermittedException $e) {
  168. continue;
  169. }
  170. $fileSize = $file->getSize();
  171. $fileTime = $file->getMTime();
  172. } else {
  173. // File is not a file? …
  174. \OC::$server->getLogger()->debug(
  175. 'File given, but no Node available. Name {file}',
  176. [ 'app' => 'files', 'file' => $file ]
  177. );
  178. continue;
  179. }
  180. $streamer->addFileFromStream($fh, $file->getName(), $fileSize, $fileTime);
  181. fclose($fh);
  182. } elseif (\OC\Files\Filesystem::is_dir($file)) {
  183. $streamer->addDirRecursive($file);
  184. }
  185. }
  186. } elseif ($getType === self::ZIP_DIR) {
  187. $file = $dir . '/' . $files;
  188. $streamer->addDirRecursive($file);
  189. }
  190. $streamer->finalize();
  191. set_time_limit($executionTime);
  192. self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
  193. } catch (\OCP\Lock\LockedException $ex) {
  194. self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
  195. OC::$server->getLogger()->logException($ex);
  196. $l = \OC::$server->getL10N('core');
  197. $hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
  198. \OC_Template::printErrorPage($l->t('File is currently busy, please try again later'), $hint, 200);
  199. } catch (\OCP\Files\ForbiddenException $ex) {
  200. self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
  201. OC::$server->getLogger()->logException($ex);
  202. $l = \OC::$server->getL10N('core');
  203. \OC_Template::printErrorPage($l->t('Can\'t read file'), $ex->getMessage(), 200);
  204. } catch (\Exception $ex) {
  205. self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
  206. OC::$server->getLogger()->logException($ex);
  207. $l = \OC::$server->getL10N('core');
  208. $hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
  209. \OC_Template::printErrorPage($l->t('Can\'t read file'), $hint, 200);
  210. }
  211. }
  212. /**
  213. * @param string $rangeHeaderPos
  214. * @param int $fileSize
  215. * @return array $rangeArray ('from'=>int,'to'=>int), ...
  216. */
  217. private static function parseHttpRangeHeader($rangeHeaderPos, $fileSize) {
  218. $rArray=explode(',', $rangeHeaderPos);
  219. $minOffset = 0;
  220. $ind = 0;
  221. $rangeArray = [];
  222. foreach ($rArray as $value) {
  223. $ranges = explode('-', $value);
  224. if (is_numeric($ranges[0])) {
  225. if ($ranges[0] < $minOffset) { // case: bytes=500-700,601-999
  226. $ranges[0] = $minOffset;
  227. }
  228. if ($ind > 0 && $rangeArray[$ind-1]['to']+1 == $ranges[0]) { // case: bytes=500-600,601-999
  229. $ind--;
  230. $ranges[0] = $rangeArray[$ind]['from'];
  231. }
  232. }
  233. if (is_numeric($ranges[0]) && is_numeric($ranges[1]) && $ranges[0] < $fileSize && $ranges[0] <= $ranges[1]) {
  234. // case: x-x
  235. if ($ranges[1] >= $fileSize) {
  236. $ranges[1] = $fileSize-1;
  237. }
  238. $rangeArray[$ind++] = [ 'from' => $ranges[0], 'to' => $ranges[1], 'size' => $fileSize ];
  239. $minOffset = $ranges[1] + 1;
  240. if ($minOffset >= $fileSize) {
  241. break;
  242. }
  243. } elseif (is_numeric($ranges[0]) && $ranges[0] < $fileSize) {
  244. // case: x-
  245. $rangeArray[$ind++] = [ 'from' => $ranges[0], 'to' => $fileSize-1, 'size' => $fileSize ];
  246. break;
  247. } elseif (is_numeric($ranges[1])) {
  248. // case: -x
  249. if ($ranges[1] > $fileSize) {
  250. $ranges[1] = $fileSize;
  251. }
  252. $rangeArray[$ind++] = [ 'from' => $fileSize-$ranges[1], 'to' => $fileSize-1, 'size' => $fileSize ];
  253. break;
  254. }
  255. }
  256. return $rangeArray;
  257. }
  258. /**
  259. * @param View $view
  260. * @param string $name
  261. * @param string $dir
  262. * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header
  263. */
  264. private static function getSingleFile($view, $dir, $name, $params) {
  265. $filename = $dir . '/' . $name;
  266. $file = null;
  267. try {
  268. $userFolder = \OC::$server->getRootFolder()->get(\OC\Files\Filesystem::getRoot());
  269. $file = $userFolder->get($filename);
  270. if (!$file instanceof \OC\Files\Node\File || !$file->isReadable()) {
  271. http_response_code(403);
  272. die('403 Forbidden');
  273. }
  274. $fileSize = $file->getSize();
  275. } catch (\OCP\Files\NotPermittedException $e) {
  276. http_response_code(403);
  277. die('403 Forbidden');
  278. } catch (\OCP\Files\InvalidPathException $e) {
  279. http_response_code(403);
  280. die('403 Forbidden');
  281. } catch (\OCP\Files\NotFoundException $e) {
  282. http_response_code(404);
  283. $tmpl = new OC_Template('', '404', 'guest');
  284. $tmpl->printPage();
  285. exit();
  286. }
  287. OC_Util::obEnd();
  288. $view->lockFile($filename, ILockingProvider::LOCK_SHARED);
  289. $rangeArray = [];
  290. if (isset($params['range']) && substr($params['range'], 0, 6) === 'bytes=') {
  291. $rangeArray = self::parseHttpRangeHeader(substr($params['range'], 6), $fileSize);
  292. }
  293. self::sendHeaders($filename, $name, $rangeArray);
  294. if (isset($params['head']) && $params['head']) {
  295. return;
  296. }
  297. if (!empty($rangeArray)) {
  298. try {
  299. if (count($rangeArray) == 1) {
  300. $view->readfilePart($filename, $rangeArray[0]['from'], $rangeArray[0]['to']);
  301. } else {
  302. // check if file is seekable (if not throw UnseekableException)
  303. // we have to check it before body contents
  304. $view->readfilePart($filename, $rangeArray[0]['size'], $rangeArray[0]['size']);
  305. $type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename));
  306. foreach ($rangeArray as $range) {
  307. echo "\r\n--".self::getBoundary()."\r\n".
  308. "Content-type: ".$type."\r\n".
  309. "Content-range: bytes ".$range['from']."-".$range['to']."/".$range['size']."\r\n\r\n";
  310. $view->readfilePart($filename, $range['from'], $range['to']);
  311. }
  312. echo "\r\n--".self::getBoundary()."--\r\n";
  313. }
  314. } catch (\OCP\Files\UnseekableException $ex) {
  315. // file is unseekable
  316. header_remove('Accept-Ranges');
  317. header_remove('Content-Range');
  318. http_response_code(200);
  319. self::sendHeaders($filename, $name, []);
  320. $view->readfile($filename);
  321. }
  322. } else {
  323. $view->readfile($filename);
  324. }
  325. }
  326. /**
  327. * Returns the total (recursive) number of files and folders in the given
  328. * FileInfos.
  329. *
  330. * @param \OCP\Files\FileInfo[] $fileInfos the FileInfos to count
  331. * @return int the total number of files and folders
  332. */
  333. private static function getNumberOfFiles($fileInfos) {
  334. $numberOfFiles = 0;
  335. $view = new View();
  336. while ($fileInfo = array_pop($fileInfos)) {
  337. $numberOfFiles++;
  338. if ($fileInfo->getType() === \OCP\Files\FileInfo::TYPE_FOLDER) {
  339. $fileInfos = array_merge($fileInfos, $view->getDirectoryContent($fileInfo->getPath()));
  340. }
  341. }
  342. return $numberOfFiles;
  343. }
  344. /**
  345. * @param View $view
  346. * @param string $dir
  347. * @param string[]|string $files
  348. */
  349. public static function lockFiles($view, $dir, $files) {
  350. if (!is_array($files)) {
  351. $file = $dir . '/' . $files;
  352. $files = [$file];
  353. }
  354. foreach ($files as $file) {
  355. $file = $dir . '/' . $file;
  356. $view->lockFile($file, ILockingProvider::LOCK_SHARED);
  357. if ($view->is_dir($file)) {
  358. $contents = $view->getDirectoryContent($file);
  359. $contents = array_map(function ($fileInfo) use ($file) {
  360. /** @var \OCP\Files\FileInfo $fileInfo */
  361. return $file . '/' . $fileInfo->getName();
  362. }, $contents);
  363. self::lockFiles($view, $dir, $contents);
  364. }
  365. }
  366. }
  367. /**
  368. * @param string $dir
  369. * @param $files
  370. * @param integer $getType
  371. * @param View $view
  372. * @param string $filename
  373. */
  374. private static function unlockAllTheFiles($dir, $files, $getType, $view, $filename) {
  375. if ($getType === self::FILE) {
  376. $view->unlockFile($filename, ILockingProvider::LOCK_SHARED);
  377. }
  378. if ($getType === self::ZIP_FILES) {
  379. foreach ($files as $file) {
  380. $file = $dir . '/' . $file;
  381. $view->unlockFile($file, ILockingProvider::LOCK_SHARED);
  382. }
  383. }
  384. if ($getType === self::ZIP_DIR) {
  385. $file = $dir . '/' . $files;
  386. $view->unlockFile($file, ILockingProvider::LOCK_SHARED);
  387. }
  388. }
  389. }