ISCSIServer.PDUProcessor.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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, FormatNullDelimitedText(request.LoginParametersText));
  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, FormatNullDelimitedText(response.LoginParametersText));
  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.Warning, "[{0}] Initiator error: 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;
  109. lock (m_targets.Lock)
  110. {
  111. response = ServerResponseHelper.GetTextResponsePDU(request, m_targets.GetList());
  112. }
  113. state.SendQueue.Enqueue(response);
  114. }
  115. else if (pdu is LogoutRequestPDU)
  116. {
  117. Log(Severity.Verbose, "[{0}] Logour Request", state.ConnectionIdentifier);
  118. LogoutRequestPDU request = (LogoutRequestPDU)pdu;
  119. if (state.Session.IsDiscovery && request.ReasonCode != LogoutReasonCode.CloseTheSession)
  120. {
  121. // RFC 3720: Discovery-session: The target MUST ONLY accept [..] logout request with the reason "close the session"
  122. RejectPDU reject = new RejectPDU();
  123. reject.Reason = RejectReason.ProtocolError;
  124. reject.Data = ByteReader.ReadBytes(pdu.GetBytes(), 0, 48);
  125. state.SendQueue.Enqueue(reject);
  126. }
  127. else
  128. {
  129. List<ConnectionState> connectionsToClose = new List<ConnectionState>();
  130. if (request.ReasonCode == LogoutReasonCode.CloseTheSession)
  131. {
  132. connectionsToClose = m_connectionManager.GetSessionConnections(state.Session.ISID, state.Session.TSIH);
  133. }
  134. else
  135. {
  136. // 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.
  137. ConnectionState existingConnection = m_connectionManager.FindConnection(state.Session.ISID, state.Session.TSIH, request.CID);
  138. if (existingConnection != null && existingConnection != state)
  139. {
  140. connectionsToClose.Add(existingConnection);
  141. }
  142. connectionsToClose.Add(state);
  143. }
  144. foreach (ConnectionState connection in connectionsToClose)
  145. {
  146. // Wait for pending I/O to complete.
  147. connection.RunningSCSICommands.WaitUntilZero();
  148. if (connection != state)
  149. {
  150. SocketUtils.ReleaseSocket(connection.ClientSocket);
  151. }
  152. m_connectionManager.RemoveConnection(connection);
  153. }
  154. LogoutResponsePDU response = ServerResponseHelper.GetLogoutResponsePDU(request);
  155. state.SendQueue.Enqueue(response);
  156. // connection will be closed after a LogoutResponsePDU has been sent.
  157. }
  158. }
  159. else if (state.Session.IsDiscovery)
  160. {
  161. // The target MUST ONLY accept text requests with the SendTargets key and a logout
  162. // request with the reason "close the session". All other requests MUST be rejected.
  163. Log(Severity.Warning, "[{0}] Initiator error: Improper command during discovery session, OpCode: 0x{1}", state.ConnectionIdentifier, pdu.OpCode.ToString("x"));
  164. RejectPDU reject = new RejectPDU();
  165. reject.Reason = RejectReason.ProtocolError;
  166. reject.Data = ByteReader.ReadBytes(pdu.GetBytes(), 0, 48);
  167. state.SendQueue.Enqueue(reject);
  168. }
  169. else if (pdu is NOPOutPDU)
  170. {
  171. NOPOutPDU request = (NOPOutPDU)pdu;
  172. if (request.InitiatorTaskTag != 0xFFFFFFFF)
  173. {
  174. NOPInPDU response = ServerResponseHelper.GetNOPResponsePDU(request);
  175. state.SendQueue.Enqueue(response);
  176. }
  177. }
  178. else if (pdu is SCSIDataOutPDU || pdu is SCSICommandPDU)
  179. {
  180. // RFC 3720: the iSCSI target layer MUST deliver the commands for execution (to the SCSI execution engine) in the order specified by CmdSN.
  181. // e.g. read requests should not be executed while previous write request data is being received (via R2T)
  182. List<SCSICommandPDU> commandsToExecute = null;
  183. List<ReadyToTransferPDU> readyToTransferPDUs = new List<ReadyToTransferPDU>();
  184. if (pdu is SCSIDataOutPDU)
  185. {
  186. SCSIDataOutPDU request = (SCSIDataOutPDU)pdu;
  187. 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);
  188. try
  189. {
  190. readyToTransferPDUs = TargetResponseHelper.GetReadyToTransferPDUs(request, state.Session, state.ConnectionParameters, out commandsToExecute);
  191. }
  192. catch (InvalidTargetTransferTagException ex)
  193. {
  194. Log(Severity.Warning, "[{0}] Initiator error: Invalid TargetTransferTag: {1}", state.ConnectionIdentifier, ex.TargetTransferTag);
  195. RejectPDU reject = new RejectPDU();
  196. reject.InitiatorTaskTag = request.InitiatorTaskTag;
  197. reject.Reason = RejectReason.InvalidPDUField;
  198. reject.Data = ByteReader.ReadBytes(request.GetBytes(), 0, 48);
  199. state.SendQueue.Enqueue(reject);
  200. }
  201. }
  202. else
  203. {
  204. SCSICommandPDU command = (SCSICommandPDU)pdu;
  205. 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);
  206. readyToTransferPDUs = TargetResponseHelper.GetReadyToTransferPDUs(command, state.Session, state.ConnectionParameters, out commandsToExecute);
  207. }
  208. foreach (ReadyToTransferPDU readyToTransferPDU in readyToTransferPDUs)
  209. {
  210. state.SendQueue.Enqueue(readyToTransferPDU);
  211. }
  212. if (commandsToExecute != null)
  213. {
  214. state.RunningSCSICommands.Add(commandsToExecute.Count);
  215. }
  216. foreach (SCSICommandPDU commandPDU in commandsToExecute)
  217. {
  218. Log(Severity.Debug, "[{0}] Queuing command: CmdSN: {1}", state.ConnectionIdentifier, commandPDU.CmdSN);
  219. state.Target.QueueCommand(commandPDU.CommandDescriptorBlock, commandPDU.LUN, commandPDU.Data, commandPDU, state.OnCommandCompleted);
  220. }
  221. }
  222. else if (pdu is LoginRequestPDU)
  223. {
  224. Log(Severity.Warning, "[{0}] Initiator Error: Login request during full feature phase", state.ConnectionIdentifier);
  225. // RFC 3720: Login requests and responses MUST be used exclusively during Login.
  226. // On any connection, the login phase MUST immediately follow TCP connection establishment and
  227. // a subsequent Login Phase MUST NOT occur before tearing down a connection
  228. RejectPDU reject = new RejectPDU();
  229. reject.Reason = RejectReason.ProtocolError;
  230. reject.Data = ByteReader.ReadBytes(pdu.GetBytes(), 0, 48);
  231. state.SendQueue.Enqueue(reject);
  232. }
  233. else
  234. {
  235. Log(Severity.Error, "[{0}] Unsupported command, OpCode: 0x{1}", state.ConnectionIdentifier, pdu.OpCode.ToString("x"));
  236. RejectPDU reject = new RejectPDU();
  237. reject.Reason = RejectReason.CommandNotSupported;
  238. reject.Data = ByteReader.ReadBytes(pdu.GetBytes(), 0, 48);
  239. state.SendQueue.Enqueue(reject);
  240. }
  241. }
  242. Log(Severity.Trace, "Leaving ProcessPDU");
  243. }
  244. private static string FormatNullDelimitedText(string text)
  245. {
  246. string result = String.Join(", ", text.Split('\0'));
  247. if (result.EndsWith(", "))
  248. {
  249. result = result.Remove(result.Length - 2);
  250. }
  251. return result;
  252. }
  253. }
  254. }