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
//! 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;
use wasmparser::Payload;

mod cgi;
mod wcgi;

/// 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,
    Wcgi,
}

impl CgiDialect {
    pub const CUSTOM_SECTION_NAME: &str = "cgi-dialect";

    /// Try to identify which [`CgiDialect`] should be used based on the
    /// WebAssembly module's binary representation.
    ///
    /// # Implementation Notes
    ///
    /// This currently works by looking through the WebAssembly binary for a
    /// custom section called [`CgiDialect::CUSTOM_SECTION_NAME`] and matching
    /// it against one of the known CGI dialects.
    ///
    /// This whole process is kinda hacky because it means you need to alter
    /// your binary to include the custom section. In the future, the CGI
    /// dialect should be specified using some external mechanism like metadata.
    pub fn from_wasm(wasm: &[u8]) -> Option<CgiDialect> {
        let dialect_sections = wasmparser::Parser::new(0)
            .parse_all(wasm)
            .filter_map(|p| match p {
                Ok(Payload::CustomSection(custom))
                    if custom.name() == CgiDialect::CUSTOM_SECTION_NAME =>
                {
                    Some(custom.data())
                }
                _ => None,
            });

        for data in dialect_sections {
            let dialect = std::str::from_utf8(data).ok().and_then(|s| s.parse().ok());
            if let Some(dialect) = dialect {
                return Some(dialect);
            }
        }

        None
    }

    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),
            CgiDialect::Wcgi => wcgi::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,
            CgiDialect::Wcgi => wcgi::extract_response_header(stdout).await,
        }
    }

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

impl FromStr for CgiDialect {
    type Err = UnknownCgiDialect;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "rfc-3875" => Ok(CgiDialect::Rfc3875),
            "wcgi" => Ok(CgiDialect::Wcgi),
            _ => 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, CgiDialect::Wcgi];

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