This repository was archived by the owner on Dec 9, 2024. It is now read-only.
forked from doctrine/couchdb-client
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathSocketClient.php
More file actions
324 lines (290 loc) · 11.4 KB
/
SocketClient.php
File metadata and controls
324 lines (290 loc) · 11.4 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
<?php
namespace Doctrine\CouchDB\HTTP;
/**
* This class uses a custom HTTP client, which may have more bugs then the
* default PHP HTTP clients, but supports keep alive connections without any
* extension dependencies.
*
* @license http://www.opensource.org/licenses/mit-license.php MIT
*
* @link www.doctrine-project.com
* @since 1.0
*
* @author Kore Nordmann <kore@arbitracker.org>
*/
class SocketClient extends AbstractHTTPClient
{
/**
* Connection pointer for connections, once keep alive is working on the
* CouchDb side.
*
* @var resource
*/
protected $connection;
/**
* Return the socket after setting up the connection to server and writing
* the headers. The returned resource can later be used to read and
* write data in chunks. These should be done without much delay as the
* connection might get closed.
*
* @throws HTTPException
*
* @return resource
*/
public function getConnection(
$method,
$path,
$data = null,
array $headers = []
) {
$fullPath = $path;
if ($this->options['path']) {
$fullPath = '/'.$this->options['path'].$path;
}
$this->checkConnection();
$stringHeader = $this->buildRequest($method, $fullPath, $data, $headers);
// Send the build request to the server
if (fwrite($this->connection, $stringHeader) === false) {
// Reestablish which seems to have been aborted
//
// The recursion in this method might be problematic if the
// connection establishing mechanism does not correctly throw an
// exception on failure.
$this->connection = null;
return $this->getConnection($method, $path, $data, $headers);
}
return $this->connection;
}
/**
* Check for server connection.
*
* Checks if the connection already has been established, or tries to
* establish the connection, if not done yet.
*
* @throws HTTPException
*
* @return void
*/
protected function checkConnection()
{
// Setting Connection scheme according ssl support
$context_options = null;
if ($this->options['ssl']) {
if (!extension_loaded('openssl')) {
// no openssl extension loaded.
// This is a bit hackisch...
$this->connection = null;
throw HTTPException::connectionFailure(
$this->options['ip'],
$this->options['port'],
'ssl activated without openssl extension loaded',
0
);
}
$host = 'ssl://'.$this->options['host'].':'.$this->options['port'];
if ($this->options['verify'] === false) {
$context_options = [
'ssl' => [
'verify_peer' => false,
],
];
}
} else {
$host = $this->options['ip'].':'.$this->options['port'];
}
// Try to establish the connection.
if ($this->connection === null) {
$context = stream_context_create($context_options);
if (($this->connection = @stream_socket_client($host, $errno, $errstr, $this->options['timeout'], STREAM_CLIENT_CONNECT, $context)) === false) {
$this->connection = null;
throw HTTPException::connectionFailure(
$this->options['ip'],
$this->options['port'],
$errstr,
$errno
);
}
}
}
/**
* Build a HTTP 1.1 request.
*
* Build the HTTP 1.1 request headers from the given input.
*
* @param string $method
* @param string $path
* @param string $data
* @param array $headers
*
* @return string
*/
protected function buildRequest(
$method,
$path,
$data = null,
array $headers = []
) {
// Create basic request headers
$host = "Host: {$this->options['host']}";
if ($this->options['port'] != 80) {
$host .= ":{$this->options['port']}";
}
$request = "$method $path HTTP/1.1\r\n$host\r\n";
// Add basic auth if set
if ($this->options['username']) {
$request .= sprintf("Authorization: Basic %s\r\n",
base64_encode($this->options['username'].':'.$this->options['password'])
);
}
// Set keep-alive header, which helps to keep to connection
// initialization costs low, especially when the database server is not
// available in the locale net.
$request .= 'Connection: '.($this->options['keep-alive'] ? 'Keep-Alive' : 'Close')."\r\n";
if ($this->options['headers']) {
$headers = array_merge($this->options['headers'], $headers);
}
if (!isset($headers['Content-Type'])) {
$headers['Content-Type'] = 'application/json';
}
foreach ($headers as $key => $value) {
if (is_bool($value) === true) {
$value = ($value) ? 'true' : 'false';
}
$request .= $key.': '.$value."\r\n";
}
// Also add headers and request body if data should be sent to the
// server. Otherwise just add the closing mark for the header section
// of the request.
if ($data !== null) {
$request .= 'Content-Length: '.strlen($data)."\r\n\r\n";
$request .= $data;
} else {
$request .= "\r\n";
}
return $request;
}
/**
* Perform a request to the server and return the result.
*
* Perform a request to the server and return the result converted into a
* Response object. If you do not expect a JSON structure, which
* could be converted in such a response object, set the forth parameter to
* true, and you get a response object returned, containing the raw body.
*
* @param string $method
* @param string $path
* @param string $data
* @param bool $raw
* @param array $headers
*
* @return Response
*/
public function request($method, $path, $data = null, $raw = false, array $headers = [])
{
$fullPath = $path;
if ($this->options['path']) {
$fullPath = '/'.$this->options['path'].$path;
}
// Try establishing the connection to the server
$this->checkConnection();
// Send the build request to the server
if (fwrite($this->connection, $request = $this->buildRequest($method, $fullPath, $data, $headers)) === false) {
// Reestablish which seems to have been aborted
//
// The recursion in this method might be problematic if the
// connection establishing mechanism does not correctly throw an
// exception on failure.
$this->connection = null;
return $this->request($method, $path, $data, $raw, $headers);
}
// Read server response headers
$rawHeaders = '';
$headers = [
'connection' => ($this->options['keep-alive'] ? 'Keep-Alive' : 'Close'),
];
// Remove leading newlines, should not occur at all, actually.
while ((($line = fgets($this->connection)) !== false) &&
(($lineContent = rtrim($line)) === ''));
// Throw exception, if connection has been aborted by the server, and
// leave handling to the user for now.
if ($line === false) {
// Reestablish which seems to have been aborted
//
// The recursion in this method might be problematic if the
// connection establishing mechanism does not correctly throw an
// exception on failure.
//
// An aborted connection seems to happen here on long running
// requests, which cause a connection timeout at server side.
$this->connection = null;
return $this->request($method, $path, $data, $raw, $headers);
}
do {
// Also store raw headers for later logging
$rawHeaders .= $lineContent."\n";
// Extract header values
if (preg_match('(^HTTP/(?P<version>\d+\.\d+)\s+(?P<status>\d+))S', $lineContent, $match)) {
$headers['version'] = $match['version'];
$headers['status'] = (int) $match['status'];
} else {
list($key, $value) = explode(':', $lineContent, 2);
$headers[strtolower($key)] = ltrim($value);
}
} while ((($line = fgets($this->connection)) !== false) &&
(($lineContent = rtrim($line)) !== ''));
// Read response body
$body = '';
if (!isset($headers['transfer-encoding']) ||
($headers['transfer-encoding'] !== 'chunked')) {
// HTTP 1.1 supports chunked transfer encoding, if the according
// header is not set, just read the specified amount of bytes.
$bytesToRead = (int) (isset($headers['content-length']) ? $headers['content-length'] : 0);
// Read body only as specified by chunk sizes, everything else
// are just footnotes, which are not relevant for us.
while ($bytesToRead > 0) {
$body .= $read = fgets($this->connection, $bytesToRead + 1);
$bytesToRead -= strlen($read);
}
} else {
// When transfer-encoding=chunked has been specified in the
// response headers, read all chunks and sum them up to the body,
// until the server has finished. Ignore all additional HTTP
// options after that.
do {
$line = rtrim(fgets($this->connection));
// Get bytes to read, with option appending comment
if (preg_match('(^([0-9a-f]+)(?:;.*)?$)', $line, $match)) {
$bytesToRead = hexdec($match[1]);
// Read body only as specified by chunk sizes, everything else
// are just footnotes, which are not relevant for us.
$bytesLeft = $bytesToRead;
while ($bytesLeft > 0) {
$read = fread($this->connection, $bytesLeft + 2);
// Chop off \r\n from the end.
$body .= rtrim($read);
$bytesLeft -= strlen($read);
}
}
} while ($bytesToRead > 0);
}
// Reset the connection if the server asks for it.
if ($headers['connection'] !== 'Keep-Alive') {
fclose($this->connection);
$this->connection = null;
}
// Handle some response state as special cases
switch ($headers['status']) {
case 301:
case 302:
case 303:
case 307:
$path = parse_url($headers['location'], PHP_URL_PATH);
return $this->request($method, $path, $data, $raw, $headers);
}
// Create response object from couch db response
if ($headers['status'] >= 400) {
return new ErrorResponse($headers['status'], $headers, $body);
}
return new Response($headers['status'], $headers, $body, $raw);
}
}