TcpConnection.class.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974
  1. <?php
  2. /**
  3. * This file is part of workerman.
  4. *
  5. * Licensed under The MIT License
  6. * For full copyright and license information, please see the MIT-LICENSE.txt
  7. * Redistributions of files must retain the above copyright notice.
  8. *
  9. * @author walkor<walkor@workerman.net>
  10. * @copyright walkor<walkor@workerman.net>
  11. * @link http://www.workerman.net/
  12. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  13. */
  14. namespace Workerman\Connection;
  15. use Workerman\Events\EventInterface;
  16. use Workerman\Worker;
  17. use \Exception;
  18. /**
  19. * TcpConnection.
  20. */
  21. class TcpConnection extends ConnectionInterface
  22. {
  23. /**
  24. * Read buffer size.
  25. *
  26. * @var int
  27. */
  28. const READ_BUFFER_SIZE = 65535;
  29. /**
  30. * Status initial.
  31. *
  32. * @var int
  33. */
  34. const STATUS_INITIAL = 0;
  35. /**
  36. * Status connecting.
  37. *
  38. * @var int
  39. */
  40. const STATUS_CONNECTING = 1;
  41. /**
  42. * Status connection established.
  43. *
  44. * @var int
  45. */
  46. const STATUS_ESTABLISHED = 2;
  47. /**
  48. * Status closing.
  49. *
  50. * @var int
  51. */
  52. const STATUS_CLOSING = 4;
  53. /**
  54. * Status closed.
  55. *
  56. * @var int
  57. */
  58. const STATUS_CLOSED = 8;
  59. /**
  60. * Emitted when data is received.
  61. *
  62. * @var callable
  63. */
  64. public $onMessage = null;
  65. /**
  66. * Emitted when the other end of the socket sends a FIN packet.
  67. *
  68. * @var callable
  69. */
  70. public $onClose = null;
  71. /**
  72. * Emitted when an error occurs with connection.
  73. *
  74. * @var callable
  75. */
  76. public $onError = null;
  77. /**
  78. * Emitted when the send buffer becomes full.
  79. *
  80. * @var callable
  81. */
  82. public $onBufferFull = null;
  83. /**
  84. * Emitted when the send buffer becomes empty.
  85. *
  86. * @var callable
  87. */
  88. public $onBufferDrain = null;
  89. /**
  90. * Application layer protocol.
  91. * The format is like this Workerman\\Protocols\\Http.
  92. *
  93. * @var \Workerman\Protocols\ProtocolInterface
  94. */
  95. public $protocol = null;
  96. /**
  97. * Transport (tcp/udp/unix/ssl).
  98. *
  99. * @var string
  100. */
  101. public $transport = 'tcp';
  102. /**
  103. * Which worker belong to.
  104. *
  105. * @var Worker
  106. */
  107. public $worker = null;
  108. /**
  109. * Bytes read.
  110. *
  111. * @var int
  112. */
  113. public $bytesRead = 0;
  114. /**
  115. * Bytes written.
  116. *
  117. * @var int
  118. */
  119. public $bytesWritten = 0;
  120. /**
  121. * Connection->id.
  122. *
  123. * @var int
  124. */
  125. public $id = 0;
  126. /**
  127. * A copy of $worker->id which used to clean up the connection in worker->connections
  128. *
  129. * @var int
  130. */
  131. protected $_id = 0;
  132. /**
  133. * Sets the maximum send buffer size for the current connection.
  134. * OnBufferFull callback will be emited When the send buffer is full.
  135. *
  136. * @var int
  137. */
  138. public $maxSendBufferSize = 1048576;
  139. /**
  140. * Default send buffer size.
  141. *
  142. * @var int
  143. */
  144. public static $defaultMaxSendBufferSize = 1048576;
  145. /**
  146. * Sets the maximum acceptable packet size for the current connection.
  147. *
  148. * @var int
  149. */
  150. public $maxPackageSize = 1048576;
  151. /**
  152. * Default maximum acceptable packet size.
  153. *
  154. * @var int
  155. */
  156. public static $defaultMaxPackageSize = 10485760;
  157. /**
  158. * Id recorder.
  159. *
  160. * @var int
  161. */
  162. protected static $_idRecorder = 1;
  163. /**
  164. * Socket
  165. *
  166. * @var resource
  167. */
  168. protected $_socket = null;
  169. /**
  170. * Send buffer.
  171. *
  172. * @var string
  173. */
  174. protected $_sendBuffer = '';
  175. /**
  176. * Receive buffer.
  177. *
  178. * @var string
  179. */
  180. protected $_recvBuffer = '';
  181. /**
  182. * Current package length.
  183. *
  184. * @var int
  185. */
  186. protected $_currentPackageLength = 0;
  187. /**
  188. * Connection status.
  189. *
  190. * @var int
  191. */
  192. protected $_status = self::STATUS_ESTABLISHED;
  193. /**
  194. * Remote address.
  195. *
  196. * @var string
  197. */
  198. protected $_remoteAddress = '';
  199. /**
  200. * Is paused.
  201. *
  202. * @var bool
  203. */
  204. protected $_isPaused = false;
  205. /**
  206. * SSL handshake completed or not.
  207. *
  208. * @var bool
  209. */
  210. protected $_sslHandshakeCompleted = false;
  211. /**
  212. * All connection instances.
  213. *
  214. * @var array
  215. */
  216. public static $connections = array();
  217. /**
  218. * Status to string.
  219. *
  220. * @var array
  221. */
  222. public static $_statusToString = array(
  223. self::STATUS_INITIAL => 'INITIAL',
  224. self::STATUS_CONNECTING => 'CONNECTING',
  225. self::STATUS_ESTABLISHED => 'ESTABLISHED',
  226. self::STATUS_CLOSING => 'CLOSING',
  227. self::STATUS_CLOSED => 'CLOSED',
  228. );
  229. /**
  230. * Construct.
  231. *
  232. * @param resource $socket
  233. * @param string $remote_address
  234. */
  235. public function __construct($socket, $remote_address = '')
  236. {
  237. ++self::$statistics['connection_count'];
  238. $this->id = $this->_id = self::$_idRecorder++;
  239. if(self::$_idRecorder === \PHP_INT_MAX){
  240. self::$_idRecorder = 0;
  241. }
  242. $this->_socket = $socket;
  243. \stream_set_blocking($this->_socket, 0);
  244. // Compatible with hhvm
  245. if (\function_exists('stream_set_read_buffer')) {
  246. \stream_set_read_buffer($this->_socket, 0);
  247. }
  248. Worker::$globalEvent->add($this->_socket, EventInterface::EV_READ, array($this, 'baseRead'));
  249. $this->maxSendBufferSize = self::$defaultMaxSendBufferSize;
  250. $this->maxPackageSize = self::$defaultMaxPackageSize;
  251. $this->_remoteAddress = $remote_address;
  252. static::$connections[$this->id] = $this;
  253. }
  254. /**
  255. * Get status.
  256. *
  257. * @param bool $raw_output
  258. *
  259. * @return int|string
  260. */
  261. public function getStatus($raw_output = true)
  262. {
  263. if ($raw_output) {
  264. return $this->_status;
  265. }
  266. return self::$_statusToString[$this->_status];
  267. }
  268. /**
  269. * Sends data on the connection.
  270. *
  271. * @param mixed $send_buffer
  272. * @param bool $raw
  273. * @return bool|null
  274. */
  275. public function send($send_buffer, $raw = false)
  276. {
  277. if ($this->_status === self::STATUS_CLOSING || $this->_status === self::STATUS_CLOSED) {
  278. return false;
  279. }
  280. // Try to call protocol::encode($send_buffer) before sending.
  281. if (false === $raw && $this->protocol !== null) {
  282. $parser = $this->protocol;
  283. $send_buffer = $parser::encode($send_buffer, $this);
  284. if ($send_buffer === '') {
  285. return;
  286. }
  287. }
  288. if ($this->_status !== self::STATUS_ESTABLISHED ||
  289. ($this->transport === 'ssl' && $this->_sslHandshakeCompleted !== true)
  290. ) {
  291. if ($this->_sendBuffer && $this->bufferIsFull()) {
  292. ++self::$statistics['send_fail'];
  293. return false;
  294. }
  295. $this->_sendBuffer .= $send_buffer;
  296. $this->checkBufferWillFull();
  297. return;
  298. }
  299. // Attempt to send data directly.
  300. if ($this->_sendBuffer === '') {
  301. if ($this->transport === 'ssl') {
  302. Worker::$globalEvent->add($this->_socket, EventInterface::EV_WRITE, array($this, 'baseWrite'));
  303. $this->_sendBuffer = $send_buffer;
  304. $this->checkBufferWillFull();
  305. return;
  306. }
  307. $len = 0;
  308. try {
  309. $len = @\fwrite($this->_socket, $send_buffer);
  310. } catch (\Exception $e) {
  311. Worker::log($e);
  312. } catch (\Error $e) {
  313. Worker::log($e);
  314. }
  315. // send successful.
  316. if ($len === \strlen($send_buffer)) {
  317. $this->bytesWritten += $len;
  318. return true;
  319. }
  320. // Send only part of the data.
  321. if ($len > 0) {
  322. $this->_sendBuffer = \substr($send_buffer, $len);
  323. $this->bytesWritten += $len;
  324. } else {
  325. // Connection closed?
  326. if (!\is_resource($this->_socket) || \feof($this->_socket)) {
  327. ++self::$statistics['send_fail'];
  328. if ($this->onError) {
  329. try {
  330. \call_user_func($this->onError, $this, \WORKERMAN_SEND_FAIL, 'client closed');
  331. } catch (\Exception $e) {
  332. Worker::stopAll(250, $e);
  333. } catch (\Error $e) {
  334. Worker::stopAll(250, $e);
  335. }
  336. }
  337. $this->destroy();
  338. return false;
  339. }
  340. $this->_sendBuffer = $send_buffer;
  341. }
  342. Worker::$globalEvent->add($this->_socket, EventInterface::EV_WRITE, array($this, 'baseWrite'));
  343. // Check if the send buffer will be full.
  344. $this->checkBufferWillFull();
  345. return;
  346. }
  347. if ($this->bufferIsFull()) {
  348. ++self::$statistics['send_fail'];
  349. return false;
  350. }
  351. $this->_sendBuffer .= $send_buffer;
  352. // Check if the send buffer is full.
  353. $this->checkBufferWillFull();
  354. }
  355. /**
  356. * Get remote IP.
  357. *
  358. * @return string
  359. */
  360. public function getRemoteIp()
  361. {
  362. $pos = \strrpos($this->_remoteAddress, ':');
  363. if ($pos) {
  364. return (string) \substr($this->_remoteAddress, 0, $pos);
  365. }
  366. return '';
  367. }
  368. /**
  369. * Get remote port.
  370. *
  371. * @return int
  372. */
  373. public function getRemotePort()
  374. {
  375. if ($this->_remoteAddress) {
  376. return (int) \substr(\strrchr($this->_remoteAddress, ':'), 1);
  377. }
  378. return 0;
  379. }
  380. /**
  381. * Get remote address.
  382. *
  383. * @return string
  384. */
  385. public function getRemoteAddress()
  386. {
  387. return $this->_remoteAddress;
  388. }
  389. /**
  390. * Get local IP.
  391. *
  392. * @return string
  393. */
  394. public function getLocalIp()
  395. {
  396. $address = $this->getLocalAddress();
  397. $pos = \strrpos($address, ':');
  398. if (!$pos) {
  399. return '';
  400. }
  401. return \substr($address, 0, $pos);
  402. }
  403. /**
  404. * Get local port.
  405. *
  406. * @return int
  407. */
  408. public function getLocalPort()
  409. {
  410. $address = $this->getLocalAddress();
  411. $pos = \strrpos($address, ':');
  412. if (!$pos) {
  413. return 0;
  414. }
  415. return (int)\substr(\strrchr($address, ':'), 1);
  416. }
  417. /**
  418. * Get local address.
  419. *
  420. * @return string
  421. */
  422. public function getLocalAddress()
  423. {
  424. if (!\is_resource($this->_socket)) {
  425. return '';
  426. }
  427. return (string)@\stream_socket_get_name($this->_socket, false);
  428. }
  429. /**
  430. * Get send buffer queue size.
  431. *
  432. * @return integer
  433. */
  434. public function getSendBufferQueueSize()
  435. {
  436. return \strlen($this->_sendBuffer);
  437. }
  438. /**
  439. * Get recv buffer queue size.
  440. *
  441. * @return integer
  442. */
  443. public function getRecvBufferQueueSize()
  444. {
  445. return \strlen($this->_recvBuffer);
  446. }
  447. /**
  448. * Is ipv4.
  449. *
  450. * return bool.
  451. */
  452. public function isIpV4()
  453. {
  454. if ($this->transport === 'unix') {
  455. return false;
  456. }
  457. return \strpos($this->getRemoteIp(), ':') === false;
  458. }
  459. /**
  460. * Is ipv6.
  461. *
  462. * return bool.
  463. */
  464. public function isIpV6()
  465. {
  466. if ($this->transport === 'unix') {
  467. return false;
  468. }
  469. return \strpos($this->getRemoteIp(), ':') !== false;
  470. }
  471. /**
  472. * Pauses the reading of data. That is onMessage will not be emitted. Useful to throttle back an upload.
  473. *
  474. * @return void
  475. */
  476. public function pauseRecv()
  477. {
  478. Worker::$globalEvent->del($this->_socket, EventInterface::EV_READ);
  479. $this->_isPaused = true;
  480. }
  481. /**
  482. * Resumes reading after a call to pauseRecv.
  483. *
  484. * @return void
  485. */
  486. public function resumeRecv()
  487. {
  488. if ($this->_isPaused === true) {
  489. Worker::$globalEvent->add($this->_socket, EventInterface::EV_READ, array($this, 'baseRead'));
  490. $this->_isPaused = false;
  491. $this->baseRead($this->_socket, false);
  492. }
  493. }
  494. /**
  495. * Base read handler.
  496. *
  497. * @param resource $socket
  498. * @param bool $check_eof
  499. * @return void
  500. */
  501. public function baseRead($socket, $check_eof = true)
  502. {
  503. // SSL handshake.
  504. if ($this->transport === 'ssl' && $this->_sslHandshakeCompleted !== true) {
  505. if ($this->doSslHandshake($socket)) {
  506. $this->_sslHandshakeCompleted = true;
  507. if ($this->_sendBuffer) {
  508. Worker::$globalEvent->add($socket, EventInterface::EV_WRITE, array($this, 'baseWrite'));
  509. }
  510. } else {
  511. return;
  512. }
  513. }
  514. $buffer = '';
  515. try {
  516. $buffer = @\fread($socket, self::READ_BUFFER_SIZE);
  517. } catch (\Exception $e) {} catch (\Error $e) {}
  518. // Check connection closed.
  519. if ($buffer === '' || $buffer === false) {
  520. if ($check_eof && (\feof($socket) || !\is_resource($socket) || $buffer === false)) {
  521. $this->destroy();
  522. return;
  523. }
  524. } else {
  525. $this->bytesRead += \strlen($buffer);
  526. $this->_recvBuffer .= $buffer;
  527. }
  528. // If the application layer protocol has been set up.
  529. if ($this->protocol !== null) {
  530. $parser = $this->protocol;
  531. while ($this->_recvBuffer !== '' && !$this->_isPaused) {
  532. // The current packet length is known.
  533. if ($this->_currentPackageLength) {
  534. // Data is not enough for a package.
  535. if ($this->_currentPackageLength > \strlen($this->_recvBuffer)) {
  536. break;
  537. }
  538. } else {
  539. // Get current package length.
  540. try {
  541. $this->_currentPackageLength = $parser::input($this->_recvBuffer, $this);
  542. } catch (\Exception $e) {} catch (\Error $e) {}
  543. // The packet length is unknown.
  544. if ($this->_currentPackageLength === 0) {
  545. break;
  546. } elseif ($this->_currentPackageLength > 0 && $this->_currentPackageLength <= $this->maxPackageSize) {
  547. // Data is not enough for a package.
  548. if ($this->_currentPackageLength > \strlen($this->_recvBuffer)) {
  549. break;
  550. }
  551. } // Wrong package.
  552. else {
  553. Worker::safeEcho('Error package. package_length=' . \var_export($this->_currentPackageLength, true));
  554. $this->destroy();
  555. return;
  556. }
  557. }
  558. // The data is enough for a packet.
  559. ++self::$statistics['total_request'];
  560. // The current packet length is equal to the length of the buffer.
  561. if (\strlen($this->_recvBuffer) === $this->_currentPackageLength) {
  562. $one_request_buffer = $this->_recvBuffer;
  563. $this->_recvBuffer = '';
  564. } else {
  565. // Get a full package from the buffer.
  566. $one_request_buffer = \substr($this->_recvBuffer, 0, $this->_currentPackageLength);
  567. // Remove the current package from the receive buffer.
  568. $this->_recvBuffer = \substr($this->_recvBuffer, $this->_currentPackageLength);
  569. }
  570. // Reset the current packet length to 0.
  571. $this->_currentPackageLength = 0;
  572. if (!$this->onMessage) {
  573. continue;
  574. }
  575. try {
  576. // Decode request buffer before Emitting onMessage callback.
  577. \call_user_func($this->onMessage, $this, $parser::decode($one_request_buffer, $this));
  578. } catch (\Exception $e) {
  579. Worker::stopAll(250, $e);
  580. } catch (\Error $e) {
  581. Worker::stopAll(250, $e);
  582. }
  583. }
  584. return;
  585. }
  586. if ($this->_recvBuffer === '' || $this->_isPaused) {
  587. return;
  588. }
  589. // Applications protocol is not set.
  590. ++self::$statistics['total_request'];
  591. if (!$this->onMessage) {
  592. $this->_recvBuffer = '';
  593. return;
  594. }
  595. try {
  596. \call_user_func($this->onMessage, $this, $this->_recvBuffer);
  597. } catch (\Exception $e) {
  598. Worker::stopAll(250, $e);
  599. } catch (\Error $e) {
  600. Worker::stopAll(250, $e);
  601. }
  602. // Clean receive buffer.
  603. $this->_recvBuffer = '';
  604. }
  605. /**
  606. * Base write handler.
  607. *
  608. * @return void|bool
  609. */
  610. public function baseWrite()
  611. {
  612. \set_error_handler(function(){});
  613. if ($this->transport === 'ssl') {
  614. $len = @\fwrite($this->_socket, $this->_sendBuffer, 8192);
  615. } else {
  616. $len = @\fwrite($this->_socket, $this->_sendBuffer);
  617. }
  618. \restore_error_handler();
  619. if ($len === \strlen($this->_sendBuffer)) {
  620. $this->bytesWritten += $len;
  621. Worker::$globalEvent->del($this->_socket, EventInterface::EV_WRITE);
  622. $this->_sendBuffer = '';
  623. // Try to emit onBufferDrain callback when the send buffer becomes empty.
  624. if ($this->onBufferDrain) {
  625. try {
  626. \call_user_func($this->onBufferDrain, $this);
  627. } catch (\Exception $e) {
  628. Worker::stopAll(250, $e);
  629. } catch (\Error $e) {
  630. Worker::stopAll(250, $e);
  631. }
  632. }
  633. if ($this->_status === self::STATUS_CLOSING) {
  634. $this->destroy();
  635. }
  636. return true;
  637. }
  638. if ($len > 0) {
  639. $this->bytesWritten += $len;
  640. $this->_sendBuffer = \substr($this->_sendBuffer, $len);
  641. } else {
  642. ++self::$statistics['send_fail'];
  643. $this->destroy();
  644. }
  645. }
  646. /**
  647. * SSL handshake.
  648. *
  649. * @param resource $socket
  650. * @return bool
  651. */
  652. public function doSslHandshake($socket){
  653. if (\feof($socket)) {
  654. $this->destroy();
  655. return false;
  656. }
  657. $async = $this instanceof AsyncTcpConnection;
  658. /**
  659. * We disabled ssl3 because https://blog.qualys.com/ssllabs/2014/10/15/ssl-3-is-dead-killed-by-the-poodle-attack.
  660. * You can enable ssl3 by the codes below.
  661. */
  662. /*if($async){
  663. $type = STREAM_CRYPTO_METHOD_SSLv2_CLIENT | STREAM_CRYPTO_METHOD_SSLv23_CLIENT | STREAM_CRYPTO_METHOD_SSLv3_CLIENT;
  664. }else{
  665. $type = STREAM_CRYPTO_METHOD_SSLv2_SERVER | STREAM_CRYPTO_METHOD_SSLv23_SERVER | STREAM_CRYPTO_METHOD_SSLv3_SERVER;
  666. }*/
  667. if($async){
  668. $type = \STREAM_CRYPTO_METHOD_SSLv2_CLIENT | \STREAM_CRYPTO_METHOD_SSLv23_CLIENT;
  669. }else{
  670. $type = \STREAM_CRYPTO_METHOD_SSLv2_SERVER | \STREAM_CRYPTO_METHOD_SSLv23_SERVER;
  671. }
  672. // Hidden error.
  673. \set_error_handler(function($errno, $errstr, $file){
  674. if (!Worker::$daemonize) {
  675. Worker::safeEcho("SSL handshake error: $errstr \n");
  676. }
  677. });
  678. $ret = \stream_socket_enable_crypto($socket, true, $type);
  679. \restore_error_handler();
  680. // Negotiation has failed.
  681. if (false === $ret) {
  682. $this->destroy();
  683. return false;
  684. } elseif (0 === $ret) {
  685. // There isn't enough data and should try again.
  686. return 0;
  687. }
  688. if (isset($this->onSslHandshake)) {
  689. try {
  690. \call_user_func($this->onSslHandshake, $this);
  691. } catch (\Exception $e) {
  692. Worker::stopAll(250, $e);
  693. } catch (\Error $e) {
  694. Worker::stopAll(250, $e);
  695. }
  696. }
  697. return true;
  698. }
  699. /**
  700. * This method pulls all the data out of a readable stream, and writes it to the supplied destination.
  701. *
  702. * @param self $dest
  703. * @return void
  704. */
  705. public function pipe(self $dest)
  706. {
  707. $source = $this;
  708. $this->onMessage = function ($source, $data) use ($dest) {
  709. $dest->send($data);
  710. };
  711. $this->onClose = function ($source) use ($dest) {
  712. $dest->close();
  713. };
  714. $dest->onBufferFull = function ($dest) use ($source) {
  715. $source->pauseRecv();
  716. };
  717. $dest->onBufferDrain = function ($dest) use ($source) {
  718. $source->resumeRecv();
  719. };
  720. }
  721. /**
  722. * Remove $length of data from receive buffer.
  723. *
  724. * @param int $length
  725. * @return void
  726. */
  727. public function consumeRecvBuffer($length)
  728. {
  729. $this->_recvBuffer = \substr($this->_recvBuffer, $length);
  730. }
  731. /**
  732. * Close connection.
  733. *
  734. * @param mixed $data
  735. * @param bool $raw
  736. * @return void
  737. */
  738. public function close($data = null, $raw = false)
  739. {
  740. if($this->_status === self::STATUS_CONNECTING){
  741. $this->destroy();
  742. return;
  743. }
  744. if ($this->_status === self::STATUS_CLOSING || $this->_status === self::STATUS_CLOSED) {
  745. return;
  746. }
  747. if ($data !== null) {
  748. $this->send($data, $raw);
  749. }
  750. $this->_status = self::STATUS_CLOSING;
  751. if ($this->_sendBuffer === '') {
  752. $this->destroy();
  753. } else {
  754. $this->pauseRecv();
  755. }
  756. }
  757. /**
  758. * Get the real socket.
  759. *
  760. * @return resource
  761. */
  762. public function getSocket()
  763. {
  764. return $this->_socket;
  765. }
  766. /**
  767. * Check whether the send buffer will be full.
  768. *
  769. * @return void
  770. */
  771. protected function checkBufferWillFull()
  772. {
  773. if ($this->maxSendBufferSize <= \strlen($this->_sendBuffer)) {
  774. if ($this->onBufferFull) {
  775. try {
  776. \call_user_func($this->onBufferFull, $this);
  777. } catch (\Exception $e) {
  778. Worker::stopAll(250, $e);
  779. } catch (\Error $e) {
  780. Worker::stopAll(250, $e);
  781. }
  782. }
  783. }
  784. }
  785. /**
  786. * Whether send buffer is full.
  787. *
  788. * @return bool
  789. */
  790. protected function bufferIsFull()
  791. {
  792. // Buffer has been marked as full but still has data to send then the packet is discarded.
  793. if ($this->maxSendBufferSize <= \strlen($this->_sendBuffer)) {
  794. if ($this->onError) {
  795. try {
  796. \call_user_func($this->onError, $this, \WORKERMAN_SEND_FAIL, 'send buffer full and drop package');
  797. } catch (\Exception $e) {
  798. Worker::stopAll(250, $e);
  799. } catch (\Error $e) {
  800. Worker::stopAll(250, $e);
  801. }
  802. }
  803. return true;
  804. }
  805. return false;
  806. }
  807. /**
  808. * Whether send buffer is Empty.
  809. *
  810. * @return bool
  811. */
  812. public function bufferIsEmpty()
  813. {
  814. return empty($this->_sendBuffer);
  815. }
  816. /**
  817. * Destroy connection.
  818. *
  819. * @return void
  820. */
  821. public function destroy()
  822. {
  823. // Avoid repeated calls.
  824. if ($this->_status === self::STATUS_CLOSED) {
  825. return;
  826. }
  827. // Remove event listener.
  828. Worker::$globalEvent->del($this->_socket, EventInterface::EV_READ);
  829. Worker::$globalEvent->del($this->_socket, EventInterface::EV_WRITE);
  830. // Close socket.
  831. try {
  832. @\fclose($this->_socket);
  833. } catch (\Exception $e) {} catch (\Error $e) {}
  834. $this->_status = self::STATUS_CLOSED;
  835. // Try to emit onClose callback.
  836. if ($this->onClose) {
  837. try {
  838. \call_user_func($this->onClose, $this);
  839. } catch (\Exception $e) {
  840. Worker::stopAll(250, $e);
  841. } catch (\Error $e) {
  842. Worker::stopAll(250, $e);
  843. }
  844. }
  845. // Try to emit protocol::onClose
  846. if ($this->protocol && \method_exists($this->protocol, 'onClose')) {
  847. try {
  848. \call_user_func(array($this->protocol, 'onClose'), $this);
  849. } catch (\Exception $e) {
  850. Worker::stopAll(250, $e);
  851. } catch (\Error $e) {
  852. Worker::stopAll(250, $e);
  853. }
  854. }
  855. $this->_sendBuffer = $this->_recvBuffer = '';
  856. $this->_currentPackageLength = 0;
  857. $this->_isPaused = $this->_sslHandshakeCompleted = false;
  858. if ($this->_status === self::STATUS_CLOSED) {
  859. // Cleaning up the callback to avoid memory leaks.
  860. $this->onMessage = $this->onClose = $this->onError = $this->onBufferFull = $this->onBufferDrain = null;
  861. // Remove from worker->connections.
  862. if ($this->worker) {
  863. unset($this->worker->connections[$this->_id]);
  864. }
  865. unset(static::$connections[$this->_id]);
  866. }
  867. }
  868. /**
  869. * Destruct.
  870. *
  871. * @return void
  872. */
  873. public function __destruct()
  874. {
  875. static $mod;
  876. self::$statistics['connection_count']--;
  877. if (Worker::getGracefulStop()) {
  878. if (!isset($mod)) {
  879. $mod = \ceil((self::$statistics['connection_count'] + 1) / 3);
  880. }
  881. if (0 === self::$statistics['connection_count'] % $mod) {
  882. Worker::log('worker[' . \posix_getpid() . '] remains ' . self::$statistics['connection_count'] . ' connection(s)');
  883. }
  884. if(0 === self::$statistics['connection_count']) {
  885. Worker::stopAll();
  886. }
  887. }
  888. }
  889. }