TcpConnection.php 20 KB

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