ISCSIServer.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  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.IO;
  10. using System.Net;
  11. using System.Net.Sockets;
  12. using System.Text;
  13. using System.Threading;
  14. using Utilities;
  15. namespace ISCSI.Server
  16. {
  17. public delegate ushort GetNextTSIH();
  18. public class ISCSIServer // Server may serve more than one target
  19. {
  20. public const int DefaultPort = 3260;
  21. // Offered Session Parameters:
  22. public static bool OfferedInitialR2T = true;
  23. public static bool OfferedImmediateData = true;
  24. public static int OfferedMaxBurstLength = SessionParameters.DefaultMaxBurstLength;
  25. public static int OfferedFirstBurstLength = SessionParameters.DefaultFirstBurstLength;
  26. public static int OfferedDefaultTime2Wait = 0;
  27. public static int OfferedDefaultTime2Retain = 20;
  28. public static int OfferedMaxOutstandingR2T = 1;
  29. public static bool OfferedDataPDUInOrder = true;
  30. public static bool OfferedDataSequenceInOrder = true;
  31. public static int OfferedErrorRecoveryLevel = 0;
  32. public static int OfferedMaxConnections = 1;
  33. private List<ISCSITarget> m_targets;
  34. private int m_port;
  35. private ushort m_nextTSIH = 1; // Next Target Session Identifying Handle
  36. private Socket m_listenerSocket;
  37. private bool m_listening;
  38. private static List<ConnectionState> m_activeConnections = new List<ConnectionState>();
  39. public event EventHandler<LogEntry> OnLogEntry;
  40. public ISCSIServer(List<ISCSITarget> targets) : this(targets, DefaultPort)
  41. { }
  42. public ISCSIServer(List<ISCSITarget> targets, int port) : this(targets, port, String.Empty)
  43. { }
  44. /// <summary>
  45. /// Server needs to be started with Start()
  46. /// </summary>
  47. public ISCSIServer(List<ISCSITarget> targets, int port, string logFilePath)
  48. {
  49. m_port = port;
  50. m_targets = targets;
  51. }
  52. public void Start()
  53. {
  54. if (!m_listening)
  55. {
  56. Log(Severity.Information, "Starting Server");
  57. m_listening = true;
  58. m_listenerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  59. m_listenerSocket.Bind(new IPEndPoint(IPAddress.Any, m_port));
  60. m_listenerSocket.Listen(1000);
  61. m_listenerSocket.BeginAccept(ConnectRequestCallback, m_listenerSocket);
  62. }
  63. }
  64. // This method Accepts new connections
  65. private void ConnectRequestCallback(IAsyncResult ar)
  66. {
  67. Socket listenerSocket = (Socket)ar.AsyncState;
  68. Socket clientSocket;
  69. try
  70. {
  71. clientSocket = listenerSocket.EndAccept(ar);
  72. }
  73. catch (ObjectDisposedException)
  74. {
  75. return;
  76. }
  77. catch (SocketException)
  78. {
  79. return;
  80. }
  81. Log(Severity.Information, "New connection has been accepted");
  82. ConnectionState state = new ConnectionState();
  83. state.ReceiveBuffer = new byte[ConnectionState.ReceiveBufferSize];
  84. // Disable the Nagle Algorithm for this tcp socket:
  85. clientSocket.NoDelay = true;
  86. state.ClientSocket = clientSocket;
  87. try
  88. {
  89. clientSocket.BeginReceive(state.ReceiveBuffer, 0, ConnectionState.ReceiveBufferSize, 0, ReceiveCallback, state);
  90. }
  91. catch (ObjectDisposedException)
  92. {
  93. Log(Severity.Debug, "[OnConnectRequest] BeginReceive ObjectDisposedException");
  94. }
  95. catch (SocketException ex)
  96. {
  97. Log(Severity.Debug, "[OnConnectRequest] BeginReceive SocketException: {0}", ex.Message);
  98. }
  99. m_listenerSocket.BeginAccept(ConnectRequestCallback, m_listenerSocket);
  100. }
  101. public void Stop()
  102. {
  103. Log(Severity.Information, "Stopping Server");
  104. m_listening = false;
  105. SocketUtils.ReleaseSocket(m_listenerSocket);
  106. }
  107. private void ReceiveCallback(IAsyncResult result)
  108. {
  109. if (!m_listening)
  110. {
  111. return;
  112. }
  113. ConnectionState state = (ConnectionState)result.AsyncState;
  114. Socket clientSocket = state.ClientSocket;
  115. if (!clientSocket.Connected)
  116. {
  117. return;
  118. }
  119. int numberOfBytesReceived;
  120. try
  121. {
  122. numberOfBytesReceived = clientSocket.EndReceive(result);
  123. }
  124. catch (ObjectDisposedException)
  125. {
  126. Log(Severity.Debug, "[ReceiveCallback] EndReceive ObjectDisposedException");
  127. return;
  128. }
  129. catch (SocketException ex)
  130. {
  131. Log(Severity.Debug, "[ReceiveCallback] EndReceive SocketException: {0}", ex.Message);
  132. return;
  133. }
  134. if (numberOfBytesReceived == 0)
  135. {
  136. // The other side has closed the connection
  137. clientSocket.Close();
  138. Log(Severity.Verbose, "The initiator has closed the connection");
  139. // Wait for pending I/O to complete.
  140. state.RunningSCSICommands.WaitUntilZero();
  141. lock (m_activeConnections)
  142. {
  143. int connectionIndex = GetConnectionStateIndex(m_activeConnections, state.SessionParameters.ISID, state.SessionParameters.TSIH, state.ConnectionParameters.CID);
  144. if (connectionIndex >= 0)
  145. {
  146. m_activeConnections.RemoveAt(connectionIndex);
  147. }
  148. }
  149. return;
  150. }
  151. byte[] currentBuffer = ByteReader.ReadBytes(state.ReceiveBuffer, 0, numberOfBytesReceived);
  152. ProcessCurrentBuffer(currentBuffer, state);
  153. try
  154. {
  155. clientSocket.BeginReceive(state.ReceiveBuffer, 0, ConnectionState.ReceiveBufferSize, 0, ReceiveCallback, state);
  156. }
  157. catch (ObjectDisposedException)
  158. {
  159. Log(Severity.Debug, "[ReceiveCallback] BeginReceive ObjectDisposedException");
  160. }
  161. catch (SocketException ex)
  162. {
  163. Log(Severity.Debug, "[ReceiveCallback] BeginReceive SocketException: {0}", ex.Message);
  164. }
  165. }
  166. private void ProcessCurrentBuffer(byte[] currentBuffer, ConnectionState state)
  167. {
  168. Socket clientSocket = state.ClientSocket;
  169. if (state.ConnectionBuffer.Length == 0)
  170. {
  171. state.ConnectionBuffer = currentBuffer;
  172. }
  173. else
  174. {
  175. state.ConnectionBuffer = ByteUtils.Concatenate(state.ConnectionBuffer, currentBuffer);
  176. }
  177. // we now have all PDU bytes received so far in state.ConnectionBuffer
  178. int bytesLeftInBuffer = state.ConnectionBuffer.Length;
  179. while (bytesLeftInBuffer >= 8)
  180. {
  181. int bufferOffset = state.ConnectionBuffer.Length - bytesLeftInBuffer;
  182. int pduLength = ISCSIPDU.GetPDULength(state.ConnectionBuffer, bufferOffset);
  183. if (pduLength > bytesLeftInBuffer)
  184. {
  185. Log(Severity.Debug, "[{0}][ProcessCurrentBuffer] Bytes left in receive buffer: {1}", state.ConnectionIdentifier, bytesLeftInBuffer);
  186. break;
  187. }
  188. else
  189. {
  190. byte[] pduBytes = ByteReader.ReadBytes(state.ConnectionBuffer, bufferOffset, pduLength);
  191. bytesLeftInBuffer -= pduLength;
  192. ISCSIPDU pdu = null;
  193. try
  194. {
  195. pdu = ISCSIPDU.GetPDU(pduBytes);
  196. }
  197. catch (Exception ex)
  198. {
  199. Log(Severity.Error, "[{0}] Failed to read PDU (Exception: {1})", state.ConnectionIdentifier, ex.Message);
  200. RejectPDU reject = new RejectPDU();
  201. reject.Reason = RejectReason.InvalidPDUField;
  202. reject.Data = ByteReader.ReadBytes(pduBytes, 0, 48);
  203. TrySendPDU(state, reject);
  204. }
  205. if (pdu != null)
  206. {
  207. if (pdu.GetType() == typeof(ISCSIPDU))
  208. {
  209. Log(Severity.Error, "[{0}][ProcessCurrentBuffer] Unsupported PDU (0x{1})", state.ConnectionIdentifier, pdu.OpCode.ToString("X"));
  210. // Unsupported PDU
  211. RejectPDU reject = new RejectPDU();
  212. reject.InitiatorTaskTag = pdu.InitiatorTaskTag;
  213. reject.Reason = RejectReason.CommandNotSupported;
  214. reject.Data = ByteReader.ReadBytes(pduBytes, 0, 48);
  215. TrySendPDU(state, reject);
  216. }
  217. else
  218. {
  219. ProcessPDU(pdu, state);
  220. }
  221. }
  222. if (!clientSocket.Connected)
  223. {
  224. // Do not continue to process the buffer if the other side closed the connection
  225. if (bytesLeftInBuffer > 0)
  226. {
  227. Log(Severity.Debug, "[{0}] Buffer processing aborted, bytes left in receive buffer: {1}", state.ConnectionIdentifier, bytesLeftInBuffer);
  228. }
  229. return;
  230. }
  231. }
  232. }
  233. if (bytesLeftInBuffer > 0)
  234. {
  235. state.ConnectionBuffer = ByteReader.ReadBytes(state.ConnectionBuffer, state.ConnectionBuffer.Length - bytesLeftInBuffer, bytesLeftInBuffer);
  236. }
  237. else
  238. {
  239. state.ConnectionBuffer = new byte[0];
  240. }
  241. }
  242. private void ProcessPDU(ISCSIPDU pdu, ConnectionState state)
  243. {
  244. Socket clientSocket = state.ClientSocket;
  245. uint? cmdSN = PDUHelper.GetCmdSN(pdu);
  246. Log(Severity.Trace, "Entering ProcessPDU");
  247. Log(Severity.Verbose, "[{0}] Received PDU from initiator, Operation: {1}, Size: {2}, CmdSN: {3}", state.ConnectionIdentifier, (ISCSIOpCodeName)pdu.OpCode, pdu.Length, cmdSN);
  248. // RFC 3720: On any connection, the iSCSI initiator MUST send the commands in increasing order of CmdSN,
  249. // except for commands that are retransmitted due to digest error recovery and connection recovery.
  250. if (cmdSN.HasValue)
  251. {
  252. if (state.SessionParameters.CommandNumberingStarted)
  253. {
  254. if (cmdSN != state.SessionParameters.ExpCmdSN)
  255. {
  256. Log(Severity.Error, "[{0}] CmdSN outside of expected range", state.ConnectionIdentifier);
  257. // We ignore this PDU
  258. Log(Severity.Trace, "Leaving ProcessPDU");
  259. return;
  260. }
  261. }
  262. else
  263. {
  264. state.SessionParameters.ExpCmdSN = cmdSN.Value;
  265. state.SessionParameters.CommandNumberingStarted = true;
  266. }
  267. if (pdu is LogoutRequestPDU || pdu is TextRequestPDU || pdu is SCSICommandPDU || pdu is RejectPDU)
  268. {
  269. if (!pdu.ImmediateDelivery)
  270. {
  271. state.SessionParameters.ExpCmdSN++;
  272. }
  273. }
  274. }
  275. if (!state.SessionParameters.IsFullFeaturePhase)
  276. {
  277. if (pdu is LoginRequestPDU)
  278. {
  279. LoginRequestPDU request = (LoginRequestPDU)pdu;
  280. Log(Severity.Verbose, "[{0}] Login Request, current stage: {1}, next stage: {2}, parameters: {3}", state.ConnectionIdentifier, request.CurrentStage, request.NextStage, KeyValuePairUtils.ToString(request.LoginParameters));
  281. if (request.TSIH != 0)
  282. {
  283. // RFC 3720: A Login Request with a non-zero TSIH and a CID equal to that of an existing
  284. // connection implies a logout of the connection followed by a Login
  285. lock (m_activeConnections)
  286. {
  287. int existingConnectionIndex = GetConnectionStateIndex(m_activeConnections, request.ISID, request.TSIH, request.CID);
  288. if (existingConnectionIndex >= 0)
  289. {
  290. // Perform implicit logout
  291. Log(Severity.Verbose, "[{0}] Initiating implicit logout", state.ConnectionIdentifier);
  292. ConnectionState existingConnection = m_activeConnections[existingConnectionIndex];
  293. // Wait for pending I/O to complete.
  294. existingConnection.RunningSCSICommands.WaitUntilZero();
  295. SocketUtils.ReleaseSocket(existingConnection.ClientSocket);
  296. m_activeConnections.RemoveAt(existingConnectionIndex);
  297. Log(Severity.Verbose, "[{0}] Implicit logout completed", state.ConnectionIdentifier);
  298. }
  299. }
  300. }
  301. LoginResponsePDU response = ServerResponseHelper.GetLoginResponsePDU(request, m_targets, state.SessionParameters, state.ConnectionParameters, ref state.Target, GetNextTSIH);
  302. if (state.SessionParameters.IsFullFeaturePhase)
  303. {
  304. state.SessionParameters.ISID = request.ISID;
  305. state.ConnectionParameters.CID = request.CID;
  306. lock (m_activeConnections)
  307. {
  308. m_activeConnections.Add(state);
  309. }
  310. }
  311. Log(Severity.Verbose, "[{0}] Login Response parameters: {1}", state.ConnectionIdentifier, KeyValuePairUtils.ToString(response.LoginParameters));
  312. TrySendPDU(state, response);
  313. }
  314. else
  315. {
  316. // Before the Full Feature Phase is established, only Login Request and Login Response PDUs are allowed.
  317. Log(Severity.Error, "[{0}] Improper command during login phase, OpCode: 0x{1}", state.ConnectionIdentifier, pdu.OpCode.ToString("x"));
  318. if (state.SessionParameters.TSIH == 0)
  319. {
  320. // A target receiving any PDU except a Login request before the Login phase is started MUST
  321. // immediately terminate the connection on which the PDU was received.
  322. clientSocket.Close();
  323. }
  324. else
  325. {
  326. // Once the Login phase has started, if the target receives any PDU except a Login request,
  327. // it MUST send a Login reject (with Status "invalid during login") and then disconnect.
  328. LoginResponsePDU loginResponse = new LoginResponsePDU();
  329. loginResponse.TSIH = state.SessionParameters.TSIH;
  330. loginResponse.Status = LoginResponseStatusName.InvalidDuringLogon;
  331. TrySendPDU(state, loginResponse);
  332. clientSocket.Close();
  333. }
  334. }
  335. }
  336. else // Logged in
  337. {
  338. if (pdu is TextRequestPDU)
  339. {
  340. TextRequestPDU request = (TextRequestPDU)pdu;
  341. TextResponsePDU response = ServerResponseHelper.GetTextResponsePDU(request, m_targets);
  342. TrySendPDU(state, response);
  343. }
  344. else if (pdu is LogoutRequestPDU)
  345. {
  346. Log(Severity.Verbose, "[{0}] Logour Request", state.ConnectionIdentifier);
  347. lock (m_activeConnections)
  348. {
  349. int connectionIndex = GetConnectionStateIndex(m_activeConnections, state.SessionParameters.ISID, state.SessionParameters.TSIH, state.ConnectionParameters.CID);
  350. if (connectionIndex >= 0)
  351. {
  352. ConnectionState existingConnection = m_activeConnections[connectionIndex];
  353. // 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.
  354. if (existingConnection != state)
  355. {
  356. // Wait for pending I/O to complete.
  357. existingConnection.RunningSCSICommands.WaitUntilZero();
  358. }
  359. m_activeConnections.RemoveAt(connectionIndex);
  360. }
  361. }
  362. // Wait for pending I/O to complete.
  363. state.RunningSCSICommands.WaitUntilZero();
  364. LogoutRequestPDU request = (LogoutRequestPDU)pdu;
  365. LogoutResponsePDU response = ServerResponseHelper.GetLogoutResponsePDU(request);
  366. TrySendPDU(state, response);
  367. clientSocket.Close(); // We can close the connection now
  368. }
  369. else if (state.SessionParameters.IsDiscovery)
  370. {
  371. // The target MUST ONLY accept text requests with the SendTargets key and a logout
  372. // request with the reason "close the session". All other requests MUST be rejected.
  373. Log(Severity.Error, "[{0}] Improper command during discovery session, OpCode: 0x{1}", state.ConnectionIdentifier, pdu.OpCode.ToString("x"));
  374. RejectPDU reject = new RejectPDU();
  375. reject.Reason = RejectReason.ProtocolError;
  376. reject.Data = ByteReader.ReadBytes(pdu.GetBytes(), 0, 48);
  377. TrySendPDU(state, reject);
  378. }
  379. else if (pdu is NOPOutPDU)
  380. {
  381. NOPOutPDU request = (NOPOutPDU)pdu;
  382. if (request.InitiatorTaskTag != 0xFFFFFFFF)
  383. {
  384. NOPInPDU response = ServerResponseHelper.GetNOPResponsePDU(request);
  385. TrySendPDU(state, response);
  386. }
  387. }
  388. else if (pdu is SCSIDataOutPDU || pdu is SCSICommandPDU)
  389. {
  390. // RFC 3720: the iSCSI target layer MUST deliver the commands for execution (to the SCSI execution engine) in the order specified by CmdSN.
  391. // e.g. read requests should not be executed while previous write request data is being received (via R2T)
  392. List<SCSICommandPDU> commandsToExecute = null;
  393. List<ReadyToTransferPDU> readyToTransferPDUs = new List<ReadyToTransferPDU>();
  394. if (pdu is SCSIDataOutPDU)
  395. {
  396. SCSIDataOutPDU request = (SCSIDataOutPDU)pdu;
  397. 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);
  398. try
  399. {
  400. readyToTransferPDUs = TargetResponseHelper.GetReadyToTransferPDUs(request, state.Target, state.SessionParameters, state.ConnectionParameters, out commandsToExecute);
  401. }
  402. catch (InvalidTargetTransferTagException ex)
  403. {
  404. Log(Severity.Error, "[{0}] Invalid TargetTransferTag: {1}", state.ConnectionIdentifier, ex.TargetTransferTag);
  405. RejectPDU reject = new RejectPDU();
  406. reject.InitiatorTaskTag = request.InitiatorTaskTag;
  407. reject.Reason = RejectReason.InvalidPDUField;
  408. reject.Data = ByteReader.ReadBytes(request.GetBytes(), 0, 48);
  409. TrySendPDU(state, reject);
  410. }
  411. }
  412. else
  413. {
  414. SCSICommandPDU command = (SCSICommandPDU)pdu;
  415. 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);
  416. readyToTransferPDUs = TargetResponseHelper.GetReadyToTransferPDUs(command, state.Target, state.SessionParameters, state.ConnectionParameters, out commandsToExecute);
  417. }
  418. foreach (ReadyToTransferPDU readyToTransferPDU in readyToTransferPDUs)
  419. {
  420. TrySendPDU(state, readyToTransferPDU);
  421. }
  422. if (commandsToExecute != null)
  423. {
  424. state.RunningSCSICommands.Add(commandsToExecute.Count);
  425. }
  426. List<ISCSIPDU> responseList = new List<ISCSIPDU>();
  427. foreach(SCSICommandPDU command in commandsToExecute)
  428. {
  429. Log(Severity.Debug, "[{0}] Executing command: CmdSN: {1}", state.ConnectionIdentifier, command.CmdSN);
  430. List<ISCSIPDU> commandResponseList = TargetResponseHelper.GetSCSICommandResponse(command, state.Target, state.SessionParameters, state.ConnectionParameters);
  431. state.RunningSCSICommands.Decrement();
  432. responseList.AddRange(commandResponseList);
  433. }
  434. foreach (ISCSIPDU response in responseList)
  435. {
  436. TrySendPDU(state, response);
  437. if (!clientSocket.Connected)
  438. {
  439. return;
  440. }
  441. }
  442. }
  443. else if (pdu is LoginRequestPDU)
  444. {
  445. Log(Severity.Error, "[{0}] Protocol Error (Login request during full feature phase)", state.ConnectionIdentifier);
  446. // RFC 3720: Login requests and responses MUST be used exclusively during Login.
  447. // On any connection, the login phase MUST immediately follow TCP connection establishment and
  448. // a subsequent Login Phase MUST NOT occur before tearing down a connection
  449. RejectPDU reject = new RejectPDU();
  450. reject.Reason = RejectReason.ProtocolError;
  451. reject.Data = ByteReader.ReadBytes(pdu.GetBytes(), 0, 48);
  452. TrySendPDU(state, reject);
  453. }
  454. else
  455. {
  456. Log(Severity.Error, "[{0}] Unsupported command, OpCode: 0x{1}", state.ConnectionIdentifier, pdu.OpCode.ToString("x"));
  457. RejectPDU reject = new RejectPDU();
  458. reject.Reason = RejectReason.CommandNotSupported;
  459. reject.Data = ByteReader.ReadBytes(pdu.GetBytes(), 0, 48);
  460. TrySendPDU(state, reject);
  461. }
  462. }
  463. Log(Severity.Trace, "Leaving ProcessPDU");
  464. }
  465. private static int GetConnectionStateIndex(List<ConnectionState> Connections, ulong isid, ushort tsih, ushort cid)
  466. {
  467. for (int index = 0; index < Connections.Count; index++)
  468. {
  469. if (Connections[index].SessionParameters.ISID == isid &&
  470. Connections[index].SessionParameters.TSIH == tsih &&
  471. Connections[index].ConnectionParameters.CID == cid)
  472. {
  473. return index;
  474. }
  475. }
  476. return -1;
  477. }
  478. private void TrySendPDU(ConnectionState state, ISCSIPDU response)
  479. {
  480. Socket clientSocket = state.ClientSocket;
  481. try
  482. {
  483. PDUHelper.SetStatSN(response, state.ConnectionParameters.StatSN);
  484. PDUHelper.SetExpCmdSN(response, state.SessionParameters.ExpCmdSN, state.SessionParameters.ExpCmdSN + state.SessionParameters.CommandQueueSize);
  485. if (response is SCSIResponsePDU ||
  486. response is LoginResponsePDU ||
  487. response is TextResponsePDU ||
  488. (response is SCSIDataInPDU && ((SCSIDataInPDU)response).StatusPresent) ||
  489. response is RejectPDU)
  490. {
  491. state.ConnectionParameters.StatSN++;
  492. }
  493. clientSocket.Send(response.GetBytes());
  494. Log(Severity.Debug, "[{0}] Sent response to initator, Operation: {1}, Size: {2}", state.ConnectionIdentifier, response.OpCode, response.Length);
  495. }
  496. catch (SocketException ex)
  497. {
  498. Log(Severity.Debug, "[{0}] Failed to send response to initator (Operation: {1}, Size: {2}), SocketException: {3}", state.ConnectionIdentifier, response.OpCode, response.Length, ex.Message);
  499. }
  500. catch (ObjectDisposedException)
  501. {
  502. }
  503. }
  504. public void Log(Severity severity, string message)
  505. {
  506. // To be thread-safe we must capture the delegate reference first
  507. EventHandler<LogEntry> handler = OnLogEntry;
  508. if (handler != null)
  509. {
  510. handler(this, new LogEntry(DateTime.Now, severity, "iSCSI Server", message));
  511. }
  512. }
  513. public void Log(Severity severity, string message, params object[] args)
  514. {
  515. Log(severity, String.Format(message, args));
  516. }
  517. public ushort GetNextTSIH()
  518. {
  519. // The iSCSI Target selects a non-zero value for the TSIH at
  520. // session creation (when an initiator presents a 0 value at Login).
  521. // After being selected, the same TSIH value MUST be used whenever the
  522. // initiator or target refers to the session and a TSIH is required
  523. ushort nextTSIH = m_nextTSIH;
  524. m_nextTSIH++;
  525. if (m_nextTSIH == 0)
  526. {
  527. m_nextTSIH++;
  528. }
  529. return nextTSIH;
  530. }
  531. }
  532. }