ObjectStoreStorage.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Bjoern Schiessle <bjoern@schiessle.org>
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author Joas Schilling <coding@schilljs.com>
  8. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  9. * @author Marcel Klehr <mklehr@gmx.net>
  10. * @author Morris Jobke <hey@morrisjobke.de>
  11. * @author Robin Appelman <robin@icewind.nl>
  12. * @author Roeland Jago Douma <roeland@famdouma.nl>
  13. * @author Tigran Mkrtchyan <tigran.mkrtchyan@desy.de>
  14. *
  15. * @license AGPL-3.0
  16. *
  17. * This code is free software: you can redistribute it and/or modify
  18. * it under the terms of the GNU Affero General Public License, version 3,
  19. * as published by the Free Software Foundation.
  20. *
  21. * This program is distributed in the hope that it will be useful,
  22. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  23. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  24. * GNU Affero General Public License for more details.
  25. *
  26. * You should have received a copy of the GNU Affero General Public License, version 3,
  27. * along with this program. If not, see <http://www.gnu.org/licenses/>
  28. *
  29. */
  30. namespace OC\Files\ObjectStore;
  31. use Icewind\Streams\CallbackWrapper;
  32. use Icewind\Streams\CountWrapper;
  33. use Icewind\Streams\IteratorDirectory;
  34. use OC\Files\Cache\Cache;
  35. use OC\Files\Cache\CacheEntry;
  36. use OC\Files\Storage\PolyFill\CopyDirectory;
  37. use OCP\Files\Cache\ICacheEntry;
  38. use OCP\Files\FileInfo;
  39. use OCP\Files\NotFoundException;
  40. use OCP\Files\ObjectStore\IObjectStore;
  41. use OCP\Files\Storage\IStorage;
  42. class ObjectStoreStorage extends \OC\Files\Storage\Common {
  43. use CopyDirectory;
  44. /**
  45. * @var \OCP\Files\ObjectStore\IObjectStore $objectStore
  46. */
  47. protected $objectStore;
  48. /**
  49. * @var string $id
  50. */
  51. protected $id;
  52. /**
  53. * @var \OC\User\User $user
  54. */
  55. protected $user;
  56. private $objectPrefix = 'urn:oid:';
  57. private $logger;
  58. /** @var bool */
  59. protected $validateWrites = true;
  60. public function __construct($params) {
  61. if (isset($params['objectstore']) && $params['objectstore'] instanceof IObjectStore) {
  62. $this->objectStore = $params['objectstore'];
  63. } else {
  64. throw new \Exception('missing IObjectStore instance');
  65. }
  66. if (isset($params['storageid'])) {
  67. $this->id = 'object::store:' . $params['storageid'];
  68. } else {
  69. $this->id = 'object::store:' . $this->objectStore->getStorageId();
  70. }
  71. if (isset($params['objectPrefix'])) {
  72. $this->objectPrefix = $params['objectPrefix'];
  73. }
  74. if (isset($params['validateWrites'])) {
  75. $this->validateWrites = (bool)$params['validateWrites'];
  76. }
  77. //initialize cache with root directory in cache
  78. if (!$this->is_dir('/')) {
  79. $this->mkdir('/');
  80. }
  81. $this->logger = \OC::$server->getLogger();
  82. }
  83. public function mkdir($path) {
  84. $path = $this->normalizePath($path);
  85. if ($this->file_exists($path)) {
  86. return false;
  87. }
  88. $mTime = time();
  89. $data = [
  90. 'mimetype' => 'httpd/unix-directory',
  91. 'size' => 0,
  92. 'mtime' => $mTime,
  93. 'storage_mtime' => $mTime,
  94. 'permissions' => \OCP\Constants::PERMISSION_ALL,
  95. ];
  96. if ($path === '') {
  97. //create root on the fly
  98. $data['etag'] = $this->getETag('');
  99. $this->getCache()->put('', $data);
  100. return true;
  101. } else {
  102. // if parent does not exist, create it
  103. $parent = $this->normalizePath(dirname($path));
  104. $parentType = $this->filetype($parent);
  105. if ($parentType === false) {
  106. if (!$this->mkdir($parent)) {
  107. // something went wrong
  108. return false;
  109. }
  110. } elseif ($parentType === 'file') {
  111. // parent is a file
  112. return false;
  113. }
  114. // finally create the new dir
  115. $mTime = time(); // update mtime
  116. $data['mtime'] = $mTime;
  117. $data['storage_mtime'] = $mTime;
  118. $data['etag'] = $this->getETag($path);
  119. $this->getCache()->put($path, $data);
  120. return true;
  121. }
  122. }
  123. /**
  124. * @param string $path
  125. * @return string
  126. */
  127. private function normalizePath($path) {
  128. $path = trim($path, '/');
  129. //FIXME why do we sometimes get a path like 'files//username'?
  130. $path = str_replace('//', '/', $path);
  131. // dirname('/folder') returns '.' but internally (in the cache) we store the root as ''
  132. if (!$path || $path === '.') {
  133. $path = '';
  134. }
  135. return $path;
  136. }
  137. /**
  138. * Object Stores use a NoopScanner because metadata is directly stored in
  139. * the file cache and cannot really scan the filesystem. The storage passed in is not used anywhere.
  140. *
  141. * @param string $path
  142. * @param \OC\Files\Storage\Storage (optional) the storage to pass to the scanner
  143. * @return \OC\Files\ObjectStore\NoopScanner
  144. */
  145. public function getScanner($path = '', $storage = null) {
  146. if (!$storage) {
  147. $storage = $this;
  148. }
  149. if (!isset($this->scanner)) {
  150. $this->scanner = new NoopScanner($storage);
  151. }
  152. return $this->scanner;
  153. }
  154. public function getId() {
  155. return $this->id;
  156. }
  157. public function rmdir($path) {
  158. $path = $this->normalizePath($path);
  159. if (!$this->is_dir($path)) {
  160. return false;
  161. }
  162. if (!$this->rmObjects($path)) {
  163. return false;
  164. }
  165. $this->getCache()->remove($path);
  166. return true;
  167. }
  168. private function rmObjects($path) {
  169. $children = $this->getCache()->getFolderContents($path);
  170. foreach ($children as $child) {
  171. if ($child['mimetype'] === 'httpd/unix-directory') {
  172. if (!$this->rmObjects($child['path'])) {
  173. return false;
  174. }
  175. } else {
  176. if (!$this->unlink($child['path'])) {
  177. return false;
  178. }
  179. }
  180. }
  181. return true;
  182. }
  183. public function unlink($path) {
  184. $path = $this->normalizePath($path);
  185. $stat = $this->stat($path);
  186. if ($stat && isset($stat['fileid'])) {
  187. if ($stat['mimetype'] === 'httpd/unix-directory') {
  188. return $this->rmdir($path);
  189. }
  190. try {
  191. $this->objectStore->deleteObject($this->getURN($stat['fileid']));
  192. } catch (\Exception $ex) {
  193. if ($ex->getCode() !== 404) {
  194. $this->logger->logException($ex, [
  195. 'app' => 'objectstore',
  196. 'message' => 'Could not delete object ' . $this->getURN($stat['fileid']) . ' for ' . $path,
  197. ]);
  198. return false;
  199. }
  200. //removing from cache is ok as it does not exist in the objectstore anyway
  201. }
  202. $this->getCache()->remove($path);
  203. return true;
  204. }
  205. return false;
  206. }
  207. public function stat($path) {
  208. $path = $this->normalizePath($path);
  209. $cacheEntry = $this->getCache()->get($path);
  210. if ($cacheEntry instanceof CacheEntry) {
  211. return $cacheEntry->getData();
  212. } else {
  213. return false;
  214. }
  215. }
  216. public function getPermissions($path) {
  217. $stat = $this->stat($path);
  218. if (is_array($stat) && isset($stat['permissions'])) {
  219. return $stat['permissions'];
  220. }
  221. return parent::getPermissions($path);
  222. }
  223. /**
  224. * Override this method if you need a different unique resource identifier for your object storage implementation.
  225. * The default implementations just appends the fileId to 'urn:oid:'. Make sure the URN is unique over all users.
  226. * You may need a mapping table to store your URN if it cannot be generated from the fileid.
  227. *
  228. * @param int $fileId the fileid
  229. * @return null|string the unified resource name used to identify the object
  230. */
  231. public function getURN($fileId) {
  232. if (is_numeric($fileId)) {
  233. return $this->objectPrefix . $fileId;
  234. }
  235. return null;
  236. }
  237. public function opendir($path) {
  238. $path = $this->normalizePath($path);
  239. try {
  240. $files = [];
  241. $folderContents = $this->getCache()->getFolderContents($path);
  242. foreach ($folderContents as $file) {
  243. $files[] = $file['name'];
  244. }
  245. return IteratorDirectory::wrap($files);
  246. } catch (\Exception $e) {
  247. $this->logger->logException($e);
  248. return false;
  249. }
  250. }
  251. public function filetype($path) {
  252. $path = $this->normalizePath($path);
  253. $stat = $this->stat($path);
  254. if ($stat) {
  255. if ($stat['mimetype'] === 'httpd/unix-directory') {
  256. return 'dir';
  257. }
  258. return 'file';
  259. } else {
  260. return false;
  261. }
  262. }
  263. public function fopen($path, $mode) {
  264. $path = $this->normalizePath($path);
  265. if (strrpos($path, '.') !== false) {
  266. $ext = substr($path, strrpos($path, '.'));
  267. } else {
  268. $ext = '';
  269. }
  270. switch ($mode) {
  271. case 'r':
  272. case 'rb':
  273. $stat = $this->stat($path);
  274. if (is_array($stat)) {
  275. // Reading 0 sized files is a waste of time
  276. if (isset($stat['size']) && $stat['size'] === 0) {
  277. return fopen('php://memory', $mode);
  278. }
  279. try {
  280. return $this->objectStore->readObject($this->getURN($stat['fileid']));
  281. } catch (NotFoundException $e) {
  282. $this->logger->logException($e, [
  283. 'app' => 'objectstore',
  284. 'message' => 'Could not get object ' . $this->getURN($stat['fileid']) . ' for file ' . $path,
  285. ]);
  286. throw $e;
  287. } catch (\Exception $ex) {
  288. $this->logger->logException($ex, [
  289. 'app' => 'objectstore',
  290. 'message' => 'Could not get object ' . $this->getURN($stat['fileid']) . ' for file ' . $path,
  291. ]);
  292. return false;
  293. }
  294. } else {
  295. return false;
  296. }
  297. // no break
  298. case 'w':
  299. case 'wb':
  300. case 'w+':
  301. case 'wb+':
  302. $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
  303. $handle = fopen($tmpFile, $mode);
  304. return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
  305. $this->writeBack($tmpFile, $path);
  306. unlink($tmpFile);
  307. });
  308. case 'a':
  309. case 'ab':
  310. case 'r+':
  311. case 'a+':
  312. case 'x':
  313. case 'x+':
  314. case 'c':
  315. case 'c+':
  316. $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
  317. if ($this->file_exists($path)) {
  318. $source = $this->fopen($path, 'r');
  319. file_put_contents($tmpFile, $source);
  320. }
  321. $handle = fopen($tmpFile, $mode);
  322. return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
  323. $this->writeBack($tmpFile, $path);
  324. unlink($tmpFile);
  325. });
  326. }
  327. return false;
  328. }
  329. public function file_exists($path) {
  330. $path = $this->normalizePath($path);
  331. return (bool)$this->stat($path);
  332. }
  333. public function rename($source, $target) {
  334. $source = $this->normalizePath($source);
  335. $target = $this->normalizePath($target);
  336. $this->remove($target);
  337. $this->getCache()->move($source, $target);
  338. $this->touch(dirname($target));
  339. return true;
  340. }
  341. public function getMimeType($path) {
  342. $path = $this->normalizePath($path);
  343. return parent::getMimeType($path);
  344. }
  345. public function touch($path, $mtime = null) {
  346. if (is_null($mtime)) {
  347. $mtime = time();
  348. }
  349. $path = $this->normalizePath($path);
  350. $dirName = dirname($path);
  351. $parentExists = $this->is_dir($dirName);
  352. if (!$parentExists) {
  353. return false;
  354. }
  355. $stat = $this->stat($path);
  356. if (is_array($stat)) {
  357. // update existing mtime in db
  358. $stat['mtime'] = $mtime;
  359. $this->getCache()->update($stat['fileid'], $stat);
  360. } else {
  361. try {
  362. //create a empty file, need to have at least on char to make it
  363. // work with all object storage implementations
  364. $this->file_put_contents($path, ' ');
  365. $mimeType = \OC::$server->getMimeTypeDetector()->detectPath($path);
  366. $stat = [
  367. 'etag' => $this->getETag($path),
  368. 'mimetype' => $mimeType,
  369. 'size' => 0,
  370. 'mtime' => $mtime,
  371. 'storage_mtime' => $mtime,
  372. 'permissions' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE,
  373. ];
  374. $this->getCache()->put($path, $stat);
  375. } catch (\Exception $ex) {
  376. $this->logger->logException($ex, [
  377. 'app' => 'objectstore',
  378. 'message' => 'Could not create object for ' . $path,
  379. ]);
  380. throw $ex;
  381. }
  382. }
  383. return true;
  384. }
  385. public function writeBack($tmpFile, $path) {
  386. $size = filesize($tmpFile);
  387. $this->writeStream($path, fopen($tmpFile, 'r'), $size);
  388. }
  389. /**
  390. * external changes are not supported, exclusive access to the object storage is assumed
  391. *
  392. * @param string $path
  393. * @param int $time
  394. * @return false
  395. */
  396. public function hasUpdated($path, $time) {
  397. return false;
  398. }
  399. public function needsPartFile() {
  400. return false;
  401. }
  402. public function file_put_contents($path, $data) {
  403. $handle = $this->fopen($path, 'w+');
  404. $result = fwrite($handle, $data);
  405. fclose($handle);
  406. return $result;
  407. }
  408. public function writeStream(string $path, $stream, int $size = null): int {
  409. $stat = $this->stat($path);
  410. if (empty($stat)) {
  411. // create new file
  412. $stat = [
  413. 'permissions' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE,
  414. ];
  415. }
  416. // update stat with new data
  417. $mTime = time();
  418. $stat['size'] = (int)$size;
  419. $stat['mtime'] = $mTime;
  420. $stat['storage_mtime'] = $mTime;
  421. $mimetypeDetector = \OC::$server->getMimeTypeDetector();
  422. $mimetype = $mimetypeDetector->detectPath($path);
  423. $stat['mimetype'] = $mimetype;
  424. $stat['etag'] = $this->getETag($path);
  425. $stat['checksum'] = '';
  426. $exists = $this->getCache()->inCache($path);
  427. $uploadPath = $exists ? $path : $path . '.part';
  428. if ($exists) {
  429. $fileId = $stat['fileid'];
  430. } else {
  431. $fileId = $this->getCache()->put($uploadPath, $stat);
  432. }
  433. $urn = $this->getURN($fileId);
  434. try {
  435. //upload to object storage
  436. if ($size === null) {
  437. $countStream = CountWrapper::wrap($stream, function ($writtenSize) use ($fileId, &$size) {
  438. $this->getCache()->update($fileId, [
  439. 'size' => $writtenSize,
  440. ]);
  441. $size = $writtenSize;
  442. });
  443. $this->objectStore->writeObject($urn, $countStream, $mimetype);
  444. if (is_resource($countStream)) {
  445. fclose($countStream);
  446. }
  447. $stat['size'] = $size;
  448. } else {
  449. $this->objectStore->writeObject($urn, $stream, $mimetype);
  450. if (is_resource($stream)) {
  451. fclose($stream);
  452. }
  453. }
  454. } catch (\Exception $ex) {
  455. if (!$exists) {
  456. /*
  457. * Only remove the entry if we are dealing with a new file.
  458. * Else people lose access to existing files
  459. */
  460. $this->getCache()->remove($uploadPath);
  461. $this->logger->logException($ex, [
  462. 'app' => 'objectstore',
  463. 'message' => 'Could not create object ' . $urn . ' for ' . $path,
  464. ]);
  465. } else {
  466. $this->logger->logException($ex, [
  467. 'app' => 'objectstore',
  468. 'message' => 'Could not update object ' . $urn . ' for ' . $path,
  469. ]);
  470. }
  471. throw $ex; // make this bubble up
  472. }
  473. if ($exists) {
  474. $this->getCache()->update($fileId, $stat);
  475. } else {
  476. if (!$this->validateWrites || $this->objectStore->objectExists($urn)) {
  477. $this->getCache()->move($uploadPath, $path);
  478. } else {
  479. $this->getCache()->remove($uploadPath);
  480. throw new \Exception("Object not found after writing (urn: $urn, path: $path)", 404);
  481. }
  482. }
  483. return $size;
  484. }
  485. public function getObjectStore(): IObjectStore {
  486. return $this->objectStore;
  487. }
  488. public function copyFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = false) {
  489. if ($sourceStorage->instanceOfStorage(ObjectStoreStorage::class)) {
  490. /** @var ObjectStoreStorage $sourceStorage */
  491. if ($sourceStorage->getObjectStore()->getStorageId() === $this->getObjectStore()->getStorageId()) {
  492. /** @var CacheEntry $sourceEntry */
  493. $sourceEntry = $sourceStorage->getCache()->get($sourceInternalPath);
  494. $sourceEntryData = $sourceEntry->getData();
  495. // $sourceEntry['permissions'] here is the permissions from the jailed storage for the current
  496. // user. Instead we use $sourceEntryData['scan_permissions'] that are the permissions from the
  497. // unjailed storage.
  498. if (is_array($sourceEntryData) && array_key_exists('scan_permissions', $sourceEntryData)) {
  499. $sourceEntry['permissions'] = $sourceEntryData['scan_permissions'];
  500. }
  501. $this->copyInner($sourceEntry, $targetInternalPath);
  502. return true;
  503. }
  504. }
  505. return parent::copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
  506. }
  507. public function copy($source, $target) {
  508. $source = $this->normalizePath($source);
  509. $target = $this->normalizePath($target);
  510. $cache = $this->getCache();
  511. $sourceEntry = $cache->get($source);
  512. if (!$sourceEntry) {
  513. throw new NotFoundException('Source object not found');
  514. }
  515. $this->copyInner($sourceEntry, $target);
  516. return true;
  517. }
  518. private function copyInner(ICacheEntry $sourceEntry, string $to) {
  519. $cache = $this->getCache();
  520. if ($sourceEntry->getMimeType() === FileInfo::MIMETYPE_FOLDER) {
  521. if ($cache->inCache($to)) {
  522. $cache->remove($to);
  523. }
  524. $this->mkdir($to);
  525. foreach ($cache->getFolderContentsById($sourceEntry->getId()) as $child) {
  526. $this->copyInner($child, $to . '/' . $child->getName());
  527. }
  528. } else {
  529. $this->copyFile($sourceEntry, $to);
  530. }
  531. }
  532. private function copyFile(ICacheEntry $sourceEntry, string $to) {
  533. $cache = $this->getCache();
  534. $sourceUrn = $this->getURN($sourceEntry->getId());
  535. if (!$cache instanceof Cache) {
  536. throw new \Exception("Invalid source cache for object store copy");
  537. }
  538. $targetId = $cache->copyFromCache($cache, $sourceEntry, $to);
  539. $targetUrn = $this->getURN($targetId);
  540. try {
  541. $this->objectStore->copyObject($sourceUrn, $targetUrn);
  542. } catch (\Exception $e) {
  543. $cache->remove($to);
  544. throw $e;
  545. }
  546. }
  547. }