pshb.php 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. <?php
  2. declare(strict_types=1);
  3. require dirname(__DIR__, 2) . '/constants.php';
  4. require LIB_PATH . '/lib_rss.php'; //Includes class autoloader
  5. const MAX_PAYLOAD = 3_145_728;
  6. header('Content-Type: text/plain; charset=UTF-8');
  7. header("Content-Security-Policy: default-src 'none'; frame-ancestors 'none'; sandbox");
  8. header('X-Content-Type-Options: nosniff');
  9. $ORIGINAL_INPUT = file_get_contents('php://input', false, null, 0, MAX_PAYLOAD) ?: '';
  10. FreshRSS_Context::initSystem();
  11. if (!FreshRSS_Context::hasSystemConf()) {
  12. header('HTTP/1.1 500 Internal Server Error');
  13. die('Invalid system init!');
  14. }
  15. FreshRSS_Context::systemConf()->auth_type = 'none'; // avoid necessity to be logged in (not saved!)
  16. // Minz_Log::debug(print_r(['_SERVER' => $_SERVER, '_GET' => $_GET, '_POST' => $_POST, 'INPUT' => $ORIGINAL_INPUT], true), PSHB_LOG);
  17. $key = isset($_GET['k']) && is_string($_GET['k']) ? substr($_GET['k'], 0, 128) : '';
  18. if (!ctype_xdigit($key)) {
  19. header('HTTP/1.1 422 Unprocessable Entity');
  20. die('Invalid feed key format!');
  21. }
  22. chdir(PSHB_PATH);
  23. $canonical = @file_get_contents('keys/' . $key . '.txt');
  24. if ($canonical === false) {
  25. if (!empty($_REQUEST['hub_mode']) && $_REQUEST['hub_mode'] === 'unsubscribe') {
  26. Minz_Log::warning('Warning: Accept unknown unsubscribe', PSHB_LOG);
  27. header('Connection: close');
  28. exit($_REQUEST['hub_challenge'] ?? '');
  29. }
  30. // https://github.com/w3c/websub/issues/106 , https://w3c.github.io/websub/#content-distribution
  31. header('HTTP/1.1 410 Gone');
  32. Minz_Log::warning('Warning: Feed key not found!: ' . $key, PSHB_LOG);
  33. die('Feed key not found!');
  34. }
  35. $canonical = trim($canonical);
  36. $canonicalHash = sha1($canonical);
  37. $hubFile = @file_get_contents('feeds/' . $canonicalHash . '/!hub.json');
  38. if ($hubFile === false) {
  39. header('HTTP/1.1 410 Gone');
  40. unlink('keys/' . $key . '.txt');
  41. Minz_Log::error('Error: Feed info not found!: ' . $canonical, PSHB_LOG);
  42. die('Feed info not found!');
  43. }
  44. $hubJson = json_decode($hubFile, true);
  45. if (!is_array($hubJson) || empty($hubJson['key']) || $hubJson['key'] !== $key) {
  46. header('HTTP/1.1 500 Internal Server Error');
  47. Minz_Log::error('Error: Invalid key cross-check!: ' . $key, PSHB_LOG);
  48. die('Invalid key cross-check!');
  49. }
  50. chdir('feeds/' . $canonicalHash);
  51. $users = glob('*.txt', GLOB_NOSORT);
  52. if (empty($users)) {
  53. header('HTTP/1.1 410 Gone');
  54. Minz_Log::warning('Warning: Nobody subscribes to this feed anymore!: ' . $canonical, PSHB_LOG);
  55. unlink('../../keys/' . $key . '.txt');
  56. $feed = new FreshRSS_Feed($canonical);
  57. $feed->pubSubHubbubSubscribe(false);
  58. unlink('!hub.json');
  59. chdir('..');
  60. recursive_unlink('feeds/' . $canonicalHash);
  61. die('Nobody subscribes to this feed anymore!');
  62. }
  63. if (!empty($_REQUEST['hub_mode']) && $_REQUEST['hub_mode'] === 'subscribe') {
  64. $leaseSeconds = empty($_REQUEST['hub_lease_seconds']) || !is_numeric($_REQUEST['hub_lease_seconds']) ? 0 : (int)$_REQUEST['hub_lease_seconds'];
  65. if ($leaseSeconds > 60) {
  66. $hubJson['lease_end'] = time() + $leaseSeconds;
  67. } else {
  68. unset($hubJson['lease_end']);
  69. }
  70. $hubJson['lease_start'] = time();
  71. if (!isset($hubJson['error'])) {
  72. $hubJson['error'] = true; //Do not assume that WebSub works until the first successful push
  73. }
  74. file_put_contents('./!hub.json', json_encode($hubJson));
  75. header('Connection: close');
  76. exit($_REQUEST['hub_challenge'] ?? '');
  77. }
  78. if (!empty($_REQUEST['hub_mode']) && $_REQUEST['hub_mode'] === 'unsubscribe') {
  79. if (empty($hubJson['lease_end']) || $hubJson['lease_end'] < time()) {
  80. header('Connection: close');
  81. exit($_REQUEST['hub_challenge'] ?? '');
  82. } else {
  83. header('HTTP/1.1 422 Unprocessable Entity');
  84. die('We did not ask to unsubscribe!');
  85. }
  86. }
  87. if ($ORIGINAL_INPUT == '') {
  88. header('HTTP/1.1 422 Unprocessable Entity');
  89. die('Missing XML payload!');
  90. }
  91. // Authenticated content distribution // https://www.w3.org/TR/websub/#signing-content
  92. $hubSecret = $hubJson['secret'] ?? null;
  93. if (is_string($hubSecret) && $hubSecret !== '') {
  94. $signatureOk = false;
  95. // The X-Hub-Signature header has the form `method=hexSignature`, e.g. `sha256=09AF`
  96. $signature = is_string($_SERVER['HTTP_X_HUB_SIGNATURE'] ?? null) ? $_SERVER['HTTP_X_HUB_SIGNATURE'] : '';
  97. // https://www.php.net/function.hash-hmac-algos
  98. if (preg_match('/^(?<algo>[a-zA-Z0-9]{4,6})=(?<signature>[0-9a-fA-F]{40,128})$/', $signature, $matches) === 1) {
  99. $algo = strtolower('' . $matches['algo']);
  100. if (in_array($algo, ['sha1', 'sha256', 'sha384', 'sha512'], true)) {
  101. $signatureOk = hash_equals(hash_hmac($algo, $ORIGINAL_INPUT, $hubSecret), '' . $matches['signature']);
  102. }
  103. }
  104. if (!$signatureOk) {
  105. Minz_Log::warning('Invalid signature for WebSub push to ' . $canonical, PSHB_LOG);
  106. header('HTTP/1.1 422 Unprocessable Entity');
  107. die('Invalid hub signature!');
  108. }
  109. }
  110. $simplePie = new FreshRSS_SimplePieCustom();
  111. $simplePie->enable_cache(false);
  112. $simplePie->set_raw_data($ORIGINAL_INPUT);
  113. $simplePie->init();
  114. unset($ORIGINAL_INPUT);
  115. $links = $simplePie->get_links('self');
  116. $self = $links[0] ?? '';
  117. // Support HTTP header `Link: <http://example.net/hub.php>; rel="hub", <http://example.net/feed.php>; rel="self"`
  118. $httpLink = is_string($_SERVER['HTTP_LINK'] ?? null) ? $_SERVER['HTTP_LINK'] : '';
  119. if ($httpLink !== '' && preg_match_all('/<([^>]+)>;\\s*rel="([^"]+)"/', $httpLink, $matches, PREG_SET_ORDER)) {
  120. $links = [];
  121. foreach ($matches as $match) {
  122. if (!empty($match[1]) && !empty($match[2])) {
  123. $links[$match[2]] = $match[1];
  124. }
  125. }
  126. // if (!empty($links['hub'])) {
  127. // // TODO: Support WebSub hub redirection
  128. // }
  129. if (!empty($links['self'])) {
  130. $httpSelf = FreshRSS_http_Util::checkUrl($links['self']) ?: '';
  131. if ($self !== '' && FreshRSS_http_Util::compareUrlIgnoringHttps($self, $httpSelf) !== 0) {
  132. Minz_Log::warning('Warning: Self URL mismatch between XML [' . $self . '] and HTTP!: ' . $httpSelf, PSHB_LOG);
  133. }
  134. $self = $httpSelf;
  135. }
  136. }
  137. if ($self !== '' && FreshRSS_http_Util::compareUrlIgnoringHttps($self, $canonical) !== 0) {
  138. header('HTTP/1.1 422 Unprocessable Entity');
  139. Minz_Log::warning('Warning: Self URL [' . $self . '] does not match registered canonical URL!: ' . $canonical, PSHB_LOG);
  140. die('Self URL does not match registered canonical URL!');
  141. }
  142. Minz_ExtensionManager::init();
  143. Minz_Translate::init();
  144. $nb = 0;
  145. foreach ($users as $userFilename) {
  146. $username = basename($userFilename, '.txt');
  147. if (!file_exists(USERS_PATH . '/' . $username . '/config.php')) {
  148. Minz_Log::warning('Warning: Removing broken user link: ' . $username . ' for ' . $canonical, PSHB_LOG);
  149. unlink($userFilename);
  150. continue;
  151. }
  152. try {
  153. FreshRSS_Context::initUser($username);
  154. if (!FreshRSS_Context::hasUserConf() || !FreshRSS_Context::userConf()->enabled) {
  155. Minz_Log::warning('FreshRSS skip disabled user ' . $username);
  156. continue;
  157. }
  158. Minz_ExtensionManager::enableByList(FreshRSS_Context::userConf()->extensions_enabled, 'user');
  159. Minz_Translate::reset(FreshRSS_Context::userConf()->language);
  160. [$nbUpdatedFeeds, ] = FreshRSS_feed_Controller::actualizeFeedsAndCommit(feed_url: $canonical, simplePiePush: $simplePie, selfUrl: $self);
  161. if ($nbUpdatedFeeds > 0) {
  162. $nb++;
  163. } else {
  164. Minz_Log::warning('Warning: User ' . $username . ' does not subscribe anymore to ' . $canonical, PSHB_LOG);
  165. unlink($userFilename);
  166. }
  167. } catch (Exception $e) {
  168. Minz_Log::error('Error: ' . $e->getMessage() . ' for user ' . $username . ' and feed ' . $canonical, PSHB_LOG);
  169. }
  170. }
  171. $simplePie->__destruct(); // https://simplepie.org/wiki/faq/i_m_getting_memory_leaks
  172. unset($simplePie);
  173. if ($nb === 0) {
  174. header('HTTP/1.1 410 Gone');
  175. Minz_Log::warning('Warning: Nobody subscribes to this feed anymore after all!: ' . $canonical, PSHB_LOG);
  176. die('Nobody subscribes to this feed anymore after all!');
  177. } elseif (!empty($hubJson['error'])) {
  178. $hubJson['error'] = false;
  179. file_put_contents('./!hub.json', json_encode($hubJson));
  180. }
  181. Minz_Log::notice('WebSub ' . $canonical . ' done: ' . $nb, PSHB_LOG);
  182. exit('Done: ' . $nb . "\n");