module main import nspkg.tests.coracle import nspkg as facade import nspkg.engine import nspkg.tests.processfixtures import nspkg.tests.hookfixtures import nspkg.tests.signaturefixtures import os #include "@DIR/reference_log.h" #include #include #flag linux -ldl #flag linux -Wl,--export-dynamic-symbol=socketpair #flag linux -Wl,--export-dynamic-symbol=fork #flag linux -Wl,--export-dynamic-symbol=chroot #flag linux -Wl,--export-dynamic-symbol=chdir #flag linux -Wl,--export-dynamic-symbol=fchmod fn C.dlsym(voidptr, &char) voidptr fn C.chdir(const_path &char) i32 fn C.chroot(const_path &char) i32 fn C.fchmod(i32, u32) i32 fn C.umask(u32) u32 type ProcessPair = fn (i32, i32, i32, &i32) i32 type ProcessFork = fn () i32 type ProcessDirectory = fn (const_path &char) i32 type ProcessChmod = fn (i32, u32) i32 struct ProcessFault { mut: ordinal int calls int fork_failure bool failures int pair voidptr fork_fn voidptr chroot_fn voidptr chdir_fn voidptr fail_chroot bool fail_child_directory bool fail_scriptlet_mode bool } const process_fault = &ProcessFault{} @[export: 'fchmod'] fn process_chmod(fd i32, mode u32) i32 { mut state := unsafe { process_fault } if state != unsafe { nil } && state.fail_scriptlet_mode { path := os.readlink('/proc/self/fd/${fd}') or { '' } if os.args.len == 3 && path.starts_with(os.args[1] + '/') && path.contains('/root/tmp/alpm_') && path.ends_with('/.INSTALL') { state.fail_scriptlet_mode = false state.failures++ C.errno = C.EPERM return -1 } } symbol := C.dlsym(unsafe { voidptr(C.RTLD_NEXT) }, c'fchmod') assert symbol != unsafe { nil } real_chmod := unsafe { ProcessChmod(symbol) } return real_chmod(fd, mode) } @[export: 'socketpair'] fn process_pair(domain i32, kind i32, protocol i32, result &i32) i32 { mut state := unsafe { process_fault } if state != unsafe { nil } && state.ordinal > 0 { state.calls++ if state.calls == state.ordinal { state.ordinal = 0 state.failures++ C.errno = C.EMFILE return -1 } } symbol := if state != unsafe { nil } && state.pair != unsafe { nil } { state.pair } else { C.dlsym(unsafe { voidptr(C.RTLD_NEXT) }, c'socketpair') } assert symbol != unsafe { nil } real_pair := unsafe { ProcessPair(symbol) } return real_pair(domain, kind, protocol, result) } @[export: 'fork'] fn process_fork() i32 { mut state := unsafe { process_fault } if state != unsafe { nil } && state.fork_failure { state.fork_failure = false state.failures++ C.errno = C.EAGAIN return -1 } symbol := if state != unsafe { nil } && state.fork_fn != unsafe { nil } { state.fork_fn } else { C.dlsym(unsafe { voidptr(C.RTLD_NEXT) }, c'fork') } assert symbol != unsafe { nil } real_fork := unsafe { ProcessFork(symbol) } return real_fork() } @[export: 'chroot'] fn process_chroot(path &char) i32 { mut state := unsafe { process_fault } if state != unsafe { nil } && state.fail_chroot { state.fail_chroot = false C.errno = C.EPERM return -1 } symbol := if state != unsafe { nil } && state.chroot_fn != unsafe { nil } { state.chroot_fn } else { C.dlsym(unsafe { voidptr(C.RTLD_NEXT) }, c'chroot') } assert symbol != unsafe { nil } real_chroot := unsafe { ProcessDirectory(symbol) } return real_chroot(path) } @[export: 'chdir'] fn process_chdir(path &char) i32 { mut state := unsafe { process_fault } if state != unsafe { nil } && state.fail_child_directory && unsafe { path[0] == char(47) && path[1] == 0 } { state.fail_child_directory = false C.errno = C.EACCES return -1 } symbol := if state != unsafe { nil } && state.chdir_fn != unsafe { nil } { state.chdir_fn } else { C.dlsym(unsafe { voidptr(C.RTLD_NEXT) }, c'chdir') } assert symbol != unsafe { nil } real_chdir := unsafe { ProcessDirectory(symbol) } return real_chdir(path) } fn arm_process_fault(scenario string) { mut state := unsafe { process_fault } state.pair = C.dlsym(unsafe { voidptr(C.RTLD_NEXT) }, c'socketpair') state.fork_fn = C.dlsym(unsafe { voidptr(C.RTLD_NEXT) }, c'fork') state.chroot_fn = C.dlsym(unsafe { voidptr(C.RTLD_NEXT) }, c'chroot') state.chdir_fn = C.dlsym(unsafe { voidptr(C.RTLD_NEXT) }, c'chdir') state.ordinal = match scenario { 'pipe-first' { 1 } 'pipe-second' { 2 } else { 0 } } state.calls = 0 state.failures = 0 state.fork_failure = scenario == 'fork-failure' state.fail_chroot = scenario == 'chroot-failure' state.fail_child_directory = scenario == 'child-directory-failure' state.fail_scriptlet_mode = scenario == 'scriptlet-mode-failure' } fn assert_process_fault(scenario string) { if scenario == 'scriptlet-mode-failure' { assert process_fault.failures == 1 assert !process_fault.fail_scriptlet_mode } if scenario in ['pipe-first', 'pipe-second', 'fork-failure'] { assert process_fault.failures == 1, scenario assert process_fault.ordinal == 0 && !process_fault.fork_failure, scenario } } type ReferenceLogLine = fn (voidptr, u32, &u8) fn C.v_alpm_reference_log_install(voidptr, ReferenceLogLine, voidptr) voidptr fn C.v_alpm_reference_log_remove(voidptr, voidptr) fn C.v_alpm_test_reap_command() struct ExtensionTrace { root string logfile string mut: action_count int items []string interrupt bool reap_on_output bool disappear_hook bool close_hook_directory bool in_hook bool stage_fault string reference_handle &coracle.Handle = unsafe { nil } native_handle &engine.Handle = unsafe { nil } public_handle &facade.Handle = unsafe { nil } } fn c_log(context voidptr, level u32, message &u8) { mut trace := unsafe { &ExtensionTrace(context) } trace.observe_log(level, unsafe { cstring_to_vstring(message) }) } fn native_log(context voidptr, level engine.LogLevel, message string) { mut trace := unsafe { &ExtensionTrace(context) } trace.observe_log(u32(level), message) } fn public_log(context voidptr, level facade.LogLevel, message &u8) { mut trace := unsafe { &ExtensionTrace(context) } trace.observe_log(u32(level), unsafe { cstring_to_vstring(message) }) } fn public_event(context voidptr, event &facade.Event) { // the retained event union has the same ABI as the frozen C facade. c_event(context, unsafe { &coracle.Event(event) }) } fn (mut trace ExtensionTrace) observe_log(level u32, message string) { if trace.close_hook_directory && level == 4 && message.starts_with('parsing hook file ') && message.ends_with('30-read-dir.hook\n') { // close only this fixture's discovery descriptor to force readdir(3) to fail. target := os.join_path(trace.root, 'usr/share/libalpm/hooks') mut closed := false for name in os.ls('/proc/self/fd') or { assert false, err.msg() []string{} } { actual := os.readlink('/proc/self/fd/' + name) or { continue } if actual == target { assert C.close(i32(name.int())) == 0 closed = true break } } assert closed trace.close_hook_directory = false } if trace.disappear_hook && level == 4 && message.starts_with('parsing hook file ') && message.ends_with('30-vanish.hook\n') { path := os.join_path(trace.root, 'usr/share/libalpm/hooks/30-vanish.hook') os.rm(path) or { assert false, err.msg() } trace.disappear_hook = false } // scriptlet shell build settings and random staging paths have a separate scope. if level !in [u32(1), 2] && !(trace.in_hook && level == 4 && message.starts_with('executing "')) { return } trace.capture_actions() mut text := message.replace(trace.root, 'ROOT') if at := text.index('ROOT/tmp/alpm_') { start := at + 'ROOT/tmp/alpm_'.len mut end := start for end < text.len && text[end] !in [`/`, `\n`, ` `] { end++ } text = text[..start] + 'STAGE' + text[end..] } trace.items << 'log:${level}:' + text } fn (mut trace ExtensionTrace) damage_scriptlet_stage(line string) { if trace.stage_fault in scriptlet_modes() && (line.starts_with('pre-remove:') || line.starts_with('post-remove:')) { tmp := os.join_path(trace.root, 'tmp') names := os.ls(tmp) or { panic(err) } assert names.len == 1 info := os.stat(os.join_path(tmp, names[0], '.INSTALL')) or { panic(err) } trace.items << 'mode:${line.all_before(':')}:${info.mode & 0o7777:o}' } if !line.starts_with('pre-remove:') || trace.stage_fault !in ['scriptlet-cleanup', 'scriptlet-directory-cleanup'] { return } tmp := os.join_path(trace.root, 'tmp') names := os.ls(tmp) or { panic(err) } assert names.len == 1 && names[0].starts_with('alpm_') directory := os.join_path(tmp, names[0]) if trace.stage_fault == 'scriptlet-cleanup' { os.rm(os.join_path(directory, '.INSTALL')) or { panic(err) } } else { os.write_file(os.join_path(directory, 'extra'), 'kept') or { panic(err) } } trace.stage_fault = '' } fn c_event(context voidptr, event &coracle.Event) { mut trace := unsafe { &ExtensionTrace(context) } if unsafe { event.type_ } == .hook_run_start { trace.in_hook = true } if unsafe { event.type_ } == .hook_run_done { trace.in_hook = false } trace.capture_actions() match unsafe { event.type_ } { .transaction_start { trace.items << 'transaction:start' } .transaction_done { trace.items << 'transaction:done' } .package_operation_start { trace.items << 'remove:start' } .package_operation_done { trace.items << 'remove:done' } .hook_start { trace.items << 'hook:start:${int(unsafe { event.hook.when })}' } .hook_done { trace.items << 'hook:done:${int(unsafe { event.hook.when })}' } .hook_run_start, .hook_run_done { value := unsafe { event.hook_run } name := unsafe { cstring_to_vstring(value.name) } description := if value.desc == unsafe { nil } { '(null)' } else { unsafe { cstring_to_vstring(value.desc) } } phase := if unsafe { event.type_ } == .hook_run_start { 'start' } else { 'done' } trace.items << 'hook:${phase}:${name}:${description}:${value.position}:${value.total}' } .scriptlet_info { line := unsafe { cstring_to_vstring(event.scriptlet_info.line) } trace.items << 'output:' + line trace.damage_scriptlet_stage(line) if trace.reap_on_output && line.starts_with('pre-hook') { C.v_alpm_test_reap_command() } if trace.interrupt && line.starts_with('pre-remove:') { if trace.public_handle != unsafe { nil } { trace.public_handle.trans_interrupt() or { assert false, err.msg() } } else { trace.reference_handle.trans_interrupt() or { assert false, err.msg() } } } } else {} } } fn native_event(context voidptr, event engine.CommitEvent) { mut trace := unsafe { &ExtensionTrace(context) } if event.kind == .hook_run_start { trace.in_hook = true } if event.kind == .hook_run_done { trace.in_hook = false } trace.capture_actions() match event.kind { .transaction_start { trace.items << 'transaction:start' } .transaction_done { trace.items << 'transaction:done' } .package_remove_start { trace.items << 'remove:start' } .package_remove_done { trace.items << 'remove:done' } .hook_start { trace.items << 'hook:start:${int(event.when)}' } .hook_done { trace.items << 'hook:done:${int(event.when)}' } .hook_run_start, .hook_run_done { phase := if event.kind == .hook_run_start { 'start' } else { 'done' } description := if event.has_description { event.description } else { '(null)' } trace.items << 'hook:${phase}:${event.name}:${description}:${event.position}:${event.total}' } .scriptlet_info { trace.items << 'output:' + event.line trace.damage_scriptlet_stage(event.line) if trace.reap_on_output && event.line.starts_with('pre-hook') { C.v_alpm_test_reap_command() } if trace.interrupt && event.line.starts_with('pre-remove:') { assert trace.native_handle.interrupt_transaction_async() == 0 } } else {} } } fn hook_text(when string, kind string, targets []string, command string, extra string) string { return '[Trigger]\nOperation = Remove\nType = ${kind}\n' + targets.map('Target = ' + it).join('\n') + '\n[Action]\nWhen = ${when}\nExec = ${command}\n${extra}\n' } fn parser_cases() map[string]string { command := '/bin/sh -c "exit 0"' valid := hook_text('PreTransaction', 'Package', ['app'], command, 'AbortOnFail') return { 'parser-missing-all': '[Trigger]\n[Trigger]\n[Action]\n' 'parser-no-target': valid.replace('Target = app\n', '') 'parser-no-type': valid.replace('Type = Package\n', '') 'parser-no-operation': valid.replace('Operation = Remove\n', '') 'parser-no-exec': valid.replace('Exec = ${command}\n', '') 'parser-no-when': valid.replace('When = PreTransaction\n', '') 'parser-section': '[Unknown]\n' 'parser-no-section': 'Exec = /bin/sh\n' 'parser-trigger-option': '[Trigger]\nUnknown = value\n' 'parser-action-option': '[Action]\nUnknown = value\n' 'parser-unknown-no-value': '[Action]\nUnknown\n' 'parser-action-trigger-key': '[Action]\nType\n' 'parser-trigger-action-key': '[Trigger]\nWhen\n' 'parser-operation': valid.replace('Operation = Remove', 'Operation = Invalid') 'parser-when': valid.replace('When = PreTransaction', 'When = Invalid') 'parser-empty-type': valid.replace('Type = Package', 'Type =') 'parser-empty-operation': valid.replace('Operation = Remove', 'Operation =') 'parser-empty-when': valid.replace('When = PreTransaction', 'When =') 'parser-empty-target': valid.replace('Target = app', 'Target =') 'parser-exec-quote': valid.replace('Exec = ${command}', 'Exec = "unfinished') 'parser-exec-no-value': valid.replace('Exec = ${command}', 'Exec') 'parser-exec-overwrite-no-value': valid + 'Exec\n' 'parser-empty-exec': valid.replace('Exec = ${command}', 'Exec =') 'parser-empty-exec-unused': valid.replace('Exec = ${command}', 'Exec =').replace('Target = app', 'Target = absent') 'parser-quoted-empty-exec': valid.replace('Exec = ${command}', 'Exec = ""') 'parser-empty-exec-overwrite': valid.replace('Exec = ${command}', 'Exec =\nExec = ${command}') '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}') 'parser-overwrite-invalid': valid.replace('Type = Package', 'Type = Package\nType = Invalid') 'parser-long-description': valid + 'Description = ' + 'x'.repeat(4100) + '\n' 'parser-long-comment': valid + '#' + 'x'.repeat(4100) + '\n' 'parser-crlf': valid.replace('\n', '\r\n') 'parser-final-line': valid.trim_right('\n') } } fn discovery_directory(root string, scenario string) string { return match scenario { 'long-hook-directory' { root + '/' + 'long/'.repeat(1000) } 'long-hook-file' { hookfixtures.deep_directory(root) } else { '' } } } fn scriptlet_modes() map[string]int { return { 'scriptlet-mode-default': 0o644 'scriptlet-mode-private': 0o700 'scriptlet-mode-group': 0o750 'scriptlet-mode-executable': 0o755 'scriptlet-mode-setuid': 0o4755 'scriptlet-mode-setgid': 0o2750 'scriptlet-mode-sticky': 0o1755 } } fn fixture(runtime processfixtures.Runtime, base string, scenario string) ! { root := os.join_path(base, 'root') entry := os.join_path(base, 'db', 'local', 'app-1-1') runtime.install(root)! os.mkdir_all(entry)! os.write_file(os.join_path(base, 'db', 'local', 'ALPM_DB_VERSION'), '9\n')! os.write_file(os.join_path(entry, 'desc'), '%DESC%\nApplication\n\n')! os.write_file(os.join_path(entry, 'files'), '%FILES%\npayload\n\n')! os.write_file(os.join_path(root, 'payload'), 'payload')! low := os.join_path(root, 'usr', 'share', 'libalpm', 'hooks') high := os.join_path(root, 'etc', 'hooks') os.mkdir_all(low)! os.mkdir_all(high)! mut extra := '' mut command := '/bin/sh -c "printf \'pre-hook\\n\'"' if scenario in ['abort', 'ignore-failure'] { command = '/bin/sh -c "exit 9"' } if scenario == 'signal' { command = '/bin/sh -c "kill -TERM $$"' } if scenario in ['abort', 'signal', 'reaped-child'] { extra = 'AbortOnFail' } if scenario in ['pipe-first', 'pipe-second', 'fork-failure', 'chroot-failure', 'child-directory-failure'] { extra = 'AbortOnFail' } if scenario in ['missing-dependency', 'ignored-dependency'] { extra = 'Depends = missing>=2' } if scenario == 'missing-dependency' { extra += '\nAbortOnFail' } if scenario in ['targets', 'mixed-targets'] { command = '/bin/sh -c \'while IFS= read -r target; do printf "target:%s\\n" "$target"; done\'' extra = 'NeedsTargets' } if scenario == 'empty-description' { extra = 'Description =' } mut pre := hook_text('PreTransaction', 'Package', ['app', '*'], command, extra) if scenario == 'mixed-targets' { pre = '[Trigger]\nOperation=Remove\nType=Path\nTarget=payload\nTarget=payload\n' + pre } os.write_file(os.join_path(low, '10-pre.hook'), pre)! post := hook_text('PostTransaction', 'Path', ['payload'], '/bin/sh -c "printf \'post-hook\\n\'"', '') os.write_file(os.join_path(low, '20-post.hook'), post)! if text := parser_cases()[scenario] { os.write_file(os.join_path(low, '30-parser.hook'), text)! } if scenario == 'disappearing-hook' { os.write_file(os.join_path(low, '30-vanish.hook'), pre)! } if scenario == 'read-directory-failure' { os.write_file(os.join_path(low, '30-read-dir.hook'), pre)! } if scenario == 'broken-hook-link' { os.symlink('absent', os.join_path(low, '30-broken.hook'))! } if scenario == 'directory-hook' { os.mkdir(os.join_path(low, '30-directory.hook'))! } if scenario in ['file-hook-directory', 'missing-hook-directory'] { os.rmdir(high)! if scenario == 'file-hook-directory' { os.write_file(high, 'not a directory')! } } if scenario == 'invalid-override' { os.write_file(os.join_path(high, '10-pre.hook'), '[Unknown]\n')! } if scenario == 'long-hook-file' { deep := discovery_directory(root, scenario) os.mkdir_all(deep)! fd := C.open(unsafe { &char(deep.str) }, C.O_RDONLY | C.O_DIRECTORY | C.O_CLOEXEC) if fd < 0 { return os.last_error() } defer { if C.close(fd) != 0 { eprintln(os.last_error()) } } name := hookfixtures.long_filename() file := C.openat(fd, unsafe { &char(name.str) }, C.O_CREAT | C.O_WRONLY | C.O_CLOEXEC, 0o600) if file < 0 { return os.last_error() } if C.close(file) != 0 { return os.last_error() } } if scenario == 'mask' { os.symlink('/dev/null', os.join_path(high, '10-pre.hook'))! } if scenario == 'override' { os.write_file(os.join_path(high, '10-pre.hook'), hook_text('PreTransaction', 'Package', ['app'], '/bin/sh -c "printf \'override\\n\'"', 'Description = Override'))! } if scenario == 'negation' { os.write_file(os.join_path(low, '10-pre.hook'), hook_text('PreTransaction', 'Package', [ '*', '!app', ], command, ''))! } if scenario == 'malformed' { os.write_file(os.join_path(low, '30-invalid.hook'), '[Trigger]\nType = Invalid\n')! } if scenario == 'missing-exec' { os.write_file(os.join_path(low, '10-pre.hook'), hook_text('PreTransaction', 'Package', ['app'], '/missing', 'AbortOnFail'))! } if scenario == 'post-failure' { os.write_file(os.join_path(low, '20-post.hook'), hook_text('PostTransaction', 'Path', ['payload'], '/bin/sh -c "exit 8"', 'AbortOnFail'))! } if scenario in ['scriptlets', 'scriptlet-failure', 'scriptlet-tmp-blocked', 'scriptlet-disk-full', 'scriptlet-cleanup', 'scriptlet-directory-cleanup', 'no-scriptlet', 'db-only', 'no-hooks', 'interrupt-one', 'interrupt-two', 'scriptlet-mode-failure'] || scenario in scriptlet_modes() { contents := r'pre_remove() { printf "pre-remove:%s:" "$1"; test -e /payload && printf "present\\n"; } post_remove() { printf "post-remove:%s:" "$1"; if test -e /payload; then printf "present\\n"; else printf "absent\\n"; fi; } ' os.write_file(os.join_path(entry, 'install'), if scenario == 'scriptlet-failure' { contents + '\npre_remove() { printf "failure\\n"; return 4; }\n' } else { contents })! } if mode := scriptlet_modes()[scenario] { os.chmod(os.join_path(entry, 'install'), mode)! } if scenario == 'scriptlet-tmp-blocked' { os.write_file(os.join_path(root, 'tmp'), 'blocked')! } if scenario == 'scriptlet-disk-full' { tmp := os.join_path(root, 'tmp') os.mkdir_all(tmp)! signaturefixtures.command('mount', ['-t', 'tmpfs', '-o', 'size=4k,nr_inodes=64', 'tmpfs', tmp])! os.write_file(os.join_path(tmp, 'fill'), 'x'.repeat(4096))! } if scenario in ['ldconfig', 'interrupt-one', 'interrupt-two'] { os.mkdir_all(os.join_path(root, 'sbin'))! os.write_file(os.join_path(root, 'etc', 'ld.so.conf'), '')! os.write_file(os.join_path(root, 'sbin', 'ldconfig'), '#!/bin/sh\nprintf "ldconfig\\n"\n')! os.chmod(os.join_path(root, 'sbin', 'ldconfig'), 0o755)! os.mkdir_all(os.join_path(root, 'usr', 'bin'))! os.cp(os.join_path(root, 'sbin', 'ldconfig'), os.join_path(root, 'usr', 'bin', 'ldconfig'))! } if scenario == 'hook-removed' { os.write_file(os.join_path(entry, 'files'), '%FILES%\npayload\nusr/share/libalpm/hooks/20-post.hook\n\n')! } if scenario == 'interrupt-two' { later := os.join_path(base, 'db', 'local', 'later-1-1') os.mkdir_all(later)! os.write_file(os.join_path(later, 'desc'), '%DESC%\nLater\n\n')! os.write_file(os.join_path(later, 'files'), '%FILES%\nlater\n\n')! os.write_file(os.join_path(root, 'later'), 'later')! } } fn scriptlet_run_mask(scenario string) u32 { saved := C.umask(0o077) if scenario !in scriptlet_modes() { C.umask(saved) } return saved } fn run_reference(base string, scenario string, mut trace ExtensionTrace) !bool { mask := scriptlet_run_mask(scenario) defer { C.umask(mask) } handle := coracle.initialize(os.join_path(base, 'root'), os.join_path(base, 'db'))! defer { handle.release() or { eprintln(err) } } handle.option_add_hookdir(os.join_path(base, 'root', 'etc', 'hooks'))! handle.option_set_logfile(os.join_path(base, 'actions.log'))! trace.reference_handle = handle handle.option_set_eventcb(c_event, &trace)! log_state := C.v_alpm_reference_log_install(handle, c_log, &trace) defer { C.v_alpm_reference_log_remove(handle, log_state) } directory := discovery_directory(trace.root, scenario) if directory != '' { handle.option_add_hookdir(directory)! } if scenario == 'no-upgrade-trigger' { handle.option_add_noupgrade('payload')! } if scenario == 'no-extract-trigger' { handle.option_add_no_extract('payload')! } mut flags := coracle.trans_flag_0 if scenario == 'no-hooks' { flags |= .no_hooks } if scenario == 'no-scriptlet' { flags |= .no_scriptlet } if scenario == 'db-only' { flags |= .db_only } if scenario == 'interrupt-two' { flags |= .no_deps } handle.trans_init(flags)! defer { handle.trans_release() or { eprintln(err) } } db := handle.get_localdb()! pkg := db.get_pkg('app') or { return error('missing reference package') } handle.remove_pkg(pkg)! if scenario == 'interrupt-two' { handle.remove_pkg(db.get_pkg('later') or { return error('missing later fixture') })! } handle.trans_prepare()!.free() arm_process_fault(scenario) defer { assert_process_fault(scenario) } result := handle.trans_commit() or { assert handle.errno() == .trans_hook_failed return false } result.free() return true } fn run_native(base string, scenario string, mut trace ExtensionTrace) !bool { mask := scriptlet_run_mask(scenario) defer { C.umask(mask) } mut handle := engine.initialize(os.join_path(base, 'root'), os.join_path(base, 'db'))! defer { handle.release() or { eprintln(err) } } handle.add_string_list(.hook_dirs, os.join_path(base, 'root', 'etc', 'hooks'))! handle.set_string_option(.logfile, os.join_path(base, 'actions.log'))! trace.native_handle = handle handle.set_commit_callback(native_event, &trace)! handle.set_log_callback(native_log, &trace)! directory := discovery_directory(trace.root, scenario) if directory != '' { handle.add_string_list(.hook_dirs, directory)! } if scenario == 'no-upgrade-trigger' { handle.add_string_list(.no_upgrade, 'payload')! } if scenario == 'no-extract-trigger' { handle.add_string_list(.no_extract, 'payload')! } mut flags := engine.transaction_flag_0 if scenario == 'no-hooks' { flags |= .no_hooks } if scenario == 'no-scriptlet' { flags |= .no_scriptlet } if scenario == 'db-only' { flags |= .db_only } if scenario == 'interrupt-two' { flags |= .no_deps } handle.start_transaction(flags)! defer { handle.release_transaction() or { eprintln(err) } } mut db := handle.local_database()! pkg := db.get_pkg('app') or { return error('missing native package') } handle.remove_package(pkg)! if scenario == 'interrupt-two' { handle.remove_package(db.get_pkg('later') or { return error('missing later fixture') })! } assert handle.prepare_transaction()!.success arm_process_fault(scenario) defer { assert_process_fault(scenario) } handle.commit_transaction() or { assert err.code() == int(engine.Errno.trans_hook_failed) assert handle.transaction_state()! == .prepared return false } return true } fn run_public(base string, scenario string, mut trace ExtensionTrace) !bool { mask := scriptlet_run_mask(scenario) defer { C.umask(mask) } handle := facade.initialize(os.join_path(base, 'root'), os.join_path(base, 'db'))! defer { handle.release() or { eprintln(err) } } handle.option_add_hookdir(os.join_path(base, 'root', 'etc', 'hooks'))! handle.option_set_logfile(os.join_path(base, 'actions.log'))! trace.public_handle = handle handle.option_set_eventcb(public_event, &trace)! handle.option_set_logcb_line(public_log, &trace)! directory := discovery_directory(trace.root, scenario) if directory != '' { handle.option_add_hookdir(directory)! } if scenario == 'no-upgrade-trigger' { handle.option_add_noupgrade('payload')! } if scenario == 'no-extract-trigger' { handle.option_add_no_extract('payload')! } mut flags := facade.trans_flag_0 if scenario == 'no-hooks' { flags |= .no_hooks } if scenario == 'no-scriptlet' { flags |= .no_scriptlet } if scenario == 'db-only' { flags |= .db_only } if scenario == 'interrupt-two' { flags |= .no_deps } handle.trans_init(flags)! defer { handle.trans_release() or { eprintln(err) } } db := handle.get_localdb()! pkg := db.get_pkg('app') or { return error('missing public package') } handle.remove_pkg(pkg)! if scenario == 'interrupt-two' { later := db.get_pkg('later') or { return error('missing public later fixture') } handle.remove_pkg(later)! } handle.trans_prepare()!.free() arm_process_fault(scenario) defer { assert_process_fault(scenario) } result := handle.trans_commit() or { assert handle.errno() == .trans_hook_failed return false } result.free() return true } fn main() { run() or { eprintln(err) exit(1) } } fn run() ! { if os.args.len != 3 || os.readlink('/proc/self/ns/mnt')! == os.args[2] { return error('requires a private mount namespace') } assert os.setenv('LC_ALL', 'C', true) == 0 signaturefixtures.command('mount', ['--make-rprivate', '/'])! base := os.args[1] defer { hookfixtures.cleanup_long_paths(base) or { eprintln(err) } } runtime := processfixtures.create(os.join_path(base, 'runtime'))! mut scenarios := ['basic', 'targets', 'mask', 'override', 'negation', 'abort', 'ignore-failure', 'missing-dependency', 'ignored-dependency', 'malformed', 'missing-exec', 'post-failure', 'scriptlets', 'scriptlet-failure', 'no-scriptlet', 'db-only', 'no-hooks', 'ldconfig', 'interrupt-one', 'interrupt-two', 'no-upgrade-trigger', 'no-extract-trigger', 'empty-description', 'mixed-targets', 'hook-removed', 'signal', 'reaped-child'] mut parser_names := parser_cases().keys() parser_names.sort() scenarios << parser_names scenarios << ['disappearing-hook', 'broken-hook-link', 'directory-hook', 'file-hook-directory', 'missing-hook-directory', 'invalid-override', 'long-hook-directory', 'long-hook-file', 'read-directory-failure'] scenarios << ['pipe-first', 'pipe-second', 'fork-failure', 'chroot-failure', 'child-directory-failure'] scenarios << ['scriptlet-tmp-blocked', 'scriptlet-cleanup', 'scriptlet-directory-cleanup', 'scriptlet-disk-full'] scenarios << scriptlet_modes().keys().sorted() scenarios << 'scriptlet-mode-failure' for scenario in scenarios { old := os.join_path(base, scenario, 'old') native := os.join_path(base, scenario, 'native') fixture(runtime, old, scenario)! fixture(runtime, native, scenario)! 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' } 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' } expected.stage_fault = scenario actual.stage_fault = scenario source_success := run_reference(old, scenario, mut expected)! if scenario in scriptlet_modes() { assert expected.items.filter(it.starts_with('mode:')).len == 2 } native_fds := os.ls('/proc/self/fd')!.len native_success := run_native(native, scenario, mut actual)! assert os.ls('/proc/self/fd')!.len == native_fds, '${scenario}: native descriptor leak' assert native_success == source_success, '${scenario}: success ${native_success} != ${source_success}' expected.capture_actions() actual.capture_actions() if scenario == 'chroot-failure' { assert expected.items.contains('output:could not change the root directory (Operation not permitted)\n') } if scenario == 'child-directory-failure' { assert expected.items.contains('output:could not change directory to / (Permission denied)\n') } assert actual.items == expected.items, '${scenario}: ${actual.items} != ${expected.items}' public := os.join_path(base, scenario, 'public') fixture(runtime, public, scenario)! 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' } public_trace.stage_fault = scenario public_fds := os.ls('/proc/self/fd')!.len public_success := run_public(public, scenario, mut public_trace)! assert os.ls('/proc/self/fd')!.len == public_fds, '${scenario}: public descriptor leak' assert public_success == source_success, '${scenario}: public success ${public_success} != ${source_success}' public_trace.capture_actions() assert public_trace.items == expected.items, '${scenario}: public ${public_trace.items} != ${expected.items}' expected_log := action_records(os.join_path(old, 'actions.log'), os.join_path(old, 'root'))! actual_log := action_records(os.join_path(native, 'actions.log'), os.join_path(native, 'root'))! assert actual_log == expected_log, '${scenario}\nnative log: ${actual_log}\nreference log: ${expected_log}' assert action_records(public_trace.logfile, public_trace.root)! == expected_log, scenario if scenario in ['long-hook-directory', 'long-hook-file', 'disappearing-hook', 'read-directory-failure'] { assert !source_success, scenario prefix := match scenario { 'long-hook-directory' { 'could not open directory:' } 'long-hook-file' { 'could not open file:' } 'disappearing-hook' { 'error while reading hook ' } else { 'could not read directory:' } } assert expected.items.any(it.starts_with('log:1:' + prefix)), scenario } if scenario in ['ldconfig', 'interrupt-one'] { assert expected.items.contains('output:ldconfig\n') } if scenario == 'interrupt-two' { assert !expected.items.contains('output:ldconfig\n') } for path in ['root/payload', 'db/local/app-1-1', 'root/later', 'db/local/later-1-1'] { assert os.exists(os.join_path(native, path)) == os.exists(os.join_path(old, path)), '${scenario}: ${path}' assert os.exists(os.join_path(public, path)) == os.exists(os.join_path(old, path)), '${scenario}: public ${path}' } for path in [old, native, public] { if os.is_dir(os.join_path(path, 'root', 'tmp')) { if scenario == 'scriptlet-disk-full' { fill := os.join_path(path, 'root', 'tmp', 'fill') assert os.read_file(fill)!.len == 4096 os.rm(fill)! } if scenario == 'scriptlet-directory-cleanup' { tmp := os.join_path(path, 'root', 'tmp') left := os.ls(tmp)! assert left.len == 1 assert os.read_file(os.join_path(tmp, left[0], 'extra'))! == 'kept' os.rmdir_all(os.join_path(tmp, left[0]))! } assert os.ls(os.join_path(path, 'root', 'tmp'))!.len == 0 } assert !os.exists(os.join_path(path, 'db', 'db.lck')) } } println('${scenarios.len} core and ${scenarios.len} public/libalpm extension transactions verified in private chroots') } fn action_records(path string, root string) ![]string { if !os.exists(path) { return []string{} } return os.read_lines(path)!.map(it.all_after('] ').replace(root, 'ROOT')) } fn (mut trace ExtensionTrace) capture_actions() { lines := action_records(trace.logfile, trace.root) or { assert false, err.msg() return } assert lines.len >= trace.action_count for line in lines[trace.action_count..] { trace.items << 'action:' + line } trace.action_count = lines.len }