| 1 |
#' Normalizing URL parser |
| 2 |
#' |
| 3 |
#' Interfaces the libcurl [URL parser](https://curl.se/libcurl/c/libcurl-url.html). |
| 4 |
#' URLs are automatically normalized where possible, such as in the case of |
| 5 |
#' relative paths or url-encoded queries (see examples). |
| 6 |
#' When parsing hyperlinks from a HTML document, it is possible to set `baseurl` |
| 7 |
#' to the location of the document itself such that relative links can be resolved. |
| 8 |
#' |
| 9 |
#' A valid URL contains at least a scheme and a host, other pieces are optional. |
| 10 |
#' If these are missing, the parser raises an error. Otherwise it returns |
| 11 |
#' a list with the following elements: |
| 12 |
#' - *url*: the normalized input URL |
| 13 |
#' - *scheme*: the protocol part before the `://` (required) |
| 14 |
#' - *host*: name of host without port (required) |
| 15 |
#' - *port*: decimal between 0 and 65535 |
| 16 |
#' - *path*: normalized path up till the `?` of the url |
| 17 |
#' - *query*: search query: part between the `?` and `#` of the url. Use `params` below to get individual parameters from the query. |
| 18 |
#' - *fragment*: the hash part after the `#` of the url |
| 19 |
#' - *user*: authentication username |
| 20 |
#' - *password*: authentication password |
| 21 |
#' - *params*: named vector with parameters from `query` if set |
| 22 |
#' |
| 23 |
#' Each element above is either a string or `NULL`, except for `params` which |
| 24 |
#' is always a character vector with the length equal to the number of parameters. |
| 25 |
#' |
| 26 |
#' Note that the `params` field is only usable if the `query` is in the usual |
| 27 |
#' `application/x-www-form-urlencoded` format which is technically not part of |
| 28 |
#' the RFC. Some services may use e.g. a json blob as the query, in which case |
| 29 |
#' the parsed `params` field here can be ignored. There is no way for the parser |
| 30 |
#' to automatically infer or validate the query format, this is up to the caller. |
| 31 |
#' |
| 32 |
#' For more details on the URL format see |
| 33 |
#' [rfc3986](https://datatracker.ietf.org/doc/html/rfc3986) |
| 34 |
#' or the steps explained in the [whatwg basic url parser](https://url.spec.whatwg.org/#concept-basic-url-parser). |
| 35 |
#' |
| 36 |
#' @export |
| 37 |
#' @param url a character string of length one |
| 38 |
#' @param baseurl use this as the parent if `url` may be a relative path |
| 39 |
#' @param decode automatically [url-decode][curl_escape] output into the actual |
| 40 |
#' values. If set to `FALSE`, values for `query`, `path`, `fragment`, `user` and `password` are returned in url-encoded format. |
| 41 |
#' @param params parse individual parameters assuming query is in `application/x-www-form-urlencoded` format. |
| 42 |
#' @param default_scheme when `url` is provided without a scheme prefix, assume `https://`. |
| 43 |
#' @useDynLib curl R_parse_url |
| 44 |
#' @examples |
| 45 |
#' url <- "https://jerry:[email protected]:888/foo/bar?test=123#bla" |
| 46 |
#' curl_parse_url(url) |
| 47 |
#' |
| 48 |
#' # Resolve relative links from a baseurl |
| 49 |
#' curl_parse_url("/somelink", baseurl = url) |
| 50 |
#' |
| 51 |
#' # Paths get normalized |
| 52 |
#' curl_parse_url("https://foobar.com/foo/bar/../baz/../yolo")$url |
| 53 |
#' |
| 54 |
#' # Also normalizes URL-encoding (these URLs are equivalent): |
| 55 |
#' url1 <- "https://ja.wikipedia.org/wiki/\u5bff\u53f8" |
| 56 |
#' url2 <- "https://ja.wikipedia.org/wiki/%e5%af%bf%e5%8f%b8" |
| 57 |
#' curl_parse_url(url1)$path |
| 58 |
#' curl_parse_url(url2)$path |
| 59 |
#' curl_parse_url(url1, decode = FALSE)$path |
| 60 |
#' curl_parse_url(url1, decode = FALSE)$path |
| 61 |
curl_parse_url <- function(url, baseurl = NULL, decode = TRUE, params = TRUE, |
| 62 |
default_scheme = FALSE){ |
| 63 |
stopifnot(is.character(url)) |
| 64 |
stopifnot(length(url) == 1) |
| 65 |
baseurl <- as.character(baseurl) |
| 66 |
|
| 67 |
# Workaround for #366 |
| 68 |
if(length(baseurl) && substr(url, 1, 1) == '#'){ |
| 69 |
url <- sub('(#.*)?$', url, baseurl) |
| 70 |
} |
| 71 |
|
| 72 |
result <- .Call(R_parse_url, url, baseurl, default_scheme) |
| 73 |
result$url <- toupper_url_encoding(result$url) |
| 74 |
|
| 75 |
|
| 76 |
# Need to parse query before url-decoding |
| 77 |
if(params){ |
| 78 |
tryCatch({ |
| 79 |
result$params <- parse_query_urlencoded(result$query) |
| 80 |
result$query <- NULL |
| 81 |
}, error = message) |
| 82 |
} |
| 83 |
|
| 84 |
result$path <- normalize_field(result$path, decode) |
| 85 |
result$query <- normalize_field(result$query, decode) |
| 86 |
result$fragment <- normalize_field(result$fragment, decode) |
| 87 |
result$user <- normalize_field(result$user, decode) |
| 88 |
result$password <- normalize_field(result$password, decode) |
| 89 |
result |
| 90 |
} |
| 91 |
|
| 92 |
#' @details You can use [curl_modify_url()] both to modify an existing URL, or to |
| 93 |
#' create new URL from scratch. Arguments get automatically URL-encoded where |
| 94 |
#' needed, unless wrapped in `I()`. If `params` is given, this gets converted |
| 95 |
#' into a `application/x-www-form-urlencoded` string which overrides `query`. |
| 96 |
#' When modifying a URL, use an empty string `""` to unset a piece of the URL. |
| 97 |
#' @export |
| 98 |
#' @rdname curl_parse_url |
| 99 |
#' @useDynLib curl R_modify_url |
| 100 |
#' @param url either URL string or list returned by [curl_parse_url]. |
| 101 |
#' Use this to modify a URL using the other parameters. |
| 102 |
#' @param scheme string with e.g. `https`. Required if no `url` parameter was given. |
| 103 |
#' @param host string with hostname. Required if no `url` parameter was given. |
| 104 |
#' @param port string or number with port, e.g. `"443"`. |
| 105 |
#' @param path piece of the url starting with `/` up till `?` or `#` |
| 106 |
#' @param query piece of url starting with `?` up till `#`. Only used if no `params` is given. |
| 107 |
#' @param fragment part of url starting with `#`. |
| 108 |
#' @param user string with username |
| 109 |
#' @param password string with password |
| 110 |
#' @param params named character vector with http GET parameters. This will automatically |
| 111 |
#' be converted to `application/x-www-form-urlencoded` and override `query`, |
| 112 |
curl_modify_url <- function(url = NULL, scheme = NULL, host = NULL, port = NULL, path = NULL, |
| 113 |
query = NULL, fragment = NULL, user = NULL, password = NULL, params = NULL){ |
| 114 |
if(is.list(url)){ |
| 115 |
url <- do.call(curl_modify_url, url) |
| 116 |
} |
| 117 |
if(!is.null(params)){ |
| 118 |
query <- I(build_query_urlencoded(params)) |
| 119 |
} |
| 120 |
port <- as.character(port) |
| 121 |
out <- .Call(R_modify_url, url, scheme, host, port, path, query, fragment, user, password) |
| 122 |
toupper_url_encoding(out) |
| 123 |
} |
| 124 |
|
| 125 |
toupper_url_encoding <- function(x){ |
| 126 |
gsub('(%..)', replacement = '\\U\\1', x, perl = TRUE) |
| 127 |
} |
| 128 |
|
| 129 |
normalize_field <- function(x, decode = TRUE){ |
| 130 |
if(is.null(x)){ |
| 131 |
return(x) |
| 132 |
} |
| 133 |
if(isTRUE(decode)){ |
| 134 |
curl_unescape(x) |
| 135 |
} else { |
| 136 |
toupper_url_encoding(x) |
| 137 |
} |
| 138 |
} |
| 139 |
|
| 140 |
# Parses a string in 'application/x-www-form-urlencoded' format |
| 141 |
parse_query_urlencoded <- function(query){ |
| 142 |
if(!length(query)) return(character()) |
| 143 |
query <- chartr('+',' ', query) |
| 144 |
argstr <- strsplit(query, "&", fixed = TRUE)[[1]] |
| 145 |
args <- lapply(argstr, function(x){ |
| 146 |
c(curl_unescape(strsplit(x, "=", fixed = TRUE)[[1]]), "") |
| 147 |
}) |
| 148 |
values <- vapply(args, `[`, character(1), 2) |
| 149 |
names(values) <- vapply(args, `[`, character(1), 1) |
| 150 |
return(values) |
| 151 |
} |
| 152 |
|
| 153 |
build_query_urlencoded <- function(params){ |
| 154 |
if(!is.character(params) || length(names(params)) != length(params)){ |
| 155 |
stop("params must be named character vector") |
| 156 |
} |
| 157 |
nms <- curl_escape(names(params)) |
| 158 |
values <- gsub("%20", "+", curl_escape(params), fixed = TRUE) |
| 159 |
paste(nms, values, collapse = '&', sep = '=') |
| 160 |
} |
| 161 |
|
| 162 |
try_parse_url <- function(url){ |
| 163 |
tryCatch(curl_parse_url(url), error = function(e){}) |
| 164 |
} |