server.rs 7.1 KB

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