Local.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC\Files\Storage;
  8. use OC\Files\Filesystem;
  9. use OC\Files\Storage\Wrapper\Encryption;
  10. use OC\Files\Storage\Wrapper\Jail;
  11. use OCP\Constants;
  12. use OCP\Files\ForbiddenException;
  13. use OCP\Files\GenericFileException;
  14. use OCP\Files\IMimeTypeDetector;
  15. use OCP\Files\Storage\IStorage;
  16. use OCP\Files\StorageNotAvailableException;
  17. use OCP\IConfig;
  18. use OCP\Util;
  19. use Psr\Log\LoggerInterface;
  20. /**
  21. * for local filestore, we only have to map the paths
  22. */
  23. class Local extends \OC\Files\Storage\Common {
  24. protected $datadir;
  25. protected $dataDirLength;
  26. protected $realDataDir;
  27. private IConfig $config;
  28. private IMimeTypeDetector $mimeTypeDetector;
  29. private $defUMask;
  30. protected bool $unlinkOnTruncate;
  31. protected bool $caseInsensitive = false;
  32. public function __construct($arguments) {
  33. if (!isset($arguments['datadir']) || !is_string($arguments['datadir'])) {
  34. throw new \InvalidArgumentException('No data directory set for local storage');
  35. }
  36. $this->datadir = str_replace('//', '/', $arguments['datadir']);
  37. // some crazy code uses a local storage on root...
  38. if ($this->datadir === '/') {
  39. $this->realDataDir = $this->datadir;
  40. } else {
  41. $realPath = realpath($this->datadir) ?: $this->datadir;
  42. $this->realDataDir = rtrim($realPath, '/') . '/';
  43. }
  44. if (!str_ends_with($this->datadir, '/')) {
  45. $this->datadir .= '/';
  46. }
  47. $this->dataDirLength = strlen($this->realDataDir);
  48. $this->config = \OC::$server->get(IConfig::class);
  49. $this->mimeTypeDetector = \OC::$server->get(IMimeTypeDetector::class);
  50. $this->defUMask = $this->config->getSystemValue('localstorage.umask', 0022);
  51. $this->caseInsensitive = $this->config->getSystemValueBool('localstorage.case_insensitive', false);
  52. // support Write-Once-Read-Many file systems
  53. $this->unlinkOnTruncate = $this->config->getSystemValueBool('localstorage.unlink_on_truncate', false);
  54. if (isset($arguments['isExternal']) && $arguments['isExternal'] && !$this->stat('')) {
  55. // data dir not accessible or available, can happen when using an external storage of type Local
  56. // on an unmounted system mount point
  57. throw new StorageNotAvailableException('Local storage path does not exist "' . $this->getSourcePath('') . '"');
  58. }
  59. }
  60. public function __destruct() {
  61. }
  62. public function getId() {
  63. return 'local::' . $this->datadir;
  64. }
  65. public function mkdir($path) {
  66. $sourcePath = $this->getSourcePath($path);
  67. $oldMask = umask($this->defUMask);
  68. $result = @mkdir($sourcePath, 0777, true);
  69. umask($oldMask);
  70. return $result;
  71. }
  72. public function rmdir($path) {
  73. if (!$this->isDeletable($path)) {
  74. return false;
  75. }
  76. try {
  77. $it = new \RecursiveIteratorIterator(
  78. new \RecursiveDirectoryIterator($this->getSourcePath($path)),
  79. \RecursiveIteratorIterator::CHILD_FIRST
  80. );
  81. /**
  82. * RecursiveDirectoryIterator on an NFS path isn't iterable with foreach
  83. * This bug is fixed in PHP 5.5.9 or before
  84. * See #8376
  85. */
  86. $it->rewind();
  87. while ($it->valid()) {
  88. /**
  89. * @var \SplFileInfo $file
  90. */
  91. $file = $it->current();
  92. clearstatcache(true, $file->getRealPath());
  93. if (in_array($file->getBasename(), ['.', '..'])) {
  94. $it->next();
  95. continue;
  96. } elseif ($file->isFile() || $file->isLink()) {
  97. unlink($file->getPathname());
  98. } elseif ($file->isDir()) {
  99. rmdir($file->getPathname());
  100. }
  101. $it->next();
  102. }
  103. unset($it); // Release iterator and thereby its potential directory lock (e.g. in case of VirtualBox shared folders)
  104. clearstatcache(true, $this->getSourcePath($path));
  105. return rmdir($this->getSourcePath($path));
  106. } catch (\UnexpectedValueException $e) {
  107. return false;
  108. }
  109. }
  110. public function opendir($path) {
  111. return opendir($this->getSourcePath($path));
  112. }
  113. public function is_dir($path) {
  114. if ($this->caseInsensitive && !$this->file_exists($path)) {
  115. return false;
  116. }
  117. if (str_ends_with($path, '/')) {
  118. $path = substr($path, 0, -1);
  119. }
  120. return is_dir($this->getSourcePath($path));
  121. }
  122. public function is_file($path) {
  123. if ($this->caseInsensitive && !$this->file_exists($path)) {
  124. return false;
  125. }
  126. return is_file($this->getSourcePath($path));
  127. }
  128. public function stat($path) {
  129. $fullPath = $this->getSourcePath($path);
  130. clearstatcache(true, $fullPath);
  131. if (!file_exists($fullPath)) {
  132. return false;
  133. }
  134. $statResult = @stat($fullPath);
  135. if (PHP_INT_SIZE === 4 && $statResult && !$this->is_dir($path)) {
  136. $filesize = $this->filesize($path);
  137. $statResult['size'] = $filesize;
  138. $statResult[7] = $filesize;
  139. }
  140. if (is_array($statResult)) {
  141. $statResult['full_path'] = $fullPath;
  142. }
  143. return $statResult;
  144. }
  145. /**
  146. * @inheritdoc
  147. */
  148. public function getMetaData($path) {
  149. try {
  150. $stat = $this->stat($path);
  151. } catch (ForbiddenException $e) {
  152. return null;
  153. }
  154. if (!$stat) {
  155. return null;
  156. }
  157. $permissions = Constants::PERMISSION_SHARE;
  158. $statPermissions = $stat['mode'];
  159. $isDir = ($statPermissions & 0x4000) === 0x4000 && !($statPermissions & 0x8000);
  160. if ($statPermissions & 0x0100) {
  161. $permissions += Constants::PERMISSION_READ;
  162. }
  163. if ($statPermissions & 0x0080) {
  164. $permissions += Constants::PERMISSION_UPDATE;
  165. if ($isDir) {
  166. $permissions += Constants::PERMISSION_CREATE;
  167. }
  168. }
  169. if (!($path === '' || $path === '/')) { // deletable depends on the parents unix permissions
  170. $parent = dirname($stat['full_path']);
  171. if (is_writable($parent)) {
  172. $permissions += Constants::PERMISSION_DELETE;
  173. }
  174. }
  175. $data = [];
  176. $data['mimetype'] = $isDir ? 'httpd/unix-directory' : $this->mimeTypeDetector->detectPath($path);
  177. $data['mtime'] = $stat['mtime'];
  178. if ($data['mtime'] === false) {
  179. $data['mtime'] = time();
  180. }
  181. if ($isDir) {
  182. $data['size'] = -1; //unknown
  183. } else {
  184. $data['size'] = $stat['size'];
  185. }
  186. $data['etag'] = $this->calculateEtag($path, $stat);
  187. $data['storage_mtime'] = $data['mtime'];
  188. $data['permissions'] = $permissions;
  189. $data['name'] = basename($path);
  190. return $data;
  191. }
  192. public function filetype($path) {
  193. $filetype = filetype($this->getSourcePath($path));
  194. if ($filetype == 'link') {
  195. $filetype = filetype(realpath($this->getSourcePath($path)));
  196. }
  197. return $filetype;
  198. }
  199. public function filesize($path): false|int|float {
  200. if (!$this->is_file($path)) {
  201. return 0;
  202. }
  203. $fullPath = $this->getSourcePath($path);
  204. if (PHP_INT_SIZE === 4) {
  205. $helper = new \OC\LargeFileHelper;
  206. return $helper->getFileSize($fullPath);
  207. }
  208. return filesize($fullPath);
  209. }
  210. public function isReadable($path) {
  211. return is_readable($this->getSourcePath($path));
  212. }
  213. public function isUpdatable($path) {
  214. return is_writable($this->getSourcePath($path));
  215. }
  216. public function file_exists($path) {
  217. if ($this->caseInsensitive) {
  218. $fullPath = $this->getSourcePath($path);
  219. $parentPath = dirname($fullPath);
  220. if (!is_dir($parentPath)) {
  221. return false;
  222. }
  223. $content = scandir($parentPath, SCANDIR_SORT_NONE);
  224. return is_array($content) && array_search(basename($fullPath), $content) !== false;
  225. } else {
  226. return file_exists($this->getSourcePath($path));
  227. }
  228. }
  229. public function filemtime($path) {
  230. $fullPath = $this->getSourcePath($path);
  231. clearstatcache(true, $fullPath);
  232. if (!$this->file_exists($path)) {
  233. return false;
  234. }
  235. if (PHP_INT_SIZE === 4) {
  236. $helper = new \OC\LargeFileHelper();
  237. return $helper->getFileMtime($fullPath);
  238. }
  239. return filemtime($fullPath);
  240. }
  241. public function touch($path, $mtime = null) {
  242. // sets the modification time of the file to the given value.
  243. // If mtime is nil the current time is set.
  244. // note that the access time of the file always changes to the current time.
  245. if ($this->file_exists($path) and !$this->isUpdatable($path)) {
  246. return false;
  247. }
  248. $oldMask = umask($this->defUMask);
  249. if (!is_null($mtime)) {
  250. $result = @touch($this->getSourcePath($path), $mtime);
  251. } else {
  252. $result = @touch($this->getSourcePath($path));
  253. }
  254. umask($oldMask);
  255. if ($result) {
  256. clearstatcache(true, $this->getSourcePath($path));
  257. }
  258. return $result;
  259. }
  260. public function file_get_contents($path) {
  261. return file_get_contents($this->getSourcePath($path));
  262. }
  263. public function file_put_contents($path, $data) {
  264. $oldMask = umask($this->defUMask);
  265. if ($this->unlinkOnTruncate) {
  266. $this->unlink($path);
  267. }
  268. $result = file_put_contents($this->getSourcePath($path), $data);
  269. umask($oldMask);
  270. return $result;
  271. }
  272. public function unlink($path) {
  273. if ($this->is_dir($path)) {
  274. return $this->rmdir($path);
  275. } elseif ($this->is_file($path)) {
  276. return unlink($this->getSourcePath($path));
  277. } else {
  278. return false;
  279. }
  280. }
  281. private function checkTreeForForbiddenItems(string $path) {
  282. $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path));
  283. foreach ($iterator as $file) {
  284. /** @var \SplFileInfo $file */
  285. if (Filesystem::isFileBlacklisted($file->getBasename())) {
  286. throw new ForbiddenException('Invalid path: ' . $file->getPathname(), false);
  287. }
  288. }
  289. }
  290. public function rename($source, $target): bool {
  291. $srcParent = dirname($source);
  292. $dstParent = dirname($target);
  293. if (!$this->isUpdatable($srcParent)) {
  294. \OC::$server->get(LoggerInterface::class)->error('unable to rename, source directory is not writable : ' . $srcParent, ['app' => 'core']);
  295. return false;
  296. }
  297. if (!$this->isUpdatable($dstParent)) {
  298. \OC::$server->get(LoggerInterface::class)->error('unable to rename, destination directory is not writable : ' . $dstParent, ['app' => 'core']);
  299. return false;
  300. }
  301. if (!$this->file_exists($source)) {
  302. \OC::$server->get(LoggerInterface::class)->error('unable to rename, file does not exists : ' . $source, ['app' => 'core']);
  303. return false;
  304. }
  305. if ($this->file_exists($target)) {
  306. if ($this->is_dir($target)) {
  307. $this->rmdir($target);
  308. } elseif ($this->is_file($target)) {
  309. $this->unlink($target);
  310. }
  311. }
  312. if ($this->is_dir($source)) {
  313. $this->checkTreeForForbiddenItems($this->getSourcePath($source));
  314. }
  315. if (@rename($this->getSourcePath($source), $this->getSourcePath($target))) {
  316. if ($this->caseInsensitive) {
  317. if (mb_strtolower($target) === mb_strtolower($source) && !$this->file_exists($target)) {
  318. return false;
  319. }
  320. }
  321. return true;
  322. }
  323. return $this->copy($source, $target) && $this->unlink($source);
  324. }
  325. public function copy($source, $target) {
  326. if ($this->is_dir($source)) {
  327. return parent::copy($source, $target);
  328. } else {
  329. $oldMask = umask($this->defUMask);
  330. if ($this->unlinkOnTruncate) {
  331. $this->unlink($target);
  332. }
  333. $result = copy($this->getSourcePath($source), $this->getSourcePath($target));
  334. umask($oldMask);
  335. if ($this->caseInsensitive) {
  336. if (mb_strtolower($target) === mb_strtolower($source) && !$this->file_exists($target)) {
  337. return false;
  338. }
  339. }
  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): string|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. /** @psalm-suppress TypeDoesNotContainType Let's be extra cautious and still check for empty string */
  438. if ($currentPath === '' || $currentPath === '.') {
  439. return $fullPath;
  440. }
  441. $realPath = realpath($this->datadir . $currentPath);
  442. }
  443. if ($realPath) {
  444. $realPath = $realPath . '/';
  445. }
  446. if (substr($realPath, 0, $this->dataDirLength) === $this->realDataDir) {
  447. return $fullPath;
  448. }
  449. \OC::$server->get(LoggerInterface::class)->error("Following symlinks is not allowed ('$fullPath' -> '$realPath' not inside '{$this->realDataDir}')", ['app' => 'core']);
  450. throw new ForbiddenException('Following symlinks is not allowed', false);
  451. }
  452. /**
  453. * {@inheritdoc}
  454. */
  455. public function isLocal() {
  456. return true;
  457. }
  458. /**
  459. * get the ETag for a file or folder
  460. *
  461. * @param string $path
  462. * @return string
  463. */
  464. public function getETag($path) {
  465. return $this->calculateEtag($path, $this->stat($path));
  466. }
  467. private function calculateEtag(string $path, array $stat): string {
  468. if ($stat['mode'] & 0x4000 && !($stat['mode'] & 0x8000)) { // is_dir & not socket
  469. return parent::getETag($path);
  470. } else {
  471. if ($stat === false) {
  472. return md5('');
  473. }
  474. $toHash = '';
  475. if (isset($stat['mtime'])) {
  476. $toHash .= $stat['mtime'];
  477. }
  478. if (isset($stat['ino'])) {
  479. $toHash .= $stat['ino'];
  480. }
  481. if (isset($stat['dev'])) {
  482. $toHash .= $stat['dev'];
  483. }
  484. if (isset($stat['size'])) {
  485. $toHash .= $stat['size'];
  486. }
  487. return md5($toHash);
  488. }
  489. }
  490. private function canDoCrossStorageMove(IStorage $sourceStorage) {
  491. /** @psalm-suppress UndefinedClass */
  492. return $sourceStorage->instanceOfStorage(Local::class)
  493. // Don't treat ACLStorageWrapper like local storage where copy can be done directly.
  494. // Instead, use the slower recursive copying in php from Common::copyFromStorage with
  495. // more permissions checks.
  496. && !$sourceStorage->instanceOfStorage('OCA\GroupFolders\ACL\ACLStorageWrapper')
  497. // Same for access control
  498. && !$sourceStorage->instanceOfStorage(\OCA\FilesAccessControl\StorageWrapper::class)
  499. // when moving encrypted files we have to handle keys and the target might not be encrypted
  500. && !$sourceStorage->instanceOfStorage(Encryption::class);
  501. }
  502. /**
  503. * @param IStorage $sourceStorage
  504. * @param string $sourceInternalPath
  505. * @param string $targetInternalPath
  506. * @param bool $preserveMtime
  507. * @return bool
  508. */
  509. public function copyFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = false) {
  510. if ($this->canDoCrossStorageMove($sourceStorage)) {
  511. // resolve any jailed paths
  512. while ($sourceStorage->instanceOfStorage(Jail::class)) {
  513. /**
  514. * @var \OC\Files\Storage\Wrapper\Jail $sourceStorage
  515. */
  516. $sourceInternalPath = $sourceStorage->getUnjailedPath($sourceInternalPath);
  517. $sourceStorage = $sourceStorage->getUnjailedStorage();
  518. }
  519. /**
  520. * @var \OC\Files\Storage\Local $sourceStorage
  521. */
  522. $rootStorage = new Local(['datadir' => '/']);
  523. return $rootStorage->copy($sourceStorage->getSourcePath($sourceInternalPath), $this->getSourcePath($targetInternalPath));
  524. } else {
  525. return parent::copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
  526. }
  527. }
  528. /**
  529. * @param IStorage $sourceStorage
  530. * @param string $sourceInternalPath
  531. * @param string $targetInternalPath
  532. * @return bool
  533. */
  534. public function moveFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
  535. if ($this->canDoCrossStorageMove($sourceStorage)) {
  536. // resolve any jailed paths
  537. while ($sourceStorage->instanceOfStorage(Jail::class)) {
  538. /**
  539. * @var \OC\Files\Storage\Wrapper\Jail $sourceStorage
  540. */
  541. $sourceInternalPath = $sourceStorage->getUnjailedPath($sourceInternalPath);
  542. $sourceStorage = $sourceStorage->getUnjailedStorage();
  543. }
  544. /**
  545. * @var \OC\Files\Storage\Local $sourceStorage
  546. */
  547. $rootStorage = new Local(['datadir' => '/']);
  548. return $rootStorage->rename($sourceStorage->getSourcePath($sourceInternalPath), $this->getSourcePath($targetInternalPath));
  549. } else {
  550. return parent::moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
  551. }
  552. }
  553. public function writeStream(string $path, $stream, ?int $size = null): int {
  554. /** @var int|false $result We consider here that returned size will never be a float because we write less than 4GB */
  555. $result = $this->file_put_contents($path, $stream);
  556. if (is_resource($stream)) {
  557. fclose($stream);
  558. }
  559. if ($result === false) {
  560. throw new GenericFileException("Failed write stream to $path");
  561. } else {
  562. return $result;
  563. }
  564. }
  565. }