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
use std::io::{ErrorKind, Read, Write};
use std::net::TcpStream;
use std::time::Duration;
use std::{error, str};
use crate::{resolve, DEFAULT_CONNECT_TIMEOUT, READ_CONNECT_TIMEOUT, WRITE_CONNECT_TIMEOUT};
pub fn grab_banner(
address: &str,
connect_timeout: &Option<Duration>,
read_timeout: &Option<Duration>,
write_timeout: &Option<Duration>,
) -> Result<String, Box<dyn error::Error>> {
let address = resolve(address)?;
let mut stream =
TcpStream::connect_timeout(&address, connect_timeout.unwrap_or(DEFAULT_CONNECT_TIMEOUT))?;
stream.set_read_timeout(Option::from(read_timeout.unwrap_or(READ_CONNECT_TIMEOUT)))?;
stream.set_write_timeout(Option::from(write_timeout.unwrap_or(WRITE_CONNECT_TIMEOUT)))?;
let mut buffer = [0; 512];
let result = stream.read_exact(&mut buffer);
if result.is_ok() {
return Ok(String::from(str::from_utf8(&buffer)?));
}
let error = result.err().unwrap();
if error.kind() != ErrorKind::WouldBlock {
return Err(error.into());
}
stream.write_all("HEAD / HTTP/1.1\n\n".as_ref())?;
stream.read_exact(&mut buffer)?;
Ok(String::from(str::from_utf8(&buffer)?))
}