Filesystem.php 17 KB

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