Local.php 16 KB

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