2022-04-10 22:21:45 +00:00
|
|
|
extern crate core;
|
|
|
|
|
2022-05-02 15:53:10 +00:00
|
|
|
use env_logger::Builder;
|
|
|
|
use std::io::Write;
|
|
|
|
use std::sync::Mutex;
|
|
|
|
use std::time::{SystemTime, UNIX_EPOCH};
|
|
|
|
|
2022-05-07 21:30:57 +00:00
|
|
|
use actix_files;
|
2022-05-02 15:53:10 +00:00
|
|
|
use actix_multipart::Multipart;
|
2022-05-07 21:30:57 +00:00
|
|
|
use actix_web::dev::ServiceRequest;
|
|
|
|
use actix_web::middleware::Condition;
|
|
|
|
use actix_web::{error, get, middleware, web, App, Error, HttpResponse, HttpServer, Responder};
|
|
|
|
use actix_web_httpauth::extractors::basic::BasicAuth;
|
|
|
|
use actix_web_httpauth::middleware::HttpAuthentication;
|
2022-04-10 22:21:45 +00:00
|
|
|
use askama::Template;
|
2022-05-02 15:53:10 +00:00
|
|
|
use chrono::Local;
|
2022-04-23 15:47:36 +00:00
|
|
|
use clap::Parser;
|
2022-05-02 15:53:10 +00:00
|
|
|
use futures::TryStreamExt as _;
|
2022-05-07 21:30:57 +00:00
|
|
|
use lazy_static::lazy_static;
|
2022-04-23 15:47:36 +00:00
|
|
|
use linkify::{LinkFinder, LinkKind};
|
2022-05-02 15:53:10 +00:00
|
|
|
use log::LevelFilter;
|
2022-04-10 22:21:45 +00:00
|
|
|
use rand::Rng;
|
2022-05-07 21:30:57 +00:00
|
|
|
use std::fs;
|
2022-04-10 22:21:45 +00:00
|
|
|
|
|
|
|
use crate::animalnumbers::{to_animal_names, to_u64};
|
2022-05-02 15:53:10 +00:00
|
|
|
use crate::dbio::save_to_file;
|
|
|
|
use crate::pasta::Pasta;
|
2022-04-10 22:21:45 +00:00
|
|
|
|
|
|
|
mod animalnumbers;
|
2022-05-02 15:53:10 +00:00
|
|
|
mod dbio;
|
2022-04-23 15:47:36 +00:00
|
|
|
mod pasta;
|
2022-04-10 22:21:45 +00:00
|
|
|
|
2022-05-07 21:30:57 +00:00
|
|
|
lazy_static! {
|
|
|
|
static ref ARGS: Args = Args::parse();
|
|
|
|
}
|
|
|
|
|
2022-04-10 22:21:45 +00:00
|
|
|
struct AppState {
|
2022-04-23 15:47:36 +00:00
|
|
|
pastas: Mutex<Vec<Pasta>>,
|
|
|
|
}
|
|
|
|
|
2022-05-07 21:30:57 +00:00
|
|
|
#[derive(Parser, Debug, Clone)]
|
2022-04-23 15:47:36 +00:00
|
|
|
#[clap(author, version, about, long_about = None)]
|
|
|
|
struct Args {
|
|
|
|
#[clap(short, long, default_value_t = 8080)]
|
|
|
|
port: u32,
|
2022-05-07 21:30:57 +00:00
|
|
|
|
|
|
|
#[clap(short, long, default_value_t = 1)]
|
|
|
|
threads: u8,
|
|
|
|
|
|
|
|
#[clap(long)]
|
|
|
|
hide_header: bool,
|
|
|
|
|
|
|
|
#[clap(long)]
|
|
|
|
hide_footer: bool,
|
|
|
|
|
|
|
|
#[clap(long)]
|
|
|
|
pure_html: bool,
|
|
|
|
|
|
|
|
#[clap(long)]
|
|
|
|
no_listing: bool,
|
|
|
|
|
|
|
|
#[clap(long)]
|
|
|
|
auth_username: Option<String>,
|
|
|
|
|
|
|
|
#[clap(long)]
|
|
|
|
auth_password: Option<String>,
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn auth_validator(
|
|
|
|
req: ServiceRequest,
|
|
|
|
credentials: BasicAuth,
|
|
|
|
) -> Result<ServiceRequest, Error> {
|
|
|
|
// check if username matches
|
|
|
|
if credentials.user_id().as_ref() == ARGS.auth_username.as_ref().unwrap() {
|
|
|
|
return match ARGS.auth_password.as_ref() {
|
|
|
|
Some(cred_pass) => match credentials.password() {
|
|
|
|
None => Err(error::ErrorBadRequest("Invalid login details.")),
|
|
|
|
Some(arg_pass) => {
|
|
|
|
if arg_pass == cred_pass {
|
|
|
|
Ok(req)
|
|
|
|
} else {
|
|
|
|
Err(error::ErrorBadRequest("Invalid login details."))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
},
|
|
|
|
None => Ok(req),
|
|
|
|
};
|
|
|
|
} else {
|
|
|
|
Err(error::ErrorBadRequest("Invalid login details."))
|
|
|
|
}
|
2022-04-10 22:21:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Template)]
|
|
|
|
#[template(path = "index.html")]
|
2022-05-07 21:30:57 +00:00
|
|
|
struct IndexTemplate<'a> {
|
|
|
|
args: &'a Args,
|
|
|
|
}
|
2022-04-10 22:21:45 +00:00
|
|
|
|
2022-05-02 15:53:10 +00:00
|
|
|
#[derive(Template)]
|
|
|
|
#[template(path = "error.html")]
|
2022-05-07 21:30:57 +00:00
|
|
|
struct ErrorTemplate<'a> {
|
|
|
|
args: &'a Args,
|
|
|
|
}
|
2022-05-02 15:53:10 +00:00
|
|
|
|
2022-04-10 22:21:45 +00:00
|
|
|
#[derive(Template)]
|
|
|
|
#[template(path = "pasta.html")]
|
|
|
|
struct PastaTemplate<'a> {
|
2022-04-23 15:47:36 +00:00
|
|
|
pasta: &'a Pasta,
|
2022-05-07 21:30:57 +00:00
|
|
|
args: &'a Args,
|
2022-04-10 22:21:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Template)]
|
|
|
|
#[template(path = "pastalist.html")]
|
|
|
|
struct PastaListTemplate<'a> {
|
2022-04-23 15:47:36 +00:00
|
|
|
pastas: &'a Vec<Pasta>,
|
2022-05-07 21:30:57 +00:00
|
|
|
args: &'a Args,
|
2022-04-10 22:21:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[get("/")]
|
|
|
|
async fn index() -> impl Responder {
|
2022-04-23 15:47:36 +00:00
|
|
|
HttpResponse::Found()
|
|
|
|
.content_type("text/html")
|
2022-05-07 21:30:57 +00:00
|
|
|
.body(IndexTemplate { args: &ARGS }.render().unwrap())
|
2022-04-10 22:21:45 +00:00
|
|
|
}
|
|
|
|
|
2022-05-02 15:53:10 +00:00
|
|
|
async fn not_found() -> Result<HttpResponse, Error> {
|
|
|
|
Ok(HttpResponse::Found()
|
|
|
|
.content_type("text/html")
|
2022-05-07 21:30:57 +00:00
|
|
|
.body(ErrorTemplate { args: &ARGS }.render().unwrap()))
|
2022-05-02 15:53:10 +00:00
|
|
|
}
|
2022-04-23 15:47:36 +00:00
|
|
|
|
2022-05-02 15:53:10 +00:00
|
|
|
async fn create(data: web::Data<AppState>, mut payload: Multipart) -> Result<HttpResponse, Error> {
|
|
|
|
let mut pastas = data.pastas.lock().unwrap();
|
2022-04-23 15:47:36 +00:00
|
|
|
|
|
|
|
let timenow: i64 = match SystemTime::now().duration_since(UNIX_EPOCH) {
|
|
|
|
Ok(n) => n.as_secs(),
|
|
|
|
Err(_) => panic!("SystemTime before UNIX EPOCH!"),
|
|
|
|
} as i64;
|
|
|
|
|
2022-05-02 15:53:10 +00:00
|
|
|
let mut new_pasta = Pasta {
|
2022-04-23 15:47:36 +00:00
|
|
|
id: rand::thread_rng().gen::<u16>() as u64,
|
2022-05-02 15:53:10 +00:00
|
|
|
content: String::from("No Text Content"),
|
|
|
|
file: String::from("no-file"),
|
2022-04-23 15:47:36 +00:00
|
|
|
created: timenow,
|
2022-05-02 15:53:10 +00:00
|
|
|
pasta_type: String::from(""),
|
|
|
|
expiration: 0,
|
2022-04-23 15:47:36 +00:00
|
|
|
};
|
|
|
|
|
2022-05-02 15:53:10 +00:00
|
|
|
while let Some(mut field) = payload.try_next().await? {
|
|
|
|
match field.name() {
|
|
|
|
"expiration" => {
|
|
|
|
while let Some(chunk) = field.try_next().await? {
|
|
|
|
new_pasta.expiration = match std::str::from_utf8(&chunk).unwrap() {
|
|
|
|
"1min" => timenow + 60,
|
|
|
|
"10min" => timenow + 60 * 10,
|
|
|
|
"1hour" => timenow + 60 * 60,
|
|
|
|
"24hour" => timenow + 60 * 60 * 24,
|
|
|
|
"1week" => timenow + 60 * 60 * 24 * 7,
|
|
|
|
"never" => 0,
|
|
|
|
_ => panic!("Unexpected expiration time!"),
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
"content" => {
|
|
|
|
while let Some(chunk) = field.try_next().await? {
|
|
|
|
new_pasta.content = std::str::from_utf8(&chunk).unwrap().to_string();
|
|
|
|
new_pasta.pasta_type = if is_valid_url(new_pasta.content.as_str()) {
|
|
|
|
String::from("url")
|
|
|
|
} else {
|
|
|
|
String::from("text")
|
|
|
|
};
|
|
|
|
}
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
"file" => {
|
|
|
|
let content_disposition = field.content_disposition();
|
|
|
|
|
|
|
|
let filename = match content_disposition.get_filename() {
|
|
|
|
Some("") => continue,
|
|
|
|
Some(filename) => filename.replace(' ', "_").to_string(),
|
|
|
|
None => continue,
|
|
|
|
};
|
|
|
|
|
|
|
|
std::fs::create_dir_all(format!("./pasta_data/{}", &new_pasta.id_as_animals()))
|
|
|
|
.unwrap();
|
|
|
|
|
|
|
|
let filepath = format!("./pasta_data/{}/{}", &new_pasta.id_as_animals(), &filename);
|
|
|
|
|
|
|
|
new_pasta.file = filename;
|
|
|
|
|
|
|
|
let mut f = web::block(|| std::fs::File::create(filepath)).await??;
|
|
|
|
|
|
|
|
while let Some(chunk) = field.try_next().await? {
|
|
|
|
f = web::block(move || f.write_all(&chunk).map(|_| f)).await??;
|
|
|
|
}
|
|
|
|
|
|
|
|
new_pasta.pasta_type = String::from("text");
|
|
|
|
}
|
|
|
|
_ => {}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-04-23 15:47:36 +00:00
|
|
|
let id = new_pasta.id;
|
|
|
|
|
|
|
|
pastas.push(new_pasta);
|
|
|
|
|
2022-05-02 15:53:10 +00:00
|
|
|
save_to_file(&pastas);
|
|
|
|
|
|
|
|
Ok(HttpResponse::Found()
|
2022-04-23 15:47:36 +00:00
|
|
|
.append_header(("Location", format!("/pasta/{}", to_animal_names(id))))
|
2022-05-02 15:53:10 +00:00
|
|
|
.finish())
|
2022-04-10 22:21:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[get("/pasta/{id}")]
|
|
|
|
async fn getpasta(data: web::Data<AppState>, id: web::Path<String>) -> HttpResponse {
|
2022-04-23 15:47:36 +00:00
|
|
|
let mut pastas = data.pastas.lock().unwrap();
|
2022-05-07 21:30:57 +00:00
|
|
|
|
2022-04-23 15:47:36 +00:00
|
|
|
let id = to_u64(&*id.into_inner());
|
2022-04-10 22:21:45 +00:00
|
|
|
|
2022-04-23 15:47:36 +00:00
|
|
|
remove_expired(&mut pastas);
|
2022-04-11 13:41:28 +00:00
|
|
|
|
2022-04-23 15:47:36 +00:00
|
|
|
for pasta in pastas.iter() {
|
|
|
|
if pasta.id == id {
|
|
|
|
return HttpResponse::Found()
|
|
|
|
.content_type("text/html")
|
2022-05-07 21:30:57 +00:00
|
|
|
.body(PastaTemplate { pasta, args: &ARGS }.render().unwrap());
|
2022-04-23 15:47:36 +00:00
|
|
|
}
|
|
|
|
}
|
2022-04-10 22:21:45 +00:00
|
|
|
|
2022-05-02 15:53:10 +00:00
|
|
|
HttpResponse::Found()
|
|
|
|
.content_type("text/html")
|
2022-05-07 21:30:57 +00:00
|
|
|
.body(ErrorTemplate { args: &ARGS }.render().unwrap())
|
2022-04-10 22:21:45 +00:00
|
|
|
}
|
|
|
|
|
2022-04-23 15:47:36 +00:00
|
|
|
#[get("/url/{id}")]
|
|
|
|
async fn redirecturl(data: web::Data<AppState>, id: web::Path<String>) -> HttpResponse {
|
|
|
|
let mut pastas = data.pastas.lock().unwrap();
|
2022-05-07 21:30:57 +00:00
|
|
|
|
2022-04-23 15:47:36 +00:00
|
|
|
let id = to_u64(&*id.into_inner());
|
|
|
|
|
|
|
|
remove_expired(&mut pastas);
|
|
|
|
|
|
|
|
for pasta in pastas.iter() {
|
|
|
|
if pasta.id == id {
|
|
|
|
if pasta.pasta_type == "url" {
|
|
|
|
return HttpResponse::Found()
|
|
|
|
.append_header(("Location", String::from(&pasta.content)))
|
|
|
|
.finish();
|
|
|
|
} else {
|
2022-05-07 21:30:57 +00:00
|
|
|
return HttpResponse::Found()
|
|
|
|
.content_type("text/html")
|
|
|
|
.body(ErrorTemplate { args: &ARGS }.render().unwrap());
|
2022-04-23 15:47:36 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-05-07 21:30:57 +00:00
|
|
|
HttpResponse::Found()
|
|
|
|
.content_type("text/html")
|
|
|
|
.body(ErrorTemplate { args: &ARGS }.render().unwrap())
|
2022-04-23 15:47:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[get("/raw/{id}")]
|
2022-04-10 22:21:45 +00:00
|
|
|
async fn getrawpasta(data: web::Data<AppState>, id: web::Path<String>) -> String {
|
2022-04-23 15:47:36 +00:00
|
|
|
let mut pastas = data.pastas.lock().unwrap();
|
2022-05-02 15:53:10 +00:00
|
|
|
|
2022-04-23 15:47:36 +00:00
|
|
|
let id = to_u64(&*id.into_inner());
|
2022-04-10 22:21:45 +00:00
|
|
|
|
2022-04-23 15:47:36 +00:00
|
|
|
remove_expired(&mut pastas);
|
2022-04-11 13:41:28 +00:00
|
|
|
|
2022-04-23 15:47:36 +00:00
|
|
|
for pasta in pastas.iter() {
|
|
|
|
if pasta.id == id {
|
|
|
|
return pasta.content.to_owned();
|
|
|
|
}
|
|
|
|
}
|
2022-04-10 22:21:45 +00:00
|
|
|
|
2022-04-23 15:47:36 +00:00
|
|
|
String::from("Pasta not found! :-(")
|
2022-04-10 22:21:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[get("/remove/{id}")]
|
|
|
|
async fn remove(data: web::Data<AppState>, id: web::Path<String>) -> HttpResponse {
|
2022-04-23 15:47:36 +00:00
|
|
|
let mut pastas = data.pastas.lock().unwrap();
|
2022-05-07 21:30:57 +00:00
|
|
|
|
2022-04-23 15:47:36 +00:00
|
|
|
let id = to_u64(&*id.into_inner());
|
2022-04-10 22:21:45 +00:00
|
|
|
|
2022-04-23 15:47:36 +00:00
|
|
|
remove_expired(&mut pastas);
|
2022-04-11 13:41:28 +00:00
|
|
|
|
2022-04-23 15:47:36 +00:00
|
|
|
for (i, pasta) in pastas.iter().enumerate() {
|
|
|
|
if pasta.id == id {
|
|
|
|
pastas.remove(i);
|
|
|
|
return HttpResponse::Found()
|
|
|
|
.append_header(("Location", "/pastalist"))
|
|
|
|
.finish();
|
|
|
|
}
|
|
|
|
}
|
2022-05-07 21:30:57 +00:00
|
|
|
|
|
|
|
HttpResponse::Found()
|
|
|
|
.content_type("text/html")
|
|
|
|
.body(ErrorTemplate { args: &ARGS }.render().unwrap())
|
2022-04-10 22:21:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[get("/pastalist")]
|
|
|
|
async fn list(data: web::Data<AppState>) -> HttpResponse {
|
2022-05-07 21:30:57 +00:00
|
|
|
if ARGS.no_listing {
|
|
|
|
return HttpResponse::Found()
|
|
|
|
.append_header(("Location", "/"))
|
|
|
|
.finish();
|
|
|
|
}
|
|
|
|
|
2022-04-23 15:47:36 +00:00
|
|
|
let mut pastas = data.pastas.lock().unwrap();
|
2022-04-10 22:21:45 +00:00
|
|
|
|
2022-04-23 15:47:36 +00:00
|
|
|
remove_expired(&mut pastas);
|
2022-04-11 13:41:28 +00:00
|
|
|
|
2022-05-07 21:30:57 +00:00
|
|
|
HttpResponse::Found().content_type("text/html").body(
|
|
|
|
PastaListTemplate {
|
|
|
|
pastas: &pastas,
|
|
|
|
args: &ARGS,
|
|
|
|
}
|
|
|
|
.render()
|
|
|
|
.unwrap(),
|
|
|
|
)
|
2022-04-10 22:21:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[actix_web::main]
|
|
|
|
async fn main() -> std::io::Result<()> {
|
2022-05-07 21:30:57 +00:00
|
|
|
let args: Args = Args::parse();
|
2022-05-02 15:53:10 +00:00
|
|
|
|
|
|
|
Builder::new()
|
|
|
|
.format(|buf, record| {
|
|
|
|
writeln!(
|
|
|
|
buf,
|
|
|
|
"{} [{}] - {}",
|
|
|
|
Local::now().format("%Y-%m-%dT%H:%M:%S"),
|
|
|
|
record.level(),
|
|
|
|
record.args()
|
|
|
|
)
|
|
|
|
})
|
|
|
|
.filter(None, LevelFilter::Info)
|
|
|
|
.init();
|
|
|
|
|
|
|
|
log::info!(
|
2022-05-07 21:30:57 +00:00
|
|
|
"MicroBin starting on http://127.0.0.1:{}",
|
2022-05-02 15:53:10 +00:00
|
|
|
args.port.to_string()
|
2022-04-23 15:47:36 +00:00
|
|
|
);
|
|
|
|
|
2022-05-07 21:30:57 +00:00
|
|
|
match std::fs::create_dir_all("./pasta_data") {
|
|
|
|
Ok(dir) => dir,
|
|
|
|
Err(error) => {
|
|
|
|
log::error!("Couldn't create data directory ./pasta_data: {:?}", error);
|
|
|
|
panic!("Couldn't create data directory ./pasta_data: {:?}", error);
|
|
|
|
}
|
|
|
|
};
|
2022-05-02 15:53:10 +00:00
|
|
|
|
2022-04-23 15:47:36 +00:00
|
|
|
let data = web::Data::new(AppState {
|
2022-05-02 15:53:10 +00:00
|
|
|
pastas: Mutex::new(dbio::load_from_file().unwrap()),
|
2022-04-23 15:47:36 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
HttpServer::new(move || {
|
|
|
|
App::new()
|
|
|
|
.app_data(data.clone())
|
2022-05-07 21:30:57 +00:00
|
|
|
.wrap(middleware::NormalizePath::trim())
|
2022-04-23 15:47:36 +00:00
|
|
|
.service(index)
|
|
|
|
.service(getpasta)
|
|
|
|
.service(redirecturl)
|
|
|
|
.service(getrawpasta)
|
2022-05-07 21:30:57 +00:00
|
|
|
.service(actix_files::Files::new("/static", "./static"))
|
|
|
|
.service(actix_files::Files::new("/file", "./pasta_data"))
|
2022-05-02 15:53:10 +00:00
|
|
|
.service(web::resource("/upload").route(web::post().to(create)))
|
|
|
|
.default_service(web::route().to(not_found))
|
2022-05-07 21:30:57 +00:00
|
|
|
.wrap(middleware::Logger::default())
|
|
|
|
.service(remove)
|
|
|
|
.service(list)
|
|
|
|
.wrap(Condition::new(
|
|
|
|
args.auth_username.is_some(),
|
|
|
|
HttpAuthentication::basic(auth_validator),
|
|
|
|
))
|
2022-04-23 15:47:36 +00:00
|
|
|
})
|
2022-05-09 21:23:51 +00:00
|
|
|
.bind(format!("0.0.0.0:{}", args.port.to_string()))?
|
2022-05-08 15:37:54 +00:00
|
|
|
.workers(args.threads as usize)
|
2022-04-23 15:47:36 +00:00
|
|
|
.run()
|
|
|
|
.await
|
2022-04-10 22:21:45 +00:00
|
|
|
}
|
2022-04-11 13:41:28 +00:00
|
|
|
|
|
|
|
fn remove_expired(pastas: &mut Vec<Pasta>) {
|
2022-05-07 21:30:57 +00:00
|
|
|
// get current time - this will be needed to check which pastas have expired
|
2022-04-23 15:47:36 +00:00
|
|
|
let timenow: i64 = match SystemTime::now().duration_since(UNIX_EPOCH) {
|
|
|
|
Ok(n) => n.as_secs(),
|
|
|
|
Err(_) => panic!("SystemTime before UNIX EPOCH!"),
|
|
|
|
} as i64;
|
|
|
|
|
2022-05-07 21:30:57 +00:00
|
|
|
pastas.retain(|p| {
|
2022-05-09 21:36:13 +00:00
|
|
|
// expiration is `never` or not reached
|
|
|
|
if p.expiration == 0 || p.expiration > timenow {
|
|
|
|
// keep
|
|
|
|
true
|
|
|
|
} else {
|
2022-05-07 21:30:57 +00:00
|
|
|
// remove the file itself
|
|
|
|
fs::remove_file(format!("./pasta_data/{}/{}", p.id_as_animals(), p.file));
|
|
|
|
// and remove the containing directory
|
|
|
|
fs::remove_dir(format!("./pasta_data/{}/", p.id_as_animals()));
|
2022-05-09 21:36:13 +00:00
|
|
|
// remove
|
|
|
|
false
|
|
|
|
}
|
2022-05-07 21:30:57 +00:00
|
|
|
});
|
2022-04-23 15:47:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn is_valid_url(url: &str) -> bool {
|
|
|
|
let finder = LinkFinder::new();
|
|
|
|
let spans: Vec<_> = finder.spans(url).collect();
|
|
|
|
spans[0].as_str() == url && Some(&LinkKind::Url) == spans[0].kind()
|
2022-04-11 13:41:28 +00:00
|
|
|
}
|