TcpConnection.php 18 KB

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