ISCSIServer.cs 29 KB

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