TcpConnection.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008
  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. // If the application layer protocol has been set up.
  543. if ($this->protocol !== null) {
  544. $parser = $this->protocol;
  545. while ($this->_recvBuffer !== '' && !$this->_isPaused) {
  546. // The current packet length is known.
  547. if ($this->_currentPackageLength) {
  548. // Data is not enough for a package.
  549. if ($this->_currentPackageLength > \strlen($this->_recvBuffer)) {
  550. break;
  551. }
  552. } else {
  553. // Get current package length.
  554. \set_error_handler(function($code, $msg, $file, $line){
  555. Worker::safeEcho("$msg in file $file on line $line\n");
  556. });
  557. $this->_currentPackageLength = $parser::input($this->_recvBuffer, $this);
  558. \restore_error_handler();
  559. // The packet length is unknown.
  560. if ($this->_currentPackageLength === 0) {
  561. break;
  562. } elseif ($this->_currentPackageLength > 0 && $this->_currentPackageLength <= $this->maxPackageSize) {
  563. // Data is not enough for a package.
  564. if ($this->_currentPackageLength > \strlen($this->_recvBuffer)) {
  565. break;
  566. }
  567. } // Wrong package.
  568. else {
  569. Worker::safeEcho('Error package. package_length=' . \var_export($this->_currentPackageLength, true));
  570. $this->destroy();
  571. return;
  572. }
  573. }
  574. // The data is enough for a packet.
  575. ++self::$statistics['total_request'];
  576. // The current packet length is equal to the length of the buffer.
  577. if (\strlen($this->_recvBuffer) === $this->_currentPackageLength) {
  578. $one_request_buffer = $this->_recvBuffer;
  579. $this->_recvBuffer = '';
  580. } else {
  581. // Get a full package from the buffer.
  582. $one_request_buffer = \substr($this->_recvBuffer, 0, $this->_currentPackageLength);
  583. // Remove the current package from the receive buffer.
  584. $this->_recvBuffer = \substr($this->_recvBuffer, $this->_currentPackageLength);
  585. }
  586. // Reset the current packet length to 0.
  587. $this->_currentPackageLength = 0;
  588. if (!$this->onMessage) {
  589. continue;
  590. }
  591. try {
  592. // Decode request buffer before Emitting onMessage callback.
  593. \call_user_func($this->onMessage, $this, $parser::decode($one_request_buffer, $this));
  594. } catch (\Exception $e) {
  595. Worker::log($e);
  596. exit(250);
  597. } catch (\Error $e) {
  598. Worker::log($e);
  599. exit(250);
  600. }
  601. }
  602. return;
  603. }
  604. if ($this->_recvBuffer === '' || $this->_isPaused) {
  605. return;
  606. }
  607. // Applications protocol is not set.
  608. ++self::$statistics['total_request'];
  609. if (!$this->onMessage) {
  610. $this->_recvBuffer = '';
  611. return;
  612. }
  613. try {
  614. \call_user_func($this->onMessage, $this, $this->_recvBuffer);
  615. } catch (\Exception $e) {
  616. Worker::log($e);
  617. exit(250);
  618. } catch (\Error $e) {
  619. Worker::log($e);
  620. exit(250);
  621. }
  622. // Clean receive buffer.
  623. $this->_recvBuffer = '';
  624. }
  625. /**
  626. * Base write handler.
  627. *
  628. * @return void|bool
  629. */
  630. public function baseWrite()
  631. {
  632. \set_error_handler(function(){});
  633. if ($this->transport === 'ssl') {
  634. $len = \fwrite($this->_socket, $this->_sendBuffer, 8192);
  635. } else {
  636. $len = \fwrite($this->_socket, $this->_sendBuffer);
  637. }
  638. \restore_error_handler();
  639. if ($len === \strlen($this->_sendBuffer)) {
  640. $this->bytesWritten += $len;
  641. Worker::$globalEvent->del($this->_socket, EventInterface::EV_WRITE);
  642. $this->_sendBuffer = '';
  643. // Try to emit onBufferDrain callback when the send buffer becomes empty.
  644. if ($this->onBufferDrain) {
  645. try {
  646. \call_user_func($this->onBufferDrain, $this);
  647. } catch (\Exception $e) {
  648. Worker::log($e);
  649. exit(250);
  650. } catch (\Error $e) {
  651. Worker::log($e);
  652. exit(250);
  653. }
  654. }
  655. if ($this->_status === self::STATUS_CLOSING) {
  656. $this->destroy();
  657. }
  658. return true;
  659. }
  660. if ($len > 0) {
  661. $this->bytesWritten += $len;
  662. $this->_sendBuffer = \substr($this->_sendBuffer, $len);
  663. } else {
  664. ++self::$statistics['send_fail'];
  665. $this->destroy();
  666. }
  667. }
  668. /**
  669. * SSL handshake.
  670. *
  671. * @param $socket
  672. * @return bool
  673. */
  674. public function doSslHandshake($socket){
  675. if (\feof($socket)) {
  676. $this->destroy();
  677. return false;
  678. }
  679. $async = $this instanceof AsyncTcpConnection;
  680. /**
  681. * We disabled ssl3 because https://blog.qualys.com/ssllabs/2014/10/15/ssl-3-is-dead-killed-by-the-poodle-attack.
  682. * You can enable ssl3 by the codes below.
  683. */
  684. /*if($async){
  685. $type = STREAM_CRYPTO_METHOD_SSLv2_CLIENT | STREAM_CRYPTO_METHOD_SSLv23_CLIENT | STREAM_CRYPTO_METHOD_SSLv3_CLIENT;
  686. }else{
  687. $type = STREAM_CRYPTO_METHOD_SSLv2_SERVER | STREAM_CRYPTO_METHOD_SSLv23_SERVER | STREAM_CRYPTO_METHOD_SSLv3_SERVER;
  688. }*/
  689. if($async){
  690. $type = \STREAM_CRYPTO_METHOD_SSLv2_CLIENT | \STREAM_CRYPTO_METHOD_SSLv23_CLIENT;
  691. }else{
  692. $type = \STREAM_CRYPTO_METHOD_SSLv2_SERVER | \STREAM_CRYPTO_METHOD_SSLv23_SERVER;
  693. }
  694. // Hidden error.
  695. \set_error_handler(function($errno, $errstr, $file){
  696. if (!Worker::$daemonize) {
  697. Worker::safeEcho("SSL handshake error: $errstr \n");
  698. }
  699. });
  700. $ret = \stream_socket_enable_crypto($socket, true, $type);
  701. \restore_error_handler();
  702. // Negotiation has failed.
  703. if (false === $ret) {
  704. $this->destroy();
  705. return false;
  706. } elseif (0 === $ret) {
  707. // There isn't enough data and should try again.
  708. return 0;
  709. }
  710. if (isset($this->onSslHandshake)) {
  711. try {
  712. \call_user_func($this->onSslHandshake, $this);
  713. } catch (\Exception $e) {
  714. Worker::log($e);
  715. exit(250);
  716. } catch (\Error $e) {
  717. Worker::log($e);
  718. exit(250);
  719. }
  720. }
  721. return true;
  722. }
  723. /**
  724. * This method pulls all the data out of a readable stream, and writes it to the supplied destination.
  725. *
  726. * @param self $dest
  727. * @return void
  728. */
  729. public function pipe(self $dest)
  730. {
  731. $source = $this;
  732. $this->onMessage = function ($source, $data) use ($dest) {
  733. $dest->send($data);
  734. };
  735. $this->onClose = function ($source) use ($dest) {
  736. $dest->destroy();
  737. };
  738. $dest->onBufferFull = function ($dest) use ($source) {
  739. $source->pauseRecv();
  740. };
  741. $dest->onBufferDrain = function ($dest) use ($source) {
  742. $source->resumeRecv();
  743. };
  744. }
  745. /**
  746. * Remove $length of data from receive buffer.
  747. *
  748. * @param int $length
  749. * @return void
  750. */
  751. public function consumeRecvBuffer($length)
  752. {
  753. $this->_recvBuffer = \substr($this->_recvBuffer, $length);
  754. }
  755. /**
  756. * Close connection.
  757. *
  758. * @param mixed $data
  759. * @param bool $raw
  760. * @return void
  761. */
  762. public function close($data = null, $raw = false)
  763. {
  764. if($this->_status === self::STATUS_CONNECTING){
  765. $this->destroy();
  766. return;
  767. }
  768. if ($this->_status === self::STATUS_CLOSING || $this->_status === self::STATUS_CLOSED) {
  769. return;
  770. }
  771. if ($data !== null) {
  772. $this->send($data, $raw);
  773. }
  774. $this->_status = self::STATUS_CLOSING;
  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. $this->_currentPackageLength = 0;
  889. $this->_isPaused = $this->_sslHandshakeCompleted = false;
  890. if ($this->_status === self::STATUS_CLOSED) {
  891. // Cleaning up the callback to avoid memory leaks.
  892. $this->onMessage = $this->onClose = $this->onError = $this->onBufferFull = $this->onBufferDrain = null;
  893. // Remove from worker->connections.
  894. if ($this->worker) {
  895. unset($this->worker->connections[$this->_id]);
  896. }
  897. unset(static::$connections[$this->_id]);
  898. }
  899. }
  900. /**
  901. * Destruct.
  902. *
  903. * @return void
  904. */
  905. public function __destruct()
  906. {
  907. static $mod;
  908. self::$statistics['connection_count']--;
  909. if (Worker::getGracefulStop()) {
  910. if (!isset($mod)) {
  911. $mod = \ceil((self::$statistics['connection_count'] + 1) / 3);
  912. }
  913. if (0 === self::$statistics['connection_count'] % $mod) {
  914. Worker::log('worker[' . \posix_getpid() . '] remains ' . self::$statistics['connection_count'] . ' connection(s)');
  915. }
  916. if(0 === self::$statistics['connection_count']) {
  917. Worker::stopAll();
  918. }
  919. }
  920. }
  921. }