Debian Codegraph @

R/handle.R

raw
1 #' Create and configure a curl handle
2 #'
3 #' Handles are the work horses of libcurl. A handle is used to configure a
4 #' request with custom options, headers and payload. Once the handle has been
5 #' set up, it can be passed to any of the download functions such as [curl()]
6 #' ,[curl_download()] or [curl_fetch_memory()]. The handle will maintain
7 #' state in between requests, including keep-alive connections, cookies and
8 #' settings.
9 #'
10 #' Use `new_handle()` to create a new clean curl handle that can be
11 #' configured with custom options and headers. Note that `handle_setopt`
12 #' appends or overrides options in the handle, whereas `handle_setheaders`
13 #' replaces the entire set of headers with the new ones. The `handle_reset`
14 #' function resets only options/headers/forms in the handle. It does not affect
15 #' active connections, cookies or response data from previous requests. The safest
16 #' way to perform multiple independent requests is by using a separate handle for
17 #' each request. There is very little performance overhead in creating handles.
18 #'
19 #' The [handle_setform] function is used to perform a `multipart/form-data` HTTP
20 #' POST request (a.k.a. posting a form). The form fields can be specified as
21 #' strings, raw vectors (for binary data), or [form_file] and [form_data] for
22 #' upload elements. See the examples.
23 #'
24 #' @family handles
25 #' @param ... named options / headers to be set in the handle.
26 #' To send a file, see [form_file()]. To list all allowed options,
27 #' see [curl_options()]
28 #' @return A handle object (external pointer to the underlying curl handle).
29 #' All functions modify the handle in place but also return the handle
30 #' so you can create a pipeline of operations.
31 #' @export
32 #' @name handle
33 #' @useDynLib curl R_new_handle
34 #' @rdname handle
35 #' @examples
36 #' h <- new_handle()
37 #' handle_setopt(h, customrequest = "PUT")
38 #' handle_setform(h, a = "1", b = "2")
39 #' r <- curl_fetch_memory("https://hb.cran.dev/put", h)
40 #' cat(rawToChar(r$content))
41 #'
42 #' # Or use the list form
43 #' h <- new_handle()
44 #' handle_setopt(h, .list = list(customrequest = "PUT"))
45 #' handle_setform(h, .list = list(a = "1", b = "2"))
46 #' r <- curl_fetch_memory("https://hb.cran.dev/put", h)
47 #' cat(rawToChar(r$content))
48 #'
49 #' # Posting multipart forms
50 #' h <- new_handle()
51 #' handle_setform(h,
52 #' foo = "blabla",
53 #' bar = charToRaw("boeboe"),
54 #' iris = form_data(serialize(iris, NULL), "application/rda"),
55 #' description = form_file(system.file("DESCRIPTION")),
56 #' logo = form_file(file.path(R.home('doc'), "html/logo.jpg"), "image/jpeg")
57 #' )
58 #' req <- curl_fetch_memory("https://hb.cran.dev/post", handle = h)
59 new_handle <- function(...){
60 h <- .Call(R_new_handle)
61 handle_setopt(h, ...)
62 h
63 }
64
65 #' @export
66 #' @useDynLib curl R_handle_setopt
67 #' @param handle Handle to modify
68 #' @param .list A named list of options. This is useful if you've created
69 #' a list of options elsewhere, avoiding the use of `do.call()`.
70 #' @rdname handle
71 handle_setopt <- function(handle, ..., .list = list()){
72 stopifnot(inherits(handle, "curl_handle"))
73 values <- c(list(...), .list)
74 opt_names <- fix_options(tolower(names(values)))
75 keys <- as.integer(curl_options()[opt_names])
76 na_keys <- is.na(keys)
77 if(any(na_keys)){
78 bad_opts <- opt_names[na_keys]
79 stop("Unknown option", ifelse(length(bad_opts) > 1, "s: ", ": "),
80 paste(bad_opts, collapse=", "))
81 }
82 stopifnot(length(keys) == length(values))
83 .Call(R_handle_setopt, handle, keys, values)
84 invisible(handle)
85 }
86
87 #' @export
88 #' @rdname handle
89 handle_setheaders <- function(handle, ..., .list = list()){
90 x <- c(list(...), .list)
91 if(!all(vapply(x, is.character, logical(1)))){
92 stop("All headers must be strings.")
93 }
94 handle_setopt(handle, httpheader = format_request_headers(x))
95 }
96
97 format_request_headers <- function(x){
98 x$Expect = ""
99 names <- names(x)
100 values <- as.character(unlist(x))
101 postfix <- ifelse(grepl("^\\s+$", values), ";", paste(":", values))
102 paste0(names, postfix)
103 }
104
105 #' @useDynLib curl R_handle_getheaders
106 #' @rdname handle
107 handle_getheaders <- function(handle){
108 stopifnot(inherits(handle, "curl_handle"))
109 .Call(R_handle_getheaders, handle)
110 }
111
112 #' @useDynLib curl R_handle_getcustom
113 handle_getcustom <- function(handle){
114 stopifnot(inherits(handle, "curl_handle"))
115 .Call(R_handle_getcustom, handle)
116 }
117
118 #' @export
119 #' @useDynLib curl R_handle_setform
120 #' @rdname handle
121 handle_setform <- function(handle, ..., .list = list()){
122 stopifnot(inherits(handle, "curl_handle"))
123 form <- c(list(...), .list)
124 for(i in seq_along(form)){
125 val <- form[[i]];
126 if(is.character(val)){
127 form[[i]] <- charToRaw(enc2utf8(val))
128 } else if(!is.raw(val) && !inherits(val, "form_file") && !inherits(val, "form_data")){
129 stop("Unsupported value type for form field '", names(form[i]), "'.")
130 }
131 }
132 .Call(R_handle_setform, handle, form)
133 invisible(handle)
134 }
135
136 #' @export
137 #' @rdname handle
138 #' @useDynLib curl R_handle_reset
139 handle_reset <- function(handle){
140 stopifnot(inherits(handle, "curl_handle"))
141 .Call(R_handle_reset, handle)
142 invisible(handle)
143 }
144
145 #' Extract cookies from a handle
146 #'
147 #' The `handle_cookies` function returns a data frame with 7 columns as specified in the
148 #' [netscape cookie file format](http://www.cookiecentral.com/faq/#3.5).
149 #'
150 #' @useDynLib curl R_get_handle_cookies
151 #' @export
152 #' @param handle a curl handle object
153 #' @family handles
154 #' @examples
155 #' h <- new_handle()
156 #' handle_cookies(h)
157 #'
158 #' # Server sets cookies
159 #' req <- curl_fetch_memory("https://hb.cran.dev/cookies/set?foo=123&bar=ftw", handle = h)
160 #' handle_cookies(h)
161 #'
162 #' # Server deletes cookies
163 #' req <- curl_fetch_memory("https://hb.cran.dev/cookies/delete?foo", handle = h)
164 #' handle_cookies(h)
165 #'
166 #' # Cookies will survive a reset!
167 #' handle_reset(h)
168 #' handle_cookies(h)
169 handle_cookies <- function(handle){
170 stopifnot(inherits(handle, "curl_handle"))
171 cookies <- .Call(R_get_handle_cookies, handle)
172 df <- if(length(cookies)){
173 values <- lapply(strsplit(cookies, split="\t"), `[`, 1:7)
174 as.data.frame(do.call(rbind, values), stringsAsFactors = FALSE)
175 } else {
176 as.data.frame(matrix(ncol=7, nrow=0))
177 }
178 names(df) <- c("domain", "flag", "path", "secure", "expiration", "name", "value")
179 df$flag <- as.logical(df$flag)
180 df$secure <- as.logical(df$secure)
181 expires <- as.numeric(df$expiration)
182 expires[expires==0] <- Inf
183 class(expires) = c("POSIXct", "POSIXt");
184 df$expiration <- expires
185 df
186
187 }
188
189 # This is for internal use in progress bars. When the download is complete,
190 # the speed is equal to content-size / elapsed-time.
191 #' @useDynLib curl R_get_handle_speed
192 handle_speed <- function(handle){
193 .Call(R_get_handle_speed, handle)
194 }
195
196 #' @useDynLib curl R_get_handle_clength
197 handle_clength <- function(handle){
198 .Call(R_get_handle_clength, handle)
199 }
200
201 #' @useDynLib curl R_get_handle_received
202 handle_received <- function(handle){
203 .Call(R_get_handle_received, handle)
204 }
205
206 #' @useDynLib curl R_get_handle_mtime
207 handle_mtime <- function(handle){
208 .Call(R_get_handle_mtime, handle)
209 }
210
211 #' @export
212 print.curl_handle <- function(x, ...){
213 stopifnot(inherits(x, "curl_handle"))
214 url <- handle_data(x)$url
215 if(!nchar(url)) url <- "empty"
216 cat(sprintf("<curl handle> (%s)\n", url))
217 }
218
219 # Only for testing memory leaks
220 #' @useDynLib curl R_total_handles
221 total_handles <- function(){
222 .Call(R_total_handles)
223 }
224
225 ## Some hacks for backward compatibilty
226 fix_options <- function(opt_names){
227 # Recent libcurl should use xferinfo instead of progress
228 has_xferinfo <- length(curl_options("xferinfofunction"))
229 if(has_xferinfo){
230 opt_names[opt_names == "progressfunction"] <- "xferinfofunction"
231 return(opt_names)
232 } else {
233 opt_names[opt_names == "xferinfofunction"] <- "progressfunction"
234 return(opt_names)
235 }
236 }