Common.php 22 KB

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