9 * Copyright (c) 1997-2017 The PHP Group
10 * All rights reserved.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
16 * o Redistributions of source code must retain the above copyright
17 * notice, this list of conditions and the following disclaimer.
18 * o Redistributions in binary form must reproduce the above copyright
19 * notice, this list of conditions and the following disclaimer in the
20 * documentation and/or other materials provided with the distribution.
22 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
25 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
26 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
27 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
28 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
32 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 * @author Stig Bakken <ssb@php.net>
37 * @author Chuck Hagenbuch <chuck@horde.org>
38 * @copyright 1997-2017 The PHP Group
39 * @license http://opensource.org/licenses/bsd-license.php BSD-2-Clause
40 * @link http://pear.php.net/packages/Net_Socket
43 require_once 'PEAR.php';
45 define('NET_SOCKET_READ', 1);
46 define('NET_SOCKET_WRITE', 2);
47 define('NET_SOCKET_ERROR', 4);
50 * Generalized Socket class.
54 * @author Stig Bakken <ssb@php.net>
55 * @author Chuck Hagenbuch <chuck@horde.org>
56 * @copyright 1997-2017 The PHP Group
57 * @license http://opensource.org/licenses/bsd-license.php BSD-2-Clause
58 * @link http://pear.php.net/packages/Net_Socket
60 class Net_Socket extends PEAR
63 * Socket file pointer.
69 * Whether the socket is blocking. Defaults to true.
70 * @var boolean $blocking
72 public $blocking = true;
75 * Whether the socket is persistent. Defaults to false.
76 * @var boolean $persistent
78 public $persistent = false;
81 * The IP address to connect to.
87 * The port number to connect to.
93 * Number of seconds to wait on socket operations before assuming
94 * there's no more data. Defaults to no timeout.
95 * @var integer|float $timeout
97 public $timeout = null;
100 * Number of bytes to read at a time in readLine() and
101 * readAll(). Defaults to 2048.
102 * @var integer $lineLength
104 public $lineLength = 2048;
107 * The string to use as a newline terminator. Usually "\r\n" or "\n".
108 * @var string $newline
110 public $newline = "\r\n";
113 * Connect to the specified port. If called when the socket is
114 * already connected, it disconnects and connects again.
116 * @param string $addr IP address or host name (may be with protocol prefix).
117 * @param integer $port TCP port number.
118 * @param boolean $persistent (optional) Whether the connection is
119 * persistent (kept open between requests
120 * by the web server).
121 * @param integer $timeout (optional) Connection socket timeout.
122 * @param array $options See options for stream_context_create.
126 * @return boolean|PEAR_Error True on success or a PEAR_Error on failure.
128 public function connect(
135 if (is_resource($this->fp)) {
141 return $this->raiseError('$addr cannot be empty');
143 if (strspn($addr, ':.0123456789') === strlen($addr)) {
144 $this->addr = strpos($addr, ':') !== false ? '[' . $addr . ']' : $addr;
150 $this->port = $port % 65536;
152 if ($persistent !== null) {
153 $this->persistent = $persistent;
156 $openfunc = $this->persistent ? 'pfsockopen' : 'fsockopen';
160 $old_track_errors = @ini_set('track_errors', 1);
163 $timeout = @ini_get('default_socket_timeout');
166 if ($options && function_exists('stream_context_create')) {
167 $context = stream_context_create($options);
169 // Since PHP 5 fsockopen doesn't allow context specification
170 if (function_exists('stream_socket_client')) {
171 $flags = STREAM_CLIENT_CONNECT;
173 if ($this->persistent) {
174 $flags = STREAM_CLIENT_PERSISTENT;
177 $addr = $this->addr . ':' . $this->port;
178 $fp = @stream_socket_client($addr, $errno, $errstr,
179 $timeout, $flags, $context);
181 $fp = @$openfunc($this->addr, $this->port, $errno,
182 $errstr, $timeout, $context);
185 $fp = @$openfunc($this->addr, $this->port, $errno, $errstr, $timeout);
189 if ($errno === 0 && !strlen($errstr) && isset($php_errormsg)) {
190 $errstr = $php_errormsg;
192 @ini_set('track_errors', $old_track_errors);
194 return $this->raiseError($errstr, $errno);
197 @ini_set('track_errors', $old_track_errors);
201 return $this->setBlocking($this->blocking);
205 * Disconnects from the peer, closes the socket.
208 * @return mixed true on success or a PEAR_Error instance otherwise
210 public function disconnect()
212 if (!is_resource($this->fp)) {
213 return $this->raiseError('not connected');
223 * Set the newline character/sequence to use.
225 * @param string $newline Newline character(s)
226 * @return boolean True
228 public function setNewline($newline)
230 $this->newline = $newline;
236 * Find out if the socket is in blocking mode.
239 * @return boolean The current blocking mode.
241 public function isBlocking()
243 return $this->blocking;
247 * Sets whether the socket connection should be blocking or
248 * not. A read call to a non-blocking socket will return immediately
249 * if there is no data available, whereas it will block until there
250 * is data for blocking sockets.
252 * @param boolean $mode True for blocking sockets, false for nonblocking.
255 * @return mixed true on success or a PEAR_Error instance otherwise
257 public function setBlocking($mode)
259 if (!is_resource($this->fp)) {
260 return $this->raiseError('not connected');
263 $this->blocking = $mode;
264 stream_set_blocking($this->fp, (int)$this->blocking);
270 * Sets the timeout value on socket descriptor,
271 * expressed in the sum of seconds and microseconds
273 * @param integer $seconds Seconds.
274 * @param integer $microseconds Microseconds, optional.
277 * @return mixed True on success or false on failure or
278 * a PEAR_Error instance when not connected
280 public function setTimeout($seconds = null, $microseconds = null)
282 if (!is_resource($this->fp)) {
283 return $this->raiseError('not connected');
286 if ($seconds === null && $microseconds === null) {
287 $seconds = (int)$this->timeout;
288 $microseconds = (int)(($this->timeout - $seconds) * 1000000);
290 $this->timeout = $seconds + $microseconds / 1000000;
293 if ($this->timeout > 0) {
294 return stream_set_timeout($this->fp, (int)$seconds, (int)$microseconds);
301 * Sets the file buffering size on the stream.
302 * See php's stream_set_write_buffer for more information.
304 * @param integer $size Write buffer size.
307 * @return mixed on success or an PEAR_Error object otherwise
309 public function setWriteBuffer($size)
311 if (!is_resource($this->fp)) {
312 return $this->raiseError('not connected');
315 $returned = stream_set_write_buffer($this->fp, $size);
316 if ($returned === 0) {
320 return $this->raiseError('Cannot set write buffer.');
324 * Returns information about an existing socket resource.
325 * Currently returns four entries in the result array:
328 * timed_out (bool) - The socket timed out waiting for data<br>
329 * blocked (bool) - The socket was blocked<br>
330 * eof (bool) - Indicates EOF event<br>
331 * unread_bytes (int) - Number of bytes left in the socket buffer<br>
335 * @return mixed Array containing information about existing socket
336 * resource or a PEAR_Error instance otherwise
338 public function getStatus()
340 if (!is_resource($this->fp)) {
341 return $this->raiseError('not connected');
344 return stream_get_meta_data($this->fp);
348 * Get a specified line of data
350 * @param int $size Reading ends when size - 1 bytes have been read,
351 * or a newline or an EOF (whichever comes first).
352 * If no size is specified, it will keep reading from
353 * the stream until it reaches the end of the line.
356 * @return mixed $size bytes of data from the socket, or a PEAR_Error if
357 * not connected. If an error occurs, FALSE is returned.
359 public function gets($size = null)
361 if (!is_resource($this->fp)) {
362 return $this->raiseError('not connected');
365 if (null === $size) {
366 return @fgets($this->fp);
368 return @fgets($this->fp, $size);
373 * Read a specified amount of data. This is guaranteed to return,
374 * and has the added benefit of getting everything in one fread()
375 * chunk; if you know the size of the data you're getting
376 * beforehand, this is definitely the way to go.
378 * @param integer $size The number of bytes to read from the socket.
381 * @return string $size bytes of data from the socket, or a PEAR_Error if
384 public function read($size)
386 if (!is_resource($this->fp)) {
387 return $this->raiseError('not connected');
390 return @fread($this->fp, $size);
394 * Write a specified amount of data.
396 * @param string $data Data to write.
397 * @param integer $blocksize Amount of data to write at once.
398 * NULL means all at once.
401 * @return mixed If the socket is not connected, returns an instance of
403 * If the write succeeds, returns the number of bytes written.
404 * If the write fails, returns false.
405 * If the socket times out, returns an instance of PEAR_Error.
407 public function write($data, $blocksize = null)
409 if (!is_resource($this->fp)) {
410 return $this->raiseError('not connected');
413 if (null === $blocksize && !OS_WINDOWS) {
414 $written = @fwrite($this->fp, $data);
416 // Check for timeout or lost connection
417 if ($written === false) {
418 $meta_data = $this->getStatus();
420 if (!is_array($meta_data)) {
421 return $meta_data; // PEAR_Error
424 if (!empty($meta_data['timed_out'])) {
425 return $this->raiseError('timed out');
431 if (null === $blocksize) {
436 $size = strlen($data);
437 while ($pos < $size) {
438 $written = @fwrite($this->fp, substr($data, $pos, $blocksize));
440 // Check for timeout or lost connection
441 if ($written === false) {
442 $meta_data = $this->getStatus();
444 if (!is_array($meta_data)) {
445 return $meta_data; // PEAR_Error
448 if (!empty($meta_data['timed_out'])) {
449 return $this->raiseError('timed out');
463 * Write a line of data to the socket, followed by a trailing newline.
465 * @param string $data Data to write
468 * @return mixed fwrite() result, or PEAR_Error when not connected
470 public function writeLine($data)
472 if (!is_resource($this->fp)) {
473 return $this->raiseError('not connected');
476 return fwrite($this->fp, $data . $this->newline);
480 * Tests for end-of-file on a socket descriptor.
482 * Also returns true if the socket is disconnected.
487 public function eof()
489 return (!is_resource($this->fp) || feof($this->fp));
493 * Reads a byte of data
496 * @return integer 1 byte of data from the socket, or a PEAR_Error if
499 public function readByte()
501 if (!is_resource($this->fp)) {
502 return $this->raiseError('not connected');
505 return ord(@fread($this->fp, 1));
509 * Reads a word of data
512 * @return integer 1 word of data from the socket, or a PEAR_Error if
515 public function readWord()
517 if (!is_resource($this->fp)) {
518 return $this->raiseError('not connected');
521 $buf = @fread($this->fp, 2);
523 return (ord($buf[0]) + (ord($buf[1]) << 8));
527 * Reads an int of data
530 * @return integer 1 int of data from the socket, or a PEAR_Error if
533 public function readInt()
535 if (!is_resource($this->fp)) {
536 return $this->raiseError('not connected');
539 $buf = @fread($this->fp, 4);
541 return (ord($buf[0]) + (ord($buf[1]) << 8) +
542 (ord($buf[2]) << 16) + (ord($buf[3]) << 24));
546 * Reads a zero-terminated string of data
549 * @return string, or a PEAR_Error if
552 public function readString()
554 if (!is_resource($this->fp)) {
555 return $this->raiseError('not connected');
559 while (($char = @fread($this->fp, 1)) !== "\x00") {
567 * Reads an IP Address and returns it in a dot formatted string
570 * @return string Dot formatted string, or a PEAR_Error if
573 public function readIPAddress()
575 if (!is_resource($this->fp)) {
576 return $this->raiseError('not connected');
579 $buf = @fread($this->fp, 4);
581 return sprintf('%d.%d.%d.%d', ord($buf[0]), ord($buf[1]),
582 ord($buf[2]), ord($buf[3]));
586 * Read until either the end of the socket or a newline, whichever
587 * comes first. Strips the trailing newline from the returned data.
590 * @return string All available data up to a newline, without that
591 * newline, or until the end of the socket, or a PEAR_Error if
594 public function readLine()
596 if (!is_resource($this->fp)) {
597 return $this->raiseError('not connected');
602 $timeout = time() + $this->timeout;
604 while (!feof($this->fp) && (!$this->timeout || time() < $timeout)) {
605 $line .= @fgets($this->fp, $this->lineLength);
606 if (substr($line, -1) == "\n") {
607 return rtrim($line, $this->newline);
615 * Read until the socket closes, or until there is no more data in
616 * the inner PHP buffer. If the inner buffer is empty, in blocking
617 * mode we wait for at least 1 byte of data. Therefore, in
618 * blocking mode, if there is no data at all to be read, this
619 * function will never exit (unless the socket is closed on the
624 * @return string All data until the socket closes, or a PEAR_Error if
627 public function readAll()
629 if (!is_resource($this->fp)) {
630 return $this->raiseError('not connected');
634 $timeout = time() + $this->timeout;
636 while (!feof($this->fp) && (!$this->timeout || time() < $timeout)) {
637 $data .= @fread($this->fp, $this->lineLength);
644 * Runs the equivalent of the select() system call on the socket
645 * with a timeout specified by tv_sec and tv_usec.
647 * @param integer $state Which of read/write/error to check for.
648 * @param integer $tv_sec Number of seconds for timeout.
649 * @param integer $tv_usec Number of microseconds for timeout.
652 * @return False if select fails, integer describing which of read/write/error
653 * are ready, or PEAR_Error if not connected.
655 public function select($state, $tv_sec, $tv_usec = 0)
657 if (!is_resource($this->fp)) {
658 return $this->raiseError('not connected');
664 if ($state & NET_SOCKET_READ) {
667 if ($state & NET_SOCKET_WRITE) {
668 $write[] = $this->fp;
670 if ($state & NET_SOCKET_ERROR) {
671 $except[] = $this->fp;
673 if (false === ($sr = stream_select($read, $write, $except,
681 $result |= NET_SOCKET_READ;
684 $result |= NET_SOCKET_WRITE;
686 if (count($except)) {
687 $result |= NET_SOCKET_ERROR;
694 * Turns encryption on/off on a connected socket.
696 * @param bool $enabled Set this parameter to true to enable encryption
697 * and false to disable encryption.
698 * @param integer $type Type of encryption. See stream_socket_enable_crypto()
701 * @see http://se.php.net/manual/en/function.stream-socket-enable-crypto.php
703 * @return false on error, true on success and 0 if there isn't enough data
704 * and the user should try again (non-blocking sockets only).
705 * A PEAR_Error object is returned if the socket is not
708 public function enableCrypto($enabled, $type)
710 if (version_compare(phpversion(), '5.1.0', '>=')) {
711 if (!is_resource($this->fp)) {
712 return $this->raiseError('not connected');
715 return @stream_socket_enable_crypto($this->fp, $enabled, $type);
717 $msg = 'Net_Socket::enableCrypto() requires php version >= 5.1.0';
719 return $this->raiseError($msg);