ISCSIServer.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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 IPEndPoint m_listenerEP;
  24. private Socket m_listenerSocket;
  25. private bool m_listening;
  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. public ISCSIServer() : this(DefaultPort)
  31. { }
  32. /// <summary>
  33. /// Server needs to be started with Start()
  34. /// </summary>
  35. /// <param name="port">The port on which the iSCSI server will listen</param>
  36. public ISCSIServer(int port) : this(new IPEndPoint(IPAddress.Any, port))
  37. {
  38. }
  39. /// <summary>
  40. /// Server needs to be started with Start()
  41. /// </summary>
  42. /// <param name="listenerEP">The endpoint on which the iSCSI server will listen</param>
  43. public ISCSIServer(IPEndPoint listenerEP)
  44. {
  45. m_listenerEP = listenerEP;
  46. }
  47. public void AddTarget(ISCSITarget target)
  48. {
  49. m_targets.AddTarget(target);
  50. }
  51. public void AddTargets(List<ISCSITarget> targets)
  52. {
  53. foreach (ISCSITarget target in targets)
  54. {
  55. m_targets.AddTarget(target);
  56. }
  57. }
  58. public bool RemoveTarget(string targetName)
  59. {
  60. // We use m_targets.Lock to synchronize between the login logic and the target removal logic.
  61. // We must obtain the lock before calling IsTargetInUse() to prevent a successful login to a target followed by its removal.
  62. lock (m_targets.Lock)
  63. {
  64. if (!m_sessionManager.IsTargetInUse(targetName))
  65. {
  66. return m_targets.RemoveTarget(targetName);
  67. }
  68. }
  69. return false;
  70. }
  71. public void Start()
  72. {
  73. if (!m_listening)
  74. {
  75. Log(Severity.Information, "Starting Server");
  76. m_listening = true;
  77. m_listenerSocket = new Socket(m_listenerEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  78. m_listenerSocket.Bind(m_listenerEP);
  79. m_listenerSocket.Listen(1000);
  80. m_listenerSocket.BeginAccept(ConnectRequestCallback, m_listenerSocket);
  81. }
  82. }
  83. // This method accepts new connections
  84. private void ConnectRequestCallback(IAsyncResult ar)
  85. {
  86. Socket listenerSocket = (Socket)ar.AsyncState;
  87. Socket clientSocket;
  88. try
  89. {
  90. clientSocket = listenerSocket.EndAccept(ar);
  91. }
  92. catch (ObjectDisposedException)
  93. {
  94. return;
  95. }
  96. catch (SocketException)
  97. {
  98. return;
  99. }
  100. Log(Severity.Information, "New connection has been accepted");
  101. ConnectionState state = new ConnectionState();
  102. state.ConnectionParameters.InitiatorEndPoint = clientSocket.RemoteEndPoint as IPEndPoint;
  103. state.ReceiveBuffer = new byte[ConnectionState.ReceiveBufferSize];
  104. // Disable the Nagle Algorithm for this tcp socket:
  105. clientSocket.NoDelay = true;
  106. state.ClientSocket = clientSocket;
  107. Thread senderThread = new Thread(delegate()
  108. {
  109. ProcessSendQueue(state);
  110. });
  111. senderThread.IsBackground = true;
  112. senderThread.Start();
  113. try
  114. {
  115. clientSocket.BeginReceive(state.ReceiveBuffer, 0, ConnectionState.ReceiveBufferSize, 0, ReceiveCallback, state);
  116. }
  117. catch (ObjectDisposedException)
  118. {
  119. Log(Severity.Debug, "[OnConnectRequest] BeginReceive ObjectDisposedException");
  120. }
  121. catch (SocketException ex)
  122. {
  123. Log(Severity.Debug, "[OnConnectRequest] BeginReceive SocketException: {0}", ex.Message);
  124. }
  125. m_listenerSocket.BeginAccept(ConnectRequestCallback, m_listenerSocket);
  126. }
  127. public void Stop()
  128. {
  129. Log(Severity.Information, "Stopping Server");
  130. m_listening = false;
  131. SocketUtils.ReleaseSocket(m_listenerSocket);
  132. }
  133. private void ReceiveCallback(IAsyncResult result)
  134. {
  135. if (!m_listening)
  136. {
  137. return;
  138. }
  139. ConnectionState state = (ConnectionState)result.AsyncState;
  140. Socket clientSocket = state.ClientSocket;
  141. if (!clientSocket.Connected)
  142. {
  143. return;
  144. }
  145. int numberOfBytesReceived;
  146. try
  147. {
  148. numberOfBytesReceived = clientSocket.EndReceive(result);
  149. }
  150. catch (ObjectDisposedException)
  151. {
  152. Log(Severity.Debug, "[ReceiveCallback] EndReceive ObjectDisposedException");
  153. return;
  154. }
  155. catch (SocketException ex)
  156. {
  157. Log(Severity.Debug, "[ReceiveCallback] EndReceive SocketException: {0}", ex.Message);
  158. return;
  159. }
  160. if (numberOfBytesReceived == 0)
  161. {
  162. // The other side has closed the connection
  163. Log(Severity.Verbose, "The initiator has closed the connection");
  164. m_connectionManager.ReleaseConnection(state);
  165. if (state.Session != null)
  166. {
  167. List<ConnectionState> connections = m_connectionManager.GetSessionConnections(state.Session);
  168. if (connections.Count == 0)
  169. {
  170. Thread timeoutThread = new Thread(delegate()
  171. {
  172. // Session timeout is an event defined to occur when the last connection [..] timeout expires
  173. int timeout = state.Session.DefaultTime2Wait + state.Session.DefaultTime2Retain;
  174. Thread.Sleep(timeout * 1000);
  175. // Check if there are still no connections in this session
  176. connections = m_connectionManager.GetSessionConnections(state.Session);
  177. if (connections.Count == 0)
  178. {
  179. m_sessionManager.RemoveSession(state.Session);
  180. }
  181. });
  182. timeoutThread.IsBackground = true;
  183. timeoutThread.Start();
  184. }
  185. }
  186. return;
  187. }
  188. byte[] currentBuffer = ByteReader.ReadBytes(state.ReceiveBuffer, 0, numberOfBytesReceived);
  189. ProcessCurrentBuffer(currentBuffer, state);
  190. try
  191. {
  192. clientSocket.BeginReceive(state.ReceiveBuffer, 0, ConnectionState.ReceiveBufferSize, 0, ReceiveCallback, state);
  193. }
  194. catch (ObjectDisposedException)
  195. {
  196. Log(Severity.Debug, "[ReceiveCallback] BeginReceive ObjectDisposedException");
  197. }
  198. catch (SocketException ex)
  199. {
  200. Log(Severity.Debug, "[ReceiveCallback] BeginReceive SocketException: {0}", ex.Message);
  201. }
  202. }
  203. private void ProcessCurrentBuffer(byte[] currentBuffer, ConnectionState state)
  204. {
  205. Socket clientSocket = state.ClientSocket;
  206. if (state.ConnectionBuffer.Length == 0)
  207. {
  208. state.ConnectionBuffer = currentBuffer;
  209. }
  210. else
  211. {
  212. state.ConnectionBuffer = ByteUtils.Concatenate(state.ConnectionBuffer, currentBuffer);
  213. }
  214. // we now have all PDU bytes received so far in state.ConnectionBuffer
  215. int bytesLeftInBuffer = state.ConnectionBuffer.Length;
  216. while (bytesLeftInBuffer >= 8)
  217. {
  218. int bufferOffset = state.ConnectionBuffer.Length - bytesLeftInBuffer;
  219. int pduLength = ISCSIPDU.GetPDULength(state.ConnectionBuffer, bufferOffset);
  220. if (pduLength > bytesLeftInBuffer)
  221. {
  222. Log(Severity.Debug, "[{0}][ProcessCurrentBuffer] Bytes left in receive buffer: {1}", state.ConnectionIdentifier, bytesLeftInBuffer);
  223. break;
  224. }
  225. else
  226. {
  227. byte[] pduBytes = ByteReader.ReadBytes(state.ConnectionBuffer, bufferOffset, pduLength);
  228. bytesLeftInBuffer -= pduLength;
  229. ISCSIPDU pdu = null;
  230. try
  231. {
  232. pdu = ISCSIPDU.GetPDU(pduBytes);
  233. }
  234. catch (Exception ex)
  235. {
  236. Log(Severity.Error, "[{0}] Failed to read PDU (Exception: {1})", state.ConnectionIdentifier, ex.Message);
  237. RejectPDU reject = new RejectPDU();
  238. reject.Reason = RejectReason.InvalidPDUField;
  239. reject.Data = ByteReader.ReadBytes(pduBytes, 0, 48);
  240. state.SendQueue.Enqueue(reject);
  241. }
  242. if (pdu != null)
  243. {
  244. if (pdu.GetType() == typeof(ISCSIPDU))
  245. {
  246. Log(Severity.Error, "[{0}][ProcessCurrentBuffer] Unsupported PDU (0x{1})", state.ConnectionIdentifier, pdu.OpCode.ToString("X"));
  247. // Unsupported PDU
  248. RejectPDU reject = new RejectPDU();
  249. reject.InitiatorTaskTag = pdu.InitiatorTaskTag;
  250. reject.Reason = RejectReason.CommandNotSupported;
  251. reject.Data = ByteReader.ReadBytes(pduBytes, 0, 48);
  252. state.SendQueue.Enqueue(reject);
  253. }
  254. else
  255. {
  256. bool valid = ValidateCommandNumbering(pdu, state);
  257. if (valid)
  258. {
  259. ProcessPDU(pdu, state);
  260. }
  261. else
  262. {
  263. // We ignore this PDU
  264. Log(Severity.Warning, "[{0}] Ignoring PDU with CmdSN outside of expected range", state.ConnectionIdentifier);
  265. }
  266. }
  267. }
  268. if (!clientSocket.Connected)
  269. {
  270. // Do not continue to process the buffer if the other side closed the connection
  271. if (bytesLeftInBuffer > 0)
  272. {
  273. Log(Severity.Debug, "[{0}] Buffer processing aborted, bytes left in receive buffer: {1}", state.ConnectionIdentifier, bytesLeftInBuffer);
  274. }
  275. return;
  276. }
  277. }
  278. }
  279. if (bytesLeftInBuffer > 0)
  280. {
  281. state.ConnectionBuffer = ByteReader.ReadBytes(state.ConnectionBuffer, state.ConnectionBuffer.Length - bytesLeftInBuffer, bytesLeftInBuffer);
  282. }
  283. else
  284. {
  285. state.ConnectionBuffer = new byte[0];
  286. }
  287. }
  288. private void ProcessSendQueue(ConnectionState state)
  289. {
  290. while (true)
  291. {
  292. Log(Severity.Trace, "Entering ProcessSendQueue");
  293. ISCSIPDU response;
  294. bool stopped = !state.SendQueue.TryDequeue(out response);
  295. if (stopped)
  296. {
  297. return;
  298. }
  299. Socket clientSocket = state.ClientSocket;
  300. PDUHelper.SetStatSN(response, state.ConnectionParameters.StatSN);
  301. if (state.Session != null)
  302. {
  303. PDUHelper.SetExpCmdSN(response, state.Session.ExpCmdSN, state.Session.ExpCmdSN + state.Session.CommandQueueSize);
  304. }
  305. if (response is SCSIResponsePDU ||
  306. response is LoginResponsePDU ||
  307. response is TextResponsePDU ||
  308. (response is SCSIDataInPDU && ((SCSIDataInPDU)response).StatusPresent) ||
  309. response is RejectPDU)
  310. {
  311. state.ConnectionParameters.StatSN++;
  312. }
  313. try
  314. {
  315. clientSocket.Send(response.GetBytes());
  316. Log(Severity.Verbose, "[{0}] Sent response to initator, Operation: {1}, Size: {2}", state.ConnectionIdentifier, response.OpCode, response.Length);
  317. if (response is LogoutResponsePDU)
  318. {
  319. clientSocket.Close(); // We can close the connection now
  320. Log(Severity.Trace, "Leaving ProcessSendQueue");
  321. return;
  322. }
  323. else if (response is LoginResponsePDU)
  324. {
  325. if (((LoginResponsePDU)response).Status != LoginResponseStatusName.Success)
  326. {
  327. // Login Response: If the Status Class is not 0, the initiator and target MUST close the TCP connection.
  328. clientSocket.Close(); // We can close the connection now
  329. Log(Severity.Trace, "Leaving ProcessSendQueue");
  330. return;
  331. }
  332. }
  333. }
  334. catch (SocketException ex)
  335. {
  336. Log(Severity.Verbose, "[{0}] Failed to send response to initator. Operation: {1}, Size: {2}, SocketException: {3}", state.ConnectionIdentifier, response.OpCode, response.Length, ex.Message);
  337. Log(Severity.Trace, "Leaving ProcessSendQueue");
  338. return;
  339. }
  340. catch (ObjectDisposedException)
  341. {
  342. Log(Severity.Verbose, "[{0}] Failed to send response to initator. Operation: {1}, Size: {2}. ObjectDisposedException", state.ConnectionIdentifier, response.OpCode, response.Length);
  343. Log(Severity.Trace, "Leaving ProcessSendQueue");
  344. return;
  345. }
  346. }
  347. }
  348. public void Log(Severity severity, string message)
  349. {
  350. // To be thread-safe we must capture the delegate reference first
  351. EventHandler<LogEntry> handler = OnLogEntry;
  352. if (handler != null)
  353. {
  354. handler(this, new LogEntry(DateTime.Now, severity, "iSCSI Server", message));
  355. }
  356. }
  357. public void Log(Severity severity, string message, params object[] args)
  358. {
  359. Log(severity, String.Format(message, args));
  360. }
  361. }
  362. }