| 1 | // the parent owns callbacks and cache writes; the child owns only the transfer. |
| 2 | // SPDX-License-Identifier: GPL-2.0-or-later |
| 3 | module engine |
| 4 | |
| 5 | import os |
| 6 | |
| 7 | struct SandboxOutcome { |
| 8 | report DownloadReport |
| 9 | failure string |
| 10 | signal i32 |
| 11 | interrupted bool |
| 12 | } |
| 13 | |
| 14 | fn (mut handle Handle) download_sandboxed(requests []DownloadRequest, directory string) !DownloadReport { |
| 15 | username := handle.opts.strings[.sandbox_user] |
| 16 | account := C.getpwnam(unsafe { &char(username.str) }) |
| 17 | if account == unsafe { nil } { |
| 18 | return handle.fail(.retrieve_prepare, 'sandbox user does not exist: ${username}') |
| 19 | } |
| 20 | mut stage := create_sandbox_stage(directory, account.pw_uid, account.pw_gid) or { return handle.fail(.retrieve_prepare, err.msg()) } |
| 21 | mut finalized := false |
| 22 | mut child_signal := i32(0) |
| 23 | defer { |
| 24 | if !finalized { |
| 25 | stage.finalize() or { handle.diagnostics << 'could not restore sandbox downloads: ${err.msg()}' } |
| 26 | } |
| 27 | stage.cleanup() or { handle.diagnostics << 'could not remove download sandbox ${stage.directory}: ${err.msg()}' } |
| 28 | handle.diagnostics << stage.diagnostics |
| 29 | if child_signal in [C.SIGINT, C.SIGQUIT] { C.kill(C.getpid(), child_signal) } |
| 30 | } |
| 31 | stage.prepare(requests) or { return handle.fail(.retrieve_prepare, err.msg()) } |
| 32 | mut report := DownloadReport{} |
| 33 | mut failure := '' |
| 34 | mut failure_code := Errno.retrieve |
| 35 | if voidptr(handle.fetch_callback) != unsafe { nil } { |
| 36 | // fetch callbacks are trusted caller code, and run in the parent as in dload.c. |
| 37 | report = handle.download_with_fetch_callback(stage.requests, stage.directory, stage.parent) or { |
| 38 | failure = err.msg() |
| 39 | failure_code = unsafe { Errno(err.code()) } |
| 40 | DownloadReport{} |
| 41 | } |
| 42 | } else { |
| 43 | outcome := handle.run_download_worker(stage) or { return handle.fail(.retrieve_prepare, err.msg()) } |
| 44 | report = outcome.report |
| 45 | failure = outcome.failure |
| 46 | child_signal = outcome.signal |
| 47 | if outcome.interrupted { failure_code = .trans_abort } |
| 48 | } |
| 49 | finalized = true |
| 50 | stage.finalize() or { |
| 51 | if failure == '' { return handle.fail(.retrieve, err.msg()) } |
| 52 | handle.diagnostics << 'could not restore sandbox downloads: ${err.msg()}' |
| 53 | } |
| 54 | if failure != '' { return handle.fail(failure_code, failure) } |
| 55 | return DownloadReport{ updated: report.updated, files: report.files.map(DownloadFile{ ...it, path: os.join_path(directory, os.file_name(it.path)) }) } |
| 56 | } |
| 57 | |