WebSocketSession.cs 17 KB

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