TcpConnection.php 27 KB

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