Common.php 22 KB

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