TcpConnection.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724
  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_ESTABLISH = 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. * Connection->id.
  110. *
  111. * @var int
  112. */
  113. public $id = 0;
  114. /**
  115. * A copy of $worker->id which used to clean up the connection in worker->connections
  116. *
  117. * @var int
  118. */
  119. protected $_id = 0;
  120. /**
  121. * Sets the maximum send buffer size for the current connection.
  122. * OnBufferFull callback will be emited When the send buffer is full.
  123. *
  124. * @var int
  125. */
  126. public $maxSendBufferSize = 1048576;
  127. /**
  128. * Default send buffer size.
  129. *
  130. * @var int
  131. */
  132. public static $defaultMaxSendBufferSize = 1048576;
  133. /**
  134. * Maximum acceptable packet size.
  135. *
  136. * @var int
  137. */
  138. public static $maxPackageSize = 10485760;
  139. /**
  140. * Id recorder.
  141. *
  142. * @var int
  143. */
  144. protected static $_idRecorder = 1;
  145. /**
  146. * Socket
  147. *
  148. * @var resource
  149. */
  150. protected $_socket = null;
  151. /**
  152. * Send buffer.
  153. *
  154. * @var string
  155. */
  156. protected $_sendBuffer = '';
  157. /**
  158. * Receive buffer.
  159. *
  160. * @var string
  161. */
  162. protected $_recvBuffer = '';
  163. /**
  164. * Current package length.
  165. *
  166. * @var int
  167. */
  168. protected $_currentPackageLength = 0;
  169. /**
  170. * Connection status.
  171. *
  172. * @var int
  173. */
  174. protected $_status = self::STATUS_ESTABLISH;
  175. /**
  176. * Remote address.
  177. *
  178. * @var string
  179. */
  180. protected $_remoteAddress = '';
  181. /**
  182. * Is paused.
  183. *
  184. * @var bool
  185. */
  186. protected $_isPaused = false;
  187. /**
  188. * SSL handshake completed or not
  189. *
  190. * @var bool
  191. */
  192. protected $_sslHandshakeCompleted = false;
  193. /**
  194. * Construct.
  195. *
  196. * @param resource $socket
  197. * @param string $remote_address
  198. */
  199. public function __construct($socket, $remote_address = '')
  200. {
  201. self::$statistics['connection_count']++;
  202. $this->id = $this->_id = self::$_idRecorder++;
  203. $this->_socket = $socket;
  204. stream_set_blocking($this->_socket, 0);
  205. // Compatible with hhvm
  206. if (function_exists('stream_set_read_buffer')) {
  207. stream_set_read_buffer($this->_socket, 0);
  208. }
  209. Worker::$globalEvent->add($this->_socket, EventInterface::EV_READ, array($this, 'baseRead'));
  210. $this->maxSendBufferSize = self::$defaultMaxSendBufferSize;
  211. $this->_remoteAddress = $remote_address;
  212. }
  213. /**
  214. * Sends data on the connection.
  215. *
  216. * @param string $send_buffer
  217. * @param bool $raw
  218. * @return void|bool|null
  219. */
  220. public function send($send_buffer, $raw = false)
  221. {
  222. if ($this->_status === self::STATUS_CLOSING || $this->_status === self::STATUS_CLOSED) {
  223. return false;
  224. }
  225. // Try to call protocol::encode($send_buffer) before sending.
  226. if (false === $raw && $this->protocol) {
  227. $parser = $this->protocol;
  228. $send_buffer = $parser::encode($send_buffer, $this);
  229. if ($send_buffer === '') {
  230. return null;
  231. }
  232. }
  233. if ($this->_status !== self::STATUS_ESTABLISH ||
  234. ($this->transport === 'ssl' && $this->_sslHandshakeCompleted !== true)
  235. ) {
  236. if ($this->_sendBuffer) {
  237. if ($this->bufferIsFull()) {
  238. self::$statistics['send_fail']++;
  239. return false;
  240. }
  241. }
  242. $this->_sendBuffer .= $send_buffer;
  243. $this->checkBufferWillFull();
  244. return null;
  245. }
  246. // Attempt to send data directly.
  247. if ($this->_sendBuffer === '') {
  248. $len = @fwrite($this->_socket, $send_buffer, 8192);
  249. // send successful.
  250. if ($len === strlen($send_buffer)) {
  251. return true;
  252. }
  253. // Send only part of the data.
  254. if ($len > 0) {
  255. $this->_sendBuffer = substr($send_buffer, $len);
  256. } else {
  257. // Connection closed?
  258. if (!is_resource($this->_socket) || feof($this->_socket)) {
  259. self::$statistics['send_fail']++;
  260. if ($this->onError) {
  261. try {
  262. call_user_func($this->onError, $this, WORKERMAN_SEND_FAIL, 'client closed');
  263. } catch (\Exception $e) {
  264. Worker::log($e);
  265. exit(250);
  266. } catch (\Error $e) {
  267. Worker::log($e);
  268. exit(250);
  269. }
  270. }
  271. $this->destroy();
  272. return false;
  273. }
  274. $this->_sendBuffer = $send_buffer;
  275. }
  276. Worker::$globalEvent->add($this->_socket, EventInterface::EV_WRITE, array($this, 'baseWrite'));
  277. // Check if the send buffer will be full.
  278. $this->checkBufferWillFull();
  279. return null;
  280. } else {
  281. if ($this->bufferIsFull()) {
  282. self::$statistics['send_fail']++;
  283. return false;
  284. }
  285. $this->_sendBuffer .= $send_buffer;
  286. // Check if the send buffer is full.
  287. $this->checkBufferWillFull();
  288. }
  289. }
  290. /**
  291. * Get remote IP.
  292. *
  293. * @return string
  294. */
  295. public function getRemoteIp()
  296. {
  297. $pos = strrpos($this->_remoteAddress, ':');
  298. if ($pos) {
  299. return trim(substr($this->_remoteAddress, 0, $pos), '[]');
  300. }
  301. return '';
  302. }
  303. /**
  304. * Get remote port.
  305. *
  306. * @return int
  307. */
  308. public function getRemotePort()
  309. {
  310. if ($this->_remoteAddress) {
  311. return (int)substr(strrchr($this->_remoteAddress, ':'), 1);
  312. }
  313. return 0;
  314. }
  315. /**
  316. * Pauses the reading of data. That is onMessage will not be emitted. Useful to throttle back an upload.
  317. *
  318. * @return void
  319. */
  320. public function pauseRecv()
  321. {
  322. Worker::$globalEvent->del($this->_socket, EventInterface::EV_READ);
  323. $this->_isPaused = true;
  324. }
  325. /**
  326. * Resumes reading after a call to pauseRecv.
  327. *
  328. * @return void
  329. */
  330. public function resumeRecv()
  331. {
  332. if ($this->_isPaused === true) {
  333. Worker::$globalEvent->add($this->_socket, EventInterface::EV_READ, array($this, 'baseRead'));
  334. $this->_isPaused = false;
  335. $this->baseRead($this->_socket, false);
  336. }
  337. }
  338. /**
  339. * Base read handler.
  340. *
  341. * @param resource $socket
  342. * @param bool $check_eof
  343. * @return void
  344. */
  345. public function baseRead($socket, $check_eof = true)
  346. {
  347. // SSL handshake.
  348. if ($this->transport === 'ssl' && $this->_sslHandshakeCompleted !== true) {
  349. $ret = stream_socket_enable_crypto($socket, true, STREAM_CRYPTO_METHOD_SSLv2_SERVER |
  350. STREAM_CRYPTO_METHOD_SSLv3_SERVER | STREAM_CRYPTO_METHOD_SSLv23_SERVER);
  351. // Negotiation has failed.
  352. if(false === $ret) {
  353. if (!feof($socket)) {
  354. echo "\nSSL Handshake fail. \nBuffer:".bin2hex(fread($socket, 8182))."\n";
  355. }
  356. return $this->destroy();
  357. } elseif(0 === $ret) {
  358. // There isn't enough data and should try again.
  359. return;
  360. }
  361. if (isset($this->onSslHandshake)) {
  362. try {
  363. call_user_func($this->onSslHandshake, $this);
  364. } catch (\Exception $e) {
  365. Worker::log($e);
  366. exit(250);
  367. } catch (\Error $e) {
  368. Worker::log($e);
  369. exit(250);
  370. }
  371. }
  372. $this->_sslHandshakeCompleted = true;
  373. if ($this->_sendBuffer) {
  374. Worker::$globalEvent->add($socket, EventInterface::EV_WRITE, array($this, 'baseWrite'));
  375. }
  376. return;
  377. }
  378. $buffer = fread($socket, self::READ_BUFFER_SIZE);
  379. // Check connection closed.
  380. if ($buffer === '' || $buffer === false) {
  381. if ($check_eof && (feof($socket) || !is_resource($socket) || $buffer === false)) {
  382. $this->destroy();
  383. return;
  384. }
  385. } else {
  386. $this->_recvBuffer .= $buffer;
  387. }
  388. // If the application layer protocol has been set up.
  389. if ($this->protocol) {
  390. $parser = $this->protocol;
  391. while ($this->_recvBuffer !== '' && !$this->_isPaused) {
  392. // The current packet length is known.
  393. if ($this->_currentPackageLength) {
  394. // Data is not enough for a package.
  395. if ($this->_currentPackageLength > strlen($this->_recvBuffer)) {
  396. break;
  397. }
  398. } else {
  399. // Get current package length.
  400. $this->_currentPackageLength = $parser::input($this->_recvBuffer, $this);
  401. // The packet length is unknown.
  402. if ($this->_currentPackageLength === 0) {
  403. break;
  404. } elseif ($this->_currentPackageLength > 0 && $this->_currentPackageLength <= self::$maxPackageSize) {
  405. // Data is not enough for a package.
  406. if ($this->_currentPackageLength > strlen($this->_recvBuffer)) {
  407. break;
  408. }
  409. } // Wrong package.
  410. else {
  411. echo 'error package. package_length=' . var_export($this->_currentPackageLength, true);
  412. $this->destroy();
  413. return;
  414. }
  415. }
  416. // The data is enough for a packet.
  417. self::$statistics['total_request']++;
  418. // The current packet length is equal to the length of the buffer.
  419. if (strlen($this->_recvBuffer) === $this->_currentPackageLength) {
  420. $one_request_buffer = $this->_recvBuffer;
  421. $this->_recvBuffer = '';
  422. } else {
  423. // Get a full package from the buffer.
  424. $one_request_buffer = substr($this->_recvBuffer, 0, $this->_currentPackageLength);
  425. // Remove the current package from the receive buffer.
  426. $this->_recvBuffer = substr($this->_recvBuffer, $this->_currentPackageLength);
  427. }
  428. // Reset the current packet length to 0.
  429. $this->_currentPackageLength = 0;
  430. if (!$this->onMessage) {
  431. continue;
  432. }
  433. try {
  434. // Decode request buffer before Emitting onMessage callback.
  435. call_user_func($this->onMessage, $this, $parser::decode($one_request_buffer, $this));
  436. } catch (\Exception $e) {
  437. Worker::log($e);
  438. exit(250);
  439. } catch (\Error $e) {
  440. Worker::log($e);
  441. exit(250);
  442. }
  443. }
  444. return;
  445. }
  446. if ($this->_recvBuffer === '' || $this->_isPaused) {
  447. return;
  448. }
  449. // Applications protocol is not set.
  450. self::$statistics['total_request']++;
  451. if (!$this->onMessage) {
  452. $this->_recvBuffer = '';
  453. return;
  454. }
  455. try {
  456. call_user_func($this->onMessage, $this, $this->_recvBuffer);
  457. } catch (\Exception $e) {
  458. Worker::log($e);
  459. exit(250);
  460. } catch (\Error $e) {
  461. Worker::log($e);
  462. exit(250);
  463. }
  464. // Clean receive buffer.
  465. $this->_recvBuffer = '';
  466. }
  467. /**
  468. * Base write handler.
  469. *
  470. * @return void|bool
  471. */
  472. public function baseWrite()
  473. {
  474. $len = @fwrite($this->_socket, $this->_sendBuffer, 8192);
  475. if ($len === strlen($this->_sendBuffer)) {
  476. Worker::$globalEvent->del($this->_socket, EventInterface::EV_WRITE);
  477. $this->_sendBuffer = '';
  478. // Try to emit onBufferDrain callback when the send buffer becomes empty.
  479. if ($this->onBufferDrain) {
  480. try {
  481. call_user_func($this->onBufferDrain, $this);
  482. } catch (\Exception $e) {
  483. Worker::log($e);
  484. exit(250);
  485. } catch (\Error $e) {
  486. Worker::log($e);
  487. exit(250);
  488. }
  489. }
  490. if ($this->_status === self::STATUS_CLOSING) {
  491. $this->destroy();
  492. }
  493. return true;
  494. }
  495. if ($len > 0) {
  496. $this->_sendBuffer = substr($this->_sendBuffer, $len);
  497. } else {
  498. self::$statistics['send_fail']++;
  499. $this->destroy();
  500. }
  501. }
  502. /**
  503. * This method pulls all the data out of a readable stream, and writes it to the supplied destination.
  504. *
  505. * @param TcpConnection $dest
  506. * @return void
  507. */
  508. public function pipe($dest)
  509. {
  510. $source = $this;
  511. $this->onMessage = function ($source, $data) use ($dest) {
  512. $dest->send($data);
  513. };
  514. $this->onClose = function ($source) use ($dest) {
  515. $dest->destroy();
  516. };
  517. $dest->onBufferFull = function ($dest) use ($source) {
  518. $source->pauseRecv();
  519. };
  520. $dest->onBufferDrain = function ($dest) use ($source) {
  521. $source->resumeRecv();
  522. };
  523. }
  524. /**
  525. * Remove $length of data from receive buffer.
  526. *
  527. * @param int $length
  528. * @return void
  529. */
  530. public function consumeRecvBuffer($length)
  531. {
  532. $this->_recvBuffer = substr($this->_recvBuffer, $length);
  533. }
  534. /**
  535. * Close connection.
  536. *
  537. * @param mixed $data
  538. * @param bool $raw
  539. * @return void
  540. */
  541. public function close($data = null, $raw = false)
  542. {
  543. if ($this->_status === self::STATUS_CLOSING || $this->_status === self::STATUS_CLOSED) {
  544. return;
  545. } else {
  546. if ($data !== null) {
  547. $this->send($data, $raw);
  548. }
  549. $this->_status = self::STATUS_CLOSING;
  550. }
  551. if ($this->_sendBuffer === '') {
  552. $this->destroy();
  553. }
  554. }
  555. /**
  556. * Get the real socket.
  557. *
  558. * @return resource
  559. */
  560. public function getSocket()
  561. {
  562. return $this->_socket;
  563. }
  564. /**
  565. * Check whether the send buffer will be full.
  566. *
  567. * @return void
  568. */
  569. protected function checkBufferWillFull()
  570. {
  571. if ($this->maxSendBufferSize <= strlen($this->_sendBuffer)) {
  572. if ($this->onBufferFull) {
  573. try {
  574. call_user_func($this->onBufferFull, $this);
  575. } catch (\Exception $e) {
  576. Worker::log($e);
  577. exit(250);
  578. } catch (\Error $e) {
  579. Worker::log($e);
  580. exit(250);
  581. }
  582. }
  583. }
  584. }
  585. /**
  586. * Whether send buffer is full.
  587. *
  588. * @return bool
  589. */
  590. protected function bufferIsFull()
  591. {
  592. // Buffer has been marked as full but still has data to send then the packet is discarded.
  593. if ($this->maxSendBufferSize <= strlen($this->_sendBuffer)) {
  594. if ($this->onError) {
  595. try {
  596. call_user_func($this->onError, $this, WORKERMAN_SEND_FAIL, 'send buffer full and drop package');
  597. } catch (\Exception $e) {
  598. Worker::log($e);
  599. exit(250);
  600. } catch (\Error $e) {
  601. Worker::log($e);
  602. exit(250);
  603. }
  604. }
  605. return true;
  606. }
  607. return false;
  608. }
  609. /**
  610. * Destroy connection.
  611. *
  612. * @return void
  613. */
  614. public function destroy()
  615. {
  616. // Avoid repeated calls.
  617. if ($this->_status === self::STATUS_CLOSED) {
  618. return;
  619. }
  620. // Remove event listener.
  621. Worker::$globalEvent->del($this->_socket, EventInterface::EV_READ);
  622. Worker::$globalEvent->del($this->_socket, EventInterface::EV_WRITE);
  623. // Close socket.
  624. @fclose($this->_socket);
  625. // Remove from worker->connections.
  626. if ($this->worker) {
  627. unset($this->worker->connections[$this->_id]);
  628. }
  629. $this->_status = self::STATUS_CLOSED;
  630. // Try to emit onClose callback.
  631. if ($this->onClose) {
  632. try {
  633. call_user_func($this->onClose, $this);
  634. } catch (\Exception $e) {
  635. Worker::log($e);
  636. exit(250);
  637. } catch (\Error $e) {
  638. Worker::log($e);
  639. exit(250);
  640. }
  641. }
  642. // Try to emit protocol::onClose
  643. if (method_exists($this->protocol, 'onClose')) {
  644. try {
  645. call_user_func(array($this->protocol, 'onClose'), $this);
  646. } catch (\Exception $e) {
  647. Worker::log($e);
  648. exit(250);
  649. } catch (\Error $e) {
  650. Worker::log($e);
  651. exit(250);
  652. }
  653. }
  654. if ($this->_status === self::STATUS_CLOSED) {
  655. // Cleaning up the callback to avoid memory leaks.
  656. $this->onMessage = $this->onClose = $this->onError = $this->onBufferFull = $this->onBufferDrain = null;
  657. }
  658. }
  659. /**
  660. * Destruct.
  661. *
  662. * @return void
  663. */
  664. public function __destruct()
  665. {
  666. self::$statistics['connection_count']--;
  667. }
  668. }