moqtap_codec/draft20/message.rs
1//! Draft-20 control message encoding and decoding.
2//!
3//! Key differences from draft-19:
4//! - **FETCH (0x16) is a different message.** The `Fetch Type` field is gone,
5//! and with it the Standalone Fetch and Joining Fetch structures and the
6//! Fetch Type registry. Track Namespace and Track Name are inline fields of
7//! FETCH, and the range travels in the `LOCATION_FILTER` parameter
8//! (Section 10.13, Figure 16).
9//! - **PUBLISH_STATE_NOTIFY (0x22) is new** and carries no Request ID
10//! (Section 10.10, Figure 13).
11//! - **`LOCATION_FILTER` (0x21) has a new value shape.** The Filter Type enum
12//! is gone; the shape comes from how many `vi64` fields the value holds
13//! (Section 5.1.2).
14//! - **`FILL_PARAMETERS` (0x23) is new**: a length-prefixed parameter carrying
15//! a nested parameter block in its own scope (Section 10.2.15).
16//! - **`INCLUDE_PROPERTIES` (0x35) is new**: a uint8 restricted to 0 and 1
17//! (Section 10.2.21).
18//! - **Parameter applicability moved off `PUBLISH_OK`.** Six definitions
19//! dropped it and several gained `PUBLISH`; only `EXPIRES` still names it.
20//! - `PUBLISH_DONE`'s `SUBSCRIPTION_ENDED` status (0x3) and `REQUEST_ERROR`'s
21//! `INVALID_JOINING_REQUEST_ID` (0x32) are unassigned here.
22//! - Section numbering shifted from Section 10.10 on; every reference in this
23//! module is draft-20's own.
24
25use crate::auth_token::{AuthorizationToken, AUTH_TOKEN_PARAMETER};
26use crate::error::MAX_FULL_TRACK_NAME_LENGTH;
27pub use crate::error::{
28 CodecError, MAX_GOAWAY_URI_LENGTH, MAX_MESSAGE_LENGTH, MAX_NAMESPACE_TUPLE_SIZE,
29 MAX_REASON_PHRASE_LENGTH,
30};
31use crate::kvp::{KeyValuePair, KvpError, KvpValue, MAX_KVP_VALUE_LEN};
32use crate::types::*;
33use crate::varint::{Moqt18 as Wire, VarInt};
34use bytes::{Buf, BufMut};
35
36// ============================================================
37// Parameter encoding helpers for draft-20
38// ============================================================
39
40/// How a parameter value is encoded on the wire.
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42enum ParamEncoding {
43 /// Bare varint.
44 Varint,
45 /// Single byte (uint8).
46 Uint8,
47 /// Two consecutive varints (group, object).
48 Location,
49 /// Length-prefixed bytes.
50 LengthPrefixed,
51 /// A Track Namespace as defined in draft-20 Section 2.4.1: a varint field
52 /// count followed by that many length-prefixed fields.
53 ///
54 /// Not one of the four value encodings draft-20 Section 10.2 lists. A
55 /// parameter definition is free to name an encoding from elsewhere in the
56 /// document, and TRACK_NAMESPACE_PREFIX does exactly that; the field count
57 /// is the only length the wire carries.
58 TrackNamespaceValue,
59}
60
61fn param_encoding(key: u64) -> Option<ParamEncoding> {
62 match key {
63 // 0x02 = OBJECT_DELIVERY_TIMEOUT (Section 10.2.4)
64 // 0x04 = RENDEZVOUS_TIMEOUT (Section 10.2.6). Not MAX_CACHE_DURATION:
65 // that is Property Type 0x04 in the separate Properties
66 // registry (Section 15.8), a different namespace that happens
67 // to reuse the number.
68 // 0x06 = SUBGROUP_DELIVERY_TIMEOUT (Section 10.2.3)
69 // 0x08 = EXPIRES (Section 10.2.16, draft-19's 10.2.15)
70 // 0x0A = FILL_TIMEOUT (Section 10.2.5)
71 // 0x32 = NEW_GROUP_REQUEST (Section 10.2.19, draft-19's 10.2.18)
72 0x02 | 0x04 | 0x06 | 0x08 | 0x0A | 0x32 => Some(ParamEncoding::Varint),
73 // 0x10 = FORWARD (Section 10.2.18), 0x20 = SUBSCRIBER_PRIORITY,
74 // 0x22 = GROUP_ORDER, and 0x35 = INCLUDE_PROPERTIES, new in draft-20.
75 // Section 10.2.21: "The INCLUDE_PROPERTIES parameter (Parameter Type
76 // 0x35) is a uint8."
77 0x10 | 0x20 | 0x22 | 0x35 => Some(ParamEncoding::Uint8),
78 // 0x09 = LARGEST_OBJECT. Draft-20 Section 10.2.17: "The LARGEST_OBJECT
79 // parameter (Parameter Type 0x9) is a Location." A Location is
80 // two consecutive varints (Section 10.2), with no length ahead
81 // of them. The type is odd, which on a Key-Value-Pair would mean
82 // length-prefixed; Message Parameters are not Key-Value-Pairs
83 // and the odd/even rule does not reach them.
84 0x09 => Some(ParamEncoding::Location),
85 // 0x34 = TRACK_NAMESPACE_PREFIX. Section 10.2.20: it "uses the Track
86 // Namespace encoding described in Section 2.4.1".
87 0x34 => Some(ParamEncoding::TrackNamespaceValue),
88 // 0x03 = AUTHORIZATION_TOKEN
89 // 0x21 = LOCATION_FILTER, whose value draft-20 rebuilt (Section 5.1.2)
90 // 0x23 = FILL_PARAMETERS, new in draft-20. Section 10.2.15: it "uses
91 // length-prefixed encoding", and the value is a nested
92 // parameter block rather than opaque bytes
93 // 0x25 = SUBGROUP_FILTER, 0x26 = OBJECTID_FILTER, 0x27 = PRIORITY_FILTER,
94 // 0x28 = OBJECT_PROPERTY_FILTER, 0x29 = TRACK_PROPERTY_FILTER
95 // (Range Filters, Section 5.1.4 — draft-19's Section 5.1.3)
96 0x03 | 0x21 | 0x23 | 0x25 | 0x26 | 0x27 | 0x28 | 0x29 => {
97 Some(ParamEncoding::LengthPrefixed)
98 }
99 _ => None,
100 }
101}
102
103/// Whether `value` is inside the range draft-20 allows for a uint8-valued
104/// parameter.
105///
106/// Three of the four uint8 parameters restrict their range and say the receiver
107/// MUST close the session with PROTOCOL_VIOLATION on anything outside it:
108/// GROUP_ORDER allows only Ascending (0x1) and Descending (0x2) (Section
109/// 10.2.8), FORWARD allows only 0 and 1 (Section 10.2.18), and
110/// INCLUDE_PROPERTIES — new in draft-20 — allows only 0 and 1 (Section
111/// 10.2.21). SUBSCRIBER_PRIORITY (Section 10.2.7) uses the whole 0-255 range,
112/// so it has no entry here.
113///
114/// Range-checking on decode is what makes the values usable: an application
115/// that tests `group_order == 2` for descending would otherwise treat 7 as
116/// neither ascending nor descending and carry on.
117fn uint8_value_in_range(key: u64, value: u8) -> bool {
118 match key {
119 // FORWARD (0x10)
120 0x10 => value <= 1,
121 // GROUP_ORDER (0x22)
122 0x22 => value == 1 || value == 2,
123 // INCLUDE_PROPERTIES (0x35), Section 10.2.21: "The allowed values are
124 // 0 (do not send Properties) or 1 (send Properties), and the default
125 // is 1. If an endpoint receives a value outside this range, it MUST
126 // close the session with PROTOCOL_VIOLATION."
127 0x35 => value <= 1,
128 _ => true,
129 }
130}
131
132/// AUTHORIZATION TOKEN, Parameter Type 0x03.
133const AUTHORIZATION_TOKEN: u64 = 0x03;
134
135/// Whether draft-20 lets a message carry parameter type `key` more than once.
136///
137/// Section 10.2 states the default: "Senders MUST NOT repeat the same Parameter
138/// Type in a message unless the parameter definition explicitly allows multiple
139/// instances of that type to be sent in a single message." Two definitions do.
140///
141/// * `AUTHORIZATION_TOKEN` (0x03), Section 10.2.2: "The AUTHORIZATION TOKEN
142/// parameter MAY be repeated within a message as long as the combination of
143/// Token Type and Token Value are unique after resolving any aliases."
144/// * The five Range Filters (0x25 through 0x29), Section 5.1.4 — draft-19's
145/// 5.1.3: "The Track Property filter parameter MAY appear multiple times in a
146/// SUBSCRIBE_TRACKS message or REQUEST_UPDATE for it. All other filter
147/// parameters MAY appear multiple times in a FETCH, SUBSCRIBE,
148/// SUBSCRIBE_TRACKS, or REQUEST_UPDATE (on a subscription, from the subscriber
149/// only) message."
150///
151/// # A zero `Type Delta` is "the same type again", not an error
152///
153/// The two rules interact, and **the draft does not say how**. Section 10.2 also
154/// requires that "Parameters MUST be serialized in ascending order by Type", so
155/// a second instance of a repeatable type produces a `Type Delta` of 0 — well
156/// formed only if the decoder reads a zero delta as a repeat rather than as a
157/// malformation. That reading is the one taken here; the alternative makes
158/// Section 5.1.4's permission unusable, because there is no other encoding for
159/// a second filter of the same type.
160///
161/// What the filters may **not** do is repeat the same (Parameter Type, SetID,
162/// Property Type) triple, and Section 5.1.4 answers that with a REQUEST_ERROR
163/// carrying INVALID_FILTER rather than with a session close. A reply an endpoint
164/// sends is not a frame a decoder refuses, so nothing here enforces it — see
165/// [`crate::range_filter`] for the reader an endpoint uses to decide.
166fn parameter_may_repeat(key: u64) -> bool {
167 matches!(key, AUTHORIZATION_TOKEN | 0x25..=0x29)
168}
169
170/// Add a delta to the previous delta-encoded key.
171///
172/// Draft-20 Section 1.4.3: "The previous Type value plus the Delta Type MUST NOT
173/// be greater than 2^64 - 1. If a Delta Type is received that would be too
174/// large, the Session MUST be closed with a PROTOCOL_VIOLATION." MoQT varints
175/// span the whole 64-bit range, so a peer can drive the sum past the end: a
176/// debug build panicked on the addition and a release build wrapped the key and
177/// reported the parameter under a type its sender never wrote.
178fn add_delta(prev_key: u64, delta: u64) -> Result<u64, CodecError> {
179 prev_key.checked_add(delta).ok_or(CodecError::KeyDeltaOverflow(prev_key, delta))
180}
181
182/// Hold a namespace-plus-name pair to the Full Track Name cap.
183///
184/// Draft-20 Section 2.4.1: "The maximum total length of a Full Track Name is
185/// 4,096 bytes. The length of a Full Track Name is computed as the sum of the
186/// Track Namespace Field Length fields and the Track Name Length field... If an
187/// endpoint receives a Track Namespace or a Full Track Name exceeding 4,096
188/// bytes, it MUST close the session with a PROTOCOL_VIOLATION."
189///
190/// The namespace half of that sentence is enforced inside the namespace decoder,
191/// which is the only place that sees a namespace with no name beside it. This is
192/// the other half, and it has to live where the two are decoded together: a
193/// namespace at 4,000 bytes and a name at 500 are each legal alone.
194fn check_full_track_name(namespace: &TrackNamespace, track_name: &[u8]) -> Result<(), CodecError> {
195 let total = namespace.field_bytes_len().saturating_add(track_name.len());
196 if total > MAX_FULL_TRACK_NAME_LENGTH {
197 return Err(CodecError::TrackNameTooLong);
198 }
199 Ok(())
200}
201
202/// Hold every AUTHORIZATION TOKEN parameter to the Token structure it names.
203///
204/// Section 10.2.2: "If the Token structure cannot be decoded, the receiver
205/// MUST close the Session with KEY_VALUE_FORMATTING_ERROR." That is the answer
206/// Section 1.4.3 gives for any Type whose value does not match the
207/// serialization that Type defines; the Token is the one structure this draft
208/// spells out, and the only parameter value in it that is more than opaque
209/// bytes.
210///
211/// Both namespaces carry the type on this draft, and both reach here.
212///
213/// A type this draft cannot name is left alone. The rule is conditional on the
214/// receiver understanding the Type, and an extension's parameter carries bytes
215/// no rule here describes.
216fn check_authorization_tokens(parameters: &[KeyValuePair]) -> Result<(), CodecError> {
217 for parameter in parameters {
218 let key = parameter.key.into_inner();
219 if key != AUTH_TOKEN_PARAMETER {
220 continue;
221 }
222 match ¶meter.value {
223 KvpValue::Bytes(value) => {
224 AuthorizationToken::decode_moqt::<Wire>(key, value)?;
225 }
226 // Unreachable from the decoder, which picks the shape from the
227 // type and finds this one length-prefixed. A caller that built the
228 // pair in memory can still get here, and it is the same rule: the
229 // value is not the serialization the type defines.
230 KvpValue::Varint(_) => {
231 return Err(CodecError::KeyValueFormatting {
232 key,
233 detail: "its value is a bare varint where the type defines a Token structure",
234 });
235 }
236 }
237 }
238 Ok(())
239}
240
241/// The LOCATION_FILTER parameter type, draft-20 Section 10.2.9.
242pub const LOCATION_FILTER: u64 = 0x21;
243
244/// The FILL_PARAMETERS parameter type, draft-20 Section 10.2.15. New in
245/// draft-20.
246pub const FILL_PARAMETERS: u64 = 0x23;
247
248/// The most `vi64` fields a `LOCATION_FILTER` value can hold: `StartGroup`,
249/// `StartObject`, `EndGroupDelta`, `EndObject` (draft-20 Section 5.1.2).
250const LOCATION_FILTER_MAX_FIELDS: usize = 4;
251
252/// The parameter types draft-20 Section 10.2.15, Table 6 permits inside a
253/// `FILL_PARAMETERS` value, in ascending order.
254///
255/// `TRACK_PROPERTY_FILTER` (0x29) is deliberately absent: a fill applies to one
256/// already-selected track, so a filter that selects tracks has nothing to do
257/// there. The draft does not say that in as many words, but it does say what
258/// happens to one that arrives anyway — "An endpoint that receives a parameter
259/// inside FILL_PARAMETERS that is not listed above MUST close the session with
260/// PROTOCOL_VIOLATION" — which is what makes the omission load-bearing rather
261/// than editorial. A relay forwarding a downstream `FILL_PARAMETERS` upstream
262/// has to strip it rather than pass it on.
263const FILL_PARAMETERS_ALLOWED: &[u64] = &[0x0A, 0x20, 0x21, 0x22, 0x25, 0x26, 0x27, 0x28];
264
265/// Decode the `vi64` fields of a draft-20 `LOCATION_FILTER` value.
266///
267/// Returns between zero and four values, in the wire order `StartGroup`,
268/// `StartObject`, `EndGroupDelta`, `EndObject`. Which of the five shapes the
269/// filter is comes from how many came back; draft-20 Section 5.1.2 gives the
270/// table.
271///
272/// # The field count comes from parsing, never from the byte length
273///
274/// The draft says "Length (in bytes) determines how many optional vi64 fields
275/// are present", and that is not implementable as written. MoQT varints are one
276/// to nine bytes wide and Section 1.4.1 permits non-minimal encodings, so a
277/// `Length` of 2 is equally consistent with two one-byte fields and one two-byte
278/// field. **This codec decodes `vi64` values until exactly `Length` bytes have
279/// been consumed and then switches on the count.** That is the only rule that
280/// round-trips, and it is a decision this codec makes: the draft states the
281/// byte-length reading and no other.
282///
283/// Two corollaries follow that the draft also does not state, and both are
284/// chosen here:
285///
286/// * a field that would run past `Length` makes the parameter malformed, rather
287/// than being truncated or read from the bytes after the parameter;
288/// * more than four decoded values makes it malformed, because Section 5.1.2
289/// defines shapes for zero through four and nothing beyond.
290///
291/// A decoder that switched on the byte length would notice neither.
292pub fn decode_location_filter(value: &[u8]) -> Result<Vec<u64>, CodecError> {
293 let mut fields: Vec<u64> = Vec::with_capacity(LOCATION_FILTER_MAX_FIELDS);
294 let mut cursor = value;
295 while cursor.has_remaining() {
296 if fields.len() == LOCATION_FILTER_MAX_FIELDS {
297 return Err(CodecError::SubscriptionFilterMalformed {
298 detail: "it holds more than the four vi64 fields Section 5.1.2 defines",
299 });
300 }
301 // The slice is already bounded by the parameter's Length, so a varint
302 // that wants more bytes than remain is one that would have run past it.
303 let field = VarInt::decode_moqt::<Wire>(&mut cursor).map_err(|_| {
304 CodecError::SubscriptionFilterMalformed {
305 detail: "a field runs past the end of the parameter's Length",
306 }
307 })?;
308 fields.push(field.into_inner());
309 }
310 Ok(fields)
311}
312
313/// Hold a decoded `LOCATION_FILTER` to the one arithmetic rule draft-20 states
314/// about it.
315///
316/// Section 5.1.2: "EndGroupDelta is delta encoded from StartGroup, but both the
317/// start and end groups are absolute, not relative to Largest Object. If
318/// StartGroup + EndGroupDelta exceeds 2^64 - 1, the endpoint MUST close the
319/// session with a PROTOCOL_VIOLATION." The sum only exists once three or four
320/// fields are present, so the shorter shapes have nothing to check.
321///
322/// There is deliberately no check that the end is at or after the start.
323/// `EndGroupDelta` is unsigned and added to `StartGroup`, so the end group can
324/// never precede the start group; and within one group draft-20 states no rule
325/// about `EndObject` being below `StartObject`. Section 5.1.2 says the opposite
326/// for subscriptions — "A Location Filter on a subscription is always valid,
327/// even if it specifies a range entirely before Largest Object" — so refusing
328/// one would close sessions over a sentence that is not there.
329fn check_location_filter_fields(fields: &[u64]) -> Result<(), CodecError> {
330 if fields.len() < 3 {
331 return Ok(());
332 }
333 let start_group = fields[0];
334 let delta = fields[2];
335 if start_group.checked_add(delta).is_none() {
336 return Err(CodecError::FilterEndGroupOverflow { start_group, delta });
337 }
338 Ok(())
339}
340
341/// Decode the nested parameter block a `FILL_PARAMETERS` value carries.
342///
343/// # The value begins with a `Number of Parameters` count
344///
345/// Section 10.2.15 says the value is "a sequence of Parameters that apply to
346/// the fill fetch stream" and is "encoded as if they were Parameters for a
347/// separate message", and stops there. **This codec reads that as the
348/// full block, count included.** The draft does not state it either way, and the
349/// wrong choice desynchronises the whole outer parameter list rather than
350/// producing a recognisable error, so it is worth naming: Section 10.2 defines a
351/// parameter block as count-bounded — "Because unknown parameters cannot be
352/// skipped, the block is bounded by a parameter count rather than a length" —
353/// and the phrase *Parameters for a message* denotes that block everywhere else
354/// in Section 10. The outer length prefix is the generic length-prefixed value
355/// encoding every such parameter gets and says nothing about the value's
356/// internal structure.
357///
358/// So an empty `FILL_PARAMETERS` — the common case, a fill with every setting
359/// inherited from the subscription — is `Length = 1` carrying the single byte
360/// `0x00`, and **not** `Length = 0`.
361///
362/// # The `Type Delta` chain restarts here, and the outer chain is unaffected
363///
364/// Section 10.2.15: "The value of FILL_PARAMETERS is a separate parameter
365/// scope. Parameters inside it are not considered to appear in the enclosing
366/// message for the purposes of Section 10.2, so a Parameter Type MAY appear
367/// both in the message and inside FILL_PARAMETERS." Section 10.2 defines
368/// `Type Delta` as the difference from "the previous Parameter Type in the
369/// message", and a separate scope is not the message — so the inner chain
370/// starts from 0, and the outer parameter after `FILL_PARAMETERS` deltas from
371/// `0x23` rather than from the last inner type. **The draft states neither
372/// half explicitly**; both are decided here.
373///
374/// # What it refuses
375///
376/// A type outside Table 6 is [`CodecError::ParameterOutOfScope`], reported
377/// against `FILL_PARAMETERS` itself because the nested scope is the "message"
378/// the parameter appeared in. A type draft-20 does not define at all is
379/// [`CodecError::UnknownMessageParameter`], checked first so an unknown type is
380/// not reported as a known one in the wrong place.
381pub fn decode_fill_parameters(value: &[u8]) -> Result<Vec<KeyValuePair>, CodecError> {
382 let mut cursor = value;
383 let count = VarInt::decode_moqt::<Wire>(&mut cursor)?.into_inner() as usize;
384 let mut params = crate::types::reserve_bounded(count, &cursor);
385 // A separate scope, so the chain starts from 0 exactly as a message's does.
386 let mut prev_key: u64 = 0;
387
388 for i in 0..count {
389 let delta = VarInt::decode_moqt::<Wire>(&mut cursor)?.into_inner();
390 let abs_key = add_delta(prev_key, delta)?;
391 if i > 0 && delta == 0 && !parameter_may_repeat(abs_key) {
392 return Err(CodecError::DuplicateParameter(abs_key));
393 }
394 prev_key = abs_key;
395
396 let encoding =
397 param_encoding(abs_key).ok_or(CodecError::UnknownMessageParameter(abs_key))?;
398 if !FILL_PARAMETERS_ALLOWED.contains(&abs_key) {
399 return Err(CodecError::ParameterOutOfScope {
400 key: abs_key,
401 message_type: FILL_PARAMETERS,
402 });
403 }
404
405 let value = decode_parameter_value(encoding, abs_key, &mut cursor)?;
406 params.push(KeyValuePair { key: VarInt::from_u64_moqt(abs_key), value });
407 }
408
409 // The block is count-bounded and the parameter is length-bounded, and the
410 // two have to agree. Bytes left over mean the count was short of what the
411 // sender wrote, which is the same disagreement a control message's Length
412 // field can have with its body.
413 if cursor.has_remaining() {
414 return Err(CodecError::SubscriptionFilterMalformed {
415 detail: "its parameter count leaves bytes unread inside FILL_PARAMETERS",
416 });
417 }
418 check_location_filters(¶ms)?;
419 Ok(params)
420}
421
422/// Hold every LOCATION_FILTER and FILL_PARAMETERS parameter to the structure
423/// its own type names.
424///
425/// Applied on both sides. A value the decoder refuses is one the peer must
426/// close the session over, so writing it is a way to end a session rather than
427/// a way to ask for anything.
428///
429/// The two are checked together because `FILL_PARAMETERS` can carry a
430/// `LOCATION_FILTER` of its own, and a filter that is malformed one level down
431/// is exactly as malformed. [`decode_fill_parameters`] recurses back into this
432/// function for that reason; the nesting bottoms out because Table 6 does not
433/// list `FILL_PARAMETERS` inside itself.
434///
435/// The values are otherwise decoded and discarded. What is kept is the refusal
436/// — each stays on its parameter as the bytes that arrived, so a caller reads
437/// one through [`decode_location_filter`] or [`decode_fill_parameters`] when it
438/// wants the structure rather than the frame.
439fn check_location_filters(parameters: &[KeyValuePair]) -> Result<(), CodecError> {
440 for parameter in parameters {
441 let key = parameter.key.into_inner();
442 if key != LOCATION_FILTER && key != FILL_PARAMETERS {
443 continue;
444 }
445 match ¶meter.value {
446 KvpValue::Bytes(value) if key == LOCATION_FILTER => {
447 check_location_filter_fields(&decode_location_filter(value)?)?;
448 }
449 KvpValue::Bytes(value) => {
450 decode_fill_parameters(value)?;
451 }
452 // Unreachable from the decoder, which picks the shape from the type
453 // and finds both of these length-prefixed. A caller that built the
454 // pair in memory can still get here, and it is the same rule.
455 KvpValue::Varint(_) => {
456 return Err(CodecError::SubscriptionFilterMalformed {
457 detail: "its value is a bare varint where the type defines a structure",
458 });
459 }
460 }
461 }
462 Ok(())
463}
464
465/// Read one parameter's value in the shape its type names.
466///
467/// Shared by the message's own parameter block and by the nested block inside
468/// `FILL_PARAMETERS`, so a type cannot be read one way in a message and another
469/// way in a fill.
470fn decode_parameter_value(
471 encoding: ParamEncoding,
472 abs_key: u64,
473 buf: &mut impl Buf,
474) -> Result<KvpValue, CodecError> {
475 Ok(match encoding {
476 ParamEncoding::Varint => KvpValue::Varint(VarInt::decode_moqt::<Wire>(buf)?),
477 ParamEncoding::Uint8 => {
478 if buf.remaining() < 1 {
479 return Err(CodecError::UnexpectedEnd);
480 }
481 let byte = buf.get_u8();
482 if !uint8_value_in_range(abs_key, byte) {
483 return Err(CodecError::ParameterValueOutOfRange {
484 key: abs_key,
485 value: byte as u64,
486 });
487 }
488 KvpValue::Varint(VarInt::from_u64_moqt(byte as u64))
489 }
490 ParamEncoding::Location => {
491 let group = VarInt::decode_moqt::<Wire>(buf)?;
492 let object = VarInt::decode_moqt::<Wire>(buf)?;
493 let mut encoded = Vec::new();
494 group.encode_moqt::<Wire>(&mut encoded);
495 object.encode_moqt::<Wire>(&mut encoded);
496 KvpValue::Bytes(encoded)
497 }
498 ParamEncoding::LengthPrefixed => {
499 let len = VarInt::decode_moqt::<Wire>(buf)?.into_inner() as usize;
500 KvpValue::Bytes(read_bytes(buf, len)?)
501 }
502 ParamEncoding::TrackNamespaceValue => {
503 // A prefix of zero fields is legal: Section 2.4.1 puts a Track
504 // Namespace at "between 0 and 32 Track Namespace Fields", and
505 // an empty prefix matches every namespace.
506 let ns = TrackNamespace::decode_allow_empty_moqt::<Wire>(buf)?;
507 let mut encoded = Vec::new();
508 ns.encode_moqt::<Wire>(&mut encoded);
509 KvpValue::Bytes(encoded)
510 }
511 })
512}
513
514/// Decode a count-prefixed list of parameters with delta-encoded types.
515fn decode_parameters(buf: &mut impl Buf) -> Result<Vec<KeyValuePair>, CodecError> {
516 let count = VarInt::decode_moqt::<Wire>(buf)?.into_inner() as usize;
517 let mut params = crate::types::reserve_bounded(count, buf);
518 let mut prev_key: u64 = 0;
519
520 for i in 0..count {
521 let delta = VarInt::decode_moqt::<Wire>(buf)?.into_inner();
522 let abs_key = add_delta(prev_key, delta)?;
523 // Types ascend, so a repeat is always a zero delta against the
524 // parameter before it. Draft-20 Section 10.2: "Receivers SHOULD check
525 // that there are no unexpected duplicate parameters and close the
526 // session with PROTOCOL_VIOLATION if found." Downstream code that scans
527 // the list for a key takes whichever copy it meets first, so two
528 // implementations reading one frame can pick opposite values.
529 //
530 // "Unexpected" is what `parameter_may_repeat` reads: a zero delta on a
531 // type whose own definition permits repeats is the second instance,
532 // which is the only encoding such an instance has.
533 if i > 0 && delta == 0 && !parameter_may_repeat(abs_key) {
534 return Err(CodecError::DuplicateParameter(abs_key));
535 }
536 prev_key = abs_key;
537
538 // Section 10.2: "All Message Parameters MUST be defined in the
539 // negotiated version of MOQT or negotiated via Setup Options. An
540 // endpoint that receives an unknown Message Parameter MUST close the
541 // session with PROTOCOL_VIOLATION. Because the receiver has to
542 // understand every Message Parameter, there is no need for a mechanism
543 // to skip unknown parameters." Because unknown parameters
544 // cannot be skipped, the block is bounded by a parameter count rather
545 // than a length.
546 //
547 // The table this consults is the registry's, so a type it cannot name
548 // is one this draft does not define. Reporting it as an ordinary
549 // malformation, which is what it did before, left the rule enforced
550 // against the frame and invisible to the session.
551 let encoding =
552 param_encoding(abs_key).ok_or(CodecError::UnknownMessageParameter(abs_key))?;
553
554 let value = decode_parameter_value(encoding, abs_key, buf)?;
555
556 params.push(KeyValuePair { key: VarInt::from_u64_moqt(abs_key), value });
557 }
558 check_authorization_tokens(¶ms)?;
559 check_location_filters(¶ms)?;
560 Ok(params)
561}
562
563/// Whether `bytes` is exactly the wire form of a Location — two consecutive
564/// varints and nothing after them.
565///
566/// `decode_parameters` builds this value by reading two varints and
567/// re-serialising them, so every value it produces satisfies this. A value
568/// built in memory need not, and the encode arm writes these bytes verbatim
569/// because a Location carries no length of its own. Without this check a
570/// caller could hand over one varint, or three, and the codec would put a
571/// frame on the wire that its own decoder answers with an error.
572fn is_location_value(bytes: &[u8]) -> bool {
573 let mut buf = bytes;
574 VarInt::decode_moqt::<Wire>(&mut buf).is_ok()
575 && VarInt::decode_moqt::<Wire>(&mut buf).is_ok()
576 && !buf.has_remaining()
577}
578
579/// Whether `bytes` is exactly the wire form of a Track Namespace, with
580/// nothing after it. The same reasoning as [`is_location_value`]: the value
581/// goes out verbatim, so it has to be something this draft can read back.
582fn is_track_namespace_value(bytes: &[u8]) -> bool {
583 let mut buf = bytes;
584 TrackNamespace::decode_allow_empty_moqt::<Wire>(&mut buf).is_ok() && !buf.has_remaining()
585}
586
587/// Encode a count-prefixed list of parameters with delta-encoded types.
588///
589/// Errors with [`CodecError::InvalidField`] on a uint8-valued parameter whose
590/// value [`decode_parameters`] would refuse, so the two directions accept the
591/// same set of frames.
592///
593/// The check is not a mirror added for tidiness. A uint8 parameter's value is
594/// written as one octet, and a value that does not fit one is otherwise
595/// truncated to its low byte: GROUP_ORDER 258 becomes the byte 0x02, which is
596/// Descending — a well-formed frame carrying a value the caller never asked
597/// for, and one no receiver could tell from a genuine Descending. Refusing is
598/// the only outcome that does not silently rewrite the message.
599///
600/// The two structure rules are here for a plainer reason. A value under a type
601/// that defines a structure and is not that structure — a Token, a filter — is
602/// one the receiver must close the session over, so writing it is not a way to
603/// send it; the sender's first sign of trouble would be the session going.
604fn encode_parameters(params: &[KeyValuePair], buf: &mut impl BufMut) -> Result<(), CodecError> {
605 check_authorization_tokens(params)?;
606 check_location_filters(params)?;
607 VarInt::from_usize(params.len()).encode_moqt::<Wire>(buf);
608 let mut prev_key: u64 = 0;
609
610 for (i, p) in params.iter().enumerate() {
611 let abs_key = p.key.into_inner();
612 // The delta is a difference, so a descending pair wraps the subtraction
613 // into a nine-byte delta the peer resolves to an unrelated key, and a
614 // repeated type is a frame `decode_parameters` refuses. Both are
615 // refused here so the two directions accept the same set of frames.
616 let delta = abs_key
617 .checked_sub(prev_key)
618 .ok_or(CodecError::ParametersOutOfOrder(prev_key, abs_key))?;
619 if i > 0 && delta == 0 && !parameter_may_repeat(abs_key) {
620 return Err(CodecError::DuplicateParameter(abs_key));
621 }
622 prev_key = abs_key;
623 VarInt::from_u64_moqt(delta).encode_moqt::<Wire>(buf);
624
625 // The same maximum the decoder below applies, and the same one this
626 // draft's Setup Option encoder has always applied: "The maximum length
627 // of a value is 2^16-1 bytes. If an endpoint receives a length larger
628 // than the maximum, it MUST close the session with a PROTOCOL_VIOLATION."
629 // A value past it is one the peer must end the session over, so writing
630 // it is not a way to send it.
631 //
632 // Hoisted above the shape table rather than repeated inside it: a
633 // Location is bytes as well, and one past the maximum is not a Location.
634 if let KvpValue::Bytes(b) = &p.value {
635 if b.len() > MAX_KVP_VALUE_LEN {
636 return Err(KvpError::ValueTooLong(b.len()).into());
637 }
638 }
639
640 let encoding = param_encoding(abs_key);
641 match (&p.value, encoding) {
642 (KvpValue::Varint(v), Some(ParamEncoding::Varint)) => {
643 v.encode_moqt::<Wire>(buf);
644 }
645 (KvpValue::Varint(v), Some(ParamEncoding::Uint8)) => {
646 let raw = v.into_inner();
647 let byte = u8::try_from(raw).map_err(|_| CodecError::InvalidField)?;
648 if !uint8_value_in_range(abs_key, byte) {
649 return Err(CodecError::ParameterValueOutOfRange {
650 key: abs_key,
651 value: byte as u64,
652 });
653 }
654 buf.put_u8(byte);
655 }
656 // Both values are already stored in their own wire form — two
657 // varints for a Location, a field count and its fields for a Track
658 // Namespace — so they go out as they are. Adding a length here is
659 // the bug these arms exist to avoid.
660 (KvpValue::Bytes(b), Some(ParamEncoding::Location)) => {
661 if !is_location_value(b) {
662 return Err(CodecError::InvalidField);
663 }
664 buf.put_slice(b);
665 }
666 (KvpValue::Bytes(b), Some(ParamEncoding::TrackNamespaceValue)) => {
667 if !is_track_namespace_value(b) {
668 return Err(CodecError::InvalidField);
669 }
670 buf.put_slice(b);
671 }
672 (KvpValue::Bytes(b), Some(ParamEncoding::LengthPrefixed)) => {
673 VarInt::from_usize(b.len()).encode_moqt::<Wire>(buf);
674 buf.put_slice(b);
675 }
676 _ => {
677 // Fallback: encode as KVP even/odd
678 match &p.value {
679 KvpValue::Varint(v) => v.encode_moqt::<Wire>(buf),
680 KvpValue::Bytes(b) => {
681 VarInt::from_usize(b.len()).encode_moqt::<Wire>(buf);
682 buf.put_slice(b);
683 }
684 }
685 }
686 }
687 }
688 Ok(())
689}
690
691/// Decode delta-encoded KVPs with even/odd convention (for setup options
692/// and track properties). Read until buffer is exhausted.
693fn decode_kvp_delta(buf: &mut impl Buf) -> Result<Vec<KeyValuePair>, CodecError> {
694 let mut pairs = Vec::new();
695 let mut prev_key: u64 = 0;
696
697 while buf.has_remaining() {
698 let delta = VarInt::decode_moqt::<Wire>(buf)?.into_inner();
699 let abs_key = add_delta(prev_key, delta)?;
700 prev_key = abs_key;
701
702 let value = if abs_key.is_multiple_of(2) {
703 let v = VarInt::decode_moqt::<Wire>(buf)?;
704 KvpValue::Varint(v)
705 } else {
706 let len = VarInt::decode_moqt::<Wire>(buf)?.into_inner() as usize;
707 // Draft-20 Section 1.4.3: "The maximum length of a value is 2^16-1
708 // bytes. If an endpoint receives a length larger than the maximum,
709 // it MUST close the session with a PROTOCOL_VIOLATION." The
710 // standalone `KeyValuePair::decode` already enforces this; stating
711 // it here too means the two readers of the same wire shape answer
712 // the same way, rather than this one leaning on the caller having
713 // clipped the buffer to a control message first.
714 if len > MAX_KVP_VALUE_LEN {
715 return Err(KvpError::ValueTooLong(len).into());
716 }
717 let data = read_bytes(buf, len)?;
718 KvpValue::Bytes(data)
719 };
720
721 pairs.push(KeyValuePair { key: VarInt::from_u64_moqt(abs_key), value });
722 }
723 Ok(pairs)
724}
725
726/// Encode delta-encoded KVPs with even/odd convention.
727///
728/// Refuses a list that is not in ascending order by type, for the same reason
729/// [`encode_parameters`] does: the delta is a difference, and a descending pair
730/// wraps it into a nine-byte delta the peer resolves to an unrelated key.
731fn encode_kvp_delta(pairs: &[KeyValuePair], buf: &mut impl BufMut) -> Result<(), CodecError> {
732 let mut prev_key: u64 = 0;
733 for p in pairs {
734 let abs_key = p.key.into_inner();
735 let delta = abs_key
736 .checked_sub(prev_key)
737 .ok_or(CodecError::ParametersOutOfOrder(prev_key, abs_key))?;
738 prev_key = abs_key;
739 VarInt::from_u64_moqt(delta).encode_moqt::<Wire>(buf);
740 match &p.value {
741 KvpValue::Varint(v) => v.encode_moqt::<Wire>(buf),
742 KvpValue::Bytes(b) => {
743 if b.len() > MAX_KVP_VALUE_LEN {
744 return Err(KvpError::ValueTooLong(b.len()).into());
745 }
746 VarInt::from_usize(b.len()).encode_moqt::<Wire>(buf);
747 buf.put_slice(b);
748 }
749 }
750 }
751 Ok(())
752}
753
754/// Immutable Properties, Property Type 0xB.
755///
756/// Section 12.7: Immutable Properties are "a Track or Object Property that
757/// contains a sequence of Key-Value-Pairs (see Figure 2) that are themselves
758/// Track or Object Properties, respectively". The Type is odd, so its value is
759/// length-prefixed bytes, and those bytes are another delta-typed run starting
760/// from 0.
761const IMMUTABLE_PROPERTIES: u64 = 0x0B;
762
763/// Whether `value` is inside the range draft-20 allows for a Track Property
764/// type that restricts one.
765///
766/// Two types do, and each answers anything outside its range with a session
767/// close. DEFAULT_PUBLISHER_GROUP_ORDER (0x22), Section 12.5: "The allowed
768/// values are Ascending (0x1) or Descending (0x2). If an endpoint receives a
769/// value outside this range, it MUST close the session with
770/// PROTOCOL_VIOLATION." DYNAMIC_GROUPS (0x30), Section 12.6: "The allowed
771/// values are 0 or 1... If an endpoint receives a value larger than 1, it MUST
772/// close the session with PROTOCOL_VIOLATION."
773///
774/// Both are Track Properties, so the list they arrive in is the one carried by
775/// a control message rather than the properties on an object.
776///
777/// DEFAULT_PUBLISHER_PRIORITY (0x0E) is not here. Section 12.4 says
778/// "Priorities above 255 are invalid" and stops, where the two above name a
779/// consequence in the next clause. A range stated without one is not a close.
780///
781/// The numbers belong to the Property registry and not the Message Parameter
782/// one. Type 0x22 is GROUP_ORDER as a parameter and
783/// DEFAULT_PUBLISHER_GROUP_ORDER as a property, and the two happen to permit the
784/// same pair of values while meaning different things — one subscriber's
785/// preference against a property of the track. Reading either table for the
786/// other's types would be right by accident here and wrong at the next entry.
787fn track_property_value_in_range(key: u64, value: u64) -> bool {
788 match key {
789 // DEFAULT_PUBLISHER_GROUP_ORDER (0x22)
790 0x22 => value == 1 || value == 2,
791 // DYNAMIC_GROUPS (0x30)
792 0x30 => value <= 1,
793 _ => true,
794 }
795}
796
797/// Refuse a Track Property whose value falls outside the range its type allows,
798/// wherever in the list it is carried.
799///
800/// # Inside Immutable Properties as well as beside them
801///
802/// The list is walked one level down through Immutable Properties, whose
803/// contents Section 12.7 defines as properties themselves. The draft asks for
804/// this in as many words: "When looking for the value of a property, processors
805/// MUST search both the mutable properties and the contents of Immutable
806/// Properties." A check applied only to the outer list is one a peer opts out of
807/// by moving a pair inside the block, and the block is where an Original
808/// Publisher puts what a relay must not rewrite — which is where a track's group
809/// order and dynamic-group support belong.
810///
811/// Bytes under 0xB that do not parse as a Key-Value-Pair run are left alone
812/// rather than refused. Section 12.7 says relays "MAY decode and view the
813/// Properties in the Key-Value-Pairs", which is a permission and not a
814/// requirement, so a block this codec cannot read is carried to the caller
815/// intact instead of ending the session.
816fn check_track_property_values(properties: &[KeyValuePair]) -> Result<(), CodecError> {
817 for property in properties {
818 let key = property.key.into_inner();
819 match &property.value {
820 KvpValue::Varint(value) => {
821 let value = value.into_inner();
822 if !track_property_value_in_range(key, value) {
823 return Err(CodecError::TrackPropertyValueOutOfRange { key, value });
824 }
825 }
826 KvpValue::Bytes(bytes) if key == IMMUTABLE_PROPERTIES => {
827 let mut inner = &bytes[..];
828 // A block that is not a Key-Value-Pair run is skipped rather
829 // than refused. See the note above: reading inside it is a
830 // permission, so one that cannot be read is carried.
831 //
832 // Skipped means this block and only this block. The rule the
833 // draft states here is about the block whose pairs will not
834 // parse, and says nothing about its neighbours; ending the
835 // whole walk would let a peer keep an out-of-range property
836 // from being looked at by putting an unparseable block in
837 // front of it.
838 if let Ok(nested) = decode_kvp_delta(&mut inner) {
839 check_track_property_values(&nested)?;
840 }
841 }
842 KvpValue::Bytes(_) => {}
843 }
844 }
845 Ok(())
846}
847
848/// Decode the Track Properties that fill the tail of a control message.
849///
850/// [`decode_kvp_delta`] with the Property registry's value rules applied. The
851/// two are separate because that function also reads Setup Options, which are a
852/// third namespace numbering its entries independently of this one.
853fn decode_track_properties(buf: &mut impl Buf) -> Result<Vec<KeyValuePair>, CodecError> {
854 let properties = decode_kvp_delta(buf)?;
855 check_track_property_values(&properties)?;
856 Ok(properties)
857}
858
859/// Encode a control message's Track Properties.
860///
861/// Held to the same value ranges as the decoder. A value this codec refuses to
862/// read is one it must not write: the peer that receives it is required to close
863/// the session, so the sender's first sign of trouble would be the session
864/// going.
865fn encode_track_properties(
866 properties: &[KeyValuePair],
867 buf: &mut impl BufMut,
868) -> Result<(), CodecError> {
869 check_track_property_values(properties)?;
870 encode_kvp_delta(properties, buf)
871}
872
873/// The Setup Option types this draft defines.
874///
875/// Section 10.3.1 assigns PATH, AUTHORIZATION TOKEN, MAX_AUTH_TOKEN_CACHE_SIZE, AUTHORITY,
876/// MAX_FILTER_RANGES, MOQT_IMPLEMENTATION and MAX_REQUEST_UPDATES.
877///
878/// The list exists for one rule and one direction. Section 10.3: "Receivers
879/// MUST allow duplicates of unknown Setup Options." A receiver may therefore
880/// refuse a repeat only of a type it can name, and an option outside this list
881/// is one an extension defined and this codec has no business closing a session
882/// over. Nothing else reads it - unknown options are still decoded and carried,
883/// as "Receivers MUST ignore unrecognized Setup Options" requires.
884const KNOWN_SETUP_OPTIONS: &[u64] = &[0x01, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08];
885
886/// The one Setup Option whose definition allows more than one instance.
887///
888/// Section 10.3.1.4: "The AUTHORIZATION TOKEN Setup Option (Option Type 0x03)
889/// is functionally equivalent to the AUTHORIZATION TOKEN message parameter...
890/// The endpoint can specify one or more tokens in SETUP that the peer can use to
891/// authorize MOQT session establishment." That is the "unless the option
892/// definition explicitly allows multiple instances" carve-out, and it is the
893/// only one on this draft.
894const REPEATABLE_SETUP_OPTION: u64 = 0x03;
895
896/// Decode the Setup Options of a SETUP message.
897///
898/// Section 10.3: "Senders MUST NOT repeat the same Option Type in a message
899/// unless the option definition explicitly allows multiple instances. Receivers
900/// MUST allow duplicates of unknown Setup Options."
901///
902/// The second sentence is why this is not the mirror of
903/// [`encode_setup_options`]: a repeat of a type this draft names is refused, and
904/// a repeat of any other type is carried. Types ascend and are delta-encoded, so
905/// a repeat is always a zero delta against the option before it.
906fn decode_setup_options(buf: &mut impl Buf) -> Result<Vec<KeyValuePair>, CodecError> {
907 let options = decode_kvp_delta(buf)?;
908 for (i, option) in options.iter().enumerate() {
909 let key = option.key.into_inner();
910 if key == REPEATABLE_SETUP_OPTION || !KNOWN_SETUP_OPTIONS.contains(&key) {
911 continue;
912 }
913 if options[..i].iter().any(|earlier| earlier.key == option.key) {
914 return Err(CodecError::DuplicateParameter(key));
915 }
916 }
917 check_authorization_tokens(&options)?;
918 Ok(options)
919}
920
921/// Encode the Setup Options of a SETUP message.
922///
923/// The sender's half of the same sentence, and it is the wider half: "Senders
924/// MUST NOT repeat the same Option Type in a message" names no exception for
925/// types the sender does not recognise, so every repeat is refused here except
926/// the one the draft allows. A caller holding an option this codec has never
927/// heard of still may not send it twice.
928///
929/// The token is in this namespace as well, and is held to its structure here for
930/// the reason [`encode_parameters`] gives.
931fn encode_setup_options(options: &[KeyValuePair], buf: &mut impl BufMut) -> Result<(), CodecError> {
932 check_authorization_tokens(options)?;
933 for (i, option) in options.iter().enumerate() {
934 if option.key.into_inner() == REPEATABLE_SETUP_OPTION {
935 continue;
936 }
937 if options[..i].iter().any(|earlier| earlier.key == option.key) {
938 return Err(CodecError::DuplicateParameter(option.key.into_inner()));
939 }
940 }
941 encode_kvp_delta(options, buf)
942}
943
944// ============================================================
945// Message Types
946// ============================================================
947
948#[derive(Debug, Clone, Copy, PartialEq, Eq)]
949#[repr(u64)]
950pub enum MessageType {
951 RequestUpdate = 0x02,
952 Subscribe = 0x03,
953 SubscribeOk = 0x04,
954 RequestError = 0x05,
955 PublishNamespace = 0x06,
956 /// REQUEST_OK (0x07). Draft-20 Section 10.5 uses PUBLISH_OK as a shorthand
957 /// for a REQUEST_OK sent in response to a PUBLISH.
958 RequestOk = 0x07,
959 Namespace = 0x08,
960 PublishDone = 0x0B,
961 TrackStatus = 0x0D,
962 NamespaceDone = 0x0E,
963 PublishSkipped = 0x0F,
964 GoAway = 0x10,
965 Fetch = 0x16,
966 FetchOk = 0x18,
967 Publish = 0x1D,
968 /// PUBLISH_STATE_NOTIFY (0x22), new in draft-20 (Section 10.10).
969 PublishStateNotify = 0x22,
970 /// SUBSCRIBE_NAMESPACE (renumbered to 0x50 in draft-18).
971 SubscribeNamespace = 0x50,
972 /// SUBSCRIBE_TRACKS (new message in draft-18).
973 SubscribeTracks = 0x51,
974 Setup = 0x2F00,
975}
976
977impl MessageType {
978 pub fn from_id(id: u64) -> Option<Self> {
979 match id {
980 0x02 => Some(MessageType::RequestUpdate),
981 0x03 => Some(MessageType::Subscribe),
982 0x04 => Some(MessageType::SubscribeOk),
983 0x05 => Some(MessageType::RequestError),
984 0x06 => Some(MessageType::PublishNamespace),
985 0x07 => Some(MessageType::RequestOk),
986 0x08 => Some(MessageType::Namespace),
987 0x0B => Some(MessageType::PublishDone),
988 0x0D => Some(MessageType::TrackStatus),
989 0x0E => Some(MessageType::NamespaceDone),
990 0x0F => Some(MessageType::PublishSkipped),
991 0x10 => Some(MessageType::GoAway),
992 0x16 => Some(MessageType::Fetch),
993 0x18 => Some(MessageType::FetchOk),
994 0x1D => Some(MessageType::Publish),
995 0x22 => Some(MessageType::PublishStateNotify),
996 0x50 => Some(MessageType::SubscribeNamespace),
997 0x51 => Some(MessageType::SubscribeTracks),
998 0x2F00 => Some(MessageType::Setup),
999 _ => None,
1000 }
1001 }
1002
1003 pub fn id(&self) -> u64 {
1004 *self as u64
1005 }
1006
1007 /// This type's name in the shared vector corpus: the `message_type` its
1008 /// draft's `codec/messages/*.json` files carry, in `snake_case`.
1009 pub fn name(&self) -> &'static str {
1010 match self {
1011 MessageType::RequestUpdate => "request_update",
1012 MessageType::Subscribe => "subscribe",
1013 MessageType::SubscribeOk => "subscribe_ok",
1014 MessageType::RequestError => "request_error",
1015 MessageType::PublishNamespace => "publish_namespace",
1016 MessageType::RequestOk => "request_ok",
1017 MessageType::Namespace => "namespace",
1018 MessageType::PublishDone => "publish_done",
1019 MessageType::TrackStatus => "track_status",
1020 MessageType::NamespaceDone => "namespace_done",
1021 MessageType::PublishSkipped => "publish_skipped",
1022 MessageType::GoAway => "goaway",
1023 MessageType::Fetch => "fetch",
1024 MessageType::FetchOk => "fetch_ok",
1025 MessageType::Publish => "publish",
1026 MessageType::PublishStateNotify => "publish_state_notify",
1027 MessageType::SubscribeNamespace => "subscribe_namespace",
1028 MessageType::SubscribeTracks => "subscribe_tracks",
1029 MessageType::Setup => "setup",
1030 }
1031 }
1032}
1033
1034// ============================================================
1035// Session Lifecycle Messages
1036// ============================================================
1037
1038/// Unified SETUP (0x2F00).
1039#[derive(Debug, Clone, PartialEq, Eq)]
1040pub struct Setup {
1041 pub options: Vec<KeyValuePair>,
1042}
1043
1044/// GOAWAY (0x10). Draft-20's GOAWAY has no Request ID field, so the
1045/// control-stream and request-stream forms are identical on the wire.
1046/// Draft-18 is the one draft that carries the field, and only when the
1047/// message is sent on the control stream.
1048#[derive(Debug, Clone, PartialEq, Eq)]
1049pub struct GoAway {
1050 pub new_session_uri: Vec<u8>,
1051 pub timeout: VarInt,
1052}
1053
1054// ============================================================
1055// Consolidated Response Messages
1056// ============================================================
1057
1058/// REQUEST_OK (0x07). Used as a generic OK response and as the alias for
1059/// PUBLISH_OK / REQUEST_UPDATE_OK / TRACK_STATUS_OK / SUBSCRIBE_NAMESPACE_OK
1060/// / PUBLISH_NAMESPACE_OK.
1061///
1062/// `track_properties` is only populated for TRACK_STATUS_OK; for every
1063/// other shape it MUST be empty (length implicit from the message length).
1064#[derive(Debug, Clone, PartialEq, Eq)]
1065pub struct RequestOk {
1066 pub parameters: Vec<KeyValuePair>,
1067 pub track_properties: Vec<KeyValuePair>,
1068}
1069
1070/// Optional Redirect structure carried in REQUEST_ERROR with code 0x34.
1071#[derive(Debug, Clone, PartialEq, Eq)]
1072pub struct Redirect {
1073 pub connect_uri: Vec<u8>,
1074 pub track_namespace: TrackNamespace,
1075 pub track_name: Vec<u8>,
1076}
1077
1078/// REQUEST_ERROR (0x05). Adds an optional Redirect structure when
1079/// `error_code` is REDIRECT (0x34).
1080#[derive(Debug, Clone, PartialEq, Eq)]
1081pub struct RequestError {
1082 pub error_code: VarInt,
1083 pub retry_interval: VarInt,
1084 pub reason_phrase: Vec<u8>,
1085 pub redirect: Option<Redirect>,
1086}
1087
1088/// REQUEST_ERROR error codes with dedicated meaning.
1089///
1090/// Drafts 16 through 18 define DUPLICATE_SUBSCRIPTION (0x19) among these
1091/// codes; drafts 19 and 20 do not, because Section 5.1 lets an endpoint hold
1092/// multiple concurrent subscriptions to the same Track, each under its own
1093/// Request ID.
1094pub mod request_error_codes {
1095 /// A Mandatory Track Property the receiver does not understand.
1096 pub const UNSUPPORTED_EXTENSION: u64 = 0x33;
1097 /// Response carries a [`super::Redirect`] structure.
1098 pub const REDIRECT: u64 = 0x34;
1099 /// New in draft-20: SUBSCRIBE_TRACKS filter parameters conflict among too
1100 /// many subscribers to aggregate the subscription upstream.
1101 pub const CONFLICTING_FILTERS: u64 = 0x35;
1102 /// New in draft-20: a Range Filter parameter is invalid or exceeds
1103 /// MAX_FILTER_RANGES.
1104 pub const INVALID_FILTER: u64 = 0x36;
1105}
1106
1107// ============================================================
1108// Subscribe Messages
1109// ============================================================
1110
1111#[derive(Debug, Clone, PartialEq, Eq)]
1112pub struct Subscribe {
1113 pub request_id: VarInt,
1114 pub track_namespace: TrackNamespace,
1115 pub track_name: Vec<u8>,
1116 pub parameters: Vec<KeyValuePair>,
1117}
1118
1119/// SUBSCRIBE_OK (0x04).
1120#[derive(Debug, Clone, PartialEq, Eq)]
1121pub struct SubscribeOk {
1122 pub track_alias: VarInt,
1123 pub parameters: Vec<KeyValuePair>,
1124 pub track_properties: Vec<KeyValuePair>,
1125}
1126
1127#[derive(Debug, Clone, PartialEq, Eq)]
1128pub struct RequestUpdate {
1129 pub request_id: VarInt,
1130 pub parameters: Vec<KeyValuePair>,
1131}
1132
1133// ============================================================
1134// Publish Messages
1135// ============================================================
1136
1137#[derive(Debug, Clone, PartialEq, Eq)]
1138pub struct Publish {
1139 pub request_id: VarInt,
1140 pub track_namespace: TrackNamespace,
1141 pub track_name: Vec<u8>,
1142 pub track_alias: VarInt,
1143 pub parameters: Vec<KeyValuePair>,
1144 pub track_properties: Vec<KeyValuePair>,
1145}
1146
1147/// PUBLISH_DONE (0x0B). The wire layout is unchanged from draft-19; what
1148/// draft-20 changed is the `Stream Count` sentinel, what the count includes,
1149/// and the removal of status code 0x3.
1150#[derive(Debug, Clone, PartialEq, Eq)]
1151pub struct PublishDone {
1152 /// The reason the publisher is ending the subscription.
1153 ///
1154 /// Not validated against the registry, on decode or on encode, and that is
1155 /// the draft's instruction rather than an omission. Draft-20 Section 14:
1156 /// "Receipt of an unknown error code in any error context (Session
1157 /// Termination, REQUEST_ERROR, PUBLISH_DONE, or Data Stream Reset) MUST be
1158 /// treated as equivalent to INTERNAL_ERROR for that context. An endpoint
1159 /// MUST NOT close the session because it received an unknown error code in
1160 /// a REQUEST_ERROR or PUBLISH_DONE." Refusing the frame would take that
1161 /// choice away from the caller, so an unassigned code is carried up and
1162 /// [`super::error_codes::PublishDoneStatusCode::from_u64`] answers `None`
1163 /// for it.
1164 ///
1165 /// That reaches 0x3 in particular. Draft-19 assigned it to
1166 /// `SUBSCRIPTION_ENDED`; draft-20 removed the row and the behaviour behind
1167 /// it together (Section 5.1.2: "A publisher does not end a subscription
1168 /// solely because the Largest Object advances past the end of the current
1169 /// Location Filter"). A draft-20 receiver reads a 0x3 as INTERNAL_ERROR.
1170 pub status_code: VarInt,
1171 /// The number of streams the publisher opened for this subscription.
1172 ///
1173 /// Draft-20 Section 10.12 widens what is counted: the total now includes
1174 /// "streams that contained no Objects (e.g., an empty Subgroup) and
1175 /// including any fill fetch streams (see Section 5.1.3)". Draft-19 counted
1176 /// no fill streams because it had none.
1177 ///
1178 /// See [`publish_done_codes::STREAM_COUNT_UNKNOWN`] for the sentinel.
1179 pub stream_count: VarInt,
1180 pub reason_phrase: Vec<u8>,
1181}
1182
1183/// Numeric values for the [`PublishDone`] fields.
1184pub mod publish_done_codes {
1185 /// Draft-18 onwards: TOO_FAR_BEHIND is 0x05 (was 0x06 in draft-17).
1186 pub const TOO_FAR_BEHIND: u64 = 0x05;
1187 /// Draft-18 onwards: EXPIRED is 0x06 (was 0x05 in draft-17).
1188 pub const EXPIRED: u64 = 0x06;
1189
1190 /// The value [`super::PublishDone::stream_count`] carries when the
1191 /// publisher cannot state an exact count.
1192 ///
1193 /// Draft-20 Section 10.12: "If the publisher is unable to set Stream Count
1194 /// to the exact number of streams opened for the subscription, it MUST set
1195 /// Stream Count to 2^64 - 1." Draft-19 said `2^62 - 1`, which is where the
1196 /// QUIC varint tops out; MoQT's own varint (Section 1.4.1) is a
1197 /// leading-ones-length prefix reaching a full 64 bits in nine bytes, so
1198 /// this value is encodable at all — as `ff` followed by eight `ff` bytes.
1199 ///
1200 /// **In draft-20 the sentinel is indistinguishable from a well-formed
1201 /// exact count.** Draft-19's `2^62 - 1` leaves headroom above the marker;
1202 /// there is none above this one, so a publisher that really opened
1203 /// `2^64 - 1` streams cannot say so and a receiver cannot tell the two
1204 /// apart. The draft does not remark on it. Not a practical problem, and
1205 /// worth knowing before writing a comparison against this constant.
1206 pub const STREAM_COUNT_UNKNOWN: u64 = u64::MAX;
1207}
1208
1209// ============================================================
1210// Publish Namespace Messages
1211// ============================================================
1212
1213#[derive(Debug, Clone, PartialEq, Eq)]
1214pub struct PublishNamespace {
1215 pub request_id: VarInt,
1216 pub track_namespace: TrackNamespace,
1217 pub parameters: Vec<KeyValuePair>,
1218}
1219
1220// ============================================================
1221// Namespace Messages
1222// ============================================================
1223
1224#[derive(Debug, Clone, PartialEq, Eq)]
1225pub struct Namespace {
1226 pub namespace_suffix: TrackNamespace,
1227}
1228
1229#[derive(Debug, Clone, PartialEq, Eq)]
1230pub struct NamespaceDone {
1231 pub namespace_suffix: TrackNamespace,
1232}
1233
1234// ============================================================
1235// Subscribe Namespace / Tracks Messages
1236// ============================================================
1237
1238/// SUBSCRIBE_NAMESPACE (0x50). Subscribes to NAMESPACE / NAMESPACE_DONE
1239/// advertisements for namespaces matching `namespace_prefix`. Only drafts 16
1240/// and 17 carry a `subscribe_options` varint here; on draft-20 a namespace
1241/// subscription only produces NAMESPACE / NAMESPACE_DONE.
1242#[derive(Debug, Clone, PartialEq, Eq)]
1243pub struct SubscribeNamespace {
1244 pub request_id: VarInt,
1245 pub namespace_prefix: TrackNamespace,
1246 pub parameters: Vec<KeyValuePair>,
1247}
1248
1249/// SUBSCRIBE_TRACKS (0x51, new in draft-18). Subscribes to PUBLISH messages
1250/// for tracks whose namespace matches `namespace_prefix`. Carries the FORWARD
1251/// parameter (Section 10.2.18), which on drafts 15 through 17 may appear on
1252/// SUBSCRIBE_NAMESPACE instead.
1253#[derive(Debug, Clone, PartialEq, Eq)]
1254pub struct SubscribeTracks {
1255 pub request_id: VarInt,
1256 pub namespace_prefix: TrackNamespace,
1257 pub parameters: Vec<KeyValuePair>,
1258}
1259
1260// ============================================================
1261// Track Status Messages
1262// ============================================================
1263
1264#[derive(Debug, Clone, PartialEq, Eq)]
1265pub struct TrackStatus {
1266 pub request_id: VarInt,
1267 pub track_namespace: TrackNamespace,
1268 pub track_name: Vec<u8>,
1269 pub parameters: Vec<KeyValuePair>,
1270}
1271
1272// ============================================================
1273// Fetch Messages
1274// ============================================================
1275
1276/// FETCH (0x16), rebuilt in draft-20 (Section 10.13, Figure 16).
1277///
1278/// ```text
1279/// FETCH Message {
1280/// Type (vi64) = 0x16,
1281/// Length (16),
1282/// Request ID (vi64),
1283/// Track Namespace (..),
1284/// Track Name Length (vi64),
1285/// Track Name (..),
1286/// Number of Parameters (vi64),
1287/// Parameters (..) ...
1288/// }
1289/// ```
1290///
1291/// # What went, and why draft-19's shape cannot be ported
1292///
1293/// Draft-19's FETCH opened with a `Fetch Type` that chose between a Standalone
1294/// Fetch — a namespace, a name and an inline `Start Location` / `End Location`
1295/// pair — and a Joining Fetch of two varints. Draft-20 deleted the field, both
1296/// structures, the Fetch Type registry and the whole joining mechanism, and
1297/// promoted the namespace and the name to fields of FETCH itself, in the
1298/// positions they hold inside draft-19's Standalone Fetch. What is left is
1299/// byte-identical to [`Subscribe`] apart from the type code.
1300///
1301/// The range now travels in the `LOCATION_FILTER` parameter (Section 5.1.2). A
1302/// FETCH with none covers `{0,0}` through Largest Object, inclusive.
1303///
1304/// # `INVALID_RANGE` and a relative start
1305///
1306/// Section 10.13 keeps draft-19's rule: "If no Objects have been published for
1307/// the track or Start Location is greater than the Largest Object" then "the
1308/// publisher MUST return REQUEST_ERROR with error code INVALID_RANGE". A
1309/// relative start —
1310/// the one-field `LOCATION_FILTER` with `StartGroup = 0`, which resolves to the
1311/// Next Group — is by construction greater than Largest Object, so read
1312/// literally the rule rejects every relative-start FETCH. That is plainly not
1313/// the intent and the text carves out nothing, so **this codec does not apply
1314/// the Start-greater-than-Largest test to a relative start**, and neither
1315/// should a caller. Nothing here can enforce either reading: the test needs
1316/// Largest Object, which is track state rather than anything in this frame, so
1317/// the decision belongs to the endpoint and is recorded here because this is
1318/// where the filter arrives.
1319///
1320/// **The codepoint did not change.** A draft-19 decoder fed one of these reads
1321/// the `Number of Track Namespace Fields` count as a `Fetch Type` and
1322/// mis-parses without complaint; there is no in-band version signal to catch
1323/// it. That is why draft-20 has a FETCH decoder of its own rather than sharing
1324/// draft-19's.
1325#[derive(Debug, Clone, PartialEq, Eq)]
1326pub struct Fetch {
1327 pub request_id: VarInt,
1328 pub track_namespace: TrackNamespace,
1329 pub track_name: Vec<u8>,
1330 pub parameters: Vec<KeyValuePair>,
1331}
1332
1333/// FETCH_OK (0x18). `end_of_track` is uint8.
1334///
1335/// Byte-identical to draft-19; the field that changed meaning is
1336/// [`FetchOk::end_object`].
1337#[derive(Debug, Clone, PartialEq, Eq)]
1338pub struct FetchOk {
1339 pub end_of_track: u8,
1340 pub end_group: VarInt,
1341 /// The Object ID of the **last Object the response covers**, inclusive.
1342 ///
1343 /// This is the silent off-by-one of the revision, and it is absent from
1344 /// draft-20's own change log. Draft-19 Section 10.13 defined the pair as
1345 /// "the end of the range covered by the FETCH response, using the same
1346 /// encoding as the FETCH request End Location (the last Object, plus 1; or
1347 /// 0 to indicate the entire Group)". Draft-20 Section 10.14 drops that
1348 /// parenthesis entirely, and Sections 5.1.2 and 10.13 both say the Location
1349 /// filter "specifies an inclusive range of Locations".
1350 ///
1351 /// So both draft-19 conventions are gone: there is no plus one, and an
1352 /// Object of 0 now means object 0 rather than the whole group. The bytes
1353 /// are identical between the two drafts and the meaning is not, and nothing
1354 /// on the wire distinguishes them — an encoder ported forward with its
1355 /// arithmetic intact fetches one object too many, and one whose end lands
1356 /// on object 0 fetches a single object where the same bytes cover a whole
1357 /// group on draft-19.
1358 ///
1359 /// **Ambiguous, and the draft leaves it so.** When the request's filter
1360 /// omitted `EndObject`, so the
1361 /// filter meant "all objects in the End Group", Section 10.14 does not say
1362 /// what to report — and with the `0`-means-whole-group encoding gone there
1363 /// is no way left to spell it. The same applies to a relative start. The
1364 /// reading this codec's corpus takes, and the only sane one, is the Object
1365 /// ID of the last Object actually covered; the draft does not say so, and
1366 /// nothing here can enforce it, because resolving it needs the track rather
1367 /// than the frame.
1368 pub end_object: VarInt,
1369 pub parameters: Vec<KeyValuePair>,
1370 pub track_properties: Vec<KeyValuePair>,
1371}
1372
1373// ============================================================
1374// Publish State Notify
1375// ============================================================
1376
1377/// PUBLISH_STATE_NOTIFY (0x22), new in draft-20 (Section 10.10, Figure 13).
1378///
1379/// ```text
1380/// PUBLISH_STATE_NOTIFY Message {
1381/// Type (vi64) = 0x22,
1382/// Length (16),
1383/// Number of Parameters (vi64),
1384/// Parameters (..) ...
1385/// }
1386/// ```
1387///
1388/// **There is no Request ID field.** The message is identified by the
1389/// subscription's bidirectional request stream it arrives on, the way
1390/// SUBSCRIBE_OK, PUBLISH_DONE and FETCH_OK are.
1391///
1392/// The rules a codec cannot check, because they are about the session rather
1393/// than the frame, and which the caller therefore owns (Section 10.10):
1394///
1395/// * it is sent by the **publisher only**, on a **subscription's** stream.
1396/// Receiving one for any other request type, or from the subscriber, MUST
1397/// close the session with a PROTOCOL_VIOLATION;
1398/// * it is **unilateral** — the receiver does not answer with REQUEST_OK or
1399/// REQUEST_ERROR — and it is not counted against the `MAX_REQUEST_UPDATES`
1400/// Setup Option;
1401/// * it carries only the parameters whose values changed, and an absent
1402/// parameter is unchanged;
1403/// * a publisher MUST NOT use it to change a subscriber-controlled parameter
1404/// unless the subscriber asked for the change;
1405/// * the publisher **MUST** include `LARGEST_OBJECT` (0x09) if known, so the
1406/// subscriber can locate the point in the track where the change took
1407/// effect. Nothing here enforces that: a missing required parameter is not
1408/// something this decoder detects, and a message that omits it is still a
1409/// well-formed frame.
1410#[derive(Debug, Clone, PartialEq, Eq)]
1411pub struct PublishStateNotify {
1412 pub parameters: Vec<KeyValuePair>,
1413}
1414
1415// ============================================================
1416// Publish Skipped
1417// ============================================================
1418
1419/// PUBLISH_SKIPPED (0x0F). Drafts 17 and 18 name this codepoint
1420/// PUBLISH_BLOCKED; the wire layout — track namespace suffix then track name —
1421/// is the same on all four drafts that carry the message.
1422#[derive(Debug, Clone, PartialEq, Eq)]
1423pub struct PublishSkipped {
1424 pub namespace_suffix: TrackNamespace,
1425 pub track_name: Vec<u8>,
1426}
1427
1428// ============================================================
1429// Unified Message Enum
1430// ============================================================
1431
1432#[derive(Debug, Clone, PartialEq, Eq)]
1433pub enum ControlMessage {
1434 Setup(Setup),
1435 GoAway(GoAway),
1436 RequestOk(RequestOk),
1437 RequestError(RequestError),
1438 Subscribe(Subscribe),
1439 SubscribeOk(SubscribeOk),
1440 RequestUpdate(RequestUpdate),
1441 Publish(Publish),
1442 PublishStateNotify(PublishStateNotify),
1443 PublishDone(PublishDone),
1444 PublishNamespace(PublishNamespace),
1445 Namespace(Namespace),
1446 NamespaceDone(NamespaceDone),
1447 SubscribeNamespace(SubscribeNamespace),
1448 SubscribeTracks(SubscribeTracks),
1449 TrackStatus(TrackStatus),
1450 Fetch(Fetch),
1451 FetchOk(FetchOk),
1452 PublishSkipped(PublishSkipped),
1453}
1454
1455// Draft-20 has no range check on a control message, and the absence is the
1456// draft's rather than an omission here.
1457//
1458// Draft-19 carried one: its FETCH held a `Start Location` and an `End Location`
1459// inline, and draft-19 Section 10.12.3 said "End Location MUST specify the
1460// same or a larger Location than Start Location for Standalone and Absolute
1461// Joining
1462// Fetches". Draft-20 deleted both fields with the rest of the FETCH rewrite
1463// (Section 10.13), so there is no pair left in any message to compare.
1464//
1465// What replaced them cannot express the malformation either. A `LOCATION_FILTER`
1466// (Section 5.1.2) states its end as an unsigned `EndGroupDelta` added to
1467// `StartGroup`, so the end group can never precede the start group; and within
1468// one group draft-20 states no rule about an `EndObject` below `StartObject`.
1469// Section 5.1.2 says the opposite for subscriptions — "A Location Filter on a
1470// subscription is always valid, even if it specifies a range entirely before
1471// Largest Object" — so refusing one would close sessions over a sentence that
1472// is not there.
1473//
1474// The one backwards-range rule draft-20 does keep is in Section 10.14: "If End
1475// Location is smaller than the Start Location in the corresponding FETCH the
1476// receiver MUST close the session with a PROTOCOL_VIOLATION." It compares a
1477// FETCH_OK against the FETCH it answers, which is session state and not
1478// anything one frame holds, so it belongs to the caller.
1479
1480/// Refuse a message whose discriminator disagrees with the fields beside it.
1481///
1482/// One draft-20 message carries a field that says which of the following fields
1483/// are on the wire: REQUEST_ERROR's Error Code, whose REDIRECT value (0x34) is
1484/// what puts the Redirect structure on the wire. This codec holds the
1485/// alternative in an `Option`, so a value can say one thing in its
1486/// discriminator and another in its body, and the two sides of the codec
1487/// resolve that differently — the encoder writes whatever the body holds, and
1488/// the decoder reads whatever the discriminator announces.
1489///
1490/// A REQUEST_ERROR with code REDIRECT and no Redirect body encodes to a message
1491/// that ends where the decoder expects a Connect URI length, so the peer reads
1492/// the redirect out of whatever follows or runs off the end. The mirror case is
1493/// quieter and no better: a Redirect body under any other error code is written
1494/// out and then skipped by a decoder that was never told to look for it, so the
1495/// sender believes it redirected a peer that never saw a redirect.
1496///
1497/// Draft-19 had a second discriminator here, FETCH's `Fetch Type`, choosing
1498/// between a standalone body and a joining pair. Draft-20 deleted the field and
1499/// both bodies (Section 10.13), so FETCH has nothing left to disagree with
1500/// itself about.
1501///
1502/// Refusing at the encoder keeps the two readings from ever diverging on the
1503/// wire.
1504fn check_discriminators(message: &ControlMessage) -> Result<(), CodecError> {
1505 // One arm, where drafts 17 to 19 have two. Written as an `if let` rather
1506 // than a one-armed `match` because that is what it now is; a second
1507 // discriminator would restore the `match`.
1508 if let ControlMessage::RequestError(m) = message {
1509 let code_is_redirect = m.error_code.into_inner() == request_error_codes::REDIRECT;
1510 if code_is_redirect != m.redirect.is_some() {
1511 return Err(CodecError::InvalidField);
1512 }
1513 }
1514 Ok(())
1515}
1516
1517/// Whether draft-20 lets Message Parameter `key` appear in `message`.
1518///
1519/// Section 10.2.1: "Each Message Parameter definition indicates the message
1520/// types in which it can appear. If it appears in some other type of message,
1521/// the receiving endpoint MUST close the connection with a PROTOCOL_VIOLATION."
1522/// One arm per entry in the Message Parameters registry (Section 15.7),
1523/// carrying the message types that entry's own definition names.
1524///
1525/// Four things about this draft the arms below fold in:
1526///
1527/// * Six of the names are one wire type. Section 10.5: "This document uses the
1528/// shorthand PUBLISH_OK, REQUEST_UPDATE_OK, TRACK_STATUS_OK,
1529/// SUBSCRIBE_NAMESPACE_OK, SUBSCRIBE_TRACKS_OK and PUBLISH_NAMESPACE_OK to
1530/// refer to a REQUEST_OK sent in response to the corresponding request type".
1531/// Which one a given REQUEST_OK is depends on the request its Request ID
1532/// answers, which is session state and not in the frame, so each of those
1533/// names widens the same arm and a REQUEST_OK is held to their union.
1534/// * The five Range Filters state their scope in Section 5.1.4 — draft-19's
1535/// Section 5.1.3 — rather than in their own subsections: the Track Property
1536/// filter "MAY appear multiple times in a SUBSCRIBE_TRACKS message or
1537/// REQUEST_UPDATE for it", and "all other filter parameters MAY appear
1538/// multiple times in a FETCH, SUBSCRIBE, SUBSCRIBE_TRACKS, or REQUEST_UPDATE
1539/// (on a subscription, from the subscriber only) message". Draft-19 listed
1540/// PUBLISH_OK in that second sentence and draft-20 removed it.
1541/// * SUBSCRIBE_TRACKS inherits SUBSCRIBE's whole set. Section 10.20.1 — the
1542/// renumbering of draft-19's 10.19.1 — keeps the sentence verbatim: "Any
1543/// Parameter that can be specified on a Subscription (ie: in SUBSCRIBE) is
1544/// valid in SUBSCRIBE_TRACKS, unless otherwise specified."
1545/// * **`PUBLISH_OK` is gone from six definitions.** `OBJECT_DELIVERY_TIMEOUT`
1546/// (0x02), `SUBGROUP_DELIVERY_TIMEOUT` (0x06), `FORWARD` (0x10),
1547/// `SUBSCRIBER_PRIORITY` (0x20), `LOCATION_FILTER` (0x21) and
1548/// `NEW_GROUP_REQUEST` (0x32) each dropped it, and several gained `PUBLISH`
1549/// instead; the Range Filters dropped it via Section 5.1.4. `EXPIRES` (0x08)
1550/// is the only parameter that still names it. A subscriber that wants to
1551/// change something now sends a REQUEST_UPDATE after the PUBLISH_OK, and
1552/// sending any of the six on a PUBLISH_OK is a Section 10.2.1 violation.
1553/// Because PUBLISH_OK and REQUEST_OK are one wire type, this table cannot
1554/// see the difference: `M::RequestOk` is admitted wherever any of the six OK
1555/// names is, so the practical effect here is that the six lose their
1556/// `M::RequestOk` arm entirely.
1557///
1558/// FETCH_OK has no arm in the table below, and that is the draft's doing rather
1559/// than an omission here: Section 10.14 gives it a Parameters field and no
1560/// parameter definition names it, so every type this draft defines is "some
1561/// other type of message" there.
1562///
1563/// PUBLISH_STATE_NOTIFY is admitted by exactly three parameters, and treating
1564/// that list as closed is **a decision this codec makes**. Section 10.10 says
1565/// only "The semantics of each parameter, including whether it may appear in
1566/// PUBLISH_STATE_NOTIFY, are defined by the parameter", and `LARGEST_OBJECT`
1567/// (0x09), `FORWARD` (0x10) and `LOCATION_FILTER` (0x21) are the three whose
1568/// definitions name it. The draft implies the closure and never states it, so
1569/// anything else there is refused under Section 10.2.1 on that reading.
1570///
1571/// The table decides scope only. A type this draft does not define has no scope
1572/// to be outside of and is answered by [`CodecError::UnknownMessageParameter`],
1573/// which is why the final arm carries rather than refuses.
1574pub fn parameter_in_scope(key: u64, message: MessageType) -> bool {
1575 use MessageType as M;
1576 // Section 10.20.1 makes SUBSCRIBE_TRACKS a superset of SUBSCRIBE, so every
1577 // arm admitting one admits the other. The arms spell both out rather than
1578 // wrapping the call, so each still reads against its own sentence.
1579 match key {
1580 // Section 10.2.4 OBJECT_DELIVERY_TIMEOUT: "It MAY appear in a
1581 // SUBSCRIBE, PUBLISH, or REQUEST_UPDATE message." Draft-19 said
1582 // PUBLISH_OK where this says PUBLISH.
1583 0x02 => {
1584 matches!(message, M::Subscribe | M::Publish | M::RequestUpdate | M::SubscribeTracks)
1585 }
1586 // Section 10.2.2 AUTHORIZATION TOKEN: "It MAY appear in a PUBLISH,
1587 // SUBSCRIBE, REQUEST_UPDATE, SUBSCRIBE_NAMESPACE, SUBSCRIBE_TRACKS,
1588 // PUBLISH_NAMESPACE, TRACK_STATUS or FETCH message." Unchanged from
1589 // draft-19; what draft-20 added is the sentence after it, "This
1590 // Parameter MUST NOT be copied from a SUBSCRIBE_TRACKS to the resulting
1591 // PUBLISH message Parameters", which is a rule about two messages and
1592 // so belongs to the caller rather than to this table.
1593 0x03 => matches!(
1594 message,
1595 M::Publish
1596 | M::Subscribe
1597 | M::RequestUpdate
1598 | M::SubscribeNamespace
1599 | M::SubscribeTracks
1600 | M::PublishNamespace
1601 | M::TrackStatus
1602 | M::Fetch
1603 ),
1604 // Section 10.2.6 RENDEZVOUS TIMEOUT: it "MAY appear in a SUBSCRIBE
1605 // message".
1606 0x04 => matches!(message, M::Subscribe | M::SubscribeTracks),
1607 // Section 10.2.3 SUBGROUP_DELIVERY_TIMEOUT: "It MAY appear in a
1608 // SUBSCRIBE, PUBLISH, or REQUEST_UPDATE message." Draft-19 said
1609 // PUBLISH_OK where this says PUBLISH.
1610 0x06 => {
1611 matches!(message, M::Subscribe | M::Publish | M::RequestUpdate | M::SubscribeTracks)
1612 }
1613 // Section 10.2.16 EXPIRES: "It MAY appear in SUBSCRIBE_OK, PUBLISH,
1614 // PUBLISH_OK, SUBSCRIBE_NAMESPACE_OK, SUBSCRIBE_TRACKS_OK,
1615 // PUBLISH_NAMESPACE_OK, or REQUEST_UPDATE_OK." Five of those seven are
1616 // a REQUEST_OK. The one parameter that still names PUBLISH_OK.
1617 0x08 => matches!(message, M::SubscribeOk | M::Publish | M::RequestOk),
1618 // Section 10.2.17 LARGEST OBJECT: "It MAY appear in SUBSCRIBE_OK,
1619 // PUBLISH, REQUEST_UPDATE_OK, TRACK_STATUS_OK, or
1620 // PUBLISH_STATE_NOTIFY." The last is new in draft-20.
1621 0x09 => {
1622 matches!(message, M::SubscribeOk | M::Publish | M::RequestOk | M::PublishStateNotify)
1623 }
1624 // Section 10.2.5 FILL TIMEOUT: it "MAY appear in a FETCH message, or
1625 // inside a FILL_PARAMETERS parameter (see Section 10.2.15) in a
1626 // SUBSCRIBE or REQUEST_UPDATE (for a subscription), where it applies to
1627 // the fill fetch stream." The nested half is not a scope this table can
1628 // answer — a nested parameter is not in the enclosing message at all,
1629 // per Section 10.2.15 — so it is enforced by
1630 // [`decode_fill_parameters`] against Table 6 instead.
1631 0x0A => matches!(message, M::Fetch),
1632 // Section 10.2.18 FORWARD: "It MAY appear in SUBSCRIBE, REQUEST_UPDATE
1633 // (for a subscription or a SUBSCRIBE_TRACKS request), PUBLISH,
1634 // SUBSCRIBE_TRACKS and PUBLISH_STATE_NOTIFY." Draft-19 listed
1635 // PUBLISH_OK and had no PUBLISH_STATE_NOTIFY.
1636 0x10 => matches!(
1637 message,
1638 M::Subscribe
1639 | M::RequestUpdate
1640 | M::Publish
1641 | M::SubscribeTracks
1642 | M::PublishStateNotify
1643 ),
1644 // Section 10.2.7 SUBSCRIBER PRIORITY: "It MAY appear in a SUBSCRIBE,
1645 // PUBLISH, FETCH, or REQUEST_UPDATE (for a subscription or FETCH)."
1646 // Draft-19 said PUBLISH_OK where this says PUBLISH.
1647 0x20 => matches!(
1648 message,
1649 M::Subscribe | M::Publish | M::Fetch | M::RequestUpdate | M::SubscribeTracks
1650 ),
1651 // Section 10.2.9 LOCATION FILTER: "It MAY appear in a FETCH, SUBSCRIBE,
1652 // PUBLISH, REQUEST_UPDATE (for a subscription) or PUBLISH_STATE_NOTIFY
1653 // message." Draft-19 admitted SUBSCRIBE, PUBLISH_OK and REQUEST_UPDATE
1654 // and no FETCH, because a draft-19 FETCH carried its range in the
1655 // message instead.
1656 0x21 => matches!(
1657 message,
1658 M::Fetch
1659 | M::Subscribe
1660 | M::Publish
1661 | M::RequestUpdate
1662 | M::PublishStateNotify
1663 | M::SubscribeTracks
1664 ),
1665 // Section 10.2.8 GROUP ORDER: "It MAY appear in a SUBSCRIBE, PUBLISH,
1666 // SUBSCRIBE_TRACKS, or FETCH, or inside a FILL_PARAMETERS parameter".
1667 // The nested half is Table 6's, as for FILL_TIMEOUT above.
1668 0x22 => matches!(message, M::Subscribe | M::Publish | M::SubscribeTracks | M::Fetch),
1669 // Section 10.2.15 FILL_PARAMETERS, new in draft-20: it "MAY appear in a
1670 // SUBSCRIBE or REQUEST_UPDATE (for a subscription) message."
1671 //
1672 // SUBSCRIBE_TRACKS is admitted on top of those two, and the draft says
1673 // it twice over: Section 10.20.1's "Any Parameter that can be specified
1674 // on a Subscription (ie: in SUBSCRIBE) is valid in SUBSCRIBE_TRACKS,
1675 // unless otherwise specified", and the same section's closing sentence,
1676 // "To join Tracks initiated via the resulting PUBLISHes, the subscriber
1677 // can specify a Location Filter and optionally include
1678 // FILL_PARAMETERS". Section 10.2.15's own list is the "unless otherwise
1679 // specified" clause read strictly, and the two readings disagree. This
1680 // takes the wider one: a rule that ends sessions should be wrong in the
1681 // direction of carrying the parameter, and Section 10.20.1 names this
1682 // message outright.
1683 //
1684 // FETCH is refused, and that is the case the corpus pins: a fill fetch
1685 // stream is something a subscription opens, and a FETCH already is one.
1686 0x23 => matches!(message, M::Subscribe | M::RequestUpdate | M::SubscribeTracks),
1687 // Section 5.1.4: "All other filter parameters MAY appear multiple times
1688 // in a FETCH, SUBSCRIBE, SUBSCRIBE_TRACKS, or REQUEST_UPDATE (on a
1689 // subscription, from the subscriber only) message." SUBGROUP_FILTER
1690 // (Section 10.2.10), OBJECTID_FILTER (10.2.11), PRIORITY_FILTER
1691 // (10.2.12) and OBJECT_PROPERTY_FILTER (10.2.13) are those four.
1692 // Draft-19's sentence also listed PUBLISH_OK.
1693 0x25..=0x28 => {
1694 matches!(message, M::Fetch | M::Subscribe | M::SubscribeTracks | M::RequestUpdate)
1695 }
1696 // Section 5.1.4, of TRACK_PROPERTY_FILTER (Section 10.2.14) alone: it
1697 // "MAY appear multiple times in a SUBSCRIBE_TRACKS message or
1698 // REQUEST_UPDATE for it". It selects tracks rather than objects, which
1699 // is why it is the one filter a SUBSCRIBE may not carry and the one
1700 // Table 6 keeps out of FILL_PARAMETERS.
1701 0x29 => matches!(message, M::SubscribeTracks | M::RequestUpdate),
1702 // Section 10.2.19 NEW GROUP REQUEST: "It MAY appear in SUBSCRIBE or
1703 // REQUEST_UPDATE for a subscription." Draft-19 also listed PUBLISH_OK.
1704 0x32 => matches!(message, M::Subscribe | M::RequestUpdate | M::SubscribeTracks),
1705 // Section 10.2.20 TRACK_NAMESPACE_PREFIX: "It MAY appear in
1706 // REQUEST_UPDATE for a SUBSCRIBE_NAMESPACE or SUBSCRIBE_TRACKS
1707 // request." The two named there are the request being updated, not two
1708 // more places the parameter may be written.
1709 0x34 => matches!(message, M::RequestUpdate),
1710 // Section 10.2.21 INCLUDE_PROPERTIES, new in draft-20: "It MAY appear
1711 // in SUBSCRIBE, TRACK_STATUS, FETCH or SUBSCRIBE_TRACKS."
1712 0x35 => matches!(message, M::Subscribe | M::TrackStatus | M::Fetch | M::SubscribeTracks),
1713 _ => true,
1714 }
1715}
1716
1717/// Refuse a message carrying a Message Parameter its own definition does not
1718/// place there.
1719///
1720/// Section 10.2.1 answers this with a close, which the drafts below do not.
1721/// Draft-16 Section 9.2.2, and drafts 07 through 15 under the older name
1722/// Version Specific Parameters, end the same sentence "it MUST be ignored" —
1723/// so this check belongs to drafts 17, 18 and 19 and to no draft before them.
1724///
1725/// Applied on both sides. A parameter outside its scope is one the peer must
1726/// close the session over, so writing one is a way to end a session rather than
1727/// a way to ask for anything.
1728fn check_parameter_scope(message: &ControlMessage) -> Result<(), CodecError> {
1729 let parameters = match message {
1730 ControlMessage::RequestOk(m) => &m.parameters,
1731 ControlMessage::Subscribe(m) => &m.parameters,
1732 ControlMessage::SubscribeOk(m) => &m.parameters,
1733 ControlMessage::RequestUpdate(m) => &m.parameters,
1734 ControlMessage::Publish(m) => &m.parameters,
1735 ControlMessage::PublishStateNotify(m) => &m.parameters,
1736 ControlMessage::PublishNamespace(m) => &m.parameters,
1737 ControlMessage::SubscribeNamespace(m) => &m.parameters,
1738 ControlMessage::SubscribeTracks(m) => &m.parameters,
1739 ControlMessage::TrackStatus(m) => &m.parameters,
1740 ControlMessage::Fetch(m) => &m.parameters,
1741 ControlMessage::FetchOk(m) => &m.parameters,
1742 // No Message Parameters field. SETUP is named here rather than left to
1743 // a wildcard because the draft says why it can never have one: Section
1744 // 10.2.1 notes that "since Setup Options use a separate namespace, it
1745 // is impossible for Message Parameters to appear in Setup messages",
1746 // and this codec keeps the two namespaces in separate fields.
1747 ControlMessage::Setup(_)
1748 | ControlMessage::GoAway(_)
1749 | ControlMessage::RequestError(_)
1750 | ControlMessage::PublishDone(_)
1751 | ControlMessage::Namespace(_)
1752 | ControlMessage::NamespaceDone(_)
1753 | ControlMessage::PublishSkipped(_) => return Ok(()),
1754 };
1755
1756 let message_type = message.message_type();
1757 for parameter in parameters {
1758 let key = parameter.key.into_inner();
1759 if !parameter_in_scope(key, message_type) {
1760 return Err(CodecError::ParameterOutOfScope { key, message_type: message_type.id() });
1761 }
1762 }
1763 Ok(())
1764}
1765
1766impl ControlMessage {
1767 pub fn encode(&self, buf: &mut impl BufMut) -> Result<(), CodecError> {
1768 check_discriminators(self)?;
1769 check_parameter_scope(self)?;
1770 let mut body = Vec::with_capacity(256);
1771 self.encode_body(&mut body)?;
1772
1773 if body.len() > MAX_MESSAGE_LENGTH {
1774 return Err(CodecError::MessageTooLong(body.len()));
1775 }
1776
1777 let msg_type = self.message_type();
1778 VarInt::from_usize(msg_type.id() as usize).encode_moqt::<Wire>(buf);
1779 // Draft-20: 16-bit length (big-endian)
1780 buf.put_u16(body.len() as u16);
1781 buf.put_slice(&body);
1782 Ok(())
1783 }
1784
1785 pub fn decode(buf: &mut impl Buf) -> Result<Self, CodecError> {
1786 let type_id = VarInt::decode_moqt::<Wire>(buf)?.into_inner();
1787 let msg_type =
1788 MessageType::from_id(type_id).ok_or(CodecError::UnknownMessageType(type_id))?;
1789 // Draft-20: 16-bit length (big-endian)
1790 if buf.remaining() < 2 {
1791 return Err(CodecError::UnexpectedEnd);
1792 }
1793 let body_len = buf.get_u16() as usize;
1794 if buf.remaining() < body_len {
1795 return Err(CodecError::UnexpectedEnd);
1796 }
1797 let body_bytes = buf.copy_to_bytes(body_len);
1798 let mut body = &body_bytes[..];
1799 let msg = match Self::decode_body(msg_type, &mut body) {
1800 Ok(msg) => msg,
1801 // The fields wanted more bytes than the Length allowed. This buffer
1802 // is already bounded by that Length, so running out inside it cannot
1803 // mean the message is still arriving - which is what the same error
1804 // means everywhere else, and why a reader loops on it rather than
1805 // closing. Here there is nothing left to arrive.
1806 Err(
1807 CodecError::UnexpectedEnd
1808 | CodecError::Kvp(crate::kvp::KvpError::UnexpectedEnd)
1809 | CodecError::Kvp(crate::kvp::KvpError::VarInt(
1810 crate::varint::VarIntError::UnexpectedEnd,
1811 ))
1812 | CodecError::VarInt(crate::varint::VarIntError::UnexpectedEnd),
1813 ) => {
1814 return Err(CodecError::ControlMessageLengthMismatch {
1815 declared: body_len,
1816 detail: "its fields ran past the end",
1817 });
1818 }
1819 Err(e) => return Err(e),
1820 };
1821 check_parameter_scope(&msg)?;
1822 // Draft-20 Section 10: "If the length does not match the length of the
1823 // Message Body, the receiver MUST close the session with a
1824 // PROTOCOL_VIOLATION." A body parser that stops short leaves bytes
1825 // here; without this the surplus is discarded and a truncated or
1826 // mis-framed field looks like a well-formed message.
1827 if body.has_remaining() {
1828 return Err(CodecError::ControlMessageLengthMismatch {
1829 declared: body_len,
1830 detail: "its fields left bytes unread",
1831 });
1832 }
1833 Ok(msg)
1834 }
1835
1836 fn encode_body(&self, buf: &mut impl BufMut) -> Result<(), CodecError> {
1837 match self {
1838 ControlMessage::Setup(m) => {
1839 encode_setup_options(&m.options, buf)?;
1840 }
1841 ControlMessage::GoAway(m) => {
1842 if m.new_session_uri.len() > MAX_GOAWAY_URI_LENGTH {
1843 return Err(CodecError::GoAwayUriTooLong);
1844 }
1845 VarInt::from_usize(m.new_session_uri.len()).encode_moqt::<Wire>(buf);
1846 buf.put_slice(&m.new_session_uri);
1847 m.timeout.encode_moqt::<Wire>(buf);
1848 }
1849 ControlMessage::RequestOk(m) => {
1850 encode_parameters(&m.parameters, buf)?;
1851 encode_track_properties(&m.track_properties, buf)?;
1852 }
1853 ControlMessage::RequestError(m) => {
1854 if m.reason_phrase.len() > MAX_REASON_PHRASE_LENGTH {
1855 return Err(CodecError::ReasonPhraseTooLong);
1856 }
1857 m.error_code.encode_moqt::<Wire>(buf);
1858 m.retry_interval.encode_moqt::<Wire>(buf);
1859 VarInt::from_usize(m.reason_phrase.len()).encode_moqt::<Wire>(buf);
1860 buf.put_slice(&m.reason_phrase);
1861 if let Some(r) = &m.redirect {
1862 r.track_namespace.validate_moqt()?;
1863 check_full_track_name(&r.track_namespace, &r.track_name)?;
1864 VarInt::from_usize(r.connect_uri.len()).encode_moqt::<Wire>(buf);
1865 buf.put_slice(&r.connect_uri);
1866 r.track_namespace.encode_moqt::<Wire>(buf);
1867 VarInt::from_usize(r.track_name.len()).encode_moqt::<Wire>(buf);
1868 buf.put_slice(&r.track_name);
1869 }
1870 }
1871 ControlMessage::Subscribe(m) => {
1872 m.track_namespace.validate_moqt()?;
1873 check_full_track_name(&m.track_namespace, &m.track_name)?;
1874 m.request_id.encode_moqt::<Wire>(buf);
1875 m.track_namespace.encode_moqt::<Wire>(buf);
1876 VarInt::from_usize(m.track_name.len()).encode_moqt::<Wire>(buf);
1877 buf.put_slice(&m.track_name);
1878 encode_parameters(&m.parameters, buf)?;
1879 }
1880 ControlMessage::SubscribeOk(m) => {
1881 m.track_alias.encode_moqt::<Wire>(buf);
1882 encode_parameters(&m.parameters, buf)?;
1883 encode_track_properties(&m.track_properties, buf)?;
1884 }
1885 ControlMessage::RequestUpdate(m) => {
1886 m.request_id.encode_moqt::<Wire>(buf);
1887 encode_parameters(&m.parameters, buf)?;
1888 }
1889 ControlMessage::Publish(m) => {
1890 m.track_namespace.validate_moqt()?;
1891 check_full_track_name(&m.track_namespace, &m.track_name)?;
1892 m.request_id.encode_moqt::<Wire>(buf);
1893 m.track_namespace.encode_moqt::<Wire>(buf);
1894 VarInt::from_usize(m.track_name.len()).encode_moqt::<Wire>(buf);
1895 buf.put_slice(&m.track_name);
1896 m.track_alias.encode_moqt::<Wire>(buf);
1897 encode_parameters(&m.parameters, buf)?;
1898 encode_track_properties(&m.track_properties, buf)?;
1899 }
1900 // Section 10.10, Figure 13: parameter count, then parameters,
1901 // and nothing else. No Request ID — the subscription's stream is
1902 // what identifies the message.
1903 ControlMessage::PublishStateNotify(m) => {
1904 encode_parameters(&m.parameters, buf)?;
1905 }
1906 ControlMessage::PublishDone(m) => {
1907 if m.reason_phrase.len() > MAX_REASON_PHRASE_LENGTH {
1908 return Err(CodecError::ReasonPhraseTooLong);
1909 }
1910 m.status_code.encode_moqt::<Wire>(buf);
1911 m.stream_count.encode_moqt::<Wire>(buf);
1912 VarInt::from_usize(m.reason_phrase.len()).encode_moqt::<Wire>(buf);
1913 buf.put_slice(&m.reason_phrase);
1914 }
1915 ControlMessage::PublishNamespace(m) => {
1916 m.track_namespace.validate_moqt()?;
1917 m.request_id.encode_moqt::<Wire>(buf);
1918 m.track_namespace.encode_moqt::<Wire>(buf);
1919 encode_parameters(&m.parameters, buf)?;
1920 }
1921 ControlMessage::Namespace(m) => {
1922 m.namespace_suffix.validate_moqt()?;
1923 m.namespace_suffix.encode_moqt::<Wire>(buf);
1924 }
1925 ControlMessage::NamespaceDone(m) => {
1926 m.namespace_suffix.validate_moqt()?;
1927 m.namespace_suffix.encode_moqt::<Wire>(buf);
1928 }
1929 ControlMessage::SubscribeNamespace(m) => {
1930 m.namespace_prefix.validate_moqt()?;
1931 m.request_id.encode_moqt::<Wire>(buf);
1932 m.namespace_prefix.encode_moqt::<Wire>(buf);
1933 encode_parameters(&m.parameters, buf)?;
1934 }
1935 ControlMessage::SubscribeTracks(m) => {
1936 m.namespace_prefix.validate_moqt()?;
1937 m.request_id.encode_moqt::<Wire>(buf);
1938 m.namespace_prefix.encode_moqt::<Wire>(buf);
1939 encode_parameters(&m.parameters, buf)?;
1940 }
1941 ControlMessage::TrackStatus(m) => {
1942 m.track_namespace.validate_moqt()?;
1943 check_full_track_name(&m.track_namespace, &m.track_name)?;
1944 m.request_id.encode_moqt::<Wire>(buf);
1945 m.track_namespace.encode_moqt::<Wire>(buf);
1946 VarInt::from_usize(m.track_name.len()).encode_moqt::<Wire>(buf);
1947 buf.put_slice(&m.track_name);
1948 encode_parameters(&m.parameters, buf)?;
1949 }
1950 // Section 10.13, Figure 16. Byte-identical to SUBSCRIBE above:
1951 // no Fetch Type, no inline range, and the namespace and name where
1952 // draft-19 put them inside its Standalone Fetch.
1953 ControlMessage::Fetch(m) => {
1954 m.track_namespace.validate_moqt()?;
1955 check_full_track_name(&m.track_namespace, &m.track_name)?;
1956 m.request_id.encode_moqt::<Wire>(buf);
1957 m.track_namespace.encode_moqt::<Wire>(buf);
1958 VarInt::from_usize(m.track_name.len()).encode_moqt::<Wire>(buf);
1959 buf.put_slice(&m.track_name);
1960 encode_parameters(&m.parameters, buf)?;
1961 }
1962 ControlMessage::FetchOk(m) => {
1963 buf.put_u8(m.end_of_track);
1964 m.end_group.encode_moqt::<Wire>(buf);
1965 m.end_object.encode_moqt::<Wire>(buf);
1966 encode_parameters(&m.parameters, buf)?;
1967 encode_track_properties(&m.track_properties, buf)?;
1968 }
1969 ControlMessage::PublishSkipped(m) => {
1970 m.namespace_suffix.validate_moqt()?;
1971 check_full_track_name(&m.namespace_suffix, &m.track_name)?;
1972 m.namespace_suffix.encode_moqt::<Wire>(buf);
1973 VarInt::from_usize(m.track_name.len()).encode_moqt::<Wire>(buf);
1974 buf.put_slice(&m.track_name);
1975 }
1976 }
1977 Ok(())
1978 }
1979
1980 fn decode_body(msg_type: MessageType, buf: &mut impl Buf) -> Result<Self, CodecError> {
1981 match msg_type {
1982 MessageType::Setup => {
1983 let options = decode_setup_options(buf)?;
1984 Ok(ControlMessage::Setup(Setup { options }))
1985 }
1986 MessageType::GoAway => {
1987 let uri_len = VarInt::decode_moqt::<Wire>(buf)?.into_inner() as usize;
1988 // Draft-20 Section 10.4: an endpoint that receives a New
1989 // Session URI Length above the maximum MUST close the session
1990 // with a PROTOCOL_VIOLATION. Checked here as well as on encode
1991 // so an oversized URI never reaches the application.
1992 if uri_len > MAX_GOAWAY_URI_LENGTH {
1993 return Err(CodecError::GoAwayUriTooLong);
1994 }
1995 let uri = read_bytes(buf, uri_len)?;
1996 let timeout = VarInt::decode_moqt::<Wire>(buf)?;
1997 Ok(ControlMessage::GoAway(GoAway { new_session_uri: uri, timeout }))
1998 }
1999 MessageType::RequestOk => {
2000 let parameters = decode_parameters(buf)?;
2001 let track_properties = decode_track_properties(buf)?;
2002 Ok(ControlMessage::RequestOk(RequestOk { parameters, track_properties }))
2003 }
2004 MessageType::RequestError => {
2005 let error_code = VarInt::decode_moqt::<Wire>(buf)?;
2006 let retry_interval = VarInt::decode_moqt::<Wire>(buf)?;
2007 let reason_len = VarInt::decode_moqt::<Wire>(buf)?.into_inner() as usize;
2008 // Draft-20 Section 1.4.4: a received reason phrase length above
2009 // the maximum MUST close the session with a PROTOCOL_VIOLATION.
2010 if reason_len > MAX_REASON_PHRASE_LENGTH {
2011 return Err(CodecError::ReasonPhraseTooLong);
2012 }
2013 let reason_phrase = read_bytes(buf, reason_len)?;
2014 let redirect = if error_code.into_inner() == request_error_codes::REDIRECT {
2015 let uri_len = VarInt::decode_moqt::<Wire>(buf)?.into_inner() as usize;
2016 let connect_uri = read_bytes(buf, uri_len)?;
2017 let track_namespace = TrackNamespace::decode_allow_empty_moqt::<Wire>(buf)?;
2018 let name_len = VarInt::decode_moqt::<Wire>(buf)?.into_inner() as usize;
2019 let track_name = read_bytes(buf, name_len)?;
2020 check_full_track_name(&track_namespace, &track_name)?;
2021 Some(Redirect { connect_uri, track_namespace, track_name })
2022 } else {
2023 None
2024 };
2025 Ok(ControlMessage::RequestError(RequestError {
2026 error_code,
2027 retry_interval,
2028 reason_phrase,
2029 redirect,
2030 }))
2031 }
2032 MessageType::Subscribe => {
2033 let request_id = VarInt::decode_moqt::<Wire>(buf)?;
2034 let track_namespace = TrackNamespace::decode_moqt::<Wire>(buf)?;
2035 let tn_len = VarInt::decode_moqt::<Wire>(buf)?.into_inner() as usize;
2036 let track_name = read_bytes(buf, tn_len)?;
2037 check_full_track_name(&track_namespace, &track_name)?;
2038 let parameters = decode_parameters(buf)?;
2039 Ok(ControlMessage::Subscribe(Subscribe {
2040 request_id,
2041 track_namespace,
2042 track_name,
2043 parameters,
2044 }))
2045 }
2046 MessageType::SubscribeOk => {
2047 let track_alias = VarInt::decode_moqt::<Wire>(buf)?;
2048 let parameters = decode_parameters(buf)?;
2049 let track_properties = decode_track_properties(buf)?;
2050 Ok(ControlMessage::SubscribeOk(SubscribeOk {
2051 track_alias,
2052 parameters,
2053 track_properties,
2054 }))
2055 }
2056 MessageType::RequestUpdate => {
2057 let request_id = VarInt::decode_moqt::<Wire>(buf)?;
2058 let parameters = decode_parameters(buf)?;
2059 Ok(ControlMessage::RequestUpdate(RequestUpdate { request_id, parameters }))
2060 }
2061 MessageType::Publish => {
2062 let request_id = VarInt::decode_moqt::<Wire>(buf)?;
2063 let track_namespace = TrackNamespace::decode_moqt::<Wire>(buf)?;
2064 let tn_len = VarInt::decode_moqt::<Wire>(buf)?.into_inner() as usize;
2065 let track_name = read_bytes(buf, tn_len)?;
2066 let track_alias = VarInt::decode_moqt::<Wire>(buf)?;
2067 check_full_track_name(&track_namespace, &track_name)?;
2068 let parameters = decode_parameters(buf)?;
2069 let track_properties = decode_track_properties(buf)?;
2070 Ok(ControlMessage::Publish(Publish {
2071 request_id,
2072 track_namespace,
2073 track_name,
2074 track_alias,
2075 parameters,
2076 track_properties,
2077 }))
2078 }
2079 MessageType::PublishStateNotify => {
2080 let parameters = decode_parameters(buf)?;
2081 Ok(ControlMessage::PublishStateNotify(PublishStateNotify { parameters }))
2082 }
2083 MessageType::PublishDone => {
2084 // The Status Code is carried up whatever it is. Section 14
2085 // forbids closing the session over an unknown one and requires
2086 // it to be read as INTERNAL_ERROR, so refusing the frame here
2087 // would take a choice away from the caller that the draft gives
2088 // it. See [`PublishDone::status_code`].
2089 let status_code = VarInt::decode_moqt::<Wire>(buf)?;
2090 let stream_count = VarInt::decode_moqt::<Wire>(buf)?;
2091 let reason_len = VarInt::decode_moqt::<Wire>(buf)?.into_inner() as usize;
2092 // Draft-20 Section 1.4.4, same bound as REQUEST_ERROR above.
2093 if reason_len > MAX_REASON_PHRASE_LENGTH {
2094 return Err(CodecError::ReasonPhraseTooLong);
2095 }
2096 let reason_phrase = read_bytes(buf, reason_len)?;
2097 Ok(ControlMessage::PublishDone(PublishDone {
2098 status_code,
2099 stream_count,
2100 reason_phrase,
2101 }))
2102 }
2103 MessageType::PublishNamespace => {
2104 let request_id = VarInt::decode_moqt::<Wire>(buf)?;
2105 let track_namespace = TrackNamespace::decode_moqt::<Wire>(buf)?;
2106 let parameters = decode_parameters(buf)?;
2107 Ok(ControlMessage::PublishNamespace(PublishNamespace {
2108 request_id,
2109 track_namespace,
2110 parameters,
2111 }))
2112 }
2113 MessageType::Namespace => {
2114 let namespace_suffix = TrackNamespace::decode_allow_empty_moqt::<Wire>(buf)?;
2115 Ok(ControlMessage::Namespace(Namespace { namespace_suffix }))
2116 }
2117 MessageType::NamespaceDone => {
2118 let namespace_suffix = TrackNamespace::decode_allow_empty_moqt::<Wire>(buf)?;
2119 Ok(ControlMessage::NamespaceDone(NamespaceDone { namespace_suffix }))
2120 }
2121 MessageType::SubscribeNamespace => {
2122 let request_id = VarInt::decode_moqt::<Wire>(buf)?;
2123 let namespace_prefix = TrackNamespace::decode_allow_empty_moqt::<Wire>(buf)?;
2124 let parameters = decode_parameters(buf)?;
2125 Ok(ControlMessage::SubscribeNamespace(SubscribeNamespace {
2126 request_id,
2127 namespace_prefix,
2128 parameters,
2129 }))
2130 }
2131 MessageType::SubscribeTracks => {
2132 let request_id = VarInt::decode_moqt::<Wire>(buf)?;
2133 let namespace_prefix = TrackNamespace::decode_allow_empty_moqt::<Wire>(buf)?;
2134 let parameters = decode_parameters(buf)?;
2135 Ok(ControlMessage::SubscribeTracks(SubscribeTracks {
2136 request_id,
2137 namespace_prefix,
2138 parameters,
2139 }))
2140 }
2141 MessageType::TrackStatus => {
2142 let request_id = VarInt::decode_moqt::<Wire>(buf)?;
2143 let track_namespace = TrackNamespace::decode_moqt::<Wire>(buf)?;
2144 let tn_len = VarInt::decode_moqt::<Wire>(buf)?.into_inner() as usize;
2145 let track_name = read_bytes(buf, tn_len)?;
2146 check_full_track_name(&track_namespace, &track_name)?;
2147 let parameters = decode_parameters(buf)?;
2148 Ok(ControlMessage::TrackStatus(TrackStatus {
2149 request_id,
2150 track_namespace,
2151 track_name,
2152 parameters,
2153 }))
2154 }
2155 MessageType::Fetch => {
2156 let request_id = VarInt::decode_moqt::<Wire>(buf)?;
2157 let track_namespace = TrackNamespace::decode_moqt::<Wire>(buf)?;
2158 let tn_len = VarInt::decode_moqt::<Wire>(buf)?.into_inner() as usize;
2159 let track_name = read_bytes(buf, tn_len)?;
2160 check_full_track_name(&track_namespace, &track_name)?;
2161 let parameters = decode_parameters(buf)?;
2162 Ok(ControlMessage::Fetch(Fetch {
2163 request_id,
2164 track_namespace,
2165 track_name,
2166 parameters,
2167 }))
2168 }
2169 MessageType::FetchOk => {
2170 if buf.remaining() < 1 {
2171 return Err(CodecError::UnexpectedEnd);
2172 }
2173 let end_of_track = buf.get_u8();
2174 let end_group = VarInt::decode_moqt::<Wire>(buf)?;
2175 let end_object = VarInt::decode_moqt::<Wire>(buf)?;
2176 let parameters = decode_parameters(buf)?;
2177 let track_properties = decode_track_properties(buf)?;
2178 Ok(ControlMessage::FetchOk(FetchOk {
2179 end_of_track,
2180 end_group,
2181 end_object,
2182 parameters,
2183 track_properties,
2184 }))
2185 }
2186 MessageType::PublishSkipped => {
2187 let namespace_suffix = TrackNamespace::decode_allow_empty_moqt::<Wire>(buf)?;
2188 let tn_len = VarInt::decode_moqt::<Wire>(buf)?.into_inner() as usize;
2189 let track_name = read_bytes(buf, tn_len)?;
2190 check_full_track_name(&namespace_suffix, &track_name)?;
2191 Ok(ControlMessage::PublishSkipped(PublishSkipped { namespace_suffix, track_name }))
2192 }
2193 }
2194 }
2195
2196 pub fn message_type(&self) -> MessageType {
2197 match self {
2198 ControlMessage::Setup(_) => MessageType::Setup,
2199 ControlMessage::GoAway(_) => MessageType::GoAway,
2200 ControlMessage::RequestOk(_) => MessageType::RequestOk,
2201 ControlMessage::RequestError(_) => MessageType::RequestError,
2202 ControlMessage::Subscribe(_) => MessageType::Subscribe,
2203 ControlMessage::SubscribeOk(_) => MessageType::SubscribeOk,
2204 ControlMessage::RequestUpdate(_) => MessageType::RequestUpdate,
2205 ControlMessage::Publish(_) => MessageType::Publish,
2206 ControlMessage::PublishStateNotify(_) => MessageType::PublishStateNotify,
2207 ControlMessage::PublishDone(_) => MessageType::PublishDone,
2208 ControlMessage::PublishNamespace(_) => MessageType::PublishNamespace,
2209 ControlMessage::Namespace(_) => MessageType::Namespace,
2210 ControlMessage::NamespaceDone(_) => MessageType::NamespaceDone,
2211 ControlMessage::SubscribeNamespace(_) => MessageType::SubscribeNamespace,
2212 ControlMessage::SubscribeTracks(_) => MessageType::SubscribeTracks,
2213 ControlMessage::TrackStatus(_) => MessageType::TrackStatus,
2214 ControlMessage::Fetch(_) => MessageType::Fetch,
2215 ControlMessage::FetchOk(_) => MessageType::FetchOk,
2216 ControlMessage::PublishSkipped(_) => MessageType::PublishSkipped,
2217 }
2218 }
2219}
2220
2221#[cfg(test)]
2222mod tests {
2223 use super::*;
2224
2225 /// Frame `body` as a draft-20 control message of `type_id`, declaring
2226 /// `declared_len` rather than the body's real length. Used to build the
2227 /// mismatched frame the length rule is about.
2228 fn frame_with_declared_len(type_id: u64, declared_len: u16, body: &[u8]) -> Vec<u8> {
2229 let mut out = Vec::new();
2230 VarInt::from_u64_moqt(type_id).encode_moqt::<Wire>(&mut out);
2231 out.put_u16(declared_len);
2232 out.put_slice(body);
2233 out
2234 }
2235
2236 fn frame(type_id: u64, body: &[u8]) -> Vec<u8> {
2237 frame_with_declared_len(type_id, body.len() as u16, body)
2238 }
2239
2240 /// A SUBSCRIBE body: request id 1, namespace ("a"), track name "b", and
2241 /// `params` already encoded.
2242 fn subscribe_body(params: &[u8]) -> Vec<u8> {
2243 let mut body = vec![0x01, 0x01, 0x01, b'a', 0x01, b'b'];
2244 body.extend_from_slice(params);
2245 body
2246 }
2247
2248 /// Draft-20 Section 10: "If the length does not match the length of the
2249 /// Message Body, the receiver MUST close the session with a
2250 /// PROTOCOL_VIOLATION."
2251 ///
2252 /// Without the trailing-byte check in `decode` this SUBSCRIBE parses and
2253 /// the two surplus bytes vanish:
2254 ///
2255 /// ```text
2256 /// assertion `left == right` failed
2257 /// left: Ok(Subscribe(Subscribe { request_id: VarInt(1), track_namespace:
2258 /// TrackNamespace([[97]]), track_name: [98], parameters: [] }))
2259 /// right: Err(InvalidField)
2260 /// ```
2261 #[test]
2262 fn a_message_body_shorter_than_the_declared_length_is_refused() {
2263 let body = subscribe_body(&[0x00]);
2264 let mut junked = body.clone();
2265 junked.extend_from_slice(&[0xff, 0xff]);
2266 let bytes = frame_with_declared_len(0x03, (body.len() + 2) as u16, &junked);
2267
2268 let mut buf = &bytes[..];
2269 assert_eq!(
2270 ControlMessage::decode(&mut buf),
2271 Err(CodecError::ControlMessageLengthMismatch {
2272 declared: (body.len() + 2),
2273 detail: "its fields left bytes unread",
2274 })
2275 );
2276
2277 // The same body with an honest length still decodes, so the guard
2278 // rejects the mismatch and not the message.
2279 let honest = frame(0x03, &body);
2280 let mut buf = &honest[..];
2281 assert!(ControlMessage::decode(&mut buf).is_ok());
2282 }
2283
2284 /// Draft-20 Section 1.4.4: "The reason phrase length has a maximum value of
2285 /// 1024 bytes. If an endpoint receives a length exceeding the maximum, it
2286 /// MUST close the session with a PROTOCOL_VIOLATION".
2287 ///
2288 /// Without the decode-side bound the 2000-byte phrase is handed to the
2289 /// application:
2290 ///
2291 /// ```text
2292 /// assertion `left == right` failed
2293 /// left: Ok(RequestError(RequestError { error_code: VarInt(1),
2294 /// retry_interval: VarInt(0), reason_phrase: [120, 120, ...],
2295 /// redirect: None }))
2296 /// right: Err(ReasonPhraseTooLong)
2297 /// ```
2298 ///
2299 /// (The 2000 repeated bytes of the phrase are elided from that transcript.)
2300 #[test]
2301 fn an_over_long_reason_phrase_is_refused_on_decode() {
2302 for (type_id, prefix) in [(0x05u64, vec![0x01, 0x00]), (0x0B, vec![0x01, 0x00])] {
2303 let mut body = prefix;
2304 let over = MAX_REASON_PHRASE_LENGTH + 976;
2305 VarInt::from_usize(over).encode_moqt::<Wire>(&mut body);
2306 body.extend(std::iter::repeat_n(b'x', over));
2307 let bytes = frame(type_id, &body);
2308
2309 let mut buf = &bytes[..];
2310 assert_eq!(
2311 ControlMessage::decode(&mut buf),
2312 Err(CodecError::ReasonPhraseTooLong),
2313 "message type 0x{type_id:x}"
2314 );
2315 }
2316 }
2317
2318 /// Draft-20 Section 10.4: "The maximum length of the New Session URI is
2319 /// 8,192 bytes. If an endpoint receives a length exceeding the maximum, it
2320 /// MUST close the session with a PROTOCOL_VIOLATION."
2321 ///
2322 /// Without the decode-side bound the oversized URI reaches the application
2323 /// and a migrating endpoint follows it:
2324 ///
2325 /// ```text
2326 /// assertion `left == right` failed
2327 /// left: Ok(GoAway(GoAway { new_session_uri: [117, 117, ...],
2328 /// timeout: VarInt(0) }))
2329 /// right: Err(GoAwayUriTooLong)
2330 /// ```
2331 ///
2332 /// (The 9000 repeated bytes of the URI are elided from that transcript.)
2333 #[test]
2334 fn an_over_long_goaway_uri_is_refused_on_decode() {
2335 let over = MAX_GOAWAY_URI_LENGTH + 808;
2336 let mut body = Vec::new();
2337 VarInt::from_usize(over).encode_moqt::<Wire>(&mut body);
2338 body.extend(std::iter::repeat_n(b'u', over));
2339 body.push(0x00); // timeout
2340 let bytes = frame(0x10, &body);
2341
2342 let mut buf = &bytes[..];
2343 assert_eq!(ControlMessage::decode(&mut buf), Err(CodecError::GoAwayUriTooLong));
2344 }
2345
2346 /// Draft-20 Section 10.2.8 (GROUP_ORDER): "The allowed values are Ascending
2347 /// (0x1) or Descending (0x2). If an endpoint receives a value outside this
2348 /// range, it MUST close the session with PROTOCOL_VIOLATION." Section
2349 /// 10.2.17 says the same of FORWARD with the values 0 and 1.
2350 ///
2351 /// Without `uint8_value_in_range` the out-of-range byte is handed up as an
2352 /// ordinary parameter:
2353 ///
2354 /// ```text
2355 /// assertion `left == right` failed
2356 /// left: Ok(Subscribe(Subscribe { request_id: VarInt(1), track_namespace:
2357 /// TrackNamespace([[97]]), track_name: [98], parameters:
2358 /// [KeyValuePair { key: VarInt(34), value: Varint(VarInt(7)) }] }))
2359 /// right: Err(InvalidField)
2360 /// ```
2361 #[test]
2362 fn a_uint8_parameter_outside_its_range_is_refused() {
2363 // key, rejected value, accepted value
2364 let cases = [(0x22u8, 7u8, 2u8), (0x10, 9, 1)];
2365 for (key, bad, good) in cases {
2366 let bytes = frame(0x03, &subscribe_body(&[0x01, key, bad]));
2367 let mut buf = &bytes[..];
2368 assert_eq!(
2369 ControlMessage::decode(&mut buf),
2370 Err(CodecError::ParameterValueOutOfRange { key: key as u64, value: bad as u64 }),
2371 "parameter 0x{key:x} value {bad}"
2372 );
2373
2374 let bytes = frame(0x03, &subscribe_body(&[0x01, key, good]));
2375 let mut buf = &bytes[..];
2376 assert!(
2377 ControlMessage::decode(&mut buf).is_ok(),
2378 "parameter 0x{key:x} value {good} should still decode"
2379 );
2380 }
2381 }
2382
2383 /// SUBSCRIBER_PRIORITY (0x20) is a uint8 with no restricted range, so it
2384 /// must keep accepting the whole 0-255 span. This is the negative half of
2385 /// the range check: a table that over-reached would fail here.
2386 #[test]
2387 fn subscriber_priority_still_accepts_the_whole_byte_range() {
2388 for value in [0u8, 1, 2, 128, 255] {
2389 let bytes = frame(0x03, &subscribe_body(&[0x01, 0x20, value]));
2390 let mut buf = &bytes[..];
2391 assert!(ControlMessage::decode(&mut buf).is_ok(), "priority {value}");
2392 }
2393 }
2394
2395 fn param(key: u64, value: &[u8]) -> KeyValuePair {
2396 KeyValuePair { key: VarInt::from_u64_moqt(key), value: KvpValue::Bytes(value.to_vec()) }
2397 }
2398
2399 /// Draft-20 Section 10.2.16: "The LARGEST_OBJECT parameter (Parameter Type
2400 /// 0x9) is a Location." Section 10.2 defines Location as "Two consecutive
2401 /// varints (Group, Object)" — the value carries no length of its own.
2402 ///
2403 /// The frame below is built from the draft rather than from this encoder:
2404 /// REQUEST_OK, four body bytes, one parameter, type delta `0x09`, then the
2405 /// two varints `0x0a` and `0x03` for Location (10, 3). A length-prefixed
2406 /// spelling would need a fifth byte.
2407 ///
2408 /// With `0x09` back in the Length-prefixed arm, the decoder reads the
2409 /// group varint `0x0a` as a value length of 10 and runs off the end of a
2410 /// four-byte body. Both this test and
2411 /// [`a_location_does_not_eat_the_block_that_follows_it`] fail with:
2412 ///
2413 /// ```text
2414 /// spec-correct frame must decode: UnexpectedEnd
2415 /// ```
2416 #[test]
2417 fn largest_object_is_two_bare_varints() {
2418 let body = [0x01, 0x09, 0x0a, 0x03];
2419 let bytes = frame(0x07, &body);
2420
2421 let msg = ControlMessage::decode(&mut &bytes[..]).expect("spec-correct frame must decode");
2422 let ControlMessage::RequestOk(ok) = &msg else {
2423 panic!("expected REQUEST_OK, got {msg:?}")
2424 };
2425 assert_eq!(ok.parameters, vec![param(0x09, &[0x0a, 0x03])]);
2426 assert!(ok.track_properties.is_empty(), "the four body bytes are all parameter");
2427
2428 let mut out = Vec::new();
2429 msg.encode(&mut out).expect("re-encode");
2430 assert_eq!(out, bytes, "the value must go back out as the two bare varints it came in as");
2431 }
2432
2433 /// A Location value the encoder was handed but the decoder could not read
2434 /// back is refused on the way out, not written.
2435 ///
2436 /// LARGEST_OBJECT carries no length of its own — that is the whole point
2437 /// of the encoding — so `encode_parameters` writes its bytes verbatim. A
2438 /// value built in memory rather than decoded is under no obligation to be
2439 /// two varints, and without this check the codec answers `Ok(())` and puts
2440 /// a frame on the wire that `ControlMessage::decode` then refuses. One
2441 /// varint short and one varint long are the two ways to get it wrong.
2442 ///
2443 /// # What it catches
2444 ///
2445 /// Dropping the `is_location_value` guard from this draft's encode arm,
2446 /// run:
2447 ///
2448 /// ```text
2449 /// panicked at crates\moqtap-codec\src\draft20\message.rs:
2450 /// LARGEST_OBJECT of one varint must not encode: the decoder cannot read it back
2451 ///
2452 /// test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 108 filtered out
2453 /// ```
2454 ///
2455 /// The sibling draft kept its guard and kept passing, which is what shows
2456 /// the check is per-draft and not inherited from somewhere shared.
2457 #[test]
2458 fn a_location_value_that_is_not_two_varints_is_refused_on_encode() {
2459 for (label, value) in
2460 [("one varint", vec![0x0a]), ("three varints", vec![0x0a, 0x03, 0x05])]
2461 {
2462 let msg = ControlMessage::RequestOk(RequestOk {
2463 parameters: vec![param(0x09, &value)],
2464 track_properties: Vec::new(),
2465 });
2466 let mut out = Vec::new();
2467 assert!(
2468 msg.encode(&mut out).is_err(),
2469 "LARGEST_OBJECT of {label} must not encode: the decoder cannot read it back"
2470 );
2471 }
2472
2473 // The well-formed value still goes out, so the check refuses the
2474 // malformed case and not the encoding itself.
2475 let msg = ControlMessage::RequestOk(RequestOk {
2476 parameters: vec![param(0x09, &[0x0a, 0x03])],
2477 track_properties: Vec::new(),
2478 });
2479 let mut out = Vec::new();
2480 msg.encode(&mut out).expect("a Location of exactly two varints must still encode");
2481 ControlMessage::decode(&mut &out[..]).expect("and must decode back");
2482 }
2483
2484 /// The same Location read through a message that carries other fields
2485 /// after it, so a stray length byte cannot hide in a trailing block.
2486 ///
2487 /// SUBSCRIBE_OK is track alias `0x05`, then the parameters, then the track
2488 /// properties. With LARGEST_OBJECT (10, 3) and one property
2489 /// (OBJECT_DELIVERY_TIMEOUT, type `0x02`, 5000ms as the two-byte varint
2490 /// `0x93 0x88`), the body is `05 01 09 0a 03 02 93 88`.
2491 #[test]
2492 fn a_location_does_not_eat_the_block_that_follows_it() {
2493 let body = [0x05, 0x01, 0x09, 0x0a, 0x03, 0x02, 0x93, 0x88];
2494 let bytes = frame(0x04, &body);
2495
2496 let msg = ControlMessage::decode(&mut &bytes[..]).expect("spec-correct frame must decode");
2497 let ControlMessage::SubscribeOk(ok) = &msg else {
2498 panic!("expected SUBSCRIBE_OK, got {msg:?}")
2499 };
2500 assert_eq!(ok.parameters, vec![param(0x09, &[0x0a, 0x03])]);
2501 assert_eq!(
2502 ok.track_properties,
2503 vec![KeyValuePair {
2504 key: VarInt::from_u64_moqt(0x02),
2505 value: KvpValue::Varint(VarInt::from_u64_moqt(5000)),
2506 }]
2507 );
2508
2509 let mut out = Vec::new();
2510 msg.encode(&mut out).expect("re-encode");
2511 assert_eq!(out, bytes);
2512 }
2513
2514 /// Draft-20 Section 10.2.19: the TRACK_NAMESPACE_PREFIX parameter
2515 /// (Parameter Type 0x34) "uses the Track Namespace encoding described in
2516 /// Section 2.4.1" — a varint field count followed by that many
2517 /// length-prefixed fields, and nothing in front of it. That encoding is not
2518 /// one of the four Section 10.2 lists, so it cannot be assumed to be
2519 /// Length-prefixed by default.
2520 ///
2521 /// The frame below is built from Section 2.4.1: REQUEST_UPDATE for request
2522 /// `7`, one parameter, type delta `0x34`, then the namespace ("live",
2523 /// "sports") as `02 04 "live" 06 "sports"`. Sixteen body bytes; a
2524 /// length-prefixed spelling would need a seventeenth for the outer length.
2525 ///
2526 /// With `0x34` back in the Length-prefixed arm the field count `0x02` is
2527 /// read as an outer length of two bytes, leaving eleven bytes of namespace
2528 /// unread. Draft-20's Section 10 body-length check turns that into a
2529 /// refusal rather than a truncated value:
2530 ///
2531 /// ```text
2532 /// spec-correct frame must decode: InvalidField
2533 /// ```
2534 ///
2535 /// That check is not a safety net here. Where the surplus lands inside the
2536 /// declared body — as in
2537 /// [`an_empty_track_namespace_prefix_is_one_zero_byte`], whose namespace is
2538 /// one byte long — the misread is silent, and that test fails instead with:
2539 ///
2540 /// ```text
2541 /// assertion `left == right` failed
2542 /// left: [KeyValuePair { key: VarInt(52), value: Bytes([]) }]
2543 /// right: [KeyValuePair { key: VarInt(52), value: Bytes([0]) }]
2544 /// ```
2545 #[test]
2546 fn track_namespace_prefix_is_a_bare_track_namespace() {
2547 let namespace: Vec<u8> = [&[0x02, 0x04][..], b"live", &[0x06][..], b"sports"].concat();
2548 assert_eq!(namespace.len(), 13);
2549
2550 let body: Vec<u8> = [&[0x07, 0x01, 0x34][..], &namespace].concat();
2551 assert_eq!(body.len(), 16);
2552 let bytes = frame(0x02, &body);
2553
2554 let msg = ControlMessage::decode(&mut &bytes[..]).expect("spec-correct frame must decode");
2555 let ControlMessage::RequestUpdate(update) = &msg else {
2556 panic!("expected REQUEST_UPDATE, got {msg:?}")
2557 };
2558 assert_eq!(update.request_id.into_inner(), 7);
2559 assert_eq!(update.parameters, vec![param(0x34, &namespace)]);
2560
2561 let mut out = Vec::new();
2562 msg.encode(&mut out).expect("re-encode");
2563 assert_eq!(out, bytes, "no outer length may appear in front of the Track Namespace");
2564 }
2565
2566 /// An empty prefix is a legal Track Namespace: Section 2.4.1 puts one at
2567 /// "between 0 and 32 Track Namespace Fields". On the wire that is the
2568 /// single byte `0x00`, and it must not be confused with a length-prefixed
2569 /// value of zero bytes.
2570 #[test]
2571 fn an_empty_track_namespace_prefix_is_one_zero_byte() {
2572 let body = [0x07, 0x01, 0x34, 0x00];
2573 let bytes = frame(0x02, &body);
2574
2575 let msg = ControlMessage::decode(&mut &bytes[..]).expect("empty prefix must decode");
2576 let ControlMessage::RequestUpdate(update) = &msg else {
2577 panic!("expected REQUEST_UPDATE, got {msg:?}")
2578 };
2579 assert_eq!(update.parameters, vec![param(0x34, &[0x00])]);
2580
2581 let mut out = Vec::new();
2582 msg.encode(&mut out).expect("re-encode");
2583 assert_eq!(out, bytes);
2584 }
2585}