AppSession.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  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.Command;
  11. using SuperSocket.SocketBase.Config;
  12. using SuperSocket.SocketBase.Logging;
  13. using SuperSocket.SocketBase.Protocol;
  14. namespace SuperSocket.SocketBase
  15. {
  16. /// <summary>
  17. /// AppSession base class
  18. /// </summary>
  19. /// <typeparam name="TAppSession">The type of the app session.</typeparam>
  20. /// <typeparam name="TRequestInfo">The type of the request info.</typeparam>
  21. public abstract class AppSession<TAppSession, TRequestInfo> : IAppSession, IAppSession<TAppSession, TRequestInfo>
  22. where TAppSession : AppSession<TAppSession, TRequestInfo>, IAppSession, new()
  23. where TRequestInfo : class, IRequestInfo
  24. {
  25. #region Properties
  26. /// <summary>
  27. /// Gets the app server instance assosiated with the session.
  28. /// </summary>
  29. public virtual AppServerBase<TAppSession, TRequestInfo> AppServer { get; private set; }
  30. /// <summary>
  31. /// Gets the app server instance assosiated with the session.
  32. /// </summary>
  33. IAppServer IAppSession.AppServer
  34. {
  35. get { return this.AppServer; }
  36. }
  37. /// <summary>
  38. /// Gets or sets the charset which is used for transfering text message.
  39. /// </summary>
  40. /// <value>
  41. /// The charset.
  42. /// </value>
  43. public Encoding Charset { get; set; }
  44. private IDictionary<object, object> m_Items;
  45. /// <summary>
  46. /// Gets the items dictionary, only support 10 items maximum
  47. /// </summary>
  48. public IDictionary<object, object> Items
  49. {
  50. get
  51. {
  52. if (m_Items == null)
  53. m_Items = new Dictionary<object, object>(10);
  54. return m_Items;
  55. }
  56. }
  57. private bool m_Connected = false;
  58. /// <summary>
  59. /// Gets a value indicating whether this <see cref="IAppSession"/> is connected.
  60. /// </summary>
  61. /// <value>
  62. /// <c>true</c> if connected; otherwise, <c>false</c>.
  63. /// </value>
  64. public bool Connected
  65. {
  66. get { return m_Connected; }
  67. internal set { m_Connected = value; }
  68. }
  69. /// <summary>
  70. /// Gets or sets the previous command.
  71. /// </summary>
  72. /// <value>
  73. /// The prev command.
  74. /// </value>
  75. public string PrevCommand { get; set; }
  76. /// <summary>
  77. /// Gets or sets the current executing command.
  78. /// </summary>
  79. /// <value>
  80. /// The current command.
  81. /// </value>
  82. public string CurrentCommand { get; set; }
  83. /// <summary>
  84. /// Gets or sets the secure protocol of transportation layer.
  85. /// </summary>
  86. /// <value>
  87. /// The secure protocol.
  88. /// </value>
  89. public SslProtocols SecureProtocol
  90. {
  91. get { return SocketSession.SecureProtocol; }
  92. set { SocketSession.SecureProtocol = value; }
  93. }
  94. /// <summary>
  95. /// Gets the local listening endpoint.
  96. /// </summary>
  97. public IPEndPoint LocalEndPoint
  98. {
  99. get { return SocketSession.LocalEndPoint; }
  100. }
  101. /// <summary>
  102. /// Gets the remote endpoint of client.
  103. /// </summary>
  104. public IPEndPoint RemoteEndPoint
  105. {
  106. get { return SocketSession.RemoteEndPoint; }
  107. }
  108. /// <summary>
  109. /// Gets the logger.
  110. /// </summary>
  111. public ILog Logger
  112. {
  113. get { return AppServer.Logger; }
  114. }
  115. /// <summary>
  116. /// Gets or sets the last active time of the session.
  117. /// </summary>
  118. /// <value>
  119. /// The last active time.
  120. /// </value>
  121. public DateTime LastActiveTime { get; set; }
  122. /// <summary>
  123. /// Gets the start time of the session.
  124. /// </summary>
  125. public DateTime StartTime { get; private set; }
  126. /// <summary>
  127. /// Gets the session ID.
  128. /// </summary>
  129. public string SessionID { get; private set; }
  130. /// <summary>
  131. /// Gets the socket session of the AppSession.
  132. /// </summary>
  133. public ISocketSession SocketSession { get; private set; }
  134. /// <summary>
  135. /// Gets the config of the server.
  136. /// </summary>
  137. public IServerConfig Config
  138. {
  139. get { return AppServer.Config; }
  140. }
  141. IReceiveFilter<TRequestInfo> m_ReceiveFilter;
  142. #endregion
  143. /// <summary>
  144. /// Initializes a new instance of the <see cref="AppSession&lt;TAppSession, TRequestInfo&gt;"/> class.
  145. /// </summary>
  146. public AppSession()
  147. {
  148. this.StartTime = DateTime.Now;
  149. this.LastActiveTime = this.StartTime;
  150. }
  151. /// <summary>
  152. /// Initializes the specified app session by AppServer and SocketSession.
  153. /// </summary>
  154. /// <param name="appServer">The app server.</param>
  155. /// <param name="socketSession">The socket session.</param>
  156. public virtual void Initialize(IAppServer<TAppSession, TRequestInfo> appServer, ISocketSession socketSession)
  157. {
  158. var castedAppServer = (AppServerBase<TAppSession, TRequestInfo>)appServer;
  159. AppServer = castedAppServer;
  160. Charset = castedAppServer.TextEncoding;
  161. SocketSession = socketSession;
  162. SessionID = socketSession.SessionID;
  163. m_Connected = true;
  164. m_ReceiveFilter = castedAppServer.ReceiveFilterFactory.CreateFilter(appServer, this, socketSession.RemoteEndPoint);
  165. var filterInitializer = m_ReceiveFilter as IReceiveFilterInitializer;
  166. if (filterInitializer != null)
  167. filterInitializer.Initialize(castedAppServer, this);
  168. socketSession.Initialize(this);
  169. OnInit();
  170. }
  171. /// <summary>
  172. /// Starts the session.
  173. /// </summary>
  174. void IAppSession.StartSession()
  175. {
  176. OnSessionStarted();
  177. }
  178. /// <summary>
  179. /// Called when [init].
  180. /// </summary>
  181. protected virtual void OnInit()
  182. {
  183. }
  184. /// <summary>
  185. /// Called when [session started].
  186. /// </summary>
  187. protected virtual void OnSessionStarted()
  188. {
  189. }
  190. /// <summary>
  191. /// Called when [session closed].
  192. /// </summary>
  193. /// <param name="reason">The reason.</param>
  194. internal protected virtual void OnSessionClosed(CloseReason reason)
  195. {
  196. }
  197. /// <summary>
  198. /// Handles the exceptional error, it only handles application error.
  199. /// </summary>
  200. /// <param name="e">The exception.</param>
  201. protected virtual void HandleException(Exception e)
  202. {
  203. Logger.Error(this, e);
  204. this.Close(CloseReason.ApplicationError);
  205. }
  206. /// <summary>
  207. /// Handles the unknown request.
  208. /// </summary>
  209. /// <param name="requestInfo">The request info.</param>
  210. protected virtual void HandleUnknownRequest(TRequestInfo requestInfo)
  211. {
  212. }
  213. internal void InternalHandleUnknownRequest(TRequestInfo requestInfo)
  214. {
  215. HandleUnknownRequest(requestInfo);
  216. }
  217. internal void InternalHandleExcetion(Exception e)
  218. {
  219. HandleException(e);
  220. }
  221. /// <summary>
  222. /// Closes the session by the specified reason.
  223. /// </summary>
  224. /// <param name="reason">The close reason.</param>
  225. public virtual void Close(CloseReason reason)
  226. {
  227. this.SocketSession.Close(reason);
  228. }
  229. /// <summary>
  230. /// Closes this session.
  231. /// </summary>
  232. public virtual void Close()
  233. {
  234. Close(CloseReason.ServerClosing);
  235. }
  236. #region Sending processing
  237. /// <summary>
  238. /// Try to send the message to client.
  239. /// </summary>
  240. /// <param name="message">The message which will be sent.</param>
  241. /// <returns>Indicate whether the message was pushed into the sending queue</returns>
  242. public virtual bool TrySend(string message)
  243. {
  244. var data = this.Charset.GetBytes(message);
  245. return InternalTrySend(new ArraySegment<byte>(data, 0, data.Length));
  246. }
  247. /// <summary>
  248. /// Sends the message to client.
  249. /// </summary>
  250. /// <param name="message">The message which will be sent.</param>
  251. public virtual void Send(string message)
  252. {
  253. var data = this.Charset.GetBytes(message);
  254. Send(data, 0, data.Length);
  255. }
  256. /// <summary>
  257. /// Try to send the data to client.
  258. /// </summary>
  259. /// <param name="data">The data which will be sent.</param>
  260. /// <param name="offset">The offset.</param>
  261. /// <param name="length">The length.</param>
  262. /// <returns>Indicate whether the message was pushed into the sending queue</returns>
  263. public virtual bool TrySend(byte[] data, int offset, int length)
  264. {
  265. return InternalTrySend(new ArraySegment<byte>(data, offset, length));
  266. }
  267. /// <summary>
  268. /// Sends the data to client.
  269. /// </summary>
  270. /// <param name="data">The data which will be sent.</param>
  271. /// <param name="offset">The offset.</param>
  272. /// <param name="length">The length.</param>
  273. public virtual void Send(byte[] data, int offset, int length)
  274. {
  275. InternalSend(new ArraySegment<byte>(data, offset, length));
  276. }
  277. private bool InternalTrySend(ArraySegment<byte> segment)
  278. {
  279. if (!SocketSession.TrySend(segment))
  280. return false;
  281. LastActiveTime = DateTime.Now;
  282. return true;
  283. }
  284. /// <summary>
  285. /// Try to send the data segment to client.
  286. /// </summary>
  287. /// <param name="segment">The segment which will be sent.</param>
  288. /// <returns>Indicate whether the message was pushed into the sending queue</returns>
  289. public virtual bool TrySend(ArraySegment<byte> segment)
  290. {
  291. if (!m_Connected)
  292. return false;
  293. return InternalTrySend(segment);
  294. }
  295. private void InternalSend(ArraySegment<byte> segment)
  296. {
  297. if (!m_Connected)
  298. return;
  299. if (InternalTrySend(segment))
  300. return;
  301. var sendTimeOut = Config.SendTimeOut;
  302. //Don't retry, timeout directly
  303. if (sendTimeOut < 0)
  304. {
  305. throw new TimeoutException("The sending attempt timed out");
  306. }
  307. var timeOutTime = sendTimeOut > 0 ? DateTime.Now.AddMilliseconds(sendTimeOut) : DateTime.Now;
  308. var spinWait = new SpinWait();
  309. while (m_Connected)
  310. {
  311. spinWait.SpinOnce();
  312. if (InternalTrySend(segment))
  313. return;
  314. //If sendTimeOut = 0, don't have timeout check
  315. if (sendTimeOut > 0 && DateTime.Now >= timeOutTime)
  316. {
  317. throw new TimeoutException("The sending attempt timed out");
  318. }
  319. }
  320. }
  321. /// <summary>
  322. /// Sends the data segment to client.
  323. /// </summary>
  324. /// <param name="segment">The segment which will be sent.</param>
  325. public virtual void Send(ArraySegment<byte> segment)
  326. {
  327. InternalSend(segment);
  328. }
  329. private bool InternalTrySend(IList<ArraySegment<byte>> segments)
  330. {
  331. if (!SocketSession.TrySend(segments))
  332. return false;
  333. LastActiveTime = DateTime.Now;
  334. return true;
  335. }
  336. /// <summary>
  337. /// Try to send the data segments to client.
  338. /// </summary>
  339. /// <param name="segments">The segments.</param>
  340. /// <returns>Indicate whether the message was pushed into the sending queue; if it returns false, the sending queue may be full or the socket is not connected</returns>
  341. public virtual bool TrySend(IList<ArraySegment<byte>> segments)
  342. {
  343. if (!m_Connected)
  344. return false;
  345. return InternalTrySend(segments);
  346. }
  347. private void InternalSend(IList<ArraySegment<byte>> segments)
  348. {
  349. if (!m_Connected)
  350. return;
  351. if (InternalTrySend(segments))
  352. return;
  353. var sendTimeOut = Config.SendTimeOut;
  354. //Don't retry, timeout directly
  355. if (sendTimeOut < 0)
  356. {
  357. throw new TimeoutException("The sending attempt timed out");
  358. }
  359. var timeOutTime = sendTimeOut > 0 ? DateTime.Now.AddMilliseconds(sendTimeOut) : DateTime.Now;
  360. var spinWait = new SpinWait();
  361. while (m_Connected)
  362. {
  363. spinWait.SpinOnce();
  364. if (InternalTrySend(segments))
  365. return;
  366. //If sendTimeOut = 0, don't have timeout check
  367. if (sendTimeOut > 0 && DateTime.Now >= timeOutTime)
  368. {
  369. throw new TimeoutException("The sending attempt timed out");
  370. }
  371. }
  372. }
  373. /// <summary>
  374. /// Sends the data segments to client.
  375. /// </summary>
  376. /// <param name="segments">The segments.</param>
  377. public virtual void Send(IList<ArraySegment<byte>> segments)
  378. {
  379. InternalSend(segments);
  380. }
  381. /// <summary>
  382. /// Sends the response.
  383. /// </summary>
  384. /// <param name="message">The message which will be sent.</param>
  385. /// <param name="paramValues">The parameter values.</param>
  386. public virtual void Send(string message, params object[] paramValues)
  387. {
  388. var data = this.Charset.GetBytes(string.Format(message, paramValues));
  389. InternalSend(new ArraySegment<byte>(data, 0, data.Length));
  390. }
  391. #endregion
  392. #region Receiving processing
  393. /// <summary>
  394. /// Sets the next Receive filter which will be used when next data block received
  395. /// </summary>
  396. /// <param name="nextReceiveFilter">The next receive filter.</param>
  397. protected void SetNextReceiveFilter(IReceiveFilter<TRequestInfo> nextReceiveFilter)
  398. {
  399. m_ReceiveFilter = nextReceiveFilter;
  400. }
  401. /// <summary>
  402. /// Gets the maximum allowed length of the request.
  403. /// </summary>
  404. /// <returns></returns>
  405. protected virtual int GetMaxRequestLength()
  406. {
  407. return AppServer.Config.MaxRequestLength;
  408. }
  409. /// <summary>
  410. /// Filters the request.
  411. /// </summary>
  412. /// <param name="readBuffer">The read buffer.</param>
  413. /// <param name="offset">The offset.</param>
  414. /// <param name="length">The length.</param>
  415. /// <param name="toBeCopied">if set to <c>true</c> [to be copied].</param>
  416. /// <param name="rest">The rest, the size of the data which has not been processed</param>
  417. /// <param name="offsetDelta">return offset delta of next receiving buffer.</param>
  418. /// <returns></returns>
  419. TRequestInfo FilterRequest(byte[] readBuffer, int offset, int length, bool toBeCopied, out int rest, out int offsetDelta)
  420. {
  421. if (!AppServer.OnRawDataReceived(this, readBuffer, offset, length))
  422. {
  423. rest = 0;
  424. offsetDelta = 0;
  425. return null;
  426. }
  427. var currentRequestLength = m_ReceiveFilter.LeftBufferSize;
  428. var requestInfo = m_ReceiveFilter.Filter(readBuffer, offset, length, toBeCopied, out rest);
  429. if (m_ReceiveFilter.State == FilterState.Error)
  430. {
  431. rest = 0;
  432. offsetDelta = 0;
  433. Close(CloseReason.ProtocolError);
  434. return null;
  435. }
  436. var offsetAdapter = m_ReceiveFilter as IOffsetAdapter;
  437. offsetDelta = offsetAdapter != null ? offsetAdapter.OffsetDelta : 0;
  438. if (requestInfo == null)
  439. {
  440. //current buffered length
  441. currentRequestLength = m_ReceiveFilter.LeftBufferSize;
  442. }
  443. else
  444. {
  445. //current request length
  446. currentRequestLength = currentRequestLength + length - rest;
  447. }
  448. var maxRequestLength = GetMaxRequestLength();
  449. if (currentRequestLength >= maxRequestLength)
  450. {
  451. if (Logger.IsErrorEnabled)
  452. Logger.Error(this, string.Format("Max request length: {0}, current processed length: {1}", maxRequestLength, currentRequestLength));
  453. Close(CloseReason.ProtocolError);
  454. return null;
  455. }
  456. //If next Receive filter wasn't set, still use current Receive filter in next round received data processing
  457. if (m_ReceiveFilter.NextReceiveFilter != null)
  458. m_ReceiveFilter = m_ReceiveFilter.NextReceiveFilter;
  459. return requestInfo;
  460. }
  461. /// <summary>
  462. /// Processes the request data.
  463. /// </summary>
  464. /// <param name="readBuffer">The read buffer.</param>
  465. /// <param name="offset">The offset.</param>
  466. /// <param name="length">The length.</param>
  467. /// <param name="toBeCopied">if set to <c>true</c> [to be copied].</param>
  468. /// <returns>
  469. /// return offset delta of next receiving buffer
  470. /// </returns>
  471. int IAppSession.ProcessRequest(byte[] readBuffer, int offset, int length, bool toBeCopied)
  472. {
  473. int rest, offsetDelta;
  474. while (true)
  475. {
  476. var requestInfo = FilterRequest(readBuffer, offset, length, toBeCopied, out rest, out offsetDelta);
  477. if (requestInfo != null)
  478. {
  479. try
  480. {
  481. AppServer.ExecuteCommand(this, requestInfo);
  482. }
  483. catch (Exception e)
  484. {
  485. HandleException(e);
  486. }
  487. }
  488. if (rest <= 0)
  489. {
  490. return offsetDelta;
  491. }
  492. //Still have data has not been processed
  493. offset = offset + length - rest;
  494. length = rest;
  495. }
  496. }
  497. #endregion
  498. }
  499. /// <summary>
  500. /// AppServer basic class for whose request infoe type is StringRequestInfo
  501. /// </summary>
  502. /// <typeparam name="TAppSession">The type of the app session.</typeparam>
  503. public abstract class AppSession<TAppSession> : AppSession<TAppSession, StringRequestInfo>
  504. where TAppSession : AppSession<TAppSession, StringRequestInfo>, IAppSession, new()
  505. {
  506. private bool m_AppendNewLineForResponse = false;
  507. private static string m_NewLine = "\r\n";
  508. /// <summary>
  509. /// Initializes a new instance of the <see cref="AppSession&lt;TAppSession&gt;"/> class.
  510. /// </summary>
  511. public AppSession()
  512. : this(true)
  513. {
  514. }
  515. /// <summary>
  516. /// Initializes a new instance of the <see cref="AppSession&lt;TAppSession&gt;"/> class.
  517. /// </summary>
  518. /// <param name="appendNewLineForResponse">if set to <c>true</c> [append new line for response].</param>
  519. public AppSession(bool appendNewLineForResponse)
  520. {
  521. m_AppendNewLineForResponse = appendNewLineForResponse;
  522. }
  523. /// <summary>
  524. /// Handles the unknown request.
  525. /// </summary>
  526. /// <param name="requestInfo">The request info.</param>
  527. protected override void HandleUnknownRequest(StringRequestInfo requestInfo)
  528. {
  529. Send("Unknown request: " + requestInfo.Key);
  530. }
  531. /// <summary>
  532. /// Processes the sending message.
  533. /// </summary>
  534. /// <param name="rawMessage">The raw message.</param>
  535. /// <returns></returns>
  536. protected virtual string ProcessSendingMessage(string rawMessage)
  537. {
  538. if (!m_AppendNewLineForResponse)
  539. return rawMessage;
  540. if (AppServer.Config.Mode == SocketMode.Udp)
  541. return rawMessage;
  542. if (string.IsNullOrEmpty(rawMessage) || !rawMessage.EndsWith(m_NewLine))
  543. return rawMessage + m_NewLine;
  544. else
  545. return rawMessage;
  546. }
  547. /// <summary>
  548. /// Sends the specified message.
  549. /// </summary>
  550. /// <param name="message">The message.</param>
  551. /// <returns></returns>
  552. public override void Send(string message)
  553. {
  554. base.Send(ProcessSendingMessage(message));
  555. }
  556. /// <summary>
  557. /// Sends the response.
  558. /// </summary>
  559. /// <param name="message">The message.</param>
  560. /// <param name="paramValues">The param values.</param>
  561. /// <returns>Indicate whether the message was pushed into the sending queue</returns>
  562. public override void Send(string message, params object[] paramValues)
  563. {
  564. base.Send(ProcessSendingMessage(message), paramValues);
  565. }
  566. }
  567. /// <summary>
  568. /// AppServer basic class for whose request infoe type is StringRequestInfo
  569. /// </summary>
  570. public class AppSession : AppSession<AppSession>
  571. {
  572. }
  573. }