4
0

httpUtil.php 28 KB

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