TcpConnection.php 17 KB

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