wcgi_host/
lib.rs

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
//! Common abstractions for implementing a WCGI host.
//!
//! # Cargo Features
//!
//! - `schemars` - will enable JSON Schema generation for certain types using the
//!   [`schemars`](https://crates.io/crates/schemars) crate

use std::{
    collections::HashMap,
    fmt::{self, Display, Formatter},
    str::FromStr,
};

use tokio::io::AsyncBufRead;

mod cgi;

/// The CGI dialect to use when running a CGI workload.
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub enum CgiDialect {
    /// The "official" CGI dialect, as defined by
    /// [RFC 3875](https://www.ietf.org/rfc/rfc3875).
    #[default]
    Rfc3875,
}

impl CgiDialect {
    pub fn prepare_environment_variables(
        self,
        parts: http::request::Parts,
        env: &mut HashMap<String, String>,
    ) {
        match self {
            CgiDialect::Rfc3875 => cgi::prepare_environment_variables(parts, env),
        }
    }

    /// Extract the [`http::response::Parts`] from a CGI script's stdout.
    ///
    /// # Note
    ///
    /// This might stall if reading from stdout stalls. Care should be taken to
    /// avoid waiting forever (e.g. by adding a timeout).
    pub async fn extract_response_header(
        self,
        stdout: &mut (impl AsyncBufRead + Unpin),
    ) -> Result<http::response::Parts, CgiError> {
        match self {
            CgiDialect::Rfc3875 => cgi::extract_response_header(stdout).await,
        }
    }

    pub const fn to_str(self) -> &'static str {
        match self {
            CgiDialect::Rfc3875 => "rfc-3875",
        }
    }
}

impl FromStr for CgiDialect {
    type Err = UnknownCgiDialect;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "rfc-3875" => Ok(CgiDialect::Rfc3875),
            _ => Err(UnknownCgiDialect),
        }
    }
}

impl Display for CgiDialect {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.to_str())
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnknownCgiDialect;

impl Display for UnknownCgiDialect {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "Unknown CGI dialect")
    }
}

impl std::error::Error for UnknownCgiDialect {}

#[derive(Debug)]
pub enum CgiError {
    StdoutRead(std::io::Error),
    InvalidHeaders {
        error: http::Error,
        header: String,
        value: String,
    },
    MalformedWcgiHeader {
        error: ::wcgi::WcgiError,
        header: String,
    },
}

impl std::error::Error for CgiError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            CgiError::StdoutRead(e) => Some(e),
            CgiError::InvalidHeaders { error, .. } => Some(error),
            CgiError::MalformedWcgiHeader { error, .. } => error.source(),
        }
    }
}

impl fmt::Display for CgiError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            CgiError::StdoutRead(_) => write!(f, "Unable to read the STDOUT pipe"),
            CgiError::InvalidHeaders { header, value, .. } => {
                write!(f, "Unable to parse header ({header}: {value})")
            }
            CgiError::MalformedWcgiHeader { header, .. } => {
                write!(f, "Unable to parse WCGI header ({header})")
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn round_trip_cgi_dialect_to_string() {
        let dialects = [CgiDialect::Rfc3875];

        for dialect in dialects {
            let repr = dialect.to_string();
            let round_tripped: CgiDialect = repr.parse().unwrap();
            assert_eq!(round_tripped, dialect);
        }
    }
}