http_stat/
http_request.rs1use super::error::{Error, Result};
19use super::stats::{HttpStat, ALPN_HTTP1, ALPN_HTTP2};
20use bytes::Bytes;
21use http::request::Builder;
22use http::HeaderValue;
23use http::Request;
24use http::Uri;
25use http::{HeaderMap, Method};
26use http_body_util::Full;
27use rustls::client::{ClientSessionMemoryCache, ClientSessionStore};
28use std::net::IpAddr;
29use std::str::FromStr;
30use std::sync::Arc;
31use std::time::Duration;
32use std::time::Instant;
33
34const VERSION: &str = env!("CARGO_PKG_VERSION");
36
37pub(crate) fn finish_with_error(
39 mut stat: HttpStat,
40 error: impl ToString,
41 start: Instant,
42) -> HttpStat {
43 stat.error = Some(error.to_string());
44 stat.total = Some(start.elapsed());
45 stat
46}
47
48#[derive(Debug, Clone)]
57pub struct ConnectTo {
58 src_host: String,
59 src_port: Option<u16>,
60 pub dst_host: String,
61 pub dst_port: Option<u16>,
62}
63
64fn parse_host_segment(s: &str) -> (String, &str) {
65 if let Some(rest) = s.strip_prefix('[') {
66 if let Some(end) = rest.find(']') {
68 return (rest[..end].to_string(), &rest[end + 1..]);
69 }
70 }
71 let colon = s.find(':').unwrap_or(s.len());
73 (s[..colon].to_string(), &s[colon..])
74}
75
76impl ConnectTo {
77 pub fn parse(s: &str) -> Option<Self> {
79 let (src_host, rest) = parse_host_segment(s);
80 let rest = rest.strip_prefix(':')?; let colon = rest.find(':')?;
84 let src_port = if rest[..colon].is_empty() {
85 None
86 } else {
87 Some(rest[..colon].parse().ok()?)
88 };
89 let rest = &rest[colon + 1..];
90
91 let (dst_host, rest) = parse_host_segment(rest);
93
94 let port2_str = rest.strip_prefix(':').unwrap_or(rest);
96 let dst_port = if port2_str.is_empty() {
97 None
98 } else {
99 Some(port2_str.parse().ok()?)
100 };
101
102 Some(ConnectTo {
103 src_host,
104 src_port,
105 dst_host,
106 dst_port,
107 })
108 }
109
110 pub fn matches(&self, host: &str, port: u16) -> bool {
112 let host_ok = self.src_host.is_empty() || self.src_host.eq_ignore_ascii_case(host);
113 let port_ok = self.src_port.is_none() || self.src_port == Some(port);
114 host_ok && port_ok
115 }
116}
117
118#[derive(Default, Debug, Clone)]
120pub struct HttpRequest {
121 pub uri: Uri, pub method: Option<String>, pub alpn_protocols: Vec<String>, pub resolve: Option<IpAddr>, pub headers: Option<HeaderMap<HeaderValue>>, pub ip_version: Option<i32>, pub skip_verify: bool, pub body: Option<Bytes>, pub dns_servers: Option<Vec<String>>, pub dns_timeout: Option<Duration>, pub tcp_timeout: Option<Duration>, pub tls_timeout: Option<Duration>, pub request_timeout: Option<Duration>, pub quic_timeout: Option<Duration>, pub client_cert: Option<Vec<u8>>, pub client_key: Option<Vec<u8>>, pub proxy: Option<String>, pub use_absolute_uri: bool, pub connect_to: Vec<String>, pub bind_addr: Option<IpAddr>, pub tls_session_store: Option<Arc<dyn ClientSessionStore>>,
147}
148
149impl HttpRequest {
150 pub fn get_port(&self) -> u16 {
151 let schema = if let Some(scheme) = self.uri.scheme() {
152 scheme.to_string()
153 } else {
154 "".to_string()
155 };
156
157 let default_port = if ["https", "grpcs"].contains(&schema.as_str()) {
158 443
159 } else {
160 80
161 };
162 self.uri.port_u16().unwrap_or(default_port)
163 }
164 pub fn builder(&self, is_http1: bool) -> Builder {
166 let uri = &self.uri;
167 let method = if let Some(method) = &self.method {
168 Method::from_str(method).unwrap_or(Method::GET)
169 } else {
170 Method::GET
171 };
172 let mut builder = if is_http1 && !self.use_absolute_uri {
173 if let Some(value) = uri.path_and_query() {
174 Request::builder().uri(value.to_string())
175 } else {
176 Request::builder().uri(uri)
177 }
178 } else {
179 Request::builder().uri(uri)
180 };
181 builder = builder.method(method);
182 let mut set_host = false;
183 let mut set_user_agent = false;
184
185 if let Some(headers) = &self.headers {
187 for (key, value) in headers.iter() {
188 builder = builder.header(key, value);
189 match key.to_string().to_lowercase().as_str() {
190 "host" => set_host = true,
191 "user-agent" => set_user_agent = true,
192 _ => {}
193 }
194 }
195 }
196
197 if !set_host {
199 if let Some(host) = uri.host() {
200 let port = self.get_port();
201 if port != 80 && port != 443 {
202 builder = builder.header("Host", format!("{host}:{port}"));
203 } else {
204 builder = builder.header("Host", host);
205 }
206 }
207 }
208
209 if !set_user_agent {
211 builder = builder.header("User-Agent", format!("httpstat.rs/{VERSION}"));
212 }
213 builder
214 }
215}
216
217pub fn new_tls_session_store(capacity: usize) -> Arc<dyn ClientSessionStore> {
222 Arc::new(ClientSessionMemoryCache::new(capacity))
223}
224
225impl TryFrom<&str> for HttpRequest {
227 type Error = Error;
228
229 fn try_from(url: &str) -> Result<Self> {
230 let prefixes = ["http://", "https://", "grpc://", "grpcs://"];
231
232 let value = if prefixes.iter().any(|prefix| url.starts_with(prefix)) {
233 url.to_string()
234 } else {
235 format!("http://{url}")
236 };
237 let uri = value.parse::<Uri>().map_err(|e| Error::Uri { source: e })?;
238 Ok(Self {
239 uri,
240 alpn_protocols: vec![ALPN_HTTP2.to_string(), ALPN_HTTP1.to_string()],
241 ..Default::default()
242 })
243 }
244}
245
246impl TryFrom<&HttpRequest> for Request<Full<Bytes>> {
248 type Error = Error;
249 fn try_from(req: &HttpRequest) -> Result<Self> {
250 req.builder(true)
251 .body(Full::new(req.body.clone().unwrap_or_default()))
252 .map_err(|e| Error::Http { source: e })
253 }
254}