#[cfg(target_os = "linux")]
use std::io;
#[cfg(target_os = "linux")]
pub(crate) fn find_header_end(buf: &[u8]) -> Option<usize> {
aria2_protocol::http::header_processor::find_header_end(buf)
}
#[cfg(target_os = "linux")]
fn parse_header(
header_str: &str,
) -> io::Result<aria2_protocol::http::header_processor::HttpResponseHead> {
let complete_header = if header_str.ends_with("\r\n\r\n") {
header_str.to_owned()
} else if header_str.ends_with("\r\n") {
format!("{header_str}\r\n")
} else {
format!("{header_str}\r\n\r\n")
};
aria2_protocol::http::header_processor::parse_response_head(complete_header.as_bytes())
.map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))
}
#[cfg(target_os = "linux")]
pub(crate) fn parse_status_code(header_str: &str) -> io::Result<u16> {
Ok(parse_header(header_str)?.status_code)
}
#[cfg(target_os = "linux")]
pub(crate) fn is_chunked(header_str: &str) -> bool {
parse_header(header_str).ok().is_some_and(|head| {
aria2_protocol::http::stream_filter::is_supported_chunked_transfer_encoding(
head.header("transfer-encoding"),
)
})
}
#[cfg(target_os = "linux")]
pub(crate) fn parse_content_length(header_str: &str) -> io::Result<Option<u64>> {
parse_header(header_str)?
.header("content-length")
.map(|value| {
value
.trim()
.parse::<u64>()
.map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))
})
.transpose()
}
#[cfg(target_os = "linux")]
pub(crate) fn write_all_at_offset(
file: &std::fs::File,
mut buf: &[u8],
mut offset: u64,
) -> io::Result<()> {
use std::os::unix::fs::FileExt;
while !buf.is_empty() {
let n = file.write_at(buf, offset)?;
if n == 0 {
return Err(io::Error::new(
io::ErrorKind::WriteZero,
"pwrite returned 0 — failed to write all bytes",
));
}
offset += n as u64;
buf = &buf[n..];
}
Ok(())
}
#[cfg(target_os = "linux")]
pub(crate) fn set_blocking(fd: std::os::unix::io::RawFd) {
let flags = unsafe { libc::fcntl(fd, libc::F_GETFL) };
if flags >= 0 {
unsafe {
libc::fcntl(fd, libc::F_SETFL, flags & !libc::O_NONBLOCK);
}
}
}