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
mod apdu;
mod asn1;
mod spdu;
pub mod sys;
mod tpdu;

use {
    anyhow::{Context, Result},
    nix::{ioctl_none, ioctl_read},
    std::{
        fs::{File, OpenOptions},
        os::unix::{
            fs::OpenOptionsExt,
            io::{AsRawFd, RawFd},
        },
        thread,
        time::Duration,
    },
    sys::*,
};

const CA_DELAY: Duration = Duration::from_millis(100);

#[derive(Debug)]
pub struct CaDevice {
    adapter: u32,
    device: u32,

    file: File,
    slot: CaSlotInfo,
}

impl AsRawFd for CaDevice {
    #[inline]
    fn as_raw_fd(&self) -> RawFd {
        self.file.as_raw_fd()
    }
}

impl CaDevice {
    /// Sends reset command to CA device
    #[inline]
    pub fn reset(&mut self) -> Result<()> {
        // CA_RESET
        ioctl_none!(
            #[inline]
            ca_reset,
            b'o',
            128
        );
        unsafe { ca_reset(self.as_raw_fd()) }.context("CA: failed to reset")?;

        Ok(())
    }

    /// Gets CA capabilities
    #[inline]
    pub fn get_caps(&self, caps: &mut CaCaps) -> Result<()> {
        // CA_GET_CAP
        ioctl_read!(
            #[inline]
            ca_get_cap,
            b'o',
            129,
            CaCaps
        );
        unsafe { ca_get_cap(self.as_raw_fd(), caps as *mut _) }
            .context("CA: failed to get caps")?;

        Ok(())
    }

    /// Gets CA slot information
    #[inline]
    pub fn get_slot_info(&mut self) -> Result<()> {
        // CA_GET_SLOT_INFO
        ioctl_read!(
            #[inline]
            ca_get_slot_info,
            b'o',
            130,
            CaSlotInfo
        );
        unsafe { ca_get_slot_info(self.as_raw_fd(), &mut self.slot as *mut _) }
            .context("CA: failed to get slot info")?;

        Ok(())
    }

    /// Attempts to open a CA device
    pub fn open(adapter: u32, device: u32, slot: u32) -> Result<CaDevice> {
        let path = format!("/dev/dvb/adapter{}/ca{}", adapter, device);
        let file = OpenOptions::new()
            .read(true)
            .write(true)
            .custom_flags(::nix::libc::O_NONBLOCK)
            .open(&path)
            .with_context(|| format!("CA: failed to open device {}", &path))?;

        let mut ca = CaDevice {
            adapter,
            device,

            file,
            slot: CaSlotInfo::default(),
        };

        ca.reset()?;

        thread::sleep(CA_DELAY);

        let mut caps = CaCaps::default();

        for _ in 0..5 {
            ca.get_caps(&mut caps)?;

            if caps.slot_num != 0 {
                break;
            }

            thread::sleep(CA_DELAY);
        }

        if slot >= caps.slot_num {
            return Err(anyhow!("CA: slot {} not found", slot));
        }

        ca.slot.slot_num = slot;
        ca.get_slot_info()?;

        if ca.slot.slot_type != CA_CI_LINK {
            return Err(anyhow!("CA: incompatible interface"));
        }

        // reset flags
        ca.slot.flags = CA_CI_MODULE_NOT_FOUND;

        Ok(ca)
    }

    fn poll_timer(&mut self) -> Result<()> {
        let flags = self.slot.flags;

        self.get_slot_info()?;

        match self.slot.flags {
            CA_CI_MODULE_PRESENT => {
                if flags == CA_CI_MODULE_READY {
                    // TODO: de-init
                }
                return Ok(());
            }
            CA_CI_MODULE_READY => {
                if flags != CA_CI_MODULE_READY {
                    tpdu::init(self, self.slot.slot_num as u8)?;
                }
            }
            CA_CI_MODULE_NOT_FOUND => {
                return Err(anyhow!("CA: module not found"));
            }
            _ => {
                return Err(anyhow!("CA: invalid slot flags"));
            }
        };

        // TODO: check queue?

        Ok(())
    }

    fn poll_event(&mut self) -> Result<()> {
        // TODO: tpdu read

        Ok(())
    }
}