// resolve directory links under a pinned root, including absolute links and parent components. // SPDX-License-Identifier: GPL-2.0-or-later module engine import crypto.md5 import os #include "@DIR/native_rootfs.h" @[typedef] struct C.v_alpm_root_info { mut: mode u32 size i64 device u64 inode u64 links u64 } fn C.v_alpm_root_stat(i32, &char, &C.v_alpm_root_info) i32 fn C.v_alpm_root_duplicate(i32) i32 fn C.readlinkat(i32, &char, &char, uint) i64 struct RootFilesystem { mut: owner &Handle fd i32 = -1 } struct RootPath { name string mut: owner &Handle fd i32 = -1 } struct RootStatus { present bool info C.v_alpm_root_info } fn root_directory_flags() i32 { $if linux { return C.O_PATH | C.O_DIRECTORY | C.O_NOFOLLOW | C.O_CLOEXEC } return C.O_RDONLY | C.O_DIRECTORY | C.O_NOFOLLOW | C.O_CLOEXEC } fn validate_package_path(path string) ! { if path == '' || path.starts_with('/') || path.contains('\x00') { return error('invalid package path: ${path}') } mut has_name := false mut start := 0 for start < path.len { end := path.index_after('/', start) or { path.len } length := end - start if length == 2 && path[start] == `.` && path[start + 1] == `.` { return error('package path traverses its root: ${path}') } if length > 0 && (length != 1 || path[start] != `.`) { has_name = true } if end == path.len { break } start = end + 1 } if !has_name { return error('package path names the filesystem root') } } fn (mut handle Handle) open_root_filesystem() !RootFilesystem { path := if handle.root == '/' { '/' } else { handle.root.trim_right('/') } fd := C.open(unsafe { &char(path.str) }, root_directory_flags()) if fd < 0 { return handle.fail(.system, 'cannot open package root: ${os.last_error().msg()}') } return RootFilesystem{ owner: handle, fd: fd } } fn (mut root RootFilesystem) close() { fd := root.fd root.fd = -1 if fd >= 0 && C.close(fd) != 0 { root.owner.diagnostics << 'could not close package root: ${os.last_error().msg()}' } } fn (mut path RootPath) close() { fd := path.fd path.fd = -1 if fd >= 0 && C.close(fd) != 0 { path.owner.diagnostics << 'could not close package path: ${os.last_error().msg()}' } } fn root_readlink(directory i32, name string) !string { mut buffer := []u8{len: 256} for buffer.len <= 65536 { count := C.readlinkat(directory, unsafe { &char(name.str) }, unsafe { &char(buffer.data) }, uint(buffer.len)) if count < 0 { return os.last_error() } if count < buffer.len { return buffer[..int(count)].bytestr() } buffer = []u8{len: buffer.len * 2} } return error('symlink target is too long') } fn root_link_components(target string, remaining []string) []string { mut next := target.split('/') next << remaining return next } fn (mut root RootFilesystem) resolve(path string, follow_leaf bool) !RootPath { return root.resolve_path(path, follow_leaf, .follow_links) } enum RootResolvePolicy { follow_links extract_parents hardlink_source } fn (mut root RootFilesystem) resolve_path(path string, follow_leaf bool, policy RootResolvePolicy) !RootPath { validate_package_path(path)! mut pending := path.split('/') // Empty interior components are skipped below. A trailing slash still names the leaf. for pending.last() == '' { pending.pop() } first := C.v_alpm_root_duplicate(root.fd) if first < 0 { return os.last_error() } mut stack := [first] defer { for fd in stack { if C.close(fd) != 0 { root.owner.diagnostics << 'could not close resolved directory: ${os.last_error().msg()}' } } } mut position := 0 mut links := 0 for position < pending.len { name := pending[position] position++ if name in ['', '.'] { continue } if name == '..' { if stack.len > 1 { fd := stack.pop() if C.close(fd) != 0 { return os.last_error() } } continue } last := position == pending.len if last && !follow_leaf { return RootPath{ owner: root.owner, fd: stack.pop(), name: name } } mut info := C.v_alpm_root_info{} if C.v_alpm_root_stat(stack.last(), unsafe { &char(name.str) }, &info) != 0 { problem := os.last_error() if last && problem.code() == int(C.ENOENT) { return RootPath{ owner: root.owner, fd: stack.pop(), name: name } } if !last && policy == .extract_parents && problem.code() == int(C.ENOENT) { if C.mkdirat(stack.last(), unsafe { &char(name.str) }, 0o777) != 0 && C.errno != C.EEXIST { return os.last_error() } // restart the lookup so a competing directory/link gets the same checks. position-- continue } return problem } if info.mode & 0o170000 == 0o120000 { if policy == .hardlink_source && !last { return error('hardlink source has an intermediate symlink: ${path}') } if policy == .extract_parents && !last { // archive extraction's UNLINK | SECURE_SYMLINKS replaces parent links. if C.unlinkat(stack.last(), unsafe { &char(name.str) }, 0) != 0 { return os.last_error() } position-- continue } links++ if links > 40 { return error_with_code('too many symlinks in package path', int(C.ELOOP)) } target := root_readlink(stack.last(), name)! if target.starts_with('/') { for stack.len > 1 { fd := stack.pop() if C.close(fd) != 0 { return os.last_error() } } } pending = root_link_components(target, pending[position..]) position = 0 continue } if last { return RootPath{ owner: root.owner, fd: stack.pop(), name: name } } fd := C.openat(stack.last(), unsafe { &char(name.str) }, root_directory_flags()) if fd < 0 { return os.last_error() } stack << fd } return RootPath{ owner: root.owner, fd: stack.pop(), name: '.' } } fn (mut root RootFilesystem) stat(path string, follow_leaf bool) !RootStatus { mut resolved := root.resolve(path, follow_leaf) or { if err.code() in [int(C.ENOENT), int(C.ENOTDIR)] { return RootStatus{} } return err } defer { resolved.close() } return resolved.stat() } fn (path &RootPath) stat() !RootStatus { mut info := C.v_alpm_root_info{} if C.v_alpm_root_stat(path.fd, unsafe { &char(path.name.str) }, &info) != 0 { if C.errno in [C.ENOENT, C.ENOTDIR] { return RootStatus{} } return os.last_error() } return RootStatus{ present: true, info: info } } fn (mut root RootFilesystem) md5sum(path string) !string { mut resolved := root.resolve(path, true)! defer { resolved.close() } return root.md5sum_at(&resolved) } fn (mut root RootFilesystem) md5sum_at(resolved &RootPath) !string { status := resolved.stat()! if !status.present || status.info.mode & 0o170000 != 0o100000 { return error('backup path is not a regular file') } fd := C.openat(resolved.fd, unsafe { &char(resolved.name.str) }, C.O_RDONLY | C.O_NOFOLLOW | C.O_CLOEXEC | C.O_NONBLOCK) if fd < 0 { return os.last_error() } defer { if C.close(fd) != 0 { root.owner.diagnostics << 'could not close backup file: ${os.last_error().msg()}' } } mut size := i64(0) mut mode := u32(0) mut links := u64(0) if C.v_alpm_download_stat(fd, &size, &mode, &links) != 0 { return os.last_error() } if mode & 0o170000 != 0o100000 { return error('backup path changed into a special file') } mut digest := md5.new() mut buffer := []u8{len: 32768} for { count := C.read(fd, buffer.data, uint(buffer.len)) if count < 0 && C.errno == C.EINTR { continue } if count < 0 { return os.last_error() } if count == 0 { break } digest.write(buffer[..count])! } return digest.sum([]).hex() } fn (mut root RootFilesystem) unlink(path string, directory bool) ! { mut resolved := root.resolve(path, false)! defer { resolved.close() } flags := if directory { C.AT_REMOVEDIR } else { 0 } if C.unlinkat(resolved.fd, unsafe { &char(resolved.name.str) }, flags) != 0 { return os.last_error() } } fn (mut root RootFilesystem) rename(source string, destination string) ! { mut from := root.resolve(source, false)! defer { from.close() } mut to := root.resolve(destination, false)! defer { to.close() } if C.renameat(from.fd, unsafe { &char(from.name.str) }, to.fd, unsafe { &char(to.name.str) }) != 0 { return os.last_error() } } fn (mut root RootFilesystem) directory_names(directory i32, limit int) ![]string { fd := C.openat(directory, c'.', C.O_RDONLY | C.O_DIRECTORY | C.O_CLOEXEC) if fd < 0 { return os.last_error() } dir := C.fdopendir(fd) if dir == unsafe { nil } { problem := os.last_error() if C.close(fd) != 0 { root.owner.diagnostics << 'could not close package directory: ${os.last_error().msg()}' } return problem } defer { if C.closedir(dir) != 0 { root.owner.diagnostics << 'could not close package directory: ${os.last_error().msg()}' } } mut names := []string{} for { mut name := &char(unsafe { nil }) result := C.v_alpm_storage_next(dir, &name) if result < 0 { return os.last_error() } if result == 0 { break } value := unsafe { cstring_to_vstring(name) } if value !in ['.', '..'] { names << value if limit > 0 && names.len >= limit { break } } } return names }