server.rs 7.0 KB

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