Skip to main content

rust_anything/
effects.rs

1use std::collections::BTreeMap;
2use std::io::{BufRead, BufReader, Read, Write};
3use std::net::{TcpListener, TcpStream};
4use std::path::Path;
5use std::process::Command;
6use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
7use std::sync::{Arc, Mutex};
8use std::thread::JoinHandle;
9use std::time::{Duration, Instant};
10
11use anyhow::{Context, Result, bail};
12use serde::{Deserialize, Serialize};
13
14pub const EXT: &str = "effects";
15const IO_TIMEOUT: Duration = Duration::from_secs(5);
16const SETTLE: Duration = Duration::from_secs(2);
17
18#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
19pub struct EffectsConfig {
20    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
21    pub http: bool,
22    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
23    pub smtp: bool,
24    /// Mail is recorded as decoded headers and MIME parts. Configs saved before it existed leave
25    /// it out and keep recording the raw DATA, so their cases still replay.
26    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
27    pub smtp_parts: bool,
28    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
29    pub env: BTreeMap<String, String>,
30    #[serde(default, skip_serializing_if = "Option::is_none")]
31    pub db_reset: Option<String>,
32    #[serde(default, skip_serializing_if = "Option::is_none")]
33    pub db_dump: Option<String>,
34}
35
36const ENV_KINDS: [&str; 4] = ["http-url", "smtp-host", "smtp-port", "smtp-url"];
37
38impl EffectsConfig {
39    pub fn is_empty(&self) -> bool {
40        !self.http && !self.smtp && self.db_dump.is_none()
41    }
42
43    pub fn serial(&self) -> bool {
44        self.db_reset.is_some() || self.db_dump.is_some()
45    }
46
47    pub fn from_args(
48        kinds: &[String],
49        env: &[String],
50        db_reset: Option<&str>,
51        db_dump: Option<&str>,
52    ) -> Result<Option<Self>> {
53        let mut config = EffectsConfig::default();
54        let mut raw = false;
55        for kind in kinds.iter().flat_map(|k| k.split(',')).map(str::trim) {
56            match kind {
57                "http" => config.http = true,
58                "smtp" => config.smtp = true,
59                "smtp-raw" => {
60                    config.smtp = true;
61                    raw = true;
62                }
63                "" => {}
64                other => bail!("unknown effect `{other}`: use http, smtp or smtp-raw"),
65            }
66        }
67        for pair in env {
68            let (var, kind) = pair
69                .split_once('=')
70                .with_context(|| format!("--effect-env `{pair}`: give VAR=KIND"))?;
71            if !ENV_KINDS.contains(&kind) {
72                bail!(
73                    "--effect-env `{pair}`: KIND is one of {}",
74                    ENV_KINDS.join(", ")
75                );
76            }
77            if kind.starts_with("http") {
78                config.http = true;
79            } else {
80                config.smtp = true;
81            }
82            config.env.insert(var.to_string(), kind.to_string());
83        }
84        config.smtp_parts = config.smtp && !raw;
85        config.db_reset = db_reset.map(str::to_string);
86        config.db_dump = db_dump.map(str::to_string);
87        Ok((!config.is_empty() || config.db_reset.is_some()).then_some(config))
88    }
89
90    pub fn merge(saved: Option<Self>, given: Option<Self>) -> Option<Self> {
91        match (saved, given) {
92            (_, Some(g)) => Some(g),
93            (s, None) => s,
94        }
95    }
96}
97
98struct Sink {
99    port: u16,
100    stop: Arc<AtomicBool>,
101    thread: Option<JoinHandle<()>>,
102}
103
104pub struct Sinks {
105    config: EffectsConfig,
106    events: Arc<Mutex<Vec<String>>>,
107    active: Arc<AtomicUsize>,
108    http: Option<Sink>,
109    smtp: Option<Sink>,
110}
111
112impl Sinks {
113    pub fn start(config: &EffectsConfig) -> Result<Sinks> {
114        let events = Arc::new(Mutex::new(Vec::new()));
115        let active = Arc::new(AtomicUsize::new(0));
116        let http = config
117            .http
118            .then(|| listen(&events, &active, serve_http))
119            .transpose()?;
120        let smtp_handler: Handler = if config.smtp_parts {
121            serve_smtp
122        } else {
123            serve_smtp_raw
124        };
125        let smtp = config
126            .smtp
127            .then(|| listen(&events, &active, smtp_handler))
128            .transpose()?;
129        Ok(Sinks {
130            config: config.clone(),
131            events,
132            active,
133            http,
134            smtp,
135        })
136    }
137
138    pub fn env(&self) -> Vec<(String, String)> {
139        let mut out = Vec::new();
140        if let Some(h) = &self.http {
141            let url = format!("http://127.0.0.1:{}", h.port);
142            for var in ["RUST_ANYTHING_HTTP_SINK", "HTTP_PROXY", "http_proxy"] {
143                out.push((var.to_string(), url.clone()));
144            }
145        }
146        if let Some(s) = &self.smtp {
147            out.push(("SMTP_HOST".into(), "127.0.0.1".into()));
148            out.push(("SMTP_PORT".into(), s.port.to_string()));
149            out.push((
150                "RUST_ANYTHING_SMTP_SINK".into(),
151                format!("smtp://127.0.0.1:{}", s.port),
152            ));
153        }
154        for (var, kind) in &self.config.env {
155            let value = match (kind.as_str(), &self.http, &self.smtp) {
156                ("http-url", Some(h), _) => format!("http://127.0.0.1:{}", h.port),
157                ("smtp-host", _, Some(_)) => "127.0.0.1".to_string(),
158                ("smtp-port", _, Some(s)) => s.port.to_string(),
159                ("smtp-url", _, Some(s)) => format!("smtp://127.0.0.1:{}", s.port),
160                _ => continue,
161            };
162            out.push((var.clone(), value));
163        }
164        out
165    }
166
167    /// Runs `--db-reset` in `cwd`, the folder the case or server runs in.
168    pub fn reset(&self, cwd: &Path, repo: &Path) -> Result<()> {
169        if let Some(cmd) = &self.config.db_reset {
170            let out = shell(cmd, cwd, repo, &self.env())?;
171            if !out.status.success() {
172                bail!(
173                    "--db-reset `{cmd}` failed ({}): {}",
174                    out.status,
175                    String::from_utf8_lossy(&out.stderr).trim()
176                );
177            }
178        }
179        Ok(())
180    }
181
182    /// Collects the effects and runs `--db-dump` in `cwd`, the folder the case or server ran in.
183    pub fn take(&self, cwd: &Path, repo: &Path) -> Vec<u8> {
184        let deadline = Instant::now() + SETTLE;
185        while self.active.load(Ordering::SeqCst) > 0 && Instant::now() < deadline {
186            std::thread::sleep(Duration::from_millis(10));
187        }
188        let mut text: String = self
189            .events
190            .lock()
191            .map(|mut e| e.drain(..).collect())
192            .unwrap_or_default();
193        if let Some(cmd) = &self.config.db_dump {
194            text.push_str("db\n");
195            match shell(cmd, cwd, repo, &self.env()) {
196                Ok(out) => {
197                    text.push_str(&String::from_utf8_lossy(&out.stdout));
198                    if !out.status.success() {
199                        text.push_str(&format!("(db dump failed: {})\n", out.status));
200                    }
201                }
202                Err(e) => text.push_str(&format!("(db dump failed: {e:#})\n")),
203            }
204        }
205        text.into_bytes()
206    }
207}
208
209impl Drop for Sinks {
210    fn drop(&mut self) {
211        for sink in [self.http.as_mut(), self.smtp.as_mut()]
212            .into_iter()
213            .flatten()
214        {
215            sink.stop.store(true, Ordering::SeqCst);
216            if let Some(t) = sink.thread.take() {
217                let _ = t.join();
218            }
219        }
220    }
221}
222
223/// Extensions of the files `with_repo_scripts` points at the repository.
224const SCRIPTS: [&str; 14] = [
225    "py", "sh", "bash", "js", "mjs", "cjs", "ts", "rb", "php", "pl", "ps1", "bat", "cmd", "sql",
226];
227
228/// The command runs where the case runs, so a script it names by a relative path (`reset.py`,
229/// `"my scripts/reset.py"`, `< schema.sql`) is pointed at the repository's copy. Other words, such
230/// as `app.db`, the target of an output redirect (`> snapshot.sql`), a here-string and the body of a
231/// here-document stay as written: they name the case's own files or are input. Everything else in
232/// the command is kept as written.
233fn with_repo_scripts(cmd: &str, repo: &Path) -> String {
234    let mut out = String::with_capacity(cmd.len());
235    let mut kept = 0;
236    let mut skip_next = false;
237    for word in shell_words(cmd) {
238        if word.op {
239            // The word after `>`, `>>` or `2>` is an output, after `<<` a here-document's
240            // delimiter, after `<<<` a here-string: none is a file to read.
241            skip_next = word.text.contains('>') || word.text.starts_with("<<");
242            continue;
243        }
244        if std::mem::take(&mut skip_next) {
245            continue;
246        }
247        let path = word.text.as_str();
248        let script = Path::new(path)
249            .extension()
250            .and_then(|e| e.to_str())
251            .is_some_and(|e| SCRIPTS.contains(&e.to_ascii_lowercase().as_str()));
252        let in_repo = repo.join(path);
253        if script && Path::new(path).is_relative() && in_repo.is_file() {
254            out.push_str(&cmd[kept..word.start]);
255            out.push_str(&quoted(&in_repo));
256            kept = word.end;
257        }
258    }
259    out.push_str(&cmd[kept..]);
260    out
261}
262
263/// A word of a shell command: where it sits in the command, its text without quotes, and whether
264/// it is a redirect operator (`<`, `>`, `>>`, `<<`, `<<-`, `<<<`) rather than a word.
265struct ShellWord {
266    start: usize,
267    end: usize,
268    text: String,
269    op: bool,
270}
271
272/// Splits a command into words as the shell does: whitespace, `;`, `&` and `|` separate words
273/// outside quotes, an unquoted `<` or `>` starts a redirect operator of its own, and quotes group
274/// without being part of the text. The body of a here-document is input, so it gives no words.
275/// cmd quotes with `"` and escapes with `^`; sh also quotes with `'`, escapes with a backslash, and
276/// skips a comment (`#` at the start of a word) to the end of the line.
277fn shell_words(cmd: &str) -> Vec<ShellWord> {
278    shell_words_as(cmd, cfg!(not(windows)))
279}
280
281/// `shell_words` as sh (`unix`) or cmd reads the command.
282fn shell_words_as(cmd: &str, unix: bool) -> Vec<ShellWord> {
283    let mut words = Vec::new();
284    let mut word: Option<ShellWord> = None;
285    let mut quote = None;
286    // Here-documents whose bodies start on the next line: the delimiter, and whether it is `<<-`,
287    // which strips leading tabs.
288    let mut heredocs = Vec::new();
289    // cmd blocks open, `(` at the start of a word, and not yet closed.
290    let mut blocks = 0usize;
291    let mut i = 0;
292    while let Some(c) = cmd[i..].chars().next() {
293        let len = c.len_utf8();
294        // A line continuation (`\` in sh, `^` in cmd, then a newline) joins the lines before the
295        // command is split into words, so it is part of no word and makes none of its own.
296        let escape = if unix { '\\' } else { '^' };
297        if quote.is_none() && c == escape {
298            let rest = &cmd[i + len..];
299            if let Some(newline) = ["\r\n", "\n"].into_iter().find(|n| rest.starts_with(n)) {
300                i += len + newline.len();
301                continue;
302            }
303        }
304        let in_op = word.as_ref().is_some_and(|w| w.op);
305        let redirect = quote.is_none() && matches!(c, '<' | '>');
306        // sh groups commands with `(` and `)`. cmd does with a `(` that starts a word and the `)`
307        // that closes it; elsewhere a parenthesis is part of a name (`my(1).py`).
308        let opens = !unix && quote.is_none() && c == '(' && word.is_none();
309        let closes = !unix && quote.is_none() && c == ')' && blocks > 0;
310        let separator = quote.is_none()
311            && (c.is_whitespace()
312                || matches!(c, ';' | '&' | '|')
313                || (unix && matches!(c, '(' | ')'))
314                || opens
315                || closes);
316        if opens {
317            blocks += 1;
318        } else if closes {
319            blocks -= 1;
320        }
321        let op_goes_on = redirect || (c == '-' && word.as_ref().is_some_and(|w| w.text == "<<"));
322        if separator || (redirect && !in_op) || (in_op && !op_goes_on) {
323            finish(&mut words, &mut heredocs, word.take());
324        }
325        // sh: an unquoted `#` that starts a word comments out the rest of the line.
326        if unix && c == '#' && quote.is_none() && word.is_none() {
327            i = cmd[i..].find('\n').map_or(cmd.len(), |n| i + n);
328            continue;
329        }
330        if separator {
331            i += len;
332            if c == '\n' && !heredocs.is_empty() {
333                i = past_heredocs(cmd, i, &mut heredocs);
334            }
335            continue;
336        }
337        let w = word.get_or_insert_with(|| ShellWord {
338            start: i,
339            end: i,
340            text: String::new(),
341            op: redirect,
342        });
343        match (quote, c) {
344            (Some(q), c) if c == q => quote = None,
345            // sh: in double quotes a backslash escapes only these, and drops a newline.
346            (Some('"'), '\\') if unix => match cmd[i + len..].chars().next() {
347                Some(next @ ('$' | '`' | '"' | '\\' | '\n')) => {
348                    if next != '\n' {
349                        w.text.push(next);
350                    }
351                    i += len + next.len_utf8();
352                    w.end = i;
353                    continue;
354                }
355                _ => w.text.push('\\'),
356            },
357            (Some(_), c) => w.text.push(c),
358            (None, '"') => quote = Some('"'),
359            (None, '\'') if unix => quote = Some('\''),
360            // A backslash (sh) or caret (cmd) escapes the next character.
361            (None, c) if c == escape => {
362                if let Some(next) = cmd[i + len..].chars().next() {
363                    w.text.push(next);
364                    i += len + next.len_utf8();
365                    w.end = i;
366                    continue;
367                }
368            }
369            (None, c) => w.text.push(c),
370        }
371        i += len;
372        w.end = i;
373    }
374    finish(&mut words, &mut heredocs, word);
375    words
376}
377
378/// Ends a word; a word right after `<<` or `<<-` is the delimiter of a here-document.
379fn finish(words: &mut Vec<ShellWord>, heredocs: &mut Vec<(String, bool)>, word: Option<ShellWord>) {
380    let Some(w) = word.filter(|w| w.end > w.start) else {
381        return;
382    };
383    let after = words
384        .last()
385        .filter(|p| p.op && !w.op)
386        .map(|p| p.text.as_str());
387    if let Some(op @ ("<<" | "<<-")) = after {
388        heredocs.push((w.text.clone(), op == "<<-"));
389    }
390    words.push(w);
391}
392
393/// Skips the bodies of the pending here-documents, which start at `from`, through each closing
394/// delimiter line, and returns where the command goes on.
395fn past_heredocs(cmd: &str, mut from: usize, heredocs: &mut Vec<(String, bool)>) -> usize {
396    for (delimiter, tabs) in heredocs.drain(..) {
397        while from < cmd.len() {
398            let end = cmd[from..].find('\n').map_or(cmd.len(), |n| from + n);
399            let line = cmd[from..end].trim_end_matches('\r');
400            let line = if tabs {
401                line.trim_start_matches('\t')
402            } else {
403                line
404            };
405            from = (end + 1).min(cmd.len());
406            if line == delimiter {
407                break;
408            }
409        }
410    }
411    from
412}
413
414#[cfg(windows)]
415fn quoted(path: &Path) -> String {
416    format!("\"{}\"", path.display())
417}
418
419#[cfg(not(windows))]
420fn quoted(path: &Path) -> String {
421    format!("'{}'", path.display().to_string().replace('\'', r"'\''"))
422}
423
424fn shell(
425    cmd: &str,
426    cwd: &Path,
427    repo: &Path,
428    env: &[(String, String)],
429) -> Result<crate::process::Output> {
430    let cmd = with_repo_scripts(cmd, repo);
431    #[cfg(windows)]
432    let mut c = {
433        use std::os::windows::process::CommandExt as _;
434        // `/S` strips exactly the outer quotes, so the command keeps the quotes `quoted` added;
435        // `arg` would escape them as `\"`, which cmd does not read.
436        let mut c = Command::new("cmd");
437        c.args(["/S", "/C"]).raw_arg(format!("\"{cmd}\""));
438        c
439    };
440    #[cfg(not(windows))]
441    let mut c = {
442        let mut c = Command::new("sh");
443        c.args(["-c", &cmd]);
444        c
445    };
446    c.current_dir(cwd)
447        .envs(env.iter().map(|(k, v)| (k, v)))
448        .stdin(std::process::Stdio::null());
449    crate::process::output(&mut c, crate::process::QUICK)
450}
451
452type Handler = fn(TcpStream, &Mutex<Vec<String>>);
453
454fn listen(
455    events: &Arc<Mutex<Vec<String>>>,
456    active: &Arc<AtomicUsize>,
457    handler: Handler,
458) -> Result<Sink> {
459    let listener = TcpListener::bind("127.0.0.1:0").context("starting an effect sink")?;
460    listener.set_nonblocking(true)?;
461    let port = listener.local_addr()?.port();
462    let stop = Arc::new(AtomicBool::new(false));
463    let (events, active, flag) = (events.clone(), active.clone(), stop.clone());
464    let thread = std::thread::spawn(move || {
465        while !flag.load(Ordering::SeqCst) {
466            match listener.accept() {
467                Ok((stream, _)) => {
468                    let _ = stream.set_nonblocking(false);
469                    let _ = stream.set_read_timeout(Some(IO_TIMEOUT));
470                    let (events, active) = (events.clone(), active.clone());
471                    active.fetch_add(1, Ordering::SeqCst);
472                    std::thread::spawn(move || {
473                        handler(stream, &events);
474                        active.fetch_sub(1, Ordering::SeqCst);
475                    });
476                }
477                Err(_) => std::thread::sleep(Duration::from_millis(5)),
478            }
479        }
480    });
481    Ok(Sink {
482        port,
483        stop,
484        thread: Some(thread),
485    })
486}
487
488fn push(events: &Mutex<Vec<String>>, event: String) {
489    if let Ok(mut e) = events.lock() {
490        e.push(event);
491    }
492}
493
494fn body_text(body: &[u8]) -> String {
495    match std::str::from_utf8(body) {
496        Ok(t) => t.to_string(),
497        Err(_) => format!("({} bytes)", body.len()),
498    }
499}
500
501fn serve_http(mut stream: TcpStream, events: &Mutex<Vec<String>>) {
502    let mut reader = BufReader::new(match stream.try_clone() {
503        Ok(s) => s,
504        Err(_) => return,
505    });
506    let mut line = String::new();
507    if reader.read_line(&mut line).unwrap_or(0) == 0 {
508        return;
509    }
510    let mut parts = line.split_whitespace();
511    let method = parts.next().unwrap_or_default().to_string();
512    let target = parts.next().unwrap_or_default().to_string();
513    let mut headers: Vec<(String, String)> = Vec::new();
514    loop {
515        let mut h = String::new();
516        if reader.read_line(&mut h).unwrap_or(0) == 0 {
517            break;
518        }
519        let h = h.trim_end();
520        if h.is_empty() {
521            break;
522        }
523        if let Some((k, v)) = h.split_once(':') {
524            headers.push((k.trim().to_ascii_lowercase(), v.trim().to_string()));
525        }
526    }
527    let header = |name: &str| {
528        headers
529            .iter()
530            .find(|(k, _)| k == name)
531            .map(|(_, v)| v.clone())
532    };
533    if method.eq_ignore_ascii_case("CONNECT") {
534        push(events, format!("https CONNECT {target}\n"));
535        let _ = stream.write_all(
536            b"HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
537        );
538        return;
539    }
540    let mut body = Vec::new();
541    if header("transfer-encoding").is_some_and(|t| t.eq_ignore_ascii_case("chunked")) {
542        loop {
543            let mut size = String::new();
544            if reader.read_line(&mut size).unwrap_or(0) == 0 {
545                break;
546            }
547            let n = usize::from_str_radix(size.trim().split(';').next().unwrap_or("0"), 16)
548                .unwrap_or(0);
549            if n == 0 {
550                break;
551            }
552            let mut chunk = vec![0; n + 2];
553            if reader.read_exact(&mut chunk).is_err() {
554                break;
555            }
556            chunk.truncate(n);
557            body.extend(chunk);
558        }
559    } else if let Some(n) = header("content-length").and_then(|v| v.parse::<usize>().ok()) {
560        body.resize(n, 0);
561        if reader.read_exact(&mut body).is_err() {
562            body.clear();
563        }
564    }
565    let url = if target.starts_with("http://") || target.starts_with("https://") {
566        target
567    } else {
568        format!("http://{}{target}", header("host").unwrap_or_default())
569    };
570    let url = match stream.local_addr() {
571        Ok(local) => url
572            .replace(&format!("127.0.0.1:{}", local.port()), "sink")
573            .replace(&format!("localhost:{}", local.port()), "sink"),
574        Err(_) => url,
575    };
576    let mut event = format!("http {method} {url}\n");
577    if let Some(ct) = header("content-type") {
578        event.push_str(&format!("content-type: {ct}\n"));
579    }
580    if !body.is_empty() {
581        event.push('\n');
582        event.push_str(&body_text(&body));
583        if !event.ends_with('\n') {
584            event.push('\n');
585        }
586    }
587    push(events, event);
588    let _ = stream.write_all(
589        b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{}",
590    );
591}
592
593fn serve_smtp(stream: TcpStream, events: &Mutex<Vec<String>>) {
594    serve_smtp_mode(stream, events, false);
595}
596
597fn serve_smtp_raw(stream: TcpStream, events: &Mutex<Vec<String>>) {
598    serve_smtp_mode(stream, events, true);
599}
600
601fn serve_smtp_mode(stream: TcpStream, events: &Mutex<Vec<String>>, raw: bool) {
602    let Ok(mut out) = stream.try_clone() else {
603        return;
604    };
605    let mut reader = BufReader::new(stream);
606    let mut say = |line: &str| out.write_all(format!("{line}\r\n").as_bytes()).is_ok();
607    if !say("220 rust-anything ESMTP") {
608        return;
609    }
610    let (mut from, mut to) = (String::new(), Vec::<String>::new());
611    loop {
612        let mut line = String::new();
613        if reader.read_line(&mut line).unwrap_or(0) == 0 {
614            return;
615        }
616        let cmd = line.trim_end();
617        let upper = cmd.to_ascii_uppercase();
618        let ok = if upper.starts_with("EHLO") {
619            say("250-rust-anything") && say("250 AUTH PLAIN LOGIN")
620        } else if upper.starts_with("HELO") {
621            say("250 rust-anything")
622        } else if upper.starts_with("MAIL FROM:") {
623            from = cmd[10..].trim().to_string();
624            say("250 OK")
625        } else if upper.starts_with("RCPT TO:") {
626            to.push(cmd[8..].trim().to_string());
627            say("250 OK")
628        } else if upper == "DATA" {
629            if !say("354 End data with <CR><LF>.<CR><LF>") {
630                return;
631            }
632            let mut data = String::new();
633            loop {
634                let mut l = String::new();
635                if reader.read_line(&mut l).unwrap_or(0) == 0 {
636                    return;
637                }
638                let t = l.trim_end_matches(['\r', '\n']);
639                if t == "." {
640                    break;
641                }
642                data.push_str(
643                    t.strip_prefix('.')
644                        .filter(|_| t.starts_with(".."))
645                        .unwrap_or(t),
646                );
647                data.push('\n');
648            }
649            let body = if raw {
650                data
651            } else {
652                crate::mime::format_email(&data)
653            };
654            push(
655                events,
656                format!("smtp from {from} to {}\n{body}", to.join(", ")),
657            );
658            from.clear();
659            to.clear();
660            say("250 OK queued")
661        } else if upper.starts_with("AUTH") {
662            say("235 Authentication succeeded")
663        } else if upper == "RSET" {
664            from.clear();
665            to.clear();
666            say("250 OK")
667        } else if upper == "QUIT" {
668            let _ = say("221 Bye");
669            return;
670        } else if upper.starts_with("STARTTLS") {
671            say("454 TLS not available")
672        } else {
673            say("250 OK")
674        };
675        if !ok {
676            return;
677        }
678    }
679}
680
681#[cfg(test)]
682mod tests {
683    use super::*;
684
685    #[test]
686    fn only_scripts_of_the_repository_are_pointed_at_it() {
687        let repo = std::env::temp_dir().join(format!("ra-effects-scripts-{}", std::process::id()));
688        std::fs::create_dir_all(repo.join("scripts")).unwrap();
689        for file in ["reset.py", "scripts/seed.sh", "app.db"] {
690            std::fs::write(repo.join(file), "").unwrap();
691        }
692        let at = |file: &str| quoted(&repo.join(file));
693        assert_eq!(
694            with_repo_scripts("python3 reset.py --all", &repo),
695            format!("python3 {} --all", at("reset.py"))
696        );
697        assert_eq!(
698            with_repo_scripts("sh scripts/seed.sh && sqlite3 app.db .dump", &repo),
699            format!("sh {} && sqlite3 app.db .dump", at("scripts/seed.sh"))
700        );
701        // Not in the repository, or not a relative path: left as written.
702        assert_eq!(
703            with_repo_scripts("python3 missing.py", &repo),
704            "python3 missing.py"
705        );
706        let absolute = repo.join("reset.py").display().to_string();
707        assert_eq!(
708            with_repo_scripts(&format!("python3 {absolute}"), &repo),
709            format!("python3 {absolute}")
710        );
711        std::fs::remove_dir_all(&repo).unwrap();
712    }
713
714    #[test]
715    fn script_words_are_read_as_the_shell_reads_them() {
716        let repo = std::env::temp_dir().join(format!("ra-effects-words-{}", std::process::id()));
717        std::fs::create_dir_all(repo.join("my scripts")).unwrap();
718        for file in [
719            "reset.py",
720            "my scripts/seed.py",
721            "schema.sql",
722            "snapshot.sql",
723        ] {
724            std::fs::write(repo.join(file), "").unwrap();
725        }
726        let at = |file: &str| quoted(&repo.join(file));
727        // Quoted, and quoted with a space.
728        assert_eq!(
729            with_repo_scripts(r#"python3 "reset.py""#, &repo),
730            format!("python3 {}", at("reset.py"))
731        );
732        assert_eq!(
733            with_repo_scripts(r#"python3 "my scripts/seed.py" --all"#, &repo),
734            format!("python3 {} --all", at("my scripts/seed.py"))
735        );
736        // An input is the repository's; an output stays in the case's folder.
737        assert_eq!(
738            with_repo_scripts("sqlite3 app.db < schema.sql", &repo),
739            format!("sqlite3 app.db < {}", at("schema.sql"))
740        );
741        assert_eq!(
742            with_repo_scripts("sqlite3 app.db <schema.sql", &repo),
743            format!("sqlite3 app.db <{}", at("schema.sql"))
744        );
745        for cmd in [
746            "sqlite3 app.db .dump > snapshot.sql",
747            "sqlite3 app.db .dump >> snapshot.sql",
748            "sqlite3 app.db .dump >snapshot.sql",
749            "sqlite3 app.db .dump 2> snapshot.sql",
750        ] {
751            assert_eq!(with_repo_scripts(cmd, &repo), cmd);
752        }
753        // Spacing and operators around the words are kept as written.
754        assert_eq!(
755            with_repo_scripts("python3  reset.py;  echo  ok", &repo),
756            format!("python3  {};  echo  ok", at("reset.py"))
757        );
758        std::fs::remove_dir_all(&repo).unwrap();
759    }
760
761    #[test]
762    fn sh_continuations_escapes_and_parentheses_are_read_as_sh_reads_them() {
763        let words = |cmd: &str| -> Vec<String> {
764            shell_words_as(cmd, true)
765                .into_iter()
766                .map(|w| w.text)
767                .collect()
768        };
769        // A line continuation is no part of any word, and makes none of its own.
770        assert_eq!(words("python3 \\\nreset.py"), ["python3", "reset.py"]);
771        assert_eq!(words("python3 \\\n  reset.py"), ["python3", "reset.py"]);
772        assert_eq!(words("echo '' x"), ["echo", "", "x"]);
773        let ops: Vec<(String, bool)> = shell_words_as("echo result > \\\n snapshot.sql", true)
774            .into_iter()
775            .map(|w| (w.text, w.op))
776            .collect();
777        assert_eq!(
778            ops,
779            [
780                ("echo".to_string(), false),
781                ("result".to_string(), false),
782                (">".to_string(), true),
783                ("snapshot.sql".to_string(), false)
784            ]
785        );
786        assert_eq!(words("python3 re\\\nset.py"), ["python3", "reset.py"]);
787        assert_eq!(words("python3 \"re\\\nset.py\""), ["python3", "reset.py"]);
788        // Unquoted parentheses group commands; quoted ones are part of a name.
789        assert_eq!(words("(python3 reset.py)"), ["python3", "reset.py"]);
790        assert_eq!(words("python3 '(x).py'"), ["python3", "(x).py"]);
791        // In double quotes a backslash escapes only `$`, `` ` ``, `"`, `\` and a newline.
792        assert_eq!(words(r#"echo "a\"b" "c\d""#), ["echo", "a\"b", "c\\d"]);
793        assert_eq!(words(r"echo 'a\b'"), ["echo", "a\\b"]);
794    }
795
796    #[test]
797    fn cmd_blocks_and_carets_are_read_as_cmd_reads_them() {
798        let words = |cmd: &str| -> Vec<String> {
799            shell_words_as(cmd, false)
800                .into_iter()
801                .map(|w| w.text)
802                .collect()
803        };
804        // A `(` that starts a word opens a block, and a `)` in a block closes it.
805        assert_eq!(
806            words("if exist app.db (python reset.py)"),
807            ["if", "exist", "app.db", "python", "reset.py"]
808        );
809        assert_eq!(words("(python reset.py)"), ["python", "reset.py"]);
810        // Outside a block, and quoted or escaped with `^`, parentheses are part of a name.
811        assert_eq!(words("python my(1).py"), ["python", "my(1).py"]);
812        assert_eq!(words(r#"python "a (1).py""#), ["python", "a (1).py"]);
813        assert_eq!(words("(echo ^(x^))"), ["echo", "(x)"]);
814    }
815
816    #[test]
817    fn sh_comments_give_no_words() {
818        let words = |cmd: &str| -> Vec<String> {
819            shell_words_as(cmd, true)
820                .into_iter()
821                .map(|w| w.text)
822                .collect()
823        };
824        // A comment's `<<EOF` starts no here-document, so the next line is still read.
825        assert_eq!(words("# <<EOF\npython3 reset.py"), ["python3", "reset.py"]);
826        assert_eq!(
827            words("python3 reset.py # then <<EOF\necho ok"),
828            ["python3", "reset.py", "echo", "ok"]
829        );
830        // `#` inside a word or in quotes is text.
831        assert_eq!(words("echo a#b '#c' \"#d\""), ["echo", "a#b", "#c", "#d"]);
832        // cmd has no `#` comments.
833        assert_eq!(
834            shell_words_as("echo # x", false)
835                .into_iter()
836                .map(|w| w.text)
837                .collect::<Vec<_>>(),
838            ["echo", "#", "x"]
839        );
840    }
841
842    #[test]
843    fn redirects_and_here_documents_are_read_as_the_shell_reads_them() {
844        let repo = std::env::temp_dir().join(format!("ra-effects-heredoc-{}", std::process::id()));
845        std::fs::create_dir_all(&repo).unwrap();
846        for file in ["reset.py", "schema.sql", "snapshot.sql"] {
847            std::fs::write(repo.join(file), "").unwrap();
848        }
849        let at = |file: &str| quoted(&repo.join(file));
850        // A redirect needs no space before it.
851        assert_eq!(
852            with_repo_scripts("sqlite3 app.db<schema.sql", &repo),
853            format!("sqlite3 app.db<{}", at("schema.sql"))
854        );
855        for cmd in [
856            "echo result> snapshot.sql",
857            "echo result>snapshot.sql",
858            "echo result>>snapshot.sql",
859            "python3 check.py 2>&1 >snapshot.sql",
860        ] {
861            assert_eq!(with_repo_scripts(cmd, &repo), cmd);
862        }
863        // A here-document's body and a here-string are input, not words; the command goes on
864        // after the delimiter.
865        let heredoc = "cat <<EOF > notes.txt\nschema.sql\nEOF\npython3 reset.py";
866        assert_eq!(
867            with_repo_scripts(heredoc, &repo),
868            format!(
869                "cat <<EOF > notes.txt\nschema.sql\nEOF\npython3 {}",
870                at("reset.py")
871            )
872        );
873        let tabs = "cat <<-END\n\tschema.sql\n\tEND\npython3 reset.py";
874        assert_eq!(
875            with_repo_scripts(tabs, &repo),
876            format!(
877                "cat <<-END\n\tschema.sql\n\tEND\npython3 {}",
878                at("reset.py")
879            )
880        );
881        assert_eq!(
882            with_repo_scripts("sqlite3 app.db <<< schema.sql", &repo),
883            "sqlite3 app.db <<< schema.sql"
884        );
885        if cfg!(not(windows)) {
886            let quoted_delim = "cat <<'EOF'\nschema.sql\nEOF\npython3 reset.py";
887            assert_eq!(
888                with_repo_scripts(quoted_delim, &repo),
889                format!("cat <<'EOF'\nschema.sql\nEOF\npython3 {}", at("reset.py"))
890            );
891        }
892        std::fs::remove_dir_all(&repo).unwrap();
893    }
894
895    fn send(port: u16, text: &str) -> String {
896        let mut s = TcpStream::connect(("127.0.0.1", port)).unwrap();
897        s.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
898        s.write_all(text.as_bytes()).unwrap();
899        let mut out = String::new();
900        let _ = s.read_to_string(&mut out);
901        out
902    }
903
904    #[test]
905    fn http_requests_and_mail_become_effects() {
906        let config = EffectsConfig::from_args(
907            &["http".into(), "smtp".into()],
908            &["HOOK=http-url".into()],
909            None,
910            None,
911        )
912        .unwrap()
913        .unwrap();
914        let sinks = Sinks::start(&config).unwrap();
915        let env: BTreeMap<String, String> = sinks.env().into_iter().collect();
916        let http: u16 = env["HOOK"].rsplit(':').next().unwrap().parse().unwrap();
917        let smtp: u16 = env["SMTP_PORT"].parse().unwrap();
918        let reply = send(
919            http,
920            "POST http://hooks.example/new HTTP/1.1\r\nHost: hooks.example\r\nContent-Type: application/json\r\nContent-Length: 7\r\n\r\n{\"a\":1}",
921        );
922        assert!(reply.starts_with("HTTP/1.1 200"), "{reply}");
923        let mut mail = TcpStream::connect(("127.0.0.1", smtp)).unwrap();
924        mail.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
925        mail.write_all(
926            b"EHLO me\r\nMAIL FROM:<a@x.test>\r\nRCPT TO:<b@y.test>\r\nDATA\r\nSubject: hi\r\n\r\n..dot\r\n.\r\nQUIT\r\n",
927        )
928        .unwrap();
929        let mut out = String::new();
930        let _ = mail.read_to_string(&mut out);
931        assert!(out.contains("221"), "{out}");
932        let text = String::from_utf8(sinks.take(Path::new("."), Path::new("."))).unwrap();
933        assert_eq!(
934            text,
935            "http POST http://hooks.example/new\ncontent-type: application/json\n\n{\"a\":1}\n\
936             smtp from <a@x.test> to <b@y.test>\nSubject: hi\npart text/plain\n.dot\n"
937        );
938        assert!(sinks.take(Path::new("."), Path::new(".")).is_empty());
939    }
940
941    #[test]
942    fn smtp_raw_records_unparsed_mime_data() {
943        let config = EffectsConfig::from_args(&["smtp-raw".into()], &[], None, None)
944            .unwrap()
945            .unwrap();
946        assert!(config.smtp && !config.smtp_parts);
947        let sinks = Sinks::start(&config).unwrap();
948        let env: BTreeMap<String, String> = sinks.env().into_iter().collect();
949        let smtp: u16 = env["SMTP_PORT"].parse().unwrap();
950        let mut mail = TcpStream::connect(("127.0.0.1", smtp)).unwrap();
951        mail.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
952        mail.write_all(
953            b"EHLO me\r\nMAIL FROM:<a@x.test>\r\nRCPT TO:<b@y.test>\r\nDATA\r\nX-Custom: keep\r\nSubject: hi\r\n\r\n..dot\r\n.\r\nQUIT\r\n",
954        )
955        .unwrap();
956        let mut out = String::new();
957        let _ = mail.read_to_string(&mut out);
958        assert!(out.contains("221"), "{out}");
959        let text = String::from_utf8(sinks.take(Path::new("."), Path::new("."))).unwrap();
960        assert_eq!(
961            text,
962            "smtp from <a@x.test> to <b@y.test>\nX-Custom: keep\nSubject: hi\n\n.dot\n"
963        );
964    }
965
966    #[test]
967    fn a_config_saved_before_smtp_parts_keeps_recording_raw_mail() {
968        let old: EffectsConfig = serde_json::from_str(r#"{"smtp":true}"#).unwrap();
969        assert!(old.smtp && !old.smtp_parts);
970        let parts = EffectsConfig::from_args(&["smtp".into()], &[], None, None)
971            .unwrap()
972            .unwrap();
973        assert!(parts.smtp_parts);
974        let saved: EffectsConfig =
975            serde_json::from_str(&serde_json::to_string(&parts).unwrap()).unwrap();
976        assert_eq!(saved, parts);
977        let env_only = EffectsConfig::from_args(&[], &["MAIL=smtp-url".into()], None, None)
978            .unwrap()
979            .unwrap();
980        assert!(env_only.smtp_parts);
981        let raw = EffectsConfig::from_args(&["smtp,smtp-raw".into()], &[], None, None)
982            .unwrap()
983            .unwrap();
984        assert!(raw.smtp && !raw.smtp_parts);
985    }
986
987    #[test]
988    fn effect_arguments_are_checked() {
989        assert!(
990            EffectsConfig::from_args(&[], &[], None, None)
991                .unwrap()
992                .is_none()
993        );
994        assert!(EffectsConfig::from_args(&["ftp".into()], &[], None, None).is_err());
995        assert!(EffectsConfig::from_args(&[], &["X".into()], None, None).is_err());
996        let c = EffectsConfig::from_args(&[], &["URL=smtp-url".into()], None, Some("cat db"))
997            .unwrap()
998            .unwrap();
999        assert!(c.smtp && !c.http && c.serial());
1000    }
1001}