From 50af610ff417dfd66b9c8d7b7846698808a3abd8 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 7a70b057..6fdc9cdc 100644 --- a/common/flatpak-context.c +++ b/common/flatpak-context.c @@ -2432,21 +2432,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 b5dca744..efc534e9 100644 --- a/common/flatpak-utils-private.h +++ b/common/flatpak-utils-private.h @@ -365,6 +365,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); + #ifdef INCLUDE_INTERNAL_TESTS typedef void (*flatpak_test_fn) (void); void flatpak_add_test (const char *path, flatpak_test_fn fn); diff --git a/common/flatpak-utils.c b/common/flatpak-utils.c index 17480917..6ddaa90b 100644 --- a/common/flatpak-utils.c +++ b/common/flatpak-utils.c @@ -2582,6 +2582,28 @@ 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; +} + #ifdef INCLUDE_INTERNAL_TESTS static GList *flatpak_test_paths = NULL; static GList *flatpak_test_fns = NULL;