mozim 0.3.2

DHCP Client Library
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
// SPDX-License-Identifier: Apache-2.0

use std::net::Ipv4Addr;

use super::{
    option::DhcpV4Options,
    socket::{CLIENT_PORT, SERVER_PORT},
};
use crate::{
    mac::BROADCAST_MAC_ADDRESS, Buffer, BufferMut, DhcpError, DhcpV4Config,
    DhcpV4Lease, DhcpV4Option, DhcpV4OptionCode, ErrorContext, ErrorKind,
};

const DEFAULT_TTL: u8 = 128;

#[derive(Debug, PartialEq, Eq, Clone, Copy, PartialOrd, Ord, Hash, Default)]
#[repr(u8)]
#[non_exhaustive]
pub enum DhcpV4MessageType {
    #[default]
    Discovery = 1,
    Offer = 2,
    Request = 3,
    Decline = 4,
    Ack = 5,
    Nack = 6,
    Release = 7,
    Inform = 8,
}

impl std::fmt::Display for DhcpV4MessageType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Discovery => write!(f, "DISCOVERY"),
            Self::Offer => write!(f, "OFFER"),
            Self::Request => write!(f, "REQUEST"),
            Self::Ack => write!(f, "ACK"),
            Self::Nack => write!(f, "NACK"),
            Self::Decline => write!(f, "DECLINE"),
            Self::Release => write!(f, "RELEASE"),
            Self::Inform => write!(f, "INFORM"),
        }
    }
}

impl std::convert::TryFrom<u8> for DhcpV4MessageType {
    type Error = DhcpError;

    fn try_from(d: u8) -> Result<Self, DhcpError> {
        match d {
            d if d == Self::Discovery as u8 => Ok(Self::Discovery),
            d if d == Self::Offer as u8 => Ok(Self::Offer),
            d if d == Self::Request as u8 => Ok(Self::Request),
            d if d == Self::Decline as u8 => Ok(Self::Decline),
            d if d == Self::Ack as u8 => Ok(Self::Ack),
            d if d == Self::Nack as u8 => Ok(Self::Nack),
            d if d == Self::Release as u8 => Ok(Self::Release),
            d if d == Self::Inform as u8 => Ok(Self::Inform),
            _ => Err(DhcpError::new(
                ErrorKind::NotSupported,
                format!("DHCPv4 message type {d} is not supported"),
            )),
        }
    }
}

const MAX_CHADDR_LEN: usize = 16;
const MAX_SNAME_LEN: usize = 64;
const MAX_FILE_LEN: usize = 128;

#[derive(Debug)]
pub(crate) struct DhcpV4Message {
    /// Message op code / message type. 1 = BOOTREQUEST, 2 = BOOTREPLY
    pub(crate) op: u8,
    /// Hardware address type
    pub(crate) htype: u8,
    /// Hardware address length
    pub(crate) hlen: u8,
    /// Client sets to zero, optionally used by relay agents when booting via a
    /// relay agent.
    pub(crate) hops: u8,
    /// Transaction ID
    pub(crate) xid: u32,
    /// Filled in by client, seconds elapsed since client began address
    /// acquisition or renewal process.
    pub(crate) secs: u16,
    pub(crate) flags: u16,
    /// Client IP address; only filled in if client is in BOUND, RENEW or
    /// REBINDING state and can respond to ARP requests.
    pub(crate) ciaddr: Ipv4Addr,
    /// 'your' (client) IP address.
    pub(crate) yiaddr: Ipv4Addr,
    /// IP address of next server to use in bootstrap; returned in DHCPOFFER,
    /// DHCPACK by server.
    pub(crate) siaddr: Ipv4Addr,
    /// Relay agent IP address, used in booting via a relay agent.
    pub(crate) giaddr: Ipv4Addr,
    /// Client hardware address.
    pub(crate) chaddr: [u8; MAX_CHADDR_LEN],
    /// Optional server host name, null terminated string.
    pub(crate) sname: String,
    /// Boot file name, null terminated string.
    pub(crate) file: String,
    /// DHCP options
    pub(crate) options: DhcpV4Options,
    // Not defined in RFC, crate private use only
    pub(crate) srv_mac: Vec<u8>,
}

const BOOTREQUEST: u8 = 1;
const ARP_HW_TYPE_ETHERNET: u8 = 1;
const HW_ADDR_LEN_ETHERNET: u8 = 6;
const DHCPV4_MAGIC_COOKIE: [u8; 4] = [99u8, 130, 83, 99];

impl Default for DhcpV4Message {
    fn default() -> Self {
        Self {
            op: BOOTREQUEST,
            htype: ARP_HW_TYPE_ETHERNET,
            hlen: HW_ADDR_LEN_ETHERNET,
            hops: 0,
            xid: 0,
            secs: 0,
            flags: 0,
            ciaddr: Ipv4Addr::UNSPECIFIED,
            yiaddr: Ipv4Addr::UNSPECIFIED,
            siaddr: Ipv4Addr::UNSPECIFIED,
            giaddr: Ipv4Addr::UNSPECIFIED,
            chaddr: [0u8; MAX_CHADDR_LEN],
            sname: String::new(),
            file: String::new(),
            options: DhcpV4Options::default(),
            srv_mac: Vec::new(),
        }
    }
}

impl DhcpV4Message {
    // The header is 236 bytes, plus 3 bytes for the mandatory option
    // `DHCP Message Type(53)`
    const MIN_LEN: usize = 239;

    /// Parse from raw DHCP message with UDP and lower layer headers purged.
    pub(crate) fn parse(raw: &[u8]) -> Result<Self, DhcpError> {
        if raw.len() < Self::MIN_LEN {
            return Err(DhcpError::new(
                ErrorKind::InvalidDhcpMessage,
                format!(
                    "RAW data length({}) is less than minimum DHCP
                    message size{}",
                    raw.len(),
                    Self::MIN_LEN
                ),
            ));
        }
        let mut buf = Buffer::new(raw);

        let mut ret = Self {
            srv_mac: Vec::new(),
            op: buf.get_u8().context("Invalid DHCPv4 header option 'op'")?,
            htype: buf
                .get_u8()
                .context("Invalid DHCPv4 header option 'htype'")?,
            hlen: buf
                .get_u8()
                .context("Invalid DHCPv4 header option 'hlen'")?,
            hops: buf
                .get_u8()
                .context("Invalid DHCPv4 header option 'hops'")?,
            xid: buf
                .get_u32_be()
                .context("Invalid DHCPv4 header option 'xid'")?,
            secs: buf
                .get_u16_be()
                .context("Invalid DHCPv4 header option 'secs'")?,
            flags: buf
                .get_u16_be()
                .context("Invalid DHCPv4 header option 'flags'")?,
            ciaddr: buf
                .get_ipv4()
                .context("Invalid DHCPv4 header option 'ciaddr'")?,
            yiaddr: buf
                .get_ipv4()
                .context("Invalid DHCPv4 header option 'yiaddr'")?,
            siaddr: buf
                .get_ipv4()
                .context("Invalid DHCPv4 header option 'siaddr'")?,
            giaddr: buf
                .get_ipv4()
                .context("Invalid DHCPv4 header option 'giaddr'")?,
            chaddr: {
                let mut chaddr = [0u8; MAX_CHADDR_LEN];
                chaddr.copy_from_slice(
                    buf.get_bytes(MAX_CHADDR_LEN)
                        .context("Invalid DHCPv4 header option 'chaddr'")?,
                );
                chaddr
            },
            sname: buf
                .get_string_with_null(MAX_SNAME_LEN)
                .context("Invalid DHCPv4 header option 'sname' ")?,
            file: buf
                .get_string_with_null(MAX_FILE_LEN)
                .context("Invalid DHCPv4 header option 'file'")?,
            options: DhcpV4Options::new(),
        };

        let magic_cookie =
            buf.get_bytes(4).context("Invalid DHCP magic cookie")?;
        if magic_cookie != DHCPV4_MAGIC_COOKIE {
            return Err(DhcpError::new(
                ErrorKind::InvalidDhcpMessage,
                format!(
                    "DHCPv4 magic cookie not match, expected {:?}, got {:?}",
                    DHCPV4_MAGIC_COOKIE, magic_cookie
                ),
            ));
        }
        ret.options = DhcpV4Options::parse(buf.get_remains())?;

        log::trace!("Parsed DHCP message {ret:?}");
        Ok(ret)
    }

    pub(crate) fn parse_eth_packet(buf: &[u8]) -> Result<Self, DhcpError> {
        let packet = match etherparse::SlicedPacket::from_ethernet(buf) {
            Err(error) => {
                return Err(DhcpError::new(
                    ErrorKind::InvalidDhcpMessage,
                    format!(
                        "Failed to parse ethernet package to DHCP message: \
                         {error}"
                    ),
                ));
            }
            Ok(v) => v,
        };
        if let Some(etherparse::TransportSlice::Udp(udp_packet)) =
            packet.transport
        {
            let mut ret = Self::parse(udp_packet.payload())?;
            // TODO(Gris Ge): Do we really need this?
            if let Some(eth_header) = packet
                .link
                .and_then(|l| l.to_header())
                .and_then(|h| h.ethernet2())
            {
                ret.srv_mac = eth_header.source.to_vec();
            }
            Ok(ret)
        } else {
            Err(DhcpError::new(
                ErrorKind::InvalidDhcpMessage,
                "Failed to parse ethernet package to DHCP message: Not UDP \
                 payload"
                    .to_string(),
            ))
        }
    }

    pub(crate) fn emit(&self, buf: &mut BufferMut) {
        buf.write_u8(self.op);
        buf.write_u8(self.htype);
        buf.write_u8(self.hlen);
        buf.write_u8(self.hops);
        buf.write_u32_be(self.xid);
        buf.write_u16_be(self.secs);
        buf.write_u16_be(self.flags);
        buf.write_ipv4(self.ciaddr);
        buf.write_ipv4(self.yiaddr);
        buf.write_ipv4(self.siaddr);
        buf.write_ipv4(self.giaddr);
        buf.write_bytes(&self.chaddr);
        buf.write_string_with_null(&self.sname, MAX_SNAME_LEN);
        buf.write_string_with_null(&self.file, MAX_FILE_LEN);
        buf.write_bytes(&DHCPV4_MAGIC_COOKIE);
        self.options.emit(buf);
    }

    pub(crate) fn to_eth_packet_broadcast(&self) -> Result<Vec<u8>, DhcpError> {
        log::trace!("Generating ethernet broadcast for DHCP message {self:?}");
        let mut buf = BufferMut::new();
        self.emit(&mut buf);
        log::trace!("DHCP packet generated {:?}", buf.data);

        gen_eth_packet(
            &self.chaddr,
            &BROADCAST_MAC_ADDRESS,
            &Ipv4Addr::new(0, 0, 0, 0),
            &Ipv4Addr::new(255, 255, 255, 255),
            CLIENT_PORT,
            SERVER_PORT,
            &buf.data,
        )
    }

    pub(crate) fn to_proxy_eth_packet_unicast(
        &self,
        lease: &DhcpV4Lease,
    ) -> Result<Vec<u8>, DhcpError> {
        let dhcp_msg_buff = self.to_dhcp_packet()?;
        gen_eth_packet(
            &self.chaddr,
            &lease.srv_mac,
            &lease.yiaddr,
            &lease.siaddr,
            CLIENT_PORT,
            SERVER_PORT,
            &dhcp_msg_buff,
        )
    }

    pub(crate) fn to_dhcp_packet(&self) -> Result<Vec<u8>, DhcpError> {
        let mut buf = BufferMut::new();
        self.emit(&mut buf);
        Ok(buf.data)
    }

    fn new(xid: u32, config: &DhcpV4Config) -> Self {
        let mut ret = Self {
            xid,
            ..Default::default()
        };
        ret.chaddr[..config.src_mac.len()].copy_from_slice(&config.src_mac);
        if !config.host_name.is_empty() {
            ret.options
                .insert(DhcpV4Option::HostName(config.host_name.clone()));
        }
        ret.options
            .insert(DhcpV4Option::ClientIdentifier(config.client_id.to_vec()));
        ret
    }

    pub(crate) fn new_discovery(xid: u32, config: &DhcpV4Config) -> Self {
        let mut ret = Self::new(xid, config);
        ret.options
            .insert(DhcpV4Option::MessageType(DhcpV4MessageType::Discovery));
        ret.options.insert(DhcpV4Option::ParameterRequestList(
            config.request_opts.to_vec(),
        ));
        ret
    }

    pub(crate) fn new_request(
        xid: u32,
        config: &DhcpV4Config,
        lease: &DhcpV4Lease,
    ) -> Self {
        let mut ret = Self::new(xid, config);
        ret.options
            .insert(DhcpV4Option::MessageType(DhcpV4MessageType::Request));
        ret.options
            .insert(DhcpV4Option::ServerIdentifier(lease.srv_id));
        if lease.srv_id != Ipv4Addr::UNSPECIFIED {
            ret.options
                .insert(DhcpV4Option::ServerIdentifier(lease.srv_id));
        } else {
            ret.options
                .insert(DhcpV4Option::ServerIdentifier(lease.siaddr));
        }
        ret.options
            .insert(DhcpV4Option::RequestedIpAddress(lease.yiaddr));
        ret.options.insert(DhcpV4Option::ParameterRequestList(
            config.request_opts.to_vec(),
        ));
        ret
    }

    pub(crate) fn new_renew(
        xid: u32,
        config: &DhcpV4Config,
        lease: &DhcpV4Lease,
    ) -> Self {
        let mut ret = Self::new_request(xid, config, lease);
        ret.ciaddr = lease.yiaddr;
        ret
    }

    pub(crate) fn new_rebind(
        xid: u32,
        config: &DhcpV4Config,
        lease: &DhcpV4Lease,
    ) -> Self {
        Self::new_renew(xid, config, lease)
    }

    pub(crate) fn new_release(
        xid: u32,
        config: &DhcpV4Config,
        lease: &DhcpV4Lease,
    ) -> Self {
        let mut ret = Self::new_request(xid, config, lease);
        ret.options
            .insert(DhcpV4Option::MessageType(DhcpV4MessageType::Release));
        ret
    }

    pub(crate) fn message_type(&self) -> Option<DhcpV4MessageType> {
        self.options
            .get(DhcpV4OptionCode::MessageType)
            .and_then(|opt| {
                if let DhcpV4Option::MessageType(t) = opt {
                    Some(*t)
                } else {
                    None
                }
            })
    }

    pub(crate) fn lease(&self) -> Option<DhcpV4Lease> {
        match DhcpV4Lease::new_from_msg(self) {
            Ok(l) => Some(l),
            Err(e) => {
                log::debug!("{e}");
                None
            }
        }
    }
}

fn gen_eth_packet(
    src_mac: &[u8],
    dst_mac: &[u8],
    src_ip: &Ipv4Addr,
    dst_ip: &Ipv4Addr,
    src_port: u16,
    dst_port: u16,
    payload: &[u8],
) -> Result<Vec<u8>, DhcpError> {
    const ETH_MAC_LEN: usize = HW_ADDR_LEN_ETHERNET as usize;
    let mut src_mac_raw = [0u8; ETH_MAC_LEN];
    let mut dst_mac_raw = [0u8; ETH_MAC_LEN];

    if src_mac.len() < ETH_MAC_LEN {
        src_mac_raw[..src_mac.len()].copy_from_slice(src_mac)
    } else {
        src_mac_raw.copy_from_slice(&src_mac[..ETH_MAC_LEN])
    }

    if dst_mac.len() < ETH_MAC_LEN {
        dst_mac_raw[..dst_mac.len()].copy_from_slice(dst_mac)
    } else {
        dst_mac_raw.copy_from_slice(&dst_mac[..ETH_MAC_LEN])
    }

    let builder =
        etherparse::PacketBuilder::ethernet2(src_mac_raw, dst_mac_raw)
            .ipv4(src_ip.octets(), dst_ip.octets(), DEFAULT_TTL)
            .udp(src_port, dst_port);

    let mut packet = Vec::<u8>::with_capacity(builder.size(payload.len()));

    builder.write(&mut packet, payload).map_err(|e| {
        DhcpError::new(
            ErrorKind::Bug,
            format!("Failed to generate ethernet packet: {e}"),
        )
    })?;

    Ok(packet)
}