Websocket.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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\Protocols;
  15. use Workerman\Connection\ConnectionInterface;
  16. /**
  17. * WebSocket protocol.
  18. */
  19. class Websocket implements \Workerman\Protocols\ProtocolInterface
  20. {
  21. /**
  22. * Minimum head length of websocket protocol.
  23. * @var int
  24. */
  25. const MIN_HEAD_LEN = 6;
  26. /**
  27. * Websocket blob type.
  28. * @var char
  29. */
  30. const BINARY_TYPE_BLOB = "\x81";
  31. /**
  32. * Websocket arraybuffer type.
  33. * @var char
  34. */
  35. const BINARY_TYPE_ARRAYBUFFER = "\x82";
  36. /**
  37. * Check the integrity of the package.
  38. * @param string $buffer
  39. */
  40. public static function input($buffer, ConnectionInterface $connection)
  41. {
  42. // Receive length.
  43. $recv_len = strlen($buffer);
  44. // We need more data.
  45. if($recv_len < self::MIN_HEAD_LEN)
  46. {
  47. return 0;
  48. }
  49. // Has not yet completed the handshake.
  50. if(empty($connection->websocketHandshake))
  51. {
  52. return self::dealHandshake($buffer, $connection);
  53. }
  54. // Buffer websocket frame data.
  55. if($connection->websocketCurrentFrameLength)
  56. {
  57. // We need more frame data.
  58. if($connection->websocketCurrentFrameLength > $recv_len)
  59. {
  60. // Return 0, because it is not clear the full packet length, waiting for the frame of fin=1.
  61. return 0;
  62. }
  63. }
  64. else
  65. {
  66. $data_len = ord($buffer[1]) & 127;
  67. $firstbyte = ord($buffer[0]);
  68. $is_fin_frame = $firstbyte>>7;
  69. $opcode = $firstbyte & 0xf;
  70. switch($opcode)
  71. {
  72. case 0x0:
  73. break;
  74. // Blob type.
  75. case 0x1:
  76. break;
  77. // Arraybuffer type.
  78. case 0x2:
  79. break;
  80. // Close package.
  81. case 0x8:
  82. // Try to emit onWebSocketClose callback.
  83. if(isset($connection->onWebSocketClose))
  84. {
  85. try
  86. {
  87. call_user_func($connection->onWebSocketClose, $connection);
  88. }
  89. catch(\Exception $e)
  90. {
  91. echo $e;
  92. exit(250);
  93. }
  94. }
  95. // Close connection.
  96. else
  97. {
  98. $connection->close();
  99. }
  100. return 0;
  101. // Ping package.
  102. case 0x9:
  103. // Try to emit onWebSocketPing callback.
  104. if(isset($connection->onWebSocketPing))
  105. {
  106. try
  107. {
  108. call_user_func($connection->onWebSocketPing, $connection);
  109. }
  110. catch(\Exception $e)
  111. {
  112. echo $e;
  113. exit(250);
  114. }
  115. }
  116. // Send pong package to client.
  117. else
  118. {
  119. $connection->send(pack('H*', '8a00'), true);
  120. }
  121. // Consume data from receive buffer.
  122. if(!$data_len)
  123. {
  124. $connection->consumeRecvBuffer(self::MIN_HEAD_LEN);
  125. return 0;
  126. }
  127. break;
  128. // Pong package.
  129. case 0xa:
  130. // Try to emit onWebSocketPong callback.
  131. if(isset($connection->onWebSocketPong))
  132. {
  133. try
  134. {
  135. call_user_func($connection->onWebSocketPong, $connection);
  136. }
  137. catch(\Exception $e)
  138. {
  139. echo $e;
  140. exit(250);
  141. }
  142. }
  143. // Consume data from receive buffer.
  144. if(!$data_len)
  145. {
  146. $connection->consumeRecvBuffer(self::MIN_HEAD_LEN);
  147. return 0;
  148. }
  149. break;
  150. // Wrong opcode.
  151. default :
  152. echo "error opcode $opcode and close websocket connection\n";
  153. $connection->close();
  154. return 0;
  155. }
  156. // Calculate packet length.
  157. $head_len = self::MIN_HEAD_LEN;
  158. if ($data_len === 126) {
  159. $head_len = 8;
  160. if($head_len > $recv_len)
  161. {
  162. return 0;
  163. }
  164. $pack = unpack('ntotal_len', substr($buffer, 2, 2));
  165. $data_len = $pack['total_len'];
  166. } else if ($data_len === 127) {
  167. $head_len = 14;
  168. if($head_len > $recv_len)
  169. {
  170. return 0;
  171. }
  172. $arr = unpack('N2', substr($buffer, 2, 8));
  173. $data_len = $arr[1]*4294967296 + $arr[2];
  174. }
  175. $current_frame_length = $head_len + $data_len;
  176. if($is_fin_frame)
  177. {
  178. return $current_frame_length;
  179. }
  180. else
  181. {
  182. $connection->websocketCurrentFrameLength = $current_frame_length;
  183. }
  184. }
  185. // Received just a frame length data.
  186. if($connection->websocketCurrentFrameLength == $recv_len)
  187. {
  188. self::decode($buffer, $connection);
  189. $connection->consumeRecvBuffer($connection->websocketCurrentFrameLength);
  190. $connection->websocketCurrentFrameLength = 0;
  191. return 0;
  192. }
  193. // The length of the received data is greater than the length of a frame.
  194. elseif($connection->websocketCurrentFrameLength < $recv_len)
  195. {
  196. self::decode(substr($buffer, 0, $connection->websocketCurrentFrameLength), $connection);
  197. $connection->consumeRecvBuffer($connection->websocketCurrentFrameLength);
  198. $current_frame_length = $connection->websocketCurrentFrameLength;
  199. $connection->websocketCurrentFrameLength = 0;
  200. // Continue to read next frame.
  201. return self::input(substr($buffer, $current_frame_length), $connection);
  202. }
  203. // The length of the received data is less than the length of a frame.
  204. else
  205. {
  206. return 0;
  207. }
  208. }
  209. /**
  210. * Websocket encode.
  211. * @param string $buffer
  212. * @return string
  213. */
  214. public static function encode($buffer, ConnectionInterface $connection)
  215. {
  216. $len = strlen($buffer);
  217. if(empty($connection->websocketType))
  218. {
  219. $connection->websocketType = self::BINARY_TYPE_BLOB;
  220. }
  221. $first_byte = $connection->websocketType;
  222. if($len<=125)
  223. {
  224. $encode_buffer = $first_byte.chr($len).$buffer;
  225. }
  226. else if($len<=65535)
  227. {
  228. $encode_buffer = $first_byte.chr(126).pack("n", $len).$buffer;
  229. }
  230. else
  231. {
  232. $encode_buffer = $first_byte.chr(127).pack("xxxxN", $len).$buffer;
  233. }
  234. // Handshake not completed so temporary buffer websocket data waiting for send.
  235. if(empty($connection->websocketHandshake))
  236. {
  237. if(empty($connection->tmpWebsocketData))
  238. {
  239. $connection->tmpWebsocketData = '';
  240. }
  241. $connection->tmpWebsocketData .= $encode_buffer;
  242. // Return empty string.
  243. return '';
  244. }
  245. return $encode_buffer;
  246. }
  247. /**
  248. * Websocket decode.
  249. * @param string $buffer
  250. * @return string
  251. */
  252. public static function decode($buffer, ConnectionInterface $connection)
  253. {
  254. $len = $masks = $data = $decoded = null;
  255. $len = ord($buffer[1]) & 127;
  256. if ($len === 126) {
  257. $masks = substr($buffer, 4, 4);
  258. $data = substr($buffer, 8);
  259. } else if ($len === 127) {
  260. $masks = substr($buffer, 10, 4);
  261. $data = substr($buffer, 14);
  262. } else {
  263. $masks = substr($buffer, 2, 4);
  264. $data = substr($buffer, 6);
  265. }
  266. for ($index = 0; $index < strlen($data); $index++) {
  267. $decoded .= $data[$index] ^ $masks[$index % 4];
  268. }
  269. if($connection->websocketCurrentFrameLength)
  270. {
  271. $connection->websocketDataBuffer .= $decoded;
  272. return $connection->websocketDataBuffer;
  273. }
  274. else
  275. {
  276. $decoded = $connection->websocketDataBuffer . $decoded;
  277. $connection->websocketDataBuffer = '';
  278. return $decoded;
  279. }
  280. }
  281. /**
  282. * Websocket handshake.
  283. * @param string $buffer
  284. * @param TcpConnection $connection
  285. * @return int
  286. */
  287. protected static function dealHandshake($buffer, $connection)
  288. {
  289. // HTTP protocol.
  290. if(0 === strpos($buffer, 'GET'))
  291. {
  292. // Find \r\n\r\n.
  293. $heder_end_pos = strpos($buffer, "\r\n\r\n");
  294. if(!$heder_end_pos)
  295. {
  296. return 0;
  297. }
  298. // Get Sec-WebSocket-Key.
  299. $Sec_WebSocket_Key = '';
  300. if(preg_match("/Sec-WebSocket-Key: *(.*?)\r\n/i", $buffer, $match))
  301. {
  302. $Sec_WebSocket_Key = $match[1];
  303. }
  304. else
  305. {
  306. $connection->send("HTTP/1.1 400 Bad Request\r\n\r\n<b>400 Bad Request</b><br>Sec-WebSocket-Key not found.<br>This is a WebSocket service and can not be accessed via HTTP.", true);
  307. $connection->close();
  308. return 0;
  309. }
  310. // Calculation websocket key.
  311. $new_key = base64_encode(sha1($Sec_WebSocket_Key."258EAFA5-E914-47DA-95CA-C5AB0DC85B11",true));
  312. // Handshake response data.
  313. $handshake_message = "HTTP/1.1 101 Switching Protocols\r\n";
  314. $handshake_message .= "Upgrade: websocket\r\n";
  315. $handshake_message .= "Sec-WebSocket-Version: 13\r\n";
  316. $handshake_message .= "Connection: Upgrade\r\n";
  317. $handshake_message .= "Sec-WebSocket-Accept: " . $new_key . "\r\n\r\n";
  318. // Mark handshake complete..
  319. $connection->websocketHandshake = true;
  320. // Websocket data buffer.
  321. $connection->websocketDataBuffer = '';
  322. // Current websocket frame length.
  323. $connection->websocketCurrentFrameLength = 0;
  324. // Current websocket frame data.
  325. $connection->websocketCurrentFrameBuffer = '';
  326. // Consume handshake data.
  327. $connection->consumeRecvBuffer(strlen($buffer));
  328. // Send handshake response.
  329. $connection->send($handshake_message, true);
  330. // There are data waiting to be sent.
  331. if(!empty($connection->tmpWebsocketData))
  332. {
  333. $connection->send($connection->tmpWebsocketData, true);
  334. $connection->tmpWebsocketData = '';
  335. }
  336. // blob or arraybuffer
  337. if(empty($connection->websocketType))
  338. {
  339. $connection->websocketType = self::BINARY_TYPE_BLOB;
  340. }
  341. // Try to emit onWebSocketConnect callback.
  342. if(isset($connection->onWebSocketConnect))
  343. {
  344. self::parseHttpHeader($buffer);
  345. try
  346. {
  347. call_user_func($connection->onWebSocketConnect, $connection, $buffer);
  348. }
  349. catch(\Exception $e)
  350. {
  351. echo $e;
  352. exit(250);
  353. }
  354. $_GET = $_COOKIE = $_SERVER = array();
  355. }
  356. return 0;
  357. }
  358. // Is flash policy-file-request.
  359. elseif(0 === strpos($buffer,'<polic'))
  360. {
  361. $policy_xml = '<?xml version="1.0"?><cross-domain-policy><site-control permitted-cross-domain-policies="all"/><allow-access-from domain="*" to-ports="*"/></cross-domain-policy>'."\0";
  362. $connection->send($policy_xml, true);
  363. $connection->consumeRecvBuffer(strlen($buffer));
  364. return 0;
  365. }
  366. // Bad websocket handshake request.
  367. $connection->send("HTTP/1.1 400 Bad Request\r\n\r\n<b>400 Bad Request</b><br>Invalid handshake data for websocket. ", true);
  368. $connection->close();
  369. return 0;
  370. }
  371. /**
  372. * Parse http header.
  373. * @param string $buffer
  374. * @return void
  375. */
  376. protected static function parseHttpHeader($buffer)
  377. {
  378. $header_data = explode("\r\n", $buffer);
  379. $_SERVER = array();
  380. list($_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI'], $_SERVER['SERVER_PROTOCOL']) = explode(' ', $header_data[0]);
  381. unset($header_data[0]);
  382. foreach($header_data as $content)
  383. {
  384. // \r\n\r\n
  385. if(empty($content))
  386. {
  387. continue;
  388. }
  389. list($key, $value) = explode(':', $content, 2);
  390. $key = strtolower($key);
  391. $value = trim($value);
  392. switch($key)
  393. {
  394. // HTTP_HOST
  395. case 'host':
  396. $_SERVER['HTTP_HOST'] = $value;
  397. $tmp = explode(':', $value);
  398. $_SERVER['SERVER_NAME'] = $tmp[0];
  399. if(isset($tmp[1]))
  400. {
  401. $_SERVER['SERVER_PORT'] = $tmp[1];
  402. }
  403. break;
  404. // HTTP_COOKIE
  405. case 'cookie':
  406. $_SERVER['HTTP_COOKIE'] = $value;
  407. parse_str(str_replace('; ', '&', $_SERVER['HTTP_COOKIE']), $_COOKIE);
  408. break;
  409. // HTTP_USER_AGENT
  410. case 'user-agent':
  411. $_SERVER['HTTP_USER_AGENT'] = $value;
  412. break;
  413. // HTTP_REFERER
  414. case 'referer':
  415. $_SERVER['HTTP_REFERER'] = $value;
  416. break;
  417. case 'origin':
  418. $_SERVER['HTTP_ORIGIN'] = $value;
  419. break;
  420. }
  421. }
  422. // QUERY_STRING
  423. $_SERVER['QUERY_STRING'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);
  424. if($_SERVER['QUERY_STRING'])
  425. {
  426. // $GET
  427. parse_str($_SERVER['QUERY_STRING'], $_GET);
  428. }
  429. else
  430. {
  431. $_SERVER['QUERY_STRING'] = '';
  432. }
  433. }
  434. }