ISCSIServer.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. /* Copyright (C) 2012-2016 Tal Aloni <tal.aloni.il@gmail.com>. All rights reserved.
  2. *
  3. * You can redistribute this program and/or modify it under the terms of
  4. * the GNU Lesser Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. */
  7. using System;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Net;
  11. using System.Net.Sockets;
  12. using System.Text;
  13. using System.Threading;
  14. using Utilities;
  15. namespace ISCSI.Server
  16. {
  17. /// <summary>
  18. /// an iSCSI server that can serve multiple iSCSI targets
  19. /// </summary>
  20. public partial class ISCSIServer
  21. {
  22. public const int DefaultPort = 3260;
  23. private Socket m_listenerSocket;
  24. private bool m_listening;
  25. private Thread m_keepAliveThread;
  26. private TargetList m_targets = new TargetList();
  27. private SessionManager m_sessionManager = new SessionManager();
  28. private ConnectionManager m_connectionManager = new ConnectionManager();
  29. public event EventHandler<LogEntry> OnLogEntry;
  30. /// <summary>
  31. /// Server needs to be started with Start()
  32. /// </summary>
  33. public ISCSIServer()
  34. {
  35. }
  36. public void AddTarget(ISCSITarget target)
  37. {
  38. m_targets.AddTarget(target);
  39. }
  40. public void AddTargets(List<ISCSITarget> targets)
  41. {
  42. foreach (ISCSITarget target in targets)
  43. {
  44. m_targets.AddTarget(target);
  45. }
  46. }
  47. public bool RemoveTarget(string targetName)
  48. {
  49. // We use m_targets.Lock to synchronize between the login logic and the target removal logic.
  50. // We must obtain the lock before calling IsTargetInUse() to prevent a successful login to a target followed by its removal.
  51. lock (m_targets.Lock)
  52. {
  53. if (!m_sessionManager.IsTargetInUse(targetName))
  54. {
  55. return m_targets.RemoveTarget(targetName);
  56. }
  57. }
  58. return false;
  59. }
  60. /// <exception cref="System.Net.Sockets.SocketException"></exception>
  61. public void Start()
  62. {
  63. Start(DefaultPort);
  64. }
  65. /// <param name="listenerPort">The port on which the iSCSI server will listen</param>
  66. /// <exception cref="System.Net.Sockets.SocketException"></exception>
  67. public void Start(int listenerPort)
  68. {
  69. Start(new IPEndPoint(IPAddress.Any, listenerPort));
  70. }
  71. /// <exception cref="System.Net.Sockets.SocketException"></exception>
  72. public void Start(IPEndPoint listenerEndPoint)
  73. {
  74. Start(listenerEndPoint, TimeSpan.FromMinutes(5));
  75. }
  76. /// <param name="listenerEP">The endpoint on which the iSCSI server will listen</param>
  77. /// <param name="keepAliveTime">The duration between keep-alive transmissions</param>
  78. /// <exception cref="System.Net.Sockets.SocketException"></exception>
  79. public void Start(IPEndPoint listenerEndPoint, TimeSpan? keepAliveTime)
  80. {
  81. if (!m_listening)
  82. {
  83. Log(Severity.Information, "Starting Server");
  84. m_listenerSocket = new Socket(listenerEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  85. m_listenerSocket.Bind(listenerEndPoint);
  86. m_listenerSocket.Listen(1000);
  87. m_listenerSocket.BeginAccept(ConnectRequestCallback, m_listenerSocket);
  88. m_listening = true;
  89. if (keepAliveTime.HasValue)
  90. {
  91. m_keepAliveThread = new Thread(delegate()
  92. {
  93. while (m_listening)
  94. {
  95. Thread.Sleep(keepAliveTime.Value);
  96. m_connectionManager.SendKeepAlive();
  97. }
  98. });
  99. m_keepAliveThread.IsBackground = true;
  100. m_keepAliveThread.Start();
  101. }
  102. }
  103. }
  104. // This method accepts new connections
  105. private void ConnectRequestCallback(IAsyncResult ar)
  106. {
  107. Socket listenerSocket = (Socket)ar.AsyncState;
  108. Socket clientSocket;
  109. try
  110. {
  111. clientSocket = listenerSocket.EndAccept(ar);
  112. }
  113. catch (ObjectDisposedException)
  114. {
  115. return;
  116. }
  117. catch (SocketException)
  118. {
  119. return;
  120. }
  121. Log(Severity.Information, "New connection has been accepted");
  122. ConnectionState state = new ConnectionState();
  123. state.ConnectionParameters.InitiatorEndPoint = clientSocket.RemoteEndPoint as IPEndPoint;
  124. state.ReceiveBuffer = new byte[ConnectionState.ReceiveBufferSize];
  125. // Disable the Nagle Algorithm for this tcp socket:
  126. clientSocket.NoDelay = true;
  127. state.ClientSocket = clientSocket;
  128. Thread senderThread = new Thread(delegate()
  129. {
  130. ProcessSendQueue(state);
  131. });
  132. senderThread.IsBackground = true;
  133. senderThread.Start();
  134. try
  135. {
  136. clientSocket.BeginReceive(state.ReceiveBuffer, 0, ConnectionState.ReceiveBufferSize, 0, ReceiveCallback, state);
  137. }
  138. catch (ObjectDisposedException)
  139. {
  140. Log(Severity.Debug, "[OnConnectRequest] BeginReceive ObjectDisposedException");
  141. }
  142. catch (SocketException ex)
  143. {
  144. Log(Severity.Debug, "[OnConnectRequest] BeginReceive SocketException: {0}", ex.Message);
  145. }
  146. m_listenerSocket.BeginAccept(ConnectRequestCallback, m_listenerSocket);
  147. }
  148. public void Stop()
  149. {
  150. Log(Severity.Information, "Stopping Server");
  151. m_listening = false;
  152. if (m_keepAliveThread != null)
  153. {
  154. m_keepAliveThread.Abort();
  155. }
  156. SocketUtils.ReleaseSocket(m_listenerSocket);
  157. lock (m_targets.Lock)
  158. {
  159. List<ISCSITarget> targets = m_targets.GetList();
  160. foreach (ISCSITarget target in targets)
  161. {
  162. ResetTarget(target.TargetName);
  163. }
  164. }
  165. }
  166. /// <summary>
  167. /// Will terminate all TCP connections to all initiators (all sessions will be terminated)
  168. /// </summary>
  169. public void ResetTarget(string targetName)
  170. {
  171. List<ISCSISession> targetSessions = m_sessionManager.FindTargetSessions(targetName);
  172. foreach (ISCSISession session in targetSessions)
  173. {
  174. List<ConnectionState> sessionConnections = m_connectionManager.GetSessionConnections(session);
  175. foreach (ConnectionState sessionConnection in sessionConnections)
  176. {
  177. m_connectionManager.ReleaseConnection(sessionConnection);
  178. }
  179. m_sessionManager.RemoveSession(session, SessionTerminationReason.TargetReset);
  180. }
  181. }
  182. private void ReceiveCallback(IAsyncResult result)
  183. {
  184. if (!m_listening)
  185. {
  186. return;
  187. }
  188. ConnectionState state = (ConnectionState)result.AsyncState;
  189. Socket clientSocket = state.ClientSocket;
  190. if (!clientSocket.Connected)
  191. {
  192. HandleConnectionTermination(state);
  193. return;
  194. }
  195. int numberOfBytesReceived;
  196. try
  197. {
  198. numberOfBytesReceived = clientSocket.EndReceive(result);
  199. }
  200. catch (ObjectDisposedException)
  201. {
  202. HandleConnectionTermination(state);
  203. Log(Severity.Debug, "[ReceiveCallback] EndReceive ObjectDisposedException");
  204. return;
  205. }
  206. catch (SocketException ex)
  207. {
  208. HandleConnectionTermination(state);
  209. Log(Severity.Debug, "[ReceiveCallback] EndReceive SocketException: {0}", ex.Message);
  210. return;
  211. }
  212. if (numberOfBytesReceived == 0)
  213. {
  214. // The other side has closed the connection
  215. Log(Severity.Verbose, "[{0}] The initiator has closed the connection", state.ConnectionIdentifier);
  216. HandleConnectionTermination(state);
  217. return;
  218. }
  219. byte[] currentBuffer = ByteReader.ReadBytes(state.ReceiveBuffer, 0, numberOfBytesReceived);
  220. ProcessCurrentBuffer(currentBuffer, state);
  221. try
  222. {
  223. clientSocket.BeginReceive(state.ReceiveBuffer, 0, ConnectionState.ReceiveBufferSize, 0, ReceiveCallback, state);
  224. }
  225. catch (ObjectDisposedException)
  226. {
  227. HandleConnectionTermination(state);
  228. Log(Severity.Debug, "[ReceiveCallback] BeginReceive ObjectDisposedException");
  229. }
  230. catch (SocketException ex)
  231. {
  232. HandleConnectionTermination(state);
  233. Log(Severity.Debug, "[ReceiveCallback] BeginReceive SocketException: {0}", ex.Message);
  234. }
  235. }
  236. private void HandleConnectionTermination(ConnectionState state)
  237. {
  238. m_connectionManager.ReleaseConnection(state);
  239. if (state.Session != null)
  240. {
  241. List<ConnectionState> connections = m_connectionManager.GetSessionConnections(state.Session);
  242. if (connections.Count == 0)
  243. {
  244. Thread timeoutThread = new Thread(delegate()
  245. {
  246. // Session timeout is an event defined to occur when the last connection [..] timeout expires
  247. int timeout = state.Session.DefaultTime2Wait + state.Session.DefaultTime2Retain;
  248. Thread.Sleep(timeout * 1000);
  249. // Check if there are still no connections in this session
  250. connections = m_connectionManager.GetSessionConnections(state.Session);
  251. if (connections.Count == 0)
  252. {
  253. m_sessionManager.RemoveSession(state.Session, SessionTerminationReason.ConnectionFailure);
  254. }
  255. });
  256. timeoutThread.IsBackground = true;
  257. timeoutThread.Start();
  258. }
  259. }
  260. }
  261. private void ProcessCurrentBuffer(byte[] currentBuffer, ConnectionState state)
  262. {
  263. Socket clientSocket = state.ClientSocket;
  264. if (state.ConnectionBuffer.Length == 0)
  265. {
  266. state.ConnectionBuffer = currentBuffer;
  267. }
  268. else
  269. {
  270. state.ConnectionBuffer = ByteUtils.Concatenate(state.ConnectionBuffer, currentBuffer);
  271. }
  272. // we now have all PDU bytes received so far in state.ConnectionBuffer
  273. int bytesLeftInBuffer = state.ConnectionBuffer.Length;
  274. while (bytesLeftInBuffer >= 8)
  275. {
  276. int bufferOffset = state.ConnectionBuffer.Length - bytesLeftInBuffer;
  277. int pduLength = ISCSIPDU.GetPDULength(state.ConnectionBuffer, bufferOffset);
  278. if (pduLength > bytesLeftInBuffer)
  279. {
  280. Log(Severity.Debug, "[{0}][ProcessCurrentBuffer] Bytes left in receive buffer: {1}", state.ConnectionIdentifier, bytesLeftInBuffer);
  281. break;
  282. }
  283. else
  284. {
  285. ISCSIPDU pdu = null;
  286. try
  287. {
  288. pdu = ISCSIPDU.GetPDU(state.ConnectionBuffer, bufferOffset);
  289. }
  290. catch (Exception ex)
  291. {
  292. Log(Severity.Error, "[{0}] Failed to read PDU (Exception: {1})", state.ConnectionIdentifier, ex.Message);
  293. RejectPDU reject = new RejectPDU();
  294. reject.Reason = RejectReason.InvalidPDUField;
  295. reject.Data = ByteReader.ReadBytes(state.ConnectionBuffer, bufferOffset, 48);
  296. state.SendQueue.Enqueue(reject);
  297. }
  298. bytesLeftInBuffer -= pduLength;
  299. if (pdu != null)
  300. {
  301. if (pdu.GetType() == typeof(ISCSIPDU))
  302. {
  303. Log(Severity.Error, "[{0}][ProcessCurrentBuffer] Unsupported PDU (0x{1})", state.ConnectionIdentifier, pdu.OpCode.ToString("X"));
  304. // Unsupported PDU
  305. RejectPDU reject = new RejectPDU();
  306. reject.InitiatorTaskTag = pdu.InitiatorTaskTag;
  307. reject.Reason = RejectReason.CommandNotSupported;
  308. reject.Data = ByteReader.ReadBytes(state.ConnectionBuffer, bufferOffset, 48);
  309. state.SendQueue.Enqueue(reject);
  310. }
  311. else
  312. {
  313. bool valid = ValidateCommandNumbering(pdu, state);
  314. if (valid)
  315. {
  316. ProcessPDU(pdu, state);
  317. }
  318. else
  319. {
  320. // We ignore this PDU
  321. Log(Severity.Warning, "[{0}] Ignoring PDU with CmdSN outside of expected range", state.ConnectionIdentifier);
  322. }
  323. }
  324. }
  325. if (!clientSocket.Connected)
  326. {
  327. // Do not continue to process the buffer if the other side closed the connection
  328. if (bytesLeftInBuffer > 0)
  329. {
  330. Log(Severity.Debug, "[{0}] Buffer processing aborted, bytes left in receive buffer: {1}", state.ConnectionIdentifier, bytesLeftInBuffer);
  331. }
  332. return;
  333. }
  334. }
  335. }
  336. if (bytesLeftInBuffer > 0)
  337. {
  338. state.ConnectionBuffer = ByteReader.ReadBytes(state.ConnectionBuffer, state.ConnectionBuffer.Length - bytesLeftInBuffer, bytesLeftInBuffer);
  339. }
  340. else
  341. {
  342. state.ConnectionBuffer = new byte[0];
  343. }
  344. }
  345. private void ProcessSendQueue(ConnectionState state)
  346. {
  347. while (true)
  348. {
  349. Log(Severity.Trace, "Entering ProcessSendQueue");
  350. ISCSIPDU response;
  351. bool stopped = !state.SendQueue.TryDequeue(out response);
  352. if (stopped)
  353. {
  354. return;
  355. }
  356. Socket clientSocket = state.ClientSocket;
  357. PDUHelper.SetStatSN(response, state.ConnectionParameters.StatSN);
  358. if (state.Session != null)
  359. {
  360. PDUHelper.SetExpCmdSN(response, state.Session.ExpCmdSN, state.Session.ExpCmdSN + state.Session.CommandQueueSize);
  361. }
  362. if (response is SCSIResponsePDU ||
  363. response is LoginResponsePDU ||
  364. response is TextResponsePDU ||
  365. (response is SCSIDataInPDU && ((SCSIDataInPDU)response).StatusPresent) ||
  366. response is RejectPDU)
  367. {
  368. state.ConnectionParameters.StatSN++;
  369. }
  370. try
  371. {
  372. clientSocket.Send(response.GetBytes());
  373. Log(Severity.Verbose, "[{0}] Sent response to initator, Operation: {1}, Size: {2}", state.ConnectionIdentifier, response.OpCode, response.Length);
  374. if (response is LogoutResponsePDU)
  375. {
  376. clientSocket.Close(); // We can close the connection now
  377. Log(Severity.Trace, "Leaving ProcessSendQueue");
  378. return;
  379. }
  380. else if (response is LoginResponsePDU)
  381. {
  382. if (((LoginResponsePDU)response).Status != LoginResponseStatusName.Success)
  383. {
  384. // Login Response: If the Status Class is not 0, the initiator and target MUST close the TCP connection.
  385. clientSocket.Close(); // We can close the connection now
  386. Log(Severity.Trace, "Leaving ProcessSendQueue");
  387. return;
  388. }
  389. }
  390. }
  391. catch (SocketException ex)
  392. {
  393. Log(Severity.Verbose, "[{0}] Failed to send response to initator. Operation: {1}, Size: {2}, SocketException: {3}", state.ConnectionIdentifier, response.OpCode, response.Length, ex.Message);
  394. Log(Severity.Trace, "Leaving ProcessSendQueue");
  395. return;
  396. }
  397. catch (ObjectDisposedException)
  398. {
  399. Log(Severity.Verbose, "[{0}] Failed to send response to initator. Operation: {1}, Size: {2}. ObjectDisposedException", state.ConnectionIdentifier, response.OpCode, response.Length);
  400. Log(Severity.Trace, "Leaving ProcessSendQueue");
  401. return;
  402. }
  403. }
  404. }
  405. public void Log(Severity severity, string message)
  406. {
  407. // To be thread-safe we must capture the delegate reference first
  408. EventHandler<LogEntry> handler = OnLogEntry;
  409. if (handler != null)
  410. {
  411. handler(this, new LogEntry(DateTime.Now, severity, "iSCSI Server", message));
  412. }
  413. }
  414. public void Log(Severity severity, string message, params object[] args)
  415. {
  416. Log(severity, String.Format(message, args));
  417. }
  418. }
  419. }