这个问题对于我正在从事的项目非常重要,所以我最终(几乎)100% 成功了。
注意:以下所有代码片段均采用 C# 编写
感谢 Hannes de Jager 之前的回答,他为我指明了正确的方向和文档,我现在可以从 VSS 快照或常规 API 无法使用的任何其他特殊设备读取 USN 日志;就我而言,我的意思是使用 VDDK(VMware SDK for VM disk)安装的 VMware 快照。
我还重用或导入了来自伟大项目的代码:
C# 中的 USN 期刊浏览器,来自 StCroixSkipper (http://www.dreamincode.net/forums/blog/1017-stcroixskippers-blog/)。仅使用官方 API 读取 USN(因此此处没有 VSS),但提供有用的 pinvoke 和 Win32 API 结构以及有关 USN 如何工作的一般信息
阿尔法FS(https://github.com/alphaleonis/AlphaFS/),它模仿了大部分System.IO
命名空间,但允许访问特殊的 Windows 路径(VSS 快照、原始设备)并提供有用的扩展。
如果其他人感兴趣,我分享我现在使用的代码,仍然处于相当粗糙的状态,但可以工作。
它是如何工作的?
首先,您必须评估所需的 Usn 日记帐组件。它们作为 ADS(备用数据流)位于设备根部的隐藏条目中。无法使用标准访问它们System.IO
命名空间,这就是我之前告诉我使用 AlphaFS 项目的原因,但是 pinvokingCreateFile()
and ReadFile()
应该足够了。
1/2
入口\$Extend\$UsnJrnl:$Max
拥有有关期刊当前状态的全球信息。最重要的部分是 usn 日志 ID(如果您想要比较多个 VSS 快照,可以使用它来检查日志是否未被重置)和最低的有效 USN 日志序列号。
USN期刊结构:
// can be directly extracted from $MAX entry using Bitconverter.ToUint64
public struct USN_JOURNAL_DATA{
public UInt64 MaximumSize; //offset 0
public UInt64 AllocationDelta; // offset 8
public UInt64 UsnJournalID; // offset 16
public Int64 LowestValidUsn; // offset 24
}
2/2
入口\$Extend\$UsnJrnl:$J
包含日志记录。它是一个稀疏文件,因此其磁盘使用量远低于其大小。
为了回答第一个问题,如何从先前的 VSS 快照中知道 Max 使用的 USN 序列并将其与另一个快照的序列进行比较?
那么,NextUsn 值就等于$Usnjrnl:$J
entry.
在“新”vss 快照 USN 日志上,如果您想解析两个快照之间更改的记录,则可以在开始解析记录之前查找“参考”VSS 快照最大 USN。
一般来说,每个USN日志条目都是一个唯一的ID(USN号),它是内部的偏移量$J
日记条目本身所在的位置。
每个条目的大小都是可变的,因此要顺序读取,我们必须计算:
next entry offset inside $J =
offset of current entry (or its USN sequennce number + length of current entry
幸运的是,记录长度也是 USN 条目记录的一个字段。说得够多了,这是美国海军的记录等级:
public class UsnEntry : IComparable<UsnEntry>{
private const int FR_OFFSET = 8;
private const int PFR_OFFSET = 16;
private const int USN_OFFSET = 24;
private const int REASON_OFFSET = 40;
private const int FA_OFFSET = 52;
private const int FNL_OFFSET = 56;
private const int FN_OFFSET = 58;
public UInt32 RecordLength {get; private set;}
public Int64 USN {get; private set;}
public UInt64 FileReferenceNumber {get;private set;}
public UInt64 ParentFileReferenceNumber {get; private set;}
public UInt32 Reason{get; set;}
public string Name {get; private set;}
public string OldName{get; private set;}
private UInt32 _fileAttributes;
public bool IsFolder{
get{
bool bRtn = false;
if (0 != (_fileAttributes & Win32Api.FILE_ATTRIBUTE_DIRECTORY))
bRtn = true;
return bRtn;
}
}
public bool IsFile{
get{
bool bRtn = false;
if (0 == (_fileAttributes & Win32Api.FILE_ATTRIBUTE_DIRECTORY))
bRtn = true;
return bRtn;
}
}
/// <summary>
/// USN Record Constructor
/// </summary>
/// <param name="p">Buffer pointer to first byte of the USN Record</param>
public UsnEntry(IntPtr ptrToUsnRecord){
RecordLength = (UInt32)Marshal.ReadInt32(ptrToUsnRecord); //record size
FileReferenceNumber = (UInt64)Marshal.ReadInt64(ptrToUsnRecord, FR_OFFSET);
ParentFileReferenceNumber = (UInt64)Marshal.ReadInt64(ptrToUsnRecord, PFR_OFFSET);
USN = (Int64)Marshal.ReadInt64(ptrToUsnRecord, USN_OFFSET);
Reason = (UInt32)Marshal.ReadInt32(ptrToUsnRecord, REASON_OFFSET);
_fileAttributes = (UInt32)Marshal.ReadInt32(ptrToUsnRecord, FA_OFFSET);
short fileNameLength = Marshal.ReadInt16(ptrToUsnRecord, FNL_OFFSET);
short fileNameOffset = Marshal.ReadInt16(ptrToUsnRecord, FN_OFFSET);
Name = Marshal.PtrToStringUni(new IntPtr(ptrToUsnRecord.ToInt32() + fileNameOffset), fileNameLength / sizeof(char));
}
public int CompareTo(UsnEntry other){
return string.Compare(this.Name, other.Name, true);
}
public override string ToString(){
return string.Format ("[UsnEntry: RecordLength={0}, USN={1}, FileReferenceNumber={2}, ParentFileReferenceNumber={3}, Reason={4}, Name={5}, OldName={6}, IsFolder={7}, IsFile={8}", RecordLength, USN, (int)FileReferenceNumber, (int)ParentFileReferenceNumber, Reason, Name, OldName, IsFolder, IsFile);
}
}
我尝试隔离可以解析 USN 日志并提取其条目的最小代码部分,从最低的有效条目开始。请记住,记录的长度是可变的;另请注意,某些记录指向下一个空记录(前 4 个字节,通常是记录长度,被清零)。在本例中,我查找 4 个字节并重试解析,直到获得下一条记录。用 Python 编写类似解析工具的人也报告了这种行为,所以我想我在这里并没有太大错。
string vol = @"\\?\path_to_your_VSS_snapshot";
string maxHandle = vol + @"\$Extend\$UsnJrnl:$Max";
string rawJournal= vol + @"\$Extend\$UsnJrnl:$J";
// cannot use regular System.IO here, but pinvoking ReadFile() should be enough
FileStream maxStream = Alphaleonis.Win32.Filesystem.File.OpenRead(maxHandle);
byte[] maxData = new byte[32];
maxStream.Read(maxData, 0, 32);
//first valid entry
long lowestUsn = BitConverter.ToInt64(maxData, 24);
// max (last) entry, is the size of the $J ADS
IntPtr journalDataHandle = Win32Api.CreateFile(rawJournal,
0,
Win32Api.FILE_SHARE_READ| Win32Api.FILE_SHARE_WRITE,
IntPtr.Zero, Win32Api.OPEN_EXISTING,
0, IntPtr.Zero);
Win32Api.BY_HANDLE_FILE_INFORMATION fileInfo = new Win32Api.BY_HANDLE_FILE_INFORMATION();
Win32Api.GetFileInformationByHandle(journalDataHandle, out fileInfo);
Win32Api.CloseHandle(journalDataHandle);
long lastUsn = fileInfo.FileSizeLow;
int read = 0;
byte[] usnrecord;
byte[] usnraw = new byte[4]; // first byte array is to store the record length
// same here : pinvoke ReadFile() to avoid AlphaFS dependancy
FileStream rawJStream = Alphaleonis.Win32.Filesystem.File.OpenRead(rawJournal);
int recordSize = 0;
long pos = lowestUsn;
while(pos < newUsnState.NextUsn){
seeked = rawJStream.Seek(pos, SeekOrigin.Begin);
read = rawJStream.Read(usnraw, 0, usnraw.Length);
recordSize = BitConverter.ToInt32(usnraw, 0);
if(recordSize == 0){
pos = pos+4;
continue;
}
usnrecord = new byte[recordSize];
rawJStream.Read(usnrecord, 4, recordSize-4);
Array.Copy(usnraw, 0, usnrecord, 0, 4);
fixed (byte* p = usnrecord){
IntPtr ptr = (IntPtr)p;
// here we use the previously defined UsnEntry class
Win32Api.UsnEntry entry = new Win32Api.UsnEntry(ptr);
Console.WriteLine ("entry: "+entry.ToString());
ptr = IntPtr.Zero;
}
pos += recordSize;
}
以下是我使用的 pinvoke:
public class Win32Api{
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct BY_HANDLE_FILE_INFORMATION{
public uint FileAttributes;
public FILETIME CreationTime;
public FILETIME LastAccessTime;
public FILETIME LastWriteTime;
public uint VolumeSerialNumber;
public uint FileSizeHigh;
public uint FileSizeLow;
public uint NumberOfLinks;
/*public uint FileIndexHigh;
public uint FileIndexLow;*/
public FileID FileIndex;
}
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool
GetFileInformationByHandle(
IntPtr hFile,
out BY_HANDLE_FILE_INFORMATION lpFileInformation);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr
CreateFile(string lpFileName,
uint dwDesiredAccess,
uint dwShareMode,
IntPtr lpSecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
IntPtr hTemplateFile);
}
这绝对不是地球上最好的代码,但我认为它将为任何必须做同样事情的人提供一个很好的起点。