ISCSIServer.PDUProcessor.cs 15 KB

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