use std::{
fmt, io,
io::{Read, Write},
net::{
IpAddr, Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr, TcpListener, TcpStream, ToSocketAddrs,
},
string::{String, ToString},
sync::{
Arc, Condvar, Mutex,
atomic::{AtomicBool, Ordering},
},
thread,
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
vec::Vec,
};
use crate::{
ClientConn, ClientEvent, HttpError, Limits, Method, Request, RequestHead, Response, ServerConn,
ServerEvent, redact::FieldValue,
};
const DRAIN_LIMIT: usize = 256 * 1024;
const DRAIN_READ_TIMEOUT: Duration = Duration::from_millis(250);
const DRAIN_TOTAL: Duration = Duration::from_secs(1);
const OUT_RETAIN: usize = 64 * 1024;
#[non_exhaustive]
#[derive(Debug)]
pub enum Error {
Io(io::Error),
Http(HttpError),
InvalidUrl(&'static str),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Io(e) => write!(f, "I/O error: {e}"),
Self::Http(e) => write!(f, "HTTP error: {e}"),
Self::InvalidUrl(why) => write!(f, "invalid URL: {why}"),
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Io(e) => Some(e),
Self::Http(e) => Some(e),
Self::InvalidUrl(_) => None,
}
}
}
impl From<io::Error> for Error {
fn from(e: io::Error) -> Self {
Self::Io(e)
}
}
impl From<HttpError> for Error {
fn from(e: HttpError) -> Self {
Self::Http(e)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ServerConfig {
limits: Limits,
max_connections: usize,
read_timeout: Option<Duration>,
request_timeout: Option<Duration>,
write_timeout: Option<Duration>,
}
impl Default for ServerConfig {
fn default() -> Self {
Self::new()
}
}
impl ServerConfig {
#[must_use]
pub const fn new() -> Self {
Self {
limits: Limits::new(),
max_connections: 64,
read_timeout: Some(Duration::from_secs(10)),
request_timeout: Some(Duration::from_secs(30)),
write_timeout: Some(Duration::from_secs(10)),
}
}
#[must_use]
pub const fn with_limits(mut self, limits: Limits) -> Self {
self.limits = limits;
self
}
#[must_use]
pub const fn with_max_connections(mut self, n: usize) -> Self {
self.max_connections = if n == 0 { 1 } else { n };
self
}
#[must_use]
pub const fn with_read_timeout(mut self, timeout: Option<Duration>) -> Self {
self.read_timeout = timeout;
self
}
#[must_use]
pub const fn with_request_timeout(mut self, timeout: Option<Duration>) -> Self {
self.request_timeout = timeout;
self
}
#[must_use]
pub const fn with_write_timeout(mut self, timeout: Option<Duration>) -> Self {
self.write_timeout = timeout;
self
}
#[must_use]
pub const fn limits(&self) -> Limits {
self.limits
}
#[must_use]
pub const fn max_connections(&self) -> usize {
self.max_connections
}
#[must_use]
pub const fn read_timeout(&self) -> Option<Duration> {
self.read_timeout
}
#[must_use]
pub const fn request_timeout(&self) -> Option<Duration> {
self.request_timeout
}
#[must_use]
pub const fn write_timeout(&self) -> Option<Duration> {
self.write_timeout
}
}
#[derive(Debug)]
pub struct Upgraded {
pub stream: TcpStream,
pub leftover: Vec<u8>,
pub target: String,
}
type UpgradeHook = Arc<dyn Fn(Upgraded) + Send + Sync>;
pub struct Server {
listener: TcpListener,
local: SocketAddr,
config: ServerConfig,
stop: Arc<AtomicBool>,
upgrade: Option<UpgradeHook>,
}
impl fmt::Debug for Server {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Server")
.field("local_addr", &self.local)
.field("config", &self.config)
.finish()
}
}
#[derive(Clone, Debug)]
pub struct ShutdownHandle {
stop: Arc<AtomicBool>,
wake: SocketAddr,
}
impl ShutdownHandle {
pub fn shutdown(&self) {
self.stop.store(true, Ordering::SeqCst);
if let Ok(stream) = TcpStream::connect_timeout(&self.wake, Duration::from_secs(1)) {
drop(stream);
}
}
}
#[derive(Default)]
struct Active {
count: Mutex<usize>,
idle: Condvar,
}
impl Active {
fn try_enter(&self, max: usize) -> bool {
let mut n = self
.count
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if *n >= max {
return false;
}
*n += 1;
true
}
fn leave(&self) {
let mut n = self
.count
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
*n = n.saturating_sub(1);
if *n == 0 {
self.idle.notify_all();
}
}
fn wait_idle(&self) {
let mut n = self
.count
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
while *n > 0 {
n = self
.idle
.wait(n)
.unwrap_or_else(std::sync::PoisonError::into_inner);
}
}
}
struct ActiveGuard(Arc<Active>);
impl Drop for ActiveGuard {
fn drop(&mut self) {
self.0.leave();
}
}
impl Server {
pub fn bind(addr: impl ToSocketAddrs) -> io::Result<Self> {
let listener = TcpListener::bind(addr)?;
let local = listener.local_addr()?;
Ok(Self {
listener,
local,
config: ServerConfig::new(),
stop: Arc::new(AtomicBool::new(false)),
upgrade: None,
})
}
#[must_use]
pub fn with_config(mut self, config: ServerConfig) -> Self {
self.config = config;
self
}
#[must_use]
pub fn on_upgrade(mut self, hook: impl Fn(Upgraded) + Send + Sync + 'static) -> Self {
self.upgrade = Some(Arc::new(hook));
self
}
#[must_use]
pub fn local_addr(&self) -> SocketAddr {
self.local
}
#[must_use]
pub fn shutdown_handle(&self) -> ShutdownHandle {
let mut wake = self.local;
if wake.ip().is_unspecified() {
wake.set_ip(match wake.ip() {
IpAddr::V4(_) => IpAddr::V4(Ipv4Addr::LOCALHOST),
IpAddr::V6(_) => IpAddr::V6(Ipv6Addr::LOCALHOST),
});
}
ShutdownHandle {
stop: Arc::clone(&self.stop),
wake,
}
}
pub fn serve<H>(self, handler: H) -> io::Result<()>
where
H: Fn(&RequestHead<'_>, &[u8]) -> Response + Send + Sync + 'static,
{
let handler = Arc::new(handler);
let active = Arc::new(Active::default());
let mut consecutive_errors = 0u32;
for incoming in self.listener.incoming() {
if self.stop.load(Ordering::SeqCst) {
break;
}
let stream = match incoming {
Ok(stream) => {
consecutive_errors = 0;
stream
}
Err(e) => {
consecutive_errors += 1;
if consecutive_errors > 1000 {
return Err(e);
}
thread::sleep(Duration::from_millis(10));
continue;
}
};
if !active.try_enter(self.config.max_connections) {
refuse_busy(stream, &self.config);
continue;
}
let guard = ActiveGuard(Arc::clone(&active));
let handler = Arc::clone(&handler);
let upgrade = self.upgrade.clone();
let stop = Arc::clone(&self.stop);
let config = self.config;
let spawned = thread::Builder::new()
.name("http-net-conn".into())
.spawn(move || {
let _guard = guard;
serve_stream(stream, &config, &*handler, upgrade.as_deref(), &stop);
});
drop(spawned);
}
active.wait_idle();
Ok(())
}
}
fn refuse_busy(mut stream: TcpStream, config: &ServerConfig) {
const BUSY: &[u8] =
b"HTTP/1.1 503 Service Unavailable\r\ncontent-length: 0\r\nconnection: close\r\n\r\n";
if stream.set_write_timeout(config.write_timeout).is_err()
|| stream.write_all(BUSY).is_err()
|| stream.shutdown(Shutdown::Write).is_err()
|| stream.set_nonblocking(true).is_err()
{
return;
}
let mut scratch = [0u8; 4096];
let mut drained = 0;
while drained < DRAIN_LIMIT {
match stream.read(&mut scratch) {
Ok(n) if n > 0 => drained += n,
_ => break,
}
}
}
fn serve_stream(
stream: TcpStream,
config: &ServerConfig,
handler: &(dyn Fn(&RequestHead<'_>, &[u8]) -> Response + Send + Sync),
upgrade: Option<&(dyn Fn(Upgraded) + Send + Sync)>,
stop: &AtomicBool,
) {
let configured = stream.set_read_timeout(config.read_timeout).is_ok()
&& stream.set_write_timeout(config.write_timeout).is_ok()
&& stream.set_nodelay(true).is_ok();
if !configured {
return;
}
let mut conn =
Connection::new(stream, config.limits).with_request_timeout(config.request_timeout);
while !stop.load(Ordering::SeqCst) {
let outcome = match conn.next_request() {
Ok(Some(incoming)) => {
let head = incoming.head();
Ok((
handler(&head, incoming.body()),
head.method() == Method::Head,
))
}
Ok(None) => break,
Err(e) => Err(e),
};
let (response, is_head) = match outcome {
Ok(answer) => answer,
Err(Error::Http(e)) => {
if conn.respond(&Response::from_error(&e)).is_err() {
return;
}
break;
}
Err(Error::Io(e)) if is_timeout(&e) && conn.request_in_progress() => {
if conn.send_request_timeout().is_ok() {
conn.close();
}
return;
}
Err(_) => return,
};
let streamed = response.body_bytes().is_none();
let response = if streamed && !is_head {
Response::text(
500,
"handler error: Server cannot send a streamed response; \
use Connection for streaming",
)
.close()
} else {
response
};
match conn.respond(&response) {
Ok(()) if streamed && is_head => {
if conn.end_body().is_err() {
return;
}
}
Ok(()) => {}
Err(Error::Http(e)) => {
let message = format!("handler error: invalid response: {e}");
if conn
.respond(&Response::text(500, &message).close())
.is_err()
{
return;
}
}
Err(_) => return,
}
if conn.is_upgraded() {
match (conn.into_upgraded(), upgrade) {
(Some(up), Some(hook)) => hook(up),
(Some(up), None) => drain_and_close(up.stream),
(None, _) => {}
}
return;
}
}
conn.close();
}
fn drain_and_close(mut stream: TcpStream) {
if stream.flush().is_err() || stream.shutdown(Shutdown::Write).is_err() {
return;
}
let deadline = Instant::now() + DRAIN_TOTAL;
let mut scratch = [0u8; 4096];
let mut drained = 0;
while drained < DRAIN_LIMIT {
let left = deadline.saturating_duration_since(Instant::now());
if left.is_zero()
|| stream
.set_read_timeout(Some(left.min(DRAIN_READ_TIMEOUT)))
.is_err()
{
break;
}
match stream.read(&mut scratch) {
Ok(0) | Err(_) => break,
Ok(n) => drained += n,
}
}
}
fn is_timeout(e: &io::Error) -> bool {
matches!(
e.kind(),
io::ErrorKind::TimedOut | io::ErrorKind::WouldBlock
)
}
#[derive(Debug)]
pub struct Incoming<'a> {
head: RequestHead<'a>,
body: &'a [u8],
}
impl<'a> Incoming<'a> {
#[must_use]
pub fn head(&self) -> RequestHead<'a> {
self.head
}
#[must_use]
pub fn body(&self) -> &'a [u8] {
self.body
}
}
#[derive(Debug)]
pub struct Connection {
stream: TcpStream,
conn: ServerConn,
body: Vec<u8>,
out: Vec<u8>,
read_timeout: Option<Duration>,
request_timeout: Option<Duration>,
deadline: Option<Instant>,
shortened: bool,
}
impl Connection {
#[must_use]
pub fn new(stream: TcpStream, limits: Limits) -> Self {
let read_timeout = stream.read_timeout().ok().flatten();
Self {
stream,
conn: ServerConn::with_limits(limits),
body: Vec::new(),
out: Vec::new(),
read_timeout,
request_timeout: None,
deadline: None,
shortened: false,
}
}
#[must_use]
pub fn with_request_timeout(mut self, timeout: Option<Duration>) -> Self {
self.request_timeout = timeout;
self
}
fn request_in_progress(&self) -> bool {
self.conn.request().is_some() || !self.conn.remaining_input().is_empty()
}
fn send_request_timeout(&mut self) -> Result<(), Error> {
if self.conn.response_started() {
return Err(Error::Http(HttpError::InvalidState(
"a response was already started",
)));
}
const BODY: &[u8] = b"request timed out";
self.out.clear();
self.out.extend_from_slice(
b"HTTP/1.1 408 Request Timeout\r\ncontent-type: text/plain; charset=utf-8\r\n\
content-length: ",
);
self.out
.extend_from_slice(BODY.len().to_string().as_bytes());
self.out
.extend_from_slice(b"\r\nconnection: close\r\ndate: ");
self.out.extend_from_slice(&http_date(SystemTime::now()));
self.out.extend_from_slice(b"\r\n\r\n");
self.out.extend_from_slice(BODY);
self.flush_out()
}
fn fill(&mut self) -> Result<(), Error> {
if let Some(limit) = self.request_timeout {
if self.deadline.is_none() && self.request_in_progress() {
self.deadline = Some(Instant::now() + limit);
}
}
match self.deadline {
Some(deadline) => {
let left = deadline.saturating_duration_since(Instant::now());
if left.is_zero() {
return Err(Error::Io(io::Error::new(
io::ErrorKind::TimedOut,
"the request did not arrive within the request timeout",
)));
}
let wait = self.read_timeout.map_or(left, |t| t.min(left));
self.stream.set_read_timeout(Some(wait))?;
self.shortened = true;
}
None if self.shortened => {
self.stream.set_read_timeout(self.read_timeout)?;
self.shortened = false;
}
None => {}
}
let spare = self.conn.read_buf();
if spare.is_empty() {
return Err(Error::Http(HttpError::InvalidState(
"input buffer full while the parser needs input",
)));
}
let n = loop {
match self.stream.read(spare) {
Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
other => break other?,
}
};
if n == 0 {
self.conn.feed_eof();
} else {
self.conn.commit(n);
}
Ok(())
}
pub fn next_request(&mut self) -> Result<Option<Incoming<'_>>, Error> {
self.body.clear();
self.deadline = None;
loop {
match self.conn.poll()? {
ServerEvent::Request(head) => {
if head.expects_continue() {
self.out.clear();
self.conn.send_continue(&mut self.out)?;
self.flush_out()?;
}
}
ServerEvent::Body(chunk) => self.body.extend_from_slice(chunk),
ServerEvent::RequestEnd => break,
ServerEvent::NeedInput => self.fill()?,
ServerEvent::AwaitingResponse => {
return Err(Error::Http(HttpError::InvalidState(
"respond to the previous request first",
)));
}
_ => return Ok(None),
}
}
match self.conn.request() {
Some(head) => Ok(Some(Incoming {
head,
body: &self.body,
})),
None => Ok(None),
}
}
pub fn respond(&mut self, response: &Response) -> Result<(), Error> {
self.out.clear();
let date = http_date(SystemTime::now());
self.conn
.respond_dated(response, Some(&date), &mut self.out)?;
self.flush_out()
}
pub fn send_body(&mut self, data: &[u8]) -> Result<(), Error> {
self.out.clear();
self.conn.send_body(data, &mut self.out)?;
self.flush_out()
}
pub fn end_body(&mut self) -> Result<(), Error> {
self.out.clear();
self.conn.end_body(&mut self.out)?;
self.flush_out()
}
fn flush_out(&mut self) -> Result<(), Error> {
self.stream.write_all(&self.out)?;
if self.out.capacity() > OUT_RETAIN {
self.out = Vec::new();
}
Ok(())
}
#[must_use]
pub fn is_upgraded(&self) -> bool {
self.conn.is_upgraded()
}
#[must_use]
pub fn into_upgraded(self) -> Option<Upgraded> {
if !self.is_upgraded() {
return None;
}
let target = self
.conn
.request()
.map(|r| r.target().to_string())
.unwrap_or_default();
if self.shortened {
let _ = self.stream.set_read_timeout(self.read_timeout);
}
Some(Upgraded {
leftover: self.conn.remaining_input().to_vec(),
target,
stream: self.stream,
})
}
pub fn close(self) {
drain_and_close(self.stream);
}
}
#[derive(Clone, PartialEq, Eq)]
pub struct ClientResponse {
status: u16,
headers: Vec<(String, Vec<u8>)>,
body: Vec<u8>,
}
impl fmt::Debug for ClientResponse {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
struct Fields<'a>(&'a [(String, Vec<u8>)]);
impl fmt::Debug for Fields<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list()
.entries(self.0.iter().map(|(name, value)| {
(
name.as_str(),
FieldValue {
name: name.as_bytes(),
value,
},
)
}))
.finish()
}
}
f.debug_struct("ClientResponse")
.field("status", &self.status)
.field("headers", &Fields(&self.headers))
.field("body", &format_args!("{} bytes", self.body.len()))
.finish()
}
}
impl ClientResponse {
#[must_use]
pub fn status(&self) -> u16 {
self.status
}
pub fn headers(&self) -> impl Iterator<Item = (&str, &[u8])> {
self.headers.iter().map(|(n, v)| (n.as_str(), v.as_slice()))
}
#[must_use]
pub fn header(&self, name: &str) -> Option<&[u8]> {
self.headers
.iter()
.find(|(n, _)| n.eq_ignore_ascii_case(name))
.map(|(_, v)| v.as_slice())
}
#[must_use]
pub fn body(&self) -> &[u8] {
&self.body
}
#[must_use]
pub fn text(&self) -> Option<&str> {
core::str::from_utf8(&self.body).ok()
}
#[must_use]
pub fn into_body(self) -> Vec<u8> {
self.body
}
}
pub fn get(url: &str) -> Result<ClientResponse, Error> {
Client::new().get(url)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Client {
limits: Limits,
timeout: Duration,
}
impl Default for Client {
fn default() -> Self {
Self::new()
}
}
impl Client {
#[must_use]
pub const fn new() -> Self {
Self {
limits: Limits::new().with_max_body(16 * 1024 * 1024),
timeout: Duration::from_secs(30),
}
}
#[must_use]
pub const fn with_limits(mut self, limits: Limits) -> Self {
self.limits = limits;
self
}
#[must_use]
pub const fn with_timeout(mut self, timeout: Duration) -> Self {
self.timeout = if timeout.is_zero() {
Duration::from_millis(1)
} else {
timeout
};
self
}
pub fn get(&self, url: &str) -> Result<ClientResponse, Error> {
let url = Url::parse(url)?;
let request = Request::get(url.target)
.header("host", url.authority)
.close();
let mut stream = self.connect(&url)?;
let mut conn = ClientConn::with_limits(self.limits);
let mut out = Vec::new();
conn.send_request(&request, &mut out)?;
stream.write_all(&out)?;
read_response(&mut stream, &mut conn)
}
fn connect(&self, url: &Url<'_>) -> Result<TcpStream, Error> {
let mut last = None;
for addr in (url.host, url.port).to_socket_addrs()? {
match TcpStream::connect_timeout(&addr, self.timeout) {
Ok(stream) => {
stream.set_read_timeout(Some(self.timeout))?;
stream.set_write_timeout(Some(self.timeout))?;
stream.set_nodelay(true)?;
return Ok(stream);
}
Err(e) => last = Some(e),
}
}
Err(Error::Io(last.unwrap_or_else(|| {
io::Error::new(io::ErrorKind::NotFound, "the host resolved to no address")
})))
}
}
fn read_response(stream: &mut TcpStream, conn: &mut ClientConn) -> Result<ClientResponse, Error> {
let mut response = ClientResponse {
status: 0,
headers: Vec::new(),
body: Vec::new(),
};
loop {
match conn.poll()? {
ClientEvent::Response(head) => {
response.status = head.status();
response.headers = head
.headers()
.map(|(n, v)| (n.to_string(), v.to_vec()))
.collect();
}
ClientEvent::Body(chunk) => response.body.extend_from_slice(chunk),
ClientEvent::ResponseEnd => return Ok(response),
ClientEvent::NeedInput => {
let spare = conn.read_buf();
if spare.is_empty() {
return Err(Error::Http(HttpError::InvalidState(
"input buffer full while the parser needs input",
)));
}
let n = loop {
match stream.read(spare) {
Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
other => break other?,
}
};
if n == 0 {
conn.feed_eof();
} else {
conn.commit(n);
}
}
_ => {
return Err(Error::Http(HttpError::InvalidState(
"the connection ended without a complete response",
)));
}
}
}
}
#[derive(Debug, PartialEq, Eq)]
struct Url<'a> {
authority: &'a str,
host: &'a str,
port: u16,
target: &'a str,
}
impl<'a> Url<'a> {
fn parse(url: &'a str) -> Result<Self, Error> {
let scheme_end = url.find("://").ok_or(Error::InvalidUrl("missing scheme"))?;
if !url[..scheme_end].eq_ignore_ascii_case("http") {
return Err(Error::InvalidUrl(
"only http:// is supported (no TLS in this crate)",
));
}
let rest = &url[scheme_end + 3..];
let rest = rest.split_once('#').map_or(rest, |(r, _)| r);
let auth_end = rest.find(['/', '?']).unwrap_or(rest.len());
let authority = &rest[..auth_end];
let target = match &rest[auth_end..] {
"" => "/",
t if t.starts_with('?') => {
return Err(Error::InvalidUrl("a query needs a path, for example /?q"));
}
t => t,
};
if authority.is_empty() {
return Err(Error::InvalidUrl("missing host"));
}
if authority.contains('@') {
return Err(Error::InvalidUrl(
"credentials in the URL are not supported",
));
}
let (host, port) = if let Some(v6) = authority.strip_prefix('[') {
let (inside, after) = v6.split_once(']').ok_or(Error::InvalidUrl("unclosed ["))?;
let port = match after {
"" => None,
p => Some(
p.strip_prefix(':')
.ok_or(Error::InvalidUrl("junk after ]"))?,
),
};
(inside, port)
} else {
match authority.rsplit_once(':') {
Some((h, p)) => (h, Some(p)),
None => (authority, None),
}
};
let port = match port {
None => 80,
Some(p) => p.parse().map_err(|_| Error::InvalidUrl("bad port"))?,
};
if host.is_empty() {
return Err(Error::InvalidUrl("missing host"));
}
Ok(Self {
authority,
host,
port,
target,
})
}
}
fn http_date(time: SystemTime) -> [u8; 29] {
let secs = time.duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs());
let days = secs / 86_400;
let rem = secs % 86_400;
let (year, month, day) = civil_from_days(days);
const WEEKDAYS: [&[u8; 3]; 7] = [b"Thu", b"Fri", b"Sat", b"Sun", b"Mon", b"Tue", b"Wed"];
const MONTHS: [&[u8; 3]; 12] = [
b"Jan", b"Feb", b"Mar", b"Apr", b"May", b"Jun", b"Jul", b"Aug", b"Sep", b"Oct", b"Nov",
b"Dec",
];
let mut out = *b"Thu, 01 Jan 1970 00:00:00 GMT";
out[..3].copy_from_slice(WEEKDAYS[(days % 7) as usize]);
two_digits(&mut out[5..7], day);
out[8..11].copy_from_slice(MONTHS[(month - 1) as usize]);
let y = year.min(9999);
two_digits(&mut out[12..14], y / 100);
two_digits(&mut out[14..16], y % 100);
two_digits(&mut out[17..19], rem / 3600);
two_digits(&mut out[20..22], rem % 3600 / 60);
two_digits(&mut out[23..25], rem % 60);
out
}
fn two_digits(dst: &mut [u8], v: u64) {
if let [tens, ones] = dst {
*tens = b'0' + (v / 10 % 10) as u8;
*ones = b'0' + (v % 10) as u8;
}
}
fn civil_from_days(days: u64) -> (u64, u64, u64) {
let z = days + 719_468;
let era = z / 146_097;
let doe = z - era * 146_097;
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let day = doy - (153 * mp + 2) / 5 + 1;
let month = if mp < 10 { mp + 3 } else { mp - 9 };
let year = yoe + era * 400 + u64::from(month <= 2);
(year, month, day)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_http_date_known_values() {
let at = |s: u64| UNIX_EPOCH + Duration::from_secs(s);
assert_eq!(&http_date(at(0)), b"Thu, 01 Jan 1970 00:00:00 GMT");
assert_eq!(
&http_date(at(784_111_777)),
b"Sun, 06 Nov 1994 08:49:37 GMT"
);
assert_eq!(
&http_date(at(951_782_400)),
b"Tue, 29 Feb 2000 00:00:00 GMT"
);
assert_eq!(
&http_date(at(1_791_072_000)),
b"Sun, 04 Oct 2026 00:00:00 GMT"
);
}
#[test]
fn test_url_parsing() {
let u = Url::parse("http://127.0.0.1:8080/a/b?c=d#frag").unwrap();
assert_eq!(
u,
Url {
authority: "127.0.0.1:8080",
host: "127.0.0.1",
port: 8080,
target: "/a/b?c=d"
}
);
let u = Url::parse("HTTP://[::1]/").unwrap();
assert_eq!((u.host, u.port, u.authority), ("::1", 80, "[::1]"));
assert_eq!(Url::parse("http://example.com").unwrap().target, "/");
for bad in [
"example.com",
"https://x/",
"http:///x",
"http://u:p@x/",
"http://x:99999/",
"http://[::1/",
"http://[::1]x/",
"http://x?q",
"http://:80/",
] {
assert!(
matches!(Url::parse(bad), Err(Error::InvalidUrl(_))),
"{bad}"
);
}
}
#[test]
fn test_error_display_and_source() {
use std::error::Error as _;
let e = Error::from(HttpError::BareCr);
assert!(e.to_string().starts_with("HTTP error"));
assert!(e.source().is_some());
let e = Error::from(io::Error::other("x"));
assert!(e.source().is_some());
assert!(Error::InvalidUrl("y").source().is_none());
}
}