TcpConnection.php 16 KB

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