forked from varspool/Wrench
-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathAbstractSocket.php
More file actions
392 lines (334 loc) · 11 KB
/
Copy pathAbstractSocket.php
File metadata and controls
392 lines (334 loc) · 11 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
<?php
namespace Wrench\Socket;
use InvalidArgumentException;
use Wrench\Exception\SocketException;
use Wrench\ResourceInterface;
use Wrench\Util\Configurable;
/**
* Socket class
* Implements low level logic for connecting, serving, reading to, and
* writing from WebSocket connections using PHP's streams.
* Unlike in previous versions of this library, a Socket instance now
* represents a single underlying socket resource. It's designed to be used
* by aggregation, rather than inheritance.
*/
abstract class AbstractSocket extends Configurable implements ResourceInterface
{
/**
* Default timeout for socket operations (reads, writes).
*
* @var int seconds
*/
public const TIMEOUT_SOCKET = 5;
public const DEFAULT_RECEIVE_LENGTH = 1400;
public const NAME_PART_IP = 0;
public const NAME_PART_PORT = 1;
/**
* @var resource|null
*/
protected $socket;
/**
* Stream context.
*/
protected $context;
/**
* Whether the socket is connected to a server
* Note, the connection may not be ready to use, but the socket is
* connected at least. See $handshaked, and other properties in
* subclasses.
*
* @var bool
*/
protected $connected = false;
/**
* The socket name according to stream_socket_get_name.
*
* @var string|null
*/
protected $name;
/**
* Gets the IP address of the socket.
*
* @throws SocketException If the IP address cannot be obtained
*
* @return string
*/
public function getIp(): string
{
$name = $this->getName();
if ($name) {
return self::getNamePart($name, self::NAME_PART_IP);
}
throw new SocketException('Cannot get socket IP address');
}
/**
* Gets the name of the socket.
*
* @return string|null
*/
protected function getName(): ?string
{
if (null === $this->socket) {
return null;
}
if (!$this->name) {
$this->name = @\stream_socket_get_name($this->socket, true);
}
return $this->name;
}
/**
* Gets part of the name of the socket
* PHP seems to return IPV6 address/port combos like this:
* ::1:1234, where ::1 is the address and 1234 the port
* So, the part number here is either the last : delimited section (the port)
* or all the other sections (the whole initial part, the address).
*
* @param string $name (from $this->getName() usually)
* @param int $part 0 or 1
*
* @throws SocketException
*/
public static function getNamePart(string $name, int $part): string
{
if (!$name) {
throw new InvalidArgumentException('Invalid name');
}
$parts = \explode(':', $name);
if (\count($parts) < 2) {
throw new SocketException('Could not parse name parts: '.$name);
}
if (self::NAME_PART_PORT == $part) {
return \end($parts);
} elseif (self::NAME_PART_IP == $part) {
return \implode(':', \array_slice($parts, 0, -1));
}
throw new InvalidArgumentException('Invalid name part');
}
/**
* Gets the port of the socket.
*
* @throws SocketException If the port cannot be obtained
*
* @return int
*/
public function getPort(): int
{
$name = $this->getName();
if ($name) {
return (int) self::getNamePart($name, self::NAME_PART_PORT);
}
throw new SocketException('Cannot get socket IP address');
}
/**
* Get the last error that occurred on the socket.
*
* @return string
*/
public function getLastError(): string
{
if ($this->isConnected() && $this->socket) {
$err = @\socket_last_error($this->socket);
if ($err) {
$err = \socket_strerror($err);
}
if (!$err) {
$err = 'Unknown error';
}
return $err;
}
return 'Not connected';
}
/**
* Whether the socket is currently connected.
*
* @return bool
*/
public function isConnected(): bool
{
return $this->connected;
}
/**
* @return resource|null
*/
public function getResource()
{
return $this->socket;
}
public function getResourceId(): ?int
{
if (null === $this->socket) {
return null;
}
return \get_resource_id($this->socket);
}
/**
* @param string $data Binary data to send down the socket
*
* @throws SocketException
*
* @return int|null The number of bytes sent or null on error
*/
public function send(string $data): ?int
{
if (!$this->isConnected()) {
throw new SocketException('Socket is not connected');
}
$length = \strlen($data);
if (0 == $length) {
return 0;
}
for ($i = $length; $i > 0; $i -= $written) {
$written = @\fwrite($this->socket, \substr($data, -1 * $i));
if (false === $written) {
return null;
} elseif (0 === $written) {
return null;
}
}
return $length;
}
/**
* Waits for data to become available on the socket.
*
* @param float $maxSeconds the maximum amount of time to wait for data, in seconds
*
* @return ?bool returns true if data is available, false if the wait timed out, and null on error
*/
public function waitForData(float $maxSeconds): ?bool
{
if (null === $this->socket) {
return null;
}
$read = [$this->socket];
$write = null;
$except = null;
$seconds = (int) \floor($maxSeconds);
$microseconds = (int) (($maxSeconds - $seconds) * 1e6);
$result = @\stream_select($read, $write, $except, $seconds, $microseconds);
if (false === $result) {
// An error occurred. stream_select() probably triggered an error internally.
return null;
} elseif (0 === $result) {
// Timeout occurred, no data available
return false;
}
// Data is available
return true;
}
/**
* Receive data from the socket.
*
* Data that has already arrived is drained without blocking. Pass a wait
* time to also wait for up to that many seconds for data to first arrive.
*
* @param float $waitSeconds the maximum amount of time to wait for data, in seconds
*/
public function receive(int $length = self::DEFAULT_RECEIVE_LENGTH, float $waitSeconds = 0.0): string
{
if ($waitSeconds > 0) {
$this->waitForData($waitSeconds);
}
$buffer = '';
$metadata['unread_bytes'] = 0;
$makeBlockingAfterRead = false;
try {
do {
// feof means socket has been closed
// also, sometimes in long running processes the system seems to kill the underlying socket
if (!$this->socket || \feof($this->socket)) {
$this->disconnect();
return $buffer;
}
// poll before reading so that an empty socket returns immediately instead
// of blocking until the socket timeout; callers that expect a reply must
// wait for data to arrive before reading, as the handshake does
$readArray = [$this->socket];
$writeArray = null;
$exceptArray = null;
$selectResult = \stream_select($readArray, $writeArray, $exceptArray, 0);
// 1 means there is data to read, false means we were unable to check if there is data to read
if (1 === $selectResult || false === $selectResult) {
$result = \fread($this->socket, $length);
} else {
$result = false;
}
if ($makeBlockingAfterRead) {
\stream_set_blocking($this->socket, true);
$makeBlockingAfterRead = false;
}
if (false === $result) {
return $buffer;
}
$buffer .= $result;
// feof means socket has been closed
if (\feof($this->socket)) {
$this->disconnect();
return $buffer;
}
$continue = false;
if (1 === \strlen($result)) {
// Workaround Chrome behavior (still needed?)
$continue = true;
}
if (\strlen($result) === $length) {
$continue = true;
}
// Continue if more data to be read
$metadata = \stream_get_meta_data($this->socket);
/** @phpstan-ignore-next-line */
if (isset($metadata['unread_bytes'])) {
if (!$metadata['unread_bytes']) {
// stop it, if we read a full message in previous time
$continue = false;
} else {
$continue = true;
// it makes sense only if unread_bytes less than DEFAULT_RECEIVE_LENGTH
if ($length > $metadata['unread_bytes']) {
// http://php.net/manual/en/function.stream-get-meta-data.php
// 'unread_bytes' don't describes real length correctly.
// $length = $metadata['unread_bytes'];
// Socket is a blocking by default. When we do a blocking read from an empty
// queue it will block and the server will hang. https://bugs.php.net/bug.php?id=1739
\stream_set_blocking($this->socket, false);
$makeBlockingAfterRead = true;
}
}
}
} while ($continue);
return $buffer;
} finally {
if ($this->socket && !\feof($this->socket) && $makeBlockingAfterRead) {
\stream_set_blocking($this->socket, true);
}
}
}
/**
* Disconnect the socket.
*
* @return void
*/
public function disconnect(): void
{
if ($this->socket) {
\stream_socket_shutdown($this->socket, \STREAM_SHUT_RDWR);
}
$this->socket = null;
$this->connected = false;
}
/**
* Configure options
* Options include
* - timeout_socket => int, seconds, default 5.
*
* @param array $options
*
* @return void
*/
protected function configure(array $options): void
{
$options = \array_merge([
'timeout_socket' => self::TIMEOUT_SOCKET,
], $options);
parent::configure($options);
}
}