aboutsummaryrefslogtreecommitdiff
path: root/src/util.rs
blob: daf0c5a683014e55a823a1756661169a031bb862 (plain) (blame)
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
use crate::{Error, Result};

use std::fs::File;
use std::net::Ipv6Addr;
use std::time::{Duration, SystemTime};

use tokio::net::{ToSocketAddrs, UdpSocket};

use dhcproto::v6::IAPrefix;
use rsdsl_pd_config::PdConfig;

pub fn expired(lease: &PdConfig) -> bool {
    let expiry = lease.timestamp + Duration::from_secs(lease.preflft.into());
    SystemTime::now() >= expiry
}

pub async fn send_to_exact<A: ToSocketAddrs>(
    sock: &UdpSocket,
    buf: &[u8],
    target: A,
) -> Result<()> {
    let n = sock.send_to(buf, target).await?;
    if n != buf.len() {
        Err(Error::PartialSend)
    } else {
        Ok(())
    }
}

pub fn write_pdconfig(
    ia_prefix: &IAPrefix,
    dnss: &[Ipv6Addr],
    aftr: &Option<String>,
) -> Result<()> {
    let pdconfig = PdConfig {
        timestamp: SystemTime::now(),
        prefix: ia_prefix.prefix_ip,
        len: ia_prefix.prefix_len,
        validlft: ia_prefix.valid_lifetime,
        preflft: ia_prefix.preferred_lifetime,
        dns1: dnss[0], // Bounds checked by packet handler.
        dns2: dnss[1], // Bounds checked by packet handler.
        aftr: aftr.clone(),
    };

    let mut file = File::create(rsdsl_pd_config::LOCATION)?;
    serde_json::to_writer_pretty(&mut file, &pdconfig)?;

    Ok(())
}