server.rs 7.7 KB

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