server.rs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  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. let timestamp = utils::millis_since(startup_time);
  60. iface.poll(&mut sockets, timestamp).expect("poll error");
  61. // udp:6969: respond "hello"
  62. {
  63. let mut socket = sockets.get::<UdpSocket>(udp_handle);
  64. if !socket.is_open() {
  65. socket.bind(6969).unwrap()
  66. }
  67. let client = match socket.recv() {
  68. Ok((data, endpoint)) => {
  69. debug!("udp:6969 recv data: {:?} from {}",
  70. str::from_utf8(data.as_ref()).unwrap(), endpoint);
  71. Some(endpoint)
  72. }
  73. Err(_) => None
  74. };
  75. if let Some(endpoint) = client {
  76. let data = b"hello\n";
  77. debug!("udp:6969 send data: {:?}",
  78. str::from_utf8(data.as_ref()).unwrap());
  79. socket.send_slice(data, endpoint).unwrap();
  80. }
  81. }
  82. // tcp:6969: respond "hello"
  83. {
  84. let mut socket = sockets.get::<TcpSocket>(tcp1_handle);
  85. if !socket.is_open() {
  86. socket.listen(6969).unwrap();
  87. }
  88. if socket.can_send() {
  89. debug!("tcp:6969 send greeting");
  90. write!(socket, "hello\n").unwrap();
  91. debug!("tcp:6969 close");
  92. socket.close();
  93. }
  94. }
  95. // tcp:6970: echo with reverse
  96. {
  97. let mut socket = sockets.get::<TcpSocket>(tcp2_handle);
  98. if !socket.is_open() {
  99. socket.listen(6970).unwrap()
  100. }
  101. if socket.is_active() && !tcp_6970_active {
  102. debug!("tcp:6970 connected");
  103. } else if !socket.is_active() && tcp_6970_active {
  104. debug!("tcp:6970 disconnected");
  105. }
  106. tcp_6970_active = socket.is_active();
  107. if socket.may_recv() {
  108. let data = socket.recv(|buffer| {
  109. let mut data = buffer.to_owned();
  110. if data.len() > 0 {
  111. debug!("tcp:6970 recv data: {:?}",
  112. str::from_utf8(data.as_ref()).unwrap_or("(invalid utf8)"));
  113. data = data.split(|&b| b == b'\n').collect::<Vec<_>>().concat();
  114. data.reverse();
  115. data.extend(b"\n");
  116. }
  117. (data.len(), data)
  118. }).unwrap();
  119. if socket.can_send() && data.len() > 0 {
  120. debug!("tcp:6970 send data: {:?}",
  121. str::from_utf8(data.as_ref()).unwrap_or("(invalid utf8)"));
  122. socket.send_slice(&data[..]).unwrap();
  123. }
  124. } else if socket.may_send() {
  125. debug!("tcp:6970 close");
  126. socket.close();
  127. }
  128. }
  129. // tcp:6971: sinkhole
  130. {
  131. let mut socket = sockets.get::<TcpSocket>(tcp3_handle);
  132. if !socket.is_open() {
  133. socket.listen(6971).unwrap();
  134. socket.set_keep_alive(Some(1000));
  135. socket.set_timeout(Some(2000));
  136. }
  137. if socket.may_recv() {
  138. socket.recv(|buffer| {
  139. if buffer.len() > 0 {
  140. debug!("tcp:6971 recv {:?} octets", buffer.len());
  141. }
  142. (buffer.len(), ())
  143. }).unwrap();
  144. } else if socket.may_send() {
  145. socket.close();
  146. }
  147. }
  148. // tcp:6972: fountain
  149. {
  150. let mut socket = sockets.get::<TcpSocket>(tcp4_handle);
  151. if !socket.is_open() {
  152. socket.listen(6972).unwrap()
  153. }
  154. if socket.may_send() {
  155. socket.send(|data| {
  156. if data.len() > 0 {
  157. debug!("tcp:6972 send {:?} octets", data.len());
  158. for (i, b) in data.iter_mut().enumerate() {
  159. *b = (i % 256) as u8;
  160. }
  161. }
  162. (data.len(), ())
  163. }).unwrap();
  164. }
  165. }
  166. phy_wait(fd, iface.poll_delay(&sockets, timestamp)).expect("wait error");
  167. }
  168. }