common.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  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 Sam Tuke <mail@samtuke.com>
  18. * @author scambra <sergio@entrecables.com>
  19. * @author Thomas Müller <thomas.mueller@tmit.eu>
  20. * @author Vincent Petry <pvince81@owncloud.com>
  21. *
  22. * @license AGPL-3.0
  23. *
  24. * This code is free software: you can redistribute it and/or modify
  25. * it under the terms of the GNU Affero General Public License, version 3,
  26. * as published by the Free Software Foundation.
  27. *
  28. * This program is distributed in the hope that it will be useful,
  29. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  30. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  31. * GNU Affero General Public License for more details.
  32. *
  33. * You should have received a copy of the GNU Affero General Public License, version 3,
  34. * along with this program. If not, see <http://www.gnu.org/licenses/>
  35. *
  36. */
  37. namespace OC\Files\Storage;
  38. use OC\Files\Cache\Cache;
  39. use OC\Files\Cache\Propagator;
  40. use OC\Files\Cache\Scanner;
  41. use OC\Files\Cache\Updater;
  42. use OC\Files\Filesystem;
  43. use OC\Files\Cache\Watcher;
  44. use OCP\Files\FileNameTooLongException;
  45. use OCP\Files\InvalidCharacterInPathException;
  46. use OCP\Files\InvalidPathException;
  47. use OCP\Files\ReservedWordException;
  48. use OCP\Files\Storage\ILockingStorage;
  49. use OCP\Lock\ILockingProvider;
  50. /**
  51. * Storage backend class for providing common filesystem operation methods
  52. * which are not storage-backend specific.
  53. *
  54. * \OC\Files\Storage\Common is never used directly; it is extended by all other
  55. * storage backends, where its methods may be overridden, and additional
  56. * (backend-specific) methods are defined.
  57. *
  58. * Some \OC\Files\Storage\Common methods call functions which are first defined
  59. * in classes which extend it, e.g. $this->stat() .
  60. */
  61. abstract class Common implements Storage, ILockingStorage {
  62. use LocalTempFileTrait;
  63. protected $cache;
  64. protected $scanner;
  65. protected $watcher;
  66. protected $propagator;
  67. protected $storageCache;
  68. protected $updater;
  69. protected $mountOptions = [];
  70. protected $owner = null;
  71. public function __construct($parameters) {
  72. }
  73. /**
  74. * Remove a file or folder
  75. *
  76. * @param string $path
  77. * @return bool
  78. */
  79. protected function remove($path) {
  80. if ($this->is_dir($path)) {
  81. return $this->rmdir($path);
  82. } else if ($this->is_file($path)) {
  83. return $this->unlink($path);
  84. } else {
  85. return false;
  86. }
  87. }
  88. public function is_dir($path) {
  89. return $this->filetype($path) === 'dir';
  90. }
  91. public function is_file($path) {
  92. return $this->filetype($path) === 'file';
  93. }
  94. public function filesize($path) {
  95. if ($this->is_dir($path)) {
  96. return 0; //by definition
  97. } else {
  98. $stat = $this->stat($path);
  99. if (isset($stat['size'])) {
  100. return $stat['size'];
  101. } else {
  102. return 0;
  103. }
  104. }
  105. }
  106. public function isReadable($path) {
  107. // at least check whether it exists
  108. // subclasses might want to implement this more thoroughly
  109. return $this->file_exists($path);
  110. }
  111. public function isUpdatable($path) {
  112. // at least check whether it exists
  113. // subclasses might want to implement this more thoroughly
  114. // a non-existing file/folder isn't updatable
  115. return $this->file_exists($path);
  116. }
  117. public function isCreatable($path) {
  118. if ($this->is_dir($path) && $this->isUpdatable($path)) {
  119. return true;
  120. }
  121. return false;
  122. }
  123. public function isDeletable($path) {
  124. if ($path === '' || $path === '/') {
  125. return false;
  126. }
  127. $parent = dirname($path);
  128. return $this->isUpdatable($parent) && $this->isUpdatable($path);
  129. }
  130. public function isSharable($path) {
  131. return $this->isReadable($path);
  132. }
  133. public function getPermissions($path) {
  134. $permissions = 0;
  135. if ($this->isCreatable($path)) {
  136. $permissions |= \OCP\Constants::PERMISSION_CREATE;
  137. }
  138. if ($this->isReadable($path)) {
  139. $permissions |= \OCP\Constants::PERMISSION_READ;
  140. }
  141. if ($this->isUpdatable($path)) {
  142. $permissions |= \OCP\Constants::PERMISSION_UPDATE;
  143. }
  144. if ($this->isDeletable($path)) {
  145. $permissions |= \OCP\Constants::PERMISSION_DELETE;
  146. }
  147. if ($this->isSharable($path)) {
  148. $permissions |= \OCP\Constants::PERMISSION_SHARE;
  149. }
  150. return $permissions;
  151. }
  152. public function filemtime($path) {
  153. $stat = $this->stat($path);
  154. if (isset($stat['mtime']) && $stat['mtime'] > 0) {
  155. return $stat['mtime'];
  156. } else {
  157. return 0;
  158. }
  159. }
  160. public function file_get_contents($path) {
  161. $handle = $this->fopen($path, "r");
  162. if (!$handle) {
  163. return false;
  164. }
  165. $data = stream_get_contents($handle);
  166. fclose($handle);
  167. return $data;
  168. }
  169. public function file_put_contents($path, $data) {
  170. $handle = $this->fopen($path, "w");
  171. $this->removeCachedFile($path);
  172. $count = fwrite($handle, $data);
  173. fclose($handle);
  174. return $count;
  175. }
  176. public function rename($path1, $path2) {
  177. $this->remove($path2);
  178. $this->removeCachedFile($path1);
  179. return $this->copy($path1, $path2) and $this->remove($path1);
  180. }
  181. public function copy($path1, $path2) {
  182. if ($this->is_dir($path1)) {
  183. $this->remove($path2);
  184. $dir = $this->opendir($path1);
  185. $this->mkdir($path2);
  186. while ($file = readdir($dir)) {
  187. if (!Filesystem::isIgnoredDir($file)) {
  188. if (!$this->copy($path1 . '/' . $file, $path2 . '/' . $file)) {
  189. return false;
  190. }
  191. }
  192. }
  193. closedir($dir);
  194. return true;
  195. } else {
  196. $source = $this->fopen($path1, 'r');
  197. $target = $this->fopen($path2, 'w');
  198. list(, $result) = \OC_Helper::streamCopy($source, $target);
  199. $this->removeCachedFile($path2);
  200. return $result;
  201. }
  202. }
  203. public function getMimeType($path) {
  204. if ($this->is_dir($path)) {
  205. return 'httpd/unix-directory';
  206. } elseif ($this->file_exists($path)) {
  207. return \OC::$server->getMimeTypeDetector()->detectPath($path);
  208. } else {
  209. return false;
  210. }
  211. }
  212. public function hash($type, $path, $raw = false) {
  213. $fh = $this->fopen($path, 'rb');
  214. $ctx = hash_init($type);
  215. hash_update_stream($ctx, $fh);
  216. fclose($fh);
  217. return hash_final($ctx, $raw);
  218. }
  219. public function search($query) {
  220. return $this->searchInDir($query);
  221. }
  222. public function getLocalFile($path) {
  223. return $this->getCachedFile($path);
  224. }
  225. /**
  226. * @param string $path
  227. * @param string $target
  228. */
  229. private function addLocalFolder($path, $target) {
  230. $dh = $this->opendir($path);
  231. if (is_resource($dh)) {
  232. while (($file = readdir($dh)) !== false) {
  233. if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
  234. if ($this->is_dir($path . '/' . $file)) {
  235. mkdir($target . '/' . $file);
  236. $this->addLocalFolder($path . '/' . $file, $target . '/' . $file);
  237. } else {
  238. $tmp = $this->toTmpFile($path . '/' . $file);
  239. rename($tmp, $target . '/' . $file);
  240. }
  241. }
  242. }
  243. }
  244. }
  245. /**
  246. * @param string $query
  247. * @param string $dir
  248. * @return array
  249. */
  250. protected function searchInDir($query, $dir = '') {
  251. $files = array();
  252. $dh = $this->opendir($dir);
  253. if (is_resource($dh)) {
  254. while (($item = readdir($dh)) !== false) {
  255. if (\OC\Files\Filesystem::isIgnoredDir($item)) continue;
  256. if (strstr(strtolower($item), strtolower($query)) !== false) {
  257. $files[] = $dir . '/' . $item;
  258. }
  259. if ($this->is_dir($dir . '/' . $item)) {
  260. $files = array_merge($files, $this->searchInDir($query, $dir . '/' . $item));
  261. }
  262. }
  263. }
  264. closedir($dh);
  265. return $files;
  266. }
  267. /**
  268. * check if a file or folder has been updated since $time
  269. *
  270. * The method is only used to check if the cache needs to be updated. Storage backends that don't support checking
  271. * the mtime should always return false here. As a result storage implementations that always return false expect
  272. * exclusive access to the backend and will not pick up files that have been added in a way that circumvents
  273. * ownClouds filesystem.
  274. *
  275. * @param string $path
  276. * @param int $time
  277. * @return bool
  278. */
  279. public function hasUpdated($path, $time) {
  280. return $this->filemtime($path) > $time;
  281. }
  282. public function getCache($path = '', $storage = null) {
  283. if (!$storage) {
  284. $storage = $this;
  285. }
  286. if (!isset($this->cache)) {
  287. $this->cache = new Cache($storage);
  288. }
  289. return $this->cache;
  290. }
  291. public function getScanner($path = '', $storage = null) {
  292. if (!$storage) {
  293. $storage = $this;
  294. }
  295. if (!isset($this->scanner)) {
  296. $this->scanner = new Scanner($storage);
  297. }
  298. return $this->scanner;
  299. }
  300. public function getWatcher($path = '', $storage = null) {
  301. if (!$storage) {
  302. $storage = $this;
  303. }
  304. if (!isset($this->watcher)) {
  305. $this->watcher = new Watcher($storage);
  306. $globalPolicy = \OC::$server->getConfig()->getSystemValue('filesystem_check_changes', Watcher::CHECK_NEVER);
  307. $this->watcher->setPolicy((int)$this->getMountOption('filesystem_check_changes', $globalPolicy));
  308. }
  309. return $this->watcher;
  310. }
  311. /**
  312. * get a propagator instance for the cache
  313. *
  314. * @param \OC\Files\Storage\Storage (optional) the storage to pass to the watcher
  315. * @return \OC\Files\Cache\Propagator
  316. */
  317. public function getPropagator($storage = null) {
  318. if (!$storage) {
  319. $storage = $this;
  320. }
  321. if (!isset($this->propagator)) {
  322. $this->propagator = new Propagator($storage);
  323. }
  324. return $this->propagator;
  325. }
  326. public function getUpdater($storage = null) {
  327. if (!$storage) {
  328. $storage = $this;
  329. }
  330. if (!isset($this->updater)) {
  331. $this->updater = new Updater($storage);
  332. }
  333. return $this->updater;
  334. }
  335. public function getStorageCache($storage = null) {
  336. if (!$storage) {
  337. $storage = $this;
  338. }
  339. if (!isset($this->storageCache)) {
  340. $this->storageCache = new \OC\Files\Cache\Storage($storage);
  341. }
  342. return $this->storageCache;
  343. }
  344. /**
  345. * get the owner of a path
  346. *
  347. * @param string $path The path to get the owner
  348. * @return string|false uid or false
  349. */
  350. public function getOwner($path) {
  351. if ($this->owner === null) {
  352. $this->owner = \OC_User::getUser();
  353. }
  354. return $this->owner;
  355. }
  356. /**
  357. * get the ETag for a file or folder
  358. *
  359. * @param string $path
  360. * @return string
  361. */
  362. public function getETag($path) {
  363. return uniqid();
  364. }
  365. /**
  366. * clean a path, i.e. remove all redundant '.' and '..'
  367. * making sure that it can't point to higher than '/'
  368. *
  369. * @param string $path The path to clean
  370. * @return string cleaned path
  371. */
  372. public function cleanPath($path) {
  373. if (strlen($path) == 0 or $path[0] != '/') {
  374. $path = '/' . $path;
  375. }
  376. $output = array();
  377. foreach (explode('/', $path) as $chunk) {
  378. if ($chunk == '..') {
  379. array_pop($output);
  380. } else if ($chunk == '.') {
  381. } else {
  382. $output[] = $chunk;
  383. }
  384. }
  385. return implode('/', $output);
  386. }
  387. /**
  388. * Test a storage for availability
  389. *
  390. * @return bool
  391. */
  392. public function test() {
  393. if ($this->stat('')) {
  394. return true;
  395. }
  396. return false;
  397. }
  398. /**
  399. * get the free space in the storage
  400. *
  401. * @param string $path
  402. * @return int|false
  403. */
  404. public function free_space($path) {
  405. return \OCP\Files\FileInfo::SPACE_UNKNOWN;
  406. }
  407. /**
  408. * {@inheritdoc}
  409. */
  410. public function isLocal() {
  411. // the common implementation returns a temporary file by
  412. // default, which is not local
  413. return false;
  414. }
  415. /**
  416. * Check if the storage is an instance of $class or is a wrapper for a storage that is an instance of $class
  417. *
  418. * @param string $class
  419. * @return bool
  420. */
  421. public function instanceOfStorage($class) {
  422. return is_a($this, $class);
  423. }
  424. /**
  425. * A custom storage implementation can return an url for direct download of a give file.
  426. *
  427. * For now the returned array can hold the parameter url - in future more attributes might follow.
  428. *
  429. * @param string $path
  430. * @return array|false
  431. */
  432. public function getDirectDownload($path) {
  433. return [];
  434. }
  435. /**
  436. * @inheritdoc
  437. */
  438. public function verifyPath($path, $fileName) {
  439. if (isset($fileName[255])) {
  440. throw new FileNameTooLongException();
  441. }
  442. // NOTE: $path will remain unverified for now
  443. if (\OC_Util::runningOnWindows()) {
  444. $this->verifyWindowsPath($fileName);
  445. } else {
  446. $this->verifyPosixPath($fileName);
  447. }
  448. }
  449. /**
  450. * https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247%28v=vs.85%29.aspx
  451. * @param string $fileName
  452. * @throws InvalidPathException
  453. */
  454. protected function verifyWindowsPath($fileName) {
  455. $fileName = trim($fileName);
  456. $this->scanForInvalidCharacters($fileName, "\\/<>:\"|?*");
  457. $reservedNames = ['CON', 'PRN', 'AUX', 'NUL', 'COM1', 'COM2', 'COM3', 'COM4', 'COM5', 'COM6', 'COM7', 'COM8', 'COM9', 'LPT1', 'LPT2', 'LPT3', 'LPT4', 'LPT5', 'LPT6', 'LPT7', 'LPT8', 'LPT9'];
  458. if (in_array(strtoupper($fileName), $reservedNames)) {
  459. throw new ReservedWordException();
  460. }
  461. }
  462. /**
  463. * @param string $fileName
  464. * @throws InvalidPathException
  465. */
  466. protected function verifyPosixPath($fileName) {
  467. $fileName = trim($fileName);
  468. $this->scanForInvalidCharacters($fileName, "\\/");
  469. $reservedNames = ['*'];
  470. if (in_array($fileName, $reservedNames)) {
  471. throw new ReservedWordException();
  472. }
  473. }
  474. /**
  475. * @param string $fileName
  476. * @param string $invalidChars
  477. * @throws InvalidPathException
  478. */
  479. private function scanForInvalidCharacters($fileName, $invalidChars) {
  480. foreach (str_split($invalidChars) as $char) {
  481. if (strpos($fileName, $char) !== false) {
  482. throw new InvalidCharacterInPathException();
  483. }
  484. }
  485. $sanitizedFileName = filter_var($fileName, FILTER_UNSAFE_RAW, FILTER_FLAG_STRIP_LOW);
  486. if ($sanitizedFileName !== $fileName) {
  487. throw new InvalidCharacterInPathException();
  488. }
  489. }
  490. /**
  491. * @param array $options
  492. */
  493. public function setMountOptions(array $options) {
  494. $this->mountOptions = $options;
  495. }
  496. /**
  497. * @param string $name
  498. * @param mixed $default
  499. * @return mixed
  500. */
  501. public function getMountOption($name, $default = null) {
  502. return isset($this->mountOptions[$name]) ? $this->mountOptions[$name] : $default;
  503. }
  504. /**
  505. * @param \OCP\Files\Storage $sourceStorage
  506. * @param string $sourceInternalPath
  507. * @param string $targetInternalPath
  508. * @param bool $preserveMtime
  509. * @return bool
  510. */
  511. public function copyFromStorage(\OCP\Files\Storage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = false) {
  512. if ($sourceStorage === $this) {
  513. return $this->copy($sourceInternalPath, $targetInternalPath);
  514. }
  515. if ($sourceStorage->is_dir($sourceInternalPath)) {
  516. $dh = $sourceStorage->opendir($sourceInternalPath);
  517. $result = $this->mkdir($targetInternalPath);
  518. if (is_resource($dh)) {
  519. while ($result and ($file = readdir($dh)) !== false) {
  520. if (!Filesystem::isIgnoredDir($file)) {
  521. $result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath . '/' . $file, $targetInternalPath . '/' . $file);
  522. }
  523. }
  524. }
  525. } else {
  526. $source = $sourceStorage->fopen($sourceInternalPath, 'r');
  527. // TODO: call fopen in a way that we execute again all storage wrappers
  528. // to avoid that we bypass storage wrappers which perform important actions
  529. // for this operation. Same is true for all other operations which
  530. // are not the same as the original one.Once this is fixed we also
  531. // need to adjust the encryption wrapper.
  532. $target = $this->fopen($targetInternalPath, 'w');
  533. list(, $result) = \OC_Helper::streamCopy($source, $target);
  534. if ($result and $preserveMtime) {
  535. $this->touch($targetInternalPath, $sourceStorage->filemtime($sourceInternalPath));
  536. }
  537. fclose($source);
  538. fclose($target);
  539. if (!$result) {
  540. // delete partially written target file
  541. $this->unlink($targetInternalPath);
  542. // delete cache entry that was created by fopen
  543. $this->getCache()->remove($targetInternalPath);
  544. }
  545. }
  546. return (bool)$result;
  547. }
  548. /**
  549. * @param \OCP\Files\Storage $sourceStorage
  550. * @param string $sourceInternalPath
  551. * @param string $targetInternalPath
  552. * @return bool
  553. */
  554. public function moveFromStorage(\OCP\Files\Storage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
  555. if ($sourceStorage === $this) {
  556. return $this->rename($sourceInternalPath, $targetInternalPath);
  557. }
  558. if (!$sourceStorage->isDeletable($sourceInternalPath)) {
  559. return false;
  560. }
  561. $result = $this->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, true);
  562. if ($result) {
  563. if ($sourceStorage->is_dir($sourceInternalPath)) {
  564. $result &= $sourceStorage->rmdir($sourceInternalPath);
  565. } else {
  566. $result &= $sourceStorage->unlink($sourceInternalPath);
  567. }
  568. }
  569. return $result;
  570. }
  571. /**
  572. * @inheritdoc
  573. */
  574. public function getMetaData($path) {
  575. $permissions = $this->getPermissions($path);
  576. if (!$permissions & \OCP\Constants::PERMISSION_READ) {
  577. //cant read, nothing we can do
  578. return null;
  579. }
  580. $data = [];
  581. $data['mimetype'] = $this->getMimeType($path);
  582. $data['mtime'] = $this->filemtime($path);
  583. if ($data['mimetype'] == 'httpd/unix-directory') {
  584. $data['size'] = -1; //unknown
  585. } else {
  586. $data['size'] = $this->filesize($path);
  587. }
  588. $data['etag'] = $this->getETag($path);
  589. $data['storage_mtime'] = $data['mtime'];
  590. $data['permissions'] = $this->getPermissions($path);
  591. return $data;
  592. }
  593. /**
  594. * @param string $path
  595. * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
  596. * @param \OCP\Lock\ILockingProvider $provider
  597. * @throws \OCP\Lock\LockedException
  598. */
  599. public function acquireLock($path, $type, ILockingProvider $provider) {
  600. $provider->acquireLock('files/' . md5($this->getId() . '::' . trim($path, '/')), $type);
  601. }
  602. /**
  603. * @param string $path
  604. * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
  605. * @param \OCP\Lock\ILockingProvider $provider
  606. */
  607. public function releaseLock($path, $type, ILockingProvider $provider) {
  608. $provider->releaseLock('files/' . md5($this->getId() . '::' . trim($path, '/')), $type);
  609. }
  610. /**
  611. * @param string $path
  612. * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
  613. * @param \OCP\Lock\ILockingProvider $provider
  614. */
  615. public function changeLock($path, $type, ILockingProvider $provider) {
  616. $provider->changeLock('files/' . md5($this->getId() . '::' . trim($path, '/')), $type);
  617. }
  618. /**
  619. * @return array [ available, last_checked ]
  620. */
  621. public function getAvailability() {
  622. return $this->getStorageCache()->getAvailability();
  623. }
  624. /**
  625. * @param bool $isAvailable
  626. */
  627. public function setAvailability($isAvailable) {
  628. $this->getStorageCache()->setAvailability($isAvailable);
  629. }
  630. }