AsyncTcpConnection.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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\Timer;
  17. use Workerman\Worker;
  18. use \Exception;
  19. /**
  20. * AsyncTcpConnection.
  21. */
  22. class AsyncTcpConnection extends TcpConnection
  23. {
  24. /**
  25. * Emitted when socket connection is successfully established.
  26. *
  27. * @var callable|null
  28. */
  29. public $onConnect = null;
  30. /**
  31. * Transport layer protocol.
  32. *
  33. * @var string
  34. */
  35. public $transport = 'tcp';
  36. /**
  37. * Socks5 proxy
  38. *
  39. * @var string
  40. */
  41. public $proxySocks5 = '';
  42. /**
  43. * Http proxy
  44. *
  45. * @var string
  46. */
  47. public $proxyHttp = '';
  48. /**
  49. * Status.
  50. *
  51. * @var int
  52. */
  53. protected $_status = self::STATUS_INITIAL;
  54. /**
  55. * Remote host.
  56. *
  57. * @var string
  58. */
  59. protected $_remoteHost = '';
  60. /**
  61. * Remote port.
  62. *
  63. * @var int
  64. */
  65. protected $_remotePort = 80;
  66. /**
  67. * Connect start time.
  68. *
  69. * @var float
  70. */
  71. protected $_connectStartTime = 0;
  72. /**
  73. * Remote URI.
  74. *
  75. * @var string
  76. */
  77. protected $_remoteURI = '';
  78. /**
  79. * Context option.
  80. *
  81. * @var array
  82. */
  83. protected $_contextOption = null;
  84. /**
  85. * Reconnect timer.
  86. *
  87. * @var int
  88. */
  89. protected $_reconnectTimer = null;
  90. /**
  91. * PHP built-in protocols.
  92. *
  93. * @var array<string,string>
  94. */
  95. const BUILD_IN_TRANSPORTS = [
  96. 'tcp' => 'tcp',
  97. 'udp' => 'udp',
  98. 'unix' => 'unix',
  99. 'ssl' => 'ssl',
  100. 'sslv2' => 'sslv2',
  101. 'sslv3' => 'sslv3',
  102. 'tls' => 'tls'
  103. ];
  104. /**
  105. * Construct.
  106. *
  107. * @param string $remote_address
  108. * @param array $context_option
  109. * @throws Exception
  110. */
  111. public function __construct($remote_address, array $context_option = [])
  112. {
  113. $address_info = \parse_url($remote_address);
  114. if (!$address_info) {
  115. list($scheme, $this->_remoteAddress) = \explode(':', $remote_address, 2);
  116. if ('unix' === strtolower($scheme)) {
  117. $this->_remoteAddress = substr($remote_address, strpos($remote_address, '/') + 2);
  118. }
  119. if (!$this->_remoteAddress) {
  120. Worker::safeEcho(new \Exception('bad remote_address'));
  121. }
  122. } else {
  123. if (!isset($address_info['port'])) {
  124. $address_info['port'] = 0;
  125. }
  126. if (!isset($address_info['path'])) {
  127. $address_info['path'] = '/';
  128. }
  129. if (!isset($address_info['query'])) {
  130. $address_info['query'] = '';
  131. } else {
  132. $address_info['query'] = '?' . $address_info['query'];
  133. }
  134. $this->_remoteHost = $address_info['host'];
  135. $this->_remotePort = $address_info['port'];
  136. $this->_remoteURI = "{$address_info['path']}{$address_info['query']}";
  137. $scheme = $address_info['scheme'] ?? 'tcp';
  138. $this->_remoteAddress = 'unix' === strtolower($scheme)
  139. ? substr($remote_address, strpos($remote_address, '/') + 2)
  140. : $this->_remoteHost . ':' . $this->_remotePort;
  141. }
  142. $this->id = $this->realId = self::$_idRecorder++;
  143. if (\PHP_INT_MAX === self::$_idRecorder) {
  144. self::$_idRecorder = 0;
  145. }
  146. // Check application layer protocol class.
  147. if (!isset(self::BUILD_IN_TRANSPORTS[$scheme])) {
  148. $scheme = \ucfirst($scheme);
  149. $this->protocol = '\\Protocols\\' . $scheme;
  150. if (!\class_exists($this->protocol)) {
  151. $this->protocol = "\\Workerman\\Protocols\\$scheme";
  152. if (!\class_exists($this->protocol)) {
  153. throw new Exception("class \\Protocols\\$scheme not exist");
  154. }
  155. }
  156. } else {
  157. $this->transport = self::BUILD_IN_TRANSPORTS[$scheme];
  158. }
  159. // For statistics.
  160. ++self::$statistics['connection_count'];
  161. $this->maxSendBufferSize = self::$defaultMaxSendBufferSize;
  162. $this->maxPackageSize = self::$defaultMaxPackageSize;
  163. $this->_contextOption = $context_option;
  164. static::$connections[$this->realId] = $this;
  165. }
  166. /**
  167. * Do connect.
  168. *
  169. * @return void
  170. */
  171. public function connect()
  172. {
  173. if ($this->_status !== self::STATUS_INITIAL && $this->_status !== self::STATUS_CLOSING &&
  174. $this->_status !== self::STATUS_CLOSED) {
  175. return;
  176. }
  177. $this->_status = self::STATUS_CONNECTING;
  178. $this->_connectStartTime = \microtime(true);
  179. if ($this->transport !== 'unix') {
  180. if (!$this->_remotePort) {
  181. $this->_remotePort = $this->transport === 'ssl' ? 443 : 80;
  182. $this->_remoteAddress = $this->_remoteHost . ':' . $this->_remotePort;
  183. }
  184. // Open socket connection asynchronously.
  185. if ($this->proxySocks5){
  186. $this->_contextOption['ssl']['peer_name'] = $this->_remoteHost;
  187. $context = \stream_context_create($this->_contextOption);
  188. $this->_socket = \stream_socket_client("tcp://{$this->proxySocks5}", $errno, $errstr, 0, \STREAM_CLIENT_ASYNC_CONNECT, $context);
  189. fwrite($this->_socket,chr(5) . chr(1) . chr(0));
  190. fread($this->_socket, 512);
  191. fwrite($this->_socket,chr(5) . chr(1) . chr(0) . chr(3) . chr(strlen($this->_remoteHost)) . $this->_remoteHost . pack("n", $this->_remotePort));
  192. fread($this->_socket, 512);
  193. }else if($this->proxyHttp){
  194. $this->_contextOption['ssl']['peer_name'] = $this->_remoteHost;
  195. $context = \stream_context_create($this->_contextOption);
  196. $this->_socket = \stream_socket_client("tcp://{$this->proxyHttp}", $errno, $errstr, 0, \STREAM_CLIENT_ASYNC_CONNECT, $context);
  197. $str = "CONNECT {$this->_remoteHost}:{$this->_remotePort} HTTP/1.1\n";
  198. $str .= "Host: {$this->_remoteHost}:{$this->_remotePort}\n";
  199. $str .= "Proxy-Connection: keep-alive\n";
  200. fwrite($this->_socket,$str);
  201. fread($this->_socket, 512);
  202. } else if ($this->_contextOption) {
  203. $context = \stream_context_create($this->_contextOption);
  204. $this->_socket = \stream_socket_client("tcp://{$this->_remoteHost}:{$this->_remotePort}",
  205. $errno, $errstr, 0, \STREAM_CLIENT_ASYNC_CONNECT, $context);
  206. } else {
  207. $this->_socket = \stream_socket_client("tcp://{$this->_remoteHost}:{$this->_remotePort}",
  208. $errno, $errstr, 0, \STREAM_CLIENT_ASYNC_CONNECT);
  209. }
  210. } else {
  211. $this->_socket = \stream_socket_client("{$this->transport}://{$this->_remoteAddress}", $errno, $errstr, 0,
  212. \STREAM_CLIENT_ASYNC_CONNECT);
  213. }
  214. // If failed attempt to emit onError callback.
  215. if (!$this->_socket || !\is_resource($this->_socket)) {
  216. $this->emitError(static::CONNECT_FAIL, $errstr);
  217. if ($this->_status === self::STATUS_CLOSING) {
  218. $this->destroy();
  219. }
  220. if ($this->_status === self::STATUS_CLOSED) {
  221. $this->onConnect = null;
  222. }
  223. return;
  224. }
  225. // Add socket to global event loop waiting connection is successfully established or faild.
  226. Worker::$globalEvent->onWritable($this->_socket, [$this, 'checkConnection']);
  227. // For windows.
  228. if (\DIRECTORY_SEPARATOR === '\\') {
  229. Worker::$globalEvent->onExcept($this->_socket, [$this, 'checkConnection']);
  230. }
  231. }
  232. /**
  233. * Reconnect.
  234. *
  235. * @param int $after
  236. * @return void
  237. */
  238. public function reconnect($after = 0)
  239. {
  240. $this->_status = self::STATUS_INITIAL;
  241. static::$connections[$this->realId] = $this;
  242. if ($this->_reconnectTimer) {
  243. Timer::del($this->_reconnectTimer);
  244. }
  245. if ($after > 0) {
  246. $this->_reconnectTimer = Timer::add($after, [$this, 'connect'], null, false);
  247. return;
  248. }
  249. $this->connect();
  250. }
  251. /**
  252. * CancelReconnect.
  253. */
  254. public function cancelReconnect()
  255. {
  256. if ($this->_reconnectTimer) {
  257. Timer::del($this->_reconnectTimer);
  258. }
  259. }
  260. /**
  261. * Get remote address.
  262. *
  263. * @return string
  264. */
  265. public function getRemoteHost()
  266. {
  267. return $this->_remoteHost;
  268. }
  269. /**
  270. * Get remote URI.
  271. *
  272. * @return string
  273. */
  274. public function getRemoteURI()
  275. {
  276. return $this->_remoteURI;
  277. }
  278. /**
  279. * Try to emit onError callback.
  280. *
  281. * @param int $code
  282. * @param string $msg
  283. * @return void
  284. */
  285. protected function emitError($code, $msg)
  286. {
  287. $this->_status = self::STATUS_CLOSING;
  288. if ($this->onError) {
  289. try {
  290. ($this->onError)($this, $code, $msg);
  291. } catch (\Throwable $e) {
  292. Worker::stopAll(250, $e);
  293. }
  294. }
  295. }
  296. /**
  297. * Check connection is successfully established or faild.
  298. *
  299. * @param resource $socket
  300. * @return void
  301. */
  302. public function checkConnection()
  303. {
  304. // Remove EV_EXPECT for windows.
  305. if (\DIRECTORY_SEPARATOR === '\\') {
  306. Worker::$globalEvent->offExcept($this->_socket);
  307. }
  308. // Remove write listener.
  309. Worker::$globalEvent->offWritable($this->_socket);
  310. if ($this->_status !== self::STATUS_CONNECTING) {
  311. return;
  312. }
  313. // Check socket state.
  314. if ($address = \stream_socket_get_name($this->_socket, true)) {
  315. // Nonblocking.
  316. \stream_set_blocking($this->_socket, false);
  317. // Compatible with hhvm
  318. if (\function_exists('stream_set_read_buffer')) {
  319. \stream_set_read_buffer($this->_socket, 0);
  320. }
  321. // Try to open keepalive for tcp and disable Nagle algorithm.
  322. if (\function_exists('socket_import_stream') && $this->transport === 'tcp') {
  323. $raw_socket = \socket_import_stream($this->_socket);
  324. \socket_set_option($raw_socket, \SOL_SOCKET, \SO_KEEPALIVE, 1);
  325. \socket_set_option($raw_socket, \SOL_TCP, \TCP_NODELAY, 1);
  326. }
  327. // SSL handshake.
  328. if ($this->transport === 'ssl') {
  329. $this->_sslHandshakeCompleted = $this->doSslHandshake($this->_socket);
  330. if ($this->_sslHandshakeCompleted === false) {
  331. return;
  332. }
  333. } else {
  334. // There are some data waiting to send.
  335. if ($this->_sendBuffer) {
  336. Worker::$globalEvent->onWritable($this->_socket, [$this, 'baseWrite']);
  337. }
  338. }
  339. // Register a listener waiting read event.
  340. Worker::$globalEvent->onReadable($this->_socket, [$this, 'baseRead']);
  341. $this->_status = self::STATUS_ESTABLISHED;
  342. $this->_remoteAddress = $address;
  343. // Try to emit onConnect callback.
  344. if ($this->onConnect) {
  345. try {
  346. ($this->onConnect)($this);
  347. } catch (\Throwable $e) {
  348. Worker::stopAll(250, $e);
  349. }
  350. }
  351. // Try to emit protocol::onConnect
  352. if ($this->protocol && \method_exists($this->protocol, 'onConnect')) {
  353. try {
  354. [$this->protocol, 'onConnect']($this);
  355. } catch (\Throwable $e) {
  356. Worker::stopAll(250, $e);
  357. }
  358. }
  359. } else {
  360. // Connection failed.
  361. $this->emitError(static::CONNECT_FAIL, 'connect ' . $this->_remoteAddress . ' fail after ' . round(\microtime(true) - $this->_connectStartTime, 4) . ' seconds');
  362. if ($this->_status === self::STATUS_CLOSING) {
  363. $this->destroy();
  364. }
  365. if ($this->_status === self::STATUS_CLOSED) {
  366. $this->onConnect = null;
  367. }
  368. }
  369. }
  370. }