files.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Bart Visscher <bartv@thisnet.nl>
  7. * @author Björn Schießle <bjoern@schiessle.org>
  8. * @author Clark Tomlinson <fallen013@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 Lukas Reschke <lukas@statuscode.ch>
  14. * @author Michael Gapczynski <GapczynskiM@gmail.com>
  15. * @author Nicolai Ehemann <en@enlightened.de>
  16. * @author Piotr Filiciak <piotr@filiciak.pl>
  17. * @author Robin Appelman <robin@icewind.nl>
  18. * @author Robin McCorkell <robin@mccorkell.me.uk>
  19. * @author Thibaut GRIDEL <tgridel@free.fr>
  20. * @author Thomas Müller <thomas.mueller@tmit.eu>
  21. * @author Victor Dubiniuk <dubiniuk@owncloud.com>
  22. * @author Vincent Petry <pvince81@owncloud.com>
  23. *
  24. * @license AGPL-3.0
  25. *
  26. * This code is free software: you can redistribute it and/or modify
  27. * it under the terms of the GNU Affero General Public License, version 3,
  28. * as published by the Free Software Foundation.
  29. *
  30. * This program is distributed in the hope that it will be useful,
  31. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  32. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  33. * GNU Affero General Public License for more details.
  34. *
  35. * You should have received a copy of the GNU Affero General Public License, version 3,
  36. * along with this program. If not, see <http://www.gnu.org/licenses/>
  37. *
  38. */
  39. use OC\Files\View;
  40. use OC\Streamer;
  41. use OCP\Lock\ILockingProvider;
  42. /**
  43. * Class for file server access
  44. *
  45. */
  46. class OC_Files {
  47. const FILE = 1;
  48. const ZIP_FILES = 2;
  49. const ZIP_DIR = 3;
  50. const UPLOAD_MIN_LIMIT_BYTES = 1048576; // 1 MiB
  51. private static $multipartBoundary = '';
  52. /**
  53. * @return string
  54. */
  55. private static function getBoundary() {
  56. if (empty(self::$multipartBoundary)) {
  57. self::$multipartBoundary = md5(mt_rand());
  58. }
  59. return self::$multipartBoundary;
  60. }
  61. /**
  62. * @param string $filename
  63. * @param string $name
  64. * @param array $rangeArray ('from'=>int,'to'=>int), ...
  65. */
  66. private static function sendHeaders($filename, $name, array $rangeArray) {
  67. OC_Response::setContentDispositionHeader($name, 'attachment');
  68. header('Content-Transfer-Encoding: binary', true);
  69. OC_Response::disableCaching();
  70. $fileSize = \OC\Files\Filesystem::filesize($filename);
  71. $type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename));
  72. if ($fileSize > -1) {
  73. if (!empty($rangeArray)) {
  74. header('HTTP/1.1 206 Partial Content', true);
  75. header('Accept-Ranges: bytes', true);
  76. if (count($rangeArray) > 1) {
  77. $type = 'multipart/byteranges; boundary='.self::getBoundary();
  78. // no Content-Length header here
  79. }
  80. else {
  81. header(sprintf('Content-Range: bytes %d-%d/%d', $rangeArray[0]['from'], $rangeArray[0]['to'], $fileSize), true);
  82. OC_Response::setContentLengthHeader($rangeArray[0]['to'] - $rangeArray[0]['from'] + 1);
  83. }
  84. }
  85. else {
  86. OC_Response::setContentLengthHeader($fileSize);
  87. }
  88. }
  89. header('Content-Type: '.$type, true);
  90. }
  91. /**
  92. * return the content of a file or return a zip file containing multiple files
  93. *
  94. * @param string $dir
  95. * @param string $files ; separated list of files to download
  96. * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header
  97. */
  98. public static function get($dir, $files, $params = null) {
  99. $view = \OC\Files\Filesystem::getView();
  100. $getType = self::FILE;
  101. $filename = $dir;
  102. try {
  103. if (is_array($files) && count($files) === 1) {
  104. $files = $files[0];
  105. }
  106. if (!is_array($files)) {
  107. $filename = $dir . '/' . $files;
  108. if (!$view->is_dir($filename)) {
  109. self::getSingleFile($view, $dir, $files, is_null($params) ? array() : $params);
  110. return;
  111. }
  112. }
  113. $name = 'download';
  114. if (is_array($files)) {
  115. $getType = self::ZIP_FILES;
  116. $basename = basename($dir);
  117. if ($basename) {
  118. $name = $basename;
  119. }
  120. $filename = $dir . '/' . $name;
  121. } else {
  122. $filename = $dir . '/' . $files;
  123. $getType = self::ZIP_DIR;
  124. // downloading root ?
  125. if ($files !== '') {
  126. $name = $files;
  127. }
  128. }
  129. $streamer = new Streamer();
  130. OC_Util::obEnd();
  131. self::lockFiles($view, $dir, $files);
  132. $streamer->sendHeaders($name);
  133. $executionTime = intval(OC::$server->getIniWrapper()->getNumeric('max_execution_time'));
  134. if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
  135. @set_time_limit(0);
  136. }
  137. ignore_user_abort(true);
  138. if ($getType === self::ZIP_FILES) {
  139. foreach ($files as $file) {
  140. $file = $dir . '/' . $file;
  141. if (\OC\Files\Filesystem::is_file($file)) {
  142. $fileSize = \OC\Files\Filesystem::filesize($file);
  143. $fileTime = \OC\Files\Filesystem::filemtime($file);
  144. $fh = \OC\Files\Filesystem::fopen($file, 'r');
  145. $streamer->addFileFromStream($fh, basename($file), $fileSize, $fileTime);
  146. fclose($fh);
  147. } elseif (\OC\Files\Filesystem::is_dir($file)) {
  148. $streamer->addDirRecursive($file);
  149. }
  150. }
  151. } elseif ($getType === self::ZIP_DIR) {
  152. $file = $dir . '/' . $files;
  153. $streamer->addDirRecursive($file);
  154. }
  155. $streamer->finalize();
  156. set_time_limit($executionTime);
  157. self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
  158. } catch (\OCP\Lock\LockedException $ex) {
  159. self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
  160. OC::$server->getLogger()->logException($ex);
  161. $l = \OC::$server->getL10N('core');
  162. $hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
  163. \OC_Template::printErrorPage($l->t('File is currently busy, please try again later'), $hint);
  164. } catch (\OCP\Files\ForbiddenException $ex) {
  165. self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
  166. OC::$server->getLogger()->logException($ex);
  167. $l = \OC::$server->getL10N('core');
  168. \OC_Template::printErrorPage($l->t('Can\'t read file'), $ex->getMessage());
  169. } catch (\Exception $ex) {
  170. self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
  171. OC::$server->getLogger()->logException($ex);
  172. $l = \OC::$server->getL10N('core');
  173. $hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
  174. \OC_Template::printErrorPage($l->t('Can\'t read file'), $hint);
  175. }
  176. }
  177. /**
  178. * @param string $rangeHeaderPos
  179. * @param int $fileSize
  180. * @return array $rangeArray ('from'=>int,'to'=>int), ...
  181. */
  182. private static function parseHttpRangeHeader($rangeHeaderPos, $fileSize) {
  183. $rArray=explode(',', $rangeHeaderPos);
  184. $minOffset = 0;
  185. $ind = 0;
  186. $rangeArray = array();
  187. foreach ($rArray as $value) {
  188. $ranges = explode('-', $value);
  189. if (is_numeric($ranges[0])) {
  190. if ($ranges[0] < $minOffset) { // case: bytes=500-700,601-999
  191. $ranges[0] = $minOffset;
  192. }
  193. if ($ind > 0 && $rangeArray[$ind-1]['to']+1 == $ranges[0]) { // case: bytes=500-600,601-999
  194. $ind--;
  195. $ranges[0] = $rangeArray[$ind]['from'];
  196. }
  197. }
  198. if (is_numeric($ranges[0]) && is_numeric($ranges[1]) && $ranges[0] < $fileSize && $ranges[0] <= $ranges[1]) {
  199. // case: x-x
  200. if ($ranges[1] >= $fileSize) {
  201. $ranges[1] = $fileSize-1;
  202. }
  203. $rangeArray[$ind++] = array( 'from' => $ranges[0], 'to' => $ranges[1], 'size' => $fileSize );
  204. $minOffset = $ranges[1] + 1;
  205. if ($minOffset >= $fileSize) {
  206. break;
  207. }
  208. }
  209. elseif (is_numeric($ranges[0]) && $ranges[0] < $fileSize) {
  210. // case: x-
  211. $rangeArray[$ind++] = array( 'from' => $ranges[0], 'to' => $fileSize-1, 'size' => $fileSize );
  212. break;
  213. }
  214. elseif (is_numeric($ranges[1])) {
  215. // case: -x
  216. if ($ranges[1] > $fileSize) {
  217. $ranges[1] = $fileSize;
  218. }
  219. $rangeArray[$ind++] = array( 'from' => $fileSize-$ranges[1], 'to' => $fileSize-1, 'size' => $fileSize );
  220. break;
  221. }
  222. }
  223. return $rangeArray;
  224. }
  225. /**
  226. * @param View $view
  227. * @param string $name
  228. * @param string $dir
  229. * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header
  230. */
  231. private static function getSingleFile($view, $dir, $name, $params) {
  232. $filename = $dir . '/' . $name;
  233. OC_Util::obEnd();
  234. $view->lockFile($filename, ILockingProvider::LOCK_SHARED);
  235. $rangeArray = array();
  236. if (isset($params['range']) && substr($params['range'], 0, 6) === 'bytes=') {
  237. $rangeArray = self::parseHttpRangeHeader(substr($params['range'], 6),
  238. \OC\Files\Filesystem::filesize($filename));
  239. }
  240. if (\OC\Files\Filesystem::isReadable($filename)) {
  241. self::sendHeaders($filename, $name, $rangeArray);
  242. } elseif (!\OC\Files\Filesystem::file_exists($filename)) {
  243. header("HTTP/1.1 404 Not Found");
  244. $tmpl = new OC_Template('', '404', 'guest');
  245. $tmpl->printPage();
  246. exit();
  247. } else {
  248. header("HTTP/1.1 403 Forbidden");
  249. die('403 Forbidden');
  250. }
  251. if (isset($params['head']) && $params['head']) {
  252. return;
  253. }
  254. if (!empty($rangeArray)) {
  255. try {
  256. if (count($rangeArray) == 1) {
  257. $view->readfilePart($filename, $rangeArray[0]['from'], $rangeArray[0]['to']);
  258. }
  259. else {
  260. // check if file is seekable (if not throw UnseekableException)
  261. // we have to check it before body contents
  262. $view->readfilePart($filename, $rangeArray[0]['size'], $rangeArray[0]['size']);
  263. $type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename));
  264. foreach ($rangeArray as $range) {
  265. echo "\r\n--".self::getBoundary()."\r\n".
  266. "Content-type: ".$type."\r\n".
  267. "Content-range: bytes ".$range['from']."-".$range['to']."/".$range['size']."\r\n\r\n";
  268. $view->readfilePart($filename, $range['from'], $range['to']);
  269. }
  270. echo "\r\n--".self::getBoundary()."--\r\n";
  271. }
  272. } catch (\OCP\Files\UnseekableException $ex) {
  273. // file is unseekable
  274. header_remove('Accept-Ranges');
  275. header_remove('Content-Range');
  276. header("HTTP/1.1 200 OK");
  277. self::sendHeaders($filename, $name, array());
  278. $view->readfile($filename);
  279. }
  280. }
  281. else {
  282. $view->readfile($filename);
  283. }
  284. }
  285. /**
  286. * @param View $view
  287. * @param string $dir
  288. * @param string[]|string $files
  289. */
  290. public static function lockFiles($view, $dir, $files) {
  291. if (!is_array($files)) {
  292. $file = $dir . '/' . $files;
  293. $files = [$file];
  294. }
  295. foreach ($files as $file) {
  296. $file = $dir . '/' . $file;
  297. $view->lockFile($file, ILockingProvider::LOCK_SHARED);
  298. if ($view->is_dir($file)) {
  299. $contents = $view->getDirectoryContent($file);
  300. $contents = array_map(function($fileInfo) use ($file) {
  301. /** @var \OCP\Files\FileInfo $fileInfo */
  302. return $file . '/' . $fileInfo->getName();
  303. }, $contents);
  304. self::lockFiles($view, $dir, $contents);
  305. }
  306. }
  307. }
  308. /**
  309. * set the maximum upload size limit for apache hosts using .htaccess
  310. *
  311. * @param int $size file size in bytes
  312. * @param array $files override '.htaccess' and '.user.ini' locations
  313. * @return bool false on failure, size on success
  314. */
  315. public static function setUploadLimit($size, $files = []) {
  316. //don't allow user to break his config
  317. $size = intval($size);
  318. if ($size < self::UPLOAD_MIN_LIMIT_BYTES) {
  319. return false;
  320. }
  321. $size = OC_Helper::phpFileSize($size);
  322. $phpValueKeys = array(
  323. 'upload_max_filesize',
  324. 'post_max_size'
  325. );
  326. // default locations if not overridden by $files
  327. $files = array_merge([
  328. '.htaccess' => OC::$SERVERROOT . '/.htaccess',
  329. '.user.ini' => OC::$SERVERROOT . '/.user.ini'
  330. ], $files);
  331. $updateFiles = [
  332. $files['.htaccess'] => [
  333. 'pattern' => '/php_value %1$s (\S)*/',
  334. 'setting' => 'php_value %1$s %2$s'
  335. ],
  336. $files['.user.ini'] => [
  337. 'pattern' => '/%1$s=(\S)*/',
  338. 'setting' => '%1$s=%2$s'
  339. ]
  340. ];
  341. $success = true;
  342. foreach ($updateFiles as $filename => $patternMap) {
  343. // suppress warnings from fopen()
  344. $handle = @fopen($filename, 'r+');
  345. if (!$handle) {
  346. \OCP\Util::writeLog('files',
  347. 'Can\'t write upload limit to ' . $filename . '. Please check the file permissions',
  348. \OCP\Util::WARN);
  349. $success = false;
  350. continue; // try to update as many files as possible
  351. }
  352. $content = '';
  353. while (!feof($handle)) {
  354. $content .= fread($handle, 1000);
  355. }
  356. foreach ($phpValueKeys as $key) {
  357. $pattern = vsprintf($patternMap['pattern'], [$key]);
  358. $setting = vsprintf($patternMap['setting'], [$key, $size]);
  359. $hasReplaced = 0;
  360. $newContent = preg_replace($pattern, $setting, $content, 2, $hasReplaced);
  361. if ($newContent !== null) {
  362. $content = $newContent;
  363. }
  364. if ($hasReplaced === 0) {
  365. $content .= "\n" . $setting;
  366. }
  367. }
  368. // write file back
  369. ftruncate($handle, 0);
  370. rewind($handle);
  371. fwrite($handle, $content);
  372. fclose($handle);
  373. }
  374. if ($success) {
  375. return OC_Helper::computerFileSize($size);
  376. }
  377. return false;
  378. }
  379. /**
  380. * @param string $dir
  381. * @param $files
  382. * @param integer $getType
  383. * @param View $view
  384. * @param string $filename
  385. */
  386. private static function unlockAllTheFiles($dir, $files, $getType, $view, $filename) {
  387. if ($getType === self::FILE) {
  388. $view->unlockFile($filename, ILockingProvider::LOCK_SHARED);
  389. }
  390. if ($getType === self::ZIP_FILES) {
  391. foreach ($files as $file) {
  392. $file = $dir . '/' . $file;
  393. $view->unlockFile($file, ILockingProvider::LOCK_SHARED);
  394. }
  395. }
  396. if ($getType === self::ZIP_DIR) {
  397. $file = $dir . '/' . $files;
  398. $view->unlockFile($file, ILockingProvider::LOCK_SHARED);
  399. }
  400. }
  401. }