/// URLs (RFC 3986) with a host, as HTTP clients need them: parse one, /// resolve a link against it, write it back, and the request target to /// send. /// /// url.parse "https://Example.com/a/b?x=1" /// // Ok(Url("https", "example.com", None, "/a/b", Some("x=1"), None)) /// url.resolve page "../c#top" // Ok: https://example.com/c#top /// url.request_target page // "/a/b?x=1" /// /// A URL here always has a scheme and a host (`mailto:` and `urn:` are /// refused). The scheme and the host are lowercased, an IPv6 host keeps /// its brackets (`[::1]`), and the path has its dot segments removed. /// Refused: a user name or password (`user@host`), a host that is not /// ASCII (there is no IDNA: write the `xn--` form), a host with a /// character outside `A-Z a-z 0-9 - . _ ~`, a port above 65535, and a /// control character anywhere. import std/bytes import std/list import std/option import std/result import std/string /// An absolute URL. `port` is `None` when the URL names none (see /// [`port_or_default`]); `query` and `fragment` are `None` when absent and /// `Some("")` after a bare `?` or `#`. The path is `""` or starts with `/`. @derive Eq Debug pub type Url { Url( scheme: String , host: String , port: Option , path: String , query: Option , fragment: Option ) } impl Show { fn show :: url { to_string url } } /// A reference split into its five parts (RFC 3986, Appendix B). type Parts { Parts( scheme: Option , authority: Option , path: String , query: Option , fragment: Option ) } // ---- parsing ------------------------------------------------------------------- /// The absolute URL `text` holds, or why it is not one. pub fn parse :: text: String -> Result { use parts <- result.try (split text) absolute parts } fn absolute :: parts: Parts -> Result { match (parts.scheme, parts.authority) { (None, _) -> Error("not an absolute URL: it has no scheme") , (_, None) -> Error("a URL needs a host: //host after the scheme") , (Some(scheme), Some(authority)) -> { use (host, port) <- result.try (authority_of authority) Ok( Url( scheme , host , port , remove_dot_segments parts.path , parts.query , parts.fragment ) ) } } } fn split :: text: String -> Result { let data = bytes.from_string text match control_at data 0 { Some(at) -> Error("a control character at byte {at}") , None -> { let colon = until data 0 [58, 47, 63, 35] if colon > 0 && bytes.read_u8 data colon == 58 { let scheme = text_of data 0 colon if is_scheme scheme { Ok(after_scheme data (colon + 1) (Some(string.to_lower scheme))) } else { Error("a scheme can only have letters, digits, + - and .") } } else { Ok(after_scheme data 0 None) } } } } fn after_scheme :: data: Bytes at: Int scheme: Option -> Parts { if at_text data at "//" { let end = until data (at + 2) [47, 63, 35] after_authority data end scheme (Some(text_of data (at + 2) end)) } else { after_authority data at scheme None } } fn after_authority :: data: Bytes start: Int scheme: Option authority: Option -> Parts { let n = bytes.length data let path_end = until data start [63, 35] let hash = until data path_end [35] let query = if path_end < hash { Some(text_of data (path_end + 1) hash) } else { None } let fragment = if hash < n { Some(text_of data (hash + 1) n) } else { None } Parts(scheme, authority, text_of data start path_end, query, fragment) } fn is_scheme :: text: String -> Bool { let data = bytes.from_string text is_alpha (bytes.read_u8 data 0) && all_from data 0 fn b { is_alpha b || is_digit b || b == 43 || b == 45 || b == 46 } } /// The host (lowercased) and the port of an authority. fn authority_of :: text: String -> Result<(String, Option), String> { let data = bytes.from_string text if until data 0 [64] < bytes.length data { Error("a user name or password in a URL (user@host) is refused") } else if bytes.read_u8 data 0 == 91 { let close = until data 0 [93] if close == bytes.length data { Error("an IPv6 host without its closing ]") } else { use host <- result.try (ipv6_host data close) use port <- result.try (port_after data (close + 1)) Ok((host, port)) } } else { let colon = until data 0 [58] use host <- result.try (name_host data colon) use port <- result.try (port_after data colon) Ok((host, port)) } } fn ipv6_host :: data: Bytes close: Int -> Result { let inside = bytes.slice data 1 close if bytes.length inside > 0 && until inside 0 [58] < bytes.length inside && all_from inside 0 fn b { is_hex b || b == 58 || b == 46 } { Ok(string.to_lower (text_of data 0 (close + 1))) } else { Error("a bad IPv6 host") } } fn name_host :: data: Bytes end: Int -> Result { let host = bytes.slice data 0 end if end == 0 { Error("a URL needs a host") } else if !all_from host 0 fn b { b < 128 } { Error("a host that is not ASCII (no IDNA here): write its xn-- form") } else if !all_from host 0 is_unreserved { Error("a host can only have letters, digits, - . _ and ~") } else { Ok(string.to_lower (text_of data 0 end)) } } /// The port after the host, which ends at `at`: none, or `:` and digits. fn port_after :: data: Bytes at: Int -> Result, String> { let n = bytes.length data if at == n || at + 1 == n && bytes.read_u8 data at == 58 { Ok(None) } else if bytes.read_u8 data at != 58 { Error("a host followed by something other than :port") } else { let digits = bytes.slice data (at + 1) n if bytes.length digits <= 5 && all_from digits 0 is_digit { let port = result.unwrap_or (string.to_int (bytes.to_string_lossy digits)) 65536 if port <= 65535 { Ok(Some(port)) } else { Error("a port above 65535") } } else { Error("a bad port") } } } // ---- resolving ----------------------------------------------------------------- /// The URL `reference` (a link: absolute, `//host/x`, `/x`, `x`, `../x`, /// `?q`, `#f`) points to from `base` (RFC 3986, §5.2). A reference with a /// scheme must itself be a URL with a host. pub fn resolve :: base: Url reference: String -> Result { use r <- result.try (split reference) match (r.scheme, r.authority) { (Some(_), _) -> absolute r , (None, Some(authority)) -> { use (host, port) <- result.try (authority_of authority) Ok( Url( base.scheme , host , port , remove_dot_segments r.path , r.query , r.fragment ) ) } , (None, None) -> Ok(relative base r) } } fn relative :: base: Url r: Parts -> Url { if r.path == "" { Url(..base, query: option.or r.query base.query, fragment: r.fragment) } else { let path = if string.starts_with r.path "/" { r.path } else { merge base.path r.path } Url( ..base , path: remove_dot_segments path , query: r.query , fragment: r.fragment ) } } /// RFC 3986, §5.2.3: the base path up to its last `/`, then `path`. fn merge :: base: String path: String -> String { if base == "" { "/" <> path } else { let data = bytes.from_string base text_of data 0 (last_slash data (bytes.length data - 1) + 1) <> path } } fn last_slash :: data: Bytes at: Int -> Int { if at < 0 || bytes.read_u8 data at == 47 { at } else { last_slash data (at - 1) } } /// RFC 3986, §5.2.4: `.` and `..` segments interpreted and removed. fn remove_dot_segments :: path: String -> String { string.concat (list.reverse (removed (bytes.from_string path) 0 [])) } /// The output so far is `out`, its last segment first. fn removed :: data: Bytes at: Int out: List -> List { if at >= bytes.length data { out } else if at_text data at "../" { removed data (at + 3) out } else if at_text data at "./" { removed data (at + 2) out } else if at_text data at "/./" { removed data (at + 2) out } else if rest_is data at "/." { ["/", ..out] } else if at_text data at "/../" { removed data (at + 3) (list.drop out 1) } else if rest_is data at "/.." { ["/", ..list.drop out 1] } else if rest_is data at "." || rest_is data at ".." { out } else { let end = until data (at + 1) [47] removed data end [text_of data at end, ..out] } } // ---- writing ------------------------------------------------------------------- /// The URL as text: `parse (to_string url) == Ok(url)` for a parsed URL. pub fn to_string :: url: Url -> String { let port = match url.port { Some(p) -> ":" <> show p, None -> "" } let query = match url.query { Some(q) -> "?" <> q, None -> "" } let fragment = match url.fragment { Some(f) -> "#" <> f, None -> "" } string.concat [url.scheme, "://", url.host, port, url.path, query, fragment] } /// The URL's port, else its scheme's: 80 for `http` and `ws`, 443 for /// `https` and `wss`, `None` for another scheme. pub fn port_or_default :: url: Url -> Option { match url.port { Some(p) -> Some(p) , None -> match url.scheme { "http" | "ws" -> Some(80), "https" | "wss" -> Some(443), _ -> None } } } /// What an HTTP request line names: the path (`/` when empty) and the /// query, without the fragment. A byte that may not appear there as it /// is (a space, `"`, `<`, a byte of a non-ASCII character, a `%` not /// followed by two hex digits) is percent-encoded; `%XX` escapes already /// written are kept. pub fn request_target :: url: Url -> String { let path = if url.path == "" { "/" } else { url.path } let query = match url.query { Some(q) -> "?" <> q, None -> "" } let data = bytes.from_string (path <> query) bytes.build_string (encoded data 0 (bytes.builder ())) } fn encoded :: data: Bytes at: Int out: bytes.Builder -> bytes.Builder { let b = bytes.read_u8 data at if b < 0 { out } else if is_target b || b == 37 && is_hex (bytes.read_u8 data (at + 1)) && is_hex (bytes.read_u8 data (at + 2)) { encoded data (at + 1) (bytes.append_byte out b) } else { let digits = "0123456789ABCDEF" let hex = string.slice digits (b / 16) (b / 16 + 1) <> string.slice digits (b % 16) (b % 16 + 1) encoded data (at + 1) (bytes.append_string out ("%" <> hex)) } } /// Bytes a request target may hold as they are: unreserved, sub-delims, /// `:`, `@`, `/` and `?` (RFC 3986's pchar and query). fn is_target :: b: Int -> Bool { is_unreserved b || b == 33 || b == 36 || b >= 38 && b <= 44 || b == 59 || b == 61 || b == 58 || b == 64 || b == 47 || b == 63 } // ---- bytes --------------------------------------------------------------------- /// The first index at or after `at` whose byte is one of `stops`, else /// the length. fn until :: data: Bytes at: Int stops: List -> Int { let b = bytes.read_u8 data at if b < 0 { bytes.length data } else if list.any stops fn s { s == b } { at } else { until data (at + 1) stops } } fn control_at :: data: Bytes at: Int -> Option { let b = bytes.read_u8 data at if b < 0 { None } else if b < 32 || b == 127 { Some(at) } else { control_at data (at + 1) } } fn all_from :: data: Bytes at: Int ok: fn(Int) -> Bool -> Bool { let b = bytes.read_u8 data at b < 0 || ok b && all_from data (at + 1) ok } fn text_of :: data: Bytes from: Int to: Int -> String { bytes.to_string_lossy (bytes.slice data from to) } fn at_text :: data: Bytes at: Int text: String -> Bool { let wanted = bytes.from_string text bytes.slice data at (at + bytes.length wanted) == wanted } fn rest_is :: data: Bytes at: Int text: String -> Bool { at + string.byte_length text == bytes.length data && at_text data at text } fn is_alpha :: b: Int -> Bool { b >= 65 && b <= 90 || b >= 97 && b <= 122 } fn is_digit :: b: Int -> Bool { b >= 48 && b <= 57 } fn is_hex :: b: Int -> Bool { is_digit b || b >= 65 && b <= 70 || b >= 97 && b <= 102 } fn is_unreserved :: b: Int -> Bool { is_alpha b || is_digit b || b == 45 || b == 46 || b == 95 || b == 126 }