S3Storage.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. <?php
  2. /**
  3. * S3.php
  4. *
  5. * an S3 compatible data backend for PrivateBin with CEPH/RadosGW in mind
  6. * see https://docs.ceph.com/en/latest/radosgw/s3/php/
  7. * based on lib/Data/GoogleCloudStorage.php from PrivateBin version 1.5.0
  8. *
  9. * @link https://github.com/PrivateBin/PrivateBin
  10. * @copyright 2022 Felix J. Ogris (https://ogris.de/)
  11. * @license https://www.opensource.org/licenses/zlib-license.php The zlib/libpng License
  12. * @version 1.4.1
  13. *
  14. * Installation:
  15. * 1. Make sure you have composer.lock and composer.json in the document root of your PasteBin
  16. * 2. If not, grab a copy from https://github.com/PrivateBin/PrivateBin
  17. * 3. As non-root user, install the AWS SDK for PHP:
  18. * composer require aws/aws-sdk-php
  19. * (On FreeBSD, install devel/php-composer2 prior, e.g.: make -C /usr/ports/devel/php-composer2 install clean)
  20. * 4. In cfg/conf.php, comment out all [model] and [model_options] settings
  21. * 5. Still in cfg/conf.php, add a new [model] section:
  22. * [model]
  23. * class = S3Storage
  24. * 6. Add a new [model_options] as well, e.g. for a Rados gateway as part of your CEPH cluster:
  25. * [model_options]
  26. * region = ""
  27. * version = "2006-03-01"
  28. * endpoint = "https://s3.my-ceph.invalid"
  29. * use_path_style_endpoint = true
  30. * bucket = "my-bucket"
  31. * prefix = "privatebin" (place all PrivateBin data beneath this prefix)
  32. * accesskey = "my-rados-user"
  33. * secretkey = "my-rados-pass"
  34. */
  35. namespace PrivateBin\Data;
  36. use Aws\S3\Exception\S3Exception;
  37. use Aws\S3\S3Client;
  38. use PrivateBin\Json;
  39. class S3Storage extends AbstractData
  40. {
  41. /**
  42. * S3 client
  43. *
  44. * @access private
  45. * @var S3Client
  46. */
  47. private $_client = null;
  48. /**
  49. * S3 client options
  50. *
  51. * @access private
  52. * @var array
  53. */
  54. private $_options = array();
  55. /**
  56. * S3 bucket
  57. *
  58. * @access private
  59. * @var string
  60. */
  61. private $_bucket = null;
  62. /**
  63. * S3 prefix for all PrivateBin data in this bucket
  64. *
  65. * @access private
  66. * @var string
  67. */
  68. private $_prefix = '';
  69. /**
  70. * instantiates a new S3 data backend.
  71. *
  72. * @access public
  73. * @param array $options
  74. * @return
  75. */
  76. public function __construct(array $options)
  77. {
  78. $this->_options['credentials'] = array();
  79. if (is_array($options) && array_key_exists('region', $options)) {
  80. $this->_options['region'] = $options['region'];
  81. }
  82. if (is_array($options) && array_key_exists('version', $options)) {
  83. $this->_options['version'] = $options['version'];
  84. }
  85. if (is_array($options) && array_key_exists('endpoint', $options)) {
  86. $this->_options['endpoint'] = $options['endpoint'];
  87. }
  88. if (is_array($options) && array_key_exists('accesskey', $options)) {
  89. $this->_options['credentials']['key'] = $options['accesskey'];
  90. }
  91. if (is_array($options) && array_key_exists('secretkey', $options)) {
  92. $this->_options['credentials']['secret'] = $options['secretkey'];
  93. }
  94. if (is_array($options) && array_key_exists('use_path_style_endpoint', $options)) {
  95. $this->_options['use_path_style_endpoint'] = filter_var($options['use_path_style_endpoint'], FILTER_VALIDATE_BOOLEAN);
  96. }
  97. if (is_array($options) && array_key_exists('bucket', $options)) {
  98. $this->_bucket = $options['bucket'];
  99. }
  100. if (is_array($options) && array_key_exists('prefix', $options)) {
  101. $this->_prefix = $options['prefix'];
  102. }
  103. $this->_client = new S3Client($this->_options);
  104. }
  105. /**
  106. * returns all objects in the given prefix.
  107. *
  108. * @access private
  109. * @param $prefix string with prefix
  110. * @return array all objects in the given prefix
  111. */
  112. private function _listAllObjects($prefix)
  113. {
  114. $allObjects = array();
  115. $options = array(
  116. 'Bucket' => $this->_bucket,
  117. 'Prefix' => $prefix,
  118. );
  119. do {
  120. $objectsListResponse = $this->_client->listObjects($options);
  121. $objects = $objectsListResponse['Contents'] ?? array();
  122. foreach ($objects as $object) {
  123. $allObjects[] = $object;
  124. $options['Marker'] = $object['Key'];
  125. }
  126. } while ($objectsListResponse['IsTruncated']);
  127. return $allObjects;
  128. }
  129. /**
  130. * returns the S3 storage object key for $pasteid in $this->_bucket.
  131. *
  132. * @access private
  133. * @param $pasteid string to get the key for
  134. * @return string
  135. */
  136. private function _getKey($pasteid)
  137. {
  138. if ($this->_prefix != '') {
  139. return $this->_prefix . '/' . $pasteid;
  140. }
  141. return $pasteid;
  142. }
  143. /**
  144. * Uploads the payload in the $this->_bucket under the specified key.
  145. * The entire payload is stored as a JSON document. The metadata is replicated
  146. * as the S3 object's metadata except for the fields attachment, attachmentname
  147. * and salt.
  148. *
  149. * @param $key string to store the payload under
  150. * @param $payload array to store
  151. * @return bool true if successful, otherwise false.
  152. */
  153. private function _upload($key, $payload)
  154. {
  155. $metadata = array_key_exists('meta', $payload) ? $payload['meta'] : array();
  156. unset($metadata['attachment'], $metadata['attachmentname'], $metadata['salt']);
  157. foreach ($metadata as $k => $v) {
  158. $metadata[$k] = strval($v);
  159. }
  160. try {
  161. $this->_client->putObject(array(
  162. 'Bucket' => $this->_bucket,
  163. 'Key' => $key,
  164. 'Body' => Json::encode($payload),
  165. 'ContentType' => 'application/json',
  166. 'Metadata' => $metadata,
  167. ));
  168. } catch (S3Exception $e) {
  169. error_log('failed to upload ' . $key . ' to ' . $this->_bucket . ', ' .
  170. trim(preg_replace('/\s\s+/', ' ', $e->getMessage())));
  171. return false;
  172. }
  173. return true;
  174. }
  175. /**
  176. * @inheritDoc
  177. */
  178. public function create($pasteid, array $paste)
  179. {
  180. if ($this->exists($pasteid)) {
  181. return false;
  182. }
  183. return $this->_upload($this->_getKey($pasteid), $paste);
  184. }
  185. /**
  186. * @inheritDoc
  187. */
  188. public function read($pasteid)
  189. {
  190. try {
  191. $object = $this->_client->getObject(array(
  192. 'Bucket' => $this->_bucket,
  193. 'Key' => $this->_getKey($pasteid),
  194. ));
  195. $data = $object['Body']->getContents();
  196. return Json::decode($data);
  197. } catch (S3Exception $e) {
  198. error_log('failed to read ' . $pasteid . ' from ' . $this->_bucket . ', ' .
  199. trim(preg_replace('/\s\s+/', ' ', $e->getMessage())));
  200. return false;
  201. }
  202. }
  203. /**
  204. * @inheritDoc
  205. */
  206. public function delete($pasteid)
  207. {
  208. $name = $this->_getKey($pasteid);
  209. try {
  210. $comments = $this->_listAllObjects($name . '/discussion/');
  211. foreach ($comments as $comment) {
  212. try {
  213. $this->_client->deleteObject(array(
  214. 'Bucket' => $this->_bucket,
  215. 'Key' => $comment['Key'],
  216. ));
  217. } catch (S3Exception $e) {
  218. // ignore if already deleted.
  219. }
  220. }
  221. } catch (S3Exception $e) {
  222. // there are no discussions associated with the paste
  223. }
  224. try {
  225. $this->_client->deleteObject(array(
  226. 'Bucket' => $this->_bucket,
  227. 'Key' => $name,
  228. ));
  229. } catch (S3Exception $e) {
  230. // ignore if already deleted
  231. }
  232. }
  233. /**
  234. * @inheritDoc
  235. */
  236. public function exists($pasteid)
  237. {
  238. return $this->_client->doesObjectExistV2($this->_bucket, $this->_getKey($pasteid));
  239. }
  240. /**
  241. * @inheritDoc
  242. */
  243. public function createComment($pasteid, $parentid, $commentid, array $comment)
  244. {
  245. if ($this->existsComment($pasteid, $parentid, $commentid)) {
  246. return false;
  247. }
  248. $key = $this->_getKey($pasteid) . '/discussion/' . $parentid . '/' . $commentid;
  249. return $this->_upload($key, $comment);
  250. }
  251. /**
  252. * @inheritDoc
  253. */
  254. public function readComments($pasteid)
  255. {
  256. $comments = array();
  257. $prefix = $this->_getKey($pasteid) . '/discussion/';
  258. try {
  259. $entries = $this->_listAllObjects($prefix);
  260. foreach ($entries as $entry) {
  261. $object = $this->_client->getObject(array(
  262. 'Bucket' => $this->_bucket,
  263. 'Key' => $entry['Key'],
  264. ));
  265. $body = JSON::decode($object['Body']->getContents());
  266. $items = explode('/', $entry['Key']);
  267. $body['id'] = $items[3];
  268. $body['parentid'] = $items[2];
  269. $slot = $this->getOpenSlot($comments, (int) $object['Metadata']['created']);
  270. $comments[$slot] = $body;
  271. }
  272. } catch (S3Exception $e) {
  273. // no comments found
  274. }
  275. return $comments;
  276. }
  277. /**
  278. * @inheritDoc
  279. */
  280. public function existsComment($pasteid, $parentid, $commentid)
  281. {
  282. $name = $this->_getKey($pasteid) . '/discussion/' . $parentid . '/' . $commentid;
  283. return $this->_client->doesObjectExistV2($this->_bucket, $name);
  284. }
  285. /**
  286. * @inheritDoc
  287. */
  288. public function purgeValues($namespace, $time)
  289. {
  290. $path = $this->_prefix;
  291. if ($path != '') {
  292. $path .= '/';
  293. }
  294. $path .= 'config/' . $namespace;
  295. try {
  296. foreach ($this->_listAllObjects($path) as $object) {
  297. $name = $object['Key'];
  298. if (strlen($name) > strlen($path) && substr($name, strlen($path), 1) !== '/') {
  299. continue;
  300. }
  301. $head = $this->_client->headObject(array(
  302. 'Bucket' => $this->_bucket,
  303. 'Key' => $name,
  304. ));
  305. if ($head->get('Metadata') != null && array_key_exists('value', $head->get('Metadata'))) {
  306. $value = $head->get('Metadata')['value'];
  307. if (is_numeric($value) && intval($value) < $time) {
  308. try {
  309. $this->_client->deleteObject(array(
  310. 'Bucket' => $this->_bucket,
  311. 'Key' => $name,
  312. ));
  313. } catch (S3Exception $e) {
  314. // deleted by another instance.
  315. }
  316. }
  317. }
  318. }
  319. } catch (S3Exception $e) {
  320. // no objects in the bucket yet
  321. }
  322. }
  323. /**
  324. * For S3, the value will also be stored in the metadata for the
  325. * namespaces traffic_limiter and purge_limiter.
  326. * @inheritDoc
  327. */
  328. public function setValue($value, $namespace, $key = '')
  329. {
  330. $prefix = $this->_prefix;
  331. if ($prefix != '') {
  332. $prefix .= '/';
  333. }
  334. if ($key === '') {
  335. $key = $prefix . 'config/' . $namespace;
  336. } else {
  337. $key = $prefix . 'config/' . $namespace . '/' . $key;
  338. }
  339. $metadata = array('namespace' => $namespace);
  340. if ($namespace != 'salt') {
  341. $metadata['value'] = strval($value);
  342. }
  343. try {
  344. $this->_client->putObject(array(
  345. 'Bucket' => $this->_bucket,
  346. 'Key' => $key,
  347. 'Body' => $value,
  348. 'ContentType' => 'application/json',
  349. 'Metadata' => $metadata,
  350. ));
  351. } catch (S3Exception $e) {
  352. error_log('failed to set key ' . $key . ' to ' . $this->_bucket . ', ' .
  353. trim(preg_replace('/\s\s+/', ' ', $e->getMessage())));
  354. return false;
  355. }
  356. return true;
  357. }
  358. /**
  359. * @inheritDoc
  360. */
  361. public function getValue($namespace, $key = '')
  362. {
  363. $prefix = $this->_prefix;
  364. if ($prefix != '') {
  365. $prefix .= '/';
  366. }
  367. if ($key === '') {
  368. $key = $prefix . 'config/' . $namespace;
  369. } else {
  370. $key = $prefix . 'config/' . $namespace . '/' . $key;
  371. }
  372. try {
  373. $object = $this->_client->getObject(array(
  374. 'Bucket' => $this->_bucket,
  375. 'Key' => $key,
  376. ));
  377. return $object['Body']->getContents();
  378. } catch (S3Exception $e) {
  379. return '';
  380. }
  381. }
  382. /**
  383. * @inheritDoc
  384. */
  385. protected function _getExpiredPastes($batchsize)
  386. {
  387. $expired = array();
  388. $now = time();
  389. $prefix = $this->_prefix;
  390. if ($prefix != '') {
  391. $prefix .= '/';
  392. }
  393. try {
  394. foreach ($this->_listAllObjects($prefix) as $object) {
  395. $head = $this->_client->headObject(array(
  396. 'Bucket' => $this->_bucket,
  397. 'Key' => $object['Key'],
  398. ));
  399. if ($head->get('Metadata') != null && array_key_exists('expire_date', $head->get('Metadata'))) {
  400. $expire_at = intval($head->get('Metadata')['expire_date']);
  401. if ($expire_at != 0 && $expire_at < $now) {
  402. array_push($expired, $object['Key']);
  403. }
  404. }
  405. if (count($expired) > $batchsize) {
  406. break;
  407. }
  408. }
  409. } catch (S3Exception $e) {
  410. // no objects in the bucket yet
  411. }
  412. return $expired;
  413. }
  414. /**
  415. * @inheritDoc
  416. */
  417. public function getAllPastes()
  418. {
  419. $pastes = array();
  420. $prefix = $this->_prefix;
  421. if ($prefix != '') {
  422. $prefix .= '/';
  423. }
  424. try {
  425. foreach ($this->_listAllObjects($prefix) as $object) {
  426. $candidate = substr($object['Key'], strlen($prefix));
  427. if (strpos($candidate, '/') === false) {
  428. $pastes[] = $candidate;
  429. }
  430. }
  431. } catch (S3Exception $e) {
  432. // no objects in the bucket yet
  433. }
  434. return $pastes;
  435. }
  436. }