TcpConnection.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  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. * Transport (tcp/udp/unix/ssl).
  98. *
  99. * @var string
  100. */
  101. public $transport = 'tcp';
  102. /**
  103. * Which worker belong to.
  104. *
  105. * @var Worker
  106. */
  107. public $worker = null;
  108. /**
  109. * Connection->id.
  110. *
  111. * @var int
  112. */
  113. public $id = 0;
  114. /**
  115. * A copy of $worker->id which used to clean up the connection in worker->connections
  116. *
  117. * @var int
  118. */
  119. protected $_id = 0;
  120. /**
  121. * Sets the maximum send buffer size for the current connection.
  122. * OnBufferFull callback will be emited When the send buffer is full.
  123. *
  124. * @var int
  125. */
  126. public $maxSendBufferSize = 1048576;
  127. /**
  128. * Default send buffer size.
  129. *
  130. * @var int
  131. */
  132. public static $defaultMaxSendBufferSize = 1048576;
  133. /**
  134. * Maximum acceptable packet size.
  135. *
  136. * @var int
  137. */
  138. public static $maxPackageSize = 10485760;
  139. /**
  140. * Id recorder.
  141. *
  142. * @var int
  143. */
  144. protected static $_idRecorder = 1;
  145. /**
  146. * Socket
  147. *
  148. * @var resource
  149. */
  150. protected $_socket = null;
  151. /**
  152. * Send buffer.
  153. *
  154. * @var string
  155. */
  156. protected $_sendBuffer = '';
  157. /**
  158. * Receive buffer.
  159. *
  160. * @var string
  161. */
  162. protected $_recvBuffer = '';
  163. /**
  164. * Current package length.
  165. *
  166. * @var int
  167. */
  168. protected $_currentPackageLength = 0;
  169. /**
  170. * Connection status.
  171. *
  172. * @var int
  173. */
  174. protected $_status = self::STATUS_ESTABLISH;
  175. /**
  176. * Remote address.
  177. *
  178. * @var string
  179. */
  180. protected $_remoteAddress = '';
  181. /**
  182. * Is paused.
  183. *
  184. * @var bool
  185. */
  186. protected $_isPaused = false;
  187. /**
  188. * SSL handshake completed or not
  189. *
  190. * @var bool
  191. */
  192. protected $_sslHandshakeCompleted = false;
  193. /**
  194. * Construct.
  195. *
  196. * @param resource $socket
  197. * @param string $remote_address
  198. */
  199. public function __construct($socket, $remote_address = '')
  200. {
  201. self::$statistics['connection_count']++;
  202. $this->id = $this->_id = self::$_idRecorder++;
  203. $this->_socket = $socket;
  204. stream_set_blocking($this->_socket, 0);
  205. // Compatible with hhvm
  206. if (function_exists('stream_set_read_buffer')) {
  207. stream_set_read_buffer($this->_socket, 0);
  208. }
  209. Worker::$globalEvent->add($this->_socket, EventInterface::EV_READ, array($this, 'baseRead'));
  210. $this->maxSendBufferSize = self::$defaultMaxSendBufferSize;
  211. $this->_remoteAddress = $remote_address;
  212. }
  213. /**
  214. * Sends data on the connection.
  215. *
  216. * @param string $send_buffer
  217. * @param bool $raw
  218. * @return void|bool|null
  219. */
  220. public function send($send_buffer, $raw = false)
  221. {
  222. if ($this->_status === self::STATUS_CLOSING || $this->_status === self::STATUS_CLOSED) {
  223. return false;
  224. }
  225. // Try to call protocol::encode($send_buffer) before sending.
  226. if (false === $raw && $this->protocol) {
  227. $parser = $this->protocol;
  228. $send_buffer = $parser::encode($send_buffer, $this);
  229. if ($send_buffer === '') {
  230. return null;
  231. }
  232. }
  233. if ($this->_status !== self::STATUS_ESTABLISH ||
  234. ($this->transport === 'ssl' && $this->_sslHandshakeCompleted !== true)
  235. ) {
  236. if ($this->_sendBuffer) {
  237. if ($this->bufferIsFull()) {
  238. self::$statistics['send_fail']++;
  239. return false;
  240. }
  241. }
  242. $this->_sendBuffer .= $send_buffer;
  243. $this->checkBufferWillFull();
  244. return null;
  245. }
  246. // Attempt to send data directly.
  247. if ($this->_sendBuffer === '') {
  248. $len = @fwrite($this->_socket, $send_buffer);
  249. // send successful.
  250. if ($len === strlen($send_buffer)) {
  251. return true;
  252. }
  253. // Send only part of the data.
  254. if ($len > 0) {
  255. $this->_sendBuffer = substr($send_buffer, $len);
  256. } else {
  257. // Connection closed?
  258. if (!is_resource($this->_socket) || feof($this->_socket)) {
  259. self::$statistics['send_fail']++;
  260. if ($this->onError) {
  261. try {
  262. call_user_func($this->onError, $this, WORKERMAN_SEND_FAIL, 'client closed');
  263. } catch (\Exception $e) {
  264. Worker::log($e);
  265. exit(250);
  266. } catch (\Error $e) {
  267. Worker::log($e);
  268. exit(250);
  269. }
  270. }
  271. $this->destroy();
  272. return false;
  273. }
  274. $this->_sendBuffer = $send_buffer;
  275. }
  276. Worker::$globalEvent->add($this->_socket, EventInterface::EV_WRITE, array($this, 'baseWrite'));
  277. // Check if the send buffer will be full.
  278. $this->checkBufferWillFull();
  279. return null;
  280. } else {
  281. if ($this->bufferIsFull()) {
  282. self::$statistics['send_fail']++;
  283. return false;
  284. }
  285. $this->_sendBuffer .= $send_buffer;
  286. // Check if the send buffer is full.
  287. $this->checkBufferWillFull();
  288. }
  289. }
  290. /**
  291. * Get remote IP.
  292. *
  293. * @return string
  294. */
  295. public function getRemoteIp()
  296. {
  297. $pos = strrpos($this->_remoteAddress, ':');
  298. if ($pos) {
  299. return trim(substr($this->_remoteAddress, 0, $pos), '[]');
  300. }
  301. return '';
  302. }
  303. /**
  304. * Get remote port.
  305. *
  306. * @return int
  307. */
  308. public function getRemotePort()
  309. {
  310. if ($this->_remoteAddress) {
  311. return (int)substr(strrchr($this->_remoteAddress, ':'), 1);
  312. }
  313. return 0;
  314. }
  315. /**
  316. * Pauses the reading of data. That is onMessage will not be emitted. Useful to throttle back an upload.
  317. *
  318. * @return void
  319. */
  320. public function pauseRecv()
  321. {
  322. Worker::$globalEvent->del($this->_socket, EventInterface::EV_READ);
  323. $this->_isPaused = true;
  324. }
  325. /**
  326. * Resumes reading after a call to pauseRecv.
  327. *
  328. * @return void
  329. */
  330. public function resumeRecv()
  331. {
  332. if ($this->_isPaused === true) {
  333. Worker::$globalEvent->add($this->_socket, EventInterface::EV_READ, array($this, 'baseRead'));
  334. $this->_isPaused = false;
  335. $this->baseRead($this->_socket, false);
  336. }
  337. }
  338. /**
  339. * Base read handler.
  340. *
  341. * @param resource $socket
  342. * @param bool $check_eof
  343. * @return void
  344. */
  345. public function baseRead($socket, $check_eof = true)
  346. {
  347. // SSL handshake.
  348. if ($this->transport === 'ssl' && $this->_sslHandshakeCompleted !== true) {
  349. $ret = stream_socket_enable_crypto($socket, true, STREAM_CRYPTO_METHOD_SSLv2_SERVER |
  350. STREAM_CRYPTO_METHOD_SSLv3_SERVER | STREAM_CRYPTO_METHOD_SSLv23_SERVER);
  351. // Negotiation has failed.
  352. if(false === $ret) {
  353. echo "\nSSL Handshake fail. \nBuffer:".bin2hex(fread($socket, 8182))."\n";
  354. return $this->destroy();
  355. } elseif(0 === $ret) {
  356. // There isn't enough data and should try again.
  357. return;
  358. }
  359. if (isset($this->onSslHandshake)) {
  360. try {
  361. call_user_func($this->onSslHandshake, $this);
  362. } catch (\Exception $e) {
  363. self::log($e);
  364. exit(250);
  365. } catch (\Error $e) {
  366. self::log($e);
  367. exit(250);
  368. }
  369. }
  370. $this->_sslHandshakeCompleted = true;
  371. if ($this->_sendBuffer) {
  372. Worker::$globalEvent->add($socket, EventInterface::EV_WRITE, array($this, 'baseWrite'));
  373. }
  374. return;
  375. }
  376. $buffer = fread($socket, self::READ_BUFFER_SIZE);
  377. // Check connection closed.
  378. if ($buffer === '' || $buffer === false) {
  379. if ($check_eof && (feof($socket) || !is_resource($socket) || $buffer === false)) {
  380. $this->destroy();
  381. return;
  382. }
  383. } else {
  384. $this->_recvBuffer .= $buffer;
  385. }
  386. // If the application layer protocol has been set up.
  387. if ($this->protocol) {
  388. $parser = $this->protocol;
  389. while ($this->_recvBuffer !== '' && !$this->_isPaused) {
  390. // The current packet length is known.
  391. if ($this->_currentPackageLength) {
  392. // Data is not enough for a package.
  393. if ($this->_currentPackageLength > strlen($this->_recvBuffer)) {
  394. break;
  395. }
  396. } else {
  397. // Get current package length.
  398. $this->_currentPackageLength = $parser::input($this->_recvBuffer, $this);
  399. // The packet length is unknown.
  400. if ($this->_currentPackageLength === 0) {
  401. break;
  402. } elseif ($this->_currentPackageLength > 0 && $this->_currentPackageLength <= self::$maxPackageSize) {
  403. // Data is not enough for a package.
  404. if ($this->_currentPackageLength > strlen($this->_recvBuffer)) {
  405. break;
  406. }
  407. } // Wrong package.
  408. else {
  409. echo 'error package. package_length=' . var_export($this->_currentPackageLength, true);
  410. $this->destroy();
  411. return;
  412. }
  413. }
  414. // The data is enough for a packet.
  415. self::$statistics['total_request']++;
  416. // The current packet length is equal to the length of the buffer.
  417. if (strlen($this->_recvBuffer) === $this->_currentPackageLength) {
  418. $one_request_buffer = $this->_recvBuffer;
  419. $this->_recvBuffer = '';
  420. } else {
  421. // Get a full package from the buffer.
  422. $one_request_buffer = substr($this->_recvBuffer, 0, $this->_currentPackageLength);
  423. // Remove the current package from the receive buffer.
  424. $this->_recvBuffer = substr($this->_recvBuffer, $this->_currentPackageLength);
  425. }
  426. // Reset the current packet length to 0.
  427. $this->_currentPackageLength = 0;
  428. if (!$this->onMessage) {
  429. continue;
  430. }
  431. try {
  432. // Decode request buffer before Emitting onMessage callback.
  433. call_user_func($this->onMessage, $this, $parser::decode($one_request_buffer, $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. return;
  443. }
  444. if ($this->_recvBuffer === '' || $this->_isPaused) {
  445. return;
  446. }
  447. // Applications protocol is not set.
  448. self::$statistics['total_request']++;
  449. if (!$this->onMessage) {
  450. $this->_recvBuffer = '';
  451. return;
  452. }
  453. try {
  454. call_user_func($this->onMessage, $this, $this->_recvBuffer);
  455. } catch (\Exception $e) {
  456. Worker::log($e);
  457. exit(250);
  458. } catch (\Error $e) {
  459. Worker::log($e);
  460. exit(250);
  461. }
  462. // Clean receive buffer.
  463. $this->_recvBuffer = '';
  464. }
  465. /**
  466. * Base write handler.
  467. *
  468. * @return void|bool
  469. */
  470. public function baseWrite()
  471. {
  472. $len = @fwrite($this->_socket, $this->_sendBuffer);
  473. if ($len === strlen($this->_sendBuffer)) {
  474. Worker::$globalEvent->del($this->_socket, EventInterface::EV_WRITE);
  475. $this->_sendBuffer = '';
  476. // Try to emit onBufferDrain callback when the send buffer becomes empty.
  477. if ($this->onBufferDrain) {
  478. try {
  479. call_user_func($this->onBufferDrain, $this);
  480. } catch (\Exception $e) {
  481. Worker::log($e);
  482. exit(250);
  483. } catch (\Error $e) {
  484. Worker::log($e);
  485. exit(250);
  486. }
  487. }
  488. if ($this->_status === self::STATUS_CLOSING) {
  489. $this->destroy();
  490. }
  491. return true;
  492. }
  493. if ($len > 0) {
  494. $this->_sendBuffer = substr($this->_sendBuffer, $len);
  495. } else {
  496. self::$statistics['send_fail']++;
  497. $this->destroy();
  498. }
  499. }
  500. /**
  501. * This method pulls all the data out of a readable stream, and writes it to the supplied destination.
  502. *
  503. * @param TcpConnection $dest
  504. * @return void
  505. */
  506. public function pipe($dest)
  507. {
  508. $source = $this;
  509. $this->onMessage = function ($source, $data) use ($dest) {
  510. $dest->send($data);
  511. };
  512. $this->onClose = function ($source) use ($dest) {
  513. $dest->destroy();
  514. };
  515. $dest->onBufferFull = function ($dest) use ($source) {
  516. $source->pauseRecv();
  517. };
  518. $dest->onBufferDrain = function ($dest) use ($source) {
  519. $source->resumeRecv();
  520. };
  521. }
  522. /**
  523. * Remove $length of data from receive buffer.
  524. *
  525. * @param int $length
  526. * @return void
  527. */
  528. public function consumeRecvBuffer($length)
  529. {
  530. $this->_recvBuffer = substr($this->_recvBuffer, $length);
  531. }
  532. /**
  533. * Close connection.
  534. *
  535. * @param mixed $data
  536. * @param bool $raw
  537. * @return void
  538. */
  539. public function close($data = null, $raw = false)
  540. {
  541. if ($this->_status === self::STATUS_CLOSING || $this->_status === self::STATUS_CLOSED) {
  542. return;
  543. } else {
  544. if ($data !== null) {
  545. $this->send($data, $raw);
  546. }
  547. $this->_status = self::STATUS_CLOSING;
  548. }
  549. if ($this->_sendBuffer === '') {
  550. $this->destroy();
  551. }
  552. }
  553. /**
  554. * Get the real socket.
  555. *
  556. * @return resource
  557. */
  558. public function getSocket()
  559. {
  560. return $this->_socket;
  561. }
  562. /**
  563. * Check whether the send buffer will be full.
  564. *
  565. * @return void
  566. */
  567. protected function checkBufferWillFull()
  568. {
  569. if ($this->maxSendBufferSize <= strlen($this->_sendBuffer)) {
  570. if ($this->onBufferFull) {
  571. try {
  572. call_user_func($this->onBufferFull, $this);
  573. } catch (\Exception $e) {
  574. Worker::log($e);
  575. exit(250);
  576. } catch (\Error $e) {
  577. Worker::log($e);
  578. exit(250);
  579. }
  580. }
  581. }
  582. }
  583. /**
  584. * Whether send buffer is full.
  585. *
  586. * @return bool
  587. */
  588. protected function bufferIsFull()
  589. {
  590. // Buffer has been marked as full but still has data to send then the packet is discarded.
  591. if ($this->maxSendBufferSize <= strlen($this->_sendBuffer)) {
  592. if ($this->onError) {
  593. try {
  594. call_user_func($this->onError, $this, WORKERMAN_SEND_FAIL, 'send buffer full and drop package');
  595. } catch (\Exception $e) {
  596. Worker::log($e);
  597. exit(250);
  598. } catch (\Error $e) {
  599. Worker::log($e);
  600. exit(250);
  601. }
  602. }
  603. return true;
  604. }
  605. return false;
  606. }
  607. /**
  608. * Destroy connection.
  609. *
  610. * @return void
  611. */
  612. public function destroy()
  613. {
  614. // Avoid repeated calls.
  615. if ($this->_status === self::STATUS_CLOSED) {
  616. return;
  617. }
  618. // Remove event listener.
  619. Worker::$globalEvent->del($this->_socket, EventInterface::EV_READ);
  620. Worker::$globalEvent->del($this->_socket, EventInterface::EV_WRITE);
  621. // Close socket.
  622. @fclose($this->_socket);
  623. // Remove from worker->connections.
  624. if ($this->worker) {
  625. unset($this->worker->connections[$this->_id]);
  626. }
  627. $this->_status = self::STATUS_CLOSED;
  628. // Try to emit onClose callback.
  629. if ($this->onClose) {
  630. try {
  631. call_user_func($this->onClose, $this);
  632. } catch (\Exception $e) {
  633. Worker::log($e);
  634. exit(250);
  635. } catch (\Error $e) {
  636. Worker::log($e);
  637. exit(250);
  638. }
  639. }
  640. // Try to emit protocol::onClose
  641. if (method_exists($this->protocol, 'onClose')) {
  642. try {
  643. call_user_func(array($this->protocol, 'onClose'), $this);
  644. } catch (\Exception $e) {
  645. Worker::log($e);
  646. exit(250);
  647. } catch (\Error $e) {
  648. Worker::log($e);
  649. exit(250);
  650. }
  651. }
  652. if ($this->_status === self::STATUS_CLOSED) {
  653. // Cleaning up the callback to avoid memory leaks.
  654. $this->onMessage = $this->onClose = $this->onError = $this->onBufferFull = $this->onBufferDrain = null;
  655. }
  656. }
  657. /**
  658. * Destruct.
  659. *
  660. * @return void
  661. */
  662. public function __destruct()
  663. {
  664. self::$statistics['connection_count']--;
  665. }
  666. }