WebSocket.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. #if !BESTHTTP_DISABLE_WEBSOCKET
  2. using System;
  3. using System.Text;
  4. using BestHTTP.Extensions;
  5. using BestHTTP.Connections;
  6. using BestHTTP.Logger;
  7. using BestHTTP.PlatformSupport.Memory;
  8. #if !UNITY_WEBGL || UNITY_EDITOR
  9. using BestHTTP.WebSocket.Frames;
  10. using BestHTTP.WebSocket.Extensions;
  11. #endif
  12. namespace BestHTTP.WebSocket
  13. {
  14. public sealed class WebSocket
  15. {
  16. /// <summary>
  17. /// Maximum payload size of a websocket frame. Its default value is 32 KiB.
  18. /// </summary>
  19. public static uint MaxFragmentSize = UInt16.MaxValue / 2;
  20. #if !UNITY_WEBGL || UNITY_EDITOR
  21. public static IExtension[] GetDefaultExtensions()
  22. {
  23. #if !BESTHTTP_DISABLE_GZIP
  24. return new IExtension[] { new PerMessageCompression(/*compression level: */ Decompression.Zlib.CompressionLevel.Default,
  25. /*clientNoContextTakeover: */ false,
  26. /*serverNoContextTakeover: */ false,
  27. /*clientMaxWindowBits: */ Decompression.Zlib.ZlibConstants.WindowBitsMax,
  28. /*desiredServerMaxWindowBits: */ Decompression.Zlib.ZlibConstants.WindowBitsMax,
  29. /*minDatalengthToCompress: */ PerMessageCompression.MinDataLengthToCompressDefault) };
  30. #else
  31. return null;
  32. #endif
  33. }
  34. #endif
  35. public WebSocketStates State { get { return this.implementation.State; } }
  36. /// <summary>
  37. /// The connection to the WebSocket server is open.
  38. /// </summary>
  39. public bool IsOpen { get { return this.implementation.IsOpen; } }
  40. /// <summary>
  41. /// Data waiting to be written to the wire.
  42. /// </summary>
  43. public int BufferedAmount { get { return this.implementation.BufferedAmount; } }
  44. #if !UNITY_WEBGL || UNITY_EDITOR
  45. /// <summary>
  46. /// Set to true to start a new thread to send Pings to the WebSocket server
  47. /// </summary>
  48. public bool StartPingThread { get; set; }
  49. /// <summary>
  50. /// The delay between two Pings in milliseconds. Minimum value is 100ms, default is 10 seconds.
  51. /// </summary>
  52. public int PingFrequency { get; set; }
  53. /// <summary>
  54. /// If StartPingThread set to true, the plugin will close the connection and emit an OnError event if no
  55. /// message is received from the server in the given time. Its default value is 2 sec.
  56. /// </summary>
  57. public TimeSpan CloseAfterNoMessage { get; set; }
  58. /// <summary>
  59. /// The internal HTTPRequest object.
  60. /// </summary>
  61. public HTTPRequest InternalRequest { get { return this.implementation.InternalRequest; } }
  62. /// <summary>
  63. /// IExtension implementations the plugin will negotiate with the server to use.
  64. /// </summary>
  65. public IExtension[] Extensions { get; private set; }
  66. /// <summary>
  67. /// Latency calculated from the ping-pong message round-trip times.
  68. /// </summary>
  69. public int Latency { get { return this.implementation.Latency; } }
  70. /// <summary>
  71. /// When we received the last message from the server.
  72. /// </summary>
  73. public DateTime LastMessageReceived { get { return this.implementation.LastMessageReceived; } }
  74. /// <summary>
  75. /// When the Websocket Over HTTP/2 implementation fails to connect and EnableImplementationFallback is true, the plugin tries to fall back to the HTTP/1 implementation.
  76. /// When this happens a new InternalRequest is created and all previous custom modifications (like added headers) are lost. With OnInternalRequestCreated these modifications can be reapplied.
  77. /// </summary>
  78. public Action<WebSocket, HTTPRequest> OnInternalRequestCreated;
  79. #endif
  80. /// <summary>
  81. /// Called when the connection to the WebSocket server is established.
  82. /// </summary>
  83. public OnWebSocketOpenDelegate OnOpen;
  84. /// <summary>
  85. /// Called when a new textual message is received from the server.
  86. /// </summary>
  87. public OnWebSocketMessageDelegate OnMessage;
  88. /// <summary>
  89. /// Called when a new binary message is received from the server.
  90. /// </summary>
  91. public OnWebSocketBinaryDelegate OnBinary;
  92. /// <summary>
  93. /// Called when a Binary message received. It's a more performant version than the OnBinary event, as the memory will be reused.
  94. /// </summary>
  95. public OnWebSocketBinaryNoAllocDelegate OnBinaryNoAlloc;
  96. /// <summary>
  97. /// Called when the WebSocket connection is closed.
  98. /// </summary>
  99. public OnWebSocketClosedDelegate OnClosed;
  100. /// <summary>
  101. /// Called when an error is encountered. The parameter will be the description of the error.
  102. /// </summary>
  103. public OnWebSocketErrorDelegate OnError;
  104. #if !UNITY_WEBGL || UNITY_EDITOR
  105. /// <summary>
  106. /// Called when an incomplete frame received. No attempt will be made to reassemble these fragments internally, and no reference are stored after this event to this frame.
  107. /// </summary>
  108. public OnWebSocketIncompleteFrameDelegate OnIncompleteFrame;
  109. #endif
  110. /// <summary>
  111. /// Logging context of this websocket instance.
  112. /// </summary>
  113. public LoggingContext Context { get; private set; }
  114. /// <summary>
  115. /// The underlying, real implementation.
  116. /// </summary>
  117. private WebSocketBaseImplementation implementation;
  118. /// <summary>
  119. /// Creates a WebSocket instance from the given uri.
  120. /// </summary>
  121. /// <param name="uri">The uri of the WebSocket server</param>
  122. public WebSocket(Uri uri)
  123. :this(uri, string.Empty, string.Empty)
  124. {
  125. #if (!UNITY_WEBGL || UNITY_EDITOR)
  126. this.Extensions = WebSocket.GetDefaultExtensions();
  127. #endif
  128. }
  129. #if !UNITY_WEBGL || UNITY_EDITOR
  130. public WebSocket(Uri uri, string origin, string protocol)
  131. :this(uri, origin, protocol, null)
  132. {
  133. #if (!UNITY_WEBGL || UNITY_EDITOR)
  134. this.Extensions = WebSocket.GetDefaultExtensions();
  135. #endif
  136. }
  137. #endif
  138. /// <summary>
  139. /// Creates a WebSocket instance from the given uri, protocol and origin.
  140. /// </summary>
  141. /// <param name="uri">The uri of the WebSocket server</param>
  142. /// <param name="origin">Servers that are not intended to process input from any web page but only for certain sites SHOULD verify the |Origin| field is an origin they expect.
  143. /// If the origin indicated is unacceptable to the server, then it SHOULD respond to the WebSocket handshake with a reply containing HTTP 403 Forbidden status code.</param>
  144. /// <param name="protocol">The application-level protocol that the client want to use(eg. "chat", "leaderboard", etc.). Can be null or empty string if not used.</param>
  145. /// <param name="extensions">Optional IExtensions implementations</param>
  146. public WebSocket(Uri uri, string origin, string protocol
  147. #if !UNITY_WEBGL || UNITY_EDITOR
  148. , params IExtension[] extensions
  149. #endif
  150. )
  151. {
  152. this.Context = new LoggingContext(this);
  153. #if !UNITY_WEBGL || UNITY_EDITOR
  154. this.Extensions = extensions;
  155. #endif
  156. SelectImplementation(uri, origin, protocol);
  157. // Under WebGL when only the WebSocket protocol is used Setup() isn't called, so we have to call it here.
  158. HTTPManager.Setup();
  159. }
  160. internal WebSocketBaseImplementation SelectImplementation(Uri uri, string origin, string protocol)
  161. {
  162. #if !UNITY_WEBGL || UNITY_EDITOR
  163. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && !BESTHTTP_DISABLE_HTTP2
  164. if (HTTPManager.HTTP2Settings.WebSocketOverHTTP2Settings.EnableWebSocketOverHTTP2 && HTTPProtocolFactory.IsSecureProtocol(uri))
  165. {
  166. // Try to find a HTTP/2 connection that supports the connect protocol.
  167. var connectionKey = Core.HostDefinition.GetKeyFor(new UriBuilder("https", uri.Host, uri.Port).Uri
  168. #if !BESTHTTP_DISABLE_PROXY && (!UNITY_WEBGL || UNITY_EDITOR)
  169. , GetProxy(uri)
  170. #endif
  171. );
  172. var con = BestHTTP.Core.HostManager.GetHost(uri.Host).GetHostDefinition(connectionKey).Find(c => {
  173. var httpConnection = c as HTTPConnection;
  174. var http2Handler = httpConnection?.requestHandler as Connections.HTTP2.HTTP2Handler;
  175. return http2Handler != null && http2Handler.settings.RemoteSettings[Connections.HTTP2.HTTP2Settings.ENABLE_CONNECT_PROTOCOL] != 0;
  176. });
  177. if (con != null)
  178. {
  179. HTTPManager.Logger.Information("WebSocket", "Connection with enabled Connect Protocol found!", this.Context);
  180. var httpConnection = con as HTTPConnection;
  181. var http2Handler = httpConnection?.requestHandler as Connections.HTTP2.HTTP2Handler;
  182. this.implementation = new OverHTTP2(this, uri, origin, protocol);
  183. }
  184. }
  185. #endif
  186. if (this.implementation == null)
  187. this.implementation = new OverHTTP1(this, uri, origin, protocol);
  188. #else
  189. this.implementation = new WebGLBrowser(this, uri, origin, protocol);
  190. #endif
  191. return this.implementation;
  192. }
  193. #if !UNITY_WEBGL || UNITY_EDITOR
  194. internal void FallbackToHTTP1()
  195. {
  196. HTTPManager.Logger.Verbose("WebSocket", "FallbackToHTTP1", this.Context);
  197. if (this.implementation == null)
  198. return;
  199. this.implementation = new OverHTTP1(this, this.implementation.Uri, this.implementation.Origin, this.implementation.Protocol);
  200. this.implementation.StartOpen();
  201. }
  202. #endif
  203. /// <summary>
  204. /// Start the opening process.
  205. /// </summary>
  206. public void Open()
  207. {
  208. this.implementation.StartOpen();
  209. }
  210. /// <summary>
  211. /// It will send the given message to the server in one frame.
  212. /// </summary>
  213. public void Send(string message)
  214. {
  215. if (!IsOpen)
  216. return;
  217. this.implementation.Send(message);
  218. }
  219. /// <summary>
  220. /// It will send the given data to the server in one frame.
  221. /// </summary>
  222. public void Send(byte[] buffer)
  223. {
  224. if (!IsOpen)
  225. return;
  226. this.implementation.Send(buffer);
  227. }
  228. /// <summary>
  229. /// Will send count bytes from a byte array, starting from offset.
  230. /// </summary>
  231. public void Send(byte[] buffer, ulong offset, ulong count)
  232. {
  233. if (!IsOpen)
  234. return;
  235. this.implementation.Send(buffer, offset, count);
  236. }
  237. /// <summary>
  238. /// Will send the data in one or more binary frame and takes ownership over it calling BufferPool.Release when sent.
  239. /// </summary>
  240. public void SendAsBinary(BufferSegment data)
  241. {
  242. if (!IsOpen)
  243. {
  244. BufferPool.Release(data);
  245. return;
  246. }
  247. this.implementation.SendAsBinary(data);
  248. }
  249. /// <summary>
  250. /// Will send data as a text frame and takes owenership over the memory region releasing it to the BufferPool as soon as possible.
  251. /// </summary>
  252. public void SendAsText(BufferSegment data)
  253. {
  254. if (!IsOpen)
  255. {
  256. BufferPool.Release(data);
  257. return;
  258. }
  259. this.implementation.SendAsText(data);
  260. }
  261. #if !UNITY_WEBGL || UNITY_EDITOR
  262. /// <summary>
  263. /// It will send the given frame to the server.
  264. /// </summary>
  265. public void Send(WebSocketFrame frame)
  266. {
  267. if (!IsOpen)
  268. return;
  269. this.implementation.Send(frame);
  270. }
  271. #endif
  272. /// <summary>
  273. /// It will initiate the closing of the connection to the server.
  274. /// </summary>
  275. public void Close()
  276. {
  277. if (State >= WebSocketStates.Closing)
  278. return;
  279. this.implementation.StartClose(1000, "Bye!");
  280. }
  281. /// <summary>
  282. /// It will initiate the closing of the connection to the server sending the given code and message.
  283. /// </summary>
  284. public void Close(UInt16 code, string message)
  285. {
  286. if (!IsOpen)
  287. return;
  288. this.implementation.StartClose(code, message);
  289. }
  290. #if !BESTHTTP_DISABLE_PROXY && (!UNITY_WEBGL || UNITY_EDITOR)
  291. internal Proxy GetProxy(Uri uri)
  292. {
  293. // WebSocket is not a request-response based protocol, so we need a 'tunnel' through the proxy
  294. HTTPProxy proxy = HTTPManager.Proxy as HTTPProxy;
  295. if (proxy != null && proxy.UseProxyForAddress(uri))
  296. proxy = new HTTPProxy(proxy.Address,
  297. proxy.Credentials,
  298. false, /*turn on 'tunneling'*/
  299. false, /*sendWholeUri*/
  300. proxy.NonTransparentForHTTPS);
  301. return proxy;
  302. }
  303. #endif
  304. #if !UNITY_WEBGL || UNITY_EDITOR
  305. public static BufferSegment EncodeCloseData(UInt16 code, string message)
  306. {
  307. //If there is a body, the first two bytes of the body MUST be a 2-byte unsigned integer
  308. // (in network byte order) representing a status code with value /code/ defined in Section 7.4 (http://tools.ietf.org/html/rfc6455#section-7.4). Following the 2-byte integer,
  309. // the body MAY contain UTF-8-encoded data with value /reason/, the interpretation of which is not defined by this specification.
  310. // This data is not necessarily human readable but may be useful for debugging or passing information relevant to the script that opened the connection.
  311. int msgLen = Encoding.UTF8.GetByteCount(message);
  312. using (var ms = new BufferPoolMemoryStream(2 + msgLen))
  313. {
  314. byte[] buff = BitConverter.GetBytes(code);
  315. if (BitConverter.IsLittleEndian)
  316. Array.Reverse(buff, 0, buff.Length);
  317. ms.Write(buff, 0, buff.Length);
  318. buff = Encoding.UTF8.GetBytes(message);
  319. ms.Write(buff, 0, buff.Length);
  320. buff = ms.ToArray();
  321. return buff.AsBuffer(buff.Length);
  322. }
  323. }
  324. internal static string GetSecKey(object[] from)
  325. {
  326. const int keysLength = 16;
  327. byte[] keys = BufferPool.Get(keysLength, true);
  328. int pos = 0;
  329. for (int i = 0; i < from.Length; ++i)
  330. {
  331. byte[] hash = BitConverter.GetBytes((Int32)from[i].GetHashCode());
  332. for (int cv = 0; cv < hash.Length && pos < keysLength; ++cv)
  333. keys[pos++] = hash[cv];
  334. }
  335. var result = Convert.ToBase64String(keys, 0, keysLength);
  336. BufferPool.Release(keys);
  337. return result;
  338. }
  339. #endif
  340. }
  341. }
  342. #endif