WebSocketSession.cs 17 KB

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