ISCSIServer.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  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].WriteLock)
  159. {
  160. // Wait for pending I/O to complete.
  161. }
  162. m_activeConnections.RemoveAt(connectionIndex);
  163. }
  164. }
  165. return;
  166. }
  167. Log("[{0}][ReceiveCallback] Received {1} bytes", state.ConnectionIdentifier, numberOfBytesReceived);
  168. byte[] currentBuffer = ByteReader.ReadBytes(state.ReceiveBuffer, 0, numberOfBytesReceived);
  169. ProcessCurrentBuffer(currentBuffer, state);
  170. if (clientSocket.Connected)
  171. {
  172. try
  173. {
  174. clientSocket.BeginReceive(state.ReceiveBuffer, 0, StateObject.ReceiveBufferSize, 0, ReceiveCallback, state);
  175. }
  176. catch (ObjectDisposedException)
  177. {
  178. Log("[ReceiveCallback] BeginReceive ObjectDisposedException");
  179. }
  180. catch (SocketException ex)
  181. {
  182. Log("[ReceiveCallback] BeginReceive SocketException: " + ex.Message);
  183. }
  184. }
  185. }
  186. public void ProcessCurrentBuffer(byte[] currentBuffer, StateObject state)
  187. {
  188. Socket clientSocket = state.ClientSocket;
  189. if (state.ConnectionBuffer.Length == 0)
  190. {
  191. state.ConnectionBuffer = currentBuffer;
  192. }
  193. else
  194. {
  195. state.ConnectionBuffer = ByteUtils.Concatenate(state.ConnectionBuffer, currentBuffer);
  196. }
  197. // we now have all PDU bytes received so far in state.ConnectionBuffer
  198. int bytesLeftInBuffer = state.ConnectionBuffer.Length;
  199. while (bytesLeftInBuffer >= 8)
  200. {
  201. int bufferOffset = state.ConnectionBuffer.Length - bytesLeftInBuffer;
  202. int pduLength = ISCSIPDU.GetPDULength(state.ConnectionBuffer, bufferOffset);
  203. if (pduLength > bytesLeftInBuffer)
  204. {
  205. Log("[{0}][ProcessCurrentBuffer] Bytes left in receive buffer: {1}", state.ConnectionIdentifier, bytesLeftInBuffer);
  206. break;
  207. }
  208. else
  209. {
  210. Log("[{0}][ProcessCurrentBuffer] PDU is being processed, Length: {1}", state.ConnectionIdentifier, pduLength);
  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 (UnsupportedSCSICommandException)
  219. {
  220. pdu = new SCSICommandPDU(pduBytes, false);
  221. }
  222. catch (Exception ex)
  223. {
  224. Log("[{0}][ProcessCurrentBuffer] Failed to read PDU (Exception: {1})", state.ConnectionIdentifier, ex.Message);
  225. RejectPDU reject = new RejectPDU();
  226. reject.Reason = RejectReason.InvalidPDUField;
  227. reject.Data = ByteReader.ReadBytes(pduBytes, 0, 48);
  228. TrySendPDU(state, reject);
  229. }
  230. if (pdu != null)
  231. {
  232. if (pdu.GetType() == typeof(ISCSIPDU))
  233. {
  234. Log("[{0}][ProcessCurrentBuffer] Unsupported PDU (0x{1})", state.ConnectionIdentifier, pdu.OpCode.ToString("X"));
  235. // Unsupported PDU
  236. RejectPDU reject = new RejectPDU();
  237. reject.Reason = RejectReason.CommandNotSupported;
  238. reject.Data = ByteReader.ReadBytes(pduBytes, 0, 48);
  239. TrySendPDU(state, reject);
  240. }
  241. else
  242. {
  243. ProcessPDU(pdu, state);
  244. }
  245. }
  246. if (!clientSocket.Connected)
  247. {
  248. // Do not continue to process the buffer if the other side closed the connection
  249. Log("[{0}][ProcessCurrentBuffer] Buffer processing aborted, bytes left in receive buffer: {1}", state.ConnectionIdentifier, bytesLeftInBuffer);
  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. public void ProcessPDU(ISCSIPDU pdu, StateObject state)
  264. {
  265. Socket clientSocket = state.ClientSocket;
  266. Log("[{0}][ProcessPDU] Received PDU from initiator, Operation: {1}, Size: {2}", state.ConnectionIdentifier, (ISCSIOpCodeName)pdu.OpCode, pdu.Length);
  267. uint? cmdSN = PDUHelper.GetCmdSN(pdu);
  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. // We ignore this PDU
  277. return;
  278. }
  279. }
  280. else
  281. {
  282. state.SessionParameters.ExpCmdSN = cmdSN.Value;
  283. state.SessionParameters.CommandNumberingStarted = true;
  284. }
  285. if (pdu is LogoutRequestPDU || pdu is TextRequestPDU || pdu is SCSICommandPDU || pdu is RejectPDU)
  286. {
  287. if (!pdu.ImmediateDelivery)
  288. {
  289. state.SessionParameters.ExpCmdSN++;
  290. }
  291. }
  292. }
  293. if (pdu is NOPOutPDU)
  294. {
  295. NOPOutPDU request = (NOPOutPDU)pdu;
  296. if (request.InitiatorTaskTag != 0xFFFFFFFF)
  297. {
  298. NOPInPDU response = ServerResponseHelper.GetNOPResponsePDU(request);
  299. TrySendPDU(state, response);
  300. }
  301. }
  302. else if (pdu is TextRequestPDU)
  303. {
  304. TextRequestPDU request = (TextRequestPDU)pdu;
  305. TextResponsePDU response = ServerResponseHelper.GetTextResponsePDU(request, m_targets);
  306. TrySendPDU(state, response);
  307. }
  308. else if (pdu is LoginRequestPDU)
  309. {
  310. LoginRequestPDU request = (LoginRequestPDU)pdu;
  311. Log("[{0}][ReceiveCallback] Login Request, current stage: {1}, next stage: {2}, parameters: {3}", state.ConnectionIdentifier, request.CurrentStage, request.NextStage, KeyValuePairUtils.ToString(request.LoginParameters));
  312. if (request.TSIH != 0)
  313. {
  314. // RFC 3720: A Login Request with a non-zero TSIH and a CID equal to that of an existing
  315. // connection implies a logout of the connection followed by a Login
  316. lock (m_activeConnectionsLock)
  317. {
  318. int existingConnectionIndex = GetStateObjectIndex(m_activeConnections, request.ISID, request.TSIH, request.CID);
  319. if (existingConnectionIndex >= 0)
  320. {
  321. // Perform implicit logout
  322. Log("[{0}][ProcessPDU] Initiating implicit logout", state.ConnectionIdentifier);
  323. SocketUtils.ReleaseSocket(m_activeConnections[existingConnectionIndex].ClientSocket);
  324. lock (m_activeConnections[existingConnectionIndex].Target.WriteLock)
  325. {
  326. // Wait for pending I/O to complete.
  327. }
  328. m_activeConnections.RemoveAt(existingConnectionIndex);
  329. Log("[{0}][ProcessPDU] Implicit logout completed", state.ConnectionIdentifier);
  330. }
  331. }
  332. }
  333. LoginResponsePDU response = ServerResponseHelper.GetLoginResponsePDU(request, m_targets, state.SessionParameters, state.ConnectionParameters, ref state.Target, GetNextTSIH);
  334. if (state.Target != null)
  335. {
  336. if (request.LoginParameters.ContainsKey("TargetMaxRecvDataSegmentLength"))
  337. {
  338. state.ConnectionParameters.InitiatorMaxRecvDataSegmentLength = Convert.ToInt32(request.LoginParameters.ValueOf("TargetMaxRecvDataSegmentLength"));
  339. Log("[{0}][ProcessPDU] Initiator's TargetMaxRecvDataSegmentLength: {1}", state.ConnectionIdentifier, state.ConnectionParameters.InitiatorMaxRecvDataSegmentLength);
  340. }
  341. state.SessionParameters.ISID = request.ISID;
  342. state.ConnectionParameters.CID = request.CID;
  343. if (response.NextStage == 3)
  344. {
  345. m_activeConnections.Add(state);
  346. }
  347. }
  348. Log("[{0}][ReceiveCallback] Login Response parameters: {1}", state.ConnectionIdentifier, KeyValuePairUtils.ToString(response.LoginParameters));
  349. TrySendPDU(state, response);
  350. }
  351. else if (pdu is LogoutRequestPDU)
  352. {
  353. lock (m_activeConnectionsLock)
  354. {
  355. int connectionIndex = GetStateObjectIndex(m_activeConnections, state.SessionParameters.ISID, state.SessionParameters.TSIH, state.ConnectionParameters.CID);
  356. if (connectionIndex >= 0)
  357. {
  358. lock (m_activeConnections[connectionIndex].Target.WriteLock)
  359. {
  360. // Wait for pending I/O to complete.
  361. }
  362. m_activeConnections.RemoveAt(connectionIndex);
  363. }
  364. }
  365. LogoutRequestPDU request = (LogoutRequestPDU)pdu;
  366. LogoutResponsePDU response = ServerResponseHelper.GetLogoutResponsePDU(request);
  367. TrySendPDU(state, response);
  368. clientSocket.Close(); // We can close the connection now
  369. }
  370. else // Target commands
  371. {
  372. if (state.SessionParameters.IsDiscovery || state.Target == null)
  373. {
  374. Log("[{0}][ProcessPDU] Unknown or improper command during discovery session, OpCode: 0x{1}", state.ConnectionIdentifier, pdu.OpCode.ToString("x"));
  375. }
  376. else // Logged in to target
  377. {
  378. if (pdu is SCSIDataOutPDU)
  379. {
  380. SCSIDataOutPDU request = (SCSIDataOutPDU)pdu;
  381. 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);
  382. ISCSIPDU response = TargetResponseHelper.GetSCSIDataOutResponsePDU(request, state.Target, state.SessionParameters, state.ConnectionParameters);
  383. TrySendPDU(state, response);
  384. }
  385. else if (pdu is SCSICommandPDU)
  386. {
  387. SCSICommandPDU command = (SCSICommandPDU)pdu;
  388. if (command.CommandDescriptorBlock == null)
  389. {
  390. Log("[{0}][ProcessPDU] Unsupported SCSI Command (0x{1})", state.ConnectionIdentifier, command.OpCodeSpecific[12].ToString("X"));
  391. SCSIResponsePDU response = new SCSIResponsePDU();
  392. response.InitiatorTaskTag = command.InitiatorTaskTag;
  393. response.Status = SCSIStatusCodeName.CheckCondition;
  394. response.Data = SCSITarget.FormatSenseData(SenseDataParameter.GetIllegalRequestUnsupportedCommandCodeSenseData());
  395. TrySendPDU(state, response);
  396. }
  397. else
  398. {
  399. ISCSIServer.Log("[{0}][ProcessPDU] SCSICommandPDU: CmdSN: {1}, SCSI command: {2}, LUN: {3}, Data segment length: {4}, Expected Data Transfer Length: {5}, Final: {6}", state.ConnectionIdentifier, command.CmdSN, (SCSIOpCodeName)command.CommandDescriptorBlock.OpCode, (ushort)command.LUN, command.DataSegmentLength, command.ExpectedDataTransferLength, command.Final);
  400. List<ISCSIPDU> scsiResponseList = TargetResponseHelper.GetSCSIResponsePDU(command, state.Target, state.SessionParameters, state.ConnectionParameters);
  401. foreach (ISCSIPDU response in scsiResponseList)
  402. {
  403. TrySendPDU(state, response);
  404. if (!clientSocket.Connected)
  405. {
  406. return;
  407. }
  408. }
  409. }
  410. }
  411. else
  412. {
  413. Log("[{0}][ProcessPDU] Unknown or improper command, OpCode: 0x{1}", state.ConnectionIdentifier, pdu.OpCode.ToString("x"));
  414. }
  415. }
  416. }
  417. }
  418. private static int GetStateObjectIndex(List<StateObject> stateObjects, ulong isid, ushort tsih, ushort cid)
  419. {
  420. for (int index = 0; index < stateObjects.Count; index++)
  421. {
  422. if (stateObjects[index].SessionParameters.ISID == isid &&
  423. stateObjects[index].SessionParameters.TSIH == tsih &&
  424. stateObjects[index].ConnectionParameters.CID == cid)
  425. {
  426. return index;
  427. }
  428. }
  429. return -1;
  430. }
  431. public static void TrySendPDU(StateObject state, ISCSIPDU response)
  432. {
  433. Socket clientSocket = state.ClientSocket;
  434. try
  435. {
  436. PDUHelper.SetStatSN(response, state.ConnectionParameters.StatSN);
  437. PDUHelper.SetExpCmdSN(response, state.SessionParameters.ExpCmdSN, state.SessionParameters.ExpCmdSN + state.SessionParameters.CommandQueueSize);
  438. if (response is SCSIResponsePDU || (response is SCSIDataInPDU && ((SCSIDataInPDU)response).StatusPresent))
  439. {
  440. state.ConnectionParameters.StatSN++;
  441. }
  442. clientSocket.Send(response.GetBytes());
  443. Log("[{0}][TrySendPDU] Sent response to initator, Operation: {1}, Size: {2}", state.ConnectionIdentifier, response.OpCode, response.Length);
  444. }
  445. catch (SocketException ex)
  446. {
  447. Log("[{0}][TrySendPDU] Failed to send response to initator (Operation: {1}, Size: {2}), SocketException: {3}", state.ConnectionIdentifier, response.OpCode, response.Length, ex.Message);
  448. }
  449. catch (ObjectDisposedException)
  450. {
  451. }
  452. }
  453. public ushort GetNextTSIH()
  454. {
  455. // The iSCSI Target selects a non-zero value for the TSIH at
  456. // session creation (when an initiator presents a 0 value at Login).
  457. // After being selected, the same TSIH value MUST be used whenever the
  458. // initiator or target refers to the session and a TSIH is required
  459. ushort nextTSIH = m_nextTSIH;
  460. m_nextTSIH++;
  461. if (m_nextTSIH == 0)
  462. {
  463. m_nextTSIH++;
  464. }
  465. return nextTSIH;
  466. }
  467. public static void Log(string message)
  468. {
  469. if (m_logFile != null)
  470. {
  471. lock (m_logSyncLock)
  472. {
  473. StreamWriter writer = new StreamWriter(m_logFile);
  474. string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ");
  475. writer.WriteLine(timestamp + message);
  476. writer.Flush();
  477. }
  478. }
  479. }
  480. public static void Log(string message, params object[] args)
  481. {
  482. Log(String.Format(message, args));
  483. }
  484. }
  485. }