Filesystem.php 17 KB

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