TcpConnection.php 27 KB

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