libdvb 0.5.0

Interface for DVB-API v5 devices in Linux
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
//! en50221 7.1 transport layer: command-response framing over a [`CaDevice`]
//!
//! The transport owns the per-slot outgoing queue and busy flag, the
//! outgoing fragmentation of oversize SPDUs and the incoming reassembly
//! of TT_DATA_MORE fragments. The module never initiates: after every
//! successful write the slot is busy until the next read event for that
//! slot; outgoing TPDUs are queued per slot and flushed one at a time on
//! each read event (driven by the slot manager).

use std::{
    collections::VecDeque,
    os::{
        fd::{
            AsFd,
            BorrowedFd,
        },
        unix::io::{
            AsRawFd,
            RawFd,
        },
    },
};

use super::{
    CaDevice,
    apdu,
    apdu::ApduTag,
    spdu,
    tpdu,
    tpdu::{
        MAX_TPDU_DATA,
        MAX_TPDU_SIZE,
        TpduTag,
    },
};
use crate::error::{
    Error,
    Result,
};

/// Transport-level unit delivered by [`CiTransport::recv_apdu`]
#[derive(Debug)]
pub enum TransportRecv {
    /// TT_CTC_REPLY - the transport connection is established for the slot
    TcReply {
        /// slot the reply arrived on
        slot_id: u8,
    },
    /// A complete reassembled SPDU (for a session_number SPDU the tail is
    /// exactly one APDU - hence the method name recv_apdu)
    Spdu {
        /// slot the SPDU arrived on
        slot_id: u8,
        /// reassembled SPDU bytes
        spdu: Vec<u8>,
    },
    /// Status-only R_TPDU or an intermediate TT_DATA_MORE fragment;
    /// nothing to dispatch, but the busy/queue state advanced
    Status {
        /// slot the frame arrived on
        slot_id: u8,
    },
    /// A frame attributable to a slot that failed the strict validation
    /// (corrupt status trailer, length mismatch, unexpected tag,
    /// reassembly overflow); the frame content is dropped but the busy
    /// flag was cleared so the slot keeps going (legacy parity: real CAMs
    /// emit quirky frames and the command-response cycle must survive)
    Malformed {
        /// slot the frame arrived on
        slot_id: u8,
        /// human-readable description of the violation
        context: String,
    },
}

impl TransportRecv {
    /// Slot the received unit belongs to
    pub fn slot_id(&self) -> u8 {
        match self {
            TransportRecv::TcReply { slot_id }
            | TransportRecv::Spdu { slot_id, .. }
            | TransportRecv::Status { slot_id }
            | TransportRecv::Malformed { slot_id, .. } => *slot_id,
        }
    }
}

/// Per-slot transport state
struct TransportSlot {
    /// a write was issued; wait for the next read event for this slot
    busy: bool,
    /// pending framed TPDUs, flushed one per read event
    queue: VecDeque<Vec<u8>>,
    /// TT_DATA_MORE reassembly buffer, capped at MAX_TPDU_SIZE
    rx_buffer: Vec<u8>,
    /// DATA_INDICATOR seen on the last received frame
    data_pending: bool,
}

impl TransportSlot {
    fn new() -> Self {
        TransportSlot {
            busy: false,
            queue: VecDeque::new(),
            rx_buffer: Vec::new(),
            data_pending: false,
        }
    }
}

/// en50221 7.1 transport layer: command-response framing over a [`CaDevice`]
///
/// The module never initiates: after every successful write the slot is
/// busy until the next read event for that slot. Outgoing TPDUs are
/// queued per slot and flushed one at a time on each read event.
pub struct CiTransport {
    link: CaDevice,
    slots: Vec<TransportSlot>,
    /// single read scratch buffer, like the legacy ca_buffer
    rx: Box<[u8; MAX_TPDU_SIZE]>,
}

impl AsRawFd for CiTransport {
    fn as_raw_fd(&self) -> RawFd {
        self.link.as_raw_fd()
    }
}

impl AsFd for CiTransport {
    fn as_fd(&self) -> BorrowedFd<'_> {
        self.link.as_fd()
    }
}

impl CiTransport {
    /// Creates a transport for `slots_num` slots over the given link
    ///
    /// `slots_num` typically comes from `CaDevice::caps().slot_num`.
    pub fn new(link: CaDevice, slots_num: u8) -> Self {
        CiTransport {
            link,
            slots: (0 .. slots_num).map(|_| TransportSlot::new()).collect(),
            rx: Box::new([0; MAX_TPDU_SIZE]),
        }
    }

    /// Returns a reference to the underlying link
    pub fn link(&self) -> &CaDevice {
        &self.link
    }

    /// Returns a mutable reference to the underlying link
    pub fn link_mut(&mut self) -> &mut CaDevice {
        &mut self.link
    }

    /// Number of slots the transport was created with
    pub fn slots_num(&self) -> u8 {
        self.slots.len() as u8
    }

    fn check_slot(&self, slot_id: u8) -> Result<()> {
        if usize::from(slot_id) < self.slots.len() {
            Ok(())
        } else {
            Err(Error::InvalidProperty(format!(
                "ca invalid slot id {}",
                slot_id
            )))
        }
    }

    /// Builds a session_number SPDU + APDU and sends it, fragmenting into
    /// TT_DATA_MORE chunks of `MAX_TPDU_DATA` plus a final TT_DATA_LAST
    pub fn send_apdu(
        &mut self,
        slot_id: u8,
        session_id: u16,
        tag: ApduTag,
        body: &[u8],
    ) -> Result<()> {
        if body.len() > usize::from(u16::MAX) {
            return Err(Error::InvalidProperty(format!(
                "ca apdu body is too large: {} bytes",
                body.len()
            )));
        }

        let mut blob = spdu::build_session_number(session_id);
        apdu::build(&mut blob, tag, body);

        self.send_spdu(slot_id, &blob)
    }

    /// Sends a raw SPDU (session-control responses built by the session
    /// layer); fragments exactly like [`CiTransport::send_apdu`]
    pub fn send_spdu(&mut self, slot_id: u8, spdu: &[u8]) -> Result<()> {
        self.check_slot(slot_id)?;

        let mut offset = 0;
        while spdu.len() - offset > MAX_TPDU_DATA {
            self.send_tpdu(
                slot_id,
                TpduTag::DATA_MORE,
                &spdu[offset .. offset + MAX_TPDU_DATA],
            )?;
            offset += MAX_TPDU_DATA;
        }

        self.send_tpdu(slot_id, TpduTag::DATA_LAST, &spdu[offset ..])
    }

    /// Queues one TPDU (TT_CREATE_TC, TT_RCV, the empty TT_DATA_LAST
    /// poll, ...) and flushes immediately when the slot is idle
    pub fn send_tpdu(&mut self, slot_id: u8, tag: TpduTag, data: &[u8]) -> Result<()> {
        self.check_slot(slot_id)?;

        let frame = tpdu::build(slot_id, tag, data)?;
        self.slots[usize::from(slot_id)].queue.push_back(frame);

        self.flush(slot_id)
    }

    /// Writes the next queued TPDU if the slot is idle (one frame only)
    ///
    /// A transient `WouldBlock` or `Interrupted` error leaves the frame at
    /// the head of the queue and the slot idle. The caller can retry `flush`
    /// when the descriptor becomes writable. Other link errors propagate
    /// with the failed frame dropped; the slot manager is expected to reset
    /// the slot in that case.
    pub fn flush(&mut self, slot_id: u8) -> Result<()> {
        self.check_slot(slot_id)?;

        let slot = &mut self.slots[usize::from(slot_id)];
        Self::flush_slot(slot, |frame| self.link.send_msg(frame))
    }

    /// Attempts one queued write. Kept separate from the device wrapper so
    /// the queue transition can be tested with deterministic write results.
    fn flush_slot(slot: &mut TransportSlot, send: impl FnOnce(&[u8]) -> Result<()>) -> Result<()> {
        if slot.busy {
            return Ok(());
        }
        let frame = match slot.queue.front() {
            Some(frame) => frame,
            None => return Ok(()),
        };

        match send(frame) {
            Ok(()) => {
                slot.queue.pop_front();
                slot.busy = true;
            }
            Err(Error::Io(e))
                if matches!(
                    e.kind(),
                    std::io::ErrorKind::WouldBlock | std::io::ErrorKind::Interrupted
                ) =>
            {
                // The frame has not been accepted by the non-blocking link.
                // Keep it queued so a writable event can retry it.
            }
            Err(e) => {
                // A short write or a permanent link failure leaves the
                // command/response state ambiguous. Drop this frame and let
                // the caller reset the slot rather than resend a potentially
                // partially accepted command.
                slot.queue.pop_front();
                return Err(e);
            }
        }

        Ok(())
    }

    /// Pulls one frame from the link and advances the transport state
    ///
    /// Returns `Ok(None)` when the link has no data. Clears the busy flag
    /// for the slot, accumulates TT_DATA_MORE fragments (bounded at
    /// `MAX_TPDU_SIZE` (2048), overflow drops the buffer) and records the
    /// DATA_INDICATOR status bit.
    pub fn recv_apdu(&mut self) -> Result<Option<TransportRecv>> {
        let len = match self.link.recv_msg(&mut self.rx[..])? {
            Some(len) => len,
            None => return Ok(None),
        };
        if len == 0 {
            // a zero-length read is end-of-stream
            return Err(Error::Io(std::io::Error::new(
                std::io::ErrorKind::UnexpectedEof,
                "ca link closed (zero-length read)",
            )));
        }

        let slots_num = self.slots.len() as u8;

        let frame_slot = tpdu::frame_slot_id(&self.rx[.. len], slots_num);
        if let Some(slot_id) = frame_slot {
            self.slots[usize::from(slot_id)].busy = false;
        }

        let parsed = match tpdu::parse(&self.rx[.. len], slots_num) {
            Ok(parsed) => parsed,
            Err(Error::InvalidData(context)) => {
                return match frame_slot {
                    // the frame content is dropped, the slot keeps going
                    Some(slot_id) => Ok(Some(TransportRecv::Malformed { slot_id, context })),
                    None => Err(Error::InvalidData(context)),
                };
            }
            Err(e) => return Err(e),
        };
        let slot_id = parsed.slot_id;
        let tag = parsed.tag;
        let data_indicator = parsed.data_indicator;

        let slot = self
            .slots
            .get_mut(usize::from(slot_id))
            .expect("tpdu::parse bounds the slot id");

        slot.data_pending = data_indicator;

        match tag {
            TpduTag::CTC_REPLY => Ok(Some(TransportRecv::TcReply { slot_id })),
            TpduTag::DATA_MORE | TpduTag::DATA_LAST => {
                if slot.rx_buffer.len() + parsed.body.len() > MAX_TPDU_SIZE {
                    slot.rx_buffer.clear();
                    return Ok(Some(TransportRecv::Malformed {
                        slot_id,
                        context: format!("ca slot {}: tpdu reassembly buffer overflow", slot_id),
                    }));
                }
                slot.rx_buffer.extend_from_slice(parsed.body);

                if tag == TpduTag::DATA_MORE || slot.rx_buffer.is_empty() {
                    // intermediate fragment, or an empty poll response
                    Ok(Some(TransportRecv::Status { slot_id }))
                } else {
                    let spdu = std::mem::take(&mut slot.rx_buffer);
                    Ok(Some(TransportRecv::Spdu { slot_id, spdu }))
                }
            }
            TpduTag::SB => Ok(Some(TransportRecv::Status { slot_id })),
            // DTC_REPLY, REQUEST_TC, NEW_TC, TC_ERROR: parsed but not
            // expected by this host - dropped, slot keeps going
            tag => Ok(Some(TransportRecv::Malformed {
                slot_id,
                context: format!("ca slot {}: unexpected tpdu tag {:?}", slot_id, tag),
            })),
        }
    }

    /// Returns true while the slot waits for a read event after a write
    pub fn is_busy(&self, slot_id: u8) -> bool {
        self.slots
            .get(usize::from(slot_id))
            .is_some_and(|slot| slot.busy)
    }

    /// Number of queued (not yet written) TPDUs for the slot
    pub fn queue_len(&self, slot_id: u8) -> usize {
        self.slots
            .get(usize::from(slot_id))
            .map_or(0, |slot| slot.queue.len())
    }

    /// Takes and clears the DATA_INDICATOR flag for the slot
    pub fn take_data_pending(&mut self, slot_id: u8) -> bool {
        match self.slots.get_mut(usize::from(slot_id)) {
            Some(slot) => std::mem::take(&mut slot.data_pending),
            None => false,
        }
    }

    /// Clears the queue, busy flag and reassembly buffer for the slot
    pub fn clear_slot(&mut self, slot_id: u8) {
        if let Some(slot) = self.slots.get_mut(usize::from(slot_id)) {
            slot.busy = false;
            slot.queue.clear();
            slot.rx_buffer.clear();
            slot.data_pending = false;
        }
    }
}

#[cfg(test)]
mod tests {
    use std::{
        fs::File,
        os::{
            fd::OwnedFd,
            unix::net::UnixDatagram,
        },
    };

    use super::*;

    #[test]
    fn test_transient_write_error_keeps_queued_frame() {
        for kind in [
            std::io::ErrorKind::WouldBlock,
            std::io::ErrorKind::Interrupted,
        ] {
            let mut slot = TransportSlot::new();
            slot.queue.push_back(vec![0x01, 0x02, 0x03]);

            CiTransport::flush_slot(&mut slot, |_| Err(Error::Io(std::io::Error::from(kind))))
                .unwrap();

            assert_eq!(slot.queue, [vec![0x01, 0x02, 0x03]]);
            assert!(!slot.busy);

            CiTransport::flush_slot(&mut slot, |_| Ok(())).unwrap();
            assert!(slot.queue.is_empty());
            assert!(slot.busy);
        }
    }

    #[test]
    fn test_permanent_write_error_drops_ambiguous_frame() {
        let mut slot = TransportSlot::new();
        slot.queue.push_back(vec![0x01]);
        slot.queue.push_back(vec![0x02]);

        let result = CiTransport::flush_slot(&mut slot, |_| {
            Err(Error::Io(std::io::Error::from(
                std::io::ErrorKind::BrokenPipe,
            )))
        });

        assert!(result.is_err());
        assert_eq!(slot.queue, [vec![0x02]]);
        assert!(!slot.busy);
    }

    #[test]
    fn test_malformed_header_is_attributed_to_physical_slot() {
        let (host, cam) = UnixDatagram::pair().unwrap();
        host.set_nonblocking(true).unwrap();
        let host = File::from(OwnedFd::from(host));
        let mut transport = CiTransport::new(CaDevice::from_file(host), 2);
        transport.slots[0].busy = true;
        transport.slots[1].busy = true;

        // Physical slot 0 with the transport connection id of slot 1.
        cam.send(&[0x00, 0x02, 0x80, 0x02, 0x02, 0x00]).unwrap();

        assert!(matches!(
            transport.recv_apdu().unwrap(),
            Some(TransportRecv::Malformed { slot_id: 0, .. })
        ));
        assert!(!transport.slots[0].busy);
        assert!(transport.slots[1].busy);
    }
}