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 $multipartBoundary = '';
  59. /**
  60. * @return string
  61. */
  62. private static function getBoundary() {
  63. if (empty(self::$multipartBoundary)) {
  64. self::$multipartBoundary = md5(mt_rand());
  65. }
  66. return self::$multipartBoundary;
  67. }
  68. /**
  69. * @param string $filename
  70. * @param string $name
  71. * @param array $rangeArray ('from'=>int,'to'=>int), ...
  72. */
  73. private static function sendHeaders($filename, $name, array $rangeArray) {
  74. OC_Response::setContentDispositionHeader($name, 'attachment');
  75. header('Content-Transfer-Encoding: binary', true);
  76. header('Pragma: public');// enable caching in IE
  77. header('Expires: 0');
  78. header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  79. $fileSize = \OC\Files\Filesystem::filesize($filename);
  80. $type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename));
  81. if ($fileSize > -1) {
  82. if (!empty($rangeArray)) {
  83. http_response_code(206);
  84. header('Accept-Ranges: bytes', true);
  85. if (count($rangeArray) > 1) {
  86. $type = 'multipart/byteranges; boundary='.self::getBoundary();
  87. // no Content-Length header here
  88. } else {
  89. header(sprintf('Content-Range: bytes %d-%d/%d', $rangeArray[0]['from'], $rangeArray[0]['to'], $fileSize), true);
  90. OC_Response::setContentLengthHeader($rangeArray[0]['to'] - $rangeArray[0]['from'] + 1);
  91. }
  92. } else {
  93. OC_Response::setContentLengthHeader($fileSize);
  94. }
  95. }
  96. header('Content-Type: '.$type, true);
  97. header('X-Accel-Buffering: no');
  98. }
  99. /**
  100. * return the content of a file or return a zip file containing multiple files
  101. *
  102. * @param string $dir
  103. * @param string $files ; separated list of files to download
  104. * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header
  105. */
  106. public static function get($dir, $files, $params = null) {
  107. OC_Util::setupFS();
  108. $view = \OC\Files\Filesystem::getView();
  109. $getType = self::FILE;
  110. $filename = $dir;
  111. try {
  112. if (is_array($files) && count($files) === 1) {
  113. $files = $files[0];
  114. }
  115. if (!is_array($files)) {
  116. $filename = $dir . '/' . $files;
  117. if (!$view->is_dir($filename)) {
  118. self::getSingleFile($view, $dir, $files, is_null($params) ? [] : $params);
  119. return;
  120. }
  121. }
  122. $name = 'download';
  123. if (is_array($files)) {
  124. $getType = self::ZIP_FILES;
  125. $basename = basename($dir);
  126. if ($basename) {
  127. $name = $basename;
  128. }
  129. $filename = $dir . '/' . $name;
  130. } else {
  131. $filename = $dir . '/' . $files;
  132. $getType = self::ZIP_DIR;
  133. // downloading root ?
  134. if ($files !== '') {
  135. $name = $files;
  136. }
  137. }
  138. self::lockFiles($view, $dir, $files);
  139. $numberOfFiles = 0;
  140. $fileSize = 0;
  141. /* Calculate filesize and number of files */
  142. if ($getType === self::ZIP_FILES) {
  143. $fileInfos = [];
  144. foreach ($files as $file) {
  145. $fileInfo = \OC\Files\Filesystem::getFileInfo($dir . '/' . $file);
  146. if ($fileInfo) {
  147. $fileSize += $fileInfo->getSize();
  148. $fileInfos[] = $fileInfo;
  149. }
  150. }
  151. $numberOfFiles = self::getNumberOfFiles($fileInfos);
  152. } elseif ($getType === self::ZIP_DIR) {
  153. $fileInfo = \OC\Files\Filesystem::getFileInfo($dir . '/' . $files);
  154. if ($fileInfo) {
  155. $fileSize = $fileInfo->getSize();
  156. $numberOfFiles = self::getNumberOfFiles([$fileInfo]);
  157. }
  158. }
  159. //Dispatch an event to see if any apps have problem with download
  160. $event = new BeforeZipCreatedEvent($dir, is_array($files) ? $files : [$files]);
  161. $dispatcher = \OCP\Server::get(IEventDispatcher::class);
  162. $dispatcher->dispatchTyped($event);
  163. if ((!$event->isSuccessful()) || $event->getErrorMessage() !== null) {
  164. throw new \OC\ForbiddenException($event->getErrorMessage());
  165. }
  166. $streamer = new Streamer(\OC::$server->getRequest(), $fileSize, $numberOfFiles);
  167. OC_Util::obEnd();
  168. $streamer->sendHeaders($name);
  169. $executionTime = (int)OC::$server->get(IniGetWrapper::class)->getNumeric('max_execution_time');
  170. if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
  171. @set_time_limit(0);
  172. }
  173. ignore_user_abort(true);
  174. if ($getType === self::ZIP_FILES) {
  175. foreach ($files as $file) {
  176. $file = $dir . '/' . $file;
  177. if (\OC\Files\Filesystem::is_file($file)) {
  178. $userFolder = \OC::$server->getRootFolder()->get(\OC\Files\Filesystem::getRoot());
  179. $file = $userFolder->get($file);
  180. if ($file instanceof \OC\Files\Node\File) {
  181. try {
  182. $fh = $file->fopen('r');
  183. } catch (\OCP\Files\NotPermittedException $e) {
  184. continue;
  185. }
  186. $fileSize = $file->getSize();
  187. $fileTime = $file->getMTime();
  188. } else {
  189. // File is not a file? …
  190. \OC::$server->getLogger()->debug(
  191. 'File given, but no Node available. Name {file}',
  192. [ 'app' => 'files', 'file' => $file ]
  193. );
  194. continue;
  195. }
  196. $streamer->addFileFromStream($fh, $file->getName(), $fileSize, $fileTime);
  197. fclose($fh);
  198. } elseif (\OC\Files\Filesystem::is_dir($file)) {
  199. $streamer->addDirRecursive($file);
  200. }
  201. }
  202. } elseif ($getType === self::ZIP_DIR) {
  203. $file = $dir . '/' . $files;
  204. $streamer->addDirRecursive($file);
  205. }
  206. $streamer->finalize();
  207. set_time_limit($executionTime);
  208. self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
  209. } catch (\OCP\Lock\LockedException $ex) {
  210. self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
  211. OC::$server->getLogger()->logException($ex);
  212. $l = \OC::$server->getL10N('lib');
  213. $hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
  214. \OC_Template::printErrorPage($l->t('File is currently busy, please try again later'), $hint, 200);
  215. } catch (\OCP\Files\ForbiddenException $ex) {
  216. self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
  217. OC::$server->getLogger()->logException($ex);
  218. $l = \OC::$server->getL10N('lib');
  219. \OC_Template::printErrorPage($l->t('Cannot download file'), $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 $fileSize
  234. * @return array $rangeArray ('from'=>int,'to'=>int), ...
  235. */
  236. private static function parseHttpRangeHeader($rangeHeaderPos, $fileSize) {
  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 = \OC::$server->query(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. }