TcpConnection.php 17 KB

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