TcpConnection.php 18 KB

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