use std::{
fmt,
path::PathBuf,
rc::{Rc, Weak},
time::Duration,
};
use crate::{
EventPayload, JsonValue, NodeId,
element::{
Answer,
task::{Action, AnswerSlot, Executor},
},
};
#[non_exhaustive]
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct DownloadDestination {
pub path: PathBuf,
pub overwrite: bool,
}
impl DownloadDestination {
pub fn new(path: impl Into<PathBuf>) -> Self {
Self {
path: path.into(),
overwrite: false,
}
}
#[must_use]
pub fn path(mut self, path: impl Into<PathBuf>) -> Self {
self.path = path.into();
self
}
#[must_use]
pub fn overwrite(mut self, overwrite: bool) -> Self {
self.overwrite = overwrite;
self
}
}
impl From<PathBuf> for DownloadDestination {
fn from(path: PathBuf) -> Self {
Self::new(path)
}
}
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum WebDownloadSource {
#[default]
Transfer,
Request,
Page,
None,
}
impl WebDownloadSource {
pub fn as_str(self) -> &'static str {
match self {
WebDownloadSource::Transfer => "transfer",
WebDownloadSource::Request => "request",
WebDownloadSource::Page => "page",
WebDownloadSource::None => "none",
}
}
pub(crate) fn parse(name: &str) -> Option<Self> {
match name {
"transfer" => Some(WebDownloadSource::Transfer),
"request" => Some(WebDownloadSource::Request),
"page" => Some(WebDownloadSource::Page),
"none" => Some(WebDownloadSource::None),
_ => None,
}
}
}
impl fmt::Display for WebDownloadSource {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum CancelReason {
App,
Timeout,
Teardown,
NoListener,
}
impl CancelReason {
pub fn as_str(self) -> &'static str {
match self {
CancelReason::App => "app",
CancelReason::Timeout => "timeout",
CancelReason::Teardown => "teardown",
CancelReason::NoListener => "noListener",
}
}
}
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum WebDownloadState {
#[default]
Started,
Finished,
Failed,
Cancelled,
}
impl WebDownloadState {
pub(crate) fn parse(name: &str) -> Option<Self> {
match name {
"started" => Some(WebDownloadState::Started),
"finished" => Some(WebDownloadState::Finished),
"failed" => Some(WebDownloadState::Failed),
"cancelled" => Some(WebDownloadState::Cancelled),
_ => None,
}
}
}
impl fmt::Display for WebDownloadState {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
WebDownloadState::Started => "started",
WebDownloadState::Finished => "finished",
WebDownloadState::Failed => "failed",
WebDownloadState::Cancelled => "cancelled",
})
}
}
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct WebDownloadPending {
pub id: String,
pub url: String,
pub filename: String,
pub source: WebDownloadSource,
pub mime_type: Option<String>,
pub bytes: Option<u64>,
pub method: Option<String>,
pub(crate) handle: Option<DownloadHandle>,
}
impl WebDownloadPending {
pub fn accept(
&self,
destination: impl Into<DownloadDestination>,
) -> Answer<Result<(), String>> {
match &self.handle {
Some(handle) => handle.decide(Decision::Accept(destination.into())),
None => unbound(),
}
}
pub fn cancel(&self) -> Answer<Result<(), String>> {
match &self.handle {
Some(handle) => handle.decide(Decision::Cancel),
None => unbound(),
}
}
}
impl PartialEq for WebDownloadPending {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
&& self.url == other.url
&& self.filename == other.filename
&& self.source == other.source
&& self.mime_type == other.mime_type
&& self.bytes == other.bytes
&& self.method == other.method
&& match (&self.handle, &other.handle) {
(Some(a), Some(b)) => a.same_as(b),
(None, None) => true,
_ => false,
}
}
}
impl Eq for WebDownloadPending {}
#[derive(Clone, Debug)]
pub(crate) enum Decision {
Accept(DownloadDestination),
Cancel,
}
#[derive(Clone, Debug)]
pub(crate) struct DownloadHandle {
identity: Rc<DownloadIdentity>,
}
#[derive(Debug)]
struct DownloadIdentity {
node: NodeId,
executor: Weak<Executor>,
id: String,
}
impl DownloadHandle {
pub(crate) fn new(node: NodeId, executor: Weak<Executor>, id: String) -> Self {
Self {
identity: Rc::new(DownloadIdentity { node, executor, id }),
}
}
fn same_as(&self, other: &Self) -> bool {
Rc::ptr_eq(&self.identity, &other.identity)
}
fn decide(&self, decision: Decision) -> Answer<Result<(), String>> {
let (answer, slot) = Answer::new();
let Some(executor) = self.identity.executor.upgrade() else {
deliver(slot, Err(NOT_MOUNTED.to_owned()));
return answer;
};
executor.act(Action::DownloadDecision {
node: self.identity.node,
id: self.identity.id.clone(),
decision,
answer: slot,
});
answer
}
}
#[non_exhaustive]
#[derive(Clone, Debug, Default)]
pub struct WebDownload {
pub state: WebDownloadState,
pub id: String,
pub url: String,
pub filename: String,
pub path: PathBuf,
pub bytes: Option<u64>,
pub message: Option<String>,
pub source: WebDownloadSource,
pub code: Option<String>,
pub reason: Option<CancelReason>,
pub(crate) handle: Option<DownloadHandle>,
}
impl PartialEq for WebDownload {
fn eq(&self, other: &Self) -> bool {
self.state == other.state
&& self.id == other.id
&& self.url == other.url
&& self.filename == other.filename
&& self.path == other.path
&& self.bytes == other.bytes
&& self.message == other.message
&& self.source == other.source
&& self.code == other.code
&& self.reason == other.reason
&& match (&self.handle, &other.handle) {
(Some(a), Some(b)) => a.same_as(b),
(None, None) => true,
_ => false,
}
}
}
impl Eq for WebDownload {}
impl WebDownload {
pub fn cancel(&self) -> Answer<Result<(), String>> {
match (&self.handle, self.state) {
(Some(handle), WebDownloadState::Started) => handle.decide(Decision::Cancel),
(Some(_), _) => {
let (answer, slot) = Answer::new();
deliver(slot, Err(crate::element::codes::DOWNLOAD_STATE.to_owned()));
answer
}
(None, _) => unbound(),
}
}
}
fn deliver(slot: AnswerSlot<Result<(), String>>, result: Result<(), String>) {
slot.borrow_mut().deliver(result);
}
fn unbound() -> Answer<Result<(), String>> {
let (answer, slot) = Answer::new();
deliver(slot, Err(UNBOUND.to_owned()));
answer
}
pub(crate) const UNBOUND: &str = "this download decision is not bound to a pending download";
pub(crate) const NOT_MOUNTED: &str = "the web view is not mounted";
pub(crate) const REPLY_TIMEOUT: Duration = Duration::from_secs(30);
pub(crate) const OFFER_TIMEOUT: Duration = Duration::from_secs(60);
#[doc(hidden)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DownloadOffer {
pub id: String,
pub url: String,
pub filename: String,
pub mime_type: Option<String>,
pub bytes: Option<u64>,
pub method: Option<String>,
pub source: WebDownloadSource,
}
#[doc(hidden)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DownloadProgress {
pub id: String,
pub received: u64,
}
#[doc(hidden)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DownloadEnd {
pub id: String,
pub outcome: DownloadOutcome,
}
#[doc(hidden)]
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DownloadOutcome {
Finished {
bytes: u64,
},
Failed {
code: Option<String>,
message: String,
},
}
#[doc(hidden)]
pub fn download_offer(offer: &DownloadOffer) -> EventPayload {
EventPayload::Json(serde_json::json!({
"id": offer.id,
"url": offer.url,
"filename": offer.filename,
"mime_type": offer.mime_type,
"bytes": offer.bytes,
"method": offer.method,
"source": offer.source.as_str(),
}))
}
#[doc(hidden)]
pub fn download_progress(progress: &DownloadProgress) -> EventPayload {
EventPayload::Json(serde_json::json!({
"id": progress.id,
"received": progress.received,
}))
}
#[doc(hidden)]
pub fn download_end(end: &DownloadEnd) -> EventPayload {
let value = match &end.outcome {
DownloadOutcome::Finished { bytes } => serde_json::json!({
"id": end.id,
"outcome": "finished",
"bytes": bytes,
}),
DownloadOutcome::Failed { code, message } => serde_json::json!({
"id": end.id,
"outcome": "failed",
"code": code,
"message": message,
}),
};
EventPayload::Json(value)
}
fn parse_u64(value: &JsonValue) -> Option<u64> {
value.as_u64().or_else(|| {
value
.as_f64()
.filter(|n| n.is_finite() && *n >= 0.0 && n.fract() == 0.0)
.map(|n| n as u64)
})
}
pub(crate) fn parse_offer(value: &JsonValue) -> Option<DownloadOffer> {
Some(DownloadOffer {
id: value.get("id")?.as_str()?.to_owned(),
url: value.get("url")?.as_str()?.to_owned(),
filename: value.get("filename")?.as_str()?.to_owned(),
mime_type: value
.get("mime_type")
.and_then(JsonValue::as_str)
.map(str::to_owned),
bytes: value.get("bytes").and_then(parse_u64),
method: value
.get("method")
.and_then(JsonValue::as_str)
.map(str::to_owned),
source: value
.get("source")
.and_then(JsonValue::as_str)
.and_then(WebDownloadSource::parse)
.unwrap_or_default(),
})
}
pub(crate) fn parse_end(value: &JsonValue) -> Option<DownloadEnd> {
let id = value.get("id")?.as_str()?.to_owned();
let outcome = match value.get("outcome")?.as_str()? {
"finished" => DownloadOutcome::Finished {
bytes: value.get("bytes").and_then(parse_u64).unwrap_or(0),
},
"failed" => DownloadOutcome::Failed {
code: value
.get("code")
.and_then(JsonValue::as_str)
.map(str::to_owned),
message: value
.get("message")
.and_then(JsonValue::as_str)
.unwrap_or_default()
.to_owned(),
},
_ => return None,
};
Some(DownloadEnd { id, outcome })
}
pub(crate) fn automatic_destination(id: &str, filename: &str) -> Option<DownloadDestination> {
let dir = crate::element::data_dir()?;
let mut component = String::with_capacity(id.len().min(64));
for c in id.chars().take(64) {
if c.is_ascii_alphanumeric() || matches!(c, '-' | '_') {
component.push(c);
} else {
component.push('_');
}
}
if component.is_empty() {
component.push('_');
}
let name = std::path::Path::new(filename)
.file_name()
.and_then(std::ffi::OsStr::to_str)
.filter(|name| !name.is_empty() && *name != "." && *name != "..")
.unwrap_or("download");
Some(DownloadDestination::new(
dir.join("downloads").join(component).join(name),
))
}
pub(crate) mod files {
#[cfg(unix)]
use std::os::unix::fs::{DirBuilderExt, MetadataExt};
use std::{
fs, io,
path::{Path, PathBuf},
};
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Staging {
dir: PathBuf,
path: PathBuf,
owned_parent: bool,
#[cfg(unix)]
identity: (u64, u64),
}
impl Staging {
pub(crate) fn path(&self) -> &Path {
&self.path
}
#[cfg(test)]
pub(crate) fn dir(&self) -> &Path {
&self.dir
}
pub(crate) fn adopt(dir: PathBuf, path: PathBuf) -> Self {
#[cfg(unix)]
let identity = fs::symlink_metadata(&dir)
.map(|meta| (meta.dev(), meta.ino()))
.unwrap_or((0, 0));
Self {
dir,
path,
owned_parent: false,
#[cfg(unix)]
identity,
}
}
}
fn dir_name(id: &str) -> String {
let mut name = String::with_capacity(id.len().min(64) + 16);
name.push_str(".nsh-download-");
for c in id.chars().take(64) {
if c.is_ascii_alphanumeric() || matches!(c, '-' | '_') {
name.push(c);
} else {
name.push('_');
}
}
name
}
pub(crate) fn stage(
destination: &Path,
id: &str,
overwrite: bool,
create_parent: bool,
) -> Result<Staging, String> {
if !destination.is_absolute() {
return Err(format!(
"`{}` is not an absolute path",
destination.display()
));
}
let Some(name) = destination.file_name().filter(|n| !n.is_empty()) else {
return Err(format!("`{}` does not name a file", destination.display()));
};
let Some(parent) = destination.parent() else {
return Err(format!("`{}` has no directory", destination.display()));
};
if !parent.is_dir() {
if !create_parent {
return Err(format!(
"`{}` is not a directory to write into",
parent.display()
));
}
fs::create_dir_all(parent)
.map_err(|error| format!("`{}` cannot be made: {error}", parent.display()))?;
}
match fs::symlink_metadata(destination) {
Ok(meta) => {
if meta.is_dir() {
return Err(format!("`{}` is a directory", destination.display()));
}
if !overwrite {
return Err(format!(
"`{}` exists; pass overwrite to replace it",
destination.display()
));
}
}
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
Err(error) => {
return Err(format!(
"`{}` cannot be checked: {error}",
destination.display()
));
}
}
let dir = parent.join(dir_name(id));
#[cfg(unix)]
let created = fs::DirBuilder::new().mode(0o700).create(&dir);
#[cfg(not(unix))]
let created = fs::create_dir(&dir);
match created {
Ok(()) => {}
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {
return Err(format!(
"a staging area for this download already exists: `{}`",
dir.display()
));
}
Err(error) => {
return Err(format!("`{}` cannot be made: {error}", dir.display()));
}
}
let path = dir.join(name);
#[cfg(unix)]
let identity = {
let meta = fs::symlink_metadata(&dir)
.map_err(|error| format!("`{}` cannot be read: {error}", dir.display()))?;
(meta.dev(), meta.ino())
};
Ok(Staging {
dir,
path,
owned_parent: create_parent,
#[cfg(unix)]
identity,
})
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum PublishError {
Size { actual: u64, declared: u64 },
Destination(String),
}
pub(crate) fn publish(
staging: &Staging,
destination: &Path,
overwrite: bool,
declared: Option<u64>,
) -> Result<u64, PublishError> {
let meta = fs::symlink_metadata(staging.path()).map_err(|error| {
PublishError::Destination(format!(
"the staged file `{}` is gone: {error}",
staging.path().display()
))
})?;
if !meta.file_type().is_file() {
return Err(PublishError::Destination(format!(
"`{}` is not a regular file",
staging.path().display()
)));
}
let actual = meta.len();
if let Some(declared) = declared
&& declared != actual
{
return Err(PublishError::Size { actual, declared });
}
if overwrite {
fs::rename(staging.path(), destination).map_err(|error| {
PublishError::Destination(format!(
"`{}` cannot be published as `{}`: {error}",
staging.path().display(),
destination.display()
))
})?;
} else {
publish_new(staging.path(), destination).map_err(|error| {
PublishError::Destination(format!(
"`{}` cannot be published as `{}`: {error}",
staging.path().display(),
destination.display()
))
})?;
}
let _ = fs::remove_dir(&staging.dir);
Ok(actual)
}
fn publish_new(from: &Path, to: &Path) -> io::Result<()> {
#[cfg(any(target_os = "linux", target_os = "android"))]
{
use std::{ffi::CString, os::unix::ffi::OsStrExt};
let from_c = CString::new(from.as_os_str().as_bytes())
.map_err(|error| io::Error::new(io::ErrorKind::InvalidInput, error))?;
let to_c = CString::new(to.as_os_str().as_bytes())
.map_err(|error| io::Error::new(io::ErrorKind::InvalidInput, error))?;
let result = unsafe {
libc::syscall(
libc::SYS_renameat2,
libc::AT_FDCWD,
from_c.as_ptr(),
libc::AT_FDCWD,
to_c.as_ptr(),
libc::RENAME_NOREPLACE,
)
};
if result == 0 {
return Ok(());
}
let error = io::Error::last_os_error();
if !matches!(
error.raw_os_error(),
Some(libc::ENOSYS | libc::EINVAL | libc::EOPNOTSUPP)
) {
return Err(error);
}
}
fs::hard_link(from, to)?;
if let Err(error) = fs::remove_file(from) {
log::warn!("download published, but its staging link could not be removed: {error}");
}
Ok(())
}
pub(crate) fn cleanup(staging: &Staging) -> Result<(), String> {
let mut removed = false;
match fs::symlink_metadata(&staging.dir) {
Ok(meta) if meta.is_dir() => {
#[cfg(unix)]
let ours = (meta.dev(), meta.ino()) == staging.identity;
#[cfg(not(unix))]
let ours = true;
if ours {
removed = fs::remove_dir_all(&staging.dir).is_ok();
} else {
log::warn!(
"web view download: `{}` is not the directory this download made; left alone",
staging.dir.display()
);
}
}
Ok(_) => {
removed = fs::remove_file(&staging.dir).is_ok();
}
Err(_) => {
removed = true;
}
}
if staging.owned_parent
&& removed
&& let Some(parent) = staging.dir.parent()
{
let _ = fs::remove_dir(parent);
}
if removed {
Ok(())
} else {
Err(format!(
"`{}` could not be removed (it is not this download's directory any more)",
staging.dir.display()
))
}
}
}
mod coordinator;
mod shutdown;
pub(crate) use coordinator::{Downloads, Effect, Mode};
#[doc(hidden)]
pub use shutdown::DownloadCleanup;