UsnOperator.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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, ulong fileNumber, 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 = fileNumber;
  128. mftEnumData.LowUsn = 0;
  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. long purvalue = ptrData.ToInt64() + sizeof(long);
  147. IntPtr ptrUsnRecord = new IntPtr(purvalue);
  148. while (outBytesCount > 60)
  149. {
  150. var usnRecord = new USN_RECORD_V2(ptrUsnRecord);
  151. UsnEntry rec = new UsnEntry(usnRecord);
  152. if (rec.FileReferenceNumber > fileNumber || rec.Usn > usn)
  153. {
  154. result.Add(rec);
  155. }
  156. ptrUsnRecord = new IntPtr(ptrUsnRecord.ToInt64() + usnRecord.RecordLength);
  157. outBytesCount -= usnRecord.RecordLength;
  158. if (result.Count >= count)
  159. {
  160. handler?.Invoke(Drive, result);
  161. result = new List<UsnEntry>();
  162. }
  163. }
  164. Marshal.WriteInt64(ptrMftEnumData, Marshal.ReadInt64(ptrData, 0));
  165. }
  166. Marshal.FreeHGlobal(ptrData);
  167. Marshal.FreeHGlobal(ptrMftEnumData);
  168. }
  169. handler?.Invoke(Drive, result);
  170. }
  171. public bool UsnIsExist(long usn)
  172. {
  173. bool rs = false;
  174. UsnErrorCode usnErrorCode = QueryUSNJournal();
  175. if (ntfsUsnJournalData.NextUsn < usn) return rs;
  176. if (usnErrorCode == UsnErrorCode.SUCCESS)
  177. {
  178. MFT_ENUM_DATA mftEnumData = new MFT_ENUM_DATA();
  179. mftEnumData.StartFileReferenceNumber = 0;
  180. mftEnumData.LowUsn = usn;
  181. mftEnumData.HighUsn = usn;
  182. int sizeMftEnumData = Marshal.SizeOf(mftEnumData);
  183. IntPtr ptrMftEnumData = GetHeapGlobalPtr(sizeMftEnumData);
  184. Marshal.StructureToPtr(mftEnumData, ptrMftEnumData, true);
  185. int ptrDataSize = sizeof(UInt64) + 10000;
  186. IntPtr ptrData = GetHeapGlobalPtr(ptrDataSize);
  187. uint outBytesCount;
  188. while (false != Win32Api.DeviceIoControl(
  189. this.DriveRootHandle,
  190. UsnControlCode.FSCTL_ENUM_USN_DATA,
  191. ptrMftEnumData,
  192. sizeMftEnumData,
  193. ptrData,
  194. ptrDataSize,
  195. out outBytesCount,
  196. IntPtr.Zero))
  197. {
  198. IntPtr ptrUsnRecord = new IntPtr(ptrData.ToInt32() + sizeof(Int64));
  199. while (outBytesCount > 60)
  200. {
  201. var usnRecord = new USN_RECORD_V2(ptrUsnRecord);
  202. ptrUsnRecord = new IntPtr(ptrUsnRecord.ToInt32() + usnRecord.RecordLength);
  203. outBytesCount -= usnRecord.RecordLength;
  204. rs = true;
  205. }
  206. Marshal.WriteInt64(ptrMftEnumData, Marshal.ReadInt64(ptrData, 0));
  207. }
  208. Marshal.FreeHGlobal(ptrData);
  209. Marshal.FreeHGlobal(ptrMftEnumData);
  210. }
  211. return rs;
  212. }
  213. private static IntPtr GetHeapGlobalPtr(int size)
  214. {
  215. IntPtr buffer = Marshal.AllocHGlobal(size);
  216. Win32Api.ZeroMemory(buffer, size);
  217. return buffer;
  218. }
  219. private UsnErrorCode QueryUSNJournal()
  220. {
  221. int sizeUsnJournalData = Marshal.SizeOf(this.ntfsUsnJournalData);
  222. USN_JOURNAL_DATA tempUsnJournalData;
  223. uint bytesReturnedCount;
  224. bool isSuccess = Win32Api.DeviceIoControl(
  225. this.DriveRootHandle,
  226. UsnControlCode.FSCTL_QUERY_USN_JOURNAL,
  227. IntPtr.Zero,
  228. 0,
  229. out tempUsnJournalData,
  230. sizeUsnJournalData,
  231. out bytesReturnedCount,
  232. IntPtr.Zero);
  233. this.ntfsUsnJournalData = tempUsnJournalData;
  234. //if (isSuccess)
  235. //{
  236. // return tempUsnJournalData;
  237. //}
  238. //else
  239. //{
  240. //int win32ErrorCode = Marshal.GetLastWin32Error();
  241. //if (Enum.IsDefined(typeof(UsnErrorCode), win32ErrorCode))
  242. //{
  243. // var usnErrorCode = (UsnErrorCode)win32ErrorCode;
  244. //}
  245. // throw new IOException("Drive returned false for Query Usn Journal", new Win32Exception(win32ErrorCode));
  246. //}
  247. return (UsnErrorCode)Marshal.GetLastWin32Error();
  248. }
  249. private IntPtr GetRootHandle()
  250. {
  251. string volume = string.Format("\\\\.\\{0}:", this.DriveLetter);
  252. var result = Win32Api.CreateFile(
  253. volume,
  254. Win32ApiConstant.GENERIC_READ,
  255. Win32ApiConstant.FILE_SHARE_READ | Win32ApiConstant.FILE_SHARE_WRITE,
  256. IntPtr.Zero,
  257. Win32ApiConstant.OPEN_EXISTING,
  258. 0,
  259. IntPtr.Zero);
  260. if (result.ToInt32() == Win32ApiConstant.INVALID_HANDLE_VALUE)
  261. {
  262. throw new IOException("Drive returned invalid root handle", new Win32Exception(Marshal.GetLastWin32Error()));
  263. }
  264. return result;
  265. }
  266. public void Dispose()
  267. {
  268. if (this.DriveRootHandle != null && this.DriveRootHandle.ToInt32() != Win32ApiConstant.INVALID_HANDLE_VALUE)
  269. {
  270. Win32Api.CloseHandle(this.DriveRootHandle);
  271. }
  272. }
  273. }
  274. }