You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Local.php 16KB

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