team-ljyzipelo

공개
301줄13 KB
1using System.Globalization;
2using System.Runtime.InteropServices;
3using System.Text;
4using Microsoft.Win32.SafeHandles;
5using Zipelo.Core;
6
7namespace Zipelo.Runtime;
8
9internal sealed class LinuxFolderPublication : PendingFolderPublication
10{
11 private readonly SafeFileHandle parent;
12 private readonly string parentPath;
13 private ulong parentMountId;
14 private readonly uint user = GetEffectiveUser();
15 private string parentIdentity = "";
16 private bool unboundCreation;
17 internal int? NativeError { get; private set; }
18 internal int? CleanupError { get; private set; }
19
20 internal LinuxFolderPublication(string path)
21 {
22 parentPath = path;
23 parent = Open(-100, path, 0x90000, 0, 0x04);
24 }
25
26 internal override void Initialize()
27 {
28 RequireFileSystem();
29 parentIdentity = Inspect(parent, true);
30 AddRoot(Create(parent, TemporaryName, true));
31 }
32
33 private void RequireFileSystem()
34 {
35 var magic = FileSystemMagic(parent);
36 var expectedType = magic switch
37 {
38 0xEF53 => "ext4",
39 0x58465342 => "xfs",
40 _ => throw new ArchiveException(ArchiveError.OutputUnavailable)
41 };
42 var before = MountStatus(parent);
43 var mountId = BitConverter.ToUInt64(before, 144);
44 var device = FormattableString.Invariant($"{BitConverter.ToUInt32(before, 136)}:{BitConverter.ToUInt32(before, 140)}");
45
46 // procfs 핸들을 고정하고 하위 bind mount와 링크를 통한 정보 대체를 거부함.
47 using var proc = Open(-100, "/proc", 0x90000, 0, 0x04);
48 if (FileSystemMagic(proc) != 0x9FA0) { throw new ArchiveException(ArchiveError.OutputUnavailable); }
49 var name = FormattableString.Invariant($"{GetProcessId()}/task/{GetThreadId()}/mountinfo");
50 using var info = Open(proc.DangerousGetHandle().ToInt32(), name, 0x80000, 0, 0x0F);
51 if (FileSystemMagic(info) != 0x9FA0) { throw new ArchiveException(ArchiveError.OutputUnavailable); }
52 using var stream = new FileStream(info, FileAccess.Read);
53 using var bytes = new MemoryStream();
54 var buffer = new byte[8192];
55 int count;
56 while ((count = stream.Read(buffer, 0, buffer.Length)) != 0)
57 {
58 if (bytes.Length + count > 4 * 1024 * 1024) { throw new ArchiveException(ArchiveError.OutputUnavailable); }
59 bytes.Write(buffer, 0, count);
60 }
61 var content = new UTF8Encoding(false, true).GetString(bytes.ToArray());
62 var matches = 0;
63 foreach (var line in content.Split('\n', StringSplitOptions.RemoveEmptyEntries))
64 {
65 var fields = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
66 if (!ulong.TryParse(fields[0], NumberStyles.None, CultureInfo.InvariantCulture, out var id))
67 {
68 throw new ArchiveException(ArchiveError.OutputUnavailable);
69 }
70 if (id != mountId) { continue; }
71 var separator = Array.IndexOf(fields, "-");
72 if (++matches != 1 || separator < 6 || fields.Length != separator + 4 ||
73 fields[2] != device || fields[separator + 1] != expectedType)
74 {
75 throw new ArchiveException(ArchiveError.OutputUnavailable);
76 }
77 }
78 var after = MountStatus(parent);
79 if (matches != 1 || BitConverter.ToUInt64(after, 144) != mountId ||
80 Identity(before) != Identity(after) || FileSystemMagic(parent) != magic)
81 {
82 throw new ArchiveException(ArchiveError.OutputUnavailable);
83 }
84 parentMountId = mountId;
85 }
86
87 private byte[] MountStatus(SafeFileHandle handle)
88 {
89 // mountinfo의 기존 mount ID와 대조하므로 UNIQUE 플래그를 요청하지 않음.
90 var status = Stat(handle, "", 0x1100, 0x17FF);
91 if ((BitConverter.ToUInt32(status, 0) & 0x1000) == 0 || BitConverter.ToUInt64(status, 144) == 0)
92 {
93 throw new ArchiveException(ArchiveError.OutputUnavailable);
94 }
95 return status;
96 }
97
98 private long FileSystemMagic(SafeFileHandle handle)
99 {
100 var system = new byte[256];
101 if (Fstatfs(handle, system) != 0) { ThrowLast(); }
102 return BitConverter.ToInt64(system, 0);
103 }
104
105 protected override SafeFileHandle Create(SafeFileHandle directory, string name, bool folder)
106 {
107 if (folder)
108 {
109 // 기존 권한은 변경하지 않고 새 디렉터리를 0700 이하로 생성함.
110 if (Mkdirat(directory, name, 0x1C0) != 0) { ThrowLast(); }
111 unboundCreation = true;
112 var handle = Open(directory.DangerousGetHandle().ToInt32(), name, 0x90000, 0, 0x0F);
113 unboundCreation = false;
114 return handle;
115 }
116 return Open(directory.DangerousGetHandle().ToInt32(), name, 0x800C2, 0x180, 0x0F);
117 }
118
119 protected override string Inspect(SafeFileHandle handle, bool directory)
120 {
121 var status = Stat(handle, "", 0x1100);
122 var mode = BitConverter.ToUInt16(status, 28);
123 if ((mode & 0xF000) != (directory ? 0x4000 : 0x8000) ||
124 BitConverter.ToUInt32(status, 20) != user || (mode & 0x12) != 0 ||
125 (!directory && BitConverter.ToUInt32(status, 16) != 1))
126 {
127 throw new ArchiveException(ArchiveError.OutputUnavailable);
128 }
129 return Identity(status);
130 }
131
132 private static string Identity(byte[] status)
133 => $"{BitConverter.ToUInt32(status, 136):X8}:{BitConverter.ToUInt32(status, 140):X8}:{BitConverter.ToUInt64(status, 32):X16}";
134
135 private byte[] Stat(SafeFileHandle directory, string name, int flags, uint mask = 0x7FF)
136 {
137 var status = new byte[256];
138 if (Statx(directory, name, flags, mask, status) != 0) { ThrowLast(); }
139 if ((BitConverter.ToUInt32(status, 0) & 0x10F) != 0x10F)
140 {
141 throw new ArchiveException(ArchiveError.OutputUnavailable);
142 }
143 return status;
144 }
145
146 protected override void VerifyChildren(Node node, IReadOnlyCollection<string> names)
147 {
148 using var enumeration = Open(node.Handle.DangerousGetHandle().ToInt32(), ".", 0x90000, 0, 0x0F);
149 var buffer = new byte[65536];
150 var remaining = new HashSet<string>(names, StringComparer.Ordinal);
151 while (true)
152 {
153 var count = Getdents64(217, enumeration, buffer, (uint)buffer.Length);
154 if (count < 0) { ThrowLast(); }
155 if (count == 0) { break; }
156 for (var offset = 0; offset < count;)
157 {
158 if (count - offset < 20) { throw new ArchiveException(ArchiveError.OutputUnavailable); }
159 var size = BitConverter.ToUInt16(buffer, offset + 16);
160 if (size < 20 || size > count - offset) { throw new ArchiveException(ArchiveError.OutputUnavailable); }
161 var end = Array.IndexOf(buffer, (byte)0, offset + 19, size - 19);
162 if (end < 0) { throw new ArchiveException(ArchiveError.OutputUnavailable); }
163 var name = new UTF8Encoding(false, true).GetString(buffer, offset + 19, end - offset - 19);
164 if (name is not ("." or "..") && !remaining.Remove(name)) { throw new ArchiveException(ArchiveError.UnsafePath); }
165 offset += size;
166 }
167 }
168 if (remaining.Count != 0) { throw new ArchiveException(ArchiveError.UnsafePath); }
169 }
170
171 private void RequireName(Node node)
172 {
173 var container = node.Parent?.Handle ?? parent;
174 if (Inspect(container, true) != (node.Parent?.Identity ?? parentIdentity) ||
175 Identity(Stat(container, node.Name, 0x100)) != node.Identity)
176 {
177 throw new ArchiveException(ArchiveError.UnsafePath);
178 }
179 }
180
181 private void RequireParentIdentity(SafeFileHandle selectedParent)
182 {
183 var pinned = MountStatus(parent);
184 var selected = MountStatus(selectedParent);
185 if (parentMountId == 0 ||
186 BitConverter.ToUInt64(pinned, 144) != parentMountId ||
187 BitConverter.ToUInt64(selected, 144) != parentMountId ||
188 Identity(pinned) != parentIdentity || Identity(selected) != parentIdentity ||
189 Inspect(parent, true) != parentIdentity || Inspect(selectedParent, true) != parentIdentity ||
190 FileSystemMagic(selectedParent) != FileSystemMagic(parent))
191 {
192 throw new ArchiveException(ArchiveError.UnsafePath);
193 }
194 }
195
196 internal override void Publish(string leaf, CancellationToken token)
197 {
198 RequireName(Root);
199 foreach (var node in Owned.Where(node => node.Directory))
200 {
201 token.ThrowIfCancellationRequested();
202 if (Fsync(node.Handle) != 0) { ThrowLast(); }
203 }
204 token.ThrowIfCancellationRequested();
205 // 원래 경로를 링크 없이 다시 열어 게시 전 교체를 검사함. rename과 원자적이지 않음.
206 using var selectedParent = Open(-100, parentPath, 0x90000, 0, 0x04);
207 RequireParentIdentity(selectedParent);
208 token.ThrowIfCancellationRequested();
209 // RENAME_NOREPLACE가 없는 커널/FS에서는 대체 경로 없이 실패함.
210 if (Renameat2(parent, TemporaryName, parent, leaf, 1) != 0) { ThrowLast(); }
211 }
212
213 internal override bool Abort()
214 {
215 var success = !unboundCreation;
216 for (var index = Owned.Count - 1; index >= 0; index--)
217 {
218 var node = Owned[index];
219 try
220 {
221 RequireName(node);
222 if (Unlinkat(node.Parent?.Handle ?? parent, node.Name, node.Directory ? 0x200 : 0) != 0)
223 {
224 CleanupError ??= Marshal.GetLastPInvokeError();
225 success = false;
226 }
227 }
228 catch (PosixPublicationException failure) { success = false; CleanupError ??= failure.NativeError; }
229 catch { success = false; }
230 }
231 return success;
232 }
233
234 public override void Dispose() { DisposeOwned(); parent.Dispose(); }
235
236 private SafeFileHandle Open(int directory, string name, ulong flags, ulong mode, ulong resolve)
237 {
238 var how = new OpenHow { Flags = flags, Mode = mode, Resolve = resolve };
239 var descriptor = Openat2(437, directory, name, ref how, 24);
240 if (descriptor < 0) { ThrowLast(); }
241 if (descriptor < 3)
242 {
243 var duplicate = Fcntl((int)descriptor, 1030, 3);
244 var error = Marshal.GetLastPInvokeError();
245 Close((int)descriptor);
246 if (duplicate < 0) { Fail(error); }
247 descriptor = duplicate;
248 }
249 return new SafeFileHandle((nint)descriptor, true);
250 }
251
252 private void ThrowLast() => Fail(Marshal.GetLastPInvokeError());
253 private void Fail(int error)
254 {
255 NativeError = error;
256 throw new PosixPublicationException(error switch
257 {
258 17 => ArchiveError.OutputConflict,
259 40 => ArchiveError.UnsafePath,
260 _ => ArchiveError.OutputUnavailable
261 }, error);
262 }
263
264 [StructLayout(LayoutKind.Sequential)]
265 private struct OpenHow { internal ulong Flags; internal ulong Mode; internal ulong Resolve; }
266 [DllImport("libc", EntryPoint = "syscall", SetLastError = true)]
267 private static extern long Openat2(long syscall, int directory, [MarshalAs(UnmanagedType.LPUTF8Str)] string name,
268 ref OpenHow how, nuint size);
269 [DllImport("libc", EntryPoint = "syscall", SetLastError = true)]
270 private static extern long Getdents64(long syscall, SafeFileHandle directory, [Out] byte[] buffer, uint size);
271 [DllImport("libc", EntryPoint = "statx", SetLastError = true)]
272 private static extern int Statx(SafeFileHandle directory, [MarshalAs(UnmanagedType.LPUTF8Str)] string name,
273 int flags, uint mask, [Out] byte[] status);
274 [DllImport("libc", EntryPoint = "fstatfs", SetLastError = true)]
275 private static extern int Fstatfs(SafeFileHandle directory, [Out] byte[] status);
276 [DllImport("libc", EntryPoint = "mkdirat", SetLastError = true)]
277 private static extern int Mkdirat(SafeFileHandle directory, [MarshalAs(UnmanagedType.LPUTF8Str)] string name, uint mode);
278 [DllImport("libc", EntryPoint = "renameat2", SetLastError = true)]
279 private static extern int Renameat2(SafeFileHandle sourceDirectory, [MarshalAs(UnmanagedType.LPUTF8Str)] string source,
280 SafeFileHandle targetDirectory, [MarshalAs(UnmanagedType.LPUTF8Str)] string target, uint flags);
281 [DllImport("libc", EntryPoint = "unlinkat", SetLastError = true)]
282 private static extern int Unlinkat(SafeFileHandle directory, [MarshalAs(UnmanagedType.LPUTF8Str)] string name, int flags);
283 [DllImport("libc", EntryPoint = "fsync", SetLastError = true)]
284 private static extern int Fsync(SafeFileHandle file);
285 [DllImport("libc", EntryPoint = "getpid")]
286 private static extern int GetProcessId();
287 [DllImport("libc", EntryPoint = "gettid")]
288 private static extern int GetThreadId();
289 [DllImport("libc", EntryPoint = "geteuid")]
290 private static extern uint GetEffectiveUser();
291 [DllImport("libc", EntryPoint = "fcntl", SetLastError = true)]
292 private static extern int Fcntl(int descriptor, int command, int minimum);
293 [DllImport("libc", EntryPoint = "close")]
294 private static extern int Close(int descriptor);
295}
296
297internal sealed class PosixPublicationException(ArchiveError code, int error) : Exception(code.ToString())
298{
299 internal ArchiveError Code { get; } = code;
300 internal int NativeError { get; } = error;
301}