Filesystem.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. <?php
  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. * @version 1.4.0
  11. */
  12. namespace PrivateBin\Data;
  13. use Exception;
  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. * first line in paste or comment files, to protect their contents from browsing exposed data directories
  24. *
  25. * @const string
  26. */
  27. const PROTECTION_LINE = '<?php http_response_code(403); /*';
  28. /**
  29. * line in generated .htaccess files, to protect exposed directories from being browsable on apache web servers
  30. *
  31. * @const string
  32. */
  33. const HTACCESS_LINE = 'Require all denied';
  34. /**
  35. * path in which to persist something
  36. *
  37. * @access private
  38. * @static
  39. * @var string
  40. */
  41. private static $_path = 'data';
  42. /**
  43. * get instance of singleton
  44. *
  45. * @access public
  46. * @static
  47. * @param array $options
  48. * @return Filesystem
  49. */
  50. public static function getInstance(array $options)
  51. {
  52. // if needed initialize the singleton
  53. if (!(self::$_instance instanceof self)) {
  54. self::$_instance = new self;
  55. }
  56. // if given update the data directory
  57. if (
  58. is_array($options) &&
  59. array_key_exists('dir', $options)
  60. ) {
  61. self::$_path = $options['dir'];
  62. }
  63. return self::$_instance;
  64. }
  65. /**
  66. * Create a paste.
  67. *
  68. * @access public
  69. * @param string $pasteid
  70. * @param array $paste
  71. * @return bool
  72. */
  73. public function create($pasteid, array $paste)
  74. {
  75. $storagedir = self::_dataid2path($pasteid);
  76. $file = $storagedir . $pasteid . '.php';
  77. if (is_file($file)) {
  78. return false;
  79. }
  80. if (!is_dir($storagedir)) {
  81. mkdir($storagedir, 0700, true);
  82. }
  83. return self::_store($file, $paste);
  84. }
  85. /**
  86. * Read a paste.
  87. *
  88. * @access public
  89. * @param string $pasteid
  90. * @return array|false
  91. */
  92. public function read($pasteid)
  93. {
  94. if (
  95. !$this->exists($pasteid) ||
  96. !$paste = self::_get(self::_dataid2path($pasteid) . $pasteid . '.php')
  97. ) {
  98. return false;
  99. }
  100. return self::upgradePreV1Format($paste);
  101. }
  102. /**
  103. * Delete a paste and its discussion.
  104. *
  105. * @access public
  106. * @param string $pasteid
  107. */
  108. public function delete($pasteid)
  109. {
  110. $pastedir = self::_dataid2path($pasteid);
  111. if (is_dir($pastedir)) {
  112. // Delete the paste itself.
  113. if (is_file($pastedir . $pasteid . '.php')) {
  114. unlink($pastedir . $pasteid . '.php');
  115. }
  116. // Delete discussion if it exists.
  117. $discdir = self::_dataid2discussionpath($pasteid);
  118. if (is_dir($discdir)) {
  119. // Delete all files in discussion directory
  120. $dir = dir($discdir);
  121. while (false !== ($filename = $dir->read())) {
  122. if (is_file($discdir . $filename)) {
  123. unlink($discdir . $filename);
  124. }
  125. }
  126. $dir->close();
  127. rmdir($discdir);
  128. }
  129. }
  130. }
  131. /**
  132. * Test if a paste exists.
  133. *
  134. * @access public
  135. * @param string $pasteid
  136. * @return bool
  137. */
  138. public function exists($pasteid)
  139. {
  140. $basePath = self::_dataid2path($pasteid) . $pasteid;
  141. $pastePath = $basePath . '.php';
  142. // convert to PHP protected files if needed
  143. if (is_readable($basePath)) {
  144. self::_prependRename($basePath, $pastePath);
  145. // convert comments, too
  146. $discdir = self::_dataid2discussionpath($pasteid);
  147. if (is_dir($discdir)) {
  148. $dir = dir($discdir);
  149. while (false !== ($filename = $dir->read())) {
  150. if (substr($filename, -4) !== '.php' && strlen($filename) >= 16) {
  151. $commentFilename = $discdir . $filename . '.php';
  152. self::_prependRename($discdir . $filename, $commentFilename);
  153. }
  154. }
  155. $dir->close();
  156. }
  157. }
  158. return is_readable($pastePath);
  159. }
  160. /**
  161. * Create a comment in a paste.
  162. *
  163. * @access public
  164. * @param string $pasteid
  165. * @param string $parentid
  166. * @param string $commentid
  167. * @param array $comment
  168. * @return bool
  169. */
  170. public function createComment($pasteid, $parentid, $commentid, array $comment)
  171. {
  172. $storagedir = self::_dataid2discussionpath($pasteid);
  173. $file = $storagedir . $pasteid . '.' . $commentid . '.' . $parentid . '.php';
  174. if (is_file($file)) {
  175. return false;
  176. }
  177. if (!is_dir($storagedir)) {
  178. mkdir($storagedir, 0700, true);
  179. }
  180. return self::_store($file, $comment);
  181. }
  182. /**
  183. * Read all comments of paste.
  184. *
  185. * @access public
  186. * @param string $pasteid
  187. * @return array
  188. */
  189. public function readComments($pasteid)
  190. {
  191. $comments = array();
  192. $discdir = self::_dataid2discussionpath($pasteid);
  193. if (is_dir($discdir)) {
  194. $dir = dir($discdir);
  195. while (false !== ($filename = $dir->read())) {
  196. // Filename is in the form pasteid.commentid.parentid.php:
  197. // - pasteid is the paste this reply belongs to.
  198. // - commentid is the comment identifier itself.
  199. // - parentid is the comment this comment replies to (It can be pasteid)
  200. if (is_file($discdir . $filename)) {
  201. $comment = self::_get($discdir . $filename);
  202. $items = explode('.', $filename);
  203. // Add some meta information not contained in file.
  204. $comment['id'] = $items[1];
  205. $comment['parentid'] = $items[2];
  206. // Store in array
  207. $key = $this->getOpenSlot($comments, (int) $comment['meta']['created']);
  208. $comments[$key] = $comment;
  209. }
  210. }
  211. $dir->close();
  212. // Sort comments by date, oldest first.
  213. ksort($comments);
  214. }
  215. return $comments;
  216. }
  217. /**
  218. * Test if a comment exists.
  219. *
  220. * @access public
  221. * @param string $pasteid
  222. * @param string $parentid
  223. * @param string $commentid
  224. * @return bool
  225. */
  226. public function existsComment($pasteid, $parentid, $commentid)
  227. {
  228. return is_file(
  229. self::_dataid2discussionpath($pasteid) .
  230. $pasteid . '.' . $commentid . '.' . $parentid . '.php'
  231. );
  232. }
  233. /**
  234. * Save a value.
  235. *
  236. * @access public
  237. * @param string $value
  238. * @param string $namespace
  239. * @param string $key
  240. * @return bool
  241. */
  242. public function setValue($value, $namespace, $key = '')
  243. {
  244. switch ($namespace) {
  245. case 'purge_limiter':
  246. return self::_storeString(
  247. self::$_path . DIRECTORY_SEPARATOR . 'purge_limiter.php',
  248. '<?php' . PHP_EOL . '$GLOBALS[\'purge_limiter\'] = ' . $value . ';'
  249. );
  250. case 'salt':
  251. return self::_storeString(
  252. self::$_path . DIRECTORY_SEPARATOR . 'salt.php',
  253. '<?php # |' . $value . '|'
  254. );
  255. case 'traffic_limiter':
  256. self::$_last_cache[$key] = $value;
  257. return self::_storeString(
  258. self::$_path . DIRECTORY_SEPARATOR . 'traffic_limiter.php',
  259. '<?php' . PHP_EOL . '$GLOBALS[\'traffic_limiter\'] = ' . var_export(self::$_last_cache, true) . ';'
  260. );
  261. }
  262. return false;
  263. }
  264. /**
  265. * Load a value.
  266. *
  267. * @access public
  268. * @param string $namespace
  269. * @param string $key
  270. * @return string
  271. */
  272. public function getValue($namespace, $key = '')
  273. {
  274. switch ($namespace) {
  275. case 'purge_limiter':
  276. $file = self::$_path . DIRECTORY_SEPARATOR . 'purge_limiter.php';
  277. if (is_readable($file)) {
  278. require $file;
  279. return $GLOBALS['purge_limiter'];
  280. }
  281. break;
  282. case 'salt':
  283. $file = self::$_path . DIRECTORY_SEPARATOR . 'salt.php';
  284. if (is_readable($file)) {
  285. $items = explode('|', file_get_contents($file));
  286. if (is_array($items) && count($items) == 3) {
  287. return $items[1];
  288. }
  289. }
  290. break;
  291. case 'traffic_limiter':
  292. $file = self::$_path . DIRECTORY_SEPARATOR . 'traffic_limiter.php';
  293. if (is_readable($file)) {
  294. require $file;
  295. self::$_last_cache = $GLOBALS['traffic_limiter'];
  296. if (array_key_exists($key, self::$_last_cache)) {
  297. return self::$_last_cache[$key];
  298. }
  299. }
  300. break;
  301. }
  302. return '';
  303. }
  304. /**
  305. * get the data
  306. *
  307. * @access public
  308. * @static
  309. * @param string $filename
  310. * @return array|false $data
  311. */
  312. private static function _get($filename)
  313. {
  314. return Json::decode(
  315. substr(
  316. file_get_contents($filename),
  317. strlen(self::PROTECTION_LINE . PHP_EOL)
  318. )
  319. );
  320. }
  321. /**
  322. * Returns up to batch size number of paste ids that have expired
  323. *
  324. * @access private
  325. * @param int $batchsize
  326. * @return array
  327. */
  328. protected function _getExpiredPastes($batchsize)
  329. {
  330. $pastes = array();
  331. $firstLevel = array_filter(
  332. scandir(self::$_path),
  333. 'self::_isFirstLevelDir'
  334. );
  335. if (count($firstLevel) > 0) {
  336. // try at most 10 times the $batchsize pastes before giving up
  337. for ($i = 0, $max = $batchsize * 10; $i < $max; ++$i) {
  338. $firstKey = array_rand($firstLevel);
  339. $secondLevel = array_filter(
  340. scandir(self::$_path . DIRECTORY_SEPARATOR . $firstLevel[$firstKey]),
  341. 'self::_isSecondLevelDir'
  342. );
  343. // skip this folder in the next checks if it is empty
  344. if (count($secondLevel) == 0) {
  345. unset($firstLevel[$firstKey]);
  346. continue;
  347. }
  348. $secondKey = array_rand($secondLevel);
  349. $path = self::$_path . DIRECTORY_SEPARATOR .
  350. $firstLevel[$firstKey] . DIRECTORY_SEPARATOR .
  351. $secondLevel[$secondKey];
  352. if (!is_dir($path)) {
  353. continue;
  354. }
  355. $thirdLevel = array_filter(
  356. array_map(
  357. function ($filename) {
  358. return strlen($filename) >= 20 ?
  359. substr($filename, 0, -4) :
  360. $filename;
  361. },
  362. scandir($path)
  363. ),
  364. 'PrivateBin\\Model\\Paste::isValidId'
  365. );
  366. if (count($thirdLevel) == 0) {
  367. continue;
  368. }
  369. $thirdKey = array_rand($thirdLevel);
  370. $pasteid = $thirdLevel[$thirdKey];
  371. if (in_array($pasteid, $pastes)) {
  372. continue;
  373. }
  374. if ($this->exists($pasteid)) {
  375. $data = $this->read($pasteid);
  376. if (
  377. array_key_exists('expire_date', $data['meta']) &&
  378. $data['meta']['expire_date'] < time()
  379. ) {
  380. $pastes[] = $pasteid;
  381. if (count($pastes) >= $batchsize) {
  382. break;
  383. }
  384. }
  385. }
  386. }
  387. }
  388. return $pastes;
  389. }
  390. /**
  391. * Convert paste id to storage path.
  392. *
  393. * The idea is to creates subdirectories in order to limit the number of files per directory.
  394. * (A high number of files in a single directory can slow things down.)
  395. * eg. "f468483c313401e8" will be stored in "data/f4/68/f468483c313401e8"
  396. * High-trafic websites may want to deepen the directory structure (like Squid does).
  397. *
  398. * eg. input 'e3570978f9e4aa90' --> output 'data/e3/57/'
  399. *
  400. * @access private
  401. * @static
  402. * @param string $dataid
  403. * @return string
  404. */
  405. private static function _dataid2path($dataid)
  406. {
  407. return self::$_path . DIRECTORY_SEPARATOR .
  408. substr($dataid, 0, 2) . DIRECTORY_SEPARATOR .
  409. substr($dataid, 2, 2) . DIRECTORY_SEPARATOR;
  410. }
  411. /**
  412. * Convert paste id to discussion storage path.
  413. *
  414. * eg. input 'e3570978f9e4aa90' --> output 'data/e3/57/e3570978f9e4aa90.discussion/'
  415. *
  416. * @access private
  417. * @static
  418. * @param string $dataid
  419. * @return string
  420. */
  421. private static function _dataid2discussionpath($dataid)
  422. {
  423. return self::_dataid2path($dataid) . $dataid .
  424. '.discussion' . DIRECTORY_SEPARATOR;
  425. }
  426. /**
  427. * Check that the given element is a valid first level directory.
  428. *
  429. * @access private
  430. * @static
  431. * @param string $element
  432. * @return bool
  433. */
  434. private static function _isFirstLevelDir($element)
  435. {
  436. return self::_isSecondLevelDir($element) &&
  437. is_dir(self::$_path . DIRECTORY_SEPARATOR . $element);
  438. }
  439. /**
  440. * Check that the given element is a valid second level directory.
  441. *
  442. * @access private
  443. * @static
  444. * @param string $element
  445. * @return bool
  446. */
  447. private static function _isSecondLevelDir($element)
  448. {
  449. return (bool) preg_match('/^[a-f0-9]{2}$/', $element);
  450. }
  451. /**
  452. * store the data
  453. *
  454. * @access public
  455. * @static
  456. * @param string $filename
  457. * @param array $data
  458. * @return bool
  459. */
  460. private static function _store($filename, array $data)
  461. {
  462. try {
  463. return self::_storeString(
  464. $filename,
  465. self::PROTECTION_LINE . PHP_EOL . Json::encode($data)
  466. );
  467. } catch (Exception $e) {
  468. return false;
  469. }
  470. }
  471. /**
  472. * store a string
  473. *
  474. * @access public
  475. * @static
  476. * @param string $filename
  477. * @param string $data
  478. * @return bool
  479. */
  480. private static function _storeString($filename, $data)
  481. {
  482. // Create storage directory if it does not exist.
  483. if (!is_dir(self::$_path)) {
  484. if (!@mkdir(self::$_path, 0700)) {
  485. return false;
  486. }
  487. }
  488. $file = self::$_path . DIRECTORY_SEPARATOR . '.htaccess';
  489. if (!is_file($file)) {
  490. $writtenBytes = 0;
  491. if ($fileCreated = @touch($file)) {
  492. $writtenBytes = @file_put_contents(
  493. $file,
  494. self::HTACCESS_LINE . PHP_EOL,
  495. LOCK_EX
  496. );
  497. }
  498. if (
  499. $fileCreated === false ||
  500. $writtenBytes === false ||
  501. $writtenBytes < strlen(self::HTACCESS_LINE . PHP_EOL)
  502. ) {
  503. return false;
  504. }
  505. }
  506. $fileCreated = true;
  507. $writtenBytes = 0;
  508. if (!is_file($filename)) {
  509. $fileCreated = @touch($filename);
  510. }
  511. if ($fileCreated) {
  512. $writtenBytes = @file_put_contents($filename, $data, LOCK_EX);
  513. }
  514. if ($fileCreated === false || $writtenBytes === false || $writtenBytes < strlen($data)) {
  515. return false;
  516. }
  517. @chmod($filename, 0640); // protect file from access by other users on the host
  518. return true;
  519. }
  520. /**
  521. * rename a file, prepending the protection line at the beginning
  522. *
  523. * @access public
  524. * @static
  525. * @param string $srcFile
  526. * @param string $destFile
  527. * @return void
  528. */
  529. private static function _prependRename($srcFile, $destFile)
  530. {
  531. // don't overwrite already converted file
  532. if (!is_readable($destFile)) {
  533. $handle = fopen($srcFile, 'r', false, stream_context_create());
  534. file_put_contents($destFile, self::PROTECTION_LINE . PHP_EOL);
  535. file_put_contents($destFile, $handle, FILE_APPEND);
  536. fclose($handle);
  537. }
  538. unlink($srcFile);
  539. }
  540. }