ISCSIServer.PDUProcessor.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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. LogTrace("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 = GetTextResponsePDU(request, state.ConnectionParameters);
  96. state.SendQueue.Enqueue(response);
  97. }
  98. else if (pdu is LogoutRequestPDU)
  99. {
  100. LogoutRequestPDU request = (LogoutRequestPDU)pdu;
  101. ISCSIPDU response = GetLogoutResponsePDU(request, state.ConnectionParameters);
  102. state.SendQueue.Enqueue(response);
  103. }
  104. else if (state.Session.IsDiscovery)
  105. {
  106. // The target MUST ONLY accept text requests with the SendTargets key and a logout
  107. // request with the reason "close the session". All other requests MUST be rejected.
  108. Log(Severity.Warning, "[{0}] Initiator error: Improper command during discovery session, OpCode: 0x{1}", state.ConnectionIdentifier, pdu.OpCode.ToString("x"));
  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 if (pdu is NOPOutPDU)
  115. {
  116. NOPOutPDU request = (NOPOutPDU)pdu;
  117. if (request.InitiatorTaskTag != 0xFFFFFFFF)
  118. {
  119. NOPInPDU response = ServerResponseHelper.GetNOPResponsePDU(request);
  120. state.SendQueue.Enqueue(response);
  121. }
  122. }
  123. else if (pdu is SCSIDataOutPDU || pdu is SCSICommandPDU)
  124. {
  125. // RFC 3720: the iSCSI target layer MUST deliver the commands for execution (to the SCSI execution engine) in the order specified by CmdSN.
  126. // e.g. read requests should not be executed while previous write request data is being received (via R2T)
  127. List<SCSICommandPDU> commandsToExecute = null;
  128. List<ReadyToTransferPDU> readyToTransferPDUs = new List<ReadyToTransferPDU>();
  129. if (pdu is SCSIDataOutPDU)
  130. {
  131. SCSIDataOutPDU request = (SCSIDataOutPDU)pdu;
  132. Log(Severity.Debug, "[{0}] SCSIDataOutPDU: InitiatorTaskTag: {1}, TargetTransferTag: {2}, LUN: {3}, BufferOffset: {4}, DataSegmentLength: {5}, DataSN: {6}, Final: {7}", state.ConnectionIdentifier, request.InitiatorTaskTag.ToString("x"), request.TargetTransferTag.ToString("x"), (ushort)request.LUN, request.BufferOffset, request.DataSegmentLength, request.DataSN, request.Final);
  133. try
  134. {
  135. readyToTransferPDUs = TargetResponseHelper.GetReadyToTransferPDUs(request, state.ConnectionParameters, out commandsToExecute);
  136. }
  137. catch (InvalidTargetTransferTagException ex)
  138. {
  139. Log(Severity.Warning, "[{0}] Initiator error: Invalid TargetTransferTag: {1}", state.ConnectionIdentifier, ex.TargetTransferTag.ToString("x"));
  140. RejectPDU reject = new RejectPDU();
  141. reject.InitiatorTaskTag = request.InitiatorTaskTag;
  142. reject.Reason = RejectReason.InvalidPDUField;
  143. reject.Data = ByteReader.ReadBytes(request.GetBytes(), 0, 48);
  144. state.SendQueue.Enqueue(reject);
  145. }
  146. }
  147. else
  148. {
  149. SCSICommandPDU command = (SCSICommandPDU)pdu;
  150. Log(Severity.Debug, "[{0}] SCSICommandPDU: CmdSN: {1}, LUN: {2}, InitiatorTaskTag: {3}, DataSegmentLength: {4}, ExpectedDataTransferLength: {5}, Final: {6}", state.ConnectionIdentifier, command.CmdSN, (ushort)command.LUN, command.InitiatorTaskTag.ToString("x"), command.DataSegmentLength, command.ExpectedDataTransferLength, command.Final);
  151. readyToTransferPDUs = TargetResponseHelper.GetReadyToTransferPDUs(command, state.ConnectionParameters, out commandsToExecute);
  152. }
  153. foreach (ReadyToTransferPDU readyToTransferPDU in readyToTransferPDUs)
  154. {
  155. state.SendQueue.Enqueue(readyToTransferPDU);
  156. Log(Severity.Debug, "[{0}] Enqueued R2T, InitiatorTaskTag: {1}, TargetTransferTag: {2}, BufferOffset: {3}, DesiredDataTransferLength: {4}, R2TSN: {5}", state.ConnectionIdentifier, readyToTransferPDU.InitiatorTaskTag.ToString("x"), readyToTransferPDU.TargetTransferTag.ToString("x"), readyToTransferPDU.BufferOffset, readyToTransferPDU.DesiredDataTransferLength, readyToTransferPDU.R2TSN);
  157. }
  158. if (commandsToExecute != null)
  159. {
  160. state.RunningSCSICommands.Add(commandsToExecute.Count);
  161. }
  162. foreach (SCSICommandPDU commandPDU in commandsToExecute)
  163. {
  164. Log(Severity.Debug, "[{0}] Queuing command: CmdSN: {1}, InitiatorTaskTag: {2}", state.ConnectionIdentifier, commandPDU.CmdSN, commandPDU.InitiatorTaskTag.ToString("x"));
  165. state.Target.QueueCommand(commandPDU.CommandDescriptorBlock, commandPDU.LUN, commandPDU.Data, commandPDU, state.OnCommandCompleted);
  166. }
  167. }
  168. else if (pdu is LoginRequestPDU)
  169. {
  170. Log(Severity.Warning, "[{0}] Initiator Error: Login request during full feature phase", state.ConnectionIdentifier);
  171. // RFC 3720: Login requests and responses MUST be used exclusively during Login.
  172. // On any connection, the login phase MUST immediately follow TCP connection establishment and
  173. // a subsequent Login Phase MUST NOT occur before tearing down a connection
  174. RejectPDU reject = new RejectPDU();
  175. reject.Reason = RejectReason.ProtocolError;
  176. reject.Data = ByteReader.ReadBytes(pdu.GetBytes(), 0, 48);
  177. state.SendQueue.Enqueue(reject);
  178. }
  179. else
  180. {
  181. Log(Severity.Error, "[{0}] Unsupported command, OpCode: 0x{1}", state.ConnectionIdentifier, pdu.OpCode.ToString("x"));
  182. RejectPDU reject = new RejectPDU();
  183. reject.Reason = RejectReason.CommandNotSupported;
  184. reject.Data = ByteReader.ReadBytes(pdu.GetBytes(), 0, 48);
  185. state.SendQueue.Enqueue(reject);
  186. }
  187. }
  188. LogTrace("Leaving ProcessPDU");
  189. }
  190. private static string FormatNullDelimitedText(string text)
  191. {
  192. string result = String.Join(", ", text.Split('\0'));
  193. if (result.EndsWith(", "))
  194. {
  195. result = result.Remove(result.Length - 2);
  196. }
  197. return result;
  198. }
  199. }
  200. }