server.rs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. mod utils;
  2. use log::debug;
  3. use std::collections::BTreeMap;
  4. use std::fmt::Write;
  5. use std::os::unix::io::AsRawFd;
  6. #[cfg(any(
  7. feature = "proto-sixlowpan-fragmentation",
  8. feature = "proto-ipv4-fragmentation"
  9. ))]
  10. use smoltcp::iface::ReassemblyBuffer;
  11. use smoltcp::iface::{InterfaceBuilder, NeighborCache, SocketSet};
  12. use smoltcp::phy::{wait as phy_wait, Device, Medium};
  13. use smoltcp::socket::{tcp, udp};
  14. use smoltcp::time::{Duration, Instant};
  15. use smoltcp::wire::{EthernetAddress, IpAddress, IpCidr};
  16. fn main() {
  17. utils::setup_logging("");
  18. let (mut opts, mut free) = utils::create_options();
  19. utils::add_tuntap_options(&mut opts, &mut free);
  20. utils::add_middleware_options(&mut opts, &mut free);
  21. let mut matches = utils::parse_options(&opts, free);
  22. let device = utils::parse_tuntap_options(&mut matches);
  23. let fd = device.as_raw_fd();
  24. let mut device =
  25. utils::parse_middleware_options(&mut matches, device, /*loopback=*/ false);
  26. let neighbor_cache = NeighborCache::new(BTreeMap::new());
  27. let udp_rx_buffer = udp::PacketBuffer::new(
  28. vec![udp::PacketMetadata::EMPTY, udp::PacketMetadata::EMPTY],
  29. vec![0; 65535],
  30. );
  31. let udp_tx_buffer = udp::PacketBuffer::new(
  32. vec![udp::PacketMetadata::EMPTY, udp::PacketMetadata::EMPTY],
  33. vec![0; 65535],
  34. );
  35. let udp_socket = udp::Socket::new(udp_rx_buffer, udp_tx_buffer);
  36. let tcp1_rx_buffer = tcp::SocketBuffer::new(vec![0; 64]);
  37. let tcp1_tx_buffer = tcp::SocketBuffer::new(vec![0; 128]);
  38. let tcp1_socket = tcp::Socket::new(tcp1_rx_buffer, tcp1_tx_buffer);
  39. let tcp2_rx_buffer = tcp::SocketBuffer::new(vec![0; 64]);
  40. let tcp2_tx_buffer = tcp::SocketBuffer::new(vec![0; 128]);
  41. let tcp2_socket = tcp::Socket::new(tcp2_rx_buffer, tcp2_tx_buffer);
  42. let tcp3_rx_buffer = tcp::SocketBuffer::new(vec![0; 65535]);
  43. let tcp3_tx_buffer = tcp::SocketBuffer::new(vec![0; 65535]);
  44. let tcp3_socket = tcp::Socket::new(tcp3_rx_buffer, tcp3_tx_buffer);
  45. let tcp4_rx_buffer = tcp::SocketBuffer::new(vec![0; 65535]);
  46. let tcp4_tx_buffer = tcp::SocketBuffer::new(vec![0; 65535]);
  47. let tcp4_socket = tcp::Socket::new(tcp4_rx_buffer, tcp4_tx_buffer);
  48. let ethernet_addr = EthernetAddress([0x02, 0x00, 0x00, 0x00, 0x00, 0x01]);
  49. let ip_addrs = [
  50. IpCidr::new(IpAddress::v4(192, 168, 69, 1), 24),
  51. IpCidr::new(IpAddress::v6(0xfdaa, 0, 0, 0, 0, 0, 0, 1), 64),
  52. IpCidr::new(IpAddress::v6(0xfe80, 0, 0, 0, 0, 0, 0, 1), 64),
  53. ];
  54. let medium = device.capabilities().medium;
  55. let mut builder = InterfaceBuilder::new().ip_addrs(ip_addrs);
  56. builder = builder.random_seed(
  57. std::time::SystemTime::now()
  58. .duration_since(std::time::UNIX_EPOCH)
  59. .unwrap()
  60. .as_secs(),
  61. );
  62. #[cfg(feature = "proto-ipv4-fragmentation")]
  63. let mut ipv4_out_packet_cache = [0u8; 10_000];
  64. #[cfg(feature = "proto-ipv4-fragmentation")]
  65. {
  66. let ipv4_frag_cache = ReassemblyBuffer::new(vec![], BTreeMap::new());
  67. builder = builder
  68. .ipv4_reassembly_buffer(ipv4_frag_cache)
  69. .ipv4_fragmentation_buffer(&mut ipv4_out_packet_cache[..]);
  70. }
  71. #[cfg(feature = "proto-sixlowpan-fragmentation")]
  72. let mut sixlowpan_out_packet_cache = [0u8; 1280];
  73. #[cfg(feature = "proto-sixlowpan-fragmentation")]
  74. {
  75. let sixlowpan_frag_cache = ReassemblyBuffer::new(vec![], BTreeMap::new());
  76. builder = builder
  77. .sixlowpan_reassembly_buffer(sixlowpan_frag_cache)
  78. .sixlowpan_fragmentation_buffer(&mut sixlowpan_out_packet_cache[..]);
  79. }
  80. if medium == Medium::Ethernet {
  81. builder = builder
  82. .hardware_addr(ethernet_addr.into())
  83. .neighbor_cache(neighbor_cache);
  84. }
  85. let mut iface = builder.finalize(&mut device);
  86. let mut sockets = SocketSet::new(vec![]);
  87. let udp_handle = sockets.add(udp_socket);
  88. let tcp1_handle = sockets.add(tcp1_socket);
  89. let tcp2_handle = sockets.add(tcp2_socket);
  90. let tcp3_handle = sockets.add(tcp3_socket);
  91. let tcp4_handle = sockets.add(tcp4_socket);
  92. let mut tcp_6970_active = false;
  93. loop {
  94. let timestamp = Instant::now();
  95. match iface.poll(timestamp, &mut device, &mut sockets) {
  96. Ok(_) => {}
  97. Err(e) => {
  98. debug!("poll error: {}", e);
  99. }
  100. }
  101. // udp:6969: respond "hello"
  102. let socket = sockets.get_mut::<udp::Socket>(udp_handle);
  103. if !socket.is_open() {
  104. socket.bind(6969).unwrap()
  105. }
  106. let client = match socket.recv() {
  107. Ok((data, endpoint)) => {
  108. debug!("udp:6969 recv data: {:?} from {}", data, endpoint);
  109. let mut data = data.to_vec();
  110. data.reverse();
  111. Some((endpoint, data))
  112. }
  113. Err(_) => None,
  114. };
  115. if let Some((endpoint, data)) = client {
  116. debug!("udp:6969 send data: {:?} to {}", data, endpoint,);
  117. socket.send_slice(&data, endpoint).unwrap();
  118. }
  119. // tcp:6969: respond "hello"
  120. let socket = sockets.get_mut::<tcp::Socket>(tcp1_handle);
  121. if !socket.is_open() {
  122. socket.listen(6969).unwrap();
  123. }
  124. if socket.can_send() {
  125. debug!("tcp:6969 send greeting");
  126. writeln!(socket, "hello").unwrap();
  127. debug!("tcp:6969 close");
  128. socket.close();
  129. }
  130. // tcp:6970: echo with reverse
  131. let socket = sockets.get_mut::<tcp::Socket>(tcp2_handle);
  132. if !socket.is_open() {
  133. socket.listen(6970).unwrap()
  134. }
  135. if socket.is_active() && !tcp_6970_active {
  136. debug!("tcp:6970 connected");
  137. } else if !socket.is_active() && tcp_6970_active {
  138. debug!("tcp:6970 disconnected");
  139. }
  140. tcp_6970_active = socket.is_active();
  141. if socket.may_recv() {
  142. let data = socket
  143. .recv(|buffer| {
  144. let recvd_len = buffer.len();
  145. let mut data = buffer.to_owned();
  146. if !data.is_empty() {
  147. debug!("tcp:6970 recv data: {:?}", data);
  148. data = data.split(|&b| b == b'\n').collect::<Vec<_>>().concat();
  149. data.reverse();
  150. data.extend(b"\n");
  151. }
  152. (recvd_len, data)
  153. })
  154. .unwrap();
  155. if socket.can_send() && !data.is_empty() {
  156. debug!("tcp:6970 send data: {:?}", data);
  157. socket.send_slice(&data[..]).unwrap();
  158. }
  159. } else if socket.may_send() {
  160. debug!("tcp:6970 close");
  161. socket.close();
  162. }
  163. // tcp:6971: sinkhole
  164. let socket = sockets.get_mut::<tcp::Socket>(tcp3_handle);
  165. if !socket.is_open() {
  166. socket.listen(6971).unwrap();
  167. socket.set_keep_alive(Some(Duration::from_millis(1000)));
  168. socket.set_timeout(Some(Duration::from_millis(2000)));
  169. }
  170. if socket.may_recv() {
  171. socket
  172. .recv(|buffer| {
  173. if !buffer.is_empty() {
  174. debug!("tcp:6971 recv {:?} octets", buffer.len());
  175. }
  176. (buffer.len(), ())
  177. })
  178. .unwrap();
  179. } else if socket.may_send() {
  180. socket.close();
  181. }
  182. // tcp:6972: fountain
  183. let socket = sockets.get_mut::<tcp::Socket>(tcp4_handle);
  184. if !socket.is_open() {
  185. socket.listen(6972).unwrap()
  186. }
  187. if socket.may_send() {
  188. socket
  189. .send(|data| {
  190. if !data.is_empty() {
  191. debug!("tcp:6972 send {:?} octets", data.len());
  192. for (i, b) in data.iter_mut().enumerate() {
  193. *b = (i % 256) as u8;
  194. }
  195. }
  196. (data.len(), ())
  197. })
  198. .unwrap();
  199. }
  200. phy_wait(fd, iface.poll_delay(timestamp, &sockets)).expect("wait error");
  201. }
  202. }