1
0

Local.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  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(): string {
  63. return 'local::' . $this->datadir;
  64. }
  65. public function mkdir($path): bool {
  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): bool {
  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): bool {
  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): bool {
  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): array|false {
  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. public function getMetaData($path): ?array {
  146. try {
  147. $stat = $this->stat($path);
  148. } catch (ForbiddenException $e) {
  149. return null;
  150. }
  151. if (!$stat) {
  152. return null;
  153. }
  154. $permissions = Constants::PERMISSION_SHARE;
  155. $statPermissions = $stat['mode'];
  156. $isDir = ($statPermissions & 0x4000) === 0x4000 && !($statPermissions & 0x8000);
  157. if ($statPermissions & 0x0100) {
  158. $permissions += Constants::PERMISSION_READ;
  159. }
  160. if ($statPermissions & 0x0080) {
  161. $permissions += Constants::PERMISSION_UPDATE;
  162. if ($isDir) {
  163. $permissions += Constants::PERMISSION_CREATE;
  164. }
  165. }
  166. if (!($path === '' || $path === '/')) { // deletable depends on the parents unix permissions
  167. $parent = dirname($stat['full_path']);
  168. if (is_writable($parent)) {
  169. $permissions += Constants::PERMISSION_DELETE;
  170. }
  171. }
  172. $data = [];
  173. $data['mimetype'] = $isDir ? 'httpd/unix-directory' : $this->mimeTypeDetector->detectPath($path);
  174. $data['mtime'] = $stat['mtime'];
  175. if ($data['mtime'] === false) {
  176. $data['mtime'] = time();
  177. }
  178. if ($isDir) {
  179. $data['size'] = -1; //unknown
  180. } else {
  181. $data['size'] = $stat['size'];
  182. }
  183. $data['etag'] = $this->calculateEtag($path, $stat);
  184. $data['storage_mtime'] = $data['mtime'];
  185. $data['permissions'] = $permissions;
  186. $data['name'] = basename($path);
  187. return $data;
  188. }
  189. public function filetype($path): string|false {
  190. $filetype = filetype($this->getSourcePath($path));
  191. if ($filetype == 'link') {
  192. $filetype = filetype(realpath($this->getSourcePath($path)));
  193. }
  194. return $filetype;
  195. }
  196. public function filesize($path): int|float|false {
  197. if (!$this->is_file($path)) {
  198. return 0;
  199. }
  200. $fullPath = $this->getSourcePath($path);
  201. if (PHP_INT_SIZE === 4) {
  202. $helper = new \OC\LargeFileHelper;
  203. return $helper->getFileSize($fullPath);
  204. }
  205. return filesize($fullPath);
  206. }
  207. public function isReadable($path): bool {
  208. return is_readable($this->getSourcePath($path));
  209. }
  210. public function isUpdatable($path): bool {
  211. return is_writable($this->getSourcePath($path));
  212. }
  213. public function file_exists($path): bool {
  214. if ($this->caseInsensitive) {
  215. $fullPath = $this->getSourcePath($path);
  216. $parentPath = dirname($fullPath);
  217. if (!is_dir($parentPath)) {
  218. return false;
  219. }
  220. $content = scandir($parentPath, SCANDIR_SORT_NONE);
  221. return is_array($content) && array_search(basename($fullPath), $content) !== false;
  222. } else {
  223. return file_exists($this->getSourcePath($path));
  224. }
  225. }
  226. public function filemtime($path): int|false {
  227. $fullPath = $this->getSourcePath($path);
  228. clearstatcache(true, $fullPath);
  229. if (!$this->file_exists($path)) {
  230. return false;
  231. }
  232. if (PHP_INT_SIZE === 4) {
  233. $helper = new \OC\LargeFileHelper();
  234. return $helper->getFileMtime($fullPath);
  235. }
  236. return filemtime($fullPath);
  237. }
  238. public function touch($path, $mtime = null): bool {
  239. // sets the modification time of the file to the given value.
  240. // If mtime is nil the current time is set.
  241. // note that the access time of the file always changes to the current time.
  242. if ($this->file_exists($path) and !$this->isUpdatable($path)) {
  243. return false;
  244. }
  245. $oldMask = umask($this->defUMask);
  246. if (!is_null($mtime)) {
  247. $result = @touch($this->getSourcePath($path), $mtime);
  248. } else {
  249. $result = @touch($this->getSourcePath($path));
  250. }
  251. umask($oldMask);
  252. if ($result) {
  253. clearstatcache(true, $this->getSourcePath($path));
  254. }
  255. return $result;
  256. }
  257. public function file_get_contents($path): string|false {
  258. return file_get_contents($this->getSourcePath($path));
  259. }
  260. public function file_put_contents($path, $data): int|float|false {
  261. $oldMask = umask($this->defUMask);
  262. if ($this->unlinkOnTruncate) {
  263. $this->unlink($path);
  264. }
  265. $result = file_put_contents($this->getSourcePath($path), $data);
  266. umask($oldMask);
  267. return $result;
  268. }
  269. public function unlink($path): bool {
  270. if ($this->is_dir($path)) {
  271. return $this->rmdir($path);
  272. } elseif ($this->is_file($path)) {
  273. return unlink($this->getSourcePath($path));
  274. } else {
  275. return false;
  276. }
  277. }
  278. private function checkTreeForForbiddenItems(string $path): void {
  279. $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path));
  280. foreach ($iterator as $file) {
  281. /** @var \SplFileInfo $file */
  282. if (Filesystem::isFileBlacklisted($file->getBasename())) {
  283. throw new ForbiddenException('Invalid path: ' . $file->getPathname(), false);
  284. }
  285. }
  286. }
  287. public function rename($source, $target): bool {
  288. $srcParent = dirname($source);
  289. $dstParent = dirname($target);
  290. if (!$this->isUpdatable($srcParent)) {
  291. \OC::$server->get(LoggerInterface::class)->error('unable to rename, source directory is not writable : ' . $srcParent, ['app' => 'core']);
  292. return false;
  293. }
  294. if (!$this->isUpdatable($dstParent)) {
  295. \OC::$server->get(LoggerInterface::class)->error('unable to rename, destination directory is not writable : ' . $dstParent, ['app' => 'core']);
  296. return false;
  297. }
  298. if (!$this->file_exists($source)) {
  299. \OC::$server->get(LoggerInterface::class)->error('unable to rename, file does not exists : ' . $source, ['app' => 'core']);
  300. return false;
  301. }
  302. if ($this->is_dir($target)) {
  303. $this->rmdir($target);
  304. } elseif ($this->is_file($target)) {
  305. $this->unlink($target);
  306. }
  307. if ($this->is_dir($source)) {
  308. $this->checkTreeForForbiddenItems($this->getSourcePath($source));
  309. }
  310. if (@rename($this->getSourcePath($source), $this->getSourcePath($target))) {
  311. if ($this->caseInsensitive) {
  312. if (mb_strtolower($target) === mb_strtolower($source) && !$this->file_exists($target)) {
  313. return false;
  314. }
  315. }
  316. return true;
  317. }
  318. return $this->copy($source, $target) && $this->unlink($source);
  319. }
  320. public function copy($source, $target): bool {
  321. if ($this->is_dir($source)) {
  322. return parent::copy($source, $target);
  323. } else {
  324. $oldMask = umask($this->defUMask);
  325. if ($this->unlinkOnTruncate) {
  326. $this->unlink($target);
  327. }
  328. $result = copy($this->getSourcePath($source), $this->getSourcePath($target));
  329. umask($oldMask);
  330. if ($this->caseInsensitive) {
  331. if (mb_strtolower($target) === mb_strtolower($source) && !$this->file_exists($target)) {
  332. return false;
  333. }
  334. }
  335. return $result;
  336. }
  337. }
  338. public function fopen($path, $mode) {
  339. $sourcePath = $this->getSourcePath($path);
  340. if (!file_exists($sourcePath) && $mode === 'r') {
  341. return false;
  342. }
  343. $oldMask = umask($this->defUMask);
  344. if (($mode === 'w' || $mode === 'w+') && $this->unlinkOnTruncate) {
  345. $this->unlink($path);
  346. }
  347. $result = @fopen($sourcePath, $mode);
  348. umask($oldMask);
  349. return $result;
  350. }
  351. public function hash($type, $path, $raw = false): string|false {
  352. return hash_file($type, $this->getSourcePath($path), $raw);
  353. }
  354. public function free_space($path): int|float|false {
  355. $sourcePath = $this->getSourcePath($path);
  356. // using !is_dir because $sourcePath might be a part file or
  357. // non-existing file, so we'd still want to use the parent dir
  358. // in such cases
  359. if (!is_dir($sourcePath)) {
  360. // disk_free_space doesn't work on files
  361. $sourcePath = dirname($sourcePath);
  362. }
  363. $space = (function_exists('disk_free_space') && is_dir($sourcePath)) ? disk_free_space($sourcePath) : false;
  364. if ($space === false || is_null($space)) {
  365. return \OCP\Files\FileInfo::SPACE_UNKNOWN;
  366. }
  367. return Util::numericToNumber($space);
  368. }
  369. public function search($query): array {
  370. return $this->searchInDir($query);
  371. }
  372. public function getLocalFile($path): string|false {
  373. return $this->getSourcePath($path);
  374. }
  375. /**
  376. * @param string $query
  377. * @param string $dir
  378. */
  379. protected function searchInDir($query, $dir = ''): array {
  380. $files = [];
  381. $physicalDir = $this->getSourcePath($dir);
  382. foreach (scandir($physicalDir) as $item) {
  383. if (\OC\Files\Filesystem::isIgnoredDir($item)) {
  384. continue;
  385. }
  386. $physicalItem = $physicalDir . '/' . $item;
  387. if (strstr(strtolower($item), strtolower($query)) !== false) {
  388. $files[] = $dir . '/' . $item;
  389. }
  390. if (is_dir($physicalItem)) {
  391. $files = array_merge($files, $this->searchInDir($query, $dir . '/' . $item));
  392. }
  393. }
  394. return $files;
  395. }
  396. public function hasUpdated($path, $time): bool {
  397. if ($this->file_exists($path)) {
  398. return $this->filemtime($path) > $time;
  399. } else {
  400. return true;
  401. }
  402. }
  403. /**
  404. * Get the source path (on disk) of a given path
  405. *
  406. * @param string $path
  407. * @throws ForbiddenException
  408. */
  409. public function getSourcePath($path): string {
  410. if (Filesystem::isFileBlacklisted($path)) {
  411. throw new ForbiddenException('Invalid path: ' . $path, false);
  412. }
  413. $fullPath = $this->datadir . $path;
  414. $currentPath = $path;
  415. $allowSymlinks = $this->config->getSystemValueBool('localstorage.allowsymlinks', false);
  416. if ($allowSymlinks || $currentPath === '') {
  417. return $fullPath;
  418. }
  419. $pathToResolve = $fullPath;
  420. $realPath = realpath($pathToResolve);
  421. while ($realPath === false) { // for non existing files check the parent directory
  422. $currentPath = dirname($currentPath);
  423. /** @psalm-suppress TypeDoesNotContainType Let's be extra cautious and still check for empty string */
  424. if ($currentPath === '' || $currentPath === '.') {
  425. return $fullPath;
  426. }
  427. $realPath = realpath($this->datadir . $currentPath);
  428. }
  429. if ($realPath) {
  430. $realPath = $realPath . '/';
  431. }
  432. if (substr($realPath, 0, $this->dataDirLength) === $this->realDataDir) {
  433. return $fullPath;
  434. }
  435. \OC::$server->get(LoggerInterface::class)->error("Following symlinks is not allowed ('$fullPath' -> '$realPath' not inside '{$this->realDataDir}')", ['app' => 'core']);
  436. throw new ForbiddenException('Following symlinks is not allowed', false);
  437. }
  438. public function isLocal(): bool {
  439. return true;
  440. }
  441. public function getETag($path): string|false {
  442. return $this->calculateEtag($path, $this->stat($path));
  443. }
  444. private function calculateEtag(string $path, array $stat): string|false {
  445. if ($stat['mode'] & 0x4000 && !($stat['mode'] & 0x8000)) { // is_dir & not socket
  446. return parent::getETag($path);
  447. } else {
  448. if ($stat === false) {
  449. return md5('');
  450. }
  451. $toHash = '';
  452. if (isset($stat['mtime'])) {
  453. $toHash .= $stat['mtime'];
  454. }
  455. if (isset($stat['ino'])) {
  456. $toHash .= $stat['ino'];
  457. }
  458. if (isset($stat['dev'])) {
  459. $toHash .= $stat['dev'];
  460. }
  461. if (isset($stat['size'])) {
  462. $toHash .= $stat['size'];
  463. }
  464. return md5($toHash);
  465. }
  466. }
  467. private function canDoCrossStorageMove(IStorage $sourceStorage): bool {
  468. /** @psalm-suppress UndefinedClass */
  469. return $sourceStorage->instanceOfStorage(Local::class)
  470. // Don't treat ACLStorageWrapper like local storage where copy can be done directly.
  471. // Instead, use the slower recursive copying in php from Common::copyFromStorage with
  472. // more permissions checks.
  473. && !$sourceStorage->instanceOfStorage('OCA\GroupFolders\ACL\ACLStorageWrapper')
  474. // Same for access control
  475. && !$sourceStorage->instanceOfStorage(\OCA\FilesAccessControl\StorageWrapper::class)
  476. // when moving encrypted files we have to handle keys and the target might not be encrypted
  477. && !$sourceStorage->instanceOfStorage(Encryption::class);
  478. }
  479. public function copyFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = false): bool {
  480. if ($this->canDoCrossStorageMove($sourceStorage)) {
  481. if ($sourceStorage->instanceOfStorage(Jail::class)) {
  482. /**
  483. * @var \OC\Files\Storage\Wrapper\Jail $sourceStorage
  484. */
  485. $sourceInternalPath = $sourceStorage->getUnjailedPath($sourceInternalPath);
  486. }
  487. /**
  488. * @var \OC\Files\Storage\Local $sourceStorage
  489. */
  490. $rootStorage = new Local(['datadir' => '/']);
  491. return $rootStorage->copy($sourceStorage->getSourcePath($sourceInternalPath), $this->getSourcePath($targetInternalPath));
  492. } else {
  493. return parent::copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
  494. }
  495. }
  496. /**
  497. * @param IStorage $sourceStorage
  498. * @param string $sourceInternalPath
  499. * @param string $targetInternalPath
  500. * @return bool
  501. */
  502. public function moveFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath): bool {
  503. if ($this->canDoCrossStorageMove($sourceStorage)) {
  504. if ($sourceStorage->instanceOfStorage(Jail::class)) {
  505. /**
  506. * @var \OC\Files\Storage\Wrapper\Jail $sourceStorage
  507. */
  508. $sourceInternalPath = $sourceStorage->getUnjailedPath($sourceInternalPath);
  509. }
  510. /**
  511. * @var \OC\Files\Storage\Local $sourceStorage
  512. */
  513. $rootStorage = new Local(['datadir' => '/']);
  514. return $rootStorage->rename($sourceStorage->getSourcePath($sourceInternalPath), $this->getSourcePath($targetInternalPath));
  515. } else {
  516. return parent::moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
  517. }
  518. }
  519. public function writeStream(string $path, $stream, ?int $size = null): int {
  520. /** @var int|false $result We consider here that returned size will never be a float because we write less than 4GB */
  521. $result = $this->file_put_contents($path, $stream);
  522. if (is_resource($stream)) {
  523. fclose($stream);
  524. }
  525. if ($result === false) {
  526. throw new GenericFileException("Failed write stream to $path");
  527. } else {
  528. return $result;
  529. }
  530. }
  531. }