httpclient.rs 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. mod utils;
  2. use log::debug;
  3. use std::os::unix::io::AsRawFd;
  4. use std::str::{self, FromStr};
  5. use url::Url;
  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, Ipv6Address};
  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("URL");
  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 url = Url::parse(&matches.free[1]).expect("invalid url format");
  25. let neighbor_cache = NeighborCache::new();
  26. let tcp_rx_buffer = tcp::SocketBuffer::new(vec![0; 1024]);
  27. let tcp_tx_buffer = tcp::SocketBuffer::new(vec![0; 1024]);
  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 mut ip_addrs = heapless::Vec::<IpCidr, 5>::new();
  31. ip_addrs
  32. .push(IpCidr::new(IpAddress::v4(192, 168, 69, 1), 24))
  33. .unwrap();
  34. ip_addrs
  35. .push(IpCidr::new(IpAddress::v6(0xfdaa, 0, 0, 0, 0, 0, 0, 1), 64))
  36. .unwrap();
  37. ip_addrs
  38. .push(IpCidr::new(IpAddress::v6(0xfe80, 0, 0, 0, 0, 0, 0, 1), 64))
  39. .unwrap();
  40. let default_v4_gw = Ipv4Address::new(192, 168, 69, 100);
  41. let default_v6_gw = Ipv6Address::new(0xfe80, 0, 0, 0, 0, 0, 0, 0x100);
  42. let mut routes = Routes::new();
  43. routes.add_default_ipv4_route(default_v4_gw).unwrap();
  44. routes.add_default_ipv6_route(default_v6_gw).unwrap();
  45. let medium = device.capabilities().medium;
  46. let mut builder = InterfaceBuilder::new().ip_addrs(ip_addrs).routes(routes);
  47. if medium == Medium::Ethernet {
  48. builder = builder
  49. .hardware_addr(ethernet_addr.into())
  50. .neighbor_cache(neighbor_cache);
  51. }
  52. let mut iface = builder.finalize(&mut device);
  53. let mut sockets = SocketSet::new(vec![]);
  54. let tcp_handle = sockets.add(tcp_socket);
  55. enum State {
  56. Connect,
  57. Request,
  58. Response,
  59. }
  60. let mut state = State::Connect;
  61. loop {
  62. let timestamp = Instant::now();
  63. iface.poll(timestamp, &mut device, &mut sockets);
  64. let socket = sockets.get_mut::<tcp::Socket>(tcp_handle);
  65. let cx = iface.context();
  66. state = match state {
  67. State::Connect if !socket.is_active() => {
  68. debug!("connecting");
  69. let local_port = 49152 + rand::random::<u16>() % 16384;
  70. socket
  71. .connect(cx, (address, url.port().unwrap_or(80)), local_port)
  72. .unwrap();
  73. State::Request
  74. }
  75. State::Request if socket.may_send() => {
  76. debug!("sending request");
  77. let http_get = "GET ".to_owned() + url.path() + " HTTP/1.1\r\n";
  78. socket.send_slice(http_get.as_ref()).expect("cannot send");
  79. let http_host = "Host: ".to_owned() + url.host_str().unwrap() + "\r\n";
  80. socket.send_slice(http_host.as_ref()).expect("cannot send");
  81. socket
  82. .send_slice(b"Connection: close\r\n")
  83. .expect("cannot send");
  84. socket.send_slice(b"\r\n").expect("cannot send");
  85. State::Response
  86. }
  87. State::Response if socket.can_recv() => {
  88. socket
  89. .recv(|data| {
  90. println!("{}", str::from_utf8(data).unwrap_or("(invalid utf8)"));
  91. (data.len(), ())
  92. })
  93. .unwrap();
  94. State::Response
  95. }
  96. State::Response if !socket.may_recv() => {
  97. debug!("received complete response");
  98. break;
  99. }
  100. _ => state,
  101. };
  102. phy_wait(fd, iface.poll_delay(timestamp, &sockets)).expect("wait error");
  103. }
  104. }