server.rs 7.2 KB

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