nspkg / engine / process.v
228 lines · 218 sloc · 8.32 KB · c01b0795d1db56c7bce2539b2c46b110637fdc1a
Raw
1// duplex child io and output events follow pacman util.c without changing the parent's cwd.
2// SPDX-License-Identifier: GPL-2.0-or-later
3module engine
4
5import os
6
7#include "@DIR/native_process.h"
8
9fn C.v_alpm_process_pair(&i32) i32
10fn C.v_alpm_process_nonblock(i32) i32
11fn C.v_alpm_process_poll(i32, i32, &i32, &i32) i32
12fn C.v_alpm_process_send(i32, voidptr, u32) i32
13fn C.v_alpm_process_exec(&char, &&char) i32
14fn C.fchdir(i32) i32
15fn C.chroot(&char) i32
16fn C.strsignal(i32) &char
17
18fn (mut handle Handle) close_process_descriptor(fd i32) i32 {
19 if fd >= 0 && C.close(fd) != 0 {
20 handle.diagnostics << 'could not close process descriptor: ${os.last_error().msg()}'
21 }
22 return -1
23}
24
25fn process_close_inherited() ! {
26 if C.v_alpm_close_range(3, ~u32(0)) == 0 { return }
27 if C.errno != C.ENOSYS { return os.last_error() }
28 limit := C.sysconf(C._SC_OPEN_MAX)
29 if limit < 0 { return os.last_error() }
30 for fd := i32(3); fd < limit; fd++ {
31 if C.close(fd) != 0 && C.errno != C.EBADF { return os.last_error() }
32 }
33}
34
35fn process_child_failure(message string) {
36 process_child_output_failure(message + '\n')
37}
38
39fn process_child_output_failure(line string) {
40 mut offset := 0
41 for offset < line.len {
42 count := C.write(2, unsafe { line.str + offset }, uint(line.len - offset))
43 if count < 0 && C.errno == C.EINTR { continue }
44 if count <= 0 { break }
45 offset += int(count)
46 }
47 C._exit(1)
48}
49
50fn process_child(root_fd i32, change_root bool, command string, argv []&char, input i32, output i32) {
51 for pair in [[input, i32(0)], [output, i32(1)], [output, i32(2)]] {
52 for {
53 if C.dup2(pair[0], pair[1]) >= 0 { break }
54 if C.errno != C.EINTR { C._exit(1) }
55 }
56 }
57 if C.fchdir(root_fd) != 0 {
58 process_child_failure('could not enter package root: ${os.last_error().msg()}')
59 }
60 if change_root && C.chroot(c'.') != 0 {
61 process_child_output_failure(localized_message('could not change the root directory (%s)\n', os.last_error().msg()))
62 }
63 if C.chdir(c'/') != 0 {
64 process_child_output_failure(localized_message('could not change directory to %s (%s)\n', '/', os.last_error().msg()))
65 }
66 if os.setenv('SHLVL', '1', false) != 0 || os.unsetenv('BASH_ENV') != 0 {
67 process_child_failure('could not prepare command environment')
68 }
69 C.umask(0o022)
70 for number in [C.SIGABRT, C.SIGALRM, C.SIGBUS, C.SIGCHLD, C.SIGCONT, C.SIGFPE, C.SIGHUP, C.SIGILL,
71 C.SIGINT, C.SIGPIPE, C.SIGQUIT, C.SIGSEGV, C.SIGTERM, C.SIGTSTP, C.SIGTTIN, C.SIGTTOU,
72 C.SIGUSR1, C.SIGUSR2, C.SIGPROF, C.SIGSYS, C.SIGTRAP, C.SIGURG, C.SIGVTALRM, C.SIGXCPU,
73 C.SIGXFSZ] {
74 if C.v_alpm_signal_default(number) != 0 {
75 process_child_failure('could not reset command signals')
76 }
77 }
78 $if linux {
79 if C.v_alpm_signal_default(C.SIGPOLL) != 0 {
80 process_child_failure('could not reset command SIGPOLL')
81 }
82 }
83 process_close_inherited() or { process_child_failure(err.msg()) }
84 // an empty Exec= yields an argv containing only NULL, as wordsplit does in C.
85 command_pointer := if argv.len == 1 {
86 &char(unsafe { nil })
87 } else {
88 unsafe { &char(command.str) }
89 }
90 C.v_alpm_process_exec(command_pointer, unsafe { &&char(argv.data) })
91 process_child_output_failure(localized_message('call to execv failed (%s)\n', os.last_error().msg()))
92}
93
94fn (mut handle Handle) process_output(mut buffered []u8, data []u8) {
95 for byte in data {
96 buffered << byte
97 if byte == `\n` || buffered.len == 2046 {
98 line := buffered.bytestr() + if byte == `\n` { '' } else { '\n' }
99 handle.record_action_as('ALPM-SCRIPTLET', line)
100 handle.commit_event(CommitEvent{ kind: .scriptlet_info, line: line })
101 buffered.clear()
102 }
103 }
104}
105
106fn (mut handle Handle) run_chroot_command(mut root RootFilesystem, command string, args []string, input []u8) ! {
107 if handle.process_active { return error('a package command is already executing') }
108 if command.contains('\x00') || (args.len == 0 && command != '') || args.any(it.contains('\x00')) {
109 return error('invalid package command')
110 }
111 handle.process_active = true
112 defer { handle.process_active = false }
113 // stdio redirection must not overwrite a root originally opened as fd 0, 1 or 2.
114 root_fd := C.v_alpm_duplicate_pipe(root.fd)
115 if root_fd < 0 { return os.last_error() }
116 defer { handle.close_process_descriptor(root_fd) }
117 label := if args.len == 0 { '(null)' } else { command }
118 handle.log(.debug, 'executing "${label}" under chroot "${handle.root}"\n')
119 C.fflush(unsafe { nil })
120 mut output_pair := [i32(-1), -1]
121 if C.v_alpm_process_pair(unsafe { &i32(output_pair.data) }) != 0 {
122 problem := os.last_error()
123 handle.log(.error, localized_message('could not create pipe (%s)\n', problem.msg()))
124 return problem
125 }
126 defer {
127 for fd in output_pair { handle.close_process_descriptor(fd) }
128 }
129 mut input_pair := [i32(-1), -1]
130 if C.v_alpm_process_pair(unsafe { &i32(input_pair.data) }) != 0 {
131 problem := os.last_error()
132 handle.log(.error, localized_message('could not create pipe (%s)\n', problem.msg()))
133 return problem
134 }
135 defer {
136 for fd in input_pair { handle.close_process_descriptor(fd) }
137 }
138 // argv strings remain rooted in the parent until waitpid has reaped the child.
139 mut argv := []&char{cap: args.len + 1}
140 for arg in args { argv << unsafe { &char(arg.str) } }
141 argv << &char(unsafe { nil })
142 child := fork_process()
143 if child < 0 {
144 problem := os.last_error()
145 handle.log(.error, localized_message('could not fork a new process (%s)\n', problem.msg()))
146 return problem
147 }
148 if child == 0 {
149 process_child(root_fd, handle.root != '/', command, argv, input_pair[0], output_pair[1])
150 C._exit(1)
151 }
152 input_pair[0] = handle.close_process_descriptor(input_pair[0])
153 output_pair[1] = handle.close_process_descriptor(output_pair[1])
154 mut failure := ''
155 if C.v_alpm_process_nonblock(output_pair[0]) != 0 || C.v_alpm_process_nonblock(input_pair[1]) != 0 {
156 failure = os.last_error().msg()
157 }
158 mut position := 0
159 mut buffered := []u8{cap: 2046}
160 mut block := []u8{len: 2046}
161 if input.len == 0 { input_pair[1] = handle.close_process_descriptor(input_pair[1]) }
162 for failure == '' && (output_pair[0] >= 0 || input_pair[1] >= 0) {
163 mut out_events := i32(0)
164 mut in_events := i32(0)
165 ready := C.v_alpm_process_poll(output_pair[0], input_pair[1], &out_events, &in_events)
166 if ready < 0 && C.errno == C.EINTR { continue }
167 if ready < 0 {
168 failure = os.last_error().msg()
169 break
170 }
171 if out_events != 0 {
172 count := C.read(output_pair[0], block.data, uint(block.len - buffered.len))
173 if count > 0 {
174 handle.process_output(mut buffered, block[..count])
175 } else if count == 0 {
176 output_pair[0] = handle.close_process_descriptor(output_pair[0])
177 } else if C.errno !in [C.EINTR, C.EAGAIN, C.EWOULDBLOCK] {
178 failure = os.last_error().msg()
179 }
180 }
181 if in_events & C.POLLOUT != 0 {
182 count := C.v_alpm_process_send(input_pair[1], unsafe { &u8(input.data) + position }, u32(int_min(4096, input.len - position)))
183 if count > 0 { position += count }
184 if count < 0 && C.errno !in [C.EINTR, C.EAGAIN, C.EWOULDBLOCK] {
185 if C.errno != C.EPIPE { failure = os.last_error().msg() }
186 input_pair[1] = handle.close_process_descriptor(input_pair[1])
187 }
188 if position == input.len {
189 input_pair[1] = handle.close_process_descriptor(input_pair[1])
190 }
191 } else if in_events != 0 {
192 input_pair[1] = handle.close_process_descriptor(input_pair[1])
193 }
194 }
195 if buffered.len > 0 {
196 line := buffered.bytestr() + '\n'
197 handle.record_action_as('ALPM-SCRIPTLET', line)
198 handle.commit_event(CommitEvent{ kind: .scriptlet_info, line: line })
199 }
200 if failure != '' { C.kill(child, C.SIGKILL) }
201 mut status := i32(0)
202 for {
203 if C.v_alpm_wait_child(child, &status, 0) >= 0 { break }
204 if C.errno != C.EINTR {
205 failure_error := os.last_error()
206 handle.log(.error, localized_message('call to waitpid failed (%s)\n', failure_error.msg()))
207 return failure_error
208 }
209 }
210 if failure != '' { return error('package command io: ${failure}') }
211 signal := C.v_alpm_term_signal(status)
212 if signal != 0 {
213 description := C.strsignal(signal)
214 message := if description == unsafe { nil } {
215 translated_message('Unknown signal')
216 } else {
217 unsafe { cstring_to_vstring(description) }
218 }
219 handle.log(.error, localized_message('command terminated by signal %d: %s\n', signal, message))
220 return error('package command terminated by signal ${signal}')
221 }
222 handle.log(.debug, 'call to waitpid succeeded\n')
223 code := C.v_alpm_exit_status(status)
224 if code != 0 {
225 handle.log(.error, localized_message('command failed to execute correctly\n'))
226 return error('package command exited ${code}')
227 }
228}
229