httpclient.rs 4.5 KB

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