Debian Codegraph @

vendor/clue/socket-raw/src/Socket.php

raw
1 <?php
2
3 namespace Socket\Raw;
4
5 /**
6 * Simple and lightweight OOP wrapper for the low-level sockets extension (ext-sockets)
7 *
8 * @author clue
9 * @link https://github.com/clue/php-socket-raw
10 */
11 class Socket
12 {
13 /**
14 * reference to actual socket resource
15 *
16 * @var \Socket|resource
17 */
18 private $resource;
19
20 /**
21 * instanciate socket wrapper for given socket resource
22 *
23 * should usually not be called manually, see Factory
24 *
25 * @param \Socket|resource $resource
26 * @see Factory as the preferred (and simplest) way to construct socket instances
27 */
28 public function __construct($resource)
29 {
30 $this->resource = $resource;
31 }
32
33 /**
34 * get actual socket resource
35 *
36 * @return \Socket|resource returns the socket resource (a `Socket` object as of PHP 8)
37 */
38 public function getResource()
39 {
40 return $this->resource;
41 }
42
43 /**
44 * accept an incomming connection on this listening socket
45 *
46 * @return \Socket\Raw\Socket new connected socket used for communication
47 * @throws Exception on error, if this is not a listening socket or there's no connection pending
48 * @throws \Error PHP 8 only: throws \Error when socket is invalid
49 * @see self::selectRead() to check if this listening socket can accept()
50 * @see Factory::createServer() to create a listening socket
51 * @see self::listen() has to be called first
52 * @uses socket_accept()
53 */
54 public function accept()
55 {
56 $resource = @socket_accept($this->resource);
57 if ($resource === false) {
58 throw Exception::createFromGlobalSocketOperation();
59 }
60 return new Socket($resource);
61 }
62
63 /**
64 * binds a name/address/path to this socket
65 *
66 * has to be called before issuing connect() or listen()
67 *
68 * @param string $address either of IPv4:port, hostname:port, [IPv6]:port, unix-path
69 * @return self $this (chainable)
70 * @throws Exception on error
71 * @throws \Error PHP 8 only: throws \Error when socket or arguments are invalid
72 * @uses socket_bind()
73 */
74 public function bind($address)
75 {
76 $ret = @socket_bind($this->resource, $this->unformatAddress($address, $port), $port);
77 if ($ret === false) {
78 throw Exception::createFromSocketResource($this->resource);
79 }
80 return $this;
81 }
82
83 /**
84 * close this socket
85 *
86 * ATTENTION: make sure to NOT re-use this socket instance after closing it!
87 * its socket resource remains closed and most further operations will fail!
88 *
89 * @return self $this (chainable)
90 * @throws \Error PHP 8 only: throws \Error when socket is invalid
91 * @see self::shutdown() should be called before closing socket
92 * @uses socket_close()
93 */
94 public function close()
95 {
96 socket_close($this->resource);
97 return $this;
98 }
99
100 /**
101 * initiate a connection to given address
102 *
103 * @param string $address either of IPv4:port, hostname:port, [IPv6]:port, unix-path
104 * @return self $this (chainable)
105 * @throws Exception on error
106 * @throws \Error PHP 8 only: throws \Error when socket or arguments are invalid
107 * @uses socket_connect()
108 */
109 public function connect($address)
110 {
111 $ret = @socket_connect($this->resource, $this->unformatAddress($address, $port), $port);
112 if ($ret === false) {
113 throw Exception::createFromSocketResource($this->resource);
114 }
115 return $this;
116 }
117
118 /**
119 * Initiates a new connection to given address, wait for up to $timeout seconds
120 *
121 * The given $timeout parameter is an upper bound, a maximum time to wait
122 * for the connection to be either accepted or rejected.
123 *
124 * The resulting socket resource will be set to non-blocking mode,
125 * regardless of its previous state and whether this method succedes or
126 * if it fails. Make sure to reset with `setBlocking(true)` if you want to
127 * continue using blocking calls.
128 *
129 * @param string $address either of IPv4:port, hostname:port, [IPv6]:port, unix-path
130 * @param float $timeout maximum time to wait (in seconds)
131 * @return self $this (chainable)
132 * @throws Exception on error
133 * @throws \Error PHP 8 only: throws \Error when socket or arguments are invalid
134 * @uses self::setBlocking() to enable non-blocking mode
135 * @uses self::connect() to initiate the connection
136 * @uses self::selectWrite() to wait for the connection to complete
137 * @uses self::assertAlive() to check connection state
138 */
139 public function connectTimeout($address, $timeout)
140 {
141 $this->setBlocking(false);
142
143 try {
144 // socket is non-blocking, so connect should emit EINPROGRESS
145 $this->connect($address);
146
147 // socket is already connected immediately?
148 return $this;
149 } catch (Exception $e) {
150 // non-blocking connect() should be EINPROGRESS (or EWOULDBLOCK on Windows) => otherwise re-throw
151 if ($e->getCode() !== SOCKET_EINPROGRESS && $e->getCode() !== SOCKET_EWOULDBLOCK) {
152 throw $e;
153 }
154
155 // connection should be completed (or rejected) within timeout: socket becomes writable on success or error
156 // Windows requires special care because it uses exceptfds for socket errors: https://github.com/reactphp/event-loop/issues/206
157 $r = null;
158 $w = array($this->resource);
159 $e = DIRECTORY_SEPARATOR === '\\' ? $w : null;
160 $ret = @socket_select($r, $w, $e, $timeout === null ? null : (int) $timeout, (int) (($timeout - floor($timeout)) * 1000000));
161
162 if ($ret === false) {
163 throw Exception::createFromGlobalSocketOperation('Failed to select socket for writing');
164 } elseif ($ret === 0) {
165 throw new Exception('Timed out while waiting for connection', SOCKET_ETIMEDOUT);
166 }
167
168 // confirm connection success (or fail if connected has been rejected)
169 $this->assertAlive();
170
171 return $this;
172 }
173 }
174
175 /**
176 * get socket option
177 *
178 * @param int $level
179 * @param int $optname
180 * @return mixed
181 * @throws Exception on error
182 * @throws \Error PHP 8 only: throws \Error when socket or arguments are invalid
183 * @uses socket_get_option()
184 */
185 public function getOption($level, $optname)
186 {
187 $value = @socket_get_option($this->resource, $level, $optname);
188 if ($value === false) {
189 throw Exception::createFromSocketResource($this->resource);
190 }
191 return $value;
192 }
193
194 /**
195 * get remote side's address/path
196 *
197 * @return string
198 * @throws Exception on error
199 * @throws \Error PHP 8 only: throws \Error when socket is invalid
200 * @uses socket_getpeername()
201 */
202 public function getPeerName()
203 {
204 $ret = @socket_getpeername($this->resource, $address, $port);
205 if ($ret === false) {
206 throw Exception::createFromSocketResource($this->resource);
207 }
208 return $this->formatAddress($address, $port);
209 }
210
211 /**
212 * get local side's address/path
213 *
214 * @return string
215 * @throws Exception on error
216 * @throws \Error PHP 8 only: throws \Error when socket is invalid
217 * @uses socket_getsockname()
218 */
219 public function getSockName()
220 {
221 $ret = @socket_getsockname($this->resource, $address, $port);
222 if ($ret === false) {
223 throw Exception::createFromSocketResource($this->resource);
224 }
225 return $this->formatAddress($address, $port);
226 }
227
228 /**
229 * start listen for incoming connections
230 *
231 * @param int $backlog maximum number of incoming connections to be queued
232 * @return self $this (chainable)
233 * @throws Exception on error
234 * @throws \Error PHP 8 only: throws \Error when socket or arguments are invalid
235 * @see self::bind() has to be called first to bind name to socket
236 * @uses socket_listen()
237 */
238 public function listen($backlog = 0)
239 {
240 $ret = @socket_listen($this->resource, $backlog);
241 if ($ret === false) {
242 throw Exception::createFromSocketResource($this->resource);
243 }
244 return $this;
245 }
246
247 /**
248 * read up to $length bytes from connect()ed / accept()ed socket
249 *
250 * The $type parameter specifies if this should use either binary safe reading
251 * (PHP_BINARY_READ, the default) or stop at CR or LF characters (PHP_NORMAL_READ)
252 *
253 * @param int $length maximum length to read
254 * @param int $type either of PHP_BINARY_READ (the default) or PHP_NORMAL_READ
255 * @return string
256 * @throws Exception on error
257 * @throws \Error PHP 8 only: throws \Error when socket or arguments are invalid
258 * @see self::recv() if you need to pass flags
259 * @uses socket_read()
260 */
261 public function read($length, $type = PHP_BINARY_READ)
262 {
263 $data = @socket_read($this->resource, $length, $type);
264 if ($data === false) {
265 throw Exception::createFromSocketResource($this->resource);
266 }
267 return $data;
268 }
269
270 /**
271 * receive up to $length bytes from connect()ed / accept()ed socket
272 *
273 * @param int $length maximum length to read
274 * @param int $flags
275 * @return string
276 * @throws Exception on error
277 * @throws \Error PHP 8 only: throws \Error when socket or arguments are invalid
278 * @see self::read() if you do not need to pass $flags
279 * @see self::recvFrom() if your socket is not connect()ed
280 * @uses socket_recv()
281 */
282 public function recv($length, $flags)
283 {
284 $ret = @socket_recv($this->resource, $buffer, $length, $flags);
285 if ($ret === false) {
286 throw Exception::createFromSocketResource($this->resource);
287 }
288 return $buffer;
289 }
290
291 /**
292 * receive up to $length bytes from socket
293 *
294 * @param int $length maximum length to read
295 * @param int $flags
296 * @param string $remote reference will be filled with remote/peer address/path
297 * @return string
298 * @throws Exception on error
299 * @throws \Error PHP 8 only: throws \Error when socket or arguments are invalid
300 * @see self::recv() if your socket is connect()ed
301 * @uses socket_recvfrom()
302 */
303 public function recvFrom($length, $flags, &$remote)
304 {
305 $ret = @socket_recvfrom($this->resource, $buffer, $length, $flags, $address, $port);
306 if ($ret === false) {
307 throw Exception::createFromSocketResource($this->resource);
308 }
309 $remote = $this->formatAddress($address, $port);
310 return $buffer;
311 }
312
313 /**
314 * check socket to see if a read/recv/revFrom will not block
315 *
316 * @param float|null $sec maximum time to wait (in seconds), 0 = immediate polling, null = no limit
317 * @return boolean true = socket ready (read will not block), false = timeout expired, socket is not ready
318 * @throws Exception on error
319 * @throws \Error PHP 8 only: throws \Error when socket or arguments are invalid
320 * @uses socket_select()
321 */
322 public function selectRead($sec = 0)
323 {
324 $usec = $sec === null ? 0 : (int) (($sec - floor($sec)) * 1000000);
325 $r = array($this->resource);
326 $n = null;
327 $ret = @socket_select($r, $n, $n, $sec === null ? null : (int) $sec, $usec);
328 if ($ret === false) {
329 throw Exception::createFromGlobalSocketOperation('Failed to select socket for reading');
330 }
331 return !!$ret;
332 }
333
334 /**
335 * check socket to see if a write/send/sendTo will not block
336 *
337 * @param float|null $sec maximum time to wait (in seconds), 0 = immediate polling, null = no limit
338 * @return boolean true = socket ready (write will not block), false = timeout expired, socket is not ready
339 * @throws Exception on error
340 * @throws \Error PHP 8 only: throws \Error when socket or arguments are invalid
341 * @uses socket_select()
342 */
343 public function selectWrite($sec = 0)
344 {
345 $usec = $sec === null ? 0 : (int) (($sec - floor($sec)) * 1000000);
346 $w = array($this->resource);
347 $n = null;
348 $ret = @socket_select($n, $w, $n, $sec === null ? null : (int) $sec, $usec);
349 if ($ret === false) {
350 throw Exception::createFromGlobalSocketOperation('Failed to select socket for writing');
351 }
352 return !!$ret;
353 }
354
355 /**
356 * send given $buffer to connect()ed / accept()ed socket
357 *
358 * @param string $buffer
359 * @param int $flags
360 * @return int number of bytes actually written (make sure to check against given buffer length!)
361 * @throws Exception on error
362 * @throws \Error PHP 8 only: throws \Error when socket or arguments are invalid
363 * @see self::write() if you do not need to pass $flags
364 * @see self::sendTo() if your socket is not connect()ed
365 * @uses socket_send()
366 */
367 public function send($buffer, $flags)
368 {
369 $ret = @socket_send($this->resource, $buffer, strlen($buffer), $flags);
370 if ($ret === false) {
371 throw Exception::createFromSocketResource($this->resource);
372 }
373 return $ret;
374 }
375
376 /**
377 * send given $buffer to socket
378 *
379 * @param string $buffer
380 * @param int $flags
381 * @param string $remote remote/peer address/path
382 * @return int number of bytes actually written
383 * @throws Exception on error
384 * @throws \Error PHP 8 only: throws \Error when socket or arguments are invalid
385 * @see self::send() if your socket is connect()ed
386 * @uses socket_sendto()
387 */
388 public function sendTo($buffer, $flags, $remote)
389 {
390 $ret = @socket_sendto($this->resource, $buffer, strlen($buffer), $flags, $this->unformatAddress($remote, $port), $port);
391 if ($ret === false) {
392 throw Exception::createFromSocketResource($this->resource);
393 }
394 return $ret;
395 }
396
397 /**
398 * enable/disable blocking/nonblocking mode (O_NONBLOCK flag)
399 *
400 * @param boolean $toggle
401 * @return self $this (chainable)
402 * @throws Exception on error
403 * @throws \Error PHP 8 only: throws \Error when socket or arguments are invalid
404 * @uses socket_set_block()
405 * @uses socket_set_nonblock()
406 */
407 public function setBlocking($toggle = true)
408 {
409 $ret = $toggle ? @socket_set_block($this->resource) : @socket_set_nonblock($this->resource);
410 if ($ret === false) {
411 throw Exception::createFromSocketResource($this->resource);
412 }
413 return $this;
414 }
415
416 /**
417 * set socket option
418 *
419 * @param int $level
420 * @param int $optname
421 * @param mixed $optval
422 * @return self $this (chainable)
423 * @throws Exception on error
424 * @throws \Error PHP 8 only: throws \Error when socket or arguments are invalid
425 * @see self::getOption()
426 * @uses socket_set_option()
427 */
428 public function setOption($level, $optname, $optval)
429 {
430 $ret = @socket_set_option($this->resource, $level, $optname, $optval);
431 if ($ret === false) {
432 throw Exception::createFromSocketResource($this->resource);
433 }
434 return $this;
435 }
436
437 /**
438 * shuts down socket for receiving, sending or both
439 *
440 * @param int $how 0 = shutdown reading, 1 = shutdown writing, 2 = shutdown reading and writing
441 * @return self $this (chainable)
442 * @throws Exception on error
443 * @throws \Error PHP 8 only: throws \Error when socket or arguments are invalid
444 * @see self::close()
445 * @uses socket_shutdown()
446 */
447 public function shutdown($how = 2)
448 {
449 $ret = @socket_shutdown($this->resource, $how);
450 if ($ret === false) {
451 throw Exception::createFromSocketResource($this->resource);
452 }
453 return $this;
454 }
455
456 /**
457 * write $buffer to connect()ed / accept()ed socket
458 *
459 * @param string $buffer
460 * @return int number of bytes actually written
461 * @throws Exception on error
462 * @throws \Error PHP 8 only: throws \Error when socket or arguments are invalid
463 * @see self::send() if you need to pass flags
464 * @uses socket_write()
465 */
466 public function write($buffer)
467 {
468 $ret = @socket_write($this->resource, $buffer);
469 if ($ret === false) {
470 throw Exception::createFromSocketResource($this->resource);
471 }
472 return $ret;
473 }
474
475 /**
476 * get socket type as passed to socket_create()
477 *
478 * @return int usually either SOCK_STREAM or SOCK_DGRAM
479 * @throws Exception on error
480 * @throws \Error PHP 8 only: throws \Error when socket is invalid
481 * @uses self::getOption()
482 */
483 public function getType()
484 {
485 return $this->getOption(SOL_SOCKET, SO_TYPE);
486 }
487
488 /**
489 * assert that this socket is alive and its error code is 0
490 *
491 * This will fetch and reset the current socket error code from the
492 * socket and options and will throw an Exception along with error
493 * message and code if the code is not 0, i.e. if it does indicate
494 * an error situation.
495 *
496 * Calling this method should not be needed in most cases and is
497 * likely to not throw an Exception. Each socket operation like
498 * connect(), send(), etc. will throw a dedicated Exception in case
499 * of an error anyway.
500 *
501 * @return self $this (chainable)
502 * @throws Exception if error code is not 0
503 * @throws \Error PHP 8 only: throws \Error when socket is invalid
504 * @uses self::getOption() to retrieve and clear current error code
505 * @uses self::getErrorMessage() to translate error code to
506 */
507 public function assertAlive()
508 {
509 $code = $this->getOption(SOL_SOCKET, SO_ERROR);
510 if ($code !== 0) {
511 throw Exception::createFromCode($code, 'Socket error');
512 }
513 return $this;
514 }
515
516 /**
517 * format given address/host/path and port
518 *
519 * @param string $address
520 * @param int $port
521 * @return string
522 */
523 protected function formatAddress($address, $port)
524 {
525 if ($port !== 0) {
526 if (strpos($address, ':') !== false) {
527 $address = '[' . $address . ']';
528 }
529 $address .= ':' . $port;
530 }
531 return $address;
532 }
533
534 /**
535 * format given address by splitting it into returned address and port set by reference
536 *
537 * @param string $address
538 * @param int $port
539 * @return string address with port removed
540 */
541 protected function unformatAddress($address, &$port)
542 {
543 // [::1]:2 => ::1 2
544 // test:2 => test 2
545 // ::1 => ::1
546 // test => test
547
548 $colon = strrpos($address, ':');
549
550 // there is a colon and this is the only colon or there's a closing IPv6 bracket right before it
551 if ($colon !== false && (strpos($address, ':') === $colon || strpos($address, ']') === ($colon - 1))) {
552 $port = (int)substr($address, $colon + 1);
553 $address = substr($address, 0, $colon);
554
555 // remove IPv6 square brackets
556 if (substr($address, 0, 1) === '[') {
557 $address = substr($address, 1, -1);
558 }
559 }
560 return $address;
561 }
562 }