Filesystem.php 16 KB

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