Filesystem.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  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. case 'salt':
  272. return self::_storeString(
  273. self::$_path . DIRECTORY_SEPARATOR . 'salt.php',
  274. '<?php # |' . $value . '|'
  275. );
  276. case 'traffic_limiter':
  277. self::$_traffic_limiter_cache[$key] = $value;
  278. return self::_storeString(
  279. self::$_path . DIRECTORY_SEPARATOR . 'traffic_limiter.php',
  280. '<?php' . PHP_EOL . '$GLOBALS[\'traffic_limiter\'] = ' . var_export(self::$_traffic_limiter_cache, true) . ';'
  281. );
  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_readable($file)) {
  299. require $file;
  300. return $GLOBALS['purge_limiter'];
  301. }
  302. break;
  303. case 'salt':
  304. $file = self::$_path . DIRECTORY_SEPARATOR . 'salt.php';
  305. if (is_readable($file)) {
  306. $items = explode('|', file_get_contents($file));
  307. if (is_array($items) && count($items) == 3) {
  308. return $items[1];
  309. }
  310. }
  311. break;
  312. case 'traffic_limiter':
  313. $file = self::$_path . DIRECTORY_SEPARATOR . 'traffic_limiter.php';
  314. if (is_readable($file)) {
  315. require $file;
  316. self::$_traffic_limiter_cache = $GLOBALS['traffic_limiter'];
  317. if (array_key_exists($key, self::$_traffic_limiter_cache)) {
  318. return self::$_traffic_limiter_cache[$key];
  319. }
  320. }
  321. break;
  322. }
  323. return '';
  324. }
  325. /**
  326. * get the data
  327. *
  328. * @access public
  329. * @static
  330. * @param string $filename
  331. * @return array|false $data
  332. */
  333. private static function _get($filename)
  334. {
  335. return Json::decode(
  336. substr(
  337. file_get_contents($filename),
  338. strlen(self::PROTECTION_LINE . PHP_EOL)
  339. )
  340. );
  341. }
  342. /**
  343. * Returns up to batch size number of paste ids that have expired
  344. *
  345. * @access private
  346. * @param int $batchsize
  347. * @return array
  348. */
  349. protected function _getExpiredPastes($batchsize)
  350. {
  351. $pastes = array();
  352. $firstLevel = array_filter(
  353. scandir(self::$_path),
  354. 'self::_isFirstLevelDir'
  355. );
  356. if (count($firstLevel) > 0) {
  357. // try at most 10 times the $batchsize pastes before giving up
  358. for ($i = 0, $max = $batchsize * 10; $i < $max; ++$i) {
  359. $firstKey = array_rand($firstLevel);
  360. $secondLevel = array_filter(
  361. scandir(self::$_path . DIRECTORY_SEPARATOR . $firstLevel[$firstKey]),
  362. 'self::_isSecondLevelDir'
  363. );
  364. // skip this folder in the next checks if it is empty
  365. if (count($secondLevel) == 0) {
  366. unset($firstLevel[$firstKey]);
  367. continue;
  368. }
  369. $secondKey = array_rand($secondLevel);
  370. $path = self::$_path . DIRECTORY_SEPARATOR .
  371. $firstLevel[$firstKey] . DIRECTORY_SEPARATOR .
  372. $secondLevel[$secondKey];
  373. if (!is_dir($path)) {
  374. continue;
  375. }
  376. $thirdLevel = array_filter(
  377. array_map(
  378. function ($filename) {
  379. return strlen($filename) >= 20 ?
  380. substr($filename, 0, -4) :
  381. $filename;
  382. },
  383. scandir($path)
  384. ),
  385. 'PrivateBin\\Model\\Paste::isValidId'
  386. );
  387. if (count($thirdLevel) == 0) {
  388. continue;
  389. }
  390. $thirdKey = array_rand($thirdLevel);
  391. $pasteid = $thirdLevel[$thirdKey];
  392. if (in_array($pasteid, $pastes)) {
  393. continue;
  394. }
  395. if ($this->exists($pasteid)) {
  396. $data = $this->read($pasteid);
  397. if (
  398. array_key_exists('expire_date', $data['meta']) &&
  399. $data['meta']['expire_date'] < time()
  400. ) {
  401. $pastes[] = $pasteid;
  402. if (count($pastes) >= $batchsize) {
  403. break;
  404. }
  405. }
  406. }
  407. }
  408. }
  409. return $pastes;
  410. }
  411. /**
  412. * Convert paste id to storage path.
  413. *
  414. * The idea is to creates subdirectories in order to limit the number of files per directory.
  415. * (A high number of files in a single directory can slow things down.)
  416. * eg. "f468483c313401e8" will be stored in "data/f4/68/f468483c313401e8"
  417. * High-trafic websites may want to deepen the directory structure (like Squid does).
  418. *
  419. * eg. input 'e3570978f9e4aa90' --> output 'data/e3/57/'
  420. *
  421. * @access private
  422. * @static
  423. * @param string $dataid
  424. * @return string
  425. */
  426. private static function _dataid2path($dataid)
  427. {
  428. return self::$_path . DIRECTORY_SEPARATOR .
  429. substr($dataid, 0, 2) . DIRECTORY_SEPARATOR .
  430. substr($dataid, 2, 2) . DIRECTORY_SEPARATOR;
  431. }
  432. /**
  433. * Convert paste id to discussion storage path.
  434. *
  435. * eg. input 'e3570978f9e4aa90' --> output 'data/e3/57/e3570978f9e4aa90.discussion/'
  436. *
  437. * @access private
  438. * @static
  439. * @param string $dataid
  440. * @return string
  441. */
  442. private static function _dataid2discussionpath($dataid)
  443. {
  444. return self::_dataid2path($dataid) . $dataid .
  445. '.discussion' . DIRECTORY_SEPARATOR;
  446. }
  447. /**
  448. * Check that the given element is a valid first level directory.
  449. *
  450. * @access private
  451. * @static
  452. * @param string $element
  453. * @return bool
  454. */
  455. private static function _isFirstLevelDir($element)
  456. {
  457. return self::_isSecondLevelDir($element) &&
  458. is_dir(self::$_path . DIRECTORY_SEPARATOR . $element);
  459. }
  460. /**
  461. * Check that the given element is a valid second level directory.
  462. *
  463. * @access private
  464. * @static
  465. * @param string $element
  466. * @return bool
  467. */
  468. private static function _isSecondLevelDir($element)
  469. {
  470. return (bool) preg_match('/^[a-f0-9]{2}$/', $element);
  471. }
  472. /**
  473. * store the data
  474. *
  475. * @access public
  476. * @static
  477. * @param string $filename
  478. * @param array $data
  479. * @return bool
  480. */
  481. private static function _store($filename, array $data)
  482. {
  483. try {
  484. return self::_storeString(
  485. $filename,
  486. self::PROTECTION_LINE . PHP_EOL . Json::encode($data)
  487. );
  488. } catch (Exception $e) {
  489. return false;
  490. }
  491. }
  492. /**
  493. * store a string
  494. *
  495. * @access public
  496. * @static
  497. * @param string $filename
  498. * @param string $data
  499. * @return bool
  500. */
  501. private static function _storeString($filename, $data)
  502. {
  503. // Create storage directory if it does not exist.
  504. if (!is_dir(self::$_path)) {
  505. if (!@mkdir(self::$_path, 0700)) {
  506. return false;
  507. }
  508. }
  509. $file = self::$_path . DIRECTORY_SEPARATOR . '.htaccess';
  510. if (!is_file($file)) {
  511. $writtenBytes = 0;
  512. if ($fileCreated = @touch($file)) {
  513. $writtenBytes = @file_put_contents(
  514. $file,
  515. 'Require all denied' . PHP_EOL,
  516. LOCK_EX
  517. );
  518. }
  519. if ($fileCreated === false || $writtenBytes === false || $writtenBytes < 19) {
  520. return false;
  521. }
  522. }
  523. $fileCreated = true;
  524. $writtenBytes = 0;
  525. if (!is_file($filename)) {
  526. $fileCreated = @touch($filename);
  527. }
  528. if ($fileCreated) {
  529. $writtenBytes = @file_put_contents($filename, $data, LOCK_EX);
  530. }
  531. if ($fileCreated === false || $writtenBytes === false || $writtenBytes < strlen($data)) {
  532. return false;
  533. }
  534. @chmod($filename, 0640); // protect file access
  535. return true;
  536. }
  537. /**
  538. * rename a file, prepending the protection line at the beginning
  539. *
  540. * @access public
  541. * @static
  542. * @param string $srcFile
  543. * @param string $destFile
  544. * @return void
  545. */
  546. private static function _prependRename($srcFile, $destFile)
  547. {
  548. // don't overwrite already converted file
  549. if (!is_readable($destFile)) {
  550. $handle = fopen($srcFile, 'r', false, stream_context_create());
  551. file_put_contents($destFile, self::PROTECTION_LINE . PHP_EOL);
  552. file_put_contents($destFile, $handle, FILE_APPEND);
  553. fclose($handle);
  554. }
  555. unlink($srcFile);
  556. }
  557. }