ClientHelper.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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.Text;
  10. using SCSI;
  11. using Utilities;
  12. namespace ISCSI.Client
  13. {
  14. public class ClientHelper
  15. {
  16. /// <param name="targetName">Set to null for discovery session</param>
  17. internal static LoginRequestPDU GetFirstStageLoginRequest(string initiatorName, string targetName, ISCSISession session, ConnectionParameters connection)
  18. {
  19. LoginRequestPDU request = new LoginRequestPDU();
  20. request.InitiatorTaskTag = session.GetNextTaskTag();
  21. request.ISID = session.ISID;
  22. request.TSIH = 0; // used on the first connection for a new session
  23. request.CID = connection.CID;
  24. request.CmdSN = session.GetNextCmdSN(false);
  25. request.ExpStatSN = 0;
  26. // The stage codes are:
  27. // 0 - SecurityNegotiation
  28. // 1 - LoginOperationalNegotiation
  29. // 3 - FullFeaturePhase
  30. request.CurrentStage = 0;
  31. request.NextStage = 1;
  32. request.Transit = true;
  33. request.VersionMax = 0;
  34. request.VersionMin = 0;
  35. KeyValuePairList<string, string> loginParameters = new KeyValuePairList<string, string>();
  36. loginParameters.Add("InitiatorName", initiatorName);
  37. loginParameters.Add("AuthMethod", "None");
  38. if (targetName == null)
  39. {
  40. loginParameters.Add("SessionType", "Discovery");
  41. }
  42. else
  43. {
  44. // RFC 3720: For any connection within a session whose type is not "Discovery", the first Login Request MUST also include the TargetName key=value pair.
  45. loginParameters.Add("SessionType", "Normal");
  46. loginParameters.Add("TargetName", targetName);
  47. }
  48. request.LoginParameters = loginParameters;
  49. return request;
  50. }
  51. internal static LoginRequestPDU GetSecondStageLoginRequest(LoginResponsePDU firstStageResponse, ISCSISession session, ConnectionParameters connection, bool isDiscovery)
  52. {
  53. LoginRequestPDU request = new LoginRequestPDU();
  54. request.ISID = firstStageResponse.ISID;
  55. request.TSIH = firstStageResponse.TSIH;
  56. request.CID = connection.CID;
  57. request.InitiatorTaskTag = session.GetNextTaskTag();
  58. request.CmdSN = session.GetNextCmdSN(false);
  59. request.CurrentStage = firstStageResponse.NextStage;
  60. request.NextStage = 3;
  61. request.Transit = true;
  62. request.VersionMax = 0;
  63. request.VersionMin = 0;
  64. KeyValuePairList<string, string> loginParameters = new KeyValuePairList<string, string>();
  65. loginParameters.Add("HeaderDigest", "None");
  66. loginParameters.Add("DataDigest", "None");
  67. loginParameters.Add("MaxRecvDataSegmentLength", connection.InitiatorMaxRecvDataSegmentLength.ToString());
  68. if (!isDiscovery)
  69. {
  70. loginParameters.Add("MaxConnections", ISCSIClient.DesiredParameters.MaxConnections.ToString());
  71. loginParameters.Add("InitialR2T", ISCSIClient.DesiredParameters.InitialR2T ? "Yes" : "No");
  72. loginParameters.Add("ImmediateData", ISCSIClient.DesiredParameters.ImmediateData ? "Yes" : "No");
  73. loginParameters.Add("MaxBurstLength", ISCSIClient.DesiredParameters.MaxBurstLength.ToString());
  74. loginParameters.Add("FirstBurstLength", ISCSIClient.DesiredParameters.FirstBurstLength.ToString());
  75. loginParameters.Add("MaxOutstandingR2T", ISCSIClient.DesiredParameters.MaxOutstandingR2T.ToString());
  76. loginParameters.Add("DataPDUInOrder", ISCSIClient.DesiredParameters.DataPDUInOrder ? "Yes" : "No");
  77. loginParameters.Add("DataSequenceInOrder", ISCSIClient.DesiredParameters.DataSequenceInOrder ? "Yes" : "No");
  78. loginParameters.Add("ErrorRecoveryLevel", ISCSIClient.DesiredParameters.ErrorRecoveryLevel.ToString());
  79. }
  80. loginParameters.Add("DefaultTime2Wait", ISCSIClient.DesiredParameters.DefaultTime2Wait.ToString());
  81. loginParameters.Add("DefaultTime2Retain", ISCSIClient.DesiredParameters.DefaultTime2Retain.ToString());
  82. request.LoginParameters = loginParameters;
  83. return request;
  84. }
  85. internal static LoginRequestPDU GetSingleStageLoginRequest(string initiatorName, string targetName, ISCSISession session, ConnectionParameters connection)
  86. {
  87. LoginRequestPDU request = new LoginRequestPDU();
  88. request.ISID = session.ISID;
  89. request.TSIH = session.TSIH;
  90. request.CID = connection.CID;
  91. request.InitiatorTaskTag = session.GetNextTaskTag();
  92. request.CmdSN = session.GetNextCmdSN(false);
  93. request.CurrentStage = 1;
  94. request.NextStage = 3;
  95. request.Transit = true;
  96. request.VersionMax = 0;
  97. request.VersionMin = 0;
  98. KeyValuePairList<string, string> loginParameters = new KeyValuePairList<string, string>();
  99. loginParameters.Add("InitiatorName", initiatorName);
  100. if (targetName == null)
  101. {
  102. loginParameters.Add("SessionType", "Discovery");
  103. }
  104. else
  105. {
  106. loginParameters.Add("SessionType", "Normal");
  107. loginParameters.Add("TargetName", targetName);
  108. }
  109. loginParameters.Add("DataDigest", "None");
  110. loginParameters.Add("MaxRecvDataSegmentLength", connection.InitiatorMaxRecvDataSegmentLength.ToString());
  111. if (targetName != null)
  112. {
  113. loginParameters.Add("MaxConnections", ISCSIClient.DesiredParameters.MaxConnections.ToString());
  114. loginParameters.Add("InitialR2T", ISCSIClient.DesiredParameters.InitialR2T ? "Yes" : "No");
  115. loginParameters.Add("ImmediateData", ISCSIClient.DesiredParameters.ImmediateData ? "Yes" : "No");
  116. loginParameters.Add("MaxBurstLength", ISCSIClient.DesiredParameters.MaxBurstLength.ToString());
  117. loginParameters.Add("FirstBurstLength", ISCSIClient.DesiredParameters.FirstBurstLength.ToString());
  118. loginParameters.Add("MaxOutstandingR2T", ISCSIClient.DesiredParameters.MaxOutstandingR2T.ToString());
  119. loginParameters.Add("DataPDUInOrder", ISCSIClient.DesiredParameters.DataPDUInOrder ? "Yes" : "No");
  120. loginParameters.Add("DataSequenceInOrder", ISCSIClient.DesiredParameters.DataSequenceInOrder ? "Yes" : "No");
  121. loginParameters.Add("ErrorRecoveryLevel", ISCSIClient.DesiredParameters.ErrorRecoveryLevel.ToString());
  122. }
  123. loginParameters.Add("DefaultTime2Wait", ISCSIClient.DesiredParameters.DefaultTime2Wait.ToString());
  124. loginParameters.Add("DefaultTime2Retain", ISCSIClient.DesiredParameters.DefaultTime2Retain.ToString());
  125. request.LoginParameters = loginParameters;
  126. return request;
  127. }
  128. internal static void UpdateOperationalParameters(KeyValuePairList<string, string> loginParameters, ISCSISession session, ConnectionParameters connection)
  129. {
  130. string value = loginParameters.ValueOf("MaxRecvDataSegmentLength");
  131. if (value != null)
  132. {
  133. connection.TargetMaxRecvDataSegmentLength = Convert.ToInt32(value);
  134. }
  135. value = loginParameters.ValueOf("MaxConnections");
  136. if (value != null)
  137. {
  138. session.MaxConnections = Convert.ToInt32(value);
  139. }
  140. else
  141. {
  142. session.MaxConnections = ISCSIClient.DesiredParameters.MaxConnections;
  143. }
  144. value = loginParameters.ValueOf("InitialR2T");
  145. if (value != null)
  146. {
  147. session.InitialR2T = (value == "Yes") ? true : false;
  148. }
  149. else
  150. {
  151. session.InitialR2T = ISCSIClient.DesiredParameters.InitialR2T;
  152. }
  153. value = loginParameters.ValueOf("ImmediateData");
  154. if (value != null)
  155. {
  156. session.ImmediateData = (value == "Yes") ? true : false;
  157. }
  158. else
  159. {
  160. session.ImmediateData = ISCSIClient.DesiredParameters.ImmediateData;
  161. }
  162. value = loginParameters.ValueOf("MaxBurstLength");
  163. if (value != null)
  164. {
  165. session.MaxBurstLength = Convert.ToInt32(value);
  166. }
  167. else
  168. {
  169. session.MaxBurstLength = ISCSIClient.DesiredParameters.MaxBurstLength;
  170. }
  171. value = loginParameters.ValueOf("FirstBurstLength");
  172. if (value != null)
  173. {
  174. session.FirstBurstLength = Convert.ToInt32(value);
  175. }
  176. else
  177. {
  178. session.FirstBurstLength = ISCSIClient.DesiredParameters.FirstBurstLength;
  179. }
  180. value = loginParameters.ValueOf("DefaultTime2Wait");
  181. if (value != null)
  182. {
  183. session.DefaultTime2Wait = Convert.ToInt32(value);
  184. }
  185. else
  186. {
  187. session.DefaultTime2Wait = ISCSIClient.DesiredParameters.DefaultTime2Wait;
  188. }
  189. value = loginParameters.ValueOf("DefaultTime2Retain");
  190. if (value != null)
  191. {
  192. session.DefaultTime2Retain = Convert.ToInt32(value);
  193. }
  194. else
  195. {
  196. session.DefaultTime2Retain = ISCSIClient.DesiredParameters.DefaultTime2Retain;
  197. }
  198. value = loginParameters.ValueOf("MaxOutstandingR2T");
  199. if (value != null)
  200. {
  201. session.MaxOutstandingR2T = Convert.ToInt32(value);
  202. }
  203. else
  204. {
  205. session.MaxOutstandingR2T = ISCSIClient.DesiredParameters.MaxOutstandingR2T;
  206. }
  207. value = loginParameters.ValueOf("DataPDUInOrder");
  208. if (value != null)
  209. {
  210. session.DataPDUInOrder = (value == "Yes") ? true : false;
  211. }
  212. else
  213. {
  214. session.DataPDUInOrder = ISCSIClient.DesiredParameters.DataPDUInOrder;
  215. }
  216. value = loginParameters.ValueOf("DataSequenceInOrder");
  217. if (value != null)
  218. {
  219. session.DataSequenceInOrder = (value == "Yes") ? true : false;
  220. }
  221. else
  222. {
  223. session.DataSequenceInOrder = ISCSIClient.DesiredParameters.DataSequenceInOrder;
  224. }
  225. value = loginParameters.ValueOf("ErrorRecoveryLevel");
  226. if (value != null)
  227. {
  228. session.ErrorRecoveryLevel = Convert.ToInt32(value);
  229. }
  230. else
  231. {
  232. session.ErrorRecoveryLevel = ISCSIClient.DesiredParameters.ErrorRecoveryLevel;
  233. }
  234. }
  235. internal static LogoutRequestPDU GetLogoutRequest(ISCSISession session, ConnectionParameters connection)
  236. {
  237. LogoutRequestPDU request = new LogoutRequestPDU();
  238. request.ReasonCode = LogoutReasonCode.CloseTheSession;
  239. request.InitiatorTaskTag = session.GetNextTaskTag();
  240. request.CID = connection.CID;
  241. request.CmdSN = session.GetNextCmdSN(true);
  242. return request;
  243. }
  244. internal static TextRequestPDU GetSendTargetsRequest(ISCSISession session, ConnectionParameters connection)
  245. {
  246. TextRequestPDU request = new TextRequestPDU();
  247. request.Text = "SendTargets=All";
  248. request.InitiatorTaskTag = session.GetNextTaskTag();
  249. request.CmdSN = session.GetNextCmdSN(true);
  250. request.Final = true;
  251. request.TargetTransferTag = 0xFFFFFFFF;
  252. return request;
  253. }
  254. internal static SCSICommandPDU GetReportLUNsCommand(ISCSISession session, ConnectionParameters connection, uint allocationLength)
  255. {
  256. SCSICommandDescriptorBlock reportLUNs = SCSICommandDescriptorBlock.Create(SCSIOpCodeName.ReportLUNs);
  257. reportLUNs.TransferLength = allocationLength;
  258. SCSICommandPDU scsiCommand = new SCSICommandPDU();
  259. scsiCommand.CommandDescriptorBlock = reportLUNs.GetBytes();
  260. scsiCommand.InitiatorTaskTag = session.GetNextTaskTag();
  261. scsiCommand.Final = true;
  262. scsiCommand.Read = true;
  263. scsiCommand.CmdSN = session.GetNextCmdSN(true);
  264. scsiCommand.ExpectedDataTransferLength = allocationLength;
  265. return scsiCommand;
  266. }
  267. internal static SCSICommandPDU GetReadCapacity10Command(ISCSISession session, ConnectionParameters connection, ushort LUN)
  268. {
  269. SCSICommandDescriptorBlock readCapacity10 = SCSICommandDescriptorBlock.Create(SCSIOpCodeName.ReadCapacity10);
  270. readCapacity10.TransferLength = ReadCapacity10Parameter.Length;
  271. SCSICommandPDU scsiCommand = new SCSICommandPDU();
  272. scsiCommand.CommandDescriptorBlock = readCapacity10.GetBytes();
  273. scsiCommand.InitiatorTaskTag = session.GetNextTaskTag();
  274. scsiCommand.Final = true;
  275. scsiCommand.Read = true;
  276. scsiCommand.LUN = LUN;
  277. scsiCommand.CmdSN = session.GetNextCmdSN(true);
  278. scsiCommand.ExpectedDataTransferLength = ReadCapacity10Parameter.Length;
  279. return scsiCommand;
  280. }
  281. internal static SCSICommandPDU GetReadCapacity16Command(ISCSISession session, ConnectionParameters connection, ushort LUN)
  282. {
  283. SCSICommandDescriptorBlock serviceActionIn = SCSICommandDescriptorBlock.Create(SCSIOpCodeName.ServiceActionIn);
  284. serviceActionIn.ServiceAction = ServiceAction.ReadCapacity16;
  285. serviceActionIn.TransferLength = ReadCapacity16Parameter.Length;
  286. SCSICommandPDU scsiCommand = new SCSICommandPDU();
  287. scsiCommand.CommandDescriptorBlock = serviceActionIn.GetBytes();
  288. scsiCommand.InitiatorTaskTag = session.GetNextTaskTag();
  289. scsiCommand.Final = true;
  290. scsiCommand.Read = true;
  291. scsiCommand.LUN = LUN;
  292. scsiCommand.CmdSN = session.GetNextCmdSN(true);
  293. scsiCommand.ExpectedDataTransferLength = ReadCapacity16Parameter.Length;
  294. return scsiCommand;
  295. }
  296. internal static SCSICommandPDU GetRead16Command(ISCSISession session, ConnectionParameters connection, ushort LUN, ulong sectorIndex, uint sectorCount, int bytesPerSector)
  297. {
  298. SCSICommandDescriptorBlock read16 = SCSICommandDescriptorBlock.Create(SCSIOpCodeName.Read16);
  299. read16.LogicalBlockAddress64 = sectorIndex;
  300. read16.TransferLength = sectorCount;
  301. SCSICommandPDU scsiCommand = new SCSICommandPDU();
  302. scsiCommand.CommandDescriptorBlock = read16.GetBytes();
  303. scsiCommand.LUN = LUN;
  304. scsiCommand.InitiatorTaskTag = session.GetNextTaskTag();
  305. scsiCommand.Final = true;
  306. scsiCommand.Read = true;
  307. scsiCommand.CmdSN = session.GetNextCmdSN(true);
  308. scsiCommand.ExpectedDataTransferLength = (uint)(sectorCount * bytesPerSector);
  309. return scsiCommand;
  310. }
  311. internal static SCSICommandPDU GetWrite16Command(ISCSISession session, ConnectionParameters connection, ushort LUN, ulong sectorIndex, byte[] data, int bytesPerSector)
  312. {
  313. SCSICommandDescriptorBlock write16 = SCSICommandDescriptorBlock.Create(SCSIOpCodeName.Write16);
  314. write16.LogicalBlockAddress64 = sectorIndex;
  315. write16.TransferLength = (uint)(data.Length / bytesPerSector);
  316. SCSICommandPDU scsiCommand = new SCSICommandPDU();
  317. scsiCommand.CommandDescriptorBlock = write16.GetBytes();
  318. if (session.ImmediateData)
  319. {
  320. int immediateDataLength = Math.Min(data.Length, session.FirstBurstLength);
  321. scsiCommand.Data = ByteReader.ReadBytes(data, 0, immediateDataLength);
  322. }
  323. scsiCommand.LUN = LUN;
  324. scsiCommand.InitiatorTaskTag = session.GetNextTaskTag();
  325. scsiCommand.Final = true;
  326. scsiCommand.Write = true;
  327. scsiCommand.CmdSN = session.GetNextCmdSN(true);
  328. scsiCommand.ExpectedDataTransferLength = (uint)(data.Length);
  329. return scsiCommand;
  330. }
  331. internal static List<SCSIDataOutPDU> GetWriteData(ISCSISession session, ConnectionParameters connection, ushort LUN, ulong sectorIndex, byte[] data, int bytesPerSector, ReadyToTransferPDU readyToTransfer)
  332. {
  333. List<SCSIDataOutPDU> result = new List<SCSIDataOutPDU>();
  334. // if readyToTransfer.DesiredDataTransferLength <= connection.TargetMaxRecvDataSegmentLength we must send multiple Data-Out PDUs
  335. // We assume DesiredDataTransferLength does not violate session.MaxBurstLength
  336. int numberOfChunks = (int)Math.Ceiling((double)readyToTransfer.DesiredDataTransferLength / connection.TargetMaxRecvDataSegmentLength);
  337. for (int chunkIndex = 0; chunkIndex < numberOfChunks; chunkIndex++)
  338. {
  339. int chunkOffset = chunkIndex * connection.TargetMaxRecvDataSegmentLength;
  340. int chunkLength = (int)Math.Min(connection.TargetMaxRecvDataSegmentLength, readyToTransfer.DesiredDataTransferLength - chunkOffset);
  341. SCSIDataOutPDU dataOut = new SCSIDataOutPDU();
  342. dataOut.BufferOffset = readyToTransfer.BufferOffset + (uint)chunkOffset;
  343. dataOut.Data = ByteReader.ReadBytes(data, (int)dataOut.BufferOffset, chunkLength);
  344. dataOut.TargetTransferTag = readyToTransfer.TargetTransferTag;
  345. dataOut.InitiatorTaskTag = readyToTransfer.InitiatorTaskTag;
  346. if (chunkIndex == numberOfChunks - 1)
  347. {
  348. dataOut.Final = true;
  349. }
  350. result.Add(dataOut);
  351. }
  352. return result;
  353. }
  354. internal static NOPOutPDU GetPingRequest(ISCSISession session, ConnectionParameters connection)
  355. {
  356. // Microsoft iSCSI Target v3.1 expects that CmdSN won't be incremented after this request regardless of whether the ImmediateDelivery bit is set or not,
  357. // So we set the ImmediateDelivery bit to work around the issue.
  358. NOPOutPDU request = new NOPOutPDU();
  359. request.ImmediateDelivery = true;
  360. request.InitiatorTaskTag = session.GetNextTaskTag();
  361. request.CmdSN = session.GetNextCmdSN(false);
  362. // RFC 3720: The NOP-Out MUST only have the Target Transfer Tag set if it is issued in response to a NOP-In (with a valid Target Transfer Tag).
  363. // Otherwise, the Target Transfer Tag MUST be set to 0xffffffff.
  364. request.TargetTransferTag = 0xFFFFFFFF;
  365. return request;
  366. }
  367. internal static NOPOutPDU GetPingResponse(NOPInPDU request, ISCSISession session, ConnectionParameters connection)
  368. {
  369. NOPOutPDU response = new NOPOutPDU();
  370. // If the Initiator Task Tag contains 0xffffffff, the I bit MUST be set to 1 and the CmdSN is not advanced after this PDU is sent.
  371. response.ImmediateDelivery = true;
  372. // RFC 3720: The NOP-Out MUST have the Initiator Task Tag set to a valid value only if a response in the form of NOP-In is requested.
  373. // Otherwise, the Initiator Task Tag MUST be set to 0xffffffff
  374. response.InitiatorTaskTag = 0xFFFFFFFF;
  375. response.CmdSN = session.GetNextCmdSN(false);
  376. response.TargetTransferTag = request.TargetTransferTag;
  377. // p.s. the Data Segment (of the request sent by the target) MUST NOT contain any data
  378. return response;
  379. }
  380. public static ulong GetRandomISID()
  381. {
  382. byte a = 0x80; // Random
  383. ushort b = (ushort)(new Random().Next(UInt16.MaxValue + 1));
  384. byte c = (byte)(new Random().Next(Byte.MaxValue + 1));
  385. ushort d = 0;
  386. ulong isid = (ulong)a << 40 | (ulong)b << 24 | (ulong)c << 16 | (ulong)d;
  387. return isid;
  388. }
  389. }
  390. }