1
0

Filesystem.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  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 (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 (
  99. !$this->exists($pasteid) ||
  100. !$paste = $this->_get($this->_dataid2path($pasteid) . $pasteid . '.php')
  101. ) {
  102. return false;
  103. }
  104. return $paste;
  105. }
  106. /**
  107. * Delete a paste and its discussion.
  108. *
  109. * @access public
  110. * @param string $pasteid
  111. */
  112. public function delete($pasteid)
  113. {
  114. $pastedir = $this->_dataid2path($pasteid);
  115. if (is_dir($pastedir)) {
  116. // Delete the paste itself.
  117. if (is_file($pastedir . $pasteid . '.php')) {
  118. unlink($pastedir . $pasteid . '.php');
  119. }
  120. // Delete discussion if it exists.
  121. $discdir = $this->_dataid2discussionpath($pasteid);
  122. if (is_dir($discdir)) {
  123. // Delete all files in discussion directory
  124. $dir = dir($discdir);
  125. while (false !== ($filename = $dir->read())) {
  126. if (is_file($discdir . $filename)) {
  127. unlink($discdir . $filename);
  128. }
  129. }
  130. $dir->close();
  131. rmdir($discdir);
  132. }
  133. }
  134. }
  135. /**
  136. * Test if a paste exists.
  137. *
  138. * @access public
  139. * @param string $pasteid
  140. * @return bool
  141. */
  142. public function exists($pasteid)
  143. {
  144. $basePath = $this->_dataid2path($pasteid) . $pasteid;
  145. $pastePath = $basePath . '.php';
  146. // convert to PHP protected files if needed
  147. if (is_readable($basePath)) {
  148. $this->_prependRename($basePath, $pastePath);
  149. // convert comments, too
  150. $discdir = $this->_dataid2discussionpath($pasteid);
  151. if (is_dir($discdir)) {
  152. $dir = dir($discdir);
  153. while (false !== ($filename = $dir->read())) {
  154. if (substr($filename, -4) !== '.php' && strlen($filename) >= 16) {
  155. $commentFilename = $discdir . $filename . '.php';
  156. $this->_prependRename($discdir . $filename, $commentFilename);
  157. }
  158. }
  159. $dir->close();
  160. }
  161. }
  162. return is_readable($pastePath);
  163. }
  164. /**
  165. * Create a comment in a paste.
  166. *
  167. * @access public
  168. * @param string $pasteid
  169. * @param string $parentid
  170. * @param string $commentid
  171. * @param array $comment
  172. * @return bool
  173. */
  174. public function createComment($pasteid, $parentid, $commentid, array &$comment)
  175. {
  176. $storagedir = $this->_dataid2discussionpath($pasteid);
  177. $file = $storagedir . $pasteid . '.' . $commentid . '.' . $parentid . '.php';
  178. if (is_file($file)) {
  179. return false;
  180. }
  181. if (!is_dir($storagedir)) {
  182. mkdir($storagedir, 0700, true);
  183. }
  184. return $this->_store($file, $comment);
  185. }
  186. /**
  187. * Read all comments of paste.
  188. *
  189. * @access public
  190. * @param string $pasteid
  191. * @return array
  192. */
  193. public function readComments($pasteid)
  194. {
  195. $comments = array();
  196. $discdir = $this->_dataid2discussionpath($pasteid);
  197. if (is_dir($discdir)) {
  198. $dir = dir($discdir);
  199. while (false !== ($filename = $dir->read())) {
  200. // Filename is in the form pasteid.commentid.parentid.php:
  201. // - pasteid is the paste this reply belongs to.
  202. // - commentid is the comment identifier itself.
  203. // - parentid is the comment this comment replies to (It can be pasteid)
  204. if (is_file($discdir . $filename)) {
  205. $comment = $this->_get($discdir . $filename);
  206. $items = explode('.', $filename);
  207. // Add some meta information not contained in file.
  208. $comment['id'] = $items[1];
  209. $comment['parentid'] = $items[2];
  210. // Store in array
  211. $key = $this->getOpenSlot(
  212. $comments,
  213. $comment['meta']['created']
  214. );
  215. $comments[$key] = $comment;
  216. }
  217. }
  218. $dir->close();
  219. // Sort comments by date, oldest first.
  220. ksort($comments);
  221. }
  222. return $comments;
  223. }
  224. /**
  225. * Test if a comment exists.
  226. *
  227. * @access public
  228. * @param string $pasteid
  229. * @param string $parentid
  230. * @param string $commentid
  231. * @return bool
  232. */
  233. public function existsComment($pasteid, $parentid, $commentid)
  234. {
  235. return is_file(
  236. $this->_dataid2discussionpath($pasteid) .
  237. $pasteid . '.' . $commentid . '.' . $parentid . '.php'
  238. );
  239. }
  240. /**
  241. * Save a value.
  242. *
  243. * @access public
  244. * @param string $value
  245. * @param string $namespace
  246. * @param string $key
  247. * @return bool
  248. */
  249. public function setValue($value, $namespace, $key = '')
  250. {
  251. switch ($namespace) {
  252. case 'purge_limiter':
  253. if (function_exists('opcache_invalidate')) {
  254. opcache_invalidate($this->_path . DIRECTORY_SEPARATOR . 'purge_limiter.php');
  255. }
  256. return $this->_storeString(
  257. $this->_path . DIRECTORY_SEPARATOR . 'purge_limiter.php',
  258. '<?php' . PHP_EOL . '$GLOBALS[\'purge_limiter\'] = ' . var_export($value, true) . ';'
  259. );
  260. case 'salt':
  261. return $this->_storeString(
  262. $this->_path . DIRECTORY_SEPARATOR . 'salt.php',
  263. '<?php # |' . $value . '|'
  264. );
  265. case 'traffic_limiter':
  266. $this->_last_cache[$key] = $value;
  267. if (function_exists('opcache_invalidate')) {
  268. opcache_invalidate($this->_path . DIRECTORY_SEPARATOR . 'traffic_limiter.php');
  269. }
  270. return $this->_storeString(
  271. $this->_path . DIRECTORY_SEPARATOR . 'traffic_limiter.php',
  272. '<?php' . PHP_EOL . '$GLOBALS[\'traffic_limiter\'] = ' . var_export($this->_last_cache, true) . ';'
  273. );
  274. }
  275. return false;
  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. return Json::decode($data);
  335. }
  336. /**
  337. * Returns up to batch size number of paste ids that have expired
  338. *
  339. * @access private
  340. * @param int $batchsize
  341. * @return array
  342. */
  343. protected function _getExpiredPastes($batchsize)
  344. {
  345. $pastes = array();
  346. $count = 0;
  347. $opened = 0;
  348. $limit = $batchsize * 10; // try at most 10 times $batchsize pastes before giving up
  349. $time = time();
  350. $files = $this->getAllPastes();
  351. shuffle($files);
  352. foreach ($files as $pasteid) {
  353. if ($this->exists($pasteid)) {
  354. $data = $this->read($pasteid);
  355. if (
  356. array_key_exists('expire_date', $data['meta']) &&
  357. $data['meta']['expire_date'] < $time
  358. ) {
  359. $pastes[] = $pasteid;
  360. if (++$count >= $batchsize) {
  361. break;
  362. }
  363. }
  364. if (++$opened >= $limit) {
  365. break;
  366. }
  367. }
  368. }
  369. return $pastes;
  370. }
  371. /**
  372. * @inheritDoc
  373. */
  374. public function getAllPastes()
  375. {
  376. $pastes = array();
  377. foreach (new GlobIterator($this->_path . self::PASTE_FILE_PATTERN) as $file) {
  378. if ($file->isFile()) {
  379. $pastes[] = $file->getBasename('.php');
  380. }
  381. }
  382. return $pastes;
  383. }
  384. /**
  385. * Convert paste id to storage path.
  386. *
  387. * The idea is to creates subdirectories in order to limit the number of files per directory.
  388. * (A high number of files in a single directory can slow things down.)
  389. * eg. "f468483c313401e8" will be stored in "data/f4/68/f468483c313401e8"
  390. * High-trafic websites may want to deepen the directory structure (like Squid does).
  391. *
  392. * eg. input 'e3570978f9e4aa90' --> output 'data/e3/57/'
  393. *
  394. * @access private
  395. * @param string $dataid
  396. * @return string
  397. */
  398. private function _dataid2path($dataid)
  399. {
  400. return $this->_path . DIRECTORY_SEPARATOR .
  401. substr($dataid, 0, 2) . DIRECTORY_SEPARATOR .
  402. substr($dataid, 2, 2) . DIRECTORY_SEPARATOR;
  403. }
  404. /**
  405. * Convert paste id to discussion storage path.
  406. *
  407. * eg. input 'e3570978f9e4aa90' --> output 'data/e3/57/e3570978f9e4aa90.discussion/'
  408. *
  409. * @access private
  410. * @param string $dataid
  411. * @return string
  412. */
  413. private function _dataid2discussionpath($dataid)
  414. {
  415. return $this->_dataid2path($dataid) . $dataid .
  416. '.discussion' . DIRECTORY_SEPARATOR;
  417. }
  418. /**
  419. * store the data
  420. *
  421. * @access public
  422. * @param string $filename
  423. * @param array $data
  424. * @return bool
  425. */
  426. private function _store($filename, array $data)
  427. {
  428. try {
  429. return $this->_storeString(
  430. $filename,
  431. self::PROTECTION_LINE . PHP_EOL . Json::encode($data)
  432. );
  433. } catch (Exception $e) {
  434. error_log('Error while trying to store data to the filesystem at path "' . $filename . '": ' . $e->getMessage());
  435. return false;
  436. }
  437. }
  438. /**
  439. * store a string
  440. *
  441. * @access public
  442. * @param string $filename
  443. * @param string $data
  444. * @return bool
  445. */
  446. private function _storeString($filename, $data)
  447. {
  448. // Create storage directory if it does not exist.
  449. if (!is_dir($this->_path)) {
  450. if (!@mkdir($this->_path, 0700)) {
  451. return false;
  452. }
  453. }
  454. $file = $this->_path . DIRECTORY_SEPARATOR . '.htaccess';
  455. if (!is_file($file)) {
  456. $writtenBytes = 0;
  457. if ($fileCreated = @touch($file)) {
  458. $writtenBytes = @file_put_contents(
  459. $file,
  460. self::HTACCESS_LINE . PHP_EOL,
  461. LOCK_EX
  462. );
  463. }
  464. if (
  465. $fileCreated === false ||
  466. $writtenBytes === false ||
  467. $writtenBytes < strlen(self::HTACCESS_LINE . PHP_EOL)
  468. ) {
  469. return false;
  470. }
  471. }
  472. $fileCreated = true;
  473. $writtenBytes = 0;
  474. if (!is_file($filename)) {
  475. $fileCreated = @touch($filename);
  476. }
  477. if ($fileCreated) {
  478. $writtenBytes = @file_put_contents($filename, $data, LOCK_EX);
  479. }
  480. if ($fileCreated === false || $writtenBytes === false || $writtenBytes < strlen($data)) {
  481. return false;
  482. }
  483. chmod($filename, 0640); // protect file from access by other users on the host
  484. return true;
  485. }
  486. /**
  487. * rename a file, prepending the protection line at the beginning
  488. *
  489. * @access public
  490. * @param string $srcFile
  491. * @param string $destFile
  492. * @return void
  493. */
  494. private function _prependRename($srcFile, $destFile)
  495. {
  496. // don't overwrite already converted file
  497. if (!is_readable($destFile)) {
  498. $handle = fopen($srcFile, 'r', false, stream_context_create());
  499. file_put_contents($destFile, self::PROTECTION_LINE . PHP_EOL);
  500. file_put_contents($destFile, $handle, FILE_APPEND);
  501. fclose($handle);
  502. }
  503. unlink($srcFile);
  504. }
  505. }