Common.php 21 KB

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