PhysicalDiskDifferencingDiskImage.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. using System;
  2. using System.IO;
  3. using System.Security.Authentication;
  4. using System.Text;
  5. using DiskAccessLibrary.FileSystems;
  6. using DiskAccessLibrary.Mod.Utility;
  7. namespace DiskAccessLibrary
  8. {
  9. public class PhysicalDiskDifferencingDiskImage : DiskImage
  10. {
  11. private const int SectorSize = 512;
  12. private PddInfo PddInfo { get; }
  13. public int NumberOfBlocks => PddInfo.NumberOfBlocks;
  14. public int BlockSize => PddInfo.BlockSize;
  15. public ReadOnlyIndexer<int, bool> IsBlockAllocated { get; }
  16. private bool _isExclusiveLock;
  17. private readonly Disk _underlyingDisk;
  18. private FileStream _snapshotFileStream;
  19. public PhysicalDiskDifferencingDiskImage(string diskImagePath, bool isReadOnly, Disk underlyingDisk) : base(diskImagePath, isReadOnly)
  20. {
  21. _underlyingDisk = underlyingDisk;
  22. PddInfo = new PddInfo(diskImagePath);
  23. IsBlockAllocated = new ReadOnlyIndexer<int, bool>(i => PddInfo.Allocated[i]);
  24. }
  25. public void OpenForRead()
  26. {
  27. _snapshotFileStream = File.Open(Path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
  28. }
  29. public void CloseForRead()
  30. {
  31. _snapshotFileStream?.Close();
  32. }
  33. public void ReadBlock(byte[] buffer, int offset, int count, int blockIndex, int blockOffset)
  34. {
  35. if (false == PddInfo.Allocated[blockIndex])
  36. {
  37. //TODO:convert block to sectors
  38. var rawOffset = (long)blockIndex * PddInfo.BlockSize + blockOffset;
  39. var sectorIndex = rawOffset / _underlyingDisk.BytesPerSector;
  40. while (count > 0)
  41. {
  42. var read = _basedFileStream.Read(buffer, offset, count);
  43. offset += read;
  44. count -= read;
  45. }
  46. }
  47. else
  48. {
  49. _snapshotFileStream.Position = PddInfo.Offset[blockIndex] + blockOffset;
  50. while (count > 0)
  51. {
  52. var read = _snapshotFileStream.Read(buffer, offset, count);
  53. offset += read;
  54. count -= read;
  55. }
  56. }
  57. }
  58. private void WriteBlock(byte[] buffer, int offset, int count, int blockIndex, int blockOffset)
  59. {
  60. if (false == PddInfo.Allocated[blockIndex])
  61. {
  62. //COW:allocate block
  63. _snapshotFileStream.Position = _snapshotFileStream.Length;
  64. PddInfo.Offset[blockIndex] = _snapshotFileStream.Position;
  65. //copy leading block from based image
  66. if (blockOffset > 0)
  67. {
  68. var readCount = blockOffset;
  69. var bufLeading = new byte[readCount];
  70. //TODO:convert block to sectors
  71. _basedFileStream.Position = (long)blockIndex * PddInfo.BlockSize;
  72. var readOffset = 0;
  73. while (readCount > 0)
  74. {
  75. var read = _basedFileStream.Read(bufLeading, readOffset, readCount);
  76. readOffset += read;
  77. readCount -= read;
  78. }
  79. _snapshotFileStream.Position = PddInfo.Offset[blockIndex];
  80. _snapshotFileStream.Write(bufLeading, 0, bufLeading.Length);
  81. }
  82. //write to snapshot directly
  83. _snapshotFileStream.Position = PddInfo.Offset[blockIndex] + blockOffset;
  84. _snapshotFileStream.Write(buffer, offset, count);
  85. //copy suffix block from based image
  86. if (blockOffset + count < PddInfo.BlockSize)
  87. {
  88. var suffixOffset = blockOffset + count;
  89. var readCount = PddInfo.BlockSize - suffixOffset;
  90. var bufSuffix = new byte[readCount];
  91. //TODO:convert block to sectors
  92. _basedFileStream.Position = (long)blockIndex * PddInfo.BlockSize + suffixOffset;
  93. var readOffset = 0;
  94. while (readCount > 0)
  95. {
  96. var read = _basedFileStream.Read(bufSuffix, readOffset, readCount);
  97. readOffset += read;
  98. readCount -= read;
  99. }
  100. _snapshotFileStream.Position = PddInfo.Offset[blockIndex] + suffixOffset;
  101. _snapshotFileStream.Write(bufSuffix, 0, bufSuffix.Length);
  102. }
  103. PddInfo.Allocated[blockIndex] = true;
  104. _snapshotFileStream.Position = PddInfo.EntryTableOffset + PddInfo.BlockIndexEntrySize * blockIndex;
  105. var bufEntry = BitConverter.GetBytes(PddInfo.Entries[blockIndex]);
  106. _snapshotFileStream.Write(bufEntry, 0, bufEntry.Length);
  107. }
  108. else
  109. {
  110. _snapshotFileStream.Position = PddInfo.Offset[blockIndex] + blockOffset;
  111. _snapshotFileStream.Write(buffer, offset, count);
  112. }
  113. }
  114. public override byte[] ReadSectors(long sectorIndex, int sectorCount)
  115. {
  116. var rawOffset = sectorIndex * SectorSize;
  117. var rawSize = sectorCount * SectorSize;
  118. var buffer = new byte[rawSize];
  119. for (var i = 0; i < rawSize;)
  120. {
  121. var blockIndex = (int)(rawOffset / PddInfo.BlockSize);
  122. var blockOffset = (int)(rawOffset % PddInfo.BlockSize);
  123. var bytesToRead = PddInfo.BlockSize - blockOffset;
  124. if (i + bytesToRead > rawSize)
  125. {
  126. bytesToRead = rawSize - i;
  127. }
  128. ReadBlock(buffer, i, bytesToRead, blockIndex, blockOffset);
  129. i += bytesToRead;
  130. rawOffset += bytesToRead;
  131. }
  132. return buffer;
  133. }
  134. public override void WriteSectors(long sectorIndex, byte[] data)
  135. {
  136. if (IsReadOnly) throw new AuthenticationException("Read only");
  137. var rawOffset = sectorIndex * SectorSize;
  138. for (var i = 0; i < data.Length;)
  139. {
  140. var blockIndex = (int)(rawOffset / PddInfo.BlockSize);
  141. var blockOffset = (int)(rawOffset % PddInfo.BlockSize);
  142. var bytesToWrite = PddInfo.BlockSize - blockOffset;
  143. if (i + bytesToWrite > data.Length)
  144. {
  145. bytesToWrite = data.Length - i;
  146. }
  147. WriteBlock(data, i, bytesToWrite, blockIndex, blockOffset);
  148. i += bytesToWrite;
  149. rawOffset += bytesToWrite;
  150. }
  151. }
  152. public override bool ExclusiveLock()
  153. {
  154. if (_isExclusiveLock) return true;
  155. _snapshotFileStream?.Close();
  156. _snapshotFileStream = IsReadOnly
  157. ? File.Open(Path, FileMode.Open, FileAccess.Read, FileShare.Read)
  158. : File.Open(Path, FileMode.Open, FileAccess.ReadWrite, FileShare.Read);
  159. _isExclusiveLock = true;
  160. return true;
  161. }
  162. public void Clean()
  163. {
  164. if (IsReadOnly) return;
  165. for (var blockIndex = 0; blockIndex < PddInfo.NumberOfBlocks; blockIndex++)
  166. {
  167. PddInfo.Allocated[blockIndex] = false;
  168. }
  169. for (var blockIndex = 0; blockIndex < PddInfo.NumberOfBlocks; blockIndex++)
  170. {
  171. _snapshotFileStream.Position = PddInfo.EntryTableOffset + PddInfo.BlockIndexEntrySize * blockIndex;
  172. var bufEntry = BitConverter.GetBytes(PddInfo.Entries[blockIndex]);
  173. _snapshotFileStream.Write(bufEntry, 0, bufEntry.Length);
  174. }
  175. _snapshotFileStream.SetLength(PddInfo.EntryTableOffset + PddInfo.NumberOfBlocks * PddInfo.BlockIndexEntrySize);
  176. }
  177. public override bool ReleaseLock()
  178. {
  179. _snapshotFileStream?.Close();
  180. _isExclusiveLock = false;
  181. return true;
  182. }
  183. public static BlockDifferencingDiskImage Create(string snapshot, long size, int blockSize)
  184. {
  185. var numberOfBlocks = (int)Math.DivRem(size, blockSize, out var rem);
  186. if (rem != 0) throw new ArgumentException("Size no align to blockSize");
  187. using var stream = File.Create(snapshot);
  188. using var writer = new BinaryWriter(stream);
  189. writer.Write((ushort)0);
  190. writer.Write(blockSize);
  191. writer.Write(numberOfBlocks);
  192. writer.Flush();
  193. stream.SetLength(stream.Length + numberOfBlocks * PddInfo.BlockIndexEntrySize);
  194. writer.Close();
  195. stream.Close();
  196. //return instance
  197. return new BlockDifferencingDiskImage(snapshot);
  198. }
  199. public static BlockDifferencingDiskImage Create(string based, string snapshot, int blockSize)
  200. {
  201. var fileSize = IoUtility.GetRealFileSize(based);
  202. if (fileSize % blockSize != 0) throw new ArgumentException("Block size no mul to base image size", nameof(blockSize));
  203. using var stream = File.Create(snapshot);
  204. using var writer = new BinaryWriter(stream);
  205. //create bdd struct
  206. var bufBasedPath = Encoding.UTF8.GetBytes(System.IO.Path.GetFullPath(based));
  207. var numberOfBlocks = (int)(fileSize / blockSize);
  208. writer.Write((ushort)bufBasedPath.Length);
  209. writer.Write(bufBasedPath);
  210. writer.Write(blockSize);
  211. writer.Write(numberOfBlocks);
  212. writer.Flush();
  213. stream.SetLength(stream.Length + numberOfBlocks * PddInfo.BlockIndexEntrySize);
  214. writer.Close();
  215. stream.Close();
  216. //return instance
  217. return new BlockDifferencingDiskImage(snapshot);
  218. }
  219. public override long Size => PddInfo.Length;
  220. public override int BytesPerSector => SectorSize;
  221. ////////////////////////////////////////////////////////////////////////////////////
  222. public PhysicalDiskDifferencingDiskImage(string diskImagePath, Disk underlyingDisk) : this(diskImagePath, false, underlyingDisk)
  223. {
  224. }
  225. public override bool ExclusiveLock(bool useOverlappedIO)
  226. {
  227. throw new System.NotImplementedException();
  228. }
  229. public override void Extend(long numberOfAdditionalBytes)
  230. {
  231. throw new System.NotImplementedException();
  232. }
  233. }
  234. }