Skip to main content

pioneer_optical/
lib.rs

1//! Pioneer optical drive (BD/DVD) firmware and vendor protocol, as pure byte
2//! transforms plus command sequences over a caller-supplied transport.
3//!
4//! The public API is five modules:
5//!
6//! - `envelope` — the codec: load, header, repack, sign/verify and encode a
7//!   firmware envelope or a Kernel+Normal update (`envelope` feature).
8//! - `classify` — pair verdicts and their vocabulary (families, required
9//!   words, why two firmwares differ); never materializes an image.
10//! - `prepare` — materialize a corrected update against the installed
11//!   receiver into an opaque plan that yields the exact byte streams to write.
12//! - [`cdb`] — the vendor command descriptor blocks, as byte constructors, the
13//!   DVR handshake solver and refusal-sense classification. `no_std`.
14//! - `drive` — identify, read, capture, dump and update sequences over a
15//!   caller-supplied `drive::Transport` (`drive` feature).
16//!
17//! The crate root carries only shared vocabulary: [`Identity`], [`Role`],
18//! [`ComponentKind`], [`DriveClass`], [`CodedError`] and the lifecycle
19//! observations [`IssueKind`], [`Phase`], [`Component`] and [`Progress`].
20//!
21//! ## Drive state
22//!
23//! Two independent drive states gate the vendor commands:
24//!
25//! - **extended read** — enabled by [`cdb::knock`]. Allows [`cdb::read_memory`]
26//!   above the `0x8000` boot window; the drive refuses reads past
27//!   [`cdb::READ_CEILING`]. Read-only.
28//! - **update session** — entered by [`cdb::enter_update`]. Accepts Kernel and
29//!   Normal chunk writes ([`cdb::transfer`]) and the [`cdb::finish`] commit. DVR
30//!   generations require the [`cdb::dvr`] handshake before entry.
31//!
32//! Neither state enables the other.
33#![cfg_attr(not(feature = "std"), no_std)]
34#![deny(missing_docs)]
35#![forbid(unsafe_code)]
36
37// ---- Public API: exactly five modules -------------------------------------
38//
39// - [`envelope`]: the codec (load, header, repack, sign/verify, encode).
40// - [`classify`]: pair verdicts and their vocabulary; no materialization.
41// - [`prepare`]: materialize a corrected update into an opaque plan that
42//   yields the exact byte streams to write.
43// - [`cdb`]: vendor command bytes; no transport.
44// - [`drive`]: command sequences over a caller-supplied transport.
45//
46// Everything else is crate-private. The non-default `internals` feature
47// exposes the analysis modules to this crate's own corpus tests and research
48// examples only; applications must not enable it.
49
50macro_rules! internal {
51    ($($(#[$meta:meta])* mod $name:ident;)*) => {$(
52        $(#[$meta])*
53        #[cfg(feature = "internals")]
54        #[doc(hidden)]
55        pub mod $name;
56        $(#[$meta])*
57        #[cfg(not(feature = "internals"))]
58        pub(crate) mod $name;
59    )*};
60}
61
62pub mod cdb;
63#[cfg(feature = "envelope")]
64pub mod classify;
65#[cfg(feature = "drive")]
66pub mod drive;
67#[cfg(feature = "envelope")]
68pub mod envelope;
69#[cfg(feature = "envelope")]
70pub mod prepare;
71
72#[cfg(any(feature = "image", feature = "envelope"))]
73extern crate alloc;
74
75mod checksum;
76#[cfg(any(feature = "image", feature = "envelope"))]
77mod comp;
78#[cfg(feature = "analysis")]
79mod comp_runtime;
80#[cfg(feature = "image")]
81mod comp_streams;
82mod error_codes;
83#[cfg(feature = "image")]
84mod memo;
85mod product_identity;
86#[cfg(feature = "image")]
87mod shape;
88
89internal! {
90    #[cfg(feature = "analysis")]
91    mod analysis;
92    #[cfg(feature = "image")]
93    mod compatibility;
94    #[cfg(feature = "drive")]
95    mod device;
96    mod diagnostic;
97    #[cfg(feature = "image")]
98    mod filters;
99    #[cfg(feature = "image")]
100    mod ident;
101    #[cfg(feature = "image")]
102    mod image;
103    #[cfg(feature = "image")]
104    mod logging;
105    mod operation;
106    mod production;
107    mod protocol;
108    #[cfg(feature = "envelope")]
109    mod receiver;
110    mod rpc;
111    mod settings;
112    #[cfg(feature = "image")]
113    mod startup;
114}
115
116pub use error_codes::CodedError;
117pub use operation::{Component, IssueKind, Phase, Progress};
118pub use product_identity::ProductIdentity;
119
120/// Length of a standard INQUIRY response header, in bytes.
121pub const INQUIRY_LEN: usize = 36;
122/// Length of the vendor identity block, in bytes.
123pub const IDENTITY_LEN: usize = cdb::IDENTITY_LEN as usize;
124/// Minimum vendor identity length that carries every field.
125pub(crate) const IDENTITY_MIN: usize = 44;
126
127/// A firmware component written during an update session.
128#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
129pub enum Role {
130    /// The Kernel (boot and update loader) component.
131    Kernel,
132    /// The Normal (application) component.
133    Normal,
134}
135
136/// The kind of firmware component a Pioneer envelope carries.
137///
138/// A superset of [`Role`]: [`ComponentKind::Plane`] exists as an envelope but
139/// is not written through the update-session commands.
140#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
141#[cfg_attr(feature = "envelope", derive(serde::Serialize))]
142#[cfg_attr(feature = "envelope", serde(rename_all = "kebab-case"))]
143#[non_exhaustive]
144pub enum ComponentKind {
145    /// The Kernel (boot and update loader) component.
146    Kernel,
147    /// The Normal (application) component.
148    Normal,
149    /// The Plane component of the DVR generations.
150    Plane,
151}
152
153impl ComponentKind {
154    /// The literal `File Type` text of the envelope header.
155    pub const fn as_str(self) -> &'static str {
156        match self {
157            ComponentKind::Kernel => "Kernel",
158            ComponentKind::Normal => "Normal",
159            ComponentKind::Plane => "Plane",
160        }
161    }
162
163    /// Parse the literal `File Type` header text; `None` when unrecognized.
164    pub fn from_header(text: &str) -> Option<Self> {
165        match text {
166            "Kernel" => Some(ComponentKind::Kernel),
167            "Normal" => Some(ComponentKind::Normal),
168            "Plane" => Some(ComponentKind::Plane),
169            _ => None,
170        }
171    }
172}
173
174impl core::fmt::Display for ComponentKind {
175    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
176        f.write_str(self.as_str())
177    }
178}
179
180impl From<Role> for ComponentKind {
181    fn from(role: Role) -> Self {
182        match role {
183            Role::Kernel => ComponentKind::Kernel,
184            Role::Normal => ComponentKind::Normal,
185        }
186    }
187}
188
189impl TryFrom<ComponentKind> for Role {
190    type Error = ComponentKind;
191    /// Fails with the offending kind for [`ComponentKind::Plane`].
192    fn try_from(kind: ComponentKind) -> Result<Self, ComponentKind> {
193        match kind {
194            ComponentKind::Kernel => Ok(Role::Kernel),
195            ComponentKind::Normal => Ok(Role::Normal),
196            other => Err(other),
197        }
198    }
199}
200
201/// The vendor command dialect a drive speaks.
202#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
203#[non_exhaustive]
204pub enum DriveClass {
205    /// BD generations: [`cdb::enter_update`] enters the update session directly.
206    Bd,
207    /// DVR generations: the [`cdb::dvr`] handshake precedes [`cdb::enter_update`].
208    Dvr,
209}
210
211impl DriveClass {
212    /// Whether a host may offer automatic installed-firmware acquisition.
213    ///
214    /// Both vendor dialects provide firmware reads. Individual reads can still
215    /// fail or be protected; callers must validate the returned evidence and
216    /// must not treat this capability as a successful or complete backup.
217    pub const fn can_read(self) -> bool {
218        match self {
219            Self::Bd | Self::Dvr => true,
220        }
221    }
222}
223
224/// Trim trailing ASCII spaces and NULs and decode as UTF-8; `""` if invalid.
225fn field(raw: &[u8]) -> &str {
226    let end = raw
227        .iter()
228        .rposition(|&b| b != b' ' && b != 0)
229        .map_or(0, |i| i + 1);
230    core::str::from_utf8(&raw[..end]).unwrap_or("")
231}
232
233/// A drive's identity: the standard INQUIRY response plus the vendor identity
234/// block ([`cdb::vendor_identity`]).
235#[derive(Clone, Debug, PartialEq, Eq)]
236pub struct Identity {
237    inquiry: [u8; INQUIRY_LEN],
238    vendor: [u8; IDENTITY_LEN],
239}
240
241impl Identity {
242    /// Decode an INQUIRY response (at least [`INQUIRY_LEN`] bytes) and a vendor
243    /// identity block (at least 44 bytes). Returns `None` if either is short.
244    pub fn parse(inquiry: &[u8], vendor: &[u8]) -> Option<Self> {
245        if inquiry.len() < INQUIRY_LEN || vendor.len() < IDENTITY_MIN {
246            return None;
247        }
248        let mut id = Self {
249            inquiry: [0; INQUIRY_LEN],
250            vendor: [0; IDENTITY_LEN],
251        };
252        id.inquiry.copy_from_slice(&inquiry[..INQUIRY_LEN]);
253        let n = vendor.len().min(IDENTITY_LEN);
254        id.vendor[..n].copy_from_slice(&vendor[..n]);
255        Some(id)
256    }
257
258    /// Peripheral device type; `0x05` for an optical drive.
259    pub fn device_type(&self) -> u8 {
260        self.inquiry[0] & 0x1f
261    }
262    /// Vendor identification, e.g. `PIONEER`.
263    pub fn vendor(&self) -> &str {
264        field(&self.inquiry[8..16])
265    }
266    /// Product identification, e.g. `BD-RW   BDR-UD04`.
267    pub fn product(&self) -> &str {
268        field(&self.inquiry[16..32])
269    }
270    /// Structured vendor, drive model, product context and revision.
271    pub fn product_identity(&self) -> ProductIdentity<'_> {
272        ProductIdentity::from_fields(self.vendor(), self.product(), self.revision())
273    }
274    /// Firmware revision, e.g. `1.14`.
275    pub fn revision(&self) -> &str {
276        field(&self.inquiry[32..36])
277    }
278    /// Serial number.
279    pub fn serial(&self) -> &str {
280        field(&self.vendor[0..16])
281    }
282    /// Hardware platform code, e.g. `SAT 8A10`.
283    pub fn platform(&self) -> &str {
284        field(&self.vendor[16..24])
285    }
286    /// Tag of the installed Kernel, e.g. `ID40`. A Normal component is built
287    /// for exactly one Kernel tag.
288    pub fn kernel_tag(&self) -> &str {
289        field(&self.vendor[24..32])
290    }
291    /// Tag of the installed Normal, e.g. `ID40`. Empty while the drive is in
292    /// an update session.
293    pub fn normal_tag(&self) -> &str {
294        field(&self.vendor[32..40])
295    }
296    /// Trailing numeric code, e.g. `0000`.
297    pub fn code(&self) -> &str {
298        field(&self.vendor[40..44])
299    }
300    /// The raw INQUIRY response.
301    pub fn inquiry_bytes(&self) -> &[u8; INQUIRY_LEN] {
302        &self.inquiry
303    }
304    /// The raw vendor identity block.
305    pub fn vendor_bytes(&self) -> &[u8; IDENTITY_LEN] {
306        &self.vendor
307    }
308
309    /// The command dialect, or `None` when the identity matches neither class.
310    ///
311    /// A `BD-` product is [`DriveClass::Bd`]; a `DVD-R` product on a `DVR`
312    /// platform is [`DriveClass::Dvr`].
313    pub fn class(&self) -> Option<DriveClass> {
314        if self.product().starts_with("BD-") {
315            Some(DriveClass::Bd)
316        } else if self.product().starts_with("DVD-R") && self.platform().starts_with("DVR") {
317            Some(DriveClass::Dvr)
318        } else {
319            None
320        }
321    }
322}
323
324#[cfg(all(test, feature = "envelope"))]
325mod hardware_matrix_tests;
326#[cfg(test)]
327#[path = "lib_tests.rs"]
328mod tests;
329
330#[cfg(all(feature = "drive", feature = "envelope"))]
331#[doc = include_str!("../README.md")]
332mod readme_examples {}