amazons3.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. <?php
  2. /**
  3. * @author André Gaul <gaul@web-yard.de>
  4. * @author Arthur Schiwon <blizzz@owncloud.com>
  5. * @author Bart Visscher <bartv@thisnet.nl>
  6. * @author Christian Berendt <berendt@b1-systems.de>
  7. * @author Christopher T. Johnson <ctjctj@gmail.com>
  8. * @author Johan Björk <johanimon@gmail.com>
  9. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  10. * @author Martin Mattel <martin.mattel@diemattels.at>
  11. * @author Michael Gapczynski <GapczynskiM@gmail.com>
  12. * @author Morris Jobke <hey@morrisjobke.de>
  13. * @author Philipp Kapfer <philipp.kapfer@gmx.at>
  14. * @author Robin Appelman <icewind@owncloud.com>
  15. * @author Robin McCorkell <robin@mccorkell.me.uk>
  16. * @author Thomas Müller <thomas.mueller@tmit.eu>
  17. * @author Vincent Petry <pvince81@owncloud.com>
  18. *
  19. * @copyright Copyright (c) 2016, ownCloud, Inc.
  20. * @license AGPL-3.0
  21. *
  22. * This code is free software: you can redistribute it and/or modify
  23. * it under the terms of the GNU Affero General Public License, version 3,
  24. * as published by the Free Software Foundation.
  25. *
  26. * This program is distributed in the hope that it will be useful,
  27. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  28. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  29. * GNU Affero General Public License for more details.
  30. *
  31. * You should have received a copy of the GNU Affero General Public License, version 3,
  32. * along with this program. If not, see <http://www.gnu.org/licenses/>
  33. *
  34. */
  35. namespace OC\Files\Storage;
  36. set_include_path(get_include_path() . PATH_SEPARATOR .
  37. \OC_App::getAppPath('files_external') . '/3rdparty/aws-sdk-php');
  38. require 'aws-autoloader.php';
  39. use Aws\S3\S3Client;
  40. use Aws\S3\Exception\S3Exception;
  41. use Icewind\Streams\IteratorDirectory;
  42. class AmazonS3 extends \OC\Files\Storage\Common {
  43. /**
  44. * @var \Aws\S3\S3Client
  45. */
  46. private $connection;
  47. /**
  48. * @var string
  49. */
  50. private $bucket;
  51. /**
  52. * @var array
  53. */
  54. private static $tmpFiles = array();
  55. /**
  56. * @var array
  57. */
  58. private $params;
  59. /**
  60. * @var bool
  61. */
  62. private $test = false;
  63. /**
  64. * @var int
  65. */
  66. private $timeout = 15;
  67. /**
  68. * @var int in seconds
  69. */
  70. private $rescanDelay = 10;
  71. /**
  72. * @param string $path
  73. * @return string correctly encoded path
  74. */
  75. private function normalizePath($path) {
  76. $path = trim($path, '/');
  77. if (!$path) {
  78. $path = '.';
  79. }
  80. return $path;
  81. }
  82. /**
  83. * when running the tests wait to let the buckets catch up
  84. */
  85. private function testTimeout() {
  86. if ($this->test) {
  87. sleep($this->timeout);
  88. }
  89. }
  90. private function isRoot($path) {
  91. return $path === '.';
  92. }
  93. private function cleanKey($path) {
  94. if ($this->isRoot($path)) {
  95. return '/';
  96. }
  97. return $path;
  98. }
  99. public function __construct($params) {
  100. if (empty($params['key']) || empty($params['secret']) || empty($params['bucket'])) {
  101. throw new \Exception("Access Key, Secret and Bucket have to be configured.");
  102. }
  103. $this->id = 'amazon::' . $params['bucket'];
  104. $this->updateLegacyId($params);
  105. $this->bucket = $params['bucket'];
  106. $this->test = isset($params['test']);
  107. $this->timeout = (!isset($params['timeout'])) ? 15 : $params['timeout'];
  108. $this->rescanDelay = (!isset($params['rescanDelay'])) ? 10 : $params['rescanDelay'];
  109. $params['region'] = empty($params['region']) ? 'eu-west-1' : $params['region'];
  110. $params['hostname'] = empty($params['hostname']) ? 's3.amazonaws.com' : $params['hostname'];
  111. if (!isset($params['port']) || $params['port'] === '') {
  112. $params['port'] = ($params['use_ssl'] === false) ? 80 : 443;
  113. }
  114. $this->params = $params;
  115. }
  116. /**
  117. * Updates old storage ids (v0.2.1 and older) that are based on key and secret to new ones based on the bucket name.
  118. * TODO Do this in an update.php. requires iterating over all users and loading the mount.json from their home
  119. *
  120. * @param array $params
  121. */
  122. public function updateLegacyId (array $params) {
  123. $oldId = 'amazon::' . $params['key'] . md5($params['secret']);
  124. // find by old id or bucket
  125. $stmt = \OC::$server->getDatabaseConnection()->prepare(
  126. 'SELECT `numeric_id`, `id` FROM `*PREFIX*storages` WHERE `id` IN (?, ?)'
  127. );
  128. $stmt->execute(array($oldId, $this->id));
  129. while ($row = $stmt->fetch()) {
  130. $storages[$row['id']] = $row['numeric_id'];
  131. }
  132. if (isset($storages[$this->id]) && isset($storages[$oldId])) {
  133. // if both ids exist, delete the old storage and corresponding filecache entries
  134. \OC\Files\Cache\Storage::remove($oldId);
  135. } else if (isset($storages[$oldId])) {
  136. // if only the old id exists do an update
  137. $stmt = \OC::$server->getDatabaseConnection()->prepare(
  138. 'UPDATE `*PREFIX*storages` SET `id` = ? WHERE `id` = ?'
  139. );
  140. $stmt->execute(array($this->id, $oldId));
  141. }
  142. // only the bucket based id may exist, do nothing
  143. }
  144. /**
  145. * Remove a file or folder
  146. *
  147. * @param string $path
  148. * @return bool
  149. */
  150. protected function remove($path) {
  151. // remember fileType to reduce http calls
  152. $fileType = $this->filetype($path);
  153. if ($fileType === 'dir') {
  154. return $this->rmdir($path);
  155. } else if ($fileType === 'file') {
  156. return $this->unlink($path);
  157. } else {
  158. return false;
  159. }
  160. }
  161. public function mkdir($path) {
  162. $path = $this->normalizePath($path);
  163. if ($this->is_dir($path)) {
  164. return false;
  165. }
  166. try {
  167. $this->getConnection()->putObject(array(
  168. 'Bucket' => $this->bucket,
  169. 'Key' => $path . '/',
  170. 'Body' => '',
  171. 'ContentType' => 'httpd/unix-directory'
  172. ));
  173. $this->testTimeout();
  174. } catch (S3Exception $e) {
  175. \OCP\Util::logException('files_external', $e);
  176. return false;
  177. }
  178. return true;
  179. }
  180. public function file_exists($path) {
  181. return $this->filetype($path) !== false;
  182. }
  183. public function rmdir($path) {
  184. $path = $this->normalizePath($path);
  185. if ($this->isRoot($path)) {
  186. return $this->clearBucket();
  187. }
  188. if (!$this->file_exists($path)) {
  189. return false;
  190. }
  191. return $this->batchDelete($path);
  192. }
  193. protected function clearBucket() {
  194. try {
  195. $this->getConnection()->clearBucket($this->bucket);
  196. return true;
  197. // clearBucket() is not working with Ceph, so if it fails we try the slower approach
  198. } catch (\Exception $e) {
  199. return $this->batchDelete();
  200. }
  201. return false;
  202. }
  203. private function batchDelete ($path = null) {
  204. $params = array(
  205. 'Bucket' => $this->bucket
  206. );
  207. if ($path !== null) {
  208. $params['Prefix'] = $path . '/';
  209. }
  210. try {
  211. // Since there are no real directories on S3, we need
  212. // to delete all objects prefixed with the path.
  213. do {
  214. // instead of the iterator, manually loop over the list ...
  215. $objects = $this->getConnection()->listObjects($params);
  216. // ... so we can delete the files in batches
  217. $this->getConnection()->deleteObjects(array(
  218. 'Bucket' => $this->bucket,
  219. 'Objects' => $objects['Contents']
  220. ));
  221. $this->testTimeout();
  222. // we reached the end when the list is no longer truncated
  223. } while ($objects['IsTruncated']);
  224. } catch (S3Exception $e) {
  225. \OCP\Util::logException('files_external', $e);
  226. return false;
  227. }
  228. return true;
  229. }
  230. public function opendir($path) {
  231. $path = $this->normalizePath($path);
  232. if ($this->isRoot($path)) {
  233. $path = '';
  234. } else {
  235. $path .= '/';
  236. }
  237. try {
  238. $files = array();
  239. $result = $this->getConnection()->getIterator('ListObjects', array(
  240. 'Bucket' => $this->bucket,
  241. 'Delimiter' => '/',
  242. 'Prefix' => $path
  243. ), array('return_prefixes' => true));
  244. foreach ($result as $object) {
  245. if (isset($object['Key']) && $object['Key'] === $path) {
  246. // it's the directory itself, skip
  247. continue;
  248. }
  249. $file = basename(
  250. isset($object['Key']) ? $object['Key'] : $object['Prefix']
  251. );
  252. $files[] = $file;
  253. }
  254. return IteratorDirectory::wrap($files);
  255. } catch (S3Exception $e) {
  256. \OCP\Util::logException('files_external', $e);
  257. return false;
  258. }
  259. }
  260. public function stat($path) {
  261. $path = $this->normalizePath($path);
  262. try {
  263. $stat = array();
  264. if ($this->is_dir($path)) {
  265. //folders don't really exist
  266. $stat['size'] = -1; //unknown
  267. $stat['mtime'] = time() - $this->rescanDelay * 1000;
  268. } else {
  269. $result = $this->getConnection()->headObject(array(
  270. 'Bucket' => $this->bucket,
  271. 'Key' => $path
  272. ));
  273. $stat['size'] = $result['ContentLength'] ? $result['ContentLength'] : 0;
  274. if ($result['Metadata']['lastmodified']) {
  275. $stat['mtime'] = strtotime($result['Metadata']['lastmodified']);
  276. } else {
  277. $stat['mtime'] = strtotime($result['LastModified']);
  278. }
  279. }
  280. $stat['atime'] = time();
  281. return $stat;
  282. } catch(S3Exception $e) {
  283. \OCP\Util::logException('files_external', $e);
  284. return false;
  285. }
  286. }
  287. public function filetype($path) {
  288. $path = $this->normalizePath($path);
  289. if ($this->isRoot($path)) {
  290. return 'dir';
  291. }
  292. try {
  293. if ($this->getConnection()->doesObjectExist($this->bucket, $path)) {
  294. return 'file';
  295. }
  296. if ($this->getConnection()->doesObjectExist($this->bucket, $path.'/')) {
  297. return 'dir';
  298. }
  299. } catch (S3Exception $e) {
  300. \OCP\Util::logException('files_external', $e);
  301. return false;
  302. }
  303. return false;
  304. }
  305. public function unlink($path) {
  306. $path = $this->normalizePath($path);
  307. if ($this->is_dir($path)) {
  308. return $this->rmdir($path);
  309. }
  310. try {
  311. $this->getConnection()->deleteObject(array(
  312. 'Bucket' => $this->bucket,
  313. 'Key' => $path
  314. ));
  315. $this->testTimeout();
  316. } catch (S3Exception $e) {
  317. \OCP\Util::logException('files_external', $e);
  318. return false;
  319. }
  320. return true;
  321. }
  322. public function fopen($path, $mode) {
  323. $path = $this->normalizePath($path);
  324. switch ($mode) {
  325. case 'r':
  326. case 'rb':
  327. $tmpFile = \OCP\Files::tmpFile();
  328. self::$tmpFiles[$tmpFile] = $path;
  329. try {
  330. $this->getConnection()->getObject(array(
  331. 'Bucket' => $this->bucket,
  332. 'Key' => $path,
  333. 'SaveAs' => $tmpFile
  334. ));
  335. } catch (S3Exception $e) {
  336. \OCP\Util::logException('files_external', $e);
  337. return false;
  338. }
  339. return fopen($tmpFile, 'r');
  340. case 'w':
  341. case 'wb':
  342. case 'a':
  343. case 'ab':
  344. case 'r+':
  345. case 'w+':
  346. case 'wb+':
  347. case 'a+':
  348. case 'x':
  349. case 'x+':
  350. case 'c':
  351. case 'c+':
  352. if (strrpos($path, '.') !== false) {
  353. $ext = substr($path, strrpos($path, '.'));
  354. } else {
  355. $ext = '';
  356. }
  357. $tmpFile = \OCP\Files::tmpFile($ext);
  358. \OC\Files\Stream\Close::registerCallback($tmpFile, array($this, 'writeBack'));
  359. if ($this->file_exists($path)) {
  360. $source = $this->fopen($path, 'r');
  361. file_put_contents($tmpFile, $source);
  362. }
  363. self::$tmpFiles[$tmpFile] = $path;
  364. return fopen('close://' . $tmpFile, $mode);
  365. }
  366. return false;
  367. }
  368. public function touch($path, $mtime = null) {
  369. $path = $this->normalizePath($path);
  370. $metadata = array();
  371. if (is_null($mtime)) {
  372. $mtime = time();
  373. }
  374. $metadata = [
  375. 'lastmodified' => gmdate(\Aws\Common\Enum\DateFormat::RFC1123, $mtime)
  376. ];
  377. $fileType = $this->filetype($path);
  378. try {
  379. if ($fileType !== false) {
  380. if ($fileType === 'dir' && ! $this->isRoot($path)) {
  381. $path .= '/';
  382. }
  383. $this->getConnection()->copyObject([
  384. 'Bucket' => $this->bucket,
  385. 'Key' => $this->cleanKey($path),
  386. 'Metadata' => $metadata,
  387. 'CopySource' => $this->bucket . '/' . $path,
  388. 'MetadataDirective' => 'REPLACE',
  389. ]);
  390. $this->testTimeout();
  391. } else {
  392. $mimeType = \OC::$server->getMimeTypeDetector()->detectPath($path);
  393. $this->getConnection()->putObject([
  394. 'Bucket' => $this->bucket,
  395. 'Key' => $this->cleanKey($path),
  396. 'Metadata' => $metadata,
  397. 'Body' => '',
  398. 'ContentType' => $mimeType,
  399. 'MetadataDirective' => 'REPLACE',
  400. ]);
  401. $this->testTimeout();
  402. }
  403. } catch (S3Exception $e) {
  404. \OCP\Util::logException('files_external', $e);
  405. return false;
  406. }
  407. return true;
  408. }
  409. public function copy($path1, $path2) {
  410. $path1 = $this->normalizePath($path1);
  411. $path2 = $this->normalizePath($path2);
  412. if ($this->is_file($path1)) {
  413. try {
  414. $this->getConnection()->copyObject(array(
  415. 'Bucket' => $this->bucket,
  416. 'Key' => $this->cleanKey($path2),
  417. 'CopySource' => S3Client::encodeKey($this->bucket . '/' . $path1)
  418. ));
  419. $this->testTimeout();
  420. } catch (S3Exception $e) {
  421. \OCP\Util::logException('files_external', $e);
  422. return false;
  423. }
  424. } else {
  425. $this->remove($path2);
  426. try {
  427. $this->getConnection()->copyObject(array(
  428. 'Bucket' => $this->bucket,
  429. 'Key' => $path2 . '/',
  430. 'CopySource' => S3Client::encodeKey($this->bucket . '/' . $path1 . '/')
  431. ));
  432. $this->testTimeout();
  433. } catch (S3Exception $e) {
  434. \OCP\Util::logException('files_external', $e);
  435. return false;
  436. }
  437. $dh = $this->opendir($path1);
  438. if (is_resource($dh)) {
  439. while (($file = readdir($dh)) !== false) {
  440. if (\OC\Files\Filesystem::isIgnoredDir($file)) {
  441. continue;
  442. }
  443. $source = $path1 . '/' . $file;
  444. $target = $path2 . '/' . $file;
  445. $this->copy($source, $target);
  446. }
  447. }
  448. }
  449. return true;
  450. }
  451. public function rename($path1, $path2) {
  452. $path1 = $this->normalizePath($path1);
  453. $path2 = $this->normalizePath($path2);
  454. if ($this->is_file($path1)) {
  455. if ($this->copy($path1, $path2) === false) {
  456. return false;
  457. }
  458. if ($this->unlink($path1) === false) {
  459. $this->unlink($path2);
  460. return false;
  461. }
  462. } else {
  463. if ($this->copy($path1, $path2) === false) {
  464. return false;
  465. }
  466. if ($this->rmdir($path1) === false) {
  467. $this->rmdir($path2);
  468. return false;
  469. }
  470. }
  471. return true;
  472. }
  473. public function test() {
  474. $test = $this->getConnection()->getBucketAcl(array(
  475. 'Bucket' => $this->bucket,
  476. ));
  477. if (isset($test) && !is_null($test->getPath('Owner/ID'))) {
  478. return true;
  479. }
  480. return false;
  481. }
  482. public function getId() {
  483. return $this->id;
  484. }
  485. /**
  486. * Returns the connection
  487. *
  488. * @return S3Client connected client
  489. * @throws \Exception if connection could not be made
  490. */
  491. public function getConnection() {
  492. if (!is_null($this->connection)) {
  493. return $this->connection;
  494. }
  495. $scheme = ($this->params['use_ssl'] === false) ? 'http' : 'https';
  496. $base_url = $scheme . '://' . $this->params['hostname'] . ':' . $this->params['port'] . '/';
  497. $this->connection = S3Client::factory(array(
  498. 'key' => $this->params['key'],
  499. 'secret' => $this->params['secret'],
  500. 'base_url' => $base_url,
  501. 'region' => $this->params['region'],
  502. S3Client::COMMAND_PARAMS => [
  503. 'PathStyle' => $this->params['use_path_style'],
  504. ],
  505. ));
  506. if (!$this->connection->isValidBucketName($this->bucket)) {
  507. throw new \Exception("The configured bucket name is invalid.");
  508. }
  509. if (!$this->connection->doesBucketExist($this->bucket)) {
  510. try {
  511. $this->connection->createBucket(array(
  512. 'Bucket' => $this->bucket
  513. ));
  514. $this->connection->waitUntilBucketExists(array(
  515. 'Bucket' => $this->bucket,
  516. 'waiter.interval' => 1,
  517. 'waiter.max_attempts' => 15
  518. ));
  519. $this->testTimeout();
  520. } catch (S3Exception $e) {
  521. \OCP\Util::logException('files_external', $e);
  522. throw new \Exception('Creation of bucket failed. '.$e->getMessage());
  523. }
  524. }
  525. return $this->connection;
  526. }
  527. public function writeBack($tmpFile) {
  528. if (!isset(self::$tmpFiles[$tmpFile])) {
  529. return false;
  530. }
  531. try {
  532. $this->getConnection()->putObject(array(
  533. 'Bucket' => $this->bucket,
  534. 'Key' => $this->cleanKey(self::$tmpFiles[$tmpFile]),
  535. 'SourceFile' => $tmpFile,
  536. 'ContentType' => \OC::$server->getMimeTypeDetector()->detect($tmpFile),
  537. 'ContentLength' => filesize($tmpFile)
  538. ));
  539. $this->testTimeout();
  540. unlink($tmpFile);
  541. } catch (S3Exception $e) {
  542. \OCP\Util::logException('files_external', $e);
  543. return false;
  544. }
  545. }
  546. /**
  547. * check if curl is installed
  548. */
  549. public static function checkDependencies() {
  550. return true;
  551. }
  552. }