Filesystem.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. <?php declare(strict_types=1);
  2. /**
  3. * PrivateBin
  4. *
  5. * a zero-knowledge paste bin
  6. *
  7. * @link https://github.com/PrivateBin/PrivateBin
  8. * @copyright 2012 Sébastien SAUVAGE (sebsauvage.net)
  9. * @license https://www.opensource.org/licenses/zlib-license.php The zlib/libpng License
  10. */
  11. namespace PrivateBin\Data;
  12. use DirectoryIterator;
  13. use GlobIterator;
  14. use JsonException;
  15. use PrivateBin\Json;
  16. /**
  17. * Filesystem
  18. *
  19. * Model for filesystem data access, implemented as a singleton.
  20. */
  21. class Filesystem extends AbstractData
  22. {
  23. /**
  24. * glob() pattern of the two folder levels and the paste files under the
  25. * configured path. Needs to return both files with and without .php suffix,
  26. * so they can be hardened by _prependRename(), which is hooked into exists().
  27. *
  28. * > Note that wildcard patterns are not regular expressions, although they
  29. * > are a bit similar.
  30. *
  31. * @link https://man7.org/linux/man-pages/man7/glob.7.html
  32. * @const string
  33. */
  34. const PASTE_FILE_PATTERN = DIRECTORY_SEPARATOR . '[a-f0-9][a-f0-9]' .
  35. DIRECTORY_SEPARATOR . '[a-f0-9][a-f0-9]' . DIRECTORY_SEPARATOR .
  36. '[a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9]' .
  37. '[a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9]*';
  38. /**
  39. * first line in paste or comment files, to protect their contents from browsing exposed data directories
  40. *
  41. * @const string
  42. */
  43. const PROTECTION_LINE = '<?php http_response_code(403); /*';
  44. /**
  45. * line in generated .htaccess files, to protect exposed directories from being browsable on apache web servers
  46. *
  47. * @const string
  48. */
  49. const HTACCESS_LINE = 'Require all denied';
  50. /**
  51. * path in which to persist something
  52. *
  53. * @access private
  54. * @var string
  55. */
  56. private $_path = 'data';
  57. /**
  58. * instantiates a new Filesystem data backend
  59. *
  60. * @access public
  61. * @param array $options
  62. */
  63. public function __construct(array $options)
  64. {
  65. // if given update the data directory
  66. if (array_key_exists('dir', $options)) {
  67. $this->_path = $options['dir'];
  68. }
  69. }
  70. /**
  71. * Create a paste.
  72. *
  73. * @access public
  74. * @param string $pasteid
  75. * @param array $paste
  76. * @return bool
  77. */
  78. public function create($pasteid, array &$paste)
  79. {
  80. $storagedir = $this->_dataid2path($pasteid);
  81. $file = $storagedir . $pasteid . '.php';
  82. if (is_file($file)) {
  83. return false;
  84. }
  85. if (!is_dir($storagedir)) {
  86. mkdir($storagedir, 0700, true);
  87. }
  88. return $this->_store($file, $paste);
  89. }
  90. /**
  91. * Read a paste.
  92. *
  93. * @access public
  94. * @param string $pasteid
  95. * @return array|false
  96. */
  97. public function read($pasteid)
  98. {
  99. if ($this->exists($pasteid)) {
  100. return $this->_get($this->_dataid2path($pasteid) . $pasteid . '.php');
  101. }
  102. return false;
  103. }
  104. /**
  105. * Delete a paste and its discussion.
  106. *
  107. * @access public
  108. * @param string $pasteid
  109. */
  110. public function delete($pasteid)
  111. {
  112. $pastedir = $this->_dataid2path($pasteid);
  113. if (is_dir($pastedir)) {
  114. // Delete the paste itself.
  115. $pastefile = $pastedir . $pasteid . '.php';
  116. if (is_file($pastefile)) {
  117. if (!unlink($pastefile)) {
  118. error_log('Error deleting paste: ' . $pastefile);
  119. }
  120. }
  121. // Delete discussion if it exists.
  122. $discdir = $this->_dataid2discussionpath($pasteid);
  123. if (is_dir($discdir)) {
  124. // Delete all files in discussion directory
  125. foreach (new DirectoryIterator($discdir) as $file) {
  126. if ($file->isFile()) {
  127. if (!unlink($file->getPathname())) {
  128. error_log('Error deleting comment: ' . $file->getPathname());
  129. }
  130. }
  131. }
  132. rmdir($discdir);
  133. }
  134. }
  135. }
  136. /**
  137. * Test if a paste exists.
  138. *
  139. * @access public
  140. * @param string $pasteid
  141. * @return bool
  142. */
  143. public function exists($pasteid)
  144. {
  145. $basePath = $this->_dataid2path($pasteid) . $pasteid;
  146. $pastePath = $basePath . '.php';
  147. // convert to PHP protected files if needed
  148. if (is_readable($basePath)) {
  149. $this->_prependRename($basePath, $pastePath);
  150. // convert comments, too
  151. $discdir = $this->_dataid2discussionpath($pasteid);
  152. if (is_dir($discdir)) {
  153. foreach (new DirectoryIterator($discdir) as $file) {
  154. if ($file->getExtension() !== 'php' && strlen($file->getFilename()) >= 16) {
  155. $this->_prependRename($file->getPathname(), $file->getPathname() . '.php');
  156. }
  157. }
  158. }
  159. }
  160. return is_readable($pastePath);
  161. }
  162. /**
  163. * Create a comment in a paste.
  164. *
  165. * @access public
  166. * @param string $pasteid
  167. * @param string $parentid
  168. * @param string $commentid
  169. * @param array $comment
  170. * @return bool
  171. */
  172. public function createComment($pasteid, $parentid, $commentid, array &$comment)
  173. {
  174. $storagedir = $this->_dataid2discussionpath($pasteid);
  175. $file = $storagedir . $pasteid . '.' . $commentid . '.' . $parentid . '.php';
  176. if (is_file($file)) {
  177. return false;
  178. }
  179. if (!is_dir($storagedir)) {
  180. mkdir($storagedir, 0700, true);
  181. }
  182. return $this->_store($file, $comment);
  183. }
  184. /**
  185. * Read all comments of paste.
  186. *
  187. * @access public
  188. * @param string $pasteid
  189. * @return array
  190. */
  191. public function readComments($pasteid)
  192. {
  193. $comments = [];
  194. $discdir = $this->_dataid2discussionpath($pasteid);
  195. if (is_dir($discdir)) {
  196. foreach (new DirectoryIterator($discdir) as $file) {
  197. // Filename is in the form pasteid.commentid.parentid.php:
  198. // - pasteid is the paste this reply belongs to.
  199. // - commentid is the comment identifier itself.
  200. // - parentid is the comment this comment replies to (It can be pasteid)
  201. if ($file->isFile()) {
  202. $items = explode('.', $file->getBasename('.php'));
  203. if (
  204. $file->getExtension() !== 'php' ||
  205. count($items) !== 3 ||
  206. $items[0] !== $pasteid ||
  207. preg_match('/\A[a-f0-9]{16}\z/', $items[1]) !== 1 ||
  208. preg_match('/\A[a-f0-9]{16}\z/', $items[2]) !== 1
  209. ) {
  210. continue;
  211. }
  212. $comment = $this->_get($file->getPathname());
  213. if (
  214. !is_array($comment) ||
  215. !isset($comment['meta']['created']) ||
  216. !(is_int($comment['meta']['created']) || is_string($comment['meta']['created']))
  217. ) {
  218. continue;
  219. }
  220. // Add some meta information not contained in file.
  221. $comment['id'] = $items[1];
  222. $comment['parentid'] = $items[2];
  223. // Store in array
  224. $key = $this->getOpenSlot(
  225. $comments,
  226. $comment['meta']['created']
  227. );
  228. $comments[$key] = $comment;
  229. }
  230. }
  231. }
  232. return $this->sortComments($comments);
  233. }
  234. /**
  235. * Test if a comment exists.
  236. *
  237. * @access public
  238. * @param string $pasteid
  239. * @param string $parentid
  240. * @param string $commentid
  241. * @return bool
  242. */
  243. public function existsComment($pasteid, $parentid, $commentid)
  244. {
  245. return is_file(
  246. $this->_dataid2discussionpath($pasteid) .
  247. $pasteid . '.' . $commentid . '.' . $parentid . '.php'
  248. );
  249. }
  250. /**
  251. * Save a value.
  252. *
  253. * @access public
  254. * @param string $value
  255. * @param string $namespace
  256. * @param string $key
  257. * @return bool
  258. */
  259. public function setValue($value, $namespace, $key = '')
  260. {
  261. $file = $this->_path . DIRECTORY_SEPARATOR . $namespace . '.php';
  262. if (function_exists('opcache_invalidate')) {
  263. opcache_invalidate($file);
  264. }
  265. switch ($namespace) {
  266. case 'purge_limiter':
  267. $content = '<?php' . PHP_EOL . '$GLOBALS[\'purge_limiter\'] = ' . var_export($value, true) . ';';
  268. break;
  269. case 'salt':
  270. $content = '<?php # |' . $value . '|';
  271. break;
  272. case 'traffic_limiter':
  273. $this->_last_cache[$key] = $value;
  274. $content = '<?php' . PHP_EOL . '$GLOBALS[\'traffic_limiter\'] = ' . var_export($this->_last_cache, true) . ';';
  275. break;
  276. default:
  277. return false;
  278. }
  279. return $this->_storeString($file, $content);
  280. }
  281. /**
  282. * Load a value.
  283. *
  284. * @access public
  285. * @param string $namespace
  286. * @param string $key
  287. * @return string
  288. */
  289. public function getValue($namespace, $key = '')
  290. {
  291. switch ($namespace) {
  292. case 'purge_limiter':
  293. $file = $this->_path . DIRECTORY_SEPARATOR . 'purge_limiter.php';
  294. if (is_readable($file)) {
  295. require $file;
  296. if (array_key_exists('purge_limiter', $GLOBALS)) {
  297. return $GLOBALS['purge_limiter'];
  298. }
  299. }
  300. break;
  301. case 'salt':
  302. $file = $this->_path . DIRECTORY_SEPARATOR . 'salt.php';
  303. if (is_readable($file)) {
  304. $items = explode('|', file_get_contents($file));
  305. if (count($items) === 3) {
  306. return $items[1];
  307. }
  308. }
  309. break;
  310. case 'traffic_limiter':
  311. $file = $this->_path . DIRECTORY_SEPARATOR . 'traffic_limiter.php';
  312. if (is_readable($file)) {
  313. require $file;
  314. if (array_key_exists('traffic_limiter', $GLOBALS)) {
  315. $this->_last_cache = $GLOBALS['traffic_limiter'];
  316. if (array_key_exists($key, $this->_last_cache)) {
  317. return $this->_last_cache[$key];
  318. }
  319. }
  320. }
  321. break;
  322. }
  323. return '';
  324. }
  325. /**
  326. * get the data
  327. *
  328. * @access public
  329. * @param string $filename
  330. * @return array|false $data
  331. */
  332. private function _get($filename)
  333. {
  334. $data = substr(
  335. file_get_contents($filename),
  336. strlen(self::PROTECTION_LINE . PHP_EOL)
  337. );
  338. try {
  339. return Json::decode($data);
  340. } catch (JsonException $e) {
  341. error_log('Error decoding JSON from "' . $filename . '": ' . $e->getMessage());
  342. return false;
  343. }
  344. }
  345. /**
  346. * Returns up to batch size number of paste ids that have expired
  347. *
  348. * @access private
  349. * @param int $batchsize
  350. * @return array
  351. */
  352. protected function _getExpiredPastes($batchsize)
  353. {
  354. $pastes = [];
  355. $count = 0;
  356. $opened = 0;
  357. $limit = $batchsize * 10; // try at most 10 times $batchsize pastes before giving up
  358. $time = time();
  359. $files = $this->getAllPastes();
  360. shuffle($files);
  361. foreach ($files as $pasteid) {
  362. if ($this->exists($pasteid)) {
  363. $data = $this->read($pasteid);
  364. if (($data['meta']['expire_date'] ?? $time) < $time) {
  365. $pastes[] = $pasteid;
  366. if (++$count >= $batchsize) {
  367. break;
  368. }
  369. }
  370. if (++$opened >= $limit) {
  371. break;
  372. }
  373. }
  374. }
  375. return $pastes;
  376. }
  377. /**
  378. * @inheritDoc
  379. */
  380. public function getAllPastes()
  381. {
  382. $pastes = [];
  383. foreach (new GlobIterator($this->_path . self::PASTE_FILE_PATTERN) as $file) {
  384. if ($file->isFile()) {
  385. $pastes[] = $file->getBasename('.php');
  386. }
  387. }
  388. return $pastes;
  389. }
  390. /**
  391. * Convert paste id to storage path.
  392. *
  393. * The idea is to creates subdirectories in order to limit the number of files per directory.
  394. * (A high number of files in a single directory can slow things down.)
  395. * eg. "f468483c313401e8" will be stored in "data/f4/68/f468483c313401e8"
  396. * High-trafic websites may want to deepen the directory structure (like Squid does).
  397. *
  398. * eg. input 'e3570978f9e4aa90' --> output 'data/e3/57/'
  399. *
  400. * @access private
  401. * @param string $dataid
  402. * @return string
  403. */
  404. private function _dataid2path($dataid)
  405. {
  406. return $this->_path . DIRECTORY_SEPARATOR .
  407. substr($dataid, 0, 2) . DIRECTORY_SEPARATOR .
  408. substr($dataid, 2, 2) . DIRECTORY_SEPARATOR;
  409. }
  410. /**
  411. * Convert paste id to discussion storage path.
  412. *
  413. * eg. input 'e3570978f9e4aa90' --> output 'data/e3/57/e3570978f9e4aa90.discussion/'
  414. *
  415. * @access private
  416. * @param string $dataid
  417. * @return string
  418. */
  419. private function _dataid2discussionpath($dataid)
  420. {
  421. return $this->_dataid2path($dataid) . $dataid .
  422. '.discussion' . DIRECTORY_SEPARATOR;
  423. }
  424. /**
  425. * store the data
  426. *
  427. * @access public
  428. * @param string $filename
  429. * @param array $data
  430. * @return bool
  431. */
  432. private function _store($filename, array $data)
  433. {
  434. try {
  435. return $this->_storeString(
  436. $filename,
  437. self::PROTECTION_LINE . PHP_EOL . Json::encode($data)
  438. );
  439. } catch (JsonException $e) {
  440. error_log('Error while trying to store data to the filesystem at path "' . $filename . '": ' . $e->getMessage());
  441. return false;
  442. }
  443. }
  444. /**
  445. * store a string
  446. *
  447. * @access public
  448. * @param string $filename
  449. * @param string $data
  450. * @return bool
  451. */
  452. private function _storeString($filename, $data)
  453. {
  454. // Create storage directory if it does not exist.
  455. if (!is_dir($this->_path)) {
  456. if (!@mkdir($this->_path, 0700)) {
  457. return false;
  458. }
  459. }
  460. $file = $this->_path . DIRECTORY_SEPARATOR . '.htaccess';
  461. if (!is_file($file)) {
  462. $writtenBytes = 0;
  463. if ($fileCreated = @touch($file)) {
  464. $writtenBytes = @file_put_contents(
  465. $file,
  466. self::HTACCESS_LINE . PHP_EOL,
  467. LOCK_EX
  468. );
  469. }
  470. if (
  471. $fileCreated === false ||
  472. $writtenBytes === false ||
  473. $writtenBytes < strlen(self::HTACCESS_LINE . PHP_EOL)
  474. ) {
  475. return false;
  476. }
  477. }
  478. $fileCreated = true;
  479. $writtenBytes = 0;
  480. if (!is_file($filename)) {
  481. $fileCreated = @touch($filename);
  482. }
  483. if ($fileCreated) {
  484. $writtenBytes = @file_put_contents($filename, $data, LOCK_EX);
  485. }
  486. if ($fileCreated === false || $writtenBytes === false || $writtenBytes < strlen($data)) {
  487. return false;
  488. }
  489. chmod($filename, 0640); // protect file from access by other users on the host
  490. return true;
  491. }
  492. /**
  493. * rename a file, prepending the protection line at the beginning
  494. *
  495. * @access public
  496. * @param string $srcFile
  497. * @param string $destFile
  498. * @return void
  499. */
  500. private function _prependRename($srcFile, $destFile)
  501. {
  502. // don't overwrite already converted file
  503. if (!is_readable($destFile)) {
  504. $handle = fopen($srcFile, 'r', false, stream_context_create());
  505. file_put_contents($destFile, self::PROTECTION_LINE . PHP_EOL);
  506. file_put_contents($destFile, $handle, FILE_APPEND);
  507. fclose($handle);
  508. chmod($destFile, 0640); // protect file from access by other users on the host
  509. }
  510. if (!unlink($srcFile)) {
  511. error_log('Error deleting converted document: ' . $srcFile);
  512. }
  513. }
  514. }