AsyncTcpConnection.php 13 KB

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