TcpConnection.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719
  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);
  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. stream_set_blocking($socket, true);
  350. stream_set_timeout($socket, 1);
  351. $ret = stream_socket_enable_crypto($socket, true, STREAM_CRYPTO_METHOD_SSLv23_SERVER);
  352. if(!$ret) {
  353. echo new \Exception('ssl handshake fail, stream_socket_enable_crypto return ' . var_export($ret, true));
  354. return $this->destroy();
  355. }
  356. if (isset($this->onSslHandshake)) {
  357. try {
  358. call_user_func($this->onSslHandshake, $this);
  359. } catch (\Exception $e) {
  360. self::log($e);
  361. exit(250);
  362. } catch (\Error $e) {
  363. self::log($e);
  364. exit(250);
  365. }
  366. }
  367. $this->_sslHandshakeCompleted = true;
  368. if ($this->_sendBuffer) {
  369. Worker::$globalEvent->add($socket, EventInterface::EV_WRITE, array($this, 'baseWrite'));
  370. }
  371. return;
  372. }
  373. $buffer = fread($socket, self::READ_BUFFER_SIZE);
  374. // Check connection closed.
  375. if ($buffer === '' || $buffer === false) {
  376. if ($check_eof && (feof($socket) || !is_resource($socket) || $buffer === false)) {
  377. $this->destroy();
  378. return;
  379. }
  380. } else {
  381. $this->_recvBuffer .= $buffer;
  382. }
  383. // If the application layer protocol has been set up.
  384. if ($this->protocol) {
  385. $parser = $this->protocol;
  386. while ($this->_recvBuffer !== '' && !$this->_isPaused) {
  387. // The current packet length is known.
  388. if ($this->_currentPackageLength) {
  389. // Data is not enough for a package.
  390. if ($this->_currentPackageLength > strlen($this->_recvBuffer)) {
  391. break;
  392. }
  393. } else {
  394. // Get current package length.
  395. $this->_currentPackageLength = $parser::input($this->_recvBuffer, $this);
  396. // The packet length is unknown.
  397. if ($this->_currentPackageLength === 0) {
  398. break;
  399. } elseif ($this->_currentPackageLength > 0 && $this->_currentPackageLength <= self::$maxPackageSize) {
  400. // Data is not enough for a package.
  401. if ($this->_currentPackageLength > strlen($this->_recvBuffer)) {
  402. break;
  403. }
  404. } // Wrong package.
  405. else {
  406. echo 'error package. package_length=' . var_export($this->_currentPackageLength, true);
  407. $this->destroy();
  408. return;
  409. }
  410. }
  411. // The data is enough for a packet.
  412. self::$statistics['total_request']++;
  413. // The current packet length is equal to the length of the buffer.
  414. if (strlen($this->_recvBuffer) === $this->_currentPackageLength) {
  415. $one_request_buffer = $this->_recvBuffer;
  416. $this->_recvBuffer = '';
  417. } else {
  418. // Get a full package from the buffer.
  419. $one_request_buffer = substr($this->_recvBuffer, 0, $this->_currentPackageLength);
  420. // Remove the current package from the receive buffer.
  421. $this->_recvBuffer = substr($this->_recvBuffer, $this->_currentPackageLength);
  422. }
  423. // Reset the current packet length to 0.
  424. $this->_currentPackageLength = 0;
  425. if (!$this->onMessage) {
  426. continue;
  427. }
  428. try {
  429. // Decode request buffer before Emitting onMessage callback.
  430. call_user_func($this->onMessage, $this, $parser::decode($one_request_buffer, $this));
  431. } catch (\Exception $e) {
  432. Worker::log($e);
  433. exit(250);
  434. } catch (\Error $e) {
  435. Worker::log($e);
  436. exit(250);
  437. }
  438. }
  439. return;
  440. }
  441. if ($this->_recvBuffer === '' || $this->_isPaused) {
  442. return;
  443. }
  444. // Applications protocol is not set.
  445. self::$statistics['total_request']++;
  446. if (!$this->onMessage) {
  447. $this->_recvBuffer = '';
  448. return;
  449. }
  450. try {
  451. call_user_func($this->onMessage, $this, $this->_recvBuffer);
  452. } catch (\Exception $e) {
  453. Worker::log($e);
  454. exit(250);
  455. } catch (\Error $e) {
  456. Worker::log($e);
  457. exit(250);
  458. }
  459. // Clean receive buffer.
  460. $this->_recvBuffer = '';
  461. }
  462. /**
  463. * Base write handler.
  464. *
  465. * @return void|bool
  466. */
  467. public function baseWrite()
  468. {
  469. $len = @fwrite($this->_socket, $this->_sendBuffer);
  470. if ($len === strlen($this->_sendBuffer)) {
  471. Worker::$globalEvent->del($this->_socket, EventInterface::EV_WRITE);
  472. $this->_sendBuffer = '';
  473. // Try to emit onBufferDrain callback when the send buffer becomes empty.
  474. if ($this->onBufferDrain) {
  475. try {
  476. call_user_func($this->onBufferDrain, $this);
  477. } catch (\Exception $e) {
  478. Worker::log($e);
  479. exit(250);
  480. } catch (\Error $e) {
  481. Worker::log($e);
  482. exit(250);
  483. }
  484. }
  485. if ($this->_status === self::STATUS_CLOSING) {
  486. $this->destroy();
  487. }
  488. return true;
  489. }
  490. if ($len > 0) {
  491. $this->_sendBuffer = substr($this->_sendBuffer, $len);
  492. } else {
  493. self::$statistics['send_fail']++;
  494. $this->destroy();
  495. }
  496. }
  497. /**
  498. * This method pulls all the data out of a readable stream, and writes it to the supplied destination.
  499. *
  500. * @param TcpConnection $dest
  501. * @return void
  502. */
  503. public function pipe($dest)
  504. {
  505. $source = $this;
  506. $this->onMessage = function ($source, $data) use ($dest) {
  507. $dest->send($data);
  508. };
  509. $this->onClose = function ($source) use ($dest) {
  510. $dest->destroy();
  511. };
  512. $dest->onBufferFull = function ($dest) use ($source) {
  513. $source->pauseRecv();
  514. };
  515. $dest->onBufferDrain = function ($dest) use ($source) {
  516. $source->resumeRecv();
  517. };
  518. }
  519. /**
  520. * Remove $length of data from receive buffer.
  521. *
  522. * @param int $length
  523. * @return void
  524. */
  525. public function consumeRecvBuffer($length)
  526. {
  527. $this->_recvBuffer = substr($this->_recvBuffer, $length);
  528. }
  529. /**
  530. * Close connection.
  531. *
  532. * @param mixed $data
  533. * @param bool $raw
  534. * @return void
  535. */
  536. public function close($data = null, $raw = false)
  537. {
  538. if ($this->_status === self::STATUS_CLOSING || $this->_status === self::STATUS_CLOSED) {
  539. return;
  540. } else {
  541. if ($data !== null) {
  542. $this->send($data, $raw);
  543. }
  544. $this->_status = self::STATUS_CLOSING;
  545. }
  546. if ($this->_sendBuffer === '') {
  547. $this->destroy();
  548. }
  549. }
  550. /**
  551. * Get the real socket.
  552. *
  553. * @return resource
  554. */
  555. public function getSocket()
  556. {
  557. return $this->_socket;
  558. }
  559. /**
  560. * Check whether the send buffer will be full.
  561. *
  562. * @return void
  563. */
  564. protected function checkBufferWillFull()
  565. {
  566. if ($this->maxSendBufferSize <= strlen($this->_sendBuffer)) {
  567. if ($this->onBufferFull) {
  568. try {
  569. call_user_func($this->onBufferFull, $this);
  570. } catch (\Exception $e) {
  571. Worker::log($e);
  572. exit(250);
  573. } catch (\Error $e) {
  574. Worker::log($e);
  575. exit(250);
  576. }
  577. }
  578. }
  579. }
  580. /**
  581. * Whether send buffer is full.
  582. *
  583. * @return bool
  584. */
  585. protected function bufferIsFull()
  586. {
  587. // Buffer has been marked as full but still has data to send then the packet is discarded.
  588. if ($this->maxSendBufferSize <= strlen($this->_sendBuffer)) {
  589. if ($this->onError) {
  590. try {
  591. call_user_func($this->onError, $this, WORKERMAN_SEND_FAIL, 'send buffer full and drop package');
  592. } catch (\Exception $e) {
  593. Worker::log($e);
  594. exit(250);
  595. } catch (\Error $e) {
  596. Worker::log($e);
  597. exit(250);
  598. }
  599. }
  600. return true;
  601. }
  602. return false;
  603. }
  604. /**
  605. * Destroy connection.
  606. *
  607. * @return void
  608. */
  609. public function destroy()
  610. {
  611. // Avoid repeated calls.
  612. if ($this->_status === self::STATUS_CLOSED) {
  613. return;
  614. }
  615. // Remove event listener.
  616. Worker::$globalEvent->del($this->_socket, EventInterface::EV_READ);
  617. Worker::$globalEvent->del($this->_socket, EventInterface::EV_WRITE);
  618. // Close socket.
  619. @fclose($this->_socket);
  620. // Remove from worker->connections.
  621. if ($this->worker) {
  622. unset($this->worker->connections[$this->_id]);
  623. }
  624. $this->_status = self::STATUS_CLOSED;
  625. // Try to emit onClose callback.
  626. if ($this->onClose) {
  627. try {
  628. call_user_func($this->onClose, $this);
  629. } catch (\Exception $e) {
  630. Worker::log($e);
  631. exit(250);
  632. } catch (\Error $e) {
  633. Worker::log($e);
  634. exit(250);
  635. }
  636. }
  637. // Try to emit protocol::onClose
  638. if (method_exists($this->protocol, 'onClose')) {
  639. try {
  640. call_user_func(array($this->protocol, 'onClose'), $this);
  641. } catch (\Exception $e) {
  642. Worker::log($e);
  643. exit(250);
  644. } catch (\Error $e) {
  645. Worker::log($e);
  646. exit(250);
  647. }
  648. }
  649. if ($this->_status === self::STATUS_CLOSED) {
  650. // Cleaning up the callback to avoid memory leaks.
  651. $this->onMessage = $this->onClose = $this->onError = $this->onBufferFull = $this->onBufferDrain = null;
  652. }
  653. }
  654. /**
  655. * Destruct.
  656. *
  657. * @return void
  658. */
  659. public function __destruct()
  660. {
  661. self::$statistics['connection_count']--;
  662. }
  663. }