summaryrefslogtreecommitdiffstats
path: root/src/sandbox/agent.rs
blob: e9626f61da77b4adc542644e2917f4577e14e87e (plain)
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
use std::io::BufReader;
use std::net::TcpStream;
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use crossbeam_channel::unbounded;

use crate::error::{Error, Result};
use crate::sandbox::wire::{self, Frame};

#[derive(Debug, Clone)]
pub struct AgentOptions {
    pub hub: String,
    pub token: String,
    pub profile: String,
    pub ttl: Duration,
    pub agent_id: Option<String>,
}

pub fn serve(opts: &AgentOptions) -> Result<()> {
    let stream = connect_with_retry(&opts.hub, Duration::from_secs(15))?;
    let agent_id = opts
        .agent_id
        .clone()
        .unwrap_or_else(|| format!("sandbox-{}", std::process::id()));
    wire::write_frame(
        &mut stream.try_clone()?,
        &Frame::Hello {
            token: opts.token.clone(),
            agent_id: agent_id.clone(),
            profiles: vec![opts.profile.clone()],
        },
    )?;

    let mut reader = BufReader::new(stream.try_clone()?);
    let writer = Arc::new(Mutex::new(stream));
    let ttl = match wire::read_frame(&mut reader)? {
        Some(Frame::HelloAck { ttl_secs }) => Duration::from_secs(ttl_secs.max(1)),
        Some(other) => return Err(Error::invalid(format!("agent: expected hello_ack, got {other:?}"))),
        None => return Err(Error::other("agent: hub closed the connection at rendezvous")),
    };

    let blobs = blob_dir(&agent_id);
    std::fs::create_dir_all(&blobs)?;

    let last_inbound = Arc::new(Mutex::new(Instant::now()));
    let child = Arc::new(Mutex::new(None::<u32>));
    let alive = Arc::new(AtomicBool::new(true));
    {
        let (last, child, alive, ttl) =
            (last_inbound.clone(), child.clone(), alive.clone(), ttl);
        std::thread::spawn(move || loop {
            std::thread::sleep(Duration::from_millis(1000));
            let quiet = last.lock().unwrap().elapsed();
            if quiet > ttl {
                eprintln!("agent: hub silent for {quiet:?} past the TTL; dying");
                if let Some(pid) = *child.lock().unwrap() {
                    unsafe {
                        libc::kill(pid as i32, libc::SIGKILL);
                    }
                }
                std::process::exit(1);
            }
            if !alive.load(Ordering::Relaxed) {
                return;
            }
        });
    }

    let mut outcome = Ok(());
    loop {
        let frame = match wire::read_frame(&mut reader) {
            Ok(Some(f)) => f,
            Ok(None) => break,
            Err(e) => {
                outcome = Err(e.into());
                break;
            }
        };
        *last_inbound.lock().unwrap() = Instant::now();
        let stop = match handle(frame, &writer, &blobs, &child) {
            Ok(stop) => stop,
            Err(e) => {
                outcome = Err(e);
                break;
            }
        };
        if stop {
            break;
        }
    }
    alive.store(false, Ordering::Relaxed);
    if let Some(pid) = *child.lock().unwrap() {
        unsafe {
            libc::kill(pid as i32, libc::SIGKILL);
        }
    }
    let _ = std::fs::remove_dir_all(&blobs);
    outcome
}

fn handle(
    frame: Frame,
    writer: &Arc<Mutex<TcpStream>>,
    blobs: &Path,
    child: &Arc<Mutex<Option<u32>>>,
) -> Result<bool> {
    match frame {
        Frame::Destroy {} => Ok(true),
        Frame::Ping {} => Ok(false),
        Frame::Put { req, digest, data } => {
            let bytes = wire::unhex(&data).map_err(io_err)?;
            if crate::hash::hex(&bytes) != digest {
                reply(writer, req, Err("put: data does not hash to the claimed digest"))?;
                return Ok(false);
            }
            std::fs::write(safe_blob_path(blobs, &digest)?, &bytes)?;
            reply(writer, req, Ok(()))?;
            Ok(false)
        }
        Frame::Get { req, digest } => match std::fs::read(safe_blob_path(blobs, &digest)?) {
            Ok(bytes) => {
                wire::write_frame(writer.lock().unwrap().deref_mut(), &Frame::Blob { req, data: wire::hex_bytes(&bytes) })?;
                Ok(false)
            }
            Err(_) => {
                reply(writer, req, Err("get: no such blob"))?;
                Ok(false)
            }
        },
        Frame::Run { req, argv, cwd, env } => {
            run_child(req, argv, cwd, env, writer, blobs, child)?;
            Ok(false)
        }
        other => Err(Error::invalid(format!("agent: unexpected frame {other:?}"))),
    }
}

fn run_child(
    req: u64,
    argv: Vec<String>,
    cwd: Option<String>,
    env: Vec<(String, String)>,
    writer: &Arc<Mutex<TcpStream>>,
    blobs: &Path,
    child: &Arc<Mutex<Option<u32>>>,
) -> Result<()> {
    let mut argv = argv;
    for a in argv.iter_mut() {
        if let Some(digest) = a.strip_prefix("blob:") {
            *a = safe_blob_path(blobs, digest)?.display().to_string();
        }
    }
    let program = argv.first().ok_or_else(|| Error::invalid("run: empty argv"))?;
    let mut c = std::process::Command::new(program);
    c.args(&argv[1..])
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    if let Some(dir) = cwd {
        c.current_dir(dir);
    }
    for (k, v) in env {
        c.env(k, v);
    }
    let mut proc = c.spawn()?;
    *child.lock().unwrap() = Some(proc.id());

    let (tx, rx) = unbounded::<(&'static str, Vec<u8>)>();
    let mut pipes = Vec::new();
    let pipes_spec: [(&'static str, Option<Box<dyn std::io::Read + Send>>); 2] = [
        ("stdout", proc.stdout.take().map(|r| Box::new(r) as Box<dyn std::io::Read + Send>)),
        ("stderr", proc.stderr.take().map(|r| Box::new(r) as Box<dyn std::io::Read + Send>)),
    ];
    for (name, pipe) in pipes_spec {
        if let Some(mut pipe) = pipe {
            let tx = tx.clone();
            pipes.push(std::thread::spawn(move || {
                use std::io::Read;
                let mut buf = [0u8; 8192];
                loop {
                    match pipe.read(&mut buf) {
                        Ok(0) | Err(_) => break,
                        Ok(n) => {
                            if tx.send((name, buf[..n].to_vec())).is_err() {
                                break;
                            }
                        }
                    }
                }
            }));
        }
    }
    drop(tx);
    while let Ok((stream, bytes)) = rx.recv() {
        wire::write_frame(
            writer.lock().unwrap().deref_mut(),
            &Frame::Log { req, stream: stream.to_string(), data: wire::hex_bytes(&bytes) },
        )?;
    }
    for p in pipes {
        let _ = p.join();
    }
    let status = proc.wait()?;
    *child.lock().unwrap() = None;
    wire::write_frame(
        writer.lock().unwrap().deref_mut(),
        &Frame::Exit { req, code: status.code() },
    )?;
    Ok(())
}

fn reply(writer: &Arc<Mutex<TcpStream>>, req: u64, result: std::result::Result<(), &str>) -> Result<()> {
    let frame = match result {
        Ok(()) => Frame::Ok { req },
        Err(msg) => Frame::Err { req, msg: msg.to_string() },
    };
    wire::write_frame(writer.lock().unwrap().deref_mut(), &frame)?;
    Ok(())
}

fn connect_with_retry(hub: &str, for_long: Duration) -> std::result::Result<TcpStream, Error> {
    let deadline = Instant::now() + for_long;
    loop {
        match TcpStream::connect(hub) {
            Ok(s) => return Ok(s),
            Err(_) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(100)),
            Err(e) => return Err(Error::other(format!("agent: cannot reach hub {hub}: {e}"))),
        }
    }
}

fn blob_dir(agent_id: &str) -> PathBuf {
    std::env::temp_dir().join(format!("aur-{agent_id}-blobs"))
}

fn safe_blob_path(blobs: &Path, digest: &str) -> Result<PathBuf> {
    if digest.is_empty()
        || digest.len() > 128
        || !digest.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
    {
        return Err(Error::fail_closed(format!("blob digest {digest:?} is not usable")));
    }
    Ok(blobs.join(digest))
}

fn io_err(e: std::io::Error) -> Error {
    Error::other(e.to_string())
}

use std::ops::DerefMut;