2022-05-03 16:28:43 -04:00
|
|
|
use std::{
|
|
|
|
collections::HashMap,
|
|
|
|
io::ErrorKind,
|
|
|
|
path::{Path, PathBuf},
|
|
|
|
};
|
2022-04-28 05:13:14 -04:00
|
|
|
|
2022-05-03 16:28:43 -04:00
|
|
|
use log::{debug, error, info};
|
2022-05-01 05:28:50 -04:00
|
|
|
use rand::{
|
|
|
|
distributions::{Alphanumeric, DistString},
|
|
|
|
thread_rng, Rng,
|
|
|
|
};
|
2022-04-30 01:38:26 -04:00
|
|
|
use serde::{Deserialize, Serialize};
|
2022-05-24 15:14:31 -04:00
|
|
|
use serde_with::skip_serializing_none;
|
2022-07-05 19:28:25 -04:00
|
|
|
use serde_with::{serde_as, FromInto, PickFirst};
|
2022-04-30 01:38:26 -04:00
|
|
|
use time::OffsetDateTime;
|
2022-04-28 05:18:35 -04:00
|
|
|
use tokio::{
|
|
|
|
fs::File,
|
|
|
|
io::{AsyncReadExt, AsyncWriteExt},
|
|
|
|
};
|
2022-04-28 05:13:14 -04:00
|
|
|
|
2022-05-24 15:14:31 -04:00
|
|
|
use crate::upload::UploadedFile;
|
2022-07-05 19:11:01 -04:00
|
|
|
use crate::zip::FileSet;
|
2022-05-24 15:14:31 -04:00
|
|
|
|
2022-04-28 05:13:14 -04:00
|
|
|
const STATE_FILE_NAME: &str = "files.json";
|
2022-05-03 16:28:43 -04:00
|
|
|
const MAX_STORAGE_FILES: usize = 1024;
|
|
|
|
|
|
|
|
pub fn gen_storage_code(use_mnemonic: bool) -> String {
|
|
|
|
if use_mnemonic {
|
2022-05-01 03:28:25 -04:00
|
|
|
mnemonic::to_string(thread_rng().gen::<[u8; 4]>())
|
2022-05-03 16:28:43 -04:00
|
|
|
} else {
|
|
|
|
Alphanumeric.sample_string(&mut thread_rng(), 8)
|
2022-05-01 03:28:25 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn is_valid_storage_code(s: &str) -> bool {
|
2022-05-01 05:28:50 -04:00
|
|
|
s.as_bytes()
|
|
|
|
.iter()
|
|
|
|
.all(|c| c.is_ascii_alphanumeric() || c == &b'-')
|
2022-05-01 03:28:25 -04:00
|
|
|
}
|
2022-04-30 01:38:26 -04:00
|
|
|
|
2022-07-05 19:11:01 -04:00
|
|
|
#[serde_as]
|
2022-05-24 15:14:31 -04:00
|
|
|
#[skip_serializing_none]
|
2022-04-30 01:38:26 -04:00
|
|
|
#[derive(Clone, Deserialize, Serialize)]
|
|
|
|
pub struct StoredFile {
|
|
|
|
pub name: String,
|
|
|
|
pub size: u64,
|
2022-05-24 15:14:31 -04:00
|
|
|
#[serde(with = "crate::timestamp")]
|
2022-04-30 01:38:26 -04:00
|
|
|
pub modtime: OffsetDateTime,
|
2022-05-24 15:14:31 -04:00
|
|
|
#[serde(with = "crate::timestamp")]
|
2022-04-30 01:38:26 -04:00
|
|
|
pub expiry: OffsetDateTime,
|
2022-07-05 19:11:01 -04:00
|
|
|
#[serde_as(as = "Option<PickFirst<(_, FromInto<Vec<UploadedFile>>)>>")]
|
|
|
|
#[serde(default)]
|
|
|
|
pub contents: Option<FileSet>,
|
2022-04-28 05:13:14 -04:00
|
|
|
}
|
|
|
|
|
2022-05-03 16:28:43 -04:00
|
|
|
async fn is_valid_entry(key: &str, info: &StoredFile, storage_dir: &Path) -> bool {
|
2022-04-30 01:38:26 -04:00
|
|
|
if info.expiry < OffsetDateTime::now_utc() {
|
|
|
|
info!("File {} has expired", key);
|
2022-04-28 06:26:44 -04:00
|
|
|
return false;
|
|
|
|
}
|
2022-04-30 01:38:26 -04:00
|
|
|
|
2022-05-03 16:28:43 -04:00
|
|
|
let file = if let Ok(f) = File::open(storage_dir.join(&key)).await {
|
2022-04-28 06:26:44 -04:00
|
|
|
f
|
|
|
|
} else {
|
|
|
|
error!(
|
|
|
|
"Unable to open file {} referenced in persistent storage",
|
|
|
|
key
|
|
|
|
);
|
|
|
|
return false;
|
|
|
|
};
|
|
|
|
let metadata = if let Ok(md) = file.metadata().await {
|
|
|
|
md
|
|
|
|
} else {
|
|
|
|
error!(
|
|
|
|
"Unable to get metadata for file {} referenced in persistent storage",
|
|
|
|
key
|
|
|
|
);
|
|
|
|
return false;
|
|
|
|
};
|
|
|
|
if metadata.len() != info.size {
|
|
|
|
error!("Mismatched file size for file {} referenced in persistent storage: expected {}, found {}", key, info.size, metadata.len());
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
true
|
|
|
|
}
|
|
|
|
|
2022-05-03 16:28:43 -04:00
|
|
|
async fn delete_file_if_exists(file: &PathBuf) -> std::io::Result<()> {
|
|
|
|
if let Err(e) = tokio::fs::remove_file(file).await {
|
|
|
|
if e.kind() != ErrorKind::NotFound {
|
|
|
|
error!("Failed to delete file {}: {}", file.to_string_lossy(), e);
|
|
|
|
return Err(e);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(thiserror::Error, Debug)]
|
|
|
|
pub enum FileAddError {
|
|
|
|
#[error("Failed to write metadata to filesystem")]
|
|
|
|
FileSystem(#[from] std::io::Error),
|
|
|
|
#[error("File was too large, available space is {0} bytes")]
|
|
|
|
TooBig(u64),
|
|
|
|
#[error("File store is full")]
|
|
|
|
Full,
|
|
|
|
}
|
|
|
|
|
|
|
|
pub struct FileStore {
|
|
|
|
files: HashMap<String, StoredFile>,
|
|
|
|
storage_dir: PathBuf,
|
|
|
|
max_storage_size: u64,
|
|
|
|
}
|
|
|
|
|
2022-04-30 01:38:26 -04:00
|
|
|
impl FileStore {
|
2022-05-03 16:28:43 -04:00
|
|
|
pub(crate) async fn load(storage_dir: PathBuf, max_storage_size: u64) -> std::io::Result<Self> {
|
|
|
|
let open_result = File::open(storage_dir.join(STATE_FILE_NAME)).await;
|
2022-04-28 05:13:14 -04:00
|
|
|
match open_result {
|
|
|
|
Ok(mut f) => {
|
|
|
|
let mut buf = String::new();
|
|
|
|
f.read_to_string(&mut buf).await?;
|
2022-04-30 01:38:26 -04:00
|
|
|
let map: HashMap<String, StoredFile> = serde_json::from_str(&buf)?;
|
2022-04-28 05:13:14 -04:00
|
|
|
info!("Loaded {} file entries from persistent storage", map.len());
|
2022-04-30 01:38:26 -04:00
|
|
|
let mut filtered: HashMap<String, StoredFile> = HashMap::new();
|
2022-04-28 05:13:14 -04:00
|
|
|
for (key, info) in map.into_iter() {
|
2022-04-30 01:38:26 -04:00
|
|
|
// Handle this case separately, because we don't
|
|
|
|
// want to try to delete it if it's not the sort
|
|
|
|
// of path we're expecting
|
2022-05-01 03:28:25 -04:00
|
|
|
if !is_valid_storage_code(&key) {
|
2022-04-30 01:38:26 -04:00
|
|
|
error!("Invalid key in persistent storage: {}", key);
|
|
|
|
continue;
|
|
|
|
}
|
2022-05-03 16:28:43 -04:00
|
|
|
if is_valid_entry(&key, &info, &storage_dir).await {
|
2022-04-28 06:26:44 -04:00
|
|
|
filtered.insert(key, info);
|
2022-04-28 05:13:14 -04:00
|
|
|
} else {
|
2022-04-30 01:38:26 -04:00
|
|
|
info!("Deleting file {}", key);
|
2022-05-03 16:28:43 -04:00
|
|
|
delete_file_if_exists(&storage_dir.join(&key)).await?;
|
2022-04-28 05:13:14 -04:00
|
|
|
}
|
|
|
|
}
|
2022-05-03 16:28:43 -04:00
|
|
|
let mut loaded = Self {
|
|
|
|
files: filtered,
|
|
|
|
storage_dir,
|
|
|
|
max_storage_size,
|
|
|
|
};
|
2022-04-28 06:26:44 -04:00
|
|
|
loaded.save().await?;
|
|
|
|
Ok(loaded)
|
2022-04-28 05:13:14 -04:00
|
|
|
}
|
|
|
|
Err(e) => {
|
|
|
|
if let ErrorKind::NotFound = e.kind() {
|
2022-05-03 16:28:43 -04:00
|
|
|
Ok(Self {
|
|
|
|
files: HashMap::new(),
|
|
|
|
storage_dir,
|
|
|
|
max_storage_size,
|
|
|
|
})
|
2022-04-28 05:13:14 -04:00
|
|
|
} else {
|
|
|
|
Err(e)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-04-30 01:38:26 -04:00
|
|
|
fn total_size(&self) -> u64 {
|
2022-05-03 16:28:43 -04:00
|
|
|
self.files.iter().fold(0, |acc, (_, f)| acc + f.size)
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn available_size(&self) -> u64 {
|
|
|
|
self.max_storage_size.saturating_sub(self.total_size())
|
2022-04-30 01:38:26 -04:00
|
|
|
}
|
|
|
|
|
2022-04-28 05:13:14 -04:00
|
|
|
async fn save(&mut self) -> std::io::Result<()> {
|
2022-05-03 16:28:43 -04:00
|
|
|
info!("saving updated state: {} entries", self.files.len());
|
|
|
|
File::create(self.storage_dir.join(STATE_FILE_NAME))
|
2022-04-28 05:18:35 -04:00
|
|
|
.await?
|
2022-05-03 16:28:43 -04:00
|
|
|
.write_all(&serde_json::to_vec_pretty(&self.files)?)
|
2022-04-28 05:18:35 -04:00
|
|
|
.await
|
2022-04-28 05:13:14 -04:00
|
|
|
}
|
|
|
|
|
2022-05-03 16:28:43 -04:00
|
|
|
pub fn full(&self) -> bool {
|
|
|
|
self.available_size() == 0 || self.files.len() >= MAX_STORAGE_FILES
|
|
|
|
}
|
|
|
|
|
2022-04-30 01:38:26 -04:00
|
|
|
/// Attempts to add a file to the store. Returns an I/O error if
|
|
|
|
/// something's broken, or a u64 of the maximum allowed file size
|
|
|
|
/// if the file was too big, or a unit if everything worked.
|
2022-04-28 05:18:35 -04:00
|
|
|
pub(crate) async fn add_file(
|
|
|
|
&mut self,
|
|
|
|
key: String,
|
2022-04-30 01:38:26 -04:00
|
|
|
file: StoredFile,
|
2022-05-03 16:28:43 -04:00
|
|
|
) -> Result<(), FileAddError> {
|
|
|
|
if self.full() {
|
|
|
|
return Err(FileAddError::Full);
|
2022-05-01 05:28:50 -04:00
|
|
|
}
|
2022-05-03 16:28:43 -04:00
|
|
|
let available_size = self.available_size();
|
|
|
|
if file.size > available_size {
|
|
|
|
return Err(FileAddError::TooBig(available_size));
|
|
|
|
}
|
|
|
|
self.files.insert(key, file);
|
|
|
|
self.save().await?;
|
|
|
|
Ok(())
|
2022-04-28 05:13:14 -04:00
|
|
|
}
|
|
|
|
|
2022-04-30 01:38:26 -04:00
|
|
|
pub(crate) fn lookup_file(&self, key: &str) -> Option<StoredFile> {
|
2022-05-03 16:28:43 -04:00
|
|
|
self.files.get(key).cloned()
|
2022-04-28 05:13:14 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
pub(crate) async fn remove_file(&mut self, key: &str) -> std::io::Result<()> {
|
2022-04-28 06:26:44 -04:00
|
|
|
debug!("removing entry {} from state", key);
|
2022-05-03 16:28:43 -04:00
|
|
|
self.files.remove(key);
|
|
|
|
self.save().await?;
|
|
|
|
if is_valid_storage_code(key) {
|
|
|
|
delete_file_if_exists(&self.storage_dir.join(key)).await?;
|
|
|
|
}
|
|
|
|
Ok(())
|
2022-04-28 05:13:14 -04:00
|
|
|
}
|
2022-04-30 01:38:26 -04:00
|
|
|
|
|
|
|
pub(crate) async fn remove_expired_files(&mut self) -> std::io::Result<()> {
|
|
|
|
info!("Checking for expired files");
|
|
|
|
let now = OffsetDateTime::now_utc();
|
2022-05-03 16:28:43 -04:00
|
|
|
for (key, file) in std::mem::take(&mut self.files).into_iter() {
|
2022-04-30 01:38:26 -04:00
|
|
|
if file.expiry > now {
|
2022-05-03 16:28:43 -04:00
|
|
|
self.files.insert(key, file);
|
2022-04-30 01:38:26 -04:00
|
|
|
} else {
|
|
|
|
info!("Deleting expired file {}", key);
|
2022-05-03 16:28:43 -04:00
|
|
|
delete_file_if_exists(&self.storage_dir.join(&key)).await?;
|
2022-04-30 01:38:26 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
self.save().await
|
|
|
|
}
|
2022-04-28 05:13:14 -04:00
|
|
|
}
|