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
use Error;
use super::Device;

// We use our own RNG to stay compatible with #![no_std].
// The use of the RNG below has a slight bias, but it doesn't matter.
fn xorshift32(state: &mut u32) -> u32 {
    let mut x = *state;
    x ^= x << 13;
    x ^= x >> 17;
    x ^= x << 5;
    *state = x;
    x
}

fn check_rng(state: &mut u32, pct: u8) -> bool {
    xorshift32(state) % 100 < pct as u32
}

fn corrupt<T: AsMut<[u8]>>(state: &mut u32, mut buffer: T) {
    let mut buffer = buffer.as_mut();
    // We introduce a single bitflip, as the most likely, and the hardest to detect, error.
    let index = (xorshift32(state) as usize) % buffer.len();
    let bit   = 1 << (xorshift32(state) % 8) as u8;
    buffer[index] ^= bit;
}

// This could be fixed once associated consts are stable.
const MTU: usize = 1536;

#[derive(Debug, Clone, Copy)]
struct Config {
    corrupt_pct: u8,
    drop_pct:    u8,
    reorder_pct: u8
}

/// A fault injector device.
///
/// A fault injector is a device that randomly drops or corrupts packets traversing it,
/// according to preset probabilities.
#[derive(Debug)]
pub struct FaultInjector<T: Device> {
    lower:  T,
    state:  u32,
    config: Config
}

impl<T: Device> FaultInjector<T> {
    /// Create a tracer device, using the given random number generator seed.
    pub fn new(lower: T, seed: u32) -> FaultInjector<T> {
        FaultInjector {
            lower: lower,
            state: seed,
            config: Config {
                corrupt_pct: 0,
                drop_pct:    0,
                reorder_pct: 0
            }
        }
    }

    /// Return the underlying device, consuming the tracer.
    pub fn into_lower(self) -> T {
        self.lower
    }

    /// Return the probability of corrupting a packet, in percents.
    pub fn corrupt_chance(&self) -> u8 {
        self.config.corrupt_pct
    }

    /// Return the probability of dropping a packet, in percents.
    pub fn drop_chance(&self) -> u8 {
        self.config.drop_pct
    }

    /// Set the probability of corrupting a packet, in percents.
    ///
    /// # Panics
    /// This function panics if the probability is not between 0% and 100%.
    pub fn set_corrupt_chance(&mut self, pct: u8) {
        if pct > 100 { panic!("percentage out of range") }
        self.config.corrupt_pct = pct
    }

    /// Set the probability of dropping a packet, in percents.
    ///
    /// # Panics
    /// This function panics if the probability is not between 0% and 100%.
    pub fn set_drop_chance(&mut self, pct: u8) {
        if pct > 100 { panic!("percentage out of range") }
        self.config.drop_pct = pct
    }
}

impl<T: Device> Device for FaultInjector<T>
        where T::RxBuffer: AsMut<[u8]> {
    type RxBuffer = T::RxBuffer;
    type TxBuffer = TxBuffer<T::TxBuffer>;

    fn mtu(&self) -> usize {
        if self.lower.mtu() < MTU {
            self.lower.mtu()
        } else {
            MTU
        }
    }

    fn receive(&mut self) -> Result<Self::RxBuffer, Error> {
        let mut buffer = try!(self.lower.receive());
        if check_rng(&mut self.state, self.config.drop_pct) {
            net_trace!("rx: dropping a packet");
            return Err(Error::Exhausted)
        }
        if check_rng(&mut self.state, self.config.corrupt_pct) {
            net_trace!("rx: corrupting a packet");
            corrupt(&mut self.state, &mut buffer)
        }
        Ok(buffer)
    }

    fn transmit(&mut self, length: usize) -> Result<Self::TxBuffer, Error> {
        let buffer;
        if check_rng(&mut self.state, self.config.drop_pct) {
            net_trace!("tx: dropping a packet");
            buffer = None;
        } else {
            buffer = Some(try!(self.lower.transmit(length)));
        }
        Ok(TxBuffer {
            buffer: buffer,
            state:  xorshift32(&mut self.state),
            config: self.config,
            junk:   [0; MTU],
            length: length
        })
    }
}

#[doc(hidden)]
pub struct TxBuffer<T: AsRef<[u8]> + AsMut<[u8]>> {
    state:  u32,
    config: Config,
    buffer: Option<T>,
    junk:   [u8; MTU],
    length: usize
}

impl<T: AsRef<[u8]> + AsMut<[u8]>> AsRef<[u8]>
        for TxBuffer<T> {
    fn as_ref(&self) -> &[u8] {
        match self.buffer {
            Some(ref buf) => buf.as_ref(),
            None => &self.junk[..self.length]
        }
    }
}

impl<T: AsRef<[u8]> + AsMut<[u8]>> AsMut<[u8]>
        for TxBuffer<T> {
    fn as_mut(&mut self) -> &mut [u8] {
        match self.buffer {
            Some(ref mut buf) => buf.as_mut(),
            None => &mut self.junk[..self.length]
        }
    }
}

impl<T: AsRef<[u8]> + AsMut<[u8]>> Drop for TxBuffer<T> {
    fn drop(&mut self) {
        match self.buffer {
            Some(ref mut buf) => {
                if check_rng(&mut self.state, self.config.corrupt_pct) {
                    net_trace!("tx: corrupting a packet");
                    corrupt(&mut self.state, buf)
                }
            },
            None => ()
        }
    }
}