AsyncTcpConnection.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  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. 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. * @throws Exception
  141. */
  142. public function __construct(string $remoteAddress, array $socketContext = [])
  143. {
  144. $addressInfo = parse_url($remoteAddress);
  145. if (!$addressInfo) {
  146. list($scheme, $this->remoteAddress) = explode(':', $remoteAddress, 2);
  147. if ('unix' === strtolower($scheme)) {
  148. $this->remoteAddress = substr($remoteAddress, strpos($remoteAddress, '/') + 2);
  149. }
  150. if (!$this->remoteAddress) {
  151. throw new RuntimeException('Bad remoteAddress');
  152. }
  153. } else {
  154. if (!isset($addressInfo['port'])) {
  155. $addressInfo['port'] = 0;
  156. }
  157. if (!isset($addressInfo['path'])) {
  158. $addressInfo['path'] = '/';
  159. }
  160. if (!isset($addressInfo['query'])) {
  161. $addressInfo['query'] = '';
  162. } else {
  163. $addressInfo['query'] = '?' . $addressInfo['query'];
  164. }
  165. $this->remoteHost = $addressInfo['host'];
  166. $this->remotePort = $addressInfo['port'];
  167. $this->remoteURI = "{$addressInfo['path']}{$addressInfo['query']}";
  168. $scheme = $addressInfo['scheme'] ?? 'tcp';
  169. $this->remoteAddress = 'unix' === strtolower($scheme)
  170. ? substr($remoteAddress, strpos($remoteAddress, '/') + 2)
  171. : $this->remoteHost . ':' . $this->remotePort;
  172. }
  173. $this->id = $this->realId = self::$idRecorder++;
  174. if (PHP_INT_MAX === self::$idRecorder) {
  175. self::$idRecorder = 0;
  176. }
  177. // Check application layer protocol class.
  178. if (!isset(self::BUILD_IN_TRANSPORTS[$scheme])) {
  179. $scheme = ucfirst($scheme);
  180. $this->protocol = '\\Protocols\\' . $scheme;
  181. if (!class_exists($this->protocol)) {
  182. $this->protocol = "\\Workerman\\Protocols\\$scheme";
  183. if (!class_exists($this->protocol)) {
  184. throw new Exception("class \\Protocols\\$scheme not exist");
  185. }
  186. }
  187. } else {
  188. $this->transport = self::BUILD_IN_TRANSPORTS[$scheme];
  189. }
  190. // For statistics.
  191. ++self::$statistics['connection_count'];
  192. $this->maxSendBufferSize = self::$defaultMaxSendBufferSize;
  193. $this->maxPackageSize = self::$defaultMaxPackageSize;
  194. $this->socketContext = $socketContext;
  195. static::$connections[$this->realId] = $this;
  196. $this->context = new stdClass;
  197. }
  198. /**
  199. * Reconnect.
  200. *
  201. * @param int $after
  202. * @return void
  203. * @throws Throwable
  204. */
  205. public function reconnect(int $after = 0): void
  206. {
  207. $this->status = self::STATUS_INITIAL;
  208. static::$connections[$this->realId] = $this;
  209. if ($this->reconnectTimer) {
  210. Timer::del($this->reconnectTimer);
  211. }
  212. if ($after > 0) {
  213. $this->reconnectTimer = Timer::add($after, [$this, 'connect'], null, false);
  214. return;
  215. }
  216. $this->connect();
  217. }
  218. /**
  219. * Do connect.
  220. *
  221. * @return void
  222. * @throws Throwable
  223. */
  224. public function connect(): void
  225. {
  226. if ($this->status !== self::STATUS_INITIAL && $this->status !== self::STATUS_CLOSING &&
  227. $this->status !== self::STATUS_CLOSED) {
  228. return;
  229. }
  230. if (!$this->eventLoop) {
  231. $this->eventLoop = Worker::$globalEvent;
  232. }
  233. $this->status = self::STATUS_CONNECTING;
  234. $this->connectStartTime = microtime(true);
  235. if ($this->transport !== 'unix') {
  236. if (!$this->remotePort) {
  237. $this->remotePort = $this->transport === 'ssl' ? 443 : 80;
  238. $this->remoteAddress = $this->remoteHost . ':' . $this->remotePort;
  239. }
  240. // Open socket connection asynchronously.
  241. if ($this->proxySocks5) {
  242. $this->socketContext['ssl']['peer_name'] = $this->remoteHost;
  243. $context = stream_context_create($this->socketContext);
  244. $this->socket = stream_socket_client("tcp://$this->proxySocks5", $errno, $err_str, 0, STREAM_CLIENT_ASYNC_CONNECT, $context);
  245. fwrite($this->socket, chr(5) . chr(1) . chr(0));
  246. fread($this->socket, 512);
  247. fwrite($this->socket, chr(5) . chr(1) . chr(0) . chr(3) . chr(strlen($this->remoteHost)) . $this->remoteHost . pack("n", $this->remotePort));
  248. fread($this->socket, 512);
  249. } else if ($this->proxyHttp) {
  250. $this->socketContext['ssl']['peer_name'] = $this->remoteHost;
  251. $context = stream_context_create($this->socketContext);
  252. $this->socket = stream_socket_client("tcp://$this->proxyHttp", $errno, $err_str, 0, STREAM_CLIENT_ASYNC_CONNECT, $context);
  253. $str = "CONNECT $this->remoteHost:$this->remotePort HTTP/1.1\n";
  254. $str .= "Host: $this->remoteHost:$this->remotePort\n";
  255. $str .= "Proxy-Connection: keep-alive\n";
  256. fwrite($this->socket, $str);
  257. fread($this->socket, 512);
  258. } else if ($this->socketContext) {
  259. $context = stream_context_create($this->socketContext);
  260. $this->socket = stream_socket_client("tcp://$this->remoteHost:$this->remotePort",
  261. $errno, $err_str, 0, STREAM_CLIENT_ASYNC_CONNECT, $context);
  262. } else {
  263. $this->socket = stream_socket_client("tcp://$this->remoteHost:$this->remotePort",
  264. $errno, $err_str, 0, STREAM_CLIENT_ASYNC_CONNECT);
  265. }
  266. } else {
  267. $this->socket = stream_socket_client("$this->transport://$this->remoteAddress", $errno, $err_str, 0,
  268. STREAM_CLIENT_ASYNC_CONNECT);
  269. }
  270. // If failed attempt to emit onError callback.
  271. if (!$this->socket || !is_resource($this->socket)) {
  272. $this->emitError(static::CONNECT_FAIL, $err_str);
  273. if ($this->status === self::STATUS_CLOSING) {
  274. $this->destroy();
  275. }
  276. if ($this->status === self::STATUS_CLOSED) {
  277. $this->onConnect = null;
  278. }
  279. return;
  280. }
  281. // Add socket to global event loop waiting connection is successfully established or faild.
  282. $this->eventLoop->onWritable($this->socket, [$this, 'checkConnection']);
  283. // For windows.
  284. if (DIRECTORY_SEPARATOR === '\\' && method_exists($this->eventLoop, 'onExcept')) {
  285. $this->eventLoop->onExcept($this->socket, [$this, 'checkConnection']);
  286. }
  287. }
  288. /**
  289. * Try to emit onError callback.
  290. *
  291. * @param int $code
  292. * @param mixed $msg
  293. * @return void
  294. * @throws Throwable
  295. */
  296. protected function emitError(int $code, mixed $msg): void
  297. {
  298. $this->status = self::STATUS_CLOSING;
  299. if ($this->onError) {
  300. try {
  301. ($this->onError)($this, $code, $msg);
  302. } catch (Throwable $e) {
  303. $this->error($e);
  304. }
  305. }
  306. }
  307. /**
  308. * CancelReconnect.
  309. */
  310. public function cancelReconnect(): void
  311. {
  312. if ($this->reconnectTimer) {
  313. Timer::del($this->reconnectTimer);
  314. $this->reconnectTimer = 0;
  315. }
  316. }
  317. /**
  318. * Get remote address.
  319. *
  320. * @return string
  321. */
  322. public function getRemoteHost(): string
  323. {
  324. return $this->remoteHost;
  325. }
  326. /**
  327. * Get remote URI.
  328. *
  329. * @return string
  330. */
  331. public function getRemoteURI(): string
  332. {
  333. return $this->remoteURI;
  334. }
  335. /**
  336. * Check connection is successfully established or failed.
  337. *
  338. * @return void
  339. * @throws Throwable
  340. */
  341. public function checkConnection(): void
  342. {
  343. // Remove EV_EXPECT for windows.
  344. if (DIRECTORY_SEPARATOR === '\\' && method_exists($this->eventLoop, 'offExcept')) {
  345. $this->eventLoop->offExcept($this->socket);
  346. }
  347. // Remove write listener.
  348. $this->eventLoop->offWritable($this->socket);
  349. if ($this->status !== self::STATUS_CONNECTING) {
  350. return;
  351. }
  352. // Check socket state.
  353. if ($address = stream_socket_get_name($this->socket, true)) {
  354. // Nonblocking.
  355. stream_set_blocking($this->socket, false);
  356. // Compatible with hhvm
  357. if (function_exists('stream_set_read_buffer')) {
  358. stream_set_read_buffer($this->socket, 0);
  359. }
  360. // Try to open keepalive for tcp and disable Nagle algorithm.
  361. if (function_exists('socket_import_stream') && $this->transport === 'tcp') {
  362. $rawSocket = socket_import_stream($this->socket);
  363. socket_set_option($rawSocket, SOL_SOCKET, SO_KEEPALIVE, 1);
  364. socket_set_option($rawSocket, SOL_TCP, TCP_NODELAY, 1);
  365. }
  366. // SSL handshake.
  367. if ($this->transport === 'ssl') {
  368. $this->sslHandshakeCompleted = $this->doSslHandshake($this->socket);
  369. if ($this->sslHandshakeCompleted === false) {
  370. return;
  371. }
  372. } else {
  373. // There are some data waiting to send.
  374. if ($this->sendBuffer) {
  375. $this->eventLoop->onWritable($this->socket, [$this, 'baseWrite']);
  376. }
  377. }
  378. // Register a listener waiting read event.
  379. $this->eventLoop->onReadable($this->socket, [$this, 'baseRead']);
  380. $this->status = self::STATUS_ESTABLISHED;
  381. $this->remoteAddress = $address;
  382. // Try to emit onConnect callback.
  383. if ($this->onConnect) {
  384. try {
  385. ($this->onConnect)($this);
  386. } catch (Throwable $e) {
  387. $this->error($e);
  388. }
  389. }
  390. // Try to emit protocol::onConnect
  391. if ($this->protocol && method_exists($this->protocol, 'onConnect')) {
  392. try {
  393. [$this->protocol, 'onConnect']($this);
  394. } catch (Throwable $e) {
  395. $this->error($e);
  396. }
  397. }
  398. } else {
  399. // Connection failed.
  400. $this->emitError(static::CONNECT_FAIL, 'connect ' . $this->remoteAddress . ' fail after ' . round(microtime(true) - $this->connectStartTime, 4) . ' seconds');
  401. if ($this->status === self::STATUS_CLOSING) {
  402. $this->destroy();
  403. }
  404. if ($this->status === self::STATUS_CLOSED) {
  405. $this->onConnect = null;
  406. }
  407. }
  408. }
  409. }