team-ljyzipelo

공개
260줄10 KB
1using System.Runtime.InteropServices;
2using System.Text;
3using Microsoft.Win32.SafeHandles;
4using Zipelo.Core;
5
6namespace Zipelo.Runtime;
7
8internal sealed class WindowsPublication : PendingPublication
9{
10 private readonly List<SafeFileHandle> directories;
11 private readonly SafeFileHandle file;
12 private readonly string temporaryName;
13 private PublicationNativeFailure? cleanupNativeFailure;
14
15 private WindowsPublication(List<SafeFileHandle> directories, SafeFileHandle file, string temporaryName)
16 {
17 this.directories = directories;
18 this.file = file;
19 this.temporaryName = temporaryName;
20 }
21
22 internal override SafeFileHandle Handle => file;
23 internal override string TemporaryFileName => temporaryName;
24 internal override PublicationNativeFailure? CleanupNativeFailure => cleanupNativeFailure;
25
26 internal static List<SafeFileHandle> OpenParent(string parent, bool readSecurity = false)
27 {
28 var root = Path.GetPathRoot(parent);
29 if (root is null || root.Length != 3 || !char.IsAsciiLetter(root[0]) || root[1] != ':' || root[2] != '\\')
30 {
31 throw new ArchiveException(ArchiveError.UnsafePath);
32 }
33 // UNC, 장치 경로와 네트워크 드라이브는 초기 게시 구현에서 제외함.
34 if (GetDriveType(root) is not (2 or 3)) { throw new ArchiveException(ArchiveError.OutputUnavailable); }
35 var relative = parent[root.Length..];
36 var segments = relative.Length == 0 ? Array.Empty<string>() :
37 OutputPathPolicy.Validate(relative, FileNamePolicy.Windows).ToArray();
38 var directories = new List<SafeFileHandle>();
39 try
40 {
41 var rootHandle = CreateFile(root, readSecurity ? 0x001200A0u : 0x001000A0u, 3, nint.Zero, 3, 0x02200000, nint.Zero);
42 if (rootHandle.IsInvalid)
43 {
44 var error = unchecked((uint)Marshal.GetLastPInvokeError());
45 rootHandle.Dispose();
46 throw Error("CreateFileW", error);
47 }
48 directories.Add(rootHandle);
49 RequireDirectory(rootHandle);
50 foreach (var segment in segments)
51 {
52 var directory = OpenRelative(directories[^1], segment, create: false, readSecurity: readSecurity);
53 directories.Add(directory);
54 RequireDirectory(directory);
55 }
56 return directories;
57 }
58 catch
59 {
60 for (var index = directories.Count - 1; index >= 0; index--) { directories[index].Dispose(); }
61 throw;
62 }
63 }
64
65 internal static WindowsPublication Create(string parent)
66 {
67 var directories = OpenParent(parent);
68 try
69 {
70 var temporaryName = $".zipelo-{Guid.NewGuid():N}.tmp";
71 var file = OpenRelative(directories[^1], temporaryName, create: true);
72 return new(directories, file, temporaryName);
73 }
74 catch
75 {
76 for (var index = directories.Count - 1; index >= 0; index--) { directories[index].Dispose(); }
77 throw;
78 }
79 }
80
81 internal override void Publish(string leaf) => Rename(file, directories[^1], leaf);
82
83 internal static void Rename(SafeFileHandle file, SafeFileHandle parent, string leaf)
84 {
85 var name = Encoding.Unicode.GetBytes(leaf);
86 // FILE_RENAME_INFORMATION의 x64 배치와 후행 패딩을 포함함. 덮어쓰기 플래그는 0임.
87 const int fileNameOffset = 20;
88 var size = checked(Marshal.SizeOf<RenameInformation>() + name.Length);
89 var buffer = Marshal.AllocHGlobal(size);
90 try
91 {
92 Marshal.Copy(new byte[size], 0, buffer, size);
93 Marshal.WriteIntPtr(buffer, 8, parent.DangerousGetHandle());
94 Marshal.WriteInt32(buffer, 16, name.Length);
95 Marshal.Copy(name, 0, buffer + fileNameOffset, name.Length);
96 // Win32 경로 변환을 거치지 않고 보유 부모 핸들에 상대적으로 게시함.
97 var status = NtSetInformationFile(file, out _, buffer, (uint)size, 10);
98 if (status < 0)
99 {
100 throw Error("NtSetInformationFile.FileRenameInformation", RtlNtStatusToDosError(status), status);
101 }
102 }
103 finally { Marshal.FreeHGlobal(buffer); }
104 }
105
106 internal override bool Abort() => DeleteOwned(file, out cleanupNativeFailure);
107
108 internal static bool DeleteOwned(SafeFileHandle file, out PublicationNativeFailure? failure)
109 {
110 failure = null;
111 var buffer = Marshal.AllocHGlobal(1);
112 try
113 {
114 // 작업 소유 핸들에 삭제를 표시함. 경로를 다시 열거나 삭제하지 않음.
115 Marshal.WriteByte(buffer, 1);
116 if (SetFileInformation(file, 4, buffer, 1)) { return true; }
117 var error = unchecked((uint)Marshal.GetLastPInvokeError());
118 failure = new("SetFileInformationByHandle.FileDispositionInfo", error);
119 return false;
120 }
121 finally { Marshal.FreeHGlobal(buffer); }
122 }
123
124 public override void Dispose()
125 {
126 file.Dispose();
127 for (var index = directories.Count - 1; index >= 0; index--) { directories[index].Dispose(); }
128 }
129
130 internal static SafeFileHandle OpenRelative(SafeFileHandle parent, string name, bool create,
131 bool directory = false, bool read = false, bool reopenOwned = false, bool readSecurity = false)
132 {
133 var nameBuffer = Marshal.StringToHGlobalUni(name);
134 var unicodeBuffer = Marshal.AllocHGlobal(Marshal.SizeOf<UnicodeString>());
135 try
136 {
137 var unicode = new UnicodeString
138 {
139 Length = checked((ushort)(name.Length * 2)),
140 MaximumLength = checked((ushort)((name.Length + 1) * 2)),
141 Buffer = nameBuffer
142 };
143 Marshal.StructureToPtr(unicode, unicodeBuffer, false);
144 var attributes = new ObjectAttributes
145 {
146 Length = Marshal.SizeOf<ObjectAttributes>(),
147 RootDirectory = parent.DangerousGetHandle(),
148 ObjectName = unicodeBuffer,
149 Attributes = 0x1040
150 };
151 // 디렉터리는 삭제 공유 없이 고정하고 최종 reparse point도 따라가지 않음.
152 var access = reopenOwned ? 0x001300A1u : !create ? 0x001000A0u : directory ? 0x001300A3u : read ? 0xC0110000u : 0x40110000u;
153 if (readSecurity) { access |= 0x20000; }
154 var options = 0x00200020u | (directory ? 1u : create ? 0x40u : 0u);
155 var status = NtCreateFile(out var handle, access,
156 ref attributes, out _, nint.Zero, create && !directory ? 0x100u : 0u, (create || reopenOwned) ? 0u : 3u,
157 create ? 2u : 1u, options, nint.Zero, 0);
158 if (status < 0)
159 {
160 handle.Dispose();
161 throw Error("NtCreateFile", RtlNtStatusToDosError(status), status);
162 }
163 return handle;
164 }
165 finally
166 {
167 Marshal.FreeHGlobal(unicodeBuffer);
168 Marshal.FreeHGlobal(nameBuffer);
169 }
170 }
171
172 private static void RequireDirectory(SafeFileHandle handle)
173 {
174 if (!GetFileInformation(handle, 9, out var info, (uint)Marshal.SizeOf<AttributeTagInfo>())) { ThrowLastError("GetFileInformationByHandleEx"); }
175 if ((info.Attributes & 0x10) == 0 || (info.Attributes & 0x400) != 0)
176 {
177 throw new ArchiveException(ArchiveError.UnsafePath);
178 }
179 }
180
181 private static void ThrowLastError(string operation)
182 {
183 var error = unchecked((uint)Marshal.GetLastPInvokeError());
184 throw Error(operation, error);
185 }
186
187 private static PublicationNativeException Error(string operation, uint error, int? status = null) => new(
188 error is 80 or 183 ? ArchiveError.OutputConflict : ArchiveError.OutputUnavailable,
189 new(operation, error, status));
190
191 [StructLayout(LayoutKind.Explicit, Size = 24)]
192 private struct RenameInformation
193 {
194 [FieldOffset(0)] internal uint Flags;
195 [FieldOffset(8)] internal nint RootDirectory;
196 [FieldOffset(16)] internal uint FileNameLength;
197 [FieldOffset(20)] internal ushort FirstCharacter;
198 }
199
200 [StructLayout(LayoutKind.Sequential)]
201 private struct UnicodeString
202 {
203 internal ushort Length;
204 internal ushort MaximumLength;
205 internal nint Buffer;
206 }
207
208 [StructLayout(LayoutKind.Sequential)]
209 private struct ObjectAttributes
210 {
211 internal int Length;
212 internal nint RootDirectory;
213 internal nint ObjectName;
214 internal uint Attributes;
215 internal nint SecurityDescriptor;
216 internal nint SecurityQualityOfService;
217 }
218
219 [StructLayout(LayoutKind.Sequential)]
220 private struct IoStatusBlock
221 {
222 internal nint Status;
223 internal nuint Information;
224 }
225
226 [StructLayout(LayoutKind.Sequential)]
227 private struct AttributeTagInfo
228 {
229 internal uint Attributes;
230 internal uint ReparseTag;
231 }
232
233 [DllImport("kernel32.dll", EntryPoint = "CreateFileW", CharSet = CharSet.Unicode, SetLastError = true)]
234 private static extern SafeFileHandle CreateFile(string path, uint access, uint share, nint security,
235 uint disposition, uint flags, nint template);
236
237 [DllImport("kernel32.dll", EntryPoint = "GetDriveTypeW", CharSet = CharSet.Unicode)]
238 private static extern uint GetDriveType(string root);
239
240 [DllImport("kernel32.dll", EntryPoint = "GetFileInformationByHandleEx", SetLastError = true)]
241 [return: MarshalAs(UnmanagedType.Bool)]
242 private static extern bool GetFileInformation(SafeFileHandle file, int informationClass,
243 out AttributeTagInfo information, uint size);
244
245 [DllImport("kernel32.dll", EntryPoint = "SetFileInformationByHandle", SetLastError = true)]
246 [return: MarshalAs(UnmanagedType.Bool)]
247 private static extern bool SetFileInformation(SafeFileHandle file, int informationClass, nint information, uint size);
248
249 [DllImport("ntdll.dll")]
250 private static extern int NtCreateFile(out SafeFileHandle file, uint access, ref ObjectAttributes attributes,
251 out IoStatusBlock status, nint allocationSize, uint fileAttributes, uint share, uint disposition,
252 uint options, nint extendedAttributes, uint extendedAttributesLength);
253
254 [DllImport("ntdll.dll")]
255 private static extern int NtSetInformationFile(SafeFileHandle file, out IoStatusBlock status,
256 nint information, uint size, int informationClass);
257
258 [DllImport("ntdll.dll")]
259 private static extern uint RtlNtStatusToDosError(int status);
260}