~mort/coffeepaste

ref: 35551150dde6d30855952c8e06d95795e8c25ef5 coffeepaste/src/main.rs -rw-r--r-- 14.0 KiB
35551150Martin Dørum load config at runtime rather than compile time 5 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
mod purge;
mod exif;
mod mime;

use serde_derive::Deserialize;
use log::{debug, info, error};
use once_cell::sync::OnceCell;
use std::borrow::Cow::Borrowed;
use std::convert::Infallible;
use std::fs;
use std::fs::{OpenOptions, File};
use std::io;
use std::io::{Write, SeekFrom};
use std::path::Path;
use std::net::SocketAddr;
use std::iter;
use std::error::Error;
use std::time::Duration;
use std::os::unix::io::AsRawFd;
use std::thread;
use toml;
use tokio;
use tokio::io::AsyncSeekExt;
use tokio_util::codec::{BytesCodec, FramedRead};
use futures::stream::StreamExt;
use rand::{Rng, thread_rng};
use rand::distributions::Alphanumeric;
use hyper::{Body, Method, Request, Response, Server};
use hyper::service::{make_service_fn, service_fn};
use hyper::header;

static INDEX_HTML: &'static [u8] = include_bytes!("../web/index.html");
static VIEW_HTML: &'static [u8] = include_bytes!("../web/view.html");
static ALBUM_HTML: &'static [u8] = include_bytes!("../web/album.html");
static FAVICON_ICO: &'static [u8] = include_bytes!("../web/favicon.ico");
static VENDOR_HIGHLIGHT_JS: &'static [u8] = include_bytes!("../web/vendor/highlight.min.js");
static VENDOR_HIGHLIGHT_CSS: &'static [u8] = include_bytes!("../web/vendor/highlight.min.css");
static ERR_400_HTML: &'static [u8] = include_bytes!("../web/400.html");
static ERR_404_HTML: &'static [u8] = include_bytes!("../web/404.html");
static ERR_413_HTML: &'static [u8] = include_bytes!("../web/413.html");
static ERR_500_HTML: &'static [u8] = include_bytes!("../web/500.html");

static CONFIG: OnceCell<Config> = OnceCell::new();

#[derive(Deserialize, Debug)]
struct Config {
    data: String,
    expiration_days: i64,
    listen: String,
    max_file_size: i64,
    url: String,
}

impl std::default::Default for Config {
    fn default() -> Self {
        Self {
            data: "./data".into(),
            expiration_days: 30,
            listen: "127.0.0.1:8080".into(),
            max_file_size: 10000000,
            url: "http://localhost:8080".into(),
        }
    }
}

fn parse_range(range: &str) -> Result<(u64, Option<u64>), Box<dyn Error>> {
    let range = range.split("bytes=").nth(1).ok_or("Missing 'bytes='")?;

    let mut parts = range.split("-");
    let from = parts.next().unwrap().parse::<u64>()?;
    let to = match parts.next() {
        Some("") => None,
        Some(to) => Some(to.parse::<u64>()?),
        None => None,
    };

    return Ok((from, to));
}

async fn serve_file(path: &Path, mime: &str, req: &Request<Body>)-> Result<Response<Body>, Box<dyn Error>> {
    let mut file = match tokio::fs::File::open(path).await {
        Err(err) => {
            error!("Couldn't open {}: {}", path.display(), err);
            return Ok(respond_404()?);
        },
        Ok(file) => file,
    };

    let meta = file.metadata().await?;

    // Update access time (to keep track of the latest access)
    // Don't change atime, because I don't want to use a value which
    // is likely to be updated by programs other than coffeepaste
    purge::update_access(
        file.as_raw_fd(),
        meta.modified()?)?;

    let content_type;
    if mime.starts_with("text/") {
        content_type = format!("{}; charset=utf-8", mime);
    } else {
        content_type = mime.to_string();
    }

    let rb = Response::builder()
        .header(header::CONTENT_TYPE, content_type)
        .header(header::ACCEPT_RANGES, "bytes")
        .header(header::X_CONTENT_TYPE_OPTIONS, "nosniff");

    if let Some(h) = req.headers().get(header::RANGE) {
        let (start, end) = match parse_range(h.to_str()?) {
            Err(err) => {
                error!("Failed to parse range: {}", err);
                return Ok(respond_400()?);
            },
            Ok(range) => range,
        };

        file.seek(SeekFrom::Start(start)).await?;

        if let Some(end) = end {
            let len = (end - start + 1) as usize;
            return Ok(rb
                .status(206)
                .header(header::CONTENT_LENGTH, &len.to_string())
                .body(Body::wrap_stream(FramedRead::new(file, BytesCodec::new()).take(len)))
                .unwrap());
        } else {
            return Ok(rb
                .status(206)
                .header(header::CONTENT_LENGTH, &(meta.len() - start).to_string())
                .body(Body::wrap_stream(FramedRead::new(file, BytesCodec::new())))
                .unwrap());
        }
    } else {
        return Ok(rb
            .status(200)
            .header(header::CONTENT_LENGTH, &meta.len().to_string())
            .body(Body::wrap_stream(FramedRead::new(file, BytesCodec::new())))
            .unwrap());
    }
}

fn is_illegal_name(name: &str) -> bool {
    return
        name == "index" ||
        name == "favicon" ||
        name == "vendor" ||
        name == "a";
}

fn create_random_file(dir: &str) -> io::Result<(File, String)> {
    let mut len = 3;
    let mut rng = thread_rng();
    loop {
        let name: String = iter::repeat(())
            .map(|()| rng.sample(Alphanumeric))
            .map(char::from)
            .take(len)
            .collect();
        if is_illegal_name(&name) {
            continue;
        }

        let pathbuf = Path::new(dir).join(&name);
        let path = pathbuf.to_string_lossy().to_string();
        len += 1;

        let file = OpenOptions::new()
            .create_new(true).write(true).open(&path);

        match file {
            Err(err) => match err.kind() {
                io::ErrorKind::AlreadyExists => continue,
                _ => return Err(err),
            },
            Ok(file) => return Ok((file, name)),
        };
    }
}

fn delete_file(dir: &str, name: &str) {
    let pathbuf = Path::new(dir).join(name);
    if let Err(err) = fs::remove_file(pathbuf) {
        error!("Failed to remove {}/{}: {}", dir, name, err);
    }
}

fn request_prefers_raw(req: &Request<Body>) -> bool {
    let headers = req.headers();
    let accept = headers.get(header::ACCEPT);
    if let None = accept {
        return true;
    }

    let accept = accept.unwrap().to_str();
    if let Err(_err) = accept {
        return true;
    }

    let accept = accept.unwrap();
    for s in accept.split(",") {
        match &s.trim().to_ascii_lowercase() as &str {
            "text/html" => return false, // Prefers HTML
            "*/*" => return true, // Prefers whatever before HTML
            "text/plain" => return false, // Prefers text/plain before HTML
            _ => (),
        }
    }

    return false;
}

fn respond_400() -> Result<Response<Body>, Infallible> {
    Ok(Response::builder().status(400)
       .header(header::CONTENT_TYPE, "text/html")
       .body(Body::from(ERR_400_HTML)).unwrap())
}

fn respond_404() -> Result<Response<Body>, Infallible> {
    Ok(Response::builder().status(404)
       .header(header::CONTENT_TYPE, "text/html")
       .body(Body::from(ERR_404_HTML)).unwrap())
}

fn respond_413() -> Result<Response<Body>, Infallible> {
    Ok(Response::builder().status(413)
       .header(header::CONTENT_TYPE, "text/html")
       .body(Body::from(ERR_413_HTML)).unwrap())
}

fn respond_500() -> Result<Response<Body>, Infallible> {
    Ok(Response::builder().status(500)
       .header(header::CONTENT_TYPE, "text/html")
       .body(Body::from(ERR_500_HTML)).unwrap())
}

async fn on_get(config: &Config, req: Request<Body>) -> Result<Response<Body>, Box<dyn Error>> {
    let path = req.uri().path();
    if path == "/" || path == "/index.html" {
        return Ok(Response::builder()
            .header(header::CONTENT_TYPE, "text/html")
            .body(Body::from(INDEX_HTML))?);
    } else if path.starts_with("/a/") {
        return Ok(Response::builder()
            .header(header::CONTENT_TYPE, "text/html")
            .body(Body::from(ALBUM_HTML))?);
    } else if path == "/a" {
        return Ok(Response::builder()
            .status(302)
            .header(header::LOCATION, "/a/")
            .body(Body::from("Redirect"))?);
    } else if path == "/favicon.ico" {
        return Ok(Response::builder()
            .header(header::CONTENT_TYPE, "image/x-icon")
            .body(Body::from(FAVICON_ICO))?);
    } else if path == "/vendor/highlight.js" {
        return Ok(Response::builder()
            .header(header::CONTENT_TYPE, "application/javascript")
            .body(Body::from(VENDOR_HIGHLIGHT_JS))?);
    } else if path == "/vendor/highlight.css" {
        return Ok(Response::builder()
            .header(header::CONTENT_TYPE, "text/css")
            .body(Body::from(VENDOR_HIGHLIGHT_CSS))?);
    }

    let name = &path[1..];

    // Two slashes after each other is probably just an error
    let firstchar = name.chars().next();
    if firstchar.is_none() || firstchar.unwrap() == '/' {
        return Ok(respond_404()?);
    }

    let extension = match &Path::new(path).extension() {
        Some(ext) => Some(ext.to_string_lossy()),
        None => None,
    };

    // If we have an extension, we need to serve with the appropriate Content-Type
    let mime = match &extension {
        Some(ext) => mime::from_ext(&ext),
        None => None,
    };

    // /ID.<extension> serves a page with javascript which does syntax highlighting,
    // if the extension/mime is a type associated with a plain-text file type
    // (and if the request is from a device which prefers HTML to plain text)
    if mime::is_plain_text(extension.as_deref(), mime) {
        if !request_prefers_raw(&req) {
            return Ok(Response::builder()
                .header(header::CONTENT_TYPE, "text/html")
                .body(Body::from(VIEW_HTML))?);
        }
    }

    // Serve the actual file
    let mut pathbuf = Path::new(&config.data as &str).join(&name);
    pathbuf.set_extension("");
    return serve_file(&pathbuf, mime.unwrap_or_else(|| "text/plain"), &req).await;
}

async fn on_put(config: &Config, req: Request<Body>) -> Result<Response<Body>, Infallible> {
    let (parts, mut reqbody) = req.into_parts();
    let pathstr = parts.uri.path();
    let path = Path::new(pathstr);
    let extension = path.extension().map(|ext| ext.to_string_lossy());
    let mut guess = match &extension {
        Some(ext) => mime::from_ext(&ext),
        None => None,
    };

    // Try to figure out what extension we should return based on the user's path
    let mut result_ext = match guess {
        Some(_) => extension,
        None => None,
    };

    let (mut file, name) = match create_random_file(&config.data) {
        Err(err) => {
            error!("Failed to create random file: {}", err);
            return Ok(Response::builder()
                .status(500)
                .body(Body::from(ERR_500_HTML))
                .unwrap());
        },
        Ok((file, name)) => (file, name),
    };

    info!("Created file '{}/{}'", config.data, name);

    let mut bodysize: usize = 0;
    let mut first = true;
    loop {
        let chunk = match reqbody.next().await {
            Some(chunkres) => match chunkres {
                Err(err) => {
                    error!("Upload file transfer error: {}", err);
                    delete_file(&config.data, &name);
                    return respond_500();
                },
                Ok(chunk) => chunk,
            },
            None => {
                break;
            },
        };

        // If we don't have an extension yet, see if we can guess one from the content
        if result_ext.is_none() && first {
            let (e, g) = mime::ext_from_file_content(&chunk);
            result_ext = e.map(|s| Borrowed(s));
            guess = g;
            first = false;
        }

        if bodysize + chunk.len() > config.max_file_size as usize {
            error!("Uploaded file exceeds max size ({} bytes)", config.max_file_size);
            delete_file(&config.data, &name);
            return respond_413();
        }

        bodysize += chunk.len();
        if let Err(err) = file.write(&chunk) {
            error!("File write error: {}", err);
            delete_file(&config.data, &name);
            return respond_500();
        }
    };

    let mut url = config.url.to_string() + "/" + &name;
    if let Some(e) = result_ext {
        url.push_str(".");
        url.push_str(&e);
    }

    // Privacy
    if guess == Some("image/jpeg") {
        exif::strip(&config.data, &name);
    }

    return Ok(Response::builder().status(201)
       .header(header::CONTENT_TYPE, "text/plain; charset=utf-8")
       .header(header::CONTENT_LOCATION, &url)
       .body(Body::from(url + "\n")).unwrap());
}

async fn on_request(config: &Config, req: Request<Body>) -> Result<Response<Body>, Infallible> {
    debug!("{} {}", req.method(), req.uri());

    let res = match req.method() {
        &Method::GET | &Method::HEAD => on_get(&config, req).await,
        &Method::PUT => Ok(on_put(&config, req).await?),
        _ => Ok(respond_404()?),
    };

    if let Err(res) = res {
        error!("Error: {}", res);
        return respond_500();
    } else {
        return Ok(res.unwrap());
    }
}

#[tokio::main]
async fn main() {
    let _ = env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
    debug!("Logger initialized");

    if let Ok(confstr) = fs::read_to_string("config.toml") {
        CONFIG.set(toml::from_str(&confstr).unwrap()).unwrap();
    } else {
        CONFIG.set(Config::default()).unwrap();
    }

    let addr: SocketAddr = CONFIG.get().unwrap().listen.parse()
        .expect("Unable to parse socket address");

    let make_svc = make_service_fn(|_conn| async {
        return Ok::<_, Infallible>(service_fn(
                |req: Request<Body>| on_request(CONFIG.get().unwrap(), req)));
    });

    // Purge thread
    let _purge_thread = thread::spawn(|| {
        let conf = CONFIG.get().unwrap();
        let expiration = Duration::from_secs(
            ((conf.expiration_days as f64) * ((60 * 60 * 24) as f64)) as u64);

        loop {
            purge::purge(&conf.data, expiration);
            thread::sleep(Duration::from_secs(10 * 60));
        }
    });

    let server = Server::bind(&addr).serve(make_svc);

    info!("Server listening on {}", addr);

    if let Err(e) = server.await {
        error!("Server error: {}", e);
        std::process::exit(1);
    }
}