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. if (string.IsNullOrEmpty(protocol))
  197. {
  198. SubProtocol = AppServer.DefaultSubProtocol;
  199. return string.Empty;
  200. }
  201. var arrNames = protocol.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
  202. if (protocol.ToLower().Contains("ocpp2.0"))
  203. {
  204. arrNames = new string[] { "ocpp2.0" };
  205. }
  206. foreach (var name in arrNames)
  207. {
  208. var subProtocol = AppServer.GetSubProtocol(name);
  209. if (subProtocol != null)
  210. {
  211. SubProtocol = subProtocol;
  212. return name;
  213. }
  214. }
  215. return string.Empty;
  216. }
  217. /// <summary>
  218. /// Gets the URI scheme, ws or wss
  219. /// </summary>
  220. public string UriScheme
  221. {
  222. get
  223. {
  224. if (SocketSession.SecureProtocol == SslProtocols.None)
  225. return WebSocketConstant.WsSchema;
  226. else
  227. return WebSocketConstant.WssSchema;
  228. }
  229. }
  230. /// <summary>
  231. /// Gets the sub protocol.
  232. /// </summary>
  233. public ISubProtocol<TWebSocketSession> SubProtocol { get; private set; }
  234. private bool m_Handshaked = false;
  235. /// <summary>
  236. /// Gets a value indicating whether this <see cref="IWebSocketSession" /> is handshaked.
  237. /// </summary>
  238. /// <value>
  239. /// <c>true</c> if handshaked; otherwise, <c>false</c>.
  240. /// </value>
  241. public bool Handshaked
  242. {
  243. get { return m_Handshaked; }
  244. }
  245. internal void OnHandshakeSuccess()
  246. {
  247. m_Handshaked = true;
  248. SetCookie();
  249. OnSessionStarted();
  250. AppServer.FireOnNewSessionConnected(this);
  251. }
  252. /// <summary>
  253. /// Gets a value indicating whether the session [in closing].
  254. /// </summary>
  255. /// <value>
  256. /// <c>true</c> if [in closing]; otherwise, <c>false</c>.
  257. /// </value>
  258. public bool InClosing { get; private set; }
  259. /// <summary>
  260. /// Called when [init].
  261. /// </summary>
  262. protected override void OnInit()
  263. {
  264. Frames = new List<WebSocketDataFrame>();
  265. base.OnInit();
  266. }
  267. void IAppSession.StartSession()
  268. {
  269. //Do nothing. Avoid firing thhe OnSessionStarted() method of base class
  270. }
  271. /// <summary>
  272. /// Sets the cookie.
  273. /// </summary>
  274. private void SetCookie()
  275. {
  276. string cookieValue = this.Items.GetValue<string>(WebSocketConstant.Cookie, string.Empty);
  277. if (string.IsNullOrEmpty(cookieValue))
  278. return;
  279. var cookies = new StringDictionary();
  280. this.Cookies = cookies;
  281. string[] pairs = cookieValue.Split(';');
  282. int pos;
  283. string key, value;
  284. foreach (var p in pairs)
  285. {
  286. pos = p.IndexOf('=');
  287. if (pos <= 0)
  288. continue;
  289. key = p.Substring(0, pos).Trim();
  290. pos += 1;
  291. if (pos < p.Length)
  292. value = p.Substring(pos).Trim();
  293. else
  294. value = string.Empty;
  295. if (string.IsNullOrEmpty(value))
  296. {
  297. cookies[key] = string.Empty;
  298. continue;
  299. }
  300. try
  301. {
  302. cookies[key] = Uri.UnescapeDataString(value);
  303. }
  304. catch (Exception e)
  305. {
  306. Logger.Error(this, string.Format("Failed to read cookie, key: {0}, value: {1}.", key, value), e);
  307. }
  308. }
  309. }
  310. /// <summary>
  311. /// Gets the cookies.
  312. /// </summary>
  313. public StringDictionary Cookies { get; private set; }
  314. /// <summary>
  315. /// Sends the message to client.
  316. /// </summary>
  317. /// <param name="message">The message.</param>
  318. public override void Send(string message)
  319. {
  320. ProtocolProcessor.SendMessage(this, message);
  321. }
  322. /// <summary>
  323. /// Tries to send.
  324. /// </summary>
  325. /// <param name="message">The message to be sent.</param>
  326. /// <returns></returns>
  327. public override bool TrySend(string message)
  328. {
  329. return ProtocolProcessor.TrySendMessage(this, message);
  330. }
  331. /// <summary>
  332. /// Sends the data to client.
  333. /// </summary>
  334. /// <param name="data">The data.</param>
  335. /// <param name="offset">The offset.</param>
  336. /// <param name="length">The length.</param>
  337. public override void Send(byte[] data, int offset, int length)
  338. {
  339. if (!ProtocolProcessor.CanSendBinaryData)
  340. {
  341. if (Logger.IsErrorEnabled)
  342. Logger.Error("The websocket of this version cannot used for sending binary data!");
  343. return;
  344. }
  345. ProtocolProcessor.SendData(this, data, offset, length);
  346. }
  347. /// <summary>
  348. /// Tries to send the data over the websocket connection.
  349. /// </summary>
  350. /// <param name="segment">The segment to be sent.</param>
  351. /// <returns></returns>
  352. public override bool TrySend(ArraySegment<byte> segment)
  353. {
  354. if (!ProtocolProcessor.CanSendBinaryData)
  355. {
  356. if (Logger.IsErrorEnabled)
  357. Logger.Error("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. if (Logger.IsErrorEnabled)
  374. Logger.Error("The websocket of this version cannot used for sending binary data!");
  375. return false;
  376. }
  377. return ProtocolProcessor.TrySendData(this, data, offset, length);
  378. }
  379. /// <summary>
  380. /// Sends the segment to client.
  381. /// </summary>
  382. /// <param name="segment">The segment.</param>
  383. public override void Send(ArraySegment<byte> segment)
  384. {
  385. this.Send(segment.Array, segment.Offset, segment.Count);
  386. }
  387. /// <summary>
  388. /// Sends the raw binary data.
  389. /// </summary>
  390. /// <param name="data">The data.</param>
  391. /// <param name="offset">The offset.</param>
  392. /// <param name="length">The length.</param>
  393. void IWebSocketSession.SendRawData(byte[] data, int offset, int length)
  394. {
  395. base.Send(data, offset, length);
  396. }
  397. /// <summary>
  398. /// Try to send the raw binary data to client.
  399. /// </summary>
  400. /// <param name="data">The data.</param>
  401. /// <param name="offset">The offset.</param>
  402. /// <param name="length">The length.</param>
  403. /// <returns>
  404. /// if the data to be sent is queued, return true, else the queue is full, then return false
  405. /// </returns>
  406. bool IWebSocketSession.TrySendRawData(byte[] data, int offset, int length)
  407. {
  408. return base.TrySend(new ArraySegment<byte>(data, offset, length));
  409. }
  410. /// <summary>
  411. /// Tries the send raw data segments.
  412. /// </summary>
  413. /// <param name="segments">The segments.</param>
  414. /// <returns></returns>
  415. internal bool TrySendRawData(IList<ArraySegment<byte>> segments)
  416. {
  417. return base.TrySend(segments);
  418. }
  419. /// <summary>
  420. /// Closes the with handshake.
  421. /// </summary>
  422. /// <param name="reasonText">The reason text.</param>
  423. public void CloseWithHandshake(string reasonText)
  424. {
  425. this.CloseWithHandshake(ProtocolProcessor.CloseStatusClode.NormalClosure, reasonText);
  426. }
  427. /// <summary>
  428. /// Closes the with handshake.
  429. /// </summary>
  430. /// <param name="statusCode">The status code.</param>
  431. /// <param name="reasonText">The reason text.</param>
  432. public void CloseWithHandshake(int statusCode, string reasonText)
  433. {
  434. if (!InClosing)
  435. InClosing = true;
  436. ProtocolProcessor.SendCloseHandshake(this, statusCode, reasonText);
  437. StartClosingHandshakeTime = DateTime.Now;
  438. AppServer.PushToCloseHandshakeQueue(this);
  439. }
  440. /// <summary>
  441. /// Sends the close handshake response.
  442. /// </summary>
  443. /// <param name="statusCode">The status code.</param>
  444. public void SendCloseHandshakeResponse(int statusCode)
  445. {
  446. if (!InClosing)
  447. InClosing = true;
  448. ProtocolProcessor.SendCloseHandshake(this, statusCode, string.Empty);
  449. }
  450. /// <summary>
  451. /// Closes the specified reason.
  452. /// </summary>
  453. /// <param name="reason">The reason.</param>
  454. public override void Close(CloseReason reason)
  455. {
  456. if (reason == CloseReason.TimeOut && ProtocolProcessor != null)
  457. {
  458. CloseWithHandshake(ProtocolProcessor.CloseStatusClode.NormalClosure, "Session timeOut");
  459. return;
  460. }
  461. base.Close(reason);
  462. }
  463. /// <summary>
  464. /// Gets or sets the protocol processor.
  465. /// </summary>
  466. /// <value>
  467. /// The protocol processor.
  468. /// </value>
  469. public IProtocolProcessor ProtocolProcessor { get; set; }
  470. /// <summary>
  471. /// Handles the unknown command.
  472. /// </summary>
  473. /// <param name="requestInfo">The request info.</param>
  474. internal protected virtual void HandleUnknownCommand(SubRequestInfo requestInfo)
  475. {
  476. }
  477. /// <summary>
  478. /// Handles the unknown request.
  479. /// </summary>
  480. /// <param name="requestInfo">The request info.</param>
  481. protected override void HandleUnknownRequest(IWebSocketFragment requestInfo)
  482. {
  483. base.Close();
  484. }
  485. }
  486. }