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 if (function_exists('error_clear_last')) {
163 $old_track_errors = @ini_set('track_errors', 1);
167 $timeout = @ini_get('default_socket_timeout');
170 if ($options && function_exists('stream_context_create')) {
171 $context = stream_context_create($options);
173 // Since PHP 5 fsockopen doesn't allow context specification
174 if (function_exists('stream_socket_client')) {
175 $flags = STREAM_CLIENT_CONNECT;
177 if ($this->persistent) {
178 $flags = STREAM_CLIENT_PERSISTENT;
181 $addr = $this->addr . ':' . $this->port;
182 $fp = @stream_socket_client($addr, $errno, $errstr,
183 $timeout, $flags, $context);
185 $fp = @$openfunc($this->addr, $this->port, $errno,
186 $errstr, $timeout, $context);
189 $fp = @$openfunc($this->addr, $this->port, $errno, $errstr, $timeout);
193 if ($errno === 0 && !strlen($errstr)) {
195 if (isset($old_track_errors)) {
196 $errstr = $php_errormsg ?: '';
197 @ini_set('track_errors', $old_track_errors);
199 $lastError = error_get_last();
200 if (isset($lastError['message'])) {
201 $errstr = $lastError['message'];
206 return $this->raiseError($errstr, $errno);
209 if (isset($old_track_errors)) {
210 @ini_set('track_errors', $old_track_errors);
216 return $this->setBlocking($this->blocking);
220 * Disconnects from the peer, closes the socket.
223 * @return mixed true on success or a PEAR_Error instance otherwise
225 public function disconnect()
227 if (!is_resource($this->fp)) {
228 return $this->raiseError('not connected');
238 * Set the newline character/sequence to use.
240 * @param string $newline Newline character(s)
241 * @return boolean True
243 public function setNewline($newline)
245 $this->newline = $newline;
251 * Find out if the socket is in blocking mode.
254 * @return boolean The current blocking mode.
256 public function isBlocking()
258 return $this->blocking;
262 * Sets whether the socket connection should be blocking or
263 * not. A read call to a non-blocking socket will return immediately
264 * if there is no data available, whereas it will block until there
265 * is data for blocking sockets.
267 * @param boolean $mode True for blocking sockets, false for nonblocking.
270 * @return mixed true on success or a PEAR_Error instance otherwise
272 public function setBlocking($mode)
274 if (!is_resource($this->fp)) {
275 return $this->raiseError('not connected');
278 $this->blocking = $mode;
279 stream_set_blocking($this->fp, (int)$this->blocking);
285 * Sets the timeout value on socket descriptor,
286 * expressed in the sum of seconds and microseconds
288 * @param integer $seconds Seconds.
289 * @param integer $microseconds Microseconds, optional.
292 * @return mixed True on success or false on failure or
293 * a PEAR_Error instance when not connected
295 public function setTimeout($seconds = null, $microseconds = null)
297 if (!is_resource($this->fp)) {
298 return $this->raiseError('not connected');
301 if ($seconds === null && $microseconds === null) {
302 $seconds = (int)$this->timeout;
303 $microseconds = (int)(($this->timeout - $seconds) * 1000000);
305 $this->timeout = $seconds + $microseconds / 1000000;
308 if ($this->timeout > 0) {
309 return stream_set_timeout($this->fp, (int)$seconds, (int)$microseconds);
316 * Sets the file buffering size on the stream.
317 * See php's stream_set_write_buffer for more information.
319 * @param integer $size Write buffer size.
322 * @return mixed on success or an PEAR_Error object otherwise
324 public function setWriteBuffer($size)
326 if (!is_resource($this->fp)) {
327 return $this->raiseError('not connected');
330 $returned = stream_set_write_buffer($this->fp, $size);
331 if ($returned === 0) {
335 return $this->raiseError('Cannot set write buffer.');
339 * Returns information about an existing socket resource.
340 * Currently returns four entries in the result array:
343 * timed_out (bool) - The socket timed out waiting for data<br>
344 * blocked (bool) - The socket was blocked<br>
345 * eof (bool) - Indicates EOF event<br>
346 * unread_bytes (int) - Number of bytes left in the socket buffer<br>
350 * @return mixed Array containing information about existing socket
351 * resource or a PEAR_Error instance otherwise
353 public function getStatus()
355 if (!is_resource($this->fp)) {
356 return $this->raiseError('not connected');
359 return stream_get_meta_data($this->fp);
363 * Get a specified line of data
365 * @param int $size Reading ends when size - 1 bytes have been read,
366 * or a newline or an EOF (whichever comes first).
367 * If no size is specified, it will keep reading from
368 * the stream until it reaches the end of the line.
371 * @return mixed $size bytes of data from the socket, or a PEAR_Error if
372 * not connected. If an error occurs, FALSE is returned.
374 public function gets($size = null)
376 if (!is_resource($this->fp)) {
377 return $this->raiseError('not connected');
380 if (null === $size) {
381 return @fgets($this->fp);
383 return @fgets($this->fp, $size);
388 * Read a specified amount of data. This is guaranteed to return,
389 * and has the added benefit of getting everything in one fread()
390 * chunk; if you know the size of the data you're getting
391 * beforehand, this is definitely the way to go.
393 * @param integer $size The number of bytes to read from the socket.
396 * @return string $size bytes of data from the socket, or a PEAR_Error if
399 public function read($size)
401 if (!is_resource($this->fp)) {
402 return $this->raiseError('not connected');
405 return @fread($this->fp, $size);
409 * Write a specified amount of data.
411 * @param string $data Data to write.
412 * @param integer $blocksize Amount of data to write at once.
413 * NULL means all at once.
416 * @return mixed If the socket is not connected, returns an instance of
418 * If the write succeeds, returns the number of bytes written.
419 * If the write fails, returns false.
420 * If the socket times out, returns an instance of PEAR_Error.
422 public function write($data, $blocksize = null)
424 if (!is_resource($this->fp)) {
425 return $this->raiseError('not connected');
428 if (null === $blocksize && !OS_WINDOWS) {
429 $written = @fwrite($this->fp, $data);
431 // Check for timeout or lost connection
432 if ($written === false) {
433 $meta_data = $this->getStatus();
435 if (!is_array($meta_data)) {
436 return $meta_data; // PEAR_Error
439 if (!empty($meta_data['timed_out'])) {
440 return $this->raiseError('timed out');
446 if (null === $blocksize) {
451 $size = strlen($data);
452 while ($pos < $size) {
453 $written = @fwrite($this->fp, substr($data, $pos, $blocksize));
455 // Check for timeout or lost connection
456 if ($written === false) {
457 $meta_data = $this->getStatus();
459 if (!is_array($meta_data)) {
460 return $meta_data; // PEAR_Error
463 if (!empty($meta_data['timed_out'])) {
464 return $this->raiseError('timed out');
478 * Write a line of data to the socket, followed by a trailing newline.
480 * @param string $data Data to write
483 * @return mixed fwrite() result, or PEAR_Error when not connected
485 public function writeLine($data)
487 if (!is_resource($this->fp)) {
488 return $this->raiseError('not connected');
491 return fwrite($this->fp, $data . $this->newline);
495 * Tests for end-of-file on a socket descriptor.
497 * Also returns true if the socket is disconnected.
502 public function eof()
504 return (!is_resource($this->fp) || feof($this->fp));
508 * Reads a byte of data
511 * @return integer 1 byte of data from the socket, or a PEAR_Error if
514 public function readByte()
516 if (!is_resource($this->fp)) {
517 return $this->raiseError('not connected');
520 return ord(@fread($this->fp, 1));
524 * Reads a word of data
527 * @return integer 1 word of data from the socket, or a PEAR_Error if
530 public function readWord()
532 if (!is_resource($this->fp)) {
533 return $this->raiseError('not connected');
536 $buf = @fread($this->fp, 2);
538 return (ord($buf[0]) + (ord($buf[1]) << 8));
542 * Reads an int of data
545 * @return integer 1 int of data from the socket, or a PEAR_Error if
548 public function readInt()
550 if (!is_resource($this->fp)) {
551 return $this->raiseError('not connected');
554 $buf = @fread($this->fp, 4);
556 return (ord($buf[0]) + (ord($buf[1]) << 8) +
557 (ord($buf[2]) << 16) + (ord($buf[3]) << 24));
561 * Reads a zero-terminated string of data
564 * @return string, or a PEAR_Error if
567 public function readString()
569 if (!is_resource($this->fp)) {
570 return $this->raiseError('not connected');
574 while (($char = @fread($this->fp, 1)) !== "\x00") {
582 * Reads an IP Address and returns it in a dot formatted string
585 * @return string Dot formatted string, or a PEAR_Error if
588 public function readIPAddress()
590 if (!is_resource($this->fp)) {
591 return $this->raiseError('not connected');
594 $buf = @fread($this->fp, 4);
596 return sprintf('%d.%d.%d.%d', ord($buf[0]), ord($buf[1]),
597 ord($buf[2]), ord($buf[3]));
601 * Read until either the end of the socket or a newline, whichever
602 * comes first. Strips the trailing newline from the returned data.
605 * @return string All available data up to a newline, without that
606 * newline, or until the end of the socket, or a PEAR_Error if
609 public function readLine()
611 if (!is_resource($this->fp)) {
612 return $this->raiseError('not connected');
617 $timeout = time() + $this->timeout;
619 while (!feof($this->fp) && (!$this->timeout || time() < $timeout)) {
620 $line .= @fgets($this->fp, $this->lineLength);
621 if (substr($line, -1) == "\n") {
622 return rtrim($line, $this->newline);
630 * Read until the socket closes, or until there is no more data in
631 * the inner PHP buffer. If the inner buffer is empty, in blocking
632 * mode we wait for at least 1 byte of data. Therefore, in
633 * blocking mode, if there is no data at all to be read, this
634 * function will never exit (unless the socket is closed on the
639 * @return string All data until the socket closes, or a PEAR_Error if
642 public function readAll()
644 if (!is_resource($this->fp)) {
645 return $this->raiseError('not connected');
649 $timeout = time() + $this->timeout;
651 while (!feof($this->fp) && (!$this->timeout || time() < $timeout)) {
652 $data .= @fread($this->fp, $this->lineLength);
659 * Runs the equivalent of the select() system call on the socket
660 * with a timeout specified by tv_sec and tv_usec.
662 * @param integer $state Which of read/write/error to check for.
663 * @param integer $tv_sec Number of seconds for timeout.
664 * @param integer $tv_usec Number of microseconds for timeout.
667 * @return False if select fails, integer describing which of read/write/error
668 * are ready, or PEAR_Error if not connected.
670 public function select($state, $tv_sec, $tv_usec = 0)
672 if (!is_resource($this->fp)) {
673 return $this->raiseError('not connected');
679 if ($state & NET_SOCKET_READ) {
682 if ($state & NET_SOCKET_WRITE) {
683 $write[] = $this->fp;
685 if ($state & NET_SOCKET_ERROR) {
686 $except[] = $this->fp;
688 if (false === ($sr = stream_select($read, $write, $except,
696 $result |= NET_SOCKET_READ;
699 $result |= NET_SOCKET_WRITE;
701 if (count($except)) {
702 $result |= NET_SOCKET_ERROR;
709 * Turns encryption on/off on a connected socket.
711 * @param bool $enabled Set this parameter to true to enable encryption
712 * and false to disable encryption.
713 * @param integer $type Type of encryption. See stream_socket_enable_crypto()
716 * @see http://se.php.net/manual/en/function.stream-socket-enable-crypto.php
718 * @return false on error, true on success and 0 if there isn't enough data
719 * and the user should try again (non-blocking sockets only).
720 * A PEAR_Error object is returned if the socket is not
723 public function enableCrypto($enabled, $type)
725 if (version_compare(phpversion(), '5.1.0', '>=')) {
726 if (!is_resource($this->fp)) {
727 return $this->raiseError('not connected');
730 return @stream_socket_enable_crypto($this->fp, $enabled, $type);
732 $msg = 'Net_Socket::enableCrypto() requires php version >= 5.1.0';
734 return $this->raiseError($msg);