Common.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833
  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. $config = \OC::$server->getSystemConfig();
  337. $storage->propagator = new Propagator($storage, \OC::$server->getDatabaseConnection(), ['appdata_' . $config->getValue('instanceid')]);
  338. }
  339. return $storage->propagator;
  340. }
  341. public function getUpdater($storage = null) {
  342. if (!$storage) {
  343. $storage = $this;
  344. }
  345. if (!isset($storage->updater)) {
  346. $storage->updater = new Updater($storage);
  347. }
  348. return $storage->updater;
  349. }
  350. public function getStorageCache($storage = null) {
  351. if (!$storage) {
  352. $storage = $this;
  353. }
  354. if (!isset($this->storageCache)) {
  355. $this->storageCache = new \OC\Files\Cache\Storage($storage);
  356. }
  357. return $this->storageCache;
  358. }
  359. /**
  360. * get the owner of a path
  361. *
  362. * @param string $path The path to get the owner
  363. * @return string|false uid or false
  364. */
  365. public function getOwner($path) {
  366. if ($this->owner === null) {
  367. $this->owner = \OC_User::getUser();
  368. }
  369. return $this->owner;
  370. }
  371. /**
  372. * get the ETag for a file or folder
  373. *
  374. * @param string $path
  375. * @return string
  376. */
  377. public function getETag($path) {
  378. return uniqid();
  379. }
  380. /**
  381. * clean a path, i.e. remove all redundant '.' and '..'
  382. * making sure that it can't point to higher than '/'
  383. *
  384. * @param string $path The path to clean
  385. * @return string cleaned path
  386. */
  387. public function cleanPath($path) {
  388. if (strlen($path) == 0 or $path[0] != '/') {
  389. $path = '/' . $path;
  390. }
  391. $output = array();
  392. foreach (explode('/', $path) as $chunk) {
  393. if ($chunk == '..') {
  394. array_pop($output);
  395. } else if ($chunk == '.') {
  396. } else {
  397. $output[] = $chunk;
  398. }
  399. }
  400. return implode('/', $output);
  401. }
  402. /**
  403. * Test a storage for availability
  404. *
  405. * @return bool
  406. */
  407. public function test() {
  408. try {
  409. if ($this->stat('')) {
  410. return true;
  411. }
  412. \OC::$server->getLogger()->info("External storage not available: stat() failed");
  413. return false;
  414. } catch (\Exception $e) {
  415. \OC::$server->getLogger()->info("External storage not available: " . $e->getMessage());
  416. \OC::$server->getLogger()->logException($e, ['level' => ILogger::DEBUG]);
  417. return false;
  418. }
  419. }
  420. /**
  421. * get the free space in the storage
  422. *
  423. * @param string $path
  424. * @return int|false
  425. */
  426. public function free_space($path) {
  427. return \OCP\Files\FileInfo::SPACE_UNKNOWN;
  428. }
  429. /**
  430. * {@inheritdoc}
  431. */
  432. public function isLocal() {
  433. // the common implementation returns a temporary file by
  434. // default, which is not local
  435. return false;
  436. }
  437. /**
  438. * Check if the storage is an instance of $class or is a wrapper for a storage that is an instance of $class
  439. *
  440. * @param string $class
  441. * @return bool
  442. */
  443. public function instanceOfStorage($class) {
  444. if (ltrim($class, '\\') === 'OC\Files\Storage\Shared') {
  445. // FIXME Temporary fix to keep existing checks working
  446. $class = '\OCA\Files_Sharing\SharedStorage';
  447. }
  448. return is_a($this, $class);
  449. }
  450. /**
  451. * A custom storage implementation can return an url for direct download of a give file.
  452. *
  453. * For now the returned array can hold the parameter url - in future more attributes might follow.
  454. *
  455. * @param string $path
  456. * @return array|false
  457. */
  458. public function getDirectDownload($path) {
  459. return [];
  460. }
  461. /**
  462. * @inheritdoc
  463. * @throws InvalidPathException
  464. */
  465. public function verifyPath($path, $fileName) {
  466. // verify empty and dot files
  467. $trimmed = trim($fileName);
  468. if ($trimmed === '') {
  469. throw new EmptyFileNameException();
  470. }
  471. if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
  472. throw new InvalidDirectoryException();
  473. }
  474. if (!\OC::$server->getDatabaseConnection()->supports4ByteText()) {
  475. // verify database - e.g. mysql only 3-byte chars
  476. if (preg_match('%(?:
  477. \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
  478. | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
  479. | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
  480. )%xs', $fileName)) {
  481. throw new InvalidCharacterInPathException();
  482. }
  483. }
  484. if (isset($fileName[255])) {
  485. throw new FileNameTooLongException();
  486. }
  487. // NOTE: $path will remain unverified for now
  488. $this->verifyPosixPath($fileName);
  489. }
  490. /**
  491. * @param string $fileName
  492. * @throws InvalidPathException
  493. */
  494. protected function verifyPosixPath($fileName) {
  495. $fileName = trim($fileName);
  496. $this->scanForInvalidCharacters($fileName, "\\/");
  497. $reservedNames = ['*'];
  498. if (in_array($fileName, $reservedNames)) {
  499. throw new ReservedWordException();
  500. }
  501. }
  502. /**
  503. * @param string $fileName
  504. * @param string $invalidChars
  505. * @throws InvalidPathException
  506. */
  507. private function scanForInvalidCharacters($fileName, $invalidChars) {
  508. foreach (str_split($invalidChars) as $char) {
  509. if (strpos($fileName, $char) !== false) {
  510. throw new InvalidCharacterInPathException();
  511. }
  512. }
  513. $sanitizedFileName = filter_var($fileName, FILTER_UNSAFE_RAW, FILTER_FLAG_STRIP_LOW);
  514. if ($sanitizedFileName !== $fileName) {
  515. throw new InvalidCharacterInPathException();
  516. }
  517. }
  518. /**
  519. * @param array $options
  520. */
  521. public function setMountOptions(array $options) {
  522. $this->mountOptions = $options;
  523. }
  524. /**
  525. * @param string $name
  526. * @param mixed $default
  527. * @return mixed
  528. */
  529. public function getMountOption($name, $default = null) {
  530. return isset($this->mountOptions[$name]) ? $this->mountOptions[$name] : $default;
  531. }
  532. /**
  533. * @param IStorage $sourceStorage
  534. * @param string $sourceInternalPath
  535. * @param string $targetInternalPath
  536. * @param bool $preserveMtime
  537. * @return bool
  538. */
  539. public function copyFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = false) {
  540. if ($sourceStorage === $this) {
  541. return $this->copy($sourceInternalPath, $targetInternalPath);
  542. }
  543. if ($sourceStorage->is_dir($sourceInternalPath)) {
  544. $dh = $sourceStorage->opendir($sourceInternalPath);
  545. $result = $this->mkdir($targetInternalPath);
  546. if (is_resource($dh)) {
  547. while ($result and ($file = readdir($dh)) !== false) {
  548. if (!Filesystem::isIgnoredDir($file)) {
  549. $result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath . '/' . $file, $targetInternalPath . '/' . $file);
  550. }
  551. }
  552. }
  553. } else {
  554. $source = $sourceStorage->fopen($sourceInternalPath, 'r');
  555. // TODO: call fopen in a way that we execute again all storage wrappers
  556. // to avoid that we bypass storage wrappers which perform important actions
  557. // for this operation. Same is true for all other operations which
  558. // are not the same as the original one.Once this is fixed we also
  559. // need to adjust the encryption wrapper.
  560. $target = $this->fopen($targetInternalPath, 'w');
  561. list(, $result) = \OC_Helper::streamCopy($source, $target);
  562. if ($result and $preserveMtime) {
  563. $this->touch($targetInternalPath, $sourceStorage->filemtime($sourceInternalPath));
  564. }
  565. fclose($source);
  566. fclose($target);
  567. if (!$result) {
  568. // delete partially written target file
  569. $this->unlink($targetInternalPath);
  570. // delete cache entry that was created by fopen
  571. $this->getCache()->remove($targetInternalPath);
  572. }
  573. }
  574. return (bool)$result;
  575. }
  576. /**
  577. * @param IStorage $sourceStorage
  578. * @param string $sourceInternalPath
  579. * @param string $targetInternalPath
  580. * @return bool
  581. */
  582. public function moveFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
  583. if ($sourceStorage === $this) {
  584. return $this->rename($sourceInternalPath, $targetInternalPath);
  585. }
  586. if (!$sourceStorage->isDeletable($sourceInternalPath)) {
  587. return false;
  588. }
  589. $result = $this->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, true);
  590. if ($result) {
  591. if ($sourceStorage->is_dir($sourceInternalPath)) {
  592. $result &= $sourceStorage->rmdir($sourceInternalPath);
  593. } else {
  594. $result &= $sourceStorage->unlink($sourceInternalPath);
  595. }
  596. }
  597. return $result;
  598. }
  599. /**
  600. * @inheritdoc
  601. */
  602. public function getMetaData($path) {
  603. $permissions = $this->getPermissions($path);
  604. if (!$permissions & \OCP\Constants::PERMISSION_READ) {
  605. //can't read, nothing we can do
  606. return null;
  607. }
  608. $data = [];
  609. $data['mimetype'] = $this->getMimeType($path);
  610. $data['mtime'] = $this->filemtime($path);
  611. if ($data['mtime'] === false) {
  612. $data['mtime'] = time();
  613. }
  614. if ($data['mimetype'] == 'httpd/unix-directory') {
  615. $data['size'] = -1; //unknown
  616. } else {
  617. $data['size'] = $this->filesize($path);
  618. }
  619. $data['etag'] = $this->getETag($path);
  620. $data['storage_mtime'] = $data['mtime'];
  621. $data['permissions'] = $permissions;
  622. return $data;
  623. }
  624. /**
  625. * @param string $path
  626. * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
  627. * @param \OCP\Lock\ILockingProvider $provider
  628. * @throws \OCP\Lock\LockedException
  629. */
  630. public function acquireLock($path, $type, ILockingProvider $provider) {
  631. $logger = $this->getLockLogger();
  632. if ($logger) {
  633. $typeString = ($type === ILockingProvider::LOCK_SHARED) ? 'shared' : 'exclusive';
  634. $logger->info(
  635. sprintf(
  636. 'acquire %s lock on "%s" on storage "%s"',
  637. $typeString,
  638. $path,
  639. $this->getId()
  640. ),
  641. [
  642. 'app' => 'locking',
  643. ]
  644. );
  645. }
  646. try {
  647. $provider->acquireLock('files/' . md5($this->getId() . '::' . trim($path, '/')), $type);
  648. } catch (LockedException $e) {
  649. if ($logger) {
  650. $logger->logException($e);
  651. }
  652. throw $e;
  653. }
  654. }
  655. /**
  656. * @param string $path
  657. * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
  658. * @param \OCP\Lock\ILockingProvider $provider
  659. * @throws \OCP\Lock\LockedException
  660. */
  661. public function releaseLock($path, $type, ILockingProvider $provider) {
  662. $logger = $this->getLockLogger();
  663. if ($logger) {
  664. $typeString = ($type === ILockingProvider::LOCK_SHARED) ? 'shared' : 'exclusive';
  665. $logger->info(
  666. sprintf(
  667. 'release %s lock on "%s" on storage "%s"',
  668. $typeString,
  669. $path,
  670. $this->getId()
  671. ),
  672. [
  673. 'app' => 'locking',
  674. ]
  675. );
  676. }
  677. try {
  678. $provider->releaseLock('files/' . md5($this->getId() . '::' . trim($path, '/')), $type);
  679. } catch (LockedException $e) {
  680. if ($logger) {
  681. $logger->logException($e);
  682. }
  683. throw $e;
  684. }
  685. }
  686. /**
  687. * @param string $path
  688. * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
  689. * @param \OCP\Lock\ILockingProvider $provider
  690. * @throws \OCP\Lock\LockedException
  691. */
  692. public function changeLock($path, $type, ILockingProvider $provider) {
  693. $logger = $this->getLockLogger();
  694. if ($logger) {
  695. $typeString = ($type === ILockingProvider::LOCK_SHARED) ? 'shared' : 'exclusive';
  696. $logger->info(
  697. sprintf(
  698. 'change lock on "%s" to %s on storage "%s"',
  699. $path,
  700. $typeString,
  701. $this->getId()
  702. ),
  703. [
  704. 'app' => 'locking',
  705. ]
  706. );
  707. }
  708. try {
  709. $provider->changeLock('files/' . md5($this->getId() . '::' . trim($path, '/')), $type);
  710. } catch (LockedException $e) {
  711. \OC::$server->getLogger()->logException($e);
  712. throw $e;
  713. }
  714. }
  715. private function getLockLogger() {
  716. if (is_null($this->shouldLogLocks)) {
  717. $this->shouldLogLocks = \OC::$server->getConfig()->getSystemValue('filelocking.debug', false);
  718. $this->logger = $this->shouldLogLocks ? \OC::$server->getLogger() : null;
  719. }
  720. return $this->logger;
  721. }
  722. /**
  723. * @return array [ available, last_checked ]
  724. */
  725. public function getAvailability() {
  726. return $this->getStorageCache()->getAvailability();
  727. }
  728. /**
  729. * @param bool $isAvailable
  730. */
  731. public function setAvailability($isAvailable) {
  732. $this->getStorageCache()->setAvailability($isAvailable);
  733. }
  734. /**
  735. * @return bool
  736. */
  737. public function needsPartFile() {
  738. return true;
  739. }
  740. /**
  741. * fallback implementation
  742. *
  743. * @param string $path
  744. * @param resource $stream
  745. * @param int $size
  746. * @return int
  747. */
  748. public function writeStream(string $path, $stream, int $size = null): int {
  749. $target = $this->fopen($path, 'w');
  750. if (!$target) {
  751. return 0;
  752. }
  753. list($count, $result) = \OC_Helper::streamCopy($stream, $target);
  754. fclose($stream);
  755. fclose($target);
  756. return $count;
  757. }
  758. }