server.rs 7.2 KB

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