1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
|
mod error_document;
use crate::model::Settings;
use anyhow::{Result, anyhow, ensure};
use futures_util::TryStreamExt;
use serde::{Deserialize, Serialize};
use std::time::{Duration, Instant};
use tokio::io::AsyncReadExt;
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Observation {
pub configuration_id: String,
pub generation: u64,
pub kind: String,
pub success: bool,
pub elapsed_ms: u64,
pub bytes: u64,
pub bytes_per_second: Option<f64>,
pub stop_reason: String,
pub retry_after_seconds: Option<u64>,
}
/// The caller supplies an authenticated, service-owned HTTPS proxy endpoint. This client
/// never inherits environment proxies or creates a direct route to the target.
pub async fn measure(
settings: &Settings,
proxy: &str,
certificate: &str,
id: String,
generation: u64,
speed: bool,
) -> Result<Observation> {
settings.validate()?;
let started = Instant::now();
let duration = if speed {
settings.maximum_duration_seconds
} else {
5
};
let deadline = tokio::time::Instant::now() + Duration::from_secs(duration);
let cap = if speed {
settings.maximum_download_mib * 1_048_576
} else {
4096
};
let proxy =
reqwest::Proxy::all(proxy).map_err(|_| anyhow!("Invalid protected probe endpoint"))?;
let certificate = reqwest::Certificate::from_pem(certificate.as_bytes())
.map_err(|_| anyhow!("Invalid private probe certificate"))?;
let client = reqwest::Client::builder()
.no_proxy()
.proxy(proxy)
.redirect(reqwest::redirect::Policy::none())
.tls_certs_merge([certificate])
.retry(reqwest::retry::never())
.user_agent(concat!("Roentgen/", env!("CARGO_PKG_VERSION")))
.build()
.map_err(|_| anyhow!("Could not initialize diagnostic TLS client"))?;
let url = if speed {
&settings.speed_url
} else {
&settings.ping_url
};
let response = tokio::time::timeout_at(deadline, client.get(url).send())
.await
.map_err(|_| anyhow!("Diagnostic request reached its deadline"))?
.map_err(|_| anyhow!("Proxied HTTPS request failed"))?;
if response.status().as_u16() == 429 || response.status().as_u16() == 503 {
let retry = response
.headers()
.get("Retry-After")
.and_then(|v| v.to_str().ok())
.and_then(|v| {
v.parse::<u64>().ok().or_else(|| {
httpdate::parse_http_date(v)
.ok()
.and_then(|date| date.duration_since(std::time::SystemTime::now()).ok())
.map(|d| d.as_secs().saturating_add(1))
})
})
.unwrap_or(30)
.max(30);
return Ok(Observation {
configuration_id: id,
generation,
kind: if speed { "speed" } else { "ping" }.into(),
success: false,
elapsed_ms: started.elapsed().as_millis() as u64,
bytes: 0,
bytes_per_second: None,
stop_reason: "provider-rate-limit".into(),
retry_after_seconds: Some(retry),
});
}
ensure!(
response.status().as_u16() == 200 || !speed && response.status().as_u16() == 204,
"Diagnostic endpoint returned an unexpected HTTP status"
);
let content_type = response
.headers()
.get("Content-Type")
.and_then(|v| v.to_str().ok())
.unwrap_or("")
.to_ascii_lowercase();
ensure!(
!content_type.contains("html"),
"Diagnostic endpoint returned HTML"
);
ensure!(
!content_type.contains("application/problem+"),
"Diagnostic endpoint returned an error document"
);
let status = response.status().as_u16();
let stream = response.bytes_stream().map_err(std::io::Error::other);
let mut reader = tokio_util::io::StreamReader::new(stream);
let mut buffer = [0u8; 16384];
let mut prefix = Vec::new();
let mut error_document = error_document::ErrorDocument::default();
let mut bytes = 0;
let reason;
loop {
if speed && bytes == cap {
reason = "byte-limit";
break;
}
let remaining = if speed {
(cap - bytes).min(buffer.len() as u64) as usize
} else {
buffer.len().min((cap + 1 - bytes) as usize)
};
let chunk =
match tokio::time::timeout_at(deadline, reader.read(&mut buffer[..remaining])).await {
Err(_) if speed && bytes > 0 => {
reason = "duration-limit";
break;
}
Err(_) => return Err(anyhow!("Diagnostic response timed out")),
Ok(Err(_)) => {
return Err(anyhow!(
"Diagnostic response failed before clean completion"
));
}
Ok(Ok(value)) => value,
};
if chunk == 0 {
reason = "complete";
break;
}
if prefix.len() < 512 {
let mut inspect = &buffer[..chunk];
if prefix.is_empty() {
inspect = inspect.trim_ascii_start();
while inspect
.first()
.is_some_and(|byte| matches!(byte, 0xef | 0xbb | 0xbf))
{
inspect = inspect[1..].trim_ascii_start();
}
}
prefix.extend_from_slice(&inspect[..inspect.len().min(512 - prefix.len())]);
}
error_document.feed(&buffer[..chunk]);
ensure!(
!error_document.confirmed_error(),
"Diagnostic endpoint returned an error document"
);
bytes += chunk as u64;
if !speed {
ensure!(bytes <= cap, "Ping body exceeds 4 KiB");
}
}
let prefix = String::from_utf8_lossy(&prefix)
.trim_start()
.to_ascii_lowercase();
ensure!(
!prefix.starts_with("<!doctype html") && !prefix.starts_with("<html"),
"Diagnostic endpoint returned an HTML document"
);
ensure!(
!error_document.is_error(),
"Diagnostic endpoint returned an error document"
);
ensure!(!speed || bytes > 0, "Speed response contained no data");
if !speed && settings.ping_url == Settings::default().ping_url {
ensure!(
bytes == 0 && status == 200,
"Default Ping must complete with HTTP 200 and an empty body"
);
}
let elapsed = started.elapsed();
Ok(Observation {
configuration_id: id,
generation,
kind: if speed { "speed" } else { "ping" }.into(),
success: true,
elapsed_ms: elapsed.as_millis() as u64,
bytes,
bytes_per_second: speed.then(|| bytes as f64 / elapsed.as_secs_f64().max(0.000_001)),
stop_reason: reason.into(),
retry_after_seconds: None,
})
}
|