client.rs 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  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::ReassemblyBuffer;
  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. let mut ipv4_out_packet_cache = [0u8; 1280];
  44. #[cfg(feature = "proto-ipv4-fragmentation")]
  45. {
  46. let ipv4_frag_cache = ReassemblyBuffer::new(vec![], BTreeMap::new());
  47. builder = builder
  48. .ipv4_reassembly_buffer(ipv4_frag_cache)
  49. .ipv4_fragmentation_buffer(&mut ipv4_out_packet_cache[..]);
  50. }
  51. #[cfg(feature = "proto-sixlowpan-fragmentation")]
  52. let mut sixlowpan_out_packet_cache = [0u8; 1280];
  53. #[cfg(feature = "proto-sixlowpan-fragmentation")]
  54. {
  55. let sixlowpan_frag_cache = ReassemblyBuffer::new(vec![], BTreeMap::new());
  56. builder = builder
  57. .sixlowpan_reassembly_buffer(sixlowpan_frag_cache)
  58. .sixlowpan_fragmentation_buffer(&mut sixlowpan_out_packet_cache[..]);
  59. }
  60. if medium == Medium::Ethernet {
  61. builder = builder
  62. .hardware_addr(ethernet_addr.into())
  63. .neighbor_cache(neighbor_cache);
  64. }
  65. let mut iface = builder.finalize(&mut device);
  66. let mut sockets = SocketSet::new(vec![]);
  67. let tcp_handle = sockets.add(tcp_socket);
  68. let socket = sockets.get_mut::<tcp::Socket>(tcp_handle);
  69. socket
  70. .connect(iface.context(), (address, port), 49500)
  71. .unwrap();
  72. let mut tcp_active = false;
  73. loop {
  74. let timestamp = Instant::now();
  75. match iface.poll(timestamp, &mut device, &mut sockets) {
  76. Ok(_) => {}
  77. Err(e) => {
  78. debug!("poll error: {}", e);
  79. }
  80. }
  81. let socket = sockets.get_mut::<tcp::Socket>(tcp_handle);
  82. if socket.is_active() && !tcp_active {
  83. debug!("connected");
  84. } else if !socket.is_active() && tcp_active {
  85. debug!("disconnected");
  86. break;
  87. }
  88. tcp_active = socket.is_active();
  89. if socket.may_recv() {
  90. let data = socket
  91. .recv(|data| {
  92. let mut data = data.to_owned();
  93. if !data.is_empty() {
  94. debug!(
  95. "recv data: {:?}",
  96. str::from_utf8(data.as_ref()).unwrap_or("(invalid utf8)")
  97. );
  98. data = data.split(|&b| b == b'\n').collect::<Vec<_>>().concat();
  99. data.reverse();
  100. data.extend(b"\n");
  101. }
  102. (data.len(), data)
  103. })
  104. .unwrap();
  105. if socket.can_send() && !data.is_empty() {
  106. debug!(
  107. "send data: {:?}",
  108. str::from_utf8(data.as_ref()).unwrap_or("(invalid utf8)")
  109. );
  110. socket.send_slice(&data[..]).unwrap();
  111. }
  112. } else if socket.may_send() {
  113. debug!("close");
  114. socket.close();
  115. }
  116. phy_wait(fd, iface.poll_delay(timestamp, &sockets)).expect("wait error");
  117. }
  118. }