~int80h/gemserv

ref: 4fb31bec38be0cc0cf0780744c6f1b4036b1ff3f gemserv/src/main.rs -rw-r--r-- 15.4 KiB
4fb31becint 80h Small amount of refactoring 6 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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
#[macro_use]
extern crate serde_derive;

use futures_util::future::TryFutureExt;
use new_mime_guess;
use openssl::ssl::NameType;
use std::env;
use std::fs;
use std::pin::Pin;
use std::fs::File;
use std::io::{self, BufRead, BufReader};
use std::net::ToSocketAddrs;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use tokio::net::TcpListener;
use tokio::io::AsyncReadExt;
use tokio::runtime;
use url::Url;

mod cgi;
mod config;
mod status;
use status::Status;
mod conn;
mod logger;
mod revproxy;
mod tls;
mod util;

fn get_mime(path: &PathBuf) -> String {
    let mut mime = "text/gemini".to_string();
    if path.is_dir() {
        return mime;
    }
    let ext = match path.extension() {
        Some(p) => p.to_str().unwrap(),
        None => return "text/plain".to_string(),
    };

    mime = match new_mime_guess::from_ext(ext).first() {
        Some(m) => m.essence_str().to_string(),
        None => "text/plain".to_string(),
    };

    return mime;
}

async fn get_binary(mut con: conn::Connection, path: PathBuf, meta: String) -> io::Result<()> {
    let fd = File::open(path)?;
    let mut reader = BufReader::with_capacity(1024 * 1024, fd);
    con.send_status(status::Status::Success, Some(&meta))
        .await?;
    loop {
        let len = {
            let buf = reader.fill_buf()?;
            con.send_raw(buf).await?;
            buf.len()
        };
        if len == 0 {
            break;
        }
        reader.consume(len);
    }
    Ok(())
}

async fn get_content(path: PathBuf, u: &url::Url) -> Result<String, io::Error> {
    let meta = tokio::fs::metadata(&path).await?;
    if meta.is_file() {
        return Ok(tokio::fs::read_to_string(path).await?);
    }

    let mut dirs: Vec<String> = Vec::new();
    let mut files: Vec<String> = Vec::new();

    // needs work
    for file in fs::read_dir(&path)? {
        if let Ok(file) = file {
            let m = file.metadata()?;
            let perm = m.permissions();
            if perm.mode() & 0o0444 != 0o0444 {
                continue;
            }
            let file = file.path();
            let p = file.strip_prefix(&path).unwrap();
            let ps = match p.to_str() {
                Some(s) => s,
                None => continue,
            };
            let ep = match u.join(ps) {
                Ok(p) => p,
                _ => continue,
            };
            if m.is_dir() {
                dirs.push(format!("=> {}/ {}/\r\n", ep, p.display()));
            } else {
                files.push(format!("=> {} {}\r\n", ep, p.display()));
            }
        }
    }

    dirs.sort();
    files.sort();

    let mut list = String::from("# Directory Listing\r\n\r\n");
    list.push_str(&format!("Path: {}\r\n\r\n", u.path()));

    for dir in dirs {
        list.push_str(&dir);
    }
    for file in files {
        list.push_str(&file);
    }

    return Ok(list);
}

// Handle CGI and return Ok(true), or indicate this request wasn't for CGI with Ok(false)
#[cfg(feature = "cgi")]
async fn handle_cgi(
    con: &mut conn::Connection,
    request: &str,
    url: &Url,
    full_path: &PathBuf,
) -> Result<bool, io::Error> {
    if con.srv.server.cgi.unwrap_or(false) {
        let mut path = full_path.clone();
        let mut segments = url.path_segments().unwrap();
        let mut path_info = "".to_string();

        // Find an ancestor url that matches a file
        while !path.exists() {
            if let Some(segment) = segments.next_back() {
                path.pop();
                path_info = format!("/{}{}", &segment, path_info);
            } else {
                return Ok(false);
            }
        }
        let script_name = format!("/{}", segments.collect::<Vec<_>>().join("/"));

        let meta = tokio::fs::metadata(&path).await?;
        let perm = meta.permissions();

        match &con.srv.server.cgipath {
            Some(c) => {
            if path.starts_with(c) {
                if perm.mode() & 0o0111 == 0o0111 {
                    cgi::cgi(con, path, url, script_name, path_info).await?;
                    return Ok(true);
                } else {
                    logger::logger(con.peer_addr, Status::CGIError, request);
                    con.send_status(Status::CGIError, None).await?;
                    return Ok(true);
                }
            }
            },
            None => {
                if meta.is_file() && perm.mode() & 0o0111 == 0o0111 {
                    cgi::cgi(con, path, url, script_name, path_info).await?;
                    return Ok(true);
                }
            },
        }
    }
    Ok(false)
}

async fn get_request(mut con: conn::Connection) -> Result<(conn::Connection, url::Url), String> {
    let mut buffer = [0; 1024];
    let len = match tokio::time::timeout(tokio::time::Duration::from_secs(5), con.stream.read(&mut buffer)).await {
        Ok(result) => result.unwrap(),
        Err(e) => {
            logger::logger(con.peer_addr, Status::BadRequest, "");
            con.send_status(Status::BadRequest, None).await.map_err(|e| e.to_string())?;
            return Err(e.to_string());
        }
    };
    let mut request = match String::from_utf8(buffer[..len].to_vec()) {
        Ok(request) => request,
        Err(e) => {
            logger::logger(con.peer_addr, Status::BadRequest, "");
            con.send_status(Status::BadRequest, None).await.map_err(|e| e.to_string())?;
            return Err(e.to_string());
        }
    };
    if request.starts_with("//") {
        request = request.replacen("//", "gemini://", 1);
    }

    if request.ends_with("\n") {
        request.pop();
        if request.ends_with("\r") {
            request.pop();
        }
    }

    let url = match Url::parse(&request) {
        Ok(url) => url,
        Err(_) => {
            logger::logger(con.peer_addr, Status::BadRequest, &request);
            con.send_status(Status::BadRequest, None).await.map_err(|e| e.to_string())?;
            return Err("Bad url".to_string());
        }
    };

    if Some(con.srv.server.hostname.as_str()) != url.host_str() {
        logger::logger(con.peer_addr, Status::ProxyRequestRefused, &url.as_str());
        con.send_status(Status::ProxyRequestRefused, None).await.map_err(|e| e.to_string())?;
        return Err("Wrong host".to_string());
    }

    match url.port() {
        Some(p) => {
            if p != con.srv.port {
                logger::logger(con.peer_addr, Status::ProxyRequestRefused, &url.as_str());
                con.send_status(status::Status::ProxyRequestRefused, None)
                    .await.map_err(|e| e.to_string())?;
            }
        }
        None => {}
    }

    if url.scheme() != "gemini" {
        logger::logger(con.peer_addr, Status::ProxyRequestRefused, &url.as_str());
        con.send_status(Status::ProxyRequestRefused, None).await.map_err(|e| e.to_string())?;
        return Err("scheme not gemini".to_string());
    }
    
    return Ok((con, url))
}

// TODO Rewrite this monster.
async fn handle_connection(
    mut con: conn::Connection,
    url: url::Url
) -> Result<(), io::Error> {
    let index = match &con.srv.server.index {
        Some(i) => i.clone(),
        None => "index.gemini".to_string(),
    };

    match &con.srv.server.redirect.to_owned() {
        Some(re) => {
            let u = match url.path() {
                "/" => "/",
                _ => url.path().trim_end_matches("/"),
            };
            match re.get(u) {
                Some(r) => {
                    logger::logger(con.peer_addr, Status::RedirectTemporary, &url.as_str());
                    con.send_status(Status::RedirectTemporary, Some(r)).await?;
                    return Ok(());
                }
                None => {}
            }
        }
        None => {}
    }

    #[cfg(feature = "proxy")]
    if let Some(pr) = con.srv.server.proxy_all.to_owned() {
        let host_port: Vec<&str> = pr.splitn(2, ':').collect();
        let host = host_port[0];
        let port: Option<u16>;
        if host_port.len() == 2 {
            port = host_port[1].parse().ok();
        } else {
            port = None;
        }

        let mut upstream_url = url.clone();
        upstream_url.set_host(Some(host)).unwrap();
        upstream_url.set_port(port).unwrap();

        revproxy::proxy_all(pr.as_str(), upstream_url, con).await?;
        return Ok(());
    }

    #[cfg(feature = "proxy")]
    match &con.srv.server.proxy {
        Some(pr) => match url.path_segments().map(|c| c.collect::<Vec<_>>()) {
            Some(s) => match pr.get(s[0]) {
                Some(p) => {
                    revproxy::proxy(p.to_string(), url, con).await?;
                    return Ok(());
                }
                None => {}
            },
            None => {}
        },
        None => {}
    }

    #[cfg(feature = "scgi")]
    match &con.srv.server.scgi {
        Some(sc) => {
            let u = match url.path() {
                "/" => "/",
                _ => url.path().trim_end_matches("/"),
            };
        match sc.get(u) {
            Some(r) => {
                cgi::scgi(r.to_string(), url, con).await?;
                return Ok(());
            }
            None => {}
        }
        },
        None => {},
    }


    let mut path = PathBuf::new();

    if url.path().starts_with("/~") && con.srv.server.usrdir.unwrap_or(false) {
        let usr = url.path().trim_start_matches("/~");
        let usr: Vec<&str> = usr.splitn(2, "/").collect();
        if cfg!(target_os = "macos") {
            path.push("/Users/");
        } else {
            path.push("/home/");
        }
        if usr.len() == 2 {
            path.push(format!("{}/{}/{}", usr[0], "public_gemini", util::url_decode(usr[1].as_bytes())));
        } else {
            path.push(format!("{}/{}/", usr[0], "public_gemini"));
        }
    } else {
        path.push(&con.srv.server.dir);
        if url.path() != "" || url.path() != "/" {
            let decoded = util::url_decode(url.path().trim_start_matches("/").as_bytes());
            path.push(decoded);
        }
    }

    if !path.exists() {
        // See if it's a subpath of a CGI script before returning NotFound
        #[cfg(feature = "cgi")]
        if handle_cgi(&mut con, &url.as_str(), &url, &path).await? {
            return Ok(());
        }

        logger::logger(con.peer_addr, Status::NotFound, &url.as_str());
        con.send_status(Status::NotFound, None).await?;
        return Ok(());
    }

    let mut meta = tokio::fs::metadata(&path).await?;
    let mut perm = meta.permissions();

    // TODO fix me
    // This block is terrible
    if meta.is_dir() {
        if !url.path().ends_with("/") {
            logger::logger(con.peer_addr, Status::RedirectPermanent, &url.as_str());
            con.send_status(
                Status::RedirectPermanent,
                Some(format!("{}/", url).as_str()),
            )
            .await?;
            return Ok(());
        }
        if path.join(&index).exists() {
            path.push(index);
            meta = tokio::fs::metadata(&path).await?;
            perm = meta.permissions();
            if perm.mode() & 0o0444 != 0o444 {
                let mut p = path.clone();
                p.pop();
                path.push(format!("{}/", p.display()));
                meta = tokio::fs::metadata(&path).await?;
                perm = meta.permissions();
            }
        }
    }

    #[cfg(feature = "cgi")]
    if handle_cgi(&mut con, &url.as_str(), &url, &path).await? {
        return Ok(());
    }

    if meta.is_file() && perm.mode() & 0o0111 == 0o0111  {
        logger::logger(con.peer_addr, Status::NotFound, &url.as_str());
        con.send_status(Status::NotFound, None).await?;
        return Ok(());
    }

    if perm.mode() & 0o0444 != 0o0444  {
        logger::logger(con.peer_addr, Status::NotFound, &url.as_str());
        con.send_status(Status::NotFound, None).await?;
        return Ok(());
    }

    let mut mime = get_mime(&path);
    if mime == "text/gemini" && con.srv.server.lang.is_some() {
        mime += &("; lang=".to_string() + &con.srv.server.lang.to_owned().unwrap());
    }
    if !mime.starts_with("text/") {
        logger::logger(con.peer_addr, Status::Success, &url.as_str());
        get_binary(con, path, mime).await?;
        return Ok(());
    }
    let content = get_content(path, &url).await?;
    con.send_body(status::Status::Success, Some(&mime), Some(content))
        .await?;
    logger::logger(con.peer_addr, Status::Success, &url.as_str());

    Ok(())
}

fn main() -> io::Result<()> {
    let args: Vec<String> = env::args().collect();
    if args.len() != 2 {
        println!("Please run with the path to the config file.");
        return Ok(());
    }
    let p = Path::new(&args[1]);
    if !p.exists() {
        println!("Config file doesn't exist");
        return Ok(());
    }

    let cfg = match config::Config::new(&p) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("Config error: {}", e);
            return Ok(());
        },
    };
    let loglev = match &cfg.log {
        None => log::Level::Info,
        Some(l) => {
            match l.as_str() {
                "error" => log::Level::Error,
                "warn" => log::Level::Warn,
                "info" => log::Level::Info,
                _ => {
                    eprintln!("Incorrect log level in config file.");
                    return Ok(());
               },
            }
        },
    };
    simple_logger::init_with_level(loglev).unwrap();
    let cmap = cfg.to_map();
    let default = &cfg.server[0].hostname;
    println!("Serving {} vhosts", cfg.server.len());

    let addr = format!("{}:{}", cfg.host, cfg.port);
    addr.to_socket_addrs()?
        .next()
        .ok_or_else(|| io::Error::from(io::ErrorKind::AddrNotAvailable))?;

    let runtime = runtime::Builder::new_multi_thread()
    //    .threaded_scheduler()
        .enable_io()
        .enable_time()
        .build()?;

    let handle = runtime.handle().clone();

    let acceptor = tls::acceptor_conf(cfg.clone())?;

    let fut = async move {
        let listener = TcpListener::bind(&addr).await?;
        loop {
            let (stream, peer_addr) = listener.accept().await?;
            let acceptor = acceptor.clone();
            let cmap = cmap.clone();
            let default = default.clone();

            let ssl = openssl::ssl::Ssl::new(acceptor.context()).unwrap();
            let mut stream = tokio_openssl::SslStream::new(ssl, stream).unwrap();

            let fut = async move {
                match Pin::new(&mut stream).accept().await {
                    Ok(s) => s,
                    Err(e) => {
                        log::error!("Error: {}",e);
                        return Ok(());
                    },
                };

                let srv = match stream.ssl().servername(NameType::HOST_NAME) {
                    Some(s) => match cmap.get(s) {
                        Some(ss) => ss,
                        None => cmap.get(&default).unwrap(),
                    },
                    None => cmap.get(&default).unwrap(),
                }.to_owned();

                let con = conn::Connection { stream, peer_addr, srv };
                let (con, url) = match get_request(con).await {
                    Ok((c, u)) => (c, u),
                    Err(_) => return Ok(()) as io::Result<()>,
                };
                handle_connection(con, url).await?;

                Ok(()) as io::Result<()>
            };

            handle.spawn(fut.unwrap_or_else(|err| eprintln!("{:?}", err)));
        }
    };

    runtime.block_on(fut)
}