// discovery, trigger sets and execution order follow pacman hook.c and common/ini.c. // SPDX-License-Identifier: GPL-2.0-or-later module engine import os #include pub enum HookWhen { unspecified pre_transaction post_transaction } enum HookTriggerType { unspecified package path } struct HookTrigger { mut: operations u8 kind HookTriggerType targets []string } struct TransactionHook { mut: name string description string has_description bool triggers []HookTrigger depends []string command []string when HookWhen abort_on_fail bool needs_targets bool matches []string } // this is wordsplit's quoting grammar, not shell expansion or backslash escaping of spaces. fn hook_wordsplit(text string) ![]string { mut result := []string{} mut word := []u8{} mut active := false mut quote := u8(0) mut index := 0 for index < text.len { byte := text[index] index++ if quote != 0 { if byte == quote { quote = 0 } else if byte == `\\` && index < text.len && text[index] == quote { word << text[index] index++ } else { word << byte } } else if byte in [`'`, `"`] { quote = byte active = true } else if byte.is_space() { if active { result << word.bytestr() word.clear() active = false } } else { active = true if byte == `\\` && index < text.len && text[index] in [`'`, `"`] { word << text[index] index++ } else { word << byte } } } if quote != 0 { return error('unbalanced hook command quotes') } if active { result << word.bytestr() } return result } fn (mut handle Handle) hook_error(message string) IError { handle.diagnostics << message.trim_right('\n') handle.log(.error, message) return error(message.trim_right('\n')) } fn (mut handle Handle) hook_warning(message string) { handle.diagnostics << message.trim_right('\n') handle.log(.warning, message) } // fgets(PATH_MAX) counts each bufferful as a line, including long-line fragments. fn hook_lines(text string) []string { mut lines := []string{} mut position := 0 for position < text.len { mut end := int_min(position + int(C.PATH_MAX) - 1, text.len) for index in position .. end { if text[index] == `\n` { end = index + 1 break } } lines << text[position..end] position = end } return lines } fn (mut handle Handle) parse_hook(path string, name string, text string) !TransactionHook { if text.contains('\x00') { return handle.hook_error('hook ${path}: contains a NUL byte\n') } mut hook := TransactionHook{ name: name } mut section := '' mut has_exec := false for index, raw in hook_lines(text) { line := raw.trim_space() if line == '' || line.starts_with('#') { continue } if line.starts_with('[') && line.ends_with(']') { section = line[1..line.len - 1] if section == 'Trigger' { hook.triggers << HookTrigger{} } else if section != 'Action' { return handle.hook_error(localized_message('hook %s line %d: invalid section %s\n', path, index + 1, section)) } continue } parts := line.split_nth('=', 2) key := parts[0].trim_space() value := if parts.len > 1 { parts[1].trim_space() } else { '' } if section == '' { return handle.hook_error(localized_message('hook %s line %d: invalid option %s\n', path, index + 1, key)) } needs_value := (section == 'Trigger' && key in ['Operation', 'Type', 'Target']) || (section == 'Action' && key in [ 'When', 'Description', 'Depends', ]) if parts.len == 1 && needs_value { // reject missing operands instead of invoking the source's NULL string operations. return handle.hook_error(localized_message('hook %s line %d: invalid value %s\n', path, index + 1, '(null)')) } if section == 'Trigger' { mut trigger := &hook.triggers[hook.triggers.len - 1] match key { 'Operation' { trigger.operations |= match value { 'Install' { u8(1) } 'Upgrade' { u8(2) } 'Remove' { u8(4) } else { return handle.hook_error(localized_message('hook %s line %d: invalid value %s\n', path, index + 1, value)) } } } 'Type' { if trigger.kind != .unspecified { handle.hook_warning(localized_message('hook %s line %d: overwriting previous definition of %s\n', path, index + 1, 'Type')) } trigger.kind = match value { 'Package' { HookTriggerType.package } 'Path' { HookTriggerType.path } else { return handle.hook_error(localized_message('hook %s line %d: invalid value %s\n', path, index + 1, value)) } } } 'Target' { trigger.targets << value } else { return handle.hook_error(localized_message('hook %s line %d: invalid option %s\n', path, index + 1, key)) } } } else if section == 'Action' { match key { 'When' { if hook.when != .unspecified { handle.hook_warning(localized_message('hook %s line %d: overwriting previous definition of %s\n', path, index + 1, 'When')) } hook.when = match value { 'PreTransaction' { HookWhen.pre_transaction } 'PostTransaction' { HookWhen.post_transaction } else { return handle.hook_error(localized_message('hook %s line %d: invalid value %s\n', path, index + 1, value)) } } } 'Description' { if hook.has_description { handle.hook_warning(localized_message('hook %s line %d: overwriting previous definition of %s\n', path, index + 1, 'Description')) } hook.description = value hook.has_description = true } 'Depends' { hook.depends << value } 'AbortOnFail' { hook.abort_on_fail = true } 'NeedsTargets' { hook.needs_targets = true } 'Exec' { if has_exec { handle.hook_warning(localized_message('hook %s line %d: overwriting previous definition of %s\n', path, index + 1, 'Exec')) } if parts.len == 1 { return handle.hook_error(localized_message('hook %s line %d: invalid value %s\n', path, index + 1, '(null)')) } hook.command = hook_wordsplit(value) or { return handle.hook_error(localized_message('hook %s line %d: invalid value %s\n', path, index + 1, value)) } has_exec = true } else { return handle.hook_error(localized_message('hook %s line %d: invalid option %s\n', path, index + 1, key)) } } } } // empty/triggerless files mask an identically named lower-priority hook. if hook.triggers.len == 0 { return hook } mut failed := false for trigger in hook.triggers { if trigger.targets.len == 0 { handle.hook_error(localized_message('Missing trigger targets in hook: %s\n', path)) failed = true } if trigger.kind == .unspecified { handle.hook_error(localized_message('Missing trigger type in hook: %s\n', path)) failed = true } if trigger.operations == 0 { handle.hook_error(localized_message('Missing trigger operation in hook: %s\n', path)) failed = true } } if !has_exec { handle.hook_error(localized_message('Missing Exec option in hook: %s\n', path)) failed = true } if hook.when == .unspecified { handle.hook_error(localized_message('Missing When option in hook: %s\n', path)) failed = true } else if hook.abort_on_fail && hook.when == .post_transaction { handle.hook_warning(localized_message('AbortOnFail set for PostTransaction hook: %s\n', path)) } if failed { return error('incomplete hook: ${path}') } return hook } fn (mut handle Handle) load_hooks() ([]TransactionHook, bool) { mut hooks := []TransactionHook{} mut seen := map[string]bool{} mut failed := false directories := handle.opts.lists[.hook_dirs] for index := directories.len - 1; index >= 0; index-- { directory := directories[index] if directory.len >= int(C.PATH_MAX) { reason := unsafe { cstring_to_vstring(C.strerror(C.ENAMETOOLONG)) } handle.hook_error(localized_message('could not open directory: %s: %s\n', directory, reason)) failed = true continue } dir := C.opendir(unsafe { &char(directory.str) }) if dir == unsafe { nil } { if C.errno != C.ENOENT { reason := os.last_error().msg() handle.hook_error(localized_message('could not open directory: %s: %s\n', directory, reason)) failed = true } continue } for { mut entry := &char(unsafe { nil }) status := C.v_alpm_storage_next(dir, &entry) if status < 0 { reason := os.last_error().msg() handle.hook_error(localized_message('could not read directory: %s: %s\n', directory, reason)) failed = true break } if status == 0 { break } name := unsafe { cstring_to_vstring(entry) } if name in ['.', '..'] { continue } path := directory + name if path.len >= int(C.PATH_MAX) { reason := unsafe { cstring_to_vstring(C.strerror(C.ENAMETOOLONG)) } handle.hook_error(localized_message('could not open file: %s: %s\n', path, reason)) failed = true continue } if !name.ends_with('.hook') { handle.log(.debug, 'skipping non-hook file ${path}\n') continue } if name in seen { handle.log(.debug, 'skipping overridden hook ${path}\n') continue } info := os.stat(path) or { handle.hook_error(localized_message('could not stat file %s: %s\n', path, err.msg())) failed = true continue } if info.mode & 0o170000 == 0o040000 { handle.log(.debug, 'skipping directory ${path}\n') continue } if info.mode & 0o170000 != 0o100000 && os.real_path(path) != '/dev/null' { handle.hook_error('hook is not a regular file: ${path}\n') failed = true continue } handle.log(.debug, 'parsing hook file ${path}\n') text := os.read_file(path) or { // read_file can add context; hook.c exposes only strerror(errno). reason := if err.code() > 0 { unsafe { cstring_to_vstring(C.strerror(i32(err.code()))) } } else { err.msg() } handle.hook_error(localized_message('error while reading hook %s: %s\n', path, reason)) handle.log(.debug, 'parsing hook file ${path} failed\n') failed = true continue } hook := handle.parse_hook(path, name, text) or { handle.log(.debug, 'parsing hook file ${path} failed\n') failed = true continue } seen[name] = true hooks << hook } if C.closedir(dir) != 0 { handle.diagnostics << 'could not close hook directory: ${os.last_error().msg()}' } } hooks.sort(a.name[..a.name.len - 5] < b.name[..b.name.len - 5]) return hooks, failed } fn (mut hook TransactionHook) match_path_trigger(trans &Transaction, trigger HookTrigger, no_extract []string) bool { mut installing := map[string]bool{} mut removing := map[string]bool{} // A path in both sets is an upgrade. When both possible operations are requested, // hooks without NeedsTargets can stop before building the rest of the sets. any_added := !hook.needs_targets && trigger.operations & 3 == 3 any_removed := !hook.needs_targets && trigger.operations & 6 == 6 for pkg in trans.add { for file in pkg.files { if match_stored_patterns(no_extract, file.name) != 0 && match_stored_patterns(trigger.targets, file.name) == 0 { if any_added { return true } installing[file.name] = true } } if pkg.old_package != unsafe { nil } { for file in pkg.old_package.files { if match_stored_patterns(trigger.targets, file.name) == 0 { if any_removed { return true } removing[file.name] = true } } } } for pkg in trans.remove { for file in pkg.files { if match_stored_patterns(trigger.targets, file.name) == 0 { if any_removed { return true } removing[file.name] = true } } } start := hook.matches.len for name, _ in installing { operation := if name in removing { u8(2) } else { u8(1) } if trigger.operations & operation != 0 { if !hook.needs_targets { return true } hook.matches << name } } if trigger.operations & 4 != 0 { for name, _ in removing { if name !in installing { if !hook.needs_targets { return true } hook.matches << name } } } return hook.matches.len > start } fn (mut hook TransactionHook) triggered(trans &Transaction, no_extract []string) bool { hook.matches.clear() for trigger in hook.triggers { if trigger.kind == .package { for pkg in trans.add { operation := if pkg.old_package == unsafe { nil } { u8(1) } else { u8(2) } if trigger.operations & operation != 0 && match_stored_patterns(trigger.targets, pkg.name) == 0 { if !hook.needs_targets { return true } hook.matches << pkg.name } } if trigger.operations & 4 != 0 { for pkg in trans.remove { if find_package(trans.add, pkg.name) == none && match_stored_patterns(trigger.targets, pkg.name) == 0 { if !hook.needs_targets { return true } hook.matches << pkg.name } } } } else if hook.match_path_trigger(trans, trigger, no_extract) && !hook.needs_targets { return true } } if hook.matches.len < 2 { return hook.matches.len == 1 } hook.matches.sort() mut unique := 1 for index in 1 .. hook.matches.len { if hook.matches[index] != hook.matches[unique - 1] { hook.matches[unique] = hook.matches[index] unique++ } } hook.matches.trim(unique) return true } fn (mut handle Handle) run_hooks(mut root RootFilesystem, trans &Transaction, when HookWhen) ! { mut hooks, mut failed := handle.load_hooks() if failed && when == .pre_transaction { return error('could not load transaction hooks') } mut triggered := []TransactionHook{} for mut hook in hooks { if hook.when == when && hook.triggered(trans, handle.opts.lists[.no_extract]) { triggered << hook } } if triggered.len == 0 { return } handle.commit_event(CommitEvent{ kind: .hook_start, when: when }) defer { handle.commit_event(CommitEvent{ kind: .hook_done, when: when }) } for index, hook in triggered { handle.record_action("running '${hook.name}'...\n") event := CommitEvent{ kind: .hook_run_start, when: when, name: hook.name, description: hook.description, has_description: hook.has_description, position: index + 1, total: triggered.len } handle.commit_event(event) handle.run_hook(mut root, &hook) or { handle.diagnostics << 'hook ${hook.name}: ${err.msg()}' if hook.abort_on_fail { failed = true } } handle.commit_event(CommitEvent{ ...event, kind: .hook_run_done }) if failed && when == .pre_transaction { return error('pre-transaction hook failed') } } if failed { return error('transaction hooks failed') } } fn (mut handle Handle) run_hook(mut root RootFilesystem, hook &TransactionHook) ! { for dependency in hook.depends { if find_satisfier(handle.local.packages, dep_from_string(dependency)) == none { handle.hook_error(localized_message('unable to run hook %s: %s\n', hook.name, Errno.unsatisfied_deps.strerror())) return error('could not satisfy dependency ${dependency}') } } input := if hook.needs_targets { (hook.matches.join('\n') + '\n').bytes() } else { []u8{} } command := if hook.command.len > 0 { hook.command[0] } else { '' } handle.run_chroot_command(mut root, command, hook.command, input)! }