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
use rand::seq::SliceRandom;
use rand::thread_rng;
use std::net::IpAddr;

use crate::bytesbits::BytesBits;
use crate::combinations::Combinations;
use crate::{confusion_level, ConfusionLevel};

/// Encode an IP address into a random, valid I-DUNNO representation at the
/// given confusion level.
///
/// Returns None if there are no possible encodings.
///
/// If there are many possible encodings, this function generates 10, and
/// chooses one of those at random.
///
/// The output of this function MAY be presented to humans, as recommended
/// by RFC8771.
///
/// # Examples
///
/// ```
/// use std::net::{Ipv4Addr, Ipv6Addr};
/// use i_dunno::{encode, ConfusionLevel};
/// let x = encode(
///     "0.0.1.1".parse().unwrap(),
///     ConfusionLevel::Delightful,
/// );
/// assert_eq!(x, None);
///
/// let a: String = encode(
///     "::16:164".parse().unwrap(),
///     ConfusionLevel::Minimum,
/// ).unwrap();
/// assert_eq!(
///     a,
///     "\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\u{2c02}d"
/// )
/// ```
pub fn encode(
    ip_addr: IpAddr,
    required_confusion_level: ConfusionLevel,
) -> Option<String> {
    encode_all(ip_addr, required_confusion_level)
        .take(10)
        .collect::<Vec<String>>()
        .choose(&mut thread_rng())
        .cloned()
}

/// Provide valid I-DUNNO encodings for the supplied IP address at the
/// given confusion level.
///
/// The output of this function should not be presented to humans, since
/// seeing multiple encodings may trigger an undesirable confusion reduction.
///
/// # Examples
///
/// ```
/// use i_dunno::{encode_all, ConfusionLevel};
/// let a: Vec<String> = encode_all(
///     "::16:164".parse().unwrap(),
///     ConfusionLevel::Minimum
/// ).collect();
/// assert_eq!(
///     a,
///     vec![
///         "\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\u{2c02}d"
///     ]
/// );
///
/// let b = encode_all(
///     "198.51.100.164".parse().unwrap(),
///     ConfusionLevel::Minimum
/// ).next().unwrap();
/// assert_eq!(b, "c\u{c}l\u{04A4}");
/// ```
pub fn encode_all(
    ip_addr: IpAddr,
    required_confusion_level: ConfusionLevel,
) -> impl Iterator<Item = String> {
    let addr_octets = match ip_addr {
        IpAddr::V4(addr_v4) => addr_v4.octets().to_vec(),
        IpAddr::V6(addr_v6) => addr_v6.octets().to_vec(),
    };
    Combinations::new(BytesBits::new(addr_octets))
        .filter_map(string_from_u32s)
        .filter(move |candidate| {
            confusion_level(candidate)
                .map(|lev| lev >= required_confusion_level)
                .unwrap_or(false)
        })
}

fn string_from_u32s(u32s: Vec<u32>) -> Option<String> {
    let mut ret = String::with_capacity(u32s.len() * 4);
    for n in u32s {
        if let Some(ch) = std::char::from_u32(n) {
            ret.push(ch);
        } else {
            return None;
        }
    }
    Some(ret)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn encoding_of_something_with_no_valid_encodings() {
        assert_eq!(
            encode("0.0.0.1".parse().unwrap(), ConfusionLevel::Minimum),
            None
        );
        assert_eq!(enc("0.0.0.1", ConfusionLevel::Minimum), Vec::<&str>::new());
    }

    #[test]
    fn encoding_of_something_with_only_one_encoding() {
        // Since we have only 1 answer, we can test encode() as well as
        // encode_all().
        assert_eq!(
            to_hex_str(
                &encode("0.0.1.1".parse().unwrap(), ConfusionLevel::Minimum)
                    .unwrap()
            ),
            "000000c481"
        );

        assert_eq!(enc("0.0.1.1", ConfusionLevel::Minimum), vec!["000000c481"]);
        assert_eq!(
            enc("0.0.1.1", ConfusionLevel::Satisfactory),
            vec!["000000c481"]
        );
        assert_eq!(
            enc("0.0.1.1", ConfusionLevel::Delightful),
            Vec::<&str>::new()
        );
    }

    #[test]
    fn encode_localhost() {
        assert_eq!(
            enc("127.0.0.1", ConfusionLevel::Delightful),
            vec!["3fd0800001", "cfb8000001"]
        );
    }

    #[test]
    fn encoding_something_with_only_one_delightful_but_more_satisfactory() {
        assert_eq!(
            enc("124.32.3.10", ConfusionLevel::Minimum),
            vec!["3e0800cc8a", "cfa100060a"]
        );
        assert_eq!(
            enc("124.32.3.10", ConfusionLevel::Satisfactory),
            vec!["3e0800cc8a", "cfa100060a"]
        );
        assert_eq!(
            enc("124.32.3.10", ConfusionLevel::Delightful),
            vec!["3e0800cc8a"]
        );
    }

    #[test]
    fn all_encodings_of_198_51_100_164() {
        assert_eq!(
            enc("198.51.100.164", ConfusionLevel::Minimum),
            vec!["630c6cd2a4", "630cdb8924", "d8b14d4924"]
        );
        assert_eq!(
            enc("198.51.100.164", ConfusionLevel::Satisfactory),
            vec!["630c6cd2a4", "630cdb8924", "d8b14d4924"]
        );
        assert_eq!(
            enc("198.51.100.164", ConfusionLevel::Delightful),
            vec!["630c6cd2a4", "630cdb8924", "d8b14d4924"]
        );
    }

    #[test]
    fn encoding_an_ipv6_address() {
        assert_eq!(
            enc("::16:164", ConfusionLevel::Minimum),
            vec!["000000000000000000000000000000e2b08264"]
        );
        assert_eq!(
            enc("::16:164", ConfusionLevel::Satisfactory),
            vec!["000000000000000000000000000000e2b08264"]
        );
        assert_eq!(
            enc("::16:164", ConfusionLevel::Delightful),
            vec!["000000000000000000000000000000e2b08264"]
        );
    }

    #[test]
    fn encoding_an_ipv6_address_with_lots_of_options() {
        let encs = enc("2001:db8::8a2e:370:7334", ConfusionLevel::Delightful);
        assert!(encs
            .contains(&String::from("1000215b400000000000000851380670e78cb4")));
        assert!(encs.contains(&String::from(
            "c480041b38000000000000010ac5b00dd88eccb4"
        )));
    }

    fn enc(s: &str, confusion_level: ConfusionLevel) -> Vec<String> {
        to_hex(encode_all(s.parse().unwrap(), confusion_level).collect())
    }

    fn to_hex(enc: Vec<String>) -> Vec<String> {
        enc.iter().map(|s| to_hex_str(s)).collect::<Vec<String>>()
    }

    fn to_hex_str(s: &str) -> String {
        s.as_bytes().iter().map(|c| format!("{:02x}", c)).collect()
    }
}