4
0

httpUtil.php 33 KB

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