UsnOperator.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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. public class UsnOperator : IDisposable
  12. {
  13. public delegate void GetEntriesHandler(DriveInfo drive, List<UsnEntry> data);
  14. protected USN_JOURNAL_DATA ntfsUsnJournalData;
  15. public DriveInfo Drive
  16. {
  17. get;
  18. private set;
  19. }
  20. public string DriveLetter
  21. {
  22. get
  23. {
  24. return this.Drive.Name.TrimEnd(new char[] { '\\', ':' });
  25. }
  26. }
  27. public IntPtr DriveRootHandle
  28. {
  29. get;
  30. private set;
  31. }
  32. public UsnOperator(DriveInfo drive)
  33. {
  34. if (string.Compare(drive.DriveFormat, "ntfs", true) != 0)
  35. {
  36. throw new ArgumentException("USN journal only exists in NTFS drive.");
  37. }
  38. this.Drive = drive;
  39. this.DriveRootHandle = this.GetRootHandle();
  40. this.ntfsUsnJournalData = new USN_JOURNAL_DATA();
  41. }
  42. public UsnJournalData GetUsnJournal()
  43. {
  44. UsnErrorCode usnErrorCode = this.QueryUSNJournal();
  45. UsnJournalData result = null;
  46. if (usnErrorCode == UsnErrorCode.SUCCESS)
  47. {
  48. result = new UsnJournalData(this.Drive, this.ntfsUsnJournalData);
  49. }
  50. return result;
  51. }
  52. public bool CreateUsnJournal(UInt64 maximumSize = 0x10000000, UInt64 allocationDelta = 0x100000)
  53. {
  54. uint bytesReturnedCount;
  55. var createUsnJournalData = new CREATE_USN_JOURNAL_DATA();
  56. createUsnJournalData.MaximumSize = maximumSize;
  57. createUsnJournalData.AllocationDelta = allocationDelta;
  58. int sizeCujd = Marshal.SizeOf(createUsnJournalData);
  59. IntPtr cujdBuffer = GetHeapGlobalPtr(sizeCujd);
  60. Marshal.StructureToPtr(createUsnJournalData, cujdBuffer, true);
  61. bool isSuccess = Win32Api.DeviceIoControl(
  62. this.DriveRootHandle,
  63. UsnControlCode.FSCTL_CREATE_USN_JOURNAL,
  64. cujdBuffer,
  65. sizeCujd,
  66. IntPtr.Zero,
  67. 0,
  68. out bytesReturnedCount,
  69. IntPtr.Zero);
  70. Marshal.FreeHGlobal(cujdBuffer);
  71. return isSuccess;
  72. }
  73. public List<UsnEntry> GetEntries()
  74. {
  75. var result = new List<UsnEntry>();
  76. UsnErrorCode usnErrorCode = this.QueryUSNJournal();
  77. if (usnErrorCode == UsnErrorCode.SUCCESS)
  78. {
  79. MFT_ENUM_DATA mftEnumData = new MFT_ENUM_DATA();
  80. mftEnumData.StartFileReferenceNumber = 0;
  81. mftEnumData.LowUsn = 0;
  82. mftEnumData.HighUsn = this.ntfsUsnJournalData.NextUsn;
  83. int sizeMftEnumData = Marshal.SizeOf(mftEnumData);
  84. IntPtr ptrMftEnumData = GetHeapGlobalPtr(sizeMftEnumData);
  85. Marshal.StructureToPtr(mftEnumData, ptrMftEnumData, true);
  86. int ptrDataSize = sizeof(UInt64) + 10000;
  87. IntPtr ptrData = GetHeapGlobalPtr(ptrDataSize);
  88. uint outBytesCount;
  89. while (false != Win32Api.DeviceIoControl(
  90. this.DriveRootHandle,
  91. UsnControlCode.FSCTL_ENUM_USN_DATA,
  92. ptrMftEnumData,
  93. sizeMftEnumData,
  94. ptrData,
  95. ptrDataSize,
  96. out outBytesCount,
  97. IntPtr.Zero))
  98. {
  99. // ptrData includes following struct:
  100. //typedef struct
  101. //{
  102. // USN LastFileReferenceNumber;
  103. // USN_RECORD_V2 Record[1];
  104. //} *PENUM_USN_DATA;
  105. IntPtr ptrUsnRecord = new IntPtr(ptrData.ToInt32() + sizeof(Int64));
  106. while (outBytesCount > 60)
  107. {
  108. var usnRecord = new USN_RECORD_V2(ptrUsnRecord);
  109. result.Add(new UsnEntry(usnRecord));
  110. ptrUsnRecord = new IntPtr(ptrUsnRecord.ToInt32() + usnRecord.RecordLength);
  111. outBytesCount -= usnRecord.RecordLength;
  112. }
  113. Marshal.WriteInt64(ptrMftEnumData, Marshal.ReadInt64(ptrData, 0));
  114. }
  115. Marshal.FreeHGlobal(ptrData);
  116. Marshal.FreeHGlobal(ptrMftEnumData);
  117. }
  118. return result;
  119. }
  120. public void GetEntries(long usn, GetEntriesHandler handler, int count)
  121. {
  122. List<UsnEntry> result = new List<UsnEntry>();
  123. UsnErrorCode usnErrorCode = this.QueryUSNJournal();
  124. if (usnErrorCode == UsnErrorCode.SUCCESS)
  125. {
  126. MFT_ENUM_DATA mftEnumData = new MFT_ENUM_DATA();
  127. mftEnumData.StartFileReferenceNumber = 0;
  128. mftEnumData.LowUsn = usn;
  129. mftEnumData.HighUsn = this.ntfsUsnJournalData.NextUsn;
  130. int sizeMftEnumData = Marshal.SizeOf(mftEnumData);
  131. IntPtr ptrMftEnumData = GetHeapGlobalPtr(sizeMftEnumData);
  132. Marshal.StructureToPtr(mftEnumData, ptrMftEnumData, true);
  133. int ptrDataSize = sizeof(UInt64) + 10000;
  134. IntPtr ptrData = GetHeapGlobalPtr(ptrDataSize);
  135. uint outBytesCount;
  136. while (false != Win32Api.DeviceIoControl(
  137. this.DriveRootHandle,
  138. UsnControlCode.FSCTL_ENUM_USN_DATA,
  139. ptrMftEnumData,
  140. sizeMftEnumData,
  141. ptrData,
  142. ptrDataSize,
  143. out outBytesCount,
  144. IntPtr.Zero))
  145. {
  146. IntPtr ptrUsnRecord = new IntPtr(ptrData.ToInt32() + sizeof(Int64));
  147. while (outBytesCount > 60)
  148. {
  149. var usnRecord = new USN_RECORD_V2(ptrUsnRecord);
  150. result.Add(new UsnEntry(usnRecord));
  151. ptrUsnRecord = new IntPtr(ptrUsnRecord.ToInt32() + usnRecord.RecordLength);
  152. outBytesCount -= usnRecord.RecordLength;
  153. if (result.Count >= count)
  154. {
  155. handler?.Invoke(Drive, result);
  156. result = new List<UsnEntry>();
  157. }
  158. }
  159. Marshal.WriteInt64(ptrMftEnumData, Marshal.ReadInt64(ptrData, 0));
  160. }
  161. Marshal.FreeHGlobal(ptrData);
  162. Marshal.FreeHGlobal(ptrMftEnumData);
  163. }
  164. handler?.Invoke(Drive, result);
  165. }
  166. public bool UsnIsExist(long usn)
  167. {
  168. bool rs = false;
  169. UsnErrorCode usnErrorCode = QueryUSNJournal();
  170. if (ntfsUsnJournalData.NextUsn < usn) return rs;
  171. if (usnErrorCode == UsnErrorCode.SUCCESS)
  172. {
  173. MFT_ENUM_DATA mftEnumData = new MFT_ENUM_DATA();
  174. mftEnumData.StartFileReferenceNumber = 0;
  175. mftEnumData.LowUsn = usn;
  176. mftEnumData.HighUsn = usn;
  177. int sizeMftEnumData = Marshal.SizeOf(mftEnumData);
  178. IntPtr ptrMftEnumData = GetHeapGlobalPtr(sizeMftEnumData);
  179. Marshal.StructureToPtr(mftEnumData, ptrMftEnumData, true);
  180. int ptrDataSize = sizeof(UInt64) + 10000;
  181. IntPtr ptrData = GetHeapGlobalPtr(ptrDataSize);
  182. uint outBytesCount;
  183. while (false != Win32Api.DeviceIoControl(
  184. this.DriveRootHandle,
  185. UsnControlCode.FSCTL_ENUM_USN_DATA,
  186. ptrMftEnumData,
  187. sizeMftEnumData,
  188. ptrData,
  189. ptrDataSize,
  190. out outBytesCount,
  191. IntPtr.Zero))
  192. {
  193. IntPtr ptrUsnRecord = new IntPtr(ptrData.ToInt32() + sizeof(Int64));
  194. while (outBytesCount > 60)
  195. {
  196. var usnRecord = new USN_RECORD_V2(ptrUsnRecord);
  197. ptrUsnRecord = new IntPtr(ptrUsnRecord.ToInt32() + usnRecord.RecordLength);
  198. outBytesCount -= usnRecord.RecordLength;
  199. rs = true;
  200. }
  201. Marshal.WriteInt64(ptrMftEnumData, Marshal.ReadInt64(ptrData, 0));
  202. }
  203. Marshal.FreeHGlobal(ptrData);
  204. Marshal.FreeHGlobal(ptrMftEnumData);
  205. }
  206. return rs;
  207. }
  208. private static IntPtr GetHeapGlobalPtr(int size)
  209. {
  210. IntPtr buffer = Marshal.AllocHGlobal(size);
  211. Win32Api.ZeroMemory(buffer, size);
  212. return buffer;
  213. }
  214. private UsnErrorCode QueryUSNJournal()
  215. {
  216. int sizeUsnJournalData = Marshal.SizeOf(this.ntfsUsnJournalData);
  217. USN_JOURNAL_DATA tempUsnJournalData;
  218. uint bytesReturnedCount;
  219. bool isSuccess = Win32Api.DeviceIoControl(
  220. this.DriveRootHandle,
  221. UsnControlCode.FSCTL_QUERY_USN_JOURNAL,
  222. IntPtr.Zero,
  223. 0,
  224. out tempUsnJournalData,
  225. sizeUsnJournalData,
  226. out bytesReturnedCount,
  227. IntPtr.Zero);
  228. this.ntfsUsnJournalData = tempUsnJournalData;
  229. //if (isSuccess)
  230. //{
  231. // return tempUsnJournalData;
  232. //}
  233. //else
  234. //{
  235. //int win32ErrorCode = Marshal.GetLastWin32Error();
  236. //if (Enum.IsDefined(typeof(UsnErrorCode), win32ErrorCode))
  237. //{
  238. // var usnErrorCode = (UsnErrorCode)win32ErrorCode;
  239. //}
  240. // throw new IOException("Drive returned false for Query Usn Journal", new Win32Exception(win32ErrorCode));
  241. //}
  242. return (UsnErrorCode)Marshal.GetLastWin32Error();
  243. }
  244. private IntPtr GetRootHandle()
  245. {
  246. string volume = string.Format("\\\\.\\{0}:", this.DriveLetter);
  247. var result = Win32Api.CreateFile(
  248. volume,
  249. Win32ApiConstant.GENERIC_READ,
  250. Win32ApiConstant.FILE_SHARE_READ | Win32ApiConstant.FILE_SHARE_WRITE,
  251. IntPtr.Zero,
  252. Win32ApiConstant.OPEN_EXISTING,
  253. 0,
  254. IntPtr.Zero);
  255. if (result.ToInt32() == Win32ApiConstant.INVALID_HANDLE_VALUE)
  256. {
  257. throw new IOException("Drive returned invalid root handle", new Win32Exception(Marshal.GetLastWin32Error()));
  258. }
  259. return result;
  260. }
  261. public void Dispose()
  262. {
  263. if (this.DriveRootHandle != null && this.DriveRootHandle.ToInt32() != Win32ApiConstant.INVALID_HANDLE_VALUE)
  264. {
  265. Win32Api.CloseHandle(this.DriveRootHandle);
  266. }
  267. }
  268. }
  269. }