ISCSIServer.cs 23 KB

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