ISCSIServer.PDUProcessor.cs 14 KB

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