Can download ISO file by URL

This commit is contained in:
2023-09-05 16:12:20 +02:00
parent 4b55e17ee0
commit e7d5747b99
11 changed files with 231 additions and 9 deletions

View File

@ -17,7 +17,11 @@ pub const ROUTES_WITHOUT_AUTH: [&str; 5] = [
];
/// Allowed ISO mimetypes
pub const ALLOWED_ISO_MIME_TYPES: [&str; 1] = ["application/x-cd-image"];
pub const ALLOWED_ISO_MIME_TYPES: [&str; 3] = [
"application/x-cd-image",
"application/x-iso9660-image",
"application/octet-stream",
];
/// ISO max size
pub const ISO_MAX_SIZE: usize = 10 * 1000 * 1000 * 1000;

View File

@ -4,7 +4,10 @@ use crate::controllers::HttpResult;
use crate::utils::files_utils;
use actix_multipart::form::tempfile::TempFile;
use actix_multipart::form::MultipartForm;
use actix_web::HttpResponse;
use actix_web::{web, HttpResponse};
use futures_util::StreamExt;
use std::fs::File;
use std::io::Write;
#[derive(Debug, MultipartForm)]
pub struct UploadIsoForm {
@ -58,3 +61,47 @@ pub async fn upload_file(MultipartForm(mut form): MultipartForm<UploadIsoForm>)
Ok(HttpResponse::Accepted().finish())
}
#[derive(serde::Deserialize)]
pub struct DownloadFromURLReq {
url: String,
filename: String,
}
/// Upload ISO file from URL
pub async fn upload_from_url(req: web::Json<DownloadFromURLReq>) -> HttpResult {
if !files_utils::check_file_name(&req.filename) || !req.filename.ends_with(".iso") {
return Ok(HttpResponse::BadRequest().json("Invalid file name!"));
}
let dest_file = AppConfig::get().iso_storage_path().join(&req.filename);
if dest_file.exists() {
return Ok(HttpResponse::Conflict().json("A similar file already exists!"));
}
let response = reqwest::get(&req.url).await?;
if let Some(len) = response.content_length() {
if len > constants::ISO_MAX_SIZE as u64 {
return Ok(HttpResponse::BadRequest().json("File is too large!"));
}
}
if let Some(ct) = response.headers().get("content-type") {
if !constants::ALLOWED_ISO_MIME_TYPES.contains(&ct.to_str()?) {
return Ok(HttpResponse::BadRequest().json("Invalid file mimetype!"));
}
}
let mut stream = response.bytes_stream();
let mut file = File::create(dest_file)?;
while let Some(item) = stream.next().await {
let bytes = item?;
file.write_all(&bytes)?;
}
Ok(HttpResponse::Accepted().finish())
}

View File

@ -65,4 +65,16 @@ impl From<tempfile::PersistError> for HttpErr {
}
}
impl From<reqwest::Error> for HttpErr {
fn from(value: reqwest::Error) -> Self {
HttpErr { err: value.into() }
}
}
impl From<reqwest::header::ToStrError> for HttpErr {
fn from(value: reqwest::header::ToStrError) -> Self {
HttpErr { err: value.into() }
}
}
pub type HttpResult = Result<HttpResponse, HttpErr>;

View File

@ -104,6 +104,10 @@ async fn main() -> std::io::Result<()> {
"/api/iso/upload",
web::post().to(iso_controller::upload_file),
)
.route(
"/api/iso/upload_from_url",
web::post().to(iso_controller::upload_from_url),
)
})
.bind(&AppConfig::get().listen_address)?
.run()

View File

@ -1 +1,2 @@
pub mod files_utils;
pub mod url_utils;

View File

@ -0,0 +1,58 @@
use std::fmt::Display;
use url::Url;
/// Check out whether a URL is valid or not
pub fn check_url(url: impl Display) -> bool {
match Url::parse(&url.to_string()) {
Ok(u) => {
if u.scheme() != "http" && u.scheme() != "https" {
log::debug!("URL is invalid, scheme is not http or https!");
return false;
}
if u.port_or_known_default() != Some(443) && u.port_or_known_default() != Some(80) {
log::debug!("URL is invalid, port is not 80 or 443!");
return false;
}
true
}
Err(e) => {
log::debug!("URL is invalid, could not be parsed! {e}");
false
}
}
}
#[cfg(test)]
mod test {
use crate::utils::url_utils::check_url;
#[test]
fn valid_url_ubuntu() {
assert!(check_url(
"https://releases.ubuntu.com/22.04.3/ubuntu-22.04.3-desktop-amd64.iso"
));
}
#[test]
fn valid_url_with_port_ubuntu() {
assert!(check_url(
"https://releases.ubuntu.com:443/22.04.3/ubuntu-22.04.3-desktop-amd64.iso"
));
}
#[test]
fn invalid_valid_url_ftp() {
assert!(!check_url(
"ftp://releases.ubuntu.com/22.04.3/ubuntu-22.04.3-desktop-amd64.iso"
));
}
#[test]
fn invalid_valid_bad_port() {
assert!(!check_url(
"http://releases.ubuntu.com:81/22.04.3/ubuntu-22.04.3-desktop-amd64.iso"
));
}
}