ObjectStoreStorage.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767
  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. $fh = fopen('php://temp', 'w+');
  418. fwrite($fh, $data);
  419. rewind($fh);
  420. return $this->writeStream($path, $fh, strlen($data));
  421. }
  422. public function writeStream(string $path, $stream, ?int $size = null): int {
  423. $stat = $this->stat($path);
  424. if (empty($stat)) {
  425. // create new file
  426. $stat = [
  427. 'permissions' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE,
  428. ];
  429. }
  430. // update stat with new data
  431. $mTime = time();
  432. $stat['size'] = (int)$size;
  433. $stat['mtime'] = $mTime;
  434. $stat['storage_mtime'] = $mTime;
  435. $mimetypeDetector = \OC::$server->getMimeTypeDetector();
  436. $mimetype = $mimetypeDetector->detectPath($path);
  437. $stat['mimetype'] = $mimetype;
  438. $stat['etag'] = $this->getETag($path);
  439. $stat['checksum'] = '';
  440. $exists = $this->getCache()->inCache($path);
  441. $uploadPath = $exists ? $path : $path . '.part';
  442. if ($exists) {
  443. $fileId = $stat['fileid'];
  444. } else {
  445. $parent = $this->normalizePath(dirname($path));
  446. if (!$this->is_dir($parent)) {
  447. throw new \InvalidArgumentException("trying to upload a file ($path) inside a non-directory ($parent)");
  448. }
  449. $fileId = $this->getCache()->put($uploadPath, $stat);
  450. }
  451. $urn = $this->getURN($fileId);
  452. try {
  453. //upload to object storage
  454. if ($size === null) {
  455. $countStream = CountWrapper::wrap($stream, function ($writtenSize) use ($fileId, &$size) {
  456. $this->getCache()->update($fileId, [
  457. 'size' => $writtenSize,
  458. ]);
  459. $size = $writtenSize;
  460. });
  461. $this->objectStore->writeObject($urn, $countStream, $mimetype);
  462. if (is_resource($countStream)) {
  463. fclose($countStream);
  464. }
  465. $stat['size'] = $size;
  466. } else {
  467. $this->objectStore->writeObject($urn, $stream, $mimetype);
  468. if (is_resource($stream)) {
  469. fclose($stream);
  470. }
  471. }
  472. } catch (\Exception $ex) {
  473. if (!$exists) {
  474. /*
  475. * Only remove the entry if we are dealing with a new file.
  476. * Else people lose access to existing files
  477. */
  478. $this->getCache()->remove($uploadPath);
  479. $this->logger->error(
  480. 'Could not create object ' . $urn . ' for ' . $path,
  481. [
  482. 'app' => 'objectstore',
  483. 'exception' => $ex,
  484. ]
  485. );
  486. } else {
  487. $this->logger->error(
  488. 'Could not update object ' . $urn . ' for ' . $path,
  489. [
  490. 'app' => 'objectstore',
  491. 'exception' => $ex,
  492. ]
  493. );
  494. }
  495. throw $ex; // make this bubble up
  496. }
  497. if ($exists) {
  498. // Always update the unencrypted size, for encryption the Encryption wrapper will update this afterwards anyways
  499. $stat['unencrypted_size'] = $stat['size'];
  500. $this->getCache()->update($fileId, $stat);
  501. } else {
  502. if (!$this->validateWrites || $this->objectStore->objectExists($urn)) {
  503. $this->getCache()->move($uploadPath, $path);
  504. } else {
  505. $this->getCache()->remove($uploadPath);
  506. throw new \Exception("Object not found after writing (urn: $urn, path: $path)", 404);
  507. }
  508. }
  509. return $size;
  510. }
  511. public function getObjectStore(): IObjectStore {
  512. return $this->objectStore;
  513. }
  514. public function copyFromStorage(
  515. IStorage $sourceStorage,
  516. $sourceInternalPath,
  517. $targetInternalPath,
  518. $preserveMtime = false
  519. ) {
  520. if ($sourceStorage->instanceOfStorage(ObjectStoreStorage::class)) {
  521. /** @var ObjectStoreStorage $sourceStorage */
  522. if ($sourceStorage->getObjectStore()->getStorageId() === $this->getObjectStore()->getStorageId()) {
  523. /** @var CacheEntry $sourceEntry */
  524. $sourceEntry = $sourceStorage->getCache()->get($sourceInternalPath);
  525. $sourceEntryData = $sourceEntry->getData();
  526. // $sourceEntry['permissions'] here is the permissions from the jailed storage for the current
  527. // user. Instead we use $sourceEntryData['scan_permissions'] that are the permissions from the
  528. // unjailed storage.
  529. if (is_array($sourceEntryData) && array_key_exists('scan_permissions', $sourceEntryData)) {
  530. $sourceEntry['permissions'] = $sourceEntryData['scan_permissions'];
  531. }
  532. $this->copyInner($sourceStorage->getCache(), $sourceEntry, $targetInternalPath);
  533. return true;
  534. }
  535. }
  536. return parent::copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
  537. }
  538. public function moveFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, ?ICacheEntry $sourceCacheEntry = null): bool {
  539. $sourceCache = $sourceStorage->getCache();
  540. if ($sourceStorage->instanceOfStorage(ObjectStoreStorage::class) && $sourceStorage->getObjectStore()->getStorageId() === $this->getObjectStore()->getStorageId()) {
  541. $this->getCache()->moveFromCache($sourceCache, $sourceInternalPath, $targetInternalPath);
  542. // Do not import any data when source and target bucket are identical.
  543. return true;
  544. }
  545. if (!$sourceCacheEntry) {
  546. $sourceCacheEntry = $sourceCache->get($sourceInternalPath);
  547. }
  548. if ($sourceCacheEntry->getMimeType() === FileInfo::MIMETYPE_FOLDER) {
  549. $this->mkdir($targetInternalPath);
  550. foreach ($sourceCache->getFolderContentsById($sourceCacheEntry->getId()) as $child) {
  551. $this->moveFromStorage($sourceStorage, $child->getPath(), $targetInternalPath . '/' . $child->getName(), $child);
  552. }
  553. $sourceStorage->rmdir($sourceInternalPath);
  554. } else {
  555. $sourceStream = $sourceStorage->fopen($sourceInternalPath, 'r');
  556. if (!$sourceStream) {
  557. return false;
  558. }
  559. // move the cache entry before the contents so that we have the correct fileid/urn for the target
  560. $this->getCache()->moveFromCache($sourceCache, $sourceInternalPath, $targetInternalPath);
  561. try {
  562. $this->writeStream($targetInternalPath, $sourceStream, $sourceCacheEntry->getSize());
  563. } catch (\Exception $e) {
  564. // restore the cache entry
  565. $sourceCache->moveFromCache($this->getCache(), $targetInternalPath, $sourceInternalPath);
  566. throw $e;
  567. }
  568. $sourceStorage->unlink($sourceInternalPath);
  569. }
  570. return true;
  571. }
  572. public function copy($source, $target) {
  573. $source = $this->normalizePath($source);
  574. $target = $this->normalizePath($target);
  575. $cache = $this->getCache();
  576. $sourceEntry = $cache->get($source);
  577. if (!$sourceEntry) {
  578. throw new NotFoundException('Source object not found');
  579. }
  580. $this->copyInner($cache, $sourceEntry, $target);
  581. return true;
  582. }
  583. private function copyInner(ICache $sourceCache, ICacheEntry $sourceEntry, string $to) {
  584. $cache = $this->getCache();
  585. if ($sourceEntry->getMimeType() === FileInfo::MIMETYPE_FOLDER) {
  586. if ($cache->inCache($to)) {
  587. $cache->remove($to);
  588. }
  589. $this->mkdir($to);
  590. foreach ($sourceCache->getFolderContentsById($sourceEntry->getId()) as $child) {
  591. $this->copyInner($sourceCache, $child, $to . '/' . $child->getName());
  592. }
  593. } else {
  594. $this->copyFile($sourceEntry, $to);
  595. }
  596. }
  597. private function copyFile(ICacheEntry $sourceEntry, string $to) {
  598. $cache = $this->getCache();
  599. $sourceUrn = $this->getURN($sourceEntry->getId());
  600. if (!$cache instanceof Cache) {
  601. throw new \Exception("Invalid source cache for object store copy");
  602. }
  603. $targetId = $cache->copyFromCache($cache, $sourceEntry, $to);
  604. $targetUrn = $this->getURN($targetId);
  605. try {
  606. $this->objectStore->copyObject($sourceUrn, $targetUrn);
  607. if ($this->handleCopiesAsOwned) {
  608. // 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 !
  609. $cache->update($targetId, ['permissions' => \OCP\Constants::PERMISSION_ALL]);
  610. }
  611. } catch (\Exception $e) {
  612. $cache->remove($to);
  613. throw $e;
  614. }
  615. }
  616. public function startChunkedWrite(string $targetPath): string {
  617. if (!$this->objectStore instanceof IObjectStoreMultiPartUpload) {
  618. throw new GenericFileException('Object store does not support multipart upload');
  619. }
  620. $cacheEntry = $this->getCache()->get($targetPath);
  621. $urn = $this->getURN($cacheEntry->getId());
  622. return $this->objectStore->initiateMultipartUpload($urn);
  623. }
  624. /**
  625. *
  626. * @throws GenericFileException
  627. */
  628. public function putChunkedWritePart(
  629. string $targetPath,
  630. string $writeToken,
  631. string $chunkId,
  632. $data,
  633. $size = null
  634. ): ?array {
  635. if (!$this->objectStore instanceof IObjectStoreMultiPartUpload) {
  636. throw new GenericFileException('Object store does not support multipart upload');
  637. }
  638. $cacheEntry = $this->getCache()->get($targetPath);
  639. $urn = $this->getURN($cacheEntry->getId());
  640. $result = $this->objectStore->uploadMultipartPart($urn, $writeToken, (int)$chunkId, $data, $size);
  641. $parts[$chunkId] = [
  642. 'PartNumber' => $chunkId,
  643. 'ETag' => trim($result->get('ETag'), '"'),
  644. ];
  645. return $parts[$chunkId];
  646. }
  647. public function completeChunkedWrite(string $targetPath, string $writeToken): int {
  648. if (!$this->objectStore instanceof IObjectStoreMultiPartUpload) {
  649. throw new GenericFileException('Object store does not support multipart upload');
  650. }
  651. $cacheEntry = $this->getCache()->get($targetPath);
  652. $urn = $this->getURN($cacheEntry->getId());
  653. $parts = $this->objectStore->getMultipartUploads($urn, $writeToken);
  654. $sortedParts = array_values($parts);
  655. sort($sortedParts);
  656. try {
  657. $size = $this->objectStore->completeMultipartUpload($urn, $writeToken, $sortedParts);
  658. $stat = $this->stat($targetPath);
  659. $mtime = time();
  660. if (is_array($stat)) {
  661. $stat['size'] = $size;
  662. $stat['mtime'] = $mtime;
  663. $stat['mimetype'] = $this->getMimeType($targetPath);
  664. $this->getCache()->update($stat['fileid'], $stat);
  665. }
  666. } catch (S3MultipartUploadException|S3Exception $e) {
  667. $this->objectStore->abortMultipartUpload($urn, $writeToken);
  668. $this->logger->error(
  669. 'Could not compete multipart upload ' . $urn . ' with uploadId ' . $writeToken,
  670. [
  671. 'app' => 'objectstore',
  672. 'exception' => $e,
  673. ]
  674. );
  675. throw new GenericFileException('Could not write chunked file');
  676. }
  677. return $size;
  678. }
  679. public function cancelChunkedWrite(string $targetPath, string $writeToken): void {
  680. if (!$this->objectStore instanceof IObjectStoreMultiPartUpload) {
  681. throw new GenericFileException('Object store does not support multipart upload');
  682. }
  683. $cacheEntry = $this->getCache()->get($targetPath);
  684. $urn = $this->getURN($cacheEntry->getId());
  685. $this->objectStore->abortMultipartUpload($urn, $writeToken);
  686. }
  687. }