From fbe5a2faa776e0f5bdd6160c1dd69b0b97c2d8eb Mon Sep 17 00:00:00 2001 From: Sebastian Wick Date: Fri, 6 Feb 2026 17:14:49 +0100 Subject: [PATCH] utils: Add flatpak_parse_fd This is meant to parse file descriptor strings passed via the command line. It is not a security mechanism and will happily accept fds 0-3 as well. --- common/flatpak-context.c | 19 +++++++------------ common/flatpak-utils-private.h | 3 +++ common/flatpak-utils.c | 22 ++++++++++++++++++++++ 3 files changed, 32 insertions(+), 12 deletions(-) diff --git a/common/flatpak-context.c b/common/flatpak-context.c index 646c5ec5..b5206aab 100644 --- a/common/flatpak-context.c +++ b/common/flatpak-context.c @@ -1382,21 +1382,16 @@ option_env_fd_cb (const gchar *option_name, GError **error) { FlatpakContext *context = data; - guint64 fd; - gchar *endptr; - gboolean ret; + glnx_autofd int fd = -1; - fd = g_ascii_strtoull (value, &endptr, 10); + fd = flatpak_parse_fd (value, error); + if (fd < 0) + return FALSE; - if (endptr == NULL || *endptr != '\0' || fd > G_MAXINT) - return glnx_throw (error, "Not a valid file descriptor: %s", value); + if (fd < 3) + return glnx_throw (error, "File descriptors 0, 1, 2 are reserved"); - ret = flatpak_context_parse_env_fd (context, (int) fd, error); - - if (fd >= 3) - close (fd); - - return ret; + return flatpak_context_parse_env_fd (context, fd, error); } static gboolean diff --git a/common/flatpak-utils-private.h b/common/flatpak-utils-private.h index 7fe509f3..8f970ea2 100644 --- a/common/flatpak-utils-private.h +++ b/common/flatpak-utils-private.h @@ -348,6 +348,9 @@ gboolean running_under_sudo_root (void); void flatpak_set_debugging (gboolean debugging); gboolean flatpak_is_debugging (void); +int flatpak_parse_fd (const char *fd_string, + GError **error); + #define FLATPAK_MESSAGE_ID "c7b39b1e006b464599465e105b361485" #endif /* __FLATPAK_UTILS_H__ */ diff --git a/common/flatpak-utils.c b/common/flatpak-utils.c index 7bfa2ad1..7a30969c 100644 --- a/common/flatpak-utils.c +++ b/common/flatpak-utils.c @@ -2473,3 +2473,25 @@ flatpak_is_debugging (void) return is_debugging; } + +int +flatpak_parse_fd (const char *fd_string, + GError **error) +{ + guint64 parsed; + char *endptr; + int fd; + struct stat stbuf; + + parsed = g_ascii_strtoull (fd_string, &endptr, 10); + + if (endptr == NULL || *endptr != '\0' || parsed > G_MAXINT) + return glnx_fd_throw (error, "Not a valid file descriptor: %s", fd_string); + + fd = (int) parsed; + + if (!glnx_fstat (fd, &stbuf, error)) + return -1; + + return fd; +}