ObjectStoreStorage.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC\Files\ObjectStore;
  8. use Aws\S3\Exception\S3Exception;
  9. use Aws\S3\Exception\S3MultipartUploadException;
  10. use Icewind\Streams\CallbackWrapper;
  11. use Icewind\Streams\CountWrapper;
  12. use Icewind\Streams\IteratorDirectory;
  13. use OC\Files\Cache\Cache;
  14. use OC\Files\Cache\CacheEntry;
  15. use OC\Files\Storage\PolyFill\CopyDirectory;
  16. use OCP\Files\Cache\ICache;
  17. use OCP\Files\Cache\ICacheEntry;
  18. use OCP\Files\FileInfo;
  19. use OCP\Files\GenericFileException;
  20. use OCP\Files\NotFoundException;
  21. use OCP\Files\ObjectStore\IObjectStore;
  22. use OCP\Files\ObjectStore\IObjectStoreMultiPartUpload;
  23. use OCP\Files\Storage\IChunkedFileWrite;
  24. use OCP\Files\Storage\IStorage;
  25. use Psr\Log\LoggerInterface;
  26. class ObjectStoreStorage extends \OC\Files\Storage\Common implements IChunkedFileWrite {
  27. use CopyDirectory;
  28. protected IObjectStore $objectStore;
  29. protected string $id;
  30. private string $objectPrefix = 'urn:oid:';
  31. private LoggerInterface $logger;
  32. private bool $handleCopiesAsOwned;
  33. protected bool $validateWrites = true;
  34. /**
  35. * @param array $params
  36. * @throws \Exception
  37. */
  38. public function __construct($params) {
  39. if (isset($params['objectstore']) && $params['objectstore'] instanceof IObjectStore) {
  40. $this->objectStore = $params['objectstore'];
  41. } else {
  42. throw new \Exception('missing IObjectStore instance');
  43. }
  44. if (isset($params['storageid'])) {
  45. $this->id = 'object::store:' . $params['storageid'];
  46. } else {
  47. $this->id = 'object::store:' . $this->objectStore->getStorageId();
  48. }
  49. if (isset($params['objectPrefix'])) {
  50. $this->objectPrefix = $params['objectPrefix'];
  51. }
  52. if (isset($params['validateWrites'])) {
  53. $this->validateWrites = (bool)$params['validateWrites'];
  54. }
  55. $this->handleCopiesAsOwned = (bool)($params['handleCopiesAsOwned'] ?? false);
  56. $this->logger = \OCP\Server::get(LoggerInterface::class);
  57. }
  58. public function mkdir($path, bool $force = false) {
  59. $path = $this->normalizePath($path);
  60. if (!$force && $this->file_exists($path)) {
  61. $this->logger->warning("Tried to create an object store folder that already exists: $path");
  62. return false;
  63. }
  64. $mTime = time();
  65. $data = [
  66. 'mimetype' => 'httpd/unix-directory',
  67. 'size' => 0,
  68. 'mtime' => $mTime,
  69. 'storage_mtime' => $mTime,
  70. 'permissions' => \OCP\Constants::PERMISSION_ALL,
  71. ];
  72. if ($path === '') {
  73. //create root on the fly
  74. $data['etag'] = $this->getETag('');
  75. $this->getCache()->put('', $data);
  76. return true;
  77. } else {
  78. // if parent does not exist, create it
  79. $parent = $this->normalizePath(dirname($path));
  80. $parentType = $this->filetype($parent);
  81. if ($parentType === false) {
  82. if (!$this->mkdir($parent)) {
  83. // something went wrong
  84. $this->logger->warning("Parent folder ($parent) doesn't exist and couldn't be created");
  85. return false;
  86. }
  87. } elseif ($parentType === 'file') {
  88. // parent is a file
  89. $this->logger->warning("Parent ($parent) is a file");
  90. return false;
  91. }
  92. // finally create the new dir
  93. $mTime = time(); // update mtime
  94. $data['mtime'] = $mTime;
  95. $data['storage_mtime'] = $mTime;
  96. $data['etag'] = $this->getETag($path);
  97. $this->getCache()->put($path, $data);
  98. return true;
  99. }
  100. }
  101. /**
  102. * @param string $path
  103. * @return string
  104. */
  105. private function normalizePath($path) {
  106. $path = trim($path, '/');
  107. //FIXME why do we sometimes get a path like 'files//username'?
  108. $path = str_replace('//', '/', $path);
  109. // dirname('/folder') returns '.' but internally (in the cache) we store the root as ''
  110. if (!$path || $path === '.') {
  111. $path = '';
  112. }
  113. return $path;
  114. }
  115. /**
  116. * Object Stores use a NoopScanner because metadata is directly stored in
  117. * the file cache and cannot really scan the filesystem. The storage passed in is not used anywhere.
  118. *
  119. * @param string $path
  120. * @param \OC\Files\Storage\Storage (optional) the storage to pass to the scanner
  121. * @return \OC\Files\ObjectStore\ObjectStoreScanner
  122. */
  123. public function getScanner($path = '', $storage = null) {
  124. if (!$storage) {
  125. $storage = $this;
  126. }
  127. if (!isset($this->scanner)) {
  128. $this->scanner = new ObjectStoreScanner($storage);
  129. }
  130. return $this->scanner;
  131. }
  132. public function getId() {
  133. return $this->id;
  134. }
  135. public function rmdir($path) {
  136. $path = $this->normalizePath($path);
  137. $entry = $this->getCache()->get($path);
  138. if (!$entry || $entry->getMimeType() !== ICacheEntry::DIRECTORY_MIMETYPE) {
  139. return false;
  140. }
  141. return $this->rmObjects($entry);
  142. }
  143. private function rmObjects(ICacheEntry $entry): bool {
  144. $children = $this->getCache()->getFolderContentsById($entry->getId());
  145. foreach ($children as $child) {
  146. if ($child->getMimeType() === ICacheEntry::DIRECTORY_MIMETYPE) {
  147. if (!$this->rmObjects($child)) {
  148. return false;
  149. }
  150. } else {
  151. if (!$this->rmObject($child)) {
  152. return false;
  153. }
  154. }
  155. }
  156. $this->getCache()->remove($entry->getPath());
  157. return true;
  158. }
  159. public function unlink($path) {
  160. $path = $this->normalizePath($path);
  161. $entry = $this->getCache()->get($path);
  162. if ($entry instanceof ICacheEntry) {
  163. if ($entry->getMimeType() === ICacheEntry::DIRECTORY_MIMETYPE) {
  164. return $this->rmObjects($entry);
  165. } else {
  166. return $this->rmObject($entry);
  167. }
  168. }
  169. return false;
  170. }
  171. public function rmObject(ICacheEntry $entry): bool {
  172. try {
  173. $this->objectStore->deleteObject($this->getURN($entry->getId()));
  174. } catch (\Exception $ex) {
  175. if ($ex->getCode() !== 404) {
  176. $this->logger->error(
  177. 'Could not delete object ' . $this->getURN($entry->getId()) . ' for ' . $entry->getPath(),
  178. [
  179. 'app' => 'objectstore',
  180. 'exception' => $ex,
  181. ]
  182. );
  183. return false;
  184. }
  185. //removing from cache is ok as it does not exist in the objectstore anyway
  186. }
  187. $this->getCache()->remove($entry->getPath());
  188. return true;
  189. }
  190. public function stat($path) {
  191. $path = $this->normalizePath($path);
  192. $cacheEntry = $this->getCache()->get($path);
  193. if ($cacheEntry instanceof CacheEntry) {
  194. return $cacheEntry->getData();
  195. } else {
  196. if ($path === '') {
  197. $this->mkdir('', true);
  198. $cacheEntry = $this->getCache()->get($path);
  199. if ($cacheEntry instanceof CacheEntry) {
  200. return $cacheEntry->getData();
  201. }
  202. }
  203. return false;
  204. }
  205. }
  206. public function getPermissions($path) {
  207. $stat = $this->stat($path);
  208. if (is_array($stat) && isset($stat['permissions'])) {
  209. return $stat['permissions'];
  210. }
  211. return parent::getPermissions($path);
  212. }
  213. /**
  214. * Override this method if you need a different unique resource identifier for your object storage implementation.
  215. * The default implementations just appends the fileId to 'urn:oid:'. Make sure the URN is unique over all users.
  216. * You may need a mapping table to store your URN if it cannot be generated from the fileid.
  217. *
  218. * @param int $fileId the fileid
  219. * @return null|string the unified resource name used to identify the object
  220. */
  221. public function getURN($fileId) {
  222. if (is_numeric($fileId)) {
  223. return $this->objectPrefix . $fileId;
  224. }
  225. return null;
  226. }
  227. public function opendir($path) {
  228. $path = $this->normalizePath($path);
  229. try {
  230. $files = [];
  231. $folderContents = $this->getCache()->getFolderContents($path);
  232. foreach ($folderContents as $file) {
  233. $files[] = $file['name'];
  234. }
  235. return IteratorDirectory::wrap($files);
  236. } catch (\Exception $e) {
  237. $this->logger->error($e->getMessage(), ['exception' => $e]);
  238. return false;
  239. }
  240. }
  241. public function filetype($path) {
  242. $path = $this->normalizePath($path);
  243. $stat = $this->stat($path);
  244. if ($stat) {
  245. if ($stat['mimetype'] === 'httpd/unix-directory') {
  246. return 'dir';
  247. }
  248. return 'file';
  249. } else {
  250. return false;
  251. }
  252. }
  253. public function fopen($path, $mode) {
  254. $path = $this->normalizePath($path);
  255. if (strrpos($path, '.') !== false) {
  256. $ext = substr($path, strrpos($path, '.'));
  257. } else {
  258. $ext = '';
  259. }
  260. switch ($mode) {
  261. case 'r':
  262. case 'rb':
  263. $stat = $this->stat($path);
  264. if (is_array($stat)) {
  265. $filesize = $stat['size'] ?? 0;
  266. // Reading 0 sized files is a waste of time
  267. if ($filesize === 0) {
  268. return fopen('php://memory', $mode);
  269. }
  270. try {
  271. $handle = $this->objectStore->readObject($this->getURN($stat['fileid']));
  272. if ($handle === false) {
  273. return false; // keep backward compatibility
  274. }
  275. $streamStat = fstat($handle);
  276. $actualSize = $streamStat['size'] ?? -1;
  277. if ($actualSize > -1 && $actualSize !== $filesize) {
  278. $this->getCache()->update((int)$stat['fileid'], ['size' => $actualSize]);
  279. }
  280. return $handle;
  281. } catch (NotFoundException $e) {
  282. $this->logger->error(
  283. 'Could not get object ' . $this->getURN($stat['fileid']) . ' for file ' . $path,
  284. [
  285. 'app' => 'objectstore',
  286. 'exception' => $e,
  287. ]
  288. );
  289. throw $e;
  290. } catch (\Exception $e) {
  291. $this->logger->error(
  292. 'Could not get object ' . $this->getURN($stat['fileid']) . ' for file ' . $path,
  293. [
  294. 'app' => 'objectstore',
  295. 'exception' => $e,
  296. ]
  297. );
  298. return false;
  299. }
  300. } else {
  301. return false;
  302. }
  303. // no break
  304. case 'w':
  305. case 'wb':
  306. case 'w+':
  307. case 'wb+':
  308. $dirName = dirname($path);
  309. $parentExists = $this->is_dir($dirName);
  310. if (!$parentExists) {
  311. return false;
  312. }
  313. $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
  314. $handle = fopen($tmpFile, $mode);
  315. return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
  316. $this->writeBack($tmpFile, $path);
  317. unlink($tmpFile);
  318. });
  319. case 'a':
  320. case 'ab':
  321. case 'r+':
  322. case 'a+':
  323. case 'x':
  324. case 'x+':
  325. case 'c':
  326. case 'c+':
  327. $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
  328. if ($this->file_exists($path)) {
  329. $source = $this->fopen($path, 'r');
  330. file_put_contents($tmpFile, $source);
  331. }
  332. $handle = fopen($tmpFile, $mode);
  333. return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
  334. $this->writeBack($tmpFile, $path);
  335. unlink($tmpFile);
  336. });
  337. }
  338. return false;
  339. }
  340. public function file_exists($path) {
  341. $path = $this->normalizePath($path);
  342. return (bool)$this->stat($path);
  343. }
  344. public function rename($source, $target) {
  345. $source = $this->normalizePath($source);
  346. $target = $this->normalizePath($target);
  347. $this->remove($target);
  348. $this->getCache()->move($source, $target);
  349. $this->touch(dirname($target));
  350. return true;
  351. }
  352. public function getMimeType($path) {
  353. $path = $this->normalizePath($path);
  354. return parent::getMimeType($path);
  355. }
  356. public function touch($path, $mtime = null) {
  357. if (is_null($mtime)) {
  358. $mtime = time();
  359. }
  360. $path = $this->normalizePath($path);
  361. $dirName = dirname($path);
  362. $parentExists = $this->is_dir($dirName);
  363. if (!$parentExists) {
  364. return false;
  365. }
  366. $stat = $this->stat($path);
  367. if (is_array($stat)) {
  368. // update existing mtime in db
  369. $stat['mtime'] = $mtime;
  370. $this->getCache()->update($stat['fileid'], $stat);
  371. } else {
  372. try {
  373. //create a empty file, need to have at least on char to make it
  374. // work with all object storage implementations
  375. $this->file_put_contents($path, ' ');
  376. $mimeType = \OC::$server->getMimeTypeDetector()->detectPath($path);
  377. $stat = [
  378. 'etag' => $this->getETag($path),
  379. 'mimetype' => $mimeType,
  380. 'size' => 0,
  381. 'mtime' => $mtime,
  382. 'storage_mtime' => $mtime,
  383. 'permissions' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE,
  384. ];
  385. $this->getCache()->put($path, $stat);
  386. } catch (\Exception $ex) {
  387. $this->logger->error(
  388. 'Could not create object for ' . $path,
  389. [
  390. 'app' => 'objectstore',
  391. 'exception' => $ex,
  392. ]
  393. );
  394. throw $ex;
  395. }
  396. }
  397. return true;
  398. }
  399. public function writeBack($tmpFile, $path) {
  400. $size = filesize($tmpFile);
  401. $this->writeStream($path, fopen($tmpFile, 'r'), $size);
  402. }
  403. /**
  404. * external changes are not supported, exclusive access to the object storage is assumed
  405. *
  406. * @param string $path
  407. * @param int $time
  408. * @return false
  409. */
  410. public function hasUpdated($path, $time) {
  411. return false;
  412. }
  413. public function needsPartFile() {
  414. return false;
  415. }
  416. public function file_put_contents($path, $data) {
  417. $handle = $this->fopen($path, 'w+');
  418. if (!$handle) {
  419. return false;
  420. }
  421. $result = fwrite($handle, $data);
  422. fclose($handle);
  423. return $result;
  424. }
  425. public function writeStream(string $path, $stream, ?int $size = null): int {
  426. $stat = $this->stat($path);
  427. if (empty($stat)) {
  428. // create new file
  429. $stat = [
  430. 'permissions' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE,
  431. ];
  432. }
  433. // update stat with new data
  434. $mTime = time();
  435. $stat['size'] = (int)$size;
  436. $stat['mtime'] = $mTime;
  437. $stat['storage_mtime'] = $mTime;
  438. $mimetypeDetector = \OC::$server->getMimeTypeDetector();
  439. $mimetype = $mimetypeDetector->detectPath($path);
  440. $stat['mimetype'] = $mimetype;
  441. $stat['etag'] = $this->getETag($path);
  442. $stat['checksum'] = '';
  443. $exists = $this->getCache()->inCache($path);
  444. $uploadPath = $exists ? $path : $path . '.part';
  445. if ($exists) {
  446. $fileId = $stat['fileid'];
  447. } else {
  448. $fileId = $this->getCache()->put($uploadPath, $stat);
  449. }
  450. $urn = $this->getURN($fileId);
  451. try {
  452. //upload to object storage
  453. if ($size === null) {
  454. $countStream = CountWrapper::wrap($stream, function ($writtenSize) use ($fileId, &$size) {
  455. $this->getCache()->update($fileId, [
  456. 'size' => $writtenSize,
  457. ]);
  458. $size = $writtenSize;
  459. });
  460. $this->objectStore->writeObject($urn, $countStream, $mimetype);
  461. if (is_resource($countStream)) {
  462. fclose($countStream);
  463. }
  464. $stat['size'] = $size;
  465. } else {
  466. $this->objectStore->writeObject($urn, $stream, $mimetype);
  467. if (is_resource($stream)) {
  468. fclose($stream);
  469. }
  470. }
  471. } catch (\Exception $ex) {
  472. if (!$exists) {
  473. /*
  474. * Only remove the entry if we are dealing with a new file.
  475. * Else people lose access to existing files
  476. */
  477. $this->getCache()->remove($uploadPath);
  478. $this->logger->error(
  479. 'Could not create object ' . $urn . ' for ' . $path,
  480. [
  481. 'app' => 'objectstore',
  482. 'exception' => $ex,
  483. ]
  484. );
  485. } else {
  486. $this->logger->error(
  487. 'Could not update object ' . $urn . ' for ' . $path,
  488. [
  489. 'app' => 'objectstore',
  490. 'exception' => $ex,
  491. ]
  492. );
  493. }
  494. throw $ex; // make this bubble up
  495. }
  496. if ($exists) {
  497. // Always update the unencrypted size, for encryption the Encryption wrapper will update this afterwards anyways
  498. $stat['unencrypted_size'] = $stat['size'];
  499. $this->getCache()->update($fileId, $stat);
  500. } else {
  501. if (!$this->validateWrites || $this->objectStore->objectExists($urn)) {
  502. $this->getCache()->move($uploadPath, $path);
  503. } else {
  504. $this->getCache()->remove($uploadPath);
  505. throw new \Exception("Object not found after writing (urn: $urn, path: $path)", 404);
  506. }
  507. }
  508. return $size;
  509. }
  510. public function getObjectStore(): IObjectStore {
  511. return $this->objectStore;
  512. }
  513. public function copyFromStorage(
  514. IStorage $sourceStorage,
  515. $sourceInternalPath,
  516. $targetInternalPath,
  517. $preserveMtime = false
  518. ) {
  519. if ($sourceStorage->instanceOfStorage(ObjectStoreStorage::class)) {
  520. /** @var ObjectStoreStorage $sourceStorage */
  521. if ($sourceStorage->getObjectStore()->getStorageId() === $this->getObjectStore()->getStorageId()) {
  522. /** @var CacheEntry $sourceEntry */
  523. $sourceEntry = $sourceStorage->getCache()->get($sourceInternalPath);
  524. $sourceEntryData = $sourceEntry->getData();
  525. // $sourceEntry['permissions'] here is the permissions from the jailed storage for the current
  526. // user. Instead we use $sourceEntryData['scan_permissions'] that are the permissions from the
  527. // unjailed storage.
  528. if (is_array($sourceEntryData) && array_key_exists('scan_permissions', $sourceEntryData)) {
  529. $sourceEntry['permissions'] = $sourceEntryData['scan_permissions'];
  530. }
  531. $this->copyInner($sourceStorage->getCache(), $sourceEntry, $targetInternalPath);
  532. return true;
  533. }
  534. }
  535. return parent::copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
  536. }
  537. public function moveFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, ?ICacheEntry $sourceCacheEntry = null): bool {
  538. $sourceCache = $sourceStorage->getCache();
  539. if (!$sourceCacheEntry) {
  540. $sourceCacheEntry = $sourceCache->get($sourceInternalPath);
  541. }
  542. if ($sourceCacheEntry->getMimeType() === FileInfo::MIMETYPE_FOLDER) {
  543. foreach ($sourceCache->getFolderContents($sourceInternalPath) as $child) {
  544. $this->moveFromStorage($sourceStorage, $child->getPath(), $targetInternalPath . '/' . $child->getName());
  545. }
  546. $sourceStorage->rmdir($sourceInternalPath);
  547. } else {
  548. // move the cache entry before the contents so that we have the correct fileid/urn for the target
  549. $this->getCache()->moveFromCache($sourceCache, $sourceInternalPath, $targetInternalPath);
  550. try {
  551. $this->writeStream($targetInternalPath, $sourceStorage->fopen($sourceInternalPath, 'r'), $sourceCacheEntry->getSize());
  552. } catch (\Exception $e) {
  553. // restore the cache entry
  554. $sourceCache->moveFromCache($this->getCache(), $targetInternalPath, $sourceInternalPath);
  555. throw $e;
  556. }
  557. $sourceStorage->unlink($sourceInternalPath);
  558. }
  559. return true;
  560. }
  561. public function copy($source, $target) {
  562. $source = $this->normalizePath($source);
  563. $target = $this->normalizePath($target);
  564. $cache = $this->getCache();
  565. $sourceEntry = $cache->get($source);
  566. if (!$sourceEntry) {
  567. throw new NotFoundException('Source object not found');
  568. }
  569. $this->copyInner($cache, $sourceEntry, $target);
  570. return true;
  571. }
  572. private function copyInner(ICache $sourceCache, ICacheEntry $sourceEntry, string $to) {
  573. $cache = $this->getCache();
  574. if ($sourceEntry->getMimeType() === FileInfo::MIMETYPE_FOLDER) {
  575. if ($cache->inCache($to)) {
  576. $cache->remove($to);
  577. }
  578. $this->mkdir($to);
  579. foreach ($sourceCache->getFolderContentsById($sourceEntry->getId()) as $child) {
  580. $this->copyInner($sourceCache, $child, $to . '/' . $child->getName());
  581. }
  582. } else {
  583. $this->copyFile($sourceEntry, $to);
  584. }
  585. }
  586. private function copyFile(ICacheEntry $sourceEntry, string $to) {
  587. $cache = $this->getCache();
  588. $sourceUrn = $this->getURN($sourceEntry->getId());
  589. if (!$cache instanceof Cache) {
  590. throw new \Exception('Invalid source cache for object store copy');
  591. }
  592. $targetId = $cache->copyFromCache($cache, $sourceEntry, $to);
  593. $targetUrn = $this->getURN($targetId);
  594. try {
  595. $this->objectStore->copyObject($sourceUrn, $targetUrn);
  596. if ($this->handleCopiesAsOwned) {
  597. // Copied the file thus we gain all permissions as we are the owner now ! warning while this aligns with local storage it should not be used and instead fix local storage !
  598. $cache->update($targetId, ['permissions' => \OCP\Constants::PERMISSION_ALL]);
  599. }
  600. } catch (\Exception $e) {
  601. $cache->remove($to);
  602. throw $e;
  603. }
  604. }
  605. public function startChunkedWrite(string $targetPath): string {
  606. if (!$this->objectStore instanceof IObjectStoreMultiPartUpload) {
  607. throw new GenericFileException('Object store does not support multipart upload');
  608. }
  609. $cacheEntry = $this->getCache()->get($targetPath);
  610. $urn = $this->getURN($cacheEntry->getId());
  611. return $this->objectStore->initiateMultipartUpload($urn);
  612. }
  613. /**
  614. *
  615. * @throws GenericFileException
  616. */
  617. public function putChunkedWritePart(
  618. string $targetPath,
  619. string $writeToken,
  620. string $chunkId,
  621. $data,
  622. $size = null
  623. ): ?array {
  624. if (!$this->objectStore instanceof IObjectStoreMultiPartUpload) {
  625. throw new GenericFileException('Object store does not support multipart upload');
  626. }
  627. $cacheEntry = $this->getCache()->get($targetPath);
  628. $urn = $this->getURN($cacheEntry->getId());
  629. $result = $this->objectStore->uploadMultipartPart($urn, $writeToken, (int)$chunkId, $data, $size);
  630. $parts[$chunkId] = [
  631. 'PartNumber' => $chunkId,
  632. 'ETag' => trim($result->get('ETag'), '"'),
  633. ];
  634. return $parts[$chunkId];
  635. }
  636. public function completeChunkedWrite(string $targetPath, string $writeToken): int {
  637. if (!$this->objectStore instanceof IObjectStoreMultiPartUpload) {
  638. throw new GenericFileException('Object store does not support multipart upload');
  639. }
  640. $cacheEntry = $this->getCache()->get($targetPath);
  641. $urn = $this->getURN($cacheEntry->getId());
  642. $parts = $this->objectStore->getMultipartUploads($urn, $writeToken);
  643. $sortedParts = array_values($parts);
  644. sort($sortedParts);
  645. try {
  646. $size = $this->objectStore->completeMultipartUpload($urn, $writeToken, $sortedParts);
  647. $stat = $this->stat($targetPath);
  648. $mtime = time();
  649. if (is_array($stat)) {
  650. $stat['size'] = $size;
  651. $stat['mtime'] = $mtime;
  652. $stat['mimetype'] = $this->getMimeType($targetPath);
  653. $this->getCache()->update($stat['fileid'], $stat);
  654. }
  655. } catch (S3MultipartUploadException|S3Exception $e) {
  656. $this->objectStore->abortMultipartUpload($urn, $writeToken);
  657. $this->logger->error(
  658. 'Could not compete multipart upload ' . $urn . ' with uploadId ' . $writeToken,
  659. [
  660. 'app' => 'objectstore',
  661. 'exception' => $e,
  662. ]
  663. );
  664. throw new GenericFileException('Could not write chunked file');
  665. }
  666. return $size;
  667. }
  668. public function cancelChunkedWrite(string $targetPath, string $writeToken): void {
  669. if (!$this->objectStore instanceof IObjectStoreMultiPartUpload) {
  670. throw new GenericFileException('Object store does not support multipart upload');
  671. }
  672. $cacheEntry = $this->getCache()->get($targetPath);
  673. $urn = $this->getURN($cacheEntry->getId());
  674. $this->objectStore->abortMultipartUpload($urn, $writeToken);
  675. }
  676. }