use std::fs::{self, File, OpenOptions};
use std::io::{self, IsTerminal as _, Read as _, Write as _};
use std::os::unix::fs::OpenOptionsExt as _;
use std::path::{Path, PathBuf};
use serde_json::json;
use stratum_node_core::{DidNostr, NostrSecretKey, ParsePodPathError, PodPath};
use crate::error::CliError;
use crate::exit;
use crate::gate::{
self, GateClient, Head, Precondition, Request, Route, ANY, LD_JSON, MAX_LISTING_BYTES,
MAX_RESOURCE_BYTES,
};
use crate::listing::{self, Child};
use crate::origin::GateTarget;
use crate::output::sanitize;
use crate::session::{Confirmation, Session};
const TURTLE: &str = "text/turtle";
const OCTET_STREAM: &str = "application/octet-stream";
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum WriteCondition {
#[default]
Always,
IfMatch(String),
CreateOnly,
}
#[derive(Debug, Clone, Default)]
pub struct PutOptions {
pub path: String,
pub file: PathBuf,
pub content_type: Option<String>,
pub condition: WriteCondition,
}
impl Session {
pub fn pod_ls(&self, target: &GateTarget, path: &str) -> Result<u8, CliError> {
let key = self.key()?;
let mut text = path.to_owned();
if !text.is_empty() && !text.ends_with('/') {
text.push('/');
}
let container = resolve_path(&key.public(), &text)?;
if !container.is_container() {
return Err(CliError::Usage(format!("{container} is not a container")));
}
let gate = GateClient::new(target.clone());
let response = gate.fetch(
&Request::new("GET", container.as_str(), LD_JSON),
Some(&key),
MAX_LISTING_BYTES,
)?;
if !response.head.is_success() {
return Err(response.into_error(Route::Pod));
}
let children = listing::children(target.origin(), &container, &response.body)?;
let mut listed = Vec::new();
let mut refused = Vec::new();
for child in children {
match child {
Child::Accepted(path) => {
self.output().line(path.as_str())?;
listed.push(json!({"path": path, "container": path.is_container()}));
}
Child::Refused { id, reason } => {
self.output()
.note(&format!("refused listed child {id:?}: {reason}"))?;
refused.push(json!({"id": id, "reason": reason}));
}
}
}
self.output().json(&json!({
"path": container,
"children": listed,
"refused": refused,
}))?;
Ok(exit::OK)
}
pub fn pod_get(
&self,
target: &GateTarget,
path: &str,
output: Option<&Path>,
) -> Result<u8, CliError> {
let key = self.key()?;
let resource = resolve_path(&key.public(), path)?;
self.download(target, &key, &resource, output)
}
pub fn pod_acl_get(
&self,
target: &GateTarget,
path: &str,
output: Option<&Path>,
) -> Result<u8, CliError> {
let key = self.key()?;
let acl = acl_of(&resolve_path(&key.public(), path)?)?;
self.download(target, &key, &acl, output)
}
pub fn pod_put(&self, target: &GateTarget, options: &PutOptions) -> Result<u8, CliError> {
let key = self.key()?;
let resource = resolve_path(&key.public(), &options.path)?;
if resource.is_container() {
return Err(CliError::Usage(format!(
"{resource} is a container; give a resource path"
)));
}
let content_type = options
.content_type
.clone()
.unwrap_or_else(|| guess_content_type(&options.file, &resource).to_owned());
self.upload(target, &key, &resource, options, &content_type)
}
pub fn pod_acl_put(&self, target: &GateTarget, options: &PutOptions) -> Result<u8, CliError> {
let key = self.key()?;
let acl = acl_of(&resolve_path(&key.public(), &options.path)?)?;
let content_type = options.content_type.as_deref().unwrap_or(TURTLE).to_owned();
self.upload(target, &key, &acl, options, &content_type)
}
pub fn pod_rm(
&self,
target: &GateTarget,
path: &str,
confirmation: Confirmation,
) -> Result<u8, CliError> {
let key = self.key()?;
let resource = resolve_path(&key.public(), path)?;
if resource.is_root_acl() {
return Err(CliError::Usage(
"the root ACL cannot be deleted: it would lock everyone out of the pod, \
its owner included; change it with `stratum pod acl put`"
.to_owned(),
));
}
if !self.confirmed(&format!("delete {resource}?"), confirmation)? {
return Err(CliError::NotConfirmed);
}
let gate = GateClient::new(target.clone());
let response = gate.fetch(
&Request::new("DELETE", resource.as_str(), ANY),
Some(&key),
crate::client::MAX_RESPONSE_BYTES,
)?;
if !response.head.is_success() {
return Err(response.into_error(Route::Pod));
}
self.output().json(&json!({
"path": resource,
"status": response.head.status,
"deleted": true,
}))?;
self.output().line(&format!("deleted {resource}"))?;
Ok(exit::OK)
}
fn download(
&self,
target: &GateTarget,
key: &NostrSecretKey,
resource: &PodPath,
output: Option<&Path>,
) -> Result<u8, CliError> {
if output.is_none() && self.output().is_json() {
return Err(CliError::Usage(
"--json reports on the resource and needs -o <file> for its bytes".to_owned(),
));
}
let gate = GateClient::new(target.clone());
let request = Request::new("GET", resource.as_str(), ANY);
let (head, streamed) = match output {
Some(path) => {
let mut file = create_output(path)?;
let result = gate.stream(&request, key, &mut file, MAX_RESOURCE_BYTES);
let finished = match result {
Ok((head, Ok(streamed))) => {
file.sync_all().map(|()| (head, streamed)).map_err(|err| {
CliError::Local(format!("writing {} failed: {err}", path.display()))
})
}
Ok((head, Err(body))) => Err(gate::error_from(&head, &body, Route::Pod)),
Err(err) => Err(err),
};
match finished {
Ok(done) => done,
Err(err) => {
drop(file);
let _removed = fs::remove_file(path);
return Err(err);
}
}
}
None => self.to_stdout(&gate, &request, key)?,
};
let report = json!({
"path": resource,
"status": head.status,
"content_type": head.content_type.as_deref().map(sanitize),
"etag": head.etag.as_deref().map(sanitize),
"size": streamed.size,
"sha256": streamed.sha256,
"output": output.map(|p| p.display().to_string()),
});
self.output().json(&report)?;
if let Some(path) = output {
self.output().line(&format!(
"wrote {} bytes to {} (sha256 {})",
streamed.size,
path.display(),
streamed.sha256
))?;
if let Some(etag) = &head.etag {
self.output().line(&format!("etag: {}", sanitize(etag)))?;
}
}
Ok(exit::OK)
}
fn to_stdout(
&self,
gate: &GateClient,
request: &Request<'_>,
key: &NostrSecretKey,
) -> Result<(Head, gate::Streamed), CliError> {
let stdout = io::stdout();
if stdout.is_terminal() {
let mut buffer = Vec::new();
let (head, streamed) = gate.stream(request, key, &mut buffer, MAX_RESOURCE_BYTES)?;
let streamed = streamed.map_err(|body| gate::error_from(&head, &body, Route::Pod))?;
self.output()
.line(sanitize(&String::from_utf8_lossy(&buffer)).trim_end())?;
return Ok((head, streamed));
}
let mut lock = stdout.lock();
let (head, streamed) = gate.stream(request, key, &mut lock, MAX_RESOURCE_BYTES)?;
let streamed = streamed.map_err(|body| gate::error_from(&head, &body, Route::Pod))?;
lock.flush()
.map_err(|err| CliError::Local(format!("writing output failed: {err}")))?;
Ok((head, streamed))
}
fn upload(
&self,
target: &GateTarget,
key: &NostrSecretKey,
resource: &PodPath,
options: &PutOptions,
content_type: &str,
) -> Result<u8, CliError> {
if !is_header_value(content_type) {
return Err(CliError::Usage(
"--content-type must be printable ASCII".to_owned(),
));
}
if let WriteCondition::IfMatch(etag) = &options.condition {
if !is_header_value(etag) {
return Err(CliError::Usage(
"--if-match must be printable ASCII, such as \"<64 hex>\"".to_owned(),
));
}
}
let body = read_upload(&options.file)?;
let precondition = match &options.condition {
WriteCondition::Always => Precondition::None,
WriteCondition::IfMatch(etag) => Precondition::IfMatch(etag),
WriteCondition::CreateOnly => Precondition::CreateOnly,
};
let gate = GateClient::new(target.clone()).with_busy_retries(*self.output());
let request = Request::new("PUT", resource.as_str(), ANY)
.with_body(&body, content_type)
.with_precondition(precondition);
let response = gate.fetch(&request, Some(key), crate::client::MAX_RESPONSE_BYTES)?;
if !response.head.is_success() {
return Err(response.into_error(Route::Pod));
}
let head = response.head;
let digest = stratum_node_core::Sha256Digest::of(&body);
self.output().json(&json!({
"path": resource,
"status": head.status,
"created": head.status == 201,
"size": body.len(),
"sha256": digest,
"content_type": content_type,
"etag": head.etag.as_deref().map(sanitize),
}))?;
let verb = if head.status == 201 {
"created"
} else {
"wrote"
};
self.output().line(&format!(
"{verb} {resource} ({} bytes, sha256 {digest})",
body.len()
))?;
if let Some(etag) = &head.etag {
self.output().line(&format!("etag: {}", sanitize(etag)))?;
}
Ok(exit::OK)
}
}
pub(crate) fn resolve_path(owner: &DidNostr, text: &str) -> Result<PodPath, CliError> {
let root = PodPath::pod_root(owner);
let result = if text.starts_with('/') {
PodPath::parse(text)
} else if text.is_empty() {
Ok(root)
} else {
root.join(text)
};
result.map_err(|err| CliError::Usage(path_refusal(text, err)))
}
fn path_refusal(text: &str, err: ParsePodPathError) -> String {
let shown = sanitize(text);
match err {
ParsePodPathError::ForbiddenCharacter => format!(
"{shown:?} is refused by the Step 2 character rule: names may use only \
A-Z a-z 0-9 - . _ ~ and / between segments; no spaces and no percent-encoding"
),
ParsePodPathError::DotSegment => {
format!("{shown:?} has a . or .. segment, which pod paths may not have")
}
ParsePodPathError::EmptySegment => format!(
"{shown:?} has an empty segment (// or a leading /); relative paths start with a name"
),
_ => format!(
"{shown:?} is not a pod path: give a path relative to your pod, or an absolute \
/pods/<64 lowercase hex>/… or /pods/<64 lowercase hex>.acl"
),
}
}
fn acl_of(path: &PodPath) -> Result<PodPath, CliError> {
path.acl_path().ok_or_else(|| {
CliError::Usage(format!(
"{path} is itself an ACL; give the resource or container it controls"
))
})
}
fn guess_content_type(file: &Path, resource: &PodPath) -> &'static str {
let name = resource.as_str();
let extension = file
.extension()
.and_then(|e| e.to_str())
.or_else(|| name.rsplit_once('.').map(|(_, e)| e))
.unwrap_or("")
.to_ascii_lowercase();
match extension.as_str() {
"acl" | "ttl" => TURTLE,
"txt" => "text/plain",
"md" => "text/markdown",
"html" | "htm" => "text/html",
"json" => "application/json",
"jsonld" => "application/ld+json",
"png" => "image/png",
"jpg" | "jpeg" => "image/jpeg",
"pdf" => "application/pdf",
_ => OCTET_STREAM,
}
}
fn is_header_value(text: &str) -> bool {
!text.is_empty() && text.bytes().all(|b| (0x20..0x7f).contains(&b))
}
fn read_upload(path: &Path) -> Result<Vec<u8>, CliError> {
let fail = |message: String| CliError::FileContents {
path: path.to_owned(),
message,
};
let file = File::open(path).map_err(|err| fail(format!("cannot be opened: {err}")))?;
let metadata = file
.metadata()
.map_err(|err| fail(format!("cannot be read: {err}")))?;
if !metadata.is_file() {
return Err(fail("is not a regular file".to_owned()));
}
if metadata.len() > MAX_RESOURCE_BYTES {
return Err(fail(format!(
"is larger than {MAX_RESOURCE_BYTES} bytes, the most a pod accepts"
)));
}
let mut body = Vec::new();
file.take(MAX_RESOURCE_BYTES + 1)
.read_to_end(&mut body)
.map_err(|err| fail(format!("cannot be read: {err}")))?;
if u64::try_from(body.len()).unwrap_or(u64::MAX) > MAX_RESOURCE_BYTES {
return Err(fail(format!(
"is larger than {MAX_RESOURCE_BYTES} bytes, the most a pod accepts"
)));
}
Ok(body)
}
fn create_output(path: &Path) -> Result<File, CliError> {
OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.open(path)
.map_err(|err| {
if err.kind() == io::ErrorKind::AlreadyExists {
CliError::File {
path: path.to_owned(),
source: crate::private_file::PrivateFileError::AlreadyExists,
}
} else {
CliError::File {
path: path.to_owned(),
source: crate::private_file::PrivateFileError::Io(err),
}
}
})
}
#[cfg(test)]
mod tests {
use super::*;
const A: &str = "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798";
#[test]
fn command_line_paths_resolve_or_say_why_not() {
let owner = DidNostr::from_hex(A).expect("key");
assert_eq!(
resolve_path(&owner, "").expect("root").as_str(),
format!("/pods/{A}/")
);
assert_eq!(
resolve_path(&owner, "private/x.txt")
.expect("relative")
.as_str(),
format!("/pods/{A}/private/x.txt")
);
assert_eq!(
resolve_path(&owner, &format!("/pods/{A}.acl"))
.expect("root acl")
.as_str(),
format!("/pods/{A}.acl")
);
let err = resolve_path(&owner, "my file.txt").expect_err("space");
assert!(err.to_string().contains("Step 2 character rule"), "{err}");
let err = resolve_path(&owner, "a%20b").expect_err("percent");
assert!(err.to_string().contains("no percent-encoding"), "{err}");
let err = resolve_path(&owner, "a/../b").expect_err("dot");
assert!(err.to_string().contains(". or .."), "{err}");
let err = resolve_path(&owner, "/etc/passwd").expect_err("outside");
assert!(err.to_string().contains("not a pod path"), "{err}");
assert_eq!(err.exit_code(), exit::USAGE);
}
#[test]
fn acl_paths_sit_beside_their_resource() {
let owner = DidNostr::from_hex(A).expect("key");
let root = resolve_path(&owner, "").expect("root");
assert_eq!(
acl_of(&root).expect("acl").as_str(),
format!("/pods/{A}.acl")
);
let acl = resolve_path(&owner, "x.txt.acl").expect("acl");
assert!(acl_of(&acl).is_err());
}
}