Filesystem.php 16 KB

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