Socket.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  1. <?php
  2. //
  3. // +----------------------------------------------------------------------+
  4. // | PHP Version 4 |
  5. // +----------------------------------------------------------------------+
  6. // | Copyright (c) 1997-2003 The PHP Group |
  7. // +----------------------------------------------------------------------+
  8. // | This source file is subject to version 2.0 of the PHP license, |
  9. // | that is bundled with this package in the file LICENSE, and is |
  10. // | available at through the world-wide-web at |
  11. // | http://www.php.net/license/2_02.txt. |
  12. // | If you did not receive a copy of the PHP license and are unable to |
  13. // | obtain it through the world-wide-web, please send a note to |
  14. // | license@php.net so we can mail you a copy immediately. |
  15. // +----------------------------------------------------------------------+
  16. // | Authors: Stig Bakken <ssb@php.net> |
  17. // | Chuck Hagenbuch <chuck@horde.org> |
  18. // +----------------------------------------------------------------------+
  19. //
  20. // $Id: Socket.php,v 1.38 2008/02/15 18:24:17 chagenbu Exp $
  21. require_once 'PEAR.php';
  22. define('NET_SOCKET_READ', 1);
  23. define('NET_SOCKET_WRITE', 2);
  24. define('NET_SOCKET_ERROR', 4);
  25. /**
  26. * Generalized Socket class.
  27. *
  28. * @version 1.1
  29. * @author Stig Bakken <ssb@php.net>
  30. * @author Chuck Hagenbuch <chuck@horde.org>
  31. */
  32. class Net_Socket extends PEAR {
  33. /**
  34. * Socket file pointer.
  35. * @var resource $fp
  36. */
  37. var $fp = null;
  38. /**
  39. * Whether the socket is blocking. Defaults to true.
  40. * @var boolean $blocking
  41. */
  42. var $blocking = true;
  43. /**
  44. * Whether the socket is persistent. Defaults to false.
  45. * @var boolean $persistent
  46. */
  47. var $persistent = false;
  48. /**
  49. * The IP address to connect to.
  50. * @var string $addr
  51. */
  52. var $addr = '';
  53. /**
  54. * The port number to connect to.
  55. * @var integer $port
  56. */
  57. var $port = 0;
  58. /**
  59. * Number of seconds to wait on socket connections before assuming
  60. * there's no more data. Defaults to no timeout.
  61. * @var integer $timeout
  62. */
  63. var $timeout = false;
  64. /**
  65. * Number of bytes to read at a time in readLine() and
  66. * readAll(). Defaults to 2048.
  67. * @var integer $lineLength
  68. */
  69. var $lineLength = 2048;
  70. /**
  71. * Connect to the specified port. If called when the socket is
  72. * already connected, it disconnects and connects again.
  73. *
  74. * @param string $addr IP address or host name.
  75. * @param integer $port TCP port number.
  76. * @param boolean $persistent (optional) Whether the connection is
  77. * persistent (kept open between requests
  78. * by the web server).
  79. * @param integer $timeout (optional) How long to wait for data.
  80. * @param array $options See options for stream_context_create.
  81. *
  82. * @access public
  83. *
  84. * @return boolean | PEAR_Error True on success or a PEAR_Error on failure.
  85. */
  86. function connect($addr, $port = 0, $persistent = null, $timeout = null, $options = null)
  87. {
  88. if (is_resource($this->fp)) {
  89. @fclose($this->fp);
  90. $this->fp = null;
  91. }
  92. if (!$addr) {
  93. return $this->raiseError('$addr cannot be empty');
  94. } elseif (strspn($addr, '.0123456789') == strlen($addr) ||
  95. strstr($addr, '/') !== false) {
  96. $this->addr = $addr;
  97. } else {
  98. $this->addr = @gethostbyname($addr);
  99. }
  100. $this->port = $port % 65536;
  101. if ($persistent !== null) {
  102. $this->persistent = $persistent;
  103. }
  104. if ($timeout !== null) {
  105. $this->timeout = $timeout;
  106. }
  107. $openfunc = $this->persistent ? 'pfsockopen' : 'fsockopen';
  108. $errno = 0;
  109. $errstr = '';
  110. $old_track_errors = @ini_set('track_errors', 1);
  111. if ($options && function_exists('stream_context_create')) {
  112. if ($this->timeout) {
  113. $timeout = $this->timeout;
  114. } else {
  115. $timeout = 0;
  116. }
  117. $context = stream_context_create($options);
  118. // Since PHP 5 fsockopen doesn't allow context specification
  119. if (function_exists('stream_socket_client')) {
  120. $flags = $this->persistent ? STREAM_CLIENT_PERSISTENT : STREAM_CLIENT_CONNECT;
  121. $addr = $this->addr . ':' . $this->port;
  122. $fp = stream_socket_client($addr, $errno, $errstr, $timeout, $flags, $context);
  123. } else {
  124. $fp = @$openfunc($this->addr, $this->port, $errno, $errstr, $timeout, $context);
  125. }
  126. } else {
  127. if ($this->timeout) {
  128. $fp = @$openfunc($this->addr, $this->port, $errno, $errstr, $this->timeout);
  129. } else {
  130. $fp = @$openfunc($this->addr, $this->port, $errno, $errstr);
  131. }
  132. }
  133. if (!$fp) {
  134. if ($errno == 0 && isset($php_errormsg)) {
  135. $errstr = $php_errormsg;
  136. }
  137. @ini_set('track_errors', $old_track_errors);
  138. return $this->raiseError($errstr, $errno);
  139. }
  140. @ini_set('track_errors', $old_track_errors);
  141. $this->fp = $fp;
  142. return $this->setBlocking($this->blocking);
  143. }
  144. /**
  145. * Disconnects from the peer, closes the socket.
  146. *
  147. * @access public
  148. * @return mixed true on success or a PEAR_Error instance otherwise
  149. */
  150. function disconnect()
  151. {
  152. if (!is_resource($this->fp)) {
  153. return $this->raiseError('not connected');
  154. }
  155. @fclose($this->fp);
  156. $this->fp = null;
  157. return true;
  158. }
  159. /**
  160. * Find out if the socket is in blocking mode.
  161. *
  162. * @access public
  163. * @return boolean The current blocking mode.
  164. */
  165. function isBlocking()
  166. {
  167. return $this->blocking;
  168. }
  169. /**
  170. * Sets whether the socket connection should be blocking or
  171. * not. A read call to a non-blocking socket will return immediately
  172. * if there is no data available, whereas it will block until there
  173. * is data for blocking sockets.
  174. *
  175. * @param boolean $mode True for blocking sockets, false for nonblocking.
  176. * @access public
  177. * @return mixed true on success or a PEAR_Error instance otherwise
  178. */
  179. function setBlocking($mode)
  180. {
  181. if (!is_resource($this->fp)) {
  182. return $this->raiseError('not connected');
  183. }
  184. $this->blocking = $mode;
  185. socket_set_blocking($this->fp, $this->blocking);
  186. return true;
  187. }
  188. /**
  189. * Sets the timeout value on socket descriptor,
  190. * expressed in the sum of seconds and microseconds
  191. *
  192. * @param integer $seconds Seconds.
  193. * @param integer $microseconds Microseconds.
  194. * @access public
  195. * @return mixed true on success or a PEAR_Error instance otherwise
  196. */
  197. function setTimeout($seconds, $microseconds)
  198. {
  199. if (!is_resource($this->fp)) {
  200. return $this->raiseError('not connected');
  201. }
  202. return socket_set_timeout($this->fp, $seconds, $microseconds);
  203. }
  204. /**
  205. * Sets the file buffering size on the stream.
  206. * See php's stream_set_write_buffer for more information.
  207. *
  208. * @param integer $size Write buffer size.
  209. * @access public
  210. * @return mixed on success or an PEAR_Error object otherwise
  211. */
  212. function setWriteBuffer($size)
  213. {
  214. if (!is_resource($this->fp)) {
  215. return $this->raiseError('not connected');
  216. }
  217. $returned = stream_set_write_buffer($this->fp, $size);
  218. if ($returned == 0) {
  219. return true;
  220. }
  221. return $this->raiseError('Cannot set write buffer.');
  222. }
  223. /**
  224. * Returns information about an existing socket resource.
  225. * Currently returns four entries in the result array:
  226. *
  227. * <p>
  228. * timed_out (bool) - The socket timed out waiting for data<br>
  229. * blocked (bool) - The socket was blocked<br>
  230. * eof (bool) - Indicates EOF event<br>
  231. * unread_bytes (int) - Number of bytes left in the socket buffer<br>
  232. * </p>
  233. *
  234. * @access public
  235. * @return mixed Array containing information about existing socket resource or a PEAR_Error instance otherwise
  236. */
  237. function getStatus()
  238. {
  239. if (!is_resource($this->fp)) {
  240. return $this->raiseError('not connected');
  241. }
  242. return socket_get_status($this->fp);
  243. }
  244. /**
  245. * Get a specified line of data
  246. *
  247. * @access public
  248. * @return $size bytes of data from the socket, or a PEAR_Error if
  249. * not connected.
  250. */
  251. function gets($size)
  252. {
  253. if (!is_resource($this->fp)) {
  254. return $this->raiseError('not connected');
  255. }
  256. return @fgets($this->fp, $size);
  257. }
  258. /**
  259. * Read a specified amount of data. This is guaranteed to return,
  260. * and has the added benefit of getting everything in one fread()
  261. * chunk; if you know the size of the data you're getting
  262. * beforehand, this is definitely the way to go.
  263. *
  264. * @param integer $size The number of bytes to read from the socket.
  265. * @access public
  266. * @return $size bytes of data from the socket, or a PEAR_Error if
  267. * not connected.
  268. */
  269. function read($size)
  270. {
  271. if (!is_resource($this->fp)) {
  272. return $this->raiseError('not connected');
  273. }
  274. return @fread($this->fp, $size);
  275. }
  276. /**
  277. * Write a specified amount of data.
  278. *
  279. * @param string $data Data to write.
  280. * @param integer $blocksize Amount of data to write at once.
  281. * NULL means all at once.
  282. *
  283. * @access public
  284. * @return mixed If the socket is not connected, returns an instance of PEAR_Error
  285. * If the write succeeds, returns the number of bytes written
  286. * If the write fails, returns false.
  287. */
  288. function write($data, $blocksize = null)
  289. {
  290. if (!is_resource($this->fp)) {
  291. return $this->raiseError('not connected');
  292. }
  293. if (is_null($blocksize) && !OS_WINDOWS) {
  294. return @fwrite($this->fp, $data);
  295. } else {
  296. if (is_null($blocksize)) {
  297. $blocksize = 1024;
  298. }
  299. $pos = 0;
  300. $size = strlen($data);
  301. while ($pos < $size) {
  302. $written = @fwrite($this->fp, substr($data, $pos, $blocksize));
  303. if ($written === false) {
  304. return false;
  305. }
  306. $pos += $written;
  307. }
  308. return $pos;
  309. }
  310. }
  311. /**
  312. * Write a line of data to the socket, followed by a trailing "\r\n".
  313. *
  314. * @access public
  315. * @return mixed fputs result, or an error
  316. */
  317. function writeLine($data)
  318. {
  319. if (!is_resource($this->fp)) {
  320. return $this->raiseError('not connected');
  321. }
  322. return fwrite($this->fp, $data . "\r\n");
  323. }
  324. /**
  325. * Tests for end-of-file on a socket descriptor.
  326. *
  327. * Also returns true if the socket is disconnected.
  328. *
  329. * @access public
  330. * @return bool
  331. */
  332. function eof()
  333. {
  334. return (!is_resource($this->fp) || feof($this->fp));
  335. }
  336. /**
  337. * Reads a byte of data
  338. *
  339. * @access public
  340. * @return 1 byte of data from the socket, or a PEAR_Error if
  341. * not connected.
  342. */
  343. function readByte()
  344. {
  345. if (!is_resource($this->fp)) {
  346. return $this->raiseError('not connected');
  347. }
  348. return ord(@fread($this->fp, 1));
  349. }
  350. /**
  351. * Reads a word of data
  352. *
  353. * @access public
  354. * @return 1 word of data from the socket, or a PEAR_Error if
  355. * not connected.
  356. */
  357. function readWord()
  358. {
  359. if (!is_resource($this->fp)) {
  360. return $this->raiseError('not connected');
  361. }
  362. $buf = @fread($this->fp, 2);
  363. return (ord($buf[0]) + (ord($buf[1]) << 8));
  364. }
  365. /**
  366. * Reads an int of data
  367. *
  368. * @access public
  369. * @return integer 1 int of data from the socket, or a PEAR_Error if
  370. * not connected.
  371. */
  372. function readInt()
  373. {
  374. if (!is_resource($this->fp)) {
  375. return $this->raiseError('not connected');
  376. }
  377. $buf = @fread($this->fp, 4);
  378. return (ord($buf[0]) + (ord($buf[1]) << 8) +
  379. (ord($buf[2]) << 16) + (ord($buf[3]) << 24));
  380. }
  381. /**
  382. * Reads a zero-terminated string of data
  383. *
  384. * @access public
  385. * @return string, or a PEAR_Error if
  386. * not connected.
  387. */
  388. function readString()
  389. {
  390. if (!is_resource($this->fp)) {
  391. return $this->raiseError('not connected');
  392. }
  393. $string = '';
  394. while (($char = @fread($this->fp, 1)) != "\x00") {
  395. $string .= $char;
  396. }
  397. return $string;
  398. }
  399. /**
  400. * Reads an IP Address and returns it in a dot formatted string
  401. *
  402. * @access public
  403. * @return Dot formatted string, or a PEAR_Error if
  404. * not connected.
  405. */
  406. function readIPAddress()
  407. {
  408. if (!is_resource($this->fp)) {
  409. return $this->raiseError('not connected');
  410. }
  411. $buf = @fread($this->fp, 4);
  412. return sprintf('%d.%d.%d.%d', ord($buf[0]), ord($buf[1]),
  413. ord($buf[2]), ord($buf[3]));
  414. }
  415. /**
  416. * Read until either the end of the socket or a newline, whichever
  417. * comes first. Strips the trailing newline from the returned data.
  418. *
  419. * @access public
  420. * @return All available data up to a newline, without that
  421. * newline, or until the end of the socket, or a PEAR_Error if
  422. * not connected.
  423. */
  424. function readLine()
  425. {
  426. if (!is_resource($this->fp)) {
  427. return $this->raiseError('not connected');
  428. }
  429. $line = '';
  430. $timeout = time() + $this->timeout;
  431. while (!feof($this->fp) && (!$this->timeout || time() < $timeout)) {
  432. $line .= @fgets($this->fp, $this->lineLength);
  433. if (substr($line, -1) == "\n") {
  434. return rtrim($line, "\r\n");
  435. }
  436. }
  437. return $line;
  438. }
  439. /**
  440. * Read until the socket closes, or until there is no more data in
  441. * the inner PHP buffer. If the inner buffer is empty, in blocking
  442. * mode we wait for at least 1 byte of data. Therefore, in
  443. * blocking mode, if there is no data at all to be read, this
  444. * function will never exit (unless the socket is closed on the
  445. * remote end).
  446. *
  447. * @access public
  448. *
  449. * @return string All data until the socket closes, or a PEAR_Error if
  450. * not connected.
  451. */
  452. function readAll()
  453. {
  454. if (!is_resource($this->fp)) {
  455. return $this->raiseError('not connected');
  456. }
  457. $data = '';
  458. while (!feof($this->fp)) {
  459. $data .= @fread($this->fp, $this->lineLength);
  460. }
  461. return $data;
  462. }
  463. /**
  464. * Runs the equivalent of the select() system call on the socket
  465. * with a timeout specified by tv_sec and tv_usec.
  466. *
  467. * @param integer $state Which of read/write/error to check for.
  468. * @param integer $tv_sec Number of seconds for timeout.
  469. * @param integer $tv_usec Number of microseconds for timeout.
  470. *
  471. * @access public
  472. * @return False if select fails, integer describing which of read/write/error
  473. * are ready, or PEAR_Error if not connected.
  474. */
  475. function select($state, $tv_sec, $tv_usec = 0)
  476. {
  477. if (!is_resource($this->fp)) {
  478. return $this->raiseError('not connected');
  479. }
  480. $read = null;
  481. $write = null;
  482. $except = null;
  483. if ($state & NET_SOCKET_READ) {
  484. $read[] = $this->fp;
  485. }
  486. if ($state & NET_SOCKET_WRITE) {
  487. $write[] = $this->fp;
  488. }
  489. if ($state & NET_SOCKET_ERROR) {
  490. $except[] = $this->fp;
  491. }
  492. if (false === ($sr = stream_select($read, $write, $except, $tv_sec, $tv_usec))) {
  493. return false;
  494. }
  495. $result = 0;
  496. if (count($read)) {
  497. $result |= NET_SOCKET_READ;
  498. }
  499. if (count($write)) {
  500. $result |= NET_SOCKET_WRITE;
  501. }
  502. if (count($except)) {
  503. $result |= NET_SOCKET_ERROR;
  504. }
  505. return $result;
  506. }
  507. /**
  508. * Turns encryption on/off on a connected socket.
  509. *
  510. * @param bool $enabled Set this parameter to true to enable encryption
  511. * and false to disable encryption.
  512. * @param integer $type Type of encryption. See
  513. * http://se.php.net/manual/en/function.stream-socket-enable-crypto.php for values.
  514. *
  515. * @access public
  516. * @return false on error, true on success and 0 if there isn't enough data and the
  517. * user should try again (non-blocking sockets only). A PEAR_Error object
  518. * is returned if the socket is not connected
  519. */
  520. function enableCrypto($enabled, $type)
  521. {
  522. if (version_compare(phpversion(), "5.1.0", ">=")) {
  523. if (!is_resource($this->fp)) {
  524. return $this->raiseError('not connected');
  525. }
  526. return @stream_socket_enable_crypto($this->fp, $enabled, $type);
  527. } else {
  528. return $this->raiseError('Net_Socket::enableCrypto() requires php version >= 5.1.0');
  529. }
  530. }
  531. }