summaryrefslogtreecommitdiffstats
path: root/l10n/en_GB.js
diff options
context:
space:
mode:
authorMorris Jobke <hey@morrisjobke.de>2019-03-08 18:36:56 +0100
committerGitHub <noreply@github.com>2019-03-08 18:36:56 +0100
commitc04c1da4c840552c946e6e475c3d754cc557cb83 (patch)
treee16a7da2d90dbc4d30fddb3ea47d249eeb06d252 /l10n/en_GB.js
parente64ee7ed5fc0fa8f1f6197e32ef9469d8f29984e (diff)
parent98028b4f513330afb4ab807d8d6a009fc33a5ff6 (diff)
Merge pull request #403 from nextcloud/version-bump13.1.0
Release 13.1.0
Diffstat (limited to 'l10n/en_GB.js')
0 files changed, 0 insertions, 0 deletions
'>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
#[macro_use] extern crate log;

mod config;
mod purge;

use config::CONFIG;
use std::convert::Infallible;
use std::fs;
use std::fs::{OpenOptions, File};
use std::io;
use std::io::Write;
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 tokio;
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::HeaderValue;
use hyper::header;

static INDEX_HTML: &'static [u8] = include_bytes!("../web/index.html");
static VIEW_HTML: &'static [u8] = include_bytes!("../web/view.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_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");

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

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))
            .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 is_plain_text(ext: &str, mime: Option<&str>) -> bool {
    fn mime_is_plain_text(mime: &str) -> bool {
        return
            mime.starts_with("text/") || (
                mime.starts_with("application/") &&
                mime != "application/octet-stream");
    }

    match ext {
        "auto" => true,
        _ => match mime {
            None => false,
            Some(mime) => mime_is_plain_text(mime),
        },
    }
}

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_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(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 == "/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 = extension.as_ref().and_then(|ext| mime_guess::from_ext(ext).first_raw());

    // /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 is_plain_text(&extension.unwrap_or(std::borrow::Cow::Borrowed("")), 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("");
    let file = tokio::fs::File::open(&pathbuf).await;
    match file {
        Err(err) => {
            error!("Couldn't open {}: {}", pathbuf.display(), err);
            return Ok(respond_404()?);
        },
        Ok(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()?)?;

            // Create a stream + body for the file
            let stream = FramedRead::new(file, BytesCodec::new());
            let body = Body::wrap_stream(stream);
            let mut resp = Response::new