1use crate::error::NetError;
2use crate::module::transport::failure::{ConnectStage, ConnectionFailure};
3use http::header::{HeaderName, HeaderValue, CONTENT_TYPE, RETRY_AFTER};
4use http::HeaderMap;
5use serde::de::{DeserializeSeed, IgnoredAny, MapAccess, SeqAccess, Visitor};
6use std::fmt;
7
8const MAX_ALLOWLIST_CODES: usize = 32;
9const MAX_CODE_BYTES: usize = 64;
10const MAX_BODY_INPUT_BYTES: usize = 16 * 1024;
11const MAX_HEADER_VALUE_BYTES: usize = 128;
12
13#[derive(Clone, Default)]
21pub struct HandshakeDiagnosticOptions {
22 pub public_json_codes: Vec<String>,
25}
26
27impl HandshakeDiagnosticOptions {
28 pub fn validate(&self) -> crate::Result<()> {
39 if self.public_json_codes.len() > MAX_ALLOWLIST_CODES {
40 return Err(NetError::config(
41 "diagnostics.public_json_codes",
42 "must contain at most 32 public codes, including duplicates",
43 ));
44 }
45 for code in &self.public_json_codes {
46 if code.is_empty()
47 || code.len() > MAX_CODE_BYTES
48 || !code
49 .bytes()
50 .all(|byte| byte.is_ascii_uppercase() || byte.is_ascii_digit() || byte == b'_')
51 {
52 return Err(NetError::config(
53 "diagnostics.public_json_codes",
54 "each public code must contain 1–64 ASCII uppercase letters, digits or underscores",
55 ));
56 }
57 }
58 Ok(())
59 }
60}
61
62impl fmt::Debug for HandshakeDiagnosticOptions {
63 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
64 formatter
65 .debug_struct("HandshakeDiagnosticOptions")
66 .field("public_json_code_count", &self.public_json_codes.len())
67 .finish()
68 }
69}
70
71#[non_exhaustive]
74#[derive(Clone, Copy, Debug, Eq, PartialEq)]
75pub enum HandshakeDiagnosticKind {
76 HttpRejected,
78 Io(
81 std::io::ErrorKind,
83 ),
84 TlsCertificate,
86 TlsProtocol,
88 Protocol,
90 Timeout,
92 Dns,
94 Local,
96 Other,
98}
99
100#[non_exhaustive]
102#[derive(Clone, Copy, Debug, Eq, PartialEq)]
103pub enum HandshakeBodyCaptureState {
104 Omitted,
106 Unavailable,
108 Incomplete,
110 Unsupported,
112 TooLarge,
114 Unrecognized,
116 Captured,
118}
119
120#[derive(Clone)]
131pub struct HandshakeDiagnostic {
132 kind: HandshakeDiagnosticKind,
134 headers: HeaderMap,
136 body_summary: Option<String>,
138 body_capture_state: HandshakeBodyCaptureState,
140}
141
142impl HandshakeDiagnostic {
143 pub(crate) fn new(kind: HandshakeDiagnosticKind) -> Self {
144 Self {
145 kind,
146 headers: HeaderMap::new(),
147 body_summary: None,
148 body_capture_state: HandshakeBodyCaptureState::Unavailable,
149 }
150 }
151
152 pub(crate) fn http<'a>(
153 options: &HandshakeDiagnosticOptions,
154 headers: impl Iterator<Item = (&'a str, &'a [u8])>,
155 body: Option<&[u8]>,
156 ) -> Self {
157 let metadata = HttpMetadata::read(headers);
158 let mut diagnostic = Self::new(HandshakeDiagnosticKind::HttpRejected);
159 if let Some(content_type) = metadata.json_content_type() {
160 diagnostic.retain_header(CONTENT_TYPE, content_type);
161 }
162 if let Some(seconds) = metadata.retry_after.unique().and_then(parse_decimal) {
163 let mut normalized = String::new();
166 if normalized.try_reserve_exact(20).is_ok() {
167 use std::fmt::Write;
168 if write!(&mut normalized, "{seconds}").is_ok() {
169 diagnostic.retain_header(RETRY_AFTER, &normalized);
170 } else {
171 log_capture_allocation_failure();
172 }
173 } else {
174 log_capture_allocation_failure();
175 }
176 }
177 let (state, summary) = capture_body(options, &metadata, body);
178 diagnostic.body_capture_state = state;
179 diagnostic.body_summary = summary;
180 diagnostic
181 }
182
183 pub(crate) fn from_failure(failure: ConnectionFailure) -> Self {
184 use HandshakeDiagnosticKind as Kind;
185 let kind = if failure.http_status().is_some() {
186 Kind::HttpRejected
187 } else if failure.error().kind() == crate::error::ErrorKind::TimedOut {
188 Kind::Timeout
189 } else {
190 match failure.stage() {
191 ConnectStage::Provider
192 | ConnectStage::RequestBuild
193 | ConnectStage::EventDelivery => Kind::Local,
194 ConnectStage::Dns => Kind::Dns,
195 ConnectStage::Tls | ConnectStage::ProxyTls => Kind::TlsProtocol,
196 _ if failure.error().kind() == crate::error::ErrorKind::Tls => Kind::TlsProtocol,
197 _ if failure.error().kind() == crate::error::ErrorKind::Protocol => Kind::Protocol,
198 _ => Kind::Other,
199 }
200 };
201 Self::new(kind)
202 }
203
204 fn retain_header(&mut self, name: HeaderName, value: &str) {
205 let Some(value) = try_owned(value) else {
206 return;
207 };
208 let Ok(value) = HeaderValue::from_maybe_shared(bytes::Bytes::from(value)) else {
209 return;
210 };
211 if self.headers.try_insert(name, value).is_err() {
212 log_capture_allocation_failure();
213 }
214 }
215
216 pub fn kind(&self) -> HandshakeDiagnosticKind {
218 self.kind
219 }
220 pub fn headers(&self) -> &HeaderMap {
222 &self.headers
223 }
224 pub fn body_summary(&self) -> Option<&str> {
226 self.body_summary.as_deref()
227 }
228 pub fn body_capture_state(&self) -> HandshakeBodyCaptureState {
230 self.body_capture_state
231 }
232}
233
234fn try_owned(value: &str) -> Option<String> {
235 let mut owned = String::new();
236 if owned.try_reserve_exact(value.len()).is_err() {
237 log_capture_allocation_failure();
238 return None;
239 }
240 owned.push_str(value);
241 Some(owned)
242}
243
244fn log_capture_allocation_failure() {
245 crate::log_e!(crate::common::log::log_def::LogType::WSC; "handshake_diagnostic", "error", "safe_capture_allocation_failed");
246}
247
248#[derive(Default)]
251struct HeaderField<'a> {
252 value: Option<&'a [u8]>,
254 duplicate: bool,
256}
257
258impl<'a> HeaderField<'a> {
259 fn insert(&mut self, value: &'a [u8]) {
260 if self.value.is_some() {
261 self.duplicate = true;
262 } else {
263 self.value = Some(value);
264 }
265 }
266
267 fn unique(&self) -> Option<&'a [u8]> {
268 if self.duplicate {
269 None
270 } else {
271 self.value
272 }
273 }
274}
275
276#[derive(Default)]
279struct HttpMetadata<'a> {
280 content_type: HeaderField<'a>,
282 content_length: HeaderField<'a>,
284 content_encoding: HeaderField<'a>,
287 retry_after: HeaderField<'a>,
290 transfer_encoding: bool,
293}
294
295impl<'a> HttpMetadata<'a> {
296 fn read(headers: impl Iterator<Item = (&'a str, &'a [u8])>) -> Self {
297 let mut metadata = Self::default();
298 for (name, value) in headers {
299 if name.eq_ignore_ascii_case("content-type") {
300 metadata.content_type.insert(value);
301 } else if name.eq_ignore_ascii_case("content-length") {
302 metadata.content_length.insert(value);
303 } else if name.eq_ignore_ascii_case("content-encoding") {
304 metadata.content_encoding.insert(value);
305 } else if name.eq_ignore_ascii_case("retry-after") {
306 metadata.retry_after.insert(value);
307 } else if name.eq_ignore_ascii_case("transfer-encoding") {
308 metadata.transfer_encoding = true;
309 }
310 }
311 metadata
312 }
313
314 fn json_content_type(&self) -> Option<&'static str> {
315 let value = self.content_type.unique()?;
316 if value.len() > MAX_HEADER_VALUE_BYTES {
317 return None;
318 }
319 let media_type = trim_ows(value.split(|byte| *byte == b';').next()?);
320 if media_type.eq_ignore_ascii_case(b"application/json") {
321 Some("application/json")
322 } else if media_type.eq_ignore_ascii_case(b"application/problem+json") {
323 Some("application/problem+json")
324 } else {
325 None
326 }
327 }
328
329 fn has_supported_encoding(&self) -> bool {
330 if self.transfer_encoding || self.content_encoding.duplicate {
331 return false;
332 }
333 match self.content_encoding.value {
334 None => true,
335 Some(value) => {
336 value.len() <= MAX_HEADER_VALUE_BYTES
337 && trim_ows(value).eq_ignore_ascii_case(b"identity")
338 }
339 }
340 }
341}
342
343fn trim_ows(mut value: &[u8]) -> &[u8] {
344 while let Some((byte, rest)) = value.split_first() {
345 if matches!(byte, b' ' | b'\t') {
346 value = rest;
347 } else {
348 break;
349 }
350 }
351 while let Some((byte, rest)) = value.split_last() {
352 if matches!(byte, b' ' | b'\t') {
353 value = rest;
354 } else {
355 break;
356 }
357 }
358 value
359}
360
361fn parse_decimal(value: &[u8]) -> Option<u64> {
362 if value.len() > MAX_HEADER_VALUE_BYTES {
363 return None;
364 }
365 let value = trim_ows(value);
366 if value.is_empty() || !value.iter().all(u8::is_ascii_digit) {
367 return None;
368 }
369 std::str::from_utf8(value).ok()?.parse().ok()
370}
371
372fn capture_body(
373 options: &HandshakeDiagnosticOptions,
374 metadata: &HttpMetadata<'_>,
375 body: Option<&[u8]>,
376) -> (HandshakeBodyCaptureState, Option<String>) {
377 use HandshakeBodyCaptureState as State;
378 if options.public_json_codes.is_empty() {
379 return (State::Omitted, None);
380 }
381 let Some(body) = body.filter(|body| !body.is_empty()) else {
382 return (State::Unavailable, None);
383 };
384 if body.len() > MAX_BODY_INPUT_BYTES {
385 return (State::TooLarge, None);
386 }
387 if metadata.json_content_type().is_none()
388 || !metadata.has_supported_encoding()
389 || metadata.content_length.duplicate
390 {
391 return (State::Unsupported, None);
392 }
393 let Some(length) = metadata.content_length.unique() else {
394 return (State::Incomplete, None);
395 };
396 let Some(length) = parse_decimal(length) else {
397 return (State::Unsupported, None);
398 };
399 if length > MAX_BODY_INPUT_BYTES as u64 {
400 return (State::TooLarge, None);
401 }
402 if length != body.len() as u64 {
403 return (State::Incomplete, None);
404 }
405 if std::str::from_utf8(body).is_err() {
406 return (State::Unsupported, None);
407 }
408 let mut deserializer = serde_json::Deserializer::from_slice(body);
409 let selected = CodeObjectSeed {
410 codes: &options.public_json_codes,
411 }
412 .deserialize(&mut deserializer);
413 let Ok(selected) = selected else {
414 return (State::Unsupported, None);
415 };
416 if deserializer.end().is_err() {
417 return (State::Unsupported, None);
418 }
419 let Some(code) = selected.and_then(|index| options.public_json_codes.get(index)) else {
420 return (State::Unrecognized, None);
421 };
422 let mut summary = String::new();
423 if summary
424 .try_reserve_exact("code=".len() + code.len())
425 .is_err()
426 {
427 log_capture_allocation_failure();
428 return (State::Unavailable, None);
429 }
430 summary.push_str("code=");
431 summary.push_str(code);
432 (State::Captured, Some(summary))
433}
434
435struct CodeObjectSeed<'a> {
439 codes: &'a [String],
441}
442
443impl<'de> DeserializeSeed<'de> for CodeObjectSeed<'_> {
444 type Value = Option<usize>;
445
446 fn deserialize<D: serde::Deserializer<'de>>(
447 self,
448 deserializer: D,
449 ) -> Result<Self::Value, D::Error> {
450 deserializer.deserialize_map(self)
451 }
452}
453
454impl<'de> Visitor<'de> for CodeObjectSeed<'_> {
455 type Value = Option<usize>;
456
457 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
458 formatter.write_str("a JSON object with at most one top-level code")
459 }
460
461 fn visit_map<M: MapAccess<'de>>(self, mut map: M) -> Result<Self::Value, M::Error> {
462 let mut seen_code = false;
463 let mut selected = None;
464 while let Some(is_code) = map.next_key_seed(CodeKeySeed)? {
465 if is_code {
466 if seen_code {
467 return Err(serde::de::Error::custom("duplicate diagnostic code"));
468 }
469 seen_code = true;
470 selected = map.next_value_seed(CodeValueSeed { codes: self.codes })?;
471 } else {
472 map.next_value::<IgnoredAny>()?;
473 }
474 }
475 Ok(selected)
476 }
477}
478
479struct CodeKeySeed;
481
482impl<'de> DeserializeSeed<'de> for CodeKeySeed {
483 type Value = bool;
484
485 fn deserialize<D: serde::Deserializer<'de>>(self, deserializer: D) -> Result<bool, D::Error> {
486 deserializer.deserialize_str(self)
487 }
488}
489
490impl Visitor<'_> for CodeKeySeed {
491 type Value = bool;
492
493 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
494 formatter.write_str("a JSON object key")
495 }
496
497 fn visit_str<E: serde::de::Error>(self, key: &str) -> Result<bool, E> {
498 Ok(key == "code")
499 }
500}
501
502struct CodeValueSeed<'a> {
505 codes: &'a [String],
507}
508
509impl<'de> DeserializeSeed<'de> for CodeValueSeed<'_> {
510 type Value = Option<usize>;
511
512 fn deserialize<D: serde::Deserializer<'de>>(
513 self,
514 deserializer: D,
515 ) -> Result<Self::Value, D::Error> {
516 deserializer.deserialize_any(self)
517 }
518}
519
520impl<'de> Visitor<'de> for CodeValueSeed<'_> {
521 type Value = Option<usize>;
522
523 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
524 formatter.write_str("a public diagnostic code")
525 }
526
527 fn visit_str<E: serde::de::Error>(self, code: &str) -> Result<Self::Value, E> {
528 Ok(self.codes.iter().position(|allowed| allowed == code))
529 }
530
531 fn visit_bool<E: serde::de::Error>(self, _value: bool) -> Result<Self::Value, E> {
532 Ok(None)
533 }
534 fn visit_i64<E: serde::de::Error>(self, _value: i64) -> Result<Self::Value, E> {
535 Ok(None)
536 }
537 fn visit_u64<E: serde::de::Error>(self, _value: u64) -> Result<Self::Value, E> {
538 Ok(None)
539 }
540 fn visit_f64<E: serde::de::Error>(self, _value: f64) -> Result<Self::Value, E> {
541 Ok(None)
542 }
543 fn visit_unit<E: serde::de::Error>(self) -> Result<Self::Value, E> {
544 Ok(None)
545 }
546
547 fn visit_seq<S: SeqAccess<'de>>(self, mut sequence: S) -> Result<Self::Value, S::Error> {
548 while sequence.next_element::<IgnoredAny>()?.is_some() {}
549 Ok(None)
550 }
551
552 fn visit_map<M: MapAccess<'de>>(self, mut map: M) -> Result<Self::Value, M::Error> {
553 while map.next_entry::<IgnoredAny, IgnoredAny>()?.is_some() {}
554 Ok(None)
555 }
556}
557
558impl fmt::Debug for HandshakeDiagnostic {
559 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
560 formatter
561 .debug_struct("HandshakeDiagnostic")
562 .field("kind", &self.kind)
563 .field("header_count", &self.headers.len())
564 .field(
565 "body_summary_bytes",
566 &self.body_summary.as_ref().map(String::len),
567 )
568 .field("body_capture_state", &self.body_capture_state)
569 .finish()
570 }
571}
572
573#[cfg(test)]
574#[path = "handshake_diagnostic_tests.rs"]
575mod tests;
576
577#[cfg(test)]
578#[path = "handshake_diagnostic_api_tests.rs"]
579mod api_tests;