Repository navigation
Expand file tree
/
Copy pathClient.php
More file actions
531 lines (464 loc) · 18 KB
/
Copy pathClient.php
File metadata and controls
531 lines (464 loc) · 18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
<?php
/*
* This file is part of Berlioz framework.
*
* @license https://opensource.org/licenses/MIT MIT License
* @copyright 2021 Ronan GIRON
* @author Ronan GIRON <https://github.com/ElGigi>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code, to the root.
*/
declare(strict_types=1);
namespace Berlioz\Http\Client;
use Berlioz\Http\Client\Adapter\AdapterInterface;
use Berlioz\Http\Client\Adapter\AutoAdapter;
use Berlioz\Http\Client\Adapter\OriginCredentialsAwareInterface;
use Berlioz\Http\Client\Components\DefaultHeadersTrait;
use Berlioz\Http\Client\Components\HeaderParserTrait;
use Berlioz\Http\Client\Components\LogTrait;
use Berlioz\Http\Client\Components\RequestFactoryTrait;
use Berlioz\Http\Client\Cookies\CookiesManager;
use Berlioz\Http\Client\Exception\HttpClientException;
use Berlioz\Http\Client\Exception\HttpException;
use Berlioz\Http\Client\Exception\RequestException;
use Berlioz\Http\Message\Request;
use Berlioz\Http\Message\Response;
use Berlioz\Http\Message\Stream;
use Berlioz\Http\Message\Uri;
use Psr\Http\Client\ClientExceptionInterface;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Client\NetworkExceptionInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\UriInterface;
use Psr\Log\LoggerAwareInterface;
use RuntimeException;
/**
* Class Client.
*/
class Client implements ClientInterface, LoggerAwareInterface
{
use DefaultHeadersTrait;
use HeaderParserTrait;
use LogTrait;
use RequestFactoryTrait;
private ?float $lastRequestTime = null;
private Options $options;
private array $adapters;
private Session $session;
/**
* Client constructor.
*
* @param Options|array|null $options
* @param AdapterInterface ...$adapter
*
* @option string "baseUri" Base of URI if not given in requests
* @option false|int "followLocation" Follow redirections (default: 5)
* @option int "sleepTime" Sleep time between requests (ms) (default: 0)
* @option string "logFile" Log file name (only file name, not path)
* @option bool "exceptions" Throw exceptions on error (default: true)
* @option null|false|CookiesManager "cookies" NULL: to use default cookie manager; FALSE: to not use cookies; a CookieManager object to use
* @option Closure "callback" Callback after each request
* @option Closure "callbackException" Callback on exception
* @option array "headers" Default headers
*/
public function __construct(Options|array|null $options = null, AdapterInterface ...$adapter)
{
$this->options = Options::make($options);
$this->defaultHeaders = &$this->options->headers;
$this->adapters = $adapter ?: [new AutoAdapter()];
$this->session = new Session(historySize: $this->options->history);
}
/**
* Client destructor.
*
* @throws HttpClientException if unable to close log file pointer
*/
public function __destruct()
{
$this->closeLogResource();
}
public function __serialize(): array
{
return [
'adapters' => $this->adapters,
'options' => $this->options,
'session' => $this->session,
];
}
public function __unserialize(array $data): void
{
$this->adapters = $data['adapters'];
$this->options = $data['options'];
$this->session = $data['session'];
$this->defaultHeaders = &$this->options->headers;
}
/**
* Get options.
*
* @return Options
*/
public function getOptions(): Options
{
return $this->options;
}
/**
* Get adapters.
*
* @return AdapterInterface[]
*/
public function getAdapters(): array
{
return $this->adapters;
}
/**
* Get adapter.
*
* @param string|null $name
*
* @return AdapterInterface
* @throws HttpClientException
*/
public function getAdapter(?string $name = null): AdapterInterface
{
if (null === $name) {
return reset($this->adapters);
}
foreach ($this->adapters as $adapter) {
if ($name === $adapter->getName()) {
return $adapter;
}
}
throw new HttpClientException(sprintf('Unknown adapter "%s"', $name));
}
/**
* Get session.
*
* @return Session
*/
public function getSession(): Session
{
return $this->session;
}
/**
* Set session.
*
* @param Session $session
*/
public function setSession(Session $session): void
{
$this->session = $session;
}
/**
* Prepare request.
*
* @param RequestInterface $request
* @param CookiesManager|false|null $cookies
* @param Options $options
*
* @return RequestInterface
* @throws RequestException If a non-seekable body cannot be read completely
*/
protected function prepareRequest(
RequestInterface $request,
CookiesManager|false|null $cookies,
Options $options
): RequestInterface {
$request = $request->withUri(
Uri::create(
$request->getUri(),
$options->baseUri ?? $this->getSession()->getHistory()->getLast()?->getRequest()->getUri()
)
);
// Add default headers to request
$request = $this->addDefaultHeaders($request, $options->headers);
// A non-seekable body can be read only once and its size is not known: copy it, so that it is sent with
// its real length, and again on a retry or a redirect
$body = $request->getBody();
if ($body->isReadable() && !$body->isSeekable()) {
$copy = new Stream();
try {
while (!$body->eof() && '' !== ($chunk = $body->read(8192))) {
$copy->write($chunk);
}
} catch (RuntimeException $exception) {
throw new RequestException('Unable to read request body', $request, previous: $exception);
}
// No more data for now, but the body is not at its end: sending it would truncate it
if (!$body->eof()) {
throw new RequestException('Request body is not completely available', $request);
}
$copy->rewind();
$request = $request->withBody($copy);
}
// Add content length
if (false === $request->hasHeader('Content-Length')) {
$length = $request->getBody()->getSize();
if (null !== $length) {
$request = $request->withHeader('Content-Length', $request->getBody()->getSize());
}
}
// Add cookies to request
if (false !== $cookies) {
$cookies ??= new CookiesManager();
$request = $cookies->addCookiesToRequest($request);
}
return $request;
}
/**
* Compare absolute HTTP origins, including effective default ports.
*/
protected function isSameOrigin(UriInterface $source, UriInterface $target): bool
{
$scheme = strtolower($source->getScheme());
if (
!in_array($scheme, ['http', 'https'], true)
|| $scheme !== strtolower($target->getScheme())
|| $source->getHost() === ''
|| strcasecmp($source->getHost(), $target->getHost()) !== 0
) {
return false;
}
$defaultPort = $scheme === 'https' ? 443 : 80;
return ($source->getPort() ?? $defaultPort) === ($target->getPort() ?? $defaultPort);
}
/**
* Is target allowed to receive the origin credentials of the transport (client certificate, adapter credentials)?
*
* @param UriInterface $source Initial request URI
* @param UriInterface $target
* @param CredentialsOrigin[] $allowedOrigins
*
* @return bool
*/
protected function isCredentialOrigin(UriInterface $source, UriInterface $target, array $allowedOrigins): bool
{
if ($this->isSameOrigin($source, $target)) {
return true;
}
foreach ($allowedOrigins as $allowedOrigin) {
if ($allowedOrigin->matches($target)) {
return true;
}
}
return false;
}
/**
* Remove mandatory and application credentials from cross-origin redirect headers.
*
* @param array<string, string|string[]> $headers
* @return array<string, string|string[]>
*/
protected function filterRedirectHeaders(array $headers, Options $options): array
{
$sensitiveHeaders = array_map(
strtolower(...),
array_merge(['Authorization', 'Proxy-Authorization', 'Cookie'], $options->redirectSensitiveHeaders),
);
foreach (array_keys($headers) as $name) {
if (in_array(strtolower($name), $sensitiveHeaders, true)) {
unset($headers[$name]);
}
}
return $headers;
}
/**
* Resolve Location before comparing origins; never accept credentials supplied by Location.
*/
protected function prepareRedirectUri(string $location, UriInterface $source): UriInterface
{
$locationUri = Uri::createFromString($location);
$target = Uri::create($locationUri, $source)->withFragment('');
if ($locationUri->getUserInfo() !== '' || !$this->isSameOrigin($source, $target)) {
$target = $target->withUserInfo('');
}
return $target;
}
/**
* Generate a Referer using strict-origin-when-cross-origin semantics.
*/
protected function createRedirectReferer(UriInterface $source, UriInterface $target): ?string
{
$sourceScheme = strtolower($source->getScheme());
$targetScheme = strtolower($target->getScheme());
if (
!in_array($sourceScheme, ['http', 'https'], true)
|| !in_array($targetScheme, ['http', 'https'], true)
|| $source->getHost() === ''
|| $target->getHost() === ''
|| ($sourceScheme === 'https' && $targetScheme === 'http')
) {
return null;
}
$referer = $source->withUserInfo('')->withFragment('');
if (!$this->isSameOrigin($source, $target)) {
$referer = $referer->withPath('/')->withQuery('');
}
return (string)$referer;
}
/**
* @inheritDoc
*/
public function sendRequest(RequestInterface $request, Options|array $options = []): ResponseInterface
{
$followLocationCounter = 0;
$stripSensitiveHeaders = false;
$originalRequest = $request;
// Keep redirect state local, including headers referenced by the client's default-header trait.
$options = clone Options::make($options, $this->options);
$headers = $options->headers;
$options->headers = &$headers;
// Keep an empty manager for history when automatic cookie handling is disabled.
$cookies = $options->cookies ?? $this->getSession()->getCookies() ?: new CookiesManager();
// Origin credentials of the transport are scoped to the initial origin and the approved ones.
$context = $options->context;
$credentialsOrigins = array_map(
CredentialsOrigin::fromString(...),
$options->context->credentials_origins ?? [],
);
$credentialsSource = null;
$originCredentials = true;
do {
$this->sleep($options);
$request = $this->prepareRequest($request, $options->cookies === false ? false : $cookies, $options);
$credentialsSource ??= $request->getUri();
$adapter = $this->getAdapter($options->adapter);
if (!$originCredentials && $adapter instanceof OriginCredentialsAwareInterface) {
$adapter = $adapter->withoutOriginCredentials();
}
try {
for ($iRetry = 0; $iRetry < max($options->retry ?: 1, 1); $iRetry++) {
try {
$this->lastRequestTime = microtime(true);
$response = $adapter->sendRequest($request, $context);
break;
} catch (NetworkExceptionInterface $exception) {
if (($iRetry + 1) >= $options->retry) {
throw $exception;
}
$this->getSession()->getHistory()->add($cookies, $request, timings: $adapter->getTimings());
usleep($options->retryTime * 1000);
}
}
// Add request to history
$this->getSession()->getHistory()->add($cookies, $request, $response ?? null, $adapter->getTimings());
} catch (ClientExceptionInterface $exception) {
$this->getSession()->getHistory()->add($cookies, $request, timings: $adapter->getTimings());
$this->log($request);
throw $exception;
}
$this->log($request, $response);
if ($options->cookies !== false) {
$cookies->addCookiesFromResponse($request->getUri(), $response);
}
// Callback
if (null !== $options->callback) {
($options->callback)($request, $response);
}
$followLocation = false;
if (!in_array(
$response->getStatusCode(),
[
Response::HTTP_STATUS_MOVED_PERMANENTLY,
Response::HTTP_STATUS_MOVED_TEMPORARILY,
Response::HTTP_STATUS_SEE_OTHER,
Response::HTTP_STATUS_TEMPORARY_REDIRECT,
Response::HTTP_STATUS_PERMANENT_REDIRECT,
]
)) {
continue;
}
if (empty($newLocation = $response->getHeader('Location'))) {
continue;
}
// Follow location ?
if (false === $options->followLocation) {
continue;
}
$followLocation = ($followLocationCounter++ <= $options->followLocation);
if (!$followLocation) {
throw new RequestException('Too many redirection from host', $originalRequest);
}
$sourceUri = $request->getUri();
$redirectUri = $this->prepareRedirectUri($newLocation[0], $sourceUri);
$stripSensitiveHeaders = $stripSensitiveHeaders || !$this->isSameOrigin($sourceUri, $redirectUri);
// Once downgraded, origin credentials are never restored, even when coming back to an approved origin.
if (
$originCredentials
&& !$this->isCredentialOrigin($credentialsSource, $redirectUri, $credentialsOrigins)
) {
$originCredentials = false;
$context = $options->context?->withoutOriginCredentials();
}
// Recompute redirect metadata rather than reapplying caller-supplied values.
foreach (array_keys($options->headers) as $name) {
if (in_array(strtolower((string)$name), ['referer', 'content-type', 'content-length'], true)) {
unset($options->headers[$name]);
}
}
if (null !== ($referer = $this->createRedirectReferer($sourceUri, $redirectUri))) {
$options->headers['Referer'] = [$referer];
}
$redirectMethod = Request::HTTP_METHOD_GET;
$redirectBody = null;
// For 307 and 308 redirect cases, method and body not changed.
// QUERY (RFC 10008, §2.5) also keeps them on 301 and 302; only 303 switches to GET.
$preserveMethodStatuses = [
Response::HTTP_STATUS_TEMPORARY_REDIRECT,
Response::HTTP_STATUS_PERMANENT_REDIRECT,
];
if (Request::HTTP_METHOD_QUERY === strtoupper($request->getMethod())) {
$preserveMethodStatuses[] = Response::HTTP_STATUS_MOVED_PERMANENTLY;
$preserveMethodStatuses[] = Response::HTTP_STATUS_MOVED_TEMPORARILY;
}
if (in_array($response->getStatusCode(), $preserveMethodStatuses, true)) {
$redirectMethod = $request->getMethod();
$redirectBody = $request->getBody();
if ($request->hasHeader('Content-Type')) {
$options->headers['Content-Type'] = $request->getHeader('Content-Type');
}
}
if ($stripSensitiveHeaders) {
$options->headers = $this->filterRedirectHeaders($options->headers, $options);
$redirectUri = $redirectUri->withUserInfo('');
}
// Prepare exactly once at the next iteration, using the persistently filtered options.
$request = new Request($redirectMethod, $redirectUri, $redirectBody);
} while ($followLocation);
// Exceptions if error?
if (true === $options->exceptions) {
if (intval(substr((string)$response->getStatusCode(), 0, 1)) > 3) {
$exception = new HttpException(
sprintf('%d - %s', $response->getStatusCode(), $response->getReasonPhrase()),
$originalRequest,
$response
);
if (null === $options->callbackException) {
throw $exception;
}
return ($options->callbackException)($exception, $options);
}
}
return $response;
}
/**
* Sleep between two request.
*/
protected function sleep(Options $options): void
{
// Initial request
if (null === $this->lastRequestTime) {
return;
}
// No sleep time
if (($sleepMicroTime = $options->sleepTime * 1000) <= 0) {
return;
}
// Sleep
$diffTime = (microtime(true) - $this->lastRequestTime);
if ($diffTime < $sleepMicroTime) {
usleep((int)ceil($sleepMicroTime - $diffTime));
}
}
}