nspkg / engine / root_filesystem.v
302 lines · 278 sloc · 8.8 KB · c01b0795d1db56c7bce2539b2c46b110637fdc1a
Raw
1// resolve directory links under a pinned root, including absolute links and parent components.
2// SPDX-License-Identifier: GPL-2.0-or-later
3module engine
4
5import crypto.md5
6import os
7
8#include "@DIR/native_rootfs.h"
9
10@[typedef]
11struct C.v_alpm_root_info {
12mut:
13 mode u32
14 size i64
15 device u64
16 inode u64
17 links u64
18}
19
20fn C.v_alpm_root_stat(i32, &char, &C.v_alpm_root_info) i32
21fn C.v_alpm_root_duplicate(i32) i32
22fn C.readlinkat(i32, &char, &char, uint) i64
23
24struct RootFilesystem {
25mut:
26 owner &Handle
27 fd i32 = -1
28}
29
30struct RootPath {
31 name string
32mut:
33 owner &Handle
34 fd i32 = -1
35}
36
37struct RootStatus {
38 present bool
39 info C.v_alpm_root_info
40}
41
42fn root_directory_flags() i32 {
43 $if linux {
44 return C.O_PATH | C.O_DIRECTORY | C.O_NOFOLLOW | C.O_CLOEXEC
45 }
46 return C.O_RDONLY | C.O_DIRECTORY | C.O_NOFOLLOW | C.O_CLOEXEC
47}
48
49fn validate_package_path(path string) ! {
50 if path == '' || path.starts_with('/') || path.contains('\x00') {
51 return error('invalid package path: ${path}')
52 }
53 mut has_name := false
54 mut start := 0
55 for start < path.len {
56 end := path.index_after('/', start) or { path.len }
57 length := end - start
58 if length == 2 && path[start] == `.` && path[start + 1] == `.` {
59 return error('package path traverses its root: ${path}')
60 }
61 if length > 0 && (length != 1 || path[start] != `.`) { has_name = true }
62 if end == path.len { break }
63 start = end + 1
64 }
65 if !has_name { return error('package path names the filesystem root') }
66}
67
68fn (mut handle Handle) open_root_filesystem() !RootFilesystem {
69 path := if handle.root == '/' { '/' } else { handle.root.trim_right('/') }
70 fd := C.open(unsafe { &char(path.str) }, root_directory_flags())
71 if fd < 0 { return handle.fail(.system, 'cannot open package root: ${os.last_error().msg()}') }
72 return RootFilesystem{ owner: handle, fd: fd }
73}
74
75fn (mut root RootFilesystem) close() {
76 fd := root.fd
77 root.fd = -1
78 if fd >= 0 && C.close(fd) != 0 {
79 root.owner.diagnostics << 'could not close package root: ${os.last_error().msg()}'
80 }
81}
82
83fn (mut path RootPath) close() {
84 fd := path.fd
85 path.fd = -1
86 if fd >= 0 && C.close(fd) != 0 {
87 path.owner.diagnostics << 'could not close package path: ${os.last_error().msg()}'
88 }
89}
90
91fn root_readlink(directory i32, name string) !string {
92 mut buffer := []u8{len: 256}
93 for buffer.len <= 65536 {
94 count := C.readlinkat(directory, unsafe { &char(name.str) }, unsafe { &char(buffer.data) }, uint(buffer.len))
95 if count < 0 { return os.last_error() }
96 if count < buffer.len { return buffer[..int(count)].bytestr() }
97 buffer = []u8{len: buffer.len * 2}
98 }
99 return error('symlink target is too long')
100}
101
102fn root_link_components(target string, remaining []string) []string {
103 mut next := target.split('/')
104 next << remaining
105 return next
106}
107
108fn (mut root RootFilesystem) resolve(path string, follow_leaf bool) !RootPath {
109 return root.resolve_path(path, follow_leaf, .follow_links)
110}
111
112enum RootResolvePolicy {
113 follow_links
114 extract_parents
115 hardlink_source
116}
117
118fn (mut root RootFilesystem) resolve_path(path string, follow_leaf bool, policy RootResolvePolicy) !RootPath {
119 validate_package_path(path)!
120 mut pending := path.split('/')
121 // Empty interior components are skipped below. A trailing slash still names the leaf.
122 for pending.last() == '' { pending.pop() }
123 first := C.v_alpm_root_duplicate(root.fd)
124 if first < 0 { return os.last_error() }
125 mut stack := [first]
126 defer {
127 for fd in stack {
128 if C.close(fd) != 0 {
129 root.owner.diagnostics << 'could not close resolved directory: ${os.last_error().msg()}'
130 }
131 }
132 }
133 mut position := 0
134 mut links := 0
135 for position < pending.len {
136 name := pending[position]
137 position++
138 if name in ['', '.'] { continue }
139 if name == '..' {
140 if stack.len > 1 {
141 fd := stack.pop()
142 if C.close(fd) != 0 { return os.last_error() }
143 }
144 continue
145 }
146 last := position == pending.len
147 if last && !follow_leaf {
148 return RootPath{ owner: root.owner, fd: stack.pop(), name: name }
149 }
150 mut info := C.v_alpm_root_info{}
151 if C.v_alpm_root_stat(stack.last(), unsafe { &char(name.str) }, &info) != 0 {
152 problem := os.last_error()
153 if last && problem.code() == int(C.ENOENT) {
154 return RootPath{ owner: root.owner, fd: stack.pop(), name: name }
155 }
156 if !last && policy == .extract_parents && problem.code() == int(C.ENOENT) {
157 if C.mkdirat(stack.last(), unsafe { &char(name.str) }, 0o777) != 0 && C.errno != C.EEXIST {
158 return os.last_error()
159 }
160 // restart the lookup so a competing directory/link gets the same checks.
161 position--
162 continue
163 }
164 return problem
165 }
166 if info.mode & 0o170000 == 0o120000 {
167 if policy == .hardlink_source && !last {
168 return error('hardlink source has an intermediate symlink: ${path}')
169 }
170 if policy == .extract_parents && !last {
171 // archive extraction's UNLINK | SECURE_SYMLINKS replaces parent links.
172 if C.unlinkat(stack.last(), unsafe { &char(name.str) }, 0) != 0 {
173 return os.last_error()
174 }
175 position--
176 continue
177 }
178 links++
179 if links > 40 {
180 return error_with_code('too many symlinks in package path', int(C.ELOOP))
181 }
182 target := root_readlink(stack.last(), name)!
183 if target.starts_with('/') {
184 for stack.len > 1 {
185 fd := stack.pop()
186 if C.close(fd) != 0 { return os.last_error() }
187 }
188 }
189 pending = root_link_components(target, pending[position..])
190 position = 0
191 continue
192 }
193 if last { return RootPath{ owner: root.owner, fd: stack.pop(), name: name } }
194 fd := C.openat(stack.last(), unsafe { &char(name.str) }, root_directory_flags())
195 if fd < 0 { return os.last_error() }
196 stack << fd
197 }
198 return RootPath{ owner: root.owner, fd: stack.pop(), name: '.' }
199}
200
201fn (mut root RootFilesystem) stat(path string, follow_leaf bool) !RootStatus {
202 mut resolved := root.resolve(path, follow_leaf) or {
203 if err.code() in [int(C.ENOENT), int(C.ENOTDIR)] { return RootStatus{} }
204 return err
205 }
206 defer { resolved.close() }
207 return resolved.stat()
208}
209
210fn (path &RootPath) stat() !RootStatus {
211 mut info := C.v_alpm_root_info{}
212 if C.v_alpm_root_stat(path.fd, unsafe { &char(path.name.str) }, &info) != 0 {
213 if C.errno in [C.ENOENT, C.ENOTDIR] { return RootStatus{} }
214 return os.last_error()
215 }
216 return RootStatus{ present: true, info: info }
217}
218
219fn (mut root RootFilesystem) md5sum(path string) !string {
220 mut resolved := root.resolve(path, true)!
221 defer { resolved.close() }
222 return root.md5sum_at(&resolved)
223}
224
225fn (mut root RootFilesystem) md5sum_at(resolved &RootPath) !string {
226 status := resolved.stat()!
227 if !status.present || status.info.mode & 0o170000 != 0o100000 {
228 return error('backup path is not a regular file')
229 }
230 fd := C.openat(resolved.fd, unsafe { &char(resolved.name.str) }, C.O_RDONLY | C.O_NOFOLLOW | C.O_CLOEXEC | C.O_NONBLOCK)
231 if fd < 0 { return os.last_error() }
232 defer {
233 if C.close(fd) != 0 {
234 root.owner.diagnostics << 'could not close backup file: ${os.last_error().msg()}'
235 }
236 }
237 mut size := i64(0)
238 mut mode := u32(0)
239 mut links := u64(0)
240 if C.v_alpm_download_stat(fd, &size, &mode, &links) != 0 { return os.last_error() }
241 if mode & 0o170000 != 0o100000 { return error('backup path changed into a special file') }
242 mut digest := md5.new()
243 mut buffer := []u8{len: 32768}
244 for {
245 count := C.read(fd, buffer.data, uint(buffer.len))
246 if count < 0 && C.errno == C.EINTR { continue }
247 if count < 0 { return os.last_error() }
248 if count == 0 { break }
249 digest.write(buffer[..count])!
250 }
251 return digest.sum([]).hex()
252}
253
254fn (mut root RootFilesystem) unlink(path string, directory bool) ! {
255 mut resolved := root.resolve(path, false)!
256 defer { resolved.close() }
257 flags := if directory { C.AT_REMOVEDIR } else { 0 }
258 if C.unlinkat(resolved.fd, unsafe { &char(resolved.name.str) }, flags) != 0 {
259 return os.last_error()
260 }
261}
262
263fn (mut root RootFilesystem) rename(source string, destination string) ! {
264 mut from := root.resolve(source, false)!
265 defer { from.close() }
266 mut to := root.resolve(destination, false)!
267 defer { to.close() }
268 if C.renameat(from.fd, unsafe { &char(from.name.str) }, to.fd, unsafe { &char(to.name.str) }) != 0 {
269 return os.last_error()
270 }
271}
272
273fn (mut root RootFilesystem) directory_names(directory i32, limit int) ![]string {
274 fd := C.openat(directory, c'.', C.O_RDONLY | C.O_DIRECTORY | C.O_CLOEXEC)
275 if fd < 0 { return os.last_error() }
276 dir := C.fdopendir(fd)
277 if dir == unsafe { nil } {
278 problem := os.last_error()
279 if C.close(fd) != 0 {
280 root.owner.diagnostics << 'could not close package directory: ${os.last_error().msg()}'
281 }
282 return problem
283 }
284 defer {
285 if C.closedir(dir) != 0 {
286 root.owner.diagnostics << 'could not close package directory: ${os.last_error().msg()}'
287 }
288 }
289 mut names := []string{}
290 for {
291 mut name := &char(unsafe { nil })
292 result := C.v_alpm_storage_next(dir, &name)
293 if result < 0 { return os.last_error() }
294 if result == 0 { break }
295 value := unsafe { cstring_to_vstring(name) }
296 if value !in ['.', '..'] {
297 names << value
298 if limit > 0 && names.len >= limit { break }
299 }
300 }
301 return names
302}
303