forked from docker-php/docker-php
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathClient.php
More file actions
182 lines (155 loc) · 6.2 KB
/
Copy pathClient.php
File metadata and controls
182 lines (155 loc) · 6.2 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
<?php
namespace Docker\SocketClient;
use Docker\SocketClient\Exception\ConnectionException;
use Docker\SocketClient\Exception\InvalidRequestException;
use Docker\SocketClient\Exception\SSLConnectionException;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Psr\Http\Client\ClientInterface;
use Http\Message\MessageFactory;
/**
* Socket Http Client.
*
* Use stream and socket capabilities of the core of PHP to send HTTP requests
*
* @author Joel Wurtz <joel.wurtz@gmail.com>
*/
class Client implements ClientInterface
{
use RequestWriter;
use ResponseReader;
private array $config = [
'remote_socket' => null,
'timeout' => null,
'stream_context_options' => [],
'stream_context_param' => [],
'ssl' => null,
'write_buffer_size' => 8192,
'ssl_method' => STREAM_CRYPTO_METHOD_TLS_CLIENT,
];
/**
* Constructor.
*
* @param array $config {
*
* @var string $remote_socket Remote entrypoint (can be a tcp or unix domain address)
* @var int $timeout Timeout before canceling request
* @var array $stream_context_options Context options as defined in the PHP documentation
* @var array $stream_context_param Context params as defined in the PHP documentation
* @var bool $ssl Use ssl, default to scheme from request, false if not present
* @var int $write_buffer_size Buffer when writing the request body, defaults to 8192
* @var int $ssl_method Crypto method for ssl/tls, see PHP doc, defaults to STREAM_CRYPTO_METHOD_TLS_CLIENT
* }
*/
public function __construct(MessageFactory $responseFactory, array $config = [])
{
$this->responseFactory = $responseFactory;
$this->config = $this->configure($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) {
throw new ConnectionException($errMsg, $request);
}
stream_set_timeout($socket, 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']), $request);
}
return $socket;
}
/**
* Close the socket, used when having an error.
*
* @param resource $socket
*/
protected function closeSocket($socket): void
{
fclose($socket);
}
/**
* Return configuration for the socket client.
*
* @param array $config Configuration from user
*
* @return array Configuration resolved
*/
protected function configure(array $config = []): array
{
$resolver = new OptionsResolver();
$resolver->setDefaults($this->config);
$resolver->setDefault('stream_context', function (Options $options) {
return stream_context_create($options['stream_context_options'], $options['stream_context_param']);
});
$resolver->setDefault('timeout', 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.
*
* @param RequestInterface $request
*
* @throws InvalidRequestException When no remote can be determined from the request
*
* @return string
*/
private function determineRemoteFromRequest(RequestInterface $request): string
{
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);
}
}