aboutsummaryrefslogtreecommitdiff
path: root/src/modules/cgi.rs
blob: 121bcacc4ec309fcd98bd473f6c52b4393061396 (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
/*
    This file is part of gnix (https://codeberg.org/metamuffin/gnix)
    which is licensed under the GNU Affero General Public License (version 3); see /COPYING.
    Copyright (C) 2025 metamuffin <metamuffin.org>
*/
use super::{Node, NodeContext, NodeKind, NodeRequest, NodeResponse};
use crate::error::ServiceError;
use anyhow::{anyhow, Result};
use futures::TryStreamExt;
use http_body_util::{combinators::BoxBody, BodyExt, StreamBody};
use hyper::{
    body::Frame,
    header::{HeaderName, HeaderValue, CONTENT_LENGTH, CONTENT_TYPE},
    Response, StatusCode,
};
use serde::Deserialize;
use serde_yml::Value;
use std::{
    collections::BTreeMap, future::Future, io::ErrorKind, path::PathBuf, pin::Pin, process::Stdio,
    str::FromStr, sync::Arc,
};
use tokio::{
    io::{copy, AsyncBufReadExt, BufReader, BufWriter},
    process::Command,
    spawn,
};
use tokio_util::io::{ReaderStream, StreamReader};
use users::get_user_by_name;

pub struct CgiKind;

#[derive(Deserialize)]
struct CgiConfig {
    bin: PathBuf,
    #[serde(default)]
    env: BTreeMap<String, String>,
    user: Option<String>,
    #[serde(default)]
    args: Vec<String>,
}

struct Cgi {
    config: CgiConfig,
    user: Option<u32>,
}

impl NodeKind for CgiKind {
    fn name(&self) -> &'static str {
        "cgi"
    }
    fn instanciate(&self, config: Value) -> Result<Arc<dyn Node>> {
        Ok(Arc::new(Cgi::new(serde_yml::from_value::<CgiConfig>(
            config,
        )?)?))
    }
}
impl Cgi {
    pub fn new(config: CgiConfig) -> Result<Self> {
        Ok(Self {
            user: config
                .user
                .as_ref()
                .map(|u| {
                    get_user_by_name(u)
                        .map(|u| u.uid())
                        .ok_or(anyhow!("user does not exist"))
                })
                .transpose()?,
            config,
        })
    }
}
impl Node for Cgi {
    fn handle<'a>(
        &'a self,
        context: &'a mut super::NodeContext,
        request: super::NodeRequest,
    ) -> Pin<Box<dyn Future<Output = Result<NodeResponse, ServiceError>> + Send + Sync + 'a>> {
        Box::pin(async move {
            let mut command = Command::new(&self.config.bin);
            command.stdin(Stdio::piped());
            command.stdout(Stdio::piped());
            command.stderr(Stdio::inherit());
            if let Some(uid) = self.user {
                command.uid(uid);
            }

            command.envs(&self.config.env);
            command.args(&self.config.args);

            set_cgi_variables(&mut command, &request, context);

            let mut child = command.spawn()?;
            let mut stdout = BufReader::new(child.stdout.take().unwrap());
            let mut stdin = BufWriter::new(child.stdin.take().unwrap());

            // TODO prevent abuse
            let mut body = StreamReader::new(
                request
                    .into_body()
                    .into_data_stream()
                    .map_err(|_| std::io::Error::new(ErrorKind::BrokenPipe, "asd")),
            );
            spawn(async move { copy(&mut body, &mut stdin).await });

            let mut line = String::new();
            let mut response = Response::new(());
            loop {
                line.clear();
                stdout.read_line(&mut line).await?;
                let line = line.trim();
                if line.is_empty() {
                    break;
                }
                let (key, value) = line.split_once(":").ok_or(ServiceError::Other)?;
                let value = value.trim();
                if key == "Status" {
                    *response.status_mut() = StatusCode::from_u16(
                        value.split_once(" ").unwrap_or((value, "")).0.parse()?,
                    )
                    .map_err(|_| ServiceError::InvalidHeader)?;
                } else {
                    response.headers_mut().insert(
                        HeaderName::from_str(key).map_err(|_| ServiceError::InvalidHeader)?,
                        HeaderValue::from_str(value).map_err(|_| ServiceError::InvalidHeader)?,
                    );
                }
            }
            Ok(response.map(|()| {
                BoxBody::new(StreamBody::new(
                    ReaderStream::new(stdout)
                        .map_ok(Frame::data)
                        .map_err(ServiceError::Io),
                ))
            }))
        })
    }
}

pub fn set_cgi_variables(command: &mut Command, request: &NodeRequest, context: &NodeContext) {
    command.env(
        "CONTENT_LENGTH",
        request
            .headers()
            .get(CONTENT_LENGTH)
            .and_then(|x| x.to_str().ok())
            .unwrap_or_default(),
    );
    command.env(
        "CONTENT_TYPE",
        request
            .headers()
            .get(CONTENT_TYPE)
            .and_then(|x| x.to_str().ok())
            .unwrap_or_default(),
    );
    command.env("GATEWAY_INTERFACE", "CGI/1.1");
    command.env("PATH_INFO", request.uri().path());
    command.env("PATH_TRANSLATED", request.uri().path());
    command.env("QUERY_STRING", request.uri().query().unwrap_or_default());
    command.env("REMOTE_ADDR", context.addr.to_string());
    // command.env("REMOTE_HOST", ));
    // command.env("REMOTE_IDENT", ));
    // command.env("REMOTE_USER", ));
    command.env("REQUEST_METHOD", request.method().to_string());
    // command.env("SCRIPT_NAME", );
    // command.env("SERVER_NAME", );
    // command.env("SERVER_PORT", );
    command.env("SERVER_PROTOCOL", "HTTP/1.1");
    command.env("SERVER_SOFTWARE", "gnix");
}