AsyncTcpConnection.php 14 KB

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