nspkg / engine / hook.v
462 lines · 446 sloc · 14.68 KB · c01b0795d1db56c7bce2539b2c46b110637fdc1a
Raw
1// discovery, trigger sets and execution order follow pacman hook.c and common/ini.c.
2// SPDX-License-Identifier: GPL-2.0-or-later
3module engine
4
5import os
6
7#include <limits.h>
8
9pub enum HookWhen {
10 unspecified
11 pre_transaction
12 post_transaction
13}
14
15enum HookTriggerType {
16 unspecified
17 package
18 path
19}
20
21struct HookTrigger {
22mut:
23 operations u8
24 kind HookTriggerType
25 targets []string
26}
27
28struct TransactionHook {
29mut:
30 name string
31 description string
32 has_description bool
33 triggers []HookTrigger
34 depends []string
35 command []string
36 when HookWhen
37 abort_on_fail bool
38 needs_targets bool
39 matches []string
40}
41
42// this is wordsplit's quoting grammar, not shell expansion or backslash escaping of spaces.
43fn hook_wordsplit(text string) ![]string {
44 mut result := []string{}
45 mut word := []u8{}
46 mut active := false
47 mut quote := u8(0)
48 mut index := 0
49 for index < text.len {
50 byte := text[index]
51 index++
52 if quote != 0 {
53 if byte == quote {
54 quote = 0
55 } else if byte == `\\` && index < text.len && text[index] == quote {
56 word << text[index]
57 index++
58 } else {
59 word << byte
60 }
61 } else if byte in [`'`, `"`] {
62 quote = byte
63 active = true
64 } else if byte.is_space() {
65 if active {
66 result << word.bytestr()
67 word.clear()
68 active = false
69 }
70 } else {
71 active = true
72 if byte == `\\` && index < text.len && text[index] in [`'`, `"`] {
73 word << text[index]
74 index++
75 } else {
76 word << byte
77 }
78 }
79 }
80 if quote != 0 { return error('unbalanced hook command quotes') }
81 if active { result << word.bytestr() }
82 return result
83}
84
85fn (mut handle Handle) hook_error(message string) IError {
86 handle.diagnostics << message.trim_right('\n')
87 handle.log(.error, message)
88 return error(message.trim_right('\n'))
89}
90
91fn (mut handle Handle) hook_warning(message string) {
92 handle.diagnostics << message.trim_right('\n')
93 handle.log(.warning, message)
94}
95
96// fgets(PATH_MAX) counts each bufferful as a line, including long-line fragments.
97fn hook_lines(text string) []string {
98 mut lines := []string{}
99 mut position := 0
100 for position < text.len {
101 mut end := int_min(position + int(C.PATH_MAX) - 1, text.len)
102 for index in position .. end {
103 if text[index] == `\n` {
104 end = index + 1
105 break
106 }
107 }
108 lines << text[position..end]
109 position = end
110 }
111 return lines
112}
113
114fn (mut handle Handle) parse_hook(path string, name string, text string) !TransactionHook {
115 if text.contains('\x00') { return handle.hook_error('hook ${path}: contains a NUL byte\n') }
116 mut hook := TransactionHook{ name: name }
117 mut section := ''
118 mut has_exec := false
119 for index, raw in hook_lines(text) {
120 line := raw.trim_space()
121 if line == '' || line.starts_with('#') { continue }
122 if line.starts_with('[') && line.ends_with(']') {
123 section = line[1..line.len - 1]
124 if section == 'Trigger' {
125 hook.triggers << HookTrigger{}
126 } else if section != 'Action' {
127 return handle.hook_error(localized_message('hook %s line %d: invalid section %s\n', path, index + 1, section))
128 }
129 continue
130 }
131 parts := line.split_nth('=', 2)
132 key := parts[0].trim_space()
133 value := if parts.len > 1 { parts[1].trim_space() } else { '' }
134 if section == '' {
135 return handle.hook_error(localized_message('hook %s line %d: invalid option %s\n', path, index + 1, key))
136 }
137 needs_value := (section == 'Trigger' && key in ['Operation', 'Type', 'Target']) || (section == 'Action' && key in [
138 'When',
139 'Description',
140 'Depends',
141 ])
142 if parts.len == 1 && needs_value {
143 // reject missing operands instead of invoking the source's NULL string operations.
144 return handle.hook_error(localized_message('hook %s line %d: invalid value %s\n', path, index + 1, '(null)'))
145 }
146 if section == 'Trigger' {
147 mut trigger := &hook.triggers[hook.triggers.len - 1]
148 match key {
149 'Operation' {
150 trigger.operations |= match value {
151 'Install' { u8(1) }
152 'Upgrade' { u8(2) }
153 'Remove' { u8(4) }
154 else {
155 return handle.hook_error(localized_message('hook %s line %d: invalid value %s\n', path, index + 1, value))
156 }
157 }
158 }
159 'Type' {
160 if trigger.kind != .unspecified {
161 handle.hook_warning(localized_message('hook %s line %d: overwriting previous definition of %s\n', path, index + 1, 'Type'))
162 }
163 trigger.kind = match value {
164 'Package' { HookTriggerType.package }
165 'Path' { HookTriggerType.path }
166 else {
167 return handle.hook_error(localized_message('hook %s line %d: invalid value %s\n', path, index + 1, value))
168 }
169 }
170 }
171 'Target' { trigger.targets << value }
172 else {
173 return handle.hook_error(localized_message('hook %s line %d: invalid option %s\n', path, index + 1, key))
174 }
175 }
176 } else if section == 'Action' {
177 match key {
178 'When' {
179 if hook.when != .unspecified {
180 handle.hook_warning(localized_message('hook %s line %d: overwriting previous definition of %s\n', path, index + 1, 'When'))
181 }
182 hook.when = match value {
183 'PreTransaction' { HookWhen.pre_transaction }
184 'PostTransaction' { HookWhen.post_transaction }
185 else {
186 return handle.hook_error(localized_message('hook %s line %d: invalid value %s\n', path, index + 1, value))
187 }
188 }
189 }
190 'Description' {
191 if hook.has_description {
192 handle.hook_warning(localized_message('hook %s line %d: overwriting previous definition of %s\n', path, index + 1, 'Description'))
193 }
194 hook.description = value
195 hook.has_description = true
196 }
197 'Depends' { hook.depends << value }
198 'AbortOnFail' { hook.abort_on_fail = true }
199 'NeedsTargets' { hook.needs_targets = true }
200 'Exec' {
201 if has_exec {
202 handle.hook_warning(localized_message('hook %s line %d: overwriting previous definition of %s\n', path, index + 1, 'Exec'))
203 }
204 if parts.len == 1 {
205 return handle.hook_error(localized_message('hook %s line %d: invalid value %s\n', path, index + 1, '(null)'))
206 }
207 hook.command = hook_wordsplit(value) or { return handle.hook_error(localized_message('hook %s line %d: invalid value %s\n', path, index + 1, value)) }
208 has_exec = true
209 }
210 else {
211 return handle.hook_error(localized_message('hook %s line %d: invalid option %s\n', path, index + 1, key))
212 }
213 }
214 }
215 }
216 // empty/triggerless files mask an identically named lower-priority hook.
217 if hook.triggers.len == 0 { return hook }
218 mut failed := false
219 for trigger in hook.triggers {
220 if trigger.targets.len == 0 {
221 handle.hook_error(localized_message('Missing trigger targets in hook: %s\n', path))
222 failed = true
223 }
224 if trigger.kind == .unspecified {
225 handle.hook_error(localized_message('Missing trigger type in hook: %s\n', path))
226 failed = true
227 }
228 if trigger.operations == 0 {
229 handle.hook_error(localized_message('Missing trigger operation in hook: %s\n', path))
230 failed = true
231 }
232 }
233 if !has_exec {
234 handle.hook_error(localized_message('Missing Exec option in hook: %s\n', path))
235 failed = true
236 }
237 if hook.when == .unspecified {
238 handle.hook_error(localized_message('Missing When option in hook: %s\n', path))
239 failed = true
240 } else if hook.abort_on_fail && hook.when == .post_transaction {
241 handle.hook_warning(localized_message('AbortOnFail set for PostTransaction hook: %s\n', path))
242 }
243 if failed { return error('incomplete hook: ${path}') }
244 return hook
245}
246
247fn (mut handle Handle) load_hooks() ([]TransactionHook, bool) {
248 mut hooks := []TransactionHook{}
249 mut seen := map[string]bool{}
250 mut failed := false
251 directories := handle.opts.lists[.hook_dirs]
252 for index := directories.len - 1; index >= 0; index-- {
253 directory := directories[index]
254 if directory.len >= int(C.PATH_MAX) {
255 reason := unsafe { cstring_to_vstring(C.strerror(C.ENAMETOOLONG)) }
256 handle.hook_error(localized_message('could not open directory: %s: %s\n', directory, reason))
257 failed = true
258 continue
259 }
260 dir := C.opendir(unsafe { &char(directory.str) })
261 if dir == unsafe { nil } {
262 if C.errno != C.ENOENT {
263 reason := os.last_error().msg()
264 handle.hook_error(localized_message('could not open directory: %s: %s\n', directory, reason))
265 failed = true
266 }
267 continue
268 }
269 for {
270 mut entry := &char(unsafe { nil })
271 status := C.v_alpm_storage_next(dir, &entry)
272 if status < 0 {
273 reason := os.last_error().msg()
274 handle.hook_error(localized_message('could not read directory: %s: %s\n', directory, reason))
275 failed = true
276 break
277 }
278 if status == 0 { break }
279 name := unsafe { cstring_to_vstring(entry) }
280 if name in ['.', '..'] { continue }
281 path := directory + name
282 if path.len >= int(C.PATH_MAX) {
283 reason := unsafe { cstring_to_vstring(C.strerror(C.ENAMETOOLONG)) }
284 handle.hook_error(localized_message('could not open file: %s: %s\n', path, reason))
285 failed = true
286 continue
287 }
288 if !name.ends_with('.hook') {
289 handle.log(.debug, 'skipping non-hook file ${path}\n')
290 continue
291 }
292 if name in seen {
293 handle.log(.debug, 'skipping overridden hook ${path}\n')
294 continue
295 }
296 info := os.stat(path) or {
297 handle.hook_error(localized_message('could not stat file %s: %s\n', path, err.msg()))
298 failed = true
299 continue
300 }
301 if info.mode & 0o170000 == 0o040000 {
302 handle.log(.debug, 'skipping directory ${path}\n')
303 continue
304 }
305 if info.mode & 0o170000 != 0o100000 && os.real_path(path) != '/dev/null' {
306 handle.hook_error('hook is not a regular file: ${path}\n')
307 failed = true
308 continue
309 }
310 handle.log(.debug, 'parsing hook file ${path}\n')
311 text := os.read_file(path) or {
312 // read_file can add context; hook.c exposes only strerror(errno).
313 reason := if err.code() > 0 {
314 unsafe { cstring_to_vstring(C.strerror(i32(err.code()))) }
315 } else {
316 err.msg()
317 }
318 handle.hook_error(localized_message('error while reading hook %s: %s\n', path, reason))
319 handle.log(.debug, 'parsing hook file ${path} failed\n')
320 failed = true
321 continue
322 }
323 hook := handle.parse_hook(path, name, text) or {
324 handle.log(.debug, 'parsing hook file ${path} failed\n')
325 failed = true
326 continue
327 }
328 seen[name] = true
329 hooks << hook
330 }
331 if C.closedir(dir) != 0 {
332 handle.diagnostics << 'could not close hook directory: ${os.last_error().msg()}'
333 }
334 }
335 hooks.sort(a.name[..a.name.len - 5] < b.name[..b.name.len - 5])
336 return hooks, failed
337}
338
339fn (mut hook TransactionHook) match_path_trigger(trans &Transaction, trigger HookTrigger, no_extract []string) bool {
340 mut installing := map[string]bool{}
341 mut removing := map[string]bool{}
342 // A path in both sets is an upgrade. When both possible operations are requested,
343 // hooks without NeedsTargets can stop before building the rest of the sets.
344 any_added := !hook.needs_targets && trigger.operations & 3 == 3
345 any_removed := !hook.needs_targets && trigger.operations & 6 == 6
346 for pkg in trans.add {
347 for file in pkg.files {
348 if match_stored_patterns(no_extract, file.name) != 0
349 && match_stored_patterns(trigger.targets, file.name) == 0 {
350 if any_added { return true }
351 installing[file.name] = true
352 }
353 }
354 if pkg.old_package != unsafe { nil } {
355 for file in pkg.old_package.files {
356 if match_stored_patterns(trigger.targets, file.name) == 0 {
357 if any_removed { return true }
358 removing[file.name] = true
359 }
360 }
361 }
362 }
363 for pkg in trans.remove {
364 for file in pkg.files {
365 if match_stored_patterns(trigger.targets, file.name) == 0 {
366 if any_removed { return true }
367 removing[file.name] = true
368 }
369 }
370 }
371 start := hook.matches.len
372 for name, _ in installing {
373 operation := if name in removing { u8(2) } else { u8(1) }
374 if trigger.operations & operation != 0 {
375 if !hook.needs_targets { return true }
376 hook.matches << name
377 }
378 }
379 if trigger.operations & 4 != 0 {
380 for name, _ in removing {
381 if name !in installing {
382 if !hook.needs_targets { return true }
383 hook.matches << name
384 }
385 }
386 }
387 return hook.matches.len > start
388}
389
390fn (mut hook TransactionHook) triggered(trans &Transaction, no_extract []string) bool {
391 hook.matches.clear()
392 for trigger in hook.triggers {
393 if trigger.kind == .package {
394 for pkg in trans.add {
395 operation := if pkg.old_package == unsafe { nil } { u8(1) } else { u8(2) }
396 if trigger.operations & operation != 0 && match_stored_patterns(trigger.targets, pkg.name) == 0 {
397 if !hook.needs_targets { return true }
398 hook.matches << pkg.name
399 }
400 }
401 if trigger.operations & 4 != 0 {
402 for pkg in trans.remove {
403 if find_package(trans.add, pkg.name) == none && match_stored_patterns(trigger.targets, pkg.name) == 0 {
404 if !hook.needs_targets { return true }
405 hook.matches << pkg.name
406 }
407 }
408 }
409 } else if hook.match_path_trigger(trans, trigger, no_extract) && !hook.needs_targets {
410 return true
411 }
412 }
413 if hook.matches.len < 2 { return hook.matches.len == 1 }
414 hook.matches.sort()
415 mut unique := 1
416 for index in 1 .. hook.matches.len {
417 if hook.matches[index] != hook.matches[unique - 1] {
418 hook.matches[unique] = hook.matches[index]
419 unique++
420 }
421 }
422 hook.matches.trim(unique)
423 return true
424}
425
426fn (mut handle Handle) run_hooks(mut root RootFilesystem, trans &Transaction, when HookWhen) ! {
427 mut hooks, mut failed := handle.load_hooks()
428 if failed && when == .pre_transaction { return error('could not load transaction hooks') }
429 mut triggered := []TransactionHook{}
430 for mut hook in hooks {
431 if hook.when == when && hook.triggered(trans, handle.opts.lists[.no_extract]) {
432 triggered << hook
433 }
434 }
435 if triggered.len == 0 { return }
436 handle.commit_event(CommitEvent{ kind: .hook_start, when: when })
437 defer { handle.commit_event(CommitEvent{ kind: .hook_done, when: when }) }
438 for index, hook in triggered {
439 handle.record_action("running '${hook.name}'...\n")
440 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 }
441 handle.commit_event(event)
442 handle.run_hook(mut root, &hook) or {
443 handle.diagnostics << 'hook ${hook.name}: ${err.msg()}'
444 if hook.abort_on_fail { failed = true }
445 }
446 handle.commit_event(CommitEvent{ ...event, kind: .hook_run_done })
447 if failed && when == .pre_transaction { return error('pre-transaction hook failed') }
448 }
449 if failed { return error('transaction hooks failed') }
450}
451
452fn (mut handle Handle) run_hook(mut root RootFilesystem, hook &TransactionHook) ! {
453 for dependency in hook.depends {
454 if find_satisfier(handle.local.packages, dep_from_string(dependency)) == none {
455 handle.hook_error(localized_message('unable to run hook %s: %s\n', hook.name, Errno.unsatisfied_deps.strerror()))
456 return error('could not satisfy dependency ${dependency}')
457 }
458 }
459 input := if hook.needs_targets { (hook.matches.join('\n') + '\n').bytes() } else { []u8{} }
460 command := if hook.command.len > 0 { hook.command[0] } else { '' }
461 handle.run_chroot_command(mut root, command, hook.command, input)!
462}
463