wol 0.5.1

Wake up remote hosts with Wake On LAN magic packets
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
// Copyright Sebastian Wiesner <sebastian@swsnr.de>
//
// Licensed under the EUPL
//
// See https://interoperable-europe.ec.europa.eu/collection/eupl/eupl-text-eupl-12

#![deny(warnings,
    missing_docs,
    missing_debug_implementations,
    missing_copy_implementations,
    clippy::all,
    clippy::pedantic,
    // Do cfg(test) right
    clippy::cfg_not_test,
    clippy::tests_outside_test_module,
    // Guard against left-over debugging output
    clippy::dbg_macro,
    clippy::print_stderr,
    clippy::print_stdout,
    clippy::unimplemented,
    clippy::use_debug,
    clippy::todo,
    // We should not exit here
    clippy::exit,
    // Don't panic carelessly
    clippy::get_unwrap,
    clippy::unused_result_ok,
    clippy::unwrap_in_result,
    clippy::indexing_slicing,
    // Do not carelessly ignore errors
    clippy::let_underscore_must_use,
    clippy::let_underscore_untyped,
    // Code smells
    clippy::float_cmp_const,
    clippy::if_then_some_else_none,
    clippy::large_include_file,
    // Disable as casts
    clippy::as_conversions,
)]
#![forbid(unsafe_code)]

//! Wake on LAN magic packets.
//!
//! ## Send magic packets
//!
//! [`send_magic_packet`] provides a convenience function to send a single packet:
//!
//! ```no_run
//! use std::str::FromStr;
//! use std::net::Ipv4Addr;
//! let mac_address = wol::MacAddress::from([0x12, 0x13, 0x14, 0x15, 0x16, 0x17]);
//! wol::send_magic_packet(mac_address, None, (Ipv4Addr::BROADCAST, 9).into()).unwrap();
//! ```
//!
//! For more control, create the [`std::net::UdpSocket`] yourself:
//!
//! ```no_run
//! use std::str::FromStr;
//! use std::net::{Ipv4Addr, UdpSocket};
//! use wol::SendMagicPacket;
//! let socket = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).unwrap();
//! let mac_address = wol::MacAddress::from([0x12, 0x13, 0x14, 0x15, 0x16, 0x17]);
//!
//! socket.send_magic_packet(mac_address, None, (Ipv4Addr::BROADCAST, 9)).unwrap();
//! ```
//!
//! ## Assemble magic packets
//!
//! To send magic packets over other socket APIs, use [`fill_magic_packet`] or [`write_magic_packet`]
//! to assmble magic packets.
//!
//! ## SecureON
//!
//! This crate supports SecureON magic packets.

use std::error::Error;
use std::fmt::Display;
use std::io::Write;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, ToSocketAddrs, UdpSocket};
use std::str::FromStr;

#[cfg(feature = "file")]
pub mod file;

/// A MAC address as a newtype wrapper around `[u8; 6]`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MacAddress([u8; 6]);

impl MacAddress {
    /// Create a MAC address from six bytes.
    #[must_use]
    pub fn new(address: [u8; 6]) -> Self {
        Self(address)
    }
}

impl AsRef<[u8]> for MacAddress {
    fn as_ref(&self) -> &[u8] {
        &self.0
    }
}

impl From<MacAddress> for [u8; 6] {
    fn from(value: MacAddress) -> Self {
        value.0
    }
}

impl From<[u8; 6]> for MacAddress {
    fn from(value: [u8; 6]) -> Self {
        Self(value)
    }
}

/// Display a [`MacAddress`].
///
/// ```
/// # use wol::MacAddress;
/// let addr = MacAddress::from([0xab, 0x0d, 0xef, 0x12, 0x34, 0x56]);
///
/// assert_eq!(&format!("{}",    addr), "AB:0D:EF:12:34:56");
/// assert_eq!(&format!("{:-}",  addr), "AB-0D-EF-12-34-56");
/// ```
impl Display for MacAddress {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let sep = if f.sign_minus() { '-' } else { ':' };
        write!(
            f,
            "{:02X}{sep}{:02X}{sep}{:02X}{sep}{:02X}{sep}{:02X}{sep}{:02X}",
            self.0[0], self.0[1], self.0[2], self.0[3], self.0[4], self.0[5]
        )
    }
}

/// A SecureON token.
///
/// A SecureON token consists of six bytes, similar to a MAC address.
///
/// If such a SecureON token is set in the firmware of the target device, the
/// device will only wake up if the magic packet additionally includes the given
/// SecureON token.
///
/// This offers a marginal amount of protection against unauthorized wake-ups in
/// case the MAC address of the target device is known. Note however that this
/// SecureON token is included in the magic packet as plain text, so it should
/// **not be assumed a secret**.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SecureOn([u8; 6]);

impl SecureOn {
    /// Create a SecureON token from six bytes.
    #[must_use]
    pub fn new(address: [u8; 6]) -> Self {
        Self(address)
    }
}

impl AsRef<[u8]> for SecureOn {
    fn as_ref(&self) -> &[u8] {
        &self.0
    }
}

impl From<SecureOn> for [u8; 6] {
    fn from(value: SecureOn) -> Self {
        value.0
    }
}

impl From<[u8; 6]> for SecureOn {
    fn from(value: [u8; 6]) -> Self {
        Self(value)
    }
}

impl Display for SecureOn {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", MacAddress::new(self.0))
    }
}

/// Kind of parse error.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ParseErrorKind {
    /// The input was too short to represent a EUI48 address.
    TooShort,
    /// An invalid separator.
    InvalidSeparator,
    /// A byte literal was invalid.
    InvalidByteLiteral,
    /// Trailing bytes where found in input.
    TrailingBytes,
}

/// A parse error.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ParseError {
    kind: ParseErrorKind,
}

impl Display for ParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.kind {
            ParseErrorKind::InvalidByteLiteral => "invalid byte literal found in string",
            ParseErrorKind::TooShort => "input too short",
            ParseErrorKind::InvalidSeparator => "invalid separator found in string",
            ParseErrorKind::TrailingBytes => "trailing bytes found in string",
        }
        .fmt(f)
    }
}

impl Error for ParseError {}

impl ParseError {
    /// The kind of parse error.
    #[must_use]
    pub fn kind(&self) -> ParseErrorKind {
        self.kind
    }
}

#[inline]
fn parse_eui48_with_sep(s: &str, sep: u8) -> Result<[u8; 6], ParseErrorKind> {
    let mut addr = [0; 6];
    let mut last_field = 0;
    for (i, byte_literal) in s.as_bytes().split(|b| *b == sep).enumerate() {
        match addr.get_mut(i) {
            Some(byte) => {
                last_field = i;
                if byte_literal.len() != 2 {
                    return Err(ParseErrorKind::InvalidByteLiteral);
                }
                // TODO: use u8::from_ascii once stabilized
                *byte = u8::from_str_radix(
                    std::str::from_utf8(byte_literal)
                        // we can safely unwrap here, because the original input is valid
                        // UTF-8 and we're not splitting inside code points.
                        .map_err(|_| ParseErrorKind::InvalidByteLiteral)?,
                    16,
                )
                .map_err(|_| ParseErrorKind::InvalidByteLiteral)?;
            }
            None => return Err(ParseErrorKind::TrailingBytes),
        }
    }
    if last_field == addr.len() - 1 {
        Ok(addr)
    } else {
        Err(ParseErrorKind::TooShort)
    }
}

fn parse_eui48(s: &str) -> Result<[u8; 6], ParseError> {
    match s.as_bytes().get(2) {
        None => Err(ParseErrorKind::TooShort),
        Some(sep @ (b'-' | b':')) => parse_eui48_with_sep(s, *sep),
        Some(_) => Err(ParseErrorKind::InvalidSeparator),
    }
    .map_err(|kind| ParseError { kind })
}

/// Parse a MAC address from a string:
///
/// ```
/// # use std::str::FromStr;
/// # use wol::MacAddress;
/// assert_eq!(MacAddress::from_str("26-ce-55-a5-c2-33"), Ok(MacAddress::new([0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33])));
/// assert_eq!(MacAddress::from_str("26-CE-55-A5-C2-33"), Ok(MacAddress::new([0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33])));
/// assert_eq!(MacAddress::from_str("26:CE:55:A5:C2:33"), Ok(MacAddress::new([0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33])));
/// assert!(MacAddress::from_str("26:CE-55:A5-C2:33").is_err());
/// assert!(MacAddress::from_str("26:CE:zz:A5:C2:33").is_err());
/// assert!(MacAddress::from_str("26:CE:55:A5:C2:33:ff").is_err());
/// ```
impl FromStr for MacAddress {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        parse_eui48(s).map(Self::new)
    }
}

/// Parse a SecureON token from a string:
///
/// ```
/// # use std::str::FromStr;
/// # use wol::SecureOn;
/// assert_eq!(SecureOn::from_str("00-DE-AD-BE-EF-00"), Ok(SecureOn::new([0x00, 0xDE, 0xAD, 0xBE, 0xEF, 0x00])));
/// assert_eq!(SecureOn::from_str("00:DE:AD:BE:EF:00"), Ok(SecureOn::new([0x00, 0xDE, 0xAD, 0xBE, 0xEF, 0x00])));
/// assert_eq!(SecureOn::from_str("00:de:ad:be:ef:00"), Ok(SecureOn::new([0x00, 0xDE, 0xAD, 0xBE, 0xEF, 0x00])));
/// assert!(SecureOn::from_str("00-DE:AD:BE:EF-00").is_err());
/// assert!(SecureOn::from_str("DE-AD-BE-EF").is_err());
/// ```
impl FromStr for SecureOn {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        parse_eui48(s).map(Self::new)
    }
}

/// Fill a buffer with a magic packet.
///
/// Fill `buffer` with a magic packet to wake up `mac_address`.
pub fn fill_magic_packet(buffer: &mut [u8; 102], mac_address: MacAddress) {
    buffer[0..6].copy_from_slice(&[0xff; 6]);
    for i in 0..16 {
        let base = (i + 1) * 6;
        // We know that `buffer` is large enough.
        #[allow(clippy::indexing_slicing)]
        buffer[base..base + 6].copy_from_slice(mac_address.as_ref());
    }
}

/// Fill a buffer with a magic packet with a SecureON token.
///
/// Fill `buffer` with a magic packet to wake up `mac_address`, using the
/// `secure_on` token.
#[allow(clippy::missing_panics_doc)]
pub fn fill_magic_packet_secure_on(
    buffer: &mut [u8; 108],
    mac_address: MacAddress,
    secure_on: SecureOn,
) {
    // We know that `buffer` is >= 102 characters so this will never panic.
    fill_magic_packet((&mut buffer[..102]).try_into().unwrap(), mac_address);
    buffer[102..].copy_from_slice(secure_on.as_ref());
}

/// Write a magic packet to a buffer.
///
/// Write a magic packet to `sink`, to wake up `mac_address`.  If `secure_on` is
/// not `None`, include it at the end of the magic packet.
///
/// See [`SecureOn`] for more information about SecureON.
///
/// # Errors
///
/// Return an error if the underlying [`Write::write_all`] fails.
pub fn write_magic_packet<W: Write>(
    sink: &mut W,
    mac_address: MacAddress,
    secure_on: Option<SecureOn>,
) -> std::io::Result<()> {
    sink.write_all(&[0xff; 6])?;
    for _ in 0..16 {
        sink.write_all(mac_address.as_ref())?;
    }
    if let Some(secure_on) = secure_on {
        sink.write_all(secure_on.as_ref())?;
    }
    Ok(())
}

/// A socket which supports sending a magic packet.
pub trait SendMagicPacket {
    /// Send a magic packet over this socket.
    ///
    /// Send a magic packet to wake up `mac_address` over this socket.  If
    /// `secure_on` is not `None`, include the SecureON token in the packet.
    /// Use `addr` as destination address for the packet.
    ///
    /// # SecureON
    ///
    /// In addition to the `mac_address`, you can optionally include a shared
    /// "SecureON" token in the magic packet.
    ///
    /// See [`SecureOn`] for more information.
    ///
    /// # Target address
    ///
    /// Normally, you would send the packet to the broadcast address (IPv4) or
    /// the link-local multicast address (IPv6), but you may specify any address
    /// as long as the target host will *physically see* the packet along its
    /// way to the target address.
    ///
    /// Any target port will do, since the magic packet never makes it to the
    /// operating system where ports matter; the NIC will directly process it.
    ///
    /// Port `9` (discard) is often a good choice, because no service will
    /// listen on this port.
    ///
    /// # Errors
    ///
    /// Return any errors from the underlying socket I/O.
    fn send_magic_packet<A: ToSocketAddrs>(
        &self,
        mac_address: MacAddress,
        secure_on: Option<SecureOn>,
        addr: A,
    ) -> std::io::Result<()>;
}

impl SendMagicPacket for UdpSocket {
    fn send_magic_packet<A: ToSocketAddrs>(
        &self,
        mac_address: MacAddress,
        secure_on: Option<SecureOn>,
        addr: A,
    ) -> std::io::Result<()> {
        if let Some(secure_on) = secure_on {
            let mut packet = [0; 108];
            fill_magic_packet_secure_on(&mut packet, mac_address, secure_on);
            let size = self.send_to(&packet, addr)?;
            // `send_to` won't send partial data until i32::MAX, according to
            // `UdpSocket::send-to`, so if we get a partial write nonetheless
            // something's seriously wrong, and we should just crash for satefy.
            assert!(size == packet.len());
        } else {
            let mut packet = [0; 102];
            fill_magic_packet(&mut packet, mac_address);
            let size = self.send_to(&packet, addr)?;
            // Same here
            assert!(size == packet.len());
        }
        Ok(())
    }
}

/// Send one magic packet.
///
/// Bind a new UDP socket to send a magic packet.  If `addr` is an IPv4 address
/// bind to [`Ipv4Addr::UNSPECIFIED`], otherwise bind [`Ipv6Addr::UNSPECIFIED`].
/// Then send a magic packet to wake up `mac_address` over this socket, to the
/// given destination `addr`.
///
/// If `secure_on` is not `None`, include the SecureON token in the magic
/// packet. See [`SecureOn`] for more information about SecureON.
///
/// See [`SendMagicPacket::send_magic_packet`] for details about the arguments.
///
/// # Errors
///
/// Return errors from underlying socket I/O.
pub fn send_magic_packet(
    mac_address: MacAddress,
    secure_on: Option<SecureOn>,
    addr: SocketAddr,
) -> std::io::Result<()> {
    let bind_address = if addr.is_ipv4() {
        IpAddr::from(Ipv4Addr::UNSPECIFIED)
    } else {
        IpAddr::from(Ipv6Addr::UNSPECIFIED)
    };
    let socket = UdpSocket::bind((bind_address, 0))?;
    socket.set_broadcast(true)?;
    socket.send_magic_packet(mac_address, secure_on, addr)
}

#[cfg(test)]
mod tests {
    use crate::{fill_magic_packet, fill_magic_packet_secure_on};

    use super::{MacAddress, write_magic_packet};

    mod parse {
        use super::super::*;

        #[test]
        fn valid_eui48() {
            assert_eq!(
                parse_eui48("12-13-14-15-16-17").unwrap(),
                [0x12, 0x13, 0x14, 0x15, 0x16, 0x17]
            );
            assert_eq!(
                parse_eui48("aa:BB:cc:DD:ee:FF").unwrap(),
                [0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF]
            );
        }

        #[test]
        fn invalid_eui48() {
            let cases = [
                "12|13-14-15-16-17", // Invalid separator
                "12:13-14-15-16-17", // Mixed separators
                "12-13-4-15-16-17",  // Missing leading zero
                "12-13-z1-15-16-17", // Invalid hex char after separator
                "12-13-1z-15-16-17", // Invalid hex char before separator
                "12-15-16-17",       // Too short
                "12-15-16-17-3",
                "12-13-14-15-16-17-18", // Too long
            ];
            for case in cases {
                let result = parse_eui48(case);
                assert!(result.is_err(), "{case}: {result:?}");
            }
        }
    }

    #[test]
    fn test_fill_magic_packet() {
        let mac_address = MacAddress::from([0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33]);
        let mut buffer = [0; 102];
        fill_magic_packet(&mut buffer, mac_address);
        let expected_packet: [u8; 102] = [
            0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // Six all 1 bytes
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, // 16 repetitions of the mac address
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //  5
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, // 10
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, // 15
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //
        ];
        assert_eq!(buffer, expected_packet);
    }

    #[test]
    fn test_fill_magic_packet_secure_on() {
        let secure_on = [0x12, 0x13, 0x14, 0x15, 0x16, 0x42];
        let mac_address = MacAddress::from([0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33]);
        let mut buffer = [0; 108];
        fill_magic_packet_secure_on(&mut buffer, mac_address, secure_on.into());
        let expected_packet: [u8; 108] = [
            0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // Six all 1 bytes
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, // 16 repetitions of the mac address
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //  5
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, // 10
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, // 15
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //
            0x12, 0x13, 0x14, 0x15, 0x16, 0x42, // SecureON
        ];
        assert_eq!(buffer, expected_packet);
    }

    #[test]
    fn test_write_magic_packet() {
        let mac_address = MacAddress::from([0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33]);
        let mut buffer = Vec::new();
        write_magic_packet(&mut buffer, mac_address, None).unwrap();
        let expected_packet: [u8; 102] = [
            0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // Six all 1 bytes
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, // 16 repetitions of the mac address
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //  5
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, // 10
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, // 15
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //
        ];
        assert_eq!(buffer.as_slice(), expected_packet.as_slice());
    }

    #[test]
    fn test_write_magic_packet_secure_on() {
        let secure_on = [0x12, 0x13, 0x14, 0x15, 0x16, 0x42];
        let mac_address = MacAddress::from([0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33]);
        let mut buffer = Vec::new();
        write_magic_packet(&mut buffer, mac_address, Some(secure_on.into())).unwrap();
        let expected_packet: [u8; 108] = [
            0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // Six all 1 bytes
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, // 16 repetitions of the mac address
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //  5
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, // 10
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, // 15
            0x26, 0xCE, 0x55, 0xA5, 0xC2, 0x33, //
            0x12, 0x13, 0x14, 0x15, 0x16, 0x42, // SecureON
        ];
        assert_eq!(buffer.as_slice(), expected_packet.as_slice());
    }
}