1#![deny(missing_docs)]
60
61use std::{io, time::Duration};
62
63use snafu::Snafu;
64
65mod address;
66mod follow;
67mod http;
68mod net;
69mod probe;
70mod send;
71
72pub use self::{
73 address::{Address, HostPort},
74 follow::follow,
75 http::{http_get, HttpResponse},
76 probe::probe,
77 send::send,
78};
79
80#[derive(Clone, Copy, Debug, Eq, PartialEq)]
82pub enum Fault {
83 Software,
85
86 Harness,
88}
89
90#[derive(Debug, Snafu)]
92#[snafu(visibility(pub(crate)))]
93pub enum Error {
94 #[snafu(display("invalid address '{address}': {reason}"))]
96 InvalidAddress {
97 address: String,
99 reason: &'static str,
101 },
102
103 #[snafu(display("{operation} cannot reach '{address}': {reason}"))]
105 Unsupported {
106 operation: &'static str,
108 address: Address,
110 reason: &'static str,
112 },
113
114 #[snafu(display("invalid HTTP path '{path}': it must start with '/' and hold no whitespace"))]
116 InvalidPath {
117 path: String,
119 },
120
121 #[snafu(display("failed to resolve '{host}': {source}"))]
123 Resolve {
124 host: String,
126 source: io::Error,
128 },
129
130 #[snafu(display("failed to {action} '{target}': {source}"))]
132 Target {
133 action: &'static str,
135 target: String,
137 source: io::Error,
139 },
140
141 #[snafu(display("'{address}' sent a malformed HTTP response: {reason}"))]
143 MalformedResponse {
144 address: Address,
146 reason: String,
148 },
149
150 #[snafu(display("{operation} on '{target}' did not finish within {limit:?}"))]
152 TimedOut {
153 operation: &'static str,
155 target: String,
157 limit: Duration,
159 },
160
161 #[snafu(display("failed to read input: {source}"))]
163 Input {
164 source: io::Error,
166 },
167
168 #[snafu(display("failed to write output: {source}"))]
170 Output {
171 source: io::Error,
173 },
174}
175
176impl Error {
177 pub fn fault(&self) -> Fault {
179 match self {
180 Self::Resolve { .. } | Self::Target { .. } | Self::MalformedResponse { .. } | Self::TimedOut { .. } => {
181 Fault::Software
182 }
183 Self::InvalidAddress { .. }
184 | Self::Unsupported { .. }
185 | Self::InvalidPath { .. }
186 | Self::Input { .. }
187 | Self::Output { .. } => Fault::Harness,
188 }
189 }
190}
191
192#[cfg(test)]
193mod tests {
194 use tokio::{
195 io::{AsyncReadExt as _, AsyncWriteExt as _},
196 net::TcpListener,
197 };
198
199 use super::*;
200
201 const LIMIT: Duration = Duration::from_secs(5);
202
203 async fn serve_once(response: Vec<u8>) -> Address {
205 let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
206 let address = format!("http://{}", listener.local_addr().unwrap()).parse().unwrap();
207 tokio::spawn(async move {
208 let (mut stream, _) = listener.accept().await.unwrap();
209 assert!(stream.read(&mut [0; 1024]).await.unwrap() > 0);
211 stream.write_all(&response).await.unwrap();
212 });
213 address
214 }
215
216 async fn closed_port(scheme: &str) -> Address {
218 let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
219 let port = listener.local_addr().unwrap().port();
220 drop(listener);
221 format!("{scheme}://127.0.0.1:{port}").parse().unwrap()
222 }
223
224 #[track_caller]
225 fn assert_software<T: std::fmt::Debug>(result: Result<T, Error>) -> Error {
226 let error = result.unwrap_err();
227 assert_eq!(error.fault(), Fault::Software, "{error}");
228 error
229 }
230
231 #[tokio::test]
232 async fn closed_port_is_refused_by_the_software() {
233 for scheme in ["tcp", "http", "grpc"] {
234 let error = assert_software(probe(&closed_port(scheme).await, LIMIT).await);
235 assert!(matches!(error, Error::Target { .. }), "{error}");
236 }
237 let error = assert_software(send(&closed_port("tcp").await, b"x", LIMIT).await);
238 assert!(matches!(error, Error::Target { .. }), "{error}");
239 let error = assert_software(http_get(&closed_port("http").await, "/", LIMIT).await);
240 assert!(matches!(error, Error::Target { .. }), "{error}");
241 }
242
243 #[cfg(unix)]
244 #[tokio::test]
245 async fn missing_socket_is_refused_by_the_software() {
246 let dir = tempfile::tempdir().unwrap();
247 let path = dir.path().join("missing.sock").display().to_string();
248 for scheme in ["unix", "unixgram"] {
249 let address: Address = format!("{scheme}://{path}").parse().unwrap();
250 let error = assert_software(probe(&address, LIMIT).await);
251 assert!(matches!(error, Error::Target { .. }), "{error}");
252 let error = assert_software(send(&address, b"x", LIMIT).await);
253 assert!(matches!(error, Error::Target { .. }), "{error}");
254 }
255 }
256
257 #[tokio::test]
258 async fn silent_server_times_out() {
259 let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
260 let address: Address = format!("http://{}", listener.local_addr().unwrap()).parse().unwrap();
261 let error = assert_software(http_get(&address, "/", Duration::from_millis(200)).await);
263 assert!(matches!(error, Error::TimedOut { .. }), "{error}");
264 }
265
266 #[tokio::test]
267 async fn file_that_never_appears_times_out() {
268 let dir = tempfile::tempdir().unwrap();
269 let mut out = Vec::new();
270 let result = follow(&dir.path().join("never.log"), Duration::from_millis(200), &mut out).await;
271 let error = assert_software(result);
272 assert!(matches!(error, Error::TimedOut { .. }), "{error}");
273 assert!(out.is_empty());
274 }
275
276 #[tokio::test]
277 async fn listening_port_accepts_a_probe() {
278 let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
279 let address: Address = format!("tcp://{}", listener.local_addr().unwrap()).parse().unwrap();
280 probe(&address, LIMIT).await.unwrap();
281 }
282
283 #[tokio::test]
284 async fn body_ends_at_content_length() {
285 let address = serve_once(b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nready, and more".to_vec()).await;
286 let response = http_get(&address, "/ready", LIMIT).await.unwrap();
287 assert_eq!(response.status, 200);
288 assert_eq!(response.body, b"ready");
289 }
290
291 #[tokio::test]
292 async fn body_without_content_length_ends_at_close() {
293 let address = serve_once(b"HTTP/1.0 503 Service Unavailable\r\n\r\nnot yet".to_vec()).await;
294 let response = http_get(&address, "/", LIMIT).await.unwrap();
295 assert_eq!(response.status, 503);
296 assert_eq!(response.body, b"not yet");
297 }
298
299 #[tokio::test]
300 async fn malformed_response_is_the_softwares_fault() {
301 let too_long = [&b"HTTP/1.1 200 OK\r\n\r\n"[..], &vec![b'x'; http::MAX_BODY_LEN + 1]].concat();
302 for response in [
303 b"SSH-2.0-OpenSSH\r\n\r\n".to_vec(),
304 b"HTTP/1.garbage 200 OK\r\n\r\n".to_vec(),
305 b"HTTP/1.1 +20 OK\r\n\r\n".to_vec(),
306 b"HTTP/1.1 000 OK\r\n\r\n".to_vec(),
307 b"HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nshort".to_vec(),
308 format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n", http::MAX_BODY_LEN + 1).into_bytes(),
309 too_long,
310 ] {
311 let address = serve_once(response).await;
312 let error = assert_software(http_get(&address, "/", LIMIT).await);
313 assert!(matches!(error, Error::MalformedResponse { .. }), "{error}");
314 }
315 }
316
317 #[tokio::test]
318 async fn unsupported_request_is_a_harness_fault() {
319 let udp: Address = "udp://127.0.0.1:9".parse().unwrap();
320 let http: Address = "http://127.0.0.1:9".parse().unwrap();
321 let cases = [
322 probe(&udp, LIMIT).await,
323 send(&http, b"x", LIMIT).await,
324 http_get(&udp, "/", LIMIT).await.map(drop),
325 http_get(&http, "ready", LIMIT).await.map(drop),
326 http_get(&http, "/a b", LIMIT).await.map(drop),
327 ];
328 for result in cases {
329 let error = result.unwrap_err();
330 assert_eq!(error.fault(), Fault::Harness, "{error}");
331 }
332 }
333}