ic-host-process 0.27.4

Native process observations, admitted execution and Git provenance
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
use super::{
    CompletedExecution, ExecutionContext, ExecutionError, ExecutionEvidence, ExecutionFailure,
    ExecutionOperation, OutputLimit, OutputLimits, OutputStream, SuccessfulExit,
};
use crate::child::{CleanupPolicy, OwnedChild};
use ic_host_artifacts::artifact::buffer::reserve_bounded;
use rustix::fs::{OFlags, fcntl_getfl, fcntl_setfl};
use std::{
    ffi::OsString,
    io::{self, BufReader, Read, Write},
    os::fd::AsFd,
    panic::{AssertUnwindSafe, catch_unwind, resume_unwind},
    path::Path,
    process::{ChildStdout, Command, ExitStatus, Stdio},
    time::{Duration, Instant},
};

#[cfg(test)]
mod tests;

const POLL_INTERVAL: Duration = Duration::from_millis(2);

#[derive(Clone, Copy)]
pub(super) enum CleanupScope {
    DirectChild,
    ProcessGroup {
        cleanup: CleanupPolicy,
        deadline: Option<Instant>,
    },
}

pub(super) fn capture(
    path: &Path,
    arguments: &[OsString],
    context: &ExecutionContext<'_>,
    limits: OutputLimits,
) -> Result<CompletedExecution, ExecutionError> {
    let mut command = Command::new(path);
    command
        .args(arguments)
        .current_dir(context.current_dir)
        .env_clear()
        .envs(context.environment.iter().map(|(key, value)| (key, value)));
    capture_command(
        &mut command,
        limits,
        CleanupScope::DirectChild,
        true,
        || false,
    )
}

pub(super) fn capture_command(
    command: &mut Command,
    mut limits: OutputLimits,
    scope: CleanupScope,
    capture_output: bool,
    mut cancelled: impl FnMut() -> bool,
) -> Result<CompletedExecution, ExecutionError> {
    let started = Instant::now();
    let deadline = match scope {
        CleanupScope::DirectChild => None,
        CleanupScope::ProcessGroup { deadline, .. } => deadline,
    };
    let failure = if cancelled() {
        Some(ExecutionFailure::Cancelled)
    } else if deadline.is_some_and(|deadline| deadline <= Instant::now()) {
        Some(ExecutionFailure::TimedOut)
    } else {
        None
    };
    if let Some(failure) = failure {
        return Err(ExecutionError {
            failure,
            evidence: ExecutionEvidence::default(),
            cleanup: None,
        });
    }
    if let Some(deadline) = deadline {
        let remaining = deadline.saturating_duration_since(started);
        limits.timeout = Some(
            limits
                .timeout
                .map_or(remaining, |timeout| timeout.min(remaining)),
        );
    }
    if capture_output {
        command
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());
    }
    let spawned = match scope {
        CleanupScope::DirectChild => OwnedChild::spawn_direct(command),
        CleanupScope::ProcessGroup { cleanup, .. } => OwnedChild::spawn(command, cleanup),
    };
    let mut child = spawned.map_err(|source| ExecutionError {
        failure: io_failure(ExecutionOperation::Spawn, source),
        evidence: ExecutionEvidence::default(),
        cleanup: None,
    })?;
    let stdout = child.take_stdout().map(BufReader::new);
    exchange(
        &mut child,
        stdout,
        false,
        None,
        limits,
        started,
        SuccessfulExit::Cleanup,
        cancelled,
        |_, _| Ok(()),
    )
}

pub(super) fn communicate(
    child: &mut OwnedChild,
    input: Option<&[u8]>,
    limits: OutputLimits,
    successful_exit: SuccessfulExit,
    cancelled: impl FnMut() -> bool,
    output: impl FnMut(OutputStream, &[u8]) -> io::Result<()>,
) -> Result<CompletedExecution, ExecutionError> {
    let stdout = child.take_stdout().map(BufReader::new);
    exchange(
        child,
        stdout,
        false,
        input,
        limits,
        Instant::now(),
        successful_exit,
        cancelled,
        output,
    )
}

pub(super) fn drain_output(
    child: &mut OwnedChild,
    stdout: Option<BufReader<ChildStdout>>,
    limits: OutputLimits,
    cancelled: impl FnMut() -> bool,
) -> Result<CompletedExecution, ExecutionError> {
    let stdout = stdout.or_else(|| child.take_stdout().map(BufReader::new));
    exchange(
        child,
        stdout,
        true,
        None,
        limits,
        Instant::now(),
        SuccessfulExit::Cleanup,
        cancelled,
        |_, _| Ok(()),
    )
}

#[expect(
    clippy::too_many_arguments,
    reason = "one capture engine retains caller IO and ownership disposition"
)]
fn exchange(
    child: &mut OwnedChild,
    mut stdout: Option<BufReader<ChildStdout>>,
    allow_reaped: bool,
    input: Option<&[u8]>,
    limits: OutputLimits,
    started: Instant,
    successful_exit: SuccessfulExit,
    mut cancelled: impl FnMut() -> bool,
    mut output: impl FnMut(OutputStream, &[u8]) -> io::Result<()>,
) -> Result<CompletedExecution, ExecutionError> {
    let timeout = limits.timeout;
    let mut evidence = ExecutionEvidence::default();
    let mut stdin = child.take_stdin();
    let mut stderr = child.take_stderr();
    // Resume the original panic after closing pipes and attempting cleanup.
    // The borrowed owner can outlive a caller's catch_unwind, so its Drop alone
    // cannot guarantee cleanup here. No callback is reused after unwinding.
    let result = catch_unwind(AssertUnwindSafe(|| {
        let admitted = child.is_owned()
            || (allow_reaped
                && child
                    .try_wait()
                    .map_err(|source| io_failure(ExecutionOperation::Wait, source))?
                    .is_some());
        if !admitted {
            return Err(io_failure(
                ExecutionOperation::Wait,
                io::ErrorKind::InvalidInput.into(),
            ));
        }
        if input.is_some() && stdin.is_none() {
            return Err(io_failure(
                ExecutionOperation::StdinPipe,
                io::ErrorKind::BrokenPipe.into(),
            ));
        }
        let mut remaining = input.unwrap_or_default();
        if remaining.is_empty() {
            drop(stdin.take());
        }
        stdin.as_ref().map(nonblocking).transpose()?;
        stdout
            .as_ref()
            .map(|reader| nonblocking(reader.get_ref()))
            .transpose()?;
        stderr.as_ref().map(nonblocking).transpose()?;
        loop {
            if cancelled() {
                return Err(ExecutionFailure::Cancelled);
            }
            if timeout.is_some_and(|timeout| started.elapsed() >= timeout) {
                return Err(ExecutionFailure::TimedOut);
            }
            let progress_in = if let Some(pipe) = &mut stdin {
                let progress = write_chunk(pipe, &mut remaining)?;
                if remaining.is_empty() {
                    drop(stdin.take());
                }
                progress
            } else {
                false
            };
            let progress_out = read_chunk(
                &mut stdout,
                &mut evidence.stdout,
                limits.stdout,
                OutputStream::Stdout,
                &mut evidence.stdout_truncated,
                &mut output,
            )?;
            let progress_err = read_chunk(
                &mut stderr,
                &mut evidence.stderr,
                limits.stderr,
                OutputStream::Stderr,
                &mut evidence.stderr_truncated,
                &mut output,
            )?;
            evidence.status = poll_completion(child, successful_exit)
                .map_err(|source| io_failure(ExecutionOperation::Wait, source))?;
            if let Some(status) = evidence.status
                && stdout.is_none()
                && stderr.is_none()
                && stdin.is_none()
            {
                if cancelled() {
                    return Err(ExecutionFailure::Cancelled);
                }
                // Retained success still needs timely caller admission. Ordinary
                // capture keeps its existing synchronous-cleanup exception.
                if successful_exit == SuccessfulExit::Retain
                    && timeout.is_some_and(|timeout| started.elapsed() >= timeout)
                {
                    return Err(ExecutionFailure::TimedOut);
                }
                return Ok(status);
            }
            if !progress_in && !progress_out && !progress_err {
                std::thread::sleep(timeout.map_or(POLL_INTERVAL, |timeout| {
                    POLL_INTERVAL.min(timeout.saturating_sub(started.elapsed()))
                }));
            }
        }
    }));
    // Close all pipes before cleanup. A descendant retaining a writer must not
    // cause a blocking drain or leave background reader threads after a timeout.
    drop(stdin);
    drop(stdout);
    drop(stderr);
    match result {
        Ok(result) => finish_capture(child, evidence, result),
        Err(panic) => {
            let _ = child.terminate();
            resume_unwind(panic)
        }
    }
}

fn poll_completion(
    child: &mut OwnedChild,
    successful_exit: SuccessfulExit,
) -> io::Result<Option<ExitStatus>> {
    if successful_exit == SuccessfulExit::Retain {
        child.poll_exit().and_then(|status| {
            if status.is_some_and(|status| !status.success()) {
                child.try_wait()
            } else {
                Ok(status)
            }
        })
    } else {
        child.try_wait()
    }
}

fn finish_capture(
    child: &mut OwnedChild,
    mut evidence: ExecutionEvidence,
    result: Result<ExitStatus, ExecutionFailure>,
) -> Result<CompletedExecution, ExecutionError> {
    match result {
        Ok(status) => Ok(CompletedExecution {
            status,
            stdout: evidence.stdout,
            stderr: evidence.stderr,
            stdout_truncated: evidence.stdout_truncated,
            stderr_truncated: evidence.stderr_truncated,
        }),
        Err(failure) => {
            let cleanup = match child.terminate() {
                Ok(status) => {
                    evidence.status = Some(status);
                    None
                }
                Err(error) => {
                    evidence.status = error.status;
                    Some(Box::new(error))
                }
            };
            Err(ExecutionError {
                failure,
                evidence,
                cleanup,
            })
        }
    }
}

fn write_chunk(writer: &mut impl Write, remaining: &mut &[u8]) -> Result<bool, ExecutionFailure> {
    let count = match writer.write(&remaining[..remaining.len().min(16 * 1024)]) {
        Ok(0) => {
            return Err(io_failure(
                ExecutionOperation::WriteInput,
                io::ErrorKind::WriteZero.into(),
            ));
        }
        Ok(count) => count,
        // Commands may deliberately stop reading and still supply useful status
        // and diagnostics. Closing early is not proof the input was consumed.
        Err(error) if error.kind() == io::ErrorKind::BrokenPipe => {
            *remaining = &[];
            return Ok(true);
        }
        Err(error)
            if matches!(
                error.kind(),
                io::ErrorKind::Interrupted | io::ErrorKind::WouldBlock
            ) =>
        {
            return Ok(false);
        }
        Err(source) => return Err(io_failure(ExecutionOperation::WriteInput, source)),
    };
    *remaining = &remaining[count..];
    Ok(true)
}

fn nonblocking(pipe: &impl AsFd) -> Result<(), ExecutionFailure> {
    let flags = fcntl_getfl(pipe)
        .map_err(|source| io_failure(ExecutionOperation::ReadPipeFlags, source.into()))?;
    fcntl_setfl(pipe, flags | OFlags::NONBLOCK)
        .map_err(|source| io_failure(ExecutionOperation::SetPipeFlags, source.into()))
}

fn read_chunk(
    reader: &mut Option<impl Read>,
    bytes: &mut Vec<u8>,
    policy: OutputLimit,
    stream: OutputStream,
    truncated: &mut bool,
    output: &mut impl FnMut(OutputStream, &[u8]) -> io::Result<()>,
) -> Result<bool, ExecutionFailure> {
    let Some(pipe) = reader.as_mut() else {
        return Ok(false);
    };
    let mut buffer = [0; 16 * 1024];
    let limit = policy.retained_bytes();
    let terminate = matches!(policy, OutputLimit::Terminate(_));
    let allowance = if terminate {
        (limit - bytes.len()).saturating_add(1).min(buffer.len())
    } else {
        buffer.len()
    };
    let count = match pipe.read(&mut buffer[..allowance]) {
        Ok(0) => {
            // A closed pipe is also the completion state; never read it again.
            drop(reader.take());
            return Ok(false);
        }
        Ok(count) => count,
        Err(source)
            if matches!(
                source.kind(),
                io::ErrorKind::Interrupted | io::ErrorKind::WouldBlock
            ) =>
        {
            return Ok(false);
        }
        Err(source) => return Err(io_failure(ExecutionOperation::ReadOutput, source)),
    };
    let retained = reserve_bounded(bytes, count, limit)
        .map_err(|source| ExecutionFailure::Allocation { stream, source })?;
    bytes.extend_from_slice(&buffer[..retained]);
    // Preserve observed overflow even when the sink rejects this chunk.
    *truncated |= retained != count;
    let observed = if terminate { retained } else { count };
    if observed != 0 {
        output(stream, &buffer[..observed])
            .map_err(|source| ExecutionFailure::Observer { stream, source })?;
    }
    if retained != count && terminate {
        return Err(ExecutionFailure::OutputLimit { stream });
    }
    Ok(true)
}

const fn io_failure(operation: ExecutionOperation, source: io::Error) -> ExecutionFailure {
    ExecutionFailure::Io { operation, source }
}