Common.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763
  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\ObjectStore\ObjectStoreStorage;
  17. use OC\Files\Storage\Wrapper\Jail;
  18. use OC\Files\Storage\Wrapper\Wrapper;
  19. use OCP\Files\Cache\ICache;
  20. use OCP\Files\Cache\IPropagator;
  21. use OCP\Files\Cache\IScanner;
  22. use OCP\Files\Cache\IUpdater;
  23. use OCP\Files\Cache\IWatcher;
  24. use OCP\Files\ForbiddenException;
  25. use OCP\Files\GenericFileException;
  26. use OCP\Files\IFilenameValidator;
  27. use OCP\Files\InvalidPathException;
  28. use OCP\Files\Storage\IConstructableStorage;
  29. use OCP\Files\Storage\ILockingStorage;
  30. use OCP\Files\Storage\IStorage;
  31. use OCP\Files\Storage\IWriteStreamStorage;
  32. use OCP\Files\StorageNotAvailableException;
  33. use OCP\Lock\ILockingProvider;
  34. use OCP\Lock\LockedException;
  35. use OCP\Server;
  36. use Psr\Log\LoggerInterface;
  37. /**
  38. * Storage backend class for providing common filesystem operation methods
  39. * which are not storage-backend specific.
  40. *
  41. * \OC\Files\Storage\Common is never used directly; it is extended by all other
  42. * storage backends, where its methods may be overridden, and additional
  43. * (backend-specific) methods are defined.
  44. *
  45. * Some \OC\Files\Storage\Common methods call functions which are first defined
  46. * in classes which extend it, e.g. $this->stat() .
  47. */
  48. abstract class Common implements Storage, ILockingStorage, IWriteStreamStorage, IConstructableStorage {
  49. use LocalTempFileTrait;
  50. protected ?Cache $cache = null;
  51. protected ?Scanner $scanner = null;
  52. protected ?Watcher $watcher = null;
  53. protected ?Propagator $propagator = null;
  54. protected $storageCache;
  55. protected ?Updater $updater = null;
  56. protected array $mountOptions = [];
  57. protected $owner = null;
  58. private ?bool $shouldLogLocks = null;
  59. private ?LoggerInterface $logger = null;
  60. private ?IFilenameValidator $filenameValidator = null;
  61. public function __construct(array $parameters) {
  62. }
  63. protected function remove(string $path): bool {
  64. if ($this->is_dir($path)) {
  65. return $this->rmdir($path);
  66. } elseif ($this->is_file($path)) {
  67. return $this->unlink($path);
  68. } else {
  69. return false;
  70. }
  71. }
  72. public function is_dir(string $path): bool {
  73. return $this->filetype($path) === 'dir';
  74. }
  75. public function is_file(string $path): bool {
  76. return $this->filetype($path) === 'file';
  77. }
  78. public function filesize(string $path): int|float|false {
  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(string $path): bool {
  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(string $path): bool {
  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(string $path): bool {
  102. if ($this->is_dir($path) && $this->isUpdatable($path)) {
  103. return true;
  104. }
  105. return false;
  106. }
  107. public function isDeletable(string $path): bool {
  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(string $path): bool {
  115. return $this->isReadable($path);
  116. }
  117. public function getPermissions(string $path): int {
  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(string $path): int|false {
  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(string $path): string|false {
  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(string $path, mixed $data): int|float|false {
  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(string $source, string $target): bool {
  164. $this->remove($target);
  165. $this->removeCachedFile($source);
  166. return $this->copy($source, $target) and $this->remove($source);
  167. }
  168. public function copy(string $source, string $target): bool {
  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(string $path): string|false {
  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(string $type, string $path, bool $raw = false): string|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 getLocalFile(string $path): string|false {
  211. return $this->getCachedFile($path);
  212. }
  213. private function addLocalFolder(string $path, string $target): void {
  214. $dh = $this->opendir($path);
  215. if (is_resource($dh)) {
  216. while (($file = readdir($dh)) !== false) {
  217. if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
  218. if ($this->is_dir($path . '/' . $file)) {
  219. mkdir($target . '/' . $file);
  220. $this->addLocalFolder($path . '/' . $file, $target . '/' . $file);
  221. } else {
  222. $tmp = $this->toTmpFile($path . '/' . $file);
  223. rename($tmp, $target . '/' . $file);
  224. }
  225. }
  226. }
  227. }
  228. }
  229. protected function searchInDir(string $query, string $dir = ''): array {
  230. $files = [];
  231. $dh = $this->opendir($dir);
  232. if (is_resource($dh)) {
  233. while (($item = readdir($dh)) !== false) {
  234. if (\OC\Files\Filesystem::isIgnoredDir($item)) {
  235. continue;
  236. }
  237. if (strstr(strtolower($item), strtolower($query)) !== false) {
  238. $files[] = $dir . '/' . $item;
  239. }
  240. if ($this->is_dir($dir . '/' . $item)) {
  241. $files = array_merge($files, $this->searchInDir($query, $dir . '/' . $item));
  242. }
  243. }
  244. }
  245. closedir($dh);
  246. return $files;
  247. }
  248. /**
  249. * @inheritDoc
  250. * Check if a file or folder has been updated since $time
  251. *
  252. * The method is only used to check if the cache needs to be updated. Storage backends that don't support checking
  253. * the mtime should always return false here. As a result storage implementations that always return false expect
  254. * exclusive access to the backend and will not pick up files that have been added in a way that circumvents
  255. * Nextcloud filesystem.
  256. */
  257. public function hasUpdated(string $path, int $time): bool {
  258. return $this->filemtime($path) > $time;
  259. }
  260. protected function getCacheDependencies(): CacheDependencies {
  261. static $dependencies = null;
  262. if (!$dependencies) {
  263. $dependencies = Server::get(CacheDependencies::class);
  264. }
  265. return $dependencies;
  266. }
  267. public function getCache(string $path = '', ?IStorage $storage = null): ICache {
  268. if (!$storage) {
  269. $storage = $this;
  270. }
  271. /** @var self $storage */
  272. if (!isset($storage->cache)) {
  273. $storage->cache = new Cache($storage, $this->getCacheDependencies());
  274. }
  275. return $storage->cache;
  276. }
  277. public function getScanner(string $path = '', ?IStorage $storage = null): IScanner {
  278. if (!$storage) {
  279. $storage = $this;
  280. }
  281. if (!$storage->instanceOfStorage(self::class)) {
  282. throw new \InvalidArgumentException('Storage is not of the correct class');
  283. }
  284. if (!isset($storage->scanner)) {
  285. $storage->scanner = new Scanner($storage);
  286. }
  287. return $storage->scanner;
  288. }
  289. public function getWatcher(string $path = '', ?IStorage $storage = null): IWatcher {
  290. if (!$storage) {
  291. $storage = $this;
  292. }
  293. if (!isset($this->watcher)) {
  294. $this->watcher = new Watcher($storage);
  295. $globalPolicy = \OC::$server->getConfig()->getSystemValue('filesystem_check_changes', Watcher::CHECK_NEVER);
  296. $this->watcher->setPolicy((int)$this->getMountOption('filesystem_check_changes', $globalPolicy));
  297. }
  298. return $this->watcher;
  299. }
  300. public function getPropagator(?IStorage $storage = null): IPropagator {
  301. if (!$storage) {
  302. $storage = $this;
  303. }
  304. if (!$storage->instanceOfStorage(self::class)) {
  305. throw new \InvalidArgumentException('Storage is not of the correct class');
  306. }
  307. /** @var self $storage */
  308. if (!isset($storage->propagator)) {
  309. $config = \OC::$server->getSystemConfig();
  310. $storage->propagator = new Propagator($storage, \OC::$server->getDatabaseConnection(), ['appdata_' . $config->getValue('instanceid')]);
  311. }
  312. return $storage->propagator;
  313. }
  314. public function getUpdater(?IStorage $storage = null): IUpdater {
  315. if (!$storage) {
  316. $storage = $this;
  317. }
  318. if (!$storage->instanceOfStorage(self::class)) {
  319. throw new \InvalidArgumentException('Storage is not of the correct class');
  320. }
  321. /** @var self $storage */
  322. if (!isset($storage->updater)) {
  323. $storage->updater = new Updater($storage);
  324. }
  325. return $storage->updater;
  326. }
  327. public function getStorageCache(?IStorage $storage = null): \OC\Files\Cache\Storage {
  328. /** @var Cache $cache */
  329. $cache = $this->getCache(storage: $storage);
  330. return $cache->getStorageCache();
  331. }
  332. public function getOwner(string $path): string|false {
  333. if ($this->owner === null) {
  334. $this->owner = \OC_User::getUser();
  335. }
  336. return $this->owner;
  337. }
  338. public function getETag(string $path): string|false {
  339. return uniqid();
  340. }
  341. /**
  342. * clean a path, i.e. remove all redundant '.' and '..'
  343. * making sure that it can't point to higher than '/'
  344. *
  345. * @param string $path The path to clean
  346. * @return string cleaned path
  347. */
  348. public function cleanPath(string $path): string {
  349. if (strlen($path) == 0 or $path[0] != '/') {
  350. $path = '/' . $path;
  351. }
  352. $output = [];
  353. foreach (explode('/', $path) as $chunk) {
  354. if ($chunk == '..') {
  355. array_pop($output);
  356. } elseif ($chunk == '.') {
  357. } else {
  358. $output[] = $chunk;
  359. }
  360. }
  361. return implode('/', $output);
  362. }
  363. /**
  364. * Test a storage for availability
  365. */
  366. public function test(): bool {
  367. try {
  368. if ($this->stat('')) {
  369. return true;
  370. }
  371. \OC::$server->get(LoggerInterface::class)->info('External storage not available: stat() failed');
  372. return false;
  373. } catch (\Exception $e) {
  374. \OC::$server->get(LoggerInterface::class)->warning(
  375. 'External storage not available: ' . $e->getMessage(),
  376. ['exception' => $e]
  377. );
  378. return false;
  379. }
  380. }
  381. public function free_space(string $path): int|float|false {
  382. return \OCP\Files\FileInfo::SPACE_UNKNOWN;
  383. }
  384. public function isLocal(): bool {
  385. // the common implementation returns a temporary file by
  386. // default, which is not local
  387. return false;
  388. }
  389. /**
  390. * Check if the storage is an instance of $class or is a wrapper for a storage that is an instance of $class
  391. */
  392. public function instanceOfStorage(string $class): bool {
  393. if (ltrim($class, '\\') === 'OC\Files\Storage\Shared') {
  394. // FIXME Temporary fix to keep existing checks working
  395. $class = '\OCA\Files_Sharing\SharedStorage';
  396. }
  397. return is_a($this, $class);
  398. }
  399. /**
  400. * A custom storage implementation can return an url for direct download of a give file.
  401. *
  402. * For now the returned array can hold the parameter url - in future more attributes might follow.
  403. */
  404. public function getDirectDownload(string $path): array|false {
  405. return [];
  406. }
  407. public function verifyPath(string $path, string $fileName): void {
  408. $this->getFilenameValidator()
  409. ->validateFilename($fileName);
  410. // verify also the path is valid
  411. if ($path && $path !== '/' && $path !== '.') {
  412. try {
  413. $this->verifyPath(dirname($path), basename($path));
  414. } catch (InvalidPathException $e) {
  415. // Ignore invalid file type exceptions on directories
  416. if ($e->getCode() !== FilenameValidator::INVALID_FILE_TYPE) {
  417. $l = \OCP\Util::getL10N('lib');
  418. throw new InvalidPathException($l->t('Invalid parent path'), previous: $e);
  419. }
  420. }
  421. }
  422. }
  423. /**
  424. * Get the filename validator
  425. * (cached for performance)
  426. */
  427. protected function getFilenameValidator(): IFilenameValidator {
  428. if ($this->filenameValidator === null) {
  429. $this->filenameValidator = \OCP\Server::get(IFilenameValidator::class);
  430. }
  431. return $this->filenameValidator;
  432. }
  433. public function setMountOptions(array $options): void {
  434. $this->mountOptions = $options;
  435. }
  436. public function getMountOption(string $name, mixed $default = null): mixed {
  437. return $this->mountOptions[$name] ?? $default;
  438. }
  439. public function copyFromStorage(IStorage $sourceStorage, string $sourceInternalPath, string $targetInternalPath, bool $preserveMtime = false): bool {
  440. if ($sourceStorage === $this) {
  441. return $this->copy($sourceInternalPath, $targetInternalPath);
  442. }
  443. if ($sourceStorage->is_dir($sourceInternalPath)) {
  444. $dh = $sourceStorage->opendir($sourceInternalPath);
  445. $result = $this->mkdir($targetInternalPath);
  446. if (is_resource($dh)) {
  447. $result = true;
  448. while ($result and ($file = readdir($dh)) !== false) {
  449. if (!Filesystem::isIgnoredDir($file)) {
  450. $result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath . '/' . $file, $targetInternalPath . '/' . $file);
  451. }
  452. }
  453. }
  454. } else {
  455. $source = $sourceStorage->fopen($sourceInternalPath, 'r');
  456. $result = false;
  457. if ($source) {
  458. try {
  459. $this->writeStream($targetInternalPath, $source);
  460. $result = true;
  461. } catch (\Exception $e) {
  462. \OC::$server->get(LoggerInterface::class)->warning('Failed to copy stream to storage', ['exception' => $e]);
  463. }
  464. }
  465. if ($result && $preserveMtime) {
  466. $mtime = $sourceStorage->filemtime($sourceInternalPath);
  467. $this->touch($targetInternalPath, is_int($mtime) ? $mtime : null);
  468. }
  469. if (!$result) {
  470. // delete partially written target file
  471. $this->unlink($targetInternalPath);
  472. // delete cache entry that was created by fopen
  473. $this->getCache()->remove($targetInternalPath);
  474. }
  475. }
  476. return (bool)$result;
  477. }
  478. /**
  479. * Check if a storage is the same as the current one, including wrapped storages
  480. */
  481. private function isSameStorage(IStorage $storage): bool {
  482. while ($storage->instanceOfStorage(Wrapper::class)) {
  483. /**
  484. * @var Wrapper $storage
  485. */
  486. $storage = $storage->getWrapperStorage();
  487. }
  488. return $storage === $this;
  489. }
  490. public function moveFromStorage(IStorage $sourceStorage, string $sourceInternalPath, string $targetInternalPath): bool {
  491. if ($this->isSameStorage($sourceStorage)) {
  492. // resolve any jailed paths
  493. while ($sourceStorage->instanceOfStorage(Jail::class)) {
  494. /**
  495. * @var Jail $sourceStorage
  496. */
  497. $sourceInternalPath = $sourceStorage->getUnjailedPath($sourceInternalPath);
  498. $sourceStorage = $sourceStorage->getUnjailedStorage();
  499. }
  500. return $this->rename($sourceInternalPath, $targetInternalPath);
  501. }
  502. if (!$sourceStorage->isDeletable($sourceInternalPath)) {
  503. return false;
  504. }
  505. $result = $this->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, true);
  506. if ($result) {
  507. if ($sourceStorage->instanceOfStorage(ObjectStoreStorage::class)) {
  508. /** @var ObjectStoreStorage $sourceStorage */
  509. $sourceStorage->setPreserveCacheOnDelete(true);
  510. }
  511. try {
  512. if ($sourceStorage->is_dir($sourceInternalPath)) {
  513. $result = $sourceStorage->rmdir($sourceInternalPath);
  514. } else {
  515. $result = $sourceStorage->unlink($sourceInternalPath);
  516. }
  517. } finally {
  518. if ($sourceStorage->instanceOfStorage(ObjectStoreStorage::class)) {
  519. /** @var ObjectStoreStorage $sourceStorage */
  520. $sourceStorage->setPreserveCacheOnDelete(false);
  521. }
  522. }
  523. }
  524. return $result;
  525. }
  526. public function getMetaData(string $path): ?array {
  527. if (Filesystem::isFileBlacklisted($path)) {
  528. throw new ForbiddenException('Invalid path: ' . $path, false);
  529. }
  530. $permissions = $this->getPermissions($path);
  531. if (!$permissions & \OCP\Constants::PERMISSION_READ) {
  532. //can't read, nothing we can do
  533. return null;
  534. }
  535. $data = [];
  536. $data['mimetype'] = $this->getMimeType($path);
  537. $data['mtime'] = $this->filemtime($path);
  538. if ($data['mtime'] === false) {
  539. $data['mtime'] = time();
  540. }
  541. if ($data['mimetype'] == 'httpd/unix-directory') {
  542. $data['size'] = -1; //unknown
  543. } else {
  544. $data['size'] = $this->filesize($path);
  545. }
  546. $data['etag'] = $this->getETag($path);
  547. $data['storage_mtime'] = $data['mtime'];
  548. $data['permissions'] = $permissions;
  549. $data['name'] = basename($path);
  550. return $data;
  551. }
  552. public function acquireLock(string $path, int $type, ILockingProvider $provider): void {
  553. $logger = $this->getLockLogger();
  554. if ($logger) {
  555. $typeString = ($type === ILockingProvider::LOCK_SHARED) ? 'shared' : 'exclusive';
  556. $logger->info(
  557. sprintf(
  558. 'acquire %s lock on "%s" on storage "%s"',
  559. $typeString,
  560. $path,
  561. $this->getId()
  562. ),
  563. [
  564. 'app' => 'locking',
  565. ]
  566. );
  567. }
  568. try {
  569. $provider->acquireLock('files/' . md5($this->getId() . '::' . trim($path, '/')), $type, $this->getId() . '::' . $path);
  570. } catch (LockedException $e) {
  571. $e = new LockedException($e->getPath(), $e, $e->getExistingLock(), $path);
  572. if ($logger) {
  573. $logger->info($e->getMessage(), ['exception' => $e]);
  574. }
  575. throw $e;
  576. }
  577. }
  578. public function releaseLock(string $path, int $type, ILockingProvider $provider): void {
  579. $logger = $this->getLockLogger();
  580. if ($logger) {
  581. $typeString = ($type === ILockingProvider::LOCK_SHARED) ? 'shared' : 'exclusive';
  582. $logger->info(
  583. sprintf(
  584. 'release %s lock on "%s" on storage "%s"',
  585. $typeString,
  586. $path,
  587. $this->getId()
  588. ),
  589. [
  590. 'app' => 'locking',
  591. ]
  592. );
  593. }
  594. try {
  595. $provider->releaseLock('files/' . md5($this->getId() . '::' . trim($path, '/')), $type);
  596. } catch (LockedException $e) {
  597. $e = new LockedException($e->getPath(), $e, $e->getExistingLock(), $path);
  598. if ($logger) {
  599. $logger->info($e->getMessage(), ['exception' => $e]);
  600. }
  601. throw $e;
  602. }
  603. }
  604. public function changeLock(string $path, int $type, ILockingProvider $provider): void {
  605. $logger = $this->getLockLogger();
  606. if ($logger) {
  607. $typeString = ($type === ILockingProvider::LOCK_SHARED) ? 'shared' : 'exclusive';
  608. $logger->info(
  609. sprintf(
  610. 'change lock on "%s" to %s on storage "%s"',
  611. $path,
  612. $typeString,
  613. $this->getId()
  614. ),
  615. [
  616. 'app' => 'locking',
  617. ]
  618. );
  619. }
  620. try {
  621. $provider->changeLock('files/' . md5($this->getId() . '::' . trim($path, '/')), $type);
  622. } catch (LockedException $e) {
  623. $e = new LockedException($e->getPath(), $e, $e->getExistingLock(), $path);
  624. if ($logger) {
  625. $logger->info($e->getMessage(), ['exception' => $e]);
  626. }
  627. throw $e;
  628. }
  629. }
  630. private function getLockLogger(): ?LoggerInterface {
  631. if (is_null($this->shouldLogLocks)) {
  632. $this->shouldLogLocks = \OC::$server->getConfig()->getSystemValueBool('filelocking.debug', false);
  633. $this->logger = $this->shouldLogLocks ? \OC::$server->get(LoggerInterface::class) : null;
  634. }
  635. return $this->logger;
  636. }
  637. /**
  638. * @return array [ available, last_checked ]
  639. */
  640. public function getAvailability(): array {
  641. return $this->getStorageCache()->getAvailability();
  642. }
  643. public function setAvailability(bool $isAvailable): void {
  644. $this->getStorageCache()->setAvailability($isAvailable);
  645. }
  646. public function setOwner(?string $user): void {
  647. $this->owner = $user;
  648. }
  649. public function needsPartFile(): bool {
  650. return true;
  651. }
  652. public function writeStream(string $path, $stream, ?int $size = null): int {
  653. $target = $this->fopen($path, 'w');
  654. if (!$target) {
  655. throw new GenericFileException("Failed to open $path for writing");
  656. }
  657. try {
  658. [$count, $result] = \OC_Helper::streamCopy($stream, $target);
  659. if (!$result) {
  660. throw new GenericFileException('Failed to copy stream');
  661. }
  662. } finally {
  663. fclose($target);
  664. fclose($stream);
  665. }
  666. return $count;
  667. }
  668. public function getDirectoryContent(string $directory): \Traversable {
  669. $dh = $this->opendir($directory);
  670. if ($dh === false) {
  671. throw new StorageNotAvailableException('Directory listing failed');
  672. }
  673. if (is_resource($dh)) {
  674. $basePath = rtrim($directory, '/');
  675. while (($file = readdir($dh)) !== false) {
  676. if (!Filesystem::isIgnoredDir($file)) {
  677. $childPath = $basePath . '/' . trim($file, '/');
  678. $metadata = $this->getMetaData($childPath);
  679. if ($metadata !== null) {
  680. yield $metadata;
  681. }
  682. }
  683. }
  684. }
  685. }
  686. }