Skip to main content

prolink_proto/
device.rs

1// SPDX-License-Identifier: GPL-3.0-only
2
3//! Device identity: numbers, names, hardware addresses and kinds.
4//!
5//! These types are shared by every layer of the protocol, and two of them exist
6//! to make a documented failure impossible to write rather than merely
7//! documented.
8
9use std::fmt;
10use std::num::NonZeroU8;
11
12use binrw::binrw;
13
14/// A device number a peer can hold.
15///
16/// Non-zero by construction: `0` on the wire means "no device", and a peer
17/// table that accepted it would grow an entry no request can ever be addressed
18/// to.
19#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
20pub struct DeviceNumber(NonZeroU8);
21
22impl DeviceNumber {
23    /// The lowest number a real player can be set to.
24    pub const MIN_PLAYER: u8 = 1;
25    /// The highest number a real player can be set to.
26    pub const MAX_PLAYER: u8 = 6;
27    /// The highest number a peer will offer as a browsable source (F45).
28    pub const MAX_BROWSABLE: u8 = 4;
29
30    /// Device number 1, the lowest a player can hold.
31    ///
32    /// Exists so that a caller needing a total fallback has one that is not a
33    /// panic.
34    pub const ONE: Self = Self(NonZeroU8::MIN);
35
36    /// Parse a device number, rejecting zero.
37    pub const fn new(raw: u8) -> Option<Self> {
38        match NonZeroU8::new(raw) {
39            Some(number) => Some(Self(number)),
40            None => None,
41        }
42    }
43
44    /// The number as it goes on the wire.
45    pub const fn get(self) -> u8 {
46        self.0.get()
47    }
48
49    /// Whether this is a number a real CDJ or mixer can be set to (1–6).
50    ///
51    /// Numbers above this range are what observer tools take, and they are
52    /// safe: they can never collide with hardware.
53    pub const fn is_player(self) -> bool {
54        self.get() >= Self::MIN_PLAYER && self.get() <= Self::MAX_PLAYER
55    }
56
57    /// This number as a [`BrowsableDeviceNumber`], or `None` if it is too high.
58    pub const fn browsable(self) -> Option<BrowsableDeviceNumber> {
59        if self.get() <= Self::MAX_BROWSABLE {
60            Some(BrowsableDeviceNumber(self))
61        } else {
62            None
63        }
64    }
65}
66
67impl fmt::Debug for DeviceNumber {
68    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69        write!(f, "device {}", self.get())
70    }
71}
72
73impl fmt::Display for DeviceNumber {
74    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75        write!(f, "{}", self.get())
76    }
77}
78
79/// A device number in 1–4: the range a peer will actually browse.
80///
81/// **This is a requirement, not a preference** (F45). At device 5 a CDJ accepts
82/// an announcement completely — it puts the announcer in its device table and
83/// unicasts hundreds of status packets to it — and then never sends a single
84/// media query, so it never offers the announcer as a source. The check
85/// precedes the whole browse path and the failure is entirely silent: every
86/// later step still works and none of them is ever reached.
87///
88/// Having a distinct type means a server that can never be browsed cannot be
89/// configured. Where 1–4 are all taken, the answer is to degrade to an observer
90/// number with serving switched off, and the type system makes that an explicit
91/// decision rather than an accident.
92#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
93pub struct BrowsableDeviceNumber(DeviceNumber);
94
95impl BrowsableDeviceNumber {
96    /// Parse a browsable device number, rejecting zero and anything above 4.
97    pub const fn new(raw: u8) -> Option<Self> {
98        match DeviceNumber::new(raw) {
99            Some(number) => number.browsable(),
100            None => None,
101        }
102    }
103
104    /// The number as it goes on the wire.
105    pub const fn get(self) -> u8 {
106        self.0.get()
107    }
108
109    /// Widen to a plain device number.
110    pub const fn number(self) -> DeviceNumber {
111        self.0
112    }
113
114    /// Every browsable number, highest first.
115    ///
116    /// Highest first because 1 and 2 are the decks a DJ reaches for, so a
117    /// virtual CDJ should leave them alone as long as it can.
118    pub fn descending() -> impl Iterator<Item = Self> {
119        (DeviceNumber::MIN_PLAYER..=DeviceNumber::MAX_BROWSABLE)
120            .rev()
121            .filter_map(Self::new)
122    }
123}
124
125impl From<BrowsableDeviceNumber> for DeviceNumber {
126    fn from(number: BrowsableDeviceNumber) -> Self {
127        number.0
128    }
129}
130
131impl fmt::Debug for BrowsableDeviceNumber {
132    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
133        fmt::Debug::fmt(&self.0, f)
134    }
135}
136
137impl fmt::Display for BrowsableDeviceNumber {
138    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
139        fmt::Display::fmt(&self.0, f)
140    }
141}
142
143/// The device model byte. Critical for impersonation.
144#[binrw]
145#[brw(big)]
146#[derive(Clone, Copy, PartialEq, Eq, Hash)]
147pub struct DeviceKind(pub u8);
148
149impl DeviceKind {
150    /// A DJM mixer.
151    pub const MIXER: Self = Self(0x01);
152    /// A CDJ player.
153    pub const CDJ: Self = Self(0x02);
154    /// rekordbox desktop, and also the CDJ-3000.
155    pub const REKORDBOX_OR_CDJ3000: Self = Self(0x03);
156    /// Seen only in the CDJ-3000 hello.
157    pub const CDJ3000_HELLO: Self = Self(0x04);
158
159    /// The `0x01` CDJ / `0x02` mixer role byte that recurs across packet kinds.
160    ///
161    /// Appears at offset `0x30` of the stage-2 claim and at `0x34` of the
162    /// keep-alive, and tracks the device kind in both. The pre-hardware
163    /// literature documents the first as a constant `0x01`; a real
164    /// DJM-2000nexus sends `0x02` (C1).
165    pub fn role(self) -> u8 {
166        if self == Self::MIXER { 0x02 } else { 0x01 }
167    }
168}
169
170impl fmt::Debug for DeviceKind {
171    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
172        match *self {
173            Self::MIXER => f.write_str("mixer"),
174            Self::CDJ => f.write_str("cdj"),
175            Self::REKORDBOX_OR_CDJ3000 => f.write_str("rekordbox_or_cdj3000"),
176            Self::CDJ3000_HELLO => f.write_str("cdj3000_hello"),
177            Self(raw) => write!(f, "DeviceKind({raw:#04x})"),
178        }
179    }
180}
181
182/// A 6-byte hardware address.
183#[binrw]
184#[brw(big)]
185#[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]
186pub struct MacAddress(pub [u8; 6]);
187
188impl fmt::Display for MacAddress {
189    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
190        let [o0, o1, o2, o3, o4, o5] = self.0;
191        write!(f, "{o0:02x}:{o1:02x}:{o2:02x}:{o3:02x}:{o4:02x}:{o5:02x}")
192    }
193}
194
195impl fmt::Debug for MacAddress {
196    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
197        fmt::Display::fmt(self, f)
198    }
199}
200
201/// A 20-byte NUL-padded device name.
202///
203/// Kept as the literal bytes rather than a `String` because the padding is part
204/// of what makes an announcement indistinguishable from a real one, and because
205/// `CDJ-2000nexus` is the exact casing observed on hardware (F1) — a decoded
206/// string cannot pin that.
207///
208/// The field sits at `0x0c` on UDP 50000 and at `0x0b` on UDP 50002. The type
209/// is shared; the offset is not.
210#[binrw]
211#[brw(big)]
212#[derive(Clone, Copy, PartialEq, Eq, Hash)]
213pub struct DeviceName(pub [u8; Self::LEN]);
214
215impl DeviceName {
216    /// Bytes the field occupies on both ports.
217    pub const LEN: usize = 20;
218
219    /// The name a CDJ-2000nexus announces, in its exact casing (F1).
220    pub const CDJ_2000_NEXUS: &'static str = "CDJ-2000nexus";
221
222    /// Build a padded name, truncating anything past [`Self::LEN`] bytes.
223    pub fn new(name: &str) -> Self {
224        let mut raw = [0u8; Self::LEN];
225        for (slot, byte) in raw.iter_mut().zip(name.bytes()) {
226            *slot = byte;
227        }
228        Self(raw)
229    }
230
231    /// The name up to its first NUL, with non-ASCII bytes replaced.
232    pub fn as_str(&self) -> String {
233        self.0
234            .iter()
235            .copied()
236            .take_while(|&byte| byte != 0)
237            .map(|byte| {
238                if byte.is_ascii() {
239                    char::from(byte)
240                } else {
241                    char::REPLACEMENT_CHARACTER
242                }
243            })
244            .collect()
245    }
246}
247
248impl Default for DeviceName {
249    fn default() -> Self {
250        Self::new(Self::CDJ_2000_NEXUS)
251    }
252}
253
254impl fmt::Display for DeviceName {
255    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
256        f.write_str(&self.as_str())
257    }
258}
259
260impl fmt::Debug for DeviceName {
261    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
262        write!(f, "{:?}", self.as_str())
263    }
264}
265
266#[cfg(test)]
267mod tests {
268    use super::*;
269
270    #[test]
271    fn zero_is_not_a_device_number() {
272        assert!(DeviceNumber::new(0).is_none());
273        assert!(BrowsableDeviceNumber::new(0).is_none());
274    }
275
276    #[test]
277    fn five_announces_fine_and_is_never_browsed() {
278        let five = DeviceNumber::new(5).expect("5 is a device number");
279        assert!(five.is_player(), "5 is a number a real player can hold");
280        assert!(
281            five.browsable().is_none(),
282            "but a peer will never browse it (F45)"
283        );
284    }
285
286    #[test]
287    fn browsable_numbers_come_out_highest_first() {
288        let numbers: Vec<u8> = BrowsableDeviceNumber::descending()
289            .map(BrowsableDeviceNumber::get)
290            .collect();
291        assert_eq!(
292            numbers,
293            vec![4, 3, 2, 1],
294            "leave 1 and 2 alone as long as possible"
295        );
296    }
297
298    #[test]
299    fn a_name_keeps_its_padding() {
300        let name = DeviceName::new(DeviceName::CDJ_2000_NEXUS);
301        assert_eq!(name.as_str(), "CDJ-2000nexus");
302        assert_eq!(name.0, *b"CDJ-2000nexus\0\0\0\0\0\0\0");
303    }
304
305    #[test]
306    fn a_name_longer_than_the_field_is_truncated() {
307        let name = DeviceName::new("a name far longer than twenty bytes");
308        assert_eq!(name.as_str(), "a name far longer th");
309    }
310}