use std::path::Path;
use serde::Deserialize;
use crate::{Client, Error, Filesystem, FilesystemPage, Result};
#[derive(Debug, Clone, Deserialize)]
pub struct PartitionName {
#[serde(default)]
pub view: String,
#[serde(default)]
pub fqdn: String,
#[serde(default)]
pub port: u16,
#[serde(default)]
pub http: bool,
}
impl PartitionName {
pub fn url(&self) -> String {
let scheme = if self.http { "http" } else { "https" };
let default_port = if self.http { 80 } else { 443 };
if self.port == 0 || self.port == default_port {
format!("{scheme}://{}", self.fqdn)
} else {
format!("{scheme}://{}:{}", self.fqdn, self.port)
}
}
}
#[derive(Debug, Clone, Deserialize)]
pub struct Partition {
#[serde(default)]
pub network: String,
#[serde(default)]
pub tld: String,
#[serde(default)]
pub quota: u64,
#[serde(default)]
pub running: bool,
#[serde(default)]
pub names: Vec<PartitionName>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct Principal {
#[serde(default)]
pub name: String,
#[serde(default)]
pub parent: Option<String>,
#[serde(default)]
pub ceiling: Vec<String>,
#[serde(default)]
pub account: bool,
}
#[derive(Debug, Clone, Deserialize)]
pub struct Grant {
#[serde(default)]
pub id: i64,
#[serde(default)]
pub principal: String,
#[serde(default)]
pub path: String,
#[serde(default)]
pub perm: Vec<String>,
#[serde(default)]
pub inheritable: bool,
}
#[derive(Debug, Clone, Deserialize)]
pub struct Exposure {
#[serde(default)]
pub token: String,
#[serde(default)]
pub path: String,
#[serde(default)]
pub filename: Option<String>,
#[serde(default)]
pub enabled: bool,
}
pub const PERMISSIONS: [&str; 4] = ["read", "write", "delete", "grant"];
#[derive(Debug, Clone, Default, Deserialize)]
pub struct ArchiveUpload {
#[serde(default)]
pub needs_restart: bool,
#[serde(default)]
pub message: String,
}
pub const ARCHIVE_FORMATS: [&str; 3] = ["tar.gz", "tar.bz2", "tar.xz"];
pub fn is_supported_archive(filename: &str) -> bool {
let lower = filename.to_ascii_lowercase();
[
".tar.gz", ".tgz", ".tar.bz2", ".tbz2", ".tar.xz", ".txz", ".tar",
]
.iter()
.any(|ext| lower.ends_with(ext))
}
impl Client {
pub async fn partitions(&self) -> Result<Vec<Partition>> {
self.get_json("/gfeh").await
}
pub async fn principals(&self, network: &str) -> Result<Vec<Principal>> {
self.get_json(&format!("/gfeh/principals?network={}", enc(network)))
.await
}
pub async fn add_principal(&self, network: &str, principal: &str) -> Result<Principal> {
self.post_json(
"/gfeh/principals/add",
&serde_json::json!({ "network": network, "principal": principal }),
)
.await
}
pub async fn remove_principal(&self, network: &str, principal: &str) -> Result<()> {
self.post_empty(
"/gfeh/principals/remove",
&serde_json::json!({ "network": network, "principal": principal }),
)
.await
}
pub async fn grants(&self, network: &str, principal: &str) -> Result<Vec<Grant>> {
self.get_json(&format!(
"/gfeh/grants?network={}&principal={}",
enc(network),
enc(principal)
))
.await
}
pub async fn add_grant(
&self,
network: &str,
principal: &str,
path: &str,
perm: &[String],
inheritable: bool,
) -> Result<Grant> {
self.post_json(
"/gfeh/grants/add",
&serde_json::json!({
"network": network,
"principal": principal,
"path": path,
"perm": perm,
"inheritable": inheritable,
}),
)
.await
}
pub async fn revoke_grant(&self, network: &str, id: i64) -> Result<()> {
self.post_empty(
"/gfeh/grants/revoke",
&serde_json::json!({ "network": network, "id": id }),
)
.await
}
pub async fn exposures(&self, network: &str) -> Result<Vec<Exposure>> {
self.get_json(&format!("/gfeh/exposures?network={}", enc(network)))
.await
}
pub async fn withdraw_exposure(&self, network: &str, token: &str) -> Result<()> {
self.post_empty(
"/gfeh/exposures/withdraw",
&serde_json::json!({ "network": network, "token": token }),
)
.await
}
pub async fn filesystems(
&self,
prefix: &str,
state: Option<&str>,
limit: u32,
offset: u32,
search: &str,
) -> Result<FilesystemPage> {
let mut body = serde_json::json!({
"name": prefix,
"limit": limit,
"offset": offset,
"sort_by": "name",
"sort_order": "asc",
});
if let Some(state) = state.filter(|s| !s.is_empty()) {
body["state"] = serde_json::Value::String(state.into());
}
if !search.is_empty() {
body["search"] = serde_json::Value::String(search.into());
}
self.post_json("/storage", &body).await
}
pub async fn create_filesystem(&self, fs: &Filesystem) -> Result<()> {
self.post_empty("/storage/create", fs).await
}
pub async fn modify_filesystem(&self, name: &str, fs: &Filesystem) -> Result<()> {
self.post_empty(
"/storage/modify",
&serde_json::json!({ "name": name, "filesystem": fs }),
)
.await
}
pub async fn remove_filesystem(&self, name: &str) -> Result<()> {
self.post_empty("/storage/remove", &serde_json::json!({ "name": name }))
.await
}
pub async fn upload_archive(
&self,
subvolume: &str,
archive: &Path,
subpath: &str,
stop_service: &str,
) -> Result<ArchiveUpload> {
let part = reqwest::multipart::Part::file(archive)
.await
.map_err(|source| Error::Io {
path: archive.display().to_string(),
source,
})?;
let mut form = reqwest::multipart::Form::new()
.text("subvolume", subvolume.to_owned())
.part("archive", part);
if !subpath.is_empty() {
form = form.text("subpath", subpath.to_owned());
}
if !stop_service.is_empty() {
form = form.text("stop_service", stop_service.to_owned());
}
const PATH: &str = "/storage/upload-archive";
let req = self
.request(reqwest::Method::POST, PATH)
.multipart(form);
let resp = self.send("POST", PATH, req).await?;
Self::decode(PATH, resp).await
}
pub async fn download_archive(
&self,
subvolume: &str,
paths: &[String],
format: &str,
destination: &Path,
) -> Result<u64> {
use tokio::io::AsyncWriteExt as _;
let mut body = serde_json::json!({ "subvolume": subvolume });
if !paths.is_empty() {
body["paths"] = serde_json::json!(paths);
}
if !format.is_empty() {
body["format"] = serde_json::Value::String(format.to_owned());
}
const PATH: &str = "/storage/download-archive";
let req = self.request(reqwest::Method::POST, PATH).json(&body);
let mut resp = self.send("POST", PATH, req).await?;
let io_error = |source: std::io::Error| Error::Io {
path: destination.display().to_string(),
source,
};
let mut file = tokio::fs::File::create(destination).await.map_err(io_error)?;
let mut written = 0u64;
while let Some(chunk) = resp.chunk().await? {
file.write_all(&chunk).await.map_err(io_error)?;
written += chunk.len() as u64;
}
file.flush().await.map_err(io_error)?;
Ok(written)
}
}
fn enc(value: &str) -> String {
let mut out = String::with_capacity(value.len());
for byte in value.bytes() {
match byte {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
out.push(byte as char)
}
other => out.push_str(&format!("%{other:02X}")),
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default_ports_are_left_off_the_url() {
let https = PartitionName {
view: "public".into(),
fqdn: "files.home.town".into(),
port: 443,
http: false,
};
assert_eq!(https.url(), "https://files.home.town");
let http = PartitionName {
view: "public".into(),
fqdn: "files.home.town".into(),
port: 80,
http: true,
};
assert_eq!(http.url(), "http://files.home.town");
}
#[test]
fn nonstandard_ports_are_kept() {
let name = PartitionName {
view: "admin".into(),
fqdn: "files.home.town".into(),
port: 8443,
http: false,
};
assert_eq!(name.url(), "https://files.home.town:8443");
}
#[test]
fn archive_names_the_box_can_unpack_are_recognised() {
for name in [
"backup.tar.gz",
"BACKUP.TAR.GZ",
"backup.tgz",
"backup.tar.bz2",
"backup.tbz2",
"backup.tar.xz",
"backup.txz",
"backup.tar",
] {
assert!(is_supported_archive(name), "{name} should be accepted");
}
}
#[test]
fn names_the_box_would_refuse_are_caught_before_the_upload() {
for name in ["backup.zip", "backup.7z", "backup", "backup.gz", "tar.gz.txt"] {
assert!(!is_supported_archive(name), "{name} should be refused");
}
}
#[test]
fn unset_port_falls_back_to_the_scheme_default() {
let name = PartitionName {
view: "public".into(),
fqdn: "files.home.town".into(),
port: 0,
http: true,
};
assert_eq!(name.url(), "http://files.home.town");
}
}