Debian Codegraph @

R/download.R

raw
1
2 # download a file from 'url' to file 'destfile'. the 'type'
3 # argument tells us the remote type, which is used to motivate
4 # what form of authentication is appropriate; the 'quiet'
5 # argument is used to display / suppress output. use 'headers'
6 # (as a named character vector) to supply additional headers
7 download <- function(url,
8 destfile,
9 preamble = NULL,
10 type = NULL,
11 quiet = FALSE,
12 headers = NULL)
13 {
14 # allow for user-defined overrides
15 override <- getOption("renv.download.override")
16 if (is.function(override)) {
17
18 result <- catch(
19 override(
20 url = url,
21 destfile = destfile,
22 quiet = quiet,
23 mode = "wb",
24 headers = headers
25 )
26 )
27
28 if (inherits(result, "error"))
29 renv_download_error(result, "%s", conditionMessage(result))
30
31 if (!file.exists(destfile))
32 renv_download_error(url, "%s does not exist", renv_path_pretty(destfile))
33
34 return(destfile)
35
36 }
37
38 if (quiet)
39 renv_scope_options(renv.verbose = FALSE)
40
41 # normalize separators (file URIs should normally use forward
42 # slashes, even on Windows where the native separator is backslash)
43 url <- chartr("\\", "/", url)
44 destfile <- chartr("\\", "/", destfile)
45
46 # notify user we're about to try downloading
47 preamble <- preamble %||% sprintf("- Downloading '%s' ... ", url)
48 printf(preamble)
49
50 # add custom headers as appropriate for the URL
51 custom <- renv_download_custom_headers(url)
52 headers[names(custom)] <- custom
53
54 # handle local files by just copying the file
55 if (renv_download_local(url, destfile, headers))
56 return(destfile)
57
58 # on Windows, try using our local curl binary if available
59 renv_scope_downloader()
60
61 # if the file already exists, compare its size with
62 # the server's reported size for that file
63 info <- renv_file_info(destfile)
64 if (identical(info$isdir, FALSE)) {
65 size <- renv_download_size(url, type, headers)
66 if (info$size == size) {
67 writef("OK [file is up to date]")
68 return(destfile)
69 }
70 }
71
72 # back up a pre-existing file if necessary
73 callback <- renv_file_backup(destfile)
74 defer(callback())
75
76 # form path to temporary file
77 tempfile <- renv_scope_tempfile(tmpdir = dirname(destfile))
78
79 # request the download
80 before <- Sys.time()
81
82 status <- renv_download_impl(
83 url = url,
84 destfile = tempfile,
85 type = type,
86 request = "GET",
87 headers = headers
88 )
89
90 after <- Sys.time()
91
92 # check for failure
93 if (inherits(status, "condition"))
94 renv_download_error(url, "%s", conditionMessage(status))
95
96 if (status != 0L)
97 renv_download_error(url, "error code %i", status)
98
99 if (!file.exists(tempfile))
100 renv_download_error(url, "%s", "unknown reason")
101
102 # double-check archives are readable
103 status <- renv_download_check_archive(tempfile)
104 if (inherits(status, "error"))
105 renv_download_error(url, "%s", "archive cannot be read")
106
107 # everything looks ok: report success
108 elapsed <- difftime(after, before, units = "auto")
109 renv_download_report(elapsed, tempfile)
110
111 # move the file to the requested location
112 renv_file_move(tempfile, destfile)
113
114 # one final sanity check
115 if (!file.exists(destfile)) {
116 fmt <- "could not move %s to %s"
117 msg <- sprintf(fmt, renv_path_pretty(tempfile), renv_path_pretty(destfile))
118 renv_download_error(url, msg)
119 }
120
121 # and return path to successfully retrieved file
122 destfile
123 }
124
125 # NOTE: only 'GET' and 'HEAD' are supported
126 #
127 # each downloader should return 0 on success
128 renv_download_impl <- function(url, destfile, type = NULL, request = "GET", headers = NULL) {
129
130 # normalize separators (file URIs should normally use forward
131 # slashes, even on Windows where the native separator is backslash)
132 url <- chartr("\\", "/", url)
133 destfile <- chartr("\\", "/", destfile)
134
135 # check that the destination file is writable
136 if (!renv_file_writable(destfile)) {
137 fmt <- "destination path '%s' is not writable; cannot proceed"
138 stopf(fmt, renv_path_pretty(destfile))
139 }
140
141 # select the appropriate downloader
142 downloader <- switch(
143 renv_download_method(),
144 curl = renv_download_curl,
145 wget = renv_download_wget,
146 renv_download_default
147 )
148
149 # disable warnings in this scope; it is not safe to try and catch
150 # warnings as R will try to clean up open sockets after emitting
151 # warnings, and catching a warning would hence prevent that
152 # https://bugs.r-project.org/show_bug.cgi?id=18634
153 catch(
154 withCallingHandlers(
155 downloader(url, destfile, type, request, headers),
156 warning = function(cnd) invokeRestart("muffleWarning")
157 )
158 )
159
160 }
161
162 renv_download_default_mode <- function(url, method) {
163
164 mode <- "wb"
165
166 fixup <-
167 renv_platform_windows() &&
168 identical(method, "wininet") &&
169 substring(url, 1L, 5L) == "file:"
170
171 if (fixup)
172 mode <- "w+b"
173
174 mode
175
176 }
177
178 renv_download_default <- function(url, destfile, type, request, headers) {
179
180 # custom request types are not supported with the default downloader
181 if (request != "GET")
182 stopf("the default downloader does not support %s requests", request)
183
184 # try and ensure headers are set for older versions of R
185 auth <- renv_download_auth(url, type)
186 headers[names(auth)] <- auth
187 renv_download_default_agent_scope(headers)
188
189 # on Windows, prefer 'wininet' as most users will have already configured
190 # authentication etc. to work with this protocol
191 methods <- c(
192 Sys.getenv("RENV_DOWNLOAD_METHOD", unset = NA),
193 Sys.getenv("RENV_DOWNLOAD_FILE_METHOD", unset = NA),
194 if (renv_platform_windows()) "wininet" else "auto"
195 )
196
197 method <- Find(Negate(is.na), methods)
198
199 # headers _must_ be NULL rather than zero-length character
200 if (length(headers) == 0)
201 headers <- NULL
202
203 mode <- renv_download_default_mode(url, method)
204
205 # handle absence of 'headers' argument in older versions of R
206 args <- list(url = url,
207 destfile = destfile,
208 method = method,
209 headers = headers,
210 mode = mode,
211 quiet = TRUE)
212
213 fmls <- formals(download.file)
214 args <- keep(args, names(fmls))
215
216 renv_download_trace_begin(url, method)
217 if (renv_download_trace())
218 str(args)
219
220 do.call(download.file, args)
221
222 }
223
224 renv_download_default_agent_scope <- function(headers, scope = parent.frame()) {
225
226 if (empty(headers))
227 return(FALSE)
228
229 if (getRversion() >= "3.6.0")
230 return(FALSE)
231
232 renv_download_default_agent_scope_impl(headers, scope)
233 }
234
235 renv_download_default_agent_scope_impl <- function(headers, scope = parent.frame()) {
236
237 utils <- asNamespace("utils")
238 makeUserAgent <- utils$makeUserAgent
239 ok <-
240 is.function(makeUserAgent) &&
241 identical(formals(makeUserAgent), pairlist(format = TRUE))
242
243 if (!ok)
244 return(FALSE)
245
246 agent <- makeUserAgent(FALSE)
247 all <- c("User-Agent" = agent, headers)
248 headertext <- paste0(names(all), ": ", all, "\r\n", collapse = "")
249
250 renv_scope_binding(utils, "makeUserAgent", function(format = TRUE) {
251 if (format) headertext else agent
252 }, scope = scope)
253
254 return(TRUE)
255
256 }
257
258 renv_download_curl_config_text <- function(url, destfile, type, headers, request = "GET") {
259
260 fields <- c(
261 "user-agent" = renv_http_useragent(),
262 "url" = url,
263 "output" = destfile
264 )
265
266 # set connect timeout
267 timeout <- config$connect.timeout()
268 if (is.numeric(timeout))
269 fields[["connect-timeout"]] <- timeout
270
271 # set number of retries
272 retries <- config$connect.retry()
273 if (is.numeric(retries))
274 fields[["retry"]] <- retries
275
276 # set up authentication headers
277 auth <- renv_download_auth(url, type)
278 if (length(auth)) {
279 authtext <- paste(names(auth), auth, sep = ": ")
280 names(authtext) <- rep.int("header", times = length(authtext))
281 fields <- c(fields, authtext)
282 }
283
284 # add other custom headers
285 if (length(headers)) {
286 lines <- paste(names(headers), headers, sep = ": ")
287 names(lines) <- rep.int("header", times = length(lines))
288 fields <- c(fields, lines)
289 }
290
291 # join together
292 keys <- names(fields)
293 vals <- renv_json_quote(fields)
294 text <- paste(keys, vals, sep = " = ")
295
296 # remove duplicated authorization headers
297 dupes <- startsWith(text, "header =") & duplicated(text)
298 text <- text[!dupes]
299
300 # add in stand-alone flags
301 flags <- c("location", "fail", "silent", "show-error")
302 if (request == "HEAD")
303 flags <- c(flags, "head", "include")
304
305 # put it all together
306 c(flags, text)
307
308 }
309
310 renv_download_curl <- function(url, destfile, type, request, headers) {
311
312 renv_download_trace_begin(url, "curl")
313
314 text <- renv_download_curl_config_text(url, destfile, type, headers, request)
315 configfile <- renv_scope_tempfile("renv-download-config-")
316 writeLines(text, con = configfile)
317 renv_download_trace_request(text)
318
319 # generate the arguments to be passed to 'curl'
320 args <- stack()
321
322 # include anything provided explicitly in 'download.file.extra' here
323 if (identical(getOption("download.file.method"), "curl")) {
324 extra <- getOption("download.file.extra")
325 if (length(extra))
326 args$push(extra)
327 }
328
329 # https://github.com/rstudio/renv/issues/1739
330 if (renv_platform_windows()) {
331 enabled <- Sys.getenv("R_LIBCURL_SSL_REVOKE_BEST_EFFORT", unset = "TRUE")
332 if (truthy(enabled))
333 args$push("--ssl-revoke-best-effort")
334 }
335
336 # add in any user configuration files
337 userconfig <- getOption(
338 "renv.curl.config",
339 renv_download_curl_config()
340 )
341
342 for (entry in userconfig)
343 if (file.exists(entry))
344 args$push("--config", renv_shell_path(entry))
345
346 # add in our own config file (the actual request)
347 args$push("--config", renv_shell_path(configfile))
348
349 # perform the download
350 curl <- renv_curl_exe()
351 output <- suppressWarnings(
352 system2(curl, args$data(), stdout = TRUE, stderr = TRUE)
353 )
354
355 renv_download_trace_result(output)
356
357 # report non-zero status as warning
358 status <- attr(output, "status", exact = TRUE) %||% 0L
359 if (status != 0L)
360 warning(output, call. = FALSE)
361
362 status
363
364 }
365
366 renv_download_curl_config <- function() {
367
368 rc <- if (renv_platform_windows()) "_curlrc" else ".curlrc"
369
370 homes <- c(
371 Sys.getenv("CURL_HOME"),
372 Sys.getenv("HOME"),
373 Sys.getenv("R_USER"),
374 path.expand("~/")
375 )
376
377 # nocov start
378 if (renv_platform_windows()) {
379 extra <- c(
380 Sys.getenv("APPDATA"),
381 file.path(Sys.getenv("USERPROFILE"), "Application Data"),
382 dirname(Sys.which("curl"))
383 )
384 homes <- c(homes, extra)
385 }
386 # nocov end
387
388 homes <- Filter(nzchar, homes)
389
390 for (home in homes) {
391 path <- file.path(home, rc)
392 if (file.exists(path))
393 return(path)
394 }
395
396 NULL
397
398 }
399
400 renv_download_parallel <- function(urls, destfiles, types, callback = NULL) {
401
402 # make sure we're using forward slashes uniformly
403 urls <- chartr("\\", "/", urls)
404 destfiles <- chartr("\\", "/", destfiles)
405
406 # prefer curl when a callback is provided, since only the curl
407 # backend supports streaming per-transfer progress via --write-out
408 method <- renv_download_parallel_method()
409 if (!is.null(callback) && method != "curl") {
410 supported <- renv_download_parallel_supported_curl()
411 if (!is.null(supported))
412 method <- supported
413 }
414
415 switch(method,
416 libcurl = renv_download_parallel_libcurl(urls, destfiles, types),
417 curl = renv_download_parallel_curl(urls, destfiles, types, callback = callback),
418 renv_download_parallel_sequential(urls, destfiles, types)
419 )
420
421 }
422
423 renv_download_parallel_method <- function() {
424
425 method <- renv_download_method()
426
427 supported <- case(
428 method == "curl" ~ renv_download_parallel_supported_curl(),
429 method == "libcurl" ~ renv_download_parallel_supported_libcurl()
430 )
431
432 supported %||% "sequential"
433
434 }
435
436 renv_download_parallel_supported_curl <- function() {
437 version <- catch(renv_curl_version())
438 if (!inherits(version, "error") && version >= "7.66.0")
439 return("curl")
440 }
441
442 renv_download_parallel_supported_libcurl <- function() {
443 if (getRversion() >= "4.5.0")
444 return("libcurl")
445 }
446
447 renv_download_parallel_curl <- function(urls, destfiles, types, callback = NULL) {
448
449 n <- length(urls)
450 names <- names(urls) %||% urls
451
452 # ensure parent directories exist
453 for (destfile in destfiles)
454 ensure_parent_directory(destfile)
455
456 # %{stderr} routes --write-out output to stderr, which is unbuffered by
457 # the C standard. without this, libc fully buffers stdout when connected
458 # to a pipe, so curl --parallel holds all --write-out output until exit.
459 # trailing sentinel ("renv-output-end") prevents strsplit dropping empty
460 # fields like errormsg on success.
461 fields <- c(
462 "renv-output-begin",
463 "%{filename_effective}",
464 "%{http_code}",
465 "%{size_download}",
466 "%{time_total}",
467 "%{exitcode}",
468 "%{errormsg}",
469 "renv-output-end"
470 )
471 writeout <- sprintf("write-out = \"%%{stderr}%s\\n\"", paste(fields, collapse = "\\t"))
472
473 # per-URL config lines that must be repeated in each section (reset by next)
474 perlines <- character()
475
476 # https://github.com/rstudio/renv/issues/1739
477 if (renv_platform_windows()) {
478 enabled <- Sys.getenv("R_LIBCURL_SSL_REVOKE_BEST_EFFORT", unset = "TRUE")
479 if (truthy(enabled))
480 perlines <- c(perlines, "ssl-revoke-best-effort")
481 }
482
483 userconfig <- getOption("renv.curl.config", renv_download_curl_config())
484 for (entry in userconfig)
485 if (file.exists(entry))
486 perlines <- c(perlines, sprintf("config = %s", renv_json_quote(entry)))
487
488 # build a single combined config file with 'next' between URL sections;
489 # this avoids the command-line length limit on Windows (cmd.exe: 8191 chars)
490 all <- character()
491 for (i in seq_len(n)) {
492
493 if (i > 1L)
494 all <- c(all, "next")
495
496 section <- renv_download_curl_config_text(
497 url = urls[[i]],
498 destfile = destfiles[[i]],
499 type = types[[i]],
500 headers = renv_download_custom_headers(urls[[i]])
501 )
502
503 all <- c(all, perlines, section, writeout)
504
505 }
506
507 configfile <- renv_scope_tempfile("renv-dl-config-")
508 writeLines(all, con = configfile)
509
510 # --parallel and --parallel-max are global (survive 'next')
511 curl <- renv_curl_exe()
512 maxjobs <- 16L
513
514 globalargs <- sprintf("--parallel --parallel-max %d", maxjobs)
515
516 # --parallel-immediate starts all connections at once instead of waiting
517 # for the first to establish; available since curl 7.68.0
518 version <- catch(renv_curl_version())
519 if (!inherits(version, "error") && version >= "7.68.0")
520 globalargs <- paste(globalargs, "--parallel-immediate")
521
522 # download.file.extra is raw command-line format, so it can't go in the
523 # config file; place it on the command line as a global option
524 if (identical(getOption("download.file.method"), "curl")) {
525 extra <- getOption("download.file.extra")
526 if (length(extra))
527 globalargs <- paste(globalargs, extra)
528 }
529
530 # stderr -> pipe (carries unbuffered --write-out), stdout -> /dev/null
531 command <- sprintf(
532 "%s %s --config %s 2>&1 >%s",
533 renv_shell_path(curl), globalargs,
534 renv_shell_path(configfile),
535 nullfile()
536 )
537
538 if (getRversion() >= "4.0") {
539 renv_download_parallel_curl_socket(command, callback)
540 } else {
541 renv_download_parallel_curl_pipe(command, callback)
542 }
543
544 # determine success by checking which destfiles exist and are non-empty
545 ok <- file.exists(destfiles) & (file.size(destfiles) > 0L)
546 names(ok) <- names
547 ok
548
549 }
550
551 renv_download_parallel_curl_pipe <- function(command, callback) {
552
553 conn <- renv_pipe_create(command)
554 defer(close(conn))
555
556 while (TRUE) {
557
558 # check for input
559 line <- readLines(conn, n = 1L, warn = FALSE)
560 if (length(line) == 0L)
561 break
562
563 # check for beginner marker
564 if (!startsWith(line, "renv-output-begin\t"))
565 next
566
567 # invoke callback on our output
568 if (!is.null(callback)) {
569 parts <- strsplit(line, "\t", fixed = TRUE)[[1L]]
570 callback(
571 destfile = parts[[2L]],
572 code = parts[[3L]],
573 size = as.numeric(parts[[4L]]),
574 time = as.numeric(parts[[5L]]),
575 exitcode = parts[[6L]],
576 error = parts[[7L]]
577 )
578 }
579
580 }
581
582 }
583
584 renv_download_parallel_curl_socket <- function(command, callback) {
585
586 server <- renv_socket_server()
587 defer(close(server$socket))
588
589 # on Windows, pipe() invokes cmd.exe /c <command>; wrap the whole
590 # command in an extra pair of quotes so inner quotes are preserved
591 if (renv_platform_windows())
592 command <- paste0("\"", command, "\"")
593
594 # build a self-contained R script that runs the curl command,
595 # reads completion events from the pipe, and sends each one
596 # to the parent over a persistent socket connection
597 code <- expr({
598
599 socket <- socketConnection(
600 host = "127.0.0.1",
601 port = !!server$port,
602 open = "wb",
603 blocking = TRUE,
604 timeout = 60
605 )
606
607 conn <- pipe(!!command, open = "r")
608
609 on.exit(close(conn), add = TRUE)
610
611 tryCatch({
612
613 while (TRUE) {
614
615 line <- readLines(conn, n = 1L, warn = FALSE)
616 if (length(line) == 0L)
617 break
618
619 if (!startsWith(line, "renv-output-begin\t"))
620 next
621
622 parts <- strsplit(line, "\t", fixed = TRUE)[[1L]]
623 result <- list(
624 type = "result",
625 destfile = parts[[2L]],
626 code = parts[[3L]],
627 size = as.numeric(parts[[4L]]),
628 time = as.numeric(parts[[5L]]),
629 exitcode = parts[[6L]],
630 error = parts[[7L]]
631 )
632
633 serialize(result, socket)
634
635 }
636
637 serialize(list(type = "done"), socket)
638
639 }, error = function(e) NULL)
640
641 close(socket)
642
643 })
644
645 script <- tempfile("renv-dl-curl-", fileext = ".R")
646 writeLines(deparse(code), con = script)
647
648 system2(
649 command = R(),
650 args = c("--vanilla", "-s", "-f", renv_shell_path(script)),
651 stdout = FALSE,
652 stderr = FALSE,
653 wait = FALSE
654 )
655
656 # accept the single child connection; short timeout to detect launch failure
657 conn <- tryCatch(
658 renv_socket_accept(server$socket, open = "rb", timeout = 30),
659 error = function(e) NULL
660 )
661
662 if (is.null(conn)) {
663 # child failed to start; fall back to blocking pipe method
664 renv_download_parallel_curl_pipe(command, callback)
665 return(invisible())
666 }
667
668 defer(close(conn))
669
670 # receive results until the child sends "done" or the connection closes
671 repeat {
672
673 ready <- socketSelect(list(conn), write = FALSE, timeout = 60)
674 if (!ready)
675 next
676
677 data <- tryCatch(unserialize(conn), error = function(e) NULL)
678
679 if (is.null(data) || identical(data$type, "done"))
680 break
681
682 if (!is.null(callback)) {
683 callback(
684 destfile = data$destfile,
685 code = data$code,
686 size = data$size,
687 time = data$time,
688 exitcode = data$exitcode,
689 error = data$error
690 )
691 }
692
693 }
694
695 }
696
697 renv_download_parallel_libcurl <- function(urls, destfiles, types) {
698
699 n <- length(urls)
700 names <- names(urls) %||% urls
701
702 # ensure parent directories exist
703 for (destfile in destfiles)
704 ensure_parent_directory(destfile)
705
706 # group URLs by their auth headers so we can pass uniform headers
707 # to each download.file() call
708 authkeys <- character(n)
709 authvals <- vector("list", n)
710 for (i in seq_len(n)) {
711 auth <- renv_download_auth(urls[[i]], types[[i]])
712 custom <- renv_download_custom_headers(urls[[i]])
713 headers <- c(auth, custom)
714 authvals[[i]] <- headers
715 authkeys[[i]] <- paste(sort(paste(names(headers), headers, sep = "=")), collapse = "\n")
716 }
717
718 groups <- split(seq_len(n), authkeys)
719
720 for (group in groups) {
721
722 gurls <- urls[group]
723 gdest <- destfiles[group]
724 headers <- authvals[[group[[1L]]]]
725
726 # headers must be NULL rather than zero-length
727 if (length(headers) == 0L)
728 headers <- NULL
729
730 tryCatch(
731 download.file(
732 url = gurls,
733 destfile = gdest,
734 method = "libcurl",
735 mode = "wb",
736 headers = headers,
737 quiet = TRUE
738 ),
739 warning = function(w) invokeRestart("muffleWarning"),
740 error = function(e) {
741 dlog("parallel", "libcurl download failed: %s", conditionMessage(e))
742 }
743 )
744
745 }
746
747 # determine success by checking which destfiles exist
748 ok <- file.exists(destfiles) & (file.size(destfiles) > 0L)
749 names(ok) <- names
750 ok
751
752 }
753
754 renv_download_parallel_sequential <- function(urls, destfiles, types) {
755
756 ok <- as.logical(.mapply(
757 renv_download_parallel_sequential_impl,
758 list(urls, destfiles, types),
759 NULL
760 ))
761
762 names(ok) <- names(urls) %||% urls
763 ok
764
765 }
766
767 renv_download_parallel_sequential_impl <- function(url, destfile, type) {
768
769 status <- catch(
770 download(
771 url = url,
772 destfile = destfile,
773 type = type,
774 quiet = TRUE
775 )
776 )
777
778 !inherits(status, "error") && file.exists(destfile)
779
780 }
781
782 # nocov start
783
784 renv_download_wget <- function(url, destfile, type, request, headers) {
785
786 renv_download_trace_begin(url, "wget")
787
788 configfile <- renv_scope_tempfile("renv-download-config-")
789
790 fields <- c(
791 "user-agent" = renv_http_useragent(),
792 "quiet" = "on"
793 )
794
795 auth <- renv_download_auth(url, type)
796 if (length(auth)) {
797 authtext <- paste(names(auth), auth, sep = ": ")
798 names(authtext) <- "header"
799 fields <- c(fields, authtext)
800 }
801
802 if (length(headers)) {
803 lines <- paste(names(headers), headers, sep = ": ")
804 names(lines) <- "header"
805 fields <- c(fields, lines)
806 }
807
808 keys <- names(fields)
809 vals <- unlist(fields)
810 text <- paste(keys, vals, sep = " = ")
811
812 writeLines(text, con = configfile)
813 renv_download_trace_request(text)
814
815 args <- stack()
816
817 if (identical(getOption("download.file.method"), "wget")) {
818 extra <- getOption("download.file.extra")
819 if (length(extra))
820 args$push(extra)
821 }
822
823 args$push("--config", renv_shell_path(configfile))
824
825 # NOTE: '-O' does not write headers to file; we need to manually redirect
826 # in that case
827 status <- if (request == "HEAD") {
828 args$push("--server-response", "--spider")
829 args$push(">", renv_shell_path(destfile), "2>&1")
830 cmdline <- paste("wget", paste(args$data(), collapse = " "))
831 return(suppressWarnings(system(cmdline)))
832 }
833
834 args$push("-O", renv_shell_path(destfile))
835 args$push(renv_shell_quote(url))
836
837 output <- suppressWarnings(
838 system2("wget", args$data(), stdout = TRUE, stderr = TRUE)
839 )
840
841 renv_download_trace_result(output)
842
843 status <- attr(output, "status", exact = TRUE) %||% 0L
844 if (status != 0L)
845 warning(output, call. = FALSE)
846
847 status
848
849 }
850
851 # nocov end
852
853 renv_download_auth_type <- function(url) {
854
855 github_hosts <- c(
856 "https://api.github.com/",
857 "https://raw.githubusercontent.com/"
858 )
859
860 for (host in github_hosts)
861 if (startsWith(url, host))
862 return("github")
863
864 gitlab_hosts <- c(
865 "https://gitlab.com/"
866 )
867
868 for (host in gitlab_hosts)
869 if (startsWith(url, host))
870 return("gitlab")
871
872 bitbucket_hosts <- c(
873 "https://api.bitbucket.org/",
874 "https://bitbucket.org/"
875 )
876
877 for (host in bitbucket_hosts)
878 if (startsWith(url, host))
879 return("bitbucket")
880
881 "unknown"
882
883 }
884
885 renv_download_auth <- function(url, type) {
886
887 type <- tolower(type %||% renv_download_auth_type(url))
888 switch(
889 type,
890 bitbucket = renv_download_auth_bitbucket(),
891 github = renv_download_auth_github(url),
892 gitlab = renv_download_auth_gitlab(),
893 character()
894 )
895
896 }
897
898 renv_download_auth_bitbucket <- function() {
899
900 user <-
901 Sys.getenv("BITBUCKET_USER", unset = NA) %NA%
902 Sys.getenv("BITBUCKET_USERNAME", unset = NA)
903
904 pass <-
905 Sys.getenv("BITBUCKET_PASS", unset = NA) %NA%
906 Sys.getenv("BITBUCKET_PASSWORD", unset = NA)
907
908 if (is.na(user) || is.na(pass))
909 return(character())
910
911 userpass <- paste(user, pass, sep = ":")
912 c("Authorization" = paste("Basic", renv_base64_encode(userpass)))
913
914 }
915
916 renv_download_auth_github <- function(url) {
917
918 token <- renv_download_auth_github_token(url)
919 if (is.null(token))
920 return(character())
921
922 c("Authorization" = paste("token", token))
923
924 }
925
926 renv_download_auth_github_token <- function(url) {
927
928 # check for an existing token from environment variable
929 token <- renv_bootstrap_github_token()
930 if (length(token))
931 return(token)
932
933 # if gitcreds is available, try to use it
934 gitcreds <-
935 getOption("renv.gitcreds.enabled", default = TRUE) &&
936 requireNamespace("gitcreds", quietly = TRUE)
937
938 if (gitcreds) {
939
940 # ensure URL has protocol pre-pended
941 url <- renv_retrieve_origin(url)
942
943 # use 'github.com' for credentials instead of 'api.github.com'
944 url <- sub("https://api.github.com", "https://github.com", url, fixed = TRUE)
945
946 # request credentials for URL
947 dlog("download", "requesting git credentials for url '%s'", url)
948 creds <- tryCatch(
949 gitcreds::gitcreds_get(url),
950 error = function(cnd) {
951 warning(conditionMessage(cnd))
952 NULL
953 }
954 )
955
956 # use if available
957 if (!is.null(creds))
958 return(creds$password)
959
960 }
961
962 # ask the user to set a GITHUB_PAT
963 if (once()) {
964 writeLines(c(
965 "- GitHub authentication credentials are not available.",
966 "- Please set GITHUB_PAT, or ensure the 'gitcreds' package is installed.",
967 "- See https://usethis.r-lib.org/articles/git-credentials.html for more details."
968 ))
969 }
970
971 }
972
973 renv_download_auth_gitlab <- function() {
974
975 pat <- Sys.getenv("GITLAB_PAT", unset = NA)
976 if (is.na(pat))
977 return(character())
978
979 c("Private-Token" = pat)
980
981 }
982
983 renv_download_headers <- function(url, type = NULL, headers = NULL) {
984
985 # check for compatible download method
986 method <- renv_download_method()
987 if (!method %in% c("libcurl", "curl", "wget"))
988 return(list())
989
990 # perform the download
991 file <- renv_scope_tempfile("renv-headers-")
992
993 status <- renv_download_impl(
994 url = url,
995 destfile = file,
996 type = type,
997 request = "HEAD",
998 headers = headers %||% renv_download_custom_headers(url)
999 )
1000
1001 # check for failure
1002 failed <-
1003 inherits(status, "error") ||
1004 !identical(status, 0L) ||
1005 !file.exists(file)
1006
1007 if (failed) {
1008 unlink(file)
1009 return(list())
1010 }
1011
1012 # read the downloaded headers
1013 contents <- read(file)
1014
1015 # if redirects were required, each set of headers will
1016 # be reported separately, so just report the final set
1017 # of headers (ie: ignore redirects)
1018 splat <- strsplit(contents, "\n\n", fixed = TRUE)[[1]]
1019 text <- strsplit(splat[[length(splat)]], "\n", fixed = TRUE)[[1]]
1020
1021 # keep only header lines
1022 lines <- grep(":", text, fixed = TRUE, value = TRUE)
1023 headers <- catch(renv_properties_read(text = lines))
1024 names(headers) <- tolower(names(headers))
1025 if (inherits(headers, "error"))
1026 return(list())
1027
1028 headers
1029
1030 }
1031
1032 renv_download_size <- function(url, type = NULL, headers = NULL) {
1033
1034 memoize(
1035 key = url,
1036 value = renv_download_size_impl(url, type, headers)
1037 )
1038
1039 }
1040
1041 renv_download_size_impl <- function(url, type = NULL, headers = NULL) {
1042
1043 headers <- catch(renv_download_headers(url, type, headers))
1044 if (inherits(headers, "error"))
1045 return(-1L)
1046
1047 size <- headers[["x-gitlab-size"]]
1048 if (!is.null(size))
1049 return(as.numeric(size))
1050
1051 size <- headers[["content-length"]]
1052 if (!is.null(size))
1053 return(as.numeric(size))
1054
1055 return(-1L)
1056
1057 }
1058
1059 # select an appropriate download file method. we prefer curl
1060 # when available as it's the most user-customizable of all the
1061 # download methods; when not available, we fall back to libcurl
1062 # and wget (in that order). note that we don't want to use the
1063 # internal or wininet downloaders as we cannot set custom headers
1064 # with those methods. users can force a method with the
1065 # RENV_DOWNLOAD_FILE_METHOD environment variable but we generally
1066 # want to override a user-specified 'download.file.method'
1067 renv_download_method <- function() {
1068
1069 method <- Sys.getenv("RENV_DOWNLOAD_METHOD", unset = NA)
1070 if (!is.na(method))
1071 return(method)
1072
1073 method <- Sys.getenv("RENV_DOWNLOAD_FILE_METHOD", unset = NA)
1074 if (!is.na(method))
1075 return(method)
1076
1077 # prefer curl if available
1078 if (nzchar(Sys.which("curl")))
1079 return("curl")
1080
1081 # if curl is not available, use libcurl if available
1082 libcurl <- capabilities("libcurl")
1083 if (length(libcurl) && libcurl)
1084 return("libcurl")
1085
1086 # on windows, just use wininet here
1087 if (renv_platform_windows())
1088 return("wininet")
1089
1090 # if neither curl nor libcurl is available, prefer wget
1091 if (nzchar(Sys.which("wget")))
1092 return("wget")
1093
1094 # all else fails, use the internal downloader
1095 "internal"
1096
1097 }
1098
1099 renv_download_report <- function(elapsed, file) {
1100
1101 if (!renv_verbose())
1102 return()
1103
1104 info <- renv_file_info(file)
1105 size <- if (testing())
1106 "XXXX bytes"
1107 else
1108 structure(info$size, class = "object_size")
1109
1110 renv_report_ok(
1111 message = format(size, units = "auto"),
1112 elapsed = elapsed
1113 )
1114
1115 }
1116
1117 renv_download_check_archive <- function(destfile) {
1118
1119 # validate the file exists
1120 if (!file.exists(destfile))
1121 return(FALSE)
1122
1123 # validate archive type
1124 type <- renv_archive_type(destfile)
1125 if (type == "unknown")
1126 return(FALSE)
1127
1128 # try listing files in the archive
1129 tryCatch({renv_archive_list(destfile); TRUE}, error = identity)
1130
1131 }
1132
1133 renv_download_local <- function(url, destfile, headers) {
1134
1135 # only ever used for downloads from file URIs and server URIs
1136 ok <-
1137 grepl("^file:", url) ||
1138 !grepl("^[a-zA-Z]+://", url)
1139
1140 if (!ok)
1141 return(FALSE)
1142
1143 methods <- list(
1144 renv_download_local_copy,
1145 renv_download_local_default
1146 )
1147
1148 for (method in methods) {
1149
1150 # perform the copy
1151 before <- Sys.time()
1152 status <- catch(method(url, destfile, headers))
1153 after <- Sys.time()
1154
1155 # check for success
1156 if (!identical(status, TRUE))
1157 next
1158
1159 # report download summary
1160 elapsed <- difftime(after, before, units = "auto")
1161 renv_download_report(elapsed, destfile)
1162
1163 return(TRUE)
1164
1165 }
1166
1167 FALSE
1168
1169 }
1170
1171 renv_download_local_copy <- function(url, destfile, headers) {
1172
1173 # remove file prefix (to get path to local / server file)
1174 url <- case(
1175 startsWith(url, "file:///") ~ substring(url, 8L),
1176 startsWith(url, "file://") ~ substring(url, 6L),
1177 startsWith(url, "file:") ~ substring(url, 6L),
1178 TRUE ~ url
1179 )
1180
1181 # fix up file URIs to local paths on Windows
1182 if (renv_platform_windows()) {
1183 badpath <- grepl("^/[a-zA-Z]:", url)
1184 if (badpath)
1185 url <- substring(url, 2L)
1186 }
1187
1188 # attempt to copy
1189 ensure_parent_directory(destfile)
1190 status <- catchall(renv_file_copy(url, destfile, overwrite = TRUE))
1191 if (!identical(status, TRUE))
1192 return(FALSE)
1193
1194 TRUE
1195
1196 }
1197
1198 renv_download_local_default <- function(url, destfile, headers) {
1199
1200 status <- renv_download_impl(
1201 url = url,
1202 destfile = destfile,
1203 headers = headers
1204 )
1205
1206 identical(status, 0L)
1207
1208 }
1209
1210 renv_download_custom_headers <- function(url) {
1211 renv_bootstrap_download_custom_headers(url)
1212 }
1213
1214 renv_download_available <- function(url) {
1215
1216 # normalize separators (file URIs should normally use forward
1217 # slashes, even on Windows where the native separator is backslash)
1218 url <- chartr("\\", "/", url)
1219
1220 # on Windows, try using our local curl binary if available
1221 renv_scope_downloader()
1222
1223 # if we're not using curl, then use fallback method
1224 method <- renv_download_method()
1225 if (!identical(method, "curl"))
1226 return(renv_download_available_fallback(url))
1227
1228 # otherwise, try a couple candidate methods
1229 methods <- list(
1230 renv_download_available_headers,
1231 renv_download_available_range
1232 )
1233
1234 for (method in methods) {
1235 result <- catch(method(url))
1236 if (identical(result, TRUE))
1237 return(TRUE)
1238 }
1239
1240 FALSE
1241
1242 }
1243
1244 renv_download_available_headers <- function(url) {
1245
1246 status <- catchall(
1247 renv_download_headers(
1248 url = url,
1249 type = NULL,
1250 headers = renv_download_custom_headers(url)
1251 )
1252 )
1253
1254 if (inherits(status, "condition"))
1255 return(FALSE)
1256
1257 is.list(status) && length(status)
1258
1259 }
1260
1261 renv_download_available_range <- function(url) {
1262
1263 destfile <- renv_scope_tempfile("renv-download-")
1264
1265 # instruct curl to request only first byte
1266 extra <- c(
1267 if (identical(getOption("download.file.method"), "curl"))
1268 getOption("download.file.extra"),
1269 "-r 0-0"
1270 )
1271
1272 renv_scope_options(download.file.extra = paste(extra, collapse = " "))
1273
1274 # perform the download
1275 status <- catchall(
1276 renv_download_curl(
1277 url = url,
1278 destfile = destfile,
1279 type = NULL,
1280 request = "GET",
1281 headers = renv_download_custom_headers(url)
1282 )
1283 )
1284
1285 if (inherits(status, "condition"))
1286 return(FALSE)
1287
1288 # check for success
1289 identical(status, 0L)
1290
1291 }
1292
1293 renv_download_available_fallback <- function(url) {
1294
1295 destfile <- renv_scope_tempfile("renv-download-")
1296
1297 # just try downloading the requested URL
1298 status <- catchall(
1299 renv_download_impl(
1300 url = url,
1301 destfile = destfile,
1302 type = NULL,
1303 request = "GET",
1304 headers = renv_download_custom_headers(url)
1305 )
1306 )
1307
1308 if (inherits(status, "condition"))
1309 return(FALSE)
1310
1311 identical(status, 0L)
1312
1313 }
1314
1315 renv_download_error <- function(url, fmt, ...) {
1316 msg <- sprintf(fmt, ...)
1317 writef("\tERROR [%s]", msg)
1318 stopf("error downloading '%s' [%s]", url, msg, call. = FALSE)
1319 }
1320
1321 renv_download_trace <- function() {
1322 getOption("renv.download.trace", default = FALSE)
1323 }
1324
1325 renv_download_trace_begin <- function(url, type) {
1326
1327 if (!renv_download_trace())
1328 return()
1329
1330 fmt <- "Downloading '%s' [%s]"
1331 msg <- sprintf(fmt, url, type)
1332
1333 title <- header(msg, n = 78L)
1334 writef(c("", title, ""))
1335
1336 }
1337
1338 renv_download_trace_request <- function(text) {
1339
1340 if (!renv_download_trace())
1341 return()
1342
1343 title <- header("Request", n = 78L, prefix = "##")
1344 writef(c(title, text, ""))
1345
1346 }
1347
1348 renv_download_trace_result <- function(output) {
1349
1350 if (!renv_download_trace())
1351 return()
1352
1353 title <- header("Output", prefix = "##", n = 78L)
1354 text <- if (empty(output)) "[no output generated]" else output
1355 all <- c(title, text, "")
1356 writef(all)
1357
1358 status <- attr(output, "status", exact = TRUE) %||% 0L
1359 title <- header("Status", prefix = "##", n = 78L)
1360 all <- c(title, status, "")
1361 writef(all)
1362
1363 }