1
0

Common.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Bart Visscher <bartv@thisnet.nl>
  7. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  8. * @author Greta Doci <gretadoci@gmail.com>
  9. * @author hkjolhede <hkjolhede@gmail.com>
  10. * @author Joas Schilling <coding@schilljs.com>
  11. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  12. * @author Julius Härtl <jus@bitgrid.net>
  13. * @author Lukas Reschke <lukas@statuscode.ch>
  14. * @author Martin Mattel <martin.mattel@diemattels.at>
  15. * @author Michael Gapczynski <GapczynskiM@gmail.com>
  16. * @author Morris Jobke <hey@morrisjobke.de>
  17. * @author Robin Appelman <robin@icewind.nl>
  18. * @author Robin McCorkell <robin@mccorkell.me.uk>
  19. * @author Roeland Jago Douma <roeland@famdouma.nl>
  20. * @author Roland Tapken <roland@bitarbeiter.net>
  21. * @author Sam Tuke <mail@samtuke.com>
  22. * @author scambra <sergio@entrecables.com>
  23. * @author Stefan Weil <sw@weilnetz.de>
  24. * @author Thomas Müller <thomas.mueller@tmit.eu>
  25. * @author Vincent Petry <vincent@nextcloud.com>
  26. * @author Vinicius Cubas Brand <vinicius@eita.org.br>
  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\Cache\Cache;
  45. use OC\Files\Cache\Propagator;
  46. use OC\Files\Cache\Scanner;
  47. use OC\Files\Cache\Updater;
  48. use OC\Files\Cache\Watcher;
  49. use OC\Files\Filesystem;
  50. use OC\Files\Storage\Wrapper\Jail;
  51. use OC\Files\Storage\Wrapper\Wrapper;
  52. use OCP\Files\EmptyFileNameException;
  53. use OCP\Files\FileNameTooLongException;
  54. use OCP\Files\ForbiddenException;
  55. use OCP\Files\GenericFileException;
  56. use OCP\Files\InvalidCharacterInPathException;
  57. use OCP\Files\InvalidDirectoryException;
  58. use OCP\Files\InvalidPathException;
  59. use OCP\Files\ReservedWordException;
  60. use OCP\Files\Storage\ILockingStorage;
  61. use OCP\Files\Storage\IStorage;
  62. use OCP\Files\Storage\IWriteStreamStorage;
  63. use OCP\Lock\ILockingProvider;
  64. use OCP\Lock\LockedException;
  65. use Psr\Log\LoggerInterface;
  66. /**
  67. * Storage backend class for providing common filesystem operation methods
  68. * which are not storage-backend specific.
  69. *
  70. * \OC\Files\Storage\Common is never used directly; it is extended by all other
  71. * storage backends, where its methods may be overridden, and additional
  72. * (backend-specific) methods are defined.
  73. *
  74. * Some \OC\Files\Storage\Common methods call functions which are first defined
  75. * in classes which extend it, e.g. $this->stat() .
  76. */
  77. abstract class Common implements Storage, ILockingStorage, IWriteStreamStorage {
  78. use LocalTempFileTrait;
  79. protected $cache;
  80. protected $scanner;
  81. protected $watcher;
  82. protected $propagator;
  83. protected $storageCache;
  84. protected $updater;
  85. protected $mountOptions = [];
  86. protected $owner = null;
  87. /** @var ?bool */
  88. private $shouldLogLocks = null;
  89. /** @var ?LoggerInterface */
  90. private $logger;
  91. public function __construct($parameters) {
  92. }
  93. /**
  94. * Remove a file or folder
  95. *
  96. * @param string $path
  97. * @return bool
  98. */
  99. protected function remove($path) {
  100. if ($this->is_dir($path)) {
  101. return $this->rmdir($path);
  102. } elseif ($this->is_file($path)) {
  103. return $this->unlink($path);
  104. } else {
  105. return false;
  106. }
  107. }
  108. public function is_dir($path) {
  109. return $this->filetype($path) === 'dir';
  110. }
  111. public function is_file($path) {
  112. return $this->filetype($path) === 'file';
  113. }
  114. public function filesize($path): false|int|float {
  115. if ($this->is_dir($path)) {
  116. return 0; //by definition
  117. } else {
  118. $stat = $this->stat($path);
  119. if (isset($stat['size'])) {
  120. return $stat['size'];
  121. } else {
  122. return 0;
  123. }
  124. }
  125. }
  126. public function isReadable($path) {
  127. // at least check whether it exists
  128. // subclasses might want to implement this more thoroughly
  129. return $this->file_exists($path);
  130. }
  131. public function isUpdatable($path) {
  132. // at least check whether it exists
  133. // subclasses might want to implement this more thoroughly
  134. // a non-existing file/folder isn't updatable
  135. return $this->file_exists($path);
  136. }
  137. public function isCreatable($path) {
  138. if ($this->is_dir($path) && $this->isUpdatable($path)) {
  139. return true;
  140. }
  141. return false;
  142. }
  143. public function isDeletable($path) {
  144. if ($path === '' || $path === '/') {
  145. return $this->isUpdatable($path);
  146. }
  147. $parent = dirname($path);
  148. return $this->isUpdatable($parent) && $this->isUpdatable($path);
  149. }
  150. public function isSharable($path) {
  151. return $this->isReadable($path);
  152. }
  153. public function getPermissions($path) {
  154. $permissions = 0;
  155. if ($this->isCreatable($path)) {
  156. $permissions |= \OCP\Constants::PERMISSION_CREATE;
  157. }
  158. if ($this->isReadable($path)) {
  159. $permissions |= \OCP\Constants::PERMISSION_READ;
  160. }
  161. if ($this->isUpdatable($path)) {
  162. $permissions |= \OCP\Constants::PERMISSION_UPDATE;
  163. }
  164. if ($this->isDeletable($path)) {
  165. $permissions |= \OCP\Constants::PERMISSION_DELETE;
  166. }
  167. if ($this->isSharable($path)) {
  168. $permissions |= \OCP\Constants::PERMISSION_SHARE;
  169. }
  170. return $permissions;
  171. }
  172. public function filemtime($path) {
  173. $stat = $this->stat($path);
  174. if (isset($stat['mtime']) && $stat['mtime'] > 0) {
  175. return $stat['mtime'];
  176. } else {
  177. return 0;
  178. }
  179. }
  180. public function file_get_contents($path) {
  181. $handle = $this->fopen($path, "r");
  182. if (!$handle) {
  183. return false;
  184. }
  185. $data = stream_get_contents($handle);
  186. fclose($handle);
  187. return $data;
  188. }
  189. public function file_put_contents($path, $data) {
  190. $handle = $this->fopen($path, "w");
  191. if (!$handle) {
  192. return false;
  193. }
  194. $this->removeCachedFile($path);
  195. $count = fwrite($handle, $data);
  196. fclose($handle);
  197. return $count;
  198. }
  199. public function rename($source, $target) {
  200. $this->remove($target);
  201. $this->removeCachedFile($source);
  202. return $this->copy($source, $target) and $this->remove($source);
  203. }
  204. public function copy($source, $target) {
  205. if ($this->is_dir($source)) {
  206. $this->remove($target);
  207. $dir = $this->opendir($source);
  208. $this->mkdir($target);
  209. while ($file = readdir($dir)) {
  210. if (!Filesystem::isIgnoredDir($file)) {
  211. if (!$this->copy($source . '/' . $file, $target . '/' . $file)) {
  212. closedir($dir);
  213. return false;
  214. }
  215. }
  216. }
  217. closedir($dir);
  218. return true;
  219. } else {
  220. $sourceStream = $this->fopen($source, 'r');
  221. $targetStream = $this->fopen($target, 'w');
  222. [, $result] = \OC_Helper::streamCopy($sourceStream, $targetStream);
  223. if (!$result) {
  224. \OCP\Server::get(LoggerInterface::class)->warning("Failed to write data while copying $source to $target");
  225. }
  226. $this->removeCachedFile($target);
  227. return $result;
  228. }
  229. }
  230. public function getMimeType($path) {
  231. if ($this->is_dir($path)) {
  232. return 'httpd/unix-directory';
  233. } elseif ($this->file_exists($path)) {
  234. return \OC::$server->getMimeTypeDetector()->detectPath($path);
  235. } else {
  236. return false;
  237. }
  238. }
  239. public function hash($type, $path, $raw = false) {
  240. $fh = $this->fopen($path, 'rb');
  241. $ctx = hash_init($type);
  242. hash_update_stream($ctx, $fh);
  243. fclose($fh);
  244. return hash_final($ctx, $raw);
  245. }
  246. public function search($query) {
  247. return $this->searchInDir($query);
  248. }
  249. public function getLocalFile($path) {
  250. return $this->getCachedFile($path);
  251. }
  252. /**
  253. * @param string $path
  254. * @param string $target
  255. */
  256. private function addLocalFolder($path, $target) {
  257. $dh = $this->opendir($path);
  258. if (is_resource($dh)) {
  259. while (($file = readdir($dh)) !== false) {
  260. if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
  261. if ($this->is_dir($path . '/' . $file)) {
  262. mkdir($target . '/' . $file);
  263. $this->addLocalFolder($path . '/' . $file, $target . '/' . $file);
  264. } else {
  265. $tmp = $this->toTmpFile($path . '/' . $file);
  266. rename($tmp, $target . '/' . $file);
  267. }
  268. }
  269. }
  270. }
  271. }
  272. /**
  273. * @param string $query
  274. * @param string $dir
  275. * @return array
  276. */
  277. protected function searchInDir($query, $dir = '') {
  278. $files = [];
  279. $dh = $this->opendir($dir);
  280. if (is_resource($dh)) {
  281. while (($item = readdir($dh)) !== false) {
  282. if (\OC\Files\Filesystem::isIgnoredDir($item)) {
  283. continue;
  284. }
  285. if (strstr(strtolower($item), strtolower($query)) !== false) {
  286. $files[] = $dir . '/' . $item;
  287. }
  288. if ($this->is_dir($dir . '/' . $item)) {
  289. $files = array_merge($files, $this->searchInDir($query, $dir . '/' . $item));
  290. }
  291. }
  292. }
  293. closedir($dh);
  294. return $files;
  295. }
  296. /**
  297. * Check if a file or folder has been updated since $time
  298. *
  299. * The method is only used to check if the cache needs to be updated. Storage backends that don't support checking
  300. * the mtime should always return false here. As a result storage implementations that always return false expect
  301. * exclusive access to the backend and will not pick up files that have been added in a way that circumvents
  302. * Nextcloud filesystem.
  303. *
  304. * @param string $path
  305. * @param int $time
  306. * @return bool
  307. */
  308. public function hasUpdated($path, $time) {
  309. return $this->filemtime($path) > $time;
  310. }
  311. public function getCache($path = '', $storage = null) {
  312. if (!$storage) {
  313. $storage = $this;
  314. }
  315. if (!isset($storage->cache)) {
  316. $storage->cache = new Cache($storage);
  317. }
  318. return $storage->cache;
  319. }
  320. public function getScanner($path = '', $storage = null) {
  321. if (!$storage) {
  322. $storage = $this;
  323. }
  324. if (!isset($storage->scanner)) {
  325. $storage->scanner = new Scanner($storage);
  326. }
  327. return $storage->scanner;
  328. }
  329. public function getWatcher($path = '', $storage = null) {
  330. if (!$storage) {
  331. $storage = $this;
  332. }
  333. if (!isset($this->watcher)) {
  334. $this->watcher = new Watcher($storage);
  335. $globalPolicy = \OC::$server->getConfig()->getSystemValue('filesystem_check_changes', Watcher::CHECK_NEVER);
  336. $this->watcher->setPolicy((int)$this->getMountOption('filesystem_check_changes', $globalPolicy));
  337. }
  338. return $this->watcher;
  339. }
  340. /**
  341. * get a propagator instance for the cache
  342. *
  343. * @param \OC\Files\Storage\Storage (optional) the storage to pass to the watcher
  344. * @return \OC\Files\Cache\Propagator
  345. */
  346. public function getPropagator($storage = null) {
  347. if (!$storage) {
  348. $storage = $this;
  349. }
  350. if (!isset($storage->propagator)) {
  351. $config = \OC::$server->getSystemConfig();
  352. $storage->propagator = new Propagator($storage, \OC::$server->getDatabaseConnection(), ['appdata_' . $config->getValue('instanceid')]);
  353. }
  354. return $storage->propagator;
  355. }
  356. public function getUpdater($storage = null) {
  357. if (!$storage) {
  358. $storage = $this;
  359. }
  360. if (!isset($storage->updater)) {
  361. $storage->updater = new Updater($storage);
  362. }
  363. return $storage->updater;
  364. }
  365. public function getStorageCache($storage = null) {
  366. if (!$storage) {
  367. $storage = $this;
  368. }
  369. if (!isset($this->storageCache)) {
  370. $this->storageCache = new \OC\Files\Cache\Storage($storage);
  371. }
  372. return $this->storageCache;
  373. }
  374. /**
  375. * get the owner of a path
  376. *
  377. * @param string $path The path to get the owner
  378. * @return string|false uid or false
  379. */
  380. public function getOwner($path) {
  381. if ($this->owner === null) {
  382. $this->owner = \OC_User::getUser();
  383. }
  384. return $this->owner;
  385. }
  386. /**
  387. * get the ETag for a file or folder
  388. *
  389. * @param string $path
  390. * @return string
  391. */
  392. public function getETag($path) {
  393. return uniqid();
  394. }
  395. /**
  396. * clean a path, i.e. remove all redundant '.' and '..'
  397. * making sure that it can't point to higher than '/'
  398. *
  399. * @param string $path The path to clean
  400. * @return string cleaned path
  401. */
  402. public function cleanPath($path) {
  403. if (strlen($path) == 0 or $path[0] != '/') {
  404. $path = '/' . $path;
  405. }
  406. $output = [];
  407. foreach (explode('/', $path) as $chunk) {
  408. if ($chunk == '..') {
  409. array_pop($output);
  410. } elseif ($chunk == '.') {
  411. } else {
  412. $output[] = $chunk;
  413. }
  414. }
  415. return implode('/', $output);
  416. }
  417. /**
  418. * Test a storage for availability
  419. *
  420. * @return bool
  421. */
  422. public function test() {
  423. try {
  424. if ($this->stat('')) {
  425. return true;
  426. }
  427. \OC::$server->get(LoggerInterface::class)->info("External storage not available: stat() failed");
  428. return false;
  429. } catch (\Exception $e) {
  430. \OC::$server->get(LoggerInterface::class)->warning(
  431. "External storage not available: " . $e->getMessage(),
  432. ['exception' => $e]
  433. );
  434. return false;
  435. }
  436. }
  437. /**
  438. * get the free space in the storage
  439. *
  440. * @param string $path
  441. * @return int|float|false
  442. */
  443. public function free_space($path) {
  444. return \OCP\Files\FileInfo::SPACE_UNKNOWN;
  445. }
  446. /**
  447. * {@inheritdoc}
  448. */
  449. public function isLocal() {
  450. // the common implementation returns a temporary file by
  451. // default, which is not local
  452. return false;
  453. }
  454. /**
  455. * Check if the storage is an instance of $class or is a wrapper for a storage that is an instance of $class
  456. *
  457. * @param string $class
  458. * @return bool
  459. */
  460. public function instanceOfStorage($class) {
  461. if (ltrim($class, '\\') === 'OC\Files\Storage\Shared') {
  462. // FIXME Temporary fix to keep existing checks working
  463. $class = '\OCA\Files_Sharing\SharedStorage';
  464. }
  465. return is_a($this, $class);
  466. }
  467. /**
  468. * A custom storage implementation can return an url for direct download of a give file.
  469. *
  470. * For now the returned array can hold the parameter url - in future more attributes might follow.
  471. *
  472. * @param string $path
  473. * @return array|false
  474. */
  475. public function getDirectDownload($path) {
  476. return [];
  477. }
  478. /**
  479. * @inheritdoc
  480. * @throws InvalidPathException
  481. */
  482. public function verifyPath($path, $fileName) {
  483. // verify empty and dot files
  484. $trimmed = trim($fileName);
  485. if ($trimmed === '') {
  486. throw new EmptyFileNameException();
  487. }
  488. if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
  489. throw new InvalidDirectoryException();
  490. }
  491. if (!\OC::$server->getDatabaseConnection()->supports4ByteText()) {
  492. // verify database - e.g. mysql only 3-byte chars
  493. if (preg_match('%(?:
  494. \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
  495. | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
  496. | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
  497. )%xs', $fileName)) {
  498. throw new InvalidCharacterInPathException();
  499. }
  500. }
  501. // 255 characters is the limit on common file systems (ext/xfs)
  502. // oc_filecache has a 250 char length limit for the filename
  503. if (isset($fileName[250])) {
  504. throw new FileNameTooLongException();
  505. }
  506. // NOTE: $path will remain unverified for now
  507. $this->verifyPosixPath($fileName);
  508. }
  509. /**
  510. * @param string $fileName
  511. * @throws InvalidPathException
  512. */
  513. protected function verifyPosixPath($fileName) {
  514. $this->scanForInvalidCharacters($fileName, "\\/");
  515. $fileName = trim($fileName);
  516. $reservedNames = ['*'];
  517. if (in_array($fileName, $reservedNames)) {
  518. throw new ReservedWordException();
  519. }
  520. }
  521. /**
  522. * @param string $fileName
  523. * @param string $invalidChars
  524. * @throws InvalidPathException
  525. */
  526. private function scanForInvalidCharacters($fileName, $invalidChars) {
  527. foreach (str_split($invalidChars) as $char) {
  528. if (strpos($fileName, $char) !== false) {
  529. throw new InvalidCharacterInPathException();
  530. }
  531. }
  532. $sanitizedFileName = filter_var($fileName, FILTER_UNSAFE_RAW, FILTER_FLAG_STRIP_LOW);
  533. if ($sanitizedFileName !== $fileName) {
  534. throw new InvalidCharacterInPathException();
  535. }
  536. }
  537. /**
  538. * @param array $options
  539. */
  540. public function setMountOptions(array $options) {
  541. $this->mountOptions = $options;
  542. }
  543. /**
  544. * @param string $name
  545. * @param mixed $default
  546. * @return mixed
  547. */
  548. public function getMountOption($name, $default = null) {
  549. return isset($this->mountOptions[$name]) ? $this->mountOptions[$name] : $default;
  550. }
  551. /**
  552. * @param IStorage $sourceStorage
  553. * @param string $sourceInternalPath
  554. * @param string $targetInternalPath
  555. * @param bool $preserveMtime
  556. * @return bool
  557. */
  558. public function copyFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = false) {
  559. if ($sourceStorage === $this) {
  560. return $this->copy($sourceInternalPath, $targetInternalPath);
  561. }
  562. if ($sourceStorage->is_dir($sourceInternalPath)) {
  563. $dh = $sourceStorage->opendir($sourceInternalPath);
  564. $result = $this->mkdir($targetInternalPath);
  565. if (is_resource($dh)) {
  566. $result = true;
  567. while ($result and ($file = readdir($dh)) !== false) {
  568. if (!Filesystem::isIgnoredDir($file)) {
  569. $result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath . '/' . $file, $targetInternalPath . '/' . $file);
  570. }
  571. }
  572. }
  573. } else {
  574. $source = $sourceStorage->fopen($sourceInternalPath, 'r');
  575. $result = false;
  576. if ($source) {
  577. try {
  578. $this->writeStream($targetInternalPath, $source);
  579. $result = true;
  580. } catch (\Exception $e) {
  581. \OC::$server->get(LoggerInterface::class)->warning('Failed to copy stream to storage', ['exception' => $e]);
  582. }
  583. }
  584. if ($result && $preserveMtime) {
  585. $mtime = $sourceStorage->filemtime($sourceInternalPath);
  586. $this->touch($targetInternalPath, is_int($mtime) ? $mtime : null);
  587. }
  588. if (!$result) {
  589. // delete partially written target file
  590. $this->unlink($targetInternalPath);
  591. // delete cache entry that was created by fopen
  592. $this->getCache()->remove($targetInternalPath);
  593. }
  594. }
  595. return (bool)$result;
  596. }
  597. /**
  598. * Check if a storage is the same as the current one, including wrapped storages
  599. *
  600. * @param IStorage $storage
  601. * @return bool
  602. */
  603. private function isSameStorage(IStorage $storage): bool {
  604. while ($storage->instanceOfStorage(Wrapper::class)) {
  605. /**
  606. * @var Wrapper $sourceStorage
  607. */
  608. $storage = $storage->getWrapperStorage();
  609. }
  610. return $storage === $this;
  611. }
  612. /**
  613. * @param IStorage $sourceStorage
  614. * @param string $sourceInternalPath
  615. * @param string $targetInternalPath
  616. * @return bool
  617. */
  618. public function moveFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
  619. if ($this->isSameStorage($sourceStorage)) {
  620. // resolve any jailed paths
  621. while ($sourceStorage->instanceOfStorage(Jail::class)) {
  622. /**
  623. * @var Jail $sourceStorage
  624. */
  625. $sourceInternalPath = $sourceStorage->getUnjailedPath($sourceInternalPath);
  626. $sourceStorage = $sourceStorage->getUnjailedStorage();
  627. }
  628. return $this->rename($sourceInternalPath, $targetInternalPath);
  629. }
  630. if (!$sourceStorage->isDeletable($sourceInternalPath)) {
  631. return false;
  632. }
  633. $result = $this->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, true);
  634. if ($result) {
  635. if ($sourceStorage->is_dir($sourceInternalPath)) {
  636. $result = $sourceStorage->rmdir($sourceInternalPath);
  637. } else {
  638. $result = $sourceStorage->unlink($sourceInternalPath);
  639. }
  640. }
  641. return $result;
  642. }
  643. /**
  644. * @inheritdoc
  645. */
  646. public function getMetaData($path) {
  647. if (Filesystem::isFileBlacklisted($path)) {
  648. throw new ForbiddenException('Invalid path: ' . $path, false);
  649. }
  650. $permissions = $this->getPermissions($path);
  651. if (!$permissions & \OCP\Constants::PERMISSION_READ) {
  652. //can't read, nothing we can do
  653. return null;
  654. }
  655. $data = [];
  656. $data['mimetype'] = $this->getMimeType($path);
  657. $data['mtime'] = $this->filemtime($path);
  658. if ($data['mtime'] === false) {
  659. $data['mtime'] = time();
  660. }
  661. if ($data['mimetype'] == 'httpd/unix-directory') {
  662. $data['size'] = -1; //unknown
  663. } else {
  664. $data['size'] = $this->filesize($path);
  665. }
  666. $data['etag'] = $this->getETag($path);
  667. $data['storage_mtime'] = $data['mtime'];
  668. $data['permissions'] = $permissions;
  669. $data['name'] = basename($path);
  670. return $data;
  671. }
  672. /**
  673. * @param string $path
  674. * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
  675. * @param \OCP\Lock\ILockingProvider $provider
  676. * @throws \OCP\Lock\LockedException
  677. */
  678. public function acquireLock($path, $type, ILockingProvider $provider) {
  679. $logger = $this->getLockLogger();
  680. if ($logger) {
  681. $typeString = ($type === ILockingProvider::LOCK_SHARED) ? 'shared' : 'exclusive';
  682. $logger->info(
  683. sprintf(
  684. 'acquire %s lock on "%s" on storage "%s"',
  685. $typeString,
  686. $path,
  687. $this->getId()
  688. ),
  689. [
  690. 'app' => 'locking',
  691. ]
  692. );
  693. }
  694. try {
  695. $provider->acquireLock('files/' . md5($this->getId() . '::' . trim($path, '/')), $type, $this->getId() . '::' . $path);
  696. } catch (LockedException $e) {
  697. $e = new LockedException($e->getPath(), $e, $e->getExistingLock(), $path);
  698. if ($logger) {
  699. $logger->info($e->getMessage(), ['exception' => $e]);
  700. }
  701. throw $e;
  702. }
  703. }
  704. /**
  705. * @param string $path
  706. * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
  707. * @param \OCP\Lock\ILockingProvider $provider
  708. * @throws \OCP\Lock\LockedException
  709. */
  710. public function releaseLock($path, $type, ILockingProvider $provider) {
  711. $logger = $this->getLockLogger();
  712. if ($logger) {
  713. $typeString = ($type === ILockingProvider::LOCK_SHARED) ? 'shared' : 'exclusive';
  714. $logger->info(
  715. sprintf(
  716. 'release %s lock on "%s" on storage "%s"',
  717. $typeString,
  718. $path,
  719. $this->getId()
  720. ),
  721. [
  722. 'app' => 'locking',
  723. ]
  724. );
  725. }
  726. try {
  727. $provider->releaseLock('files/' . md5($this->getId() . '::' . trim($path, '/')), $type);
  728. } catch (LockedException $e) {
  729. $e = new LockedException($e->getPath(), $e, $e->getExistingLock(), $path);
  730. if ($logger) {
  731. $logger->info($e->getMessage(), ['exception' => $e]);
  732. }
  733. throw $e;
  734. }
  735. }
  736. /**
  737. * @param string $path
  738. * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
  739. * @param \OCP\Lock\ILockingProvider $provider
  740. * @throws \OCP\Lock\LockedException
  741. */
  742. public function changeLock($path, $type, ILockingProvider $provider) {
  743. $logger = $this->getLockLogger();
  744. if ($logger) {
  745. $typeString = ($type === ILockingProvider::LOCK_SHARED) ? 'shared' : 'exclusive';
  746. $logger->info(
  747. sprintf(
  748. 'change lock on "%s" to %s on storage "%s"',
  749. $path,
  750. $typeString,
  751. $this->getId()
  752. ),
  753. [
  754. 'app' => 'locking',
  755. ]
  756. );
  757. }
  758. try {
  759. $provider->changeLock('files/' . md5($this->getId() . '::' . trim($path, '/')), $type);
  760. } catch (LockedException $e) {
  761. $e = new LockedException($e->getPath(), $e, $e->getExistingLock(), $path);
  762. if ($logger) {
  763. $logger->info($e->getMessage(), ['exception' => $e]);
  764. }
  765. throw $e;
  766. }
  767. }
  768. private function getLockLogger(): ?LoggerInterface {
  769. if (is_null($this->shouldLogLocks)) {
  770. $this->shouldLogLocks = \OC::$server->getConfig()->getSystemValueBool('filelocking.debug', false);
  771. $this->logger = $this->shouldLogLocks ? \OC::$server->get(LoggerInterface::class) : null;
  772. }
  773. return $this->logger;
  774. }
  775. /**
  776. * @return array [ available, last_checked ]
  777. */
  778. public function getAvailability() {
  779. return $this->getStorageCache()->getAvailability();
  780. }
  781. /**
  782. * @param bool $isAvailable
  783. */
  784. public function setAvailability($isAvailable) {
  785. $this->getStorageCache()->setAvailability($isAvailable);
  786. }
  787. /**
  788. * @return bool
  789. */
  790. public function needsPartFile() {
  791. return true;
  792. }
  793. /**
  794. * fallback implementation
  795. *
  796. * @param string $path
  797. * @param resource $stream
  798. * @param int $size
  799. * @return int
  800. */
  801. public function writeStream(string $path, $stream, int $size = null): int {
  802. $target = $this->fopen($path, 'w');
  803. if (!$target) {
  804. throw new GenericFileException("Failed to open $path for writing");
  805. }
  806. try {
  807. [$count, $result] = \OC_Helper::streamCopy($stream, $target);
  808. if (!$result) {
  809. throw new GenericFileException("Failed to copy stream");
  810. }
  811. } finally {
  812. fclose($target);
  813. fclose($stream);
  814. }
  815. return $count;
  816. }
  817. public function getDirectoryContent($directory): \Traversable {
  818. $dh = $this->opendir($directory);
  819. if (is_resource($dh)) {
  820. $basePath = rtrim($directory, '/');
  821. while (($file = readdir($dh)) !== false) {
  822. if (!Filesystem::isIgnoredDir($file)) {
  823. $childPath = $basePath . '/' . trim($file, '/');
  824. $metadata = $this->getMetaData($childPath);
  825. if ($metadata !== null) {
  826. yield $metadata;
  827. }
  828. }
  829. }
  830. }
  831. }
  832. }