1use crate::messages::{
4 endpoint_hex, scope_allows, service, stamp, OpenMode, OpenOk, OpenRequest, PairOk, PairRequest,
5 RenewOk, RenewRequest, ServiceCall, StampIdentity,
6};
7use crate::registry::{SessionClose, SessionRegistry};
8use crate::traits::{BoxRecv, BoxSend, HostBus, SessionStreams, WebRtcSignaling};
9use crate::tunnel::{self, Gate};
10use crate::types::{
11 IngressSocket, PairingAdmission, Refusal, Session, SessionEnd, SessionPath, WireSocket,
12};
13use crate::wire::{
14 decode_request, encode_response, peek_method, DEVICE_CALL_METHOD, HTTP_REQUEST_METHOD,
15 MAX_FRAME_BYTES, RESPONSE_STATUS_ERR, RESPONSE_STATUS_OK, SESSION_OPEN_METHOD,
16 SESSION_PAIR_METHOD, SESSION_RENEW_METHOD, WEBRTC_SIGNAL_METHOD, WIRE_METHOD, WS_STREAM_METHOD,
17};
18use crate::wire_stream;
19use std::sync::Arc;
20use std::time::Duration;
21use tokio::io::{AsyncReadExt, AsyncWriteExt};
22use tokio::task::JoinSet;
23
24const OPEN_DEADLINE: Duration = Duration::from_secs(10);
25const CALL_DEADLINE: Duration = Duration::from_secs(30);
26const CALL_READ_DEADLINE: Duration = Duration::from_secs(30);
27const CLOSE_GRACE: Duration = Duration::from_secs(2);
28const MAX_SESSION_STREAMS: usize = 16;
29const RENEWAL_LIFETIME: Duration = Duration::from_secs(120);
30const PAIRING_LIFETIME: Duration = Duration::from_secs(120);
31const PROTOCOL_CLOSE_CODE: u32 = 1;
32
33fn err_frame(code: &str, message: &str) -> Vec<u8> {
34 encode_response(RESPONSE_STATUS_ERR, format!("{code}: {message}").as_bytes())
35}
36
37fn session_from_verify(session: Session) -> OpenOk {
38 OpenOk {
39 mode: OpenMode::Full,
40 device_id: session.device_id,
41 device_did: session.device_did,
42 scopes: session.scopes,
43 expires_at: session.expires_at,
44 }
45}
46
47fn session_from_admit(session: Session) -> OpenOk {
48 OpenOk {
49 mode: OpenMode::Renewal,
50 device_id: session.device_id,
51 device_did: session.device_did,
52 scopes: vec![],
53 expires_at: if session.expires_at.is_empty() {
54 renewal_expires_at()
55 } else {
56 session.expires_at
57 },
58 }
59}
60
61fn map_verify_refusal(refusal: Refusal) -> Vec<u8> {
62 match refusal.code.as_str() {
63 "invalid_request"
64 | "endpoint_mismatch"
65 | "invalid_credential"
66 | "device_revoked"
67 | "expired"
68 | "verifier_unavailable" => err_frame(&refusal.code, &refusal.message),
69 _ => err_frame(
70 "verifier_unavailable",
71 "verification is temporarily unavailable",
72 ),
73 }
74}
75
76fn map_renew_refusal(refusal: Refusal) -> (&'static str, &'static str) {
77 match refusal.code.as_str() {
78 "device_revoked" => ("device_revoked", "the device is revoked"),
79 "device_not_registered" => ("device_not_registered", "the device is not registered"),
80 "pending_approval" => ("pending_approval", "the device awaits approval"),
81 "rejected" => ("rejected", "the device was rejected"),
82 "rate_limited" => ("rate_limited", "try renewal later"),
83 "invalid_request" => ("invalid_request", "invalid renewal request"),
84 "internal_error" => ("internal_error", "renewal failed"),
85 _ => ("renew_unavailable", "renewal is temporarily unavailable"),
86 }
87}
88
89fn map_admit_refusal(refusal: Refusal) -> Vec<u8> {
90 match refusal.code.as_str() {
91 "rate_limited" => err_frame("rate_limited", "renewal admission rate limited"),
92 "device_revoked" => err_frame("device_revoked", "the device is revoked"),
93 "unknown_endpoint" => err_frame("unknown_endpoint", "the endpoint is not registered"),
94 _ => err_frame(
95 "verifier_unavailable",
96 "verification is temporarily unavailable",
97 ),
98 }
99}
100
101struct Pairing {
103 member: String,
105 endpoint: String,
107 lifetime: Duration,
110}
111
112fn map_pairing_refusal(refusal: Refusal) -> Vec<u8> {
113 match refusal.code.as_str() {
114 "pairing_token_invalid" => {
115 err_frame("pairing_token_invalid", "the door token is not valid")
116 }
117 "pairing_token_expired" => err_frame("pairing_token_expired", "the door token has expired"),
118 "pairing_token_bound" => err_frame(
119 "pairing_token_bound",
120 "the door token belongs to another device",
121 ),
122 "pairing_rate_limited" => err_frame("pairing_rate_limited", "try pairing later"),
123 "not_open" => err_frame("not_open", "this node does not open pairing sessions"),
124 "invalid_request" => err_frame("invalid_request", "invalid pairing request"),
125 _ => err_frame(
126 "verifier_unavailable",
127 "verification is temporarily unavailable",
128 ),
129 }
130}
131
132fn member_node_id_ok(member: &str) -> bool {
134 !member.is_empty() && member.len() <= 256 && member.bytes().all(|b| b.is_ascii_alphanumeric())
135}
136
137async fn respond(send: &mut (impl AsyncWriteExt + Unpin), frame: Vec<u8>) {
138 let _ = send.write_all(&frame).await;
139 let _ = send.shutdown().await;
140}
141
142async fn respond_before_close(send: &mut (impl AsyncWriteExt + Unpin), frame: Vec<u8>) {
143 respond(send, frame).await;
144 tokio::time::sleep(CLOSE_GRACE).await;
145}
146
147#[non_exhaustive]
152#[derive(Clone, Default)]
153pub struct ServeOptions {
154 pub registry: Option<SessionRegistry>,
156 pub wire: WireSocket,
158}
159
160pub async fn serve<C, B>(
170 conn: C,
171 bus: B,
172 ingress: IngressSocket,
173 path: SessionPath,
174 webrtc: Option<Arc<dyn WebRtcSignaling>>,
175) -> Result<(), SessionEnd>
176where
177 C: SessionStreams + 'static,
178 B: HostBus + 'static,
179{
180 serve_with_options(conn, bus, ingress, path, webrtc, ServeOptions::default()).await
181}
182
183pub async fn serve_with_registry<C, B>(
192 conn: C,
193 bus: B,
194 ingress: IngressSocket,
195 path: SessionPath,
196 webrtc: Option<Arc<dyn WebRtcSignaling>>,
197 registry: SessionRegistry,
198) -> Result<(), SessionEnd>
199where
200 C: SessionStreams + 'static,
201 B: HostBus + 'static,
202{
203 serve_with_options(
204 conn,
205 bus,
206 ingress,
207 path,
208 webrtc,
209 ServeOptions {
210 registry: Some(registry),
211 ..ServeOptions::default()
212 },
213 )
214 .await
215}
216
217pub async fn serve_with_options<C, B>(
219 conn: C,
220 bus: B,
221 ingress: IngressSocket,
222 path: SessionPath,
223 webrtc: Option<Arc<dyn WebRtcSignaling>>,
224 options: ServeOptions,
225) -> Result<(), SessionEnd>
226where
227 C: SessionStreams + 'static,
228 B: HostBus + 'static,
229{
230 serve_inner(
231 conn,
232 bus,
233 ingress,
234 options.wire,
235 path,
236 webrtc,
237 options.registry,
238 )
239 .await
240}
241
242async fn serve_inner<C, B>(
243 conn: C,
244 bus: B,
245 ingress: IngressSocket,
246 wire: WireSocket,
247 path: SessionPath,
248 webrtc: Option<Arc<dyn WebRtcSignaling>>,
249 registry: Option<SessionRegistry>,
250) -> Result<(), SessionEnd>
251where
252 C: SessionStreams + 'static,
253 B: HostBus + 'static,
254{
255 let conn = Arc::new(conn);
256 let bus = Arc::new(bus);
257 let ingress = Arc::new(ingress);
258 let wire = Arc::new(wire);
259
260 let attempt = tokio::time::timeout(OPEN_DEADLINE, async {
261 let (mut send, mut recv) = conn.accept_bi().await?;
262 let mut bytes = Vec::new();
263 (&mut recv)
264 .take(MAX_FRAME_BYTES as u64 + 1)
265 .read_to_end(&mut bytes)
266 .await?;
267 if bytes.len() > MAX_FRAME_BYTES {
268 conn.close(PROTOCOL_CLOSE_CODE, b"frame too large or unreadable");
269 return Err(SessionEnd::NotOpened("frame too large".into()));
270 }
271 match decode_request(&bytes) {
272 Ok((method, payload)) if method == SESSION_OPEN_METHOD => {
273 open_first(conn.as_ref(), bus.as_ref(), send, payload)
274 .await
275 .map(|(send, ok, credential)| (send, ok, credential, None))
276 }
277 Ok((method, payload)) if method == SESSION_RENEW_METHOD => {
278 renew_first(conn.as_ref(), bus.as_ref(), send, payload)
280 .await
281 .map(|(send, ok)| (send, ok, None, None))
282 }
283 Ok((method, payload)) if method == SESSION_PAIR_METHOD => {
284 pair_first(conn.as_ref(), bus.as_ref(), send, payload)
286 .await
287 .map(|(send, ok, pairing)| (send, ok, None, Some(pairing)))
288 }
289 _ => {
290 respond_before_close(
291 &mut send,
292 err_frame("not_open", "the first stream must be session.open/1"),
293 )
294 .await;
295 conn.close(PROTOCOL_CLOSE_CODE, b"session not opened");
296 Err(SessionEnd::NotOpened("not_open".into()))
297 }
298 }
299 })
300 .await;
301
302 let (send, identity, credential, pairing) = match attempt {
303 Ok(Ok(v)) => v,
304 Ok(Err(e)) => return Err(e),
305 Err(_) => {
306 conn.close(PROTOCOL_CLOSE_CODE, b"session not opened in time");
307 return Err(SessionEnd::OpenTimeout);
308 }
309 };
310
311 let registered = match (registry.as_ref(), credential) {
312 (Some(registry), Some(credential)) => {
313 let conn_close = conn.clone();
314 let close: SessionClose = Arc::new(move |code, reason| {
315 conn_close.close(code, reason);
316 });
317 let device_id = identity.device_id.clone();
318 let endpoint = endpoint_hex(&conn.peer_key());
319 let session_id = registry.insert(device_id.clone(), credential, endpoint, close);
320 Some((device_id, session_id))
321 }
322 _ => None,
323 };
324
325 let result = serve_opened(
326 conn, bus, ingress, wire, path, webrtc, send, identity, pairing,
327 )
328 .await;
329
330 if let (Some(registry), Some((device_id, session_id))) = (registry, registered) {
331 registry.remove_if(&device_id, session_id);
332 }
333 result
334}
335
336async fn open_first(
337 conn: &impl SessionStreams,
338 bus: &impl HostBus,
339 mut send: BoxSend,
340 payload: &[u8],
341) -> Result<(BoxSend, OpenOk, Option<String>), SessionEnd> {
342 let request: OpenRequest = match serde_json::from_slice(payload) {
343 Ok(r) => r,
344 Err(_) => {
345 respond_before_close(
346 &mut send,
347 err_frame(
348 "invalid_request",
349 "session.open/1 needs {credential} or {mode: renewal}",
350 ),
351 )
352 .await;
353 conn.close(PROTOCOL_CLOSE_CODE, b"session not opened");
354 return Err(SessionEnd::NotOpened("invalid_request".into()));
355 }
356 };
357
358 let endpoint = endpoint_hex(&conn.peer_key());
359 let (ok, credential) = if request.mode == Some(OpenMode::Renewal) {
360 if request.credential.is_some() {
361 respond_before_close(
362 &mut send,
363 err_frame("invalid_request", "renewal mode takes no credential"),
364 )
365 .await;
366 conn.close(PROTOCOL_CLOSE_CODE, b"session not opened");
367 return Err(SessionEnd::NotOpened("invalid_request".into()));
368 }
369 let ok = match bus.admit_renewal(&endpoint).await {
370 Ok(session) => session_from_admit(session),
371 Err(refusal) => {
372 respond_before_close(&mut send, map_admit_refusal(refusal)).await;
373 conn.close(PROTOCOL_CLOSE_CODE, b"session not opened");
374 return Err(SessionEnd::NotOpened("admit refused".into()));
375 }
376 };
377 (ok, None)
378 } else {
379 let credential = match request.credential.filter(|c| !c.is_empty()) {
380 Some(c) => c,
381 None => {
382 respond_before_close(
383 &mut send,
384 err_frame("invalid_request", "full mode needs a credential"),
385 )
386 .await;
387 conn.close(PROTOCOL_CLOSE_CODE, b"session not opened");
388 return Err(SessionEnd::NotOpened("invalid_request".into()));
389 }
390 };
391 let ok = match bus.verify(&credential, &endpoint).await {
392 Ok(session) => session_from_verify(session),
393 Err(refusal) => {
394 respond_before_close(&mut send, map_verify_refusal(refusal)).await;
395 conn.close(PROTOCOL_CLOSE_CODE, b"session not opened");
396 return Err(SessionEnd::NotOpened("verify refused".into()));
397 }
398 };
399 (ok, Some(credential))
400 };
401
402 let body = serde_json::to_vec(&ok).map_err(|_| SessionEnd::NotOpened("encode".into()))?;
403 respond(&mut send, encode_response(RESPONSE_STATUS_OK, &body)).await;
404 Ok((send, ok, credential))
405}
406
407async fn renew_first(
408 conn: &impl SessionStreams,
409 bus: &impl HostBus,
410 mut send: BoxSend,
411 payload: &[u8],
412) -> Result<(BoxSend, OpenOk), SessionEnd> {
413 let endpoint = endpoint_hex(&conn.peer_key());
414 let value: serde_json::Value = match serde_json::from_slice::<serde_json::Value>(payload) {
415 Ok(v) if v.is_object() => v,
416 _ => {
417 respond_before_close(
418 &mut send,
419 err_frame("invalid_request", "session.renew/1 needs {}"),
420 )
421 .await;
422 conn.close(PROTOCOL_CLOSE_CODE, b"renewal complete");
423 return Err(SessionEnd::NotOpened("invalid_request".into()));
424 }
425 };
426 if serde_json::from_value::<RenewRequest>(value).is_err() {
427 respond_before_close(
428 &mut send,
429 err_frame("invalid_request", "session.renew/1 needs {}"),
430 )
431 .await;
432 conn.close(PROTOCOL_CLOSE_CODE, b"renewal complete");
433 return Err(SessionEnd::NotOpened("invalid_request".into()));
434 }
435
436 match bus.renew(&endpoint).await {
437 Ok(session) => {
438 let ok = RenewOk {
439 credential: session.credential.unwrap_or_default(),
440 expires_at: session.expires_at,
441 scopes: session.scopes,
442 device_id: session.device_id,
443 device_did: session.device_did,
444 revocation_id: None,
445 };
446 let body = serde_json::to_vec(&ok).unwrap_or_default();
447 respond_before_close(&mut send, encode_response(RESPONSE_STATUS_OK, &body)).await;
448 conn.close(0, b"renewal complete");
449 Err(SessionEnd::Closed)
450 }
451 Err(refusal) => {
452 let (code, detail) = map_renew_refusal(refusal);
453 respond_before_close(&mut send, err_frame(code, detail)).await;
454 conn.close(PROTOCOL_CLOSE_CODE, b"renewal complete");
455 Err(SessionEnd::NotOpened(code.into()))
456 }
457 }
458}
459
460async fn pair_first(
461 conn: &impl SessionStreams,
462 bus: &impl HostBus,
463 mut send: BoxSend,
464 payload: &[u8],
465) -> Result<(BoxSend, OpenOk, Pairing), SessionEnd> {
466 let endpoint = endpoint_hex(&conn.peer_key());
467 let request = serde_json::from_slice::<serde_json::Value>(payload)
468 .ok()
469 .filter(serde_json::Value::is_object)
470 .and_then(|v| serde_json::from_value::<PairRequest>(v).ok())
471 .filter(|r| !r.token.is_empty());
472 let Some(request) = request else {
473 respond_before_close(
474 &mut send,
475 err_frame(
476 "invalid_request",
477 "session.pair/1 needs {token, endpoint_id}",
478 ),
479 )
480 .await;
481 conn.close(PROTOCOL_CLOSE_CODE, b"session not opened");
482 return Err(SessionEnd::NotOpened("invalid_request".into()));
483 };
484 if !request.endpoint_id.eq_ignore_ascii_case(&endpoint) {
485 respond_before_close(
486 &mut send,
487 err_frame(
488 "endpoint_mismatch",
489 "endpoint_id is not the key this connection proved",
490 ),
491 )
492 .await;
493 conn.close(PROTOCOL_CLOSE_CODE, b"session not opened");
494 return Err(SessionEnd::NotOpened("endpoint_mismatch".into()));
495 }
496
497 let refusal = match bus.admit_pairing(&request.token, &endpoint).await {
498 Ok(admission) if member_node_id_ok(&admission.member_node_id) => {
499 let pairing = match pairing_from_admission(admission, &endpoint) {
500 Ok(pairing) => pairing,
501 Err(refusal) => {
502 respond_before_close(&mut send, map_pairing_refusal(refusal)).await;
503 conn.close(PROTOCOL_CLOSE_CODE, b"session not opened");
504 return Err(SessionEnd::NotOpened("pairing refused".into()));
505 }
506 };
507 let ok = OpenOk {
508 mode: OpenMode::Renewal,
509 device_id: String::new(),
510 device_did: String::new(),
511 scopes: vec![],
512 expires_at: String::new(),
513 };
514 let body = serde_json::to_vec(&PairOk {
515 mode: "pairing",
516 expires_at_ms: now_ms().saturating_add(pairing.lifetime.as_millis() as i64),
517 })
518 .map_err(|_| SessionEnd::NotOpened("encode".into()))?;
519 respond(&mut send, encode_response(RESPONSE_STATUS_OK, &body)).await;
520 return Ok((send, ok, pairing));
521 }
522 Ok(_) => Refusal::new("internal_error", "unusable member id"),
524 Err(refusal) => refusal,
525 };
526 respond_before_close(&mut send, map_pairing_refusal(refusal)).await;
527 conn.close(PROTOCOL_CLOSE_CODE, b"session not opened");
528 Err(SessionEnd::NotOpened("pairing refused".into()))
529}
530
531fn now_ms() -> i64 {
532 use std::time::{SystemTime, UNIX_EPOCH};
533 SystemTime::now()
534 .duration_since(UNIX_EPOCH)
535 .unwrap_or_default()
536 .as_millis() as i64
537}
538
539const MIN_PAIRING_LIFETIME: Duration = Duration::from_secs(1);
541
542fn pairing_from_admission(admission: PairingAdmission, endpoint: &str) -> Result<Pairing, Refusal> {
547 if admission.expires_at_ms <= 0 {
548 return Err(Refusal::new(
549 "internal_error",
550 "admission without an expiry",
551 ));
552 }
553 let until_expiry = admission.expires_at_ms.saturating_sub(now_ms());
554 if until_expiry < MIN_PAIRING_LIFETIME.as_millis() as i64 {
555 return Err(Refusal::new(
556 "pairing_token_expired",
557 "the door token has expired",
558 ));
559 }
560 Ok(Pairing {
561 member: admission.member_node_id,
562 endpoint: endpoint.to_string(),
563 lifetime: PAIRING_LIFETIME.min(Duration::from_millis(until_expiry as u64)),
564 })
565}
566
567fn renewal_expires_at() -> String {
568 use std::time::{SystemTime, UNIX_EPOCH};
569 let secs = SystemTime::now()
570 .duration_since(UNIX_EPOCH)
571 .unwrap_or_default()
572 .as_secs()
573 + RENEWAL_LIFETIME.as_secs();
574 format!("{secs}")
575}
576
577#[allow(clippy::too_many_arguments)]
578async fn serve_opened<C, B>(
579 conn: Arc<C>,
580 bus: Arc<B>,
581 ingress: Arc<IngressSocket>,
582 wire: Arc<WireSocket>,
583 path: SessionPath,
584 webrtc: Option<Arc<dyn WebRtcSignaling>>,
585 _open_send: BoxSend,
586 identity: OpenOk,
587 pairing: Option<Pairing>,
588) -> Result<(), SessionEnd>
589where
590 C: SessionStreams + 'static,
591 B: HostBus + 'static,
592{
593 let identity = Arc::new(identity);
594 let pairing = pairing.map(Arc::new);
595 let peer = conn.peer_key();
596 let mut streams = JoinSet::new();
597 let lifetime = async {
598 if let Some(pairing) = pairing.as_ref() {
599 tokio::time::sleep(pairing.lifetime).await;
600 } else if identity.mode == OpenMode::Renewal {
601 tokio::time::sleep(RENEWAL_LIFETIME).await;
602 } else {
603 std::future::pending::<()>().await;
604 }
605 };
606 tokio::pin!(lifetime);
607
608 let serve = async {
609 loop {
610 while streams.try_join_next().is_some() {}
611 let (send, recv) = match conn.accept_bi().await {
612 Ok(s) => s,
613 Err(_) => break,
614 };
615 if streams.len() >= MAX_SESSION_STREAMS {
616 let mut send = send;
617 let mut recv = recv;
618 let _ = tokio::time::timeout(CALL_READ_DEADLINE, async {
619 if let Ok(method) = peek_method(&mut recv).await {
620 let _ = tunnel::refuse(&mut send, &method, "too_many_streams").await;
621 }
622 })
623 .await;
624 let _ = send.shutdown().await;
625 continue;
626 }
627 let bus = bus.clone();
628 let ingress = ingress.clone();
629 let wire = wire.clone();
630 let identity = identity.clone();
631 let pairing = pairing.clone();
632 let webrtc = webrtc.clone();
633 streams.spawn(async move {
634 serve_stream(
635 bus,
636 ingress,
637 wire,
638 path,
639 peer,
640 &identity,
641 pairing.as_deref(),
642 webrtc,
643 send,
644 recv,
645 )
646 .await;
647 });
648 }
649 };
650
651 tokio::select! {
652 biased;
653 _ = &mut lifetime => {
654 let reason: &[u8] = if pairing.is_some() {
655 b"pairing session expired"
656 } else {
657 b"renewal session expired"
658 };
659 conn.close(PROTOCOL_CLOSE_CODE, reason);
660 }
661 _ = serve => {}
662 }
663 streams.abort_all();
664 while streams.join_next().await.is_some() {}
665 Ok(())
666}
667
668#[allow(clippy::too_many_arguments)]
669async fn serve_stream<B: HostBus>(
670 bus: Arc<B>,
671 ingress: Arc<IngressSocket>,
672 wire: Arc<WireSocket>,
673 path: SessionPath,
674 peer: [u8; 32],
675 identity: &OpenOk,
676 pairing: Option<&Pairing>,
677 webrtc: Option<Arc<dyn WebRtcSignaling>>,
678 mut send: BoxSend,
679 mut recv: BoxRecv,
680) {
681 let deadline = tokio::time::Instant::now() + CALL_READ_DEADLINE;
682 let method = match tokio::time::timeout_at(deadline, peek_method(&mut recv)).await {
683 Err(_) | Ok(Err(_)) => {
684 let _ = tunnel::refuse(&mut send, "unknown/1", "invalid_request").await;
685 let _ = send.shutdown().await;
686 return;
687 }
688 Ok(Ok(method)) => method,
689 };
690
691 if pairing.is_some() && method != HTTP_REQUEST_METHOD {
694 let _ = tunnel::refuse(&mut send, &method, "pairing_only").await;
695 let _ = send.shutdown().await;
696 return;
697 }
698
699 if identity.mode == OpenMode::Renewal && method != HTTP_REQUEST_METHOD {
700 let _ = tunnel::refuse(&mut send, &method, "renewal_only").await;
701 let _ = send.shutdown().await;
702 return;
703 }
704
705 if method == WEBRTC_SIGNAL_METHOD {
706 match webrtc {
707 Some(hook) => {
708 hook.handle(identity, peer, send, recv).await;
709 }
710 None => {
711 let _ = tunnel::refuse(&mut send, &method, "unsupported_transport").await;
712 let _ = send.shutdown().await;
713 }
714 }
715 return;
716 }
717
718 if method == WIRE_METHOD {
720 match wire.path.as_ref() {
721 Some(socket) => {
722 let _ =
724 wire_stream::splice_to_wire_socket(socket, path.as_str(), None, "", send, recv)
725 .await;
726 }
727 None => {
728 let _ = tunnel::refuse(&mut send, WIRE_METHOD, "wire_unavailable").await;
729 let _ = send.shutdown().await;
730 }
731 }
732 return;
733 }
734
735 if method == HTTP_REQUEST_METHOD {
736 let gate = match (pairing, identity.mode) {
737 (Some(pairing), _) => Gate::Pairing {
738 member: &pairing.member,
739 endpoint: &pairing.endpoint,
740 },
741 (None, OpenMode::Renewal) => Gate::Renewal,
742 (None, OpenMode::Full) => Gate::Full,
743 };
744 let _ = tunnel::serve_http(&ingress, path, &mut recv, &mut send, gate).await;
745 let _ = send.shutdown().await;
746 return;
747 }
748
749 if method == WS_STREAM_METHOD {
750 let _ = tunnel::serve_ws(&ingress, path, recv, send).await;
751 return;
752 }
753
754 let mut payload = Vec::new();
755 let read = tokio::time::timeout_at(
756 deadline,
757 recv.take((MAX_FRAME_BYTES - 2 - method.len()) as u64)
758 .read_to_end(&mut payload),
759 )
760 .await;
761 if read.is_err() || matches!(read, Ok(Err(_))) {
762 respond(
763 &mut send,
764 err_frame("invalid_request", "frame too large or unreadable"),
765 )
766 .await;
767 return;
768 }
769
770 let response = if method == SESSION_OPEN_METHOD || method == SESSION_PAIR_METHOD {
771 err_frame("already_open", "this connection already has a session")
772 } else if method == DEVICE_CALL_METHOD {
773 match device_call(bus.as_ref(), identity, &peer, &payload).await {
774 Ok(body) => encode_response(RESPONSE_STATUS_OK, body.to_string().as_bytes()),
775 Err(frame) => frame,
776 }
777 } else {
778 err_frame("unknown_method", &method)
779 };
780 respond(&mut send, response).await;
781}
782
783async fn device_call(
784 bus: &impl HostBus,
785 identity: &OpenOk,
786 peer: &[u8; 32],
787 payload: &[u8],
788) -> Result<serde_json::Value, Vec<u8>> {
789 let call: ServiceCall = serde_json::from_slice(payload)
790 .map_err(|_| err_frame("invalid_request", "device.call/1 needs {service, payload}"))?;
791 let svc = service(&call.service).ok_or_else(|| err_frame("unknown_service", &call.service))?;
792 if !scope_allows(&identity.scopes, svc.scope) {
793 return Err(err_frame("scope_denied", svc.scope));
794 }
795 let endpoint = endpoint_hex(peer);
796 let stamped = stamp(
797 call.payload,
798 &StampIdentity {
799 device_id: &identity.device_id,
800 device_did: &identity.device_did,
801 scopes: &identity.scopes,
802 endpoint_hex: &endpoint,
803 },
804 );
805 match tokio::time::timeout(CALL_DEADLINE, bus.invoke(svc.capability, stamped)).await {
806 Err(_) => Err(err_frame(
807 "timeout",
808 "the node service did not answer in time",
809 )),
810 Ok(Ok(value)) => Ok(value),
811 Ok(Err(refusal)) => Err(err_frame("service_error", &refusal.message)),
812 }
813}