ISCSIServer.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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 void Start()
  59. {
  60. if (!m_listening)
  61. {
  62. Log(Severity.Information, "Starting Server");
  63. m_listening = true;
  64. m_listenerSocket = new Socket(m_listenerEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  65. m_listenerSocket.Bind(m_listenerEP);
  66. m_listenerSocket.Listen(1000);
  67. m_listenerSocket.BeginAccept(ConnectRequestCallback, m_listenerSocket);
  68. }
  69. }
  70. // This method accepts new connections
  71. private void ConnectRequestCallback(IAsyncResult ar)
  72. {
  73. Socket listenerSocket = (Socket)ar.AsyncState;
  74. Socket clientSocket;
  75. try
  76. {
  77. clientSocket = listenerSocket.EndAccept(ar);
  78. }
  79. catch (ObjectDisposedException)
  80. {
  81. return;
  82. }
  83. catch (SocketException)
  84. {
  85. return;
  86. }
  87. Log(Severity.Information, "New connection has been accepted");
  88. ConnectionState state = new ConnectionState();
  89. state.ConnectionParameters.InitiatorEndPoint = clientSocket.RemoteEndPoint as IPEndPoint;
  90. state.ReceiveBuffer = new byte[ConnectionState.ReceiveBufferSize];
  91. // Disable the Nagle Algorithm for this tcp socket:
  92. clientSocket.NoDelay = true;
  93. state.ClientSocket = clientSocket;
  94. Thread senderThread = new Thread(delegate()
  95. {
  96. ProcessSendQueue(state);
  97. });
  98. senderThread.IsBackground = true;
  99. senderThread.Start();
  100. try
  101. {
  102. clientSocket.BeginReceive(state.ReceiveBuffer, 0, ConnectionState.ReceiveBufferSize, 0, ReceiveCallback, state);
  103. }
  104. catch (ObjectDisposedException)
  105. {
  106. Log(Severity.Debug, "[OnConnectRequest] BeginReceive ObjectDisposedException");
  107. }
  108. catch (SocketException ex)
  109. {
  110. Log(Severity.Debug, "[OnConnectRequest] BeginReceive SocketException: {0}", ex.Message);
  111. }
  112. m_listenerSocket.BeginAccept(ConnectRequestCallback, m_listenerSocket);
  113. }
  114. public void Stop()
  115. {
  116. Log(Severity.Information, "Stopping Server");
  117. m_listening = false;
  118. SocketUtils.ReleaseSocket(m_listenerSocket);
  119. }
  120. private void ReceiveCallback(IAsyncResult result)
  121. {
  122. if (!m_listening)
  123. {
  124. return;
  125. }
  126. ConnectionState state = (ConnectionState)result.AsyncState;
  127. Socket clientSocket = state.ClientSocket;
  128. if (!clientSocket.Connected)
  129. {
  130. return;
  131. }
  132. int numberOfBytesReceived;
  133. try
  134. {
  135. numberOfBytesReceived = clientSocket.EndReceive(result);
  136. }
  137. catch (ObjectDisposedException)
  138. {
  139. Log(Severity.Debug, "[ReceiveCallback] EndReceive ObjectDisposedException");
  140. return;
  141. }
  142. catch (SocketException ex)
  143. {
  144. Log(Severity.Debug, "[ReceiveCallback] EndReceive SocketException: {0}", ex.Message);
  145. return;
  146. }
  147. if (numberOfBytesReceived == 0)
  148. {
  149. // The other side has closed the connection
  150. clientSocket.Close();
  151. Log(Severity.Verbose, "The initiator has closed the connection");
  152. // Wait for pending I/O to complete.
  153. state.RunningSCSICommands.WaitUntilZero();
  154. state.SendQueue.Stop();
  155. m_connectionManager.RemoveConnection(state);
  156. return;
  157. }
  158. byte[] currentBuffer = ByteReader.ReadBytes(state.ReceiveBuffer, 0, numberOfBytesReceived);
  159. ProcessCurrentBuffer(currentBuffer, state);
  160. try
  161. {
  162. clientSocket.BeginReceive(state.ReceiveBuffer, 0, ConnectionState.ReceiveBufferSize, 0, ReceiveCallback, state);
  163. }
  164. catch (ObjectDisposedException)
  165. {
  166. Log(Severity.Debug, "[ReceiveCallback] BeginReceive ObjectDisposedException");
  167. }
  168. catch (SocketException ex)
  169. {
  170. Log(Severity.Debug, "[ReceiveCallback] BeginReceive SocketException: {0}", ex.Message);
  171. }
  172. }
  173. private void ProcessCurrentBuffer(byte[] currentBuffer, ConnectionState state)
  174. {
  175. Socket clientSocket = state.ClientSocket;
  176. if (state.ConnectionBuffer.Length == 0)
  177. {
  178. state.ConnectionBuffer = currentBuffer;
  179. }
  180. else
  181. {
  182. state.ConnectionBuffer = ByteUtils.Concatenate(state.ConnectionBuffer, currentBuffer);
  183. }
  184. // we now have all PDU bytes received so far in state.ConnectionBuffer
  185. int bytesLeftInBuffer = state.ConnectionBuffer.Length;
  186. while (bytesLeftInBuffer >= 8)
  187. {
  188. int bufferOffset = state.ConnectionBuffer.Length - bytesLeftInBuffer;
  189. int pduLength = ISCSIPDU.GetPDULength(state.ConnectionBuffer, bufferOffset);
  190. if (pduLength > bytesLeftInBuffer)
  191. {
  192. Log(Severity.Debug, "[{0}][ProcessCurrentBuffer] Bytes left in receive buffer: {1}", state.ConnectionIdentifier, bytesLeftInBuffer);
  193. break;
  194. }
  195. else
  196. {
  197. byte[] pduBytes = ByteReader.ReadBytes(state.ConnectionBuffer, bufferOffset, pduLength);
  198. bytesLeftInBuffer -= pduLength;
  199. ISCSIPDU pdu = null;
  200. try
  201. {
  202. pdu = ISCSIPDU.GetPDU(pduBytes);
  203. }
  204. catch (Exception ex)
  205. {
  206. Log(Severity.Error, "[{0}] Failed to read PDU (Exception: {1})", state.ConnectionIdentifier, ex.Message);
  207. RejectPDU reject = new RejectPDU();
  208. reject.Reason = RejectReason.InvalidPDUField;
  209. reject.Data = ByteReader.ReadBytes(pduBytes, 0, 48);
  210. state.SendQueue.Enqueue(reject);
  211. }
  212. if (pdu != null)
  213. {
  214. if (pdu.GetType() == typeof(ISCSIPDU))
  215. {
  216. Log(Severity.Error, "[{0}][ProcessCurrentBuffer] Unsupported PDU (0x{1})", state.ConnectionIdentifier, pdu.OpCode.ToString("X"));
  217. // Unsupported PDU
  218. RejectPDU reject = new RejectPDU();
  219. reject.InitiatorTaskTag = pdu.InitiatorTaskTag;
  220. reject.Reason = RejectReason.CommandNotSupported;
  221. reject.Data = ByteReader.ReadBytes(pduBytes, 0, 48);
  222. state.SendQueue.Enqueue(reject);
  223. }
  224. else
  225. {
  226. bool valid = ValidateCommandNumbering(pdu, state);
  227. if (valid)
  228. {
  229. ProcessPDU(pdu, state);
  230. }
  231. else
  232. {
  233. // We ignore this PDU
  234. Log(Severity.Warning, "[{0}] Ignoring PDU with CmdSN outside of expected range", state.ConnectionIdentifier);
  235. }
  236. }
  237. }
  238. if (!clientSocket.Connected)
  239. {
  240. // Do not continue to process the buffer if the other side closed the connection
  241. if (bytesLeftInBuffer > 0)
  242. {
  243. Log(Severity.Debug, "[{0}] Buffer processing aborted, bytes left in receive buffer: {1}", state.ConnectionIdentifier, bytesLeftInBuffer);
  244. }
  245. return;
  246. }
  247. }
  248. }
  249. if (bytesLeftInBuffer > 0)
  250. {
  251. state.ConnectionBuffer = ByteReader.ReadBytes(state.ConnectionBuffer, state.ConnectionBuffer.Length - bytesLeftInBuffer, bytesLeftInBuffer);
  252. }
  253. else
  254. {
  255. state.ConnectionBuffer = new byte[0];
  256. }
  257. }
  258. private void ProcessSendQueue(ConnectionState state)
  259. {
  260. while (true)
  261. {
  262. Log(Severity.Trace, "Entering ProcessSendQueue");
  263. ISCSIPDU response;
  264. bool stopped = !state.SendQueue.TryDequeue(out response);
  265. if (stopped)
  266. {
  267. return;
  268. }
  269. Socket clientSocket = state.ClientSocket;
  270. PDUHelper.SetStatSN(response, state.ConnectionParameters.StatSN);
  271. PDUHelper.SetExpCmdSN(response, state.Session.ExpCmdSN, state.Session.ExpCmdSN + state.Session.CommandQueueSize);
  272. if (response is SCSIResponsePDU ||
  273. response is LoginResponsePDU ||
  274. response is TextResponsePDU ||
  275. (response is SCSIDataInPDU && ((SCSIDataInPDU)response).StatusPresent) ||
  276. response is RejectPDU)
  277. {
  278. state.ConnectionParameters.StatSN++;
  279. }
  280. try
  281. {
  282. clientSocket.Send(response.GetBytes());
  283. Log(Severity.Verbose, "[{0}] Sent response to initator, Operation: {1}, Size: {2}", state.ConnectionIdentifier, response.OpCode, response.Length);
  284. if (response is LogoutResponsePDU)
  285. {
  286. clientSocket.Close(); // We can close the connection now
  287. Log(Severity.Trace, "Leaving ProcessSendQueue");
  288. return;
  289. }
  290. else if (response is LoginResponsePDU)
  291. {
  292. if (((LoginResponsePDU)response).Status == LoginResponseStatusName.InvalidDuringLogon)
  293. {
  294. clientSocket.Close(); // We can close the connection now
  295. Log(Severity.Trace, "Leaving ProcessSendQueue");
  296. return;
  297. }
  298. }
  299. }
  300. catch (SocketException ex)
  301. {
  302. Log(Severity.Verbose, "[{0}] Failed to send response to initator. Operation: {1}, Size: {2}, SocketException: {3}", state.ConnectionIdentifier, response.OpCode, response.Length, ex.Message);
  303. Log(Severity.Trace, "Leaving ProcessSendQueue");
  304. return;
  305. }
  306. catch (ObjectDisposedException)
  307. {
  308. Log(Severity.Verbose, "[{0}] Failed to send response to initator. Operation: {1}, Size: {2}. ObjectDisposedException", state.ConnectionIdentifier, response.OpCode, response.Length);
  309. Log(Severity.Trace, "Leaving ProcessSendQueue");
  310. return;
  311. }
  312. }
  313. }
  314. public void Log(Severity severity, string message)
  315. {
  316. // To be thread-safe we must capture the delegate reference first
  317. EventHandler<LogEntry> handler = OnLogEntry;
  318. if (handler != null)
  319. {
  320. handler(this, new LogEntry(DateTime.Now, severity, "iSCSI Server", message));
  321. }
  322. }
  323. public void Log(Severity severity, string message, params object[] args)
  324. {
  325. Log(severity, String.Format(message, args));
  326. }
  327. }
  328. }