httpclient.rs 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  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 url::Url;
  7. use smoltcp::iface::{InterfaceBuilder, NeighborCache, Routes, SocketSet};
  8. use smoltcp::phy::{wait as phy_wait, Device, Medium};
  9. use smoltcp::socket::tcp;
  10. use smoltcp::time::Instant;
  11. use smoltcp::wire::{EthernetAddress, IpAddress, IpCidr, Ipv4Address, Ipv6Address};
  12. fn main() {
  13. utils::setup_logging("");
  14. let (mut opts, mut free) = utils::create_options();
  15. utils::add_tuntap_options(&mut opts, &mut free);
  16. utils::add_middleware_options(&mut opts, &mut free);
  17. free.push("ADDRESS");
  18. free.push("URL");
  19. let mut matches = utils::parse_options(&opts, free);
  20. let device = utils::parse_tuntap_options(&mut matches);
  21. let fd = device.as_raw_fd();
  22. let mut device =
  23. utils::parse_middleware_options(&mut matches, device, /*loopback=*/ false);
  24. let address = IpAddress::from_str(&matches.free[0]).expect("invalid address format");
  25. let url = Url::parse(&matches.free[1]).expect("invalid url format");
  26. let neighbor_cache = NeighborCache::new(BTreeMap::new());
  27. let tcp_rx_buffer = tcp::SocketBuffer::new(vec![0; 1024]);
  28. let tcp_tx_buffer = tcp::SocketBuffer::new(vec![0; 1024]);
  29. let tcp_socket = tcp::Socket::new(tcp_rx_buffer, tcp_tx_buffer);
  30. let ethernet_addr = EthernetAddress([0x02, 0x00, 0x00, 0x00, 0x00, 0x02]);
  31. let ip_addrs = [
  32. IpCidr::new(IpAddress::v4(192, 168, 69, 1), 24),
  33. IpCidr::new(IpAddress::v6(0xfdaa, 0, 0, 0, 0, 0, 0, 1), 64),
  34. IpCidr::new(IpAddress::v6(0xfe80, 0, 0, 0, 0, 0, 0, 1), 64),
  35. ];
  36. let default_v4_gw = Ipv4Address::new(192, 168, 69, 100);
  37. let default_v6_gw = Ipv6Address::new(0xfe80, 0, 0, 0, 0, 0, 0, 0x100);
  38. let mut routes_storage = [None; 2];
  39. let mut routes = Routes::new(&mut routes_storage[..]);
  40. routes.add_default_ipv4_route(default_v4_gw).unwrap();
  41. routes.add_default_ipv6_route(default_v6_gw).unwrap();
  42. let medium = device.capabilities().medium;
  43. let mut builder = InterfaceBuilder::new().ip_addrs(ip_addrs).routes(routes);
  44. if medium == Medium::Ethernet {
  45. builder = builder
  46. .hardware_addr(ethernet_addr.into())
  47. .neighbor_cache(neighbor_cache);
  48. }
  49. let mut iface = builder.finalize(&mut device);
  50. let mut sockets = SocketSet::new(vec![]);
  51. let tcp_handle = sockets.add(tcp_socket);
  52. enum State {
  53. Connect,
  54. Request,
  55. Response,
  56. }
  57. let mut state = State::Connect;
  58. loop {
  59. let timestamp = Instant::now();
  60. match iface.poll(timestamp, &mut device, &mut sockets) {
  61. Ok(_) => {}
  62. Err(e) => {
  63. debug!("poll error: {}", e);
  64. }
  65. }
  66. let socket = sockets.get_mut::<tcp::Socket>(tcp_handle);
  67. let cx = &mut iface;
  68. state = match state {
  69. State::Connect if !socket.is_active() => {
  70. debug!("connecting");
  71. let local_port = 49152 + rand::random::<u16>() % 16384;
  72. socket
  73. .connect(cx, (address, url.port().unwrap_or(80)), local_port)
  74. .unwrap();
  75. State::Request
  76. }
  77. State::Request if socket.may_send() => {
  78. debug!("sending request");
  79. let http_get = "GET ".to_owned() + url.path() + " HTTP/1.1\r\n";
  80. socket.send_slice(http_get.as_ref()).expect("cannot send");
  81. let http_host = "Host: ".to_owned() + url.host_str().unwrap() + "\r\n";
  82. socket.send_slice(http_host.as_ref()).expect("cannot send");
  83. socket
  84. .send_slice(b"Connection: close\r\n")
  85. .expect("cannot send");
  86. socket.send_slice(b"\r\n").expect("cannot send");
  87. State::Response
  88. }
  89. State::Response if socket.can_recv() => {
  90. socket
  91. .recv(|data| {
  92. println!("{}", str::from_utf8(data).unwrap_or("(invalid utf8)"));
  93. (data.len(), ())
  94. })
  95. .unwrap();
  96. State::Response
  97. }
  98. State::Response if !socket.may_recv() => {
  99. debug!("received complete response");
  100. break;
  101. }
  102. _ => state,
  103. };
  104. phy_wait(fd, iface.poll_delay(timestamp, &sockets)).expect("wait error");
  105. }
  106. }