Local.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  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\Jail;
  47. use OCP\Constants;
  48. use OCP\Files\ForbiddenException;
  49. use OCP\Files\GenericFileException;
  50. use OCP\Files\IMimeTypeDetector;
  51. use OCP\Files\Storage\IStorage;
  52. use OCP\IConfig;
  53. use Psr\Log\LoggerInterface;
  54. /**
  55. * for local filestore, we only have to map the paths
  56. */
  57. class Local extends \OC\Files\Storage\Common {
  58. protected $datadir;
  59. protected $dataDirLength;
  60. protected $realDataDir;
  61. private IConfig $config;
  62. private IMimeTypeDetector $mimeTypeDetector;
  63. private $defUMask;
  64. protected bool $unlinkOnTruncate;
  65. public function __construct($arguments) {
  66. if (!isset($arguments['datadir']) || !is_string($arguments['datadir'])) {
  67. throw new \InvalidArgumentException('No data directory set for local storage');
  68. }
  69. $this->datadir = str_replace('//', '/', $arguments['datadir']);
  70. // some crazy code uses a local storage on root...
  71. if ($this->datadir === '/') {
  72. $this->realDataDir = $this->datadir;
  73. } else {
  74. $realPath = realpath($this->datadir) ?: $this->datadir;
  75. $this->realDataDir = rtrim($realPath, '/') . '/';
  76. }
  77. if (substr($this->datadir, -1) !== '/') {
  78. $this->datadir .= '/';
  79. }
  80. $this->dataDirLength = strlen($this->realDataDir);
  81. $this->config = \OC::$server->get(IConfig::class);
  82. $this->mimeTypeDetector = \OC::$server->get(IMimeTypeDetector::class);
  83. $this->defUMask = $this->config->getSystemValue('localstorage.umask', 0022);
  84. // support Write-Once-Read-Many file systems
  85. $this->unlinkOnTruncate = $this->config->getSystemValue('localstorage.unlink_on_truncate', false);
  86. }
  87. public function __destruct() {
  88. }
  89. public function getId() {
  90. return 'local::' . $this->datadir;
  91. }
  92. public function mkdir($path) {
  93. $sourcePath = $this->getSourcePath($path);
  94. $oldMask = umask($this->defUMask);
  95. $result = @mkdir($sourcePath, 0777, true);
  96. umask($oldMask);
  97. return $result;
  98. }
  99. public function rmdir($path) {
  100. if (!$this->isDeletable($path)) {
  101. return false;
  102. }
  103. try {
  104. $it = new \RecursiveIteratorIterator(
  105. new \RecursiveDirectoryIterator($this->getSourcePath($path)),
  106. \RecursiveIteratorIterator::CHILD_FIRST
  107. );
  108. /**
  109. * RecursiveDirectoryIterator on an NFS path isn't iterable with foreach
  110. * This bug is fixed in PHP 5.5.9 or before
  111. * See #8376
  112. */
  113. $it->rewind();
  114. while ($it->valid()) {
  115. /**
  116. * @var \SplFileInfo $file
  117. */
  118. $file = $it->current();
  119. clearstatcache(true, $this->getSourcePath($file));
  120. if (in_array($file->getBasename(), ['.', '..'])) {
  121. $it->next();
  122. continue;
  123. } elseif ($file->isDir()) {
  124. rmdir($file->getPathname());
  125. } elseif ($file->isFile() || $file->isLink()) {
  126. unlink($file->getPathname());
  127. }
  128. $it->next();
  129. }
  130. clearstatcache(true, $this->getSourcePath($path));
  131. return rmdir($this->getSourcePath($path));
  132. } catch (\UnexpectedValueException $e) {
  133. return false;
  134. }
  135. }
  136. public function opendir($path) {
  137. return opendir($this->getSourcePath($path));
  138. }
  139. public function is_dir($path) {
  140. if (substr($path, -1) == '/') {
  141. $path = substr($path, 0, -1);
  142. }
  143. return is_dir($this->getSourcePath($path));
  144. }
  145. public function is_file($path) {
  146. return is_file($this->getSourcePath($path));
  147. }
  148. public function stat($path) {
  149. $fullPath = $this->getSourcePath($path);
  150. clearstatcache(true, $fullPath);
  151. if (!file_exists($fullPath)) {
  152. return false;
  153. }
  154. $statResult = @stat($fullPath);
  155. if (is_array($statResult)) {
  156. $statResult['full_path'] = $fullPath;
  157. }
  158. return $statResult;
  159. }
  160. /**
  161. * @inheritdoc
  162. */
  163. public function getMetaData($path) {
  164. try {
  165. $stat = $this->stat($path);
  166. } catch (ForbiddenException $e) {
  167. return null;
  168. }
  169. if (!$stat) {
  170. return null;
  171. }
  172. $permissions = Constants::PERMISSION_SHARE;
  173. $statPermissions = $stat['mode'];
  174. $isDir = ($statPermissions & 0x4000) === 0x4000 && !($statPermissions & 0x8000);
  175. if ($statPermissions & 0x0100) {
  176. $permissions += Constants::PERMISSION_READ;
  177. }
  178. if ($statPermissions & 0x0080) {
  179. $permissions += Constants::PERMISSION_UPDATE;
  180. if ($isDir) {
  181. $permissions += Constants::PERMISSION_CREATE;
  182. }
  183. }
  184. if (!($path === '' || $path === '/')) { // deletable depends on the parents unix permissions
  185. $parent = dirname($stat['full_path']);
  186. if (is_writable($parent)) {
  187. $permissions += Constants::PERMISSION_DELETE;
  188. }
  189. }
  190. $data = [];
  191. $data['mimetype'] = $isDir ? 'httpd/unix-directory' : $this->mimeTypeDetector->detectPath($path);
  192. $data['mtime'] = $stat['mtime'];
  193. if ($data['mtime'] === false) {
  194. $data['mtime'] = time();
  195. }
  196. if ($isDir) {
  197. $data['size'] = -1; //unknown
  198. } else {
  199. $data['size'] = $stat['size'];
  200. }
  201. $data['etag'] = $this->calculateEtag($path, $stat);
  202. $data['storage_mtime'] = $data['mtime'];
  203. $data['permissions'] = $permissions;
  204. $data['name'] = basename($path);
  205. return $data;
  206. }
  207. public function filetype($path) {
  208. $filetype = filetype($this->getSourcePath($path));
  209. if ($filetype == 'link') {
  210. $filetype = filetype(realpath($this->getSourcePath($path)));
  211. }
  212. return $filetype;
  213. }
  214. public function filesize($path) {
  215. if (!$this->is_file($path)) {
  216. return 0;
  217. }
  218. $fullPath = $this->getSourcePath($path);
  219. return filesize($fullPath);
  220. }
  221. public function isReadable($path) {
  222. return is_readable($this->getSourcePath($path));
  223. }
  224. public function isUpdatable($path) {
  225. return is_writable($this->getSourcePath($path));
  226. }
  227. public function file_exists($path) {
  228. return file_exists($this->getSourcePath($path));
  229. }
  230. public function filemtime($path) {
  231. $fullPath = $this->getSourcePath($path);
  232. clearstatcache(true, $fullPath);
  233. if (!$this->file_exists($path)) {
  234. return false;
  235. }
  236. return filemtime($fullPath);
  237. }
  238. public function touch($path, $mtime = null) {
  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) {
  258. return file_get_contents($this->getSourcePath($path));
  259. }
  260. public function file_put_contents($path, $data) {
  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) {
  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) {
  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) {
  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. // we can't move folders across devices, use copy instead
  309. $stat1 = stat(dirname($this->getSourcePath($source)));
  310. $stat2 = stat(dirname($this->getSourcePath($target)));
  311. if ($stat1['dev'] !== $stat2['dev']) {
  312. $result = $this->copy($source, $target);
  313. if ($result) {
  314. $result &= $this->rmdir($source);
  315. }
  316. return $result;
  317. }
  318. $this->checkTreeForForbiddenItems($this->getSourcePath($source));
  319. }
  320. return rename($this->getSourcePath($source), $this->getSourcePath($target));
  321. }
  322. public function copy($source, $target) {
  323. if ($this->is_dir($source)) {
  324. return parent::copy($source, $target);
  325. } else {
  326. $oldMask = umask($this->defUMask);
  327. if ($this->unlinkOnTruncate) {
  328. $this->unlink($target);
  329. }
  330. $result = copy($this->getSourcePath($source), $this->getSourcePath($target));
  331. umask($oldMask);
  332. return $result;
  333. }
  334. }
  335. public function fopen($path, $mode) {
  336. $sourcePath = $this->getSourcePath($path);
  337. if (!file_exists($sourcePath) && $mode === 'r') {
  338. return false;
  339. }
  340. $oldMask = umask($this->defUMask);
  341. if (($mode === 'w' || $mode === 'w+') && $this->unlinkOnTruncate) {
  342. $this->unlink($path);
  343. }
  344. $result = @fopen($sourcePath, $mode);
  345. umask($oldMask);
  346. return $result;
  347. }
  348. public function hash($type, $path, $raw = false) {
  349. return hash_file($type, $this->getSourcePath($path), $raw);
  350. }
  351. public function free_space($path) {
  352. $sourcePath = $this->getSourcePath($path);
  353. // using !is_dir because $sourcePath might be a part file or
  354. // non-existing file, so we'd still want to use the parent dir
  355. // in such cases
  356. if (!is_dir($sourcePath)) {
  357. // disk_free_space doesn't work on files
  358. $sourcePath = dirname($sourcePath);
  359. }
  360. $space = function_exists('disk_free_space') ? disk_free_space($sourcePath) : false;
  361. if ($space === false || is_null($space)) {
  362. return \OCP\Files\FileInfo::SPACE_UNKNOWN;
  363. }
  364. return (int)$space;
  365. }
  366. public function search($query) {
  367. return $this->searchInDir($query);
  368. }
  369. public function getLocalFile($path) {
  370. return $this->getSourcePath($path);
  371. }
  372. public function getLocalFolder($path) {
  373. return $this->getSourcePath($path);
  374. }
  375. /**
  376. * @param string $query
  377. * @param string $dir
  378. * @return array
  379. */
  380. protected function searchInDir($query, $dir = '') {
  381. $files = [];
  382. $physicalDir = $this->getSourcePath($dir);
  383. foreach (scandir($physicalDir) as $item) {
  384. if (\OC\Files\Filesystem::isIgnoredDir($item)) {
  385. continue;
  386. }
  387. $physicalItem = $physicalDir . '/' . $item;
  388. if (strstr(strtolower($item), strtolower($query)) !== false) {
  389. $files[] = $dir . '/' . $item;
  390. }
  391. if (is_dir($physicalItem)) {
  392. $files = array_merge($files, $this->searchInDir($query, $dir . '/' . $item));
  393. }
  394. }
  395. return $files;
  396. }
  397. /**
  398. * check if a file or folder has been updated since $time
  399. *
  400. * @param string $path
  401. * @param int $time
  402. * @return bool
  403. */
  404. public function hasUpdated($path, $time) {
  405. if ($this->file_exists($path)) {
  406. return $this->filemtime($path) > $time;
  407. } else {
  408. return true;
  409. }
  410. }
  411. /**
  412. * Get the source path (on disk) of a given path
  413. *
  414. * @param string $path
  415. * @return string
  416. * @throws ForbiddenException
  417. */
  418. public function getSourcePath($path) {
  419. if (Filesystem::isFileBlacklisted($path)) {
  420. throw new ForbiddenException('Invalid path: ' . $path, false);
  421. }
  422. $fullPath = $this->datadir . $path;
  423. $currentPath = $path;
  424. $allowSymlinks = $this->config->getSystemValue('localstorage.allowsymlinks', false);
  425. if ($allowSymlinks || $currentPath === '') {
  426. return $fullPath;
  427. }
  428. $pathToResolve = $fullPath;
  429. $realPath = realpath($pathToResolve);
  430. while ($realPath === false) { // for non existing files check the parent directory
  431. $currentPath = dirname($currentPath);
  432. if ($currentPath === '' || $currentPath === '.') {
  433. return $fullPath;
  434. }
  435. $realPath = realpath($this->datadir . $currentPath);
  436. }
  437. if ($realPath) {
  438. $realPath = $realPath . '/';
  439. }
  440. if (substr($realPath, 0, $this->dataDirLength) === $this->realDataDir) {
  441. return $fullPath;
  442. }
  443. \OC::$server->get(LoggerInterface::class)->error("Following symlinks is not allowed ('$fullPath' -> '$realPath' not inside '{$this->realDataDir}')", ['app' => 'core']);
  444. throw new ForbiddenException('Following symlinks is not allowed', false);
  445. }
  446. /**
  447. * {@inheritdoc}
  448. */
  449. public function isLocal() {
  450. return true;
  451. }
  452. /**
  453. * get the ETag for a file or folder
  454. *
  455. * @param string $path
  456. * @return string
  457. */
  458. public function getETag($path) {
  459. return $this->calculateEtag($path, $this->stat($path));
  460. }
  461. private function calculateEtag(string $path, array $stat): string {
  462. if ($stat['mode'] & 0x4000 && !($stat['mode'] & 0x8000)) { // is_dir & not socket
  463. return parent::getETag($path);
  464. } else {
  465. if ($stat === false) {
  466. return md5('');
  467. }
  468. $toHash = '';
  469. if (isset($stat['mtime'])) {
  470. $toHash .= $stat['mtime'];
  471. }
  472. if (isset($stat['ino'])) {
  473. $toHash .= $stat['ino'];
  474. }
  475. if (isset($stat['dev'])) {
  476. $toHash .= $stat['dev'];
  477. }
  478. if (isset($stat['size'])) {
  479. $toHash .= $stat['size'];
  480. }
  481. return md5($toHash);
  482. }
  483. }
  484. /**
  485. * @param IStorage $sourceStorage
  486. * @param string $sourceInternalPath
  487. * @param string $targetInternalPath
  488. * @param bool $preserveMtime
  489. * @return bool
  490. */
  491. public function copyFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = false) {
  492. // Don't treat ACLStorageWrapper like local storage where copy can be done directly.
  493. // Instead use the slower recursive copying in php from Common::copyFromStorage with
  494. // more permissions checks.
  495. if ($sourceStorage->instanceOfStorage(Local::class) && !$sourceStorage->instanceOfStorage('OCA\GroupFolders\ACL\ACLStorageWrapper')) {
  496. if ($sourceStorage->instanceOfStorage(Jail::class)) {
  497. /**
  498. * @var \OC\Files\Storage\Wrapper\Jail $sourceStorage
  499. */
  500. $sourceInternalPath = $sourceStorage->getUnjailedPath($sourceInternalPath);
  501. }
  502. /**
  503. * @var \OC\Files\Storage\Local $sourceStorage
  504. */
  505. $rootStorage = new Local(['datadir' => '/']);
  506. return $rootStorage->copy($sourceStorage->getSourcePath($sourceInternalPath), $this->getSourcePath($targetInternalPath));
  507. } else {
  508. return parent::copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
  509. }
  510. }
  511. /**
  512. * @param IStorage $sourceStorage
  513. * @param string $sourceInternalPath
  514. * @param string $targetInternalPath
  515. * @return bool
  516. */
  517. public function moveFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
  518. if ($sourceStorage->instanceOfStorage(Local::class)) {
  519. if ($sourceStorage->instanceOfStorage(Jail::class)) {
  520. /**
  521. * @var \OC\Files\Storage\Wrapper\Jail $sourceStorage
  522. */
  523. $sourceInternalPath = $sourceStorage->getUnjailedPath($sourceInternalPath);
  524. }
  525. /**
  526. * @var \OC\Files\Storage\Local $sourceStorage
  527. */
  528. $rootStorage = new Local(['datadir' => '/']);
  529. return $rootStorage->rename($sourceStorage->getSourcePath($sourceInternalPath), $this->getSourcePath($targetInternalPath));
  530. } else {
  531. return parent::moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
  532. }
  533. }
  534. public function writeStream(string $path, $stream, int $size = null): int {
  535. $result = $this->file_put_contents($path, $stream);
  536. if (is_resource($stream)) {
  537. fclose($stream);
  538. }
  539. if ($result === false) {
  540. throw new GenericFileException("Failed write stream to $path");
  541. } else {
  542. return $result;
  543. }
  544. }
  545. }