Filesystem.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  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. // Sort comments by date, oldest first.
  232. ksort($comments);
  233. }
  234. return $comments;
  235. }
  236. /**
  237. * Test if a comment exists.
  238. *
  239. * @access public
  240. * @param string $pasteid
  241. * @param string $parentid
  242. * @param string $commentid
  243. * @return bool
  244. */
  245. public function existsComment($pasteid, $parentid, $commentid)
  246. {
  247. return is_file(
  248. $this->_dataid2discussionpath($pasteid) .
  249. $pasteid . '.' . $commentid . '.' . $parentid . '.php'
  250. );
  251. }
  252. /**
  253. * Save a value.
  254. *
  255. * @access public
  256. * @param string $value
  257. * @param string $namespace
  258. * @param string $key
  259. * @return bool
  260. */
  261. public function setValue($value, $namespace, $key = '')
  262. {
  263. $file = $this->_path . DIRECTORY_SEPARATOR . $namespace . '.php';
  264. if (function_exists('opcache_invalidate')) {
  265. opcache_invalidate($file);
  266. }
  267. switch ($namespace) {
  268. case 'purge_limiter':
  269. $content = '<?php' . PHP_EOL . '$GLOBALS[\'purge_limiter\'] = ' . var_export($value, true) . ';';
  270. break;
  271. case 'salt':
  272. $content = '<?php # |' . $value . '|';
  273. break;
  274. case 'traffic_limiter':
  275. $this->_last_cache[$key] = $value;
  276. $content = '<?php' . PHP_EOL . '$GLOBALS[\'traffic_limiter\'] = ' . var_export($this->_last_cache, true) . ';';
  277. break;
  278. default:
  279. return false;
  280. }
  281. return $this->_storeString($file, $content);
  282. }
  283. /**
  284. * Load a value.
  285. *
  286. * @access public
  287. * @param string $namespace
  288. * @param string $key
  289. * @return string
  290. */
  291. public function getValue($namespace, $key = '')
  292. {
  293. switch ($namespace) {
  294. case 'purge_limiter':
  295. $file = $this->_path . DIRECTORY_SEPARATOR . 'purge_limiter.php';
  296. if (is_readable($file)) {
  297. require $file;
  298. if (array_key_exists('purge_limiter', $GLOBALS)) {
  299. return $GLOBALS['purge_limiter'];
  300. }
  301. }
  302. break;
  303. case 'salt':
  304. $file = $this->_path . DIRECTORY_SEPARATOR . 'salt.php';
  305. if (is_readable($file)) {
  306. $items = explode('|', file_get_contents($file));
  307. if (count($items) === 3) {
  308. return $items[1];
  309. }
  310. }
  311. break;
  312. case 'traffic_limiter':
  313. $file = $this->_path . DIRECTORY_SEPARATOR . 'traffic_limiter.php';
  314. if (is_readable($file)) {
  315. require $file;
  316. if (array_key_exists('traffic_limiter', $GLOBALS)) {
  317. $this->_last_cache = $GLOBALS['traffic_limiter'];
  318. if (array_key_exists($key, $this->_last_cache)) {
  319. return $this->_last_cache[$key];
  320. }
  321. }
  322. }
  323. break;
  324. }
  325. return '';
  326. }
  327. /**
  328. * get the data
  329. *
  330. * @access public
  331. * @param string $filename
  332. * @return array|false $data
  333. */
  334. private function _get($filename)
  335. {
  336. $data = substr(
  337. file_get_contents($filename),
  338. strlen(self::PROTECTION_LINE . PHP_EOL)
  339. );
  340. try {
  341. return Json::decode($data);
  342. } catch (JsonException $e) {
  343. error_log('Error decoding JSON from "' . $filename . '": ' . $e->getMessage());
  344. return false;
  345. }
  346. }
  347. /**
  348. * Returns up to batch size number of paste ids that have expired
  349. *
  350. * @access private
  351. * @param int $batchsize
  352. * @return array
  353. */
  354. protected function _getExpiredPastes($batchsize)
  355. {
  356. $pastes = [];
  357. $count = 0;
  358. $opened = 0;
  359. $limit = $batchsize * 10; // try at most 10 times $batchsize pastes before giving up
  360. $time = time();
  361. $files = $this->getAllPastes();
  362. shuffle($files);
  363. foreach ($files as $pasteid) {
  364. if ($this->exists($pasteid)) {
  365. $data = $this->read($pasteid);
  366. if (($data['meta']['expire_date'] ?? $time) < $time) {
  367. $pastes[] = $pasteid;
  368. if (++$count >= $batchsize) {
  369. break;
  370. }
  371. }
  372. if (++$opened >= $limit) {
  373. break;
  374. }
  375. }
  376. }
  377. return $pastes;
  378. }
  379. /**
  380. * @inheritDoc
  381. */
  382. public function getAllPastes()
  383. {
  384. $pastes = [];
  385. foreach (new GlobIterator($this->_path . self::PASTE_FILE_PATTERN) as $file) {
  386. if ($file->isFile()) {
  387. $pastes[] = $file->getBasename('.php');
  388. }
  389. }
  390. return $pastes;
  391. }
  392. /**
  393. * Convert paste id to storage path.
  394. *
  395. * The idea is to creates subdirectories in order to limit the number of files per directory.
  396. * (A high number of files in a single directory can slow things down.)
  397. * eg. "f468483c313401e8" will be stored in "data/f4/68/f468483c313401e8"
  398. * High-trafic websites may want to deepen the directory structure (like Squid does).
  399. *
  400. * eg. input 'e3570978f9e4aa90' --> output 'data/e3/57/'
  401. *
  402. * @access private
  403. * @param string $dataid
  404. * @return string
  405. */
  406. private function _dataid2path($dataid)
  407. {
  408. return $this->_path . DIRECTORY_SEPARATOR .
  409. substr($dataid, 0, 2) . DIRECTORY_SEPARATOR .
  410. substr($dataid, 2, 2) . DIRECTORY_SEPARATOR;
  411. }
  412. /**
  413. * Convert paste id to discussion storage path.
  414. *
  415. * eg. input 'e3570978f9e4aa90' --> output 'data/e3/57/e3570978f9e4aa90.discussion/'
  416. *
  417. * @access private
  418. * @param string $dataid
  419. * @return string
  420. */
  421. private function _dataid2discussionpath($dataid)
  422. {
  423. return $this->_dataid2path($dataid) . $dataid .
  424. '.discussion' . DIRECTORY_SEPARATOR;
  425. }
  426. /**
  427. * store the data
  428. *
  429. * @access public
  430. * @param string $filename
  431. * @param array $data
  432. * @return bool
  433. */
  434. private function _store($filename, array $data)
  435. {
  436. try {
  437. return $this->_storeString(
  438. $filename,
  439. self::PROTECTION_LINE . PHP_EOL . Json::encode($data)
  440. );
  441. } catch (JsonException $e) {
  442. error_log('Error while trying to store data to the filesystem at path "' . $filename . '": ' . $e->getMessage());
  443. return false;
  444. }
  445. }
  446. /**
  447. * store a string
  448. *
  449. * @access public
  450. * @param string $filename
  451. * @param string $data
  452. * @return bool
  453. */
  454. private function _storeString($filename, $data)
  455. {
  456. // Create storage directory if it does not exist.
  457. if (!is_dir($this->_path)) {
  458. if (!@mkdir($this->_path, 0700)) {
  459. return false;
  460. }
  461. }
  462. $file = $this->_path . DIRECTORY_SEPARATOR . '.htaccess';
  463. if (!is_file($file)) {
  464. $writtenBytes = 0;
  465. if ($fileCreated = @touch($file)) {
  466. $writtenBytes = @file_put_contents(
  467. $file,
  468. self::HTACCESS_LINE . PHP_EOL,
  469. LOCK_EX
  470. );
  471. }
  472. if (
  473. $fileCreated === false ||
  474. $writtenBytes === false ||
  475. $writtenBytes < strlen(self::HTACCESS_LINE . PHP_EOL)
  476. ) {
  477. return false;
  478. }
  479. }
  480. $fileCreated = true;
  481. $writtenBytes = 0;
  482. if (!is_file($filename)) {
  483. $fileCreated = @touch($filename);
  484. }
  485. if ($fileCreated) {
  486. $writtenBytes = @file_put_contents($filename, $data, LOCK_EX);
  487. }
  488. if ($fileCreated === false || $writtenBytes === false || $writtenBytes < strlen($data)) {
  489. return false;
  490. }
  491. chmod($filename, 0640); // protect file from access by other users on the host
  492. return true;
  493. }
  494. /**
  495. * rename a file, prepending the protection line at the beginning
  496. *
  497. * @access public
  498. * @param string $srcFile
  499. * @param string $destFile
  500. * @return void
  501. */
  502. private function _prependRename($srcFile, $destFile)
  503. {
  504. // don't overwrite already converted file
  505. if (!is_readable($destFile)) {
  506. $handle = fopen($srcFile, 'r', false, stream_context_create());
  507. file_put_contents($destFile, self::PROTECTION_LINE . PHP_EOL);
  508. file_put_contents($destFile, $handle, FILE_APPEND);
  509. fclose($handle);
  510. }
  511. if (!unlink($srcFile)) {
  512. error_log('Error deleting converted document: ' . $srcFile);
  513. }
  514. }
  515. }