Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions pkgs/id/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,7 @@ it is — a valid world capability, minted by the host's admin with
| `repl` | `shell` | Interactive REPL with pipes and subshells |
| `put` | `in`, `add`, `store`, `import` | Store files in blob store |
| `put-hash` | | Store content by hash only (no named tag) |
| `send` | | Copy a file from one server to another |
| `get` | | Retrieve files by name or hash |
| `get-hash` | | Retrieve file by hash with explicit output path |
| `cat` | `output`, `out` | Output file content to stdout |
Expand Down
40 changes: 40 additions & 0 deletions pkgs/id/crates/id-cli/src/cli/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
//! repl Interactive REPL (alias: shell)
//! put Store files (aliases: in, add, store, import)
//! put-hash Store content by hash only
//! send Copy a file from one server to another
//! get Retrieve files by name or hash
//! get-hash Retrieve by hash (shortcut)
//! cat Output files to stdout (aliases: output, out)
Expand Down Expand Up @@ -747,6 +748,45 @@ pub enum Command {
/// File path to store, or "-" for stdin.
source: String,
},
/// Copy a file from one running server to another (server-to-server send).
///
/// The *source server* performs the transfer with its own identity:
/// it pushes the file's blob to the destination and registers the
/// name there. The destination's write policy must allow the source
/// server's node ID, and that node is recorded as the copy's origin.
/// No file bytes pass through this client.
///
/// # Examples
///
/// ```bash
/// # Copy report.txt from server A to server B under the same name
/// id send A_NODE_ID report.txt --to B_NODE_ID
///
/// # Copy under a different destination name
/// id send A_NODE_ID report.txt --to B_NODE_ID --as summary.txt
///
/// # Replace an existing destination name (old file is archived first)
/// id send A_NODE_ID report.txt --to B_NODE_ID --replace
/// ```
Send {
/// Source server node ID (64 hex characters).
source: String,
/// Name of the file on the source server.
name: String,
/// Destination server node ID (64 hex characters).
#[arg(long)]
to: String,
/// Name to register on the destination (defaults to the source name).
#[arg(long = "as")]
dest_name: Option<String>,
/// Replace an existing, different destination file; the old file
/// is preserved under an archive name on the destination first.
#[arg(long)]
replace: bool,
/// Disable relay servers for the connection to the source.
#[arg(long)]
no_relay: bool,
},
/// Retrieve one or more files by name or hash.
///
/// Files can be written to different output paths using `source:output`.
Expand Down
2 changes: 2 additions & 0 deletions pkgs/id/crates/id-cli/src/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ pub mod match_audit;
pub mod peers;
pub mod put;
pub mod repl;
pub mod send;
pub mod serve;
pub mod tag;
pub mod text;
Expand All @@ -95,6 +96,7 @@ pub use put::{
cmd_put_one_remote,
};
pub use repl::{ReplContext, ReplContextInner};
pub use send::cmd_send;
pub use serve::{
ServeInfo, ServeOptions, build_access_policy, cmd_serve, create_serve_lock, get_serve_info,
is_process_alive, remove_serve_lock,
Expand Down
84 changes: 10 additions & 74 deletions pkgs/id/crates/id-cli/src/commands/put.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,16 +63,6 @@ use std::io::IsTerminal;
use std::path::PathBuf;
use tokio::fs as afs;

use crate::local::LocalNode;
use crate::meta_client::{expect_ok, request_over};
use crate::{
CLIENT_KEY_FILE, META_ALPN, MetaRequest, MetaResponse, create_local_client_endpoint,
get_serve_info, is_node_id, load_or_create_keypair, open_store, parse_put_spec,
parse_stdin_items, read_input,
};

const PUT_FINALIZATION_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2 * 60);

/// Add `data` to `store` as a raw blob; returns its hash and a guard that keeps
/// the blob protected until dropped (hold it until the blob has been named).
pub async fn add_raw(store: &Store, data: Vec<u8>) -> Result<(Hash, TempTag)> {
Expand All @@ -89,70 +79,16 @@ pub async fn add_raw(store: &Store, data: Vec<u8>) -> Result<(Hash, TempTag)> {
Ok((guard.hash(), guard))
}

/// Upload `hash` to `target`, **then** register `name` for it.
///
/// Two ordering rules make this safe:
///
/// 1. **Bytes before name.** The server verifies the blob is present before it
/// creates a name, so a failed upload can never leave a dangling name.
/// 2. **Keep the blobs connection open until the server confirms.** A push is
/// one-way — the server sends no acknowledgement — and closing the QUIC
/// connection right after the last write can abort the server's import of
/// data it has buffered but not yet processed. The `Put` request is the
/// acknowledgement: the server answers it once the blob is complete, so we
/// close the blobs connection only after that.
///
/// A `Put` for a blob that is still being finalized is retried for up to two
/// minutes (large blobs take a moment to finish on the server).
pub async fn push_and_name(
store: &Store,
endpoint: &Endpoint,
target: EndpointAddr,
name: &str,
hash: Hash,
) -> Result<()> {
let blobs_conn = id_core::connectivity::connect(endpoint, target.clone(), BLOBS_ALPN).await?;
let push_request = PushRequest::new(hash, ChunkRangesSeq::from_ranges([ChunkRanges::all()]));
store
.remote()
.execute_push(blobs_conn.clone(), push_request)
.await
.context(
"blob push rejected: the server only accepts writes from allowed nodes \
(run `id id --client` on this machine and add the printed ID to the \
server's `--allow-node` or `.iroh-allowed`)",
)?;

let meta_conn = id_core::connectivity::connect(endpoint, target, META_ALPN).await?;
let req = MetaRequest::Put {
filename: name.to_owned(),
hash,
};
let outcome = id_core::connectivity::within(
PUT_FINALIZATION_TIMEOUT,
"registering the blob name",
async {
loop {
match request_over(&meta_conn, &req).await? {
MetaResponse::Error { message }
if id_sync::fileops::is_blob_missing_message(&message) =>
{
tokio::time::sleep(std::time::Duration::from_millis(250)).await;
}
response => return Ok(response),
}
}
},
)
.await;
meta_conn.close(0u32.into(), b"done");
blobs_conn.close(0u32.into(), b"done");
match expect_ok(outcome?)? {
MetaResponse::Put { success: true } => Ok(()),
MetaResponse::Put { success: false } => bail!("server rejected"),
_ => bail!("unexpected response"),
}
}
pub use id_sync::meta_client::push_and_name;

use crate::local::LocalNode;
use crate::meta_client::{expect_ok, request_over};
use crate::{
CLIENT_KEY_FILE, META_ALPN, MetaRequest, MetaResponse, create_local_client_endpoint,
get_serve_info, is_node_id, load_or_create_keypair, open_store, parse_put_spec,
parse_stdin_items, read_input,
};


/// Trim a name typed at the forgiving CLI surface before FileOps sees it.
///
Expand Down
47 changes: 47 additions & 0 deletions pkgs/id/crates/id-cli/src/commands/repl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -738,6 +738,53 @@ impl ReplContext {
Ok(())
}

/// Ask this context's node (the source) to copy a file to another
/// server (#5345).
///
/// The source server performs the transfer with its own identity; see
/// [`id_sync::transfer`]. `dest_name` defaults to `name`; with
/// `replace`, an existing different destination file is archived and
/// replaced instead of refusing the send.
pub async fn send(
&mut self,
name: &str,
dest_str: &str,
dest_name: Option<&str>,
replace: bool,
) -> Result<()> {
if !is_node_id(dest_str) {
bail!("invalid destination node ID: must be 64 hex characters");
}
let dest: EndpointId = dest_str.parse()?;
let req = MetaRequest::Send {
name: name.to_owned(),
dest,
dest_name: dest_name.map(ToOwned::to_owned),
replace,
};
match expect_ok(self.request(req).await?)? {
MetaResponse::Send {
hash,
name: registered,
already_present,
replaced,
..
} => {
if already_present {
println!("already present: {name} -> {dest}:{registered} ({hash})");
} else if replaced {
println!(
"sent: {name} -> {dest}:{registered} ({hash}); previous file archived"
);
} else {
println!("sent: {name} -> {dest}:{registered} ({hash})");
}
Ok(())
}
_ => bail!("unexpected response"),
}
}

/// Search for blobs matching a query.
///
/// Performs case-insensitive matching against tag names and blob hashes.
Expand Down
98 changes: 98 additions & 0 deletions pkgs/id/crates/id-cli/src/commands/send.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
//! `id send` — copy a file from one running server to another (#5345).
//!
//! The command only *asks* the source server to perform the transfer: the
//! source server reads its stored file and pushes it to the destination
//! with its own server identity (see [`id_sync::transfer`]). The local CLI
//! client key is never the sending identity, and no file bytes pass
//! through this process.
//!
//! ```bash
//! # Copy report.txt from server A to server B under the same name
//! id send A_NODE_ID report.txt --to B_NODE_ID
//!
//! # Copy under a different destination name
//! id send A_NODE_ID report.txt --to B_NODE_ID --as summary.txt
//!
//! # Replace an existing destination name (the old file is archived first)
//! id send A_NODE_ID report.txt --to B_NODE_ID --replace
//! ```

use anyhow::{Result, bail};
use iroh_base::EndpointId;

use crate::is_node_id;
use crate::meta_client::{MetaClient, MetaRequester, expect_ok};
use crate::protocol::{MetaRequest, MetaResponse};

/// Trim a name typed at the CLI surface (FileOps stores names verbatim and
/// refuses padding, so a stray space is a typing slip, as in `id put`).
fn trim_surface_name(name: &str) -> &str {
name.trim()
}

/// Ask the server `source` to copy its file `name` to the server `to`.
///
/// `dest_name` defaults to `name`. With `replace`, an existing different
/// file at the destination name is archived and replaced; without it, a
/// conflict is an error and nothing is sent.
pub async fn cmd_send(
source: &str,
name: &str,
to: &str,
dest_name: Option<String>,
replace: bool,
no_relay: bool,
) -> Result<()> {
if !is_node_id(source) {
bail!("invalid source node ID: must be 64 hex characters");
}
if !is_node_id(to) {
bail!("invalid destination node ID: must be 64 hex characters");
}
let source_id: EndpointId = source.parse()?;
let dest_id: EndpointId = to.parse()?;
let name = trim_surface_name(name);
let dest_name = dest_name.as_deref().map(trim_surface_name);

let mut client = MetaClient::connect_node(source_id, no_relay).await?;
let resp = client
.request(MetaRequest::Send {
name: name.to_owned(),
dest: dest_id,
dest_name: dest_name.map(ToOwned::to_owned),
replace,
})
.await;
let resp = match resp {
Ok(resp) => resp,
Err(e) => {
let _ = client.close().await;
return Err(e);
}
};
let result = match expect_ok(resp)? {
MetaResponse::Send {
hash,
name: registered,
dest,
already_present,
replaced,
} => {
if already_present {
println!(
"already present: {name} -> {dest}:{registered} ({hash}); nothing to send"
);
} else if replaced {
println!(
"sent: {name} -> {dest}:{registered} ({hash}); previous file archived on the destination"
);
} else {
println!("sent: {name} -> {dest}:{registered} ({hash})");
}
Ok(())
}
_ => bail!("unexpected response"),
};
client.close().await?;
result
}
7 changes: 6 additions & 1 deletion pkgs/id/crates/id-cli/src/commands/serve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1852,14 +1852,19 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> {
let abuse_handle: Option<std::sync::Arc<std::sync::Mutex<id_core::abuse::AbuseEvaluator>>> =
None;

let meta = MetaProtocol::new(
let mut meta = MetaProtocol::new(
&store_handle,
Some(peer_discovery.clone()),
Arc::clone(&tag_store),
access.clone(),
node_id,
abuse_handle,
);
// Server-to-server transfers (#5345) are initiated from this handler
// with the server's own endpoint and identity.
if let Some(inner) = Arc::get_mut(&mut meta) {
inner.endpoint = Some(endpoint.clone());
}

#[cfg(all(feature = "world", feature = "ssh"))]
let (ssh_tunnel, ssh_tunnel_port) = id_worlds::world_ssh::SshTunnelProtocol::deferred();
Expand Down
14 changes: 13 additions & 1 deletion pkgs/id/crates/id-cli/src/local.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,9 @@ impl LocalNode {
// Nothing is in flight for an in-process node: a missing blob is missing.
if let Some(inner) = Arc::get_mut(&mut m) {
inner.blob_wait = std::time::Duration::ZERO;
// The in-process handler answers with this node's own
// endpoint, so an offline `send` behaves like an online one.
inner.endpoint = Some(endpoint.clone());
}
m
};
Expand Down Expand Up @@ -194,6 +197,12 @@ impl LocalNode {
self.node_id
}

/// This node's QUIC endpoint (bound on loopback; its identity is the
/// node's key). Used by the transfer module to dial peers as this node.
pub fn endpoint(&self) -> &Endpoint {
&self.endpoint
}

/// Dialable address of this node on loopback (for in-process tests and
/// same-machine clients; no discovery is involved).
pub fn addr(&self) -> EndpointAddr {
Expand All @@ -212,14 +221,17 @@ impl LocalNode {
/// Used by tests and by programs embedding an `id` node. Shut the returned
/// router down before [`LocalNode::shutdown`].
pub fn serve(&self, access: AccessPolicy) -> Router {
let meta = MetaProtocol::new(
let mut meta = MetaProtocol::new(
&self.blobs,
None,
Arc::clone(&self.tags),
access.clone(),
self.node_id,
None,
);
if let Some(inner) = Arc::get_mut(&mut meta) {
inner.endpoint = Some(self.endpoint.clone());
}
// With a gate, blob fetches and observes are membership-checked (#173) and
// pushes keep this policy; without one, pushes alone are gated, as before.
let blobs = match &self.blob_gate {
Expand Down
Loading