ISCSIServer.cs 24 KB

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