use std::borrow::Cow;
use std::net::Ipv6Addr;
use super::percent::{self, Mode};
use super::{UriRef, split};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Reading {
Uri,
Opaque,
Url,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct JavaParts<'a> {
pub reading: Reading,
pub scheme: Option<&'a str>,
pub user_info: Option<&'a str>,
pub host: Option<&'a str>,
pub port: Option<u32>,
pub path: Option<&'a str>,
pub query: Option<&'a str>,
pub fragment: Option<&'a str>,
}
impl<'a> JavaParts<'a> {
#[must_use]
pub fn username(&self) -> Option<&'a str> {
self.user_info
.map(|info| info.split_once(':').map_or(info, |(name, _)| name))
}
#[must_use]
pub fn password(&self) -> Option<&'a str> {
self.user_info
.and_then(|info| info.split_once(':'))
.map(|(_, password)| password)
}
#[must_use]
pub fn decoded_path(&self) -> Option<Cow<'a, str>> {
self.path.map(|path| self.decoded(path))
}
#[must_use]
pub fn decoded_query(&self) -> Option<Cow<'a, str>> {
self.query.map(|query| self.decoded(query))
}
fn decoded(&self, part: &'a str) -> Cow<'a, str> {
match self.reading {
Reading::Uri => percent::decode(part, Mode::URI).unwrap_or(Cow::Borrowed(part)),
Reading::Opaque | Reading::Url => Cow::Borrowed(part),
}
}
}
#[must_use]
pub fn parts(text: &str) -> Option<JavaParts<'_>> {
if text.is_empty() {
return None;
}
let whole = split(text);
let uri_legal = uri_legal(text, &whole);
let (uri, reading) = if uri_legal {
(whole, Reading::Uri)
} else {
let uri = split(url_spec(text));
if !url_parses(&uri) {
return None;
}
(uri, Reading::Url)
};
if let Some(scheme) = uri_legal.then(|| opaque_scheme(text)).flatten() {
return Some(JavaParts {
reading: Reading::Opaque,
scheme: Some(scheme),
user_info: None,
host: None,
port: None,
path: None,
query: None,
fragment: uri.fragment,
});
}
let server = !uri_legal || server_authority(&uri);
let path = if uri.path.is_empty() {
uri.host.map(|_| uri.path)
} else {
Some(uri.path)
};
Some(JavaParts {
reading,
scheme: uri.scheme,
user_info: uri.user_info,
host: uri.host.filter(|host| server && !host.is_empty()),
port: uri
.port
.filter(|_| server)
.and_then(|port| port.parse::<u32>().ok()),
path,
query: uri.query,
fragment: uri.fragment,
})
}
fn uri_legal(text: &str, uri: &UriRef<'_>) -> bool {
if !scheme_prefix_legal(text) || !authority_legal(uri) {
return false;
}
let bytes = text.as_bytes();
let mut i = 0;
while i < bytes.len() {
let b = bytes[i];
if !b.is_ascii() {
i += 1;
continue;
}
if b == b'%' {
let hex = bytes.get(i + 1..i + 3);
if !hex.is_some_and(|h| h.iter().all(u8::is_ascii_hexdigit)) {
return false;
}
i += 3;
continue;
}
if !(b.is_ascii_alphanumeric() || b"-_.!~*'();/?:@&=+$,[]#".contains(&b)) {
return false;
}
i += 1;
}
if uri.path.contains(['[', ']']) {
return false;
}
text.chars().all(|c| !c.is_control() && !is_space_char(c))
}
fn scheme_prefix_legal(text: &str) -> bool {
let stop = text.find(['/', '?', '#']).unwrap_or(text.len());
match text[..stop].find(':') {
Some(0) => false,
Some(colon) => super::is_scheme(&text[..colon]),
None => true,
}
}
fn authority_legal(uri: &UriRef<'_>) -> bool {
let bracketed = |part: &str| part.contains(['[', ']']);
if uri.user_info.is_some_and(bracketed) || uri.port.is_some_and(bracketed) {
return false;
}
match uri.host {
Some(host) if bracketed(host) => ipv6_reference(host),
_ => true,
}
}
fn ipv6_reference(host: &str) -> bool {
let Some(inner) = host.strip_prefix('[').and_then(|h| h.strip_suffix(']')) else {
return false;
};
let address = inner.split_once('%').map_or(inner, |(head, _)| head);
address.parse::<Ipv6Addr>().is_ok()
}
fn url_spec(text: &str) -> &str {
text.trim_matches(|c: char| c <= ' ')
}
fn opaque_scheme(text: &str) -> Option<&str> {
let stop = text.find(['/', '?', '#']).unwrap_or(text.len());
let colon = text[..stop].find(':')?;
let scheme = &text[..colon];
if !super::is_scheme(scheme) {
return None;
}
let part = &text[colon + 1..text.find('#').unwrap_or(text.len())];
(!part.is_empty() && !part.starts_with('/')).then_some(scheme)
}
const fn is_space_char(c: char) -> bool {
matches!(
c,
' ' | '\u{a0}' | '\u{1680}' | '\u{2000}'
..='\u{200a}' | '\u{2028}' | '\u{2029}' | '\u{202f}' | '\u{205f}' | '\u{3000}'
)
}
fn server_authority(uri: &UriRef<'_>) -> bool {
let Some(host) = uri.host else {
return false;
};
if !uri
.port
.is_none_or(|port| port.bytes().all(|b| b.is_ascii_digit()))
{
return false;
}
if let Some(inner) = host.strip_prefix('[') {
return inner.ends_with(']');
}
ipv4_address(host) || hostname(host)
}
fn ipv4_address(host: &str) -> bool {
let mut groups = 0_usize;
for group in host.split('.') {
groups += 1;
if group.is_empty() || group.len() > 3 || !group.bytes().all(|b| b.is_ascii_digit()) {
return false;
}
if group.parse::<u16>().is_ok_and(|octet| octet > 255) {
return false;
}
}
groups == 4
}
fn hostname(host: &str) -> bool {
let trimmed = host
.strip_suffix('.')
.filter(|head| !head.is_empty())
.unwrap_or(host);
let mut labels = 0_usize;
let mut last_first = 0_u8;
for label in trimmed.split('.') {
let bytes = label.as_bytes();
let (Some(&first), Some(&end)) = (bytes.first(), bytes.last()) else {
return false;
};
if !first.is_ascii_alphanumeric()
|| !end.is_ascii_alphanumeric()
|| !bytes
.iter()
.all(|b| b.is_ascii_alphanumeric() || *b == b'-')
{
return false;
}
labels += 1;
last_first = first;
}
labels == 1 || last_first.is_ascii_alphabetic()
}
fn url_parses(uri: &UriRef<'_>) -> bool {
let Some(scheme) = uri.scheme else {
return false;
};
let known = ["http", "https", "file", "ftp", "jar", "mailto"];
if !known.iter().any(|name| scheme.eq_ignore_ascii_case(name)) {
return false;
}
if uri
.host
.is_some_and(|host| host.starts_with('[') && !ipv6_reference(host))
{
return false;
}
uri.port
.is_none_or(|port| port.bytes().all(|b| b.is_ascii_digit()))
}