Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
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
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,23 @@
# Changelog

## Unreleased — proposed 0.9.0

- Opt-in persistence now saves every INVITE final response before its ACK,
including rejection and authentication challenges. A successful re-INVITE
checkpoint contains the accepted Contact and the observed response in one
coherent snapshot boundary. Failed writes continue to block protected sends.

- **Breaking (requires maintainer approval for 0.9.0):** `DialogSnapshot` adds
coherent `runtime` metadata and becomes `#[non_exhaustive]`. External callers
must use `DialogSnapshot::builder(...)` and include `..` in destructuring
patterns. State, both CSeq values and runtime metadata must be explicit.
- **Recovery behavior:** confirmed snapshots with unfinished signaling or invalid
lifecycle history are rejected. Stored transactions and handlers are not
replayed. Lifecycle records can be reconstructed with `DialogLifecycleRecord::new`.
- See [the migration guide](MIGRATING-0.9.md) for storage defaults, legacy-record
handling, and the release compatibility plan. The release target is proposed;
this change does not itself bump or publish the package version.

## 0.8.1

Fourteen fixes and additions merged (#223–#236).
Expand Down
6 changes: 6 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@
parking_lot = { version = "0.12", optional = true }
tokio-tungstenite = { version = "0.29.0", optional = true }
tokio-rustls = { version = "0.26", default-features = false, features = ["ring", "tls12", "logging"], optional = true }
rustls-pki-types = { version = "1", features = ["alloc"], optional = true }

Check warning on line 53 in Cargo.toml

View workflow job for this annotation

GitHub Actions / cargo shear

shear/unused_optional_dependency

unused optional dependency `rustls-pki-types`
rustls = { version = "0.23", default-features = false, features = ["ring"], optional = true }
base64 = { version = "0.22", default-features = false, features = ["alloc"] }
clap = { version = "4.5.53", optional = true, features = ["derive"] }
Expand Down Expand Up @@ -86,6 +86,7 @@
critical-section = { version = "1", optional = true }

[dev-dependencies]
tokio = { version = "1.50.0", features = ["test-util"] }
dotenvy = "0.15.7"
tempfile = "3"
sdp-rs = "0.2.1"
Expand All @@ -112,3 +113,8 @@
[[example]]
name = "interop_b2bua"
required-features = ["platform-tokio"]

[[example]]
name = "prack_probe"
path = "examples/prack_probe.rs"
required-features = ["platform-tokio"]
101 changes: 101 additions & 0 deletions MIGRATING-0.9.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
# Snapshot migration for the proposed 0.9.0 release

These changes require a breaking release. The proposed target is **0.9.0**,
subject to maintainer approval; this document does not announce a release or
change the package version. Do not backport this API change into 0.8.x.

## Constructing and reading snapshots

`DialogSnapshot` now includes coherent runtime metadata and is
`#[non_exhaustive]`. Adding `runtime` breaks old struct literals and exhaustive
patterns. The attribute also prevents external struct literals, even if they
include `runtime`. Replace them with `DialogSnapshot::builder(...)`; adding
`runtime: DialogSnapshotRuntime::default()` to a literal is not sufficient.

Supply the stored identity, role, From/To headers, remote URI, state, both CSeq
counters, and runtime metadata. The builder requires state, counters and runtime
explicitly: it never assumes a stored dialog was confirmed or quiescent. Copy
optional stored contacts, routes, 100rel support and Session-ID through their
builder methods too. Omitting those optional settings yields `None`, no routes,
`false`, and `None`, respectively; it does not recover their persisted values.

This example illustrates an application-approved migration of a legacy,
confirmed record known to have been captured with no signaling in flight:

```rust
use rsipstack::{
dialog::{
dialog::{DialogSnapshot, DialogSnapshotState},
snapshot::DialogSnapshotRuntime,
DialogId,
},
sip::{headers, prelude::ToTypedHeader},
transaction::key::TransactionRole,
};

let snapshot = DialogSnapshot::builder(
DialogId {
call_id: "stored-call".into(),
local_tag: "local".into(),
remote_tag: "remote".into(),
},
TransactionRole::Client,
headers::From::from("<sip:alice@example.com>;tag=local").typed()?,
headers::To::from("<sip:bob@example.com>;tag=remote").typed()?,
"sip:bob@example.com".try_into()?,
)
.state(DialogSnapshotState::Confirmed)
.local_cseq(42)
.remote_cseq(7)
.local_contact(Some("sip:alice@example.com".try_into()?))
// The application has established that this legacy record was quiescent.
.runtime(DialogSnapshotRuntime::default())
.build()?;

// Field access is unchanged. Patterns must allow future fields.
let DialogSnapshot { id, runtime, .. } = snapshot;
assert_eq!(id.call_id, "stored-call");
assert!(runtime.lifecycle.is_empty());
# Ok::<(), Box<dyn std::error::Error>>(())
```

The builder checks required inputs and the lifecycle history of confirmed
snapshots. It also represents pending and non-confirmed snapshots so applications
can inspect or store them. `build()` succeeding does **not** guarantee that
restore will resume the dialog. Public fields remain mutable, so restore retains
its own validation.

## Storage and recovery behavior

The application owns serialization, storage schema versions and migrations.
`runtime.revision` identifies a dialog state revision, **not a storage schema**.
Persist the complete runtime metadata, including pending operations and lifecycle
records. Reconstruct individual facts with
`DialogLifecycleRecord::new(sequence, since_unix_epoch, kind)`. Preserve their
sequence and optional wall-clock time; do not invent timestamps or acceptance
events during migration. Restoring retains the history without replaying it to
notification consumers. Monotonic timestamps are process-local and not stored.

For a pre-0.9 record without runtime metadata, explicitly passing
`DialogSnapshotRuntime::default()` represents revision zero, no recorded history,
and no pending operations. This is appropriate only when the application's
existing capture contract or other reliable evidence establishes that signaling
was quiescent. Missing metadata alone does not establish that fact. Empty history
means no history was retained; it is not evidence that the call was never answered.
If quiescence cannot be established, apply an explicit application recovery policy
instead of silently resuming the call. Never discard known pending work or use a
default to hide corrupt metadata.

Calls to `dialog.snapshot()` and `layer.restore_from_snapshot(snapshot, sender)`
keep their signatures. The restore behavior changes as follows:

- A confirmed snapshot with non-empty `runtime.pending` returns an error. SIP
transactions, outstanding ACKs and application handlers are not replayed.
- Invalid confirmed lifecycle history or revision returns an error.
- Non-confirmed snapshots are still skipped with `Ok(false)`.
- An already registered dialog is still retained and restore returns `Ok(false)`.

Future optional fields may have safe defaults without breaking builder callers.
New data required for safe recovery must instead have an explicit migration or
compatibility plan. `#[non_exhaustive]` protects source construction and matching;
it is not a promise that every future persisted record can be silently migrated.
82 changes: 82 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,88 @@ A RFC 3261/3262 compliant SIP stack written in Rust. The goal of this project is
- **Digest Authentication**: Built-in authentication support
- **no_std / Embedded**: alloc-only core with an embassy backend

## Reliable provisional responses (100rel / PRACK)

Full UAC and UAS signaling is enabled explicitly on the dialog layer:

```rust,ignore
use rsipstack::dialog::reliable::ReliableProvisionalConfig;

// media implements the async PrackHandler trait.
let mut config = ReliableProvisionalConfig::new(media);
config.require = false; // true additionally sends Require: 100rel on INVITEs
dialog_layer.set_reliable_provisional(Some(config));
```

The setting applies to new calls and restored confirmed dialogs. The UAS sends
reliable 101–199 only when the INVITE advertises or requires 100rel. Without this
configuration, required 100rel is rejected with 420/Unsupported; ordinary calls
keep their existing behavior. The legacy `InviteOption::support_prack` switch
does not install a media handler and is not needed with the full configuration.

The stack assigns RSeq, validates RAck, keeps state per dialog and INVITE CSeq,
retransmits reliable provisionals from T1 with exponential backoff (without a
T2 cap), and rejects the INVITE after 64*T1 without PRACK. It serializes reliable
provisionals and defers final 2xx while a reliable SDP response is unacknowledged.
CANCEL/non-2xx finals discard a queued successful final; late PRACK remains
routable for 64*T1 when a dialog is removed. PRACK requests use independent
transactions, including authentication and retransmission, so waiting for their
responses does not block INVITE final responses or cancellation.

`PrackHandler` is the media boundary:

- `on_reliable_response`: for `Offer`, return an SDP answer for PRACK. For
`Answer`, consume the answer and return either no body or a new SDP offer.
- `on_prack`: consume an SDP answer received in PRACK; return an SDP answer
when PRACK contains an offer.
- `on_prack_result`: receives the final PRACK response, including the answer
to an offer sent in PRACK; `None` means transaction timeout.
- `on_error`: reports transport, timeout, protocol or media-handler failures.

`SdpKind::Ignored` marks subsequent SDP for an INVITE whose initial description
has already been processed. Do not renegotiate from that body. The ordinary
Early/Confirmed events retain raw SIP messages for observation; applications
using the handler should not apply their SDP a second time. Media negotiation,
codec selection, rejected-media answers, RTP, and coordination with application
UPDATE/re-INVITE offers remain the media application's responsibility. A failed
UAS media callback returns 500 and fails the pending INVITE rather than leaving
a deferred final response waiting indefinitely.

The existing INVITE/ACK API still handles SDP first delivered in a final 2xx.
For an offerless INVITE that might receive its first offer in 2xx instead of
reliable 1xx, disable automatic 2xx ACKs (`EndpointOption::auto_ack_2xx = false`)
and supply the SDP answer through the application's ACK handling. The new
handler owns SDP in reliable provisional responses and PRACK, not ordinary
INVITE/ACK or UPDATE exchanges.

For an initial server INVITE, use the usual `ringing()` and `accept()` methods;
for a re-INVITE, use its `TransactionHandle`. Keep the INVITE transaction's owning
task running: it sends queued responses and retransmissions. With 100rel enabled,
Early/WaitAck notifications reflect actual response transmission, which may occur
after `ringing()`/`accept()` returns. Configure the layer before creating calls;
do not change a dialog's configuration during an INVITE exchange.

An independent UDP signaling probe is provided in `examples/prack_probe.rs`.
It accepts an application-prepared SDP file and sends no RTP:

```bash
cargo run --example prack_probe -- \
0.0.0.0:5062 sip:100@example.net sip:destination@example.net \
sip:100@YOUR_PUBLIC_IP:5062 ./compatible-sdp.txt --require
```

The probe sends the file as the INVITE offer. Optional digest credentials
come from `SIP_USERNAME`, `SIP_PASSWORD`, and `SIP_REALM`. The probe sends BYE
after an answered call and does not modify any application configuration.

The regression suite covers RFC 3262 sections 3–5 and the SDP patterns clarified
by RFC 6337, including real UDP stack-to-stack calls and deterministic timers:

```bash
cargo test --lib test_reliable_provisional
bash scripts/interop/run.sh regression prack
```

## no_std / Embedded Support

rsipstack compiles without `std` (`alloc`-only) for embassy-based targets —
Expand Down
141 changes: 141 additions & 0 deletions examples/prack_probe.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
//! UDP SIP signaling probe; it does not run an RTP/media engine.
//! Usage: prack_probe LISTEN FROM CALLEE CONTACT SDP_FILE [--require]
//! Supply an SDP offer prepared for the peer's media capabilities.
use async_trait::async_trait;
use rsipstack::dialog::{
authenticate::Credential,
dialog_layer::DialogLayer,
invitation::InviteOption,
reliable::{
IncomingPrack, PrackBody, PrackHandler, ReliableProvisionalConfig, ReliableResponse,
SdpKind,
},
DialogId,
};
use rsipstack::sip::{Request, Response, StatusCodeKind};
use rsipstack::transport::{udp::UdpConnection, TransportLayer};
use rsipstack::{EndpointBuilder, Result};
use std::{env, sync::Arc, time::Duration};
use tokio_util::sync::CancellationToken;

struct Media {
sdp: Vec<u8>,
}
#[async_trait]
impl PrackHandler for Media {
async fn on_reliable_response(&self, event: ReliableResponse) -> Result<Option<PrackBody>> {
eprintln!(
"reliable {}: {:?}, dialog {}",
event.response.status_code, event.sdp_kind, event.dialog_id
);
Ok((event.sdp_kind == SdpKind::Offer).then(|| PrackBody::sdp(self.sdp.clone())))
}
async fn on_prack(&self, event: IncomingPrack) -> Result<Option<PrackBody>> {
eprintln!("incoming PRACK: {:?}", event.sdp_kind);
Ok((event.sdp_kind == SdpKind::Offer).then(|| PrackBody::sdp(self.sdp.clone())))
}
async fn on_prack_result(&self, _: Request, response: Option<Response>) {
eprintln!(
"PRACK result: {}",
response
.map(|r| r.status_code.to_string())
.unwrap_or_else(|| "timeout".into())
);
}
async fn on_error(&self, id: DialogId, message: String) {
eprintln!("100rel error ({id}): {message}");
}
}

#[tokio::main]
async fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
let args: Vec<_> = env::args().skip(1).collect();
if args.len() < 5 || args.iter().any(|a| a == "--help") {
eprintln!("Usage: prack_probe LISTEN FROM CALLEE CONTACT SDP_FILE [--require]\nSends one real SIP call and BYE after answer. SDP must be prepared for the peer; no RTP is sent.");
return Ok(());
}
for flag in &args[5..] {
if flag != "--require" {
return Err(format!("Unknown option: {flag}").into());
}
}
let media = Arc::new(Media {
sdp: std::fs::read(&args[4])?,
});
if media.sdp.is_empty() {
return Err("SDP file is empty".into());
}
let token = CancellationToken::new();
let transport = TransportLayer::new(token.child_token());
let udp =
UdpConnection::create_connection(args[0].parse()?, None, Some(token.child_token())).await?;
transport.add_transport(udp.into());
let endpoint = EndpointBuilder::new()
.with_transport_layer(transport)
.with_cancel_token(token.child_token())
.build();
let layer = Arc::new(DialogLayer::new(endpoint.inner.clone()));
layer.set_reliable_provisional(Some(ReliableProvisionalConfig {
handler: media.clone(),
require: args.iter().any(|a| a == "--require"),
}));
let mut incoming = endpoint.incoming_transactions()?;
let router = layer.clone();
tokio::spawn(async move {
while let Some(mut tx) = incoming.recv().await {
if let Some(mut dialog) = router.match_dialog(&tx) {
tokio::spawn(async move { dialog.handle(&mut tx).await });
} else {
tx.reply(rsipstack::sip::StatusCode::CallTransactionDoesNotExist)
.await
.ok();
}
}
});
let server = endpoint.inner.clone();
tokio::spawn(async move { server.serve().await });
let credential = match (env::var("SIP_USERNAME"), env::var("SIP_PASSWORD")) {
(Ok(username), Ok(password)) => Some(Credential {
username,
password,
realm: env::var("SIP_REALM").ok(),
auth_username: None,
}),
(Err(_), Err(_)) => None,
_ => return Err("Set both SIP_USERNAME and SIP_PASSWORD".into()),
};
let option = InviteOption {
caller: args[1].as_str().try_into()?,
callee: args[2].as_str().try_into()?,
contact: args[3].as_str().try_into()?,
offer: Some(media.sdp.clone()),
credential,
..Default::default()
};
let (states, mut events) = tokio::sync::mpsc::unbounded_channel();
tokio::spawn(async move {
while let Some(event) = events.recv().await {
eprintln!("{event}");
}
});
let (dialog, mut join) = layer.do_invite_async(option, states)?;
let (_, result) = match tokio::time::timeout(Duration::from_secs(60), &mut join).await {
Ok(result) => result??,
Err(_) => {
dialog.cancel().await?;
let _ = tokio::time::timeout(Duration::from_secs(35), &mut join).await;
token.cancel();
return Err("Call setup timed out; CANCEL requested".into());
}
};
if let Some(response) = result {
eprintln!("INVITE result: {}", response.status_code);
if response.status_code.kind() == StatusCodeKind::Successful {
tokio::time::sleep(Duration::from_secs(2)).await;
dialog.bye().await?;
}
}
layer.remove_dialog(&dialog.id());
token.cancel();
Ok(())
}
Loading
Loading