Filesystem.php 16 KB

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