httpUtil.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844
  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 const PRIVATE_SUBNETS = [
  6. '127.0.0.0/8', // RFC1700 (Loopback)
  7. '10.0.0.0/8', // RFC1918
  8. '192.168.0.0/16', // RFC1918
  9. '172.16.0.0/12', // RFC1918
  10. '169.254.0.0/16', // RFC3927
  11. '0.0.0.0/8', // RFC5735
  12. '240.0.0.0/4', // RFC1112
  13. '100.64.0.0/10', // RFC6598 (Shared Address Space of Carrier-Grade NAT)
  14. '::1/128', // Loopback
  15. 'fc00::/7', // Unique Local Address
  16. 'fe80::/10', // Link Local Address
  17. '::ffff:0:0/96', // IPv4 translations
  18. '64:ff9b::/96', // RFC6052 (IPv6 Addressing of IPv4/IPv6 Translators, NAT64)
  19. '::/128', // Unspecified address
  20. ];
  21. /** @var array<string, string[]> $resolve_ok */
  22. private static array $resolve_ok = [];
  23. /** @var array<string, bool> $retry_after_domain_wide */
  24. private static array $retry_after_domain_wide = [];
  25. private static function getRetryAfterFile(string $url, string $proxy): string {
  26. $domain = parse_url($url, PHP_URL_HOST);
  27. if (!is_string($domain) || $domain === '') {
  28. return '';
  29. }
  30. // Once per host, as serverIsPublic() may resolve it
  31. $domainWide = self::$retry_after_domain_wide[$domain] ??= Minz_Request::serverIsPublic($url);
  32. $port = parse_url($url, PHP_URL_PORT);
  33. if (is_int($port)) {
  34. $domain .= ':' . $port;
  35. }
  36. return self::RETRY_AFTER_PATH . urlencode($domain) .
  37. ($domainWide ? '' : '_' . hash('sha256', $url)) .
  38. (empty($proxy) ? '' : '_' . urlencode($proxy)) . '.txt';
  39. }
  40. /**
  41. * Clean up old Retry-After files
  42. */
  43. private static function cleanRetryAfters(): void {
  44. if (!is_dir(self::RETRY_AFTER_PATH)) {
  45. return;
  46. }
  47. $files = glob(self::RETRY_AFTER_PATH . '*.txt', GLOB_NOSORT);
  48. if ($files === false) {
  49. return;
  50. }
  51. foreach ($files as $file) {
  52. if (@filemtime($file) < time()) {
  53. @unlink($file);
  54. }
  55. }
  56. }
  57. /**
  58. * Check whether the URL needs to wait for a Retry-After period.
  59. * @return int The timestamp of when the Retry-After expires, or 0 if not set.
  60. */
  61. public static function getRetryAfter(string $url, string $proxy): int {
  62. if (rand(0, 30) === 1) { // Remove old files once in a while
  63. self::cleanRetryAfters();
  64. }
  65. $txt = self::getRetryAfterFile($url, $proxy);
  66. if ($txt === '') {
  67. return 0;
  68. }
  69. $retryAfter = @filemtime($txt) ?: 0;
  70. if ($retryAfter <= 0) {
  71. return 0;
  72. }
  73. if ($retryAfter < time()) {
  74. @unlink($txt);
  75. return 0;
  76. }
  77. return $retryAfter;
  78. }
  79. /**
  80. * Store the HTTP Retry-After header value of an HTTP `429 Too Many Requests` or `503 Service Unavailable` response.
  81. */
  82. public static function setRetryAfter(string $url, string $proxy, string $retryAfter): int {
  83. $txt = self::getRetryAfterFile($url, $proxy);
  84. if ($txt === '') {
  85. return 0;
  86. }
  87. $limits = FreshRSS_Context::systemConf()->limits;
  88. if (ctype_digit($retryAfter)) {
  89. $retryAfter = time() + (int)$retryAfter;
  90. } else {
  91. $retryAfter = \SimplePie\Misc::parse_date($retryAfter) ?:
  92. (time() + max(600, $limits['retry_after_default'] ?? 0));
  93. }
  94. $retryAfter = min($retryAfter, time() + max(3600, $limits['retry_after_max'] ?? 0));
  95. @mkdir(self::RETRY_AFTER_PATH);
  96. if (!touch($txt, $retryAfter)) {
  97. Minz_Log::error('Failed to set Retry-After for ' . $url);
  98. return 0;
  99. }
  100. return $retryAfter;
  101. }
  102. /**
  103. * @param array<mixed> $curl_params
  104. * @return array<mixed>
  105. */
  106. public static function sanitizeCurlParams(array $curl_params): array {
  107. $safe_params = [
  108. CURLOPT_COOKIE,
  109. CURLOPT_COOKIEFILE,
  110. CURLOPT_FOLLOWLOCATION, // We filter this value later, only allowing `false`
  111. CURLOPT_HTTPHEADER,
  112. CURLOPT_MAXREDIRS,
  113. CURLOPT_POST,
  114. CURLOPT_POSTFIELDS,
  115. CURLOPT_PROXY,
  116. CURLOPT_PROXYTYPE,
  117. CURLOPT_USERAGENT,
  118. ];
  119. foreach ($curl_params as $k => $_) {
  120. if (!in_array($k, $safe_params, true)) {
  121. unset($curl_params[$k]);
  122. continue;
  123. }
  124. // Allow only an empty value just to enable the libcurl cookie engine
  125. if ($k === CURLOPT_COOKIEFILE) {
  126. $curl_params[$k] = '';
  127. }
  128. // Remove HTTP authentication headers problematic for security
  129. if ($k === CURLOPT_HTTPHEADER && is_array($curl_params[$k])) {
  130. $curl_params[$k] = array_filter($curl_params[$k],
  131. fn($header) => is_string($header) && !preg_match('/^(Remote[-_\s]*User|X[-_\s]*WebAuth[-_\s]*User)\\s*:/i', $header));
  132. }
  133. }
  134. return $curl_params;
  135. }
  136. private static function idn_to_puny(string $url): string {
  137. if (function_exists('idn_to_ascii')) {
  138. $idn = parse_url($url, PHP_URL_HOST);
  139. if (is_string($idn) && $idn != '') {
  140. $puny = idn_to_ascii($idn);
  141. $pos = strpos($url, $idn);
  142. if ($puny != false && $pos !== false) {
  143. $url = substr_replace($url, $puny, $pos, strlen($idn));
  144. }
  145. }
  146. }
  147. return $url;
  148. }
  149. public static function checkUrl(string $url, bool $fixScheme = true): string|false {
  150. $url = trim($url);
  151. if ($url == '') {
  152. return '';
  153. }
  154. if ($fixScheme && preg_match('#^https?://#i', $url) !== 1) {
  155. $url = 'https://' . ltrim($url, '/');
  156. }
  157. $url = self::idn_to_puny($url); // https://bugs.php.net/bug.php?id=53474
  158. $urlRelaxed = str_replace('_', 'z', $url); //PHP discussion #64948 Underscore
  159. if (is_string(filter_var($urlRelaxed, FILTER_VALIDATE_URL))) {
  160. return $url;
  161. } else {
  162. return false;
  163. }
  164. }
  165. /**
  166. * Remove the charset meta information of an HTML document, e.g.:
  167. * `<meta charset="..." />`
  168. * `<meta http-equiv="Content-Type" content="text/html; charset=...">`
  169. */
  170. private static function stripHtmlMetaCharset(string $html): string {
  171. return preg_replace('/<meta\s[^>]*charset\s*=\s*[^>]+>/i', '', $html, 1) ?? '';
  172. }
  173. /**
  174. * Set an XML preamble to enforce the HTML content type charset received by HTTP.
  175. * @param string $html the raw downloaded HTML content
  176. * @param string $contentType an HTTP Content-Type such as 'text/html; charset=utf-8'
  177. * @return string an HTML string with XML encoding information for DOMDocument::loadHTML()
  178. */
  179. private static function enforceHttpEncoding(string $html, string $contentType = ''): string {
  180. $httpCharset = preg_match('/\bcharset=([0-9a-z_-]{2,12})$/i', $contentType, $matches) === 1 ? $matches[1] : '';
  181. if ($httpCharset == '') {
  182. // No charset defined by HTTP
  183. if (preg_match('/<meta\s[^>]*charset\s*=[\s\'"]*UTF-?8\b/i', substr($html, 0, 2048))) {
  184. // Detect UTF-8 even if declared too deep in HTML for DOMDocument
  185. $httpCharset = 'UTF-8';
  186. } else {
  187. // Do nothing
  188. return $html;
  189. }
  190. }
  191. $httpCharsetNormalized = \SimplePie\Misc::encoding($httpCharset);
  192. if (in_array($httpCharsetNormalized, ['windows-1252', 'US-ASCII'], true)) {
  193. // Default charset for HTTP, do nothing
  194. return $html;
  195. }
  196. if (substr($html, 0, 3) === "\xEF\xBB\xBF" || // UTF-8 BOM
  197. substr($html, 0, 2) === "\xFF\xFE" || // UTF-16 Little Endian BOM
  198. substr($html, 0, 2) === "\xFE\xFF" || // UTF-16 Big Endian BOM
  199. substr($html, 0, 4) === "\xFF\xFE\x00\x00" || // UTF-32 Little Endian BOM
  200. substr($html, 0, 4) === "\x00\x00\xFE\xFF") { // UTF-32 Big Endian BOM
  201. // Existing byte order mark, do nothing
  202. return $html;
  203. }
  204. if (preg_match('/^<[?]xml[^>]+encoding\b/', substr($html, 0, 64))) {
  205. // Existing XML declaration, do nothing
  206. return $html;
  207. }
  208. if ($httpCharsetNormalized !== 'UTF-8') {
  209. // Try to change encoding to UTF-8 using mbstring or iconv or intl
  210. $utf8 = \SimplePie\Misc::change_encoding($html, $httpCharsetNormalized, 'UTF-8');
  211. if (is_string($utf8)) {
  212. $html = self::stripHtmlMetaCharset($utf8);
  213. $httpCharsetNormalized = 'UTF-8';
  214. }
  215. }
  216. if ($httpCharsetNormalized === 'UTF-8') {
  217. // Save encoding information as Unicode BOM
  218. return "\xEF\xBB\xBF" . $html;
  219. }
  220. // Give up
  221. return $html;
  222. }
  223. /**
  224. * Set an HTML base URL to the HTML content if there is none.
  225. * @param string $html the raw downloaded HTML content
  226. * @param string $href the HTML base URL
  227. * @return string an HTML string
  228. */
  229. private static function enforceHtmlBase(string $html, string $href): string {
  230. $doc = new DOMDocument();
  231. $doc->loadHTML($html, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING);
  232. if ($doc->documentElement === null) {
  233. return '';
  234. }
  235. $xpath = new DOMXPath($doc);
  236. $bases = $xpath->evaluate('//base');
  237. if (!($bases instanceof DOMNodeList) || $bases->length === 0) {
  238. $base = $doc->createElement('base');
  239. if ($base === false) {
  240. return $html;
  241. }
  242. $base->setAttribute('href', $href);
  243. $head = null;
  244. $heads = $xpath->evaluate('//head');
  245. if ($heads instanceof DOMNodeList && $heads->length > 0) {
  246. $head = $heads->item(0);
  247. }
  248. if ($head instanceof DOMElement) {
  249. $head->insertBefore($base, $head->firstChild);
  250. } else {
  251. $doc->documentElement->insertBefore($base, $doc->documentElement->firstChild);
  252. }
  253. }
  254. // Save the start of HTML because libxml2 saveHTML() risks scrambling it
  255. $htmlPos = stripos($html, '<html');
  256. $htmlStart = $htmlPos === false || $htmlPos > 512 ? '' : substr($html, 0, $htmlPos);
  257. $html = $doc->saveHTML() ?: $html;
  258. if ($htmlStart !== '' && !str_starts_with($html, $htmlStart)) {
  259. // libxml2 saveHTML() risks removing Unicode BOM and XML declaration,
  260. // which affects future detection of charset encoding, so manually restore it
  261. $htmlPos = stripos($html, '<html');
  262. $html = $htmlPos === false || $htmlPos > 512 ? $html : $htmlStart . substr($html, $htmlPos);
  263. }
  264. return $html;
  265. }
  266. public static function compareURLOrigins(string $url1, string $url2): bool {
  267. $url1 = parse_url(strtolower($url1));
  268. $url2 = parse_url(strtolower($url2));
  269. if ($url1 === false || $url2 === false) {
  270. return false;
  271. }
  272. foreach ([&$url1, &$url2] as &$url) {
  273. $url['port'] ??= match ($url['scheme'] ?? '') {
  274. 'http' => 80,
  275. 'https' => 443,
  276. default => 0,
  277. };
  278. }
  279. return ($url1['scheme'] ?? '') === ($url2['scheme'] ?? '') &&
  280. ($url1['host'] ?? '') === ($url2['host'] ?? '') &&
  281. ($url1['port'] ?? '') === ($url2['port'] ?? '');
  282. }
  283. /**
  284. * Return 0 if values on either side are equal ignoring the HTTP vs HTTPS differences, or 1/-1 if they differ.
  285. */
  286. public static function compareUrlIgnoringHttps(string $url1, string $url2): int {
  287. $normalizeScheme = static fn(string $url): string => preg_replace('#^https?://#i', '//', trim($url)) ?? $url;
  288. return $normalizeScheme($url1) <=> $normalizeScheme($url2);
  289. }
  290. /**
  291. * Returns a value for CURLOPT_RESOLVE as an array, null if no allowed IPs were found, false if the domain failed to resolve.
  292. *
  293. * @return array<string>|null|false
  294. */
  295. public static function getCurlResolveInfo(string $url): array|null|false {
  296. $url = strtolower($url);
  297. $parsed = parse_url($url);
  298. if ($parsed === false) {
  299. return false;
  300. }
  301. $host = $parsed['host'] ?? null;
  302. $scheme = $parsed['scheme'] ?? null;
  303. if ($host === null || $scheme === null) {
  304. return false;
  305. }
  306. if (str_starts_with($host, '[') && str_ends_with($host, ']')) {
  307. if (strlen($host) === 2) {
  308. return false;
  309. }
  310. $host = substr($host, 1, strlen($host) - 2);
  311. }
  312. $internal_host_allowlist = getenv('INTERNAL_HOST_ALLOWLIST');
  313. if (is_string($internal_host_allowlist) && $internal_host_allowlist !== '') {
  314. $internal_host_allowlist = preg_split('/\s+/', $internal_host_allowlist, -1, PREG_SPLIT_NO_EMPTY);
  315. }
  316. if (!is_array($internal_host_allowlist) || empty($internal_host_allowlist)) {
  317. $internal_host_allowlist = FreshRSS_Context::systemConf()->internal_host_allowlist;
  318. }
  319. $port = parse_url($url)['port'] ?? match ($scheme) {
  320. 'http' => 80,
  321. 'https' => 443,
  322. 'socks4' => 1080,
  323. 'socks4a' => 1080,
  324. 'socks5' => 1080,
  325. 'socks5h' => 1080,
  326. default => 0,
  327. };
  328. if (in_array('*', $internal_host_allowlist, true)) {
  329. return []; // Disables SSRF checks entirely (unsafe)
  330. }
  331. $resolve_str = "$host:$port:";
  332. $ips_ok = [];
  333. $ips = [];
  334. $records = [];
  335. if (filter_var($host, FILTER_VALIDATE_IP) !== false) {
  336. $ips[] = $host;
  337. } elseif (isset(self::$resolve_ok[$host])) {
  338. $ips = self::$resolve_ok[$host];
  339. } else {
  340. $records = @dns_get_record($host, DNS_A + DNS_AAAA);
  341. if ($records === false) {
  342. return false;
  343. }
  344. foreach ($records as $record) {
  345. $ip = $record['ip'] ?? $record['ipv6'];
  346. if (is_string($ip)) {
  347. $ips[] = $ip;
  348. }
  349. }
  350. self::$resolve_ok[$host] = $ips;
  351. }
  352. $cidr_allowlist = array_filter($internal_host_allowlist, fn($v, $_) => str_contains($v, '/'), ARRAY_FILTER_USE_BOTH);
  353. foreach ($ips as $ip) {
  354. $allowlist_str = "$ip:$port";
  355. $add_ip = $ip;
  356. if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false) {
  357. $allowlist_str = "[$ip]:$port";
  358. $add_ip = "[$ip]";
  359. }
  360. foreach ($cidr_allowlist as $cidr) {
  361. if (self::checkCIDR($ip, $cidr)) {
  362. $ips_ok[] = $add_ip;
  363. continue 2;
  364. }
  365. }
  366. if (in_array($allowlist_str, $internal_host_allowlist, true) ||
  367. in_array("$host:$port", $internal_host_allowlist, true)) {
  368. $ips_ok[] = $add_ip;
  369. continue;
  370. }
  371. if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) {
  372. continue;
  373. }
  374. // Extra check because the above one might not be enough: https://github.com/php/php-src/issues/16944
  375. // Workaround is available by using `FILTER_FLAG_GLOBAL_RANGE` instead, but that was only added in PHP 8.2, and we need to support PHP 8.1+
  376. foreach (self::PRIVATE_SUBNETS as $cidr) {
  377. if (self::checkCIDR($ip, $cidr)) {
  378. continue 2;
  379. }
  380. }
  381. $ips_ok[] = $add_ip;
  382. }
  383. if (count($ips_ok) > 0) {
  384. if (count($records) > 0 || isset(self::$resolve_ok[$host])) {
  385. $resolve_str .= implode(',', $ips_ok);
  386. return [$resolve_str];
  387. }
  388. if (filter_var($host, FILTER_VALIDATE_IP) !== false) {
  389. // No resolve overrides since the URL only contained an IP, not a domain
  390. return [];
  391. }
  392. }
  393. if (count($ips) === 0) {
  394. return false;
  395. }
  396. return null;
  397. }
  398. /**
  399. * @param non-empty-string $url
  400. * @param string|null $cachePath path to cache file, or `null` to disable caching
  401. * @param string $type {html,ico,json,opml,xml}
  402. * @param array<string,mixed> $attributes May contain user-defined cURL options in `$attributes['curl_params']`
  403. * @param array<int,mixed> $curl_options Internal overrides of cURL options
  404. * @return array{body:string,effective_url:string,redirect_count:int,fail:bool,status:int,error:string}
  405. * `status` is the HTTP response code (e.g. 200, 404), or a custom negative value:
  406. * * `-200` served from local cache;
  407. * * `-429` blocked by active `Retry-After` period;
  408. * * `-500` `curl_init()` failure.
  409. */
  410. public static function httpGet(string $url, ?string $cachePath = null, string $type = 'html', array $attributes = [], array $curl_options = []): array {
  411. if (!\SimplePie\Misc::is_remote_uri($url)) {
  412. Minz_Log::warning('Error fetching content: malformed URL “' . $url . '“');
  413. return ['body' => '', 'effective_url' => '', 'redirect_count' => 0, 'fail' => true, 'status' => -500, 'error' => ''];
  414. }
  415. $limits = FreshRSS_Context::systemConf()->limits;
  416. $feed_timeout = empty($attributes['timeout']) || !is_numeric($attributes['timeout']) ? 0 : intval($attributes['timeout']);
  417. if ($cachePath !== null) {
  418. $cacheMtime = @filemtime($cachePath);
  419. if ($cacheMtime !== false && $cacheMtime > time() - intval($limits['cache_duration'])) {
  420. $body = @file_get_contents($cachePath);
  421. if ($body != false) {
  422. if (FreshRSS_Context::systemConf()->simplepie_syslog_enabled) {
  423. syslog(LOG_DEBUG, 'FreshRSS uses cache for ' . \SimplePie\Misc::url_remove_credentials($url));
  424. }
  425. return ['body' => $body, 'effective_url' => $url, 'redirect_count' => 0, 'fail' => false, 'status' => -200, 'error' => ''];
  426. }
  427. }
  428. }
  429. if (rand(0, 30) === 1) { // Remove old cache once in a while
  430. cleanCache(CLEANCACHE_HOURS);
  431. }
  432. $accept = '';
  433. $proxy = is_string(FreshRSS_Context::systemConf()->curl_options[CURLOPT_PROXY] ?? null) ? FreshRSS_Context::systemConf()->curl_options[CURLOPT_PROXY] : '';
  434. $proxy_type = is_int(FreshRSS_Context::systemConf()->curl_options[CURLOPT_PROXYTYPE] ?? null) ?
  435. FreshRSS_Context::systemConf()->curl_options[CURLOPT_PROXYTYPE] : 0;
  436. $options = []; // User-defined cURL options
  437. if (is_array($attributes['curl_params'] ?? null)) {
  438. $options = self::sanitizeCurlParams($attributes['curl_params']);
  439. $proxy = is_string($options[CURLOPT_PROXY] ?? null) ? $options[CURLOPT_PROXY] : $proxy;
  440. $proxy_type = is_int($options[CURLOPT_PROXYTYPE] ?? null) ? $options[CURLOPT_PROXYTYPE] : $proxy_type;
  441. if (is_array($options[CURLOPT_HTTPHEADER] ?? null)) {
  442. // Add Accept header if it is not set
  443. if (preg_grep('/^Accept\\s*:/i', $options[CURLOPT_HTTPHEADER]) === false) {
  444. $options[CURLOPT_HTTPHEADER][] = 'Accept: ' . $accept;
  445. }
  446. }
  447. }
  448. $proxy = is_string($curl_options[CURLOPT_PROXY] ?? null) ? $curl_options[CURLOPT_PROXY] : $proxy;
  449. $proxy_type = is_int($curl_options[CURLOPT_PROXYTYPE] ?? null) ? $curl_options[CURLOPT_PROXYTYPE] : $proxy_type;
  450. if (($retryAfter = FreshRSS_http_Util::getRetryAfter($url, $proxy)) > 0) {
  451. Minz_Log::warning('For that domain, will first retry after ' . date('c', $retryAfter) . '. ' . \SimplePie\Misc::url_remove_credentials($url));
  452. return ['body' => '', 'effective_url' => $url, 'redirect_count' => 0, 'fail' => true, 'status' => -429, 'error' => ''];
  453. }
  454. if (FreshRSS_Context::systemConf()->simplepie_syslog_enabled) {
  455. syslog(LOG_INFO, 'FreshRSS GET ' . $type . ' ' . \SimplePie\Misc::url_remove_credentials($url));
  456. }
  457. switch ($type) {
  458. case 'json':
  459. $accept = 'application/json,application/feed+json,application/javascript;q=0.9,text/javascript;q=0.8,*/*;q=0.7';
  460. break;
  461. case 'opml':
  462. $accept = 'text/x-opml,text/xml;q=0.9,application/xml;q=0.9,*/*;q=0.8';
  463. break;
  464. case 'xml':
  465. $accept = 'application/xml,application/xhtml+xml,text/xml;q=0.9,*/*;q=0.8';
  466. break;
  467. case 'ico':
  468. $accept = 'image/x-icon,image/vnd.microsoft.icon,image/ico,image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.1';
  469. break;
  470. case 'html':
  471. default:
  472. $accept = 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8';
  473. break;
  474. }
  475. $original_url = $url;
  476. $fail = false;
  477. $redirs = 0;
  478. $max_redirs = $curl_options[CURLOPT_MAXREDIRS] ?? $options[CURLOPT_MAXREDIRS] ?? FreshRSS_Context::systemConf()->curl_options[CURLOPT_MAXREDIRS] ?? null;
  479. if (!is_int($max_redirs)) {
  480. $max_redirs = 4;
  481. }
  482. while (true) {
  483. $url = is_string($url) ? $url : '';
  484. $resolve = [];
  485. if ($proxy === '') {
  486. $resolve = self::getCurlResolveInfo($url);
  487. if ($resolve === null) {
  488. Minz_Log::warning('Fetching this URL is not allowed, because the host’s IP is not in the allowlist [' .
  489. \SimplePie\Misc::url_remove_credentials($url) . ']');
  490. return ['body' => '', 'effective_url' => '', 'redirect_count' => 0, 'fail' => true, 'status' => -500, 'error' => ''];
  491. } elseif ($resolve === false) {
  492. return ['body' => '', 'effective_url' => '', 'redirect_count' => 0, 'fail' => true, 'status' => -500, 'error' => ''];
  493. }
  494. if (!empty($resolve)) {
  495. $curl_options[CURLOPT_RESOLVE] = $resolve; // Prevent DNS rebinding
  496. }
  497. } else {
  498. defined('CURLPROXY_HTTPS') or define('CURLPROXY_HTTPS', 2); // Compatibility cURL 7.51
  499. $proxy_scheme = match ($proxy_type) {
  500. CURLPROXY_HTTP => 'http',
  501. CURLPROXY_HTTPS => 'https',
  502. CURLPROXY_SOCKS4 => 'socks4',
  503. CURLPROXY_SOCKS4A => 'socks4a',
  504. CURLPROXY_SOCKS5 => 'socks5',
  505. CURLPROXY_SOCKS5_HOSTNAME => 'socks5h',
  506. default => null,
  507. };
  508. if ($proxy_scheme === null) {
  509. // Unsupported proxy type
  510. return ['body' => '', 'effective_url' => '', 'redirect_count' => 0, 'fail' => true, 'status' => -500, 'error' => ''];
  511. }
  512. $proxy_url = "$proxy_scheme://$proxy"; // CURLOPT_PROXY ($proxy) is formatted as user:pass@hostname:port, with the part before @ being optional
  513. $resolve = self::getCurlResolveInfo($proxy_url);
  514. if ($resolve === null) {
  515. Minz_Log::warning('Failed to fetch this URL, because the proxy’s IP is not in the allowlist [' .
  516. \SimplePie\Misc::url_remove_credentials($url) . '] [' .
  517. \SimplePie\Misc::url_remove_credentials($proxy_url) . ']');
  518. return ['body' => '', 'effective_url' => '', 'redirect_count' => 0, 'fail' => true, 'status' => -500, 'error' => ''];
  519. } elseif ($resolve === false) {
  520. return ['body' => '', 'effective_url' => '', 'redirect_count' => 0, 'fail' => true, 'status' => -500, 'error' => ''];
  521. }
  522. if (!empty($resolve)) {
  523. // Only for the proxy domain, socks4a and socks5h DNS queries will be passed through the proxy.
  524. // For the other proxy protocols, note that IPs for internal domains can be leaked,
  525. // since the domain is resolved outside of the proxy.
  526. $curl_options[CURLOPT_RESOLVE] = $resolve;
  527. }
  528. }
  529. // TODO: Implement HTTP 1.1 conditional GET If-Modified-Since
  530. $ch = curl_init();
  531. if ($ch === false || $url === '') {
  532. return ['body' => '', 'effective_url' => '', 'redirect_count' => 0, 'fail' => true, 'status' => -500, 'error' => ''];
  533. }
  534. curl_setopt_array($ch, [
  535. CURLOPT_URL => $url,
  536. CURLOPT_HTTPHEADER => ['Accept: ' . $accept],
  537. CURLOPT_USERAGENT => FRESHRSS_USERAGENT,
  538. CURLOPT_CONNECTTIMEOUT => $feed_timeout > 0 ? $feed_timeout : $limits['timeout'],
  539. CURLOPT_TIMEOUT => $feed_timeout > 0 ? $feed_timeout : $limits['timeout'],
  540. CURLOPT_RETURNTRANSFER => true,
  541. CURLOPT_ACCEPT_ENCODING => '', //Enable all encodings
  542. //CURLOPT_VERBOSE => 1, // To debug sent HTTP headers
  543. ]);
  544. curl_setopt_array($ch, $options);
  545. curl_setopt_array($ch, FreshRSS_Context::systemConf()->curl_options);
  546. $responseHeaders = '';
  547. curl_setopt($ch, CURLOPT_HEADERFUNCTION, function (\CurlHandle $ch, string $header) use (&$responseHeaders) {
  548. if (trim($header) !== '') { // Skip e.g. separation with trailer headers
  549. $responseHeaders .= $header;
  550. }
  551. return strlen($header);
  552. });
  553. if (isset($attributes['ssl_verify'])) {
  554. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, empty($attributes['ssl_verify']) ? 0 : 2);
  555. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (bool)$attributes['ssl_verify']);
  556. if (empty($attributes['ssl_verify'])) {
  557. curl_setopt($ch, CURLOPT_SSL_CIPHER_LIST, 'DEFAULT@SECLEVEL=1');
  558. }
  559. }
  560. if (defined('CURLOPT_PROTOCOLS_STR') && is_int(CURLOPT_PROTOCOLS_STR)) {
  561. $curl_options[CURLOPT_PROTOCOLS_STR] = 'http,https';
  562. if (defined('CURLOPT_REDIR_PROTOCOLS_STR') && is_int(CURLOPT_REDIR_PROTOCOLS_STR)) {
  563. $curl_options[CURLOPT_REDIR_PROTOCOLS_STR] = 'http,https';
  564. }
  565. } elseif (defined('CURLPROTO_HTTP') && defined('CURLPROTO_HTTPS')) {
  566. // Legacy PHP 8.2-
  567. if (defined('CURLOPT_PROTOCOLS')) {
  568. $curl_options[CURLOPT_PROTOCOLS] = CURLPROTO_HTTP | CURLPROTO_HTTPS;
  569. }
  570. if (defined('CURLOPT_REDIR_PROTOCOLS')) {
  571. $curl_options[CURLOPT_REDIR_PROTOCOLS] = CURLPROTO_HTTP | CURLPROTO_HTTPS;
  572. }
  573. }
  574. curl_setopt_array($ch, $curl_options);
  575. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); // We handle HTTP redirections manually for security
  576. $body = curl_exec($ch);
  577. $c_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  578. $c_content_type = '' . curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
  579. $c_effective_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
  580. $c_error = curl_error($ch);
  581. $headers = [];
  582. if ($body !== false) {
  583. $responseHeaders .= "\r\n";
  584. $responseHeaders = \SimplePie\HTTP\Parser::prepareHeaders($responseHeaders);
  585. $parser = new \SimplePie\HTTP\Parser($responseHeaders);
  586. if ($parser->parse()) {
  587. $headers = $parser->headers;
  588. }
  589. }
  590. if (in_array($c_status, [301, 302, 303, 307, 308], true)) {
  591. // Handle the redirect by making another request
  592. $location = \SimplePie\Misc::absolutize_url($headers['location'] ?? $url, $url);
  593. if ($location === false || !\SimplePie\Misc::is_remote_uri($location)) {
  594. Minz_Log::warning('Invalid redirect location: malformed URL “' . ($headers['location'] ?? $url) . '“');
  595. break;
  596. }
  597. if (!self::compareURLOrigins($url, $location)) {
  598. unset($curl_options[CURLOPT_COOKIE]);
  599. unset($curl_options[CURLOPT_USERPWD]);
  600. unset($options[CURLOPT_COOKIE]);
  601. unset($options[CURLOPT_USERPWD]);
  602. if (is_array($options[CURLOPT_HTTPHEADER] ?? null)) {
  603. $options[CURLOPT_HTTPHEADER] = array_filter($options[CURLOPT_HTTPHEADER], fn(mixed $header): bool =>
  604. is_string($header) && !preg_match('/^(Cookie|Authorization)\\s*:/i', $header));
  605. }
  606. if (is_array($curl_options[CURLOPT_HTTPHEADER] ?? null)) {
  607. $curl_options[CURLOPT_HTTPHEADER] = array_filter($curl_options[CURLOPT_HTTPHEADER], fn(mixed $header): bool =>
  608. is_string($header) && !preg_match('/^(Cookie|Authorization)\\s*:/i', $header));
  609. }
  610. }
  611. if ($max_redirs >= 0) {
  612. $redirs++;
  613. }
  614. if ($redirs > $max_redirs) {
  615. Minz_Log::warning('Error fetching content: Too many redirects were hit [' . \SimplePie\Misc::url_remove_credentials($original_url) . ']');
  616. break;
  617. }
  618. if ((isset($options[CURLOPT_POST]) || isset($curl_options[CURLOPT_POST])) &&
  619. in_array($c_status, [301, 302, 303], true)) { // Not for 307 and 308, which must not change the HTTP method
  620. unset($curl_options[CURLOPT_POST]);
  621. unset($curl_options[CURLOPT_POSTFIELDS]);
  622. unset($options[CURLOPT_POST]);
  623. unset($options[CURLOPT_POSTFIELDS]);
  624. if (is_array($options[CURLOPT_HTTPHEADER] ?? null)) {
  625. $options[CURLOPT_HTTPHEADER] = array_filter($options[CURLOPT_HTTPHEADER], fn(mixed $header): bool =>
  626. is_string($header) && !str_starts_with(strtolower(trim($header)), 'content-type:'));
  627. }
  628. if (is_array($curl_options[CURLOPT_HTTPHEADER] ?? null)) {
  629. $curl_options[CURLOPT_HTTPHEADER] = array_filter($curl_options[CURLOPT_HTTPHEADER], fn(mixed $header): bool =>
  630. is_string($header) && !str_starts_with(strtolower(trim($header)), 'content-type:'));
  631. }
  632. }
  633. $url = $location;
  634. continue;
  635. }
  636. $fail = $c_status != 200 || $c_error != '' || $body === false;
  637. if ($fail) {
  638. $body = '';
  639. Minz_Log::warning('Error fetching content: HTTP code ' . $c_status . ': ' . $c_error . ' ' . $url);
  640. if (in_array($c_status, [429, 503], true)) {
  641. $retryAfter = FreshRSS_http_Util::setRetryAfter($url, $proxy, $headers['retry-after'] ?? '');
  642. if ($c_status === 429) {
  643. $errorMessage = 'HTTP 429 Too Many Requests! [' . \SimplePie\Misc::url_remove_credentials($url) . ']';
  644. } elseif ($c_status === 503) {
  645. $errorMessage = 'HTTP 503 Service Unavailable! [' . \SimplePie\Misc::url_remove_credentials($url) . ']';
  646. }
  647. if ($retryAfter > 0) {
  648. $errorMessage .= ' We may retry after ' . date('c', $retryAfter);
  649. }
  650. }
  651. } elseif (!is_string($body) || strlen($body) === 0) { // TODO: Implement HTTP 410 Gone
  652. $body = '';
  653. } else {
  654. if (in_array($type, ['html', 'json', 'opml', 'xml'], true)) {
  655. $body = trim($body, " \n\r\t\v"); // Do not trim \x00 to avoid breaking a BOM
  656. }
  657. if (in_array($type, ['html', 'xml', 'opml'], true)) {
  658. $body = self::enforceHttpEncoding($body, $c_content_type);
  659. }
  660. if (in_array($type, ['html'], true)) {
  661. if (stripos($c_content_type, 'text/plain') !== false) {
  662. // Plain text to be displayed as preformatted text. Prefixed with UTF-8 BOM
  663. $body = "\xEF\xBB\xBF" . '<pre class="text-plain">' . htmlspecialchars($body, ENT_NOQUOTES, 'UTF-8') . '</pre>';
  664. } else {
  665. $body = self::enforceHtmlBase($body, $c_effective_url);
  666. }
  667. }
  668. }
  669. break;
  670. }
  671. if ($cachePath !== null && file_put_contents($cachePath, $body) === false) {
  672. Minz_Log::warning("Error saving cache for $url");
  673. }
  674. return ['body' => is_string($body) ? $body : '', 'effective_url' => $c_effective_url, 'redirect_count' => $redirs,
  675. 'fail' => $fail, 'status' => $c_status, 'error' => $c_error];
  676. }
  677. /**
  678. * Converts an IP (v4 or v6) to a binary representation using inet_pton
  679. *
  680. * @param string $ip the IP to convert
  681. * @return string a binary representation of the specified IP
  682. */
  683. private static function ipToBits(string $ip): string {
  684. $binaryip = '';
  685. foreach (str_split(inet_pton($ip) ?: '') as $char) {
  686. $binaryip .= str_pad(decbin(ord($char)), 8, '0', STR_PAD_LEFT);
  687. }
  688. return $binaryip;
  689. }
  690. /**
  691. * Check if an ip belongs to the provided range (in CIDR format)
  692. *
  693. * @param string $ip the IP that we want to verify (ex: 192.168.16.1)
  694. * @param string $range the range to check against (ex: 192.168.16.0/24)
  695. * @return bool true if the IP is in the range, otherwise false
  696. */
  697. private static function checkCIDR(string $ip, string $range): bool {
  698. $binary_ip = self::ipToBits($ip);
  699. if ($binary_ip === '') {
  700. return false;
  701. }
  702. $split = explode('/', $range);
  703. $subnet = $split[0] ?? '';
  704. if ($subnet == '') {
  705. return false;
  706. }
  707. $binary_subnet = self::ipToBits($subnet);
  708. if ($binary_subnet === '') {
  709. return false;
  710. }
  711. if (strlen($binary_ip) !== strlen($binary_subnet)) {
  712. return false; // Do not mix IPv4 and IPv6
  713. }
  714. $max_mask_bits = str_contains($ip, ':') ? 128 : 32;
  715. // A range without a subnet is a single address, like Apache’s mod_remoteip accepts
  716. $mask_bits_str = $split[1] ?? (string)$max_mask_bits;
  717. if (!ctype_digit($mask_bits_str)) {
  718. return false;
  719. }
  720. $mask_bits = (int)$mask_bits_str;
  721. if ($mask_bits < 0 || $mask_bits > $max_mask_bits) {
  722. return false; // Reject invalid mask bits lengths
  723. }
  724. if ($mask_bits === 0) {
  725. return true;
  726. }
  727. $ip_net_bits = substr($binary_ip, 0, $mask_bits);
  728. $subnet_bits = substr($binary_subnet, 0, $mask_bits);
  729. return $ip_net_bits === $subnet_bits;
  730. }
  731. /**
  732. * Check if the client (e.g. last proxy) is allowed to send unsafe headers.
  733. * This uses the `TRUSTED_PROXY` environment variable or the `trusted_sources` configuration option to get an array of the authorized ranges,
  734. * The connection IP is obtained from the `CONN_REMOTE_ADDR`
  735. * (if available, to be robust even when using Apache mod_remoteip) or `REMOTE_ADDR` environment variables.
  736. * @return bool true if the sender’s IP is in one of the ranges defined in the configuration, else false
  737. */
  738. public static function checkTrustedIP(): bool {
  739. if (!FreshRSS_Context::hasSystemConf()) {
  740. return false;
  741. }
  742. $remoteIp = Minz_Request::connectionRemoteAddress();
  743. if ($remoteIp === '') {
  744. return false;
  745. }
  746. $trusted = getenv('TRUSTED_PROXY');
  747. if ($trusted != 0 && is_string($trusted)) {
  748. $trusted = preg_split('/\s+/', $trusted, -1, PREG_SPLIT_NO_EMPTY);
  749. }
  750. if (!is_array($trusted) || empty($trusted)) {
  751. $trusted = FreshRSS_Context::systemConf()->trusted_sources;
  752. }
  753. foreach ($trusted as $cidr) {
  754. if (self::checkCIDR($remoteIp, $cidr)) {
  755. return true;
  756. }
  757. }
  758. return false;
  759. }
  760. public static function httpAuthUser(bool $onlyTrusted = true): string {
  761. $auths = array_unique(array_filter(
  762. array_intersect_key($_SERVER, ['REMOTE_USER' => '', 'REDIRECT_REMOTE_USER' => '', 'HTTP_REMOTE_USER' => '', 'HTTP_X_WEBAUTH_USER' => '']),
  763. fn($value) => is_string($value) && $value !== ''
  764. ));
  765. if (count($auths) > 1) {
  766. Minz_Log::warning('Multiple HTTP authentication headers!');
  767. return '';
  768. }
  769. if (!empty($_SERVER['REMOTE_USER']) && is_string($_SERVER['REMOTE_USER'])) {
  770. return $_SERVER['REMOTE_USER'];
  771. }
  772. if (!empty($_SERVER['REDIRECT_REMOTE_USER']) && is_string($_SERVER['REDIRECT_REMOTE_USER'])) {
  773. return $_SERVER['REDIRECT_REMOTE_USER'];
  774. }
  775. if (!$onlyTrusted || self::checkTrustedIP()) {
  776. if (!empty($_SERVER['HTTP_REMOTE_USER']) && is_string($_SERVER['HTTP_REMOTE_USER'])) {
  777. return $_SERVER['HTTP_REMOTE_USER'];
  778. }
  779. if (!empty($_SERVER['HTTP_X_WEBAUTH_USER']) && is_string($_SERVER['HTTP_X_WEBAUTH_USER'])) {
  780. return $_SERVER['HTTP_X_WEBAUTH_USER'];
  781. }
  782. }
  783. return '';
  784. }
  785. }