files.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  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. set_time_limit(0);
  135. if ($getType === self::ZIP_FILES) {
  136. foreach ($files as $file) {
  137. $file = $dir . '/' . $file;
  138. if (\OC\Files\Filesystem::is_file($file)) {
  139. $fileSize = \OC\Files\Filesystem::filesize($file);
  140. $fh = \OC\Files\Filesystem::fopen($file, 'r');
  141. $streamer->addFileFromStream($fh, basename($file), $fileSize);
  142. fclose($fh);
  143. } elseif (\OC\Files\Filesystem::is_dir($file)) {
  144. $streamer->addDirRecursive($file);
  145. }
  146. }
  147. } elseif ($getType === self::ZIP_DIR) {
  148. $file = $dir . '/' . $files;
  149. $streamer->addDirRecursive($file);
  150. }
  151. $streamer->finalize();
  152. set_time_limit($executionTime);
  153. self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
  154. } catch (\OCP\Lock\LockedException $ex) {
  155. self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
  156. OC::$server->getLogger()->logException($ex);
  157. $l = \OC::$server->getL10N('core');
  158. $hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
  159. \OC_Template::printErrorPage($l->t('File is currently busy, please try again later'), $hint);
  160. } catch (\OCP\Files\ForbiddenException $ex) {
  161. self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
  162. OC::$server->getLogger()->logException($ex);
  163. $l = \OC::$server->getL10N('core');
  164. \OC_Template::printErrorPage($l->t('Can\'t read file'), $ex->getMessage());
  165. } catch (\Exception $ex) {
  166. self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
  167. OC::$server->getLogger()->logException($ex);
  168. $l = \OC::$server->getL10N('core');
  169. $hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
  170. \OC_Template::printErrorPage($l->t('Can\'t read file'), $hint);
  171. }
  172. }
  173. /**
  174. * @param string $rangeHeaderPos
  175. * @param int $fileSize
  176. * @return array $rangeArray ('from'=>int,'to'=>int), ...
  177. */
  178. private static function parseHttpRangeHeader($rangeHeaderPos, $fileSize) {
  179. $rArray=explode(',', $rangeHeaderPos);
  180. $minOffset = 0;
  181. $ind = 0;
  182. $rangeArray = array();
  183. foreach ($rArray as $value) {
  184. $ranges = explode('-', $value);
  185. if (is_numeric($ranges[0])) {
  186. if ($ranges[0] < $minOffset) { // case: bytes=500-700,601-999
  187. $ranges[0] = $minOffset;
  188. }
  189. if ($ind > 0 && $rangeArray[$ind-1]['to']+1 == $ranges[0]) { // case: bytes=500-600,601-999
  190. $ind--;
  191. $ranges[0] = $rangeArray[$ind]['from'];
  192. }
  193. }
  194. if (is_numeric($ranges[0]) && is_numeric($ranges[1]) && $ranges[0] < $fileSize && $ranges[0] <= $ranges[1]) {
  195. // case: x-x
  196. if ($ranges[1] >= $fileSize) {
  197. $ranges[1] = $fileSize-1;
  198. }
  199. $rangeArray[$ind++] = array( 'from' => $ranges[0], 'to' => $ranges[1], 'size' => $fileSize );
  200. $minOffset = $ranges[1] + 1;
  201. if ($minOffset >= $fileSize) {
  202. break;
  203. }
  204. }
  205. elseif (is_numeric($ranges[0]) && $ranges[0] < $fileSize) {
  206. // case: x-
  207. $rangeArray[$ind++] = array( 'from' => $ranges[0], 'to' => $fileSize-1, 'size' => $fileSize );
  208. break;
  209. }
  210. elseif (is_numeric($ranges[1])) {
  211. // case: -x
  212. if ($ranges[1] > $fileSize) {
  213. $ranges[1] = $fileSize;
  214. }
  215. $rangeArray[$ind++] = array( 'from' => $fileSize-$ranges[1], 'to' => $fileSize-1, 'size' => $fileSize );
  216. break;
  217. }
  218. }
  219. return $rangeArray;
  220. }
  221. /**
  222. * @param View $view
  223. * @param string $name
  224. * @param string $dir
  225. * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header
  226. */
  227. private static function getSingleFile($view, $dir, $name, $params) {
  228. $filename = $dir . '/' . $name;
  229. OC_Util::obEnd();
  230. $view->lockFile($filename, ILockingProvider::LOCK_SHARED);
  231. $rangeArray = array();
  232. if (isset($params['range']) && substr($params['range'], 0, 6) === 'bytes=') {
  233. $rangeArray = self::parseHttpRangeHeader(substr($params['range'], 6),
  234. \OC\Files\Filesystem::filesize($filename));
  235. }
  236. if (\OC\Files\Filesystem::isReadable($filename)) {
  237. self::sendHeaders($filename, $name, $rangeArray);
  238. } elseif (!\OC\Files\Filesystem::file_exists($filename)) {
  239. header("HTTP/1.0 404 Not Found");
  240. $tmpl = new OC_Template('', '404', 'guest');
  241. $tmpl->printPage();
  242. exit();
  243. } else {
  244. header("HTTP/1.0 403 Forbidden");
  245. die('403 Forbidden');
  246. }
  247. if (isset($params['head']) && $params['head']) {
  248. return;
  249. }
  250. if (!empty($rangeArray)) {
  251. try {
  252. if (count($rangeArray) == 1) {
  253. $view->readfilePart($filename, $rangeArray[0]['from'], $rangeArray[0]['to']);
  254. }
  255. else {
  256. // check if file is seekable (if not throw UnseekableException)
  257. // we have to check it before body contents
  258. $view->readfilePart($filename, $rangeArray[0]['size'], $rangeArray[0]['size']);
  259. $type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename));
  260. foreach ($rangeArray as $range) {
  261. echo "\r\n--".self::getBoundary()."\r\n".
  262. "Content-type: ".$type."\r\n".
  263. "Content-range: bytes ".$range['from']."-".$range['to']."/".$range['size']."\r\n\r\n";
  264. $view->readfilePart($filename, $range['from'], $range['to']);
  265. }
  266. echo "\r\n--".self::getBoundary()."--\r\n";
  267. }
  268. } catch (\OCP\Files\UnseekableException $ex) {
  269. // file is unseekable
  270. header_remove('Accept-Ranges');
  271. header_remove('Content-Range');
  272. header("HTTP/1.1 200 OK");
  273. self::sendHeaders($filename, $name, array());
  274. $view->readfile($filename);
  275. }
  276. }
  277. else {
  278. $view->readfile($filename);
  279. }
  280. }
  281. /**
  282. * @param View $view
  283. * @param string $dir
  284. * @param string[]|string $files
  285. */
  286. public static function lockFiles($view, $dir, $files) {
  287. if (!is_array($files)) {
  288. $file = $dir . '/' . $files;
  289. $files = [$file];
  290. }
  291. foreach ($files as $file) {
  292. $file = $dir . '/' . $file;
  293. $view->lockFile($file, ILockingProvider::LOCK_SHARED);
  294. if ($view->is_dir($file)) {
  295. $contents = $view->getDirectoryContent($file);
  296. $contents = array_map(function($fileInfo) use ($file) {
  297. /** @var \OCP\Files\FileInfo $fileInfo */
  298. return $file . '/' . $fileInfo->getName();
  299. }, $contents);
  300. self::lockFiles($view, $dir, $contents);
  301. }
  302. }
  303. }
  304. /**
  305. * set the maximum upload size limit for apache hosts using .htaccess
  306. *
  307. * @param int $size file size in bytes
  308. * @param array $files override '.htaccess' and '.user.ini' locations
  309. * @return bool false on failure, size on success
  310. */
  311. public static function setUploadLimit($size, $files = []) {
  312. //don't allow user to break his config
  313. $size = intval($size);
  314. if ($size < self::UPLOAD_MIN_LIMIT_BYTES) {
  315. return false;
  316. }
  317. $size = OC_Helper::phpFileSize($size);
  318. $phpValueKeys = array(
  319. 'upload_max_filesize',
  320. 'post_max_size'
  321. );
  322. // default locations if not overridden by $files
  323. $files = array_merge([
  324. '.htaccess' => OC::$SERVERROOT . '/.htaccess',
  325. '.user.ini' => OC::$SERVERROOT . '/.user.ini'
  326. ], $files);
  327. $updateFiles = [
  328. $files['.htaccess'] => [
  329. 'pattern' => '/php_value %1$s (\S)*/',
  330. 'setting' => 'php_value %1$s %2$s'
  331. ],
  332. $files['.user.ini'] => [
  333. 'pattern' => '/%1$s=(\S)*/',
  334. 'setting' => '%1$s=%2$s'
  335. ]
  336. ];
  337. $success = true;
  338. foreach ($updateFiles as $filename => $patternMap) {
  339. // suppress warnings from fopen()
  340. $handle = @fopen($filename, 'r+');
  341. if (!$handle) {
  342. \OCP\Util::writeLog('files',
  343. 'Can\'t write upload limit to ' . $filename . '. Please check the file permissions',
  344. \OCP\Util::WARN);
  345. $success = false;
  346. continue; // try to update as many files as possible
  347. }
  348. $content = '';
  349. while (!feof($handle)) {
  350. $content .= fread($handle, 1000);
  351. }
  352. foreach ($phpValueKeys as $key) {
  353. $pattern = vsprintf($patternMap['pattern'], [$key]);
  354. $setting = vsprintf($patternMap['setting'], [$key, $size]);
  355. $hasReplaced = 0;
  356. $newContent = preg_replace($pattern, $setting, $content, 2, $hasReplaced);
  357. if ($newContent !== null) {
  358. $content = $newContent;
  359. }
  360. if ($hasReplaced === 0) {
  361. $content .= "\n" . $setting;
  362. }
  363. }
  364. // write file back
  365. ftruncate($handle, 0);
  366. rewind($handle);
  367. fwrite($handle, $content);
  368. fclose($handle);
  369. }
  370. if ($success) {
  371. return OC_Helper::computerFileSize($size);
  372. }
  373. return false;
  374. }
  375. /**
  376. * @param string $dir
  377. * @param $files
  378. * @param integer $getType
  379. * @param View $view
  380. * @param string $filename
  381. */
  382. private static function unlockAllTheFiles($dir, $files, $getType, $view, $filename) {
  383. if ($getType === self::FILE) {
  384. $view->unlockFile($filename, ILockingProvider::LOCK_SHARED);
  385. }
  386. if ($getType === self::ZIP_FILES) {
  387. foreach ($files as $file) {
  388. $file = $dir . '/' . $file;
  389. $view->unlockFile($file, ILockingProvider::LOCK_SHARED);
  390. }
  391. }
  392. if ($getType === self::ZIP_DIR) {
  393. $file = $dir . '/' . $files;
  394. $view->unlockFile($file, ILockingProvider::LOCK_SHARED);
  395. }
  396. }
  397. }