-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathClient.php
198 lines (168 loc) · 8.47 KB
/
Client.php
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
<?php
namespace Http\Client\Socket;
use Http\Client\Socket\Exception\ConnectionException;
use Http\Client\Socket\Exception\InvalidRequestException;
use Http\Client\Socket\Exception\SSLConnectionException;
use Http\Client\Socket\Exception\TimeoutException;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* Socket Http Client.
*
* Use stream and socket capabilities of the core of PHP to send HTTP requests
*
* @author Joel Wurtz <[email protected]>
*/
class Client implements ClientInterface
{
use RequestWriter;
use ResponseReader;
/**
* @var array{remote_socket: string|null, timeout: int, stream_context: resource, stream_context_options: array<string, mixed>, stream_context_param: array<string, mixed>, ssl: ?boolean, write_buffer_size: int, ssl_method: int}
*/
private $config;
/**
* Constructor.
*
* @param array{remote_socket?: string|null, timeout?: int, stream_context?: resource, stream_context_options?: array<string, mixed>, stream_context_param?: array<string, mixed>, ssl?: ?boolean, write_buffer_size?: int, ssl_method?: int}|ResponseFactoryInterface $config1
* @param array{remote_socket?: string|null, timeout?: int, stream_context?: resource, stream_context_options?: array<string, mixed>, stream_context_param?: array<string, mixed>, ssl?: ?boolean, write_buffer_size?: int, ssl_method?: int}|null $config2 Mistake when refactoring the constructor from version 1 to version 2 - used as $config if set and $configOrResponseFactory is a response factory instance
* @param array{remote_socket?: string|null, timeout?: int, stream_context?: resource, stream_context_options?: array<string, mixed>, stream_context_param?: array<string, mixed>, ssl?: ?boolean, write_buffer_size?: int, ssl_method?: int} $config intended for version 1 BC, used as $config if $config2 is not set and $configOrResponseFactory is a response factory instance
*
* string|null remote_socket Remote entrypoint (can be a tcp or unix domain address)
* int timeout Timeout before canceling request
* stream resource The initialized stream context, if not set the context is created from the options and param.
* array<string, mixed> stream_context_options Context options as defined in the PHP documentation
* array<string, mixed> stream_context_param Context params as defined in the PHP documentation
* boolean ssl Use ssl, default to scheme from request, false if not present
* int write_buffer_size Buffer when writing the request body, defaults to 8192
* int ssl_method Crypto method for ssl/tls, see PHP doc, defaults to STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT
*/
public function __construct($config1 = [], $config2 = null, array $config = [])
{
if (\is_array($config1)) {
$this->config = $this->configure($config1);
return;
}
@trigger_error('Passing a Psr\Http\Message\ResponseFactoryInterface to SocketClient is deprecated, and will be removed in 3.0, you should only pass config options.', E_USER_DEPRECATED);
$this->config = $this->configure($config2 ?: $config);
}
/**
* {@inheritdoc}
*/
public function sendRequest(RequestInterface $request): ResponseInterface
{
$remote = $this->config['remote_socket'];
$useSsl = $this->config['ssl'];
if (!$request->hasHeader('Connection')) {
$request = $request->withHeader('Connection', 'close');
}
if (null === $remote) {
$remote = $this->determineRemoteFromRequest($request);
}
if (null === $useSsl) {
$useSsl = ('https' === $request->getUri()->getScheme());
}
$socket = $this->createSocket($request, $remote, $useSsl);
try {
$this->writeRequest($socket, $request, $this->config['write_buffer_size']);
$response = $this->readResponse($request, $socket);
} catch (\Exception $e) {
$this->closeSocket($socket);
throw $e;
}
return $response;
}
/**
* Create the socket to write request and read response on it.
*
* @param RequestInterface $request Request for
* @param string $remote Entrypoint for the connection
* @param bool $useSsl Whether to use ssl or not
*
* @throws ConnectionException|SSLConnectionException When the connection fail
*
* @return resource Socket resource
*/
protected function createSocket(RequestInterface $request, string $remote, bool $useSsl)
{
$errNo = null;
$errMsg = null;
$socket = @stream_socket_client($remote, $errNo, $errMsg, floor($this->config['timeout'] / 1000), STREAM_CLIENT_CONNECT, $this->config['stream_context']);
if (false === $socket) {
if (110 === $errNo) {
throw new TimeoutException($errMsg, $request);
}
throw new ConnectionException($errMsg, $request);
}
stream_set_timeout($socket, (int) floor($this->config['timeout'] / 1000), $this->config['timeout'] % 1000);
if ($useSsl && false === @stream_socket_enable_crypto($socket, true, $this->config['ssl_method'])) {
throw new SSLConnectionException(sprintf('Cannot enable tls: %s', error_get_last()['message'] ?? 'no error reported'), $request);
}
return $socket;
}
/**
* Close the socket, used when having an error.
*
* @param resource $socket
*
* @return void
*/
protected function closeSocket($socket)
{
fclose($socket);
}
/**
* Return configuration for the socket client.
*
* @param array{remote_socket?: string|null, timeout?: int, stream_context?: resource, stream_context_options?: array<string, mixed>, stream_context_param?: array<string, mixed>, ssl?: ?boolean, write_buffer_size?: int, ssl_method?: int} $config
*
* @return array{remote_socket: string|null, timeout: int, stream_context: resource, stream_context_options: array<string, mixed>, stream_context_param: array<string, mixed>, ssl: ?boolean, write_buffer_size: int, ssl_method: int}
*/
protected function configure(array $config = [])
{
$resolver = new OptionsResolver();
$resolver->setDefaults([
'remote_socket' => null,
'timeout' => null,
'stream_context_options' => [],
'stream_context_param' => [],
'ssl' => null,
'write_buffer_size' => 8192,
'ssl_method' => STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT,
]);
$resolver->setDefault('stream_context', function (Options $options) {
return stream_context_create($options['stream_context_options'], $options['stream_context_param']);
});
$resolver->setDefault('timeout', ((int) ini_get('default_socket_timeout')) * 1000);
$resolver->setAllowedTypes('stream_context_options', 'array');
$resolver->setAllowedTypes('stream_context_param', 'array');
$resolver->setAllowedTypes('stream_context', 'resource');
$resolver->setAllowedTypes('ssl', ['bool', 'null']);
return $resolver->resolve($config);
}
/**
* Return remote socket from the request.
*
* @throws InvalidRequestException When no remote can be determined from the request
*
* @return string
*/
private function determineRemoteFromRequest(RequestInterface $request)
{
if (!$request->hasHeader('Host') && '' === $request->getUri()->getHost()) {
throw new InvalidRequestException('Remote is not defined and we cannot determine a connection endpoint for this request (no Host header)', $request);
}
$host = $request->getUri()->getHost();
$port = $request->getUri()->getPort() ?: ('https' === $request->getUri()->getScheme() ? 443 : 80);
$endpoint = sprintf('%s:%s', $host, $port);
// If use the host header if present for the endpoint
if (empty($host) && $request->hasHeader('Host')) {
$endpoint = $request->getHeaderLine('Host');
}
return sprintf('tcp://%s', $endpoint);
}
}