TcpConnection.php 27 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001
  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. * 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. * Adding support of custom functions within protocols
  231. *
  232. * @param string $name
  233. * @param array $arguments
  234. * @return void
  235. */
  236. public function __call($name, $arguments) {
  237. // Try to emit custom function within protocol
  238. if (method_exists($this->protocol, $name)) {
  239. try {
  240. return call_user_func(array($this->protocol, $name), $this, $arguments);
  241. } catch (\Exception $e) {
  242. Worker::log($e);
  243. exit(250);
  244. } catch (\Error $e) {
  245. Worker::log($e);
  246. exit(250);
  247. }
  248. }
  249. }
  250. /**
  251. * Construct.
  252. *
  253. * @param resource $socket
  254. * @param string $remote_address
  255. */
  256. public function __construct($socket, $remote_address = '')
  257. {
  258. self::$statistics['connection_count']++;
  259. $this->id = $this->_id = self::$_idRecorder++;
  260. if(self::$_idRecorder === PHP_INT_MAX){
  261. self::$_idRecorder = 0;
  262. }
  263. $this->_socket = $socket;
  264. stream_set_blocking($this->_socket, 0);
  265. // Compatible with hhvm
  266. if (function_exists('stream_set_read_buffer')) {
  267. stream_set_read_buffer($this->_socket, 0);
  268. }
  269. Worker::$globalEvent->add($this->_socket, EventInterface::EV_READ, array($this, 'baseRead'));
  270. $this->maxSendBufferSize = self::$defaultMaxSendBufferSize;
  271. $this->maxPackageSize = self::$defaultMaxPackageSize;
  272. $this->_remoteAddress = $remote_address;
  273. static::$connections[$this->id] = $this;
  274. }
  275. /**
  276. * Get status.
  277. *
  278. * @param bool $raw_output
  279. *
  280. * @return int
  281. */
  282. public function getStatus($raw_output = true)
  283. {
  284. if ($raw_output) {
  285. return $this->_status;
  286. }
  287. return self::$_statusToString[$this->_status];
  288. }
  289. /**
  290. * Sends data on the connection.
  291. *
  292. * @param string $send_buffer
  293. * @param bool $raw
  294. * @return bool|null
  295. */
  296. public function send($send_buffer, $raw = false)
  297. {
  298. if ($this->_status === self::STATUS_CLOSING || $this->_status === self::STATUS_CLOSED) {
  299. return false;
  300. }
  301. // Try to call protocol::encode($send_buffer) before sending.
  302. if (false === $raw && $this->protocol !== null) {
  303. $parser = $this->protocol;
  304. $send_buffer = $parser::encode($send_buffer, $this);
  305. if ($send_buffer === '') {
  306. return null;
  307. }
  308. }
  309. if ($this->_status !== self::STATUS_ESTABLISHED ||
  310. ($this->transport === 'ssl' && $this->_sslHandshakeCompleted !== true)
  311. ) {
  312. if ($this->_sendBuffer) {
  313. if ($this->bufferIsFull()) {
  314. self::$statistics['send_fail']++;
  315. return false;
  316. }
  317. }
  318. $this->_sendBuffer .= $send_buffer;
  319. $this->checkBufferWillFull();
  320. return null;
  321. }
  322. // Attempt to send data directly.
  323. if ($this->_sendBuffer === '') {
  324. if ($this->transport === 'ssl') {
  325. Worker::$globalEvent->add($this->_socket, EventInterface::EV_WRITE, array($this, 'baseWrite'));
  326. $this->_sendBuffer = $send_buffer;
  327. $this->checkBufferWillFull();
  328. return null;
  329. }
  330. set_error_handler(function(){});
  331. $len = fwrite($this->_socket, $send_buffer);
  332. restore_error_handler();
  333. // send successful.
  334. if ($len === strlen($send_buffer)) {
  335. $this->bytesWritten += $len;
  336. return true;
  337. }
  338. // Send only part of the data.
  339. if ($len > 0) {
  340. $this->_sendBuffer = substr($send_buffer, $len);
  341. $this->bytesWritten += $len;
  342. } else {
  343. // Connection closed?
  344. if (!is_resource($this->_socket) || feof($this->_socket)) {
  345. self::$statistics['send_fail']++;
  346. if ($this->onError) {
  347. try {
  348. call_user_func($this->onError, $this, WORKERMAN_SEND_FAIL, 'client closed');
  349. } catch (\Exception $e) {
  350. Worker::log($e);
  351. exit(250);
  352. } catch (\Error $e) {
  353. Worker::log($e);
  354. exit(250);
  355. }
  356. }
  357. $this->destroy();
  358. return false;
  359. }
  360. $this->_sendBuffer = $send_buffer;
  361. }
  362. Worker::$globalEvent->add($this->_socket, EventInterface::EV_WRITE, array($this, 'baseWrite'));
  363. // Check if the send buffer will be full.
  364. $this->checkBufferWillFull();
  365. return null;
  366. } else {
  367. if ($this->bufferIsFull()) {
  368. self::$statistics['send_fail']++;
  369. return false;
  370. }
  371. $this->_sendBuffer .= $send_buffer;
  372. // Check if the send buffer is full.
  373. $this->checkBufferWillFull();
  374. }
  375. }
  376. /**
  377. * Get remote IP.
  378. *
  379. * @return string
  380. */
  381. public function getRemoteIp()
  382. {
  383. $pos = strrpos($this->_remoteAddress, ':');
  384. if ($pos) {
  385. return substr($this->_remoteAddress, 0, $pos);
  386. }
  387. return '';
  388. }
  389. /**
  390. * Get remote port.
  391. *
  392. * @return int
  393. */
  394. public function getRemotePort()
  395. {
  396. if ($this->_remoteAddress) {
  397. return (int)substr(strrchr($this->_remoteAddress, ':'), 1);
  398. }
  399. return 0;
  400. }
  401. /**
  402. * Get remote address.
  403. *
  404. * @return string
  405. */
  406. public function getRemoteAddress()
  407. {
  408. return $this->_remoteAddress;
  409. }
  410. /**
  411. * Get local IP.
  412. *
  413. * @return string
  414. */
  415. public function getLocalIp()
  416. {
  417. $address = $this->getLocalAddress();
  418. $pos = strrpos($address, ':');
  419. if (!$pos) {
  420. return '';
  421. }
  422. return substr($address, 0, $pos);
  423. }
  424. /**
  425. * Get local port.
  426. *
  427. * @return int
  428. */
  429. public function getLocalPort()
  430. {
  431. $address = $this->getLocalAddress();
  432. $pos = strrpos($address, ':');
  433. if (!$pos) {
  434. return 0;
  435. }
  436. return (int)substr(strrchr($address, ':'), 1);
  437. }
  438. /**
  439. * Get local address.
  440. *
  441. * @return string
  442. */
  443. public function getLocalAddress()
  444. {
  445. return (string)@stream_socket_get_name($this->_socket, false);
  446. }
  447. /**
  448. * Get send buffer queue size.
  449. *
  450. * @return integer
  451. */
  452. public function getSendBufferQueueSize()
  453. {
  454. return strlen($this->_sendBuffer);
  455. }
  456. /**
  457. * Get recv buffer queue size.
  458. *
  459. * @return integer
  460. */
  461. public function getRecvBufferQueueSize()
  462. {
  463. return strlen($this->_recvBuffer);
  464. }
  465. /**
  466. * Is ipv4.
  467. *
  468. * return bool.
  469. */
  470. public function isIpV4()
  471. {
  472. if ($this->transport === 'unix') {
  473. return false;
  474. }
  475. return strpos($this->getRemoteIp(), ':') === false;
  476. }
  477. /**
  478. * Is ipv6.
  479. *
  480. * return bool.
  481. */
  482. public function isIpV6()
  483. {
  484. if ($this->transport === 'unix') {
  485. return false;
  486. }
  487. return strpos($this->getRemoteIp(), ':') !== false;
  488. }
  489. /**
  490. * Pauses the reading of data. That is onMessage will not be emitted. Useful to throttle back an upload.
  491. *
  492. * @return void
  493. */
  494. public function pauseRecv()
  495. {
  496. Worker::$globalEvent->del($this->_socket, EventInterface::EV_READ);
  497. $this->_isPaused = true;
  498. }
  499. /**
  500. * Resumes reading after a call to pauseRecv.
  501. *
  502. * @return void
  503. */
  504. public function resumeRecv()
  505. {
  506. if ($this->_isPaused === true) {
  507. Worker::$globalEvent->add($this->_socket, EventInterface::EV_READ, array($this, 'baseRead'));
  508. $this->_isPaused = false;
  509. $this->baseRead($this->_socket, false);
  510. }
  511. }
  512. /**
  513. * Base read handler.
  514. *
  515. * @param resource $socket
  516. * @param bool $check_eof
  517. * @return void
  518. */
  519. public function baseRead($socket, $check_eof = true)
  520. {
  521. // SSL handshake.
  522. if ($this->transport === 'ssl' && $this->_sslHandshakeCompleted !== true) {
  523. if ($this->doSslHandshake($socket)) {
  524. $this->_sslHandshakeCompleted = true;
  525. if ($this->_sendBuffer) {
  526. Worker::$globalEvent->add($socket, EventInterface::EV_WRITE, array($this, 'baseWrite'));
  527. }
  528. } else {
  529. return;
  530. }
  531. }
  532. set_error_handler(function(){});
  533. $buffer = fread($socket, self::READ_BUFFER_SIZE);
  534. restore_error_handler();
  535. // Check connection closed.
  536. if ($buffer === '' || $buffer === false) {
  537. if ($check_eof && (feof($socket) || !is_resource($socket) || $buffer === false)) {
  538. $this->destroy();
  539. return;
  540. }
  541. } else {
  542. $this->bytesRead += strlen($buffer);
  543. $this->_recvBuffer .= $buffer;
  544. }
  545. // If the application layer protocol has been set up.
  546. if ($this->protocol !== null) {
  547. $parser = $this->protocol;
  548. while ($this->_recvBuffer !== '' && !$this->_isPaused) {
  549. // The current packet length is known.
  550. if ($this->_currentPackageLength) {
  551. // Data is not enough for a package.
  552. if ($this->_currentPackageLength > strlen($this->_recvBuffer)) {
  553. break;
  554. }
  555. } else {
  556. // Get current package length.
  557. set_error_handler(function($code, $msg, $file, $line){
  558. Worker::safeEcho("$msg in file $file on line $line\n");
  559. });
  560. $this->_currentPackageLength = $parser::input($this->_recvBuffer, $this);
  561. restore_error_handler();
  562. // The packet length is unknown.
  563. if ($this->_currentPackageLength === 0) {
  564. break;
  565. } elseif ($this->_currentPackageLength > 0 && $this->_currentPackageLength <= $this->maxPackageSize) {
  566. // Data is not enough for a package.
  567. if ($this->_currentPackageLength > strlen($this->_recvBuffer)) {
  568. break;
  569. }
  570. } // Wrong package.
  571. else {
  572. Worker::safeEcho('error package. package_length=' . var_export($this->_currentPackageLength, true));
  573. $this->destroy();
  574. return;
  575. }
  576. }
  577. // The data is enough for a packet.
  578. self::$statistics['total_request']++;
  579. // The current packet length is equal to the length of the buffer.
  580. if (strlen($this->_recvBuffer) === $this->_currentPackageLength) {
  581. $one_request_buffer = $this->_recvBuffer;
  582. $this->_recvBuffer = '';
  583. } else {
  584. // Get a full package from the buffer.
  585. $one_request_buffer = substr($this->_recvBuffer, 0, $this->_currentPackageLength);
  586. // Remove the current package from the receive buffer.
  587. $this->_recvBuffer = substr($this->_recvBuffer, $this->_currentPackageLength);
  588. }
  589. // Reset the current packet length to 0.
  590. $this->_currentPackageLength = 0;
  591. if (!$this->onMessage) {
  592. continue;
  593. }
  594. try {
  595. // Decode request buffer before Emitting onMessage callback.
  596. call_user_func($this->onMessage, $this, $parser::decode($one_request_buffer, $this));
  597. } catch (\Exception $e) {
  598. Worker::log($e);
  599. exit(250);
  600. } catch (\Error $e) {
  601. Worker::log($e);
  602. exit(250);
  603. }
  604. }
  605. return;
  606. }
  607. if ($this->_recvBuffer === '' || $this->_isPaused) {
  608. return;
  609. }
  610. // Applications protocol is not set.
  611. self::$statistics['total_request']++;
  612. if (!$this->onMessage) {
  613. $this->_recvBuffer = '';
  614. return;
  615. }
  616. try {
  617. call_user_func($this->onMessage, $this, $this->_recvBuffer);
  618. } catch (\Exception $e) {
  619. Worker::log($e);
  620. exit(250);
  621. } catch (\Error $e) {
  622. Worker::log($e);
  623. exit(250);
  624. }
  625. // Clean receive buffer.
  626. $this->_recvBuffer = '';
  627. }
  628. /**
  629. * Base write handler.
  630. *
  631. * @return void|bool
  632. */
  633. public function baseWrite()
  634. {
  635. set_error_handler(function(){});
  636. if ($this->transport === 'ssl') {
  637. $len = fwrite($this->_socket, $this->_sendBuffer, 8192);
  638. } else {
  639. $len = fwrite($this->_socket, $this->_sendBuffer);
  640. }
  641. restore_error_handler();
  642. if ($len === strlen($this->_sendBuffer)) {
  643. $this->bytesWritten += $len;
  644. Worker::$globalEvent->del($this->_socket, EventInterface::EV_WRITE);
  645. $this->_sendBuffer = '';
  646. // Try to emit onBufferDrain callback when the send buffer becomes empty.
  647. if ($this->onBufferDrain) {
  648. try {
  649. call_user_func($this->onBufferDrain, $this);
  650. } catch (\Exception $e) {
  651. Worker::log($e);
  652. exit(250);
  653. } catch (\Error $e) {
  654. Worker::log($e);
  655. exit(250);
  656. }
  657. }
  658. if ($this->_status === self::STATUS_CLOSING) {
  659. $this->destroy();
  660. }
  661. return true;
  662. }
  663. if ($len > 0) {
  664. $this->bytesWritten += $len;
  665. $this->_sendBuffer = substr($this->_sendBuffer, $len);
  666. } else {
  667. self::$statistics['send_fail']++;
  668. $this->destroy();
  669. }
  670. }
  671. /**
  672. * SSL handshake.
  673. *
  674. * @param $socket
  675. * @return bool
  676. */
  677. public function doSslHandshake($socket){
  678. if (feof($socket)) {
  679. $this->destroy();
  680. return false;
  681. }
  682. $async = $this instanceof AsyncTcpConnection;
  683. /**
  684. * We disabled ssl3 because https://blog.qualys.com/ssllabs/2014/10/15/ssl-3-is-dead-killed-by-the-poodle-attack.
  685. * You can enable ssl3 by the codes below.
  686. */
  687. /*if($async){
  688. $type = STREAM_CRYPTO_METHOD_SSLv2_CLIENT | STREAM_CRYPTO_METHOD_SSLv23_CLIENT | STREAM_CRYPTO_METHOD_SSLv3_CLIENT;
  689. }else{
  690. $type = STREAM_CRYPTO_METHOD_SSLv2_SERVER | STREAM_CRYPTO_METHOD_SSLv23_SERVER | STREAM_CRYPTO_METHOD_SSLv3_SERVER;
  691. }*/
  692. if($async){
  693. $type = STREAM_CRYPTO_METHOD_SSLv2_CLIENT | STREAM_CRYPTO_METHOD_SSLv23_CLIENT;
  694. }else{
  695. $type = STREAM_CRYPTO_METHOD_SSLv2_SERVER | STREAM_CRYPTO_METHOD_SSLv23_SERVER;
  696. }
  697. // Hidden error.
  698. set_error_handler(function($errno, $errstr, $file){
  699. if (!Worker::$daemonize) {
  700. Worker::safeEcho("SSL handshake error: $errstr \n");
  701. }
  702. });
  703. $ret = stream_socket_enable_crypto($socket, true, $type);
  704. restore_error_handler();
  705. // Negotiation has failed.
  706. if (false === $ret) {
  707. $this->destroy();
  708. return false;
  709. } elseif (0 === $ret) {
  710. // There isn't enough data and should try again.
  711. return false;
  712. }
  713. if (isset($this->onSslHandshake)) {
  714. try {
  715. call_user_func($this->onSslHandshake, $this);
  716. } catch (\Exception $e) {
  717. Worker::log($e);
  718. exit(250);
  719. } catch (\Error $e) {
  720. Worker::log($e);
  721. exit(250);
  722. }
  723. }
  724. return true;
  725. }
  726. /**
  727. * This method pulls all the data out of a readable stream, and writes it to the supplied destination.
  728. *
  729. * @param TcpConnection $dest
  730. * @return void
  731. */
  732. public function pipe($dest)
  733. {
  734. $source = $this;
  735. $this->onMessage = function ($source, $data) use ($dest) {
  736. $dest->send($data);
  737. };
  738. $this->onClose = function ($source) use ($dest) {
  739. $dest->destroy();
  740. };
  741. $dest->onBufferFull = function ($dest) use ($source) {
  742. $source->pauseRecv();
  743. };
  744. $dest->onBufferDrain = function ($dest) use ($source) {
  745. $source->resumeRecv();
  746. };
  747. }
  748. /**
  749. * Remove $length of data from receive buffer.
  750. *
  751. * @param int $length
  752. * @return void
  753. */
  754. public function consumeRecvBuffer($length)
  755. {
  756. $this->_recvBuffer = substr($this->_recvBuffer, $length);
  757. }
  758. /**
  759. * Close connection.
  760. *
  761. * @param mixed $data
  762. * @param bool $raw
  763. * @return void
  764. */
  765. public function close($data = null, $raw = false)
  766. {
  767. if ($this->_status === self::STATUS_CLOSING || $this->_status === self::STATUS_CLOSED) {
  768. return;
  769. } else {
  770. if ($data !== null) {
  771. $this->send($data, $raw);
  772. }
  773. $this->_status = self::STATUS_CLOSING;
  774. }
  775. if ($this->_sendBuffer === '') {
  776. $this->destroy();
  777. } else {
  778. $this->pauseRecv();
  779. }
  780. }
  781. /**
  782. * Get the real socket.
  783. *
  784. * @return resource
  785. */
  786. public function getSocket()
  787. {
  788. return $this->_socket;
  789. }
  790. /**
  791. * Check whether the send buffer will be full.
  792. *
  793. * @return void
  794. */
  795. protected function checkBufferWillFull()
  796. {
  797. if ($this->maxSendBufferSize <= strlen($this->_sendBuffer)) {
  798. if ($this->onBufferFull) {
  799. try {
  800. call_user_func($this->onBufferFull, $this);
  801. } catch (\Exception $e) {
  802. Worker::log($e);
  803. exit(250);
  804. } catch (\Error $e) {
  805. Worker::log($e);
  806. exit(250);
  807. }
  808. }
  809. }
  810. }
  811. /**
  812. * Whether send buffer is full.
  813. *
  814. * @return bool
  815. */
  816. protected function bufferIsFull()
  817. {
  818. // Buffer has been marked as full but still has data to send then the packet is discarded.
  819. if ($this->maxSendBufferSize <= strlen($this->_sendBuffer)) {
  820. if ($this->onError) {
  821. try {
  822. call_user_func($this->onError, $this, WORKERMAN_SEND_FAIL, 'send buffer full and drop package');
  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. return true;
  832. }
  833. return false;
  834. }
  835. /**
  836. * Whether send buffer is Empty.
  837. *
  838. * @return bool
  839. */
  840. public function bufferIsEmpty()
  841. {
  842. return empty($this->_sendBuffer);
  843. }
  844. /**
  845. * Destroy connection.
  846. *
  847. * @return void
  848. */
  849. public function destroy()
  850. {
  851. // Avoid repeated calls.
  852. if ($this->_status === self::STATUS_CLOSED) {
  853. return;
  854. }
  855. // Remove event listener.
  856. Worker::$globalEvent->del($this->_socket, EventInterface::EV_READ);
  857. Worker::$globalEvent->del($this->_socket, EventInterface::EV_WRITE);
  858. // Close socket.
  859. set_error_handler(function(){});
  860. fclose($this->_socket);
  861. restore_error_handler();
  862. $this->_status = self::STATUS_CLOSED;
  863. // Try to emit onClose callback.
  864. if ($this->onClose) {
  865. try {
  866. call_user_func($this->onClose, $this);
  867. } catch (\Exception $e) {
  868. Worker::log($e);
  869. exit(250);
  870. } catch (\Error $e) {
  871. Worker::log($e);
  872. exit(250);
  873. }
  874. }
  875. // Try to emit protocol::onClose
  876. if ($this->protocol && method_exists($this->protocol, 'onClose')) {
  877. try {
  878. call_user_func(array($this->protocol, 'onClose'), $this);
  879. } catch (\Exception $e) {
  880. Worker::log($e);
  881. exit(250);
  882. } catch (\Error $e) {
  883. Worker::log($e);
  884. exit(250);
  885. }
  886. }
  887. $this->_sendBuffer = $this->_recvBuffer = '';
  888. if ($this->_status === self::STATUS_CLOSED) {
  889. // Cleaning up the callback to avoid memory leaks.
  890. $this->onMessage = $this->onClose = $this->onError = $this->onBufferFull = $this->onBufferDrain = null;
  891. // Remove from worker->connections.
  892. if ($this->worker) {
  893. unset($this->worker->connections[$this->_id]);
  894. }
  895. unset(static::$connections[$this->_id]);
  896. }
  897. }
  898. /**
  899. * Destruct.
  900. *
  901. * @return void
  902. */
  903. public function __destruct()
  904. {
  905. static $mod;
  906. self::$statistics['connection_count']--;
  907. if (Worker::getGracefulStop()) {
  908. if (!isset($mod)) {
  909. $mod = ceil((self::$statistics['connection_count'] + 1) / 3);
  910. }
  911. if (0 === self::$statistics['connection_count'] % $mod) {
  912. Worker::log('worker[' . posix_getpid() . '] remains ' . self::$statistics['connection_count'] . ' connection(s)');
  913. }
  914. if(0 === self::$statistics['connection_count']) {
  915. Worker::stopAll();
  916. }
  917. }
  918. }
  919. }