Filesystem.php 17 KB

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