1
0

Common.php 22 KB

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