Program.AttachCommand.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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 DiskAccessLibrary;
  11. using DiskAccessLibrary.LogicalDiskManager;
  12. using ISCSI.Server;
  13. using Utilities;
  14. namespace ISCSIConsole
  15. {
  16. partial class Program
  17. {
  18. public const string DefaultTargetIQN = "iqn.1991-05.com.microsoft";
  19. public static void AttachCommand(string[] args)
  20. {
  21. if (m_server != null)
  22. {
  23. Console.WriteLine("Server is already running");
  24. return;
  25. }
  26. if (args.Length >= 2)
  27. {
  28. KeyValuePairList<string, string> parameters = ParseParameters(args, 2);
  29. if (!VerifyParameters(parameters, "vdisk", "disk", "volume", "readonly", "target"))
  30. {
  31. Console.WriteLine();
  32. Console.WriteLine("Invalid parameter");
  33. HelpAttach();
  34. return;
  35. }
  36. switch (args[1].ToLower())
  37. {
  38. case "vdisk":
  39. {
  40. if (m_selectedDisk == null)
  41. {
  42. Console.WriteLine("No disk has been selected");
  43. break;
  44. }
  45. if (!(m_selectedDisk is DiskImage))
  46. {
  47. Console.WriteLine("Selected disk is not a disk image");
  48. break;
  49. }
  50. DiskImage disk = (DiskImage)m_selectedDisk;
  51. string defaultStorageTargetName = Path.GetFileNameWithoutExtension(disk.Path);
  52. string defaultTargetName = DefaultTargetIQN + ":" + defaultStorageTargetName.Replace(" ", ""); // spaces are not allowed
  53. AttachISCSIDisk(disk, defaultTargetName, parameters);
  54. break;
  55. }
  56. case "disk":
  57. {
  58. if (m_selectedDisk == null)
  59. {
  60. Console.WriteLine("Error: No disk has been selected.");
  61. break;
  62. }
  63. if (!(m_selectedDisk is PhysicalDisk))
  64. {
  65. Console.WriteLine("Error: The selected disk is not a physical disk.");
  66. break;
  67. }
  68. bool isAttachmentReadOnly = parameters.ContainsKey("readonly");
  69. PhysicalDisk disk = (PhysicalDisk)m_selectedDisk;
  70. if (!isAttachmentReadOnly)
  71. {
  72. if (Environment.OSVersion.Version.Major >= 6)
  73. {
  74. bool isDiskReadOnly;
  75. bool isOnline = disk.GetOnlineStatus(out isDiskReadOnly);
  76. if (isOnline)
  77. {
  78. Console.WriteLine();
  79. Console.WriteLine("Error: The selected disk must be taken offline.");
  80. break;
  81. }
  82. if (!isAttachmentReadOnly && isDiskReadOnly)
  83. {
  84. Console.WriteLine();
  85. Console.WriteLine("Error: The selected disk is set to readonly!");
  86. break;
  87. }
  88. }
  89. else
  90. {
  91. Console.WriteLine();
  92. // Locking mechanism is not implemented
  93. Console.Write("Warning: if a volume on this disk is mounted locally, data corruption may occur!");
  94. }
  95. }
  96. string defaultStorageTargetName = string.Format("disk{0}", disk.PhysicalDiskIndex);
  97. string defaultTargetName = DefaultTargetIQN + ":" + defaultStorageTargetName;
  98. AttachISCSIDisk(disk, defaultTargetName, parameters);
  99. break;
  100. }
  101. case "volume":
  102. {
  103. if (m_selectedVolume == null)
  104. {
  105. Console.WriteLine("No volume has been selected.");
  106. break;
  107. }
  108. VolumeDisk virtualDisk = new VolumeDisk(m_selectedVolume);
  109. string defaultTargetName = DefaultTargetIQN + ":Volume";
  110. bool isAttachmentReadOnly = parameters.ContainsKey("readonly");
  111. if (!isAttachmentReadOnly)
  112. {
  113. if (Environment.OSVersion.Version.Major >= 6)
  114. {
  115. if (m_selectedVolume is DynamicVolume)
  116. {
  117. foreach(DiskExtent extent in ((DynamicVolume)m_selectedVolume).Extents)
  118. {
  119. if (extent.Disk is PhysicalDisk)
  120. {
  121. bool isDiskReadOnly;
  122. bool isOnline = ((PhysicalDisk)extent.Disk).GetOnlineStatus(out isDiskReadOnly);
  123. if (isOnline)
  124. {
  125. Console.WriteLine("Error: All disks containing the volume must be taken offline.");
  126. return;
  127. }
  128. if (isDiskReadOnly)
  129. {
  130. Console.WriteLine("Error: A disk containing the volume is set to readonly.");
  131. return;
  132. }
  133. }
  134. }
  135. }
  136. else if (m_selectedVolume is Partition)
  137. {
  138. Disk disk = ((Partition)m_selectedVolume).Disk;
  139. if (disk is PhysicalDisk)
  140. {
  141. bool isDiskReadOnly;
  142. bool isOnline = ((PhysicalDisk)disk).GetOnlineStatus(out isDiskReadOnly);
  143. if (isOnline)
  144. {
  145. Console.WriteLine("Error: The disk containing the volume must be taken offline.");
  146. return;
  147. }
  148. if (isDiskReadOnly)
  149. {
  150. Console.WriteLine("Error: The disk containing the volume is set to readonly.");
  151. return;
  152. }
  153. }
  154. }
  155. }
  156. else
  157. {
  158. Console.WriteLine();
  159. // Locking mechanism is not implemented
  160. Console.WriteLine("Warning: if this volume is mounted locally, data corruption may occur!");
  161. }
  162. }
  163. AttachISCSIDisk(virtualDisk, defaultTargetName, parameters);
  164. break;
  165. }
  166. default:
  167. {
  168. Console.WriteLine();
  169. Console.WriteLine("Invalid argument.");
  170. HelpAttach();
  171. break;
  172. }
  173. }
  174. }
  175. else
  176. {
  177. HelpAttach();
  178. }
  179. }
  180. public static void HelpAttach()
  181. {
  182. Console.WriteLine();
  183. Console.WriteLine("ATTACH VDISK [READONLY] [TARGET=<NAME>] - Attach virtual hard disk file");
  184. Console.WriteLine("ATTACH DISK [READONLY] [TARGET=<NAME>] - Attach selected physical disk");
  185. Console.WriteLine("ATTACH VOLUME [READONLY] [TARGET=<NAME>] - Attach selected volume");
  186. }
  187. public static void AttachISCSIDisk(Disk disk, string defaultTargetName, KeyValuePairList<string, string> parameters)
  188. {
  189. if (VerifyParameters(parameters, "readonly", "target"))
  190. {
  191. bool isReadOnly = parameters.ContainsKey("readonly");
  192. disk.IsReadOnly |= isReadOnly;
  193. if (disk is DiskImage)
  194. {
  195. bool isLocked = ((DiskImage)disk).ExclusiveLock();
  196. if (!isLocked)
  197. {
  198. Console.WriteLine("Error: Cannot lock the disk image for exclusive access");
  199. return;
  200. }
  201. }
  202. ISCSITarget target = null;
  203. string targetName = defaultTargetName;
  204. if (parameters.ContainsKey("target"))
  205. {
  206. string name = parameters.ValueOf("target");
  207. if (IsValidISCSIName(name))
  208. {
  209. targetName = name;
  210. }
  211. else if (IsValidStorageTargetName(name))
  212. {
  213. targetName = DefaultTargetIQN + ":" + name;
  214. }
  215. else
  216. {
  217. Console.WriteLine("Invalid parameter.");
  218. HelpAttach();
  219. }
  220. }
  221. target = FindTarget(targetName);
  222. if (target == null)
  223. {
  224. target = AddTarget(targetName);
  225. }
  226. target.Disks.Add(disk);
  227. Console.WriteLine("Disk added to target: {0}", target.TargetName);
  228. }
  229. else
  230. {
  231. HelpAttach();
  232. }
  233. }
  234. public static ISCSITarget AddTarget(string targetName)
  235. {
  236. List<Disk> disks = new List<Disk>();
  237. ISCSITarget target = new ISCSITarget(targetName, disks);
  238. m_targets.Add(target);
  239. return target;
  240. }
  241. public static ISCSITarget FindTarget(string targetName)
  242. {
  243. foreach (ISCSITarget target in m_targets)
  244. {
  245. // iSCSI names are not case sensitive
  246. if (target.TargetName.ToLower() == targetName.ToLower())
  247. {
  248. return target;
  249. }
  250. }
  251. return null;
  252. }
  253. /// <summary>
  254. /// Check if a name is a valid initiator or target name (a.k.a. iSCSI name)
  255. /// </summary>
  256. public static bool IsValidISCSIName(string name)
  257. {
  258. if (name.ToLower().StartsWith("iqn."))
  259. {
  260. return IsValidIQN(name);
  261. }
  262. else
  263. {
  264. return IsValidEUI(name);
  265. }
  266. }
  267. public static bool IsValidIQN(string name)
  268. {
  269. if (name.ToLower().StartsWith("iqn."))
  270. {
  271. if (name.Length > 12 && name[8] == '-' && name[11] == '.')
  272. {
  273. int year = Conversion.ToInt32(name.Substring(4, 4), -1);
  274. int month = Conversion.ToInt32(name.Substring(9, 2), -1);
  275. if (year != -1 && (month >= 1 && month <= 12))
  276. {
  277. string reversedDomain;
  278. string storageTargetName = String.Empty;
  279. int index = name.IndexOf(":");
  280. if (index >= 12) // index cannot be < 12
  281. {
  282. reversedDomain = name.Substring(12, index - 12);
  283. storageTargetName = name.Substring(index + 1);
  284. return IsValidReversedDomainName(reversedDomain) && IsValidStorageTargetName(storageTargetName);
  285. }
  286. else
  287. {
  288. reversedDomain = name.Substring(12);
  289. return IsValidReversedDomainName(reversedDomain);
  290. }
  291. }
  292. }
  293. }
  294. return false;
  295. }
  296. public static bool IsValidReversedDomainName(string name)
  297. {
  298. string[] components = name.Split('.');
  299. if (components.Length < 1)
  300. {
  301. return false;
  302. }
  303. foreach (string component in components)
  304. {
  305. if (component.Length == 0 || component.StartsWith("-") || component.EndsWith("-"))
  306. {
  307. return false;
  308. }
  309. for (int index = 0; index < component.Length; index++)
  310. {
  311. bool isValid = (component[index] >= '0' && component[index] <= '9') ||
  312. (component[index] >= 'a' && component[index] <= 'z') ||
  313. (component[index] >= 'A' && component[index] <= 'Z') ||
  314. (component[index] == '-');
  315. if (!isValid)
  316. {
  317. return false;
  318. }
  319. }
  320. }
  321. return true;
  322. }
  323. public static bool IsValidStorageTargetName(string name)
  324. {
  325. // With the exception of the colon prefix, the owner of the domain name can assign everything after the reversed domain name as desired
  326. // No whitespace characters are used in iSCSI names
  327. // Note: String.Empty is a valid storage target name
  328. if (name.StartsWith(":") || name.Contains(" "))
  329. {
  330. return false;
  331. }
  332. return true;
  333. }
  334. public static bool IsValidEUI(string name)
  335. {
  336. if (name.ToLower().StartsWith("eui.") && name.Length == 20)
  337. {
  338. string identifier = name.Substring(5);
  339. return OnlyHexChars(identifier);
  340. }
  341. return false;
  342. }
  343. public static bool OnlyHexChars(string value)
  344. {
  345. for (int index = 0; index < value.Length; index++)
  346. {
  347. bool isValid = (value[index] >= '0' && value[index] <= '9') ||
  348. (value[index] >= 'a' && value[index] <= 'f') ||
  349. (value[index] >= 'A' && value[index] <= 'F');
  350. if (!isValid)
  351. {
  352. return false;
  353. }
  354. }
  355. return true;
  356. }
  357. }
  358. }