ISCSIServer.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  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. if (m_activeConnections[connectionIndex].Target != null)
  159. {
  160. lock (m_activeConnections[connectionIndex].Target.IOLock)
  161. {
  162. // Wait for pending I/O to complete.
  163. }
  164. }
  165. m_activeConnections.RemoveAt(connectionIndex);
  166. }
  167. }
  168. return;
  169. }
  170. byte[] currentBuffer = ByteReader.ReadBytes(state.ReceiveBuffer, 0, numberOfBytesReceived);
  171. ProcessCurrentBuffer(currentBuffer, state);
  172. if (clientSocket.Connected)
  173. {
  174. try
  175. {
  176. clientSocket.BeginReceive(state.ReceiveBuffer, 0, StateObject.ReceiveBufferSize, 0, ReceiveCallback, state);
  177. }
  178. catch (ObjectDisposedException)
  179. {
  180. Log("[ReceiveCallback] BeginReceive ObjectDisposedException");
  181. }
  182. catch (SocketException ex)
  183. {
  184. Log("[ReceiveCallback] BeginReceive SocketException: " + ex.Message);
  185. }
  186. }
  187. }
  188. public 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. public 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 (pdu is LoginRequestPDU)
  296. {
  297. LoginRequestPDU request = (LoginRequestPDU)pdu;
  298. Log("[{0}][ReceiveCallback] Login Request, current stage: {1}, next stage: {2}, parameters: {3}", state.ConnectionIdentifier, request.CurrentStage, request.NextStage, KeyValuePairUtils.ToString(request.LoginParameters));
  299. if (request.TSIH != 0)
  300. {
  301. // RFC 3720: A Login Request with a non-zero TSIH and a CID equal to that of an existing
  302. // connection implies a logout of the connection followed by a Login
  303. lock (m_activeConnectionsLock)
  304. {
  305. int existingConnectionIndex = GetStateObjectIndex(m_activeConnections, request.ISID, request.TSIH, request.CID);
  306. if (existingConnectionIndex >= 0)
  307. {
  308. // Perform implicit logout
  309. Log("[{0}][ProcessPDU] Initiating implicit logout", state.ConnectionIdentifier);
  310. SocketUtils.ReleaseSocket(m_activeConnections[existingConnectionIndex].ClientSocket);
  311. if (m_activeConnections[existingConnectionIndex].Target != null)
  312. {
  313. lock (m_activeConnections[existingConnectionIndex].Target.IOLock)
  314. {
  315. // Wait for pending I/O to complete.
  316. }
  317. }
  318. m_activeConnections.RemoveAt(existingConnectionIndex);
  319. Log("[{0}][ProcessPDU] Implicit logout completed", state.ConnectionIdentifier);
  320. }
  321. }
  322. }
  323. LoginResponsePDU response = ServerResponseHelper.GetLoginResponsePDU(request, m_targets, state.SessionParameters, state.ConnectionParameters, ref state.Target, GetNextTSIH);
  324. if (state.SessionParameters.IsFullFeaturePhase)
  325. {
  326. state.SessionParameters.ISID = request.ISID;
  327. state.ConnectionParameters.CID = request.CID;
  328. lock (m_activeConnectionsLock)
  329. {
  330. m_activeConnections.Add(state);
  331. }
  332. }
  333. Log("[{0}][ReceiveCallback] Login Response parameters: {1}", state.ConnectionIdentifier, KeyValuePairUtils.ToString(response.LoginParameters));
  334. TrySendPDU(state, response);
  335. }
  336. else if (!state.SessionParameters.IsFullFeaturePhase)
  337. {
  338. // Before the Full Feature Phase is established, only Login Request and Login Response PDUs are allowed.
  339. Log("[{0}][ProcessPDU] Improper command during login phase, OpCode: 0x{1}", state.ConnectionIdentifier, pdu.OpCode.ToString("x"));
  340. // A target receiving any PDU except a Login request before the Login phase is started MUST
  341. // immediately terminate the connection on which the PDU was received.
  342. // Once the Login phase has started, if the target receives any PDU except a Login request,
  343. // it MUST send a Login reject (with Status "invalid during login") and then disconnect.
  344. clientSocket.Close();
  345. }
  346. else // Logged in
  347. {
  348. if (pdu is TextRequestPDU)
  349. {
  350. TextRequestPDU request = (TextRequestPDU)pdu;
  351. TextResponsePDU response = ServerResponseHelper.GetTextResponsePDU(request, m_targets);
  352. TrySendPDU(state, response);
  353. }
  354. else if (pdu is LogoutRequestPDU)
  355. {
  356. lock (m_activeConnectionsLock)
  357. {
  358. int connectionIndex = GetStateObjectIndex(m_activeConnections, state.SessionParameters.ISID, state.SessionParameters.TSIH, state.ConnectionParameters.CID);
  359. if (connectionIndex >= 0)
  360. {
  361. if (m_activeConnections[connectionIndex].Target != null)
  362. {
  363. lock (m_activeConnections[connectionIndex].Target.IOLock)
  364. {
  365. // Wait for pending I/O to complete.
  366. }
  367. }
  368. m_activeConnections.RemoveAt(connectionIndex);
  369. }
  370. }
  371. LogoutRequestPDU request = (LogoutRequestPDU)pdu;
  372. LogoutResponsePDU response = ServerResponseHelper.GetLogoutResponsePDU(request);
  373. TrySendPDU(state, response);
  374. clientSocket.Close(); // We can close the connection now
  375. }
  376. else if (state.SessionParameters.IsDiscovery)
  377. {
  378. // The target MUST ONLY accept text requests with the SendTargets key and a logout
  379. // request with the reason "close the session". All other requests MUST be rejected.
  380. Log("[{0}][ProcessPDU] Improper command during discovery session, OpCode: 0x{1}", state.ConnectionIdentifier, pdu.OpCode.ToString("x"));
  381. RejectPDU reject = new RejectPDU();
  382. reject.Reason = RejectReason.ProtocolError;
  383. reject.Data = ByteReader.ReadBytes(pdu.GetBytes(), 0, 48);
  384. TrySendPDU(state, reject);
  385. }
  386. else if (pdu is NOPOutPDU)
  387. {
  388. NOPOutPDU request = (NOPOutPDU)pdu;
  389. if (request.InitiatorTaskTag != 0xFFFFFFFF)
  390. {
  391. NOPInPDU response = ServerResponseHelper.GetNOPResponsePDU(request);
  392. TrySendPDU(state, response);
  393. }
  394. }
  395. else if (pdu is SCSIDataOutPDU)
  396. {
  397. // FIXME: the iSCSI target layer MUST deliver the commands for execution (to the SCSI execution engin) in the order specified by CmdSN
  398. // e.g. read requests should not be executed while previous write request data is being received (via R2T)
  399. SCSIDataOutPDU request = (SCSIDataOutPDU)pdu;
  400. 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);
  401. ISCSIPDU response = TargetResponseHelper.GetSCSIDataOutResponsePDU(request, state.Target, state.SessionParameters, state.ConnectionParameters);
  402. TrySendPDU(state, response);
  403. }
  404. else if (pdu is SCSICommandPDU)
  405. {
  406. SCSICommandPDU command = (SCSICommandPDU)pdu;
  407. 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);
  408. List<ISCSIPDU> scsiResponseList = TargetResponseHelper.GetSCSIResponsePDU(command, state.Target, state.SessionParameters, state.ConnectionParameters);
  409. foreach (ISCSIPDU response in scsiResponseList)
  410. {
  411. TrySendPDU(state, response);
  412. if (!clientSocket.Connected)
  413. {
  414. return;
  415. }
  416. }
  417. }
  418. else
  419. {
  420. Log("[{0}][ProcessPDU] Unsupported command, OpCode: 0x{1}", state.ConnectionIdentifier, pdu.OpCode.ToString("x"));
  421. }
  422. }
  423. }
  424. private static int GetStateObjectIndex(List<StateObject> stateObjects, ulong isid, ushort tsih, ushort cid)
  425. {
  426. for (int index = 0; index < stateObjects.Count; index++)
  427. {
  428. if (stateObjects[index].SessionParameters.ISID == isid &&
  429. stateObjects[index].SessionParameters.TSIH == tsih &&
  430. stateObjects[index].ConnectionParameters.CID == cid)
  431. {
  432. return index;
  433. }
  434. }
  435. return -1;
  436. }
  437. public static void TrySendPDU(StateObject state, ISCSIPDU response)
  438. {
  439. Socket clientSocket = state.ClientSocket;
  440. try
  441. {
  442. PDUHelper.SetStatSN(response, state.ConnectionParameters.StatSN);
  443. PDUHelper.SetExpCmdSN(response, state.SessionParameters.ExpCmdSN, state.SessionParameters.ExpCmdSN + state.SessionParameters.CommandQueueSize);
  444. if (response is SCSIResponsePDU || (response is SCSIDataInPDU && ((SCSIDataInPDU)response).StatusPresent))
  445. {
  446. state.ConnectionParameters.StatSN++;
  447. }
  448. clientSocket.Send(response.GetBytes());
  449. Log("[{0}][TrySendPDU] Sent response to initator, Operation: {1}, Size: {2}", state.ConnectionIdentifier, response.OpCode, response.Length);
  450. }
  451. catch (SocketException ex)
  452. {
  453. Log("[{0}][TrySendPDU] Failed to send response to initator (Operation: {1}, Size: {2}), SocketException: {3}", state.ConnectionIdentifier, response.OpCode, response.Length, ex.Message);
  454. }
  455. catch (ObjectDisposedException)
  456. {
  457. }
  458. }
  459. public ushort GetNextTSIH()
  460. {
  461. // The iSCSI Target selects a non-zero value for the TSIH at
  462. // session creation (when an initiator presents a 0 value at Login).
  463. // After being selected, the same TSIH value MUST be used whenever the
  464. // initiator or target refers to the session and a TSIH is required
  465. ushort nextTSIH = m_nextTSIH;
  466. m_nextTSIH++;
  467. if (m_nextTSIH == 0)
  468. {
  469. m_nextTSIH++;
  470. }
  471. return nextTSIH;
  472. }
  473. public static void Log(string message)
  474. {
  475. if (m_logFile != null)
  476. {
  477. lock (m_logSyncLock)
  478. {
  479. StreamWriter writer = new StreamWriter(m_logFile);
  480. string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ");
  481. writer.WriteLine(timestamp + message);
  482. writer.Flush();
  483. }
  484. }
  485. }
  486. public static void Log(string message, params object[] args)
  487. {
  488. Log(String.Format(message, args));
  489. }
  490. }
  491. }