Filesystem.php 16 KB

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