TcpConnection.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  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. stream_set_read_buffer($this->_socket, 0);
  194. Worker::$globalEvent->add($this->_socket, EventInterface::EV_READ, array($this, 'baseRead'));
  195. $this->maxSendBufferSize = self::$defaultMaxSendBufferSize;
  196. $this->_remoteAddress = $remote_address;
  197. }
  198. /**
  199. * Sends data on the connection.
  200. *
  201. * @param string $send_buffer
  202. * @param bool $raw
  203. * @return void|bool|null
  204. */
  205. public function send($send_buffer, $raw = false)
  206. {
  207. // Try to call protocol::encode($send_buffer) before sending.
  208. if (false === $raw && $this->protocol) {
  209. $parser = $this->protocol;
  210. $send_buffer = $parser::encode($send_buffer, $this);
  211. if ($send_buffer === '') {
  212. return null;
  213. }
  214. }
  215. if ($this->_status === self::STATUS_INITIAL || $this->_status === self::STATUS_CONNECTING) {
  216. $this->_sendBuffer .= $send_buffer;
  217. return null;
  218. } elseif ($this->_status === self::STATUS_CLOSING || $this->_status === self::STATUS_CLOSED) {
  219. return false;
  220. }
  221. // Attempt to send data directly.
  222. if ($this->_sendBuffer === '') {
  223. $len = @fwrite($this->_socket, $send_buffer);
  224. // send successful.
  225. if ($len === strlen($send_buffer)) {
  226. return true;
  227. }
  228. // Send only part of the data.
  229. if ($len > 0) {
  230. $this->_sendBuffer = substr($send_buffer, $len);
  231. } else {
  232. // Connection closed?
  233. if (!is_resource($this->_socket) || feof($this->_socket)) {
  234. self::$statistics['send_fail']++;
  235. if ($this->onError) {
  236. try {
  237. call_user_func($this->onError, $this, WORKERMAN_SEND_FAIL, 'client closed');
  238. } catch (\Exception $e) {
  239. Worker::log($e);
  240. exit(250);
  241. } catch (\Error $e) {
  242. Worker::log($e);
  243. exit(250);
  244. }
  245. }
  246. $this->destroy();
  247. return false;
  248. }
  249. $this->_sendBuffer = $send_buffer;
  250. }
  251. Worker::$globalEvent->add($this->_socket, EventInterface::EV_WRITE, array($this, 'baseWrite'));
  252. // Check if the send buffer is full.
  253. $this->checkBufferIsFull();
  254. return null;
  255. } else {
  256. // Buffer has been marked as full but still has data to send the packet is discarded.
  257. if ($this->maxSendBufferSize <= strlen($this->_sendBuffer)) {
  258. self::$statistics['send_fail']++;
  259. if ($this->onError) {
  260. try {
  261. call_user_func($this->onError, $this, WORKERMAN_SEND_FAIL, 'send buffer full and drop package');
  262. } catch (\Exception $e) {
  263. Worker::log($e);
  264. exit(250);
  265. } catch (\Error $e) {
  266. Worker::log($e);
  267. exit(250);
  268. }
  269. }
  270. return false;
  271. }
  272. $this->_sendBuffer .= $send_buffer;
  273. // Check if the send buffer is full.
  274. $this->checkBufferIsFull();
  275. }
  276. }
  277. /**
  278. * Get remote IP.
  279. *
  280. * @return string
  281. */
  282. public function getRemoteIp()
  283. {
  284. $pos = strrpos($this->_remoteAddress, ':');
  285. if ($pos) {
  286. return trim(substr($this->_remoteAddress, 0, $pos), '[]');
  287. }
  288. return '';
  289. }
  290. /**
  291. * Get remote port.
  292. *
  293. * @return int
  294. */
  295. public function getRemotePort()
  296. {
  297. if ($this->_remoteAddress) {
  298. return (int)substr(strrchr($this->_remoteAddress, ':'), 1);
  299. }
  300. return 0;
  301. }
  302. /**
  303. * Pauses the reading of data. That is onMessage will not be emitted. Useful to throttle back an upload.
  304. *
  305. * @return void
  306. */
  307. public function pauseRecv()
  308. {
  309. Worker::$globalEvent->del($this->_socket, EventInterface::EV_READ);
  310. $this->_isPaused = true;
  311. }
  312. /**
  313. * Resumes reading after a call to pauseRecv.
  314. *
  315. * @return void
  316. */
  317. public function resumeRecv()
  318. {
  319. if ($this->_isPaused === true) {
  320. Worker::$globalEvent->add($this->_socket, EventInterface::EV_READ, array($this, 'baseRead'));
  321. $this->_isPaused = false;
  322. $this->baseRead($this->_socket, false);
  323. }
  324. }
  325. /**
  326. * Base read handler.
  327. *
  328. * @param resource $socket
  329. * @param bool $check_eof
  330. * @return void
  331. */
  332. public function baseRead($socket, $check_eof = true)
  333. {
  334. $buffer = fread($socket, self::READ_BUFFER_SIZE);
  335. // Check connection closed.
  336. if ($buffer === '' || $buffer === false) {
  337. if ($check_eof && (feof($socket) || !is_resource($socket) || $buffer === false)) {
  338. $this->destroy();
  339. return;
  340. }
  341. } else {
  342. $this->_recvBuffer .= $buffer;
  343. }
  344. // If the application layer protocol has been set up.
  345. if ($this->protocol) {
  346. $parser = $this->protocol;
  347. while ($this->_recvBuffer !== '' && !$this->_isPaused) {
  348. // The current packet length is known.
  349. if ($this->_currentPackageLength) {
  350. // Data is not enough for a package.
  351. if ($this->_currentPackageLength > strlen($this->_recvBuffer)) {
  352. break;
  353. }
  354. } else {
  355. // Get current package length.
  356. $this->_currentPackageLength = $parser::input($this->_recvBuffer, $this);
  357. // The packet length is unknown.
  358. if ($this->_currentPackageLength === 0) {
  359. break;
  360. } elseif ($this->_currentPackageLength > 0 && $this->_currentPackageLength <= self::$maxPackageSize) {
  361. // Data is not enough for a package.
  362. if ($this->_currentPackageLength > strlen($this->_recvBuffer)) {
  363. break;
  364. }
  365. } // Wrong package.
  366. else {
  367. echo 'error package. package_length=' . var_export($this->_currentPackageLength, true);
  368. $this->destroy();
  369. return;
  370. }
  371. }
  372. // The data is enough for a packet.
  373. self::$statistics['total_request']++;
  374. // The current packet length is equal to the length of the buffer.
  375. if (strlen($this->_recvBuffer) === $this->_currentPackageLength) {
  376. $one_request_buffer = $this->_recvBuffer;
  377. $this->_recvBuffer = '';
  378. } else {
  379. // Get a full package from the buffer.
  380. $one_request_buffer = substr($this->_recvBuffer, 0, $this->_currentPackageLength);
  381. // Remove the current package from the receive buffer.
  382. $this->_recvBuffer = substr($this->_recvBuffer, $this->_currentPackageLength);
  383. }
  384. // Reset the current packet length to 0.
  385. $this->_currentPackageLength = 0;
  386. if (!$this->onMessage) {
  387. continue;
  388. }
  389. try {
  390. // Decode request buffer before Emitting onMessage callback.
  391. call_user_func($this->onMessage, $this, $parser::decode($one_request_buffer, $this));
  392. } catch (\Exception $e) {
  393. Worker::log($e);
  394. exit(250);
  395. } catch (\Error $e) {
  396. Worker::log($e);
  397. exit(250);
  398. }
  399. }
  400. return;
  401. }
  402. if ($this->_recvBuffer === '' || $this->_isPaused) {
  403. return;
  404. }
  405. // Applications protocol is not set.
  406. self::$statistics['total_request']++;
  407. if (!$this->onMessage) {
  408. $this->_recvBuffer = '';
  409. return;
  410. }
  411. try {
  412. call_user_func($this->onMessage, $this, $this->_recvBuffer);
  413. } catch (\Exception $e) {
  414. Worker::log($e);
  415. exit(250);
  416. } catch (\Error $e) {
  417. Worker::log($e);
  418. exit(250);
  419. }
  420. // Clean receive buffer.
  421. $this->_recvBuffer = '';
  422. }
  423. /**
  424. * Base write handler.
  425. *
  426. * @return void|bool
  427. */
  428. public function baseWrite()
  429. {
  430. $len = @fwrite($this->_socket, $this->_sendBuffer);
  431. if ($len === strlen($this->_sendBuffer)) {
  432. Worker::$globalEvent->del($this->_socket, EventInterface::EV_WRITE);
  433. $this->_sendBuffer = '';
  434. // Try to emit onBufferDrain callback when the send buffer becomes empty.
  435. if ($this->onBufferDrain) {
  436. try {
  437. call_user_func($this->onBufferDrain, $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. if ($this->_status === self::STATUS_CLOSING) {
  447. $this->destroy();
  448. }
  449. return true;
  450. }
  451. if ($len > 0) {
  452. $this->_sendBuffer = substr($this->_sendBuffer, $len);
  453. } else {
  454. self::$statistics['send_fail']++;
  455. $this->destroy();
  456. }
  457. }
  458. /**
  459. * This method pulls all the data out of a readable stream, and writes it to the supplied destination.
  460. *
  461. * @param TcpConnection $dest
  462. * @return void
  463. */
  464. public function pipe($dest)
  465. {
  466. $source = $this;
  467. $this->onMessage = function ($source, $data) use ($dest) {
  468. $dest->send($data);
  469. };
  470. $this->onClose = function ($source) use ($dest) {
  471. $dest->destroy();
  472. };
  473. $dest->onBufferFull = function ($dest) use ($source) {
  474. $source->pauseRecv();
  475. };
  476. $dest->onBufferDrain = function ($dest) use ($source) {
  477. $source->resumeRecv();
  478. };
  479. }
  480. /**
  481. * Remove $length of data from receive buffer.
  482. *
  483. * @param int $length
  484. * @return void
  485. */
  486. public function consumeRecvBuffer($length)
  487. {
  488. $this->_recvBuffer = substr($this->_recvBuffer, $length);
  489. }
  490. /**
  491. * Close connection.
  492. *
  493. * @param mixed $data
  494. * @param bool $raw
  495. * @return void
  496. */
  497. public function close($data = null, $raw = false)
  498. {
  499. if ($this->_status === self::STATUS_CLOSING || $this->_status === self::STATUS_CLOSED) {
  500. return;
  501. } else {
  502. if ($data !== null) {
  503. $this->send($data, $raw);
  504. }
  505. $this->_status = self::STATUS_CLOSING;
  506. }
  507. if ($this->_sendBuffer === '') {
  508. $this->destroy();
  509. }
  510. }
  511. /**
  512. * Get the real socket.
  513. *
  514. * @return resource
  515. */
  516. public function getSocket()
  517. {
  518. return $this->_socket;
  519. }
  520. /**
  521. * Check whether the send buffer is full.
  522. *
  523. * @return void
  524. */
  525. protected function checkBufferIsFull()
  526. {
  527. if ($this->maxSendBufferSize <= strlen($this->_sendBuffer)) {
  528. if ($this->onBufferFull) {
  529. try {
  530. call_user_func($this->onBufferFull, $this);
  531. } catch (\Exception $e) {
  532. Worker::log($e);
  533. exit(250);
  534. } catch (\Error $e) {
  535. Worker::log($e);
  536. exit(250);
  537. }
  538. }
  539. }
  540. }
  541. /**
  542. * Destroy connection.
  543. *
  544. * @return void
  545. */
  546. public function destroy()
  547. {
  548. // Avoid repeated calls.
  549. if ($this->_status === self::STATUS_CLOSED) {
  550. return;
  551. }
  552. // Remove event listener.
  553. Worker::$globalEvent->del($this->_socket, EventInterface::EV_READ);
  554. Worker::$globalEvent->del($this->_socket, EventInterface::EV_WRITE);
  555. // Close socket.
  556. @fclose($this->_socket);
  557. // Remove from worker->connections.
  558. if ($this->worker) {
  559. unset($this->worker->connections[$this->_id]);
  560. }
  561. $this->_status = self::STATUS_CLOSED;
  562. // Try to emit onClose callback.
  563. if ($this->onClose) {
  564. try {
  565. call_user_func($this->onClose, $this);
  566. } catch (\Exception $e) {
  567. Worker::log($e);
  568. exit(250);
  569. } catch (\Error $e) {
  570. Worker::log($e);
  571. exit(250);
  572. }
  573. }
  574. if ($this->_status === self::STATUS_CLOSED) {
  575. // Cleaning up the callback to avoid memory leaks.
  576. $this->onMessage = $this->onClose = $this->onError = $this->onBufferFull = $this->onBufferDrain = null;
  577. }
  578. }
  579. /**
  580. * Destruct.
  581. *
  582. * @return void
  583. */
  584. public function __destruct()
  585. {
  586. self::$statistics['connection_count']--;
  587. }
  588. }