client.rs 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. mod utils;
  2. use log::debug;
  3. use std::collections::BTreeMap;
  4. use std::os::unix::io::AsRawFd;
  5. use std::str::{self, FromStr};
  6. use smoltcp::iface::{InterfaceBuilder, NeighborCache, Routes, SocketSet};
  7. use smoltcp::phy::{wait as phy_wait, Device, Medium};
  8. use smoltcp::socket::tcp;
  9. use smoltcp::time::Instant;
  10. use smoltcp::wire::{EthernetAddress, IpAddress, IpCidr, Ipv4Address};
  11. fn main() {
  12. utils::setup_logging("");
  13. let (mut opts, mut free) = utils::create_options();
  14. utils::add_tuntap_options(&mut opts, &mut free);
  15. utils::add_middleware_options(&mut opts, &mut free);
  16. free.push("ADDRESS");
  17. free.push("PORT");
  18. let mut matches = utils::parse_options(&opts, free);
  19. let device = utils::parse_tuntap_options(&mut matches);
  20. let fd = device.as_raw_fd();
  21. let mut device =
  22. utils::parse_middleware_options(&mut matches, device, /*loopback=*/ false);
  23. let address = IpAddress::from_str(&matches.free[0]).expect("invalid address format");
  24. let port = u16::from_str(&matches.free[1]).expect("invalid port format");
  25. let neighbor_cache = NeighborCache::new(BTreeMap::new());
  26. let tcp_rx_buffer = tcp::SocketBuffer::new(vec![0; 64]);
  27. let tcp_tx_buffer = tcp::SocketBuffer::new(vec![0; 128]);
  28. let tcp_socket = tcp::Socket::new(tcp_rx_buffer, tcp_tx_buffer);
  29. let ethernet_addr = EthernetAddress([0x02, 0x00, 0x00, 0x00, 0x00, 0x02]);
  30. let ip_addrs = [IpCidr::new(IpAddress::v4(192, 168, 69, 2), 24)];
  31. let default_v4_gw = Ipv4Address::new(192, 168, 69, 100);
  32. let mut routes_storage = [None; 1];
  33. let mut routes = Routes::new(&mut routes_storage[..]);
  34. routes.add_default_ipv4_route(default_v4_gw).unwrap();
  35. let medium = device.capabilities().medium;
  36. let mut builder = InterfaceBuilder::new().ip_addrs(ip_addrs).routes(routes);
  37. if medium == Medium::Ethernet {
  38. builder = builder
  39. .hardware_addr(ethernet_addr.into())
  40. .neighbor_cache(neighbor_cache);
  41. }
  42. let mut iface = builder.finalize(&mut device);
  43. let mut sockets = SocketSet::new(vec![]);
  44. let tcp_handle = sockets.add(tcp_socket);
  45. let socket = sockets.get_mut::<tcp::Socket>(tcp_handle);
  46. socket.connect(&mut iface, (address, port), 49500).unwrap();
  47. let mut tcp_active = false;
  48. loop {
  49. let timestamp = Instant::now();
  50. match iface.poll(timestamp, &mut device, &mut sockets) {
  51. Ok(_) => {}
  52. Err(e) => {
  53. debug!("poll error: {}", e);
  54. }
  55. }
  56. let socket = sockets.get_mut::<tcp::Socket>(tcp_handle);
  57. if socket.is_active() && !tcp_active {
  58. debug!("connected");
  59. } else if !socket.is_active() && tcp_active {
  60. debug!("disconnected");
  61. break;
  62. }
  63. tcp_active = socket.is_active();
  64. if socket.may_recv() {
  65. let data = socket
  66. .recv(|data| {
  67. let mut data = data.to_owned();
  68. if !data.is_empty() {
  69. debug!(
  70. "recv data: {:?}",
  71. str::from_utf8(data.as_ref()).unwrap_or("(invalid utf8)")
  72. );
  73. data = data.split(|&b| b == b'\n').collect::<Vec<_>>().concat();
  74. data.reverse();
  75. data.extend(b"\n");
  76. }
  77. (data.len(), data)
  78. })
  79. .unwrap();
  80. if socket.can_send() && !data.is_empty() {
  81. debug!(
  82. "send data: {:?}",
  83. str::from_utf8(data.as_ref()).unwrap_or("(invalid utf8)")
  84. );
  85. socket.send_slice(&data[..]).unwrap();
  86. }
  87. } else if socket.may_send() {
  88. debug!("close");
  89. socket.close();
  90. }
  91. phy_wait(fd, iface.poll_delay(timestamp, &sockets)).expect("wait error");
  92. }
  93. }