тип прокси для cURL. */ private const TYPES = [ 'http' => CURLPROXY_HTTP, 'https' => CURLPROXY_HTTPS, 'socks4' => CURLPROXY_SOCKS4, 'socks4a' => CURLPROXY_SOCKS4A, 'socks5' => CURLPROXY_SOCKS5, 'socks5h' => CURLPROXY_SOCKS5_HOSTNAME, ]; /** * @param string $host адрес без схемы и креденшелов * @param list $noProxy хосты, которые прокси не трогает */ private function __construct( private readonly string $host, private readonly int $port, private readonly int $type, private readonly string $user = '', private readonly string $password = '', private readonly array $noProxy = [], private readonly bool $direct = false, ) { } /** * Ходить напрямую, не глядя на http_proxy/HTTPS_PROXY. Так AI_PROXY=none * спасает от прокси в окружении, которое мешает локальной модели. */ public static function direct(): self { return new self('', 0, CURLPROXY_HTTP, direct: true); } /** * Прокси из окружения: AI_PROXY и связанные с ним переменные. * null — переменная не задана, поведение cURL по умолчанию. * * @throws \InvalidArgumentException если адрес некорректен */ public static function fromEnv(): ?self { return self::fromString( (string) Env::get('AI_PROXY', ''), (string) Env::get('AI_PROXY_USER', ''), (string) Env::get('AI_PROXY_PASS', ''), (string) Env::get('AI_NO_PROXY', ''), ); } /** * Прокси из настроек клиента (Config::ENV: proxy, proxy_user, proxy_pass, * no_proxy). Пустое значение — null, как у fromEnv(). * * @throws \InvalidArgumentException если адрес некорректен */ public static function fromConfig(Config $config): ?self { return self::fromString( $config->string('proxy', ''), $config->string('proxy_user', ''), $config->string('proxy_pass', ''), $config->string('no_proxy', ''), ); } /** * Собрать прокси из строки. Пустая строка — null (не задан), * none/direct/off/no — direct(). * * @throws \InvalidArgumentException если адрес некорректен */ public static function fromString( string $address, string $user = '', string $password = '', string $noProxy = '', ): ?self { $address = trim($address); if ($address === '') { return null; } if (in_array(strtolower($address), self::DIRECT_WORDS, true)) { return self::direct(); } if (!str_contains($address, '://')) { $address = 'http://' . $address; } $parts = parse_url($address); if ($parts === false || !isset($parts['scheme'], $parts['host'])) { throw new \InvalidArgumentException( 'Некорректный адрес прокси: "' . $address . '". Пример: http://proxy.local:3128' ); } $scheme = strtolower($parts['scheme']); if (!isset(self::TYPES[$scheme])) { throw new \InvalidArgumentException( 'Неизвестный тип прокси: ' . $scheme . '. Поддерживаются: ' . implode(', ', array_keys(self::TYPES)) . '.' ); } $path = (string) ($parts['path'] ?? ''); if ($path !== '' && $path !== '/') { throw new \InvalidArgumentException( 'В адресе прокси не должно быть пути: "' . $address . '". Нужны только хост и порт.' ); } if (isset($parts['query']) || isset($parts['fragment'])) { throw new \InvalidArgumentException( 'В адресе прокси не должно быть параметров: "' . $address . '". Нужны только хост и порт.' ); } if (!isset($parts['port'])) { throw new \InvalidArgumentException( 'В адресе прокси не указан порт: "' . $address . '". Пример: http://proxy.local:3128' ); } return new self( host: (string) $parts['host'], port: (int) $parts['port'], type: self::TYPES[$scheme], // Явные настройки важнее креденшелов из URL. user: $user !== '' ? $user : rawurldecode((string) ($parts['user'] ?? '')), password: $password !== '' ? $password : rawurldecode((string) ($parts['pass'] ?? '')), noProxy: self::parseNoProxy($noProxy), ); } /** * @return list */ private static function parseNoProxy(string $list): array { $entries = array_map('trim', explode(',', $list)); return array_values(array_filter($entries, static fn (string $entry): bool => $entry !== '')); } /** * Идёт ли запрос на этот URL через прокси. */ public function appliesTo(string $url): bool { if ($this->direct) { return false; } if ($this->noProxy === []) { return true; } $parts = parse_url($url); $host = strtolower(trim((string) ($parts['host'] ?? ''), '[]')); if ($host === '') { return true; } $scheme = strtolower((string) ($parts['scheme'] ?? 'http')); $port = (int) ($parts['port'] ?? ($scheme === 'https' ? 443 : 80)); foreach ($this->noProxy as $entry) { if (self::matchesNoProxy($host, $port, $entry)) { return false; } } return true; } /** * Запись NO_PROXY: `*` — всё, `example.com` — сам хост и поддомены, * `.example.com` и `*.example.com` — то же, `example.com:8080` — только * этот порт. */ private static function matchesNoProxy(string $host, int $port, string $entry): bool { $entry = strtolower(trim($entry)); if ($entry === '') { return false; } if ($entry === '*') { return true; } $entryPort = null; if (preg_match('/^(\[[^\]]+\]|[^:]+):(\d+)$/', $entry, $match) === 1) { $entry = $match[1]; $entryPort = (int) $match[2]; } if ($entryPort !== null && $entryPort !== $port) { return false; } $entry = trim(ltrim($entry, '.'), '[]'); if (str_starts_with($entry, '*.')) { $entry = substr($entry, 2); } if ($entry === '') { return false; } return $host === $entry || str_ends_with($host, '.' . $entry); } public function isDirect(): bool { return $this->direct; } /** * Параметры cURL для этого запроса. Целевой хост из NO_PROXY получает * CURLOPT_PROXY = '' — соединение напрямую, без прокси из окружения. * * @return array */ public function curlOptions(string $url): array { if (!$this->appliesTo($url)) { // Пустая строка отключает и прокси из окружения: решение явное. return [CURLOPT_PROXY => '']; } $options = [ CURLOPT_PROXY => $this->host, CURLOPT_PROXYPORT => $this->port, CURLOPT_PROXYTYPE => $this->type, ]; if ($this->user !== '' || $this->password !== '') { $options[CURLOPT_PROXYUSERPWD] = $this->user . ':' . $this->password; } // Пустой список — тоже важно: иначе NO_PROXY из окружения мог бы // молча отменить явно заданный прокси. $options[CURLOPT_NOPROXY] = implode(',', $this->noProxy); return $options; } /** * Человеческое описание для логов и примеров. Пароль не показывается. */ public function describe(): string { if ($this->direct) { return 'напрямую (прокси из окружения игнорируется)'; } $scheme = array_search($this->type, self::TYPES, true); $auth = $this->user === '' ? '' : $this->user . ':***@'; return ($scheme === false ? 'http' : (string) $scheme) . '://' . $auth . $this->host . ':' . $this->port . ($this->noProxy === [] ? '' : ' (кроме ' . implode(', ', $this->noProxy) . ')'); } }