TcpConnection.php 17 KB

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