fault_injector.rs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. use core::cell::RefCell;
  2. use crate::{Error, Result};
  3. use crate::phy::{self, DeviceCapabilities, Device};
  4. use crate::time::{Duration, Instant};
  5. // We use our own RNG to stay compatible with #![no_std].
  6. // The use of the RNG below has a slight bias, but it doesn't matter.
  7. fn xorshift32(state: &mut u32) -> u32 {
  8. let mut x = *state;
  9. x ^= x << 13;
  10. x ^= x >> 17;
  11. x ^= x << 5;
  12. *state = x;
  13. x
  14. }
  15. // This could be fixed once associated consts are stable.
  16. const MTU: usize = 1536;
  17. #[derive(Debug, Default, Clone, Copy)]
  18. #[cfg_attr(feature = "defmt", derive(defmt::Format))]
  19. struct Config {
  20. corrupt_pct: u8,
  21. drop_pct: u8,
  22. reorder_pct: u8,
  23. max_size: usize,
  24. max_tx_rate: u64,
  25. max_rx_rate: u64,
  26. interval: Duration,
  27. }
  28. #[derive(Debug, Clone)]
  29. #[cfg_attr(feature = "defmt", derive(defmt::Format))]
  30. struct State {
  31. rng_seed: u32,
  32. refilled_at: Instant,
  33. tx_bucket: u64,
  34. rx_bucket: u64,
  35. }
  36. impl State {
  37. fn maybe(&mut self, pct: u8) -> bool {
  38. xorshift32(&mut self.rng_seed) % 100 < pct as u32
  39. }
  40. fn corrupt<T: AsMut<[u8]>>(&mut self, mut buffer: T) {
  41. let buffer = buffer.as_mut();
  42. // We introduce a single bitflip, as the most likely, and the hardest to detect, error.
  43. let index = (xorshift32(&mut self.rng_seed) as usize) % buffer.len();
  44. let bit = 1 << (xorshift32(&mut self.rng_seed) % 8) as u8;
  45. buffer[index] ^= bit;
  46. }
  47. fn refill(&mut self, config: &Config, timestamp: Instant) {
  48. if timestamp - self.refilled_at > config.interval {
  49. self.tx_bucket = config.max_tx_rate;
  50. self.rx_bucket = config.max_rx_rate;
  51. self.refilled_at = timestamp;
  52. }
  53. }
  54. fn maybe_transmit(&mut self, config: &Config, timestamp: Instant) -> bool {
  55. if config.max_tx_rate == 0 { return true }
  56. self.refill(config, timestamp);
  57. if self.tx_bucket > 0 {
  58. self.tx_bucket -= 1;
  59. true
  60. } else {
  61. false
  62. }
  63. }
  64. fn maybe_receive(&mut self, config: &Config, timestamp: Instant) -> bool {
  65. if config.max_rx_rate == 0 { return true }
  66. self.refill(config, timestamp);
  67. if self.rx_bucket > 0 {
  68. self.rx_bucket -= 1;
  69. true
  70. } else {
  71. false
  72. }
  73. }
  74. }
  75. /// A fault injector device.
  76. ///
  77. /// A fault injector is a device that alters packets traversing through it to simulate
  78. /// adverse network conditions (such as random packet loss or corruption), or software
  79. /// or hardware limitations (such as a limited number or size of usable network buffers).
  80. #[derive(Debug)]
  81. pub struct FaultInjector<D: for<'a> Device<'a>> {
  82. inner: D,
  83. state: RefCell<State>,
  84. config: Config,
  85. }
  86. impl<D: for<'a> Device<'a>> FaultInjector<D> {
  87. /// Create a fault injector device, using the given random number generator seed.
  88. pub fn new(inner: D, seed: u32) -> FaultInjector<D> {
  89. let state = State {
  90. rng_seed: seed,
  91. refilled_at: Instant::from_millis(0),
  92. tx_bucket: 0,
  93. rx_bucket: 0,
  94. };
  95. FaultInjector {
  96. inner: inner,
  97. state: RefCell::new(state),
  98. config: Config::default(),
  99. }
  100. }
  101. /// Return the underlying device, consuming the fault injector.
  102. pub fn into_inner(self) -> D {
  103. self.inner
  104. }
  105. /// Return the probability of corrupting a packet, in percents.
  106. pub fn corrupt_chance(&self) -> u8 {
  107. self.config.corrupt_pct
  108. }
  109. /// Return the probability of dropping a packet, in percents.
  110. pub fn drop_chance(&self) -> u8 {
  111. self.config.drop_pct
  112. }
  113. /// Return the maximum packet size, in octets.
  114. pub fn max_packet_size(&self) -> usize {
  115. self.config.max_size
  116. }
  117. /// Return the maximum packet transmission rate, in packets per second.
  118. pub fn max_tx_rate(&self) -> u64 {
  119. self.config.max_rx_rate
  120. }
  121. /// Return the maximum packet reception rate, in packets per second.
  122. pub fn max_rx_rate(&self) -> u64 {
  123. self.config.max_tx_rate
  124. }
  125. /// Return the interval for packet rate limiting, in milliseconds.
  126. pub fn bucket_interval(&self) -> Duration {
  127. self.config.interval
  128. }
  129. /// Set the probability of corrupting a packet, in percents.
  130. ///
  131. /// # Panics
  132. /// This function panics if the probability is not between 0% and 100%.
  133. pub fn set_corrupt_chance(&mut self, pct: u8) {
  134. if pct > 100 { panic!("percentage out of range") }
  135. self.config.corrupt_pct = pct
  136. }
  137. /// Set the probability of dropping a packet, in percents.
  138. ///
  139. /// # Panics
  140. /// This function panics if the probability is not between 0% and 100%.
  141. pub fn set_drop_chance(&mut self, pct: u8) {
  142. if pct > 100 { panic!("percentage out of range") }
  143. self.config.drop_pct = pct
  144. }
  145. /// Set the maximum packet size, in octets.
  146. pub fn set_max_packet_size(&mut self, size: usize) {
  147. self.config.max_size = size
  148. }
  149. /// Set the maximum packet transmission rate, in packets per interval.
  150. pub fn set_max_tx_rate(&mut self, rate: u64) {
  151. self.config.max_tx_rate = rate
  152. }
  153. /// Set the maximum packet reception rate, in packets per interval.
  154. pub fn set_max_rx_rate(&mut self, rate: u64) {
  155. self.config.max_rx_rate = rate
  156. }
  157. /// Set the interval for packet rate limiting, in milliseconds.
  158. pub fn set_bucket_interval(&mut self, interval: Duration) {
  159. self.state.borrow_mut().refilled_at = Instant::from_millis(0);
  160. self.config.interval = interval
  161. }
  162. }
  163. impl<'a, D> Device<'a> for FaultInjector<D>
  164. where D: for<'b> Device<'b>,
  165. {
  166. type RxToken = RxToken<'a, <D as Device<'a>>::RxToken>;
  167. type TxToken = TxToken<'a, <D as Device<'a>>::TxToken>;
  168. fn capabilities(&self) -> DeviceCapabilities {
  169. let mut caps = self.inner.capabilities();
  170. if caps.max_transmission_unit > MTU {
  171. caps.max_transmission_unit = MTU;
  172. }
  173. caps
  174. }
  175. fn receive(&'a mut self) -> Option<(Self::RxToken, Self::TxToken)> {
  176. let &mut Self { ref mut inner, ref state, config } = self;
  177. inner.receive().map(|(rx_token, tx_token)| {
  178. let rx = RxToken {
  179. state: &state,
  180. config: config,
  181. token: rx_token,
  182. corrupt: [0; MTU],
  183. };
  184. let tx = TxToken {
  185. state: &state,
  186. config: config,
  187. token: tx_token,
  188. junk: [0; MTU],
  189. };
  190. (rx, tx)
  191. })
  192. }
  193. fn transmit(&'a mut self) -> Option<Self::TxToken> {
  194. let &mut Self { ref mut inner, ref state, config } = self;
  195. inner.transmit().map(|token| TxToken {
  196. state: &state,
  197. config: config,
  198. token: token,
  199. junk: [0; MTU],
  200. })
  201. }
  202. }
  203. #[doc(hidden)]
  204. pub struct RxToken<'a, Rx: phy::RxToken> {
  205. state: &'a RefCell<State>,
  206. config: Config,
  207. token: Rx,
  208. corrupt: [u8; MTU],
  209. }
  210. impl<'a, Rx: phy::RxToken> phy::RxToken for RxToken<'a, Rx> {
  211. fn consume<R, F>(self, timestamp: Instant, f: F) -> Result<R>
  212. where F: FnOnce(&mut [u8]) -> Result<R>
  213. {
  214. if self.state.borrow_mut().maybe(self.config.drop_pct) {
  215. net_trace!("rx: randomly dropping a packet");
  216. return Err(Error::Exhausted)
  217. }
  218. if !self.state.borrow_mut().maybe_receive(&self.config, timestamp) {
  219. net_trace!("rx: dropping a packet because of rate limiting");
  220. return Err(Error::Exhausted)
  221. }
  222. let Self { token, config, state, mut corrupt } = self;
  223. token.consume(timestamp, |buffer| {
  224. if config.max_size > 0 && buffer.as_ref().len() > config.max_size {
  225. net_trace!("rx: dropping a packet that is too large");
  226. return Err(Error::Exhausted)
  227. }
  228. if state.borrow_mut().maybe(config.corrupt_pct) {
  229. net_trace!("rx: randomly corrupting a packet");
  230. let mut corrupt = &mut corrupt[..buffer.len()];
  231. corrupt.copy_from_slice(buffer);
  232. state.borrow_mut().corrupt(&mut corrupt);
  233. f(&mut corrupt)
  234. } else {
  235. f(buffer)
  236. }
  237. })
  238. }
  239. }
  240. #[doc(hidden)]
  241. pub struct TxToken<'a, Tx: phy::TxToken> {
  242. state: &'a RefCell<State>,
  243. config: Config,
  244. token: Tx,
  245. junk: [u8; MTU],
  246. }
  247. impl<'a, Tx: phy::TxToken> phy::TxToken for TxToken<'a, Tx> {
  248. fn consume<R, F>(mut self, timestamp: Instant, len: usize, f: F) -> Result<R>
  249. where F: FnOnce(&mut [u8]) -> Result<R>
  250. {
  251. let drop = if self.state.borrow_mut().maybe(self.config.drop_pct) {
  252. net_trace!("tx: randomly dropping a packet");
  253. true
  254. } else if self.config.max_size > 0 && len > self.config.max_size {
  255. net_trace!("tx: dropping a packet that is too large");
  256. true
  257. } else if !self.state.borrow_mut().maybe_transmit(&self.config, timestamp) {
  258. net_trace!("tx: dropping a packet because of rate limiting");
  259. true
  260. } else {
  261. false
  262. };
  263. if drop {
  264. return f(&mut self.junk[..len]);
  265. }
  266. let Self { token, state, config, .. } = self;
  267. token.consume(timestamp, len, |mut buf| {
  268. if state.borrow_mut().maybe(config.corrupt_pct) {
  269. net_trace!("tx: corrupting a packet");
  270. state.borrow_mut().corrupt(&mut buf)
  271. }
  272. f(buf)
  273. })
  274. }
  275. }