Filesystem.php 16 KB

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