Websocket.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. <?php
  2. namespace Workerman\Protocols;
  3. /**
  4. * WebSocket 协议服务端解包和打包
  5. * @author walkor <walkor@workerman.net>
  6. */
  7. use Workerman\Connection\ConnectionInterface;
  8. class Websocket implements \Workerman\Protocols\ProtocolInterface
  9. {
  10. /**
  11. * websocket头部最小长度
  12. * @var int
  13. */
  14. const MIN_HEAD_LEN = 6;
  15. /**
  16. * websocket blob类型
  17. * @var char
  18. */
  19. const BINARY_TYPE_BLOB = "\x81";
  20. /**
  21. * websocket arraybuffer类型
  22. * @var char
  23. */
  24. const BINARY_TYPE_ARRAYBUFFER = "\x82";
  25. /**
  26. * 检查包的完整性
  27. * @param string $buffer
  28. */
  29. public static function input($buffer, ConnectionInterface $connection)
  30. {
  31. // 数据长度
  32. $recv_len = strlen($buffer);
  33. // 长度不够
  34. if($recv_len < self::MIN_HEAD_LEN)
  35. {
  36. return 0;
  37. }
  38. // 还没有握手
  39. if(empty($connection->websocketHandshake))
  40. {
  41. return self::dealHandshake($buffer, $connection);
  42. }
  43. // $connection->websocketCurrentFrameLength有值说明当前fin为0,则缓冲websocket帧数据
  44. if($connection->websocketCurrentFrameLength)
  45. {
  46. // 如果当前帧数据未收全,则继续收
  47. if($connection->websocketCurrentFrameLength > $recv_len)
  48. {
  49. // 返回0,因为不清楚完整的数据包长度,需要等待fin=1的帧
  50. return 0;
  51. }
  52. }
  53. else
  54. {
  55. $data_len = ord($buffer[1]) & 127;
  56. $firstbyte = ord($buffer[0]);
  57. $is_fin_frame = $firstbyte>>7;
  58. $opcode = $firstbyte & 0xf;
  59. switch($opcode)
  60. {
  61. // 附加数据帧 @todo 实现附加数据帧
  62. case 0x0:
  63. break;
  64. // 文本数据帧
  65. case 0x1:
  66. break;
  67. // 二进制数据帧
  68. case 0x2:
  69. break;
  70. // 关闭的包
  71. case 0x8:
  72. // 如果有设置onWebSocketClose回调,尝试执行
  73. if(isset($connection->onWebSocketClose))
  74. {
  75. call_user_func($connection->onWebSocketClose, $connection);
  76. }
  77. // 默认行为是关闭连接
  78. else
  79. {
  80. $connection->close();
  81. }
  82. return 0;
  83. // ping的包
  84. case 0x9:
  85. // 如果有设置onWebSocketPing回调,尝试执行
  86. if(isset($connection->onWebSocketPing))
  87. {
  88. call_user_func($connection->onWebSocketPing, $connection);
  89. }
  90. // 默认发送pong
  91. else
  92. {
  93. $connection->send(pack('H*', '8a00'), true);
  94. }
  95. // 从接受缓冲区中消费掉该数据包
  96. if(!$data_len)
  97. {
  98. $connection->consumeRecvBuffer(self::MIN_HEAD_LEN);
  99. return 0;
  100. }
  101. break;
  102. // pong的包
  103. case 0xa:
  104. // 如果有设置onWebSocketPong回调,尝试执行
  105. if(isset($connection->onWebSocketPong))
  106. {
  107. call_user_func($connection->onWebSocketPong, $connection);
  108. }
  109. // 从接受缓冲区中消费掉该数据包
  110. if(!$data_len)
  111. {
  112. $connection->consumeRecvBuffer(self::MIN_HEAD_LEN);
  113. return 0;
  114. }
  115. break;
  116. // 错误的opcode
  117. default :
  118. echo "error opcode $opcode and close websocket connection\n";
  119. $connection->close();
  120. return 0;
  121. }
  122. // websocket二进制数据
  123. $head_len = self::MIN_HEAD_LEN;
  124. if ($data_len === 126) {
  125. $head_len = 8;
  126. if($head_len > $recv_len)
  127. {
  128. return 0;
  129. }
  130. $pack = unpack('ntotal_len', substr($buffer, 2, 2));
  131. $data_len = $pack['total_len'];
  132. } else if ($data_len === 127) {
  133. $head_len = 14;
  134. if($head_len > $recv_len)
  135. {
  136. return 0;
  137. }
  138. $arr = unpack('N2', substr($buffer, 2, 8));
  139. $data_len = $arr[1]*4294967296 + $arr[2];
  140. }
  141. $current_frame_length = $head_len + $data_len;
  142. if($is_fin_frame)
  143. {
  144. return $current_frame_length;
  145. }
  146. else
  147. {
  148. $connection->websocketCurrentFrameLength = $current_frame_length;
  149. }
  150. }
  151. // 收到的数据刚好是一个frame
  152. if($connection->websocketCurrentFrameLength == $recv_len)
  153. {
  154. self::decode($buffer, $connection);
  155. $connection->consumeRecvBuffer($connection->websocketCurrentFrameLength);
  156. $connection->websocketCurrentFrameLength = 0;
  157. return 0;
  158. }
  159. // 收到的数据大于一个frame
  160. elseif($connection->websocketCurrentFrameLength < $recv_len)
  161. {
  162. self::decode(substr($buffer, 0, $connection->websocketCurrentFrameLength), $connection);
  163. $connection->consumeRecvBuffer($connection->websocketCurrentFrameLength);
  164. $current_frame_length = $connection->websocketCurrentFrameLength;
  165. $connection->websocketCurrentFrameLength = 0;
  166. // 继续读取下一个frame
  167. return self::input(substr($buffer, $current_frame_length), $connection);
  168. }
  169. // 收到的数据不足一个frame
  170. else
  171. {
  172. return 0;
  173. }
  174. }
  175. /**
  176. * 打包
  177. * @param string $buffer
  178. * @return string
  179. */
  180. public static function encode($buffer, ConnectionInterface $connection)
  181. {
  182. $len = strlen($buffer);
  183. // 还没握手不能发数据
  184. if(empty($connection->websocketHandshake))
  185. {
  186. $connection->send("HTTP/1.1 400 Bad Request\r\n\r\n<b>400 Bad Request</b><br>Send data before handshake. ", true);
  187. $connection->close();
  188. return false;
  189. }
  190. $first_byte = $connection->websocketType;
  191. if($len<=125)
  192. {
  193. return $first_byte.chr($len).$buffer;
  194. }
  195. else if($len<=65535)
  196. {
  197. return $first_byte.chr(126).pack("n", $len).$buffer;
  198. }
  199. else
  200. {
  201. return $first_byte.chr(127).pack("xxxxN", $len).$buffer;
  202. }
  203. }
  204. /**
  205. * 解包
  206. * @param string $buffer
  207. * @return string
  208. */
  209. public static function decode($buffer, ConnectionInterface $connection)
  210. {
  211. $len = $masks = $data = $decoded = null;
  212. $len = ord($buffer[1]) & 127;
  213. if ($len === 126) {
  214. $masks = substr($buffer, 4, 4);
  215. $data = substr($buffer, 8);
  216. } else if ($len === 127) {
  217. $masks = substr($buffer, 10, 4);
  218. $data = substr($buffer, 14);
  219. } else {
  220. $masks = substr($buffer, 2, 4);
  221. $data = substr($buffer, 6);
  222. }
  223. for ($index = 0; $index < strlen($data); $index++) {
  224. $decoded .= $data[$index] ^ $masks[$index % 4];
  225. }
  226. if($connection->websocketCurrentFrameLength)
  227. {
  228. $connection->websocketDataBuffer .= $decoded;
  229. return $connection->websocketDataBuffer;
  230. }
  231. else
  232. {
  233. $decoded = $connection->websocketDataBuffer . $decoded;
  234. $connection->websocketDataBuffer = '';
  235. return $decoded;
  236. }
  237. }
  238. /**
  239. * 处理websocket握手
  240. * @param string $buffer
  241. * @param TcpConnection $connection
  242. * @return int
  243. */
  244. protected static function dealHandshake($buffer, $connection)
  245. {
  246. // 握手阶段客户端发送HTTP协议
  247. if(0 === strpos($buffer, 'GET'))
  248. {
  249. // 判断\r\n\r\n边界
  250. $heder_end_pos = strpos($buffer, "\r\n\r\n");
  251. if(!$heder_end_pos)
  252. {
  253. return 0;
  254. }
  255. // 解析Sec-WebSocket-Key
  256. $Sec_WebSocket_Key = '';
  257. if(preg_match("/Sec-WebSocket-Key: *(.*?)\r\n/", $buffer, $match))
  258. {
  259. $Sec_WebSocket_Key = $match[1];
  260. }
  261. else
  262. {
  263. $connection->send("HTTP/1.1 400 Bad Request\r\n\r\n<b>400 Bad Request</b><br>Sec-WebSocket-Key not found", true);
  264. $connection->close();
  265. return 0;
  266. }
  267. $new_key = base64_encode(sha1($Sec_WebSocket_Key."258EAFA5-E914-47DA-95CA-C5AB0DC85B11",true));
  268. // 握手返回的数据
  269. $new_message = "HTTP/1.1 101 Switching Protocols\r\n";
  270. $new_message .= "Upgrade: websocket\r\n";
  271. $new_message .= "Sec-WebSocket-Version: 13\r\n";
  272. $new_message .= "Connection: Upgrade\r\n";
  273. $new_message .= "Sec-WebSocket-Accept: " . $new_key . "\r\n\r\n";
  274. $connection->websocketHandshake = true;
  275. $connection->websocketDataBuffer = '';
  276. $connection->websocketCurrentFrameLength = 0;
  277. $connection->websocketCurrentFrameBuffer = '';
  278. $connection->consumeRecvBuffer(strlen($buffer));
  279. $connection->send($new_message, true);
  280. // blob or arraybuffer
  281. $connection->websocketType = self::BINARY_TYPE_BLOB;
  282. // 如果有设置onWebSocketConnect回调,尝试执行
  283. if(isset($connection->onWebSocketConnect))
  284. {
  285. self::parseHttpHeader($buffer);
  286. try
  287. {
  288. call_user_func($connection->onWebSocketConnect, $connection, $buffer);
  289. }
  290. catch(\Exception $e)
  291. {
  292. echo $e;
  293. }
  294. $_GET = $_COOKIE = $_SERVER = array();
  295. }
  296. return 0;
  297. }
  298. // 如果是flash的policy-file-request
  299. elseif(0 === strpos($buffer,'<polic'))
  300. {
  301. $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";
  302. $connection->send($policy_xml, true);
  303. $connection->consumeRecvBuffer(strlen($buffer));
  304. return 0;
  305. }
  306. // 出错
  307. $connection->send("HTTP/1.1 400 Bad Request\r\n\r\n<b>400 Bad Request</b><br>Invalid handshake data for websocket. ", true);
  308. $connection->close();
  309. return 0;
  310. }
  311. /**
  312. * 从header中获取
  313. * @param string $buffer
  314. * @return void
  315. */
  316. protected static function parseHttpHeader($buffer)
  317. {
  318. $header_data = explode("\r\n", $buffer);
  319. $_SERVER = array();
  320. list($_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI'], $_SERVER['SERVER_PROTOCOL']) = explode(' ', $header_data[0]);
  321. unset($header_data[0]);
  322. foreach($header_data as $content)
  323. {
  324. // \r\n\r\n
  325. if(empty($content))
  326. {
  327. continue;
  328. }
  329. list($key, $value) = explode(':', $content, 2);
  330. $key = strtolower($key);
  331. $value = trim($value);
  332. switch($key)
  333. {
  334. // HTTP_HOST
  335. case 'host':
  336. $_SERVER['HTTP_HOST'] = $value;
  337. $tmp = explode(':', $value);
  338. $_SERVER['SERVER_NAME'] = $tmp[0];
  339. if(isset($tmp[1]))
  340. {
  341. $_SERVER['SERVER_PORT'] = $tmp[1];
  342. }
  343. break;
  344. // HTTP_COOKIE
  345. case 'cookie':
  346. $_SERVER['HTTP_COOKIE'] = $value;
  347. parse_str(str_replace('; ', '&', $_SERVER['HTTP_COOKIE']), $_COOKIE);
  348. break;
  349. // HTTP_USER_AGENT
  350. case 'user-agent':
  351. $_SERVER['HTTP_USER_AGENT'] = $value;
  352. break;
  353. // HTTP_REFERER
  354. case 'referer':
  355. $_SERVER['HTTP_REFERER'] = $value;
  356. break;
  357. case 'origin':
  358. $_SERVER['HTTP_ORIGIN'] = $value;
  359. break;
  360. }
  361. }
  362. // QUERY_STRING
  363. $_SERVER['QUERY_STRING'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);
  364. if($_SERVER['QUERY_STRING'])
  365. {
  366. // $GET
  367. parse_str($_SERVER['QUERY_STRING'], $_GET);
  368. }
  369. else
  370. {
  371. $_SERVER['QUERY_STRING'] = '';
  372. }
  373. }
  374. }