UsnOperator.cs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.ComponentModel;
  5. using System.Runtime.InteropServices;
  6. using Y.FileQueryEngine.Win32.Structures;
  7. using Y.FileQueryEngine.Win32;
  8. using Y.FileQueryEngine.Win32.Constants;
  9. namespace Y.FileQueryEngine.UsnOperation
  10. {
  11. internal class UsnOperator : IDisposable
  12. {
  13. protected USN_JOURNAL_DATA ntfsUsnJournalData;
  14. public DriveInfo Drive
  15. {
  16. get;
  17. private set;
  18. }
  19. public string DriveLetter
  20. {
  21. get
  22. {
  23. return this.Drive.Name.TrimEnd(new char[] { '\\', ':' });
  24. }
  25. }
  26. public IntPtr DriveRootHandle
  27. {
  28. get;
  29. private set;
  30. }
  31. public UsnOperator(DriveInfo drive)
  32. {
  33. if (string.Compare(drive.DriveFormat, "ntfs", true) != 0)
  34. {
  35. throw new ArgumentException("USN journal only exists in NTFS drive.");
  36. }
  37. this.Drive = drive;
  38. this.DriveRootHandle = this.GetRootHandle();
  39. this.ntfsUsnJournalData = new USN_JOURNAL_DATA();
  40. }
  41. public UsnJournalData GetUsnJournal()
  42. {
  43. UsnErrorCode usnErrorCode = this.QueryUSNJournal();
  44. UsnJournalData result = null;
  45. if (usnErrorCode == UsnErrorCode.SUCCESS)
  46. {
  47. result = new UsnJournalData(this.Drive, this.ntfsUsnJournalData);
  48. }
  49. return result;
  50. }
  51. public bool CreateUsnJournal(UInt64 maximumSize = 0x10000000, UInt64 allocationDelta = 0x100000)
  52. {
  53. uint bytesReturnedCount;
  54. var createUsnJournalData = new CREATE_USN_JOURNAL_DATA();
  55. createUsnJournalData.MaximumSize = maximumSize;
  56. createUsnJournalData.AllocationDelta = allocationDelta;
  57. int sizeCujd = Marshal.SizeOf(createUsnJournalData);
  58. IntPtr cujdBuffer = GetHeapGlobalPtr(sizeCujd);
  59. Marshal.StructureToPtr(createUsnJournalData, cujdBuffer, true);
  60. bool isSuccess = Win32Api.DeviceIoControl(
  61. this.DriveRootHandle,
  62. UsnControlCode.FSCTL_CREATE_USN_JOURNAL,
  63. cujdBuffer,
  64. sizeCujd,
  65. IntPtr.Zero,
  66. 0,
  67. out bytesReturnedCount,
  68. IntPtr.Zero);
  69. Marshal.FreeHGlobal(cujdBuffer);
  70. return isSuccess;
  71. }
  72. public List<UsnEntry> GetEntries()
  73. {
  74. var result = new List<UsnEntry>();
  75. UsnErrorCode usnErrorCode = this.QueryUSNJournal();
  76. if (usnErrorCode == UsnErrorCode.SUCCESS)
  77. {
  78. MFT_ENUM_DATA mftEnumData = new MFT_ENUM_DATA();
  79. mftEnumData.StartFileReferenceNumber = 0;
  80. mftEnumData.LowUsn = 0;
  81. mftEnumData.HighUsn = this.ntfsUsnJournalData.NextUsn;
  82. int sizeMftEnumData = Marshal.SizeOf(mftEnumData);
  83. IntPtr ptrMftEnumData = GetHeapGlobalPtr(sizeMftEnumData);
  84. Marshal.StructureToPtr(mftEnumData, ptrMftEnumData, true);
  85. int ptrDataSize = sizeof(UInt64) + 10000;
  86. IntPtr ptrData = GetHeapGlobalPtr(ptrDataSize);
  87. uint outBytesCount;
  88. while (false != Win32Api.DeviceIoControl(
  89. this.DriveRootHandle,
  90. UsnControlCode.FSCTL_ENUM_USN_DATA,
  91. ptrMftEnumData,
  92. sizeMftEnumData,
  93. ptrData,
  94. ptrDataSize,
  95. out outBytesCount,
  96. IntPtr.Zero))
  97. {
  98. // ptrData includes following struct:
  99. //typedef struct
  100. //{
  101. // USN LastFileReferenceNumber;
  102. // USN_RECORD_V2 Record[1];
  103. //} *PENUM_USN_DATA;
  104. IntPtr ptrUsnRecord = new IntPtr(ptrData.ToInt32() + sizeof(Int64));
  105. while (outBytesCount > 60)
  106. {
  107. var usnRecord = new USN_RECORD_V2(ptrUsnRecord);
  108. result.Add(new UsnEntry(usnRecord));
  109. ptrUsnRecord = new IntPtr(ptrUsnRecord.ToInt32() + usnRecord.RecordLength);
  110. outBytesCount -= usnRecord.RecordLength;
  111. }
  112. Marshal.WriteInt64(ptrMftEnumData, Marshal.ReadInt64(ptrData, 0));
  113. }
  114. Marshal.FreeHGlobal(ptrData);
  115. Marshal.FreeHGlobal(ptrMftEnumData);
  116. }
  117. return result;
  118. }
  119. private static IntPtr GetHeapGlobalPtr(int size)
  120. {
  121. IntPtr buffer = Marshal.AllocHGlobal(size);
  122. Win32Api.ZeroMemory(buffer, size);
  123. return buffer;
  124. }
  125. private UsnErrorCode QueryUSNJournal()
  126. {
  127. int sizeUsnJournalData = Marshal.SizeOf(this.ntfsUsnJournalData);
  128. USN_JOURNAL_DATA tempUsnJournalData;
  129. uint bytesReturnedCount;
  130. bool isSuccess = Win32Api.DeviceIoControl(
  131. this.DriveRootHandle,
  132. UsnControlCode.FSCTL_QUERY_USN_JOURNAL,
  133. IntPtr.Zero,
  134. 0,
  135. out tempUsnJournalData,
  136. sizeUsnJournalData,
  137. out bytesReturnedCount,
  138. IntPtr.Zero);
  139. this.ntfsUsnJournalData = tempUsnJournalData;
  140. //if (isSuccess)
  141. //{
  142. // return tempUsnJournalData;
  143. //}
  144. //else
  145. //{
  146. //int win32ErrorCode = Marshal.GetLastWin32Error();
  147. //if (Enum.IsDefined(typeof(UsnErrorCode), win32ErrorCode))
  148. //{
  149. // var usnErrorCode = (UsnErrorCode)win32ErrorCode;
  150. //}
  151. // throw new IOException("Drive returned false for Query Usn Journal", new Win32Exception(win32ErrorCode));
  152. //}
  153. return (UsnErrorCode)Marshal.GetLastWin32Error();
  154. }
  155. private IntPtr GetRootHandle()
  156. {
  157. string volume = string.Format("\\\\.\\{0}:", this.DriveLetter);
  158. var result = Win32Api.CreateFile(
  159. volume,
  160. Win32ApiConstant.GENERIC_READ,
  161. Win32ApiConstant.FILE_SHARE_READ | Win32ApiConstant.FILE_SHARE_WRITE,
  162. IntPtr.Zero,
  163. Win32ApiConstant.OPEN_EXISTING,
  164. 0,
  165. IntPtr.Zero);
  166. if (result.ToInt32() == Win32ApiConstant.INVALID_HANDLE_VALUE)
  167. {
  168. throw new IOException("Drive returned invalid root handle", new Win32Exception(Marshal.GetLastWin32Error()));
  169. }
  170. return result;
  171. }
  172. public void Dispose()
  173. {
  174. if (this.DriveRootHandle != null && this.DriveRootHandle.ToInt32() != Win32ApiConstant.INVALID_HANDLE_VALUE)
  175. {
  176. Win32Api.CloseHandle(this.DriveRootHandle);
  177. }
  178. }
  179. }
  180. }