~zethra/stargazer

ref: 0d90acda5b1c79a14699af75a40a4675040f567c stargazer/src/router.rs -rw-r--r-- 8.4 KiB
0d90acda — Ben Aaron Goldberg docs: update changelog 3 months ago
                                                                                
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
// stargazer - A Gemini Server
// Copyright (C) 2021 Ben Aaron Goldberg <ben@benaaron.dev>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

use crate::error::{bad_req, error, Context, ErrorConv, GemError, Result};
use crate::CONF;
use async_net::SocketAddr;
use regex::Captures;
use std::convert::From;
use std::convert::TryFrom;
use std::path::PathBuf;
use users::User;

#[derive(Debug, Clone)]
pub struct Route {
    /// Domain for site
    pub domain: String,
    /// Routing directive
    pub path: RoutePath,
    /// Rewrite rule
    pub rewrite: Option<String>,
    pub lang: Option<String>,
    pub charset: Option<String>,
    pub route_type: RouteType,
}

#[derive(Debug, Clone)]
pub enum RouteType {
    Static(StaticRoute),
    Cgi(CGIRoute),
    Scgi(SCGIRoute),
    Redirect(RedirectRoute),
}

#[derive(Debug, Clone)]
pub struct StaticRoute {
    /// Path to serve files from
    pub root: PathBuf,
    /// Index file name
    pub index: String,
    /// Auto generate index
    pub auto_index: bool,
}

impl From<StaticRoute> for RouteType {
    fn from(route: StaticRoute) -> Self {
        RouteType::Static(route)
    }
}

#[derive(Debug, Clone)]
pub struct CGIRoute {
    /// Path to serve files from
    pub root: PathBuf,
    /// Index file name
    pub index: String,
    /// User to run CGI process as
    pub user: Option<User>,
    /// Timeout for request to complete
    pub timeout: Option<u64>,
}

impl From<CGIRoute> for RouteType {
    fn from(route: CGIRoute) -> Self {
        RouteType::Cgi(route)
    }
}

#[derive(Debug, Clone)]
pub struct SCGIRoute {
    /// SCGI address (either unix socket of TCP)
    pub addr: SCGIAddress,
    /// Timeout for request to complete
    pub timeout: Option<u64>,
}

impl From<SCGIRoute> for RouteType {
    fn from(route: SCGIRoute) -> Self {
        RouteType::Scgi(route)
    }
}

#[derive(Debug, Clone)]
pub enum SCGIAddress {
    Unix(PathBuf),
    Tcp(SocketAddr),
}

#[derive(Debug, Clone)]
pub struct RedirectRoute {
    pub permanent: bool,
    pub url: String,
}

impl From<RedirectRoute> for RouteType {
    fn from(route: RedirectRoute) -> Self {
        RouteType::Redirect(route)
    }
}

#[derive(Debug, Clone)]
pub enum RoutePath {
    All,
    Prefix(String),
    Exact(String),
    Regex(Box<regex::Regex>),
}

#[allow(clippy::blocks_in_if_conditions)]
pub fn route(uri: &str) -> Result<(&'static Route, Request)> {
    let mut req = Request::from_uri(uri)?;

    let mut domain_found = false;

    for site in &CONF.routes {
        if site.domain != req.host {
            continue;
        }
        domain_found = true;
        if match &site.path {
            RoutePath::All => true,
            RoutePath::Prefix(s) => req.path.starts_with(s),
            RoutePath::Exact(s) => req.path == *s,
            RoutePath::Regex(r) => {
                if let Some(captures) = r.captures(&req.path) {
                    if let Some(rewrite) = &site.rewrite {
                        if rewrite.contains('\\') {
                            let new_path = do_rewrite(&rewrite, captures)
                                .map_err(|e| {
                                    GemError::ServerError(
                                        e.unwrap_err().context(format!(
                                            "Error doing rewrite {}",
                                            rewrite
                                        )),
                                    )
                                })?;
                            req.path = new_path;
                        } else {
                            req.path = rewrite.clone();
                        };
                    }
                    true
                } else {
                    false
                }
            }
        } {
            return Ok((site, req));
        }
    }
    if domain_found {
        Err(GemError::NotFound)
    } else {
        Err(GemError::NoProxy(anyhow::anyhow!(
            "No route for host: {}",
            req.host
        )))
    }
}

fn do_rewrite(input: &str, captures: Captures<'_>) -> Result<String> {
    #[derive(PartialEq, Eq, Debug)]
    enum State {
        Text,
        Capture,
        Named(String),
    }
    let mut state = State::Text;
    let mut output = String::with_capacity(input.len());
    for c in input.chars() {
        match &mut state {
            State::Text if c == '\\' => state = State::Capture,
            State::Text => output.push(c),
            State::Capture if c.is_digit(10) => {
                let idx = c.to_digit(10).unwrap() as usize;
                let capture = captures.get(idx).with_context(|| {
                    format!("Url didn't contain capture `{}`", idx)
                })?;
                output.push_str(capture.as_str());
                state = State::Text;
            }
            State::Capture if c == '{' => state = State::Named(String::new()),
            // Backslash followed by a char that isn't a number or '{' is invalid
            State::Capture => return Err(error("Invalid rewrite directive")),
            State::Named(s) if c == '}' => {
                let capture = captures.name(s).with_context(|| {
                    format!("Url didn't contain capture `{}`", s)
                })?;
                output.push_str(capture.as_str());
                state = State::Text;
            }
            State::Named(s) => {
                s.push(c);
            }
        }
    }
    if state != State::Text {
        return Err(error(
            "Invalid rewrite directive, incomplete capture directive",
        ));
    }
    Ok(output)
}

#[derive(Debug)]
pub struct Request {
    pub uri: String,
    pub path: String,
    pub query: String,
    pub host: String,
}

impl Request {
    fn from_uri(uri_str: &str) -> Result<Request> {
        use uriparse::URIReference;

        if uri_str.is_empty() {
            return Err(bad_req("Empty URL"));
        }

        let mut uri = URIReference::try_from(uri_str)
            .with_context(|| format!("Bad URI: {}", uri_str))
            .into_bad_req()?;

        let mut path = uri.path().to_owned();
        let authority = uri
            .authority()
            .context("Username and password URI fields not allowed")
            .into_bad_req()?;
        if authority.has_password() || authority.has_username() {
            return Err(bad_req(
                "Username and password URI fields not allowed",
            ));
        }
        let host = authority.host().to_string().to_lowercase();
        let port = authority.port();
        let scheme = uri
            .scheme()
            .context("URI mush have a scheme")
            .into_bad_req()?;
        if scheme.as_str() != "gemini" {
            return Err(GemError::NoProxy(anyhow::anyhow!(
                "Schema {} not supported",
                scheme
            )));
        }

        if let Some(port) = port {
            if !CONF
                .listen
                .iter()
                .fold(false, |found, addr| (addr.port() == port) || found)
            {
                return Err(GemError::NoProxy(anyhow::anyhow!(
                    "Port {} not listened on",
                    port
                )));
            }
        }

        if host.is_empty() {
            return Err(bad_req("No relative URLs"));
        }

        if !path.is_normalized(false) {
            path.normalize(false);
            uri.set_path(path).context("Path normalization failed")?;
            return Err(GemError::Redirect(uri.to_string()));
        }
        let query = uri.query().map(|v| v.as_str()).unwrap_or("").to_owned();

        Ok(Request {
            uri: uri.to_string(),
            host,
            query,
            path: path.to_string(),
        })
    }
}

use std::fmt::{self, Display, Formatter};

impl Display for Request {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        self.uri.fmt(f)
    }
}