NTFSVolume.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. /* Copyright (C) 2014-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.Text;
  11. using DiskAccessLibrary;
  12. using Utilities;
  13. namespace DiskAccessLibrary.FileSystems.NTFS
  14. {
  15. /// <summary>
  16. /// Implements the low level NTFS volume logic.
  17. /// This class can be used by higher level implementation that may include
  18. /// functions such as file copy, caching, symbolic links and etc.
  19. /// </summary>
  20. public partial class NTFSVolume : IExtendableFileSystem
  21. {
  22. private Volume m_volume;
  23. private MasterFileTable m_mft;
  24. private ClusterUsageBitmap m_bitmap;
  25. private NTFSBootRecord m_bootRecord; // partition's boot record
  26. public NTFSVolume(Volume volume) : this(volume, false)
  27. {
  28. }
  29. public NTFSVolume(Volume volume, bool useMftMirror)
  30. {
  31. m_volume = volume;
  32. byte[] bootSector = m_volume.ReadSector(0);
  33. m_bootRecord = NTFSBootRecord.ReadRecord(bootSector);
  34. if (m_bootRecord != null)
  35. {
  36. m_mft = new MasterFileTable(this, useMftMirror);
  37. m_bitmap = new ClusterUsageBitmap(this);
  38. }
  39. }
  40. public FileRecord GetFileRecord(string path)
  41. {
  42. if (path != String.Empty && !path.StartsWith(@"\"))
  43. {
  44. throw new ArgumentException("Invalid path");
  45. }
  46. if (path.EndsWith(@"\"))
  47. {
  48. path = path.Substring(0, path.Length - 1);
  49. }
  50. if (path == String.Empty)
  51. {
  52. return m_mft.GetFileRecord(MasterFileTable.RootDirSegmentNumber);
  53. }
  54. string[] components = path.Substring(1).Split('\\');
  55. long directorySegmentNumber = MasterFileTable.RootDirSegmentNumber;
  56. for (int index = 0; index < components.Length; index++)
  57. {
  58. KeyValuePairList<MftSegmentReference, FileNameRecord> records = GetFileNameRecordsInDirectory(directorySegmentNumber);
  59. if (index < components.Length - 1)
  60. {
  61. FileRecord record = FindDirectoryRecord(records, components[index]);
  62. if (record != null)
  63. {
  64. directorySegmentNumber = record.MftSegmentNumber;
  65. }
  66. else
  67. {
  68. return null;
  69. }
  70. }
  71. else // last component
  72. {
  73. return FindRecord(records, components[index]);
  74. }
  75. }
  76. return null;
  77. }
  78. private FileRecord FindDirectoryRecord(KeyValuePairList<MftSegmentReference, FileNameRecord> records, string directoryName)
  79. {
  80. FileRecord directoryRecord = FindRecord(records, directoryName);
  81. if (directoryRecord.IsDirectory)
  82. {
  83. return directoryRecord;
  84. }
  85. return null;
  86. }
  87. private FileRecord FindRecord(KeyValuePairList<MftSegmentReference, FileNameRecord> records, string name)
  88. {
  89. KeyValuePair<MftSegmentReference, FileNameRecord>? nameRecord = FindFileNameRecord(records, name);
  90. if (nameRecord != null)
  91. {
  92. FileRecord record = m_mft.GetFileRecord(nameRecord.Value.Key);
  93. if (record.IsInUse && !record.IsMetaFile)
  94. {
  95. return record;
  96. }
  97. }
  98. return null;
  99. }
  100. private KeyValuePairList<MftSegmentReference, FileNameRecord> GetFileNameRecordsInDirectory(long directoryBaseSegmentNumber)
  101. {
  102. FileRecord record = m_mft.GetFileRecord(directoryBaseSegmentNumber);
  103. KeyValuePairList<MftSegmentReference, FileNameRecord> result = null;
  104. if (record != null && record.IsDirectory)
  105. {
  106. IndexRootRecord indexRoot = (IndexRootRecord)record.GetAttributeRecord(AttributeType.IndexRoot, IndexRootRecord.FileNameIndexName);
  107. IndexAllocationRecord indexAllocation = (IndexAllocationRecord)record.GetAttributeRecord(AttributeType.IndexAllocation, IndexRootRecord.FileNameIndexName);
  108. if (indexRoot.IsLargeIndex)
  109. {
  110. if (indexAllocation != null)
  111. {
  112. result = indexAllocation.GetAllEntries(this, indexRoot);
  113. }
  114. }
  115. else
  116. {
  117. result = indexRoot.GetSmallIndexEntries();
  118. }
  119. if (result != null)
  120. {
  121. for (int index = 0; index < result.Count; index++)
  122. {
  123. if (result[index].Value.Namespace == FilenameNamespace.DOS)
  124. {
  125. // The same FileRecord can have multiple entries, each with it's own namespace
  126. result.RemoveAt(index);
  127. index--;
  128. }
  129. }
  130. }
  131. }
  132. return result;
  133. }
  134. public List<FileRecord> GetFileRecordsInDirectory(long directoryBaseSegmentNumber)
  135. {
  136. return GetFileRecordsInDirectory(directoryBaseSegmentNumber, false);
  137. }
  138. private List<FileRecord> GetFileRecordsInDirectory(long directoryBaseSegmentNumber, bool includeMetaFiles)
  139. {
  140. KeyValuePairList<MftSegmentReference, FileNameRecord> entries = GetFileNameRecordsInDirectory(directoryBaseSegmentNumber);
  141. List<FileRecord> result = new List<FileRecord>();
  142. if (entries != null)
  143. {
  144. List<MftSegmentReference> files = entries.Keys;
  145. foreach (MftSegmentReference reference in files)
  146. {
  147. FileRecord record = m_mft.GetFileRecord(reference);
  148. if (record != null)
  149. {
  150. if (record.IsInUse && (includeMetaFiles || !record.IsMetaFile))
  151. {
  152. result.Add(record);
  153. }
  154. }
  155. }
  156. }
  157. return result;
  158. }
  159. // logical cluster
  160. public byte[] ReadCluster(long clusterLCN)
  161. {
  162. return ReadClusters(clusterLCN, 1);
  163. }
  164. public byte[] ReadClusters(long clusterLCN, int count)
  165. {
  166. long firstSectorIndex = clusterLCN * m_bootRecord.SectorsPerCluster;
  167. int sectorsToRead = m_bootRecord.SectorsPerCluster * count;
  168. byte[] result = m_volume.ReadSectors(firstSectorIndex, sectorsToRead);
  169. return result;
  170. }
  171. public void WriteClusters(long clusterLCN, byte[] data)
  172. {
  173. long firstSectorIndex = clusterLCN * m_bootRecord.SectorsPerCluster;
  174. m_volume.WriteSectors(firstSectorIndex, data);
  175. }
  176. public byte[] ReadSectors(long sectorIndex, int sectorCount)
  177. {
  178. return m_volume.ReadSectors(sectorIndex, sectorCount);
  179. }
  180. public void WriteSectors(long sectorIndex, byte[] data)
  181. {
  182. m_volume.WriteSectors(sectorIndex, data);
  183. }
  184. public VolumeInformationRecord GetVolumeInformationRecord()
  185. {
  186. FileRecord volumeRecord = m_mft.GetVolumeRecord();
  187. if (volumeRecord != null)
  188. {
  189. VolumeInformationRecord volumeInformationRecord = (VolumeInformationRecord)volumeRecord.GetAttributeRecord(AttributeType.VolumeInformation, String.Empty);
  190. return volumeInformationRecord;
  191. }
  192. else
  193. {
  194. throw new InvalidDataException("Invalid NTFS volume record");
  195. }
  196. }
  197. public override string ToString()
  198. {
  199. StringBuilder builder = new StringBuilder();
  200. if (m_bootRecord != null)
  201. {
  202. builder.AppendLine("Bytes Per Sector: " + m_bootRecord.BytesPerSector);
  203. builder.AppendLine("Bytes Per Cluster: " + m_bootRecord.BytesPerCluster);
  204. builder.AppendLine("File Record Length: " + m_bootRecord.FileRecordSegmentLength);
  205. builder.AppendLine("First MFT Cluster (LCN): " + m_bootRecord.MftStartLCN);
  206. builder.AppendLine("First MFT Mirror Cluster (LCN): " + m_bootRecord.MftMirrorStartLCN);
  207. builder.AppendLine("Volume size (bytes): " + this.Size);
  208. builder.AppendLine();
  209. VolumeInformationRecord volumeInformationRecord = GetVolumeInformationRecord();
  210. if (volumeInformationRecord != null)
  211. {
  212. builder.AppendFormat("NTFS Version: {0}.{1}\n", volumeInformationRecord.MajorVersion, volumeInformationRecord.MinorVersion);
  213. builder.AppendLine();
  214. }
  215. FileRecord mftRecord = m_mft.GetMftRecord();
  216. if (mftRecord != null)
  217. {
  218. builder.AppendLine("Number of $MFT Data Runs: " + mftRecord.NonResidentDataRecord.DataRunSequence.Count);
  219. builder.AppendLine("Number of $MFT Clusters: " + mftRecord.NonResidentDataRecord.DataRunSequence.DataClusterCount);
  220. builder.Append(mftRecord.NonResidentDataRecord.DataRunSequence.ToString());
  221. builder.AppendLine("Number of $MFT Attributes: " + mftRecord.Attributes.Count);
  222. builder.AppendLine("Length of $MFT Attributes: " + mftRecord.StoredAttributesLength);
  223. builder.AppendLine();
  224. FileRecord bitmapRecord = m_mft.GetBitmapRecord();
  225. if (bitmapRecord != null)
  226. {
  227. builder.AppendLine("$Bitmap LCN: " + bitmapRecord.NonResidentDataRecord.DataRunSequence.FirstDataRunLCN);
  228. builder.AppendLine("$Bitmap Clusters: " + bitmapRecord.NonResidentDataRecord.DataRunSequence.DataClusterCount);
  229. builder.AppendLine("Number of $Bitmap Attributes: " + bitmapRecord.Attributes.Count);
  230. builder.AppendLine("Length of $Bitmap Attributes: " + bitmapRecord.StoredAttributesLength);
  231. }
  232. }
  233. byte[] bootRecord = ReadSectors(0, 1);
  234. long backupBootSectorIndex = (long)m_bootRecord.TotalSectors;
  235. byte[] backupBootRecord = ReadSectors(backupBootSectorIndex, 1);
  236. builder.AppendLine();
  237. builder.AppendLine("Valid backup boot sector: " + ByteUtils.AreByteArraysEqual(bootRecord, backupBootRecord));
  238. builder.AppendLine("Free space: " + this.FreeSpace);
  239. }
  240. return builder.ToString();
  241. }
  242. public bool IsValid
  243. {
  244. get
  245. {
  246. return (m_bootRecord != null && m_mft.GetMftRecord() != null);
  247. }
  248. }
  249. public bool IsValidAndSupported
  250. {
  251. get
  252. {
  253. return (this.IsValid && MajorVersion == 3 && MinorVersion == 1);
  254. }
  255. }
  256. public long Size
  257. {
  258. get
  259. {
  260. return (long)(m_bootRecord.TotalSectors * m_bootRecord.BytesPerSector);
  261. }
  262. }
  263. public long FreeSpace
  264. {
  265. get
  266. {
  267. return m_bitmap.CountNumberOfFreeClusters() * this.BytesPerCluster;
  268. }
  269. }
  270. public NTFSBootRecord BootRecord
  271. {
  272. get
  273. {
  274. return m_bootRecord;
  275. }
  276. }
  277. public MasterFileTable MasterFileTable
  278. {
  279. get
  280. {
  281. return m_mft;
  282. }
  283. }
  284. public int BytesPerCluster
  285. {
  286. get
  287. {
  288. return m_bootRecord.BytesPerCluster;
  289. }
  290. }
  291. public int BytesPerSector
  292. {
  293. get
  294. {
  295. return m_bootRecord.BytesPerSector;
  296. }
  297. }
  298. public int SectorsPerCluster
  299. {
  300. get
  301. {
  302. return m_bootRecord.SectorsPerCluster;
  303. }
  304. }
  305. public int SectorsPerFileRecordSegment
  306. {
  307. get
  308. {
  309. return m_bootRecord.SectorsPerFileRecordSegment;
  310. }
  311. }
  312. public ushort MajorVersion
  313. {
  314. get
  315. {
  316. VolumeInformationRecord volumeInformationRecord = GetVolumeInformationRecord();
  317. return volumeInformationRecord.MajorVersion;
  318. }
  319. }
  320. public ushort MinorVersion
  321. {
  322. get
  323. {
  324. VolumeInformationRecord volumeInformationRecord = GetVolumeInformationRecord();
  325. return volumeInformationRecord.MinorVersion;
  326. }
  327. }
  328. public KeyValuePairList<ulong, long> AllocateClusters(ulong desiredStartLCN, long numberOfClusters)
  329. {
  330. return m_bitmap.AllocateClusters(desiredStartLCN, numberOfClusters);
  331. }
  332. private static KeyValuePair<MftSegmentReference, FileNameRecord>? FindFileNameRecord(KeyValuePairList<MftSegmentReference, FileNameRecord> records, string name)
  333. {
  334. foreach (KeyValuePair<MftSegmentReference, FileNameRecord> record in records)
  335. {
  336. if (String.Equals(record.Value.FileName, name, StringComparison.InvariantCultureIgnoreCase))
  337. {
  338. return record;
  339. }
  340. }
  341. return null;
  342. }
  343. }
  344. }