'', 'ip' => '']; } if (in_array($bare, self::METADATA_HOSTS, true)) { /* translators: %s: host name */ return ['reason' => sprintf(__('%s is a cloud metadata service, not a vector store.', 'aipcf-ai-provider-for-cloudflare'), $host), 'ip' => '']; } $literal = filter_var($bare, FILTER_VALIDATE_IP) !== false; $ips = $literal ? [$bare] : self::resolve($bare); foreach ($ips as $ip) { if (self::isLinkLocal($ip)) { /* translators: 1: host name, 2: IP address */ return ['reason' => sprintf(__('%1$s resolves to the link-local address %2$s (where cloud metadata services live), which a vector store never uses.', 'aipcf-ai-provider-for-cloudflare'), $host, $ip), 'ip' => '']; } } return ['reason' => '', 'ip' => $literal ? '' : (string) ($ips[0] ?? '')]; } /** * Why the host must not be used, or '' when it may. */ public static function blockedReason(string $host): string { return self::check($host)['reason']; } /** * IPv4 and IPv6 addresses of a name. * * @return list */ private static function resolve(string $name): array { $ips = gethostbynamel($name) ?: []; if (function_exists('dns_get_record')) { $aaaa = @dns_get_record($name, DNS_AAAA); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- a failed lookup just means no AAAA records foreach (is_array($aaaa) ? $aaaa : [] as $r) { if (!empty($r['ipv6'])) { $ips[] = (string) $r['ipv6']; } } } return array_values(array_unique(array_map('strval', $ips))); } /** * Link-local in any spelling: 169.254.0.0/16, fe80::/10, AWS's fd00:ec2::/32, and * IPv4 addresses wrapped in IPv6 (::ffff:169.254.169.254, NAT64 64:ff9b::/96). */ public static function isLinkLocal(string $ip): bool { $bin = @inet_pton(trim($ip, '[]')); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- invalid input returns false if ($bin === false) { return false; } if (strlen($bin) === 16) { $mapped = substr($bin, 0, 12) === str_repeat("\0", 10) . "\xff\xff"; $nat64 = substr($bin, 0, 12) === "\x00\x64\xff\x9b" . str_repeat("\0", 8); if ($mapped || $nat64) { $bin = substr($bin, 12); } else { $b0 = ord($bin[0]); $b1 = ord($bin[1]); return ($b0 === 0xfe && ($b1 & 0xc0) === 0x80) || substr($bin, 0, 4) === "\xfd\x00\x0e\xc2"; } } return ord($bin[0]) === 169 && ord($bin[1]) === 254; } public static function isLocal(string $host): bool { $host = strtolower(trim($host, '[]')); return in_array($host, ['localhost', '127.0.0.1', '::1'], true) || strpos($host, '127.') === 0 || substr($host, -10) === '.localhost'; } }