Ws.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. <?php
  2. namespace Workerman\Protocols;
  3. use Workerman\Worker;
  4. /**
  5. * Websocket protocol for client.
  6. */
  7. class Ws
  8. {
  9. /**
  10. * Minimum head length of websocket protocol.
  11. *
  12. * @var int
  13. */
  14. const MIN_HEAD_LEN = 2;
  15. /**
  16. * Websocket blob type.
  17. *
  18. * @var string
  19. */
  20. const BINARY_TYPE_BLOB = "\x81";
  21. /**
  22. * Websocket arraybuffer type.
  23. *
  24. * @var string
  25. */
  26. const BINARY_TYPE_ARRAYBUFFER = "\x82";
  27. /**
  28. * Check the integrity of the package.
  29. *
  30. * @param string $buffer
  31. * @param ConnectionInterface $connection
  32. * @return int
  33. */
  34. public static function input($buffer, $connection)
  35. {
  36. if (empty($connection->handshakeStep)) {
  37. echo "recv data before handshake\n";
  38. return false;
  39. }
  40. // Recv handshake response
  41. if ($connection->handshakeStep === 1) {
  42. return self::dealHandshake($buffer, $connection);
  43. }
  44. $recv_len = strlen($buffer);
  45. if ($recv_len < self::MIN_HEAD_LEN) {
  46. return 0;
  47. }
  48. // Buffer websocket frame data.
  49. if ($connection->websocketCurrentFrameLength) {
  50. // We need more frame data.
  51. if ($connection->websocketCurrentFrameLength > $recv_len) {
  52. // Return 0, because it is not clear the full packet length, waiting for the frame of fin=1.
  53. return 0;
  54. }
  55. } else {
  56. $data_len = ord($buffer[1]) & 127;
  57. $firstbyte = ord($buffer[0]);
  58. $is_fin_frame = $firstbyte >> 7;
  59. $opcode = $firstbyte & 0xf;
  60. switch ($opcode) {
  61. case 0x0:
  62. break;
  63. // Blob type.
  64. case 0x1:
  65. break;
  66. // Arraybuffer type.
  67. case 0x2:
  68. break;
  69. // Close package.
  70. case 0x8:
  71. // Try to emit onWebSocketClose callback.
  72. if (isset($connection->onWebSocketClose)) {
  73. try {
  74. call_user_func($connection->onWebSocketClose, $connection);
  75. } catch (\Exception $e) {
  76. Worker::log($e);
  77. exit(250);
  78. } catch (\Error $e) {
  79. Worker::log($e);
  80. exit(250);
  81. }
  82. } // Close connection.
  83. else {
  84. $connection->close();
  85. }
  86. return 0;
  87. // Ping package.
  88. case 0x9:
  89. // Try to emit onWebSocketPing callback.
  90. if (isset($connection->onWebSocketPing)) {
  91. try {
  92. call_user_func($connection->onWebSocketPing, $connection);
  93. } catch (\Exception $e) {
  94. Worker::log($e);
  95. exit(250);
  96. } catch (\Error $e) {
  97. Worker::log($e);
  98. exit(250);
  99. }
  100. } // Send pong package to client.
  101. else {
  102. $connection->send(pack('H*', '8a00'), true);
  103. }
  104. // Consume data from receive buffer.
  105. if (!$data_len) {
  106. $connection->consumeRecvBuffer(self::MIN_HEAD_LEN);
  107. if ($recv_len > self::MIN_HEAD_LEN) {
  108. return self::input(substr($buffer, self::MIN_HEAD_LEN), $connection);
  109. }
  110. return 0;
  111. }
  112. break;
  113. // Pong package.
  114. case 0xa:
  115. // Try to emit onWebSocketPong callback.
  116. if (isset($connection->onWebSocketPong)) {
  117. try {
  118. call_user_func($connection->onWebSocketPong, $connection);
  119. } catch (\Exception $e) {
  120. Worker::log($e);
  121. exit(250);
  122. } catch (\Error $e) {
  123. Worker::log($e);
  124. exit(250);
  125. }
  126. }
  127. // Consume data from receive buffer.
  128. if (!$data_len) {
  129. $connection->consumeRecvBuffer(self::MIN_HEAD_LEN);
  130. if ($recv_len > self::MIN_HEAD_LEN) {
  131. return self::input(substr($buffer, self::MIN_HEAD_LEN), $connection);
  132. }
  133. return 0;
  134. }
  135. break;
  136. // Wrong opcode.
  137. default :
  138. echo "error opcode $opcode and close websocket connection\n";
  139. $connection->close();
  140. return 0;
  141. }
  142. // Calculate packet length.
  143. if ($data_len === 126) {
  144. if (strlen($buffer) < 6) {
  145. return 0;
  146. }
  147. $pack = unpack('nn/ntotal_len', $buffer);
  148. $current_frame_length = $pack['total_len'] + 4;
  149. } else if ($data_len === 127) {
  150. if (strlen($buffer) < 10) {
  151. return 0;
  152. }
  153. $arr = unpack('n/N2c', $buffer);
  154. $current_frame_length = $arr['c1']*4294967296 + $arr['c2'] + 10;
  155. } else {
  156. $current_frame_length = $data_len + 2;
  157. }
  158. if ($is_fin_frame) {
  159. return $current_frame_length;
  160. } else {
  161. $connection->websocketCurrentFrameLength = $current_frame_length;
  162. }
  163. }
  164. // Received just a frame length data.
  165. if ($connection->websocketCurrentFrameLength === $recv_len) {
  166. self::decode($buffer, $connection);
  167. $connection->consumeRecvBuffer($connection->websocketCurrentFrameLength);
  168. $connection->websocketCurrentFrameLength = 0;
  169. return 0;
  170. } // The length of the received data is greater than the length of a frame.
  171. elseif ($connection->websocketCurrentFrameLength < $recv_len) {
  172. self::decode(substr($buffer, 0, $connection->websocketCurrentFrameLength), $connection);
  173. $connection->consumeRecvBuffer($connection->websocketCurrentFrameLength);
  174. $current_frame_length = $connection->websocketCurrentFrameLength;
  175. $connection->websocketCurrentFrameLength = 0;
  176. // Continue to read next frame.
  177. return self::input(substr($buffer, $current_frame_length), $connection);
  178. } // The length of the received data is less than the length of a frame.
  179. else {
  180. return 0;
  181. }
  182. }
  183. /**
  184. * Websocket encode.
  185. *
  186. * @param string $buffer
  187. * @param ConnectionInterface $connection
  188. * @return string
  189. */
  190. public static function encode($payload, $connection)
  191. {
  192. $payload = (string)$payload;
  193. if (empty($connection->handshakeStep)) {
  194. self::sendHandshake($connection);
  195. }
  196. $mask = 1;
  197. $mask_key = "\x00\x00\x00\x00";
  198. $pack = '';
  199. $length = $length_flag = strlen($payload);
  200. if (65535 < $length) {
  201. $pack = pack('NN', ($length & 0xFFFFFFFF00000000) >> 32, $length & 0x00000000FFFFFFFF);
  202. $length_flag = 127;
  203. } else if (125 < $length) {
  204. $pack = pack('n*', $length);
  205. $length_flag = 126;
  206. }
  207. $head = ($mask << 7) | $length_flag;
  208. $head = $connection->websocketType . chr($head) . $pack;
  209. $frame = $head . $mask_key;
  210. // append payload to frame:
  211. for ($i = 0; $i < $length; $i++) {
  212. $frame .= $payload[$i] ^ $mask_key[$i % 4];
  213. }
  214. if ($connection->handshakeStep === 1) {
  215. $connection->tmpWebsocketData = isset($connection->tmpWebsocketData) ? $connection->tmpWebsocketData . $frame : $frame;
  216. return '';
  217. }
  218. return $frame;
  219. }
  220. /**
  221. * Websocket decode.
  222. *
  223. * @param string $buffer
  224. * @param ConnectionInterface $connection
  225. * @return string
  226. */
  227. public static function decode($bytes, $connection)
  228. {
  229. $masked = $bytes[1] >> 7;
  230. $data_length = $masked ? ord($bytes[1]) & 127 : ord($bytes[1]);
  231. $decoded_data = '';
  232. if ($masked === true) {
  233. if ($data_length === 126) {
  234. $mask = substr($bytes, 4, 4);
  235. $coded_data = substr($bytes, 8);
  236. } else if ($data_length === 127) {
  237. $mask = substr($bytes, 10, 4);
  238. $coded_data = substr($bytes, 14);
  239. } else {
  240. $mask = substr($bytes, 2, 4);
  241. $coded_data = substr($bytes, 6);
  242. }
  243. for ($i = 0; $i < strlen($coded_data); $i++) {
  244. $decoded_data .= $coded_data[$i] ^ $mask[$i % 4];
  245. }
  246. } else {
  247. if ($data_length === 126) {
  248. $decoded_data = substr($bytes, 4);
  249. } else if ($data_length === 127) {
  250. $decoded_data = substr($bytes, 10);
  251. } else {
  252. $decoded_data = substr($bytes, 2);
  253. }
  254. }
  255. if ($connection->websocketCurrentFrameLength) {
  256. $connection->websocketDataBuffer .= $decoded_data;
  257. return $connection->websocketDataBuffer;
  258. } else {
  259. if ($connection->websocketDataBuffer !== '') {
  260. $decoded_data = $connection->websocketDataBuffer . $decoded_data;
  261. $connection->websocketDataBuffer = '';
  262. }
  263. return $decoded_data;
  264. }
  265. }
  266. /**
  267. * Send websocket handshake data.
  268. *
  269. * @return void
  270. */
  271. public static function onConnect($connection)
  272. {
  273. $connection->handshakeStep = null;
  274. self::sendHandshake($connection);
  275. }
  276. /**
  277. * Send websocket handshake.
  278. *
  279. * @param \Workerman\Connection\TcpConnection $connection
  280. * @return void
  281. */
  282. public static function sendHandshake($connection)
  283. {
  284. if (!empty($connection->handshakeStep)) {
  285. return;
  286. }
  287. // Get Host.
  288. $port = $connection->getRemotePort();
  289. $host = $port === 80 ? $connection->getRemoteHost() : $connection->getRemoteHost() . ':' . $port;
  290. // Handshake header.
  291. $header = "GET / HTTP/1.1\r\n".
  292. "Host: $host\r\n".
  293. "Connection: Upgrade\r\n".
  294. "Upgrade: websocket\r\n".
  295. "Origin: ". (isset($connection->websocketOrigin) ? $connection->websocketOrigin : '*') ."\r\n".
  296. "Sec-WebSocket-Version: 13\r\n".
  297. "Sec-WebSocket-Key: ".base64_encode(sha1(uniqid(mt_rand(), true), true))."\r\n\r\n";
  298. $connection->send($header, true);
  299. $connection->handshakeStep = 1;
  300. $connection->websocketCurrentFrameLength = 0;
  301. $connection->websocketDataBuffer = '';
  302. if (empty($connection->websocketType)) {
  303. $connection->websocketType = self::BINARY_TYPE_BLOB;
  304. }
  305. }
  306. /**
  307. * Websocket handshake.
  308. *
  309. * @param string $buffer
  310. * @param \Workerman\Connection\TcpConnection $connection
  311. * @return int
  312. */
  313. public static function dealHandshake($buffer, $connection)
  314. {
  315. $pos = strpos($buffer, "\r\n\r\n");
  316. if ($pos) {
  317. // handshake complete
  318. $connection->handshakeStep = 2;
  319. $handshake_respnse_length = $pos + 4;
  320. // Try to emit onWebSocketConnect callback.
  321. if (isset($connection->onWebSocketConnect)) {
  322. try {
  323. call_user_func($connection->onWebSocketConnect, $connection, substr($buffer, 0, $handshake_respnse_length));
  324. } catch (\Exception $e) {
  325. Worker::log($e);
  326. exit(250);
  327. } catch (\Error $e) {
  328. Worker::log($e);
  329. exit(250);
  330. }
  331. }
  332. // Headbeat.
  333. if (!empty($connection->websocketPingInterval)) {
  334. $connection->websocketPingTimer = \Workerman\Lib\Timer::add($connection->websocketPingInterval, function() use ($connection){
  335. if (false === $connection->send(pack('H*', '8900'), true)) {
  336. \Workerman\Lib\Timer::del($connection->websocketPingTimer);
  337. }
  338. });
  339. }
  340. $connection->consumeRecvBuffer($handshake_respnse_length);
  341. if (!empty($connection->tmpWebsocketData)) {
  342. $connection->send($connection->tmpWebsocketData, true);
  343. $connection->tmpWebsocketData = '';
  344. }
  345. if (strlen($buffer > $handshake_respnse_length)) {
  346. return self::input(substr($buffer, $handshake_respnse_length));
  347. }
  348. }
  349. return 0;
  350. }
  351. }