ISCSIClient.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. /* Copyright (C) 2012-2019 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.Diagnostics;
  10. using System.IO;
  11. using System.Net;
  12. using System.Net.Sockets;
  13. using System.Text;
  14. using System.Threading;
  15. using SCSI;
  16. using Utilities;
  17. namespace ISCSI.Client
  18. {
  19. public partial class ISCSIClient
  20. {
  21. private ConnectionParameters m_connection = new ConnectionParameters();
  22. private string m_initiatorName;
  23. private IPAddress m_targetAddress;
  24. private int m_targetPort;
  25. private bool m_isConnected;
  26. private Socket m_clientSocket;
  27. private object m_incomingQueueLock = new object();
  28. private List<ISCSIPDU> m_incomingQueue = new List<ISCSIPDU>();
  29. private EventWaitHandle m_incomingQueueEventHandle = new EventWaitHandle(false, EventResetMode.AutoReset);
  30. public static object m_logSyncLock = new object();
  31. private static FileStream m_logFile = null;
  32. public ISCSIClient(string initiatorName)
  33. {
  34. m_initiatorName = initiatorName;
  35. }
  36. public bool Connect(IPAddress targetAddress, int targetPort)
  37. {
  38. m_targetAddress = targetAddress;
  39. m_targetPort = targetPort;
  40. if (!m_isConnected)
  41. {
  42. m_clientSocket = new Socket(m_targetAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  43. try
  44. {
  45. m_clientSocket.Connect(m_targetAddress, m_targetPort);
  46. }
  47. catch (SocketException)
  48. {
  49. return false;
  50. }
  51. ConnectionState state = new ConnectionState();
  52. ISCSIConnectionReceiveBuffer buffer = state.ReceiveBuffer;
  53. m_clientSocket.BeginReceive(buffer.Buffer, buffer.WriteOffset, buffer.AvailableLength, SocketFlags.None, new AsyncCallback(OnClientSocketReceive), state);
  54. m_isConnected = true;
  55. }
  56. return m_isConnected;
  57. }
  58. public void Disconnect()
  59. {
  60. if (m_isConnected)
  61. {
  62. m_clientSocket.Disconnect(false);
  63. m_isConnected = false;
  64. }
  65. }
  66. /// <param name="targetName">Set to null for discovery session</param>
  67. public bool Login(string targetName)
  68. {
  69. if (!m_isConnected)
  70. {
  71. throw new InvalidOperationException("iSCSI client is not connected");
  72. }
  73. m_connection.Session = new ISCSISession();
  74. m_connection.Session.ISID = ClientHelper.GetRandomISID();
  75. m_connection.CID = m_connection.Session.GetNextCID();
  76. // p.s. It's possible to perform a single stage login (stage 1 to stage 3, tested against Microsoft iSCSI Target v3.1)
  77. LoginRequestPDU request = ClientHelper.GetFirstStageLoginRequest(m_initiatorName, targetName, m_connection);
  78. SendPDU(request);
  79. LoginResponsePDU response = WaitForPDU(request.InitiatorTaskTag) as LoginResponsePDU;
  80. if (response != null && response.Status == LoginResponseStatusName.Success)
  81. {
  82. m_connection.Session.TSIH = response.TSIH;
  83. // Status numbering starts with the Login response to the first Login request of the connection
  84. m_connection.StatusNumberingStarted = true;
  85. m_connection.ExpStatSN = response.StatSN + 1;
  86. request = ClientHelper.GetSecondStageLoginRequest(response, m_connection, targetName == null);
  87. SendPDU(request);
  88. response = WaitForPDU(request.InitiatorTaskTag) as LoginResponsePDU;
  89. if (response != null && response.Status == LoginResponseStatusName.Success)
  90. {
  91. KeyValuePairList<string, string> loginParameters = KeyValuePairUtils.GetKeyValuePairList(response.LoginParametersText);
  92. ClientHelper.UpdateOperationalParameters(loginParameters, m_connection);
  93. return true;
  94. }
  95. }
  96. return false;
  97. }
  98. public bool Logout()
  99. {
  100. if (!m_isConnected)
  101. {
  102. throw new InvalidOperationException("iSCSI client is not connected");
  103. }
  104. LogoutRequestPDU request = ClientHelper.GetLogoutRequest(m_connection);
  105. SendPDU(request);
  106. LogoutResponsePDU response = WaitForPDU(request.InitiatorTaskTag) as LogoutResponsePDU;
  107. return (response != null && response.Response == LogoutResponse.ClosedSuccessfully);
  108. }
  109. public List<string> ListTargets()
  110. {
  111. if (!m_isConnected)
  112. {
  113. throw new InvalidOperationException("iSCSI client is not connected");
  114. }
  115. TextRequestPDU request = ClientHelper.GetSendTargetsRequest(m_connection);
  116. SendPDU(request);
  117. TextResponsePDU response = WaitForPDU(request.InitiatorTaskTag) as TextResponsePDU;
  118. if (response != null && response.Final)
  119. {
  120. KeyValuePairList<string, string> entries = KeyValuePairUtils.GetKeyValuePairList(response.Text);
  121. List<string> result = new List<string>();
  122. foreach(KeyValuePair<string, string> entry in entries)
  123. {
  124. if (entry.Key == "TargetName")
  125. {
  126. result.Add(entry.Value);
  127. }
  128. }
  129. return result;
  130. }
  131. return null;
  132. }
  133. public List<ushort> GetLUNList()
  134. {
  135. if (!m_isConnected)
  136. {
  137. throw new InvalidOperationException("iSCSI client is not connected");
  138. }
  139. SCSICommandPDU reportLUNs = ClientHelper.GetReportLUNsCommand(m_connection, ReportLUNsParameter.MinimumAllocationLength);
  140. SendPDU(reportLUNs);
  141. SCSIDataInPDU data = WaitForPDU(reportLUNs.InitiatorTaskTag) as SCSIDataInPDU;
  142. if (data != null && data.StatusPresent && data.Status == SCSIStatusCodeName.Good)
  143. {
  144. uint requiredAllocationLength = ReportLUNsParameter.GetRequiredAllocationLength(data.Data);
  145. if (requiredAllocationLength > ReportLUNsParameter.MinimumAllocationLength)
  146. {
  147. reportLUNs = ClientHelper.GetReportLUNsCommand(m_connection, requiredAllocationLength);
  148. m_clientSocket.Send(reportLUNs.GetBytes());
  149. data = WaitForPDU(reportLUNs.InitiatorTaskTag) as SCSIDataInPDU;
  150. if (data == null || !data.StatusPresent || data.Status != SCSIStatusCodeName.Good)
  151. {
  152. return null;
  153. }
  154. }
  155. ReportLUNsParameter parameter = new ReportLUNsParameter(data.Data);
  156. List<ushort> result = new List<ushort>();
  157. foreach(LUNStructure lun in parameter.LUNList)
  158. {
  159. if (lun.IsSingleLevelLUN)
  160. {
  161. result.Add(lun);
  162. }
  163. }
  164. return result;
  165. }
  166. return null;
  167. }
  168. /// <returns>Capacity in bytes</returns>
  169. public ulong ReadCapacity(ushort LUN, out int bytesPerSector)
  170. {
  171. if (!m_isConnected)
  172. {
  173. throw new InvalidOperationException("iSCSI client is not connected");
  174. }
  175. SCSICommandPDU readCapacity = ClientHelper.GetReadCapacity10Command(m_connection, LUN);
  176. SendPDU(readCapacity);
  177. // SCSIResponsePDU with CheckCondition could be returned in case of an error
  178. SCSIDataInPDU data = WaitForPDU(readCapacity.InitiatorTaskTag) as SCSIDataInPDU;
  179. if (data != null && data.StatusPresent && data.Status == SCSIStatusCodeName.Good)
  180. {
  181. ReadCapacity10Parameter capacity = new ReadCapacity10Parameter(data.Data);
  182. if (capacity.ReturnedLBA != 0xFFFFFFFF)
  183. {
  184. bytesPerSector = (int)capacity.BlockLengthInBytes;
  185. return (ulong)(capacity.ReturnedLBA + 1) * capacity.BlockLengthInBytes;
  186. }
  187. readCapacity = ClientHelper.GetReadCapacity16Command(m_connection, LUN);
  188. m_clientSocket.Send(readCapacity.GetBytes());
  189. data = WaitForPDU(readCapacity.InitiatorTaskTag) as SCSIDataInPDU;
  190. if (data != null && data.StatusPresent && data.Status == SCSIStatusCodeName.Good)
  191. {
  192. ReadCapacity16Parameter capacity16 = new ReadCapacity16Parameter(data.Data);
  193. bytesPerSector = (int)capacity16.BlockLengthInBytes;
  194. return (ulong)(capacity16.ReturnedLBA + 1) * capacity16.BlockLengthInBytes;
  195. }
  196. }
  197. bytesPerSector = 0;
  198. return 0;
  199. }
  200. public byte[] Read(ushort LUN, ulong sectorIndex, uint sectorCount, int bytesPerSector)
  201. {
  202. if (!m_isConnected)
  203. {
  204. throw new InvalidOperationException("iSCSI client is not connected");
  205. }
  206. SCSICommandPDU readCommand = ClientHelper.GetRead16Command(m_connection, LUN, sectorIndex, sectorCount, bytesPerSector);
  207. SendPDU(readCommand);
  208. // RFC 3720: Data payload is associated with a specific SCSI command through the Initiator Task Tag
  209. SCSIDataInPDU data = WaitForPDU(readCommand.InitiatorTaskTag) as SCSIDataInPDU;
  210. byte[] result = new byte[sectorCount * bytesPerSector];
  211. while (data != null)
  212. {
  213. Array.Copy(data.Data, 0, result, data.BufferOffset, data.DataSegmentLength);
  214. if (data.StatusPresent)
  215. {
  216. break;
  217. }
  218. data = WaitForPDU(readCommand.InitiatorTaskTag) as SCSIDataInPDU;
  219. }
  220. if (data != null && data.Status == SCSIStatusCodeName.Good)
  221. {
  222. return result;
  223. }
  224. else
  225. {
  226. return null;
  227. }
  228. }
  229. public bool Write(ushort LUN, ulong sectorIndex, byte[] data, int bytesPerSector)
  230. {
  231. if (!m_isConnected)
  232. {
  233. throw new InvalidOperationException("iSCSI client is not connected");
  234. }
  235. SCSICommandPDU writeCommand = ClientHelper.GetWrite16Command(m_connection, LUN, sectorIndex, data, bytesPerSector);
  236. SendPDU(writeCommand);
  237. ISCSIPDU response = WaitForPDU(writeCommand.InitiatorTaskTag);
  238. while (response is ReadyToTransferPDU)
  239. {
  240. List<SCSIDataOutPDU> requestedData = ClientHelper.GetWriteData(m_connection, LUN, sectorIndex, data, bytesPerSector, (ReadyToTransferPDU)response);
  241. foreach (SCSIDataOutPDU dataOut in requestedData)
  242. {
  243. SendPDU(dataOut);
  244. }
  245. response = WaitForPDU(writeCommand.InitiatorTaskTag);
  246. }
  247. if (response is SCSIResponsePDU)
  248. {
  249. if (((SCSIResponsePDU)response).Status == SCSIStatusCodeName.Good)
  250. {
  251. return true;
  252. }
  253. }
  254. return false;
  255. }
  256. public bool PingTarget()
  257. {
  258. if (!m_isConnected)
  259. {
  260. throw new InvalidOperationException("iSCSI client is not connected");
  261. }
  262. NOPOutPDU request = ClientHelper.GetPingRequest(m_connection);
  263. SendPDU(request);
  264. NOPInPDU response = WaitForPDU(request.InitiatorTaskTag) as NOPInPDU;
  265. return response != null;
  266. }
  267. private void OnClientSocketReceive(IAsyncResult ar)
  268. {
  269. ConnectionState state = (ConnectionState)ar.AsyncState;
  270. if (!m_clientSocket.Connected)
  271. {
  272. return;
  273. }
  274. int numberOfBytesReceived = 0;
  275. try
  276. {
  277. numberOfBytesReceived = m_clientSocket.EndReceive(ar);
  278. }
  279. catch (ArgumentException) // The IAsyncResult object was not returned from the corresponding synchronous method on this class.
  280. {
  281. return;
  282. }
  283. catch (ObjectDisposedException)
  284. {
  285. Log("[ReceiveCallback] EndReceive ObjectDisposedException");
  286. return;
  287. }
  288. catch (SocketException ex)
  289. {
  290. Log("[ReceiveCallback] EndReceive SocketException: " + ex.Message);
  291. return;
  292. }
  293. if (numberOfBytesReceived == 0)
  294. {
  295. m_isConnected = false;
  296. }
  297. else
  298. {
  299. ISCSIConnectionReceiveBuffer buffer = state.ReceiveBuffer;
  300. buffer.SetNumberOfBytesReceived(numberOfBytesReceived);
  301. ProcessConnectionBuffer(state);
  302. try
  303. {
  304. m_clientSocket.BeginReceive(buffer.Buffer, buffer.WriteOffset, buffer.AvailableLength, SocketFlags.None, new AsyncCallback(OnClientSocketReceive), state);
  305. }
  306. catch (ObjectDisposedException)
  307. {
  308. m_isConnected = false;
  309. Log("[ReceiveCallback] BeginReceive ObjectDisposedException");
  310. }
  311. catch (SocketException ex)
  312. {
  313. m_isConnected = false;
  314. Log("[ReceiveCallback] BeginReceive SocketException: " + ex.Message);
  315. }
  316. }
  317. }
  318. private void ProcessConnectionBuffer(ConnectionState state)
  319. {
  320. ISCSIConnectionReceiveBuffer buffer = state.ReceiveBuffer;
  321. while (buffer.HasCompletePDU())
  322. {
  323. ISCSIPDU pdu = null;
  324. try
  325. {
  326. pdu = buffer.DequeuePDU();
  327. }
  328. catch (Exception)
  329. {
  330. throw;
  331. }
  332. if (pdu.GetType() == typeof(ISCSIPDU))
  333. {
  334. throw new Exception("Unsupported");
  335. }
  336. else
  337. {
  338. ProcessPDU(pdu, state);
  339. }
  340. }
  341. }
  342. private void ProcessPDU(ISCSIPDU pdu, ConnectionState state)
  343. {
  344. if (pdu is NOPInPDU)
  345. {
  346. if (((NOPInPDU)pdu).TargetTransferTag != 0xFFFFFFFF)
  347. {
  348. // Send NOP-OUT
  349. NOPOutPDU response = ClientHelper.GetPingResponse((NOPInPDU)pdu, m_connection);
  350. SendPDU(response);
  351. return;
  352. }
  353. }
  354. if (m_connection.StatusNumberingStarted)
  355. {
  356. uint? responseStatSN = PDUHelper.GetStatSN(pdu);
  357. if (m_connection.ExpStatSN == responseStatSN)
  358. {
  359. m_connection.ExpStatSN++;
  360. }
  361. }
  362. lock (m_incomingQueueLock)
  363. {
  364. m_incomingQueue.Add(pdu);
  365. m_incomingQueueEventHandle.Set();
  366. }
  367. }
  368. public ISCSIPDU WaitForPDU(uint initiatorTaskTag)
  369. {
  370. const int TimeOut = 5000;
  371. Stopwatch stopwatch = new Stopwatch();
  372. stopwatch.Start();
  373. while (stopwatch.ElapsedMilliseconds < TimeOut)
  374. {
  375. lock (m_incomingQueueLock)
  376. {
  377. for (int index = 0; index < m_incomingQueue.Count; index++)
  378. {
  379. ISCSIPDU pdu = m_incomingQueue[index];
  380. if (pdu.InitiatorTaskTag == initiatorTaskTag)
  381. {
  382. m_incomingQueue.RemoveAt(index);
  383. return pdu;
  384. }
  385. }
  386. }
  387. m_incomingQueueEventHandle.WaitOne(100);
  388. }
  389. return null;
  390. }
  391. public void SendPDU(ISCSIPDU request)
  392. {
  393. try
  394. {
  395. if (m_connection.StatusNumberingStarted)
  396. {
  397. PDUHelper.SetExpStatSN(request, m_connection.ExpStatSN);
  398. }
  399. m_clientSocket.Send(request.GetBytes());
  400. Log("[{0}][SendPDU] Sent request to target, Operation: {1}, Size: {2}", m_connection.ConnectionIdentifier, (ISCSIOpCodeName)request.OpCode, request.Length);
  401. }
  402. catch (SocketException ex)
  403. {
  404. Log("[{0}][SendPDU] Failed to send PDU to target (Operation: {1}, Size: {2}), SocketException: {3}", m_connection.ConnectionIdentifier, (ISCSIOpCodeName)request.OpCode, request.Length, ex.Message);
  405. m_isConnected = false;
  406. }
  407. catch (ObjectDisposedException)
  408. {
  409. m_isConnected = false;
  410. }
  411. }
  412. public bool IsConnected
  413. {
  414. get
  415. {
  416. return m_isConnected;
  417. }
  418. }
  419. public static void Log(string message, params object[] args)
  420. {
  421. Log(String.Format(message, args));
  422. }
  423. public static void Log(string message)
  424. {
  425. if (m_logFile != null)
  426. {
  427. lock (m_logSyncLock)
  428. {
  429. StreamWriter writer = new StreamWriter(m_logFile);
  430. string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ");
  431. writer.WriteLine(timestamp + message);
  432. writer.Flush();
  433. }
  434. }
  435. }
  436. }
  437. }