amazons3.php 15 KB

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