master
ブランチ master
LittleBeast / src / Std / Lib / Curl.php
27.4 KB、860行 生 Blame 履歴
1<?php
2/*************************************************************
3# 076 License
4
5Copyright (c) テクニカル諏訪子
6
7Permission is hereby granted to any person obtaining a copy of the software
8Little Beast (the "Software") to use, modify, merge, copy, publish, distribute,
9sublicense, and/or sell copies of the Software, subject to the following conditions:
10
11 1. **Origin Attribution**:
12 - You must not misrepresent the origin of the Software; you must not claim
13 you created the original Software.
14 - If the Software is used in a product, you must either:
15 a. Provide clear attribution in the product's documentation, user interface,
16 or other visible areas, **OR**
17 b. Pay the original developers a fee they specify in writing.
18 2. **Usage Restriction**:
19 - The Software, or any derivative works, dependencies, or libraries
20 incorporating it, must not be used for censorship or to suppress freedom of
21 speech, expression, or creativity. Prohibited uses include, but are not
22 limited to:
23 - Censorship of so-called "hate speech", visuals, non-mainstream opinions,
24 ideas, or objective reality.
25 - Tools or systems designed to restrict access to information or
26 artistic works.
27 3. **Notice Preservation**:
28 - This license and the above copyright notice must remain intact in all copies
29 of the source code.
30
31THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
32INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
33PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
34HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
35CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
36OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
37 */
38namespace Std\Lib;
39
40use Result;
41use Uri\Rfc3986\Uri;
42
43/**
44 * php_curlへの依存を排除するための独自のCURL実装
45 */
46class Curl {
47 // リクエスト関連のプロパティ
48 private string $url = '';
49 private string $method = 'GET';
50 private int $timeout = 30;
51 private array $headers = [];
52 private array $cookies = [];
53 private array $postFields = [];
54 private string $postRaw = '';
55 private string $userAgent = 'LittleBeast/1.0';
56 private bool $followRedirects = true;
57 private int $maxRedirects = 5;
58 private bool $verbose = false;
59 private $stderr = null;
60 private string $caInfoPath = '';
61 private bool $verifySSL = true;
62 private string $username = '';
63 private string $password = '';
64 private string $token = '';
65 private string $referer = '';
66 private string $authType = '';
67 private int $maxResponseSize = 10485760; // 10 MiB
68 private bool $blockPrivate = true;
69
70 // デバッグ用
71 private string $DEBUG_REQ_HDR = '';
72
73 // レスポンス関連のプロパティ
74 private array $responseHeaders = [];
75 private string $responseBody = '';
76 private int $responseCode = 0;
77 private string $responseError = '';
78 private array $info = [];
79
80 /**
81 * コンストラクタ
82 *
83 * @param string|null $url リクエスト先のURL
84 */
85 public function __construct(?string $url = null) {
86 if (!CURL_ENABLED) return;
87 if ($url !== null) {
88 $this->url = $url;
89 }
90 }
91
92 /**
93 * リクエスト先のURLを設定する
94 *
95 * @param string $url リクエスト先のURL
96 * @return Curl このインスタンス(メソッドチェーン用)
97 */
98 public function setUrl(string $url): Curl {
99 $this->url = $url;
100 return $this;
101 }
102
103 /**
104 * リクエストメソッドを設定する
105 *
106 * @param string $method GE又はPOST等のHTTPメソッド
107 * @return Curl このインスタンス(メソッドチェーン用)
108 */
109 public function setMethod(string $method): Curl {
110 $this->method = strtoupper($method);
111 return $this;
112 }
113
114 /**
115 * リクエストのタイムアウト秒数を設定する
116 *
117 * @param int $seconds タイムアウト秒数
118 * @return Curl このインスタンス(メソッドチェーン用)
119 */
120 public function setTimeout(int $seconds): Curl {
121 $this->timeout = (int)$seconds;
122 return $this;
123 }
124
125 /**
126 * リクエストヘッダーを設定する
127 *
128 * @param array $headers リクエストヘッダーの配列
129 * @return Curl このインスタンス(メソッドチェーン用)
130 */
131 public function setHeaders(array $headers): Curl {
132 $this->headers = $headers;
133 return $this;
134 }
135
136 /**
137 * 単一のヘッダーを追加する
138 *
139 * @param string $name ヘッダー名
140 * @param mixed $value ヘッダー値
141 * @return Curl このインスタンス(メソッドチェーン用)
142 */
143 public function addHeader(string $name, mixed $value): Curl {
144 $this->headers[$name] = $value;
145 return $this;
146 }
147
148 /**
149 * リクエストのクッキーを設定する
150 *
151 * @param array $cookies クッキーの配列
152 * @return Curl このインスタンス(メソッドチェーン用)
153 */
154 public function setCookies(array $cookies): Curl {
155 $this->cookies = $cookies;
156 return $this;
157 }
158
159 /**
160 * 単一のクッキーを追加する
161 *
162 * @param string $name クッキー名
163 * @param mixed $value クッキー値
164 * @return Curl このインスタンス(メソッドチェーン用)
165 */
166 public function addCookie(string $name, mixed $value): Curl {
167 $this->cookies[$name] = $value;
168 return $this;
169 }
170
171 /**
172 * POSTフィールドを設定する
173 *
174 * @param array $fields POSTデータの配列
175 * @return Curl このインスタンス(メソッドチェーン用)
176 */
177 public function setPostFields(array $fields): Curl {
178 $this->postFields = $fields;
179 return $this;
180 }
181
182 /**
183 * 生のPOSTデータを設定する
184 *
185 * @param string $data 生のPOSTデータ
186 * @return Curl このインスタンス(メソッドチェーン用)
187 */
188 public function setPostRaw(string $data): Curl {
189 $this->postRaw = $data;
190 return $this;
191 }
192
193 /**
194 * ユーザーエージェントを設定する
195 *
196 * @param string $userAgent カスタムユーザーエージェント
197 * @return Curl このインスタンス(メソッドチェーン用)
198 */
199 public function setUserAgent(string $userAgent): Curl {
200 $this->userAgent = $userAgent;
201 return $this;
202 }
203
204 /**
205 * リダイレクトを追跡するかどうかを設定する
206 *
207 * @param bool $follow 追跡するかどうか(デフォルトはtrue)
208 * @return Curl このインスタンス(メソッドチェーン用)
209 */
210 public function setFollowRedirects(bool $follow): Curl {
211 $this->followRedirects = (bool)$follow;
212 return $this;
213 }
214
215 /**
216 * 追跡するリダイレクトの最大数を設定する
217 *
218 * @param int $max リダイレクトの最大数
219 * @return Curl このインスタンス(メソッドチェーン用)
220 */
221 public function setMaxRedirects(int $max): Curl {
222 $this->maxRedirects = (int)$max;
223 return $this;
224 }
225
226 /**
227 * SSL証明書を検証するかどうかを設定する
228 *
229 * @param bool $verify SSL検証を行うかどうか(デフォルトはtrue)
230 * @return Curl このインスタンス(メソッドチェーン用)
231 */
232 public function setVerifySSL(bool $verify): Curl {
233 $this->verifySSL = (bool)$verify;
234 return $this;
235 }
236
237 /**
238 * 基本認証の資格情報を設定する
239 *
240 * @param string $username ユーザー名
241 * @param string $password パスワード
242 * @return Curl このインスタンス(メソッドチェーン用)
243 */
244 public function setBasicAuth(string $username = '', string $password = ''): Curl {
245 if ($username !== '') $this->username = $username;
246 if ($password !== '') $this->password = $password;
247 $this->authType = 'Basic';
248 return $this;
249 }
250
251 /**
252 * トークン認証の資格情報を設定する
253 *
254 * @param string $token セッショントークン
255 * @return Curl このインスタンス(メソッドチェーン用)
256 */
257 public function setBearerAuth(string $token = ''): Curl {
258 if ($token !== '') $this->token = $token;
259 $this->authType = 'Bearer';
260 return $this;
261 }
262
263 /**
264 * 認証を取りけソ
265 *
266 * @return Curl このインスタンス(メソッドチェーン用)
267 */
268 public function unsetAuth(): Curl {
269 $this->username = '';
270 $this->password = '';
271 $this->token = '';
272 $this->authType = '';
273 return $this;
274 }
275
276 /**
277 * リファラーURLを設定する
278 *
279 * @param string $referer リファラーURL
280 * @return Curl このインスタンス(メソッドチェーン用)
281 */
282 public function setReferer(string $referer): Curl {
283 $this->referer = $referer;
284 return $this;
285 }
286
287 /**
288 * 詳細ログを有効にする
289 *
290 * @param bool $verbose 詳細ログを有効にするかどうか
291 * @return Curl このインスタンス(メソッドチェーン用)
292 */
293 public function setVerbose(bool $verbose): Curl {
294 $this->verbose = (bool)$verbose;
295 return $this;
296 }
297
298 /**
299 * エラー出力先を設定する
300 *
301 * @param resource $handle エラー出力先のファイルハンドル
302 * @return Curl このインスタンス(メソッドチェーン用)
303 */
304 public function setStderr($handle): Curl {
305 $this->stderr = $handle;
306 return $this;
307 }
308
309 /**
310 * SSL証明書のファイルパスを設定する
311 *
312 * @param string $path 証明書ファイルのパス
313 * @return Curl このインスタンス(メソッドチェーン用)
314 */
315 public function setCaInfo(string $path): Curl {
316 $this->caInfoPath = $path;
317 return $this;
318 }
319
320 /**
321 * レスポンスの最大バイト数を設定する
322 *
323 * @param int $bytes 最大バイト数
324 * @return Curl このインスタンス(メソッドチェーン用)
325 */
326 public function setMaxResponseSize(int $bytes): Curl {
327 $this->maxResponseSize = $bytes;
328 return $this;
329 }
330
331 /**
332 * ローカル・プライベートアドレスへの接続を拒否するかどうかを設定する(デフォルトはtrue)
333 * 有効の場合、名前解決は1回だけ行い、確認したIPに直接接続する(DNSリバインディング対策)
334 *
335 * @param bool $block 拒否するかどうか
336 * @return Curl このインスタンス(メソッドチェーン用)
337 */
338 public function setBlockPrivateAddresses(bool $block): Curl {
339 $this->blockPrivate = $block;
340 return $this;
341 }
342
343 /**
344 * リクエストを実行する
345 *
346 * @return Result 成功または失敗
347 */
348 public function execute(): Result {
349 if (!CURL_ENABLED) return Result::Error('エラー:Curlは無効です。');
350 if (empty($this->url)) {
351 $this->responseError = 'URLがありません';
352 return Result::Error($this->responseError);
353 }
354
355 // レスポンスデータのリセット
356 $this->responseHeaders = [];
357 $this->responseBody = '';
358 $this->responseCode = 0;
359 $this->responseError = '';
360 $this->info = [
361 'url' => $this->url,
362 'content_type' => '',
363 'http_code' => 0,
364 'header_size' => 0,
365 'request_size' => 0,
366 'total_time' => 0,
367 'redirect_count' => 0,
368 'redirect_url' => '',
369 ];
370
371 $startTime = microtime(true);
372
373 // ソケットベースの実装を使用する
374 $redirectCount = 0;
375 $currentUrl = $this->url;
376 $originalMethod = $this->method;
377
378 do {
379 if ($this->verbose && $this->stderr) {
380 fwrite($this->stderr, "* 接続中: {$currentUrl}\n");
381 }
382
383 $uri = preg_match('/[\x00-\x20\x7f]/', $currentUrl) ? null : Uri::parse($currentUrl);
384 if (!$uri || !$uri->getHost()) {
385 $this->responseError = "無効なURL: {$currentUrl}";
386 $this->method = $originalMethod;
387 return Result::Error($this->responseError);
388 }
389
390 $scheme = strtolower($uri->getScheme() ?? 'http');
391 if ($scheme !== 'http' && $scheme !== 'https') {
392 $this->responseError = "未対応のスキーム: {$scheme}";
393 $this->method = $originalMethod;
394 return Result::Error($this->responseError);
395 }
396 $host = $uri->getHost();
397 $port = $uri->getPort() ?? ($scheme === 'https' ? 443 : 80);
398
399 // 名前解決は1回だけ行い、確認したIPに直接接続する(DNSリバインディング対策)
400 $connectHost = $host;
401 if ($this->blockPrivate) {
402 $ip = $this->resolvePublicIp($host, $unresolved);
403 if ($ip === null) {
404 // 以前は名前解決の失敗も「非公開アドレス」と表示していた
405 $this->responseError = $unresolved ? "名前解決に失敗: {$host}" : "非公開アドレスへの接続を拒否: {$host}";
406 $this->method = $originalMethod;
407 return Result::Error($this->responseError);
408 }
409 $connectHost = $ip;
410 }
411
412 // 最初と違うオリジンへリダイレクトされた場合、認証情報とクッキーを送らない
413 $origin = "{$scheme}://{$host}:{$port}";
414 if (!isset($firstOrigin)) $firstOrigin = $origin;
415 $sameOrigin = $origin === $firstOrigin;
416 $path = $uri->getPath();
417 if ($path === '') $path = '/';
418 if (NULL !== $uri->getQuery()) {
419 $path .= '?'.$uri->getQuery();
420 }
421
422 // 認証
423 $authHeader = '';
424 if (!$sameOrigin) {
425 // 送らない
426 } else if (!empty($this->authType) && $this->authType === 'Basic') {
427 assert_not_null($this->username);
428 assert_not_null($this->password);
429 $authHeader = "Authorization: Basic "
430 .base64_encode($this->username.':'.$this->password)."\r\n";
431 } else if (!empty($this->authType) && $this->authType === 'Bearer') {
432 assert_not_null($this->token);
433 $authHeader = "Authorization: Bearer ".$this->token."\r\n";
434 }
435
436 // 送信するHTTPリクエストを構築
437 $method = $this->method;
438 $httpData = '';
439
440 if ($method === 'POST' || $method === 'PUT') {
441 if (!empty($this->postRaw)) {
442 $httpData = $this->postRaw;
443 } else if (!empty($this->postFields)) {
444 $httpData = http_build_query($this->postFields);
445 if (!isset($this->headers['Content-Type'])) {
446 $this->headers['Content-Type'] = 'application/x-www-form-urlencoded';
447 }
448 }
449 $this->headers['Content-Length'] = strlen($httpData);
450 }
451
452 // HTTPリクエストを構築
453 // ['Name: value']形式と['Name' => 'value']形式の両方を受け付け、改行等を含むヘッダーは拒否する
454 $hdrs = $this->normalizedHeaders();
455 if ($hdrs === null || preg_match('/[\r\n\0]/', $authHeader === '' ? '' : rtrim($authHeader, "\r\n"))) {
456 $this->responseError = '不正なヘッダー(改行等を含む)';
457 $this->method = $originalMethod;
458 return Result::Error($this->responseError);
459 }
460
461 $accept = 'Accept: '.($hdrs['accept'][1] ?? '*/*');
462 $userAgent = $hdrs['user-agent'][1] ?? $this->userAgent;
463 // 自分で付けるヘッダーは重複させない
464 unset($hdrs['accept'], $hdrs['user-agent'], $hdrs['host'], $hdrs['connection']);
465 // 302/303でGETに変わった後に古いContent-Lengthを送らない
466 if ($method !== 'POST' && $method !== 'PUT') unset($hdrs['content-length']);
467 if (!$sameOrigin) unset($hdrs['authorization'], $hdrs['cookie']);
468
469 $request = "{$method} {$path} HTTP/1.1\r\n";
470 $request .= "Host: {$host}\r\n";
471 $request .= "User-Agent: {$userAgent}\r\n";
472 $request .= "{$accept}\r\n";
473 $request .= "Connection: close\r\n";
474
475 // 認証ヘッダー
476 if (!empty($authHeader)) {
477 $request .= $authHeader;
478 }
479
480 // ヘッダーを追加
481 $ext = $this->buildHeaderString($hdrs, $sameOrigin);
482 if (!empty($ext)) {
483 $request .= $ext;
484 }
485
486 // ヘッダー終了
487 $request .= "\r\n";
488
489 // POSTデータを追加
490 if ($httpData !== '') {
491 $request .= $httpData;
492 }
493
494 $this->DEBUG_REQ_HDR = $request;
495
496 if ($this->verbose && $this->stderr) {
497 fwrite($this->stderr, "* リクエストヘッダー:\n{$request}\n");
498 }
499
500 // ソケット接続を確立
501 $errno = 0;
502 $errstr = '';
503
504 if ($scheme === 'https') {
505 // PHP純正のTLS 1.3・1.2(Std\Lib\Tls)
506 $sslOptions = [
507 'verify_peer' => $this->verifySSL,
508 'verify_peer_name' => $this->verifySSL,
509 'peer_name' => trim($host, '[]'),
510 'alpn' => ['http/1.1'],
511 ];
512
513 if (!empty($this->caInfoPath) && file_exists($this->caInfoPath)) {
514 $sslOptions['cafile'] = $this->caInfoPath;
515 }
516
517 try {
518 $socket = Tls::connect($connectHost, (int)$port, $sslOptions, $this->timeout);
519 } catch (Tls\TlsException $e) {
520 $socket = false;
521 $errstr = $e->getMessage();
522 $errno = $e->alert;
523 }
524 } else {
525 $socket = @fsockopen($connectHost, $port, $errno, $errstr, $this->timeout);
526 }
527
528 if (!$socket) {
529 $this->responseError = "接続出来ません: {$errstr} ({$errno})";
530 if ($this->verbose && $this->stderr) {
531 fwrite($this->stderr, "* エラー: {$this->responseError}\n");
532 }
533
534 $this->method = $originalMethod;
535 return Result::Error($this->responseError);
536 }
537
538 // タイムアウトを設定
539 stream_set_timeout($socket, $this->timeout);
540
541 // リクエストを送信
542 fwrite($socket, $request);
543
544 // レスポンスを読み込む
545 $rawResponse = '';
546 $headers = '';
547 $body = '';
548 $headersComplete = false;
549
550 // 読み込み(大きさと合計時間に上限を付ける)
551 // 以前はタイムアウトしてもfeof()がfalseのままで、無限ループになった
552 $deadline = microtime(true) + $this->timeout;
553 $readError = '';
554 while (!feof($socket)) {
555 $chunk = fread($socket, 8192);
556 if ($chunk !== false) $rawResponse .= $chunk;
557 if (strlen($rawResponse) > $this->maxResponseSize) {
558 $readError = "レスポンスが大き過ぎます(上限:{$this->maxResponseSize}バイト)";
559 break;
560 }
561 if (stream_get_meta_data($socket)['timed_out'] || Tls::timedOut($socket) || microtime(true) > $deadline) {
562 $readError = "タイムアウト({$this->timeout}秒)";
563 break;
564 }
565 if ($chunk === false) break;
566 }
567
568 // 読み込み中のTLSのエラー(改ざん等)
569 $tlsError = Tls::error($socket);
570 if ($readError === '' && $tlsError !== null) $readError = $tlsError->getMessage();
571 fclose($socket);
572
573 if ($readError !== '') {
574 $this->responseError = $readError;
575 $this->method = $originalMethod;
576 return Result::Error($this->responseError);
577 }
578
579 if ($rawResponse === '') {
580 $this->responseError = 'リスポンスエラー';
581 return Result::Error($this->responseError);
582 }
583
584 list($headerLines, $body) = $this->parseResponse($rawResponse);
585
586 // ヘッダーを解析
587 $this->responseHeaders = [];
588 $this->responseCode = 0;
589 $redirectUrl = '';
590
591 foreach ($headerLines as $index => $header) {
592 if ($index === 0) {
593 if (preg_match('#HTTP/\d\.\d (\d+)#', $header, $m))
594 $this->responseCode = (int)$m[1];
595 continue;
596 }
597
598 if (strpos($header, ':') !== false) {
599 [$name, $value] = explode(':', $header, 2);
600 $name = trim($name);
601 $value = trim($value);
602 $this->responseHeaders[$name] = $value;
603
604 // 以前はLocationの後のヘッダーで空文字に上書きされていた
605 $red = $this->checkReds($name, $value, $uri);
606 if ($red !== '') $redirectUrl = $red;
607 }
608 }
609
610 $this->info['http_code'] = $this->responseCode;
611 if (isset($this->responseHeaders['Transfer-Encoding'])
612 && stripos($this->responseHeaders['Transfer-Encoding'], 'chunked') !== false) {
613 $body = $this->decodeChunkedBody($body);
614 }
615
616 $this->info['header_size'] += strlen($headers);
617 $this->responseBody = $body;
618
619 if ($this->verbose && $this->stderr) {
620 fwrite($this->stderr, "* レスポンスコード: {$this->responseCode}\n");
621 fwrite($this->stderr, "* レスポンスヘッダー:\n{$headers}\n");
622 if (!empty($redirectUrl)) {
623 fwrite($this->stderr, "* リダイレクト先: {$redirectUrl}\n");
624 }
625 }
626
627 // リダイレクトが必要な場合
628 if ($redirectUrl !== '' && $redirectCount < $this->maxRedirects) {
629 $currentUrl = $redirectUrl;
630 $redirectCount++;
631 $this->info['redirect_count'] = $redirectCount;
632 $this->info['redirect_url'] = $redirectUrl;
633
634 // 302や303リダイレクトはGETにメソッドを変更
635 if (in_array($this->responseCode, [302, 303], true)) {
636 $this->method = 'GET';
637 $this->postRaw = '';
638 $this->postFields = [];
639 }
640
641 continue;
642 }
643
644 break;
645 } while (true);
646
647 // リクエスト完了後、元のメソッドに戻す
648 $this->method = $originalMethod;
649 $this->info['total_time'] = microtime(true) - $startTime;
650
651 return Result::Success();
652 }
653
654 /**
655 * レスポンスボディを取得する
656 *
657 * @return string レスポンスボディ
658 */
659 public function getResponseBody(): string {
660 return $this->responseBody;
661 }
662
663 /**
664 * レスポンスヘッダーを取得する
665 *
666 * @return array レスポンスヘッダーの配列
667 */
668 public function getResponseHeaders(): array {
669 return $this->responseHeaders;
670 }
671
672 /**
673 * HTTPレスポンスコードを取得する
674 *
675 * @return int HTTPレスポンスコード
676 */
677 public function getResponseCode(): int {
678 return $this->responseCode;
679 }
680
681 /**
682 * エラーメッセージがあれば取得する
683 *
684 * @return string エラーメッセージ
685 */
686 public function getError(): string {
687 return $this->responseError;
688 }
689
690 /**
691 * リクエスト/レスポンス情報を取得する
692 *
693 * @return array 情報の配列
694 */
695 public function getInfo(): array {
696 return $this->info;
697 }
698
699 /**
700 * リクエスト情報を取得する
701 *
702 * @return string 情報の配列
703 */
704 public function getRequestHeader(): string {
705 return $this->DEBUG_REQ_HDR;
706 }
707
708 // 機能性メソッド
709
710 /**
711 * ヘッダーを「小文字の名前 => [名前, 値]」の形にまとめ、改行等の注入を拒否する
712 *
713 * @return array|null ヘッダーの配列、不正な文字を含む場合はnull
714 */
715 private function normalizedHeaders(): ?array {
716 $out = [];
717 foreach ($this->headers as $name => $value) {
718 if (is_int($name)) {
719 if (!is_string($value) || !str_contains($value, ':')) continue;
720 [$name, $value] = explode(':', $value, 2);
721 }
722 $name = trim((string)$name);
723 $value = trim((string)$value);
724 if (!preg_match('/^[A-Za-z0-9!#$%&\'*+.^_`|~-]+$/', $name)) return null;
725 if (preg_match('/[\r\n\0]/', $value)) return null;
726 $out[strtolower($name)] = [$name, $value];
727 }
728
729 if (preg_match('/[\r\n\0]/', $this->referer)) return null;
730 foreach ($this->cookies as $name => $value) {
731 if (preg_match('/[\x00-\x20\x7f;=,]/', (string)$name)) return null;
732 }
733
734 return $out;
735 }
736
737 /**
738 * ホスト名を解決し、全てのIPが公開アドレスの場合だけ接続先のIPを返す
739 *
740 * @param string $host ホスト名又はIPアドレス
741 * @param bool|null $unresolved 名前解決に失敗した場合true
742 * @return string|null 接続先のIP(IPv6は[]付き)、拒否する場合はnull
743 */
744 private function resolvePublicIp(string $host, ?bool &$unresolved = null): ?string {
745 $unresolved = false;
746 $host = trim($host, '[]');
747 if (filter_var($host, FILTER_VALIDATE_IP)) {
748 $ips = [$host];
749 } else {
750 $ips = @gethostbynamel($host) ?: [];
751 foreach ((@dns_get_record($host, DNS_AAAA) ?: []) as $r) {
752 if (isset($r['ipv6'])) $ips[] = $r['ipv6'];
753 }
754 }
755 if (empty($ips)) {
756 $unresolved = true;
757 return null;
758 }
759
760 foreach ($ips as $ip) {
761 if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) return null;
762 }
763
764 $v4 = array_values(array_filter($ips, fn($ip) => filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)));
765 return $v4[0] ?? '['.$ips[0].']';
766 }
767
768 /**
769 * リダイレクトURLを確認する
770 *
771 * @param string $name ヘッダー名
772 * @param string $value ヘッダー値
773 * @param string $currentUrl 現在のURL
774 * @return string リダイレクトURL、リダイレクトがない場合は空文字
775 */
776 private function checkReds(string $name, string $value, Uri $current): string {
777 if (!$this->followRedirects) return '';
778 if (strtolower($name) !== 'location') return '';
779 if ($this->responseCode < 300 || $this->responseCode >= 400) return '';
780 if ($value === '') return '';
781
782 // 相対URL(「/x」「x」「//host/x」等)はRFC 3986の通りに解決する
783 try {
784 return $current->resolve($value)->toString();
785 } catch (\Throwable $e) {
786 return '';
787 }
788 }
789
790 /**
791 * ヘッダー文字列を構築する
792 *
793 * @return string 構築されたヘッダー文字列
794 */
795 private function buildHeaderString(array $hdrs, bool $sameOrigin = true): string {
796 $request = '';
797
798 // ユーザー指定のヘッダーを追加(normalizedHeaders()で確認済み)
799 foreach ($hdrs as [$name, $value]) {
800 $request .= "{$name}: {$value}\r\n";
801 }
802
803 // リファラーが設定されていれば追加
804 if (!empty($this->referer) && !isset($hdrs['referer'])) {
805 $request .= "Referer: {$this->referer}\r\n";
806 }
807
808 // 必要に応じてクッキーヘッダーを追加(別のオリジンには送らない)
809 if ($sameOrigin && !empty($this->cookies) && !isset($hdrs['cookie'])) {
810 $cookieStrings = [];
811 foreach ($this->cookies as $name => $value) {
812 $cookieStrings[] = $name.'='.urlencode($value);
813 }
814
815 $request .= 'Cookie: '.implode('; ', $cookieStrings)."\r\n";
816 }
817
818 return $request;
819 }
820
821 /**
822 * レスポンスを解析してヘッダーとボディに分割する
823 *
824 * @param string $response 完全なHTTPレスポンス
825 * @return array [ヘッダー配列, ボディ文字列]
826 */
827 private function parseResponse(string $response): array {
828 $parts = explode("\r\n\r\n", $response, 2);
829 if (count($parts) < 2) return [explode("\r\n", $response), ''];
830
831 $headers = explode("\r\n", $parts[0]);
832 $body = $parts[1];
833
834 return [$headers, $body];
835 }
836
837 /**
838 * チャンク転送エンコーディングされたボディをデコードする
839 *
840 * @param string $body チャンクエンコードされたボディ
841 * @return string デコードされたボディ
842 */
843 private function decodeChunkedBody(string $body): string {
844 $decodedBody = '';
845 $position = 0;
846
847 while ($position < strlen($body)) {
848 $lineEnd = strpos($body, "\r\n", $position);
849 if ($lineEnd === false) break;
850 $chunkSize = hexdec(substr($body, $position, $lineEnd - $position));
851 if ($chunkSize === 0) break;
852
853 $position = $lineEnd + 2;
854 $decodedBody .= substr($body, $position, $chunkSize);
855 $position += $chunkSize + 2; // チャンクサイズ + CRLF
856 }
857
858 return $decodedBody;
859 }
860}