WebSocketSession.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.Specialized;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Security.Authentication;
  7. using System.Text;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using Microsoft.Extensions.Logging;
  11. using SuperSocket.Common;
  12. using SuperSocket.SocketBase;
  13. using SuperSocket.SocketBase.Command;
  14. using SuperSocket.SocketBase.Protocol;
  15. using SuperWebSocket.Protocol;
  16. using SuperWebSocket.SubProtocol;
  17. namespace SuperWebSocket
  18. {
  19. /// <summary>
  20. /// WebSocketSession basic interface
  21. /// </summary>
  22. public interface IWebSocketSession : IAppSession
  23. {
  24. /// <summary>
  25. /// Gets or sets the method.
  26. /// </summary>
  27. /// <value>
  28. /// The method.
  29. /// </value>
  30. string Method { get; set; }
  31. /// <summary>
  32. /// Gets the host.
  33. /// </summary>
  34. string Host { get; }
  35. /// <summary>
  36. /// Gets or sets the path.
  37. /// </summary>
  38. /// <value>
  39. /// The path.
  40. /// </value>
  41. string Path { get; set; }
  42. /// <summary>
  43. /// Gets or sets the HTTP version.
  44. /// </summary>
  45. /// <value>
  46. /// The HTTP version.
  47. /// </value>
  48. string HttpVersion { get; set; }
  49. /// <summary>
  50. /// Gets the sec web socket version.
  51. /// </summary>
  52. string SecWebSocketVersion { get; }
  53. /// <summary>
  54. /// Gets the origin.
  55. /// </summary>
  56. string Origin { get; }
  57. /// <summary>
  58. /// Gets the URI scheme.
  59. /// </summary>
  60. string UriScheme { get; }
  61. /// <summary>
  62. /// Gets a value indicating whether this <see cref="IWebSocketSession" /> is handshaked.
  63. /// </summary>
  64. /// <value>
  65. /// <c>true</c> if handshaked; otherwise, <c>false</c>.
  66. /// </value>
  67. bool Handshaked { get; }
  68. /// <summary>
  69. /// Sends the raw binary data to client.
  70. /// </summary>
  71. /// <param name="data">The data.</param>
  72. /// <param name="offset">The offset.</param>
  73. /// <param name="length">The length.</param>
  74. void SendRawData(byte[] data, int offset, int length);
  75. /// <summary>
  76. /// Try to send the raw binary data to client.
  77. /// </summary>
  78. /// <param name="data">The data.</param>
  79. /// <param name="offset">The offset.</param>
  80. /// <param name="length">The length.</param>
  81. /// <returns>if the data to be sent is queued, return true, else the queue is full, then return false</returns>
  82. bool TrySendRawData(byte[] data, int offset, int length);
  83. /// <summary>
  84. /// Gets the app server.
  85. /// </summary>
  86. new IWebSocketServer AppServer { get; }
  87. /// <summary>
  88. /// Gets or sets the protocol processor.
  89. /// </summary>
  90. /// <value>
  91. /// The protocol processor.
  92. /// </value>
  93. IProtocolProcessor ProtocolProcessor { get; set; }
  94. /// <summary>
  95. /// Gets the available sub protocol.
  96. /// </summary>
  97. /// <param name="protocol">The protocol.</param>
  98. /// <returns></returns>
  99. string GetAvailableSubProtocol(string protocol);
  100. }
  101. /// <summary>
  102. /// WebSocket AppSession
  103. /// </summary>
  104. public class WebSocketSession : WebSocketSession<WebSocketSession>
  105. {
  106. /// <summary>
  107. /// Gets the app server.
  108. /// </summary>
  109. public new WebSocketServer AppServer
  110. {
  111. get { return (WebSocketServer)base.AppServer; }
  112. }
  113. }
  114. /// <summary>
  115. /// WebSocket AppSession class
  116. /// </summary>
  117. /// <typeparam name="TWebSocketSession">The type of the web socket session.</typeparam>
  118. public class WebSocketSession<TWebSocketSession> : AppSession<TWebSocketSession, IWebSocketFragment>, IWebSocketSession, IAppSession
  119. where TWebSocketSession : WebSocketSession<TWebSocketSession>, new()
  120. {
  121. /// <summary>
  122. /// Gets or sets the method.
  123. /// </summary>
  124. /// <value>
  125. /// The method.
  126. /// </value>
  127. public string Method { get; set; }
  128. /// <summary>
  129. /// Gets or sets the path.
  130. /// </summary>
  131. /// <value>
  132. /// The path.
  133. /// </value>
  134. public string Path { get; set; }
  135. /// <summary>
  136. /// Gets or sets the HTTP version.
  137. /// </summary>
  138. /// <value>
  139. /// The HTTP version.
  140. /// </value>
  141. public string HttpVersion { get; set; }
  142. /// <summary>
  143. /// Gets the host.
  144. /// </summary>
  145. public string Host { get { return this.Items.GetValue<string>(WebSocketConstant.Host, string.Empty); } }
  146. /// <summary>
  147. /// Gets the origin.
  148. /// </summary>
  149. public string Origin { get; internal set; }
  150. /// <summary>
  151. /// Gets the upgrade.
  152. /// </summary>
  153. public string Upgrade { get { return this.Items.GetValue<string>(WebSocketConstant.Upgrade, string.Empty); } }
  154. /// <summary>
  155. /// Gets the connection.
  156. /// </summary>
  157. public string Connection { get { return this.Items.GetValue<string>(WebSocketConstant.Connection, string.Empty); } }
  158. /// <summary>
  159. /// Gets the sec web socket version.
  160. /// </summary>
  161. public string SecWebSocketVersion { get { return this.Items.GetValue<string>(WebSocketConstant.SecWebSocketVersion, string.Empty); } }
  162. /// <summary>
  163. /// Gets the sec web socket protocol.
  164. /// </summary>
  165. public string SecWebSocketProtocol { get { return this.Items.GetValue<string>(WebSocketConstant.SecWebSocketProtocol, string.Empty); } }
  166. internal List<WebSocketDataFrame> Frames { get; private set; }
  167. internal DateTime StartClosingHandshakeTime { get; private set; }
  168. private const string m_CurrentTokenSlotName = "CurrentRequestToken";
  169. internal LocalDataStoreSlot SetCurrentToken(string token)
  170. {
  171. var slot = Thread.GetNamedDataSlot(m_CurrentTokenSlotName);
  172. Thread.SetData(slot, token);
  173. return slot;
  174. }
  175. /// <summary>
  176. /// Gets the current token.
  177. /// </summary>
  178. public string CurrentToken
  179. {
  180. get
  181. {
  182. return Thread.GetData(Thread.GetNamedDataSlot(m_CurrentTokenSlotName)) as string;
  183. }
  184. }
  185. /// <summary>
  186. /// Gets the app server.
  187. /// </summary>
  188. public new WebSocketServer<TWebSocketSession> AppServer
  189. {
  190. get { return (WebSocketServer<TWebSocketSession>)base.AppServer; }
  191. }
  192. IWebSocketServer IWebSocketSession.AppServer
  193. {
  194. get { return (IWebSocketServer)base.AppServer; }
  195. }
  196. string IWebSocketSession.GetAvailableSubProtocol(string protocol)
  197. {
  198. if (string.IsNullOrEmpty(protocol))
  199. {
  200. SubProtocol = AppServer.DefaultSubProtocol;
  201. return string.Empty;
  202. }
  203. var arrNames = protocol.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
  204. if (protocol.ToLower().Contains("ocpp2.0"))
  205. {
  206. arrNames = new string[] { "ocpp2.0" };
  207. }
  208. foreach (var name in arrNames)
  209. {
  210. var subProtocol = AppServer.GetSubProtocol(name);
  211. if (subProtocol != null)
  212. {
  213. SubProtocol = subProtocol;
  214. return name;
  215. }
  216. }
  217. return string.Empty;
  218. }
  219. /// <summary>
  220. /// Gets the URI scheme, ws or wss
  221. /// </summary>
  222. public string UriScheme
  223. {
  224. get
  225. {
  226. if (SocketSession.SecureProtocol == SslProtocols.None)
  227. return WebSocketConstant.WsSchema;
  228. else
  229. return WebSocketConstant.WssSchema;
  230. }
  231. }
  232. /// <summary>
  233. /// Gets the sub protocol.
  234. /// </summary>
  235. public ISubProtocol<TWebSocketSession> SubProtocol { get; private set; }
  236. private bool m_Handshaked = false;
  237. /// <summary>
  238. /// Gets a value indicating whether this <see cref="IWebSocketSession" /> is handshaked.
  239. /// </summary>
  240. /// <value>
  241. /// <c>true</c> if handshaked; otherwise, <c>false</c>.
  242. /// </value>
  243. public bool Handshaked
  244. {
  245. get { return m_Handshaked; }
  246. }
  247. internal void OnHandshakeSuccess()
  248. {
  249. m_Handshaked = true;
  250. SetCookie();
  251. OnSessionStarted();
  252. AppServer.FireOnNewSessionConnected(this);
  253. }
  254. /// <summary>
  255. /// Gets a value indicating whether the session [in closing].
  256. /// </summary>
  257. /// <value>
  258. /// <c>true</c> if [in closing]; otherwise, <c>false</c>.
  259. /// </value>
  260. public bool InClosing { get; private set; }
  261. /// <summary>
  262. /// Called when [init].
  263. /// </summary>
  264. protected override void OnInit()
  265. {
  266. Frames = new List<WebSocketDataFrame>();
  267. base.OnInit();
  268. }
  269. void IAppSession.StartSession()
  270. {
  271. //Do nothing. Avoid firing thhe OnSessionStarted() method of base class
  272. }
  273. /// <summary>
  274. /// Sets the cookie.
  275. /// </summary>
  276. private void SetCookie()
  277. {
  278. string cookieValue = this.Items.GetValue<string>(WebSocketConstant.Cookie, string.Empty);
  279. if (string.IsNullOrEmpty(cookieValue))
  280. return;
  281. var cookies = new StringDictionary();
  282. this.Cookies = cookies;
  283. string[] pairs = cookieValue.Split(';');
  284. int pos;
  285. string key, value;
  286. foreach (var p in pairs)
  287. {
  288. pos = p.IndexOf('=');
  289. if (pos <= 0)
  290. continue;
  291. key = p.Substring(0, pos).Trim();
  292. pos += 1;
  293. if (pos < p.Length)
  294. value = p.Substring(pos).Trim();
  295. else
  296. value = string.Empty;
  297. if (string.IsNullOrEmpty(value))
  298. {
  299. cookies[key] = string.Empty;
  300. continue;
  301. }
  302. try
  303. {
  304. cookies[key] = Uri.UnescapeDataString(value);
  305. }
  306. catch (Exception e)
  307. {
  308. Logger.LogError(this, string.Format("Failed to read cookie, key: {0}, value: {1}.", key, value), e);
  309. }
  310. }
  311. }
  312. /// <summary>
  313. /// Gets the cookies.
  314. /// </summary>
  315. public StringDictionary Cookies { get; private set; }
  316. /// <summary>
  317. /// Sends the message to client.
  318. /// </summary>
  319. /// <param name="message">The message.</param>
  320. public override void Send(string message)
  321. {
  322. ProtocolProcessor.SendMessage(this, message);
  323. }
  324. /// <summary>
  325. /// Tries to send.
  326. /// </summary>
  327. /// <param name="message">The message to be sent.</param>
  328. /// <returns></returns>
  329. public override bool TrySend(string message)
  330. {
  331. return ProtocolProcessor.TrySendMessage(this, message);
  332. }
  333. /// <summary>
  334. /// Sends the data to client.
  335. /// </summary>
  336. /// <param name="data">The data.</param>
  337. /// <param name="offset">The offset.</param>
  338. /// <param name="length">The length.</param>
  339. public override void Send(byte[] data, int offset, int length)
  340. {
  341. if (!ProtocolProcessor.CanSendBinaryData)
  342. {
  343. Logger.LogError("The websocket of this version cannot used for sending binary data!");
  344. return;
  345. }
  346. ProtocolProcessor.SendData(this, data, offset, length);
  347. }
  348. /// <summary>
  349. /// Tries to send the data over the websocket connection.
  350. /// </summary>
  351. /// <param name="segment">The segment to be sent.</param>
  352. /// <returns></returns>
  353. public override bool TrySend(ArraySegment<byte> segment)
  354. {
  355. if (!ProtocolProcessor.CanSendBinaryData)
  356. {
  357. Logger.LogError("The websocket of this version cannot used for sending binary data!");
  358. return false;
  359. }
  360. return ProtocolProcessor.TrySendData(this, segment.Array, segment.Offset, segment.Count);
  361. }
  362. /// <summary>
  363. /// Tries to send the data over the websocket connection.
  364. /// </summary>
  365. /// <param name="data">The data.</param>
  366. /// <param name="offset">The offset.</param>
  367. /// <param name="length">The length.</param>
  368. /// <returns></returns>
  369. public override bool TrySend(byte[] data, int offset, int length)
  370. {
  371. if (!ProtocolProcessor.CanSendBinaryData)
  372. {
  373. Logger.LogError("The websocket of this version cannot used for sending binary data!");
  374. return false;
  375. }
  376. return ProtocolProcessor.TrySendData(this, data, offset, length);
  377. }
  378. /// <summary>
  379. /// Sends the segment to client.
  380. /// </summary>
  381. /// <param name="segment">The segment.</param>
  382. public override void Send(ArraySegment<byte> segment)
  383. {
  384. this.Send(segment.Array, segment.Offset, segment.Count);
  385. }
  386. /// <summary>
  387. /// Sends the raw binary data.
  388. /// </summary>
  389. /// <param name="data">The data.</param>
  390. /// <param name="offset">The offset.</param>
  391. /// <param name="length">The length.</param>
  392. void IWebSocketSession.SendRawData(byte[] data, int offset, int length)
  393. {
  394. base.Send(data, offset, length);
  395. }
  396. /// <summary>
  397. /// Try to send the raw binary data to client.
  398. /// </summary>
  399. /// <param name="data">The data.</param>
  400. /// <param name="offset">The offset.</param>
  401. /// <param name="length">The length.</param>
  402. /// <returns>
  403. /// if the data to be sent is queued, return true, else the queue is full, then return false
  404. /// </returns>
  405. bool IWebSocketSession.TrySendRawData(byte[] data, int offset, int length)
  406. {
  407. return base.TrySend(new ArraySegment<byte>(data, offset, length));
  408. }
  409. /// <summary>
  410. /// Tries the send raw data segments.
  411. /// </summary>
  412. /// <param name="segments">The segments.</param>
  413. /// <returns></returns>
  414. internal bool TrySendRawData(IList<ArraySegment<byte>> segments)
  415. {
  416. return base.TrySend(segments);
  417. }
  418. /// <summary>
  419. /// Closes the with handshake.
  420. /// </summary>
  421. /// <param name="reasonText">The reason text.</param>
  422. public void CloseWithHandshake(string reasonText)
  423. {
  424. this.CloseWithHandshake(ProtocolProcessor.CloseStatusClode.NormalClosure, reasonText);
  425. }
  426. /// <summary>
  427. /// Closes the with handshake.
  428. /// </summary>
  429. /// <param name="statusCode">The status code.</param>
  430. /// <param name="reasonText">The reason text.</param>
  431. public void CloseWithHandshake(int statusCode, string reasonText)
  432. {
  433. if (!InClosing)
  434. InClosing = true;
  435. ProtocolProcessor.SendCloseHandshake(this, statusCode, reasonText);
  436. StartClosingHandshakeTime = DateTime.UtcNow;
  437. AppServer.PushToCloseHandshakeQueue(this);
  438. }
  439. /// <summary>
  440. /// Sends the close handshake response.
  441. /// </summary>
  442. /// <param name="statusCode">The status code.</param>
  443. public void SendCloseHandshakeResponse(int statusCode)
  444. {
  445. if (!InClosing)
  446. InClosing = true;
  447. ProtocolProcessor.SendCloseHandshake(this, statusCode, string.Empty);
  448. }
  449. /// <summary>
  450. /// Closes the specified reason.
  451. /// </summary>
  452. /// <param name="reason">The reason.</param>
  453. public override void Close(CloseReason reason)
  454. {
  455. if (reason == CloseReason.TimeOut && ProtocolProcessor != null)
  456. {
  457. CloseWithHandshake(ProtocolProcessor.CloseStatusClode.NormalClosure, "Session timeOut");
  458. return;
  459. }
  460. base.Close(reason);
  461. }
  462. /// <summary>
  463. /// Gets or sets the protocol processor.
  464. /// </summary>
  465. /// <value>
  466. /// The protocol processor.
  467. /// </value>
  468. public IProtocolProcessor ProtocolProcessor { get; set; }
  469. /// <summary>
  470. /// Handles the unknown command.
  471. /// </summary>
  472. /// <param name="requestInfo">The request info.</param>
  473. internal protected virtual void HandleUnknownCommand(SubRequestInfo requestInfo)
  474. {
  475. }
  476. /// <summary>
  477. /// Handles the unknown request.
  478. /// </summary>
  479. /// <param name="requestInfo">The request info.</param>
  480. protected override void HandleUnknownRequest(IWebSocketFragment requestInfo)
  481. {
  482. base.Close();
  483. }
  484. }
  485. }