1
0

Common.php 24 KB

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