ISCSIServer.PDUProcessor.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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.Net;
  10. using System.Net.Sockets;
  11. using System.Text;
  12. using Utilities;
  13. namespace ISCSI.Server
  14. {
  15. public partial class ISCSIServer
  16. {
  17. private bool ValidateCommandNumbering(ISCSIPDU pdu, ConnectionState state)
  18. {
  19. if (state.Session == null)
  20. {
  21. return true;
  22. }
  23. uint? cmdSN = PDUHelper.GetCmdSN(pdu);
  24. Log(Severity.Verbose, "[{0}] Received PDU from initiator, Operation: {1}, Size: {2}, CmdSN: {3}", state.ConnectionIdentifier, (ISCSIOpCodeName)pdu.OpCode, pdu.Length, cmdSN);
  25. // RFC 3720: On any connection, the iSCSI initiator MUST send the commands in increasing order of CmdSN,
  26. // except for commands that are retransmitted due to digest error recovery and connection recovery.
  27. if (cmdSN.HasValue)
  28. {
  29. if (state.Session.CommandNumberingStarted)
  30. {
  31. if (cmdSN != state.Session.ExpCmdSN)
  32. {
  33. return false;
  34. }
  35. }
  36. else
  37. {
  38. state.Session.ExpCmdSN = cmdSN.Value;
  39. state.Session.CommandNumberingStarted = true;
  40. }
  41. if (pdu is LogoutRequestPDU || pdu is TextRequestPDU || pdu is SCSICommandPDU || pdu is RejectPDU)
  42. {
  43. if (!pdu.ImmediateDelivery)
  44. {
  45. state.Session.ExpCmdSN++;
  46. }
  47. }
  48. }
  49. return true;
  50. }
  51. private void ProcessPDU(ISCSIPDU pdu, ConnectionState state)
  52. {
  53. Log(Severity.Trace, "Entering ProcessPDU");
  54. if (state.Session == null || !state.Session.IsFullFeaturePhase)
  55. {
  56. if (pdu is LoginRequestPDU)
  57. {
  58. LoginRequestPDU request = (LoginRequestPDU)pdu;
  59. string loginIdentifier = String.Format("ISID={0},TSIH={1},CID={2}", request.ISID.ToString("x"), request.TSIH.ToString("x"), request.CID.ToString("x"));
  60. Log(Severity.Verbose, "[{0}] Login Request, current stage: {1}, next stage: {2}, parameters: {3}", loginIdentifier, request.CurrentStage, request.NextStage, FormatNullDelimitedText(request.LoginParametersText));
  61. LoginResponsePDU response = GetLoginResponsePDU(request, state.ConnectionParameters);
  62. if (state.Session != null && state.Session.IsFullFeaturePhase)
  63. {
  64. m_connectionManager.AddConnection(state);
  65. }
  66. Log(Severity.Verbose, "[{0}] Login Response parameters: {1}", state.ConnectionIdentifier, FormatNullDelimitedText(response.LoginParametersText));
  67. state.SendQueue.Enqueue(response);
  68. }
  69. else
  70. {
  71. // Before the Full Feature Phase is established, only Login Request and Login Response PDUs are allowed.
  72. Log(Severity.Warning, "[{0}] Initiator error: Improper command during login phase, OpCode: 0x{1}", state.ConnectionIdentifier, pdu.OpCode.ToString("x"));
  73. if (state.Session == null)
  74. {
  75. // A target receiving any PDU except a Login request before the Login phase is started MUST
  76. // immediately terminate the connection on which the PDU was received.
  77. state.ClientSocket.Close();
  78. }
  79. else
  80. {
  81. // Once the Login phase has started, if the target receives any PDU except a Login request,
  82. // it MUST send a Login reject (with Status "invalid during login") and then disconnect.
  83. LoginResponsePDU loginResponse = new LoginResponsePDU();
  84. loginResponse.TSIH = state.Session.TSIH;
  85. loginResponse.Status = LoginResponseStatusName.InvalidDuringLogon;
  86. state.SendQueue.Enqueue(loginResponse);
  87. }
  88. }
  89. }
  90. else // Logged in
  91. {
  92. if (pdu is TextRequestPDU)
  93. {
  94. TextRequestPDU request = (TextRequestPDU)pdu;
  95. TextResponsePDU response;
  96. lock (m_targets.Lock)
  97. {
  98. response = ServerResponseHelper.GetTextResponsePDU(request, m_targets.GetList());
  99. }
  100. state.SendQueue.Enqueue(response);
  101. }
  102. else if (pdu is LogoutRequestPDU)
  103. {
  104. Log(Severity.Verbose, "[{0}] Logour Request", state.ConnectionIdentifier);
  105. LogoutRequestPDU request = (LogoutRequestPDU)pdu;
  106. if (state.Session.IsDiscovery && request.ReasonCode != LogoutReasonCode.CloseTheSession)
  107. {
  108. // RFC 3720: Discovery-session: The target MUST ONLY accept [..] logout request with the reason "close the session"
  109. RejectPDU reject = new RejectPDU();
  110. reject.Reason = RejectReason.ProtocolError;
  111. reject.Data = ByteReader.ReadBytes(pdu.GetBytes(), 0, 48);
  112. state.SendQueue.Enqueue(reject);
  113. }
  114. else
  115. {
  116. List<ConnectionState> connectionsToClose = new List<ConnectionState>();
  117. if (request.ReasonCode == LogoutReasonCode.CloseTheSession)
  118. {
  119. connectionsToClose = m_connectionManager.GetSessionConnections(state.Session.ISID, state.Session.TSIH);
  120. }
  121. else
  122. {
  123. // RFC 3720: A Logout for a CID may be performed on a different transport connection when the TCP connection for the CID has already been terminated.
  124. ConnectionState existingConnection = m_connectionManager.FindConnection(state.Session.ISID, state.Session.TSIH, request.CID);
  125. if (existingConnection != null && existingConnection != state)
  126. {
  127. connectionsToClose.Add(existingConnection);
  128. }
  129. connectionsToClose.Add(state);
  130. }
  131. foreach (ConnectionState connection in connectionsToClose)
  132. {
  133. // Wait for pending I/O to complete.
  134. connection.RunningSCSICommands.WaitUntilZero();
  135. if (connection != state)
  136. {
  137. SocketUtils.ReleaseSocket(connection.ClientSocket);
  138. }
  139. m_connectionManager.RemoveConnection(connection);
  140. }
  141. if (request.ReasonCode == LogoutReasonCode.CloseTheSession)
  142. {
  143. Log(Severity.Verbose, "[{0}] Session has been closed", state.Session.SessionIdentifier);
  144. m_sessionManager.RemoveSession(state.Session, SessionTerminationReason.Logout);
  145. }
  146. LogoutResponsePDU response = ServerResponseHelper.GetLogoutResponsePDU(request);
  147. state.SendQueue.Enqueue(response);
  148. // connection will be closed after a LogoutResponsePDU has been sent.
  149. }
  150. }
  151. else if (state.Session.IsDiscovery)
  152. {
  153. // The target MUST ONLY accept text requests with the SendTargets key and a logout
  154. // request with the reason "close the session". All other requests MUST be rejected.
  155. Log(Severity.Warning, "[{0}] Initiator error: Improper command during discovery session, OpCode: 0x{1}", state.ConnectionIdentifier, pdu.OpCode.ToString("x"));
  156. RejectPDU reject = new RejectPDU();
  157. reject.Reason = RejectReason.ProtocolError;
  158. reject.Data = ByteReader.ReadBytes(pdu.GetBytes(), 0, 48);
  159. state.SendQueue.Enqueue(reject);
  160. }
  161. else if (pdu is NOPOutPDU)
  162. {
  163. NOPOutPDU request = (NOPOutPDU)pdu;
  164. if (request.InitiatorTaskTag != 0xFFFFFFFF)
  165. {
  166. NOPInPDU response = ServerResponseHelper.GetNOPResponsePDU(request);
  167. state.SendQueue.Enqueue(response);
  168. }
  169. }
  170. else if (pdu is SCSIDataOutPDU || pdu is SCSICommandPDU)
  171. {
  172. // RFC 3720: the iSCSI target layer MUST deliver the commands for execution (to the SCSI execution engine) in the order specified by CmdSN.
  173. // e.g. read requests should not be executed while previous write request data is being received (via R2T)
  174. List<SCSICommandPDU> commandsToExecute = null;
  175. List<ReadyToTransferPDU> readyToTransferPDUs = new List<ReadyToTransferPDU>();
  176. if (pdu is SCSIDataOutPDU)
  177. {
  178. SCSIDataOutPDU request = (SCSIDataOutPDU)pdu;
  179. Log(Severity.Debug, "[{0}] SCSIDataOutPDU: Target transfer tag: {1}, LUN: {2}, Buffer offset: {3}, Data segment length: {4}, DataSN: {5}, Final: {6}", state.ConnectionIdentifier, request.TargetTransferTag, (ushort)request.LUN, request.BufferOffset, request.DataSegmentLength, request.DataSN, request.Final);
  180. try
  181. {
  182. readyToTransferPDUs = TargetResponseHelper.GetReadyToTransferPDUs(request, state.ConnectionParameters, out commandsToExecute);
  183. }
  184. catch (InvalidTargetTransferTagException ex)
  185. {
  186. Log(Severity.Warning, "[{0}] Initiator error: Invalid TargetTransferTag: {1}", state.ConnectionIdentifier, ex.TargetTransferTag);
  187. RejectPDU reject = new RejectPDU();
  188. reject.InitiatorTaskTag = request.InitiatorTaskTag;
  189. reject.Reason = RejectReason.InvalidPDUField;
  190. reject.Data = ByteReader.ReadBytes(request.GetBytes(), 0, 48);
  191. state.SendQueue.Enqueue(reject);
  192. }
  193. }
  194. else
  195. {
  196. SCSICommandPDU command = (SCSICommandPDU)pdu;
  197. Log(Severity.Debug, "[{0}] SCSICommandPDU: CmdSN: {1}, LUN: {2}, Data segment length: {3}, Expected Data Transfer Length: {4}, Final: {5}", state.ConnectionIdentifier, command.CmdSN, (ushort)command.LUN, command.DataSegmentLength, command.ExpectedDataTransferLength, command.Final);
  198. readyToTransferPDUs = TargetResponseHelper.GetReadyToTransferPDUs(command, state.ConnectionParameters, out commandsToExecute);
  199. }
  200. foreach (ReadyToTransferPDU readyToTransferPDU in readyToTransferPDUs)
  201. {
  202. state.SendQueue.Enqueue(readyToTransferPDU);
  203. }
  204. if (commandsToExecute != null)
  205. {
  206. state.RunningSCSICommands.Add(commandsToExecute.Count);
  207. }
  208. foreach (SCSICommandPDU commandPDU in commandsToExecute)
  209. {
  210. Log(Severity.Debug, "[{0}] Queuing command: CmdSN: {1}", state.ConnectionIdentifier, commandPDU.CmdSN);
  211. state.Target.QueueCommand(commandPDU.CommandDescriptorBlock, commandPDU.LUN, commandPDU.Data, commandPDU, state.OnCommandCompleted);
  212. }
  213. }
  214. else if (pdu is LoginRequestPDU)
  215. {
  216. Log(Severity.Warning, "[{0}] Initiator Error: Login request during full feature phase", state.ConnectionIdentifier);
  217. // RFC 3720: Login requests and responses MUST be used exclusively during Login.
  218. // On any connection, the login phase MUST immediately follow TCP connection establishment and
  219. // a subsequent Login Phase MUST NOT occur before tearing down a connection
  220. RejectPDU reject = new RejectPDU();
  221. reject.Reason = RejectReason.ProtocolError;
  222. reject.Data = ByteReader.ReadBytes(pdu.GetBytes(), 0, 48);
  223. state.SendQueue.Enqueue(reject);
  224. }
  225. else
  226. {
  227. Log(Severity.Error, "[{0}] Unsupported command, OpCode: 0x{1}", state.ConnectionIdentifier, pdu.OpCode.ToString("x"));
  228. RejectPDU reject = new RejectPDU();
  229. reject.Reason = RejectReason.CommandNotSupported;
  230. reject.Data = ByteReader.ReadBytes(pdu.GetBytes(), 0, 48);
  231. state.SendQueue.Enqueue(reject);
  232. }
  233. }
  234. Log(Severity.Trace, "Leaving ProcessPDU");
  235. }
  236. private static string FormatNullDelimitedText(string text)
  237. {
  238. string result = String.Join(", ", text.Split('\0'));
  239. if (result.EndsWith(", "))
  240. {
  241. result = result.Remove(result.Length - 2);
  242. }
  243. return result;
  244. }
  245. }
  246. }