nspkg / tests / extension_probe.v
789 lines · 751 sloc · 33.02 KB · c01b0795d1db56c7bce2539b2c46b110637fdc1a
Raw
1module main
2
3import nspkg.tests.coracle
4import nspkg as facade
5import nspkg.engine
6import nspkg.tests.processfixtures
7import nspkg.tests.hookfixtures
8import nspkg.tests.signaturefixtures
9import os
10
11#include "@DIR/reference_log.h"
12#include <dlfcn.h>
13#include <sys/socket.h>
14#flag linux -ldl
15#flag linux -Wl,--export-dynamic-symbol=socketpair
16#flag linux -Wl,--export-dynamic-symbol=fork
17#flag linux -Wl,--export-dynamic-symbol=chroot
18#flag linux -Wl,--export-dynamic-symbol=chdir
19#flag linux -Wl,--export-dynamic-symbol=fchmod
20
21fn C.dlsym(voidptr, &char) voidptr
22fn C.chdir(const_path &char) i32
23fn C.chroot(const_path &char) i32
24fn C.fchmod(i32, u32) i32
25fn C.umask(u32) u32
26
27type ProcessPair = fn (i32, i32, i32, &i32) i32
28type ProcessFork = fn () i32
29type ProcessDirectory = fn (const_path &char) i32
30type ProcessChmod = fn (i32, u32) i32
31
32struct ProcessFault {
33mut:
34 ordinal int
35 calls int
36 fork_failure bool
37 failures int
38 pair voidptr
39 fork_fn voidptr
40 chroot_fn voidptr
41 chdir_fn voidptr
42 fail_chroot bool
43 fail_child_directory bool
44 fail_scriptlet_mode bool
45}
46
47const process_fault = &ProcessFault{}
48
49@[export: 'fchmod']
50fn process_chmod(fd i32, mode u32) i32 {
51 mut state := unsafe { process_fault }
52 if state != unsafe { nil } && state.fail_scriptlet_mode {
53 path := os.readlink('/proc/self/fd/${fd}') or { '' }
54 if os.args.len == 3 && path.starts_with(os.args[1] + '/') && path.contains('/root/tmp/alpm_') && path.ends_with('/.INSTALL') {
55 state.fail_scriptlet_mode = false
56 state.failures++
57 C.errno = C.EPERM
58 return -1
59 }
60 }
61 symbol := C.dlsym(unsafe { voidptr(C.RTLD_NEXT) }, c'fchmod')
62 assert symbol != unsafe { nil }
63 real_chmod := unsafe { ProcessChmod(symbol) }
64 return real_chmod(fd, mode)
65}
66
67@[export: 'socketpair']
68fn process_pair(domain i32, kind i32, protocol i32, result &i32) i32 {
69 mut state := unsafe { process_fault }
70 if state != unsafe { nil } && state.ordinal > 0 {
71 state.calls++
72 if state.calls == state.ordinal {
73 state.ordinal = 0
74 state.failures++
75 C.errno = C.EMFILE
76 return -1
77 }
78 }
79 symbol := if state != unsafe { nil } && state.pair != unsafe { nil } {
80 state.pair
81 } else {
82 C.dlsym(unsafe { voidptr(C.RTLD_NEXT) }, c'socketpair')
83 }
84 assert symbol != unsafe { nil }
85 real_pair := unsafe { ProcessPair(symbol) }
86 return real_pair(domain, kind, protocol, result)
87}
88
89@[export: 'fork']
90fn process_fork() i32 {
91 mut state := unsafe { process_fault }
92 if state != unsafe { nil } && state.fork_failure {
93 state.fork_failure = false
94 state.failures++
95 C.errno = C.EAGAIN
96 return -1
97 }
98 symbol := if state != unsafe { nil } && state.fork_fn != unsafe { nil } {
99 state.fork_fn
100 } else {
101 C.dlsym(unsafe { voidptr(C.RTLD_NEXT) }, c'fork')
102 }
103 assert symbol != unsafe { nil }
104 real_fork := unsafe { ProcessFork(symbol) }
105 return real_fork()
106}
107
108@[export: 'chroot']
109fn process_chroot(path &char) i32 {
110 mut state := unsafe { process_fault }
111 if state != unsafe { nil } && state.fail_chroot {
112 state.fail_chroot = false
113 C.errno = C.EPERM
114 return -1
115 }
116 symbol := if state != unsafe { nil } && state.chroot_fn != unsafe { nil } {
117 state.chroot_fn
118 } else {
119 C.dlsym(unsafe { voidptr(C.RTLD_NEXT) }, c'chroot')
120 }
121 assert symbol != unsafe { nil }
122 real_chroot := unsafe { ProcessDirectory(symbol) }
123 return real_chroot(path)
124}
125
126@[export: 'chdir']
127fn process_chdir(path &char) i32 {
128 mut state := unsafe { process_fault }
129 if state != unsafe { nil } && state.fail_child_directory && unsafe { path[0] == char(47) && path[1] == 0 } {
130 state.fail_child_directory = false
131 C.errno = C.EACCES
132 return -1
133 }
134 symbol := if state != unsafe { nil } && state.chdir_fn != unsafe { nil } {
135 state.chdir_fn
136 } else {
137 C.dlsym(unsafe { voidptr(C.RTLD_NEXT) }, c'chdir')
138 }
139 assert symbol != unsafe { nil }
140 real_chdir := unsafe { ProcessDirectory(symbol) }
141 return real_chdir(path)
142}
143
144fn arm_process_fault(scenario string) {
145 mut state := unsafe { process_fault }
146 state.pair = C.dlsym(unsafe { voidptr(C.RTLD_NEXT) }, c'socketpair')
147 state.fork_fn = C.dlsym(unsafe { voidptr(C.RTLD_NEXT) }, c'fork')
148 state.chroot_fn = C.dlsym(unsafe { voidptr(C.RTLD_NEXT) }, c'chroot')
149 state.chdir_fn = C.dlsym(unsafe { voidptr(C.RTLD_NEXT) }, c'chdir')
150 state.ordinal = match scenario {
151 'pipe-first' { 1 }
152 'pipe-second' { 2 }
153 else { 0 }
154 }
155 state.calls = 0
156 state.failures = 0
157 state.fork_failure = scenario == 'fork-failure'
158 state.fail_chroot = scenario == 'chroot-failure'
159 state.fail_child_directory = scenario == 'child-directory-failure'
160 state.fail_scriptlet_mode = scenario == 'scriptlet-mode-failure'
161}
162
163fn assert_process_fault(scenario string) {
164 if scenario == 'scriptlet-mode-failure' {
165 assert process_fault.failures == 1
166 assert !process_fault.fail_scriptlet_mode
167 }
168 if scenario in ['pipe-first', 'pipe-second', 'fork-failure'] {
169 assert process_fault.failures == 1, scenario
170 assert process_fault.ordinal == 0 && !process_fault.fork_failure, scenario
171 }
172}
173
174type ReferenceLogLine = fn (voidptr, u32, &u8)
175
176fn C.v_alpm_reference_log_install(voidptr, ReferenceLogLine, voidptr) voidptr
177fn C.v_alpm_reference_log_remove(voidptr, voidptr)
178fn C.v_alpm_test_reap_command()
179
180struct ExtensionTrace {
181 root string
182 logfile string
183mut:
184 action_count int
185 items []string
186 interrupt bool
187 reap_on_output bool
188 disappear_hook bool
189 close_hook_directory bool
190 in_hook bool
191 stage_fault string
192 reference_handle &coracle.Handle = unsafe { nil }
193 native_handle &engine.Handle = unsafe { nil }
194 public_handle &facade.Handle = unsafe { nil }
195}
196
197fn c_log(context voidptr, level u32, message &u8) {
198 mut trace := unsafe { &ExtensionTrace(context) }
199 trace.observe_log(level, unsafe { cstring_to_vstring(message) })
200}
201
202fn native_log(context voidptr, level engine.LogLevel, message string) {
203 mut trace := unsafe { &ExtensionTrace(context) }
204 trace.observe_log(u32(level), message)
205}
206
207fn public_log(context voidptr, level facade.LogLevel, message &u8) {
208 mut trace := unsafe { &ExtensionTrace(context) }
209 trace.observe_log(u32(level), unsafe { cstring_to_vstring(message) })
210}
211
212fn public_event(context voidptr, event &facade.Event) {
213 // the retained event union has the same ABI as the frozen C facade.
214 c_event(context, unsafe { &coracle.Event(event) })
215}
216
217fn (mut trace ExtensionTrace) observe_log(level u32, message string) {
218 if trace.close_hook_directory && level == 4 && message.starts_with('parsing hook file ') && message.ends_with('30-read-dir.hook\n') {
219 // close only this fixture's discovery descriptor to force readdir(3) to fail.
220 target := os.join_path(trace.root, 'usr/share/libalpm/hooks')
221 mut closed := false
222 for name in os.ls('/proc/self/fd') or {
223 assert false, err.msg()
224 []string{}
225 } {
226 actual := os.readlink('/proc/self/fd/' + name) or { continue }
227 if actual == target {
228 assert C.close(i32(name.int())) == 0
229 closed = true
230 break
231 }
232 }
233 assert closed
234 trace.close_hook_directory = false
235 }
236 if trace.disappear_hook && level == 4 && message.starts_with('parsing hook file ') && message.ends_with('30-vanish.hook\n') {
237 path := os.join_path(trace.root, 'usr/share/libalpm/hooks/30-vanish.hook')
238 os.rm(path) or { assert false, err.msg() }
239 trace.disappear_hook = false
240 }
241 // scriptlet shell build settings and random staging paths have a separate scope.
242 if level !in [u32(1), 2] && !(trace.in_hook && level == 4 && message.starts_with('executing "')) {
243 return
244 }
245 trace.capture_actions()
246 mut text := message.replace(trace.root, 'ROOT')
247 if at := text.index('ROOT/tmp/alpm_') {
248 start := at + 'ROOT/tmp/alpm_'.len
249 mut end := start
250 for end < text.len && text[end] !in [`/`, `\n`, ` `] { end++ }
251 text = text[..start] + 'STAGE' + text[end..]
252 }
253 trace.items << 'log:${level}:' + text
254}
255
256fn (mut trace ExtensionTrace) damage_scriptlet_stage(line string) {
257 if trace.stage_fault in scriptlet_modes() && (line.starts_with('pre-remove:') || line.starts_with('post-remove:')) {
258 tmp := os.join_path(trace.root, 'tmp')
259 names := os.ls(tmp) or { panic(err) }
260 assert names.len == 1
261 info := os.stat(os.join_path(tmp, names[0], '.INSTALL')) or { panic(err) }
262 trace.items << 'mode:${line.all_before(':')}:${info.mode & 0o7777:o}'
263 }
264 if !line.starts_with('pre-remove:') || trace.stage_fault !in ['scriptlet-cleanup',
265 'scriptlet-directory-cleanup'] {
266 return
267 }
268 tmp := os.join_path(trace.root, 'tmp')
269 names := os.ls(tmp) or { panic(err) }
270 assert names.len == 1 && names[0].starts_with('alpm_')
271 directory := os.join_path(tmp, names[0])
272 if trace.stage_fault == 'scriptlet-cleanup' {
273 os.rm(os.join_path(directory, '.INSTALL')) or { panic(err) }
274 } else {
275 os.write_file(os.join_path(directory, 'extra'), 'kept') or { panic(err) }
276 }
277 trace.stage_fault = ''
278}
279
280fn c_event(context voidptr, event &coracle.Event) {
281 mut trace := unsafe { &ExtensionTrace(context) }
282 if unsafe { event.type_ } == .hook_run_start { trace.in_hook = true }
283 if unsafe { event.type_ } == .hook_run_done { trace.in_hook = false }
284 trace.capture_actions()
285 match unsafe { event.type_ } {
286 .transaction_start { trace.items << 'transaction:start' }
287 .transaction_done { trace.items << 'transaction:done' }
288 .package_operation_start { trace.items << 'remove:start' }
289 .package_operation_done { trace.items << 'remove:done' }
290 .hook_start { trace.items << 'hook:start:${int(unsafe { event.hook.when })}' }
291 .hook_done { trace.items << 'hook:done:${int(unsafe { event.hook.when })}' }
292 .hook_run_start, .hook_run_done {
293 value := unsafe { event.hook_run }
294 name := unsafe { cstring_to_vstring(value.name) }
295 description := if value.desc == unsafe { nil } {
296 '(null)'
297 } else {
298 unsafe { cstring_to_vstring(value.desc) }
299 }
300 phase := if unsafe { event.type_ } == .hook_run_start { 'start' } else { 'done' }
301 trace.items << 'hook:${phase}:${name}:${description}:${value.position}:${value.total}'
302 }
303 .scriptlet_info {
304 line := unsafe { cstring_to_vstring(event.scriptlet_info.line) }
305 trace.items << 'output:' + line
306 trace.damage_scriptlet_stage(line)
307 if trace.reap_on_output && line.starts_with('pre-hook') { C.v_alpm_test_reap_command() }
308 if trace.interrupt && line.starts_with('pre-remove:') {
309 if trace.public_handle != unsafe { nil } {
310 trace.public_handle.trans_interrupt() or { assert false, err.msg() }
311 } else {
312 trace.reference_handle.trans_interrupt() or { assert false, err.msg() }
313 }
314 }
315 }
316 else {}
317 }
318}
319
320fn native_event(context voidptr, event engine.CommitEvent) {
321 mut trace := unsafe { &ExtensionTrace(context) }
322 if event.kind == .hook_run_start { trace.in_hook = true }
323 if event.kind == .hook_run_done { trace.in_hook = false }
324 trace.capture_actions()
325 match event.kind {
326 .transaction_start { trace.items << 'transaction:start' }
327 .transaction_done { trace.items << 'transaction:done' }
328 .package_remove_start { trace.items << 'remove:start' }
329 .package_remove_done { trace.items << 'remove:done' }
330 .hook_start { trace.items << 'hook:start:${int(event.when)}' }
331 .hook_done { trace.items << 'hook:done:${int(event.when)}' }
332 .hook_run_start, .hook_run_done {
333 phase := if event.kind == .hook_run_start { 'start' } else { 'done' }
334 description := if event.has_description { event.description } else { '(null)' }
335 trace.items << 'hook:${phase}:${event.name}:${description}:${event.position}:${event.total}'
336 }
337 .scriptlet_info {
338 trace.items << 'output:' + event.line
339 trace.damage_scriptlet_stage(event.line)
340 if trace.reap_on_output && event.line.starts_with('pre-hook') {
341 C.v_alpm_test_reap_command()
342 }
343 if trace.interrupt && event.line.starts_with('pre-remove:') {
344 assert trace.native_handle.interrupt_transaction_async() == 0
345 }
346 }
347 else {}
348 }
349}
350
351fn hook_text(when string, kind string, targets []string, command string, extra string) string {
352 return '[Trigger]\nOperation = Remove\nType = ${kind}\n' + targets.map('Target = ' + it).join('\n') + '\n[Action]\nWhen = ${when}\nExec = ${command}\n${extra}\n'
353}
354
355fn parser_cases() map[string]string {
356 command := '/bin/sh -c "exit 0"'
357 valid := hook_text('PreTransaction', 'Package', ['app'], command, 'AbortOnFail')
358 return {
359 'parser-missing-all': '[Trigger]\n[Trigger]\n[Action]\n'
360 'parser-no-target': valid.replace('Target = app\n', '')
361 'parser-no-type': valid.replace('Type = Package\n', '')
362 'parser-no-operation': valid.replace('Operation = Remove\n', '')
363 'parser-no-exec': valid.replace('Exec = ${command}\n', '')
364 'parser-no-when': valid.replace('When = PreTransaction\n', '')
365 'parser-section': '[Unknown]\n'
366 'parser-no-section': 'Exec = /bin/sh\n'
367 'parser-trigger-option': '[Trigger]\nUnknown = value\n'
368 'parser-action-option': '[Action]\nUnknown = value\n'
369 'parser-unknown-no-value': '[Action]\nUnknown\n'
370 'parser-action-trigger-key': '[Action]\nType\n'
371 'parser-trigger-action-key': '[Trigger]\nWhen\n'
372 'parser-operation': valid.replace('Operation = Remove', 'Operation = Invalid')
373 'parser-when': valid.replace('When = PreTransaction', 'When = Invalid')
374 'parser-empty-type': valid.replace('Type = Package', 'Type =')
375 'parser-empty-operation': valid.replace('Operation = Remove', 'Operation =')
376 'parser-empty-when': valid.replace('When = PreTransaction', 'When =')
377 'parser-empty-target': valid.replace('Target = app', 'Target =')
378 'parser-exec-quote': valid.replace('Exec = ${command}', 'Exec = "unfinished')
379 'parser-exec-no-value': valid.replace('Exec = ${command}', 'Exec')
380 'parser-exec-overwrite-no-value': valid + 'Exec\n'
381 'parser-empty-exec': valid.replace('Exec = ${command}', 'Exec =')
382 'parser-empty-exec-unused': valid.replace('Exec = ${command}', 'Exec =').replace('Target = app', 'Target = absent')
383 'parser-quoted-empty-exec': valid.replace('Exec = ${command}', 'Exec = ""')
384 'parser-empty-exec-overwrite': valid.replace('Exec = ${command}', 'Exec =\nExec = ${command}')
385 'parser-duplicates': valid.replace('Type = Package', 'Type = Path\nType = Package').replace('When = PreTransaction', 'When = PostTransaction\nWhen = PreTransaction').replace('Exec = ${command}', 'Description =\nDescription = replacement\nExec = ""\nExec = ${command}')
386 'parser-overwrite-invalid': valid.replace('Type = Package', 'Type = Package\nType = Invalid')
387 'parser-long-description': valid + 'Description = ' + 'x'.repeat(4100) + '\n'
388 'parser-long-comment': valid + '#' + 'x'.repeat(4100) + '\n'
389 'parser-crlf': valid.replace('\n', '\r\n')
390 'parser-final-line': valid.trim_right('\n')
391 }
392}
393
394fn discovery_directory(root string, scenario string) string {
395 return match scenario {
396 'long-hook-directory' { root + '/' + 'long/'.repeat(1000) }
397 'long-hook-file' { hookfixtures.deep_directory(root) }
398 else { '' }
399 }
400}
401
402fn scriptlet_modes() map[string]int {
403 return {
404 'scriptlet-mode-default': 0o644
405 'scriptlet-mode-private': 0o700
406 'scriptlet-mode-group': 0o750
407 'scriptlet-mode-executable': 0o755
408 'scriptlet-mode-setuid': 0o4755
409 'scriptlet-mode-setgid': 0o2750
410 'scriptlet-mode-sticky': 0o1755
411 }
412}
413
414fn fixture(runtime processfixtures.Runtime, base string, scenario string) ! {
415 root := os.join_path(base, 'root')
416 entry := os.join_path(base, 'db', 'local', 'app-1-1')
417 runtime.install(root)!
418 os.mkdir_all(entry)!
419 os.write_file(os.join_path(base, 'db', 'local', 'ALPM_DB_VERSION'), '9\n')!
420 os.write_file(os.join_path(entry, 'desc'), '%DESC%\nApplication\n\n')!
421 os.write_file(os.join_path(entry, 'files'), '%FILES%\npayload\n\n')!
422 os.write_file(os.join_path(root, 'payload'), 'payload')!
423 low := os.join_path(root, 'usr', 'share', 'libalpm', 'hooks')
424 high := os.join_path(root, 'etc', 'hooks')
425 os.mkdir_all(low)!
426 os.mkdir_all(high)!
427 mut extra := ''
428 mut command := '/bin/sh -c "printf \'pre-hook\\n\'"'
429 if scenario in ['abort', 'ignore-failure'] { command = '/bin/sh -c "exit 9"' }
430 if scenario == 'signal' { command = '/bin/sh -c "kill -TERM $$"' }
431 if scenario in ['abort', 'signal', 'reaped-child'] { extra = 'AbortOnFail' }
432 if scenario in ['pipe-first', 'pipe-second', 'fork-failure', 'chroot-failure',
433 'child-directory-failure'] {
434 extra = 'AbortOnFail'
435 }
436 if scenario in ['missing-dependency', 'ignored-dependency'] { extra = 'Depends = missing>=2' }
437 if scenario == 'missing-dependency' { extra += '\nAbortOnFail' }
438 if scenario in ['targets', 'mixed-targets'] {
439 command = '/bin/sh -c \'while IFS= read -r target; do printf "target:%s\\n" "$target"; done\''
440 extra = 'NeedsTargets'
441 }
442 if scenario == 'empty-description' { extra = 'Description =' }
443 mut pre := hook_text('PreTransaction', 'Package', ['app', '*'], command, extra)
444 if scenario == 'mixed-targets' {
445 pre = '[Trigger]\nOperation=Remove\nType=Path\nTarget=payload\nTarget=payload\n' + pre
446 }
447 os.write_file(os.join_path(low, '10-pre.hook'), pre)!
448 post := hook_text('PostTransaction', 'Path', ['payload'], '/bin/sh -c "printf \'post-hook\\n\'"', '')
449 os.write_file(os.join_path(low, '20-post.hook'), post)!
450 if text := parser_cases()[scenario] {
451 os.write_file(os.join_path(low, '30-parser.hook'), text)!
452 }
453 if scenario == 'disappearing-hook' { os.write_file(os.join_path(low, '30-vanish.hook'), pre)! }
454 if scenario == 'read-directory-failure' {
455 os.write_file(os.join_path(low, '30-read-dir.hook'), pre)!
456 }
457 if scenario == 'broken-hook-link' { os.symlink('absent', os.join_path(low, '30-broken.hook'))! }
458 if scenario == 'directory-hook' { os.mkdir(os.join_path(low, '30-directory.hook'))! }
459 if scenario in ['file-hook-directory', 'missing-hook-directory'] {
460 os.rmdir(high)!
461 if scenario == 'file-hook-directory' { os.write_file(high, 'not a directory')! }
462 }
463 if scenario == 'invalid-override' {
464 os.write_file(os.join_path(high, '10-pre.hook'), '[Unknown]\n')!
465 }
466 if scenario == 'long-hook-file' {
467 deep := discovery_directory(root, scenario)
468 os.mkdir_all(deep)!
469 fd := C.open(unsafe { &char(deep.str) }, C.O_RDONLY | C.O_DIRECTORY | C.O_CLOEXEC)
470 if fd < 0 { return os.last_error() }
471 defer { if C.close(fd) != 0 { eprintln(os.last_error()) } }
472 name := hookfixtures.long_filename()
473 file := C.openat(fd, unsafe { &char(name.str) }, C.O_CREAT | C.O_WRONLY | C.O_CLOEXEC, 0o600)
474 if file < 0 { return os.last_error() }
475 if C.close(file) != 0 { return os.last_error() }
476 }
477 if scenario == 'mask' { os.symlink('/dev/null', os.join_path(high, '10-pre.hook'))! }
478 if scenario == 'override' {
479 os.write_file(os.join_path(high, '10-pre.hook'), hook_text('PreTransaction', 'Package', ['app'], '/bin/sh -c "printf \'override\\n\'"', 'Description = Override'))!
480 }
481 if scenario == 'negation' {
482 os.write_file(os.join_path(low, '10-pre.hook'), hook_text('PreTransaction', 'Package', [
483 '*',
484 '!app',
485 ], command, ''))!
486 }
487 if scenario == 'malformed' {
488 os.write_file(os.join_path(low, '30-invalid.hook'), '[Trigger]\nType = Invalid\n')!
489 }
490 if scenario == 'missing-exec' {
491 os.write_file(os.join_path(low, '10-pre.hook'), hook_text('PreTransaction', 'Package', ['app'], '/missing', 'AbortOnFail'))!
492 }
493 if scenario == 'post-failure' {
494 os.write_file(os.join_path(low, '20-post.hook'), hook_text('PostTransaction', 'Path', ['payload'], '/bin/sh -c "exit 8"', 'AbortOnFail'))!
495 }
496 if scenario in ['scriptlets', 'scriptlet-failure', 'scriptlet-tmp-blocked', 'scriptlet-disk-full',
497 'scriptlet-cleanup', 'scriptlet-directory-cleanup', 'no-scriptlet', 'db-only', 'no-hooks',
498 'interrupt-one', 'interrupt-two', 'scriptlet-mode-failure'] || scenario in scriptlet_modes() {
499 contents := r'pre_remove() { printf "pre-remove:%s:" "$1"; test -e /payload && printf "present\\n"; }
500post_remove() { printf "post-remove:%s:" "$1"; if test -e /payload; then printf "present\\n"; else printf "absent\\n"; fi; }
501'
502 os.write_file(os.join_path(entry, 'install'), if scenario == 'scriptlet-failure' {
503 contents + '\npre_remove() { printf "failure\\n"; return 4; }\n'
504 } else {
505 contents
506 })!
507 }
508 if mode := scriptlet_modes()[scenario] { os.chmod(os.join_path(entry, 'install'), mode)! }
509 if scenario == 'scriptlet-tmp-blocked' { os.write_file(os.join_path(root, 'tmp'), 'blocked')! }
510 if scenario == 'scriptlet-disk-full' {
511 tmp := os.join_path(root, 'tmp')
512 os.mkdir_all(tmp)!
513 signaturefixtures.command('mount', ['-t', 'tmpfs', '-o', 'size=4k,nr_inodes=64', 'tmpfs',
514 tmp])!
515 os.write_file(os.join_path(tmp, 'fill'), 'x'.repeat(4096))!
516 }
517 if scenario in ['ldconfig', 'interrupt-one', 'interrupt-two'] {
518 os.mkdir_all(os.join_path(root, 'sbin'))!
519 os.write_file(os.join_path(root, 'etc', 'ld.so.conf'), '')!
520 os.write_file(os.join_path(root, 'sbin', 'ldconfig'), '#!/bin/sh\nprintf "ldconfig\\n"\n')!
521 os.chmod(os.join_path(root, 'sbin', 'ldconfig'), 0o755)!
522 os.mkdir_all(os.join_path(root, 'usr', 'bin'))!
523 os.cp(os.join_path(root, 'sbin', 'ldconfig'), os.join_path(root, 'usr', 'bin', 'ldconfig'))!
524 }
525 if scenario == 'hook-removed' {
526 os.write_file(os.join_path(entry, 'files'), '%FILES%\npayload\nusr/share/libalpm/hooks/20-post.hook\n\n')!
527 }
528 if scenario == 'interrupt-two' {
529 later := os.join_path(base, 'db', 'local', 'later-1-1')
530 os.mkdir_all(later)!
531 os.write_file(os.join_path(later, 'desc'), '%DESC%\nLater\n\n')!
532 os.write_file(os.join_path(later, 'files'), '%FILES%\nlater\n\n')!
533 os.write_file(os.join_path(root, 'later'), 'later')!
534 }
535}
536
537fn scriptlet_run_mask(scenario string) u32 {
538 saved := C.umask(0o077)
539 if scenario !in scriptlet_modes() { C.umask(saved) }
540 return saved
541}
542
543fn run_reference(base string, scenario string, mut trace ExtensionTrace) !bool {
544 mask := scriptlet_run_mask(scenario)
545 defer { C.umask(mask) }
546 handle := coracle.initialize(os.join_path(base, 'root'), os.join_path(base, 'db'))!
547 defer { handle.release() or { eprintln(err) } }
548 handle.option_add_hookdir(os.join_path(base, 'root', 'etc', 'hooks'))!
549 handle.option_set_logfile(os.join_path(base, 'actions.log'))!
550 trace.reference_handle = handle
551 handle.option_set_eventcb(c_event, &trace)!
552 log_state := C.v_alpm_reference_log_install(handle, c_log, &trace)
553 defer { C.v_alpm_reference_log_remove(handle, log_state) }
554 directory := discovery_directory(trace.root, scenario)
555 if directory != '' { handle.option_add_hookdir(directory)! }
556 if scenario == 'no-upgrade-trigger' { handle.option_add_noupgrade('payload')! }
557 if scenario == 'no-extract-trigger' { handle.option_add_no_extract('payload')! }
558 mut flags := coracle.trans_flag_0
559 if scenario == 'no-hooks' { flags |= .no_hooks }
560 if scenario == 'no-scriptlet' { flags |= .no_scriptlet }
561 if scenario == 'db-only' { flags |= .db_only }
562 if scenario == 'interrupt-two' { flags |= .no_deps }
563 handle.trans_init(flags)!
564 defer { handle.trans_release() or { eprintln(err) } }
565 db := handle.get_localdb()!
566 pkg := db.get_pkg('app') or { return error('missing reference package') }
567 handle.remove_pkg(pkg)!
568 if scenario == 'interrupt-two' {
569 handle.remove_pkg(db.get_pkg('later') or { return error('missing later fixture') })!
570 }
571 handle.trans_prepare()!.free()
572 arm_process_fault(scenario)
573 defer { assert_process_fault(scenario) }
574 result := handle.trans_commit() or {
575 assert handle.errno() == .trans_hook_failed
576 return false
577 }
578 result.free()
579 return true
580}
581
582fn run_native(base string, scenario string, mut trace ExtensionTrace) !bool {
583 mask := scriptlet_run_mask(scenario)
584 defer { C.umask(mask) }
585 mut handle := engine.initialize(os.join_path(base, 'root'), os.join_path(base, 'db'))!
586 defer { handle.release() or { eprintln(err) } }
587 handle.add_string_list(.hook_dirs, os.join_path(base, 'root', 'etc', 'hooks'))!
588 handle.set_string_option(.logfile, os.join_path(base, 'actions.log'))!
589 trace.native_handle = handle
590 handle.set_commit_callback(native_event, &trace)!
591 handle.set_log_callback(native_log, &trace)!
592 directory := discovery_directory(trace.root, scenario)
593 if directory != '' { handle.add_string_list(.hook_dirs, directory)! }
594 if scenario == 'no-upgrade-trigger' { handle.add_string_list(.no_upgrade, 'payload')! }
595 if scenario == 'no-extract-trigger' { handle.add_string_list(.no_extract, 'payload')! }
596 mut flags := engine.transaction_flag_0
597 if scenario == 'no-hooks' { flags |= .no_hooks }
598 if scenario == 'no-scriptlet' { flags |= .no_scriptlet }
599 if scenario == 'db-only' { flags |= .db_only }
600 if scenario == 'interrupt-two' { flags |= .no_deps }
601 handle.start_transaction(flags)!
602 defer { handle.release_transaction() or { eprintln(err) } }
603 mut db := handle.local_database()!
604 pkg := db.get_pkg('app') or { return error('missing native package') }
605 handle.remove_package(pkg)!
606 if scenario == 'interrupt-two' {
607 handle.remove_package(db.get_pkg('later') or { return error('missing later fixture') })!
608 }
609 assert handle.prepare_transaction()!.success
610 arm_process_fault(scenario)
611 defer { assert_process_fault(scenario) }
612 handle.commit_transaction() or {
613 assert err.code() == int(engine.Errno.trans_hook_failed)
614 assert handle.transaction_state()! == .prepared
615 return false
616 }
617 return true
618}
619
620fn run_public(base string, scenario string, mut trace ExtensionTrace) !bool {
621 mask := scriptlet_run_mask(scenario)
622 defer { C.umask(mask) }
623 handle := facade.initialize(os.join_path(base, 'root'), os.join_path(base, 'db'))!
624 defer { handle.release() or { eprintln(err) } }
625 handle.option_add_hookdir(os.join_path(base, 'root', 'etc', 'hooks'))!
626 handle.option_set_logfile(os.join_path(base, 'actions.log'))!
627 trace.public_handle = handle
628 handle.option_set_eventcb(public_event, &trace)!
629 handle.option_set_logcb_line(public_log, &trace)!
630 directory := discovery_directory(trace.root, scenario)
631 if directory != '' { handle.option_add_hookdir(directory)! }
632 if scenario == 'no-upgrade-trigger' { handle.option_add_noupgrade('payload')! }
633 if scenario == 'no-extract-trigger' { handle.option_add_no_extract('payload')! }
634 mut flags := facade.trans_flag_0
635 if scenario == 'no-hooks' { flags |= .no_hooks }
636 if scenario == 'no-scriptlet' { flags |= .no_scriptlet }
637 if scenario == 'db-only' { flags |= .db_only }
638 if scenario == 'interrupt-two' { flags |= .no_deps }
639 handle.trans_init(flags)!
640 defer { handle.trans_release() or { eprintln(err) } }
641 db := handle.get_localdb()!
642 pkg := db.get_pkg('app') or { return error('missing public package') }
643 handle.remove_pkg(pkg)!
644 if scenario == 'interrupt-two' {
645 later := db.get_pkg('later') or { return error('missing public later fixture') }
646 handle.remove_pkg(later)!
647 }
648 handle.trans_prepare()!.free()
649 arm_process_fault(scenario)
650 defer { assert_process_fault(scenario) }
651 result := handle.trans_commit() or {
652 assert handle.errno() == .trans_hook_failed
653 return false
654 }
655 result.free()
656 return true
657}
658
659fn main() {
660 run() or {
661 eprintln(err)
662 exit(1)
663 }
664}
665
666fn run() ! {
667 if os.args.len != 3 || os.readlink('/proc/self/ns/mnt')! == os.args[2] {
668 return error('requires a private mount namespace')
669 }
670 assert os.setenv('LC_ALL', 'C', true) == 0
671 signaturefixtures.command('mount', ['--make-rprivate', '/'])!
672 base := os.args[1]
673 defer { hookfixtures.cleanup_long_paths(base) or { eprintln(err) } }
674 runtime := processfixtures.create(os.join_path(base, 'runtime'))!
675 mut scenarios := ['basic', 'targets', 'mask', 'override', 'negation', 'abort', 'ignore-failure',
676 'missing-dependency', 'ignored-dependency', 'malformed', 'missing-exec', 'post-failure',
677 'scriptlets', 'scriptlet-failure', 'no-scriptlet', 'db-only', 'no-hooks', 'ldconfig',
678 'interrupt-one', 'interrupt-two', 'no-upgrade-trigger', 'no-extract-trigger',
679 'empty-description', 'mixed-targets', 'hook-removed', 'signal', 'reaped-child']
680 mut parser_names := parser_cases().keys()
681 parser_names.sort()
682 scenarios << parser_names
683 scenarios << ['disappearing-hook', 'broken-hook-link', 'directory-hook', 'file-hook-directory',
684 'missing-hook-directory', 'invalid-override', 'long-hook-directory', 'long-hook-file',
685 'read-directory-failure']
686 scenarios << ['pipe-first', 'pipe-second', 'fork-failure', 'chroot-failure',
687 'child-directory-failure']
688 scenarios << ['scriptlet-tmp-blocked', 'scriptlet-cleanup', 'scriptlet-directory-cleanup',
689 'scriptlet-disk-full']
690 scenarios << scriptlet_modes().keys().sorted()
691 scenarios << 'scriptlet-mode-failure'
692 for scenario in scenarios {
693 old := os.join_path(base, scenario, 'old')
694 native := os.join_path(base, scenario, 'native')
695 fixture(runtime, old, scenario)!
696 fixture(runtime, native, scenario)!
697 mut expected := ExtensionTrace{ root: os.join_path(old, 'root'), logfile: os.join_path(old, 'actions.log'), interrupt: scenario.starts_with('interrupt-'), reap_on_output: scenario == 'reaped-child', disappear_hook: scenario == 'disappearing-hook', close_hook_directory: scenario == 'read-directory-failure' }
698 mut actual := ExtensionTrace{ root: os.join_path(native, 'root'), logfile: os.join_path(native, 'actions.log'), interrupt: scenario.starts_with('interrupt-'), reap_on_output: scenario == 'reaped-child', disappear_hook: scenario == 'disappearing-hook', close_hook_directory: scenario == 'read-directory-failure' }
699 expected.stage_fault = scenario
700 actual.stage_fault = scenario
701 source_success := run_reference(old, scenario, mut expected)!
702 if scenario in scriptlet_modes() {
703 assert expected.items.filter(it.starts_with('mode:')).len == 2
704 }
705 native_fds := os.ls('/proc/self/fd')!.len
706 native_success := run_native(native, scenario, mut actual)!
707 assert os.ls('/proc/self/fd')!.len == native_fds, '${scenario}: native descriptor leak'
708 assert native_success == source_success, '${scenario}: success ${native_success} != ${source_success}'
709
710 expected.capture_actions()
711 actual.capture_actions()
712 if scenario == 'chroot-failure' {
713 assert expected.items.contains('output:could not change the root directory (Operation not permitted)\n')
714 }
715 if scenario == 'child-directory-failure' {
716 assert expected.items.contains('output:could not change directory to / (Permission denied)\n')
717 }
718 assert actual.items == expected.items, '${scenario}: ${actual.items} != ${expected.items}'
719 public := os.join_path(base, scenario, 'public')
720 fixture(runtime, public, scenario)!
721 mut public_trace := ExtensionTrace{ root: os.join_path(public, 'root'), logfile: os.join_path(public, 'actions.log'), interrupt: scenario.starts_with('interrupt-'), reap_on_output: scenario == 'reaped-child', disappear_hook: scenario == 'disappearing-hook', close_hook_directory: scenario == 'read-directory-failure' }
722 public_trace.stage_fault = scenario
723 public_fds := os.ls('/proc/self/fd')!.len
724 public_success := run_public(public, scenario, mut public_trace)!
725 assert os.ls('/proc/self/fd')!.len == public_fds, '${scenario}: public descriptor leak'
726 assert public_success == source_success, '${scenario}: public success ${public_success} != ${source_success}'
727 public_trace.capture_actions()
728 assert public_trace.items == expected.items, '${scenario}: public ${public_trace.items} != ${expected.items}'
729 expected_log := action_records(os.join_path(old, 'actions.log'), os.join_path(old, 'root'))!
730 actual_log := action_records(os.join_path(native, 'actions.log'), os.join_path(native, 'root'))!
731 assert actual_log == expected_log, '${scenario}\nnative log: ${actual_log}\nreference log: ${expected_log}'
732 assert action_records(public_trace.logfile, public_trace.root)! == expected_log, scenario
733 if scenario in ['long-hook-directory', 'long-hook-file', 'disappearing-hook',
734 'read-directory-failure'] {
735 assert !source_success, scenario
736 prefix := match scenario {
737 'long-hook-directory' { 'could not open directory:' }
738 'long-hook-file' { 'could not open file:' }
739 'disappearing-hook' { 'error while reading hook ' }
740 else { 'could not read directory:' }
741 }
742 assert expected.items.any(it.starts_with('log:1:' + prefix)), scenario
743 }
744 if scenario in ['ldconfig', 'interrupt-one'] {
745 assert expected.items.contains('output:ldconfig\n')
746 }
747 if scenario == 'interrupt-two' {
748 assert !expected.items.contains('output:ldconfig\n')
749 }
750 for path in ['root/payload', 'db/local/app-1-1', 'root/later', 'db/local/later-1-1'] {
751 assert os.exists(os.join_path(native, path)) == os.exists(os.join_path(old, path)), '${scenario}: ${path}'
752 assert os.exists(os.join_path(public, path)) == os.exists(os.join_path(old, path)), '${scenario}: public ${path}'
753 }
754 for path in [old, native, public] {
755 if os.is_dir(os.join_path(path, 'root', 'tmp')) {
756 if scenario == 'scriptlet-disk-full' {
757 fill := os.join_path(path, 'root', 'tmp', 'fill')
758 assert os.read_file(fill)!.len == 4096
759 os.rm(fill)!
760 }
761 if scenario == 'scriptlet-directory-cleanup' {
762 tmp := os.join_path(path, 'root', 'tmp')
763 left := os.ls(tmp)!
764 assert left.len == 1
765 assert os.read_file(os.join_path(tmp, left[0], 'extra'))! == 'kept'
766 os.rmdir_all(os.join_path(tmp, left[0]))!
767 }
768 assert os.ls(os.join_path(path, 'root', 'tmp'))!.len == 0
769 }
770 assert !os.exists(os.join_path(path, 'db', 'db.lck'))
771 }
772 }
773 println('${scenarios.len} core and ${scenarios.len} public/libalpm extension transactions verified in private chroots')
774}
775
776fn action_records(path string, root string) ![]string {
777 if !os.exists(path) { return []string{} }
778 return os.read_lines(path)!.map(it.all_after('] ').replace(root, 'ROOT'))
779}
780
781fn (mut trace ExtensionTrace) capture_actions() {
782 lines := action_records(trace.logfile, trace.root) or {
783 assert false, err.msg()
784 return
785 }
786 assert lines.len >= trace.action_count
787 for line in lines[trace.action_count..] { trace.items << 'action:' + line }
788 trace.action_count = lines.len
789}
790