ISCSIServer.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  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. public ConnectionManager m_connectionManager = new ConnectionManager();
  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. m_connectionManager.RemoveConnection(state);
  142. return;
  143. }
  144. byte[] currentBuffer = ByteReader.ReadBytes(state.ReceiveBuffer, 0, numberOfBytesReceived);
  145. ProcessCurrentBuffer(currentBuffer, state);
  146. try
  147. {
  148. clientSocket.BeginReceive(state.ReceiveBuffer, 0, ConnectionState.ReceiveBufferSize, 0, ReceiveCallback, state);
  149. }
  150. catch (ObjectDisposedException)
  151. {
  152. Log(Severity.Debug, "[ReceiveCallback] BeginReceive ObjectDisposedException");
  153. }
  154. catch (SocketException ex)
  155. {
  156. Log(Severity.Debug, "[ReceiveCallback] BeginReceive SocketException: {0}", ex.Message);
  157. }
  158. }
  159. private void ProcessCurrentBuffer(byte[] currentBuffer, ConnectionState state)
  160. {
  161. Socket clientSocket = state.ClientSocket;
  162. if (state.ConnectionBuffer.Length == 0)
  163. {
  164. state.ConnectionBuffer = currentBuffer;
  165. }
  166. else
  167. {
  168. state.ConnectionBuffer = ByteUtils.Concatenate(state.ConnectionBuffer, currentBuffer);
  169. }
  170. // we now have all PDU bytes received so far in state.ConnectionBuffer
  171. int bytesLeftInBuffer = state.ConnectionBuffer.Length;
  172. while (bytesLeftInBuffer >= 8)
  173. {
  174. int bufferOffset = state.ConnectionBuffer.Length - bytesLeftInBuffer;
  175. int pduLength = ISCSIPDU.GetPDULength(state.ConnectionBuffer, bufferOffset);
  176. if (pduLength > bytesLeftInBuffer)
  177. {
  178. Log(Severity.Debug, "[{0}][ProcessCurrentBuffer] Bytes left in receive buffer: {1}", state.ConnectionIdentifier, bytesLeftInBuffer);
  179. break;
  180. }
  181. else
  182. {
  183. byte[] pduBytes = ByteReader.ReadBytes(state.ConnectionBuffer, bufferOffset, pduLength);
  184. bytesLeftInBuffer -= pduLength;
  185. ISCSIPDU pdu = null;
  186. try
  187. {
  188. pdu = ISCSIPDU.GetPDU(pduBytes);
  189. }
  190. catch (Exception ex)
  191. {
  192. Log(Severity.Error, "[{0}] Failed to read PDU (Exception: {1})", state.ConnectionIdentifier, ex.Message);
  193. RejectPDU reject = new RejectPDU();
  194. reject.Reason = RejectReason.InvalidPDUField;
  195. reject.Data = ByteReader.ReadBytes(pduBytes, 0, 48);
  196. TrySendPDU(state, reject);
  197. }
  198. if (pdu != null)
  199. {
  200. if (pdu.GetType() == typeof(ISCSIPDU))
  201. {
  202. Log(Severity.Error, "[{0}][ProcessCurrentBuffer] Unsupported PDU (0x{1})", state.ConnectionIdentifier, pdu.OpCode.ToString("X"));
  203. // Unsupported PDU
  204. RejectPDU reject = new RejectPDU();
  205. reject.InitiatorTaskTag = pdu.InitiatorTaskTag;
  206. reject.Reason = RejectReason.CommandNotSupported;
  207. reject.Data = ByteReader.ReadBytes(pduBytes, 0, 48);
  208. TrySendPDU(state, reject);
  209. }
  210. else
  211. {
  212. ProcessPDU(pdu, state);
  213. }
  214. }
  215. if (!clientSocket.Connected)
  216. {
  217. // Do not continue to process the buffer if the other side closed the connection
  218. if (bytesLeftInBuffer > 0)
  219. {
  220. Log(Severity.Debug, "[{0}] Buffer processing aborted, bytes left in receive buffer: {1}", state.ConnectionIdentifier, bytesLeftInBuffer);
  221. }
  222. return;
  223. }
  224. }
  225. }
  226. if (bytesLeftInBuffer > 0)
  227. {
  228. state.ConnectionBuffer = ByteReader.ReadBytes(state.ConnectionBuffer, state.ConnectionBuffer.Length - bytesLeftInBuffer, bytesLeftInBuffer);
  229. }
  230. else
  231. {
  232. state.ConnectionBuffer = new byte[0];
  233. }
  234. }
  235. private void ProcessPDU(ISCSIPDU pdu, ConnectionState state)
  236. {
  237. Socket clientSocket = state.ClientSocket;
  238. uint? cmdSN = PDUHelper.GetCmdSN(pdu);
  239. Log(Severity.Trace, "Entering ProcessPDU");
  240. Log(Severity.Verbose, "[{0}] Received PDU from initiator, Operation: {1}, Size: {2}, CmdSN: {3}", state.ConnectionIdentifier, (ISCSIOpCodeName)pdu.OpCode, pdu.Length, cmdSN);
  241. // RFC 3720: On any connection, the iSCSI initiator MUST send the commands in increasing order of CmdSN,
  242. // except for commands that are retransmitted due to digest error recovery and connection recovery.
  243. if (cmdSN.HasValue)
  244. {
  245. if (state.SessionParameters.CommandNumberingStarted)
  246. {
  247. if (cmdSN != state.SessionParameters.ExpCmdSN)
  248. {
  249. Log(Severity.Error, "[{0}] CmdSN outside of expected range", state.ConnectionIdentifier);
  250. // We ignore this PDU
  251. Log(Severity.Trace, "Leaving ProcessPDU");
  252. return;
  253. }
  254. }
  255. else
  256. {
  257. state.SessionParameters.ExpCmdSN = cmdSN.Value;
  258. state.SessionParameters.CommandNumberingStarted = true;
  259. }
  260. if (pdu is LogoutRequestPDU || pdu is TextRequestPDU || pdu is SCSICommandPDU || pdu is RejectPDU)
  261. {
  262. if (!pdu.ImmediateDelivery)
  263. {
  264. state.SessionParameters.ExpCmdSN++;
  265. }
  266. }
  267. }
  268. if (!state.SessionParameters.IsFullFeaturePhase)
  269. {
  270. if (pdu is LoginRequestPDU)
  271. {
  272. LoginRequestPDU request = (LoginRequestPDU)pdu;
  273. Log(Severity.Verbose, "[{0}] Login Request, current stage: {1}, next stage: {2}, parameters: {3}", state.ConnectionIdentifier, request.CurrentStage, request.NextStage, KeyValuePairUtils.ToString(request.LoginParameters));
  274. if (request.TSIH != 0)
  275. {
  276. // RFC 3720: A Login Request with a non-zero TSIH and a CID equal to that of an existing
  277. // connection implies a logout of the connection followed by a Login
  278. ConnectionState existingConnection = m_connectionManager.FindConnection(request.ISID, request.TSIH, request.CID);
  279. if (existingConnection != null)
  280. {
  281. // Perform implicit logout
  282. Log(Severity.Verbose, "[{0}] Initiating implicit logout", state.ConnectionIdentifier);
  283. // Wait for pending I/O to complete.
  284. existingConnection.RunningSCSICommands.WaitUntilZero();
  285. SocketUtils.ReleaseSocket(existingConnection.ClientSocket);
  286. m_connectionManager.RemoveConnection(existingConnection);
  287. Log(Severity.Verbose, "[{0}] Implicit logout completed", state.ConnectionIdentifier);
  288. }
  289. }
  290. LoginResponsePDU response = ServerResponseHelper.GetLoginResponsePDU(request, m_targets, state.SessionParameters, state.ConnectionParameters, ref state.Target, GetNextTSIH);
  291. if (state.SessionParameters.IsFullFeaturePhase)
  292. {
  293. state.SessionParameters.ISID = request.ISID;
  294. state.ConnectionParameters.CID = request.CID;
  295. m_connectionManager.AddConnection(state);
  296. }
  297. Log(Severity.Verbose, "[{0}] Login Response parameters: {1}", state.ConnectionIdentifier, KeyValuePairUtils.ToString(response.LoginParameters));
  298. TrySendPDU(state, response);
  299. }
  300. else
  301. {
  302. // Before the Full Feature Phase is established, only Login Request and Login Response PDUs are allowed.
  303. Log(Severity.Error, "[{0}] Improper command during login phase, OpCode: 0x{1}", state.ConnectionIdentifier, pdu.OpCode.ToString("x"));
  304. if (state.SessionParameters.TSIH == 0)
  305. {
  306. // A target receiving any PDU except a Login request before the Login phase is started MUST
  307. // immediately terminate the connection on which the PDU was received.
  308. clientSocket.Close();
  309. }
  310. else
  311. {
  312. // Once the Login phase has started, if the target receives any PDU except a Login request,
  313. // it MUST send a Login reject (with Status "invalid during login") and then disconnect.
  314. LoginResponsePDU loginResponse = new LoginResponsePDU();
  315. loginResponse.TSIH = state.SessionParameters.TSIH;
  316. loginResponse.Status = LoginResponseStatusName.InvalidDuringLogon;
  317. TrySendPDU(state, loginResponse);
  318. clientSocket.Close();
  319. }
  320. }
  321. }
  322. else // Logged in
  323. {
  324. if (pdu is TextRequestPDU)
  325. {
  326. TextRequestPDU request = (TextRequestPDU)pdu;
  327. TextResponsePDU response = ServerResponseHelper.GetTextResponsePDU(request, m_targets);
  328. TrySendPDU(state, response);
  329. }
  330. else if (pdu is LogoutRequestPDU)
  331. {
  332. Log(Severity.Verbose, "[{0}] Logour Request", state.ConnectionIdentifier);
  333. LogoutRequestPDU request = (LogoutRequestPDU)pdu;
  334. if (state.SessionParameters.IsDiscovery && request.ReasonCode != LogoutReasonCode.CloseTheSession)
  335. {
  336. // RFC 3720: Discovery-session: The target MUST ONLY accept [..] logout request with the reason "close the session"
  337. RejectPDU reject = new RejectPDU();
  338. reject.Reason = RejectReason.ProtocolError;
  339. reject.Data = ByteReader.ReadBytes(pdu.GetBytes(), 0, 48);
  340. TrySendPDU(state, reject);
  341. }
  342. else
  343. {
  344. List<ConnectionState> connectionsToClose = new List<ConnectionState>();
  345. if (request.ReasonCode == LogoutReasonCode.CloseTheSession)
  346. {
  347. connectionsToClose = m_connectionManager.GetSessionConnections(state.SessionParameters.ISID, state.SessionParameters.TSIH);
  348. }
  349. else
  350. {
  351. // 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.
  352. ConnectionState existingConnection = m_connectionManager.FindConnection(state.SessionParameters.ISID, state.SessionParameters.TSIH, request.CID);
  353. if (existingConnection != null && existingConnection != state)
  354. {
  355. connectionsToClose.Add(existingConnection);
  356. }
  357. connectionsToClose.Add(state);
  358. }
  359. foreach (ConnectionState connection in connectionsToClose)
  360. {
  361. // Wait for pending I/O to complete.
  362. connection.RunningSCSICommands.WaitUntilZero();
  363. if (connection != state)
  364. {
  365. SocketUtils.ReleaseSocket(connection.ClientSocket);
  366. }
  367. m_connectionManager.RemoveConnection(connection);
  368. }
  369. LogoutResponsePDU response = ServerResponseHelper.GetLogoutResponsePDU(request);
  370. TrySendPDU(state, response);
  371. clientSocket.Close(); // We can close the connection now
  372. }
  373. }
  374. else if (state.SessionParameters.IsDiscovery)
  375. {
  376. // The target MUST ONLY accept text requests with the SendTargets key and a logout
  377. // request with the reason "close the session". All other requests MUST be rejected.
  378. Log(Severity.Error, "[{0}] Improper command during discovery session, OpCode: 0x{1}", state.ConnectionIdentifier, pdu.OpCode.ToString("x"));
  379. RejectPDU reject = new RejectPDU();
  380. reject.Reason = RejectReason.ProtocolError;
  381. reject.Data = ByteReader.ReadBytes(pdu.GetBytes(), 0, 48);
  382. TrySendPDU(state, reject);
  383. }
  384. else if (pdu is NOPOutPDU)
  385. {
  386. NOPOutPDU request = (NOPOutPDU)pdu;
  387. if (request.InitiatorTaskTag != 0xFFFFFFFF)
  388. {
  389. NOPInPDU response = ServerResponseHelper.GetNOPResponsePDU(request);
  390. TrySendPDU(state, response);
  391. }
  392. }
  393. else if (pdu is SCSIDataOutPDU || pdu is SCSICommandPDU)
  394. {
  395. // RFC 3720: the iSCSI target layer MUST deliver the commands for execution (to the SCSI execution engine) in the order specified by CmdSN.
  396. // e.g. read requests should not be executed while previous write request data is being received (via R2T)
  397. List<SCSICommandPDU> commandsToExecute = null;
  398. List<ReadyToTransferPDU> readyToTransferPDUs = new List<ReadyToTransferPDU>();
  399. if (pdu is SCSIDataOutPDU)
  400. {
  401. SCSIDataOutPDU request = (SCSIDataOutPDU)pdu;
  402. 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);
  403. try
  404. {
  405. readyToTransferPDUs = TargetResponseHelper.GetReadyToTransferPDUs(request, state.Target, state.SessionParameters, state.ConnectionParameters, out commandsToExecute);
  406. }
  407. catch (InvalidTargetTransferTagException ex)
  408. {
  409. Log(Severity.Error, "[{0}] Invalid TargetTransferTag: {1}", state.ConnectionIdentifier, ex.TargetTransferTag);
  410. RejectPDU reject = new RejectPDU();
  411. reject.InitiatorTaskTag = request.InitiatorTaskTag;
  412. reject.Reason = RejectReason.InvalidPDUField;
  413. reject.Data = ByteReader.ReadBytes(request.GetBytes(), 0, 48);
  414. TrySendPDU(state, reject);
  415. }
  416. }
  417. else
  418. {
  419. SCSICommandPDU command = (SCSICommandPDU)pdu;
  420. 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);
  421. readyToTransferPDUs = TargetResponseHelper.GetReadyToTransferPDUs(command, state.Target, state.SessionParameters, state.ConnectionParameters, out commandsToExecute);
  422. }
  423. foreach (ReadyToTransferPDU readyToTransferPDU in readyToTransferPDUs)
  424. {
  425. TrySendPDU(state, readyToTransferPDU);
  426. }
  427. if (commandsToExecute != null)
  428. {
  429. state.RunningSCSICommands.Add(commandsToExecute.Count);
  430. }
  431. List<ISCSIPDU> responseList = new List<ISCSIPDU>();
  432. foreach(SCSICommandPDU command in commandsToExecute)
  433. {
  434. Log(Severity.Debug, "[{0}] Executing command: CmdSN: {1}", state.ConnectionIdentifier, command.CmdSN);
  435. List<ISCSIPDU> commandResponseList = TargetResponseHelper.GetSCSICommandResponse(command, state.Target, state.SessionParameters, state.ConnectionParameters);
  436. state.RunningSCSICommands.Decrement();
  437. responseList.AddRange(commandResponseList);
  438. }
  439. foreach (ISCSIPDU response in responseList)
  440. {
  441. TrySendPDU(state, response);
  442. if (!clientSocket.Connected)
  443. {
  444. return;
  445. }
  446. }
  447. }
  448. else if (pdu is LoginRequestPDU)
  449. {
  450. Log(Severity.Error, "[{0}] Protocol Error (Login request during full feature phase)", state.ConnectionIdentifier);
  451. // RFC 3720: Login requests and responses MUST be used exclusively during Login.
  452. // On any connection, the login phase MUST immediately follow TCP connection establishment and
  453. // a subsequent Login Phase MUST NOT occur before tearing down a connection
  454. RejectPDU reject = new RejectPDU();
  455. reject.Reason = RejectReason.ProtocolError;
  456. reject.Data = ByteReader.ReadBytes(pdu.GetBytes(), 0, 48);
  457. TrySendPDU(state, reject);
  458. }
  459. else
  460. {
  461. Log(Severity.Error, "[{0}] Unsupported command, OpCode: 0x{1}", state.ConnectionIdentifier, pdu.OpCode.ToString("x"));
  462. RejectPDU reject = new RejectPDU();
  463. reject.Reason = RejectReason.CommandNotSupported;
  464. reject.Data = ByteReader.ReadBytes(pdu.GetBytes(), 0, 48);
  465. TrySendPDU(state, reject);
  466. }
  467. }
  468. Log(Severity.Trace, "Leaving ProcessPDU");
  469. }
  470. private void TrySendPDU(ConnectionState state, ISCSIPDU response)
  471. {
  472. Socket clientSocket = state.ClientSocket;
  473. try
  474. {
  475. PDUHelper.SetStatSN(response, state.ConnectionParameters.StatSN);
  476. PDUHelper.SetExpCmdSN(response, state.SessionParameters.ExpCmdSN, state.SessionParameters.ExpCmdSN + state.SessionParameters.CommandQueueSize);
  477. if (response is SCSIResponsePDU ||
  478. response is LoginResponsePDU ||
  479. response is TextResponsePDU ||
  480. (response is SCSIDataInPDU && ((SCSIDataInPDU)response).StatusPresent) ||
  481. response is RejectPDU)
  482. {
  483. state.ConnectionParameters.StatSN++;
  484. }
  485. clientSocket.Send(response.GetBytes());
  486. Log(Severity.Debug, "[{0}] Sent response to initator, Operation: {1}, Size: {2}", state.ConnectionIdentifier, response.OpCode, response.Length);
  487. }
  488. catch (SocketException ex)
  489. {
  490. Log(Severity.Debug, "[{0}] Failed to send response to initator (Operation: {1}, Size: {2}), SocketException: {3}", state.ConnectionIdentifier, response.OpCode, response.Length, ex.Message);
  491. }
  492. catch (ObjectDisposedException)
  493. {
  494. }
  495. }
  496. public void Log(Severity severity, string message)
  497. {
  498. // To be thread-safe we must capture the delegate reference first
  499. EventHandler<LogEntry> handler = OnLogEntry;
  500. if (handler != null)
  501. {
  502. handler(this, new LogEntry(DateTime.Now, severity, "iSCSI Server", message));
  503. }
  504. }
  505. public void Log(Severity severity, string message, params object[] args)
  506. {
  507. Log(severity, String.Format(message, args));
  508. }
  509. public ushort GetNextTSIH()
  510. {
  511. // The iSCSI Target selects a non-zero value for the TSIH at
  512. // session creation (when an initiator presents a 0 value at Login).
  513. // After being selected, the same TSIH value MUST be used whenever the
  514. // initiator or target refers to the session and a TSIH is required
  515. ushort nextTSIH = m_nextTSIH;
  516. m_nextTSIH++;
  517. if (m_nextTSIH == 0)
  518. {
  519. m_nextTSIH++;
  520. }
  521. return nextTSIH;
  522. }
  523. }
  524. }