TcpConnection.php 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006
  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. 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. }