S3Storage.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  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.4.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. * @static
  46. * @var S3Client
  47. */
  48. private static $_client = null;
  49. /**
  50. * S3 client options
  51. *
  52. * @access private
  53. * @static
  54. * @var array
  55. */
  56. private static $_options = array();
  57. /**
  58. * S3 bucket
  59. *
  60. * @access private
  61. * @static
  62. * @var string
  63. */
  64. private static $_bucket = null;
  65. /**
  66. * S3 prefix for all PrivateBin data in this bucket
  67. *
  68. * @access private
  69. * @static
  70. * @var string
  71. */
  72. private static $_prefix = '';
  73. /**
  74. * returns an S3 data backend.
  75. *
  76. * @access public
  77. * @static
  78. * @param array $options
  79. * @return S3Storage
  80. */
  81. public static function getInstance(array $options)
  82. {
  83. // if needed initialize the singleton
  84. if (!(self::$_instance instanceof self)) {
  85. self::$_instance = new self;
  86. }
  87. self::$_options = array();
  88. self::$_options['credentials'] = array();
  89. if (is_array($options) && array_key_exists('region', $options)) {
  90. self::$_options['region'] = $options['region'];
  91. }
  92. if (is_array($options) && array_key_exists('version', $options)) {
  93. self::$_options['version'] = $options['version'];
  94. }
  95. if (is_array($options) && array_key_exists('endpoint', $options)) {
  96. self::$_options['endpoint'] = $options['endpoint'];
  97. }
  98. if (is_array($options) && array_key_exists('accesskey', $options)) {
  99. self::$_options['credentials']['key'] = $options['accesskey'];
  100. }
  101. if (is_array($options) && array_key_exists('secretkey', $options)) {
  102. self::$_options['credentials']['secret'] = $options['secretkey'];
  103. }
  104. if (is_array($options) && array_key_exists('use_path_style_endpoint', $options)) {
  105. self::$_options['use_path_style_endpoint'] = filter_var($options['use_path_style_endpoint'], FILTER_VALIDATE_BOOLEAN);
  106. }
  107. if (is_array($options) && array_key_exists('bucket', $options)) {
  108. self::$_bucket = $options['bucket'];
  109. }
  110. if (is_array($options) && array_key_exists('prefix', $options)) {
  111. self::$_prefix = $options['prefix'];
  112. }
  113. if (empty(self::$_client)) {
  114. self::$_client = new S3Client(self::$_options);
  115. }
  116. return self::$_instance;
  117. }
  118. /**
  119. * returns all objects in the given prefix.
  120. *
  121. * @access private
  122. * @param $prefix string with prefix
  123. * @return array all objects in the given prefix
  124. */
  125. private function _listAllObjects($prefix)
  126. {
  127. $allObjects = array();
  128. $options = array(
  129. 'Bucket' => self::$_bucket,
  130. 'Prefix' => $prefix,
  131. );
  132. do {
  133. $objectsListResponse = self::$_client->listObjects($options);
  134. $objects = $objectsListResponse['Contents'] ?? array();
  135. foreach ($objects as $object) {
  136. $allObjects[] = $object;
  137. $options['Marker'] = $object['Key'];
  138. }
  139. } while ($objectsListResponse['IsTruncated']);
  140. return $allObjects;
  141. }
  142. /**
  143. * returns the S3 storage object key for $pasteid in self::$_bucket.
  144. *
  145. * @access private
  146. * @param $pasteid string to get the key for
  147. * @return string
  148. */
  149. private function _getKey($pasteid)
  150. {
  151. if (self::$_prefix != '') {
  152. return self::$_prefix . '/' . $pasteid;
  153. }
  154. return $pasteid;
  155. }
  156. /**
  157. * Uploads the payload in the self::$_bucket under the specified key.
  158. * The entire payload is stored as a JSON document. The metadata is replicated
  159. * as the S3 object's metadata except for the fields attachment, attachmentname
  160. * and salt.
  161. *
  162. * @param $key string to store the payload under
  163. * @param $payload array to store
  164. * @return bool true if successful, otherwise false.
  165. */
  166. private function _upload($key, $payload)
  167. {
  168. $metadata = array_key_exists('meta', $payload) ? $payload['meta'] : array();
  169. unset($metadata['attachment'], $metadata['attachmentname'], $metadata['salt']);
  170. foreach ($metadata as $k => $v) {
  171. $metadata[$k] = strval($v);
  172. }
  173. try {
  174. self::$_client->putObject(array(
  175. 'Bucket' => self::$_bucket,
  176. 'Key' => $key,
  177. 'Body' => Json::encode($payload),
  178. 'ContentType' => 'application/json',
  179. 'Metadata' => $metadata,
  180. ));
  181. } catch (S3Exception $e) {
  182. error_log('failed to upload ' . $key . ' to ' . self::$_bucket . ', ' .
  183. trim(preg_replace('/\s\s+/', ' ', $e->getMessage())));
  184. return false;
  185. }
  186. return true;
  187. }
  188. /**
  189. * @inheritDoc
  190. */
  191. public function create($pasteid, array $paste)
  192. {
  193. if ($this->exists($pasteid)) {
  194. return false;
  195. }
  196. return $this->_upload($this->_getKey($pasteid), $paste);
  197. }
  198. /**
  199. * @inheritDoc
  200. */
  201. public function read($pasteid)
  202. {
  203. try {
  204. $object = self::$_client->getObject(array(
  205. 'Bucket' => self::$_bucket,
  206. 'Key' => $this->_getKey($pasteid),
  207. ));
  208. $data = $object['Body']->getContents();
  209. return Json::decode($data);
  210. } catch (S3Exception $e) {
  211. error_log('failed to read ' . $pasteid . ' from ' . self::$_bucket . ', ' .
  212. trim(preg_replace('/\s\s+/', ' ', $e->getMessage())));
  213. return false;
  214. }
  215. }
  216. /**
  217. * @inheritDoc
  218. */
  219. public function delete($pasteid)
  220. {
  221. $name = $this->_getKey($pasteid);
  222. try {
  223. $comments = $this->_listAllObjects($name . '/discussion/');
  224. foreach ($comments as $comment) {
  225. try {
  226. self::$_client->deleteObject(array(
  227. 'Bucket' => self::$_bucket,
  228. 'Key' => $comment['Key'],
  229. ));
  230. } catch (S3Exception $e) {
  231. // ignore if already deleted.
  232. }
  233. }
  234. } catch (S3Exception $e) {
  235. // there are no discussions associated with the paste
  236. }
  237. try {
  238. self::$_client->deleteObject(array(
  239. 'Bucket' => self::$_bucket,
  240. 'Key' => $name,
  241. ));
  242. } catch (S3Exception $e) {
  243. // ignore if already deleted
  244. }
  245. }
  246. /**
  247. * @inheritDoc
  248. */
  249. public function exists($pasteid)
  250. {
  251. return self::$_client->doesObjectExistV2(self::$_bucket, $this->_getKey($pasteid));
  252. }
  253. /**
  254. * @inheritDoc
  255. */
  256. public function createComment($pasteid, $parentid, $commentid, array $comment)
  257. {
  258. if ($this->existsComment($pasteid, $parentid, $commentid)) {
  259. return false;
  260. }
  261. $key = $this->_getKey($pasteid) . '/discussion/' . $parentid . '/' . $commentid;
  262. return $this->_upload($key, $comment);
  263. }
  264. /**
  265. * @inheritDoc
  266. */
  267. public function readComments($pasteid)
  268. {
  269. $comments = array();
  270. $prefix = $this->_getKey($pasteid) . '/discussion/';
  271. try {
  272. $entries = $this->_listAllObjects($prefix);
  273. foreach ($entries as $entry) {
  274. $object = self::$_client->getObject(array(
  275. 'Bucket' => self::$_bucket,
  276. 'Key' => $entry['Key'],
  277. ));
  278. $body = JSON::decode($object['Body']->getContents());
  279. $items = explode('/', $entry['Key']);
  280. $body['id'] = $items[3];
  281. $body['parentid'] = $items[2];
  282. $slot = $this->getOpenSlot($comments, (int) $object['Metadata']['created']);
  283. $comments[$slot] = $body;
  284. }
  285. } catch (S3Exception $e) {
  286. // no comments found
  287. }
  288. return $comments;
  289. }
  290. /**
  291. * @inheritDoc
  292. */
  293. public function existsComment($pasteid, $parentid, $commentid)
  294. {
  295. $name = $this->_getKey($pasteid) . '/discussion/' . $parentid . '/' . $commentid;
  296. return self::$_client->doesObjectExistV2(self::$_bucket, $name);
  297. }
  298. /**
  299. * @inheritDoc
  300. */
  301. public function purgeValues($namespace, $time)
  302. {
  303. $path = self::$_prefix;
  304. if ($path != '') {
  305. $path .= '/';
  306. }
  307. $path .= 'config/' . $namespace;
  308. try {
  309. foreach ($this->_listAllObjects($path) as $object) {
  310. $name = $object['Key'];
  311. if (strlen($name) > strlen($path) && substr($name, strlen($path), 1) !== '/') {
  312. continue;
  313. }
  314. $head = self::$_client->headObject(array(
  315. 'Bucket' => self::$_bucket,
  316. 'Key' => $name,
  317. ));
  318. if (array_key_exists('Metadata', $head) && array_key_exists('value', $head['Metadata'])) {
  319. $value = $head['Metadata']['value'];
  320. if (is_numeric($value) && intval($value) < $time) {
  321. try {
  322. self::$_client->deleteObject(array(
  323. 'Bucket' => self::$_bucket,
  324. 'Key' => $name,
  325. ));
  326. } catch (S3Exception $e) {
  327. // deleted by another instance.
  328. }
  329. }
  330. }
  331. }
  332. } catch (S3Exception $e) {
  333. // no objects in the bucket yet
  334. }
  335. }
  336. /**
  337. * For S3, the value will also be stored in the metadata for the
  338. * namespaces traffic_limiter and purge_limiter.
  339. * @inheritDoc
  340. */
  341. public function setValue($value, $namespace, $key = '')
  342. {
  343. $prefix = self::$_prefix;
  344. if ($prefix != '') {
  345. $prefix .= '/';
  346. }
  347. if ($key === '') {
  348. $key = $prefix . 'config/' . $namespace;
  349. } else {
  350. $key = $prefix . 'config/' . $namespace . '/' . $key;
  351. }
  352. $metadata = array('namespace' => $namespace);
  353. if ($namespace != 'salt') {
  354. $metadata['value'] = strval($value);
  355. }
  356. try {
  357. self::$_client->putObject(array(
  358. 'Bucket' => self::$_bucket,
  359. 'Key' => $key,
  360. 'Body' => $value,
  361. 'ContentType' => 'application/json',
  362. 'Metadata' => $metadata,
  363. ));
  364. } catch (S3Exception $e) {
  365. error_log('failed to set key ' . $key . ' to ' . self::$_bucket . ', ' .
  366. trim(preg_replace('/\s\s+/', ' ', $e->getMessage())));
  367. return false;
  368. }
  369. return true;
  370. }
  371. /**
  372. * @inheritDoc
  373. */
  374. public function getValue($namespace, $key = '')
  375. {
  376. $prefix = self::$_prefix;
  377. if ($prefix != '') {
  378. $prefix .= '/';
  379. }
  380. if ($key === '') {
  381. $key = $prefix . 'config/' . $namespace;
  382. } else {
  383. $key = $prefix . 'config/' . $namespace . '/' . $key;
  384. }
  385. try {
  386. $object = self::$_client->getObject(array(
  387. 'Bucket' => self::$_bucket,
  388. 'Key' => $key,
  389. ));
  390. return $object['Body']->getContents();
  391. } catch (S3Exception $e) {
  392. return '';
  393. }
  394. }
  395. /**
  396. * @inheritDoc
  397. */
  398. protected function _getExpiredPastes($batchsize)
  399. {
  400. $expired = array();
  401. $now = time();
  402. $prefix = self::$_prefix;
  403. if ($prefix != '') {
  404. $prefix .= '/';
  405. }
  406. try {
  407. foreach ($this->_listAllObjects($prefix) as $object) {
  408. $head = self::$_client->headObject(array(
  409. 'Bucket' => self::$_bucket,
  410. 'Key' => $object['Key'],
  411. ));
  412. if (array_key_exists('Metadata', $head) && array_key_exists('expire_date', $head['Metadata'])) {
  413. $expire_at = intval($head['Metadata']['expire_date']);
  414. if ($expire_at != 0 && $expire_at < $now) {
  415. array_push($expired, $object['Key']);
  416. }
  417. }
  418. if (count($expired) > $batchsize) {
  419. break;
  420. }
  421. }
  422. } catch (S3Exception $e) {
  423. // no objects in the bucket yet
  424. }
  425. return $expired;
  426. }
  427. }