client.rs 4.6 KB

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