SocketSession.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Collections.ObjectModel;
  5. using System.IO;
  6. using System.Net;
  7. using System.Net.Sockets;
  8. using System.Security.Authentication;
  9. using System.Text;
  10. using System.Threading;
  11. using SuperSocket.Common;
  12. using SuperSocket.SocketBase;
  13. using SuperSocket.SocketBase.Command;
  14. using SuperSocket.SocketBase.Config;
  15. using SuperSocket.SocketBase.Protocol;
  16. namespace SuperSocket.SocketEngine
  17. {
  18. static class SocketState
  19. {
  20. public const int Normal = 0;//0000 0000
  21. public const int InClosing = 16;//0001 0000 >= 16
  22. public const int Closed = 16777216;//256 * 256 * 256; 0x01 0x00 0x00 0x00
  23. public const int InSending = 1;//0000 0001 > 1
  24. public const int InReceiving = 2;//0000 0010 > 2
  25. public const int InSendingReceivingMask = -4;// ~(InSending | InReceiving); 0xf0 0xff 0xff 0xff
  26. }
  27. /// <summary>
  28. /// Socket Session, all application session should base on this class
  29. /// </summary>
  30. abstract partial class SocketSession : ISocketSession
  31. {
  32. public IAppSession AppSession { get; private set; }
  33. protected readonly object SyncRoot = new object();
  34. //0x00 0x00 0x00 0x00
  35. //1st byte: Closed(Y/N) - 0x01
  36. //2nd byte: N/A
  37. //3th byte: CloseReason
  38. //Last byte: 0000 0000 - normal state
  39. //0000 0001: in sending
  40. //0000 0010: in receiving
  41. //0001 0000: in closing
  42. private int m_State = 0;
  43. private void AddStateFlag(int stateValue)
  44. {
  45. AddStateFlag(stateValue, false);
  46. }
  47. private bool AddStateFlag(int stateValue, bool notClosing)
  48. {
  49. while(true)
  50. {
  51. var oldState = m_State;
  52. if (notClosing)
  53. {
  54. // don't update the state if the connection has entered the closing procedure
  55. if (oldState >= SocketState.InClosing)
  56. {
  57. return false;
  58. }
  59. }
  60. var newState = m_State | stateValue;
  61. if(Interlocked.CompareExchange(ref m_State, newState, oldState) == oldState)
  62. return true;
  63. }
  64. }
  65. private bool TryAddStateFlag(int stateValue)
  66. {
  67. while (true)
  68. {
  69. var oldState = m_State;
  70. var newState = m_State | stateValue;
  71. //Already marked
  72. if (oldState == newState)
  73. {
  74. return false;
  75. }
  76. var compareState = Interlocked.CompareExchange(ref m_State, newState, oldState);
  77. if (compareState == oldState)
  78. return true;
  79. }
  80. }
  81. private void RemoveStateFlag(int stateValue)
  82. {
  83. while(true)
  84. {
  85. var oldState = m_State;
  86. var newState = m_State & (~stateValue);
  87. if(Interlocked.CompareExchange(ref m_State, newState, oldState) == oldState)
  88. return;
  89. }
  90. }
  91. private bool CheckState(int stateValue)
  92. {
  93. return (m_State & stateValue) == stateValue;
  94. }
  95. protected bool SyncSend { get; private set; }
  96. private ISmartPool<SendingQueue> m_SendingQueuePool;
  97. public SocketSession(Socket client)
  98. : this(Guid.NewGuid().ToString())
  99. {
  100. if (client == null)
  101. throw new ArgumentNullException("client");
  102. m_Client = client;
  103. LocalEndPoint = (IPEndPoint)client.LocalEndPoint;
  104. RemoteEndPoint = (IPEndPoint)client.RemoteEndPoint;
  105. }
  106. public SocketSession(string sessionID)
  107. {
  108. SessionID = sessionID;
  109. }
  110. public virtual void Initialize(IAppSession appSession)
  111. {
  112. AppSession = appSession;
  113. Config = appSession.Config;
  114. SyncSend = Config.SyncSend;
  115. if (m_SendingQueuePool == null)
  116. m_SendingQueuePool = ((SocketServerBase)((ISocketServerAccessor)appSession.AppServer).SocketServer).SendingQueuePool;
  117. SendingQueue queue;
  118. if (m_SendingQueuePool.TryGet(out queue))
  119. {
  120. m_SendingQueue = queue;
  121. queue.StartEnqueue();
  122. }
  123. }
  124. /// <summary>
  125. /// Gets or sets the session ID.
  126. /// </summary>
  127. /// <value>The session ID.</value>
  128. public string SessionID { get; private set; }
  129. /// <summary>
  130. /// Gets or sets the config.
  131. /// </summary>
  132. /// <value>
  133. /// The config.
  134. /// </value>
  135. public IServerConfig Config { get; set; }
  136. /// <summary>
  137. /// Starts this session.
  138. /// </summary>
  139. public abstract void Start();
  140. /// <summary>
  141. /// Says the welcome information when a client connectted.
  142. /// </summary>
  143. protected virtual void StartSession()
  144. {
  145. AppSession.StartSession();
  146. }
  147. /// <summary>
  148. /// Called when [close].
  149. /// </summary>
  150. protected virtual void OnClosed(CloseReason reason)
  151. {
  152. //Already closed
  153. if (!TryAddStateFlag(SocketState.Closed))
  154. return;
  155. //Before changing m_SendingQueue, must check m_IsClosed
  156. while (true)
  157. {
  158. var sendingQueue = m_SendingQueue;
  159. if (sendingQueue == null)
  160. break;
  161. //There is no sending was started after the m_Closed ws set to 'true'
  162. if (Interlocked.CompareExchange(ref m_SendingQueue, null, sendingQueue) == sendingQueue)
  163. {
  164. sendingQueue.Clear();
  165. m_SendingQueuePool.Push(sendingQueue);
  166. break;
  167. }
  168. }
  169. var closedHandler = Closed;
  170. if (closedHandler != null)
  171. {
  172. closedHandler(this, reason);
  173. }
  174. }
  175. /// <summary>
  176. /// Occurs when [closed].
  177. /// </summary>
  178. public Action<ISocketSession, CloseReason> Closed { get; set; }
  179. private SendingQueue m_SendingQueue;
  180. /// <summary>
  181. /// Tries to send array segment.
  182. /// </summary>
  183. /// <param name="segments">The segments.</param>
  184. /// <returns></returns>
  185. public bool TrySend(IList<ArraySegment<byte>> segments)
  186. {
  187. if (IsClosed)
  188. return false;
  189. var queue = m_SendingQueue;
  190. if (queue == null)
  191. return false;
  192. var trackID = queue.TrackID;
  193. if (!queue.Enqueue(segments, trackID))
  194. return false;
  195. StartSend(queue, trackID, true);
  196. return true;
  197. }
  198. /// <summary>
  199. /// Tries to send array segment.
  200. /// </summary>
  201. /// <param name="segment">The segment.</param>
  202. /// <returns></returns>
  203. public bool TrySend(ArraySegment<byte> segment)
  204. {
  205. if (IsClosed)
  206. return false;
  207. var queue = m_SendingQueue;
  208. if (queue == null)
  209. return false;
  210. var trackID = queue.TrackID;
  211. if (!queue.Enqueue(segment, trackID))
  212. return false;
  213. StartSend(queue, trackID, true);
  214. return true;
  215. }
  216. /// <summary>
  217. /// Sends in async mode.
  218. /// </summary>
  219. /// <param name="queue">The queue.</param>
  220. protected abstract void SendAsync(SendingQueue queue);
  221. /// <summary>
  222. /// Sends in sync mode.
  223. /// </summary>
  224. /// <param name="queue">The queue.</param>
  225. protected abstract void SendSync(SendingQueue queue);
  226. private void Send(SendingQueue queue)
  227. {
  228. if (SyncSend)
  229. {
  230. SendSync(queue);
  231. }
  232. else
  233. {
  234. SendAsync(queue);
  235. }
  236. }
  237. private void StartSend(SendingQueue queue, int sendingTrackID, bool initial)
  238. {
  239. if (initial)
  240. {
  241. if (!TryAddStateFlag(SocketState.InSending))
  242. {
  243. return;
  244. }
  245. var currentQueue = m_SendingQueue;
  246. if (currentQueue != queue || sendingTrackID != currentQueue.TrackID)
  247. {
  248. //Has been sent
  249. OnSendEnd();
  250. return;
  251. }
  252. }
  253. Socket client;
  254. if (IsInClosingOrClosed && TryValidateClosedBySocket(out client))
  255. {
  256. OnSendEnd(true);
  257. return;
  258. }
  259. SendingQueue newQueue;
  260. if (!m_SendingQueuePool.TryGet(out newQueue))
  261. {
  262. AppSession.Logger.Error("There is no enougth sending queue can be used.");
  263. OnSendEnd(false);
  264. this.Close(CloseReason.InternalError);
  265. return;
  266. }
  267. var oldQueue = Interlocked.CompareExchange(ref m_SendingQueue, newQueue, queue);
  268. if (!ReferenceEquals(oldQueue, queue))
  269. {
  270. if (newQueue != null)
  271. m_SendingQueuePool.Push(newQueue);
  272. if (IsInClosingOrClosed)
  273. {
  274. OnSendEnd(true);
  275. }
  276. else
  277. {
  278. OnSendEnd(false);
  279. AppSession.Logger.Error("Failed to switch the sending queue.");
  280. this.Close(CloseReason.InternalError);
  281. }
  282. return;
  283. }
  284. //Start to allow enqueue
  285. newQueue.StartEnqueue();
  286. queue.StopEnqueue();
  287. if (queue.Count == 0)
  288. {
  289. AppSession.Logger.Error("There is no data to be sent in the queue.");
  290. m_SendingQueuePool.Push(queue);
  291. OnSendEnd(false);
  292. this.Close(CloseReason.InternalError);
  293. return;
  294. }
  295. Send(queue);
  296. }
  297. private void OnSendEnd()
  298. {
  299. OnSendEnd(IsInClosingOrClosed);
  300. }
  301. private void OnSendEnd(bool isInClosingOrClosed)
  302. {
  303. RemoveStateFlag(SocketState.InSending);
  304. if (isInClosingOrClosed)
  305. {
  306. Socket client;
  307. if (!TryValidateClosedBySocket(out client))
  308. {
  309. var sendingQueue = m_SendingQueue;
  310. //No data to be sent
  311. if (sendingQueue != null && sendingQueue.Count == 0)
  312. {
  313. if (client != null)// the socket instance is not closed yet, do it now
  314. InternalClose(client, GetCloseReasonFromState(), false);
  315. else// The UDP mode, the socket instance always is null, fire the closed event directly
  316. OnClosed(GetCloseReasonFromState());
  317. return;
  318. }
  319. return;
  320. }
  321. if (ValidateNotInSendingReceiving())
  322. {
  323. FireCloseEvent();
  324. }
  325. }
  326. }
  327. protected virtual void OnSendingCompleted(SendingQueue queue)
  328. {
  329. queue.Clear();
  330. m_SendingQueuePool.Push(queue);
  331. var newQueue = m_SendingQueue;
  332. if (IsInClosingOrClosed)
  333. {
  334. Socket client;
  335. //has data is being sent and the socket isn't closed
  336. if (newQueue.Count > 0 && !TryValidateClosedBySocket(out client))
  337. {
  338. StartSend(newQueue, newQueue.TrackID, false);
  339. return;
  340. }
  341. OnSendEnd(true);
  342. return;
  343. }
  344. if (newQueue.Count == 0)
  345. {
  346. OnSendEnd();
  347. if (newQueue.Count > 0)
  348. {
  349. StartSend(newQueue, newQueue.TrackID, true);
  350. }
  351. }
  352. else
  353. {
  354. StartSend(newQueue, newQueue.TrackID, false);
  355. }
  356. }
  357. public abstract void ApplySecureProtocol();
  358. public Stream GetUnderlyStream()
  359. {
  360. return new NetworkStream(Client);
  361. }
  362. private Socket m_Client;
  363. /// <summary>
  364. /// Gets or sets the client.
  365. /// </summary>
  366. /// <value>The client.</value>
  367. public Socket Client
  368. {
  369. get { return m_Client; }
  370. }
  371. protected bool IsInClosingOrClosed
  372. {
  373. get { return m_State >= SocketState.InClosing; }
  374. }
  375. protected bool IsClosed
  376. {
  377. get { return m_State >= SocketState.Closed; }
  378. }
  379. /// <summary>
  380. /// Gets the local end point.
  381. /// </summary>
  382. /// <value>The local end point.</value>
  383. public virtual IPEndPoint LocalEndPoint { get; protected set; }
  384. /// <summary>
  385. /// Gets the remote end point.
  386. /// </summary>
  387. /// <value>The remote end point.</value>
  388. public virtual IPEndPoint RemoteEndPoint { get; protected set; }
  389. /// <summary>
  390. /// Gets or sets the secure protocol.
  391. /// </summary>
  392. /// <value>The secure protocol.</value>
  393. public SslProtocols SecureProtocol { get; set; }
  394. protected virtual bool TryValidateClosedBySocket(out Socket socket)
  395. {
  396. socket = m_Client;
  397. //Already closed/closing
  398. return socket == null;
  399. }
  400. public virtual void Close(CloseReason reason)
  401. {
  402. //Already in closing procedure
  403. if (!TryAddStateFlag(SocketState.InClosing))
  404. return;
  405. Socket client;
  406. //No need to clean the socket instance
  407. if (TryValidateClosedBySocket(out client))
  408. return;
  409. //Some data is in sending
  410. if (CheckState(SocketState.InSending))
  411. {
  412. //Set closing reason only, don't close the socket directly
  413. AddStateFlag(GetCloseReasonValue(reason));
  414. return;
  415. }
  416. // In the udp mode, we needn't close the socket instance
  417. if (client != null)
  418. InternalClose(client, reason, true);
  419. else //In Udp mode, and the socket is not in the sending state, then fire the closed event directly
  420. OnClosed(reason);
  421. }
  422. private void InternalClose(Socket client, CloseReason reason, bool setCloseReason)
  423. {
  424. if (Interlocked.CompareExchange(ref m_Client, null, client) == client)
  425. {
  426. if (setCloseReason)
  427. AddStateFlag(GetCloseReasonValue(reason));
  428. client.SafeClose();
  429. if (ValidateNotInSendingReceiving())
  430. {
  431. OnClosed(reason);
  432. }
  433. }
  434. }
  435. protected void OnSendError(SendingQueue queue, CloseReason closeReason)
  436. {
  437. queue.Clear();
  438. m_SendingQueuePool.Push(queue);
  439. OnSendEnd();
  440. ValidateClosed(closeReason);
  441. }
  442. // the receive action won't be started for this connection any more
  443. protected void OnReceiveTerminated(CloseReason closeReason)
  444. {
  445. OnReceiveEnded();
  446. ValidateClosed(closeReason);
  447. }
  448. // return false if the connection has entered the closing procedure or has closed already
  449. protected bool OnReceiveStarted()
  450. {
  451. return AddStateFlag(SocketState.InReceiving, true);
  452. }
  453. protected void OnReceiveEnded()
  454. {
  455. RemoveStateFlag(SocketState.InReceiving);
  456. }
  457. /// <summary>
  458. /// Validates the socket is not in the sending or receiving operation.
  459. /// </summary>
  460. /// <returns></returns>
  461. private bool ValidateNotInSendingReceiving()
  462. {
  463. var oldState = m_State;
  464. if ((oldState & SocketState.InSendingReceivingMask) == oldState)
  465. {
  466. return true;
  467. }
  468. return false;
  469. }
  470. private const int m_CloseReasonMagic = 256;
  471. private int GetCloseReasonValue(CloseReason reason)
  472. {
  473. return ((int)reason + 1) * m_CloseReasonMagic;
  474. }
  475. private CloseReason GetCloseReasonFromState()
  476. {
  477. return (CloseReason)(m_State / m_CloseReasonMagic - 1);
  478. }
  479. private void FireCloseEvent()
  480. {
  481. OnClosed(GetCloseReasonFromState());
  482. }
  483. private void ValidateClosed(CloseReason closeReason)
  484. {
  485. if (IsClosed)
  486. return;
  487. if (CheckState(SocketState.InClosing))
  488. {
  489. if (ValidateNotInSendingReceiving())
  490. {
  491. FireCloseEvent();
  492. }
  493. }
  494. else
  495. {
  496. Close(closeReason);
  497. }
  498. }
  499. public abstract int OrigReceiveOffset { get; }
  500. protected virtual bool IsIgnorableSocketError(int socketErrorCode)
  501. {
  502. if (socketErrorCode == 10004 //Interrupted
  503. || socketErrorCode == 10053 //ConnectionAborted
  504. || socketErrorCode == 10054 //ConnectionReset
  505. || socketErrorCode == 10058 //Shutdown
  506. || socketErrorCode == 10060 //TimedOut
  507. || socketErrorCode == 995 //OperationAborted
  508. || socketErrorCode == -1073741299)
  509. {
  510. return true;
  511. }
  512. return false;
  513. }
  514. protected virtual bool IsIgnorableException(Exception e, out int socketErrorCode)
  515. {
  516. socketErrorCode = 0;
  517. if (e is ObjectDisposedException || e is NullReferenceException)
  518. return true;
  519. SocketException socketException = null;
  520. if (e is IOException)
  521. {
  522. if (e.InnerException is ObjectDisposedException || e.InnerException is NullReferenceException)
  523. return true;
  524. socketException = e.InnerException as SocketException;
  525. }
  526. else
  527. {
  528. socketException = e as SocketException;
  529. }
  530. if (socketException == null)
  531. return false;
  532. socketErrorCode = socketException.ErrorCode;
  533. if (Config.LogAllSocketException)
  534. return false;
  535. return IsIgnorableSocketError(socketErrorCode);
  536. }
  537. }
  538. }