amazons3.php 16 KB

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