1
// Copyright 2020 sacn Developers
2
//
3
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
4
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5
// http://opensource.org/licenses/MIT>, at your option. This file may not be
6
// copied, modified, or distributed except according to those terms.
7
//
8
// This file was modified as part of a University of St Andrews Computer Science BSC Senior Honours Dissertation Project.
9

            
10
#![warn(missing_docs)]
11

            
12
//! Parsing of sacn network packets.
13
//!
14
//! The packets live within the scope of the ACN protocol suite.
15
//!
16
//! # Examples
17
//!
18
//! ```
19
//! # extern crate uuid;
20
//! # extern crate sacn;
21
//! # use uuid::Uuid;
22
//! # use sacn::packet::{AcnRootLayerProtocol, E131RootLayer, E131RootLayerData, DataPacketFramingLayer, DataPacketDmpLayer};
23
//! # fn main() {
24
//! #[cfg(feature = "std")]
25
//! # {
26
//! let packet = AcnRootLayerProtocol {
27
//!     pdu: E131RootLayer {
28
//!         cid: Uuid::new_v4(),
29
//!         data: E131RootLayerData::DataPacket(DataPacketFramingLayer {
30
//!             source_name: "Source_A".into(),
31
//!             priority: 100,
32
//!             synchronization_address: 7962,
33
//!             sequence_number: 154,
34
//!             preview_data: false,
35
//!             stream_terminated: false,
36
//!             force_synchronization: false,
37
//!             universe: 1,
38
//!             data: DataPacketDmpLayer {
39
//!                 property_values: vec![0, 1, 2, 3].into(),
40
//!             },
41
//!         }),
42
//!     },
43
//! };
44
//!
45
//! let mut buf = [0; 638];
46
//! packet.pack(&mut buf).unwrap();
47
//!
48
//! assert_eq!(
49
//!     AcnRootLayerProtocol::parse(&buf).unwrap(),
50
//!     packet
51
//! );
52
//! # }}
53
//! ```
54

            
55
/// Uses the sACN errors.
56
use crate::error::errors::{Result, SacnError};
57
use crate::sacn_parse_pack_error::ParsePacketError;
58

            
59
/// The core crate is used for string processing during packet parsing/packing as well as to provide access to the Hash trait.
60
use core::hash::{self, Hash};
61
use core::str;
62

            
63
use std::borrow::Cow;
64
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
65
use std::vec::Vec;
66
use std::{time, time::Duration};
67

            
68
use socket2::SockAddr;
69

            
70
/// The byteorder crate is used for marshalling data on/off the network in Network Byte Order.
71
use byteorder::{ByteOrder, NetworkEndian};
72

            
73
/// The uuid crate is used for working with/generating UUIDs which sACN uses as part of the cid field in the protocol.
74
use uuid::Uuid;
75

            
76
/// The maximum number of universes per page in a universe discovery packet.
77
pub const DISCOVERY_UNI_PER_PAGE: usize = 512;
78

            
79
/// The universe used for universe discovery as defined in ANSI E1.31-2018 Appendix A: Defined Parameters (Normative)
80
pub const E131_DISCOVERY_UNIVERSE: u16 = 64214;
81

            
82
/// The default priority used for the E1.31 packet priority field, as per ANSI E1.31-2018 Section 4.1 Table 4-1
83
pub const E131_DEFAULT_PRIORITY: u8 = 100;
84

            
85
/// The maximum allowed priority for a E1.31 packet, as per ANSI E1.31-2018 Section 6.2.3
86
pub const E131_MAX_PRIORITY: u8 = 200;
87

            
88
/// Value of the highest byte of the IPV4 multicast address as specified in section 9.3.1 of ANSI E1.31-2018.
89
pub const E131_MULTICAST_IPV4_HIGHEST_BYTE: u8 = 239;
90

            
91
/// Value of the second highest byte of the IPV4 multicast address as specified in section 9.3.1 of ANSI E1.31-2018.
92
pub const E131_MULTICAST_IPV4_SECOND_BYTE: u8 = 255;
93

            
94
/// The maximum universe number that can be used with the E1.31 protocol as specified in section 9.1.1 of ANSI E1.31-2018.
95
pub const E131_MAX_MULTICAST_UNIVERSE: u16 = 63999;
96

            
97
/// The lowest / minimum universe number that can be used with the E1.31 protocol as specified in section 9.1.1 of ANSI E1.31-2018.
98
pub const E131_MIN_MULTICAST_UNIVERSE: u16 = 1;
99

            
100
/// The synchronisation address used to indicate that there is no synchronisation required for the data packet.
101
/// As defined in ANSI E1.31-2018 Section 6.2.4.1
102
pub const E131_NO_SYNC_ADDR: u16 = 0;
103

            
104
/// The DMX512-A Null START Code, the first property value of a data packet carrying ordinary dimmer levels.
105
/// As defined in ANSI E1.11 Section 8.5.1 and used by ANSI E1.31-2016 Section 6.6.
106
pub const E131_NULL_START_CODE: u8 = 0x00;
107

            
108
/// The interval between universe discovery packets (adverts) as defined by ANSI E1.31-2018 Appendix A.
109
pub const E131_UNIVERSE_DISCOVERY_INTERVAL: Duration = time::Duration::from_secs(10);
110

            
111
/// The exclusive lower bound on the different between the received and expected sequence numbers within which a
112
/// packet will be discarded. Outside of the range specified by (`E131_SEQ_DIFF_DISCARD_LOWER_BOUND`, `E131_SEQ_DIFF_DISCARD_UPPER_BOUND`]
113
/// the packet won't be discarded.
114
///
115
/// Having a range allows receivers to catch up if packets are lost.
116
/// Value as specified in ANSI E1.31-2018 Section 6.7.2 Sequence Numbering.
117
pub const E131_SEQ_DIFF_DISCARD_LOWER_BOUND: isize = -20;
118

            
119
/// The inclusive upper bound on the different between the received and expected sequence numbers within which a
120
/// packet will be discarded. Outside of the range specified by (`E131_SEQ_DIFF_DISCARD_LOWER_BOUND`, `E131_SEQ_DIFF_DISCARD_UPPER_BOUND`]
121
/// the packet won't be discarded.
122
///
123
/// Having a range allows receivers to catch up if packets are lost.
124
/// Value as specified in ANSI E1.31-2018 Section 6.7.2 Sequence Numbering.
125
pub const E131_SEQ_DIFF_DISCARD_UPPER_BOUND: isize = 0;
126

            
127
/// The bit mask used to get the preview-data option within the packet option field as per
128
/// ANSI E1.31-2018 Section 6.2.6
129
pub const E131_PREVIEW_DATA_OPTION_BIT_MASK: u8 = 0b1000_0000;
130

            
131
/// The bit mask used to get the stream-termination option within the packet option field as per
132
/// ANSI E1.31-2018 Section 6.2.6
133
pub const E131_STREAM_TERMINATION_OPTION_BIT_MASK: u8 = 0b0100_0000;
134

            
135
/// The bit mask used to get the force-synchronisation option within the packet option field as per
136
/// ANSI E1.31-2018 Section 6.2.6
137
pub const E131_FORCE_SYNCHRONISATION_OPTION_BIT_MASK: u8 = 0b0010_0000;
138

            
139
/// The minimum allowed length of the discovery layer of an ANSI E1.31-2018 universe discovery packet.
140
/// As per ANSI E1.31-2018 Section 8 Table 8-9.
141
pub const E131_UNIVERSE_DISCOVERY_LAYER_MIN_LENGTH: usize = 8;
142

            
143
/// The maximum allowed length of the discovery layer of an ANSI E1.31-2018 universe discovery packet.
144
/// As per ANSI E1.31-2018 Section 8 Table 8-9.
145
pub const E131_UNIVERSE_DISCOVERY_LAYER_MAX_LENGTH: usize = 1032;
146

            
147
/// The expected value of the root layer length field for a synchronisation packet.
148
/// 33 bytes as per ANSI E1.31-2018 Section 4.2 Table 4-2.
149
pub const E131_UNIVERSE_SYNC_PACKET_ROOT_LENGTH: usize = 33;
150

            
151
/// The expected value of the framing layer length field for a synchronisation packet.
152
/// 11 bytes as per ANSI E1.31-2018 Section 4.2 Table 4-2.
153
pub const E131_UNIVERSE_SYNC_PACKET_FRAMING_LAYER_LENGTH: usize = 11;
154

            
155
/// The minimum expected value of the framing layer length field for a discovery packet.
156
/// 84 bytes as per ANSI E1.31-2018 Section 4.3 Table 4-3.
157
pub const E131_UNIVERSE_DISCOVERY_FRAMING_LAYER_MIN_LENGTH: usize = 82;
158

            
159
/// The number of stream termination packets sent when a source terminates a stream.
160
/// Set to 3 as per section 6.2.6 , `Stream_Terminated`: Bit 6 of ANSI E1.31-2018.
161
pub const E131_TERMINATE_STREAM_PACKET_COUNT: usize = 3;
162

            
163
/// The length of the pdu flags and length field in bytes.
164
pub const E131_PDU_LENGTH_FLAGS_LENGTH: usize = 2;
165

            
166
/// The pdu flags expected for an ANSI E1.31-2018 packet as per ANSI E1.31-2018 Section 4 Table 4-1, 4-2, 4-3.
167
pub const E131_PDU_FLAGS: u8 = 0x70;
168

            
169
/// The length in bytes of the root layer vector field as per ANSI E1.31-2018 Section 4 Table 4-1, 4-2, 4-3.
170
pub const E131_ROOT_LAYER_VECTOR_LENGTH: usize = 4;
171

            
172
/// The length in bytes of the E1.31 framing layer vector field as per ANSI E1.31-2018 Section 4 Table 4-1, 4-2, 4-3.
173
pub const E131_FRAMING_LAYER_VECTOR_LENGTH: usize = 4;
174

            
175
/// The length in bytes of the priority field within an ANSI E1.31-2018 data packet as defined in ANSI E1.31-2018 Section 4, Table 4-1.
176
const E131_PRIORITY_FIELD_LENGTH: usize = 1;
177

            
178
/// The length in bytes of the sequence number field within an ANSI E1.31-2018 packet as defined in ANSI E1.31-2018 Section 4, Table 4-1, 4-2.
179
const E131_SEQ_NUM_FIELD_LENGTH: usize = 1;
180

            
181
/// The length in bytes of the options field within an ANSI E1.31-2018 data packet as defined in ANSI E1.31-2018 Section 4, Table 4-1.
182
const E131_OPTIONS_FIELD_LENGTH: usize = 1;
183

            
184
/// The length in bytes of a universe field within an ANSI E1.31-2018 packet as defined in ANSI E1.31-2018 Section 4, Table 4-1, 4-3.
185
const E131_UNIVERSE_FIELD_LENGTH: usize = 2;
186

            
187
/// The length in bytes of the Vector field within the DMP layer of an ANSI E1.31-2018 data packet as per ANSI E1.31-2018
188
/// Section 4, Table 4-1.
189
const E131_DATA_PACKET_DMP_LAYER_VECTOR_FIELD_LENGTH: usize = 1;
190

            
191
/// The length in bytes of the "Address Type and Data Type" field within an ANSI E1.31-2018 data packet DMP layer as per
192
/// ANSI E1.31-2018 Section 4, Table 4-1.
193
const E131_DATA_PACKET_DMP_LAYER_ADDRESS_DATA_FIELD_LENGTH: usize = 1;
194

            
195
/// The length in bytes of the "First Property Address" field within an ANSI E1.31-2018 data packet DMP layer as per
196
/// ANSI E1.31-2018 Section 4, Table 4-1.
197
const E131_DATA_PACKET_DMP_LAYER_FIRST_PROPERTY_ADDRESS_FIELD_LENGTH: usize = 2;
198

            
199
/// The length in bytes of the "Address Increment" field within an ANSI E1.31-2018 data packet DMP layer as per
200
/// ANSI E1.31-2018 Section 4, Table 4-1.
201
const E131_DATA_PACKET_DMP_LAYER_ADDRESS_INCREMENT_FIELD_LENGTH: usize = 2;
202

            
203
/// The length in bytes of the "Property value count" field within an ANSI E1.31-2018 data packet DMP layer as per
204
/// ANSI E1.31-2018 Section 4, Table 4-1.
205
const E131_DATA_PACKET_DMP_LAYER_PROPERTY_VALUE_COUNT_FIELD_LENGTH: usize = 2;
206

            
207
/// The length in bytes of the Vector field in the Universe Discovery Layer of an ANSI E1.31-2018 Universe Discovery Packet.
208
/// 4 bytes as per ANSI E1.31-2018 Section 4, Table 4-3.
209
const E131_DISCOVERY_LAYER_VECTOR_FIELD_LENGTH: usize = 4;
210

            
211
/// The length in bytes of the Page field in the Universe Discovery Layer of an ANSI E1.31-2018 Universe Discovery Packet.
212
/// 1 bytes as per ANSI E1.31-2018 Section 4, Table 4-3.
213
const E131_DISCOVERY_LAYER_PAGE_FIELD_LENGTH: usize = 1;
214

            
215
/// The length in bytes of the Last Page field in the Universe Discovery Layer of an ANSI E1.31-2018 Universe Discovery Packet.
216
/// 1 bytes as per ANSI E1.31-2018 Section 4, Table 4-3.
217
const E131_DISCOVERY_LAYER_LAST_PAGE_FIELD_LENGTH: usize = 1;
218

            
219
/// The value of the "Address Type and Data Type" field within an ANSI E1.31-2018 data packet DMP layer as per ANSI E1.31-2018
220
/// Section 4, Table 4-1.
221
const E131_DMP_LAYER_ADDRESS_DATA_FIELD: u8 = 0xa1;
222

            
223
/// The value of the "First Property Address" field within an ANSI E1.31-2018 data packet DMP layer as per ANSI E1.31-2018
224
/// Section 4, Table 4-1.
225
const E131_DATA_PACKET_DMP_LAYER_FIRST_PROPERTY_FIELD: u16 = 0x0000;
226

            
227
/// The value of the "Address Increment" field within an ANSI E1.31-2018 data packet DMP layer as per ANSI E1.31-2018
228
/// Section 4, Table 4-1.
229
const E131_DATA_PACKET_DMP_LAYER_ADDRESS_INCREMENT: u16 = 0x0001;
230

            
231
/// The size of the ACN root layer preamble, must be 0x0010 bytes as per ANSI E1.31-2018 Section 5.1.
232
/// Often treated as a usize for comparison or use with arrays however stored as u16 as this represents its field size
233
/// within a packet and converting u16 -> usize is always safe as len(usize) is always greater than len(u16), usize -> u16 is unsafe.
234
const E131_PREAMBLE_SIZE: u16 = 0x0010;
235

            
236
/// The size of the ACN root layer postamble, must be 0x0 bytes as per ANSI E1.31-2018 Section 5.2.
237
const E131_POSTAMBLE_SIZE: u16 = 0x0;
238

            
239
/// The E131 ACN packet identifier field value. Must be 0x41 0x53 0x43 0x2d 0x45 0x31 0x2e 0x31 0x37 0x00 0x00 0x00 as per
240
/// ANSI E1.31-2018 Section 5.3.
241
const E131_ACN_PACKET_IDENTIFIER: [u8; 12] = [
242
    0x41, 0x53, 0x43, 0x2d, 0x45, 0x31, 0x2e, 0x31, 0x37, 0x00, 0x00, 0x00,
243
];
244

            
245
/// The E131 CID field length in bytes as per ANSI E1.31-2018 Section 4 Table 4-1, 4-2, 4-3.
246
pub const E131_CID_FIELD_LENGTH: usize = 16;
247

            
248
// The exclusive end index of the CID field. Calculated based on previous values defined in ANSI E1.31-2018 Section 4 Table 4-1, 4-2, 4-3.
249
const E131_CID_END_INDEX: usize =
250
    E131_PDU_LENGTH_FLAGS_LENGTH + E131_ROOT_LAYER_VECTOR_LENGTH + E131_CID_FIELD_LENGTH;
251

            
252
/// The length of the Source Name field in bytes in an ANSI E1.31-2018 packet as per ANSI E1.31-2018 Section 4, Table 4-1, 4-2, 4-3.
253
pub const E131_SOURCE_NAME_FIELD_LENGTH: usize = 64;
254

            
255
/// The maximum length of a source name in bytes (UTF-8), as per ANSI E1.31-2016 Section 6.2.2.
256
///
257
/// The source name field is 64 bytes and must be null-terminated, which leaves 63 bytes for the name itself.
258
pub const E131_SOURCE_NAME_MAX_LENGTH: usize = E131_SOURCE_NAME_FIELD_LENGTH - 1;
259

            
260
/// The length of the Synchronisation Address field in bytes in an ANSI E1.31-2018 packet as per ANSI E1.31-2018 Section 4, Table 4-1, 4-2, 4-3.
261
pub const E131_SYNC_ADDR_FIELD_LENGTH: usize = 2;
262

            
263
/// The length in bytes of the sequence number field within the framing layer of an E1.31 synchronisation packet.
264
/// AS per ANSI E1.31-2018 Section 4, Table 4-2.
265
const E131_SYNC_FRAMING_LAYER_SEQ_NUM_FIELD_LENGTH: usize = 1;
266

            
267
/// The length in bytes of the reserved field within the framing layer of an E1.31 synchronisation packet.
268
/// AS per ANSI E1.31-2018 Section 4, Table 4-2.
269
const E131_SYNC_FRAMING_LAYER_RESERVE_FIELD_LENGTH: usize = 2;
270

            
271
// The length in bytes of the reserve field in the universe discovery framing layer of an ANSI E1.31-2018 Universe Discovery Packet.
272
// Length as per ANSI E1.31-2018 Section 4, Table 4-3.
273
const E131_DISCOVERY_FRAMING_LAYER_RESERVE_FIELD_LENGTH: usize = 4;
274

            
275
/// The initial/starting sequence number used.
276
pub const STARTING_SEQUENCE_NUMBER: u8 = 0;
277

            
278
/// The vector field value used to identify the ACN packet as an ANSI E1.31 data packet.
279
/// This is used at the ACN packet layer not the E1.31 layer.
280
/// Value as defined in ANSI E1.31-2018 Appendix A: Defined Parameters (Normative).
281
pub const VECTOR_ROOT_E131_DATA: u32 = 0x0000_0004;
282

            
283
/// The vector field value used to identify the packet as an ANSI E1.31 universe discovery or synchronisation packet.
284
/// This is used at the ACN packet layer not the E1.31 layer.
285
/// Value as defined in ANSI E1.31-2018 Appendix A: Defined Parameters (Normative).
286
pub const VECTOR_ROOT_E131_EXTENDED: u32 = 0x0000_0008;
287

            
288
/// The E1.31 packet vector field value used to identify the E1.31 packet as a synchronisation packet.
289
/// This is used at the E1.31 layer and shouldn't be confused with the VECTOR values used for the ACN layer (i.e. `VECTOR_ROOT_E131_DATA` and `VECTOR_ROOT_E131_EXTENDED`).
290
/// Value as defined in ANSI E1.31-2018 Appendix A: Defined Parameters (Normative).
291
pub const VECTOR_E131_EXTENDED_SYNCHRONIZATION: u32 = 0x0000_0001;
292

            
293
/// The E1.31 packet vector field value used to identify the E1.31 packet as a universe discovery packet.
294
/// This is used at the E1.31 layer and shouldn't be confused with the VECTOR values used for the ACN layer (i.e. `VECTOR_ROOT_E131_DATA` and `VECTOR_ROOT_E131_EXTENDED`).
295
/// This VECTOR value is shared by E1.31 data packets, distinguished by the value of the ACN `ROOT_VECTOR`.
296
/// Value as defined in ANSI E1.31-2018 Appendix A: Defined Parameters (Normative).
297
pub const VECTOR_E131_EXTENDED_DISCOVERY: u32 = 0x0000_0002;
298

            
299
/// The E1.31 packet vector field value used to identify the E1.31 packet as a data packet.
300
/// This is used at the E1.31 layer and shouldn't be confused with the VECTOR values used for the ACN layer (i.e. `VECTOR_ROOT_E131_DATA` and `VECTOR_ROOT_E131_EXTENDED`).
301
/// This VECTOR value is shared by E1.31 universe discovery packets, distinguished by the value of the ACN `ROOT_VECTOR`.
302
/// Value as defined in ANSI E1.31-2018 Appendix A: Defined Parameters (Normative).
303
pub const VECTOR_E131_DATA_PACKET: u32 = 0x0000_0002;
304

            
305
/// Used at the DMP layer in E1.31 data packets to identify the packet as a set property message.
306
/// Not to be confused with the other VECTOR values used at the E1.31, ACN etc. layers.
307
/// Value as defined in ANSI E1.31-2018 Appendix A: Defined Parameters (Normative).
308
pub const VECTOR_DMP_SET_PROPERTY: u8 = 0x02;
309

            
310
/// Used at the universe discovery packet universe discovery layer to identify the packet as a universe discovery list of universes.
311
/// Not to be confused with the other VECTOR values used at the E1.31, ACN, DMP, etc. layers.
312
/// Value as defined in ANSI E1.31-2018 Appendix A: Defined Parameters (Normative).
313
pub const VECTOR_UNIVERSE_DISCOVERY_UNIVERSE_LIST: u32 = 0x0000_0001;
314

            
315
/// The port number used for the ACN family of protocols and therefore the sACN protocol.
316
/// As defined in ANSI E1.31-2018 Appendix A: Defined Parameters (Normative)
317
pub const ACN_SDT_MULTICAST_PORT: u16 = 5568;
318

            
319
/// The payload capacity for a sacn packet, for DMX data this would translate to 512 frames + a startcode byte.
320
pub const UNIVERSE_CHANNEL_CAPACITY: usize = 513;
321

            
322
/// The synchronisation universe/address of packets which do not require synchronisation as specified in section 6.2.4.1 of ANSI E1.31-2018.
323
pub const NO_SYNC_UNIVERSE: u16 = 0;
324

            
325
/// The timeout before data loss is assumed for an E131 source, as defined in Appendix A of ANSI E1.31-2018.
326
pub const E131_NETWORK_DATA_LOSS_TIMEOUT: Duration = Duration::from_millis(2500);
327

            
328
/// The timeout before a discovered source is assumed to be lost.
329
///
330
/// Sources send universe discovery packets every `E131_UNIVERSE_DISCOVERY_INTERVAL` (10 seconds, ANSI E1.31-2016 Appendix A),
331
/// so this must be longer than that interval or discovered sources expire between adverts. The standard doesn't define a
332
/// receiver timeout, so two intervals are used: a source is only treated as lost after missing a whole advert.
333
pub const UNIVERSE_DISCOVERY_SOURCE_TIMEOUT: Duration =
334
    Duration::from_secs(2 * E131_UNIVERSE_DISCOVERY_INTERVAL.as_secs());
335

            
336
/// Converts the given ANSI E1.31-2018 universe into an Ipv4 multicast address with the port set to the acn multicast port as defined
337
/// in `packet::ACN_SDT_MULTICAST_PORT`.
338
///
339
/// Conversion done as specified in section 9.3.1 of ANSI E1.31-2018
340
///
341
/// Returns the multicast address.
342
///
343
/// # Errors
344
/// `IllegalUniverse`: Returned if the given universe is outwith the allowed range of universes,
345
///     see [`is_universe_in_range`].
346
9779
pub fn universe_to_ipv4_multicast_addr(universe: u16) -> Result<SockAddr> {
347
9779
    is_universe_in_range(universe)?;
348

            
349
9777
    let high_byte: u8 = ((universe >> 8) & 0xff) as u8;
350
9777
    let low_byte: u8 = (universe & 0xff) as u8;
351

            
352
    // As per ANSI E1.31-2018 Section 9.3.1 Table 9-10.
353
9777
    Ok(SocketAddr::new(
354
9777
        IpAddr::V4(Ipv4Addr::new(239, 255, high_byte, low_byte)),
355
9777
        ACN_SDT_MULTICAST_PORT,
356
9777
    )
357
9777
    .into())
358
9779
}
359

            
360
/// Converts the given ANSI E1.31-2018 universe into an Ipv6 multicast address with the port set to the acn multicast port as defined
361
/// in `packet::ACN_SDT_MULTICAST_PORT`.
362
///
363
/// Conversion done as specified in section 9.3.2 of ANSI E1.31-2018
364
///
365
/// Returns the multicast address.
366
///
367
/// # Errors
368
/// `IllegalUniverse`: Returned if the given universe is outwith the allowed range of universes,
369
///     see [`is_universe_in_range`].
370
3154
pub fn universe_to_ipv6_multicast_addr(universe: u16) -> Result<SockAddr> {
371
3154
    is_universe_in_range(universe)?;
372

            
373
    // As per ANSI E1.31-2018 Section 9.3.2 Table 9-12.
374
3152
    Ok(SocketAddr::new(
375
3152
        IpAddr::V6(Ipv6Addr::new(0xFF18, 0, 0, 0, 0, 0, 0x8300, universe)),
376
3152
        ACN_SDT_MULTICAST_PORT,
377
3152
    )
378
3152
    .into())
379
3154
}
380

            
381
/// Checks if the given universe is a valid universe to send on or listen to (within allowed range).
382
///
383
/// This includes `E131_DISCOVERY_UNIVERSE`, which carries universe discovery packets. Use
384
/// [`is_data_universe_in_range`] for universes that carry DMX data or synchronisation packets.
385
///
386
/// # Errors
387
/// `IllegalUniverse`: Returned if the universe is outwith the allowed range of universes
388
///     [`E131_MIN_MULTICAST_UNIVERSE`, `E131_MAX_MULTICAST_UNIVERSE`] + `E131_DISCOVERY_UNIVERSE`.
389
16812
pub fn is_universe_in_range(universe: u16) -> Result<()> {
390
16812
    if (universe != E131_DISCOVERY_UNIVERSE)
391
14311
        && !(E131_MIN_MULTICAST_UNIVERSE..=E131_MAX_MULTICAST_UNIVERSE).contains(&universe)
392
    {
393
4
        return Err(SacnError::IllegalUniverse(universe));
394
16808
    }
395
16808
    Ok(())
396
16812
}
397

            
398
/// Checks if the given universe can carry DMX data or synchronisation packets.
399
///
400
/// As per ANSI E1.31-2016 Section 6.2.7 data universes are limited to the range 1 to 63999, so unlike
401
/// [`is_universe_in_range`] this excludes `E131_DISCOVERY_UNIVERSE` (64214), which is reserved for universe discovery.
402
///
403
/// # Errors
404
/// `IllegalUniverse`: Returned if the universe is outwith [`E131_MIN_MULTICAST_UNIVERSE`, `E131_MAX_MULTICAST_UNIVERSE`].
405
13203
pub fn is_data_universe_in_range(universe: u16) -> Result<()> {
406
13203
    if !(E131_MIN_MULTICAST_UNIVERSE..=E131_MAX_MULTICAST_UNIVERSE).contains(&universe) {
407
11
        return Err(SacnError::IllegalUniverse(universe));
408
13192
    }
409
13192
    Ok(())
410
13203
}
411

            
412
/// Fills the given array of bytes with the given length n with bytes of value 0.
413
#[inline]
414
28193
fn zeros(buf: &mut [u8], n: usize) {
415
28193
    for b in buf.iter_mut().take(n) {
416
514176
        *b = 0;
417
    }
418
28193
}
419

            
420
/// Takes the given byte buffer (e.g. a c char array) and parses it into a rust &str.
421
///
422
/// # Arguments
423
/// buf: The byte buffer to parse into a str.
424
///
425
/// # Errors
426
/// `SourceNameNotNullTerminated`: Returned if the source name is not null terminated as required by ANSI E1.31-2018 Section 6.2.2
427
#[inline]
428
6164
fn parse_source_name_str(buf: &[u8]) -> Result<&str> {
429
6164
    let mut source_name_length = buf.len();
430
6164
    for (i, b) in buf.iter().enumerate() {
431
21125
        if *b == 0 {
432
6163
            source_name_length = i;
433
6163
            break;
434
14962
        }
435
    }
436

            
437
6164
    if source_name_length == buf.len() && buf[buf.len() - 1] != 0 {
438
1
        return Err(SacnError::SacnParsePackError(
439
1
            ParsePacketError::SourceNameNotNullTerminated(),
440
1
        ));
441
6163
    }
442

            
443
6163
    Ok(str::from_utf8(&buf[..source_name_length])?)
444
6164
}
445

            
446
/// Root layer protocol of the Architecture for Control Networks (ACN) protocol.
447
#[derive(Clone, Eq, PartialEq, Hash, Debug)]
448
pub struct AcnRootLayerProtocol<'a> {
449
    /// The PDU this packet carries.
450
    pub pdu: E131RootLayer<'a>,
451
}
452

            
453
impl<'a> AcnRootLayerProtocol<'a> {
454
    /// Parse the packet from the given buffer.
455
14435
    pub fn parse(buf: &[u8]) -> Result<AcnRootLayerProtocol<'_>> {
456
14435
        if buf.len() < (E131_PREAMBLE_SIZE as usize) {
457
            return Err(SacnError::SacnParsePackError(
458
                ParsePacketError::ParseInsufficientData(
459
                    "Insufficient data for ACN root layer preamble".to_string(),
460
                ),
461
            ));
462
14435
        }
463

            
464
        // Preamble Size
465
14435
        if NetworkEndian::read_u16(&buf[0..2]) != E131_PREAMBLE_SIZE {
466
2
            return Err(SacnError::SacnParsePackError(
467
2
                ParsePacketError::ParseInvalidData("invalid Preamble Size".to_string()),
468
2
            ));
469
14433
        }
470

            
471
        // Post-amble Size
472
14433
        if NetworkEndian::read_u16(&buf[2..4]) != E131_POSTAMBLE_SIZE {
473
2
            return Err(SacnError::SacnParsePackError(
474
2
                ParsePacketError::ParseInvalidData("invalid Post-amble Size".to_string()),
475
2
            ));
476
14431
        }
477

            
478
        // ACN Packet Identifier
479
14431
        if buf[4..(E131_PREAMBLE_SIZE as usize)] != E131_ACN_PACKET_IDENTIFIER {
480
1
            return Err(SacnError::SacnParsePackError(
481
1
                ParsePacketError::ParseInvalidData("invalid ACN packet identifier".to_string()),
482
1
            ));
483
14430
        }
484

            
485
        // PDU block
486
        Ok(AcnRootLayerProtocol {
487
14430
            pdu: E131RootLayer::parse(&buf[(E131_PREAMBLE_SIZE as usize)..])?,
488
        })
489
14435
    }
490

            
491
    /// Packs the packet into heap allocated memory.
492
10401
    pub fn pack_alloc(&self) -> Result<Vec<u8>> {
493
10401
        let mut buf = Vec::with_capacity(self.len());
494
10401
        self.pack_vec(&mut buf)?;
495
10397
        Ok(buf)
496
10401
    }
497

            
498
    /// Packs the packet into the given vector.
499
    ///
500
    /// Grows the vector `buf` if necessary.
501
10401
    pub fn pack_vec(&self, buf: &mut Vec<u8>) -> Result<()> {
502
10401
        buf.clear();
503
10401
        buf.resize(self.len(), 0);
504
10401
        self.pack(buf)
505
10401
    }
506

            
507
    /// Packs the packet into the given buffer.
508
10407
    pub fn pack(&self, buf: &mut [u8]) -> Result<()> {
509
10407
        if buf.len() < self.len() {
510
            return Err(SacnError::SacnParsePackError(
511
                ParsePacketError::ParseInvalidData("Invalid ACN packet identifier".to_string()),
512
            ));
513
10407
        }
514

            
515
        // Preamble Size
516
10407
        NetworkEndian::write_u16(&mut buf[0..2], 0x0010);
517

            
518
        // Post-amble Size
519
10407
        zeros(&mut buf[2..4], 2);
520

            
521
        // ACN Packet Identifier
522
10407
        buf[4..16].copy_from_slice(b"ASC-E1.17\x00\x00\x00");
523

            
524
        // PDU block
525
10407
        self.pdu.pack(&mut buf[16..])
526
10407
    }
527

            
528
    #[allow(clippy::len_without_is_empty)]
529
    /// The length of the packet when packed.
530
31215
    pub fn len(&self) -> usize {
531
        // Preamble Field Size (Bytes)
532
31215
        2 +
533
31215
        // Post-amble Field Size (Bytes)
534
31215
        2 +
535
31215
        // ACN Packet Identifier Field Size (Bytes)
536
31215
        E131_ACN_PACKET_IDENTIFIER.len() +
537
31215
        // PDU block
538
31215
        self.pdu.len()
539
31215
    }
540
}
541

            
542
/// Represents the data contained with the `PduInfo` section that appears at the start of a layer in an sACN packet.
543
struct PduInfo {
544
    /// The length in bytes of this layer inclusive of the `PduInfo`.
545
    length: usize,
546
    /// The vector which indicates what the layer is, context dependent.
547
    vector: u32,
548
}
549

            
550
/// Takes the given byte buffer and parses the flags, length and vector fields into a `PduInfo` struct.
551
///
552
/// # Arguments
553
/// buf: The raw byte buffer.
554
///
555
/// `vector_length`: The length of the vectorfield in bytes.
556
///
557
/// # Errors
558
/// `ParseInsufficientData`: If the length of the buffer is less than the flag, length and vector fields (`E131_PDU_LENGTH_FLAGS_LENGTH` + `vector_length`).
559
///
560
/// `ParsePduInvalidFlags`: If the flags parsed don't match the flags expected for an ANSI E1.31-2018 packet as per ANSI E1.31-2018 Section 4 Table 4-1, 4-2, 4-3.
561
32121
fn pdu_info(buf: &[u8], vector_length: usize) -> Result<PduInfo> {
562
32121
    if buf.len() < E131_PDU_LENGTH_FLAGS_LENGTH + vector_length {
563
9
        return Err(SacnError::SacnParsePackError(
564
9
            ParsePacketError::ParseInsufficientData(
565
9
                "Insufficient data when parsing pdu_info, no flags or length field".to_string(),
566
9
            ),
567
9
        ));
568
32112
    }
569

            
570
    // Flags
571
32112
    let flags = buf[0] & 0xf0; // Flags are stored in the top 4 bits.
572
32112
    if flags != E131_PDU_FLAGS {
573
12
        return Err(SacnError::SacnParsePackError(
574
12
            ParsePacketError::ParsePduInvalidFlags(flags),
575
12
        ));
576
32100
    }
577
    // Length
578
32100
    let length = (NetworkEndian::read_u16(&buf[0..E131_PDU_LENGTH_FLAGS_LENGTH]) & 0x0fff) as usize;
579

            
580
    // Vector
581
    let vector =
582
32100
        NetworkEndian::read_uint(&buf[E131_PDU_LENGTH_FLAGS_LENGTH..], vector_length) as u32;
583

            
584
32100
    Ok(PduInfo { length, vector })
585
32121
}
586

            
587
trait Pdu: Sized {
588
    fn parse(buf: &[u8]) -> Result<Self>;
589

            
590
    fn pack(&self, buf: &mut [u8]) -> Result<()>;
591

            
592
    fn len(&self) -> usize;
593
}
594

            
595
/// Payload of the Root Layer PDU.
596
#[derive(Clone, Eq, PartialEq, Hash, Debug)]
597
pub enum E131RootLayerData<'a> {
598
    /// DMX data packet.
599
    DataPacket(DataPacketFramingLayer<'a>),
600

            
601
    /// Synchronization packet.
602
    SynchronizationPacket(SynchronizationPacketFramingLayer),
603

            
604
    /// Universe discovery packet.
605
    UniverseDiscoveryPacket(UniverseDiscoveryPacketFramingLayer<'a>),
606
}
607

            
608
/// Root layer protocol data unit (PDU).
609
#[derive(Clone, Eq, PartialEq, Hash, Debug)]
610
pub struct E131RootLayer<'a> {
611
    /// Sender UUID.
612
    pub cid: Uuid,
613
    /// Data carried by the Root Layer PDU.
614
    pub data: E131RootLayerData<'a>,
615
}
616

            
617
impl<'a> Pdu for E131RootLayer<'a> {
618
14430
    fn parse(buf: &[u8]) -> Result<E131RootLayer<'a>> {
619
        // Length and Vector
620
14430
        let PduInfo { length, vector } = pdu_info(buf, E131_ROOT_LAYER_VECTOR_LENGTH)?;
621
14428
        if buf.len() < length {
622
3477
            return Err(SacnError::SacnParsePackError(
623
3477
                ParsePacketError::ParseInsufficientData(
624
3477
                    "Buffer contains insufficient data based on ACN root layer pdu length field"
625
3477
                        .to_string(),
626
3477
                ),
627
3477
            ));
628
10951
        }
629

            
630
        // The PDU must at least hold the flags/length, vector and CID fields.
631
10951
        if length < E131_CID_END_INDEX {
632
23
            return Err(SacnError::SacnParsePackError(
633
23
                ParsePacketError::PduInvalidLength(length),
634
23
            ));
635
10928
        }
636

            
637
10928
        if vector != VECTOR_ROOT_E131_DATA && vector != VECTOR_ROOT_E131_EXTENDED {
638
3
            return Err(SacnError::SacnParsePackError(
639
3
                ParsePacketError::PduInvalidVector(vector),
640
3
            ));
641
10925
        }
642

            
643
        // CID
644
10925
        let cid = Uuid::from_slice(
645
10925
            &buf[E131_PDU_LENGTH_FLAGS_LENGTH + E131_ROOT_LAYER_VECTOR_LENGTH..E131_CID_END_INDEX],
646
10925
        )?;
647

            
648
        // Data
649
10925
        let data = match vector {
650
10310
            VECTOR_ROOT_E131_DATA => E131RootLayerData::DataPacket(DataPacketFramingLayer::parse(
651
10310
                &buf[E131_CID_END_INDEX..length],
652
10310
            )?),
653
            VECTOR_ROOT_E131_EXTENDED => {
654
615
                let data_buf = &buf[E131_CID_END_INDEX..length];
655
                let PduInfo { length, vector } =
656
615
                    pdu_info(data_buf, E131_FRAMING_LAYER_VECTOR_LENGTH)?;
657
611
                if data_buf.len() < length {
658
2
                    return Err(SacnError::SacnParsePackError(
659
2
                        ParsePacketError::ParseInsufficientData(
660
2
                            "Buffer contains insufficient data based on E131 framing layer pdu length field".to_string(),
661
2
                        ),
662
2
                    ));
663
609
                }
664

            
665
609
                match vector {
666
                    VECTOR_E131_EXTENDED_SYNCHRONIZATION => {
667
                        E131RootLayerData::SynchronizationPacket(
668
574
                            SynchronizationPacketFramingLayer::parse(data_buf)?,
669
                        )
670
                    }
671
                    VECTOR_E131_EXTENDED_DISCOVERY => E131RootLayerData::UniverseDiscoveryPacket(
672
33
                        UniverseDiscoveryPacketFramingLayer::parse(data_buf)?,
673
                    ),
674
                    vector => {
675
2
                        return Err(SacnError::SacnParsePackError(
676
2
                            ParsePacketError::PduInvalidVector(vector),
677
2
                        ));
678
                    }
679
                }
680
            }
681
            vector => {
682
                return Err(SacnError::SacnParsePackError(
683
                    ParsePacketError::PduInvalidVector(vector),
684
                ));
685
            }
686
        };
687

            
688
2090
        Ok(E131RootLayer { cid, data })
689
14430
    }
690

            
691
10407
    fn pack(&self, buf: &mut [u8]) -> Result<()> {
692
10407
        if buf.len() < self.len() {
693
            return Err(SacnError::SacnParsePackError(
694
                ParsePacketError::PackBufferInsufficient("".to_string()),
695
            ));
696
10407
        }
697

            
698
        // Flags and Length, flags are stored in the top 4 bits.
699
        let flags_and_length =
700
10407
            NetworkEndian::read_u16(&[E131_PDU_FLAGS, 0x0]) | (self.len() as u16) & 0x0fff;
701
10407
        NetworkEndian::write_u16(&mut buf[0..E131_PDU_LENGTH_FLAGS_LENGTH], flags_and_length);
702

            
703
        // Vector
704
10407
        match self.data {
705
7363
            E131RootLayerData::DataPacket(_) => NetworkEndian::write_u32(
706
7363
                &mut buf[E131_PDU_LENGTH_FLAGS_LENGTH
707
7363
                    ..E131_PDU_LENGTH_FLAGS_LENGTH + E131_ROOT_LAYER_VECTOR_LENGTH],
708
7363
                VECTOR_ROOT_E131_DATA,
709
7363
            ),
710
            E131RootLayerData::SynchronizationPacket(_)
711
3044
            | E131RootLayerData::UniverseDiscoveryPacket(_) => NetworkEndian::write_u32(
712
3044
                &mut buf[E131_PDU_LENGTH_FLAGS_LENGTH
713
3044
                    ..E131_PDU_LENGTH_FLAGS_LENGTH + E131_ROOT_LAYER_VECTOR_LENGTH],
714
3044
                VECTOR_ROOT_E131_EXTENDED,
715
3044
            ),
716
        }
717

            
718
        // CID
719
10407
        buf[E131_PDU_LENGTH_FLAGS_LENGTH + E131_ROOT_LAYER_VECTOR_LENGTH..E131_CID_END_INDEX]
720
10407
            .copy_from_slice(self.cid.as_bytes());
721

            
722
        // Data
723
10407
        match self.data {
724
            E131RootLayerData::DataPacket(ref data) => {
725
7363
                Ok(data.pack(&mut buf[E131_CID_END_INDEX..])?)
726
            }
727
            E131RootLayerData::SynchronizationPacket(ref data) => {
728
3020
                Ok(data.pack(&mut buf[E131_CID_END_INDEX..])?)
729
            }
730
            E131RootLayerData::UniverseDiscoveryPacket(ref data) => {
731
24
                Ok(data.pack(&mut buf[E131_CID_END_INDEX..])?)
732
            }
733
        }
734
10407
    }
735

            
736
52029
    fn len(&self) -> usize {
737
        // Length and Flags
738
52029
        E131_PDU_LENGTH_FLAGS_LENGTH +
739
52029
        // Vector
740
52029
        E131_ROOT_LAYER_VECTOR_LENGTH +
741
52029
        // CID
742
52029
        E131_CID_FIELD_LENGTH +
743
        // Data
744
52029
        match self.data {
745
36811
            E131RootLayerData::DataPacket(ref data) => data.len(),
746
15099
            E131RootLayerData::SynchronizationPacket(ref data) => data.len(),
747
119
            E131RootLayerData::UniverseDiscoveryPacket(ref data) => data.len(),
748
        }
749
52029
    }
750
}
751

            
752
/// Framing layer PDU for sACN data packets.
753
#[derive(Eq, PartialEq, Debug)]
754
pub struct DataPacketFramingLayer<'a> {
755
    /// The name of the source.
756
    pub source_name: Cow<'a, str>,
757

            
758
    /// Priority of this data packet.
759
    pub priority: u8,
760

            
761
    /// Synchronization address.
762
    pub synchronization_address: u16,
763

            
764
    /// The sequence number of this packet.
765
    pub sequence_number: u8,
766

            
767
    /// If this packets data is preview data.
768
    pub preview_data: bool,
769

            
770
    /// If transmission on this universe is terminated.
771
    pub stream_terminated: bool,
772

            
773
    /// Force synchronization if no synchronization packets are received.
774
    pub force_synchronization: bool,
775

            
776
    /// The universe DMX data is transmitted for.
777
    pub universe: u16,
778

            
779
    /// DMP layer containing the DMX data.
780
    pub data: DataPacketDmpLayer<'a>,
781
}
782

            
783
// Calculate the indexes of the fields within the buffer based on the size of the fields previous.
784
// Constants are replaced inline so this increases readability by removing magic numbers without affecting runtime performance.
785
// Theses indexes are only valid within the scope of this part of the protocol (DataPacketFramingLayer).
786
const SOURCE_NAME_INDEX: usize = E131_PDU_LENGTH_FLAGS_LENGTH + E131_FRAMING_LAYER_VECTOR_LENGTH;
787
const PRIORITY_INDEX: usize = SOURCE_NAME_INDEX + E131_SOURCE_NAME_FIELD_LENGTH;
788
const SYNC_ADDR_INDEX: usize = PRIORITY_INDEX + E131_PRIORITY_FIELD_LENGTH;
789
const SEQ_NUM_INDEX: usize = SYNC_ADDR_INDEX + E131_SYNC_ADDR_FIELD_LENGTH;
790
const OPTIONS_FIELD_INDEX: usize = SEQ_NUM_INDEX + E131_SEQ_NUM_FIELD_LENGTH;
791
const UNIVERSE_INDEX: usize = OPTIONS_FIELD_INDEX + E131_OPTIONS_FIELD_LENGTH;
792
const DATA_INDEX: usize = UNIVERSE_INDEX + E131_UNIVERSE_FIELD_LENGTH;
793

            
794
impl<'a> Pdu for DataPacketFramingLayer<'a> {
795
10310
    fn parse(buf: &[u8]) -> Result<DataPacketFramingLayer<'a>> {
796
        // Length and Vector
797
10310
        let PduInfo { length, vector } = pdu_info(buf, E131_FRAMING_LAYER_VECTOR_LENGTH)?;
798
10302
        if buf.len() < length {
799
4090
            return Err(SacnError::SacnParsePackError(ParsePacketError::ParseInsufficientData("Buffer contains insufficient data based on data packet framing layer pdu length field".to_string())));
800
6212
        }
801

            
802
6212
        if vector != VECTOR_E131_DATA_PACKET {
803
2
            return Err(SacnError::SacnParsePackError(
804
2
                ParsePacketError::PduInvalidVector(vector),
805
2
            ));
806
6210
        }
807

            
808
        // The PDU must at least hold every fixed framing layer field before the DMP layer.
809
6210
        if length < DATA_INDEX {
810
78
            return Err(SacnError::SacnParsePackError(
811
78
                ParsePacketError::PduInvalidLength(length),
812
78
            ));
813
6132
        }
814

            
815
        // Source Name
816
6132
        let source_name = String::from(parse_source_name_str(
817
6132
            &buf[SOURCE_NAME_INDEX..PRIORITY_INDEX],
818
6132
        )?);
819

            
820
        // Priority
821
6131
        let priority = buf[PRIORITY_INDEX];
822
6131
        if priority > E131_MAX_PRIORITY {
823
1
            return Err(SacnError::SacnParsePackError(
824
1
                ParsePacketError::ParseInvalidPriority(priority),
825
1
            ));
826
6130
        }
827

            
828
        // Synchronization Address
829
6130
        let synchronization_address = NetworkEndian::read_u16(&buf[SYNC_ADDR_INDEX..SEQ_NUM_INDEX]);
830
6130
        if synchronization_address > E131_MAX_MULTICAST_UNIVERSE {
831
1
            return Err(SacnError::SacnParsePackError(
832
1
                ParsePacketError::ParseInvalidSyncAddr(synchronization_address),
833
1
            ));
834
6129
        }
835

            
836
        // Sequence Number
837
6129
        let sequence_number = buf[SEQ_NUM_INDEX];
838

            
839
        // Options, Stored as bit flag.
840
6129
        let preview_data = buf[OPTIONS_FIELD_INDEX] & E131_PREVIEW_DATA_OPTION_BIT_MASK != 0;
841
        let stream_terminated =
842
6129
            buf[OPTIONS_FIELD_INDEX] & E131_STREAM_TERMINATION_OPTION_BIT_MASK != 0;
843
        let force_synchronization =
844
6129
            buf[OPTIONS_FIELD_INDEX] & E131_FORCE_SYNCHRONISATION_OPTION_BIT_MASK != 0;
845

            
846
        // Universe
847
6129
        let universe = NetworkEndian::read_u16(&buf[UNIVERSE_INDEX..DATA_INDEX]);
848

            
849
6129
        if !(E131_MIN_MULTICAST_UNIVERSE..=E131_MAX_MULTICAST_UNIVERSE).contains(&universe) {
850
2
            return Err(SacnError::SacnParsePackError(
851
2
                ParsePacketError::ParseInvalidUniverse(universe),
852
2
            ));
853
6127
        }
854

            
855
        // Data layer.
856
6127
        let data = DataPacketDmpLayer::parse(&buf[DATA_INDEX..length])?;
857

            
858
1498
        Ok(DataPacketFramingLayer {
859
1498
            source_name: source_name.into(),
860
1498
            priority,
861
1498
            synchronization_address,
862
1498
            sequence_number,
863
1498
            preview_data,
864
1498
            stream_terminated,
865
1498
            force_synchronization,
866
1498
            universe,
867
1498
            data,
868
1498
        })
869
10310
    }
870

            
871
7363
    fn pack(&self, buf: &mut [u8]) -> Result<()> {
872
7363
        if buf.len() < self.len() {
873
            return Err(SacnError::SacnParsePackError(
874
                ParsePacketError::PackBufferInsufficient("".to_string()),
875
            ));
876
7363
        }
877

            
878
        // Flags and Length
879
        let flags_and_length =
880
7363
            NetworkEndian::read_u16(&[E131_PDU_FLAGS, 0x0]) | (self.len() as u16) & 0x0fff;
881
7363
        NetworkEndian::write_u16(&mut buf[0..E131_PDU_LENGTH_FLAGS_LENGTH], flags_and_length);
882

            
883
        // Vector
884
7363
        NetworkEndian::write_u32(
885
7363
            &mut buf[E131_PDU_LENGTH_FLAGS_LENGTH..SOURCE_NAME_INDEX],
886
7363
            VECTOR_E131_DATA_PACKET,
887
7363
        );
888

            
889
        // Source Name, padded with 0's up to the required 64 byte length, always leaving room for the null terminator.
890
7363
        if self.source_name.len() > E131_SOURCE_NAME_MAX_LENGTH {
891
2
            return Err(SacnError::SacnParsePackError(
892
2
                ParsePacketError::PackInvalidData(format!(
893
2
                    "Source name must be at most {} bytes",
894
2
                    E131_SOURCE_NAME_MAX_LENGTH
895
2
                )),
896
2
            ));
897
7361
        }
898
7361
        zeros(
899
7361
            &mut buf[SOURCE_NAME_INDEX..PRIORITY_INDEX],
900
7361
            E131_SOURCE_NAME_FIELD_LENGTH,
901
7361
        );
902
7361
        buf[SOURCE_NAME_INDEX..SOURCE_NAME_INDEX + self.source_name.len()]
903
7361
            .copy_from_slice(self.source_name.as_bytes());
904

            
905
        // Priority
906
7361
        buf[PRIORITY_INDEX] = self.priority;
907

            
908
        // Synchronization Address
909
7361
        NetworkEndian::write_u16(
910
7361
            &mut buf[SYNC_ADDR_INDEX..SEQ_NUM_INDEX],
911
7361
            self.synchronization_address,
912
7361
        );
913

            
914
        // Sequence Number
915
7361
        buf[SEQ_NUM_INDEX] = self.sequence_number;
916

            
917
        // Options, zero out all the bits to start including bits 0-4 as per ANSI E1.31-2018 Section 6.2.6.
918
7361
        buf[OPTIONS_FIELD_INDEX] = 0;
919

            
920
        // Preview Data
921
7361
        if self.preview_data {
922
4
            buf[OPTIONS_FIELD_INDEX] = E131_PREVIEW_DATA_OPTION_BIT_MASK;
923
7357
        }
924

            
925
        // Stream Terminated
926
7361
        if self.stream_terminated {
927
4020
            buf[OPTIONS_FIELD_INDEX] |= E131_STREAM_TERMINATION_OPTION_BIT_MASK;
928
3341
        }
929

            
930
        // Force Synchronization
931
7361
        if self.force_synchronization {
932
            buf[OPTIONS_FIELD_INDEX] |= E131_FORCE_SYNCHRONISATION_OPTION_BIT_MASK;
933
7361
        }
934

            
935
        // Universe
936
7361
        NetworkEndian::write_u16(&mut buf[UNIVERSE_INDEX..DATA_INDEX], self.universe);
937

            
938
        // Data
939
7361
        self.data.pack(&mut buf[DATA_INDEX..])
940
7363
    }
941

            
942
51537
    fn len(&self) -> usize {
943
        // Length and Flags
944
51537
        E131_PDU_LENGTH_FLAGS_LENGTH +
945
51537
        // Vector
946
51537
        E131_FRAMING_LAYER_VECTOR_LENGTH +
947
51537
        // Source Name
948
51537
        E131_SOURCE_NAME_FIELD_LENGTH +
949
51537
        // Priority
950
51537
        E131_PRIORITY_FIELD_LENGTH +
951
51537
        // Synchronization Address
952
51537
        E131_SYNC_ADDR_FIELD_LENGTH +
953
51537
        // Sequence Number
954
51537
        E131_SEQ_NUM_FIELD_LENGTH +
955
51537
        // Options
956
51537
        E131_OPTIONS_FIELD_LENGTH +
957
51537
        // Universe
958
51537
        E131_UNIVERSE_FIELD_LENGTH +
959
51537
        // Data
960
51537
        self.data.len()
961
51537
    }
962
}
963

            
964
impl<'a> Clone for DataPacketFramingLayer<'a> {
965
    fn clone(&self) -> Self {
966
        DataPacketFramingLayer {
967
            source_name: self.source_name.clone(),
968
            priority: self.priority,
969
            synchronization_address: self.synchronization_address,
970
            sequence_number: self.sequence_number,
971
            preview_data: self.preview_data,
972
            stream_terminated: self.stream_terminated,
973
            force_synchronization: self.force_synchronization,
974
            universe: self.universe,
975
            data: self.data.clone(),
976
        }
977
    }
978
}
979

            
980
impl<'a> Hash for DataPacketFramingLayer<'a> {
981
    #[inline]
982
    fn hash<H: hash::Hasher>(&self, state: &mut H) {
983
        (*self.source_name).hash(state);
984
        self.priority.hash(state);
985
        self.synchronization_address.hash(state);
986
        self.sequence_number.hash(state);
987
        self.preview_data.hash(state);
988
        self.stream_terminated.hash(state);
989
        self.force_synchronization.hash(state);
990
        self.universe.hash(state);
991
        self.data.hash(state);
992
    }
993
}
994

            
995
/// Device Management Protocol PDU with SET PROPERTY vector.
996
///
997
/// Used for sACN data packets.
998
#[derive(Eq, PartialEq, Debug)]
999
pub struct DataPacketDmpLayer<'a> {
    /// DMX data property values (DMX start coder + 512 slots).
    pub property_values: Cow<'a, [u8]>,
}
// Calculate the indexes of the fields within the buffer based on the size of the fields previous.
// Constants are replaced inline so this increases readability by removing magic numbers without affecting runtime performance.
// Theses indexes are only valid within the scope of this part of the protocol (DataPacketDmpLayer).
const VECTOR_FIELD_INDEX: usize = E131_PDU_LENGTH_FLAGS_LENGTH;
const ADDRESS_DATA_FIELD_INDEX: usize =
    VECTOR_FIELD_INDEX + E131_DATA_PACKET_DMP_LAYER_VECTOR_FIELD_LENGTH;
const FIRST_PRIORITY_FIELD_INDEX: usize =
    ADDRESS_DATA_FIELD_INDEX + E131_DATA_PACKET_DMP_LAYER_ADDRESS_DATA_FIELD_LENGTH;
const ADDRESS_INCREMENT_FIELD_INDEX: usize =
    FIRST_PRIORITY_FIELD_INDEX + E131_DATA_PACKET_DMP_LAYER_FIRST_PROPERTY_ADDRESS_FIELD_LENGTH;
const PROPERTY_VALUE_COUNT_FIELD_INDEX: usize =
    ADDRESS_INCREMENT_FIELD_INDEX + E131_DATA_PACKET_DMP_LAYER_ADDRESS_INCREMENT_FIELD_LENGTH;
const PROPERTY_VALUES_FIELD_INDEX: usize =
    PROPERTY_VALUE_COUNT_FIELD_INDEX + E131_DATA_PACKET_DMP_LAYER_PROPERTY_VALUE_COUNT_FIELD_LENGTH;
impl<'a> Pdu for DataPacketDmpLayer<'a> {
6127
    fn parse(buf: &[u8]) -> Result<DataPacketDmpLayer<'a>> {
        // Length and Vector
        let PduInfo { length, vector } =
6127
            pdu_info(buf, E131_DATA_PACKET_DMP_LAYER_VECTOR_FIELD_LENGTH)?;
6122
        if buf.len() < length {
4093
            return Err(SacnError::SacnParsePackError(ParsePacketError::ParseInsufficientData("Buffer contains insufficient data based on data packet dmp layer pdu length field".to_string())));
2029
        }
2029
        if vector != u32::from(VECTOR_DMP_SET_PROPERTY) {
1
            return Err(SacnError::SacnParsePackError(
1
                ParsePacketError::PduInvalidVector(vector),
1
            ));
2028
        }
        // The PDU must at least hold every fixed DMP layer field before the property values.
2028
        if length < PROPERTY_VALUES_FIELD_INDEX {
12
            return Err(SacnError::SacnParsePackError(
12
                ParsePacketError::ParseInsufficientData(format!(
12
                    "Data packet dmp layer pdu length {} is shorter than its {} byte header",
12
                    length, PROPERTY_VALUES_FIELD_INDEX
12
                )),
12
            ));
2016
        }
        // Address and Data Type
2016
        if buf[ADDRESS_DATA_FIELD_INDEX] != E131_DMP_LAYER_ADDRESS_DATA_FIELD {
1
            return Err(SacnError::SacnParsePackError(
1
                ParsePacketError::ParseInvalidData("invalid Address and Data Type".to_string()),
1
            ));
2015
        }
        // First Property Address
2015
        if NetworkEndian::read_u16(&buf[FIRST_PRIORITY_FIELD_INDEX..ADDRESS_INCREMENT_FIELD_INDEX])
2015
            != E131_DATA_PACKET_DMP_LAYER_FIRST_PROPERTY_FIELD
        {
1
            return Err(SacnError::SacnParsePackError(
1
                ParsePacketError::ParseInvalidData("invalid First Property Address".to_string()),
1
            ));
2014
        }
        // Address Increment
2014
        if NetworkEndian::read_u16(
2014
            &buf[ADDRESS_INCREMENT_FIELD_INDEX..PROPERTY_VALUE_COUNT_FIELD_INDEX],
2014
        ) != E131_DATA_PACKET_DMP_LAYER_ADDRESS_INCREMENT
        {
1
            return Err(SacnError::SacnParsePackError(
1
                ParsePacketError::ParseInvalidData("invalid Address Increment".to_string()),
1
            ));
2013
        }
        // Property value count
2013
        let property_value_count = NetworkEndian::read_u16(
2013
            &buf[PROPERTY_VALUE_COUNT_FIELD_INDEX..PROPERTY_VALUES_FIELD_INDEX],
2013
        );
        // Check that the property value count matches the expected count based on the pdu length given previously.
2013
        if property_value_count as usize + PROPERTY_VALUES_FIELD_INDEX != length {
515
            return Err(SacnError::SacnParsePackError(
515
                ParsePacketError::ParseInsufficientData(
515
                    format!("Invalid data packet dmp layer property value count, pdu length indicates {} property values, property value count field indicates {} property values",
515
                        length , property_value_count)
515
                    .to_string()
515
                )
515
            ));
1498
        }
        // Property values
        // The property value length is only of the property values and not the headers so start counting at the index that the property values start.
1498
        let property_values_length = length - PROPERTY_VALUES_FIELD_INDEX;
1498
        if property_values_length > UNIVERSE_CHANNEL_CAPACITY {
            return Err(SacnError::SacnParsePackError(
                ParsePacketError::ParseInvalidData("only 512 DMX slots allowed".to_string()),
            ));
1498
        }
1498
        let mut property_values = Vec::with_capacity(property_values_length);
1498
        property_values.extend_from_slice(&buf[PROPERTY_VALUES_FIELD_INDEX..length]);
1498
        Ok(DataPacketDmpLayer {
1498
            property_values: property_values.into(),
1498
        })
6127
    }
7361
    fn pack(&self, buf: &mut [u8]) -> Result<()> {
7361
        if self.property_values.len() > UNIVERSE_CHANNEL_CAPACITY {
            return Err(SacnError::SacnParsePackError(
                ParsePacketError::PackInvalidData("only 512 DMX values allowed".to_string()),
            ));
7361
        }
7361
        if buf.len() < self.len() {
            return Err(SacnError::SacnParsePackError(
                ParsePacketError::PackBufferInsufficient(
                    "DataPacketDmpLayer pack buffer length insufficient".to_string(),
                ),
            ));
7361
        }
        // Flags and Length
        let flags_and_length =
7361
            NetworkEndian::read_u16(&[E131_PDU_FLAGS, 0x0]) | (self.len() as u16) & 0x0fff;
7361
        NetworkEndian::write_u16(&mut buf[0..E131_PDU_LENGTH_FLAGS_LENGTH], flags_and_length);
        // Vector
7361
        buf[VECTOR_FIELD_INDEX] = VECTOR_DMP_SET_PROPERTY;
        // Address and Data Type
7361
        buf[ADDRESS_DATA_FIELD_INDEX] = E131_DMP_LAYER_ADDRESS_DATA_FIELD;
        // First Property Address
7361
        zeros(
7361
            &mut buf[FIRST_PRIORITY_FIELD_INDEX..ADDRESS_INCREMENT_FIELD_INDEX],
7361
            E131_DATA_PACKET_DMP_LAYER_FIRST_PROPERTY_ADDRESS_FIELD_LENGTH,
7361
        );
        // Address Increment
7361
        NetworkEndian::write_u16(
7361
            &mut buf[ADDRESS_INCREMENT_FIELD_INDEX..PROPERTY_VALUE_COUNT_FIELD_INDEX],
7361
            E131_DATA_PACKET_DMP_LAYER_ADDRESS_INCREMENT,
7361
        );
        // Property value count
7361
        NetworkEndian::write_u16(
7361
            &mut buf[PROPERTY_VALUE_COUNT_FIELD_INDEX..PROPERTY_VALUES_FIELD_INDEX],
7361
            self.property_values.len() as u16,
7361
        );
        // Property values
7361
        buf[PROPERTY_VALUES_FIELD_INDEX..PROPERTY_VALUES_FIELD_INDEX + self.property_values.len()]
7361
            .copy_from_slice(&self.property_values);
7361
        Ok(())
7361
    }
66259
    fn len(&self) -> usize {
        // Length and Flags
66259
        E131_PDU_LENGTH_FLAGS_LENGTH +
66259
        // Vector
66259
        E131_DATA_PACKET_DMP_LAYER_VECTOR_FIELD_LENGTH +
66259
        // Address and Data Type
66259
        E131_DATA_PACKET_DMP_LAYER_ADDRESS_DATA_FIELD_LENGTH +
66259
        // First Property Address
66259
        E131_DATA_PACKET_DMP_LAYER_FIRST_PROPERTY_ADDRESS_FIELD_LENGTH +
66259
        // Address Increment
66259
        E131_DATA_PACKET_DMP_LAYER_ADDRESS_INCREMENT_FIELD_LENGTH +
66259
        // Property value count
66259
        E131_DATA_PACKET_DMP_LAYER_PROPERTY_VALUE_COUNT_FIELD_LENGTH +
66259
        // Property values
66259
        self.property_values.len()
66259
    }
}
impl<'a> Clone for DataPacketDmpLayer<'a> {
    fn clone(&self) -> Self {
        DataPacketDmpLayer {
            property_values: self.property_values.clone(),
        }
    }
}
impl<'a> Hash for DataPacketDmpLayer<'a> {
    #[inline]
    fn hash<H: hash::Hasher>(&self, state: &mut H) {
        (*self.property_values).hash(state);
    }
}
/// sACN synchronization packet PDU.
#[derive(Clone, Eq, PartialEq, Hash, Debug, Copy)]
pub struct SynchronizationPacketFramingLayer {
    /// The sequence number of the packet.
    pub sequence_number: u8,
    /// The address to synchronize.
    pub synchronization_address: u16,
}
// Calculate the indexes of the fields within the buffer based on the size of the fields previous.
// Constants are replaced inline so this increases readability by removing magic numbers without affecting runtime performance.
// Theses indexes are only valid within the scope of this part of the protocol (SynchronisationPacketFramingLayer).
const E131_SYNC_FRAMING_LAYER_VECTOR_FIELD_INDEX: usize = E131_PDU_LENGTH_FLAGS_LENGTH;
const E131_SYNC_FRAMING_LAYER_SEQ_NUM_FIELD_INDEX: usize =
    E131_SYNC_FRAMING_LAYER_VECTOR_FIELD_INDEX + E131_FRAMING_LAYER_VECTOR_LENGTH;
const E131_SYNC_FRAMING_LAYER_SYNC_ADDRESS_FIELD_INDEX: usize =
    E131_SYNC_FRAMING_LAYER_SEQ_NUM_FIELD_INDEX + E131_SYNC_FRAMING_LAYER_SEQ_NUM_FIELD_LENGTH;
const E131_SYNC_FRAMING_LAYER_RESERVE_FIELD_INDEX: usize =
    E131_SYNC_FRAMING_LAYER_SYNC_ADDRESS_FIELD_INDEX + E131_SYNC_ADDR_FIELD_LENGTH;
const E131_SYNC_FRAMING_LAYER_END_INDEX: usize =
    E131_SYNC_FRAMING_LAYER_RESERVE_FIELD_INDEX + E131_SYNC_FRAMING_LAYER_RESERVE_FIELD_LENGTH;
impl Pdu for SynchronizationPacketFramingLayer {
574
    fn parse(buf: &[u8]) -> Result<SynchronizationPacketFramingLayer> {
        // Length and Vector
574
        let PduInfo { length, vector } = pdu_info(buf, E131_FRAMING_LAYER_VECTOR_LENGTH)?;
574
        if buf.len() < length {
            return Err(SacnError::SacnParsePackError(ParsePacketError::ParseInsufficientData("Buffer contains insufficient data based on synchronisation packet framing layer pdu length field".to_string())));
574
        }
574
        if vector != VECTOR_E131_EXTENDED_SYNCHRONIZATION {
            return Err(SacnError::SacnParsePackError(
                ParsePacketError::PduInvalidVector(vector),
            ));
574
        }
574
        if length != E131_UNIVERSE_SYNC_PACKET_FRAMING_LAYER_LENGTH {
2
            return Err(SacnError::SacnParsePackError(
2
                ParsePacketError::PduInvalidLength(length),
2
            ));
572
        }
        // Sequence Number
572
        let sequence_number = buf[E131_SYNC_FRAMING_LAYER_SEQ_NUM_FIELD_INDEX];
        // Synchronization Address
572
        let synchronization_address = NetworkEndian::read_u16(
572
            &buf[E131_SYNC_FRAMING_LAYER_SYNC_ADDRESS_FIELD_INDEX
572
                ..E131_SYNC_FRAMING_LAYER_RESERVE_FIELD_INDEX],
572
        );
572
        if !(E131_MIN_MULTICAST_UNIVERSE..=E131_MAX_MULTICAST_UNIVERSE)
572
            .contains(&synchronization_address)
        {
2
            return Err(SacnError::SacnParsePackError(
2
                ParsePacketError::ParseInvalidSyncAddr(synchronization_address),
2
            ));
570
        }
        // Reserved fields (2 bytes right immediately after the synchronisation address) should be ignored by receivers as per
        // ANSI E1.31-2018 Section 6.3.4.
570
        Ok(SynchronizationPacketFramingLayer {
570
            sequence_number,
570
            synchronization_address,
570
        })
574
    }
3020
    fn pack(&self, buf: &mut [u8]) -> Result<()> {
3020
        if buf.len() < self.len() {
            return Err(SacnError::SacnParsePackError(
                ParsePacketError::PackBufferInsufficient(
                    "SynchronizationPacketFramingLayer pack buffer length insufficient".to_string(),
                ),
            ));
3020
        }
        // Flags and Length
        let flags_and_length =
3020
            NetworkEndian::read_u16(&[E131_PDU_FLAGS, 0x0]) | (self.len() as u16) & 0x0fff;
3020
        NetworkEndian::write_u16(&mut buf[0..E131_PDU_LENGTH_FLAGS_LENGTH], flags_and_length);
        // Vector
3020
        NetworkEndian::write_u32(
3020
            &mut buf[E131_SYNC_FRAMING_LAYER_VECTOR_FIELD_INDEX
3020
                ..E131_SYNC_FRAMING_LAYER_SEQ_NUM_FIELD_INDEX],
3020
            VECTOR_E131_EXTENDED_SYNCHRONIZATION,
3020
        );
        // Sequence Number
3020
        buf[E131_SYNC_FRAMING_LAYER_SEQ_NUM_FIELD_INDEX] = self.sequence_number;
        // Synchronization Address
3020
        NetworkEndian::write_u16(
3020
            &mut buf[E131_SYNC_FRAMING_LAYER_SYNC_ADDRESS_FIELD_INDEX
3020
                ..E131_SYNC_FRAMING_LAYER_RESERVE_FIELD_INDEX],
3020
            self.synchronization_address,
3020
        );
        // Reserved, transmitted as zeros as per ANSI E1.31-2018 Section 6.3.4.
3020
        zeros(
3020
            &mut buf
3020
                [E131_SYNC_FRAMING_LAYER_RESERVE_FIELD_INDEX..E131_SYNC_FRAMING_LAYER_END_INDEX],
3020
            E131_SYNC_FRAMING_LAYER_RESERVE_FIELD_LENGTH,
3020
        );
3020
        Ok(())
3020
    }
21139
    fn len(&self) -> usize {
        // Length and Flags
21139
        E131_PDU_LENGTH_FLAGS_LENGTH +
21139
        // Vector
21139
        E131_FRAMING_LAYER_VECTOR_LENGTH +
21139
        // Sequence Number
21139
        E131_SYNC_FRAMING_LAYER_SEQ_NUM_FIELD_LENGTH +
21139
        // Synchronization Address
21139
        E131_SYNC_ADDR_FIELD_LENGTH +
21139
        // Reserved
21139
        E131_SYNC_FRAMING_LAYER_RESERVE_FIELD_LENGTH
21139
    }
}
/// Framing layer PDU for sACN universe discovery packets.
#[derive(Eq, PartialEq, Debug)]
pub struct UniverseDiscoveryPacketFramingLayer<'a> {
    /// Name of the source.
    pub source_name: Cow<'a, str>,
    /// Universe discovery layer.
    pub data: UniverseDiscoveryPacketUniverseDiscoveryLayer<'a>,
}
// Calculate the indexes of the fields within the buffer based on the size of the fields previous.
// Constants are replaced inline so this increases readability by removing magic numbers without affecting runtime performance.
// Theses indexes are only valid within the scope of this part of the protocol (UniverseDiscoveryPacketFramingLayer).
const E131_DISCOVERY_FRAMING_LAYER_VECTOR_FIELD_INDEX: usize = E131_PDU_LENGTH_FLAGS_LENGTH;
const E131_DISCOVERY_FRAMING_LAYER_SOURCE_NAME_FIELD_INDEX: usize =
    E131_DISCOVERY_FRAMING_LAYER_VECTOR_FIELD_INDEX + E131_FRAMING_LAYER_VECTOR_LENGTH;
const E131_DISCOVERY_FRAMING_LAYER_RESERVE_FIELD_INDEX: usize =
    E131_DISCOVERY_FRAMING_LAYER_SOURCE_NAME_FIELD_INDEX + E131_SOURCE_NAME_FIELD_LENGTH;
const E131_DISCOVERY_FRAMING_LAYER_DATA_INDEX: usize =
    E131_DISCOVERY_FRAMING_LAYER_RESERVE_FIELD_INDEX
        + E131_DISCOVERY_FRAMING_LAYER_RESERVE_FIELD_LENGTH;
impl<'a> Pdu for UniverseDiscoveryPacketFramingLayer<'a> {
33
    fn parse(buf: &[u8]) -> Result<UniverseDiscoveryPacketFramingLayer<'a>> {
        // Length and Vector
33
        let PduInfo { length, vector } = pdu_info(buf, E131_FRAMING_LAYER_VECTOR_LENGTH)?;
33
        if buf.len() < length {
            return Err(SacnError::SacnParsePackError(ParsePacketError::ParseInsufficientData("Buffer contains insufficient data based on universe discovery packet framing layer pdu length field".to_string())));
33
        }
33
        if vector != VECTOR_E131_EXTENDED_DISCOVERY {
            return Err(SacnError::SacnParsePackError(
                ParsePacketError::PduInvalidVector(vector),
            ));
33
        }
33
        if length < E131_UNIVERSE_DISCOVERY_FRAMING_LAYER_MIN_LENGTH {
1
            return Err(SacnError::SacnParsePackError(
1
                ParsePacketError::PduInvalidLength(length),
1
            ));
32
        }
        // Source Name
32
        let source_name = String::from(parse_source_name_str(
32
            &buf[E131_DISCOVERY_FRAMING_LAYER_SOURCE_NAME_FIELD_INDEX
32
                ..E131_DISCOVERY_FRAMING_LAYER_RESERVE_FIELD_INDEX],
32
        )?);
        // Reserved data (immediately after source_name) ignored as per ANSI E1.31-2018 Section 6.4.3.
        // The universe discovery data.
32
        let data = UniverseDiscoveryPacketUniverseDiscoveryLayer::parse(
32
            &buf[E131_DISCOVERY_FRAMING_LAYER_DATA_INDEX..length],
32
        )?;
22
        Ok(UniverseDiscoveryPacketFramingLayer {
22
            source_name: source_name.into(),
22
            data,
22
        })
33
    }
24
    fn pack(&self, buf: &mut [u8]) -> Result<()> {
24
        if buf.len() < self.len() {
            return Err(SacnError::SacnParsePackError(
                ParsePacketError::PackBufferInsufficient(
                    "UniverseDiscoveryPacketFramingLayer pack buffer length insufficient"
                        .to_string(),
                ),
            ));
24
        }
        // Flags and Length
        let flags_and_length =
24
            NetworkEndian::read_u16(&[E131_PDU_FLAGS, 0x0]) | (self.len() as u16) & 0x0fff;
24
        NetworkEndian::write_u16(
24
            &mut buf[0..E131_DISCOVERY_FRAMING_LAYER_VECTOR_FIELD_INDEX],
24
            flags_and_length,
24
        );
        // Vector
24
        NetworkEndian::write_u32(
24
            &mut buf[E131_DISCOVERY_FRAMING_LAYER_VECTOR_FIELD_INDEX
24
                ..E131_DISCOVERY_FRAMING_LAYER_SOURCE_NAME_FIELD_INDEX],
24
            VECTOR_E131_EXTENDED_DISCOVERY,
24
        );
        // Source Name, always leaving room for the null terminator.
24
        if self.source_name.len() > E131_SOURCE_NAME_MAX_LENGTH {
2
            return Err(SacnError::SacnParsePackError(
2
                ParsePacketError::PackInvalidData(format!(
2
                    "Source name must be at most {} bytes",
2
                    E131_SOURCE_NAME_MAX_LENGTH
2
                )),
2
            ));
22
        }
22
        zeros(
22
            &mut buf[E131_DISCOVERY_FRAMING_LAYER_SOURCE_NAME_FIELD_INDEX
22
                ..E131_DISCOVERY_FRAMING_LAYER_RESERVE_FIELD_INDEX],
22
            E131_SOURCE_NAME_FIELD_LENGTH,
22
        );
22
        buf[E131_DISCOVERY_FRAMING_LAYER_SOURCE_NAME_FIELD_INDEX
22
            ..E131_DISCOVERY_FRAMING_LAYER_SOURCE_NAME_FIELD_INDEX + self.source_name.len()]
22
            .copy_from_slice(self.source_name.as_bytes());
        // Reserved
22
        zeros(
22
            &mut buf[E131_DISCOVERY_FRAMING_LAYER_RESERVE_FIELD_INDEX
22
                ..E131_DISCOVERY_FRAMING_LAYER_DATA_INDEX],
22
            E131_DISCOVERY_FRAMING_LAYER_RESERVE_FIELD_LENGTH,
22
        );
        // Data
22
        self.data
22
            .pack(&mut buf[E131_DISCOVERY_FRAMING_LAYER_DATA_INDEX..])
24
    }
167
    fn len(&self) -> usize {
        // Length and Flags
167
        E131_PDU_LENGTH_FLAGS_LENGTH +
167
        // Vector
167
        E131_FRAMING_LAYER_VECTOR_LENGTH +
167
        // Source Name
167
        E131_SOURCE_NAME_FIELD_LENGTH +
167
        // Reserved
167
        E131_DISCOVERY_FRAMING_LAYER_RESERVE_FIELD_LENGTH +
167
        // Data
167
        self.data.len()
167
    }
}
impl<'a> Clone for UniverseDiscoveryPacketFramingLayer<'a> {
    fn clone(&self) -> Self {
        UniverseDiscoveryPacketFramingLayer {
            source_name: self.source_name.clone(),
            data: self.data.clone(),
        }
    }
}
impl<'a> Hash for UniverseDiscoveryPacketFramingLayer<'a> {
    #[inline]
    fn hash<H: hash::Hasher>(&self, state: &mut H) {
        (*self.source_name).hash(state);
        self.data.hash(state);
    }
}
/// Universe discovery layer PDU.
#[derive(Eq, PartialEq, Debug)]
pub struct UniverseDiscoveryPacketUniverseDiscoveryLayer<'a> {
    /// Current page of the discovery packet.
    pub page: u8,
    /// The number of the final page.
    pub last_page: u8,
    /// List of universes.
    pub universes: Cow<'a, [u16]>,
}
// Calculate the indexes of the fields within the buffer based on the size of the fields previous.
// Constants are replaced inline so this increases readability by removing magic numbers without affecting runtime performance.
// Theses indexes are only valid within the scope of this part of the protocol (UniverseDiscoveryPacketUniverseDiscoveryLayer).
const E131_DISCOVERY_LAYER_VECTOR_FIELD_INDEX: usize = E131_PDU_LENGTH_FLAGS_LENGTH;
const E131_DISCOVERY_LAYER_PAGE_FIELD_INDEX: usize =
    E131_DISCOVERY_LAYER_VECTOR_FIELD_INDEX + E131_DISCOVERY_LAYER_VECTOR_FIELD_LENGTH;
const E131_DISCOVERY_LAYER_LAST_PAGE_FIELD_INDEX: usize =
    E131_DISCOVERY_LAYER_PAGE_FIELD_INDEX + E131_DISCOVERY_LAYER_PAGE_FIELD_LENGTH;
const E131_DISCOVERY_LAYER_UNIVERSE_LIST_FIELD_INDEX: usize =
    E131_DISCOVERY_LAYER_LAST_PAGE_FIELD_INDEX + E131_DISCOVERY_LAYER_LAST_PAGE_FIELD_LENGTH;
impl<'a> Pdu for UniverseDiscoveryPacketUniverseDiscoveryLayer<'a> {
32
    fn parse(buf: &[u8]) -> Result<UniverseDiscoveryPacketUniverseDiscoveryLayer<'a>> {
        // Length and Vector
32
        let PduInfo { length, vector } = pdu_info(buf, E131_DISCOVERY_LAYER_VECTOR_FIELD_LENGTH)?;
30
        if buf.len() != length {
3
            return Err(SacnError::SacnParsePackError(ParsePacketError::ParseInsufficientData(
3
                format!("Buffer contains incorrect amount of data ({} bytes) based on universe discovery packet universe discovery layer pdu length field ({} bytes)"
3
                , buf.len() ,length).to_string())));
27
        }
27
        if vector != VECTOR_UNIVERSE_DISCOVERY_UNIVERSE_LIST {
1
            return Err(SacnError::SacnParsePackError(
1
                ParsePacketError::PduInvalidVector(vector),
1
            ));
26
        }
26
        if !(E131_UNIVERSE_DISCOVERY_LAYER_MIN_LENGTH..=E131_UNIVERSE_DISCOVERY_LAYER_MAX_LENGTH)
26
            .contains(&length)
        {
1
            return Err(SacnError::SacnParsePackError(
1
                ParsePacketError::PduInvalidLength(length),
1
            ));
25
        }
        // Page
25
        let page = buf[E131_DISCOVERY_LAYER_PAGE_FIELD_INDEX];
        // Last Page
25
        let last_page = buf[E131_DISCOVERY_LAYER_LAST_PAGE_FIELD_INDEX];
25
        if page > last_page {
1
            return Err(SacnError::SacnParsePackError(
1
                ParsePacketError::ParseInvalidPage("Page value higher than last_page".to_string()),
1
            ));
24
        }
        // The number of universes, calculated by dividing the remaining space in the packet by the size of a single universe.
        let universes_length =
24
            (length - E131_DISCOVERY_LAYER_UNIVERSE_LIST_FIELD_INDEX) / E131_UNIVERSE_FIELD_LENGTH;
24
        let universes: Cow<'a, [u16]> = parse_universe_list(
24
            &buf[E131_DISCOVERY_LAYER_UNIVERSE_LIST_FIELD_INDEX..],
24
            universes_length,
24
        )?;
22
        Ok(UniverseDiscoveryPacketUniverseDiscoveryLayer {
22
            page,
22
            last_page,
22
            universes,
22
        })
32
    }
22
    fn pack(&self, buf: &mut [u8]) -> Result<()> {
22
        if self.universes.len() > DISCOVERY_UNI_PER_PAGE {
            return Err(SacnError::SacnParsePackError(
                ParsePacketError::PackInvalidData(
                    format!(
                        "Maximum {} universes allowed per discovery page",
                        DISCOVERY_UNI_PER_PAGE
                    )
                    .to_string(),
                ),
            ));
22
        }
22
        if buf.len() < self.len() {
            return Err(SacnError::SacnParsePackError(
                ParsePacketError::PackBufferInsufficient(
                    "UniverseDiscoveryPacketUniverseDiscoveryLayer pack buffer insufficient"
                        .to_string(),
                ),
            ));
22
        }
        // Flags and Length
        let flags_and_length =
22
            NetworkEndian::read_u16(&[E131_PDU_FLAGS, 0x0]) | (self.len() as u16) & 0x0fff;
22
        NetworkEndian::write_u16(
22
            &mut buf[0..E131_DISCOVERY_FRAMING_LAYER_VECTOR_FIELD_INDEX],
22
            flags_and_length,
22
        );
        // Vector
22
        NetworkEndian::write_u32(
22
            &mut buf
22
                [E131_DISCOVERY_LAYER_VECTOR_FIELD_INDEX..E131_DISCOVERY_LAYER_PAGE_FIELD_INDEX],
22
            VECTOR_UNIVERSE_DISCOVERY_UNIVERSE_LIST,
22
        );
        // Page
22
        buf[E131_DISCOVERY_LAYER_PAGE_FIELD_INDEX] = self.page;
        // Last Page
22
        buf[E131_DISCOVERY_LAYER_LAST_PAGE_FIELD_INDEX] = self.last_page;
        // Universes
22
        for i in 1..self.universes.len() {
1220
            if self.universes[i] == self.universes[i - 1] {
                return Err(SacnError::SacnParsePackError(
                    ParsePacketError::PackInvalidData("Universes are not unique".to_string()),
                ));
1220
            }
1220
            if self.universes[i] <= self.universes[i - 1] {
                return Err(SacnError::SacnParsePackError(
                    ParsePacketError::PackInvalidData("Universes are not sorted".to_string()),
                ));
1220
            }
        }
22
        NetworkEndian::write_u16_into(
22
            &self.universes[..self.universes.len()],
22
            &mut buf[E131_DISCOVERY_LAYER_UNIVERSE_LIST_FIELD_INDEX
22
                ..E131_DISCOVERY_LAYER_UNIVERSE_LIST_FIELD_INDEX
22
                    + self.universes.len() * E131_UNIVERSE_FIELD_LENGTH],
22
        );
22
        Ok(())
22
    }
211
    fn len(&self) -> usize {
        // Length and Flags
211
        E131_PDU_LENGTH_FLAGS_LENGTH +
211
        // Vector
211
        E131_DISCOVERY_LAYER_VECTOR_FIELD_LENGTH +
211
        // Page
211
        E131_DISCOVERY_LAYER_PAGE_FIELD_LENGTH +
211
        // Last Page
211
        E131_DISCOVERY_LAYER_LAST_PAGE_FIELD_LENGTH +
211
        // Universes
211
        self.universes.len() * E131_UNIVERSE_FIELD_LENGTH
211
    }
}
impl<'a> Clone for UniverseDiscoveryPacketUniverseDiscoveryLayer<'a> {
    fn clone(&self) -> Self {
        UniverseDiscoveryPacketUniverseDiscoveryLayer {
            page: self.page,
            last_page: self.last_page,
            universes: self.universes.clone(),
        }
    }
}
impl<'a> Hash for UniverseDiscoveryPacketUniverseDiscoveryLayer<'a> {
    #[inline]
    fn hash<H: hash::Hasher>(&self, state: &mut H) {
        self.page.hash(state);
        self.last_page.hash(state);
        (*self.universes).hash(state);
    }
}
/// Takes the given buffer representing the "List of Universe" field in an ANSI E1.31-2018 discovery packet and parses it into the universe values.
///
/// This enforces the requirement from ANSI E1.31-2018 Section 8.5 that the universes must be numerically sorted.
///
/// # Arguments
/// buf: The byte buffer to parse into the universe.
/// length: The number of universes to attempt to parse from the buffer.
///
/// # Errors
/// `ParseInvalidUniverseOrder`: If the universes are not sorted in ascending order with no duplicates.
///
/// `ParseInsufficientData`: If the buffer doesn't contain sufficient bytes and so cannot be parsed into the specified number of u16 universes.
24
fn parse_universe_list<'a>(buf: &[u8], length: usize) -> Result<Cow<'a, [u16]>> {
24
    let mut universes: Vec<u16> = Vec::with_capacity(length);
24
    let mut i = 0;
    // Last_universe starts as a placeholder value that is guaranteed to be less than the lowest possible advertised universe.
    // Cannot use 0 even though under ANSI E1.31-2018 it cannot be used for data or as a sync_address as it is reserved for future use
    // so may be used in future.
24
    let mut last_universe: i32 = -1;
24
    if buf.len() < length * E131_UNIVERSE_FIELD_LENGTH {
        return Err(SacnError::SacnParsePackError(
            ParsePacketError::ParseInsufficientData(format!(
                "The given buffer of length {} bytes cannot be parsed into the given number of universes {}",
                buf.len(),
                length
            )),
        ));
24
    }
1779
    while i < (length * E131_UNIVERSE_FIELD_LENGTH) {
1757
        let u = NetworkEndian::read_u16(&buf[i..i + E131_UNIVERSE_FIELD_LENGTH]);
1757
        if (u as i32) > last_universe {
            // Enforce assending ordering of universes as per ANSI E1.31-2018 Section 8.5.
1755
            universes.push(u);
1755
            last_universe = u as i32;
1755
            i += E131_UNIVERSE_FIELD_LENGTH; // Jump to the next universe.
        } else {
2
            return Err(SacnError::SacnParsePackError(
2
                ParsePacketError::ParseInvalidUniverseOrder(format!(
2
                    "Universe {u} is out of order, discovery packet universe list must be in accending order!"
2
                )),
2
            ));
        }
    }
22
    Ok(universes.into())
24
}
#[cfg(test)]
mod test {
    use super::*;
    use std::net::{Ipv4Addr, Ipv6Addr, SocketAddrV4, SocketAddrV6};
    /// The `universe_to` tests below check that the conversion from a universe to an IPv6 or IPv4 multicast address is done as
    /// per ANSI E1.31-2018 Section 9.3.1 Table 9-10 (IPv4) and ANSI E1.31-2018 Section 9.3.2 Table 9-11 + Table 9-12.
    #[test]
1
    fn test_universe_to_ipv4_lowest_byte_normal() {
1
        let val: u16 = 119;
1
        let res = universe_to_ipv4_multicast_addr(val).unwrap();
1
        assert!(res.as_socket_ipv4().unwrap().ip().is_multicast());
1
        assert_eq!(
1
            res.as_socket_ipv4().unwrap(),
1
            SocketAddrV4::new(
1
                Ipv4Addr::new(239, 255, (val / 256) as u8, (val % 256) as u8),
1
                ACN_SDT_MULTICAST_PORT
1
            )
        );
1
    }
    #[test]
1
    fn test_universe_to_ip_ipv4_both_bytes_normal() {
1
        let val: u16 = 300;
1
        let res = universe_to_ipv4_multicast_addr(val).unwrap();
1
        assert!(res.as_socket_ipv4().unwrap().ip().is_multicast());
1
        assert_eq!(
1
            res.as_socket_ipv4().unwrap(),
1
            SocketAddrV4::new(
1
                Ipv4Addr::new(239, 255, (val / 256) as u8, (val % 256) as u8),
1
                ACN_SDT_MULTICAST_PORT
1
            )
        );
1
    }
    #[test]
1
    fn test_universe_to_ip_ipv4_limit_high() {
1
        let res = universe_to_ipv4_multicast_addr(E131_MAX_MULTICAST_UNIVERSE).unwrap();
1
        assert!(res.as_socket_ipv4().unwrap().ip().is_multicast());
1
        assert_eq!(
1
            res.as_socket_ipv4().unwrap(),
1
            SocketAddrV4::new(
1
                Ipv4Addr::new(
1
                    239,
1
                    255,
1
                    (E131_MAX_MULTICAST_UNIVERSE / 256) as u8,
1
                    (E131_MAX_MULTICAST_UNIVERSE % 256) as u8
1
                ),
1
                ACN_SDT_MULTICAST_PORT
1
            )
        );
1
    }
    #[test]
1
    fn test_universe_to_ip_ipv4_limit_low() {
1
        let res = universe_to_ipv4_multicast_addr(E131_MIN_MULTICAST_UNIVERSE).unwrap();
1
        assert!(res.as_socket_ipv4().unwrap().ip().is_multicast());
1
        assert_eq!(
1
            res.as_socket_ipv4().unwrap(),
1
            SocketAddrV4::new(
1
                Ipv4Addr::new(
1
                    239,
1
                    255,
1
                    (E131_MIN_MULTICAST_UNIVERSE / 256) as u8,
1
                    (E131_MIN_MULTICAST_UNIVERSE % 256) as u8
1
                ),
1
                ACN_SDT_MULTICAST_PORT
1
            )
        );
1
    }
    #[test]
1
    fn test_universe_to_ip_ipv4_out_range_low() {
1
        match universe_to_ipv4_multicast_addr(0) {
            Ok(_) => panic!("Universe to ipv4 multicast allowed below minimum allowed universe"),
1
            Err(e) => match e {
1
                SacnError::IllegalUniverse(_) => {}
                _ => panic!("Unexpected error type returned"),
            },
        }
1
    }
    #[test]
1
    fn test_universe_to_ip_ipv4_out_range_high() {
1
        match universe_to_ipv4_multicast_addr(E131_MAX_MULTICAST_UNIVERSE + 10) {
            Ok(_) => panic!("Universe to ipv4 multicast allowed above maximum allowed universe"),
1
            Err(e) => match e {
1
                SacnError::IllegalUniverse(_) => {}
                _ => panic!("Unexpected error type returned"),
            },
        }
1
    }
    #[test]
1
    fn test_universe_to_ipv6_lowest_byte_normal() {
1
        let val: u16 = 119;
1
        let res = universe_to_ipv6_multicast_addr(val).unwrap();
1
        assert!(res.as_socket_ipv6().unwrap().ip().is_multicast());
1
        let low_16: u16 = ((val / 256) << 8) | (val % 256);
1
        assert_eq!(
1
            res.as_socket_ipv6().unwrap(),
1
            SocketAddrV6::new(
1
                Ipv6Addr::new(0xFF18, 0, 0, 0, 0, 0, 0x8300, low_16),
1
                ACN_SDT_MULTICAST_PORT,
1
                0,
1
                0
1
            )
        );
1
    }
    #[test]
1
    fn test_universe_to_ip_ipv6_both_bytes_normal() {
1
        let val: u16 = 300;
1
        let res = universe_to_ipv6_multicast_addr(val).unwrap();
1
        assert!(res.as_socket_ipv6().unwrap().ip().is_multicast());
1
        let low_16: u16 = ((val / 256) << 8) | (val % 256);
1
        assert_eq!(
1
            res.as_socket_ipv6().unwrap(),
1
            SocketAddrV6::new(
1
                Ipv6Addr::new(0xFF18, 0, 0, 0, 0, 0, 0x8300, low_16),
1
                ACN_SDT_MULTICAST_PORT,
1
                0,
1
                0
1
            )
        );
1
    }
    #[test]
1
    fn test_universe_to_ip_ipv6_limit_high() {
1
        let res = universe_to_ipv6_multicast_addr(E131_MAX_MULTICAST_UNIVERSE).unwrap();
1
        assert!(res.as_socket_ipv6().unwrap().ip().is_multicast());
        let low_16: u16 =
1
            ((E131_MAX_MULTICAST_UNIVERSE / 256) << 8) | (E131_MAX_MULTICAST_UNIVERSE % 256);
1
        assert_eq!(
1
            res.as_socket_ipv6().unwrap(),
1
            SocketAddrV6::new(
1
                Ipv6Addr::new(0xFF18, 0, 0, 0, 0, 0, 0x8300, low_16),
1
                ACN_SDT_MULTICAST_PORT,
1
                0,
1
                0
1
            )
        );
1
    }
    #[test]
1
    fn test_universe_to_ip_ipv6_limit_low() {
1
        let res = universe_to_ipv6_multicast_addr(E131_MIN_MULTICAST_UNIVERSE).unwrap();
1
        assert!(res.as_socket_ipv6().unwrap().ip().is_multicast());
        let low_16: u16 =
1
            ((E131_MIN_MULTICAST_UNIVERSE / 256) << 8) | (E131_MIN_MULTICAST_UNIVERSE % 256);
1
        assert_eq!(
1
            res.as_socket_ipv6().unwrap(),
1
            SocketAddrV6::new(
1
                Ipv6Addr::new(0xFF18, 0, 0, 0, 0, 0, 0x8300, low_16),
1
                ACN_SDT_MULTICAST_PORT,
1
                0,
1
                0
1
            )
        );
1
    }
    #[test]
1
    fn test_universe_to_ip_ipv6_out_range_low() {
1
        match universe_to_ipv6_multicast_addr(0) {
            Ok(_) => panic!("Universe to ipv4 multicast allowed below minimum allowed universe"),
1
            Err(e) => match e {
1
                SacnError::IllegalUniverse(_) => {}
                _ => panic!("Unexpected error type returned"),
            },
        }
1
    }
    #[test]
1
    fn test_universe_to_ip_ipv6_out_range_high() {
1
        match universe_to_ipv6_multicast_addr(E131_MAX_MULTICAST_UNIVERSE + 10) {
            Ok(_) => panic!("Universe to ipv4 multicast allowed above maximum allowed universe"),
1
            Err(e) => match e {
1
                SacnError::IllegalUniverse(_) => {}
                _ => panic!("Unexpected error type returned"),
            },
        }
1
    }
    /// Verifies that the parameters are set correctly as per ANSI E1.31-2018 Appendix A: Defined Parameters (Normative).
    /// This test is particularly useful at the maintenance stage as it will flag up if any protocol defined constant is changed.
    #[test]
1
    fn check_ansi_e131_2018_parameter_values() {
1
        assert_eq!(VECTOR_ROOT_E131_DATA, 0x0000_0004);
1
        assert_eq!(VECTOR_ROOT_E131_EXTENDED, 0x0000_0008);
1
        assert_eq!(VECTOR_DMP_SET_PROPERTY, 0x02);
1
        assert_eq!(VECTOR_E131_DATA_PACKET, 0x0000_0002);
1
        assert_eq!(VECTOR_E131_EXTENDED_SYNCHRONIZATION, 0x0000_0001);
1
        assert_eq!(VECTOR_E131_EXTENDED_DISCOVERY, 0x0000_0002);
1
        assert_eq!(VECTOR_UNIVERSE_DISCOVERY_UNIVERSE_LIST, 0x0000_0001);
1
        assert_eq!(E131_UNIVERSE_DISCOVERY_INTERVAL, Duration::from_secs(10));
1
        assert_eq!(E131_NETWORK_DATA_LOSS_TIMEOUT, Duration::from_millis(2500));
1
        assert_eq!(E131_DISCOVERY_UNIVERSE, 64214);
1
        assert_eq!(ACN_SDT_MULTICAST_PORT, 5568);
1
    }
}