ISCSIServer.PDUProcessor.cs 14 KB

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