server.rs 7.2 KB

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