| 1 | // Copyright 2026 Deno Land Inc. All rights reserved. |
| 2 | |
| 3 | //! The peer tunnel: an upgraded stream per peer, plain HTTP inside. |
| 4 | //! |
| 5 | //! Establishment is an h1 upgrade on `/peer/tunnel` — CONNECT semantics with Upgrade |
| 6 | //! mechanics, because CONNECT's authority-form target fits this use badly. |
| 7 | //! After the 101 the connection is an opaque duplex stream, and app requests |
| 8 | //! cross as literal HTTP driven by hyper on both ends: the hop never |
| 9 | //! interprets the inner bytes, so the headers the cell must receive |
| 10 | //! byte-faithful (`Host`, `Content-Length`, `Upgrade`) are data here, not |
| 11 | //! metadata. Per-call control (scope, cell name, request id, capacity |
| 12 | //! handoff) rides `x-cells-*` headers on the inner request; node A overwrites |
| 13 | //! and node B strips them, so the reserved names cannot be smuggled by an |
| 14 | //! application in either direction. |
| 15 | //! |
| 16 | //! Idle tunnels are pooled per peer and reused for sequential calls — plain |
| 17 | //! h1 keep-alive inside the tunnel, never multiplexing. Without reuse every |
| 18 | //! call is a fresh TCP connection, and a loopback-speed caller saturates the |
| 19 | //! whole ephemeral-port range into TIME_WAIT within seconds (~1k calls/s is |
| 20 | //! the hard OS ceiling), which the pooled transport this replaces never hit. |
| 21 | |
| 22 | use std::collections::HashMap; |
| 23 | use std::convert::Infallible; |
| 24 | |
| 25 | use bytes::Bytes; |
| 26 | use futures_util::StreamExt; |
| 27 | use futures_util::TryStreamExt; |
| 28 | use http_body_util::BodyExt; |
| 29 | use hyper::body::Body; |
| 30 | use hyper::body::Incoming; |
| 31 | use hyper::service::service_fn; |
| 32 | use hyper::Request; |
| 33 | use hyper::Response; |
| 34 | use hyper::StatusCode; |
| 35 | use hyper_util::rt::TokioIo; |
| 36 | |
| 37 | use super::*; |
| 38 | use celld::js::HttpChunkStream; |
| 39 | |
| 40 | pub(crate) const TUNNEL_PROTOCOL: &str = "celld-tunnel"; |
| 41 | pub(crate) const TUNNEL_VERSION: &str = "5"; |
| 42 | pub(crate) const VERSION_HEADER: &str = "x-cells-tunnel-version"; |
| 43 | pub(crate) const KIND_HEADER: &str = "x-cells-tunnel-kind"; |
| 44 | pub(crate) const SCOPE_HEADER: &str = "x-cells-scope"; |
| 45 | pub(crate) const NAME_HEADER: &str = "x-cells-do-name"; |
| 46 | pub(crate) const REQUEST_ID_HEADER: &str = "x-cells-request-id"; |
| 47 | pub(crate) const HANDOFF_HEADER: &str = "x-cells-capacity-handoff"; |
| 48 | |
| 49 | /// The inner headers node A owns. A overwrites them on the way in and B |
| 50 | /// strips them on the way out, so an application header with a reserved name |
| 51 | /// is dropped rather than obeyed. |
| 52 | const CONTROL_HEADERS: [&str; 4] = [SCOPE_HEADER, NAME_HEADER, REQUEST_ID_HEADER, HANDOFF_HEADER]; |
| 53 | |
| 54 | enum TunnelKind { |
| 55 | Do, |
| 56 | Rpc, |
| 57 | } |
| 58 | |
| 59 | /// The control fields of one tunneled call, carried as inner-request headers |
| 60 | /// so one tunnel can serve calls for any cell. |
| 61 | pub(crate) struct TunnelControl { |
| 62 | pub(crate) scope: String, |
| 63 | pub(crate) name: Option<String>, |
| 64 | pub(crate) request_id: Option<celld::js::RequestId>, |
| 65 | pub(crate) capacity_handoff: bool, |
| 66 | } |
| 67 | |
| 68 | pub(crate) fn is_tunnel_request(request: &Request<Incoming>) -> bool { |
| 69 | request |
| 70 | .headers() |
| 71 | .get(hyper::header::UPGRADE) |
| 72 | .is_some_and(|value| value.as_bytes() == TUNNEL_PROTOCOL.as_bytes()) |
| 73 | } |
| 74 | |
| 75 | /// Node B: answer a tunnel establishment on `/peer/tunnel` with a 101 and serve the |
| 76 | /// inner connection until the peer closes it. |
| 77 | /// |
| 78 | /// The establishment carries the fleet HMAC and nothing after it does. The |
| 79 | /// signature gates who can open a tunnel — the inner calls it then carries |
| 80 | /// are cell dispatches, and a reserved-class dispatch must demand the fleet |
| 81 | /// secret on every path the way `/runtime/` does. The signature does not |
| 82 | /// authenticate the bytes after the 101 and does not encrypt anything; the |
| 83 | /// private network remains the boundary for both. |
| 84 | pub(crate) fn accept(mut request: Request<Incoming>, app: AppHandle) -> HttpReply { |
| 85 | let path_and_query = request |
| 86 | .uri() |
| 87 | .path_and_query() |
| 88 | .map_or_else(|| request.uri().path().to_string(), ToString::to_string); |
| 89 | if let Err(error) = app.peer_auth.verify( |
| 90 | request.method(), |
| 91 | &path_and_query, |
| 92 | request.headers(), |
| 93 | b"", |
| 94 | app.peer_auth.source(), |
| 95 | ) { |
| 96 | let mut denied = response(error.status(), error.message()); |
| 97 | // A wrong target means the dialer holds a stale lease for this |
| 98 | // address; the stale marker lets its redispatch invalidate the |
| 99 | // route instead of retrying the same dead name. |
| 100 | if matches!(error, peer_auth::VerifyError::WrongTarget) { |
| 101 | denied.headers_mut().insert( |
| 102 | hyper::header::HeaderName::from_static(STALE_ROUTE_HEADER), |
| 103 | hyper::header::HeaderValue::from_static(STALE_ROUTE_VALUE), |
| 104 | ); |
| 105 | } |
| 106 | return peer_response(denied); |
| 107 | } |
| 108 | let headers = request.headers(); |
| 109 | if headers |
| 110 | .get(VERSION_HEADER) |
| 111 | .is_none_or(|value| value.as_bytes() != TUNNEL_VERSION.as_bytes()) |
| 112 | { |
| 113 | return peer_response(response( |
| 114 | StatusCode::UPGRADE_REQUIRED, |
| 115 | "peer tunnel version is incompatible", |
| 116 | )); |
| 117 | } |
| 118 | let kind = match headers |
| 119 | .get(KIND_HEADER) |
| 120 | .map(hyper::header::HeaderValue::as_bytes) |
| 121 | { |
| 122 | Some(b"do") => TunnelKind::Do, |
| 123 | Some(b"rpc") => TunnelKind::Rpc, |
| 124 | _ => { |
| 125 | return peer_response(response(StatusCode::BAD_REQUEST, "unknown tunnel kind")); |
| 126 | } |
| 127 | }; |
| 128 | let upgrade = hyper::upgrade::on(&mut request); |
| 129 | tokio::spawn(async move { |
| 130 | let upgraded = match upgrade.await { |
| 131 | Ok(upgraded) => upgraded, |
| 132 | Err(_) => return, |
| 133 | }; |
| 134 | match kind { |
| 135 | TunnelKind::Do => serve_do(upgraded, app).await, |
| 136 | TunnelKind::Rpc => serve_rpc(upgraded, app).await, |
| 137 | } |
| 138 | }); |
| 139 | let mut reply = response(StatusCode::SWITCHING_PROTOCOLS, ""); |
| 140 | reply.headers_mut().insert( |
| 141 | hyper::header::UPGRADE, |
| 142 | hyper::header::HeaderValue::from_static(TUNNEL_PROTOCOL), |
| 143 | ); |
| 144 | reply.headers_mut().insert( |
| 145 | hyper::header::CONNECTION, |
| 146 | hyper::header::HeaderValue::from_static("upgrade"), |
| 147 | ); |
| 148 | reply.headers_mut().insert( |
| 149 | hyper::header::HeaderName::from_static(VERSION_HEADER), |
| 150 | hyper::header::HeaderValue::from_static(TUNNEL_VERSION), |
| 151 | ); |
| 152 | peer_response(reply) |
| 153 | } |
| 154 | |
| 155 | /// One inner request, one call: parse the app request hyper already framed, |
| 156 | /// dispatch it exactly as the enveloped path did, and let the reply stream |
| 157 | /// back as an ordinary HTTP response. The connection serves calls until the |
| 158 | /// peer closes it or an inner upgrade consumes it. |
| 159 | async fn serve_do(upgraded: hyper::upgrade::Upgraded, app: AppHandle) { |
| 160 | let service = service_fn(move |mut inner: Request<Incoming>| { |
| 161 | let app = app.clone(); |
| 162 | async move { |
| 163 | let Some(scope) = inner |
| 164 | .headers() |
| 165 | .get(SCOPE_HEADER) |
| 166 | .and_then(|value| value.to_str().ok()) |
| 167 | .map(str::to_string) |
| 168 | .filter(|scope| celld_logic::cell::valid_cell_scope(scope)) |
| 169 | else { |
| 170 | return Ok::<_, Infallible>(peer_response(malformed_scope())); |
| 171 | }; |
| 172 | let control = TunnelControl { |
| 173 | scope, |
| 174 | name: inner |
| 175 | .headers() |
| 176 | .get(NAME_HEADER) |
| 177 | .and_then(|value| value.to_str().ok()) |
| 178 | .map(str::to_string), |
| 179 | request_id: inner |
| 180 | .headers() |
| 181 | .get(REQUEST_ID_HEADER) |
| 182 | .and_then(|value| value.to_str().ok()) |
| 183 | .and_then(celld::js::parse_request_id), |
| 184 | capacity_handoff: inner.headers().get(HANDOFF_HEADER).is_some(), |
| 185 | }; |
| 186 | // A tunneled upgrade is the client's own handshake, so the |
| 187 | // owner answers it directly: fastwebsockets computes the 101 |
| 188 | // for the client's key, and the inner connection becomes the |
| 189 | // socket the cell speaks — the same machinery a locally |
| 190 | // connected client gets. |
| 191 | let client_upgrade = if fastwebsockets::upgrade::is_upgrade_request(&inner) { |
| 192 | match fastwebsockets::upgrade::upgrade(&mut inner) { |
| 193 | Ok(pair) => Some(pair), |
| 194 | Err(error) => { |
| 195 | return Ok(peer_response(response( |
| 196 | StatusCode::BAD_REQUEST, |
| 197 | format!("tunneled upgrade: {error}"), |
| 198 | ))); |
| 199 | } |
| 200 | } |
| 201 | } else { |
| 202 | None |
| 203 | }; |
| 204 | let (parts, body) = inner.into_parts(); |
| 205 | let headers = parts |
| 206 | .headers |
| 207 | .iter() |
| 208 | .filter(|(name, _)| !CONTROL_HEADERS.contains(&name.as_str())) |
| 209 | .filter_map(|(name, value)| { |
| 210 | value |
| 211 | .to_str() |
| 212 | .ok() |
| 213 | .map(|value| (name.as_str().to_string(), value.to_string())) |
| 214 | }) |
| 215 | .collect(); |
| 216 | // Streaming by construction: the inner body is handed to the |
| 217 | // isolate as a stream whatever its size, bounded the way the |
| 218 | // enveloped path bounded its frame. |
| 219 | let limited = http_body_util::Limited::new(body, MAX_PEER_FORWARD_BODY_BYTES); |
| 220 | let chunks: HttpChunkStream = Box::pin( |
| 221 | http_body_util::BodyStream::new(limited) |
| 222 | .try_filter_map(|frame| async move { Ok(frame.into_data().ok()) }) |
| 223 | .map_ok(|data: Bytes| data.to_vec()) |
| 224 | .map_err(|error| error.to_string()), |
| 225 | ); |
| 226 | let body = celld::js::RequestBody::Stream(celld::js::register_body_stream(chunks)); |
| 227 | let fetch = ForwardedFetch { |
| 228 | name: control.name, |
| 229 | url: parts.uri.to_string(), |
| 230 | method: parts.method.to_string(), |
| 231 | headers, |
| 232 | request_id: control.request_id, |
| 233 | capacity_handoff: control.capacity_handoff, |
| 234 | }; |
| 235 | let outcome = dispatch_forwarded_fetch(app.clone(), control.scope, fetch, body).await; |
| 236 | let (target, worker_headers) = match outcome { |
| 237 | ForwardedFetchOutcome::Reply(reply) => return Ok(reply), |
| 238 | ForwardedFetchOutcome::WebSocket { target, headers } => (target, headers), |
| 239 | }; |
| 240 | let Some((accept, upgrade)) = client_upgrade else { |
| 241 | return Ok(peer_response(response( |
| 242 | StatusCode::BAD_GATEWAY, |
| 243 | "the cell accepted a WebSocket for a request that did not upgrade", |
| 244 | ))); |
| 245 | }; |
| 246 | // The cell accepted: hand the inner stream to the same socket |
| 247 | // task a local client gets, and answer with the real 101. The |
| 248 | // Worker's application headers ride along; the sidecars and |
| 249 | // the hop framing die here. |
| 250 | tokio::spawn(async move { |
| 251 | match upgrade.await { |
| 252 | Ok(socket) => super::websocket::websocket_task(app, target, socket).await, |
| 253 | Err(error) => { |
| 254 | eprintln!("celld tunneled upgrade failed: {error}"); |
| 255 | } |
| 256 | } |
| 257 | }); |
| 258 | let (accept_parts, _) = accept.into_parts(); |
| 259 | let mut answer = Response::from_parts( |
| 260 | accept_parts, |
| 261 | BodyExt::boxed_unsync(http_body_util::Empty::new().map_err(|never| match never {})), |
| 262 | ); |
| 263 | for (name, value) in &worker_headers { |
| 264 | let lowered = name.to_ascii_lowercase(); |
| 265 | if lowered == "content-length" |
| 266 | || lowered == "upgrade" |
| 267 | || lowered == "connection" |
| 268 | || lowered == "sec-websocket-accept" |
| 269 | { |
| 270 | continue; |
| 271 | } |
| 272 | let Ok(name) = hyper::header::HeaderName::from_bytes(name.as_bytes()) else { |
| 273 | continue; |
| 274 | }; |
| 275 | let Ok(value) = hyper::header::HeaderValue::from_str(value) else { |
| 276 | continue; |
| 277 | }; |
| 278 | answer.headers_mut().append(name, value); |
| 279 | } |
| 280 | Ok(peer_response(answer)) |
| 281 | } |
| 282 | }); |
| 283 | let _ = hyper::server::conn::http1::Builder::new() |
| 284 | .serve_connection(upgraded, service) |
| 285 | .with_upgrades() |
| 286 | .await; |
| 287 | } |
| 288 | |
| 289 | type TunnelSender = hyper::client::conn::http1::SendRequest<TunnelBody>; |
| 290 | |
| 291 | /// Who node A dials and how it proves itself. One borrow carries the |
| 292 | /// client, the fleet key, and the routed peer's address and name through |
| 293 | /// an attempt. |
| 294 | pub(crate) struct Peer<'a> { |
| 295 | pub(crate) http: &'a reqwest::Client, |
| 296 | pub(crate) auth: &'a PeerAuth, |
| 297 | pub(crate) addr: &'a str, |
| 298 | pub(crate) node: &'a str, |
| 299 | } |
| 300 | |
| 301 | /// Idle tunnels per (peer, kind). A sender goes back only after its response |
| 302 | /// body reaches a clean end, so active replies do not consume the idle bound. |
| 303 | /// A dropped or poisoned connection reports `is_closed` and is purged on scan. |
| 304 | static TUNNELS: std::sync::OnceLock<std::sync::Mutex<HashMap<String, Vec<TunnelSender>>>> = |
| 305 | std::sync::OnceLock::new(); |
| 306 | /// Completed idle tunnels count against this bound. Active calls own their |
| 307 | /// senders outside the pool, so concurrency cannot evict a reusable tunnel. |
| 308 | const TUNNEL_POOL_CAP: usize = 64; |
| 309 | |
| 310 | fn checkout(key: &str) -> Option<TunnelSender> { |
| 311 | let mut pool = TUNNELS.get_or_init(Default::default).lock().unwrap(); |
| 312 | let senders = pool.get_mut(key)?; |
| 313 | senders.retain(|sender| !sender.is_closed()); |
| 314 | let index = senders.iter().position(TunnelSender::is_ready)?; |
| 315 | Some(senders.swap_remove(index)) |
| 316 | } |
| 317 | |
| 318 | fn park(key: &str, sender: TunnelSender) { |
| 319 | let mut pool = TUNNELS.get_or_init(Default::default).lock().unwrap(); |
| 320 | let senders = pool.entry(key.to_string()).or_default(); |
| 321 | if senders.len() < TUNNEL_POOL_CAP { |
| 322 | senders.push(sender); |
| 323 | } |
| 324 | } |
| 325 | |
| 326 | /// Establish a fresh tunnel to `addr` and hand back its inner h1 client. |
| 327 | /// The establishment is a bodiless GET, so the fleet HMAC signs it whole — |
| 328 | /// the one signature every call on this tunnel then rides. |
| 329 | async fn establish(peer: &Peer<'_>, kind: &'static str) -> anyhow::Result<TunnelSender> { |
| 330 | let request = peer |
| 331 | .http |
| 332 | .get(format!("http://{}/peer/tunnel", peer.addr)) |
| 333 | .header(reqwest::header::UPGRADE, TUNNEL_PROTOCOL) |
| 334 | .header(reqwest::header::CONNECTION, "upgrade") |
| 335 | .header(VERSION_HEADER, TUNNEL_VERSION) |
| 336 | .header(KIND_HEADER, kind) |
| 337 | .header( |
| 338 | peer_auth::RESPONSE_VERSION_HEADER, |
| 339 | peer_auth::PROTOCOL_VERSION_TEXT, |
| 340 | ); |
| 341 | let response = peer |
| 342 | .auth |
| 343 | .sign(request, "GET", "/peer/tunnel", b"", peer.node)? |
| 344 | .send() |
| 345 | .await?; |
| 346 | peer_auth::validate_response(response.headers())?; |
| 347 | anyhow::ensure!( |
| 348 | response.status() == reqwest::StatusCode::SWITCHING_PROTOCOLS, |
| 349 | "tunnel establishment answered {}", |
| 350 | response.status() |
| 351 | ); |
| 352 | let upgraded = response.upgrade().await?; |
| 353 | let (sender, connection) = hyper::client::conn::http1::Builder::new() |
| 354 | .handshake(TokioIo::new(upgraded)) |
| 355 | .await?; |
| 356 | tokio::spawn(async move { |
| 357 | let _ = connection.with_upgrades().await; |
| 358 | }); |
| 359 | Ok(sender) |
| 360 | } |
| 361 | |
| 362 | fn inner_request( |
| 363 | control: &TunnelControl, |
| 364 | url: &str, |
| 365 | method: &str, |
| 366 | headers: &[(String, String)], |
| 367 | body: TunnelBody, |
| 368 | ) -> anyhow::Result<Request<TunnelBody>> { |
| 369 | let mut inner = Request::builder().method(method).uri(url); |
| 370 | for (name, value) in headers { |
| 371 | if CONTROL_HEADERS |
| 372 | .iter() |
| 373 | .any(|reserved| reserved.eq_ignore_ascii_case(name)) |
| 374 | { |
| 375 | continue; |
| 376 | } |
| 377 | inner = inner.header(name.as_str(), value.as_str()); |
| 378 | } |
| 379 | inner = inner.header(SCOPE_HEADER, control.scope.as_str()); |
| 380 | if let Some(name) = &control.name { |
| 381 | inner = inner.header(NAME_HEADER, name); |
| 382 | } |
| 383 | if let Some(request_id) = control.request_id { |
| 384 | inner = inner.header(REQUEST_ID_HEADER, celld::js::request_id_string(request_id)); |
| 385 | } |
| 386 | if control.capacity_handoff { |
| 387 | inner = inner.header(HANDOFF_HEADER, "1"); |
| 388 | } |
| 389 | Ok(inner.body(body)?) |
| 390 | } |
| 391 | |
| 392 | /// Send one inner request, preferring a pooled tunnel. A pooled connection |
| 393 | /// can die between checkout and use, so a replayable body retries once on a |
| 394 | /// fresh tunnel — the same stale keep-alive race every h1 pool has. A |
| 395 | /// streamed body is not replayable; its pooled failure surfaces as the |
| 396 | /// attempt failure the caller already handles. |
| 397 | async fn send_inner( |
| 398 | peer: &Peer<'_>, |
| 399 | kind: &'static str, |
| 400 | build: impl Fn(TunnelBody) -> anyhow::Result<Request<TunnelBody>>, |
| 401 | body: celld::js::RequestBody, |
| 402 | ) -> anyhow::Result<Response<PooledResponseBody>> { |
| 403 | let key = format!("{}#{kind}", peer.addr); |
| 404 | let replay = match &body { |
| 405 | celld::js::RequestBody::Bytes(bytes) => Some(bytes.clone()), |
| 406 | celld::js::RequestBody::Stream(_) => None, |
| 407 | }; |
| 408 | let body = match body { |
| 409 | celld::js::RequestBody::Bytes(bytes) => full_body(bytes), |
| 410 | celld::js::RequestBody::Stream(stream_id) => { |
| 411 | let payload = celld::js::take_body_stream(stream_id) |
| 412 | .map_err(|error| anyhow::anyhow!("take tunnel body: {error}"))?; |
| 413 | stream_body(payload) |
| 414 | } |
| 415 | }; |
| 416 | let mut body = Some(body); |
| 417 | if let Some(sender) = checkout(&key) { |
| 418 | match send_on_tunnel(&key, sender, build(body.take().unwrap())?).await { |
| 419 | Ok(response) => { |
| 420 | return Ok(response); |
| 421 | } |
| 422 | Err(error) => { |
| 423 | let Some(bytes) = replay else { |
| 424 | return Err(error); |
| 425 | }; |
| 426 | body = Some(full_body(bytes)); |
| 427 | } |
| 428 | } |
| 429 | } |
| 430 | let sender = establish(peer, kind).await?; |
| 431 | send_on_tunnel(&key, sender, build(body.take().unwrap())?).await |
| 432 | } |
| 433 | |
| 434 | async fn send_on_tunnel( |
| 435 | key: &str, |
| 436 | mut sender: TunnelSender, |
| 437 | request: Request<TunnelBody>, |
| 438 | ) -> anyhow::Result<Response<PooledResponseBody>> { |
| 439 | let response = sender.send_request(request).await?; |
| 440 | let reusable = |
| 441 | (response.status() != StatusCode::SWITCHING_PROTOCOLS).then(|| (key.to_string(), sender)); |
| 442 | Ok(response.map(|body| PooledResponseBody { body, reusable })) |
| 443 | } |
| 444 | |
| 445 | /// An inner response owns its tunnel until the body finishes successfully. |
| 446 | /// Returning the sender at the response head makes active replies consume the |
| 447 | /// idle-pool bound. Sustained RPC concurrency then creates and discards one |
| 448 | /// upgraded TCP connection for every overflow call. |
| 449 | pub(crate) struct PooledResponseBody { |
| 450 | body: Incoming, |
| 451 | reusable: Option<(String, TunnelSender)>, |
| 452 | } |
| 453 | |
| 454 | impl Body for PooledResponseBody { |
| 455 | type Data = Bytes; |
| 456 | type Error = hyper::Error; |
| 457 | |
| 458 | fn poll_frame( |
| 459 | mut self: std::pin::Pin<&mut Self>, |
| 460 | cx: &mut std::task::Context<'_>, |
| 461 | ) -> std::task::Poll<Option<Result<hyper::body::Frame<Self::Data>, Self::Error>>> { |
| 462 | match std::pin::Pin::new(&mut self.body).poll_frame(cx) { |
| 463 | std::task::Poll::Ready(None) => { |
| 464 | if let Some((key, sender)) = self.reusable.take() { |
| 465 | park(&key, sender); |
| 466 | } |
| 467 | std::task::Poll::Ready(None) |
| 468 | } |
| 469 | std::task::Poll::Ready(Some(Err(error))) => { |
| 470 | // The unread or failed stream cannot carry another request. |
| 471 | self.reusable.take(); |
| 472 | std::task::Poll::Ready(Some(Err(error))) |
| 473 | } |
| 474 | other => other, |
| 475 | } |
| 476 | } |
| 477 | |
| 478 | fn is_end_stream(&self) -> bool { |
| 479 | // Force one final poll while the sender is still attached. A zero-byte |
| 480 | // response can otherwise skip `poll_frame` and close a reusable tunnel. |
| 481 | self.reusable.is_none() && self.body.is_end_stream() |
| 482 | } |
| 483 | |
| 484 | fn size_hint(&self) -> hyper::body::SizeHint { |
| 485 | self.body.size_hint() |
| 486 | } |
| 487 | } |
| 488 | |
| 489 | pub(crate) async fn fetch( |
| 490 | peer: &Peer<'_>, |
| 491 | control: &TunnelControl, |
| 492 | url: String, |
| 493 | method: String, |
| 494 | headers: Vec<(String, String)>, |
| 495 | body: celld::js::RequestBody, |
| 496 | ) -> anyhow::Result<Response<PooledResponseBody>> { |
| 497 | send_inner( |
| 498 | peer, |
| 499 | "do", |
| 500 | |body| inner_request(control, &url, &method, &headers, body), |
| 501 | body, |
| 502 | ) |
| 503 | .await |
| 504 | } |
| 505 | |
| 506 | pub(crate) const METHOD_HEADER: &str = "x-cells-rpc-method"; |
| 507 | |
| 508 | /// One inner request, one RPC: the method name rides a header, the |
| 509 | /// arguments ride the body, and the content type says which encoding the |
| 510 | /// caller used. |
| 511 | async fn serve_rpc(upgraded: hyper::upgrade::Upgraded, app: AppHandle) { |
| 512 | let service = service_fn(move |inner: Request<Incoming>| { |
| 513 | let app = app.clone(); |
| 514 | async move { |
| 515 | let Some(scope) = inner |
| 516 | .headers() |
| 517 | .get(SCOPE_HEADER) |
| 518 | .and_then(|value| value.to_str().ok()) |
| 519 | .map(str::to_string) |
| 520 | .filter(|scope| celld_logic::cell::valid_cell_scope(scope)) |
| 521 | else { |
| 522 | return Ok::<_, Infallible>(peer_response(malformed_scope())); |
| 523 | }; |
| 524 | let name = inner |
| 525 | .headers() |
| 526 | .get(NAME_HEADER) |
| 527 | .and_then(|value| value.to_str().ok()) |
| 528 | .map(str::to_string); |
| 529 | let structured = inner |
| 530 | .headers() |
| 531 | .get(hyper::header::CONTENT_TYPE) |
| 532 | .is_some_and(|value| value.as_bytes() == b"application/octet-stream"); |
| 533 | let Some(method) = inner |
| 534 | .headers() |
| 535 | .get(METHOD_HEADER) |
| 536 | .and_then(|value| value.to_str().ok()) |
| 537 | .map(str::to_string) |
| 538 | else { |
| 539 | return Ok::<_, Infallible>(peer_response(response( |
| 540 | StatusCode::BAD_REQUEST, |
| 541 | "RPC method header is missing", |
| 542 | ))); |
| 543 | }; |
| 544 | let body = |
| 545 | match collect_limited_body(inner.into_body(), MAX_PEER_FORWARD_BODY_BYTES).await { |
| 546 | Ok(body) => body, |
| 547 | Err(error) => { |
| 548 | return Ok(peer_response(body_read_error("tunnel RPC", error))); |
| 549 | } |
| 550 | }; |
| 551 | let args = if structured { |
| 552 | celld::js::RpcData::V8(body) |
| 553 | } else { |
| 554 | match String::from_utf8(body.to_vec()) { |
| 555 | Ok(json) => celld::js::RpcData::Json(json), |
| 556 | Err(_) => { |
| 557 | return Ok(peer_response(response( |
| 558 | StatusCode::BAD_REQUEST, |
| 559 | "JSON RPC arguments are not UTF-8", |
| 560 | ))); |
| 561 | } |
| 562 | } |
| 563 | }; |
| 564 | let reply = dispatch_forwarded_rpc(app, scope, name, method, args).await; |
| 565 | Ok(reply) |
| 566 | } |
| 567 | }); |
| 568 | let _ = hyper::server::conn::http1::Builder::new() |
| 569 | .serve_connection(upgraded, service) |
| 570 | .await; |
| 571 | } |
| 572 | |
| 573 | /// Node A: one RPC through the pooled rpc tunnel. |
| 574 | pub(crate) async fn rpc( |
| 575 | peer: &Peer<'_>, |
| 576 | scope: &str, |
| 577 | name: Option<&str>, |
| 578 | method: &str, |
| 579 | args: &celld::js::RpcData, |
| 580 | ) -> anyhow::Result<Response<PooledResponseBody>> { |
| 581 | let (content_type, payload) = match args { |
| 582 | celld::js::RpcData::Json(json) => ("application/json", Bytes::from(json.clone())), |
| 583 | celld::js::RpcData::V8(bytes) => ("application/octet-stream", bytes.clone()), |
| 584 | }; |
| 585 | send_inner( |
| 586 | peer, |
| 587 | "rpc", |
| 588 | |body| { |
| 589 | let mut inner = Request::builder() |
| 590 | .method("POST") |
| 591 | .uri("/") |
| 592 | .header(SCOPE_HEADER, scope) |
| 593 | .header(METHOD_HEADER, method) |
| 594 | .header(hyper::header::CONTENT_TYPE, content_type); |
| 595 | if let Some(name) = name { |
| 596 | inner = inner.header(NAME_HEADER, name); |
| 597 | } |
| 598 | Ok(inner.body(body)?) |
| 599 | }, |
| 600 | celld::js::RequestBody::Bytes(payload), |
| 601 | ) |
| 602 | .await |
| 603 | } |
| 604 | |
| 605 | /// The owner half of a tunneled WebSocket 101, parked until the caller's own |
| 606 | /// client socket finishes upgrading. |
| 607 | static TUNNEL_UPGRADES: std::sync::OnceLock< |
| 608 | std::sync::Mutex<HashMap<u64, hyper::upgrade::OnUpgrade>>, |
| 609 | > = std::sync::OnceLock::new(); |
| 610 | static NEXT_TUNNEL_UPGRADE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); |
| 611 | |
| 612 | pub(crate) fn park_upgrade(upgrade: hyper::upgrade::OnUpgrade) -> u64 { |
| 613 | let id = NEXT_TUNNEL_UPGRADE.fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 614 | TUNNEL_UPGRADES |
| 615 | .get_or_init(Default::default) |
| 616 | .lock() |
| 617 | .unwrap() |
| 618 | .insert(id, upgrade); |
| 619 | id |
| 620 | } |
| 621 | |
| 622 | /// Splice the upgraded client socket to the tunneled owner: the hop stops |
| 623 | /// interpreting WebSocket frames and copies bytes until either side closes. |
| 624 | pub(crate) async fn splice<S>(client: S, parked: u64) -> anyhow::Result<()> |
| 625 | where |
| 626 | S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin, |
| 627 | { |
| 628 | let upgrade = TUNNEL_UPGRADES |
| 629 | .get_or_init(Default::default) |
| 630 | .lock() |
| 631 | .unwrap() |
| 632 | .remove(&parked) |
| 633 | .ok_or_else(|| anyhow::anyhow!("tunneled upgrade {parked} is gone"))?; |
| 634 | let inner = upgrade.await?; |
| 635 | let inner = TokioIo::new(inner); |
| 636 | let (mut client_read, mut client_write) = tokio::io::split(client); |
| 637 | let (mut inner_read, mut inner_write) = tokio::io::split(inner); |
| 638 | celld::asyncrt::select! { |
| 639 | _ = tokio::io::copy(&mut client_read, &mut inner_write) => { |
| 640 | // The client went away; the owner sees EOF through the tunnel |
| 641 | // and runs its own close dispatch. |
| 642 | } |
| 643 | _ = tokio::io::copy(&mut inner_read, &mut client_write) => { |
| 644 | // The owner side ended. A clean close frame already crossed as |
| 645 | // bytes; an abnormal end left the client mid-conversation, so |
| 646 | // tell it the service restarted — the same 1012 the enveloped |
| 647 | // tunnel sent. After a clean close the client has already shut |
| 648 | // its state machine and ignores this frame. |
| 649 | let client = client_read.unsplit(client_write); |
| 650 | let mut ws = fastwebsockets::WebSocket::after_handshake( |
| 651 | client, |
| 652 | fastwebsockets::Role::Server, |
| 653 | ); |
| 654 | let _ = ws |
| 655 | .write_frame(fastwebsockets::Frame::close(1012, b"owner unavailable")) |
| 656 | .await; |
| 657 | } |
| 658 | } |
| 659 | Ok(()) |
| 660 | } |
| 661 | |
| 662 | type TunnelBody = http_body_util::combinators::UnsyncBoxBody<Bytes, std::io::Error>; |
| 663 | |
| 664 | fn full_body(bytes: Bytes) -> TunnelBody { |
| 665 | BodyExt::boxed_unsync(http_body_util::Full::new(bytes).map_err(|never| match never {})) |
| 666 | } |
| 667 | |
| 668 | fn stream_body(payload: HttpChunkStream) -> TunnelBody { |
| 669 | let frames = payload.map(|chunk| { |
| 670 | chunk |
| 671 | .map(|data| hyper::body::Frame::data(Bytes::from(data))) |
| 672 | .map_err(std::io::Error::other) |
| 673 | }); |
| 674 | BodyExt::boxed_unsync(http_body_util::StreamBody::new(frames)) |
| 675 | } |
| 676 | |
| 677 | /// The inner response body as the chunk stream the reply path already |
| 678 | /// speaks. |
| 679 | pub(crate) fn response_stream(body: PooledResponseBody) -> HttpChunkStream { |
| 680 | Box::pin( |
| 681 | http_body_util::BodyStream::new(body) |
| 682 | .try_filter_map(|frame| async move { Ok(frame.into_data().ok()) }) |
| 683 | .map_ok(|data: Bytes| data.to_vec()) |
| 684 | .map_err(|error| error.to_string()), |
| 685 | ) |
| 686 | } |
| 687 | |
| 688 | #[cfg(all(test, celld_internal_tests))] |
| 689 | mod private_tests { |
| 690 | include!(env!("CELLD_CONFORMANCE_PEER_TUNNEL_TESTS")); |
| 691 | } |