TcpConnection.php 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030
  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\Protocols\Http\Request;
  17. use Workerman\Worker;
  18. /**
  19. * TcpConnection.
  20. */
  21. class TcpConnection extends ConnectionInterface implements \JsonSerializable
  22. {
  23. /**
  24. * Read buffer size.
  25. *
  26. * @var int
  27. */
  28. const READ_BUFFER_SIZE = 87380;
  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. * Context.
  141. *
  142. * @var object|null
  143. */
  144. public $context = null;
  145. /**
  146. * Default send buffer size.
  147. *
  148. * @var int
  149. */
  150. public static $defaultMaxSendBufferSize = 1048576;
  151. /**
  152. * Sets the maximum acceptable packet size for the current connection.
  153. *
  154. * @var int
  155. */
  156. public $maxPackageSize = 1048576;
  157. /**
  158. * Default maximum acceptable packet size.
  159. *
  160. * @var int
  161. */
  162. public static $defaultMaxPackageSize = 10485760;
  163. /**
  164. * Id recorder.
  165. *
  166. * @var int
  167. */
  168. protected static $_idRecorder = 1;
  169. /**
  170. * Cache.
  171. *
  172. * @var bool.
  173. */
  174. protected static $_enableCache = true;
  175. /**
  176. * Socket
  177. *
  178. * @var resource
  179. */
  180. protected $_socket = null;
  181. /**
  182. * Send buffer.
  183. *
  184. * @var string
  185. */
  186. protected $_sendBuffer = '';
  187. /**
  188. * Receive buffer.
  189. *
  190. * @var string
  191. */
  192. protected $_recvBuffer = '';
  193. /**
  194. * Current package length.
  195. *
  196. * @var int
  197. */
  198. protected $_currentPackageLength = 0;
  199. /**
  200. * Connection status.
  201. *
  202. * @var int
  203. */
  204. protected $_status = self::STATUS_ESTABLISHED;
  205. /**
  206. * Remote address.
  207. *
  208. * @var string
  209. */
  210. protected $_remoteAddress = '';
  211. /**
  212. * Is paused.
  213. *
  214. * @var bool
  215. */
  216. protected $_isPaused = false;
  217. /**
  218. * SSL handshake completed or not.
  219. *
  220. * @var bool
  221. */
  222. protected $_sslHandshakeCompleted = false;
  223. /**
  224. * All connection instances.
  225. *
  226. * @var array
  227. */
  228. public static $connections = [];
  229. /**
  230. * Status to string.
  231. *
  232. * @var array
  233. */
  234. public static $_statusToString = [
  235. self::STATUS_INITIAL => 'INITIAL',
  236. self::STATUS_CONNECTING => 'CONNECTING',
  237. self::STATUS_ESTABLISHED => 'ESTABLISHED',
  238. self::STATUS_CLOSING => 'CLOSING',
  239. self::STATUS_CLOSED => 'CLOSED',
  240. ];
  241. /**
  242. * Construct.
  243. *
  244. * @param resource $socket
  245. * @param string $remote_address
  246. */
  247. public function __construct($socket, $remote_address = '')
  248. {
  249. ++self::$statistics['connection_count'];
  250. $this->id = $this->_id = self::$_idRecorder++;
  251. if (self::$_idRecorder === \PHP_INT_MAX) {
  252. self::$_idRecorder = 0;
  253. }
  254. $this->_socket = $socket;
  255. \stream_set_blocking($this->_socket, 0);
  256. // Compatible with hhvm
  257. if (\function_exists('stream_set_read_buffer')) {
  258. \stream_set_read_buffer($this->_socket, 0);
  259. }
  260. Worker::$globalEvent->onReadable($this->_socket, [$this, 'baseRead']);
  261. $this->maxSendBufferSize = self::$defaultMaxSendBufferSize;
  262. $this->maxPackageSize = self::$defaultMaxPackageSize;
  263. $this->_remoteAddress = $remote_address;
  264. static::$connections[$this->id] = $this;
  265. $this->context = new \stdClass;
  266. }
  267. /**
  268. * Get status.
  269. *
  270. * @param bool $raw_output
  271. *
  272. * @return int|string
  273. */
  274. public function getStatus($raw_output = true)
  275. {
  276. if ($raw_output) {
  277. return $this->_status;
  278. }
  279. return self::$_statusToString[$this->_status];
  280. }
  281. /**
  282. * Sends data on the connection.
  283. *
  284. * @param mixed $send_buffer
  285. * @param bool $raw
  286. * @return bool|null
  287. */
  288. public function send($send_buffer, $raw = false)
  289. {
  290. if ($this->_status === self::STATUS_CLOSING || $this->_status === self::STATUS_CLOSED) {
  291. return false;
  292. }
  293. // Try to call protocol::encode($send_buffer) before sending.
  294. if (false === $raw && $this->protocol !== null) {
  295. $send_buffer = $this->protocol::encode($send_buffer, $this);
  296. if ($send_buffer === '') {
  297. return;
  298. }
  299. }
  300. if ($this->_status !== self::STATUS_ESTABLISHED ||
  301. ($this->transport === 'ssl' && $this->_sslHandshakeCompleted !== true)
  302. ) {
  303. if ($this->_sendBuffer && $this->bufferIsFull()) {
  304. ++self::$statistics['send_fail'];
  305. return false;
  306. }
  307. $this->_sendBuffer .= $send_buffer;
  308. $this->checkBufferWillFull();
  309. return;
  310. }
  311. // Attempt to send data directly.
  312. if ($this->_sendBuffer === '') {
  313. if ($this->transport === 'ssl') {
  314. Worker::$globalEvent->onWritable($this->_socket, [$this, 'baseWrite']);
  315. $this->_sendBuffer = $send_buffer;
  316. $this->checkBufferWillFull();
  317. return;
  318. }
  319. $len = 0;
  320. try {
  321. $len = @\fwrite($this->_socket, $send_buffer);
  322. } catch (\Throwable $e) {
  323. Worker::log($e);
  324. }
  325. // send successful.
  326. if ($len === \strlen($send_buffer)) {
  327. $this->bytesWritten += $len;
  328. return true;
  329. }
  330. // Send only part of the data.
  331. if ($len > 0) {
  332. $this->_sendBuffer = \substr($send_buffer, $len);
  333. $this->bytesWritten += $len;
  334. } else {
  335. // Connection closed?
  336. if (!\is_resource($this->_socket) || \feof($this->_socket)) {
  337. ++self::$statistics['send_fail'];
  338. if ($this->onError) {
  339. try {
  340. ($this->onError)($this, static::SEND_FAIL, 'client closed');
  341. } catch (\Throwable $e) {
  342. Worker::stopAll(250, $e);
  343. }
  344. }
  345. $this->destroy();
  346. return false;
  347. }
  348. $this->_sendBuffer = $send_buffer;
  349. }
  350. Worker::$globalEvent->onWritable($this->_socket, [$this, 'baseWrite']);
  351. // Check if the send buffer will be full.
  352. $this->checkBufferWillFull();
  353. return;
  354. }
  355. if ($this->bufferIsFull()) {
  356. ++self::$statistics['send_fail'];
  357. return false;
  358. }
  359. $this->_sendBuffer .= $send_buffer;
  360. // Check if the send buffer is full.
  361. $this->checkBufferWillFull();
  362. }
  363. /**
  364. * Get remote IP.
  365. *
  366. * @return string
  367. */
  368. public function getRemoteIp()
  369. {
  370. $pos = \strrpos($this->_remoteAddress, ':');
  371. if ($pos) {
  372. return (string)\substr($this->_remoteAddress, 0, $pos);
  373. }
  374. return '';
  375. }
  376. /**
  377. * Get remote port.
  378. *
  379. * @return int
  380. */
  381. public function getRemotePort()
  382. {
  383. if ($this->_remoteAddress) {
  384. return (int)\substr(\strrchr($this->_remoteAddress, ':'), 1);
  385. }
  386. return 0;
  387. }
  388. /**
  389. * Get remote address.
  390. *
  391. * @return string
  392. */
  393. public function getRemoteAddress()
  394. {
  395. return $this->_remoteAddress;
  396. }
  397. /**
  398. * Get local IP.
  399. *
  400. * @return string
  401. */
  402. public function getLocalIp()
  403. {
  404. $address = $this->getLocalAddress();
  405. $pos = \strrpos($address, ':');
  406. if (!$pos) {
  407. return '';
  408. }
  409. return \substr($address, 0, $pos);
  410. }
  411. /**
  412. * Get local port.
  413. *
  414. * @return int
  415. */
  416. public function getLocalPort()
  417. {
  418. $address = $this->getLocalAddress();
  419. $pos = \strrpos($address, ':');
  420. if (!$pos) {
  421. return 0;
  422. }
  423. return (int)\substr(\strrchr($address, ':'), 1);
  424. }
  425. /**
  426. * Get local address.
  427. *
  428. * @return string
  429. */
  430. public function getLocalAddress()
  431. {
  432. if (!\is_resource($this->_socket)) {
  433. return '';
  434. }
  435. return (string)@\stream_socket_get_name($this->_socket, false);
  436. }
  437. /**
  438. * Get send buffer queue size.
  439. *
  440. * @return integer
  441. */
  442. public function getSendBufferQueueSize()
  443. {
  444. return \strlen($this->_sendBuffer);
  445. }
  446. /**
  447. * Get recv buffer queue size.
  448. *
  449. * @return integer
  450. */
  451. public function getRecvBufferQueueSize()
  452. {
  453. return \strlen($this->_recvBuffer);
  454. }
  455. /**
  456. * Is ipv4.
  457. *
  458. * return bool.
  459. */
  460. public function isIpV4()
  461. {
  462. if ($this->transport === 'unix') {
  463. return false;
  464. }
  465. return \strpos($this->getRemoteIp(), ':') === false;
  466. }
  467. /**
  468. * Is ipv6.
  469. *
  470. * return bool.
  471. */
  472. public function isIpV6()
  473. {
  474. if ($this->transport === 'unix') {
  475. return false;
  476. }
  477. return \strpos($this->getRemoteIp(), ':') !== false;
  478. }
  479. /**
  480. * Pauses the reading of data. That is onMessage will not be emitted. Useful to throttle back an upload.
  481. *
  482. * @return void
  483. */
  484. public function pauseRecv()
  485. {
  486. Worker::$globalEvent->offReadable($this->_socket);
  487. $this->_isPaused = true;
  488. }
  489. /**
  490. * Resumes reading after a call to pauseRecv.
  491. *
  492. * @return void
  493. */
  494. public function resumeRecv()
  495. {
  496. if ($this->_isPaused === true) {
  497. Worker::$globalEvent->onReadable($this->_socket, [$this, 'baseRead']);
  498. $this->_isPaused = false;
  499. $this->baseRead($this->_socket, false);
  500. }
  501. }
  502. /**
  503. * Base read handler.
  504. *
  505. * @param resource $socket
  506. * @param bool $check_eof
  507. * @return void
  508. */
  509. public function baseRead($socket, $check_eof = true)
  510. {
  511. static $requests = [];
  512. // SSL handshake.
  513. if ($this->transport === 'ssl' && $this->_sslHandshakeCompleted !== true) {
  514. if ($this->doSslHandshake($socket)) {
  515. $this->_sslHandshakeCompleted = true;
  516. if ($this->_sendBuffer) {
  517. Worker::$globalEvent->onWritable($socket, [$this, 'baseWrite']);
  518. }
  519. } else {
  520. return;
  521. }
  522. }
  523. $buffer = '';
  524. try {
  525. $buffer = @\fread($socket, self::READ_BUFFER_SIZE);
  526. } catch (\Throwable $e) {
  527. }
  528. // Check connection closed.
  529. if ($buffer === '' || $buffer === false) {
  530. if ($check_eof && (\feof($socket) || !\is_resource($socket) || $buffer === false)) {
  531. $this->destroy();
  532. return;
  533. }
  534. } else {
  535. $this->bytesRead += \strlen($buffer);
  536. if ($this->_recvBuffer === '') {
  537. if (static::$_enableCache && !isset($buffer[512]) && isset($requests[$buffer])) {
  538. ++self::$statistics['total_request'];
  539. $request = $requests[$buffer];
  540. if ($request instanceof Request) {
  541. $request = clone $request;
  542. $requests[$buffer] = $request;
  543. $request->connection = $this;
  544. $this->__request = $request;
  545. $request->properties = [];
  546. }
  547. try {
  548. ($this->onMessage)($this, $request);
  549. } catch (\Throwable $e) {
  550. Worker::stopAll(250, $e);
  551. }
  552. return;
  553. }
  554. $this->_recvBuffer = $buffer;
  555. } else {
  556. $this->_recvBuffer .= $buffer;
  557. }
  558. }
  559. // If the application layer protocol has been set up.
  560. if ($this->protocol !== null) {
  561. while ($this->_recvBuffer !== '' && !$this->_isPaused) {
  562. // The current packet length is known.
  563. if ($this->_currentPackageLength) {
  564. // Data is not enough for a package.
  565. if ($this->_currentPackageLength > \strlen($this->_recvBuffer)) {
  566. break;
  567. }
  568. } else {
  569. // Get current package length.
  570. try {
  571. $this->_currentPackageLength = $this->protocol::input($this->_recvBuffer, $this);
  572. } catch (\Throwable $e) {
  573. }
  574. // The packet length is unknown.
  575. if ($this->_currentPackageLength === 0) {
  576. break;
  577. } elseif ($this->_currentPackageLength > 0 && $this->_currentPackageLength <= $this->maxPackageSize) {
  578. // Data is not enough for a package.
  579. if ($this->_currentPackageLength > \strlen($this->_recvBuffer)) {
  580. break;
  581. }
  582. } // Wrong package.
  583. else {
  584. Worker::safeEcho('Error package. package_length=' . \var_export($this->_currentPackageLength, true));
  585. $this->destroy();
  586. return;
  587. }
  588. }
  589. // The data is enough for a packet.
  590. ++self::$statistics['total_request'];
  591. // The current packet length is equal to the length of the buffer.
  592. if ($one = \strlen($this->_recvBuffer) === $this->_currentPackageLength) {
  593. $one_request_buffer = $this->_recvBuffer;
  594. $this->_recvBuffer = '';
  595. } else {
  596. // Get a full package from the buffer.
  597. $one_request_buffer = \substr($this->_recvBuffer, 0, $this->_currentPackageLength);
  598. // Remove the current package from the receive buffer.
  599. $this->_recvBuffer = \substr($this->_recvBuffer, $this->_currentPackageLength);
  600. }
  601. // Reset the current packet length to 0.
  602. $this->_currentPackageLength = 0;
  603. try {
  604. // Decode request buffer before Emitting onMessage callback.
  605. $request = $this->protocol::decode($one_request_buffer, $this);
  606. if (static::$_enableCache && (!\is_object($request) || $request instanceof Request) && $one && !isset($one_request_buffer[512])) {
  607. $requests[$one_request_buffer] = $request;
  608. if (\count($requests) > 512) {
  609. unset($requests[\key($requests)]);
  610. }
  611. }
  612. ($this->onMessage)($this, $request);
  613. } catch (\Throwable $e) {
  614. Worker::stopAll(250, $e);
  615. }
  616. }
  617. return;
  618. }
  619. if ($this->_recvBuffer === '' || $this->_isPaused) {
  620. return;
  621. }
  622. // Applications protocol is not set.
  623. ++self::$statistics['total_request'];
  624. try {
  625. ($this->onMessage)($this, $this->_recvBuffer);
  626. } catch (\Throwable $e) {
  627. Worker::stopAll(250, $e);
  628. }
  629. // Clean receive buffer.
  630. $this->_recvBuffer = '';
  631. }
  632. /**
  633. * Base write handler.
  634. *
  635. * @return void|bool
  636. */
  637. public function baseWrite()
  638. {
  639. \set_error_handler(function () {
  640. });
  641. if ($this->transport === 'ssl') {
  642. $len = @\fwrite($this->_socket, $this->_sendBuffer, 8192);
  643. } else {
  644. $len = @\fwrite($this->_socket, $this->_sendBuffer);
  645. }
  646. \restore_error_handler();
  647. if ($len === \strlen($this->_sendBuffer)) {
  648. $this->bytesWritten += $len;
  649. Worker::$globalEvent->offWritable($this->_socket);
  650. $this->_sendBuffer = '';
  651. // Try to emit onBufferDrain callback when the send buffer becomes empty.
  652. if ($this->onBufferDrain) {
  653. try {
  654. ($this->onBufferDrain)($this);
  655. } catch (\Throwable $e) {
  656. Worker::stopAll(250, $e);
  657. }
  658. }
  659. if ($this->_status === self::STATUS_CLOSING) {
  660. if ($this->context->streamSending) {
  661. return true;
  662. }
  663. $this->destroy();
  664. }
  665. return true;
  666. }
  667. if ($len > 0) {
  668. $this->bytesWritten += $len;
  669. $this->_sendBuffer = \substr($this->_sendBuffer, $len);
  670. } else {
  671. ++self::$statistics['send_fail'];
  672. $this->destroy();
  673. }
  674. }
  675. /**
  676. * SSL handshake.
  677. *
  678. * @param resource $socket
  679. * @return bool
  680. */
  681. public function doSslHandshake($socket)
  682. {
  683. if (\feof($socket)) {
  684. $this->destroy();
  685. return false;
  686. }
  687. $async = $this instanceof AsyncTcpConnection;
  688. /**
  689. * We disabled ssl3 because https://blog.qualys.com/ssllabs/2014/10/15/ssl-3-is-dead-killed-by-the-poodle-attack.
  690. * You can enable ssl3 by the codes below.
  691. */
  692. /*if($async){
  693. $type = STREAM_CRYPTO_METHOD_SSLv2_CLIENT | STREAM_CRYPTO_METHOD_SSLv23_CLIENT | STREAM_CRYPTO_METHOD_SSLv3_CLIENT;
  694. }else{
  695. $type = STREAM_CRYPTO_METHOD_SSLv2_SERVER | STREAM_CRYPTO_METHOD_SSLv23_SERVER | STREAM_CRYPTO_METHOD_SSLv3_SERVER;
  696. }*/
  697. if ($async) {
  698. $type = \STREAM_CRYPTO_METHOD_SSLv2_CLIENT | \STREAM_CRYPTO_METHOD_SSLv23_CLIENT;
  699. } else {
  700. $type = \STREAM_CRYPTO_METHOD_SSLv2_SERVER | \STREAM_CRYPTO_METHOD_SSLv23_SERVER;
  701. }
  702. // Hidden error.
  703. \set_error_handler(function ($errno, $errstr, $file) {
  704. if (!Worker::$daemonize) {
  705. Worker::safeEcho("SSL handshake error: $errstr \n");
  706. }
  707. });
  708. $ret = \stream_socket_enable_crypto($socket, true, $type);
  709. \restore_error_handler();
  710. // Negotiation has failed.
  711. if (false === $ret) {
  712. $this->destroy();
  713. return false;
  714. } elseif (0 === $ret) {
  715. // There isn't enough data and should try again.
  716. return 0;
  717. }
  718. if (isset($this->onSslHandshake)) {
  719. try {
  720. ($this->onSslHandshake)($this);
  721. } catch (\Throwable $e) {
  722. Worker::stopAll(250, $e);
  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->close();
  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. ($this->onBufferFull)($this);
  805. } catch (\Throwable $e) {
  806. Worker::stopAll(250, $e);
  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. ($this->onError)($this, static::SEND_FAIL, 'send buffer full and drop package');
  823. } catch (\Throwable $e) {
  824. Worker::stopAll(250, $e);
  825. }
  826. }
  827. return true;
  828. }
  829. return false;
  830. }
  831. /**
  832. * Whether send buffer is Empty.
  833. *
  834. * @return bool
  835. */
  836. public function bufferIsEmpty()
  837. {
  838. return empty($this->_sendBuffer);
  839. }
  840. /**
  841. * Destroy connection.
  842. *
  843. * @return void
  844. */
  845. public function destroy()
  846. {
  847. // Avoid repeated calls.
  848. if ($this->_status === self::STATUS_CLOSED) {
  849. return;
  850. }
  851. // Remove event listener.
  852. Worker::$globalEvent->offReadable($this->_socket);
  853. Worker::$globalEvent->offWritable($this->_socket);
  854. // Close socket.
  855. try {
  856. @\fclose($this->_socket);
  857. } catch (\Throwable $e) {
  858. }
  859. $this->_status = self::STATUS_CLOSED;
  860. // Try to emit onClose callback.
  861. if ($this->onClose) {
  862. try {
  863. ($this->onClose)($this);
  864. } catch (\Throwable $e) {
  865. Worker::stopAll(250, $e);
  866. }
  867. }
  868. // Try to emit protocol::onClose
  869. if ($this->protocol && \method_exists($this->protocol, 'onClose')) {
  870. try {
  871. ([$this->protocol, 'onClose'])($this);
  872. } catch (\Throwable $e) {
  873. Worker::stopAll(250, $e);
  874. }
  875. }
  876. $this->_sendBuffer = $this->_recvBuffer = '';
  877. $this->_currentPackageLength = 0;
  878. $this->_isPaused = $this->_sslHandshakeCompleted = false;
  879. if ($this->_status === self::STATUS_CLOSED) {
  880. // Cleaning up the callback to avoid memory leaks.
  881. $this->onMessage = $this->onClose = $this->onError = $this->onBufferFull = $this->onBufferDrain = null;
  882. // Remove from worker->connections.
  883. if ($this->worker) {
  884. unset($this->worker->connections[$this->_id]);
  885. }
  886. unset(static::$connections[$this->_id]);
  887. }
  888. }
  889. /**
  890. * Enable or disable Cache.
  891. *
  892. * @param mixed $value
  893. */
  894. public static function enableCache($value)
  895. {
  896. static::$_enableCache = (bool)$value;
  897. }
  898. /**
  899. * Get the json_encode information.
  900. *
  901. * @return mixed
  902. */
  903. #[\ReturnTypeWillChange]
  904. public function jsonSerialize()
  905. {
  906. return [
  907. 'id' => $this->id,
  908. 'status' => $this->getStatus(),
  909. 'transport' => $this->transport,
  910. 'getRemoteIp' => $this->getRemoteIp(),
  911. 'remotePort' => $this->getRemotePort(),
  912. 'getRemoteAddress' => $this->getRemoteAddress(),
  913. 'getLocalIp' => $this->getLocalIp(),
  914. 'getLocalPort' => $this->getLocalPort(),
  915. 'getLocalAddress' => $this->getLocalAddress(),
  916. 'isIpV4' => $this->isIpV4(),
  917. 'isIpV6' => $this->isIpV6(),
  918. ];
  919. }
  920. /**
  921. * Destruct.
  922. *
  923. * @return void
  924. */
  925. public function __destruct()
  926. {
  927. static $mod;
  928. self::$statistics['connection_count']--;
  929. if (Worker::getGracefulStop()) {
  930. if (!isset($mod)) {
  931. $mod = \ceil((self::$statistics['connection_count'] + 1) / 3);
  932. }
  933. if (0 === self::$statistics['connection_count'] % $mod) {
  934. Worker::log('worker[' . \posix_getpid() . '] remains ' . self::$statistics['connection_count'] . ' connection(s)');
  935. }
  936. if (0 === self::$statistics['connection_count']) {
  937. Worker::stopAll();
  938. }
  939. }
  940. }
  941. }