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 Exception;
  13. use GlobIterator;
  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 (
  66. is_array($options) &&
  67. array_key_exists('dir', $options)
  68. ) {
  69. $this->_path = $options['dir'];
  70. }
  71. }
  72. /**
  73. * Create a paste.
  74. *
  75. * @access public
  76. * @param string $pasteid
  77. * @param array $paste
  78. * @return bool
  79. */
  80. public function create($pasteid, array &$paste)
  81. {
  82. $storagedir = $this->_dataid2path($pasteid);
  83. $file = $storagedir . $pasteid . '.php';
  84. if (is_file($file)) {
  85. return false;
  86. }
  87. if (!is_dir($storagedir)) {
  88. mkdir($storagedir, 0700, true);
  89. }
  90. return $this->_store($file, $paste);
  91. }
  92. /**
  93. * Read a paste.
  94. *
  95. * @access public
  96. * @param string $pasteid
  97. * @return array|false
  98. */
  99. public function read($pasteid)
  100. {
  101. if (
  102. !$this->exists($pasteid) ||
  103. !$paste = $this->_get($this->_dataid2path($pasteid) . $pasteid . '.php')
  104. ) {
  105. return false;
  106. }
  107. return self::upgradePreV1Format($paste);
  108. }
  109. /**
  110. * Delete a paste and its discussion.
  111. *
  112. * @access public
  113. * @param string $pasteid
  114. */
  115. public function delete($pasteid)
  116. {
  117. $pastedir = $this->_dataid2path($pasteid);
  118. if (is_dir($pastedir)) {
  119. // Delete the paste itself.
  120. if (is_file($pastedir . $pasteid . '.php')) {
  121. unlink($pastedir . $pasteid . '.php');
  122. }
  123. // Delete discussion if it exists.
  124. $discdir = $this->_dataid2discussionpath($pasteid);
  125. if (is_dir($discdir)) {
  126. // Delete all files in discussion directory
  127. $dir = dir($discdir);
  128. while (false !== ($filename = $dir->read())) {
  129. if (is_file($discdir . $filename)) {
  130. unlink($discdir . $filename);
  131. }
  132. }
  133. $dir->close();
  134. rmdir($discdir);
  135. }
  136. }
  137. }
  138. /**
  139. * Test if a paste exists.
  140. *
  141. * @access public
  142. * @param string $pasteid
  143. * @return bool
  144. */
  145. public function exists($pasteid)
  146. {
  147. $basePath = $this->_dataid2path($pasteid) . $pasteid;
  148. $pastePath = $basePath . '.php';
  149. // convert to PHP protected files if needed
  150. if (is_readable($basePath)) {
  151. $this->_prependRename($basePath, $pastePath);
  152. // convert comments, too
  153. $discdir = $this->_dataid2discussionpath($pasteid);
  154. if (is_dir($discdir)) {
  155. $dir = dir($discdir);
  156. while (false !== ($filename = $dir->read())) {
  157. if (substr($filename, -4) !== '.php' && strlen($filename) >= 16) {
  158. $commentFilename = $discdir . $filename . '.php';
  159. $this->_prependRename($discdir . $filename, $commentFilename);
  160. }
  161. }
  162. $dir->close();
  163. }
  164. }
  165. return is_readable($pastePath);
  166. }
  167. /**
  168. * Create a comment in a paste.
  169. *
  170. * @access public
  171. * @param string $pasteid
  172. * @param string $parentid
  173. * @param string $commentid
  174. * @param array $comment
  175. * @return bool
  176. */
  177. public function createComment($pasteid, $parentid, $commentid, array &$comment)
  178. {
  179. $storagedir = $this->_dataid2discussionpath($pasteid);
  180. $file = $storagedir . $pasteid . '.' . $commentid . '.' . $parentid . '.php';
  181. if (is_file($file)) {
  182. return false;
  183. }
  184. if (!is_dir($storagedir)) {
  185. mkdir($storagedir, 0700, true);
  186. }
  187. return $this->_store($file, $comment);
  188. }
  189. /**
  190. * Read all comments of paste.
  191. *
  192. * @access public
  193. * @param string $pasteid
  194. * @return array
  195. */
  196. public function readComments($pasteid)
  197. {
  198. $comments = array();
  199. $discdir = $this->_dataid2discussionpath($pasteid);
  200. if (is_dir($discdir)) {
  201. $dir = dir($discdir);
  202. while (false !== ($filename = $dir->read())) {
  203. // Filename is in the form pasteid.commentid.parentid.php:
  204. // - pasteid is the paste this reply belongs to.
  205. // - commentid is the comment identifier itself.
  206. // - parentid is the comment this comment replies to (It can be pasteid)
  207. if (is_file($discdir . $filename)) {
  208. $comment = $this->_get($discdir . $filename);
  209. $items = explode('.', $filename);
  210. // Add some meta information not contained in file.
  211. $comment['id'] = $items[1];
  212. $comment['parentid'] = $items[2];
  213. // Store in array
  214. $key = $this->getOpenSlot(
  215. $comments,
  216. (int) array_key_exists('created', $comment['meta']) ?
  217. $comment['meta']['created'] : // v2 comments
  218. $comment['meta']['postdate'] // v1 comments
  219. );
  220. $comments[$key] = $comment;
  221. }
  222. }
  223. $dir->close();
  224. // Sort comments by date, oldest first.
  225. ksort($comments);
  226. }
  227. return $comments;
  228. }
  229. /**
  230. * Test if a comment exists.
  231. *
  232. * @access public
  233. * @param string $pasteid
  234. * @param string $parentid
  235. * @param string $commentid
  236. * @return bool
  237. */
  238. public function existsComment($pasteid, $parentid, $commentid)
  239. {
  240. return is_file(
  241. $this->_dataid2discussionpath($pasteid) .
  242. $pasteid . '.' . $commentid . '.' . $parentid . '.php'
  243. );
  244. }
  245. /**
  246. * Save a value.
  247. *
  248. * @access public
  249. * @param string $value
  250. * @param string $namespace
  251. * @param string $key
  252. * @return bool
  253. */
  254. public function setValue($value, $namespace, $key = '')
  255. {
  256. switch ($namespace) {
  257. case 'purge_limiter':
  258. if (function_exists('opcache_invalidate')) {
  259. opcache_invalidate($this->_path . DIRECTORY_SEPARATOR . 'purge_limiter.php');
  260. }
  261. return $this->_storeString(
  262. $this->_path . DIRECTORY_SEPARATOR . 'purge_limiter.php',
  263. '<?php' . PHP_EOL . '$GLOBALS[\'purge_limiter\'] = ' . var_export($value, true) . ';'
  264. );
  265. case 'salt':
  266. return $this->_storeString(
  267. $this->_path . DIRECTORY_SEPARATOR . 'salt.php',
  268. '<?php # |' . $value . '|'
  269. );
  270. case 'traffic_limiter':
  271. $this->_last_cache[$key] = $value;
  272. if (function_exists('opcache_invalidate')) {
  273. opcache_invalidate($this->_path . DIRECTORY_SEPARATOR . 'traffic_limiter.php');
  274. }
  275. return $this->_storeString(
  276. $this->_path . DIRECTORY_SEPARATOR . 'traffic_limiter.php',
  277. '<?php' . PHP_EOL . '$GLOBALS[\'traffic_limiter\'] = ' . var_export($this->_last_cache, true) . ';'
  278. );
  279. }
  280. return false;
  281. }
  282. /**
  283. * Load a value.
  284. *
  285. * @access public
  286. * @param string $namespace
  287. * @param string $key
  288. * @return string
  289. */
  290. public function getValue($namespace, $key = '')
  291. {
  292. switch ($namespace) {
  293. case 'purge_limiter':
  294. $file = $this->_path . DIRECTORY_SEPARATOR . 'purge_limiter.php';
  295. if (is_readable($file)) {
  296. require $file;
  297. if (array_key_exists('purge_limiter', $GLOBALS)) {
  298. return $GLOBALS['purge_limiter'];
  299. }
  300. }
  301. break;
  302. case 'salt':
  303. $file = $this->_path . DIRECTORY_SEPARATOR . 'salt.php';
  304. if (is_readable($file)) {
  305. $items = explode('|', file_get_contents($file));
  306. if (is_array($items) && count($items) == 3) {
  307. return $items[1];
  308. }
  309. }
  310. break;
  311. case 'traffic_limiter':
  312. $file = $this->_path . DIRECTORY_SEPARATOR . 'traffic_limiter.php';
  313. if (is_readable($file)) {
  314. require $file;
  315. if (array_key_exists('traffic_limiter', $GLOBALS)) {
  316. $this->_last_cache = $GLOBALS['traffic_limiter'];
  317. if (array_key_exists($key, $this->_last_cache)) {
  318. return $this->_last_cache[$key];
  319. }
  320. }
  321. }
  322. break;
  323. }
  324. return '';
  325. }
  326. /**
  327. * get the data
  328. *
  329. * @access public
  330. * @param string $filename
  331. * @return array|false $data
  332. */
  333. private function _get($filename)
  334. {
  335. $data = substr(
  336. file_get_contents($filename),
  337. strlen(self::PROTECTION_LINE . PHP_EOL)
  338. );
  339. return Json::decode($data);
  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 = array();
  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 (
  361. array_key_exists('expire_date', $data['meta']) &&
  362. $data['meta']['expire_date'] < $time
  363. ) {
  364. $pastes[] = $pasteid;
  365. if (++$count >= $batchsize) {
  366. break;
  367. }
  368. }
  369. if (++$opened >= $limit) {
  370. break;
  371. }
  372. }
  373. }
  374. return $pastes;
  375. }
  376. /**
  377. * @inheritDoc
  378. */
  379. public function getAllPastes()
  380. {
  381. $pastes = array();
  382. foreach (new GlobIterator($this->_path . self::PASTE_FILE_PATTERN) as $file) {
  383. if ($file->isFile()) {
  384. $pastes[] = $file->getBasename('.php');
  385. }
  386. }
  387. return $pastes;
  388. }
  389. /**
  390. * Convert paste id to storage path.
  391. *
  392. * The idea is to creates subdirectories in order to limit the number of files per directory.
  393. * (A high number of files in a single directory can slow things down.)
  394. * eg. "f468483c313401e8" will be stored in "data/f4/68/f468483c313401e8"
  395. * High-trafic websites may want to deepen the directory structure (like Squid does).
  396. *
  397. * eg. input 'e3570978f9e4aa90' --> output 'data/e3/57/'
  398. *
  399. * @access private
  400. * @param string $dataid
  401. * @return string
  402. */
  403. private function _dataid2path($dataid)
  404. {
  405. return $this->_path . DIRECTORY_SEPARATOR .
  406. substr($dataid, 0, 2) . DIRECTORY_SEPARATOR .
  407. substr($dataid, 2, 2) . DIRECTORY_SEPARATOR;
  408. }
  409. /**
  410. * Convert paste id to discussion storage path.
  411. *
  412. * eg. input 'e3570978f9e4aa90' --> output 'data/e3/57/e3570978f9e4aa90.discussion/'
  413. *
  414. * @access private
  415. * @param string $dataid
  416. * @return string
  417. */
  418. private function _dataid2discussionpath($dataid)
  419. {
  420. return $this->_dataid2path($dataid) . $dataid .
  421. '.discussion' . DIRECTORY_SEPARATOR;
  422. }
  423. /**
  424. * store the data
  425. *
  426. * @access public
  427. * @param string $filename
  428. * @param array $data
  429. * @return bool
  430. */
  431. private function _store($filename, array $data)
  432. {
  433. try {
  434. return $this->_storeString(
  435. $filename,
  436. self::PROTECTION_LINE . PHP_EOL . Json::encode($data)
  437. );
  438. } catch (Exception $e) {
  439. return false;
  440. }
  441. }
  442. /**
  443. * store a string
  444. *
  445. * @access public
  446. * @param string $filename
  447. * @param string $data
  448. * @return bool
  449. */
  450. private function _storeString($filename, $data)
  451. {
  452. // Create storage directory if it does not exist.
  453. if (!is_dir($this->_path)) {
  454. if (!@mkdir($this->_path, 0700)) {
  455. return false;
  456. }
  457. }
  458. $file = $this->_path . DIRECTORY_SEPARATOR . '.htaccess';
  459. if (!is_file($file)) {
  460. $writtenBytes = 0;
  461. if ($fileCreated = @touch($file)) {
  462. $writtenBytes = @file_put_contents(
  463. $file,
  464. self::HTACCESS_LINE . PHP_EOL,
  465. LOCK_EX
  466. );
  467. }
  468. if (
  469. $fileCreated === false ||
  470. $writtenBytes === false ||
  471. $writtenBytes < strlen(self::HTACCESS_LINE . PHP_EOL)
  472. ) {
  473. return false;
  474. }
  475. }
  476. $fileCreated = true;
  477. $writtenBytes = 0;
  478. if (!is_file($filename)) {
  479. $fileCreated = @touch($filename);
  480. }
  481. if ($fileCreated) {
  482. $writtenBytes = @file_put_contents($filename, $data, LOCK_EX);
  483. }
  484. if ($fileCreated === false || $writtenBytes === false || $writtenBytes < strlen($data)) {
  485. return false;
  486. }
  487. @chmod($filename, 0640); // protect file from access by other users on the host
  488. return true;
  489. }
  490. /**
  491. * rename a file, prepending the protection line at the beginning
  492. *
  493. * @access public
  494. * @param string $srcFile
  495. * @param string $destFile
  496. * @return void
  497. */
  498. private function _prependRename($srcFile, $destFile)
  499. {
  500. // don't overwrite already converted file
  501. if (!is_readable($destFile)) {
  502. $handle = fopen($srcFile, 'r', false, stream_context_create());
  503. file_put_contents($destFile, self::PROTECTION_LINE . PHP_EOL);
  504. file_put_contents($destFile, $handle, FILE_APPEND);
  505. fclose($handle);
  506. }
  507. unlink($srcFile);
  508. }
  509. }