ISCSIServer.cs 28 KB

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