use std::fmt;
use std::io::Cursor;
use std::net::Ipv4Addr;
use std::time::Duration;
use binrw::{BinRead, binrw, helpers::until_eof};
use crate::device::{DeviceKind, DeviceName, MacAddress};
use crate::{Error, MAGIC, Result};
pub const KEEPALIVE_INTERVAL: Duration = Duration::from_secs(2);
pub const DISCOVERY_INTERVAL: Duration = Duration::from_millis(300);
pub const DEVICE_TIMEOUT: Duration = Duration::from_secs(10);
pub const HEADER_LEN: usize = 0x24;
#[binrw]
#[brw(big)]
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct PacketKind(pub u8);
impl PacketKind {
pub const CLAIM_MAC: Self = Self(0x00);
pub const MIXER_ASSIGN_INTENT: Self = Self(0x01);
pub const CLAIM_IP: Self = Self(0x02);
pub const MIXER_ASSIGN: Self = Self(0x03);
pub const CLAIM_NUMBER: Self = Self(0x04);
pub const NUMBER_IN_USE: Self = Self(0x05);
pub const KEEP_ALIVE: Self = Self(0x06);
pub const NUMBER_CONFLICT: Self = Self(0x08);
pub const HELLO: Self = Self(0x0a);
pub fn name(self) -> Option<&'static str> {
Some(match self {
Self::CLAIM_MAC => "claim_mac",
Self::MIXER_ASSIGN_INTENT => "mixer_assign_intent",
Self::CLAIM_IP => "claim_ip",
Self::MIXER_ASSIGN => "mixer_assign",
Self::CLAIM_NUMBER => "claim_number",
Self::NUMBER_IN_USE => "number_in_use",
Self::KEEP_ALIVE => "keep_alive",
Self::NUMBER_CONFLICT => "number_conflict",
Self::HELLO => "hello",
_ => return None,
})
}
pub fn wire_length(self) -> Option<u8> {
Some(match self {
Self::HELLO => 0x25,
Self::CLAIM_MAC => 0x2c,
Self::CLAIM_IP => 0x32,
Self::CLAIM_NUMBER | Self::NUMBER_IN_USE => 0x26,
Self::KEEP_ALIVE => 0x36,
Self::NUMBER_CONFLICT => 0x29,
_ => return None,
})
}
}
impl fmt::Debug for PacketKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.name() {
Some(name) => f.write_str(name),
None => write!(f, "PacketKind({:#04x})", self.0),
}
}
}
#[binrw]
#[brw(big)]
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct AssignmentMode(pub u8);
impl AssignmentMode {
pub const AUTO: Self = Self(0x01);
pub const MANUAL: Self = Self(0x02);
}
impl fmt::Debug for AssignmentMode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
Self::AUTO => f.write_str("auto"),
Self::MANUAL => f.write_str("manual"),
Self(raw) => write!(f, "AssignmentMode({raw:#04x})"),
}
}
}
#[binrw]
#[brw(big, magic = b"Qspt1WmJOL")]
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Packet {
#[br(temp)]
#[bw(calc = body.kind())]
kind: PacketKind,
pub subtype: u8,
pub name: DeviceName,
pub const_one: u8,
pub device_kind: DeviceKind,
pub pad_22: u8,
pub stype: u8,
#[br(args(kind))]
pub body: Body,
#[br(parse_with = until_eof)]
pub trailing: Vec<u8>,
}
#[binrw]
#[brw(big)]
#[br(import(kind: PacketKind))]
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum Body {
#[br(pre_assert(kind == PacketKind::HELLO))]
Hello {
payload: u8,
},
#[br(pre_assert(kind == PacketKind::CLAIM_MAC))]
ClaimMac {
iteration: u8,
flags: u8,
mac: MacAddress,
},
#[br(pre_assert(kind == PacketKind::CLAIM_IP))]
ClaimIp {
#[br(map = |raw: [u8; 4]| Ipv4Addr::from(raw))]
#[bw(map = |ip: &Ipv4Addr| ip.octets())]
ip: Ipv4Addr,
mac: MacAddress,
device_number: u8,
iteration: u8,
role: u8,
assignment_mode: AssignmentMode,
},
#[br(pre_assert(kind == PacketKind::CLAIM_NUMBER))]
ClaimNumber {
device_number: u8,
iteration: u8,
},
#[br(pre_assert(kind == PacketKind::NUMBER_IN_USE))]
NumberInUse {
device_number: u8,
iteration: u8,
},
#[br(pre_assert(kind == PacketKind::KEEP_ALIVE))]
KeepAlive {
device_number: u8,
was_first_on_network: u8,
mac: MacAddress,
#[br(map = |raw: [u8; 4]| Ipv4Addr::from(raw))]
#[bw(map = |ip: &Ipv4Addr| ip.octets())]
ip: Ipv4Addr,
peer_count: u8,
pad_31: [u8; 3],
flags: u8,
trailing: u8,
},
#[br(pre_assert(kind == PacketKind::NUMBER_CONFLICT))]
NumberConflict {
device_number: u8,
#[br(map = |raw: [u8; 4]| Ipv4Addr::from(raw))]
#[bw(map = |ip: &Ipv4Addr| ip.octets())]
ip: Ipv4Addr,
},
Unknown {
#[br(calc = kind)]
#[bw(ignore)]
kind: PacketKind,
#[br(parse_with = until_eof)]
payload: Vec<u8>,
},
}
impl Body {
pub fn kind(&self) -> PacketKind {
match self {
Self::Hello { .. } => PacketKind::HELLO,
Self::ClaimMac { .. } => PacketKind::CLAIM_MAC,
Self::ClaimIp { .. } => PacketKind::CLAIM_IP,
Self::ClaimNumber { .. } => PacketKind::CLAIM_NUMBER,
Self::NumberInUse { .. } => PacketKind::NUMBER_IN_USE,
Self::KeepAlive { .. } => PacketKind::KEEP_ALIVE,
Self::NumberConflict { .. } => PacketKind::NUMBER_CONFLICT,
Self::Unknown { kind, .. } => *kind,
}
}
pub fn device_number(&self) -> Option<u8> {
match *self {
Self::ClaimIp { device_number, .. }
| Self::ClaimNumber { device_number, .. }
| Self::NumberInUse { device_number, .. }
| Self::KeepAlive { device_number, .. }
| Self::NumberConflict { device_number, .. } => Some(device_number),
_ => None,
}
}
pub fn mac(&self) -> Option<MacAddress> {
match *self {
Self::ClaimMac { mac, .. }
| Self::ClaimIp { mac, .. }
| Self::KeepAlive { mac, .. } => Some(mac),
_ => None,
}
}
pub fn ip(&self) -> Option<Ipv4Addr> {
match *self {
Self::ClaimIp { ip, .. }
| Self::KeepAlive { ip, .. }
| Self::NumberConflict { ip, .. } => Some(ip),
_ => None,
}
}
}
impl Packet {
pub fn new(name: DeviceName, device_kind: DeviceKind, body: Body) -> Self {
let stype = body.kind().wire_length().unwrap_or(0);
Self {
subtype: 0x00,
name,
const_one: 0x01,
device_kind,
pad_22: 0x00,
stype,
body,
trailing: Vec::new(),
}
}
pub fn kind(&self) -> PacketKind {
self.body.kind()
}
pub fn decode(data: &[u8]) -> Result<Self> {
if !carries_magic(data) {
let got = data.get(..MAGIC.len()).unwrap_or(data);
return Err(Error::BadMagic {
expected: MAGIC.as_slice().into(),
got: got.into(),
});
}
if data.len() < HEADER_LEN {
return Err(Error::Truncated {
need: HEADER_LEN,
at: 0,
have: data.len(),
});
}
Ok(Self::read(&mut Cursor::new(data))?)
}
pub fn encode(&self) -> Vec<u8> {
crate::to_bytes(self)
}
}
pub fn carries_magic(data: &[u8]) -> bool {
data.get(..MAGIC.len()) == Some(MAGIC.as_slice())
}
#[cfg(test)]
mod tests {
use super::*;
const KEEP_ALIVE: &[u8] = &[
0x51, 0x73, 0x70, 0x74, 0x31, 0x57, 0x6d, 0x4a, 0x4f, 0x4c, 0x06, 0x00, 0x43, 0x44, 0x4a,
0x2d, 0x32, 0x30, 0x30, 0x30, 0x6e, 0x65, 0x78, 0x75, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x01, 0x02, 0x00, 0x36, 0x05, 0x02, 0xa0, 0xce, 0xc8, 0xe2, 0x26, 0xde, 0xa9,
0xfe, 0x63, 0x64, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00,
];
#[test]
fn decodes_a_real_keep_alive() {
let packet = Packet::decode(KEEP_ALIVE).unwrap();
assert_eq!(packet.kind(), PacketKind::KEEP_ALIVE);
assert_eq!(packet.name.as_str(), "CDJ-2000nexus");
assert_eq!(packet.name.0, *b"CDJ-2000nexus\0\0\0\0\0\0\0");
assert_eq!(packet.device_kind, DeviceKind::CDJ);
assert_eq!(usize::from(packet.stype), KEEP_ALIVE.len());
assert_eq!(packet.stype, 0x36);
let Body::KeepAlive {
device_number,
mac,
ip,
peer_count,
trailing,
..
} = packet.body
else {
panic!("expected a keep-alive body, got {:?}", packet.body);
};
assert_eq!(device_number, 5);
assert_eq!(mac.to_string(), "a0:ce:c8:e2:26:de");
assert_eq!(ip, Ipv4Addr::new(169, 254, 99, 100));
assert_eq!(peer_count, 1);
assert_eq!(trailing, 0x00);
}
#[test]
fn round_trips_byte_for_byte() {
let packet = Packet::decode(KEEP_ALIVE).unwrap();
assert_eq!(packet.encode(), KEEP_ALIVE);
}
#[test]
fn an_unknown_kind_decodes_instead_of_failing() {
let mut raw = KEEP_ALIVE.to_vec();
raw[0x0a] = 0x7f;
let packet = Packet::decode(&raw).unwrap();
assert_eq!(packet.kind(), PacketKind(0x7f));
assert!(matches!(packet.body, Body::Unknown { .. }));
assert_eq!(
packet.encode(),
raw,
"an unknown body must survive a round trip"
);
}
#[test]
fn rejects_a_datagram_without_the_magic() {
assert!(matches!(
Packet::decode(b"not a djl packet at all"),
Err(Error::BadMagic { .. })
));
}
#[test]
fn rejects_a_short_datagram() {
assert!(matches!(
Packet::decode(&MAGIC),
Err(Error::Truncated { .. })
));
}
#[test]
fn builds_a_keep_alive_a_deck_would_accept() {
let built = Packet::new(
DeviceName::new(DeviceName::CDJ_2000_NEXUS),
DeviceKind::CDJ,
Body::KeepAlive {
device_number: 5,
was_first_on_network: 0x02,
mac: MacAddress([0xa0, 0xce, 0xc8, 0xe2, 0x26, 0xde]),
ip: Ipv4Addr::new(169, 254, 99, 100),
peer_count: 1,
pad_31: [0; 3],
flags: 0x01,
trailing: 0x00,
},
);
assert_eq!(
built.encode(),
KEEP_ALIVE,
"must be indistinguishable from the real one"
);
}
}