Skip to main content

node_app_sdk_rust/
pipe.rs

1//! In-process pipes to another native app (`core.pipe.*`, ADR-300).
2//!
3//! Two native apps in one host process can share a live two-way byte stream: the opener gets
4//! one end of a host-made `AF_UNIX` socket pair and a token for the other; it passes the token
5//! on in a capability call of its own; the receiver claims it. Each side then owns a plain Unix
6//! stream socket and wraps it on its own runtime (`tokio::net::UnixStream::from_std` after
7//! `set_nonblocking(true)`). A token nobody claims within its TTL closes, and the opener reads
8//! EOF.
9//!
10//! ```ignore
11//! // opener
12//! let (ours, token) = node_app_sdk_rust::pipe::open("ln-bolt8", None)?;
13//! invoke_capability(/* the other app's capability, carrying `token` */)?;
14//! // receiver, inside that capability
15//! let (theirs, _info) = node_app_sdk_rust::pipe::claim(&token)?;
16//! ```
17
18use std::os::fd::{FromRawFd, OwnedFd, RawFd};
19use std::os::unix::net::UnixStream;
20
21use crate::{invoke_capability, CapabilityRequest, NodeAppError};
22
23/// Opens a pair.
24pub const OPEN: &str = "core.pipe.open";
25/// Claims a parked end.
26pub const CLAIM: &str = "core.pipe.claim";
27
28/// What the claimer learns about the pipe.
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct ClaimInfo {
31    /// The opener's purpose.
32    pub purpose: String,
33    /// The app that opened the pair.
34    pub opener: String,
35}
36
37fn call(capability: &str, payload: serde_json::Value) -> Result<serde_json::Value, NodeAppError> {
38    let response = invoke_capability(&CapabilityRequest {
39        id: format!("pipe-{}", std::process::id()),
40        capability: capability.to_string(),
41        payload,
42        ..Default::default()
43    })?;
44    if response.success {
45        Ok(response.payload)
46    } else {
47        let message = response
48            .payload
49            .get("message")
50            .or_else(|| response.payload.get("error"))
51            .and_then(serde_json::Value::as_str)
52            .unwrap_or("pipe call failed")
53            .to_string();
54        Err(NodeAppError::CapabilityError(message))
55    }
56}
57
58/// Takes ownership of the fd a pipe answer names, after checking it is an open socket.
59fn adopt(answer: &serde_json::Value) -> Result<OwnedFd, NodeAppError> {
60    let fd = answer
61        .get("fd")
62        .and_then(serde_json::Value::as_i64)
63        .and_then(|fd| RawFd::try_from(fd).ok())
64        .filter(|fd| *fd >= 0)
65        .ok_or_else(|| NodeAppError::CapabilityError("pipe answer has no fd".into()))?;
66    // SAFETY: `fstat` only writes into the zeroed struct we own.
67    let mut stat: libc::stat = unsafe { std::mem::zeroed() };
68    if unsafe { libc::fstat(fd, &mut stat) } != 0 || (stat.st_mode & libc::S_IFMT) != libc::S_IFSOCK {
69        return Err(NodeAppError::CapabilityError(format!(
70            "fd {} is not an open socket in this process",
71            fd
72        )));
73    }
74    // SAFETY: the host transferred ownership of this descriptor in its answer.
75    Ok(unsafe { OwnedFd::from_raw_fd(fd) })
76}
77
78/// Opens a pair for `purpose` (1..=64 printable ASCII): this app's end, and the token of the
79/// other end to pass on. `ttl_ms` bounds the wait for a claimer (host default 10 s, max 30 s).
80pub fn open(purpose: &str, ttl_ms: Option<u64>) -> Result<(UnixStream, String), NodeAppError> {
81    let mut payload = serde_json::json!({ "pid": std::process::id(), "purpose": purpose });
82    if let Some(ttl_ms) = ttl_ms {
83        payload["ttl_ms"] = ttl_ms.into();
84    }
85    let answer = call(OPEN, payload)?;
86    let token = answer
87        .get("peer_token")
88        .and_then(serde_json::Value::as_str)
89        .ok_or_else(|| NodeAppError::CapabilityError("pipe answer has no token".into()))?
90        .to_string();
91    Ok((UnixStream::from(adopt(&answer)?), token))
92}
93
94/// Claims the end parked under `token`.
95pub fn claim(token: &str) -> Result<(UnixStream, ClaimInfo), NodeAppError> {
96    let answer = call(CLAIM, serde_json::json!({ "pid": std::process::id(), "token": token }))?;
97    let text = |key: &str| {
98        answer.get(key).and_then(serde_json::Value::as_str).unwrap_or_default().to_string()
99    };
100    let info = ClaimInfo { purpose: text("purpose"), opener: text("opener") };
101    Ok((UnixStream::from(adopt(&answer)?), info))
102}