Local.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author aler9 <46489434+aler9@users.noreply.github.com>
  6. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  7. * @author Bart Visscher <bartv@thisnet.nl>
  8. * @author Boris Rybalkin <ribalkin@gmail.com>
  9. * @author Brice Maron <brice@bmaron.net>
  10. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  11. * @author J0WI <J0WI@users.noreply.github.com>
  12. * @author Jakob Sack <mail@jakobsack.de>
  13. * @author Joas Schilling <coding@schilljs.com>
  14. * @author Johannes Leuker <j.leuker@hosting.de>
  15. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  16. * @author Klaas Freitag <freitag@owncloud.com>
  17. * @author Lukas Reschke <lukas@statuscode.ch>
  18. * @author Martin Brugnara <martin@0x6d62.eu>
  19. * @author Michael Gapczynski <GapczynskiM@gmail.com>
  20. * @author Morris Jobke <hey@morrisjobke.de>
  21. * @author Robin Appelman <robin@icewind.nl>
  22. * @author Roeland Jago Douma <roeland@famdouma.nl>
  23. * @author Sjors van der Pluijm <sjors@desjors.nl>
  24. * @author Stefan Weil <sw@weilnetz.de>
  25. * @author Thomas Müller <thomas.mueller@tmit.eu>
  26. * @author Tigran Mkrtchyan <tigran.mkrtchyan@desy.de>
  27. * @author Vincent Petry <vincent@nextcloud.com>
  28. *
  29. * @license AGPL-3.0
  30. *
  31. * This code is free software: you can redistribute it and/or modify
  32. * it under the terms of the GNU Affero General Public License, version 3,
  33. * as published by the Free Software Foundation.
  34. *
  35. * This program is distributed in the hope that it will be useful,
  36. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  37. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  38. * GNU Affero General Public License for more details.
  39. *
  40. * You should have received a copy of the GNU Affero General Public License, version 3,
  41. * along with this program. If not, see <http://www.gnu.org/licenses/>
  42. *
  43. */
  44. namespace OC\Files\Storage;
  45. use OC\Files\Filesystem;
  46. use OC\Files\Storage\Wrapper\Encryption;
  47. use OC\Files\Storage\Wrapper\Jail;
  48. use OCP\Constants;
  49. use OCP\Files\ForbiddenException;
  50. use OCP\Files\GenericFileException;
  51. use OCP\Files\IMimeTypeDetector;
  52. use OCP\Files\Storage\IStorage;
  53. use OCP\IConfig;
  54. use OCP\Util;
  55. use Psr\Log\LoggerInterface;
  56. /**
  57. * for local filestore, we only have to map the paths
  58. */
  59. class Local extends \OC\Files\Storage\Common {
  60. protected $datadir;
  61. protected $dataDirLength;
  62. protected $realDataDir;
  63. private IConfig $config;
  64. private IMimeTypeDetector $mimeTypeDetector;
  65. private $defUMask;
  66. protected bool $unlinkOnTruncate;
  67. public function __construct($arguments) {
  68. if (!isset($arguments['datadir']) || !is_string($arguments['datadir'])) {
  69. throw new \InvalidArgumentException('No data directory set for local storage');
  70. }
  71. $this->datadir = str_replace('//', '/', $arguments['datadir']);
  72. // some crazy code uses a local storage on root...
  73. if ($this->datadir === '/') {
  74. $this->realDataDir = $this->datadir;
  75. } else {
  76. $realPath = realpath($this->datadir) ?: $this->datadir;
  77. $this->realDataDir = rtrim($realPath, '/') . '/';
  78. }
  79. if (substr($this->datadir, -1) !== '/') {
  80. $this->datadir .= '/';
  81. }
  82. $this->dataDirLength = strlen($this->realDataDir);
  83. $this->config = \OC::$server->get(IConfig::class);
  84. $this->mimeTypeDetector = \OC::$server->get(IMimeTypeDetector::class);
  85. $this->defUMask = $this->config->getSystemValue('localstorage.umask', 0022);
  86. // support Write-Once-Read-Many file systems
  87. $this->unlinkOnTruncate = $this->config->getSystemValueBool('localstorage.unlink_on_truncate', false);
  88. }
  89. public function __destruct() {
  90. }
  91. public function getId() {
  92. return 'local::' . $this->datadir;
  93. }
  94. public function mkdir($path) {
  95. $sourcePath = $this->getSourcePath($path);
  96. $oldMask = umask($this->defUMask);
  97. $result = @mkdir($sourcePath, 0777, true);
  98. umask($oldMask);
  99. return $result;
  100. }
  101. public function rmdir($path) {
  102. if (!$this->isDeletable($path)) {
  103. return false;
  104. }
  105. try {
  106. $it = new \RecursiveIteratorIterator(
  107. new \RecursiveDirectoryIterator($this->getSourcePath($path)),
  108. \RecursiveIteratorIterator::CHILD_FIRST
  109. );
  110. /**
  111. * RecursiveDirectoryIterator on an NFS path isn't iterable with foreach
  112. * This bug is fixed in PHP 5.5.9 or before
  113. * See #8376
  114. */
  115. $it->rewind();
  116. while ($it->valid()) {
  117. /**
  118. * @var \SplFileInfo $file
  119. */
  120. $file = $it->current();
  121. clearstatcache(true, $this->getSourcePath($file));
  122. if (in_array($file->getBasename(), ['.', '..'])) {
  123. $it->next();
  124. continue;
  125. } elseif ($file->isFile() || $file->isLink()) {
  126. unlink($file->getPathname());
  127. } elseif ($file->isDir()) {
  128. rmdir($file->getPathname());
  129. }
  130. $it->next();
  131. }
  132. clearstatcache(true, $this->getSourcePath($path));
  133. return rmdir($this->getSourcePath($path));
  134. } catch (\UnexpectedValueException $e) {
  135. return false;
  136. }
  137. }
  138. public function opendir($path) {
  139. return opendir($this->getSourcePath($path));
  140. }
  141. public function is_dir($path) {
  142. if (substr($path, -1) == '/') {
  143. $path = substr($path, 0, -1);
  144. }
  145. return is_dir($this->getSourcePath($path));
  146. }
  147. public function is_file($path) {
  148. return is_file($this->getSourcePath($path));
  149. }
  150. public function stat($path) {
  151. $fullPath = $this->getSourcePath($path);
  152. clearstatcache(true, $fullPath);
  153. if (!file_exists($fullPath)) {
  154. return false;
  155. }
  156. $statResult = @stat($fullPath);
  157. if (PHP_INT_SIZE === 4 && $statResult && !$this->is_dir($path)) {
  158. $filesize = $this->filesize($path);
  159. $statResult['size'] = $filesize;
  160. $statResult[7] = $filesize;
  161. }
  162. if (is_array($statResult)) {
  163. $statResult['full_path'] = $fullPath;
  164. }
  165. return $statResult;
  166. }
  167. /**
  168. * @inheritdoc
  169. */
  170. public function getMetaData($path) {
  171. try {
  172. $stat = $this->stat($path);
  173. } catch (ForbiddenException $e) {
  174. return null;
  175. }
  176. if (!$stat) {
  177. return null;
  178. }
  179. $permissions = Constants::PERMISSION_SHARE;
  180. $statPermissions = $stat['mode'];
  181. $isDir = ($statPermissions & 0x4000) === 0x4000 && !($statPermissions & 0x8000);
  182. if ($statPermissions & 0x0100) {
  183. $permissions += Constants::PERMISSION_READ;
  184. }
  185. if ($statPermissions & 0x0080) {
  186. $permissions += Constants::PERMISSION_UPDATE;
  187. if ($isDir) {
  188. $permissions += Constants::PERMISSION_CREATE;
  189. }
  190. }
  191. if (!($path === '' || $path === '/')) { // deletable depends on the parents unix permissions
  192. $parent = dirname($stat['full_path']);
  193. if (is_writable($parent)) {
  194. $permissions += Constants::PERMISSION_DELETE;
  195. }
  196. }
  197. $data = [];
  198. $data['mimetype'] = $isDir ? 'httpd/unix-directory' : $this->mimeTypeDetector->detectPath($path);
  199. $data['mtime'] = $stat['mtime'];
  200. if ($data['mtime'] === false) {
  201. $data['mtime'] = time();
  202. }
  203. if ($isDir) {
  204. $data['size'] = -1; //unknown
  205. } else {
  206. $data['size'] = $stat['size'];
  207. }
  208. $data['etag'] = $this->calculateEtag($path, $stat);
  209. $data['storage_mtime'] = $data['mtime'];
  210. $data['permissions'] = $permissions;
  211. $data['name'] = basename($path);
  212. return $data;
  213. }
  214. public function filetype($path) {
  215. $filetype = filetype($this->getSourcePath($path));
  216. if ($filetype == 'link') {
  217. $filetype = filetype(realpath($this->getSourcePath($path)));
  218. }
  219. return $filetype;
  220. }
  221. public function filesize($path): false|int|float {
  222. if (!$this->is_file($path)) {
  223. return 0;
  224. }
  225. $fullPath = $this->getSourcePath($path);
  226. if (PHP_INT_SIZE === 4) {
  227. $helper = new \OC\LargeFileHelper;
  228. return $helper->getFileSize($fullPath);
  229. }
  230. return filesize($fullPath);
  231. }
  232. public function isReadable($path) {
  233. return is_readable($this->getSourcePath($path));
  234. }
  235. public function isUpdatable($path) {
  236. return is_writable($this->getSourcePath($path));
  237. }
  238. public function file_exists($path) {
  239. return file_exists($this->getSourcePath($path));
  240. }
  241. public function filemtime($path) {
  242. $fullPath = $this->getSourcePath($path);
  243. clearstatcache(true, $fullPath);
  244. if (!$this->file_exists($path)) {
  245. return false;
  246. }
  247. if (PHP_INT_SIZE === 4) {
  248. $helper = new \OC\LargeFileHelper();
  249. return $helper->getFileMtime($fullPath);
  250. }
  251. return filemtime($fullPath);
  252. }
  253. public function touch($path, $mtime = null) {
  254. // sets the modification time of the file to the given value.
  255. // If mtime is nil the current time is set.
  256. // note that the access time of the file always changes to the current time.
  257. if ($this->file_exists($path) and !$this->isUpdatable($path)) {
  258. return false;
  259. }
  260. $oldMask = umask($this->defUMask);
  261. if (!is_null($mtime)) {
  262. $result = @touch($this->getSourcePath($path), $mtime);
  263. } else {
  264. $result = @touch($this->getSourcePath($path));
  265. }
  266. umask($oldMask);
  267. if ($result) {
  268. clearstatcache(true, $this->getSourcePath($path));
  269. }
  270. return $result;
  271. }
  272. public function file_get_contents($path) {
  273. return file_get_contents($this->getSourcePath($path));
  274. }
  275. public function file_put_contents($path, $data) {
  276. $oldMask = umask($this->defUMask);
  277. if ($this->unlinkOnTruncate) {
  278. $this->unlink($path);
  279. }
  280. $result = file_put_contents($this->getSourcePath($path), $data);
  281. umask($oldMask);
  282. return $result;
  283. }
  284. public function unlink($path) {
  285. if ($this->is_dir($path)) {
  286. return $this->rmdir($path);
  287. } elseif ($this->is_file($path)) {
  288. return unlink($this->getSourcePath($path));
  289. } else {
  290. return false;
  291. }
  292. }
  293. private function checkTreeForForbiddenItems(string $path) {
  294. $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path));
  295. foreach ($iterator as $file) {
  296. /** @var \SplFileInfo $file */
  297. if (Filesystem::isFileBlacklisted($file->getBasename())) {
  298. throw new ForbiddenException('Invalid path: ' . $file->getPathname(), false);
  299. }
  300. }
  301. }
  302. public function rename($source, $target): bool {
  303. $srcParent = dirname($source);
  304. $dstParent = dirname($target);
  305. if (!$this->isUpdatable($srcParent)) {
  306. \OC::$server->get(LoggerInterface::class)->error('unable to rename, source directory is not writable : ' . $srcParent, ['app' => 'core']);
  307. return false;
  308. }
  309. if (!$this->isUpdatable($dstParent)) {
  310. \OC::$server->get(LoggerInterface::class)->error('unable to rename, destination directory is not writable : ' . $dstParent, ['app' => 'core']);
  311. return false;
  312. }
  313. if (!$this->file_exists($source)) {
  314. \OC::$server->get(LoggerInterface::class)->error('unable to rename, file does not exists : ' . $source, ['app' => 'core']);
  315. return false;
  316. }
  317. if ($this->is_dir($target)) {
  318. $this->rmdir($target);
  319. } elseif ($this->is_file($target)) {
  320. $this->unlink($target);
  321. }
  322. if ($this->is_dir($source)) {
  323. $this->checkTreeForForbiddenItems($this->getSourcePath($source));
  324. }
  325. if (@rename($this->getSourcePath($source), $this->getSourcePath($target))) {
  326. return true;
  327. }
  328. return $this->copy($source, $target) && $this->rmdir($source);
  329. }
  330. public function copy($source, $target) {
  331. if ($this->is_dir($source)) {
  332. return parent::copy($source, $target);
  333. } else {
  334. $oldMask = umask($this->defUMask);
  335. if ($this->unlinkOnTruncate) {
  336. $this->unlink($target);
  337. }
  338. $result = copy($this->getSourcePath($source), $this->getSourcePath($target));
  339. umask($oldMask);
  340. return $result;
  341. }
  342. }
  343. public function fopen($path, $mode) {
  344. $sourcePath = $this->getSourcePath($path);
  345. if (!file_exists($sourcePath) && $mode === 'r') {
  346. return false;
  347. }
  348. $oldMask = umask($this->defUMask);
  349. if (($mode === 'w' || $mode === 'w+') && $this->unlinkOnTruncate) {
  350. $this->unlink($path);
  351. }
  352. $result = @fopen($sourcePath, $mode);
  353. umask($oldMask);
  354. return $result;
  355. }
  356. public function hash($type, $path, $raw = false) {
  357. return hash_file($type, $this->getSourcePath($path), $raw);
  358. }
  359. public function free_space($path) {
  360. $sourcePath = $this->getSourcePath($path);
  361. // using !is_dir because $sourcePath might be a part file or
  362. // non-existing file, so we'd still want to use the parent dir
  363. // in such cases
  364. if (!is_dir($sourcePath)) {
  365. // disk_free_space doesn't work on files
  366. $sourcePath = dirname($sourcePath);
  367. }
  368. $space = (function_exists('disk_free_space') && is_dir($sourcePath)) ? disk_free_space($sourcePath) : false;
  369. if ($space === false || is_null($space)) {
  370. return \OCP\Files\FileInfo::SPACE_UNKNOWN;
  371. }
  372. return Util::numericToNumber($space);
  373. }
  374. public function search($query) {
  375. return $this->searchInDir($query);
  376. }
  377. public function getLocalFile($path) {
  378. return $this->getSourcePath($path);
  379. }
  380. /**
  381. * @param string $query
  382. * @param string $dir
  383. * @return array
  384. */
  385. protected function searchInDir($query, $dir = '') {
  386. $files = [];
  387. $physicalDir = $this->getSourcePath($dir);
  388. foreach (scandir($physicalDir) as $item) {
  389. if (\OC\Files\Filesystem::isIgnoredDir($item)) {
  390. continue;
  391. }
  392. $physicalItem = $physicalDir . '/' . $item;
  393. if (strstr(strtolower($item), strtolower($query)) !== false) {
  394. $files[] = $dir . '/' . $item;
  395. }
  396. if (is_dir($physicalItem)) {
  397. $files = array_merge($files, $this->searchInDir($query, $dir . '/' . $item));
  398. }
  399. }
  400. return $files;
  401. }
  402. /**
  403. * check if a file or folder has been updated since $time
  404. *
  405. * @param string $path
  406. * @param int $time
  407. * @return bool
  408. */
  409. public function hasUpdated($path, $time) {
  410. if ($this->file_exists($path)) {
  411. return $this->filemtime($path) > $time;
  412. } else {
  413. return true;
  414. }
  415. }
  416. /**
  417. * Get the source path (on disk) of a given path
  418. *
  419. * @param string $path
  420. * @return string
  421. * @throws ForbiddenException
  422. */
  423. public function getSourcePath($path) {
  424. if (Filesystem::isFileBlacklisted($path)) {
  425. throw new ForbiddenException('Invalid path: ' . $path, false);
  426. }
  427. $fullPath = $this->datadir . $path;
  428. $currentPath = $path;
  429. $allowSymlinks = $this->config->getSystemValueBool('localstorage.allowsymlinks', false);
  430. if ($allowSymlinks || $currentPath === '') {
  431. return $fullPath;
  432. }
  433. $pathToResolve = $fullPath;
  434. $realPath = realpath($pathToResolve);
  435. while ($realPath === false) { // for non existing files check the parent directory
  436. $currentPath = dirname($currentPath);
  437. if ($currentPath === '' || $currentPath === '.') {
  438. return $fullPath;
  439. }
  440. $realPath = realpath($this->datadir . $currentPath);
  441. }
  442. if ($realPath) {
  443. $realPath = $realPath . '/';
  444. }
  445. if (substr($realPath, 0, $this->dataDirLength) === $this->realDataDir) {
  446. return $fullPath;
  447. }
  448. \OC::$server->get(LoggerInterface::class)->error("Following symlinks is not allowed ('$fullPath' -> '$realPath' not inside '{$this->realDataDir}')", ['app' => 'core']);
  449. throw new ForbiddenException('Following symlinks is not allowed', false);
  450. }
  451. /**
  452. * {@inheritdoc}
  453. */
  454. public function isLocal() {
  455. return true;
  456. }
  457. /**
  458. * get the ETag for a file or folder
  459. *
  460. * @param string $path
  461. * @return string
  462. */
  463. public function getETag($path) {
  464. return $this->calculateEtag($path, $this->stat($path));
  465. }
  466. private function calculateEtag(string $path, array $stat): string {
  467. if ($stat['mode'] & 0x4000 && !($stat['mode'] & 0x8000)) { // is_dir & not socket
  468. return parent::getETag($path);
  469. } else {
  470. if ($stat === false) {
  471. return md5('');
  472. }
  473. $toHash = '';
  474. if (isset($stat['mtime'])) {
  475. $toHash .= $stat['mtime'];
  476. }
  477. if (isset($stat['ino'])) {
  478. $toHash .= $stat['ino'];
  479. }
  480. if (isset($stat['dev'])) {
  481. $toHash .= $stat['dev'];
  482. }
  483. if (isset($stat['size'])) {
  484. $toHash .= $stat['size'];
  485. }
  486. return md5($toHash);
  487. }
  488. }
  489. private function canDoCrossStorageMove(IStorage $sourceStorage) {
  490. return $sourceStorage->instanceOfStorage(Local::class)
  491. // Don't treat ACLStorageWrapper like local storage where copy can be done directly.
  492. // Instead, use the slower recursive copying in php from Common::copyFromStorage with
  493. // more permissions checks.
  494. && !$sourceStorage->instanceOfStorage('OCA\GroupFolders\ACL\ACLStorageWrapper')
  495. // when moving encrypted files we have to handle keys and the target might not be encrypted
  496. && !$sourceStorage->instanceOfStorage(Encryption::class);
  497. }
  498. /**
  499. * @param IStorage $sourceStorage
  500. * @param string $sourceInternalPath
  501. * @param string $targetInternalPath
  502. * @param bool $preserveMtime
  503. * @return bool
  504. */
  505. public function copyFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = false) {
  506. if ($this->canDoCrossStorageMove($sourceStorage)) {
  507. if ($sourceStorage->instanceOfStorage(Jail::class)) {
  508. /**
  509. * @var \OC\Files\Storage\Wrapper\Jail $sourceStorage
  510. */
  511. $sourceInternalPath = $sourceStorage->getUnjailedPath($sourceInternalPath);
  512. }
  513. /**
  514. * @var \OC\Files\Storage\Local $sourceStorage
  515. */
  516. $rootStorage = new Local(['datadir' => '/']);
  517. return $rootStorage->copy($sourceStorage->getSourcePath($sourceInternalPath), $this->getSourcePath($targetInternalPath));
  518. } else {
  519. return parent::copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
  520. }
  521. }
  522. /**
  523. * @param IStorage $sourceStorage
  524. * @param string $sourceInternalPath
  525. * @param string $targetInternalPath
  526. * @return bool
  527. */
  528. public function moveFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
  529. if ($this->canDoCrossStorageMove($sourceStorage)) {
  530. if ($sourceStorage->instanceOfStorage(Jail::class)) {
  531. /**
  532. * @var \OC\Files\Storage\Wrapper\Jail $sourceStorage
  533. */
  534. $sourceInternalPath = $sourceStorage->getUnjailedPath($sourceInternalPath);
  535. }
  536. /**
  537. * @var \OC\Files\Storage\Local $sourceStorage
  538. */
  539. $rootStorage = new Local(['datadir' => '/']);
  540. return $rootStorage->rename($sourceStorage->getSourcePath($sourceInternalPath), $this->getSourcePath($targetInternalPath));
  541. } else {
  542. return parent::moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
  543. }
  544. }
  545. public function writeStream(string $path, $stream, int $size = null): int {
  546. /** @var int|false $result We consider here that returned size will never be a float because we write less than 4GB */
  547. $result = $this->file_put_contents($path, $stream);
  548. if (is_resource($stream)) {
  549. fclose($stream);
  550. }
  551. if ($result === false) {
  552. throw new GenericFileException("Failed write stream to $path");
  553. } else {
  554. return $result;
  555. }
  556. }
  557. }