TcpConnection.php 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003
  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 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. } else {
  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. /**
  375. * Get remote IP.
  376. *
  377. * @return string
  378. */
  379. public function getRemoteIp()
  380. {
  381. $pos = \strrpos($this->_remoteAddress, ':');
  382. if ($pos) {
  383. return \substr($this->_remoteAddress, 0, $pos);
  384. }
  385. return '';
  386. }
  387. /**
  388. * Get remote port.
  389. *
  390. * @return int
  391. */
  392. public function getRemotePort()
  393. {
  394. if ($this->_remoteAddress) {
  395. return (int)\substr(\strrchr($this->_remoteAddress, ':'), 1);
  396. }
  397. return 0;
  398. }
  399. /**
  400. * Get remote address.
  401. *
  402. * @return string
  403. */
  404. public function getRemoteAddress()
  405. {
  406. return $this->_remoteAddress;
  407. }
  408. /**
  409. * Get local IP.
  410. *
  411. * @return string
  412. */
  413. public function getLocalIp()
  414. {
  415. $address = $this->getLocalAddress();
  416. $pos = \strrpos($address, ':');
  417. if (!$pos) {
  418. return '';
  419. }
  420. return \substr($address, 0, $pos);
  421. }
  422. /**
  423. * Get local port.
  424. *
  425. * @return int
  426. */
  427. public function getLocalPort()
  428. {
  429. $address = $this->getLocalAddress();
  430. $pos = \strrpos($address, ':');
  431. if (!$pos) {
  432. return 0;
  433. }
  434. return (int)\substr(\strrchr($address, ':'), 1);
  435. }
  436. /**
  437. * Get local address.
  438. *
  439. * @return string
  440. */
  441. public function getLocalAddress()
  442. {
  443. return (string)@\stream_socket_get_name($this->_socket, false);
  444. }
  445. /**
  446. * Get send buffer queue size.
  447. *
  448. * @return integer
  449. */
  450. public function getSendBufferQueueSize()
  451. {
  452. return \strlen($this->_sendBuffer);
  453. }
  454. /**
  455. * Get recv buffer queue size.
  456. *
  457. * @return integer
  458. */
  459. public function getRecvBufferQueueSize()
  460. {
  461. return \strlen($this->_recvBuffer);
  462. }
  463. /**
  464. * Is ipv4.
  465. *
  466. * return bool.
  467. */
  468. public function isIpV4()
  469. {
  470. if ($this->transport === 'unix') {
  471. return false;
  472. }
  473. return \strpos($this->getRemoteIp(), ':') === false;
  474. }
  475. /**
  476. * Is ipv6.
  477. *
  478. * return bool.
  479. */
  480. public function isIpV6()
  481. {
  482. if ($this->transport === 'unix') {
  483. return false;
  484. }
  485. return \strpos($this->getRemoteIp(), ':') !== false;
  486. }
  487. /**
  488. * Pauses the reading of data. That is onMessage will not be emitted. Useful to throttle back an upload.
  489. *
  490. * @return void
  491. */
  492. public function pauseRecv()
  493. {
  494. Worker::$globalEvent->del($this->_socket, EventInterface::EV_READ);
  495. $this->_isPaused = true;
  496. }
  497. /**
  498. * Resumes reading after a call to pauseRecv.
  499. *
  500. * @return void
  501. */
  502. public function resumeRecv()
  503. {
  504. if ($this->_isPaused === true) {
  505. Worker::$globalEvent->add($this->_socket, EventInterface::EV_READ, array($this, 'baseRead'));
  506. $this->_isPaused = false;
  507. $this->baseRead($this->_socket, false);
  508. }
  509. }
  510. /**
  511. * Base read handler.
  512. *
  513. * @param resource $socket
  514. * @param bool $check_eof
  515. * @return void
  516. */
  517. public function baseRead($socket, $check_eof = true)
  518. {
  519. // SSL handshake.
  520. if ($this->transport === 'ssl' && $this->_sslHandshakeCompleted !== true) {
  521. if ($this->doSslHandshake($socket)) {
  522. $this->_sslHandshakeCompleted = true;
  523. if ($this->_sendBuffer) {
  524. Worker::$globalEvent->add($socket, EventInterface::EV_WRITE, array($this, 'baseWrite'));
  525. }
  526. } else {
  527. return;
  528. }
  529. }
  530. \set_error_handler(function(){});
  531. $buffer = \fread($socket, self::READ_BUFFER_SIZE);
  532. \restore_error_handler();
  533. // Check connection closed.
  534. if ($buffer === '' || $buffer === false) {
  535. if ($check_eof && (\feof($socket) || !\is_resource($socket) || $buffer === false)) {
  536. $this->destroy();
  537. return;
  538. }
  539. } else {
  540. $this->bytesRead += \strlen($buffer);
  541. $this->_recvBuffer .= $buffer;
  542. }
  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 > \strlen($this->_recvBuffer)) {
  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 > \strlen($this->_recvBuffer)) {
  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 (\strlen($this->_recvBuffer) === $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 TcpConnection $dest
  728. * @return void
  729. */
  730. public function pipe($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. } else {
  772. if ($data !== null) {
  773. $this->send($data, $raw);
  774. }
  775. $this->_status = self::STATUS_CLOSING;
  776. }
  777. if ($this->_sendBuffer === '') {
  778. $this->destroy();
  779. } else {
  780. $this->pauseRecv();
  781. }
  782. }
  783. /**
  784. * Get the real socket.
  785. *
  786. * @return resource
  787. */
  788. public function getSocket()
  789. {
  790. return $this->_socket;
  791. }
  792. /**
  793. * Check whether the send buffer will be full.
  794. *
  795. * @return void
  796. */
  797. protected function checkBufferWillFull()
  798. {
  799. if ($this->maxSendBufferSize <= \strlen($this->_sendBuffer)) {
  800. if ($this->onBufferFull) {
  801. try {
  802. \call_user_func($this->onBufferFull, $this);
  803. } catch (\Exception $e) {
  804. Worker::log($e);
  805. exit(250);
  806. } catch (\Error $e) {
  807. Worker::log($e);
  808. exit(250);
  809. }
  810. }
  811. }
  812. }
  813. /**
  814. * Whether send buffer is full.
  815. *
  816. * @return bool
  817. */
  818. protected function bufferIsFull()
  819. {
  820. // Buffer has been marked as full but still has data to send then the packet is discarded.
  821. if ($this->maxSendBufferSize <= \strlen($this->_sendBuffer)) {
  822. if ($this->onError) {
  823. try {
  824. \call_user_func($this->onError, $this, WORKERMAN_SEND_FAIL, 'send buffer full and drop package');
  825. } catch (\Exception $e) {
  826. Worker::log($e);
  827. exit(250);
  828. } catch (\Error $e) {
  829. Worker::log($e);
  830. exit(250);
  831. }
  832. }
  833. return true;
  834. }
  835. return false;
  836. }
  837. /**
  838. * Whether send buffer is Empty.
  839. *
  840. * @return bool
  841. */
  842. public function bufferIsEmpty()
  843. {
  844. return empty($this->_sendBuffer);
  845. }
  846. /**
  847. * Destroy connection.
  848. *
  849. * @return void
  850. */
  851. public function destroy()
  852. {
  853. // Avoid repeated calls.
  854. if ($this->_status === self::STATUS_CLOSED) {
  855. return;
  856. }
  857. // Remove event listener.
  858. Worker::$globalEvent->del($this->_socket, EventInterface::EV_READ);
  859. Worker::$globalEvent->del($this->_socket, EventInterface::EV_WRITE);
  860. // Close socket.
  861. \set_error_handler(function(){});
  862. \fclose($this->_socket);
  863. \restore_error_handler();
  864. $this->_status = self::STATUS_CLOSED;
  865. // Try to emit onClose callback.
  866. if ($this->onClose) {
  867. try {
  868. \call_user_func($this->onClose, $this);
  869. } catch (\Exception $e) {
  870. Worker::log($e);
  871. exit(250);
  872. } catch (\Error $e) {
  873. Worker::log($e);
  874. exit(250);
  875. }
  876. }
  877. // Try to emit protocol::onClose
  878. if ($this->protocol && \method_exists($this->protocol, 'onClose')) {
  879. try {
  880. \call_user_func(array($this->protocol, 'onClose'), $this);
  881. } catch (\Exception $e) {
  882. Worker::log($e);
  883. exit(250);
  884. } catch (\Error $e) {
  885. Worker::log($e);
  886. exit(250);
  887. }
  888. }
  889. $this->_sendBuffer = $this->_recvBuffer = '';
  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. }