server.rs 7.9 KB

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