1use super::{Body, Conn, Transport, TypeSet};
2use crate::{ClientHandler, ConnExt, Error, Result, Version};
3use smallvec::SmallVec;
4#[cfg(feature = "hickory")]
5use std::net::IpAddr;
6use std::{
7 borrow::Cow,
8 fmt::{self, Debug, Formatter},
9 future::{Future, IntoFuture},
10 mem,
11 net::SocketAddr,
12 pin::Pin,
13};
14use trillium_http::{ProtocolSession, Upgrade};
15use trillium_server_common::Destination;
16
17#[cfg(any(feature = "serde_json", feature = "sonic-rs"))]
21#[derive(thiserror::Error, Debug)]
22pub enum ClientSerdeError {
23 #[error(transparent)]
25 HttpError(#[from] Error),
26
27 #[cfg(feature = "sonic-rs")]
28 #[error(transparent)]
30 JsonError(#[from] sonic_rs::Error),
31
32 #[cfg(feature = "serde_json")]
33 #[error(transparent)]
35 JsonError(#[from] serde_json::Error),
36}
37
38impl Conn {
39 pub(crate) async fn exec(&mut self) -> Result<()> {
40 if let Some(error) = self.error.take() {
44 return Err(error);
45 }
46
47 let handler = self.client.arc_handler().clone();
49 handler.run(self).await?;
50
51 if !self.halted {
52 if let Err(e) = self.exec_network().await {
55 self.error = Some(e);
56 }
57 } else {
58 log::trace!("conn is halted, skipping network round-trip");
59 self.request_body = None;
64 }
65
66 handler.after_response(self).await?;
68
69 if let Some(e) = self.error.take() {
70 Err(e)
71 } else {
72 Ok(())
73 }
74 }
75
76 async fn exec_network(&mut self) -> Result<()> {
77 self.select_route();
78 if self.http_version == Some(Version::Http0_9) {
79 return Err(Error::UnsupportedVersion(Version::Http0_9));
80 }
81 #[cfg(feature = "webtransport")]
84 if self.protocol.as_deref() == Some("webtransport") && !self.h3_permitted() {
85 return Err(crate::webtransport::Http3Unavailable.into());
86 }
87
88 match self.exec_network_dispatch().await {
89 Err(Error::ExtendedConnectUnsupported)
95 if !self.strict_http_version && self.protocol.is_some() =>
96 {
97 log::debug!(
98 "peer does not support extended CONNECT; retrying as an HTTP/1.1 upgrade"
99 );
100 self.http_version = Some(Version::Http1_1);
101 self.headers_finalized = false;
102 self.exec_h1_or_promote_h2().await
103 }
104 other => other,
105 }
106 }
107
108 async fn exec_network_dispatch(&mut self) -> Result<()> {
109 if self.try_reuse_h3_pool().await? {
115 return Ok(());
116 }
117 if !self.route.is_forward() && self.try_exec_h2_pooled().await? {
118 return Ok(());
119 }
120
121 if self.try_establish_h3().await? {
124 return Ok(());
125 }
126
127 if self.http_version == Some(Version::Http2) {
131 return self.exec_h2_prior_knowledge().await;
132 }
133
134 self.exec_h1_or_promote_h2().await
135 }
136
137 pub(crate) fn body_len(&self) -> Option<u64> {
138 if let Some(ref body) = self.request_body {
139 body.len()
140 } else {
141 Some(0)
142 }
143 }
144
145 pub(crate) fn finalize_headers(&mut self) -> Result<()> {
146 match self.http_version() {
147 Version::Http1_0 | Version::Http1_1 => self.finalize_headers_h1(),
148 Version::Http2 => self.finalize_headers_h2(),
149 Version::Http3 if self.client.h3().is_some() => self.finalize_headers_h3(),
150 other => Err(Error::UnsupportedVersion(other)),
151 }
152 }
153
154 pub(crate) async fn origin_destination(&self) -> Result<Destination> {
163 let mut destination = Destination::from_url(&self.url)?;
164 let addrs = if self.route.is_direct() {
165 self.origin_socket_addrs().await?
166 } else {
167 SmallVec::new()
168 };
169 if !addrs.is_empty() {
170 destination.set_addrs(addrs);
171 }
172 match self.http_version {
173 Some(Version::Http1_0 | Version::Http1_1) => {
174 destination.set_alpn([Cow::Borrowed(b"http/1.1".as_slice())]);
175 }
176 Some(Version::Http2) => {
177 destination.set_alpn([Cow::Borrowed(b"h2".as_slice())]);
178 }
179 _ => {}
180 }
181 Ok(destination)
182 }
183
184 pub(crate) async fn origin_socket_addrs(&self) -> Result<SmallVec<[SocketAddr; 4]>> {
188 let Some(host) = self.url.host_str() else {
189 return Ok(SmallVec::new());
190 };
191 let port = self.url.port_or_known_default().unwrap_or(443);
192 self.resolve_socket_addrs(host, port).await
193 }
194}
195
196#[cfg(feature = "hickory")]
197impl Conn {
198 pub(crate) async fn resolve(
211 &self,
212 host: &str,
213 port: u16,
214 ) -> Result<Option<crate::dns::Resolved>> {
215 if host.parse::<IpAddr>().is_ok() {
216 return Ok(None);
217 }
218 match &self.client.resolver {
219 Some(resolver) => Ok(Some(
220 resolver
221 .resolve(&self.client, host, port, self.timeout)
222 .await?,
223 )),
224 None => Ok(None),
225 }
226 }
227
228 pub(crate) async fn resolve_socket_addrs(
229 &self,
230 host: &str,
231 port: u16,
232 ) -> Result<SmallVec<[SocketAddr; 4]>> {
233 Ok(self
234 .resolve(host, port)
235 .await?
236 .map(|resolved| resolved.socket_addrs(port))
237 .unwrap_or_default())
238 }
239}
240
241#[cfg(not(feature = "hickory"))]
242impl Conn {
243 pub(crate) async fn resolve_socket_addrs(
244 &self,
245 _host: &str,
246 _port: u16,
247 ) -> Result<SmallVec<[SocketAddr; 4]>> {
248 Ok(SmallVec::new())
249 }
250}
251
252impl Drop for Conn {
253 fn drop(&mut self) {
254 log::trace!("dropping client conn");
255 drop(self.take_response_body());
256 }
257}
258
259impl From<Conn> for Body {
260 fn from(mut conn: Conn) -> Body {
261 if let Some(body) = conn.body_override.take() {
264 return body;
265 }
266
267 match conn.take_received_body(true) {
268 Some(rb) => rb.into(),
269 None => Body::default(),
270 }
271 }
272}
273
274impl From<Conn> for Upgrade<Box<dyn Transport>> {
275 fn from(mut conn: Conn) -> Self {
284 let path = conn.path.take().unwrap_or_else(|| match conn.url.query() {
287 Some(q) => Cow::Owned(format!("{}?{q}", conn.url.path())),
288 None => Cow::Owned(conn.url.path().to_owned()),
289 });
290 let secure = conn.url.scheme() == "https";
291
292 Upgrade::from_parts(
293 mem::take(&mut conn.response_headers),
294 mem::take(&mut conn.request_headers),
295 path,
296 conn.method,
297 conn.transport
298 .take()
299 .expect("client conn has no transport — request not yet sent"),
300 mem::take(&mut conn.buffer),
301 mem::take(&mut conn.state),
302 conn.context.clone(),
303 None,
304 conn.authority.take(),
305 conn.scheme.take(),
306 mem::replace(&mut conn.protocol_session, ProtocolSession::Http1),
307 conn.protocol.take(),
308 conn.http_version(),
309 conn.status,
310 secure,
311 mem::take(&mut conn.response_body_state),
313 conn.response_trailers.take(),
316 )
317 }
318}
319
320impl IntoFuture for Conn {
321 type IntoFuture = Pin<Box<dyn Future<Output = Self::Output> + Send + 'static>>;
322 type Output = Result<Conn>;
323
324 fn into_future(mut self) -> Self::IntoFuture {
325 Box::pin(async move { (&mut self).await.map(|()| self) })
326 }
327}
328
329impl<'conn> IntoFuture for &'conn mut Conn {
330 type IntoFuture = Pin<Box<dyn Future<Output = Self::Output> + Send + 'conn>>;
331 type Output = Result<()>;
332
333 fn into_future(self) -> Self::IntoFuture {
334 Box::pin(async move {
335 loop {
338 let result = if let Some(duration) = self.timeout {
339 self.client
340 .connector()
341 .runtime()
342 .timeout(duration, self.exec())
343 .await
344 .unwrap_or(Err(Error::TimedOut("Conn", duration)))
345 } else {
346 self.exec().await
347 };
348
349 self.halted = false;
351
352 if let Err(e) = result {
353 self.followup = None;
356 return Err(e);
357 }
358
359 let Some(next) = self.take_followup() else {
360 break;
361 };
362
363 if let Some(body) = self.take_response_body() {
364 body.recycle().await;
365 }
366
367 let _displaced = mem::replace(self, next);
368 }
369 Ok(())
370 })
371 }
372}
373
374impl Debug for Conn {
375 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
376 f.debug_struct("Conn")
377 .field("authority", &self.authority)
378 .field("buffer", &String::from_utf8_lossy(&self.buffer))
379 .field("client", &self.client)
380 .field("protocol_session", &self.protocol_session)
381 .field("http_version", &self.http_version)
382 .field("method", &self.method)
383 .field("path", &self.path)
384 .field("request_body", &self.request_body)
385 .field("request_headers", &self.request_headers)
386 .field("request_target", &self.request_target)
387 .field("request_trailers", &self.request_trailers)
388 .field("response_body_state", &self.response_body_state)
389 .field("response_headers", &self.response_headers)
390 .field("response_trailers", &self.response_trailers)
391 .field("scheme", &self.scheme)
392 .field("state", &self.state)
393 .field("status", &self.status)
394 .field("url", &self.url)
395 .finish()
396 }
397}
398
399impl AsRef<TypeSet> for Conn {
400 fn as_ref(&self) -> &TypeSet {
401 &self.state
402 }
403}
404
405impl AsMut<TypeSet> for Conn {
406 fn as_mut(&mut self) -> &mut TypeSet {
407 &mut self.state
408 }
409}