ISCSIServer.cs 26 KB

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