server.rs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. #[macro_use]
  2. extern crate log;
  3. extern crate env_logger;
  4. extern crate getopts;
  5. extern crate smoltcp;
  6. mod utils;
  7. use std::str;
  8. use std::collections::BTreeMap;
  9. use std::fmt::Write;
  10. use std::time::Instant;
  11. use std::os::unix::io::AsRawFd;
  12. use smoltcp::phy::wait as phy_wait;
  13. use smoltcp::wire::{EthernetAddress, IpAddress, IpCidr};
  14. use smoltcp::iface::{NeighborCache, EthernetInterfaceBuilder};
  15. use smoltcp::socket::SocketSet;
  16. use smoltcp::socket::{UdpSocket, UdpSocketBuffer, UdpPacketBuffer};
  17. use smoltcp::socket::{TcpSocket, TcpSocketBuffer};
  18. fn main() {
  19. utils::setup_logging("");
  20. let (mut opts, mut free) = utils::create_options();
  21. utils::add_tap_options(&mut opts, &mut free);
  22. utils::add_middleware_options(&mut opts, &mut free);
  23. let mut matches = utils::parse_options(&opts, free);
  24. let device = utils::parse_tap_options(&mut matches);
  25. let fd = device.as_raw_fd();
  26. let device = utils::parse_middleware_options(&mut matches, device, /*loopback=*/false);
  27. let startup_time = Instant::now();
  28. let neighbor_cache = NeighborCache::new(BTreeMap::new());
  29. let udp_rx_buffer = UdpSocketBuffer::new(vec![UdpPacketBuffer::new(vec![0; 64])]);
  30. let udp_tx_buffer = UdpSocketBuffer::new(vec![UdpPacketBuffer::new(vec![0; 128])]);
  31. let udp_socket = UdpSocket::new(udp_rx_buffer, udp_tx_buffer);
  32. let tcp1_rx_buffer = TcpSocketBuffer::new(vec![0; 64]);
  33. let tcp1_tx_buffer = TcpSocketBuffer::new(vec![0; 128]);
  34. let tcp1_socket = TcpSocket::new(tcp1_rx_buffer, tcp1_tx_buffer);
  35. let tcp2_rx_buffer = TcpSocketBuffer::new(vec![0; 64]);
  36. let tcp2_tx_buffer = TcpSocketBuffer::new(vec![0; 128]);
  37. let tcp2_socket = TcpSocket::new(tcp2_rx_buffer, tcp2_tx_buffer);
  38. let tcp3_rx_buffer = TcpSocketBuffer::new(vec![0; 65535]);
  39. let tcp3_tx_buffer = TcpSocketBuffer::new(vec![0; 65535]);
  40. let tcp3_socket = TcpSocket::new(tcp3_rx_buffer, tcp3_tx_buffer);
  41. let tcp4_rx_buffer = TcpSocketBuffer::new(vec![0; 65535]);
  42. let tcp4_tx_buffer = TcpSocketBuffer::new(vec![0; 65535]);
  43. let tcp4_socket = TcpSocket::new(tcp4_rx_buffer, tcp4_tx_buffer);
  44. let ethernet_addr = EthernetAddress([0x02, 0x00, 0x00, 0x00, 0x00, 0x01]);
  45. let ip_addrs = [IpCidr::new(IpAddress::v4(192, 168, 69, 1), 24)];
  46. let mut iface = EthernetInterfaceBuilder::new(device)
  47. .ethernet_addr(ethernet_addr)
  48. .neighbor_cache(neighbor_cache)
  49. .ip_addrs(ip_addrs)
  50. .finalize();
  51. let mut sockets = SocketSet::new(vec![]);
  52. let udp_handle = sockets.add(udp_socket);
  53. let tcp1_handle = sockets.add(tcp1_socket);
  54. let tcp2_handle = sockets.add(tcp2_socket);
  55. let tcp3_handle = sockets.add(tcp3_socket);
  56. let tcp4_handle = sockets.add(tcp4_socket);
  57. let mut tcp_6970_active = false;
  58. loop {
  59. // udp:6969: respond "hello"
  60. {
  61. let mut socket = sockets.get::<UdpSocket>(udp_handle);
  62. if !socket.is_open() {
  63. socket.bind(6969).unwrap()
  64. }
  65. let client = match socket.recv() {
  66. Ok((data, endpoint)) => {
  67. debug!("udp:6969 recv data: {:?} from {}",
  68. str::from_utf8(data.as_ref()).unwrap(), endpoint);
  69. Some(endpoint)
  70. }
  71. Err(_) => None
  72. };
  73. if let Some(endpoint) = client {
  74. let data = b"hello\n";
  75. debug!("udp:6969 send data: {:?}",
  76. str::from_utf8(data.as_ref()).unwrap());
  77. socket.send_slice(data, endpoint).unwrap();
  78. }
  79. }
  80. // tcp:6969: respond "hello"
  81. {
  82. let mut socket = sockets.get::<TcpSocket>(tcp1_handle);
  83. if !socket.is_open() {
  84. socket.listen(6969).unwrap();
  85. }
  86. if socket.can_send() {
  87. debug!("tcp:6969 send greeting");
  88. write!(socket, "hello\n").unwrap();
  89. debug!("tcp:6969 close");
  90. socket.close();
  91. }
  92. }
  93. // tcp:6970: echo with reverse
  94. {
  95. let mut socket = sockets.get::<TcpSocket>(tcp2_handle);
  96. if !socket.is_open() {
  97. socket.listen(6970).unwrap()
  98. }
  99. if socket.is_active() && !tcp_6970_active {
  100. debug!("tcp:6970 connected");
  101. } else if !socket.is_active() && tcp_6970_active {
  102. debug!("tcp:6970 disconnected");
  103. }
  104. tcp_6970_active = socket.is_active();
  105. if socket.may_recv() {
  106. let data = socket.recv(|buffer| {
  107. let mut data = buffer.to_owned();
  108. if data.len() > 0 {
  109. debug!("tcp:6970 recv data: {:?}",
  110. str::from_utf8(data.as_ref()).unwrap_or("(invalid utf8)"));
  111. data = data.split(|&b| b == b'\n').collect::<Vec<_>>().concat();
  112. data.reverse();
  113. data.extend(b"\n");
  114. }
  115. (data.len(), data)
  116. }).unwrap();
  117. if socket.can_send() && data.len() > 0 {
  118. debug!("tcp:6970 send data: {:?}",
  119. str::from_utf8(data.as_ref()).unwrap_or("(invalid utf8)"));
  120. socket.send_slice(&data[..]).unwrap();
  121. }
  122. } else if socket.may_send() {
  123. debug!("tcp:6970 close");
  124. socket.close();
  125. }
  126. }
  127. // tcp:6971: sinkhole
  128. {
  129. let mut socket = sockets.get::<TcpSocket>(tcp3_handle);
  130. if !socket.is_open() {
  131. socket.listen(6971).unwrap();
  132. socket.set_keep_alive(Some(1000));
  133. socket.set_timeout(Some(2000));
  134. }
  135. if socket.may_recv() {
  136. socket.recv(|buffer| {
  137. if buffer.len() > 0 {
  138. debug!("tcp:6971 recv {:?} octets", buffer.len());
  139. }
  140. (buffer.len(), ())
  141. }).unwrap();
  142. } else if socket.may_send() {
  143. socket.close();
  144. }
  145. }
  146. // tcp:6972: fountain
  147. {
  148. let mut socket = sockets.get::<TcpSocket>(tcp4_handle);
  149. if !socket.is_open() {
  150. socket.listen(6972).unwrap()
  151. }
  152. if socket.may_send() {
  153. socket.send(|data| {
  154. if data.len() > 0 {
  155. debug!("tcp:6972 send {:?} octets", data.len());
  156. for (i, b) in data.iter_mut().enumerate() {
  157. *b = (i % 256) as u8;
  158. }
  159. }
  160. (data.len(), ())
  161. }).unwrap();
  162. }
  163. }
  164. let timestamp = utils::millis_since(startup_time);
  165. let poll_at = iface.poll(&mut sockets, timestamp).expect("poll error");
  166. phy_wait(fd, poll_at.map(|at| at.saturating_sub(timestamp))).expect("wait error");
  167. }
  168. }