team-ljyzipelo

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