WebSocketFrame.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Text;
  6. namespace SocketHttpListener
  7. {
  8. internal class WebSocketFrame : IEnumerable<byte>
  9. {
  10. #region Private Fields
  11. private byte[] _extPayloadLength;
  12. private Fin _fin;
  13. private Mask _mask;
  14. private byte[] _maskingKey;
  15. private Opcode _opcode;
  16. private PayloadData _payloadData;
  17. private byte _payloadLength;
  18. private Rsv _rsv1;
  19. private Rsv _rsv2;
  20. private Rsv _rsv3;
  21. #endregion
  22. #region Internal Fields
  23. internal static readonly byte[] EmptyUnmaskPingData;
  24. #endregion
  25. #region Static Constructor
  26. static WebSocketFrame()
  27. {
  28. EmptyUnmaskPingData = CreatePingFrame(Mask.Unmask).ToByteArray();
  29. }
  30. #endregion
  31. #region Private Constructors
  32. private WebSocketFrame()
  33. {
  34. }
  35. #endregion
  36. #region Internal Constructors
  37. internal WebSocketFrame(Opcode opcode, PayloadData payload)
  38. : this(Fin.Final, opcode, Mask.Mask, payload, false)
  39. {
  40. }
  41. internal WebSocketFrame(Opcode opcode, Mask mask, PayloadData payload)
  42. : this(Fin.Final, opcode, mask, payload, false)
  43. {
  44. }
  45. internal WebSocketFrame(Fin fin, Opcode opcode, Mask mask, PayloadData payload)
  46. : this(fin, opcode, mask, payload, false)
  47. {
  48. }
  49. internal WebSocketFrame(
  50. Fin fin, Opcode opcode, Mask mask, PayloadData payload, bool compressed)
  51. {
  52. _fin = fin;
  53. _rsv1 = isData(opcode) && compressed ? Rsv.On : Rsv.Off;
  54. _rsv2 = Rsv.Off;
  55. _rsv3 = Rsv.Off;
  56. _opcode = opcode;
  57. _mask = mask;
  58. var len = payload.Length;
  59. if (len < 126)
  60. {
  61. _payloadLength = (byte)len;
  62. _extPayloadLength = new byte[0];
  63. }
  64. else if (len < 0x010000)
  65. {
  66. _payloadLength = (byte)126;
  67. _extPayloadLength = ((ushort)len).ToByteArrayInternally(ByteOrder.Big);
  68. }
  69. else
  70. {
  71. _payloadLength = (byte)127;
  72. _extPayloadLength = len.ToByteArrayInternally(ByteOrder.Big);
  73. }
  74. if (mask == Mask.Mask)
  75. {
  76. _maskingKey = createMaskingKey();
  77. payload.Mask(_maskingKey);
  78. }
  79. else
  80. {
  81. _maskingKey = new byte[0];
  82. }
  83. _payloadData = payload;
  84. }
  85. #endregion
  86. #region Public Properties
  87. public byte[] ExtendedPayloadLength
  88. {
  89. get
  90. {
  91. return _extPayloadLength;
  92. }
  93. }
  94. public Fin Fin
  95. {
  96. get
  97. {
  98. return _fin;
  99. }
  100. }
  101. public bool IsBinary
  102. {
  103. get
  104. {
  105. return _opcode == Opcode.Binary;
  106. }
  107. }
  108. public bool IsClose
  109. {
  110. get
  111. {
  112. return _opcode == Opcode.Close;
  113. }
  114. }
  115. public bool IsCompressed
  116. {
  117. get
  118. {
  119. return _rsv1 == Rsv.On;
  120. }
  121. }
  122. public bool IsContinuation
  123. {
  124. get
  125. {
  126. return _opcode == Opcode.Cont;
  127. }
  128. }
  129. public bool IsControl
  130. {
  131. get
  132. {
  133. return _opcode == Opcode.Close || _opcode == Opcode.Ping || _opcode == Opcode.Pong;
  134. }
  135. }
  136. public bool IsData
  137. {
  138. get
  139. {
  140. return _opcode == Opcode.Binary || _opcode == Opcode.Text;
  141. }
  142. }
  143. public bool IsFinal
  144. {
  145. get
  146. {
  147. return _fin == Fin.Final;
  148. }
  149. }
  150. public bool IsFragmented
  151. {
  152. get
  153. {
  154. return _fin == Fin.More || _opcode == Opcode.Cont;
  155. }
  156. }
  157. public bool IsMasked
  158. {
  159. get
  160. {
  161. return _mask == Mask.Mask;
  162. }
  163. }
  164. public bool IsPerMessageCompressed
  165. {
  166. get
  167. {
  168. return (_opcode == Opcode.Binary || _opcode == Opcode.Text) && _rsv1 == Rsv.On;
  169. }
  170. }
  171. public bool IsPing
  172. {
  173. get
  174. {
  175. return _opcode == Opcode.Ping;
  176. }
  177. }
  178. public bool IsPong
  179. {
  180. get
  181. {
  182. return _opcode == Opcode.Pong;
  183. }
  184. }
  185. public bool IsText
  186. {
  187. get
  188. {
  189. return _opcode == Opcode.Text;
  190. }
  191. }
  192. public ulong Length
  193. {
  194. get
  195. {
  196. return 2 + (ulong)(_extPayloadLength.Length + _maskingKey.Length) + _payloadData.Length;
  197. }
  198. }
  199. public Mask Mask
  200. {
  201. get
  202. {
  203. return _mask;
  204. }
  205. }
  206. public byte[] MaskingKey
  207. {
  208. get
  209. {
  210. return _maskingKey;
  211. }
  212. }
  213. public Opcode Opcode
  214. {
  215. get
  216. {
  217. return _opcode;
  218. }
  219. }
  220. public PayloadData PayloadData
  221. {
  222. get
  223. {
  224. return _payloadData;
  225. }
  226. }
  227. public byte PayloadLength
  228. {
  229. get
  230. {
  231. return _payloadLength;
  232. }
  233. }
  234. public Rsv Rsv1
  235. {
  236. get
  237. {
  238. return _rsv1;
  239. }
  240. }
  241. public Rsv Rsv2
  242. {
  243. get
  244. {
  245. return _rsv2;
  246. }
  247. }
  248. public Rsv Rsv3
  249. {
  250. get
  251. {
  252. return _rsv3;
  253. }
  254. }
  255. #endregion
  256. #region Private Methods
  257. private byte[] createMaskingKey()
  258. {
  259. var key = new byte[4];
  260. var rand = new Random();
  261. rand.NextBytes(key);
  262. return key;
  263. }
  264. private static bool isControl(Opcode opcode)
  265. {
  266. return opcode == Opcode.Close || opcode == Opcode.Ping || opcode == Opcode.Pong;
  267. }
  268. private static bool isData(Opcode opcode)
  269. {
  270. return opcode == Opcode.Text || opcode == Opcode.Binary;
  271. }
  272. private static WebSocketFrame read(byte[] header, Stream stream, bool unmask)
  273. {
  274. /* Header */
  275. // FIN
  276. var fin = (header[0] & 0x80) == 0x80 ? Fin.Final : Fin.More;
  277. // RSV1
  278. var rsv1 = (header[0] & 0x40) == 0x40 ? Rsv.On : Rsv.Off;
  279. // RSV2
  280. var rsv2 = (header[0] & 0x20) == 0x20 ? Rsv.On : Rsv.Off;
  281. // RSV3
  282. var rsv3 = (header[0] & 0x10) == 0x10 ? Rsv.On : Rsv.Off;
  283. // Opcode
  284. var opcode = (Opcode)(header[0] & 0x0f);
  285. // MASK
  286. var mask = (header[1] & 0x80) == 0x80 ? Mask.Mask : Mask.Unmask;
  287. // Payload Length
  288. var payloadLen = (byte)(header[1] & 0x7f);
  289. // Check if correct frame.
  290. var incorrect = isControl(opcode) && fin == Fin.More
  291. ? "A control frame is fragmented."
  292. : !isData(opcode) && rsv1 == Rsv.On
  293. ? "A non data frame is compressed."
  294. : null;
  295. if (incorrect != null)
  296. throw new WebSocketException(CloseStatusCode.IncorrectData, incorrect);
  297. // Check if consistent frame.
  298. if (isControl(opcode) && payloadLen > 125)
  299. throw new WebSocketException(
  300. CloseStatusCode.InconsistentData,
  301. "The length of payload data of a control frame is greater than 125 bytes.");
  302. var frame = new WebSocketFrame();
  303. frame._fin = fin;
  304. frame._rsv1 = rsv1;
  305. frame._rsv2 = rsv2;
  306. frame._rsv3 = rsv3;
  307. frame._opcode = opcode;
  308. frame._mask = mask;
  309. frame._payloadLength = payloadLen;
  310. /* Extended Payload Length */
  311. var size = payloadLen < 126
  312. ? 0
  313. : payloadLen == 126
  314. ? 2
  315. : 8;
  316. var extPayloadLen = size > 0 ? stream.ReadBytes(size) : new byte[0];
  317. if (size > 0 && extPayloadLen.Length != size)
  318. throw new WebSocketException(
  319. "The 'Extended Payload Length' of a frame cannot be read from the data source.");
  320. frame._extPayloadLength = extPayloadLen;
  321. /* Masking Key */
  322. var masked = mask == Mask.Mask;
  323. var maskingKey = masked ? stream.ReadBytes(4) : new byte[0];
  324. if (masked && maskingKey.Length != 4)
  325. throw new WebSocketException(
  326. "The 'Masking Key' of a frame cannot be read from the data source.");
  327. frame._maskingKey = maskingKey;
  328. /* Payload Data */
  329. ulong len = payloadLen < 126
  330. ? payloadLen
  331. : payloadLen == 126
  332. ? extPayloadLen.ToUInt16(ByteOrder.Big)
  333. : extPayloadLen.ToUInt64(ByteOrder.Big);
  334. byte[] data = null;
  335. if (len > 0)
  336. {
  337. // Check if allowable payload data length.
  338. if (payloadLen > 126 && len > PayloadData.MaxLength)
  339. throw new WebSocketException(
  340. CloseStatusCode.TooBig,
  341. "The length of 'Payload Data' of a frame is greater than the allowable length.");
  342. data = payloadLen > 126
  343. ? stream.ReadBytes((long)len, 1024)
  344. : stream.ReadBytes((int)len);
  345. //if (data.LongLength != (long)len)
  346. // throw new WebSocketException(
  347. // "The 'Payload Data' of a frame cannot be read from the data source.");
  348. }
  349. else
  350. {
  351. data = new byte[0];
  352. }
  353. var payload = new PayloadData(data, masked);
  354. if (masked && unmask)
  355. {
  356. payload.Mask(maskingKey);
  357. frame._mask = Mask.Unmask;
  358. frame._maskingKey = new byte[0];
  359. }
  360. frame._payloadData = payload;
  361. return frame;
  362. }
  363. #endregion
  364. #region Internal Methods
  365. internal static WebSocketFrame CreateCloseFrame(Mask mask, byte[] data)
  366. {
  367. return new WebSocketFrame(Opcode.Close, mask, new PayloadData(data));
  368. }
  369. internal static WebSocketFrame CreateCloseFrame(Mask mask, PayloadData payload)
  370. {
  371. return new WebSocketFrame(Opcode.Close, mask, payload);
  372. }
  373. internal static WebSocketFrame CreateCloseFrame(Mask mask, CloseStatusCode code, string reason)
  374. {
  375. return new WebSocketFrame(
  376. Opcode.Close, mask, new PayloadData(((ushort)code).Append(reason)));
  377. }
  378. internal static WebSocketFrame CreatePingFrame(Mask mask)
  379. {
  380. return new WebSocketFrame(Opcode.Ping, mask, new PayloadData());
  381. }
  382. internal static WebSocketFrame CreatePingFrame(Mask mask, byte[] data)
  383. {
  384. return new WebSocketFrame(Opcode.Ping, mask, new PayloadData(data));
  385. }
  386. internal static WebSocketFrame CreatePongFrame(Mask mask, PayloadData payload)
  387. {
  388. return new WebSocketFrame(Opcode.Pong, mask, payload);
  389. }
  390. internal static WebSocketFrame CreateWebSocketFrame(
  391. Fin fin, Opcode opcode, Mask mask, byte[] data, bool compressed)
  392. {
  393. return new WebSocketFrame(fin, opcode, mask, new PayloadData(data), compressed);
  394. }
  395. internal static WebSocketFrame Read(Stream stream)
  396. {
  397. return Read(stream, true);
  398. }
  399. internal static WebSocketFrame Read(Stream stream, bool unmask)
  400. {
  401. var header = stream.ReadBytes(2);
  402. if (header.Length != 2)
  403. throw new WebSocketException(
  404. "The header part of a frame cannot be read from the data source.");
  405. return read(header, stream, unmask);
  406. }
  407. internal static async void ReadAsync(
  408. Stream stream, bool unmask, Action<WebSocketFrame> completed, Action<Exception> error)
  409. {
  410. try
  411. {
  412. var header = await stream.ReadBytesAsync(2).ConfigureAwait(false);
  413. if (header.Length != 2)
  414. throw new WebSocketException(
  415. "The header part of a frame cannot be read from the data source.");
  416. var frame = read(header, stream, unmask);
  417. if (completed != null)
  418. completed(frame);
  419. }
  420. catch (Exception ex)
  421. {
  422. if (error != null)
  423. {
  424. error(ex);
  425. }
  426. }
  427. }
  428. #endregion
  429. #region Public Methods
  430. public IEnumerator<byte> GetEnumerator()
  431. {
  432. foreach (var b in ToByteArray())
  433. yield return b;
  434. }
  435. public void Print(bool dumped)
  436. {
  437. //Console.WriteLine(dumped ? dump(this) : print(this));
  438. }
  439. public byte[] ToByteArray()
  440. {
  441. using (var buff = new MemoryStream())
  442. {
  443. var header = (int)_fin;
  444. header = (header << 1) + (int)_rsv1;
  445. header = (header << 1) + (int)_rsv2;
  446. header = (header << 1) + (int)_rsv3;
  447. header = (header << 4) + (int)_opcode;
  448. header = (header << 1) + (int)_mask;
  449. header = (header << 7) + (int)_payloadLength;
  450. buff.Write(((ushort)header).ToByteArrayInternally(ByteOrder.Big), 0, 2);
  451. if (_payloadLength > 125)
  452. buff.Write(_extPayloadLength, 0, _extPayloadLength.Length);
  453. if (_mask == Mask.Mask)
  454. buff.Write(_maskingKey, 0, _maskingKey.Length);
  455. if (_payloadLength > 0)
  456. {
  457. var payload = _payloadData.ToByteArray();
  458. if (_payloadLength < 127)
  459. buff.Write(payload, 0, payload.Length);
  460. else
  461. buff.WriteBytes(payload);
  462. }
  463. return buff.ToArray();
  464. }
  465. }
  466. public override string ToString()
  467. {
  468. return BitConverter.ToString(ToByteArray());
  469. }
  470. #endregion
  471. #region Explicitly Implemented Interface Members
  472. IEnumerator IEnumerable.GetEnumerator()
  473. {
  474. return GetEnumerator();
  475. }
  476. #endregion
  477. }
  478. }