Filesystem.php 16 KB

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