You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ObjectStoreStorage.php 16KB

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