httpUtil.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. <?php
  2. declare(strict_types=1);
  3. final class FreshRSS_http_Util {
  4. private const RETRY_AFTER_PATH = DATA_PATH . '/Retry-After/';
  5. private static function getRetryAfterFile(string $url, string $proxy): string {
  6. $domain = parse_url($url, PHP_URL_HOST);
  7. if (!is_string($domain) || $domain === '') {
  8. return '';
  9. }
  10. $port = parse_url($url, PHP_URL_PORT);
  11. if (is_int($port)) {
  12. $domain .= ':' . $port;
  13. }
  14. return self::RETRY_AFTER_PATH . urlencode($domain) . (empty($proxy) ? '' : ('_' . urlencode($proxy))) . '.txt';
  15. }
  16. /**
  17. * Clean up old Retry-After files
  18. */
  19. private static function cleanRetryAfters(): void {
  20. if (!is_dir(self::RETRY_AFTER_PATH)) {
  21. return;
  22. }
  23. $files = glob(self::RETRY_AFTER_PATH . '*.txt', GLOB_NOSORT);
  24. if ($files === false) {
  25. return;
  26. }
  27. foreach ($files as $file) {
  28. if (@filemtime($file) < time()) {
  29. @unlink($file);
  30. }
  31. }
  32. }
  33. /**
  34. * Check whether the URL needs to wait for a Retry-After period.
  35. * @return int The timestamp of when the Retry-After expires, or 0 if not set.
  36. */
  37. public static function getRetryAfter(string $url, string $proxy): int {
  38. if (rand(0, 30) === 1) { // Remove old files once in a while
  39. self::cleanRetryAfters();
  40. }
  41. $txt = self::getRetryAfterFile($url, $proxy);
  42. if ($txt === '') {
  43. return 0;
  44. }
  45. $retryAfter = @filemtime($txt) ?: 0;
  46. if ($retryAfter <= 0) {
  47. return 0;
  48. }
  49. if ($retryAfter < time()) {
  50. @unlink($txt);
  51. return 0;
  52. }
  53. return $retryAfter;
  54. }
  55. /**
  56. * Store the HTTP Retry-After header value of an HTTP `429 Too Many Requests` or `503 Service Unavailable` response.
  57. */
  58. public static function setRetryAfter(string $url, string $proxy, string $retryAfter): int {
  59. $txt = self::getRetryAfterFile($url, $proxy);
  60. if ($txt === '') {
  61. return 0;
  62. }
  63. $limits = FreshRSS_Context::systemConf()->limits;
  64. if (ctype_digit($retryAfter)) {
  65. $retryAfter = time() + (int)$retryAfter;
  66. } else {
  67. $retryAfter = \SimplePie\Misc::parse_date($retryAfter) ?:
  68. (time() + max(600, $limits['retry_after_default'] ?? 0));
  69. }
  70. $retryAfter = min($retryAfter, time() + max(3600, $limits['retry_after_max'] ?? 0));
  71. @mkdir(self::RETRY_AFTER_PATH);
  72. if (!touch($txt, $retryAfter)) {
  73. Minz_Log::error('Failed to set Retry-After for ' . $url);
  74. return 0;
  75. }
  76. return $retryAfter;
  77. }
  78. /**
  79. * @param array<mixed> $curl_params
  80. * @return array<mixed>
  81. */
  82. public static function sanitizeCurlParams(array $curl_params): array {
  83. $safe_params = [
  84. CURLOPT_COOKIE,
  85. CURLOPT_COOKIEFILE,
  86. CURLOPT_FOLLOWLOCATION,
  87. CURLOPT_HTTPHEADER,
  88. CURLOPT_MAXREDIRS,
  89. CURLOPT_POST,
  90. CURLOPT_POSTFIELDS,
  91. CURLOPT_PROXY,
  92. CURLOPT_PROXYTYPE,
  93. CURLOPT_USERAGENT,
  94. ];
  95. foreach ($curl_params as $k => $_) {
  96. if (!in_array($k, $safe_params, true)) {
  97. unset($curl_params[$k]);
  98. continue;
  99. }
  100. // Allow only an empty value just to enable the libcurl cookie engine
  101. if ($k === CURLOPT_COOKIEFILE) {
  102. $curl_params[$k] = '';
  103. }
  104. }
  105. return $curl_params;
  106. }
  107. private static function idn_to_puny(string $url): string {
  108. if (function_exists('idn_to_ascii')) {
  109. $idn = parse_url($url, PHP_URL_HOST);
  110. if (is_string($idn) && $idn != '') {
  111. $puny = idn_to_ascii($idn);
  112. $pos = strpos($url, $idn);
  113. if ($puny != false && $pos !== false) {
  114. $url = substr_replace($url, $puny, $pos, strlen($idn));
  115. }
  116. }
  117. }
  118. return $url;
  119. }
  120. public static function checkUrl(string $url, bool $fixScheme = true): string|false {
  121. $url = trim($url);
  122. if ($url == '') {
  123. return '';
  124. }
  125. if ($fixScheme && preg_match('#^https?://#i', $url) !== 1) {
  126. $url = 'https://' . ltrim($url, '/');
  127. }
  128. $url = self::idn_to_puny($url); // https://bugs.php.net/bug.php?id=53474
  129. $urlRelaxed = str_replace('_', 'z', $url); //PHP discussion #64948 Underscore
  130. if (is_string(filter_var($urlRelaxed, FILTER_VALIDATE_URL))) {
  131. return $url;
  132. } else {
  133. return false;
  134. }
  135. }
  136. /**
  137. * Remove the charset meta information of an HTML document, e.g.:
  138. * `<meta charset="..." />`
  139. * `<meta http-equiv="Content-Type" content="text/html; charset=...">`
  140. */
  141. private static function stripHtmlMetaCharset(string $html): string {
  142. return preg_replace('/<meta\s[^>]*charset\s*=\s*[^>]+>/i', '', $html, 1) ?? '';
  143. }
  144. /**
  145. * Set an XML preamble to enforce the HTML content type charset received by HTTP.
  146. * @param string $html the raw downloaded HTML content
  147. * @param string $contentType an HTTP Content-Type such as 'text/html; charset=utf-8'
  148. * @return string an HTML string with XML encoding information for DOMDocument::loadHTML()
  149. */
  150. private static function enforceHttpEncoding(string $html, string $contentType = ''): string {
  151. $httpCharset = preg_match('/\bcharset=([0-9a-z_-]{2,12})$/i', $contentType, $matches) === 1 ? $matches[1] : '';
  152. if ($httpCharset == '') {
  153. // No charset defined by HTTP
  154. if (preg_match('/<meta\s[^>]*charset\s*=[\s\'"]*UTF-?8\b/i', substr($html, 0, 2048))) {
  155. // Detect UTF-8 even if declared too deep in HTML for DOMDocument
  156. $httpCharset = 'UTF-8';
  157. } else {
  158. // Do nothing
  159. return $html;
  160. }
  161. }
  162. $httpCharsetNormalized = \SimplePie\Misc::encoding($httpCharset);
  163. if (in_array($httpCharsetNormalized, ['windows-1252', 'US-ASCII'], true)) {
  164. // Default charset for HTTP, do nothing
  165. return $html;
  166. }
  167. if (substr($html, 0, 3) === "\xEF\xBB\xBF" || // UTF-8 BOM
  168. substr($html, 0, 2) === "\xFF\xFE" || // UTF-16 Little Endian BOM
  169. substr($html, 0, 2) === "\xFE\xFF" || // UTF-16 Big Endian BOM
  170. substr($html, 0, 4) === "\xFF\xFE\x00\x00" || // UTF-32 Little Endian BOM
  171. substr($html, 0, 4) === "\x00\x00\xFE\xFF") { // UTF-32 Big Endian BOM
  172. // Existing byte order mark, do nothing
  173. return $html;
  174. }
  175. if (preg_match('/^<[?]xml[^>]+encoding\b/', substr($html, 0, 64))) {
  176. // Existing XML declaration, do nothing
  177. return $html;
  178. }
  179. if ($httpCharsetNormalized !== 'UTF-8') {
  180. // Try to change encoding to UTF-8 using mbstring or iconv or intl
  181. $utf8 = \SimplePie\Misc::change_encoding($html, $httpCharsetNormalized, 'UTF-8');
  182. if (is_string($utf8)) {
  183. $html = self::stripHtmlMetaCharset($utf8);
  184. $httpCharsetNormalized = 'UTF-8';
  185. }
  186. }
  187. if ($httpCharsetNormalized === 'UTF-8') {
  188. // Save encoding information as XML declaration
  189. return '<' . '?xml version="1.0" encoding="' . $httpCharsetNormalized . '" ?' . ">\n" . $html;
  190. }
  191. // Give up
  192. return $html;
  193. }
  194. /**
  195. * Set an HTML base URL to the HTML content if there is none.
  196. * @param string $html the raw downloaded HTML content
  197. * @param string $href the HTML base URL
  198. * @return string an HTML string
  199. */
  200. private static function enforceHtmlBase(string $html, string $href): string {
  201. $doc = new DOMDocument();
  202. $doc->loadHTML($html, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING);
  203. if ($doc->documentElement === null) {
  204. return '';
  205. }
  206. $xpath = new DOMXPath($doc);
  207. $bases = $xpath->evaluate('//base');
  208. if (!($bases instanceof DOMNodeList) || $bases->length === 0) {
  209. $base = $doc->createElement('base');
  210. if ($base === false) {
  211. return $html;
  212. }
  213. $base->setAttribute('href', $href);
  214. $head = null;
  215. $heads = $xpath->evaluate('//head');
  216. if ($heads instanceof DOMNodeList && $heads->length > 0) {
  217. $head = $heads->item(0);
  218. }
  219. if ($head instanceof DOMElement) {
  220. $head->insertBefore($base, $head->firstChild);
  221. } else {
  222. $doc->documentElement->insertBefore($base, $doc->documentElement->firstChild);
  223. }
  224. }
  225. return $doc->saveHTML() ?: $html;
  226. }
  227. /**
  228. * @param non-empty-string $url
  229. * @param string $type {html,ico,json,opml,xml}
  230. * @param array<string,mixed> $attributes
  231. * @param array<int,mixed> $curl_options
  232. * @return array{body:string,effective_url:string,redirect_count:int,fail:bool}
  233. */
  234. public static function httpGet(string $url, string $cachePath, string $type = 'html', array $attributes = [], array $curl_options = []): array {
  235. $limits = FreshRSS_Context::systemConf()->limits;
  236. $feed_timeout = empty($attributes['timeout']) || !is_numeric($attributes['timeout']) ? 0 : intval($attributes['timeout']);
  237. $cacheMtime = @filemtime($cachePath);
  238. if ($cacheMtime !== false && $cacheMtime > time() - intval($limits['cache_duration'])) {
  239. $body = @file_get_contents($cachePath);
  240. if ($body != false) {
  241. syslog(LOG_DEBUG, 'FreshRSS uses cache for ' . \SimplePie\Misc::url_remove_credentials($url));
  242. return ['body' => $body, 'effective_url' => $url, 'redirect_count' => 0, 'fail' => false];
  243. }
  244. }
  245. if (rand(0, 30) === 1) { // Remove old cache once in a while
  246. cleanCache(CLEANCACHE_HOURS);
  247. }
  248. $options = [];
  249. $accept = '';
  250. $proxy = is_string(FreshRSS_Context::systemConf()->curl_options[CURLOPT_PROXY] ?? null) ? FreshRSS_Context::systemConf()->curl_options[CURLOPT_PROXY] : '';
  251. if (is_array($attributes['curl_params'] ?? null)) {
  252. $options = self::sanitizeCurlParams($attributes['curl_params']);
  253. $proxy = is_string($options[CURLOPT_PROXY]) ? $options[CURLOPT_PROXY] : '';
  254. if (is_array($options[CURLOPT_HTTPHEADER] ?? null)) {
  255. // Remove headers problematic for security
  256. $options[CURLOPT_HTTPHEADER] = array_filter($options[CURLOPT_HTTPHEADER],
  257. fn($header) => is_string($header) && !preg_match('/^(Remote-User|X-WebAuth-User)\\s*:/i', $header));
  258. // Add Accept header if it is not set
  259. if (preg_grep('/^Accept\\s*:/i', $options[CURLOPT_HTTPHEADER]) === false) {
  260. $options[CURLOPT_HTTPHEADER][] = 'Accept: ' . $accept;
  261. }
  262. }
  263. }
  264. if (($retryAfter = FreshRSS_http_Util::getRetryAfter($url, $proxy)) > 0) {
  265. Minz_Log::warning('For that domain, will first retry after ' . date('c', $retryAfter) . '. ' . \SimplePie\Misc::url_remove_credentials($url));
  266. return ['body' => '', 'effective_url' => $url, 'redirect_count' => 0, 'fail' => true];
  267. }
  268. if (FreshRSS_Context::systemConf()->simplepie_syslog_enabled) {
  269. syslog(LOG_INFO, 'FreshRSS GET ' . $type . ' ' . \SimplePie\Misc::url_remove_credentials($url));
  270. }
  271. switch ($type) {
  272. case 'json':
  273. $accept = 'application/json,application/feed+json,application/javascript;q=0.9,text/javascript;q=0.8,*/*;q=0.7';
  274. break;
  275. case 'opml':
  276. $accept = 'text/x-opml,text/xml;q=0.9,application/xml;q=0.9,*/*;q=0.8';
  277. break;
  278. case 'xml':
  279. $accept = 'application/xml,application/xhtml+xml,text/xml;q=0.9,*/*;q=0.8';
  280. break;
  281. case 'ico':
  282. $accept = 'image/x-icon,image/vnd.microsoft.icon,image/ico,image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.1';
  283. break;
  284. case 'html':
  285. default:
  286. $accept = 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8';
  287. break;
  288. }
  289. // TODO: Implement HTTP 1.1 conditional GET If-Modified-Since
  290. $ch = curl_init();
  291. if ($ch === false) {
  292. return ['body' => '', 'effective_url' => '', 'redirect_count' => 0, 'fail' => true];
  293. }
  294. curl_setopt_array($ch, [
  295. CURLOPT_URL => $url,
  296. CURLOPT_HTTPHEADER => ['Accept: ' . $accept],
  297. CURLOPT_USERAGENT => FRESHRSS_USERAGENT,
  298. CURLOPT_CONNECTTIMEOUT => $feed_timeout > 0 ? $feed_timeout : $limits['timeout'],
  299. CURLOPT_TIMEOUT => $feed_timeout > 0 ? $feed_timeout : $limits['timeout'],
  300. CURLOPT_MAXREDIRS => 4,
  301. CURLOPT_RETURNTRANSFER => true,
  302. CURLOPT_FOLLOWLOCATION => true,
  303. CURLOPT_ENCODING => '', //Enable all encodings
  304. //CURLOPT_VERBOSE => 1, // To debug sent HTTP headers
  305. ]);
  306. curl_setopt_array($ch, $options);
  307. curl_setopt_array($ch, FreshRSS_Context::systemConf()->curl_options);
  308. $responseHeaders = '';
  309. curl_setopt($ch, CURLOPT_HEADERFUNCTION, function (\CurlHandle $ch, string $header) use (&$responseHeaders) {
  310. if (trim($header) !== '') { // Skip e.g. separation with trailer headers
  311. $responseHeaders .= $header;
  312. }
  313. return strlen($header);
  314. });
  315. if (isset($attributes['ssl_verify'])) {
  316. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, empty($attributes['ssl_verify']) ? 0 : 2);
  317. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (bool)$attributes['ssl_verify']);
  318. if (empty($attributes['ssl_verify'])) {
  319. curl_setopt($ch, CURLOPT_SSL_CIPHER_LIST, 'DEFAULT@SECLEVEL=1');
  320. }
  321. }
  322. curl_setopt_array($ch, $curl_options);
  323. $body = curl_exec($ch);
  324. $c_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  325. $c_content_type = '' . curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
  326. $c_effective_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
  327. $c_redirect_count = curl_getinfo($ch, CURLINFO_REDIRECT_COUNT);
  328. $c_error = curl_error($ch);
  329. $headers = [];
  330. if ($body !== false) {
  331. assert($c_redirect_count >= 0);
  332. $responseHeaders = \SimplePie\HTTP\Parser::prepareHeaders($responseHeaders, $c_redirect_count + 1);
  333. $parser = new \SimplePie\HTTP\Parser($responseHeaders);
  334. if ($parser->parse()) {
  335. $headers = $parser->headers;
  336. }
  337. }
  338. $fail = $c_status != 200 || $c_error != '' || $body === false;
  339. if ($fail) {
  340. $body = '';
  341. Minz_Log::warning('Error fetching content: HTTP code ' . $c_status . ': ' . $c_error . ' ' . $url);
  342. if (in_array($c_status, [429, 503], true)) {
  343. $retryAfter = FreshRSS_http_Util::setRetryAfter($url, $proxy, $headers['retry-after'] ?? '');
  344. if ($c_status === 429) {
  345. $errorMessage = 'HTTP 429 Too Many Requests! [' . \SimplePie\Misc::url_remove_credentials($url) . ']';
  346. } elseif ($c_status === 503) {
  347. $errorMessage = 'HTTP 503 Service Unavailable! [' . \SimplePie\Misc::url_remove_credentials($url) . ']';
  348. }
  349. if ($retryAfter > 0) {
  350. $errorMessage .= ' We may retry after ' . date('c', $retryAfter);
  351. }
  352. }
  353. // TODO: Implement HTTP 410 Gone
  354. } elseif (!is_string($body) || strlen($body) === 0) {
  355. $body = '';
  356. } else {
  357. if (in_array($type, ['html', 'json', 'opml', 'xml'], true)) {
  358. $body = trim($body, " \n\r\t\v"); // Do not trim \x00 to avoid breaking a BOM
  359. }
  360. if (in_array($type, ['html', 'xml', 'opml'], true)) {
  361. $body = self::enforceHttpEncoding($body, $c_content_type);
  362. }
  363. if (in_array($type, ['html'], true)) {
  364. $body = self::enforceHtmlBase($body, $c_effective_url);
  365. }
  366. }
  367. if (file_put_contents($cachePath, $body) === false) {
  368. Minz_Log::warning("Error saving cache $cachePath for $url");
  369. }
  370. return ['body' => $body, 'effective_url' => $c_effective_url, 'redirect_count' => $c_redirect_count, 'fail' => $fail];
  371. }
  372. /**
  373. * Converts an IP (v4 or v6) to a binary representation using inet_pton
  374. *
  375. * @param string $ip the IP to convert
  376. * @return string a binary representation of the specified IP
  377. */
  378. private static function ipToBits(string $ip): string {
  379. $binaryip = '';
  380. foreach (str_split(inet_pton($ip) ?: '') as $char) {
  381. $binaryip .= str_pad(decbin(ord($char)), 8, '0', STR_PAD_LEFT);
  382. }
  383. return $binaryip;
  384. }
  385. /**
  386. * Check if an ip belongs to the provided range (in CIDR format)
  387. *
  388. * @param string $ip the IP that we want to verify (ex: 192.168.16.1)
  389. * @param string $range the range to check against (ex: 192.168.16.0/24)
  390. * @return bool true if the IP is in the range, otherwise false
  391. */
  392. private static function checkCIDR(string $ip, string $range): bool {
  393. $binary_ip = self::ipToBits($ip);
  394. $split = explode('/', $range);
  395. $subnet = $split[0] ?? '';
  396. if ($subnet == '') {
  397. return false;
  398. }
  399. $binary_subnet = self::ipToBits($subnet);
  400. $mask_bits = $split[1] ?? '';
  401. $mask_bits = (int)$mask_bits;
  402. if ($mask_bits === 0) {
  403. $mask_bits = null;
  404. }
  405. $ip_net_bits = substr($binary_ip, 0, $mask_bits);
  406. $subnet_bits = substr($binary_subnet, 0, $mask_bits);
  407. return $ip_net_bits === $subnet_bits;
  408. }
  409. /**
  410. * Check if the client (e.g. last proxy) is allowed to send unsafe headers.
  411. * This uses the `TRUSTED_PROXY` environment variable or the `trusted_sources` configuration option to get an array of the authorized ranges,
  412. * The connection IP is obtained from the `CONN_REMOTE_ADDR`
  413. * (if available, to be robust even when using Apache mod_remoteip) or `REMOTE_ADDR` environment variables.
  414. * @return bool true if the sender’s IP is in one of the ranges defined in the configuration, else false
  415. */
  416. public static function checkTrustedIP(): bool {
  417. if (!FreshRSS_Context::hasSystemConf()) {
  418. return false;
  419. }
  420. $remoteIp = Minz_Request::connectionRemoteAddress();
  421. if ($remoteIp === '') {
  422. return false;
  423. }
  424. $trusted = getenv('TRUSTED_PROXY');
  425. if ($trusted != 0 && is_string($trusted)) {
  426. $trusted = preg_split('/\s+/', $trusted, -1, PREG_SPLIT_NO_EMPTY);
  427. }
  428. if (!is_array($trusted) || empty($trusted)) {
  429. $trusted = FreshRSS_Context::systemConf()->trusted_sources;
  430. }
  431. foreach ($trusted as $cidr) {
  432. if (self::checkCIDR($remoteIp, $cidr)) {
  433. return true;
  434. }
  435. }
  436. return false;
  437. }
  438. public static function httpAuthUser(bool $onlyTrusted = true): string {
  439. $auths = array_unique(
  440. array_intersect_key($_SERVER, ['REMOTE_USER' => '', 'REDIRECT_REMOTE_USER' => '', 'HTTP_REMOTE_USER' => '', 'HTTP_X_WEBAUTH_USER' => ''])
  441. );
  442. if (count($auths) > 1) {
  443. Minz_Log::warning('Multiple HTTP authentication headers!');
  444. return '';
  445. }
  446. if (!empty($_SERVER['REMOTE_USER']) && is_string($_SERVER['REMOTE_USER'])) {
  447. return $_SERVER['REMOTE_USER'];
  448. }
  449. if (!empty($_SERVER['REDIRECT_REMOTE_USER']) && is_string($_SERVER['REDIRECT_REMOTE_USER'])) {
  450. return $_SERVER['REDIRECT_REMOTE_USER'];
  451. }
  452. if (!$onlyTrusted || self::checkTrustedIP()) {
  453. if (!empty($_SERVER['HTTP_REMOTE_USER']) && is_string($_SERVER['HTTP_REMOTE_USER'])) {
  454. return $_SERVER['HTTP_REMOTE_USER'];
  455. }
  456. if (!empty($_SERVER['HTTP_X_WEBAUTH_USER']) && is_string($_SERVER['HTTP_X_WEBAUTH_USER'])) {
  457. return $_SERVER['HTTP_X_WEBAUTH_USER'];
  458. }
  459. }
  460. return '';
  461. }
  462. }