| 1 | // directory modes follow pacman util.c, independent of the caller's umask. |
| 2 | // SPDX-License-Identifier: GPL-2.0-or-later |
| 3 | module engine |
| 4 | |
| 5 | import os |
| 6 | |
| 7 | fn C.umask(u32) u32 |
| 8 | fn C.fchmod(i32, u32) i32 |
| 9 | |
| 10 | fn make_directory_mode(path string, mode u32) ! { |
| 11 | old_mask := C.umask(0) |
| 12 | defer { C.umask(old_mask) } |
| 13 | mut current := if path.starts_with('/') { '/' } else { '' } |
| 14 | for component in path.split('/') { |
| 15 | if component == '' { continue } |
| 16 | current += component |
| 17 | status := unsafe { C.mkdir(&char(current.str), mode) } |
| 18 | if status != 0 && C.errno != C.EEXIST { return os.last_error() } |
| 19 | current += '/' |
| 20 | } |
| 21 | } |
| 22 | |
| 23 | fn (mut handle Handle) remove_temporary_file(path string) { |
| 24 | if C.unlink(unsafe { &char(path.str) }) != 0 && C.errno != C.ENOENT { |
| 25 | handle.diagnostics << 'could not remove ${path}: ${os.last_error().msg()}' |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | fn (mut handle Handle) temporary_download_name(directory string) !string { |
| 30 | mut pattern := (directory + 'alpmtmp.XXXXXX\x00').bytes() |
| 31 | fd := C.mkstemp(pattern.data) |
| 32 | if fd < 0 { return handle.fail(.retrieve, os.last_error().msg()) } |
| 33 | path := pattern[..pattern.len - 1].bytestr() |
| 34 | mut keep := false |
| 35 | defer { if !keep { handle.remove_temporary_file(path) } } |
| 36 | mask := C.umask(0) |
| 37 | C.umask(mask) |
| 38 | if C.fchmod(fd, ~mask & u32(0o666)) != 0 { |
| 39 | problem := os.last_error() |
| 40 | if C.close(fd) != 0 { |
| 41 | handle.diagnostics << 'could not close temporary download: ${os.last_error().msg()}' |
| 42 | } |
| 43 | return handle.fail(.retrieve, problem.msg()) |
| 44 | } |
| 45 | if C.close(fd) != 0 { return handle.fail(.retrieve, os.last_error().msg()) } |
| 46 | keep = true |
| 47 | return path |
| 48 | } |
| 49 | |