-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBSDSocket.class.php
More file actions
executable file
·451 lines (407 loc) · 10.9 KB
/
BSDSocket.class.php
File metadata and controls
executable file
·451 lines (407 loc) · 10.9 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
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
<?php namespace peer;
/**
* Provide an interface to the BSD sockets
*
* @test xp://peer.unittest.sockets.BSDSocketTest
* @see php://sockets
* @see http://www.developerweb.net/sock-faq/ The UNIX Socket FAQ
* @ext sockets
*/
class BSDSocket extends Socket {
public
$_eof = false,
$domain = AF_INET,
$type = SOCK_STREAM,
$protocol = SOL_TCP,
$options = [];
protected
$rq = '',
$state = 0;
/** @return peer.Sockets */
public function kind() { return Sockets::$BSD; }
/** @return void */
public function useNoDelay() {
socket_set_option($this->_sock, SOL_TCP, TCP_NODELAY, true);
}
/**
* Returns local endpoint
*
* @return peer.SocketEndpoint
* @throws peer.SocketException
*/
public function localEndpoint() {
if ($this->_sock) {
if (false === socket_getsockname($this->_sock, $host, $port)) {
throw new SocketException('Cannot get socket name on '.$this->_sock);
}
return new SocketEndpoint($host, $port);
}
return null; // Not connected
}
/**
* Set Domain
*
* @param int domain one of AF_INET or AF_UNIX
* @throws lang.IllegalStateException if socket is already connected
*/
public function setDomain($domain) {
if ($this->_sock) {
throw new \lang\IllegalStateException('Cannot set domain on connected socket');
}
$this->domain= $domain;
}
/**
* Get Domain
*
* @return int
*/
public function getDomain() {
return $this->domain;
}
/**
* Set Type
*
* @param int type one of SOCK_STREAM, SOCK_DGRAM, SOCK_RAW, SOCK_SEQPACKET or SOCK_RDM
* @throws lang.IllegalStateException if socket is already connected
*/
public function setType($type) {
if ($this->_sock) {
throw new \lang\IllegalStateException('Cannot set type on connected socket');
}
$this->type= $type;
}
/**
* Get Type
*
* @return int
*/
public function getType() {
return $this->type;
}
/**
* Set Protocol
*
* @see php://getprotobyname
* @param int protocol one of SOL_TCP or SOL_UDP
* @throws lang.IllegalStateException if socket is already connected
*/
public function setProtocol($protocol) {
if ($this->_sock) {
throw new \lang\IllegalStateException('Cannot set protocol on connected socket');
}
$this->protocol= $protocol;
}
/**
* Get Protocol
*
* @return int
*/
public function getProtocol() {
return $this->protocol;
}
/**
* Get last error
*
* @return string error
*/
public function getLastError() {
return sprintf('%d: %s', $e= socket_last_error($this->_sock), socket_strerror($e));
}
/**
* Set socket option
*
* @param int level
* @param int name
* @param var value
* @see php://socket_set_option
*/
public function setOption($level, $name, $value) {
$this->options[$level][$name]= $value;
if ($this->_sock) {
socket_set_option($this->_sock, $level, $name, $value);
}
}
/**
* Returns whether a connection has been established
*
* @return bool
*/
public function isConnected() {
if (null === $this->_sock) return false;
// For asynchronously connected sockets, check whether we can get the
// peer name. Once we get one, we've successfully established a connection!
if (1 === $this->state) {
if (false === socket_getpeername($this->_sock, $_, $_)) {
\xp::gc(__FILE__, __LINE__ - 1);
return false;
}
socket_set_block($this->_sock);
$this->state= 2;
}
return true;
}
/**
* Establish a connection
*
* @param float $timeout
* @param int $flags
* @return bool
* @throws peer.ConnectException
*/
protected function establish($timeout, $flags) {
static $domains= [
AF_INET => 'AF_INET',
AF_INET6 => 'AF_INET6',
AF_UNIX => 'AF_UNIX'
];
static $types= [
SOCK_STREAM => 'SOCK_STREAM',
SOCK_DGRAM => 'SOCK_DGRAM',
SOCK_RAW => 'SOCK_RAW',
SOCK_SEQPACKET => 'SOCK_SEQPACKET',
SOCK_RDM => 'SOCK_RDM'
];
// Create socket...
if (!($this->_sock= socket_create($this->domain, $this->type, $this->protocol))) {
$this->_sock= null;
$e= new ConnectException(sprintf(
'Create of %s socket (type %s, protocol %s) failed: %d: %s',
$domains[$this->domain],
$types[$this->type],
getprotobynumber($this->protocol),
$e= socket_last_error(),
socket_strerror($e)
));
\xp::gc(__FILE__);
throw $e;
}
// Set options
foreach ($this->options as $level => $pairs) {
foreach ($pairs as $name => $value) {
socket_set_option($this->_sock, $level, $name, $value);
}
}
// ... and connection timeouts
$origTimeout= $this->getTimeout();
$this->setTimeout($timeout);
// ...and connect it
$host= (string)$this->host;
switch ($this->domain) {
case AF_INET:
case AF_INET6: {
if ($flags & STREAM_CLIENT_ASYNC_CONNECT) {
socket_set_nonblock($this->_sock);
socket_connect($this->_sock, $host, $this->port);
$this->state= 1;
$r= null;
} else {
$r= socket_connect($this->_sock, $host, $this->port);
$this->state= 2;
}
break;
}
case AF_UNIX: {
$r= socket_connect($this->_sock, $host);
break;
}
}
// Reset initial timeout settings
$this->setTimeout($origTimeout);
// Check return status
if (false === $r) {
$this->state= 0;
$this->_sock= null;
$e= new ConnectException(sprintf(
'Connect to %s:%d failed: %s',
$this->host,
$this->port,
$this->getLastError()
));
\xp::gc(__FILE__);
throw $e;
}
return true;
}
/**
* Close socket
*
* @return bool success
*/
public function close() {
if (null === $this->_sock) return false;
socket_close($this->_sock);
$this->_sock= null;
$this->_eof= false;
$this->state= 0;
return true;
}
/**
* Set timeout
*
* @param int|float $timeout
*/
public function setTimeout($timeout) {
$this->_timeout= $timeout;
// Apply changes to already opened connection
$sec= (int)$this->_timeout;
$usec= (int)(1000 * ($this->_timeout - $sec));
$this->setOption(SOL_SOCKET, SO_RCVTIMEO, ['sec' => $sec, 'usec' => $usec]);
$this->setOption(SOL_SOCKET, SO_SNDTIMEO, ['sec' => $sec, 'usec' => $usec]);
}
/**
* Set socket blocking
*
* @param bool blocking
* @return bool success
* @throws peer.SocketException
*/
public function setBlocking($blocking) {
if ($blocking) {
$ret= socket_set_block($this->_sock);
} else {
$ret= socket_set_nonblock($this->_sock);
}
if (false === $ret) {
$e= new SocketException(sprintf(
'setBlocking (%s) failed: %s',
($blocking ? 'blocking' : 'nonblocking'),
$this->getLastError()
));
\xp::gc(__FILE__);
throw $e;
}
return true;
}
/**
* Returns whether there is data that can be read
*
* @param float timeout default NULL Timeout value in seconds (e.g. 0.5)
* @return bool there is data that can be read
* @throws peer.SocketException in case of failure
*/
public function canRead($timeout= null) {
if (!$this->_sock) {
throw new SocketException('Socket not connected');
}
$r= [$this->_sock]; $w= null; $e= null;
$n= Sockets::$BSD->select0($r, $w, $e, $timeout);
return $n > 0;
}
/**
* Returns whether eof has been reached
*
* @return bool
*/
public function eof() {
return $this->_eof;
}
/**
* Reading helper
*
* @param int maxLen
* @param int type PHP_BINARY_READ or PHP_NORMAL_READ
* @param bool chop
* @return string data
*/
protected function _read($maxLen, $type, $chop= false) {
if (null === $this->_sock) {
throw new SocketException('Read of '.$maxLen.' bytes failed: Socket closed');
}
$res= '';
if (!$this->_eof && 0 === strlen($this->rq)) {
$r= $this->_sock ? [$this->_sock] : null; $w= null; $e= null;
$n= Sockets::$BSD->select0($r, $w, $e, $this->_timeout);
if (0 === $n) {
$e= new SocketTimeoutException('Read of '.$maxLen.' bytes failed', $this->_timeout);
\xp::gc(__FILE__);
throw $e;
}
$res= @socket_read($this->_sock, $maxLen);
if (false === $res || null === $res) {
$error= socket_last_error($this->_sock);
if (0 === $error || SOCKET_ECONNRESET === $error) {
$this->_eof= true;
return null;
}
$e= new SocketException('Read of '.$maxLen.' bytes failed: '.$this->getLastError());
\xp::gc(__FILE__);
throw $e;
} else if ('' === $res) {
$this->_eof= true;
}
}
$read= $this->rq.$res;
if (PHP_NORMAL_READ === $type) {
if ('' === $read) return null;
$c= strcspn($read, "\n");
$this->rq= substr($read, $c+ 1);
$chunk= substr($read, 0, $c+ 1);
return $chop ? chop($chunk) : $chunk;
} else if (PHP_BINARY_READ === $type) {
if ('' === $read) return '';
$this->rq= substr($read, $maxLen);
return substr($read, 0, $maxLen);
}
}
/**
* Read data from a socket
*
* @param int maxLen maximum bytes to read
* @return string data
* @throws peer.SocketException
*/
public function read($maxLen= 4096) {
return $this->_read($maxLen, PHP_NORMAL_READ);
}
/**
* Read data from a socket
*
* @param int maxLen maximum bytes to read
* @return string data
* @throws peer.SocketException
*/
public function readLine($maxLen= 4096) {
return $this->_read($maxLen, PHP_NORMAL_READ, true);
}
/**
* Read data from a socket (binary-safe)
*
* @param int maxLen maximum bytes to read
* @return string data
* @throws peer.SocketException
*/
public function readBinary($maxLen= 4096) {
return $this->_read($maxLen, PHP_BINARY_READ);
}
/**
* Write a string to the socket
*
* @param string str
* @return int bytes written
* @throws peer.SocketException
*/
public function write($str) {
if (null === $this->_sock) {
throw new SocketException('Write of '.strlen($str).' bytes to socket failed: Socket closed');
}
$len= strlen($str);
$bytesWritten= socket_write($this->_sock, $str, $len);
if (false === $bytesWritten || null === $bytesWritten) {
$e= new SocketException('Write of '.$len.' bytes to socket failed: '.$this->getLastError());
\xp::gc(__FILE__);
throw $e;
}
return $bytesWritten;
}
/** @return string */
public function toString() {
return sprintf(
'%s(%s -> %s%s:%d)',
nameof($this),
null === $this->_sock ? '(closed)' : spl_object_id($this->_sock),
$this->_prefix,
$this->host,
$this->port
);
}
}