TcpConnection.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949
  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 callback
  63. */
  64. public $onMessage = null;
  65. /**
  66. * Emitted when the other end of the socket sends a FIN packet.
  67. *
  68. * @var callback
  69. */
  70. public $onClose = null;
  71. /**
  72. * Emitted when an error occurs with connection.
  73. *
  74. * @var callback
  75. */
  76. public $onError = null;
  77. /**
  78. * Emitted when the send buffer becomes full.
  79. *
  80. * @var callback
  81. */
  82. public $onBufferFull = null;
  83. /**
  84. * Emitted when the send buffer becomes empty.
  85. *
  86. * @var callback
  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. * Maximum acceptable packet size.
  147. *
  148. * @var int
  149. */
  150. public static $maxPackageSize = 10485760;
  151. /**
  152. * Id recorder.
  153. *
  154. * @var int
  155. */
  156. protected static $_idRecorder = 1;
  157. /**
  158. * Socket
  159. *
  160. * @var resource
  161. */
  162. protected $_socket = null;
  163. /**
  164. * Send buffer.
  165. *
  166. * @var string
  167. */
  168. protected $_sendBuffer = '';
  169. /**
  170. * Receive buffer.
  171. *
  172. * @var string
  173. */
  174. protected $_recvBuffer = '';
  175. /**
  176. * Current package length.
  177. *
  178. * @var int
  179. */
  180. protected $_currentPackageLength = 0;
  181. /**
  182. * Connection status.
  183. *
  184. * @var int
  185. */
  186. protected $_status = self::STATUS_ESTABLISHED;
  187. /**
  188. * Remote address.
  189. *
  190. * @var string
  191. */
  192. protected $_remoteAddress = '';
  193. /**
  194. * Is paused.
  195. *
  196. * @var bool
  197. */
  198. protected $_isPaused = false;
  199. /**
  200. * SSL handshake completed or not.
  201. *
  202. * @var bool
  203. */
  204. protected $_sslHandshakeCompleted = false;
  205. /**
  206. * All connection instances.
  207. *
  208. * @var array
  209. */
  210. public static $connections = array();
  211. /**
  212. * Status to string.
  213. *
  214. * @var array
  215. */
  216. public static $_statusToString = array(
  217. self::STATUS_INITIAL => 'INITIAL',
  218. self::STATUS_CONNECTING => 'CONNECTING',
  219. self::STATUS_ESTABLISHED => 'ESTABLISHED',
  220. self::STATUS_CLOSING => 'CLOSING',
  221. self::STATUS_CLOSED => 'CLOSED',
  222. );
  223. /**
  224. * Adding support of custom functions within protocols
  225. *
  226. * @param string $name
  227. * @param array $arguments
  228. */
  229. public function __call($name, $arguments) {
  230. // Try to emit custom function within protocol
  231. if (method_exists($this->protocol, $name)) {
  232. try {
  233. return call_user_func(array($this->protocol, $name), $this, $arguments);
  234. } catch (\Exception $e) {
  235. Worker::log($e);
  236. exit(250);
  237. } catch (\Error $e) {
  238. Worker::log($e);
  239. exit(250);
  240. }
  241. } else {
  242. trigger_error('Call to undefined method '.__CLASS__.'::'.$name.'()', E_USER_ERROR);
  243. }
  244. }
  245. /**
  246. * Construct.
  247. *
  248. * @param resource $socket
  249. * @param string $remote_address
  250. */
  251. public function __construct($socket, $remote_address = '')
  252. {
  253. self::$statistics['connection_count']++;
  254. $this->id = $this->_id = self::$_idRecorder++;
  255. if(self::$_idRecorder === PHP_INT_MAX){
  256. self::$_idRecorder = 0;
  257. }
  258. $this->_socket = $socket;
  259. stream_set_blocking($this->_socket, 0);
  260. // Compatible with hhvm
  261. if (function_exists('stream_set_read_buffer')) {
  262. stream_set_read_buffer($this->_socket, 0);
  263. }
  264. Worker::$globalEvent->add($this->_socket, EventInterface::EV_READ, array($this, 'baseRead'));
  265. $this->maxSendBufferSize = self::$defaultMaxSendBufferSize;
  266. $this->_remoteAddress = $remote_address;
  267. static::$connections[$this->id] = $this;
  268. }
  269. /**
  270. * Get status.
  271. *
  272. * @param bool $raw_output
  273. *
  274. * @return int
  275. */
  276. public function getStatus($raw_output = true)
  277. {
  278. if ($raw_output) {
  279. return $this->_status;
  280. }
  281. return self::$_statusToString[$this->_status];
  282. }
  283. /**
  284. * Sends data on the connection.
  285. *
  286. * @param string $send_buffer
  287. * @param bool $raw
  288. * @return void|bool|null
  289. */
  290. public function send($send_buffer, $raw = false)
  291. {
  292. if ($this->_status === self::STATUS_CLOSING || $this->_status === self::STATUS_CLOSED) {
  293. return false;
  294. }
  295. // Try to call protocol::encode($send_buffer) before sending.
  296. if (false === $raw && $this->protocol !== null) {
  297. $parser = $this->protocol;
  298. $send_buffer = $parser::encode($send_buffer, $this);
  299. if ($send_buffer === '') {
  300. return null;
  301. }
  302. }
  303. if ($this->_status !== self::STATUS_ESTABLISHED ||
  304. ($this->transport === 'ssl' && $this->_sslHandshakeCompleted !== true)
  305. ) {
  306. if ($this->_sendBuffer) {
  307. if ($this->bufferIsFull()) {
  308. self::$statistics['send_fail']++;
  309. return false;
  310. }
  311. }
  312. $this->_sendBuffer .= $send_buffer;
  313. $this->checkBufferWillFull();
  314. return null;
  315. }
  316. // Attempt to send data directly.
  317. if ($this->_sendBuffer === '') {
  318. $len = @fwrite($this->_socket, $send_buffer, 8192);
  319. // send successful.
  320. if ($len === strlen($send_buffer)) {
  321. $this->bytesWritten += $len;
  322. return true;
  323. }
  324. // Send only part of the data.
  325. if ($len > 0) {
  326. $this->_sendBuffer = substr($send_buffer, $len);
  327. $this->bytesWritten += $len;
  328. } else {
  329. // Connection closed?
  330. if (!is_resource($this->_socket) || feof($this->_socket)) {
  331. self::$statistics['send_fail']++;
  332. if ($this->onError) {
  333. try {
  334. call_user_func($this->onError, $this, WORKERMAN_SEND_FAIL, 'client closed');
  335. } catch (\Exception $e) {
  336. Worker::log($e);
  337. exit(250);
  338. } catch (\Error $e) {
  339. Worker::log($e);
  340. exit(250);
  341. }
  342. }
  343. $this->destroy();
  344. return false;
  345. }
  346. $this->_sendBuffer = $send_buffer;
  347. }
  348. Worker::$globalEvent->add($this->_socket, EventInterface::EV_WRITE, array($this, 'baseWrite'));
  349. // Check if the send buffer will be full.
  350. $this->checkBufferWillFull();
  351. return null;
  352. } else {
  353. if ($this->bufferIsFull()) {
  354. self::$statistics['send_fail']++;
  355. return false;
  356. }
  357. $this->_sendBuffer .= $send_buffer;
  358. // Check if the send buffer is full.
  359. $this->checkBufferWillFull();
  360. }
  361. }
  362. /**
  363. * Get remote IP.
  364. *
  365. * @return string
  366. */
  367. public function getRemoteIp()
  368. {
  369. $pos = strrpos($this->_remoteAddress, ':');
  370. if ($pos) {
  371. return substr($this->_remoteAddress, 0, $pos);
  372. }
  373. return '';
  374. }
  375. /**
  376. * Get remote port.
  377. *
  378. * @return int
  379. */
  380. public function getRemotePort()
  381. {
  382. if ($this->_remoteAddress) {
  383. return (int)substr(strrchr($this->_remoteAddress, ':'), 1);
  384. }
  385. return 0;
  386. }
  387. /**
  388. * Get remote address.
  389. *
  390. * @return string
  391. */
  392. public function getRemoteAddress()
  393. {
  394. return $this->_remoteAddress;
  395. }
  396. /**
  397. * Get local IP.
  398. *
  399. * @return string
  400. */
  401. public function getLocalIp()
  402. {
  403. $address = $this->getLocalAddress();
  404. $pos = strrpos($address, ':');
  405. if (!$pos) {
  406. return '';
  407. }
  408. return substr($address, 0, $pos);
  409. }
  410. /**
  411. * Get local port.
  412. *
  413. * @return int
  414. */
  415. public function getLocalPort()
  416. {
  417. $address = $this->getLocalAddress();
  418. $pos = strrpos($address, ':');
  419. if (!$pos) {
  420. return 0;
  421. }
  422. return (int)substr(strrchr($address, ':'), 1);
  423. }
  424. /**
  425. * Get local address.
  426. *
  427. * @return string
  428. */
  429. public function getLocalAddress()
  430. {
  431. return (string)@stream_socket_get_name($this->_socket, false);
  432. }
  433. /**
  434. * Get send buffer queue size.
  435. *
  436. * @return integer
  437. */
  438. public function getSendBufferQueueSize()
  439. {
  440. return strlen($this->_sendBuffer);
  441. }
  442. /**
  443. * Get recv buffer queue size.
  444. *
  445. * @return integer
  446. */
  447. public function getRecvBufferQueueSize()
  448. {
  449. return strlen($this->_recvBuffer);
  450. }
  451. /**
  452. * Is ipv4.
  453. *
  454. * return bool.
  455. */
  456. public function isIpV4()
  457. {
  458. if ($this->transport === 'unix') {
  459. return false;
  460. }
  461. return strpos($this->getRemoteIp(), ':') === false;
  462. }
  463. /**
  464. * Is ipv6.
  465. *
  466. * return bool.
  467. */
  468. public function isIpV6()
  469. {
  470. if ($this->transport === 'unix') {
  471. return false;
  472. }
  473. return strpos($this->getRemoteIp(), ':') !== false;
  474. }
  475. /**
  476. * Pauses the reading of data. That is onMessage will not be emitted. Useful to throttle back an upload.
  477. *
  478. * @return void
  479. */
  480. public function pauseRecv()
  481. {
  482. Worker::$globalEvent->del($this->_socket, EventInterface::EV_READ);
  483. $this->_isPaused = true;
  484. }
  485. /**
  486. * Resumes reading after a call to pauseRecv.
  487. *
  488. * @return void
  489. */
  490. public function resumeRecv()
  491. {
  492. if ($this->_isPaused === true) {
  493. Worker::$globalEvent->add($this->_socket, EventInterface::EV_READ, array($this, 'baseRead'));
  494. $this->_isPaused = false;
  495. $this->baseRead($this->_socket, false);
  496. }
  497. }
  498. /**
  499. * Base read handler.
  500. *
  501. * @param resource $socket
  502. * @param bool $check_eof
  503. * @return void
  504. */
  505. public function baseRead($socket, $check_eof = true)
  506. {
  507. // SSL handshake.
  508. if ($this->transport === 'ssl' && $this->_sslHandshakeCompleted !== true) {
  509. if ($this->doSslHandshake($socket)) {
  510. $this->_sslHandshakeCompleted = true;
  511. }
  512. return;
  513. }
  514. $buffer = @fread($socket, self::READ_BUFFER_SIZE);
  515. // Check connection closed.
  516. if ($buffer === '' || $buffer === false) {
  517. if ($check_eof && (feof($socket) || !is_resource($socket) || $buffer === false)) {
  518. $this->destroy();
  519. return;
  520. }
  521. } else {
  522. $this->bytesRead += strlen($buffer);
  523. $this->_recvBuffer .= $buffer;
  524. }
  525. // If the application layer protocol has been set up.
  526. if ($this->protocol !== null) {
  527. $parser = $this->protocol;
  528. while ($this->_recvBuffer !== '' && !$this->_isPaused) {
  529. // The current packet length is known.
  530. if ($this->_currentPackageLength) {
  531. // Data is not enough for a package.
  532. if ($this->_currentPackageLength > strlen($this->_recvBuffer)) {
  533. break;
  534. }
  535. } else {
  536. // Get current package length.
  537. $this->_currentPackageLength = $parser::input($this->_recvBuffer, $this);
  538. // The packet length is unknown.
  539. if ($this->_currentPackageLength === 0) {
  540. break;
  541. } elseif ($this->_currentPackageLength > 0 && $this->_currentPackageLength <= self::$maxPackageSize) {
  542. // Data is not enough for a package.
  543. if ($this->_currentPackageLength > strlen($this->_recvBuffer)) {
  544. break;
  545. }
  546. } // Wrong package.
  547. else {
  548. echo 'error package. package_length=' . var_export($this->_currentPackageLength, true);
  549. $this->destroy();
  550. return;
  551. }
  552. }
  553. // The data is enough for a packet.
  554. self::$statistics['total_request']++;
  555. // The current packet length is equal to the length of the buffer.
  556. if (strlen($this->_recvBuffer) === $this->_currentPackageLength) {
  557. $one_request_buffer = $this->_recvBuffer;
  558. $this->_recvBuffer = '';
  559. } else {
  560. // Get a full package from the buffer.
  561. $one_request_buffer = substr($this->_recvBuffer, 0, $this->_currentPackageLength);
  562. // Remove the current package from the receive buffer.
  563. $this->_recvBuffer = substr($this->_recvBuffer, $this->_currentPackageLength);
  564. }
  565. // Reset the current packet length to 0.
  566. $this->_currentPackageLength = 0;
  567. if (!$this->onMessage) {
  568. continue;
  569. }
  570. try {
  571. // Decode request buffer before Emitting onMessage callback.
  572. call_user_func($this->onMessage, $this, $parser::decode($one_request_buffer, $this));
  573. } catch (\Exception $e) {
  574. Worker::log($e);
  575. exit(250);
  576. } catch (\Error $e) {
  577. Worker::log($e);
  578. exit(250);
  579. }
  580. }
  581. return;
  582. }
  583. if ($this->_recvBuffer === '' || $this->_isPaused) {
  584. return;
  585. }
  586. // Applications protocol is not set.
  587. self::$statistics['total_request']++;
  588. if (!$this->onMessage) {
  589. $this->_recvBuffer = '';
  590. return;
  591. }
  592. try {
  593. call_user_func($this->onMessage, $this, $this->_recvBuffer);
  594. } catch (\Exception $e) {
  595. Worker::log($e);
  596. exit(250);
  597. } catch (\Error $e) {
  598. Worker::log($e);
  599. exit(250);
  600. }
  601. // Clean receive buffer.
  602. $this->_recvBuffer = '';
  603. }
  604. /**
  605. * Base write handler.
  606. *
  607. * @return void|bool
  608. */
  609. public function baseWrite()
  610. {
  611. $len = @fwrite($this->_socket, $this->_sendBuffer, 8192);
  612. if ($len === strlen($this->_sendBuffer)) {
  613. $this->bytesWritten += $len;
  614. Worker::$globalEvent->del($this->_socket, EventInterface::EV_WRITE);
  615. $this->_sendBuffer = '';
  616. // Try to emit onBufferDrain callback when the send buffer becomes empty.
  617. if ($this->onBufferDrain) {
  618. try {
  619. call_user_func($this->onBufferDrain, $this);
  620. } catch (\Exception $e) {
  621. Worker::log($e);
  622. exit(250);
  623. } catch (\Error $e) {
  624. Worker::log($e);
  625. exit(250);
  626. }
  627. }
  628. if ($this->_status === self::STATUS_CLOSING) {
  629. $this->destroy();
  630. }
  631. return true;
  632. }
  633. if ($len > 0) {
  634. $this->bytesWritten += $len;
  635. $this->_sendBuffer = substr($this->_sendBuffer, $len);
  636. } else {
  637. self::$statistics['send_fail']++;
  638. $this->destroy();
  639. }
  640. }
  641. /**
  642. * SSL handshake.
  643. *
  644. * @param $socket
  645. * @return bool
  646. */
  647. public function doSslHandshake($socket){
  648. if (feof($socket)) {
  649. $this->destroy();
  650. return false;
  651. }
  652. $ret = stream_socket_enable_crypto($socket, true, STREAM_CRYPTO_METHOD_SSLv2_SERVER |
  653. STREAM_CRYPTO_METHOD_SSLv23_SERVER);
  654. // Negotiation has failed.
  655. if(false === $ret) {
  656. if (!feof($socket)) {
  657. echo "\nSSL Handshake fail. \nBuffer:".bin2hex(fread($socket, 8182))."\n";
  658. }
  659. $this->destroy();
  660. return false;
  661. } elseif(0 === $ret) {
  662. // There isn't enough data and should try again.
  663. return false;
  664. }
  665. if (isset($this->onSslHandshake)) {
  666. try {
  667. call_user_func($this->onSslHandshake, $this);
  668. } catch (\Exception $e) {
  669. Worker::log($e);
  670. exit(250);
  671. } catch (\Error $e) {
  672. Worker::log($e);
  673. exit(250);
  674. }
  675. }
  676. if ($this->_sendBuffer) {
  677. Worker::$globalEvent->add($socket, EventInterface::EV_WRITE, array($this, 'baseWrite'));
  678. }
  679. return true;
  680. }
  681. /**
  682. * This method pulls all the data out of a readable stream, and writes it to the supplied destination.
  683. *
  684. * @param TcpConnection $dest
  685. * @return void
  686. */
  687. public function pipe($dest)
  688. {
  689. $source = $this;
  690. $this->onMessage = function ($source, $data) use ($dest) {
  691. $dest->send($data);
  692. };
  693. $this->onClose = function ($source) use ($dest) {
  694. $dest->destroy();
  695. };
  696. $dest->onBufferFull = function ($dest) use ($source) {
  697. $source->pauseRecv();
  698. };
  699. $dest->onBufferDrain = function ($dest) use ($source) {
  700. $source->resumeRecv();
  701. };
  702. }
  703. /**
  704. * Remove $length of data from receive buffer.
  705. *
  706. * @param int $length
  707. * @return void
  708. */
  709. public function consumeRecvBuffer($length)
  710. {
  711. $this->_recvBuffer = substr($this->_recvBuffer, $length);
  712. }
  713. /**
  714. * Close connection.
  715. *
  716. * @param mixed $data
  717. * @param bool $raw
  718. * @return void
  719. */
  720. public function close($data = null, $raw = false)
  721. {
  722. if ($this->_status === self::STATUS_CLOSING || $this->_status === self::STATUS_CLOSED) {
  723. return;
  724. } else {
  725. if ($data !== null) {
  726. $this->send($data, $raw);
  727. }
  728. $this->_status = self::STATUS_CLOSING;
  729. }
  730. if ($this->_sendBuffer === '') {
  731. $this->destroy();
  732. }
  733. }
  734. /**
  735. * Get the real socket.
  736. *
  737. * @return resource
  738. */
  739. public function getSocket()
  740. {
  741. return $this->_socket;
  742. }
  743. /**
  744. * Check whether the send buffer will be full.
  745. *
  746. * @return void
  747. */
  748. protected function checkBufferWillFull()
  749. {
  750. if ($this->maxSendBufferSize <= strlen($this->_sendBuffer)) {
  751. if ($this->onBufferFull) {
  752. try {
  753. call_user_func($this->onBufferFull, $this);
  754. } catch (\Exception $e) {
  755. Worker::log($e);
  756. exit(250);
  757. } catch (\Error $e) {
  758. Worker::log($e);
  759. exit(250);
  760. }
  761. }
  762. }
  763. }
  764. /**
  765. * Whether send buffer is full.
  766. *
  767. * @return bool
  768. */
  769. protected function bufferIsFull()
  770. {
  771. // Buffer has been marked as full but still has data to send then the packet is discarded.
  772. if ($this->maxSendBufferSize <= strlen($this->_sendBuffer)) {
  773. if ($this->onError) {
  774. try {
  775. call_user_func($this->onError, $this, WORKERMAN_SEND_FAIL, 'send buffer full and drop package');
  776. } catch (\Exception $e) {
  777. Worker::log($e);
  778. exit(250);
  779. } catch (\Error $e) {
  780. Worker::log($e);
  781. exit(250);
  782. }
  783. }
  784. return true;
  785. }
  786. return false;
  787. }
  788. /**
  789. * Whether send buffer is Empty.
  790. *
  791. * @return bool
  792. */
  793. public function bufferIsEmpty()
  794. {
  795. return empty($this->_sendBuffer);
  796. }
  797. /**
  798. * Destroy connection.
  799. *
  800. * @return void
  801. */
  802. public function destroy()
  803. {
  804. // Avoid repeated calls.
  805. if ($this->_status === self::STATUS_CLOSED) {
  806. return;
  807. }
  808. // Remove event listener.
  809. Worker::$globalEvent->del($this->_socket, EventInterface::EV_READ);
  810. Worker::$globalEvent->del($this->_socket, EventInterface::EV_WRITE);
  811. // Close socket.
  812. @fclose($this->_socket);
  813. // Remove from worker->connections.
  814. if ($this->worker) {
  815. unset($this->worker->connections[$this->_id]);
  816. }
  817. unset(static::$connections[$this->_id]);
  818. $this->_status = self::STATUS_CLOSED;
  819. // Try to emit onClose callback.
  820. if ($this->onClose) {
  821. try {
  822. call_user_func($this->onClose, $this);
  823. } catch (\Exception $e) {
  824. Worker::log($e);
  825. exit(250);
  826. } catch (\Error $e) {
  827. Worker::log($e);
  828. exit(250);
  829. }
  830. }
  831. // Try to emit protocol::onClose
  832. if ($this->protocol && method_exists($this->protocol, 'onClose')) {
  833. try {
  834. call_user_func(array($this->protocol, 'onClose'), $this);
  835. } catch (\Exception $e) {
  836. Worker::log($e);
  837. exit(250);
  838. } catch (\Error $e) {
  839. Worker::log($e);
  840. exit(250);
  841. }
  842. }
  843. if ($this->_status === self::STATUS_CLOSED) {
  844. // Cleaning up the callback to avoid memory leaks.
  845. $this->onMessage = $this->onClose = $this->onError = $this->onBufferFull = $this->onBufferDrain = null;
  846. }
  847. }
  848. /**
  849. * Destruct.
  850. *
  851. * @return void
  852. */
  853. public function __destruct()
  854. {
  855. static $mod;
  856. self::$statistics['connection_count']--;
  857. if (Worker::getGracefulStop()) {
  858. if (!isset($mod)) {
  859. $mod = ceil((self::$statistics['connection_count'] + 1) / 3);
  860. }
  861. if (0 === self::$statistics['connection_count'] % $mod) {
  862. Worker::log('worker[' . posix_getpid() . '] remains ' . self::$statistics['connection_count'] . ' connection(s)');
  863. }
  864. if(0 === self::$statistics['connection_count']) {
  865. Worker::$globalEvent->destroy();
  866. exit(0);
  867. }
  868. }
  869. }
  870. }