modules: support getting app_id in pw_check_flatpak

Support getting the Flatpak application ID from the .flatpak-info file,
similarly as what xdg-desktop-portal does.
This commit is contained in:
Pauli Virtanen 2022-07-30 21:29:42 +03:00 committed by Wim Taymans
parent 5e5339ce6c
commit 3730e54484
6 changed files with 89 additions and 5 deletions

View file

@ -28,20 +28,64 @@
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/vfs.h>
#include <spa/include/spa/utils/result.h>
#include "config.h"
#ifdef HAVE_GLIB2
#include <glib.h>
#endif
#include <spa/utils/result.h>
#include <pipewire/log.h>
static int pw_check_flatpak_parse_metadata(const char *buf, size_t size, char **app_id, char **devices)
{
#ifdef HAVE_GLIB2
/*
* See flatpak-metadata(5)
*
* The .flatpak-info file is in GLib key_file .ini format.
*/
g_autoptr(GKeyFile) metadata = NULL;
char *s;
static int pw_check_flatpak(pid_t pid)
metadata = g_key_file_new();
if (!g_key_file_load_from_data(metadata, buf, size, G_KEY_FILE_NONE, NULL))
return -EINVAL;
if (app_id) {
s = g_key_file_get_value(metadata, "Application", "name", NULL);
*app_id = s ? strdup(s) : NULL;
g_free(s);
}
if (devices) {
s = g_key_file_get_value(metadata, "Context", "devices", NULL);
*devices = s ? strdup(s) : NULL;
g_free(s);
}
return 0;
#else
return -ENOTSUP;
#endif
}
static int pw_check_flatpak(pid_t pid, char **app_id, char **devices)
{
#if defined(__linux__)
char root_path[2048];
int root_fd, info_fd, res;
struct stat stat_buf;
if (app_id)
*app_id = NULL;
if (devices)
*devices = NULL;
snprintf(root_path, sizeof(root_path), "/proc/%d/root", (int)pid);
root_fd = openat (AT_FDCWD, root_path, O_RDONLY | O_NONBLOCK | O_DIRECTORY | O_CLOEXEC | O_NOCTTY);
if (root_fd == -1) {
@ -77,6 +121,28 @@ static int pw_check_flatpak(pid_t pid)
if (fstat (info_fd, &stat_buf) != 0 || !S_ISREG (stat_buf.st_mode)) {
/* Some weird fd => failure, assume sandboxed */
pw_log_error("error fstat .flatpak-info: %m");
} else if (app_id || devices) {
/* Parse the application ID if needed */
const size_t size = stat_buf.st_size;
if (size > 0) {
void *buf = mmap(NULL, size, PROT_READ, MAP_PRIVATE, info_fd, 0);
if (buf != MAP_FAILED) {
res = pw_check_flatpak_parse_metadata(buf, size, app_id, devices);
munmap(buf, size);
} else {
res = -errno;
}
} else {
res = -EINVAL;
}
if (res == -EINVAL)
pw_log_error("PID %d .flatpak-info file is malformed",
(int)pid);
else if (res < 0)
pw_log_error("PID %d .flatpak-info parsing failed: %s",
(int)pid, spa_strerror(res));
}
close(info_fd);
return 1;