Hi all,

I'd like to propose a small change to the default HTTP User-Agent on Linux and 
a related fix to the `libcurl` download method.
The patch is attached and based on r90452.

(The patch and parts of this email have been assisted/refined with the help of 
AI, though the overall design and motivation is human-based).

Motivation
----------

Binary package repositories for Linux have to know which distribution and 
release a client is running, since a binary built for Ubuntu 24.04 is of no use 
on other distributions.
Today the default User-Agent tells a server the R version, platform, 
architecture and OS:

  R (4.7.0 x86_64-pc-linux-gnu x86_64 linux-gnu)

but nothing about the distribution.
If one wants to workaround this, a custom `HTTPUserAgent` must be set today.
I believe that the default user agent should include the distribution 
information, so that requests can be handled dynamically based on the 
underlying distribution (and their respective release).

A concrete case: cran.rpkgs.com
-------------------------------

I run https://cran.rpkgs.com, which serves CRAN binaries for several Linux 
distributions (Ubuntu, RHEL-compatible, Alpine) on both amd64 and arm64. The 
project is fully public and supported through an R consortium grant 
[(2025/1)](https://r-consortium.org/all-projects/2025-group-1.html#r-package-binaries-for-linux-community-edition).
Each distribution/releases combinations lives under its own path, for example

  https://cran.rpkgs.com/arm64/noble/latest
  https://cran.rpkgs.com/amd64/alpine321/latest

Hardcoding such a path works, but it ties a project's repos setting to one 
OS/arch combination, which breaks as soon as the same `renv.lock` or CI matrix 
runs on a different machine.

What users actually want is a single repository URL, https://cran.rpkgs.com, 
and have the server pick the right binary for them in a dynamic way.
That is possible today, but only after pasting a dozen lines into 
`Rprofile.site` that read `/etc/os-release` and rebuild `HTTPUserAgent` by hand.
In practice most people never do this. On top, it feels “hacky” and also 
doesn’t show a good light on R as with respect to package distribution and 
handling. Pretty much any other language handles this case dynamically for 
their main repositories.

With the proposed patch the default header already carries everything needed: 
the architecture from `R.version$arch`, and the distribution, release and 
codename from `os-release`.
A stock R installation could then use one repository URL on any supported Linux 
system and be routed to the matching binaries, with no client-side 
configuration at all - assuming the backend is capable of dynamically routing 
the requests as needed.

What the patch does in detail
-------------------

1. On Linux, utils reads `/etc/os-release` (falling back to 
`/usr/lib/os-release`) and appends the `ID`, `VERSION_ID` and 
`VERSION_CODENAME` fields to the default User-Agent.
   On Ubuntu the result looks like

     ```
     R (4.7.0 aarch64-unknown-linux-gnu aarch64 linux-gnu; distro=ubuntu; 
version=26.04; codename=resolute)
     ```

   Other platforms are unchanged.

2. The `libcurl` method now sends whatever `HTTPUserAgent` is set to, like the 
other methods do.
   More on why below.

3. `NEWS.Rd` and `options.Rd` are updated, and a small test file is added under 
`src/library/utils/tests`.

The parser
----------

The reader is deliberately minimal and does not source the file.
It strips surrounding quotes, does not interpret escape sequences, takes the 
last assignment of a key (as os-release specifies), and only accepts values 
made of ASCII letters, digits, dots, underscores and hyphens.
Anything else is silently dropped, so a malformed or hostile os-release cannot 
inject arbitrary text into an HTTP header.
Descriptive fields such as PRETTY_NAME are not used.
ID_LIKE is left out for now because it is a space-separated list; it could be 
added later if repositories need it.

utils already reads /etc/os-release in .osVersion() at load time.
I kept the new reader separate to keep the patch small, but I'd be happy to 
merge the two into one helper, which would also give osVersion the 
/usr/lib/os-release fallback.
The extra cost at package load is one small file read on Linux.

Why the libcurl change is needed
--------------------------------

`libcurl.c` currently ignores any `HTTPUserAgent` value that starts with `R (` 
and sends `libcurl/<version>` instead; `options.Rd` documents this as a 
reserved prefix.
Since `libcurl` is the default method on Linux, the new identifiers would never 
actually reach a server without changing this.

The reservation is also only a heuristic: the C code cannot tell a 
user-supplied value starting with `R (` from the utils default, so a user who 
sets such a value on purpose currently has it replaced without notice.
The patch removes the special case so that all methods send the configured 
value, and `options.Rd` is adjusted accordingly.
If R Core would rather keep a libcurl-specific default, an alternative would be 
for utils to set the option only for non-libcurl methods, though that seems 
more fragile in my view.

Note: Users can still override or disable the header via `options(HTTPUserAgent 
= …)` exactly as before.

Privacy
-------

The added fields modestly increase what a server can learn about a client, 
although the header already reveals R version, architecture and platform.
If exposing them by default is considered too broad, I'm happy to rework this 
as an opt-in (e.g. via an env var or adjacent option) while keeping the parser 
and the `libcurl` fix.

Testing
-------

Build and tested on a checkout of `r90452` on x86_64 Linux with GCC 16 and 
libcurl 8.21.0.

The new tests in `src/library/utils/tests/user-agent.R` cover quoted and 
unquoted values, Alpine on linux-musl, a rolling release without `VERSION_ID`, 
duplicate keys and surrounding whitespace, unsafe values, a missing file, a 
directory in place of the file, and non-Linux platforms.

`tests/download.file.R` passes over HTTP and HTTPS and confirms that libcurl 
now transmits the R User-Agent.
A live request from this machine sent

  ```
  R (4.7.0 x86_64-pc-linux-gnu x86_64 linux-gnu; distro=almalinux; version=10.2)
  ```

`make check` passed the package examples.

I hope this patch can make it in at some point; I consider it as very important 
for the future of a modern R package/repository management.

Best,
Patrick Schratz
https://pat-s.me
diff --git a/doc/NEWS.Rd b/doc/NEWS.Rd
index 1ebd0b3682..878faf9544 100644
--- a/doc/NEWS.Rd
+++ b/doc/NEWS.Rd
@@ -125,6 +125,11 @@
 
   \subsection{Utilities}{
     \itemize{
+      \item The default HTTP user agent on Linux now includes
+      machine-readable distribution identifiers from \file{os-release} when
+      available.  The \samp{libcurl} download method now uses the same default
+      user agent as the other HTTP methods.
+
       \item \code{tools::texi2pdf()} now reports BibTeX warnings;
       in particular, missing references are now noted by
       \command{R CMD check} when re-building PDF vignettes.
diff --git a/src/library/base/man/options.Rd b/src/library/base/man/options.Rd
index 114bdb27c1..2dba451c56 100644
--- a/src/library/base/man/options.Rd
+++ b/src/library/base/man/options.Rd
@@ -707,12 +707,10 @@ getOption(x, default = NULL)
       HTTP(S) requests by \code{\link{download.file}}, \code{\link{url}}
       and \code{\link{curlGetHeaders}}, or \code{NULL} when requests will
       be made without a user agent header.  The default is
-      \code{"R (\var{version} \var{platform} \var{arch} \var{os})"}
-      except when \samp{libcurl} is used when it is
-      \code{"libcurl/\var{version}"} for the \samp{libcurl} version in use.
-      With \samp{libcurl}, the \code{"R "} prefix is reserved:
-      \code{HTTPUserAgent} with the prefix will be ignored and the default will
-      be used.}
+      \code{"R (\var{version} \var{platform} \var{arch} \var{os})"}.
+      On Linux, machine-readable distribution identifiers from
+      \file{/etc/os-release} or \file{/usr/lib/os-release} are appended when
+      available.}
 
     \item{\code{install.lock}:}{logical: should per-directory package
       locking be used by \code{\link{install.packages}}?  Most useful
diff --git a/src/library/utils/R/readhttp.R b/src/library/utils/R/readhttp.R
index e441ea7882..ffef100132 100644
--- a/src/library/utils/R/readhttp.R
+++ b/src/library/utils/R/readhttp.R
@@ -1,7 +1,7 @@
 #  File src/library/utils/R/readhttp.R
 #  Part of the R package, https://www.R-project.org
 #
-#  Copyright (C) 1995-2012 The R Core Team
+#  Copyright (C) 1995-2026 The R Core Team
 #
 #  This program is free software; you can redistribute it and/or modify
 #  it under the terms of the GNU General Public License as published by
@@ -26,6 +26,35 @@
 }
 
 
+.linuxOSRelease <- function(files = c("/etc/os-release", 
"/usr/lib/os-release"),
+                            os = R.version$os)
+{
+    if (!startsWith(os, "linux")) return(character())
+
+    files <- files[file_test("-f", files)]
+    if (!length(files)) return(character())
+    lines <- tryCatch(suppressWarnings(readLines(files[1L], warn = FALSE)),
+                      error = function(e) character())
+    if (!length(lines)) return(character())
+
+    value <- function(key) {
+        ## os-release: the last assignment of a key wins
+        line <- rev(grep(paste0("^", key, "="), lines, value = TRUE))[1L]
+        if (is.na(line)) return("")
+        ans <- trimws(substring(line, nchar(key) + 2L))
+        if (grepl('^".*"$', ans) || grepl("^'.*'$", ans))
+            ans <- substring(ans, 2L, nchar(ans) - 1L)
+        if (!grepl("^[A-Za-z0-9._-]+$", ans)) "" else ans
+    }
+
+    ans <- c(distro = value("ID"), version = value("VERSION_ID"),
+             codename = value("VERSION_CODENAME"))
+    ans[nzchar(ans)]
+}
+
 
 defaultUserAgent <- function()
 {
@@ -34,6 +63,11 @@
                       if (length(grep("^darwin", R.version$os))) ## use 
run-time (vs build)
                         gsub(" ","",tolower(system("uname -sr 
2>/dev/null||echo darwin", intern=TRUE)))
                       else R.version$os)
+    distro <- .linuxOSRelease()
+    if (length(distro))
+        Rdetails <- paste0(Rdetails, "; ",
+                           paste(names(distro), distro, sep = "=",
+                                 collapse = "; "))
     paste0("R (", Rdetails, ")")
 }
 
diff --git a/src/library/utils/tests/user-agent.R 
b/src/library/utils/tests/user-agent.R
new file mode 100644
index 0000000000..4bb2847f8d
--- /dev/null
+++ b/src/library/utils/tests/user-agent.R
@@ -0,0 +1,49 @@
+## Test machine-readable Linux distribution details in the default user agent.
+
+write_os_release <- function(lines) {
+    path <- tempfile()
+    writeLines(lines, path)
+    path
+}
+
+ubuntu <- write_os_release(c(
+    'NAME="Ubuntu"',
+    'ID=ubuntu',
+    'VERSION_ID="26.04"',
+    'VERSION_CODENAME=resolute'
+))
+info <- utils:::.linuxOSRelease(ubuntu, os = "linux-gnu")
+stopifnot(identical(info, c(
+    distro = "ubuntu", version = "26.04", codename = "resolute"
+)))
+
+alpine <- write_os_release(c("ID=alpine", 'VERSION_ID="3.24.1"'))
+info <- utils:::.linuxOSRelease(alpine, os = "linux-musl")
+stopifnot(identical(info, c(distro = "alpine", version = "3.24.1")))
+
+unsafe <- write_os_release(c(
+    "ID=example", "VERSION_ID=1.0", "VERSION_CODENAME=bad/value"
+))
+info <- utils:::.linuxOSRelease(unsafe, os = "linux-gnu")
+stopifnot(identical(info, c(distro = "example", version = "1.0")))
+
+dups <- write_os_release(c("ID=first", "ID=last", 'VERSION_ID="2.0"  '))
+info <- utils:::.linuxOSRelease(dups, os = "linux-gnu")
+stopifnot(identical(info, c(distro = "last", version = "2.0")))
+
+rolling <- write_os_release("ID=arch")
+info <- utils:::.linuxOSRelease(rolling, os = "linux-gnu")
+stopifnot(identical(info, c(distro = "arch")))
+
+stopifnot(!length(utils:::.linuxOSRelease(ubuntu, os = "darwin23")))
+stopifnot(!length(utils:::.linuxOSRelease(tempfile(), os = "linux-gnu")))
+
+dir <- tempfile(); dir.create(dir)
+info <- withCallingHandlers(utils:::.linuxOSRelease(dir, os = "linux-gnu"),
+                            warning = function(w) stop(w))
+stopifnot(!length(info))
+
+unlink(c(ubuntu, alpine, unsafe, dups, rolling, dir), recursive = TRUE)
diff --git a/src/modules/internet/libcurl.c b/src/modules/internet/libcurl.c
index 2b07785d2a..e65e01c6e6 100644
--- a/src/modules/internet/libcurl.c
+++ b/src/modules/internet/libcurl.c
@@ -288,11 +288,8 @@ void curlCommon(CURL *hnd, int redirect, int verify)
     if (TYPEOF(sua) == STRSXP && LENGTH(sua) == 1 ) {
        const void *vmax = vmaxget();
        const char *p = translateChar(STRING_ELT(sua, 0));
-       if (p[0] && p[1] && p[2] && p[0] == 'R' && p[1] == ' ' && p[2] == '(') {
-       } else {
-           Default = 0;
-           curl_easy_setopt(hnd, CURLOPT_USERAGENT, p);
-       }
+       Default = 0;
+       curl_easy_setopt(hnd, CURLOPT_USERAGENT, p);
        vmaxset(vmax);
     }
     if (Default) {
diff --git a/tests/download.file.R b/tests/download.file.R
index fa73fceda9..2465fc33be 100644
--- a/tests/download.file.R
+++ b/tests/download.file.R
@@ -61,6 +61,12 @@ with_options <- function(opts, expr) {
 
 tests <- function() {
   cat("- User agent is still set\n")
+  with_options(list(HTTPUserAgent = utils:::defaultUserAgent()), {
+    h <- get_headers()
+    stopifnot(grep_hdr("User-Agent.*R \\(", h))
+  })
+
   with_options(list(HTTPUserAgent = "foobar"), {
     h <- get_headers()
     stopifnot(grep_hdr("User-Agent.*foobar", h))
______________________________________________
[email protected] mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel

Reply via email to