httpclient.rs 4.3 KB

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