team-ljyzipelo

공개
205줄9.0 KB
1using System.Runtime.InteropServices;
2using System.Text;
3using Microsoft.Win32.SafeHandles;
4using Zipelo.Core;
5
6namespace Zipelo.Runtime;
7
8internal sealed class LinuxFolderPublication : PendingFolderPublication
9{
10 private readonly SafeFileHandle parent;
11 private readonly uint user = GetEffectiveUser();
12 private string parentIdentity = "";
13 private bool unboundCreation;
14 internal int? NativeError { get; private set; }
15 internal int? CleanupError { get; private set; }
16
17 internal LinuxFolderPublication(string path) => parent = Open(-100, path, 0x90000, 0, 0x04);
18
19 internal override void Initialize()
20 {
21 var system = new byte[256];
22 if (Fstatfs(parent, system) != 0) { ThrowLast(); }
23 // 로컬 ext4, XFS만 초기 구현 대상으로 삼음. FUSE와 네트워크 FS는 거부함.
24 if (BitConverter.ToInt64(system, 0) is not (0xEF53 or 0x58465342))
25 {
26 throw new ArchiveException(ArchiveError.OutputUnavailable);
27 }
28 parentIdentity = Inspect(parent, true);
29 AddRoot(Create(parent, TemporaryName, true));
30 }
31
32 protected override SafeFileHandle Create(SafeFileHandle directory, string name, bool folder)
33 {
34 if (folder)
35 {
36 // 기존 권한은 변경하지 않고 새 디렉터리를 0700 이하로 생성함.
37 if (Mkdirat(directory, name, 0x1C0) != 0) { ThrowLast(); }
38 unboundCreation = true;
39 var handle = Open(directory.DangerousGetHandle().ToInt32(), name, 0x90000, 0, 0x0E);
40 unboundCreation = false;
41 return handle;
42 }
43 return Open(directory.DangerousGetHandle().ToInt32(), name, 0x800C2, 0x180, 0x0E);
44 }
45
46 protected override string Inspect(SafeFileHandle handle, bool directory)
47 {
48 var status = Stat(handle, "", 0x1100);
49 var mode = BitConverter.ToUInt16(status, 28);
50 if ((mode & 0xF000) != (directory ? 0x4000 : 0x8000) ||
51 BitConverter.ToUInt32(status, 20) != user || (mode & 0x12) != 0 ||
52 (!directory && BitConverter.ToUInt32(status, 16) != 1))
53 {
54 throw new ArchiveException(ArchiveError.OutputUnavailable);
55 }
56 return Identity(status);
57 }
58
59 private static string Identity(byte[] status)
60 => $"{BitConverter.ToUInt32(status, 136):X8}:{BitConverter.ToUInt32(status, 140):X8}:{BitConverter.ToUInt64(status, 32):X16}";
61
62 private byte[] Stat(SafeFileHandle directory, string name, int flags)
63 {
64 var status = new byte[256];
65 if (Statx(directory, name, flags, 0x7FF, status) != 0) { ThrowLast(); }
66 if ((BitConverter.ToUInt32(status, 0) & 0x10F) != 0x10F)
67 {
68 throw new ArchiveException(ArchiveError.OutputUnavailable);
69 }
70 return status;
71 }
72
73 protected override void VerifyChildren(Node node, IReadOnlyCollection<string> names)
74 {
75 using var enumeration = Open(node.Handle.DangerousGetHandle().ToInt32(), ".", 0x90000, 0, 0x0E);
76 var buffer = new byte[65536];
77 var remaining = new HashSet<string>(names, StringComparer.Ordinal);
78 while (true)
79 {
80 var count = Getdents64(217, enumeration, buffer, (uint)buffer.Length);
81 if (count < 0) { ThrowLast(); }
82 if (count == 0) { break; }
83 for (var offset = 0; offset < count;)
84 {
85 if (count - offset < 20) { throw new ArchiveException(ArchiveError.OutputUnavailable); }
86 var size = BitConverter.ToUInt16(buffer, offset + 16);
87 if (size < 20 || size > count - offset) { throw new ArchiveException(ArchiveError.OutputUnavailable); }
88 var end = Array.IndexOf(buffer, (byte)0, offset + 19, size - 19);
89 if (end < 0) { throw new ArchiveException(ArchiveError.OutputUnavailable); }
90 var name = new UTF8Encoding(false, true).GetString(buffer, offset + 19, end - offset - 19);
91 if (name is not ("." or "..") && !remaining.Remove(name)) { throw new ArchiveException(ArchiveError.UnsafePath); }
92 offset += size;
93 }
94 }
95 if (remaining.Count != 0) { throw new ArchiveException(ArchiveError.UnsafePath); }
96 }
97
98 private void RequireName(Node node)
99 {
100 var container = node.Parent?.Handle ?? parent;
101 if (Inspect(container, true) != (node.Parent?.Identity ?? parentIdentity) ||
102 Identity(Stat(container, node.Name, 0x100)) != node.Identity)
103 {
104 throw new ArchiveException(ArchiveError.UnsafePath);
105 }
106 }
107
108 internal override void Publish(string leaf, CancellationToken token)
109 {
110 RequireName(Root);
111 foreach (var node in Owned.Where(node => node.Directory))
112 {
113 token.ThrowIfCancellationRequested();
114 if (Fsync(node.Handle) != 0) { ThrowLast(); }
115 }
116 token.ThrowIfCancellationRequested();
117 // RENAME_NOREPLACE가 없는 커널/FS에서는 대체 경로 없이 실패함.
118 if (Renameat2(parent, TemporaryName, parent, leaf, 1) != 0) { ThrowLast(); }
119 }
120
121 internal override bool Abort()
122 {
123 var success = !unboundCreation;
124 for (var index = Owned.Count - 1; index >= 0; index--)
125 {
126 var node = Owned[index];
127 try
128 {
129 RequireName(node);
130 if (Unlinkat(node.Parent?.Handle ?? parent, node.Name, node.Directory ? 0x200 : 0) != 0)
131 {
132 CleanupError ??= Marshal.GetLastPInvokeError();
133 success = false;
134 }
135 }
136 catch (PosixPublicationException failure) { success = false; CleanupError ??= failure.NativeError; }
137 catch { success = false; }
138 }
139 return success;
140 }
141
142 public override void Dispose() { DisposeOwned(); parent.Dispose(); }
143
144 private SafeFileHandle Open(int directory, string name, ulong flags, ulong mode, ulong resolve)
145 {
146 var how = new OpenHow { Flags = flags, Mode = mode, Resolve = resolve };
147 var descriptor = Openat2(437, directory, name, ref how, 24);
148 if (descriptor < 0) { ThrowLast(); }
149 if (descriptor < 3)
150 {
151 var duplicate = Fcntl((int)descriptor, 1030, 3);
152 var error = Marshal.GetLastPInvokeError();
153 Close((int)descriptor);
154 if (duplicate < 0) { Fail(error); }
155 descriptor = duplicate;
156 }
157 return new SafeFileHandle((nint)descriptor, true);
158 }
159
160 private void ThrowLast() => Fail(Marshal.GetLastPInvokeError());
161 private void Fail(int error)
162 {
163 NativeError = error;
164 throw new PosixPublicationException(error switch
165 {
166 17 => ArchiveError.OutputConflict,
167 40 => ArchiveError.UnsafePath,
168 _ => ArchiveError.OutputUnavailable
169 }, error);
170 }
171
172 [StructLayout(LayoutKind.Sequential)]
173 private struct OpenHow { internal ulong Flags; internal ulong Mode; internal ulong Resolve; }
174 [DllImport("libc", EntryPoint = "syscall", SetLastError = true)]
175 private static extern long Openat2(long syscall, int directory, [MarshalAs(UnmanagedType.LPUTF8Str)] string name,
176 ref OpenHow how, nuint size);
177 [DllImport("libc", EntryPoint = "syscall", SetLastError = true)]
178 private static extern long Getdents64(long syscall, SafeFileHandle directory, [Out] byte[] buffer, uint size);
179 [DllImport("libc", EntryPoint = "statx", SetLastError = true)]
180 private static extern int Statx(SafeFileHandle directory, [MarshalAs(UnmanagedType.LPUTF8Str)] string name,
181 int flags, uint mask, [Out] byte[] status);
182 [DllImport("libc", EntryPoint = "fstatfs", SetLastError = true)]
183 private static extern int Fstatfs(SafeFileHandle directory, [Out] byte[] status);
184 [DllImport("libc", EntryPoint = "mkdirat", SetLastError = true)]
185 private static extern int Mkdirat(SafeFileHandle directory, [MarshalAs(UnmanagedType.LPUTF8Str)] string name, uint mode);
186 [DllImport("libc", EntryPoint = "renameat2", SetLastError = true)]
187 private static extern int Renameat2(SafeFileHandle sourceDirectory, [MarshalAs(UnmanagedType.LPUTF8Str)] string source,
188 SafeFileHandle targetDirectory, [MarshalAs(UnmanagedType.LPUTF8Str)] string target, uint flags);
189 [DllImport("libc", EntryPoint = "unlinkat", SetLastError = true)]
190 private static extern int Unlinkat(SafeFileHandle directory, [MarshalAs(UnmanagedType.LPUTF8Str)] string name, int flags);
191 [DllImport("libc", EntryPoint = "fsync", SetLastError = true)]
192 private static extern int Fsync(SafeFileHandle file);
193 [DllImport("libc", EntryPoint = "geteuid")]
194 private static extern uint GetEffectiveUser();
195 [DllImport("libc", EntryPoint = "fcntl", SetLastError = true)]
196 private static extern int Fcntl(int descriptor, int command, int minimum);
197 [DllImport("libc", EntryPoint = "close")]
198 private static extern int Close(int descriptor);
199}
200
201internal sealed class PosixPublicationException(ArchiveError code, int error) : Exception(code.ToString())
202{
203 internal ArchiveError Code { get; } = code;
204 internal int NativeError { get; } = error;
205}