1
0

Common.php 22 KB

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