aboutsummaryrefslogtreecommitdiff
path: root/src/main.rs
blob: 3d86a8e2ae5b49e2ef03089765118003f3b4618c (plain)
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
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
#![feature(cursor_split)]
pub mod dhcp;
pub mod tftp;
pub mod wire;

use std::io::{BufRead, Cursor, Read, Result, Write};
use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, UdpSocket};

const FLAG_BROADCAST: u16 = 1 << 15;

const OPTION_CODE_PAD: u8 = 0;
const OPTION_CODE_END: u8 = 255;
const OPTION_CODE_VENDOR_CLASS_IDENTIFIER: u8 = 60;
const OPTION_CODE_USER_CLASS_INFORMATION: u8 = 77;

const MAGIC_COOKIE: [u8; 4] = [0x63, 0x82, 0x53, 0x63];

//const BOOT_FILE_NAME: &[u8] = b"pxelinux.0";
//const BOOT_FILE_NAME: &[u8] = b"debian-installer/amd64/bootnetx64.efi";
const BOOT_FILE_NAME: &[u8] = b"ipxe.efi";
const BOOT_FILE_NAME_IPXE: &[u8] = b"test.ipxe";

const LOCAL_IPV4: Ipv4Addr = Ipv4Addr::new(192, 168, 1, 100);

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum BootOp {
    Request,
    Reply,
}

impl BootOp {
    pub const OP_REQUEST: u8 = 1;
    pub const OP_REPLY: u8 = 2;
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum HardwareType {
    Ethernet,
}

impl HardwareType {
    pub const TYPE_ETHER: u8 = 1;
    pub const LEN_ETHER: u8 = 6;
}

#[derive(Debug, Clone)]
enum DhcpOption {
    Pad,
    End,
    VendorClassIdentifier(String),
    UserClassInformation(String),
    Unknown { code: u8, data: Vec<u8> },
}

#[derive(Debug)]
struct DhcpPacket {
    op: BootOp,
    htype: HardwareType,
    hlen: u8,
    hops: u8, // should be zero
    xid: u32,
    secs: u16,
    flags: u16,
    ciaddr: Ipv4Addr,
    yiaddr: Ipv4Addr,
    siaddr: Ipv4Addr,
    giaddr: Ipv4Addr,
    chaddr: [u8; 16],
    sname: [u8; 64],
    file: [u8; 128],
    options: Vec<DhcpOption>,
}

fn read_u8(cursor: &mut Cursor<&[u8]>) -> Result<u8> {
    let mut buf = [0u8; 1];
    cursor.read_exact(&mut buf)?;
    Ok(buf[0])
}

fn read_u16(cursor: &mut Cursor<&[u8]>) -> Result<u16> {
    let mut buf = [0u8; 2];
    cursor.read_exact(&mut buf)?;
    Ok(u16::from_be_bytes(buf))
}

fn read_u32(cursor: &mut Cursor<&[u8]>) -> Result<u32> {
    let mut buf = [0u8; 4];
    cursor.read_exact(&mut buf)?;
    Ok(u32::from_be_bytes(buf))
}

fn read_arr<const N: usize>(cursor: &mut Cursor<&[u8]>) -> Result<[u8; N]> {
    let mut buf = [0u8; N];
    cursor.read_exact(&mut buf)?;
    Ok(buf)
}

fn read_null_terminated_vec(cursor: &mut Cursor<&[u8]>) -> Result<Vec<u8>> {
    let mut buf = Vec::default();
    cursor.read_until(0, &mut buf)?;
    buf.pop();
    Ok(buf)
}

fn read_null_terminated_string(cursor: &mut Cursor<&[u8]>) -> Result<String> {
    let buf = read_null_terminated_vec(cursor)?;
    Ok(String::from_utf8(buf).unwrap())
}

fn read_len8_prefixed_vec(cursor: &mut Cursor<&[u8]>) -> Result<Vec<u8>> {
    let len = read_u8(cursor)?;
    let mut buf = vec![0u8; len as usize];
    cursor.read_exact(&mut buf)?;
    Ok(buf)
}

fn read_len8_prefixed_string(cursor: &mut Cursor<&[u8]>) -> Result<String> {
    let buf = read_len8_prefixed_vec(cursor)?;
    Ok(String::from_utf8(buf).unwrap())
}

fn read_ipv4(cursor: &mut Cursor<&[u8]>) -> Result<Ipv4Addr> {
    Ok(Ipv4Addr::from_octets(read_arr(cursor)?))
}

fn read_op(cursor: &mut Cursor<&[u8]>) -> Result<BootOp> {
    let v = read_u8(cursor)?;
    match v {
        BootOp::OP_REQUEST => Ok(BootOp::Request),
        BootOp::OP_REPLY => Ok(BootOp::Reply),
        _ => Err(std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            "invalid boot op",
        )),
    }
}

fn read_htype(cursor: &mut Cursor<&[u8]>) -> Result<HardwareType> {
    match read_u8(cursor)? {
        HardwareType::TYPE_ETHER => Ok(HardwareType::Ethernet),
        _ => Err(std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            "invalid hardware type",
        )),
    }
}

fn read_option(cursor: &mut Cursor<&[u8]>) -> Result<DhcpOption> {
    let code = read_u8(cursor)?;
    Ok(match code {
        OPTION_CODE_PAD => DhcpOption::Pad,
        OPTION_CODE_END => DhcpOption::End,
        OPTION_CODE_VENDOR_CLASS_IDENTIFIER => {
            DhcpOption::VendorClassIdentifier(read_len8_prefixed_string(cursor)?)
        }
        OPTION_CODE_USER_CLASS_INFORMATION => {
            DhcpOption::UserClassInformation(read_len8_prefixed_string(cursor)?)
        }
        _ => {
            let len = read_u8(cursor)?;
            let mut data = vec![0u8; usize::from(len)];
            cursor.read_exact(&mut data)?;
            DhcpOption::Unknown { code, data }
        }
    })
}

fn parse_packet(buf: &[u8]) -> Result<DhcpPacket> {
    let mut cursor = Cursor::new(buf);
    let mut packet = DhcpPacket {
        op: read_op(&mut cursor)?,
        htype: read_htype(&mut cursor)?,
        hlen: read_u8(&mut cursor)?,
        hops: read_u8(&mut cursor)?,
        xid: read_u32(&mut cursor)?,
        secs: read_u16(&mut cursor)?,
        flags: read_u16(&mut cursor)?,
        ciaddr: read_ipv4(&mut cursor)?,
        yiaddr: read_ipv4(&mut cursor)?,
        siaddr: read_ipv4(&mut cursor)?,
        giaddr: read_ipv4(&mut cursor)?,
        chaddr: read_arr(&mut cursor)?,
        sname: read_arr(&mut cursor)?,
        file: read_arr(&mut cursor)?,
        options: Default::default(),
    };

    let magic = read_arr::<4>(&mut cursor)?;
    assert_eq!(magic, MAGIC_COOKIE);

    while cursor.position() < buf.len() as u64 {
        let option = read_option(&mut cursor)?;
        packet.options.push(option);
    }

    Ok(packet)
}

fn write_buf(writer: &mut Vec<u8>, buf: &[u8]) -> Result<()> {
    writer.write_all(buf)
}

fn write_u8(writer: &mut Vec<u8>, v: u8) -> Result<()> {
    write_buf(writer, &[v])
}

fn write_u16(writer: &mut Vec<u8>, v: u16) -> Result<()> {
    let buf = u16::to_be_bytes(v);
    write_buf(writer, &buf)
}

fn write_u32(writer: &mut Vec<u8>, v: u32) -> Result<()> {
    let buf = u32::to_be_bytes(v);
    write_buf(writer, &buf)
}

fn write_ipv4(writer: &mut Vec<u8>, v: Ipv4Addr) -> Result<()> {
    write_buf(writer, &v.octets())
}

fn write_boot_packet(
    xid: u32,
    chaddr: [u8; 16],
    client_uuid: Option<Vec<u8>>,
    ipxe: bool,
) -> Result<Vec<u8>> {
    let mut writer = Vec::default();
    write_u8(&mut writer, BootOp::OP_REPLY)?;
    write_u8(&mut writer, HardwareType::TYPE_ETHER)?;
    write_u8(&mut writer, 6)?;
    write_u8(&mut writer, 0)?;
    write_u32(&mut writer, xid)?;
    write_u16(&mut writer, 0)?;
    write_u16(&mut writer, FLAG_BROADCAST)?;
    write_ipv4(&mut writer, Ipv4Addr::UNSPECIFIED)?; // ciaddr
    write_ipv4(&mut writer, Ipv4Addr::UNSPECIFIED)?; // yiaddr  
    write_ipv4(&mut writer, LOCAL_IPV4)?; // siaddr (TFTP server)
    write_ipv4(&mut writer, Ipv4Addr::UNSPECIFIED)?; // giaddr
    write_buf(&mut writer, &chaddr)?;
    write_buf(&mut writer, &[0u8; 64])?;
    write_buf(&mut writer, &[0u8; 128])?;
    write_buf(&mut writer, &MAGIC_COOKIE)?;

    // Option 53: DHCP Message Type (DHCPOFFER)
    write_u8(&mut writer, 53)?;
    write_u8(&mut writer, 1)?;
    write_u8(&mut writer, 2)?; // DHCPOFFER

    // Option 54: DHCP Server Identifier
    write_u8(&mut writer, 54)?;
    write_u8(&mut writer, 4)?;
    write_ipv4(&mut writer, LOCAL_IPV4)?; // Your server IP

    // Option 60: Vendor Class Identifier
    const PXE_CLIENT: &[u8] = b"PXEClient";
    write_u8(&mut writer, 60)?;
    write_u8(&mut writer, PXE_CLIENT.len() as u8)?;
    write_buf(&mut writer, PXE_CLIENT)?;

    // Option 97: Client Machine Identifier (UUID from client)
    if let Some(uuid) = client_uuid {
        write_u8(&mut writer, 97)?;
        write_u8(&mut writer, uuid.len() as u8)?;
        write_buf(&mut writer, &uuid)?;
    }

    // TFTP server name
    const SERVER_NAME: &[u8] = b"diogos-air";
    write_u8(&mut writer, 66)?;
    write_u8(&mut writer, SERVER_NAME.len() as u8)?;
    write_buf(&mut writer, SERVER_NAME)?;

    write_u8(&mut writer, 67)?;
    if !ipxe {
        write_u8(&mut writer, BOOT_FILE_NAME.len() as u8)?;
        write_buf(&mut writer, BOOT_FILE_NAME)?;
    } else {
        write_u8(&mut writer, BOOT_FILE_NAME_IPXE.len() as u8)?;
        write_buf(&mut writer, BOOT_FILE_NAME_IPXE)?;
    }

    // Option 255: End
    write_u8(&mut writer, 255)?;

    Ok(writer)
}

fn write_boot_ack(xid: u32, chaddr: [u8; 16], client_uuid: Option<Vec<u8>>) -> Result<Vec<u8>> {
    let mut writer = Vec::default();
    write_u8(&mut writer, BootOp::OP_REPLY)?;
    write_u8(&mut writer, HardwareType::TYPE_ETHER)?;
    write_u8(&mut writer, 6)?;
    write_u8(&mut writer, 0)?;
    write_u32(&mut writer, xid)?;
    write_u16(&mut writer, 0)?;
    write_u16(&mut writer, 0)?;
    write_ipv4(&mut writer, Ipv4Addr::UNSPECIFIED)?; // ciaddr
    write_ipv4(&mut writer, Ipv4Addr::UNSPECIFIED)?; // yiaddr  
    write_ipv4(&mut writer, Ipv4Addr::UNSPECIFIED)?; // siaddr (TFTP server)
    write_ipv4(&mut writer, Ipv4Addr::UNSPECIFIED)?; // giaddr
    write_buf(&mut writer, &chaddr)?;
    write_buf(&mut writer, &[0u8; 64])?;
    write_buf(&mut writer, &[0u8; 128])?;
    write_buf(&mut writer, &MAGIC_COOKIE)?;

    // Option 53: DHCP Message Type (DHCPOFFER)
    write_u8(&mut writer, 53)?;
    write_u8(&mut writer, 1)?;
    write_u8(&mut writer, 5)?; // DHCPACK

    // Option 54: DHCP Server Identifier
    write_u8(&mut writer, 54)?;
    write_u8(&mut writer, 4)?;
    write_ipv4(&mut writer, LOCAL_IPV4)?; // Your server IP

    // Option 60: Vendor Class Identifier
    const PXE_CLIENT: &[u8] = b"PXEClient";
    write_u8(&mut writer, 60)?;
    write_u8(&mut writer, PXE_CLIENT.len() as u8)?;
    write_buf(&mut writer, PXE_CLIENT)?;

    // Option 97: Client Machine Identifier (UUID from client)
    if let Some(uuid) = client_uuid {
        write_u8(&mut writer, 97)?;
        write_u8(&mut writer, uuid.len() as u8)?;
        write_buf(&mut writer, &uuid)?;
    }

    // TFTP server name
    const SERVER_NAME: &[u8] = b"diogos-air";
    write_u8(&mut writer, 66)?;
    write_u8(&mut writer, SERVER_NAME.len() as u8)?;
    write_buf(&mut writer, SERVER_NAME)?;

    // TFTP file name
    write_u8(&mut writer, 67)?;
    write_u8(&mut writer, BOOT_FILE_NAME.len() as u8)?;
    write_buf(&mut writer, BOOT_FILE_NAME)?;

    write_u8(&mut writer, 71)?;
    write_u8(&mut writer, 4)?;
    write_buf(&mut writer, &[0, 0, 0, 0])?;

    // Option 255: End
    write_u8(&mut writer, 255)?;

    Ok(writer)
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct InvalidTftpOp(u16);

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

impl std::error::Error for InvalidTftpOp {}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum TftpOp {
    ReadRequest,
    WriteRequest,
    Data,
    Ack,
    Error,
    Oack,
}

impl Into<u16> for TftpOp {
    fn into(self) -> u16 {
        match self {
            TftpOp::ReadRequest => 1,
            TftpOp::WriteRequest => 2,
            TftpOp::Data => 3,
            TftpOp::Ack => 4,
            TftpOp::Error => 5,
            TftpOp::Oack => 6,
        }
    }
}

impl TryFrom<u16> for TftpOp {
    type Error = InvalidTftpOp;

    fn try_from(value: u16) -> std::result::Result<Self, InvalidTftpOp> {
        match value {
            1 => Ok(Self::ReadRequest),
            2 => Ok(Self::WriteRequest),
            3 => Ok(Self::Data),
            4 => Ok(Self::Ack),
            5 => Ok(Self::Error),
            6 => Ok(Self::Oack),
            unknown => Err(InvalidTftpOp(unknown)),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum TftpMode {
    NetAscii,
    Octet,
    Mail,
}

#[derive(Debug)]
struct TftpRequestPacket {
    filename: String,
    mode: String,
    tsize: Option<u64>,
    blksize: Option<u64>,
}

#[derive(Debug)]
struct TftpDataPacket {
    block: u16,
    data: Vec<u8>,
}

#[derive(Debug)]
struct TftpAckPacket {
    block: u16,
}

#[derive(Debug)]
struct TftpErrorPacket {
    code: u16,
    message: String,
}

fn tftp_request_packet_parse(cursor: &mut Cursor<&[u8]>) -> Result<TftpRequestPacket> {
    let filename = read_null_terminated_string(cursor)?;
    let mode = read_null_terminated_string(cursor)?;
    let mut tsize = None;
    let mut blksize = None;
    while let Ok(opt_name) = read_null_terminated_string(cursor) {
        if opt_name.is_empty() {
            break;
        }
        let opt_data = read_null_terminated_string(cursor)?;
        match opt_name.as_str() {
            "tsize" => tsize = Some(opt_data.parse::<u64>().unwrap()),
            "blksize" => blksize = Some(opt_data.parse::<u64>().unwrap()),
            _ => eprintln!("unknown tftp request option '{opt_name}'"),
        }
    }

    Ok(TftpRequestPacket {
        filename,
        mode,
        tsize,
        blksize,
    })
}

fn tftp_data_packet_write(writer: &mut Vec<u8>, block: u16, data: Vec<u8>) -> Result<()> {
    write_u16(writer, TftpOp::Data.into())?;
    write_u16(writer, block)?;
    write_buf(writer, &data)?;
    Ok(())
}

fn tftp_oack_packet_write(
    writer: &mut Vec<u8>,
    tsize: Option<u64>,
    blksize: Option<u64>,
) -> Result<()> {
    write_u16(writer, TftpOp::Oack.into())?;

    // Only include options that were requested by the client
    if let Some(blksize_val) = blksize {
        write_buf(writer, b"blksize")?;
        write_u8(writer, 0)?; // null terminator
        let blksize_str = blksize_val.to_string();
        write_buf(writer, blksize_str.as_bytes())?;
        write_u8(writer, 0)?; // null terminator
    }

    if let Some(tsize_val) = tsize {
        write_buf(writer, b"tsize")?;
        write_u8(writer, 0)?; // null terminator
        let tsize_str = tsize_val.to_string();
        write_buf(writer, tsize_str.as_bytes())?;
        write_u8(writer, 0)?; // null terminator
    }

    Ok(())
}

#[derive(Debug)]
enum TftpPacket {
    Request(TftpRequestPacket),
    Data(TftpDataPacket),
    Ack(TftpAckPacket),
    Error(TftpErrorPacket),
}

fn tftp_packet_parse(cursor: &mut Cursor<&[u8]>) -> Result<TftpPacket> {
    let op = TftpOp::try_from(read_u16(cursor)?).unwrap();
    match op {
        TftpOp::ReadRequest | TftpOp::WriteRequest => {
            let filename = read_null_terminated_string(cursor)?;
            let mode = read_null_terminated_string(cursor)?;
            let mut tsize = None;
            let mut blksize = None;

            while let Ok(opt_name) = read_null_terminated_string(cursor) {
                if opt_name.is_empty() {
                    break;
                }
                let opt_data = read_null_terminated_string(cursor)?;
                match opt_name.as_str() {
                    "tsize" => tsize = Some(opt_data.parse::<u64>().unwrap()),
                    "blksize" => blksize = Some(opt_data.parse::<u64>().unwrap()),
                    _ => eprintln!("unknown tftp request option '{opt_name}'"),
                }
            }

            Ok(TftpPacket::Request(TftpRequestPacket {
                filename,
                mode,
                tsize,
                blksize,
            }))
        }
        TftpOp::Data => {
            let block = read_u16(cursor)?;
            let mut data = Vec::new();
            cursor.read_to_end(&mut data)?;
            Ok(TftpPacket::Data(TftpDataPacket { block, data }))
        }
        TftpOp::Ack => {
            let block = read_u16(cursor)?;
            Ok(TftpPacket::Ack(TftpAckPacket { block }))
        }
        TftpOp::Error => {
            let code = read_u16(cursor)?;
            let message = read_null_terminated_string(cursor)?;
            Ok(TftpPacket::Error(TftpErrorPacket { code, message }))
        }
        TftpOp::Oack => {
            // OACK parsing not implemented for now
            Err(std::io::Error::new(
                std::io::ErrorKind::Unsupported,
                "OACK parsing not implemented",
            ))
        }
    }
}

fn main() {
    let socket67 = UdpSocket::bind("0.0.0.0:67").unwrap();
    socket67.set_broadcast(true).unwrap();
    socket67.set_nonblocking(true).unwrap();

    let socket69 = UdpSocket::bind("0.0.0.0:69").unwrap();
    socket69.set_broadcast(false).unwrap();
    socket69.set_nonblocking(true).unwrap();

    let socket4011 = UdpSocket::bind("0.0.0.0:4011").unwrap();
    socket4011.set_broadcast(true).unwrap();
    socket4011.set_nonblocking(true).unwrap();

    let mut last_blksize = 512u64;
    let mut current_file = String::new();

    loop {
        let mut buf = [0u8; 1500];

        // Try port 67 first
        if let Ok((n, addr)) = socket67.recv_from(&mut buf) {
            println!("Received {} bytes from {} on port 67", n, addr);
            handle_packet(&buf[..n], &socket67);
        } else if let Ok((n, addr)) = socket4011.recv_from(&mut buf) {
            println!("Received {} bytes from {} on port 4011", n, addr);
            handle_packet_4011(&buf[..n], &socket4011, addr);
        } else if let Ok((n, addr)) = socket69.recv_from(&mut buf) {
            let mut cursor = Cursor::new(&buf[..n]);

            let packet = tftp_packet_parse(&mut cursor).unwrap();
            println!("Received TFTP request from {addr}: {packet:#?}");

            let mut response = Vec::default();
            match packet {
                TftpPacket::Request(tftp_request_packet) => {
                    println!(
                        "Request options: tsize={:?}, blksize={:?}",
                        tftp_request_packet.tsize, tftp_request_packet.blksize
                    );

                    let filepath = format!("tftp/{}", tftp_request_packet.filename);
                    current_file = filepath.clone();
                    let meta = std::fs::metadata(&filepath).unwrap();
                    let actual_file_size = meta.len();

                    // Only send OACK if client sent options
                    if tftp_request_packet.tsize.is_some() || tftp_request_packet.blksize.is_some()
                    {
                        if let Some(blksize) = tftp_request_packet.blksize {
                            last_blksize = blksize;
                        }

                        let tsize_response = if tftp_request_packet.tsize.is_some() {
                            Some(actual_file_size)
                        } else {
                            None
                        };

                        tftp_oack_packet_write(
                            &mut response,
                            tsize_response,
                            tftp_request_packet.blksize,
                        )
                        .unwrap();
                    } else {
                        // No options, send first data block directly
                        let contents = std::fs::read(&filepath).unwrap();
                        let block_size = 512;
                        let first_block = if contents.len() > block_size {
                            contents[..block_size].to_vec()
                        } else {
                            contents
                        };

                        tftp_data_packet_write(&mut response, 1, first_block).unwrap();
                    }
                }
                TftpPacket::Data(tftp_data_packet) => {
                    println!("Received DATA packet: block {}", tftp_data_packet.block);
                }
                TftpPacket::Ack(tftp_ack_packet) => {
                    println!("Received ACK packet: block {}", tftp_ack_packet.block);

                    let contents = std::fs::read(&current_file).unwrap();
                    let next_block = tftp_ack_packet.block + 1;
                    let start_offset = (next_block - 1) as u64 * last_blksize;
                    let end_offset = next_block as u64 * last_blksize;
                    let prev_start_offset = (next_block.saturating_sub(2)) as u64 * last_blksize;
                    let prev_remain = contents.len() - prev_start_offset as usize;
                    if prev_remain as u64 >= last_blksize || tftp_ack_packet.block == 0 {
                        let end = std::cmp::min(end_offset as usize, contents.len());
                        let block_data = contents[start_offset as usize..end].to_vec();
                        println!("sending tftp data packet with {} bytes", block_data.len());
                        tftp_data_packet_write(&mut response, next_block, block_data).unwrap();
                    }
                }
                TftpPacket::Error(tftp_error_packet) => {
                    println!(
                        "Received ERROR packet: code {}, message: {}",
                        tftp_error_packet.code, tftp_error_packet.message
                    );
                }
            }
            //
            // let filepath = format!("tftp/{}", request.filename);
            // let meta = std::fs::metadata(&filepath).unwrap();
            // let contents = std::fs::read(&filepath).unwrap();
            // let mut response = Vec::default();
            if !response.is_empty() {
                socket69.send_to(&response, addr).unwrap();
            }
        } else {
            std::thread::sleep(std::time::Duration::from_millis(10));
        }
    }
}

fn handle_packet(buf: &[u8], socket: &UdpSocket) {
    match parse_packet(buf) {
        Ok(packet) => {
            println!("Parsed DHCP packet: XID={:08x}", packet.xid);

            // Check if it's a PXE client and extract client UUID
            let mut is_pxe = false;
            let mut client_uuid = None;
            let mut is_ipxe = false;

            for option in &packet.options {
                match option {
                    DhcpOption::VendorClassIdentifier(vendor_class) => {
                        println!("Vendor class: {}", vendor_class);
                        if vendor_class.contains("PXEClient") {
                            is_pxe = true;
                        }
                    }
                    DhcpOption::UserClassInformation(user_class) => {
                        println!("User class: {}", user_class);
                        is_ipxe = true;
                    }
                    DhcpOption::Unknown { code: 97, data } => {
                        println!("Found client machine identifier");
                        client_uuid = Some(data.clone());
                    }
                    _ => {}
                }
            }

            if is_pxe {
                println!("Responding to PXE client with DHCPOFFER");
                let response =
                    write_boot_packet(packet.xid, packet.chaddr, client_uuid, is_ipxe).unwrap();
                socket
                    .send_to(&response, SocketAddrV4::new(Ipv4Addr::BROADCAST, 68))
                    .unwrap();
            } else {
                println!("Not a PXE client, ignoring");
            }
        }
        Err(e) => {
            println!("Failed to parse packet: {}", e);
        }
    }
}

fn handle_packet_4011(buf: &[u8], socket: &UdpSocket, sender_addr: SocketAddr) {
    match parse_packet(buf) {
        Ok(packet) => {
            println!("Parsed DHCP packet on 4011: XID={:08x}", packet.xid);

            // Extract client UUID
            let mut client_uuid = None;
            for option in &packet.options {
                if let DhcpOption::Unknown { code: 97, data } = option {
                    client_uuid = Some(data.clone());
                    break;
                }
            }

            println!("Responding with DHCPACK");
            let response = write_boot_ack(packet.xid, packet.chaddr, client_uuid).unwrap();
            socket.send_to(&response, sender_addr).unwrap();
        }
        Err(e) => {
            println!("Failed to parse packet on 4011: {}", e);
        }
    }
}

const DHCP_PACKET_PAYLOAD: &'static [u8] = &[
    0x1, 0x1, 0x6, 0x0, 0xf1, 0x25, 0x7c, 0x21, 0x0, 0x0, 0x80, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
    0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x2b, 0x67, 0x3f, 0xda, 0x70, 0x0, 0x0,
    0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
    0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
    0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
    0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
    0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
    0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
    0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
    0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
    0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
    0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
    0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x63, 0x82, 0x53, 0x63, 0x35, 0x1, 0x1, 0x39,
    0x2, 0x5, 0xc0, 0x37, 0x23, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0xc, 0xd, 0xf, 0x11, 0x12, 0x16,
    0x17, 0x1c, 0x28, 0x29, 0x2a, 0x2b, 0x32, 0x33, 0x36, 0x3a, 0x3b, 0x3c, 0x42, 0x43, 0x61, 0x80,
    0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x61, 0x11, 0x0, 0xcc, 0xfc, 0x32, 0x1b, 0xce, 0x2a,
    0xb2, 0x11, 0xa8, 0x5c, 0xb1, 0xac, 0x38, 0x38, 0x10, 0xf, 0x5e, 0x3, 0x1, 0x3, 0x10, 0x5d,
    0x2, 0x0, 0x7, 0x3c, 0x20, 0x50, 0x58, 0x45, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x3a, 0x41,
    0x72, 0x63, 0x68, 0x3a, 0x30, 0x30, 0x30, 0x30, 0x37, 0x3a, 0x55, 0x4e, 0x44, 0x49, 0x3a, 0x30,
    0x30, 0x33, 0x30, 0x31, 0x36, 0xff,
];