Common.php 24 KB

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