4
0

httpUtil.php 32 KB

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