4
0

httpUtil.php 36 KB

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