This repository has been archived by the owner on Jan 8, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Socket.php
622 lines (538 loc) · 20.7 KB
/
Socket.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
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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @package Zend_Http
*/
namespace Zend\Http\Client\Adapter;
use Traversable;
use Zend\Http\Client\Adapter\AdapterInterface as HttpAdapter;
use Zend\Http\Client\Adapter\Exception as AdapterException;
use Zend\Http\Response;
use Zend\Stdlib\ArrayUtils;
use Zend\Stdlib\ErrorHandler;
/**
* A sockets based (stream\socket\client) adapter class for Zend\Http\Client. Can be used
* on almost every PHP environment, and does not require any special extensions.
*
* @category Zend
* @package Zend_Http
* @subpackage Client_Adapter
*/
class Socket implements HttpAdapter, StreamInterface
{
/**
* Map SSL transport wrappers to stream crypto method constants
*
* @var array
*/
protected static $sslCryptoTypes = array(
'ssl' => STREAM_CRYPTO_METHOD_SSLv23_CLIENT,
'sslv2' => STREAM_CRYPTO_METHOD_SSLv2_CLIENT,
'sslv3' => STREAM_CRYPTO_METHOD_SSLv3_CLIENT,
'tls' => STREAM_CRYPTO_METHOD_TLS_CLIENT
);
/**
* The socket for server connection
*
* @var resource|null
*/
protected $socket = null;
/**
* What host/port are we connected to?
*
* @var array
*/
protected $connected_to = array(null, null);
/**
* Stream for storing output
*
* @var resource
*/
protected $out_stream = null;
/**
* Parameters array
*
* @var array
*/
protected $config = array(
'persistent' => false,
'ssltransport' => 'ssl',
'sslcert' => null,
'sslpassphrase' => null,
'sslverifypeer' => true,
'sslcapath' => null,
'sslallowselfsigned' => false,
'sslusecontext' => false
);
/**
* Request method - will be set by write() and might be used by read()
*
* @var string
*/
protected $method = null;
/**
* Stream context
*
* @var resource
*/
protected $context = null;
/**
* Adapter constructor, currently empty. Config is set using setOptions()
*
*/
public function __construct()
{
}
/**
* Set the configuration array for the adapter
*
* @param array|Traversable $options
* @throws AdapterException\InvalidArgumentException
*/
public function setOptions($options = array())
{
if ($options instanceof Traversable) {
$options = ArrayUtils::iteratorToArray($options);
}
if (!is_array($options)) {
throw new AdapterException\InvalidArgumentException(
'Array or Zend_Config object expected, got ' . gettype($options)
);
}
foreach ($options as $k => $v) {
$this->config[strtolower($k)] = $v;
}
}
/**
* Retrieve the array of all configuration options
*
* @return array
*/
public function getConfig()
{
return $this->config;
}
/**
* Set the stream context for the TCP connection to the server
*
* Can accept either a pre-existing stream context resource, or an array
* of stream options, similar to the options array passed to the
* stream_context_create() PHP function. In such case a new stream context
* will be created using the passed options.
*
* @since Zend Framework 1.9
*
* @param mixed $context Stream context or array of context options
* @throws Exception\InvalidArgumentException
* @return Socket
*/
public function setStreamContext($context)
{
if (is_resource($context) && get_resource_type($context) == 'stream-context') {
$this->context = $context;
} elseif (is_array($context)) {
$this->context = stream_context_create($context);
} else {
// Invalid parameter
throw new AdapterException\InvalidArgumentException(
"Expecting either a stream context resource or array, got " . gettype($context)
);
}
return $this;
}
/**
* Get the stream context for the TCP connection to the server.
*
* If no stream context is set, will create a default one.
*
* @return resource
*/
public function getStreamContext()
{
if (! $this->context) {
$this->context = stream_context_create();
}
return $this->context;
}
/**
* Connect to the remote server
*
* @param string $host
* @param int $port
* @param boolean $secure
* @throws AdapterException\RuntimeException
*/
public function connect($host, $port = 80, $secure = false)
{
// If we are connected to the wrong host, disconnect first
$connected_host = (strpos($this->connected_to[0], '://'))
? substr($this->connected_to[0], (strpos($this->connected_to[0], '://') + 3), strlen($this->connected_to[0]))
: $this->connected_to[0];
if ($connected_host != $host || $this->connected_to[1] != $port) {
if (is_resource($this->socket)) {
$this->close();
}
}
// Now, if we are not connected, connect
if (!is_resource($this->socket) || ! $this->config['keepalive']) {
$context = $this->getStreamContext();
if ($secure || $this->config['sslusecontext']) {
if ($this->config['sslverifypeer'] !== null) {
if (!stream_context_set_option($context, 'ssl', 'verify_peer', $this->config['sslverifypeer'])) {
throw new AdapterException\RuntimeException('Unable to set sslverifypeer option');
}
}
if ($this->config['sslcapath']) {
if (!stream_context_set_option($context, 'ssl', 'capath', $this->config['sslcapath'])) {
throw new AdapterException\RuntimeException('Unable to set sslcapath option');
}
}
if ($this->config['sslallowselfsigned'] !== null) {
if (!stream_context_set_option($context, 'ssl', 'allow_self_signed', $this->config['sslallowselfsigned'])) {
throw new AdapterException\RuntimeException('Unable to set sslallowselfsigned option');
}
}
if ($this->config['sslcert'] !== null) {
if (!stream_context_set_option($context, 'ssl', 'local_cert', $this->config['sslcert'])) {
throw new AdapterException\RuntimeException('Unable to set sslcert option');
}
}
if ($this->config['sslpassphrase'] !== null) {
if (!stream_context_set_option($context, 'ssl', 'passphrase', $this->config['sslpassphrase'])) {
throw new AdapterException\RuntimeException('Unable to set sslpassphrase option');
}
}
}
$flags = STREAM_CLIENT_CONNECT;
if ($this->config['persistent']) {
$flags |= STREAM_CLIENT_PERSISTENT;
}
ErrorHandler::start();
$this->socket = stream_socket_client(
$host . ':' . $port,
$errno,
$errstr,
(int) $this->config['timeout'],
$flags,
$context
);
$error = ErrorHandler::stop();
if (!$this->socket) {
$this->close();
throw new AdapterException\RuntimeException(
sprintf(
'Unable to connect to %s:%d%s',
$host,
$port,
($error ? ' . Error #' . $error->getCode() . ': ' . $error->getMessage() : '')
),
0,
$error
);
}
// Set the stream timeout
if (!stream_set_timeout($this->socket, (int) $this->config['timeout'])) {
throw new AdapterException\RuntimeException('Unable to set the connection timeout');
}
if ($secure || $this->config['sslusecontext']) {
if ($this->config['ssltransport'] && isset(static::$sslCryptoTypes[$this->config['ssltransport']])) {
$sslCryptoMethod = static::$sslCryptoTypes[$this->config['ssltransport']];
} else {
$sslCryptoMethod = STREAM_CRYPTO_METHOD_SSLv3_CLIENT;
}
ErrorHandler::start();
$test = stream_socket_enable_crypto($this->socket, true, $sslCryptoMethod);
$error = ErrorHandler::stop();
if (!$test || $error) {
// Error handling is kind of difficult when it comes to SSL
$errorString = '';
while (($sslError = openssl_error_string()) != false) {
$errorString .= "; SSL error: $sslError";
}
$this->close();
if ((! $errorString) && $this->config['sslverifypeer']) {
// There's good chance our error is due to sslcapath not being properly set
if (! ($this->config['sslcapath'] && is_dir($this->config['sslcapath']))) {
$errorString = 'make sure the "sslcapath" option points to a valid SSL certificate directory';
}
}
if ($errorString) {
$errorString = ": $errorString";
}
throw new AdapterException\RuntimeException(sprintf(
'Unable to enable crypto on TCP connection %s%s',
$host,
$errorString
), 0, $error);
}
$host = $this->config['ssltransport'] . "://" . $host;
} else {
$host = 'tcp://' . $host;
}
// Update connected_to
$this->connected_to = array($host, $port);
}
}
/**
* Send request to the remote server
*
* @param string $method
* @param \Zend\Uri\Uri $uri
* @param string $http_ver
* @param array $headers
* @param string $body
* @throws AdapterException\RuntimeException
* @return string Request as string
*/
public function write($method, $uri, $http_ver = '1.1', $headers = array(), $body = '')
{
// Make sure we're properly connected
if (! $this->socket) {
throw new AdapterException\RuntimeException('Trying to write but we are not connected');
}
$host = $uri->getHost();
$host = (strtolower($uri->getScheme()) == 'https' ? $this->config['ssltransport'] : 'tcp') . '://' . $host;
if ($this->connected_to[0] != $host || $this->connected_to[1] != $uri->getPort()) {
throw new AdapterException\RuntimeException('Trying to write but we are connected to the wrong host');
}
// Save request method for later
$this->method = $method;
// Build request headers
$path = $uri->getPath();
if ($uri->getQuery()) $path .= '?' . $uri->getQuery();
$request = "{$method} {$path} HTTP/{$http_ver}\r\n";
foreach ($headers as $k => $v) {
if (is_string($k)) $v = ucfirst($k) . ": $v";
$request .= "$v\r\n";
}
if (is_resource($body)) {
$request .= "\r\n";
} else {
// Add the request body
$request .= "\r\n" . $body;
}
// Send the request
ErrorHandler::start();
$test = fwrite($this->socket, $request);
$error = ErrorHandler::stop();
if (!$test) {
throw new AdapterException\RuntimeException('Error writing request to server', 0, $error);
}
if (is_resource($body)) {
if (stream_copy_to_stream($body, $this->socket) == 0) {
throw new AdapterException\RuntimeException('Error writing request to server');
}
}
return $request;
}
/**
* Read response from server
*
* @throws AdapterException\RuntimeException
* @return string
*/
public function read()
{
// First, read headers only
$response = '';
$gotStatus = false;
while (($line = fgets($this->socket)) !== false) {
$gotStatus = $gotStatus || (strpos($line, 'HTTP') !== false);
if ($gotStatus) {
$response .= $line;
if (rtrim($line) === '') break;
}
}
$this->_checkSocketReadTimeout();
$responseObj= Response::fromString($response);
$statusCode = $responseObj->getStatusCode();
// Handle 100 and 101 responses internally by restarting the read again
if ($statusCode == 100 || $statusCode == 101) return $this->read();
// Check headers to see what kind of connection / transfer encoding we have
$headers = $responseObj->getHeaders();
/**
* Responses to HEAD requests and 204 or 304 responses are not expected
* to have a body - stop reading here
*/
if ($statusCode == 304 || $statusCode == 204 ||
$this->method == \Zend\Http\Request::METHOD_HEAD) {
// Close the connection if requested to do so by the server
$connection = $headers->get('connection');
if ($connection && $connection->getFieldValue() == 'close') {
$this->close();
}
return $response;
}
// If we got a 'transfer-encoding: chunked' header
$transfer_encoding = $headers->get('transfer-encoding');
$content_length = $headers->get('content-length');
if ($transfer_encoding !== false) {
if (strtolower($transfer_encoding->getFieldValue()) == 'chunked') {
do {
$line = fgets($this->socket);
$this->_checkSocketReadTimeout();
$chunk = $line;
// Figure out the next chunk size
$chunksize = trim($line);
if (! ctype_xdigit($chunksize)) {
$this->close();
throw new AdapterException\RuntimeException('Invalid chunk size "' .
$chunksize . '" unable to read chunked body');
}
// Convert the hexadecimal value to plain integer
$chunksize = hexdec($chunksize);
// Read next chunk
$read_to = ftell($this->socket) + $chunksize;
do {
$current_pos = ftell($this->socket);
if ($current_pos >= $read_to) break;
if ($this->out_stream) {
if (stream_copy_to_stream($this->socket, $this->out_stream, $read_to - $current_pos) == 0) {
$this->_checkSocketReadTimeout();
break;
}
} else {
$line = fread($this->socket, $read_to - $current_pos);
if ($line === false || strlen($line) === 0) {
$this->_checkSocketReadTimeout();
break;
}
$chunk .= $line;
}
} while (! feof($this->socket));
ErrorHandler::start();
$chunk .= fgets($this->socket);
ErrorHandler::stop();
$this->_checkSocketReadTimeout();
if (!$this->out_stream) {
$response .= $chunk;
}
} while ($chunksize > 0);
} else {
$this->close();
throw new AdapterException\RuntimeException('Cannot handle "' .
$transfer_encoding->getFieldValue() . '" transfer encoding');
}
// We automatically decode chunked-messages when writing to a stream
// this means we have to disallow the Zend_Http_Response to do it again
if ($this->out_stream) {
$response = str_ireplace("Transfer-Encoding: chunked\r\n", '', $response);
}
// Else, if we got the content-length header, read this number of bytes
} elseif ($content_length !== false) {
// If we got more than one Content-Length header (see ZF-9404) use
// the last value sent
if (is_array($content_length)) {
$content_length = $content_length[count($content_length) - 1];
}
$contentLength = $content_length->getFieldValue();
$current_pos = ftell($this->socket);
$chunk = '';
for ($read_to = $current_pos + $contentLength;
$read_to > $current_pos;
$current_pos = ftell($this->socket)) {
if ($this->out_stream) {
if (stream_copy_to_stream($this->socket, $this->out_stream, $read_to - $current_pos) == 0) {
$this->_checkSocketReadTimeout();
break;
}
} else {
$chunk = fread($this->socket, $read_to - $current_pos);
if ($chunk === false || strlen($chunk) === 0) {
$this->_checkSocketReadTimeout();
break;
}
$response .= $chunk;
}
// Break if the connection ended prematurely
if (feof($this->socket)) break;
}
// Fallback: just read the response until EOF
} else {
do {
if ($this->out_stream) {
if (stream_copy_to_stream($this->socket, $this->out_stream) == 0) {
$this->_checkSocketReadTimeout();
break;
}
} else {
$buff = fread($this->socket, 8192);
if ($buff === false || strlen($buff) === 0) {
$this->_checkSocketReadTimeout();
break;
} else {
$response .= $buff;
}
}
} while (feof($this->socket) === false);
$this->close();
}
// Close the connection if requested to do so by the server
$connection = $headers->get('connection');
if ($connection && $connection->getFieldValue() == 'close') {
$this->close();
}
return $response;
}
/**
* Close the connection to the server
*
*/
public function close()
{
if (is_resource($this->socket)) {
ErrorHandler::start();
fclose($this->socket);
ErrorHandler::stop();
}
$this->socket = null;
$this->connected_to = array(null, null);
}
/**
* Check if the socket has timed out - if so close connection and throw
* an exception
*
* @throws AdapterException\TimeoutException with READ_TIMEOUT code
*/
protected function _checkSocketReadTimeout()
{
if ($this->socket) {
$info = stream_get_meta_data($this->socket);
$timedout = $info['timed_out'];
if ($timedout) {
$this->close();
throw new AdapterException\TimeoutException(
"Read timed out after {$this->config['timeout']} seconds",
AdapterException\TimeoutException::READ_TIMEOUT
);
}
}
}
/**
* Set output stream for the response
*
* @param resource $stream
* @return \Zend\Http\Client\Adapter\Socket
*/
public function setOutputStream($stream)
{
$this->out_stream = $stream;
return $this;
}
/**
* Destructor: make sure the socket is disconnected
*
* If we are in persistent TCP mode, will not close the connection
*
*/
public function __destruct()
{
if (! $this->config['persistent']) {
if ($this->socket) $this->close();
}
}
}