toe-beans 0.10.0

DHCP library, client, and server
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
use super::config::*;
use super::leases::*;
use crate::v4::error::Result;
use crate::v4::message::*;
use log::{debug, error, info, warn};
use std::net::Ipv4Addr;
use std::net::SocketAddrV4;

/// Ties together a Config, Socket, and Leases in order to handle incoming Client Messages,
/// and construct server-specific response Messages.
///
/// Used by the server binary and integration tests.
///
/// Requires the `v4_server` feature, which is enabled by default.
#[derive(Debug)]
pub struct Server {
    /// A UdpSocket that understands Deliverables to communicate with the Client
    pub socket: Socket,
    /// Direct access to the ipv4 address passed to the `UdpSocket`.
    ///
    /// A server with multiple network addresses may use any of its addresses.
    pub ip: Ipv4Addr,
    /// Configuration read from toe-beans.toml
    pub config: Config,
    /// Manages the leasing logic of a range of ip addresses
    pub leases: Leases,
}

impl Server {
    /// Setup everything necessary for a Server to listen for incoming Messages.
    ///
    /// This fn is relatively "slow" and may panic, but that is okay
    /// because it is called before the `listen` or `listen_once` fns.
    pub fn new(config: Config) -> Self {
        let socket = Socket::new(config.listen_address, config.interface.as_ref());
        let ip = config.server_address.unwrap_or_else(|| socket.get_ip());
        let leases = Leases::new(&config);

        if config.rapid_commit {
            debug!("Rapid commit is enabled on server");
        }

        Self {
            socket,
            ip,
            config,
            leases,
        }
    }

    /// A server will send its response to different locations in different scenarios.
    fn reply(&self, response: Message, port: u16) {
        let reply_result = if !response.giaddr.is_unspecified() {
            // received request from relay agent so send response to relay agent.
            self.socket
                .unicast(&response, SocketAddrV4::new(response.giaddr, port))
        } else {
            self.socket.broadcast(&response, port)
        };

        match reply_result {
            Ok(_) => {}
            Err(error) => {
                error!("{error}");
            }
        };
    }

    /// Will wait for one Message on the UdpSocket and send a response based on it.
    ///
    /// To handle more than one Message, use `listen`.
    pub fn listen_once(&mut self) {
        let (decoded, src) = match self.socket.receive::<Message>() {
            Ok(values) => values,
            Err(error) => {
                error!("{error}");
                return;
            }
        };

        let message_type = match decoded.find_option(53) {
            Some(MessageOptions::MessageType(message_type)) => message_type,
            _ => {
                error!("Request does not have option 53");
                return;
            }
        };

        let response = match message_type {
            MessageTypes::Discover => 'discover: {
                debug!("Received Discover message");
                if self.config.rapid_commit {
                    match decoded.find_option(80) {
                        Some(MessageOptions::RapidCommit) => {
                            debug!(
                                "Discover message has rapid commit option. Will send Ack instead of Offer"
                            );
                            let mac_address = decoded.get_mac_address();

                            let ip = match self.leases.ack(mac_address) {
                                Ok(ip) => ip,
                                Err(error) => {
                                    error!("{}", error);
                                    return;
                                }
                            };
                            let mut message = self.ack(decoded, ip);
                            message.add_option(MessageOptions::RapidCommit);
                            break 'discover message;
                        }
                        _ => {
                            // Discover message did not send a rapid commit option or it wasnt valid. Will send Offer
                        }
                    };
                }

                match self.offer(decoded) {
                    Ok(message) => message,
                    Err(error) => {
                        error!("{}", error);
                        return;
                    }
                }
            }
            MessageTypes::Request => 'request: {
                debug!("Received Request message");
                let mac_address = decoded.get_mac_address();

                // "If the DHCPREQUEST message contains a 'server identifier' option, the message is in response to a DHCPOFFER message."
                // "Otherwise, the message is a request to verify or extend an existing lease."
                match decoded.find_option(54) {
                    Some(MessageOptions::ServerIdentifier(address_option)) => {
                        let server_identifier = address_option.inner();
                        if server_identifier != self.ip {
                            debug!(
                                "Ignoring client broadcast of DHCP Request for {} which is not this server ({}).",
                                server_identifier, self.ip
                            );

                            match self.leases.release(mac_address) {
                                Ok(_) => {
                                    debug!("Removed IP address previously offered to this client")
                                }
                                Err(error) => error!("{}", error),
                            }

                            return;
                        }

                        debug!("client has selected this server for a lease");
                        let ip = match self.leases.ack(mac_address) {
                            Ok(ip) => ip,
                            Err(error) => {
                                error!("{}", error);
                                return;
                            }
                        };
                        self.ack(decoded, ip)
                    }
                    _ => {
                        if decoded.ciaddr.is_unspecified() {
                            // no server identifier, and no ciaddr = init-reboot (verify)
                            debug!("client is attempting to verify lease");

                            let ip = match decoded.find_option(50) {
                                Some(MessageOptions::RequestedIp(address_option)) => {
                                    address_option.inner()
                                }
                                _ => {
                                    // If a server receives a DHCPREQUEST message with an invalid 'requested IP address',
                                    // the server SHOULD respond to the client with a DHCPNAK message
                                    break 'request self.nak(decoded, "Request does not have required option 50 (requested ip address)".to_string());
                                }
                            };

                            match self.leases.verify_lease(mac_address, &ip) {
                                Ok(_) => self.ack(decoded, ip),
                                Err(error) => {
                                    if error == "No IP address lease found with that owner" {
                                        // If the DHCP server has no record of this client, then it MUST remain silent,
                                        // This is necessary for peaceful coexistence of non-communicating DHCP servers on the same wire.
                                        debug!("{}. Not sending response", error);
                                        return;
                                    } else {
                                        // Client's notion of ip address is wrong or lease expired
                                        debug!("Lease not verified: {}", error);
                                        self.nak(decoded, error.to_string())
                                    }
                                }
                            }
                        } else {
                            // no server identifier, and a ciaddr = renew/rebind (extend)
                            debug!("client is attempting to renew/rebind lease");
                            match self.leases.extend(mac_address) {
                                Ok(_) => {
                                    // TODO The server SHOULD return T1 and T2,
                                    // and their values SHOULD be adjusted from their original values
                                    // to take account of the time remaining on the lease.
                                    let ip = decoded.ciaddr;
                                    self.ack(decoded, ip)
                                }
                                Err(error) => {
                                    debug!("Lease not extended: {}", error);
                                    self.nak(decoded, error.to_string())
                                }
                            }
                        }
                    }
                }
            }
            MessageTypes::Release => {
                debug!("Received Release message");
                if let Err(error) = self.leases.release(decoded.get_mac_address()) {
                    error!("{}", error);
                }
                return;
            }
            MessageTypes::Decline => {
                debug!("Received Decline message");

                // RFC 2131 says to mark the network address as not available,
                // but I'm concerned that could be a vector for easy ip address exhaustion.
                // For now, I'll release the address as there is no sense in keeping it acked.
                if let Err(error) = self.leases.release(decoded.get_mac_address()) {
                    error!("{}", error);
                }
                return;
            }
            MessageTypes::Inform => {
                debug!("Received Inform message");
                self.ack_inform(decoded)
            }
            MessageTypes::LeaseQuery
            | MessageTypes::BulkLeaseQuery
            | MessageTypes::ActiveLeaseQuery
            | MessageTypes::Tls => {
                warn!("Client sent a message type that is known but not yet handled");
                return;
            }
            _ => {
                error!("Client sent unknown message type");
                return;
            }
        };

        self.reply(response, src.port());
    }

    /// Calls `listen_once` in a loop forever.
    pub fn listen(&mut self) -> ! {
        info!("Listening for DHCP requests");
        loop {
            self.listen_once();
        }
    }

    /// If a request message has a parameter request list,
    /// each requested parameter is added to the response message
    /// if the parameter's value is configured on the server.
    fn handle_parameter_requests(&self, request_message: &Message) -> Vec<MessageOptions> {
        match request_message.find_option(55) {
            Some(MessageOptions::RequestedOptions(list)) => {
                // list is a Vec<u8> of dhcp option numbers
                list.iter()
                    .filter_map(|parameter_request| {
                        self.config
                            .parameters
                            .get(&parameter_request.to_string())
                            .cloned()
                    })
                    .collect()
            }
            _ => vec![],
        }
    }

    /// Sent from the server to client following a Discover message
    pub fn offer(&mut self, message: Message) -> Result<Message> {
        debug!("Sending Offer message");

        // The client may suggest values for the network address
        // and lease time in the DHCPDISCOVER message. The client may include
        // the 'requested IP address' option to suggest that a particular IP
        // address be assigned
        let maybe_requested_ip = match message.find_option(50) {
            Some(MessageOptions::RequestedIp(address_option)) => Some(address_option.inner()),
            _ => None,
        };
        let mac_address = message.get_mac_address();
        let yiaddr = self.leases.offer(mac_address, maybe_requested_ip)?;

        let mut parameters = self.handle_parameter_requests(&message);
        parameters.push(MessageOptions::MessageType(MessageTypes::Offer)); // must
        parameters.push(MessageOptions::LeaseTime(TimeOption::new(
            self.config.lease_time.as_client(),
        ))); // must
        parameters.push(MessageOptions::ServerIdentifier(AddressOption::new(
            self.ip,
        ))); // must, rfc2132

        Ok(Message {
            op: Ops::Reply,
            htype: HTypes::Ethernet,
            hlen: 6,
            hops: 0,
            xid: message.xid,
            secs: 0,
            flags: message.flags,
            ciaddr: Ipv4Addr::UNSPECIFIED, // field not used
            yiaddr,
            siaddr: self.ip,
            giaddr: message.giaddr,
            chaddr: message.chaddr,
            sname: SName::EMPTY,
            file: File::EMPTY,
            magic: MAGIC,
            options: parameters.into(),
        })
    }

    /// Sent from the server to client following a Request message
    ///
    /// Acks behave differently depending on if they are sent in response to a DHCP Request or DHCP Inform.
    /// For example, a DHCP Request must send lease time and a DHCP Inform must not.
    ///
    /// Any configuration parameters in the DHCPACK message SHOULD NOT
    /// conflict with those in the earlier DHCPOFFER message to which the
    /// client is responding.
    pub fn ack(&mut self, message: Message, yiaddr: Ipv4Addr) -> Message {
        debug!("Sending Ack message");

        let mut parameters = self.handle_parameter_requests(&message);
        parameters.push(MessageOptions::MessageType(MessageTypes::Ack)); // must
        parameters.push(MessageOptions::LeaseTime(TimeOption::new(
            self.config.lease_time.as_client(),
        ))); // must
        parameters.push(MessageOptions::ServerIdentifier(AddressOption::new(
            self.ip,
        ))); // must

        Message {
            op: Ops::Reply,
            htype: HTypes::Ethernet,
            hlen: 6,
            hops: 0,
            xid: message.xid,
            secs: 0,
            flags: message.flags,
            ciaddr: message.ciaddr,
            yiaddr,
            siaddr: self.ip, // ip address of next bootstrap server
            giaddr: message.giaddr,
            chaddr: message.chaddr,
            sname: SName::EMPTY,
            file: File::EMPTY,
            magic: MAGIC,
            options: parameters.into(),
        }
    }

    /// Sent from server to client in response to an Inform message
    ///
    /// Acks behave differently depending on if they are sent in response to a DHCP Request or DHCP Inform.
    /// For example, a DHCP Request must send lease time and a DHCP Inform must not.
    pub fn ack_inform(&self, message: Message) -> Message {
        debug!("Sending Ack message (in response to an inform)");

        let mut parameters = self.handle_parameter_requests(&message);
        parameters.push(MessageOptions::MessageType(MessageTypes::Ack)); // must
        parameters.push(MessageOptions::ServerIdentifier(AddressOption::new(
            self.ip,
        ))); // must

        Message {
            op: Ops::Reply,
            htype: HTypes::Ethernet,
            hlen: 6,
            hops: 0,
            xid: message.xid,
            secs: 0,
            flags: message.flags,
            ciaddr: message.ciaddr,
            yiaddr: Ipv4Addr::UNSPECIFIED,
            siaddr: self.ip, // ip address of next bootstrap server
            giaddr: message.giaddr,
            chaddr: message.chaddr,
            sname: SName::EMPTY,
            file: File::EMPTY,
            magic: MAGIC,
            options: parameters.into(),
        }
    }

    /// Sent from the server to client following a Request message
    pub fn nak(&self, message: Message, error: String) -> Message {
        debug!("Sending Nak message");

        let mut response = Message {
            op: Ops::Reply,
            htype: HTypes::Ethernet,
            hlen: 6,
            hops: 0,
            xid: message.xid,
            secs: 0,
            flags: message.flags,
            ciaddr: Ipv4Addr::UNSPECIFIED,
            yiaddr: Ipv4Addr::UNSPECIFIED,
            siaddr: Ipv4Addr::UNSPECIFIED,
            giaddr: message.giaddr,
            chaddr: message.chaddr,
            sname: SName::EMPTY, // this field not used
            file: File::EMPTY,   // this field not used
            magic: MAGIC,
            options: vec![
                MessageOptions::MessageType(MessageTypes::Nak), // must
                MessageOptions::ServerIdentifier(AddressOption::new(self.ip)), // must
            ]
            .into(),
        };

        match StringOption::new(error) {
            Ok(converted) => {
                response.add_option(MessageOptions::Message(converted)); // should
            }
            Err(_) => {
                error!("Sending Nak without error message option because option's value is empty");
            }
        };

        response
    }
}