AppSession.cs 22 KB

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