ISCSIServer.PDUProcessor.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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.Session.ISID = request.ISID;
  77. state.ConnectionParameters.CID = request.CID;
  78. m_connectionManager.AddConnection(state);
  79. }
  80. Log(Severity.Verbose, "[{0}] Login Response parameters: {1}", state.ConnectionIdentifier, KeyValuePairUtils.ToString(response.LoginParameters));
  81. state.SendQueue.Enqueue(response);
  82. }
  83. else
  84. {
  85. // Before the Full Feature Phase is established, only Login Request and Login Response PDUs are allowed.
  86. Log(Severity.Error, "[{0}] Improper command during login phase, OpCode: 0x{1}", state.ConnectionIdentifier, pdu.OpCode.ToString("x"));
  87. if (state.Session.TSIH == 0)
  88. {
  89. // A target receiving any PDU except a Login request before the Login phase is started MUST
  90. // immediately terminate the connection on which the PDU was received.
  91. state.ClientSocket.Close();
  92. }
  93. else
  94. {
  95. // Once the Login phase has started, if the target receives any PDU except a Login request,
  96. // it MUST send a Login reject (with Status "invalid during login") and then disconnect.
  97. LoginResponsePDU loginResponse = new LoginResponsePDU();
  98. loginResponse.TSIH = state.Session.TSIH;
  99. loginResponse.Status = LoginResponseStatusName.InvalidDuringLogon;
  100. state.SendQueue.Enqueue(loginResponse);
  101. }
  102. }
  103. }
  104. else // Logged in
  105. {
  106. if (pdu is TextRequestPDU)
  107. {
  108. TextRequestPDU request = (TextRequestPDU)pdu;
  109. TextResponsePDU response = ServerResponseHelper.GetTextResponsePDU(request, m_targets);
  110. state.SendQueue.Enqueue(response);
  111. }
  112. else if (pdu is LogoutRequestPDU)
  113. {
  114. Log(Severity.Verbose, "[{0}] Logour Request", state.ConnectionIdentifier);
  115. LogoutRequestPDU request = (LogoutRequestPDU)pdu;
  116. if (state.Session.IsDiscovery && request.ReasonCode != LogoutReasonCode.CloseTheSession)
  117. {
  118. // RFC 3720: Discovery-session: The target MUST ONLY accept [..] logout request with the reason "close the session"
  119. RejectPDU reject = new RejectPDU();
  120. reject.Reason = RejectReason.ProtocolError;
  121. reject.Data = ByteReader.ReadBytes(pdu.GetBytes(), 0, 48);
  122. state.SendQueue.Enqueue(reject);
  123. }
  124. else
  125. {
  126. List<ConnectionState> connectionsToClose = new List<ConnectionState>();
  127. if (request.ReasonCode == LogoutReasonCode.CloseTheSession)
  128. {
  129. connectionsToClose = m_connectionManager.GetSessionConnections(state.Session.ISID, state.Session.TSIH);
  130. }
  131. else
  132. {
  133. // 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.
  134. ConnectionState existingConnection = m_connectionManager.FindConnection(state.Session.ISID, state.Session.TSIH, request.CID);
  135. if (existingConnection != null && existingConnection != state)
  136. {
  137. connectionsToClose.Add(existingConnection);
  138. }
  139. connectionsToClose.Add(state);
  140. }
  141. foreach (ConnectionState connection in connectionsToClose)
  142. {
  143. // Wait for pending I/O to complete.
  144. connection.RunningSCSICommands.WaitUntilZero();
  145. if (connection != state)
  146. {
  147. SocketUtils.ReleaseSocket(connection.ClientSocket);
  148. }
  149. m_connectionManager.RemoveConnection(connection);
  150. }
  151. LogoutResponsePDU response = ServerResponseHelper.GetLogoutResponsePDU(request);
  152. state.SendQueue.Enqueue(response);
  153. // connection will be closed after a LogoutResponsePDU has been sent.
  154. }
  155. }
  156. else if (state.Session.IsDiscovery)
  157. {
  158. // The target MUST ONLY accept text requests with the SendTargets key and a logout
  159. // request with the reason "close the session". All other requests MUST be rejected.
  160. Log(Severity.Error, "[{0}] Improper command during discovery session, OpCode: 0x{1}", state.ConnectionIdentifier, pdu.OpCode.ToString("x"));
  161. RejectPDU reject = new RejectPDU();
  162. reject.Reason = RejectReason.ProtocolError;
  163. reject.Data = ByteReader.ReadBytes(pdu.GetBytes(), 0, 48);
  164. state.SendQueue.Enqueue(reject);
  165. }
  166. else if (pdu is NOPOutPDU)
  167. {
  168. NOPOutPDU request = (NOPOutPDU)pdu;
  169. if (request.InitiatorTaskTag != 0xFFFFFFFF)
  170. {
  171. NOPInPDU response = ServerResponseHelper.GetNOPResponsePDU(request);
  172. state.SendQueue.Enqueue(response);
  173. }
  174. }
  175. else if (pdu is SCSIDataOutPDU || pdu is SCSICommandPDU)
  176. {
  177. // RFC 3720: the iSCSI target layer MUST deliver the commands for execution (to the SCSI execution engine) in the order specified by CmdSN.
  178. // e.g. read requests should not be executed while previous write request data is being received (via R2T)
  179. List<SCSICommandPDU> commandsToExecute = null;
  180. List<ReadyToTransferPDU> readyToTransferPDUs = new List<ReadyToTransferPDU>();
  181. if (pdu is SCSIDataOutPDU)
  182. {
  183. SCSIDataOutPDU request = (SCSIDataOutPDU)pdu;
  184. 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);
  185. try
  186. {
  187. readyToTransferPDUs = TargetResponseHelper.GetReadyToTransferPDUs(request, state.Target, state.Session, state.ConnectionParameters, out commandsToExecute);
  188. }
  189. catch (InvalidTargetTransferTagException ex)
  190. {
  191. Log(Severity.Error, "[{0}] Invalid TargetTransferTag: {1}", state.ConnectionIdentifier, ex.TargetTransferTag);
  192. RejectPDU reject = new RejectPDU();
  193. reject.InitiatorTaskTag = request.InitiatorTaskTag;
  194. reject.Reason = RejectReason.InvalidPDUField;
  195. reject.Data = ByteReader.ReadBytes(request.GetBytes(), 0, 48);
  196. state.SendQueue.Enqueue(reject);
  197. }
  198. }
  199. else
  200. {
  201. SCSICommandPDU command = (SCSICommandPDU)pdu;
  202. 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);
  203. readyToTransferPDUs = TargetResponseHelper.GetReadyToTransferPDUs(command, state.Target, state.Session, state.ConnectionParameters, out commandsToExecute);
  204. }
  205. foreach (ReadyToTransferPDU readyToTransferPDU in readyToTransferPDUs)
  206. {
  207. state.SendQueue.Enqueue(readyToTransferPDU);
  208. }
  209. if (commandsToExecute != null)
  210. {
  211. state.RunningSCSICommands.Add(commandsToExecute.Count);
  212. }
  213. foreach (SCSICommandPDU commandPDU in commandsToExecute)
  214. {
  215. Log(Severity.Debug, "[{0}] Queuing command: CmdSN: {1}", state.ConnectionIdentifier, commandPDU.CmdSN);
  216. state.Target.QueueCommand(commandPDU.CommandDescriptorBlock, commandPDU.LUN, commandPDU.Data, commandPDU, state.OnCommandCompleted);
  217. }
  218. }
  219. else if (pdu is LoginRequestPDU)
  220. {
  221. Log(Severity.Error, "[{0}] Protocol Error (Login request during full feature phase)", state.ConnectionIdentifier);
  222. // RFC 3720: Login requests and responses MUST be used exclusively during Login.
  223. // On any connection, the login phase MUST immediately follow TCP connection establishment and
  224. // a subsequent Login Phase MUST NOT occur before tearing down a connection
  225. RejectPDU reject = new RejectPDU();
  226. reject.Reason = RejectReason.ProtocolError;
  227. reject.Data = ByteReader.ReadBytes(pdu.GetBytes(), 0, 48);
  228. state.SendQueue.Enqueue(reject);
  229. }
  230. else
  231. {
  232. Log(Severity.Error, "[{0}] Unsupported command, OpCode: 0x{1}", state.ConnectionIdentifier, pdu.OpCode.ToString("x"));
  233. RejectPDU reject = new RejectPDU();
  234. reject.Reason = RejectReason.CommandNotSupported;
  235. reject.Data = ByteReader.ReadBytes(pdu.GetBytes(), 0, 48);
  236. state.SendQueue.Enqueue(reject);
  237. }
  238. }
  239. Log(Severity.Trace, "Leaving ProcessPDU");
  240. }
  241. }
  242. }