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
|
//! Minimal DHCPv6 client implementation with Rapid Commit support
//! and auto-rebinding after link disruption.
use tokio::sync::{mpsc, watch};
use tokio::time::{Duration, Instant, Interval};
/// Possible states of the client.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub enum Dhcp6cState {
#[default]
Starting, // Lower layer down, no restart timer.
Soliciting, // Soliciting a new lease.
Requesting, // Advertise received, requesting the lease (no Rapid Commit).
Renewing, // Renewing the active lease.
Rebinding, // Rebinding the active lease.
Rerouting, // Rebinding the lease after link disruption (prefix not valid).
Opened, // Lower layer up, idle, lease valid, no renewal or rebind needed.
}
/// List of valid packets for this implementation.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Packet {
Solicit,
Advertise,
Request,
Reply(Lease, bool),
Renew,
Rebind,
}
/// Information on the various timers of a lease.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Lease {
pub timestamp: Instant,
pub t1: Duration,
pub t2: Duration,
pub valid_lifetime: Duration,
}
impl Lease {
/// Reports whether a renewal is needed.
pub fn needs_renewal(&self) -> bool {
!self.has_expired()
&& !self.needs_rebind()
&& Instant::now().duration_since(self.timestamp) > self.t1
}
/// Reports whether a rebind is needed.
pub fn needs_rebind(&self) -> bool {
!self.has_expired() && Instant::now().duration_since(self.timestamp) > self.t2
}
/// Reports whether the lease has expired.
pub fn has_expired(&self) -> bool {
Instant::now().duration_since(self.timestamp) > self.valid_lifetime
}
/// Waits until a renewal is needed.
pub async fn wait_renew(&self) {
tokio::time::sleep_until(self.timestamp + self.t1).await
}
/// Waits until a rebind is needed.
pub async fn wait_rebind(&self) {
tokio::time::sleep_until(self.timestamp + self.t2).await
}
/// Waits until the lease expires.
pub async fn wait_expire(&self) {
tokio::time::sleep_until(self.timestamp + self.valid_lifetime).await
}
}
/// A simple DHCPv6-PD client that supports Rapid Commit and auto-rebinding
/// after link disruption.
#[derive(Debug)]
pub struct Dhcp6c {
state: Dhcp6cState,
lease: Option<Lease>,
restart_timer: Interval,
restart_counter: u32,
max_request: u32,
output_tx: mpsc::UnboundedSender<Packet>,
output_rx: mpsc::UnboundedReceiver<Packet>,
upper_status_tx: watch::Sender<bool>,
upper_status_rx: watch::Receiver<bool>,
}
impl Dhcp6c {
/// Creates a new `Dhcp6c`.
///
/// You **must** start calling the [`Dhcp6c::to_send`] method
/// before calling the [`Dhcp6c::up`] method
/// and keep calling it until [`Dhcp6c::down`] has been issued.
///
/// # Arguments
///
/// * `lease` - The existing [`Lease`] if one exists.
/// * `restart_interval` - The retransmission interval, default is 6 seconds.
/// * `max_request` - The maximum number of Request or Rebind (reroute) attempts, default is 10.
pub fn new(
lease: Option<Lease>,
restart_interval: Option<Duration>,
max_request: Option<u32>,
) -> Self {
let restart_timer =
tokio::time::interval(restart_interval.unwrap_or(Duration::from_secs(6)));
let (output_tx, output_rx) = mpsc::unbounded_channel();
let (upper_status_tx, upper_status_rx) = watch::channel(false);
Self {
state: Dhcp6cState::default(),
lease,
restart_timer, // Needs to be reset by some events.
restart_counter: 0, // Needs to be initialized by some events.
max_request: max_request.unwrap_or(10),
output_tx,
output_rx,
upper_status_tx,
upper_status_rx,
}
}
/// Waits for and returns the next packet to send.
pub async fn to_send(&mut self) -> Packet {
loop {
tokio::select! {
packet = self.output_rx.recv() => return packet.expect("output channel is closed"),
_ = self.restart_timer.tick() => if self.restart_counter > 0 { // TO+ event
if let Some(packet) = self.timeout_positive() { return packet; }
} else { // TO- event
if let Some(packet) = self.timeout_negative() { return packet; }
},
Some(_) = option_wait_renew(self.lease.as_ref()) => if let Some(packet) = self.t1() { return packet; },
Some(_) = option_wait_rebind(self.lease.as_ref()) => if let Some(packet) = self.t2() { return packet; },
Some(_) = option_wait_expire(self.lease.as_ref()) => if let Some(packet) = self.expire() { return packet; },
}
}
}
/// Feeds a packet into the state machine for processing.
/// Can trigger the RA, RR+ or RR- events.
pub fn from_recv(&mut self, packet: Packet) {
match packet {
Packet::Solicit | Packet::Request | Packet::Renew | Packet::Rebind => {} // illegal
Packet::Advertise => self.ra(),
Packet::Reply(lease, no_binding) => self.rr(lease, no_binding),
}
}
/// Signals to the state machine that the lower layer is now up.
/// This is equivalent to the Up event.
pub fn up(&mut self) {
match self.lease {
Some(ref lease) if !lease.has_expired() => self.up_positive(),
_ => self.up_negative(),
}
}
fn up_positive(&mut self) {
if self.state == Dhcp6cState::Starting {
self.restart_timer.reset();
self.restart_counter = self.max_request;
self.output_tx
.send(Packet::Rebind)
.expect("output channel is closed");
self.restart_counter -= 1;
self.state = Dhcp6cState::Rerouting;
}
}
fn up_negative(&mut self) {
if self.state == Dhcp6cState::Starting {
self.restart_timer.reset();
self.output_tx
.send(Packet::Solicit)
.expect("output channel is closed");
self.state = Dhcp6cState::Soliciting;
}
}
/// Signals to the state machine that the lower layer is now down.
/// This is equivalent to the Down event.
pub fn down(&mut self) {
match self.state {
Dhcp6cState::Starting => {} // illegal
Dhcp6cState::Soliciting | Dhcp6cState::Requesting | Dhcp6cState::Rerouting => {
self.state = Dhcp6cState::Starting
}
Dhcp6cState::Renewing | Dhcp6cState::Rebinding | Dhcp6cState::Opened => {
self.upper_status_tx
.send(false)
.expect("upper status channel is closed");
self.state = Dhcp6cState::Starting;
}
}
}
/// Reports whether the `Dhcp6c` is in the `Soliciting` state.
pub fn is_soliciting(&self) -> bool {
self.state == Dhcp6cState::Soliciting
}
/// Reports whether the `Dhcp6c` is in the `Rebinding` state.
pub fn is_rebinding(&self) -> bool {
self.state == Dhcp6cState::Rebinding
}
/// Reports whether the `Dhcp6c` is in the `Rerouting` state.
pub fn is_rerouting(&self) -> bool {
self.state == Dhcp6cState::Rerouting
}
/// Reports whether the `Dhcp6c` is in a state that accepts new server IDs.
pub fn accept_new_server_id(&self) -> bool {
self.is_soliciting() || self.is_rebinding() || self.is_rerouting()
}
/// Returns a watch channel receiver that can be used to monitor whether
/// the `Dhcp6c` has a valid and routed prefix.
/// This is equivalent to the `Renewing`, `Rebinding` and `Opened` states.
pub fn opened(&self) -> watch::Receiver<bool> {
self.upper_status_rx.clone()
}
/// Returns a reference to the current internal lease if there is one,
/// or `None` otherwise.
pub fn lease(&self) -> Option<&Lease> {
self.lease.as_ref()
}
fn timeout_positive(&mut self) -> Option<Packet> {
match self.state {
Dhcp6cState::Starting | Dhcp6cState::Opened => None, // illegal
Dhcp6cState::Soliciting => Some(Packet::Solicit),
Dhcp6cState::Requesting => {
self.restart_counter -= 1;
Some(Packet::Request)
}
Dhcp6cState::Renewing => Some(Packet::Renew),
Dhcp6cState::Rebinding => Some(Packet::Rebind),
Dhcp6cState::Rerouting => {
self.restart_counter -= 1;
Some(Packet::Rebind)
}
}
}
fn timeout_negative(&mut self) -> Option<Packet> {
match self.state {
Dhcp6cState::Starting | Dhcp6cState::Opened => None, // illegal
Dhcp6cState::Soliciting => Some(Packet::Solicit),
Dhcp6cState::Requesting => {
self.state = Dhcp6cState::Soliciting;
Some(Packet::Solicit)
}
Dhcp6cState::Renewing => Some(Packet::Renew),
Dhcp6cState::Rebinding => Some(Packet::Rebind),
Dhcp6cState::Rerouting => {
self.state = Dhcp6cState::Soliciting;
Some(Packet::Solicit)
}
}
}
fn t1(&mut self) -> Option<Packet> {
match self.state {
Dhcp6cState::Opened => {
self.restart_timer.reset();
self.state = Dhcp6cState::Renewing;
Some(Packet::Renew)
}
_ => None, // illegal
}
}
fn t2(&mut self) -> Option<Packet> {
match self.state {
Dhcp6cState::Renewing => {
self.restart_timer.reset();
self.state = Dhcp6cState::Rebinding;
Some(Packet::Rebind)
}
_ => None, // illegal
}
}
fn expire(&mut self) -> Option<Packet> {
match self.state {
Dhcp6cState::Rebinding => {
self.restart_timer.reset();
self.upper_status_tx
.send(false)
.expect("upper status channel is closed");
self.state = Dhcp6cState::Soliciting;
Some(Packet::Solicit)
}
Dhcp6cState::Rerouting => {
self.restart_timer.reset();
self.state = Dhcp6cState::Soliciting;
Some(Packet::Solicit)
}
_ => None, // illegal
}
}
fn ra(&mut self) {
if self.state == Dhcp6cState::Soliciting {
self.restart_timer.reset();
self.restart_counter = self.max_request;
self.output_tx
.send(Packet::Request)
.expect("output channel is closed");
self.restart_counter -= 1;
self.state = Dhcp6cState::Requesting;
}
}
fn rr(&mut self, lease: Lease, no_binding: bool) {
match self.state {
Dhcp6cState::Starting | Dhcp6cState::Opened => {} // illegal
Dhcp6cState::Soliciting
| Dhcp6cState::Requesting
| Dhcp6cState::Renewing
| Dhcp6cState::Rebinding
| Dhcp6cState::Rerouting => {
self.upper_status_tx
.send(true)
.expect("upper status channel is closed");
// TODO: t1, t2 = 0 or inf
// TODO: req if status nobinding
// TODO: lft = 0
self.lease = Some(lease);
self.state = Dhcp6cState::Opened;
}
}
}
}
async fn option_wait_renew(lease: Option<&Lease>) -> Option<()> {
match lease {
Some(lease) => {
lease.wait_renew().await;
Some(())
}
None => None,
}
}
async fn option_wait_rebind(lease: Option<&Lease>) -> Option<()> {
match lease {
Some(lease) => {
lease.wait_rebind().await;
Some(())
}
None => None,
}
}
async fn option_wait_expire(lease: Option<&Lease>) -> Option<()> {
match lease {
Some(lease) => {
lease.wait_expire().await;
Some(())
}
None => None,
}
}
|