server.rs 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. #[macro_use]
  2. extern crate log;
  3. extern crate env_logger;
  4. extern crate getopts;
  5. extern crate smoltcp;
  6. use std::str::{self, FromStr};
  7. use std::env;
  8. use std::time::{Instant, SystemTime, UNIX_EPOCH};
  9. use log::{LogLevelFilter, LogRecord};
  10. use env_logger::{LogBuilder};
  11. use smoltcp::Error;
  12. use smoltcp::phy::{Tracer, FaultInjector, TapInterface};
  13. use smoltcp::wire::{EthernetFrame, EthernetAddress, IpAddress};
  14. use smoltcp::wire::PrettyPrinter;
  15. use smoltcp::iface::{ArpCache, SliceArpCache, EthernetInterface};
  16. use smoltcp::socket::{AsSocket, SocketSet};
  17. use smoltcp::socket::{UdpSocket, UdpSocketBuffer, UdpPacketBuffer};
  18. use smoltcp::socket::{TcpSocket, TcpSocketBuffer};
  19. fn main() {
  20. let mut opts = getopts::Options::new();
  21. opts.optopt("", "drop-chance", "Chance of dropping a packet (%)", "CHANCE");
  22. opts.optopt("", "corrupt-chance", "Chance of corrupting a packet (%)", "CHANCE");
  23. opts.optflag("h", "help", "print this help menu");
  24. let matches = opts.parse(env::args().skip(1)).unwrap();
  25. if matches.opt_present("h") || matches.free.len() != 1 {
  26. let brief = format!("Usage: {} FILE [options]", env::args().nth(0).unwrap());
  27. print!("{}", opts.usage(&brief));
  28. return
  29. }
  30. let drop_chance = u8::from_str(&matches.opt_str("drop-chance")
  31. .unwrap_or("0".to_string())).unwrap();
  32. let corrupt_chance = u8::from_str(&matches.opt_str("corrupt-chance")
  33. .unwrap_or("0".to_string())).unwrap();
  34. let seed = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().subsec_nanos();
  35. let startup_time = Instant::now();
  36. LogBuilder::new()
  37. .format(move |record: &LogRecord| {
  38. let elapsed = Instant::now().duration_since(startup_time);
  39. if record.target().starts_with("smoltcp::") {
  40. format!("\x1b[0m[{:6}.{:03}s] ({}): {}\x1b[0m",
  41. elapsed.as_secs(), elapsed.subsec_nanos() / 1000000,
  42. record.target().replace("smoltcp::", ""), record.args())
  43. } else {
  44. format!("\x1b[32m[{:6}.{:03}s] ({}): {}\x1b[0m",
  45. elapsed.as_secs(), elapsed.subsec_nanos() / 1000000,
  46. record.target(), record.args())
  47. }
  48. })
  49. .filter(None, LogLevelFilter::Trace)
  50. .init()
  51. .unwrap();
  52. fn trace_writer(printer: PrettyPrinter<EthernetFrame<&[u8]>>) {
  53. print!("\x1b[37m{}\x1b[0m", printer)
  54. }
  55. let device = TapInterface::new(&matches.free[0]).unwrap();
  56. let mut device = FaultInjector::new(device, seed);
  57. device.set_drop_chance(drop_chance);
  58. device.set_corrupt_chance(corrupt_chance);
  59. let device = Tracer::<_, EthernetFrame<&[u8]>>::new(device, trace_writer);
  60. let arp_cache = SliceArpCache::new(vec![Default::default(); 8]);
  61. let udp_rx_buffer = UdpSocketBuffer::new(vec![UdpPacketBuffer::new(vec![0; 64])]);
  62. let udp_tx_buffer = UdpSocketBuffer::new(vec![UdpPacketBuffer::new(vec![0; 128])]);
  63. let udp_socket = UdpSocket::new(udp_rx_buffer, udp_tx_buffer);
  64. let tcp1_rx_buffer = TcpSocketBuffer::new(vec![0; 64]);
  65. let tcp1_tx_buffer = TcpSocketBuffer::new(vec![0; 128]);
  66. let tcp1_socket = TcpSocket::new(tcp1_rx_buffer, tcp1_tx_buffer);
  67. let tcp2_rx_buffer = TcpSocketBuffer::new(vec![0; 64]);
  68. let tcp2_tx_buffer = TcpSocketBuffer::new(vec![0; 128]);
  69. let tcp2_socket = TcpSocket::new(tcp2_rx_buffer, tcp2_tx_buffer);
  70. let hardware_addr = EthernetAddress([0x02, 0x00, 0x00, 0x00, 0x00, 0x01]);
  71. let protocol_addrs = [IpAddress::v4(192, 168, 69, 1)];
  72. let mut iface = EthernetInterface::new(
  73. Box::new(device), Box::new(arp_cache) as Box<ArpCache>,
  74. hardware_addr, protocol_addrs);
  75. let mut sockets = SocketSet::new(vec![]);
  76. let udp_handle = sockets.add(udp_socket);
  77. let tcp1_handle = sockets.add(tcp1_socket);
  78. let tcp2_handle = sockets.add(tcp2_socket);
  79. let mut tcp_6969_connected = false;
  80. loop {
  81. // udp:6969: respond "yo dawg"
  82. {
  83. let socket: &mut UdpSocket = sockets.get_mut(&udp_handle).as_socket();
  84. if socket.endpoint().is_unspecified() {
  85. socket.bind(6969)
  86. }
  87. let client = match socket.recv() {
  88. Ok((data, endpoint)) => {
  89. debug!("udp:6969 recv data: {:?} from {}",
  90. str::from_utf8(data.as_ref()).unwrap(), endpoint);
  91. Some(endpoint)
  92. }
  93. Err(Error::Exhausted) => {
  94. None
  95. }
  96. Err(e) => {
  97. debug!("udp:6969 recv error: {}", e);
  98. None
  99. }
  100. };
  101. if let Some(endpoint) = client {
  102. let data = b"yo dawg\n";
  103. debug!("udp:6969 send data: {:?}",
  104. str::from_utf8(data.as_ref()).unwrap());
  105. socket.send_slice(data, endpoint).unwrap();
  106. }
  107. }
  108. // tcp:6969: respond "yo dawg"
  109. {
  110. let socket: &mut TcpSocket = sockets.get_mut(&tcp1_handle).as_socket();
  111. if !socket.is_open() {
  112. socket.listen(6969).unwrap();
  113. }
  114. if socket.can_send() {
  115. let data = b"yo dawg\n";
  116. debug!("tcp:6969 send data: {:?}",
  117. str::from_utf8(data.as_ref()).unwrap());
  118. socket.send_slice(data).unwrap();
  119. debug!("tcp:6969 close");
  120. socket.close();
  121. }
  122. }
  123. // tcp:6970: echo with reverse
  124. {
  125. let socket: &mut TcpSocket = sockets.get_mut(&tcp2_handle).as_socket();
  126. if !socket.is_open() {
  127. socket.listen(6970).unwrap()
  128. }
  129. if socket.is_connected() && !tcp_6969_connected {
  130. debug!("tcp:6970 connected");
  131. } else if !socket.is_connected() && tcp_6969_connected {
  132. debug!("tcp:6970 disconnected");
  133. }
  134. tcp_6969_connected = socket.is_connected();
  135. if socket.can_recv() {
  136. let data = {
  137. let mut data = socket.recv(128).unwrap().to_owned();
  138. if data.len() > 0 {
  139. debug!("tcp:6970 recv data: {:?}",
  140. str::from_utf8(data.as_ref()).unwrap_or("(invalid utf8)"));
  141. data = data.split(|&b| b == b'\n').collect::<Vec<_>>().concat();
  142. data.reverse();
  143. data.extend(b"\n");
  144. }
  145. data
  146. };
  147. if socket.can_send() && data.len() > 0 {
  148. debug!("tcp:6970 send data: {:?}",
  149. str::from_utf8(data.as_ref()).unwrap_or("(invalid utf8)"));
  150. socket.send_slice(&data[..]).unwrap();
  151. }
  152. } else if socket.can_send() {
  153. debug!("tcp:6970 close");
  154. socket.close();
  155. }
  156. }
  157. let timestamp = Instant::now().duration_since(startup_time);
  158. let timestamp_ms = (timestamp.as_secs() * 1000) +
  159. (timestamp.subsec_nanos() / 1000000) as u64;
  160. match iface.poll(&mut sockets, timestamp_ms) {
  161. Ok(()) => (),
  162. Err(e) => debug!("poll error: {}", e)
  163. }
  164. }
  165. }