Local.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  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(array $parameters) {
  33. if (!isset($parameters['datadir']) || !is_string($parameters['datadir'])) {
  34. throw new \InvalidArgumentException('No data directory set for local storage');
  35. }
  36. $this->datadir = str_replace('//', '/', $parameters['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($parameters['isExternal']) && $parameters['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(string $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(string $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(string $path) {
  111. return opendir($this->getSourcePath($path));
  112. }
  113. public function is_dir(string $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(string $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(string $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(string $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(string $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(string $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(string $path): bool {
  208. return is_readable($this->getSourcePath($path));
  209. }
  210. public function isUpdatable(string $path): bool {
  211. return is_writable($this->getSourcePath($path));
  212. }
  213. public function file_exists(string $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(string $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(string $path, ?int $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(string $path): string|false {
  258. return file_get_contents($this->getSourcePath($path));
  259. }
  260. public function file_put_contents(string $path, mixed $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(string $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(string $source, string $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(string $source, string $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(string $path, string $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(string $type, string $path, bool $raw = false): string|false {
  352. return hash_file($type, $this->getSourcePath($path), $raw);
  353. }
  354. public function free_space(string $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(string $query): array {
  370. return $this->searchInDir($query);
  371. }
  372. public function getLocalFile(string $path): string|false {
  373. return $this->getSourcePath($path);
  374. }
  375. protected function searchInDir(string $query, string $dir = ''): array {
  376. $files = [];
  377. $physicalDir = $this->getSourcePath($dir);
  378. foreach (scandir($physicalDir) as $item) {
  379. if (\OC\Files\Filesystem::isIgnoredDir($item)) {
  380. continue;
  381. }
  382. $physicalItem = $physicalDir . '/' . $item;
  383. if (strstr(strtolower($item), strtolower($query)) !== false) {
  384. $files[] = $dir . '/' . $item;
  385. }
  386. if (is_dir($physicalItem)) {
  387. $files = array_merge($files, $this->searchInDir($query, $dir . '/' . $item));
  388. }
  389. }
  390. return $files;
  391. }
  392. public function hasUpdated(string $path, int $time): bool {
  393. if ($this->file_exists($path)) {
  394. return $this->filemtime($path) > $time;
  395. } else {
  396. return true;
  397. }
  398. }
  399. /**
  400. * Get the source path (on disk) of a given path
  401. *
  402. * @throws ForbiddenException
  403. */
  404. public function getSourcePath(string $path): string {
  405. if (Filesystem::isFileBlacklisted($path)) {
  406. throw new ForbiddenException('Invalid path: ' . $path, false);
  407. }
  408. $fullPath = $this->datadir . $path;
  409. $currentPath = $path;
  410. $allowSymlinks = $this->config->getSystemValueBool('localstorage.allowsymlinks', false);
  411. if ($allowSymlinks || $currentPath === '') {
  412. return $fullPath;
  413. }
  414. $pathToResolve = $fullPath;
  415. $realPath = realpath($pathToResolve);
  416. while ($realPath === false) { // for non existing files check the parent directory
  417. $currentPath = dirname($currentPath);
  418. /** @psalm-suppress TypeDoesNotContainType Let's be extra cautious and still check for empty string */
  419. if ($currentPath === '' || $currentPath === '.') {
  420. return $fullPath;
  421. }
  422. $realPath = realpath($this->datadir . $currentPath);
  423. }
  424. if ($realPath) {
  425. $realPath = $realPath . '/';
  426. }
  427. if (substr($realPath, 0, $this->dataDirLength) === $this->realDataDir) {
  428. return $fullPath;
  429. }
  430. \OC::$server->get(LoggerInterface::class)->error("Following symlinks is not allowed ('$fullPath' -> '$realPath' not inside '{$this->realDataDir}')", ['app' => 'core']);
  431. throw new ForbiddenException('Following symlinks is not allowed', false);
  432. }
  433. public function isLocal(): bool {
  434. return true;
  435. }
  436. public function getETag(string $path): string|false {
  437. return $this->calculateEtag($path, $this->stat($path));
  438. }
  439. private function calculateEtag(string $path, array $stat): string|false {
  440. if ($stat['mode'] & 0x4000 && !($stat['mode'] & 0x8000)) { // is_dir & not socket
  441. return parent::getETag($path);
  442. } else {
  443. if ($stat === false) {
  444. return md5('');
  445. }
  446. $toHash = '';
  447. if (isset($stat['mtime'])) {
  448. $toHash .= $stat['mtime'];
  449. }
  450. if (isset($stat['ino'])) {
  451. $toHash .= $stat['ino'];
  452. }
  453. if (isset($stat['dev'])) {
  454. $toHash .= $stat['dev'];
  455. }
  456. if (isset($stat['size'])) {
  457. $toHash .= $stat['size'];
  458. }
  459. return md5($toHash);
  460. }
  461. }
  462. private function canDoCrossStorageMove(IStorage $sourceStorage): bool {
  463. /** @psalm-suppress UndefinedClass,InvalidArgument */
  464. return $sourceStorage->instanceOfStorage(Local::class)
  465. // Don't treat ACLStorageWrapper like local storage where copy can be done directly.
  466. // Instead, use the slower recursive copying in php from Common::copyFromStorage with
  467. // more permissions checks.
  468. && !$sourceStorage->instanceOfStorage('OCA\GroupFolders\ACL\ACLStorageWrapper')
  469. // Same for access control
  470. && !$sourceStorage->instanceOfStorage(\OCA\FilesAccessControl\StorageWrapper::class)
  471. // when moving encrypted files we have to handle keys and the target might not be encrypted
  472. && !$sourceStorage->instanceOfStorage(Encryption::class);
  473. }
  474. public function copyFromStorage(IStorage $sourceStorage, string $sourceInternalPath, string $targetInternalPath, bool $preserveMtime = false): bool {
  475. if ($this->canDoCrossStorageMove($sourceStorage)) {
  476. // resolve any jailed paths
  477. while ($sourceStorage->instanceOfStorage(Jail::class)) {
  478. /**
  479. * @var \OC\Files\Storage\Wrapper\Jail $sourceStorage
  480. */
  481. $sourceInternalPath = $sourceStorage->getUnjailedPath($sourceInternalPath);
  482. $sourceStorage = $sourceStorage->getUnjailedStorage();
  483. }
  484. /**
  485. * @var \OC\Files\Storage\Local $sourceStorage
  486. */
  487. $rootStorage = new Local(['datadir' => '/']);
  488. return $rootStorage->copy($sourceStorage->getSourcePath($sourceInternalPath), $this->getSourcePath($targetInternalPath));
  489. } else {
  490. return parent::copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
  491. }
  492. }
  493. public function moveFromStorage(IStorage $sourceStorage, string $sourceInternalPath, string $targetInternalPath): bool {
  494. if ($this->canDoCrossStorageMove($sourceStorage)) {
  495. // resolve any jailed paths
  496. while ($sourceStorage->instanceOfStorage(Jail::class)) {
  497. /**
  498. * @var \OC\Files\Storage\Wrapper\Jail $sourceStorage
  499. */
  500. $sourceInternalPath = $sourceStorage->getUnjailedPath($sourceInternalPath);
  501. $sourceStorage = $sourceStorage->getUnjailedStorage();
  502. }
  503. /**
  504. * @var \OC\Files\Storage\Local $sourceStorage
  505. */
  506. $rootStorage = new Local(['datadir' => '/']);
  507. return $rootStorage->rename($sourceStorage->getSourcePath($sourceInternalPath), $this->getSourcePath($targetInternalPath));
  508. } else {
  509. return parent::moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
  510. }
  511. }
  512. public function writeStream(string $path, $stream, ?int $size = null): int {
  513. /** @var int|false $result We consider here that returned size will never be a float because we write less than 4GB */
  514. $result = $this->file_put_contents($path, $stream);
  515. if (is_resource($stream)) {
  516. fclose($stream);
  517. }
  518. if ($result === false) {
  519. throw new GenericFileException("Failed write stream to $path");
  520. } else {
  521. return $result;
  522. }
  523. }
  524. }