From b01f6a3b42646ac66305446827c4b1761c20a197 Mon Sep 17 00:00:00 2001 From: deepend-tildeclub Date: Thu, 3 Sep 2026 15:19:21 -0600 Subject: [PATCH 01/15] bring sysinfo into 2026 --- plugins/sysinfo/meson.build | 84 +- plugins/sysinfo/sysinfo.c | 39 +- plugins/sysinfo/unix/modern-backend.c | 1089 +++++++++++++++++++++++++ plugins/sysinfo/win32/backend.c | 786 ++++++++++++++++-- 4 files changed, 1874 insertions(+), 124 deletions(-) create mode 100644 plugins/sysinfo/unix/modern-backend.c diff --git a/plugins/sysinfo/meson.build b/plugins/sysinfo/meson.build index c95ebc01..420d28c4 100644 --- a/plugins/sysinfo/meson.build +++ b/plugins/sysinfo/meson.build @@ -6,50 +6,66 @@ sysinfo_sources = [ sysinfo_deps = [ libgio_dep, zoitechat_plugin_dep, - common_sysinfo_deps, ] sysinfo_includes = [] sysinfo_cargs = ['-DHAVE_CONFIG_H'] system = host_machine.system() -if system == 'linux' or system == 'gnu' or system.startswith('gnu/') or system == 'darwin' or system == 'freebsd' - sysinfo_includes += 'shared' - sysinfo_sources += [ - 'shared/df.c' - ] - - if system == 'linux' or system == 'gnu' or system.startswith('gnu/') or system == 'freebsd' - libpci = dependency('libpci', required: false, method: 'pkg-config') - if libpci.found() - sysinfo_deps += libpci - sysinfo_cargs += '-DHAVE_LIBPCI' - sysinfo_sources += 'unix/pci.c' - - picidsdir = libpci.get_variable(pkgconfig : 'idsdir') - pciids = join_paths(picidsdir, 'pci.ids') - sysinfo_cargs += '-DPCIIDS_FILE="@0@"'.format(pciids) - endif - if get_option('gtk-frontend') - sysinfo_deps += dependency('gtk+-3.0', version: '>= 3.22') - endif - - sysinfo_includes += 'unix' - sysinfo_sources += [ - 'unix/backend.c', - 'unix/match.c', - 'unix/parse.c', - ] - elif system == 'darwin' - add_languages('objc') - sysinfo_sources += 'osx/backend.m' +if system == 'linux' or system == 'gnu' or system.startswith('gnu/') + if get_option('gtk-frontend') + sysinfo_deps += dependency('gtk+-3.0', version: '>= 3.22') endif -elif system == 'windows' + libpci = dependency('libpci', required: false, method: 'pkg-config') + if libpci.found() + sysinfo_deps += libpci + sysinfo_cargs += '-DHAVE_LIBPCI' + endif + + sysinfo_includes += 'unix' + sysinfo_sources += 'unix/modern-backend.c' + +elif system == 'freebsd' + sysinfo_includes += ['shared', 'unix'] sysinfo_sources += [ - 'win32/backend.c', - '../../src/common/sysinfo/win32/backend.c' + 'shared/df.c', + 'unix/backend.c', + 'unix/match.c', + 'unix/parse.c', ] + + libpci = dependency('libpci', required: false, method: 'pkg-config') + if libpci.found() + sysinfo_deps += libpci + sysinfo_cargs += '-DHAVE_LIBPCI' + sysinfo_sources += 'unix/pci.c' + + picidsdir = libpci.get_pkgconfig_variable('idsdir') + pciids = join_paths(picidsdir, 'pci.ids') + sysinfo_cargs += '-DPCIIDS_FILE="@0@"'.format(pciids) + endif + + if get_option('gtk-frontend') + sysinfo_deps += dependency('gtk+-3.0', version: '>= 3.22') + endif + +elif system == 'darwin' + sysinfo_includes += 'shared' + sysinfo_sources += 'shared/df.c' + add_languages('objc') + sysinfo_sources += 'osx/backend.m' + +elif system == 'windows' + cc = meson.get_compiler('c') + sysinfo_deps += [ + cc.find_library('advapi32', required: true), + cc.find_library('dxgi', required: true), + cc.find_library('dxguid', required: true), + cc.find_library('iphlpapi', required: true), + cc.find_library('winmm', required: true), + ] + sysinfo_sources += 'win32/backend.c' else error('sysinfo: Unknown system?') endif diff --git a/plugins/sysinfo/sysinfo.c b/plugins/sysinfo/sysinfo.c index 21c50bbb..fa46a5c8 100644 --- a/plugins/sysinfo/sysinfo.c +++ b/plugins/sysinfo/sysinfo.c @@ -40,8 +40,8 @@ static zoitechat_plugin *ph; static char name[] = "Sysinfo"; static char desc[] = "Display info about your hardware and OS"; -static char version[] = "1.0"; -static char sysinfo_help[] = "SysInfo Usage:\n /SYSINFO [-e|-o] [CLIENT|UI|OS|CPU|RAM|STORAGE|GPU|CHIPSET|SOUND|ETHERNET|UPTIME], print various details about your system or print a summary without arguments\n /SYSINFO SET \n"; +static char version[] = "2.0"; +static char sysinfo_help[] = "SysInfo Usage:\n /SYSINFO [-e|-o] [CLIENT|UI|OS|CPU|RAM|MEMORY|STORAGE|DISK|GPU|VGA|CHIPSET|SOUND|NETWORK|ETHERNET|UPTIME], print various details about your system or print a summary without arguments\n /SYSINFO SET \n"; typedef struct { @@ -68,11 +68,15 @@ static hwinfo hwinfos[] = { {"os", "OS", sysinfo_backend_get_os}, {"cpu", "CPU", sysinfo_backend_get_cpu}, {"memory", "Memory", sysinfo_backend_get_memory}, +#if defined(__linux__) + {"storage", "Storage", sysinfo_backend_get_disk, FALSE}, +#else {"storage", "Storage", sysinfo_backend_get_disk, TRUE}, +#endif {"gpu", "GPU", sysinfo_backend_get_gpu}, - {"chipset", "CHIPSET", sysinfo_backend_get_chipset, TRUE}, + {"chipset", "Chipset", sysinfo_backend_get_chipset, TRUE}, {"sound", "Sound", sysinfo_backend_get_sound, TRUE}, - {"ethernet", "Ethernet", sysinfo_backend_get_network, TRUE}, + {"ethernet", "Network", sysinfo_backend_get_network, TRUE}, {"uptime", "Uptime", sysinfo_backend_get_uptime}, {NULL, NULL}, }; @@ -115,14 +119,30 @@ print_summary (gboolean announce) g_free (output); } +static const char * +normalize_info_name (const char *info) +{ + if (!g_ascii_strcasecmp (info, "ram")) + return "memory"; + if (!g_ascii_strcasecmp (info, "disk")) + return "storage"; + if (!g_ascii_strcasecmp (info, "vga")) + return "gpu"; + if (!g_ascii_strcasecmp (info, "network")) + return "ethernet"; + + return info; +} + static void print_info (char *info, gboolean announce) { + const char *normalized = normalize_info_name (info); int i; for (i = 0; hwinfos[i].name != NULL; i++) { - if (!g_ascii_strcasecmp (info, hwinfos[i].name)) + if (!g_ascii_strcasecmp (normalized, hwinfos[i].name)) { char *str = hwinfos[i].callback(); if (str) @@ -183,12 +203,17 @@ sysinfo_set_pref (char *key, char *value) } else if (g_str_has_prefix (key, "hide_")) { + const char *normalized = normalize_info_name (key + 5); int i; + for (i = 0; hwinfos[i].name != NULL; i++) { - if (!strcmp (key + 5, hwinfos[i].name)) + if (!strcmp (normalized, hwinfos[i].name)) { - sysinfo_set_pref_real (key, value, hwinfos[i].def); + char canonical[32]; + + g_snprintf (canonical, sizeof (canonical), "hide_%s", hwinfos[i].name); + sysinfo_set_pref_real (canonical, value, hwinfos[i].def); return; } } diff --git a/plugins/sysinfo/unix/modern-backend.c b/plugins/sysinfo/unix/modern-backend.c new file mode 100644 index 00000000..56425036 --- /dev/null +++ b/plugins/sysinfo/unix/modern-backend.c @@ -0,0 +1,1089 @@ +/* + * Modern Linux SysInfo backend for ZoiteChat. + * + * Uses native kernel/sysfs interfaces and caches static hardware data. + */ + +#include +#include +#include +#include +#include +#include + +#include + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#if defined(USE_GTK_FRONTEND) +#include +#endif + +#ifdef HAVE_LIBPCI +#include +#endif + +#include "../format.h" +#include "../sysinfo-backend.h" + +#define SYSINFO_SEP " \xC2\xB7 " + +typedef struct +{ + char *os; + char *cpu; + char *gpu; + char *chipset; + char *sound; + GHashTable *pci_names; +} LinuxStaticSnapshot; + +static LinuxStaticSnapshot snapshot; +static gsize os_initialized = 0; +static gsize cpu_initialized = 0; +static gsize pci_initialized = 0; +static gsize sound_initialized = 0; + +static char *read_trimmed_file (const char *path); +static gboolean read_hex_file (const char *path, guint *value); +static char *join_ptr_array (GPtrArray *items, const char *separator); +static void ptr_array_add_unique (GPtrArray *items, const char *value); +static char *read_os_pretty_name (void); +static char *read_cpu_model (void); +static guint count_physical_cores (void); +static char *build_cpu_string (void); +static char *build_sound_string (void); +static void scan_pci_devices (void); +static void ensure_os_snapshot (void); +static void ensure_cpu_snapshot (void); +static void ensure_pci_snapshot (void); +static void ensure_sound_snapshot (void); +static char *format_usage (guint64 total, guint64 available); +static char *read_driver_name (const char *interface_path); + +static char * +read_trimmed_file (const char *path) +{ + char *contents = NULL; + gsize length = 0; + + if (!g_file_get_contents (path, &contents, &length, NULL)) + { + return NULL; + } + + g_strstrip (contents); + if (contents[0] == '\0') + { + g_free (contents); + return NULL; + } + + return contents; +} + +static gboolean +read_hex_file (const char *path, guint *value) +{ + char *contents; + char *end = NULL; + guint64 parsed; + + contents = read_trimmed_file (path); + if (!contents) + { + return FALSE; + } + + errno = 0; + parsed = g_ascii_strtoull (contents, &end, 16); + if (errno != 0 || end == contents) + { + g_free (contents); + return FALSE; + } + + *value = (guint) parsed; + g_free (contents); + return TRUE; +} + +static char * +join_ptr_array (GPtrArray *items, const char *separator) +{ + GString *joined; + guint i; + + if (!items || items->len == 0) + { + return NULL; + } + + joined = g_string_new (NULL); + for (i = 0; i < items->len; i++) + { + const char *item = g_ptr_array_index (items, i); + + if (i != 0) + { + g_string_append (joined, separator); + } + g_string_append (joined, item); + } + + return g_string_free (joined, FALSE); +} + +static void +ptr_array_add_unique (GPtrArray *items, const char *value) +{ + guint i; + + if (!value || value[0] == '\0') + { + return; + } + + for (i = 0; i < items->len; i++) + { + const char *existing = g_ptr_array_index (items, i); + if (g_strcmp0 (existing, value) == 0) + { + return; + } + } + + g_ptr_array_add (items, g_strdup (value)); +} + +static char * +unquote_os_release_value (const char *value) +{ + char *copy; + gsize len; + + if (!value) + { + return NULL; + } + + copy = g_strdup (value); + g_strstrip (copy); + len = strlen (copy); + + if (len >= 2 && + ((copy[0] == '"' && copy[len - 1] == '"') || + (copy[0] == '\'' && copy[len - 1] == '\''))) + { + copy[len - 1] = '\0'; + memmove (copy, copy + 1, len - 1); + } + + return copy; +} + +static char * +read_pretty_name_from_os_release (const char *path) +{ + char *contents = NULL; + char **lines; + char *result = NULL; + guint i; + + if (!g_file_get_contents (path, &contents, NULL, NULL)) + { + return NULL; + } + + lines = g_strsplit (contents, "\n", -1); + for (i = 0; lines[i] != NULL; i++) + { + if (g_str_has_prefix (lines[i], "PRETTY_NAME=")) + { + result = unquote_os_release_value (lines[i] + strlen ("PRETTY_NAME=")); + break; + } + } + + g_strfreev (lines); + g_free (contents); + return result; +} + +static char * +read_os_pretty_name (void) +{ + char *pretty = NULL; + + /* Flatpak exposes the host os-release here. Prefer it over the runtime. */ + if (g_file_test ("/run/host/etc/os-release", G_FILE_TEST_IS_REGULAR)) + { + pretty = read_pretty_name_from_os_release ("/run/host/etc/os-release"); + } + + if (!pretty) + { + pretty = g_get_os_info (G_OS_INFO_KEY_PRETTY_NAME); + } + + if (!pretty) + { + pretty = read_pretty_name_from_os_release ("/etc/os-release"); + } + + return pretty ? pretty : g_strdup ("Linux"); +} + +static char * +read_cpu_model (void) +{ + FILE *fp; + char line[1024]; + static const char *keys[] = { + "model name", + "Hardware", + "Processor", + "cpu model", + "Model Name", + NULL + }; + + fp = fopen ("/proc/cpuinfo", "r"); + if (fp) + { + while (fgets (line, sizeof (line), fp) != NULL) + { + char *colon = strchr (line, ':'); + guint i; + + if (!colon) + { + continue; + } + + *colon = '\0'; + g_strstrip (line); + for (i = 0; keys[i] != NULL; i++) + { + if (g_ascii_strcasecmp (line, keys[i]) == 0) + { + char *value = g_strdup (colon + 1); + char *endptr = NULL; + g_strstrip (value); + + /* + * On x86 /proc/cpuinfo starts with `processor : 0`. + * `Processor` is also a useful model key on some ARM systems, + * so only reject it when the value is purely a CPU index. + */ + if (g_ascii_strcasecmp (keys[i], "Processor") == 0 && value[0] != '\0') + { + g_ascii_strtoull (value, &endptr, 10); + if (endptr && endptr != value && *endptr == '\0') + { + g_free (value); + continue; + } + } + + if (value[0] != '\0') + { + fclose (fp); + return value; + } + g_free (value); + } + } + } + fclose (fp); + } + + if (g_file_test ("/sys/firmware/devicetree/base/model", G_FILE_TEST_IS_REGULAR)) + { + char *model = read_trimmed_file ("/sys/firmware/devicetree/base/model"); + if (model) + { + return model; + } + } + + return g_strdup ("Unknown CPU"); +} + +static guint +count_physical_cores (void) +{ + GDir *dir; + const char *entry; + GHashTable *cores; + guint count; + + dir = g_dir_open ("/sys/devices/system/cpu", 0, NULL); + if (!dir) + { + return 0; + } + + cores = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL); + while ((entry = g_dir_read_name (dir)) != NULL) + { + char *package_path; + char *core_path; + char *package_id; + char *core_id; + char *key; + + if (!g_str_has_prefix (entry, "cpu") || !g_ascii_isdigit (entry[3])) + { + continue; + } + + package_path = g_build_filename ("/sys/devices/system/cpu", entry, "topology", "physical_package_id", NULL); + core_path = g_build_filename ("/sys/devices/system/cpu", entry, "topology", "core_id", NULL); + package_id = read_trimmed_file (package_path); + core_id = read_trimmed_file (core_path); + g_free (package_path); + g_free (core_path); + + if (!package_id || !core_id) + { + g_free (package_id); + g_free (core_id); + continue; + } + + key = g_strdup_printf ("%s:%s", package_id, core_id); + g_hash_table_add (cores, key); + g_free (package_id); + g_free (core_id); + } + + count = g_hash_table_size (cores); + g_hash_table_destroy (cores); + g_dir_close (dir); + return count; +} + +static char * +build_cpu_string (void) +{ + char *model; + long logical_long; + guint logical; + guint physical; + + model = read_cpu_model (); + logical_long = sysconf (_SC_NPROCESSORS_ONLN); + logical = logical_long > 0 ? (guint) logical_long : 0; + physical = count_physical_cores (); + + if (physical == 0) + { + physical = logical; + } + + if (physical != 0 && logical != 0) + { + char *result = g_strdup_printf ("%s" SYSINFO_SEP "%uC/%uT", model, physical, logical); + g_free (model); + return result; + } + + return model; +} + + +static char * +build_sound_string (void) +{ + FILE *fp; + char line[1024]; + GPtrArray *cards; + char *result; + + fp = fopen ("/proc/asound/cards", "r"); + if (!fp) + { + return NULL; + } + + cards = g_ptr_array_new_with_free_func (g_free); + while (fgets (line, sizeof (line), fp) != NULL) + { + char *start = line; + char *separator; + char *name; + + while (*start && g_ascii_isspace (*start)) + { + start++; + } + if (!g_ascii_isdigit (*start)) + { + continue; + } + + separator = strstr (start, " - "); + if (!separator) + { + continue; + } + + name = g_strdup (separator + 3); + g_strstrip (name); + ptr_array_add_unique (cards, name); + g_free (name); + } + fclose (fp); + + result = join_ptr_array (cards, ", "); + g_ptr_array_free (cards, TRUE); + return result; +} + +#ifdef HAVE_LIBPCI +static char * +resolve_pci_name (struct pci_access *pacc, guint vendor, guint device) +{ + char name[1024]; + char *resolved; + + resolved = pci_lookup_name (pacc, name, sizeof (name), + PCI_LOOKUP_VENDOR | PCI_LOOKUP_DEVICE, + vendor, device); + if (resolved && resolved[0] != '\0') + { + return g_strdup (resolved); + } + + return g_strdup_printf ("%04x:%04x", vendor, device); +} +#endif + +static char * +clean_gpu_name (const char *raw_name) +{ + static const char *vendor_prefixes[] = { + "NVIDIA Corporation ", + "Advanced Micro Devices, Inc. [AMD/ATI] ", + "Advanced Micro Devices, Inc. ", + "Intel Corporation ", + NULL + }; + char *name; + char *open; + char *close; + guint i; + + if (!raw_name || raw_name[0] == '\0') + return NULL; + + name = g_strdup (raw_name); + g_strstrip (name); + + /* Prefer the friendly product name at the end of pci.ids entries. */ + close = strrchr (name, ']'); + open = strrchr (name, '['); + if (open && close && close > open + 1 && close[1] == '\0') + { + char *clean; + + *close = '\0'; + clean = g_strdup (open + 1); + g_strstrip (clean); + if (clean[0] != '\0') + { + g_free (name); + return clean; + } + g_free (clean); + } + + /* Fall back to removing common PCI vendor prefixes. */ + for (i = 0; vendor_prefixes[i] != NULL; i++) + { + if (g_str_has_prefix (name, vendor_prefixes[i])) + { + char *clean = g_strdup (name + strlen (vendor_prefixes[i])); + g_strstrip (clean); + if (clean[0] != '\0') + { + g_free (name); + return clean; + } + g_free (clean); + } + } + + return name; +} + +static void +scan_pci_devices (void) +{ + GDir *dir; + const char *entry; + GPtrArray *gpus; + GPtrArray *chipsets; +#ifdef HAVE_LIBPCI + struct pci_access *pacc = NULL; +#endif + + snapshot.pci_names = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free); + gpus = g_ptr_array_new_with_free_func (g_free); + chipsets = g_ptr_array_new_with_free_func (g_free); + +#ifdef HAVE_LIBPCI + pacc = pci_alloc (); + if (pacc) + { + pci_init (pacc); + } +#endif + + dir = g_dir_open ("/sys/bus/pci/devices", 0, NULL); + if (dir) + { + while ((entry = g_dir_read_name (dir)) != NULL) + { + char *class_path; + char *vendor_path; + char *device_path; + char *name; + char *key; + guint class_code; + guint vendor; + guint device; + guint base_class; + guint class_subclass; + + class_path = g_build_filename ("/sys/bus/pci/devices", entry, "class", NULL); + vendor_path = g_build_filename ("/sys/bus/pci/devices", entry, "vendor", NULL); + device_path = g_build_filename ("/sys/bus/pci/devices", entry, "device", NULL); + + if (!read_hex_file (class_path, &class_code) || + !read_hex_file (vendor_path, &vendor) || + !read_hex_file (device_path, &device)) + { + g_free (class_path); + g_free (vendor_path); + g_free (device_path); + continue; + } + + g_free (class_path); + g_free (vendor_path); + g_free (device_path); + +#ifdef HAVE_LIBPCI + if (pacc) + { + name = resolve_pci_name (pacc, vendor, device); + } + else +#endif + { + name = g_strdup_printf ("%04x:%04x", vendor, device); + } + + key = g_strdup_printf ("%04x:%04x", vendor, device); + if (!g_hash_table_contains (snapshot.pci_names, key)) + { + g_hash_table_insert (snapshot.pci_names, key, g_strdup (name)); + } + else + { + g_free (key); + } + + base_class = (class_code >> 16) & 0xff; + class_subclass = (class_code >> 8) & 0xffff; + + if (base_class == 0x03) + { + char *gpu_name = clean_gpu_name (name); + if (gpu_name) + { + ptr_array_add_unique (gpus, gpu_name); + g_free (gpu_name); + } + } + else if (class_subclass == 0x0600) + { + ptr_array_add_unique (chipsets, name); + } + + g_free (name); + } + g_dir_close (dir); + } + +#ifdef HAVE_LIBPCI + if (pacc) + { + pci_cleanup (pacc); + } +#endif + + snapshot.gpu = join_ptr_array (gpus, ", "); + snapshot.chipset = join_ptr_array (chipsets, ", "); + g_ptr_array_free (gpus, TRUE); + g_ptr_array_free (chipsets, TRUE); +} + +static char * +build_os_string (void) +{ + char *pretty; + struct utsname uts; + char *result; + + pretty = read_os_pretty_name (); + if (uname (&uts) != 0) + { + return pretty; + } + + result = g_strdup_printf ("%s" SYSINFO_SEP "%s %s" SYSINFO_SEP "%s", + pretty, uts.sysname, uts.release, uts.machine); + g_free (pretty); + return result; +} + +static void +ensure_os_snapshot (void) +{ + if (g_once_init_enter (&os_initialized)) + { + snapshot.os = build_os_string (); + g_once_init_leave (&os_initialized, 1); + } +} + +static void +ensure_cpu_snapshot (void) +{ + if (g_once_init_enter (&cpu_initialized)) + { + snapshot.cpu = build_cpu_string (); + g_once_init_leave (&cpu_initialized, 1); + } +} + +static void +ensure_pci_snapshot (void) +{ + if (g_once_init_enter (&pci_initialized)) + { + scan_pci_devices (); + g_once_init_leave (&pci_initialized, 1); + } +} + +static void +ensure_sound_snapshot (void) +{ + if (g_once_init_enter (&sound_initialized)) + { + snapshot.sound = build_sound_string (); + g_once_init_leave (&sound_initialized, 1); + } +} + +static char * +format_usage (guint64 total, guint64 available) +{ + guint64 used; + char *used_fmt; + char *total_fmt; + char *result; + double percent; + + if (total == 0) + { + return NULL; + } + + if (available > total) + { + available = total; + } + used = total - available; + percent = ((double) used / (double) total) * 100.0; + + used_fmt = g_format_size_full (used, G_FORMAT_SIZE_IEC_UNITS); + total_fmt = g_format_size_full (total, G_FORMAT_SIZE_IEC_UNITS); + result = g_strdup_printf ("%s / %s used (%.0f%%)", used_fmt, total_fmt, percent); + g_free (used_fmt); + g_free (total_fmt); + return result; +} + +char * +sysinfo_backend_get_os (void) +{ + ensure_os_snapshot (); + return g_strdup (snapshot.os); +} + +char * +sysinfo_backend_get_cpu (void) +{ + ensure_cpu_snapshot (); + return g_strdup (snapshot.cpu); +} + +char * +sysinfo_backend_get_gpu (void) +{ + ensure_pci_snapshot (); + return g_strdup (snapshot.gpu); +} + +char * +sysinfo_backend_get_chipset (void) +{ + ensure_pci_snapshot (); + return g_strdup (snapshot.chipset); +} + +char * +sysinfo_backend_get_sound (void) +{ + ensure_sound_snapshot (); + return g_strdup (snapshot.sound); +} + +char * +sysinfo_backend_get_memory (void) +{ + FILE *fp; + char line[512]; + guint64 mem_total_kib = 0; + guint64 mem_available_kib = 0; + guint64 swap_total_kib = 0; + guint64 swap_free_kib = 0; + char *memory; + + fp = fopen ("/proc/meminfo", "r"); + if (!fp) + { + return NULL; + } + + while (fgets (line, sizeof (line), fp) != NULL) + { + if (g_str_has_prefix (line, "MemTotal:")) + { + mem_total_kib = g_ascii_strtoull (line + strlen ("MemTotal:"), NULL, 10); + } + else if (g_str_has_prefix (line, "MemAvailable:")) + { + mem_available_kib = g_ascii_strtoull (line + strlen ("MemAvailable:"), NULL, 10); + } + else if (g_str_has_prefix (line, "SwapTotal:")) + { + swap_total_kib = g_ascii_strtoull (line + strlen ("SwapTotal:"), NULL, 10); + } + else if (g_str_has_prefix (line, "SwapFree:")) + { + swap_free_kib = g_ascii_strtoull (line + strlen ("SwapFree:"), NULL, 10); + } + } + fclose (fp); + + if (mem_total_kib == 0) + { + return NULL; + } + + memory = format_usage (mem_total_kib * 1024, mem_available_kib * 1024); + if (memory && swap_total_kib != 0) + { + char *swap = format_usage (swap_total_kib * 1024, swap_free_kib * 1024); + if (swap) + { + char *result = g_strdup_printf ("%s" SYSINFO_SEP "Swap: %s", memory, swap); + g_free (memory); + g_free (swap); + return result; + } + } + + return memory; +} + +char * +sysinfo_backend_get_disk (void) +{ + const char *path; + struct statvfs fs; + guint64 block_size; + guint64 total; + guint64 available; + char *usage; + + path = g_get_home_dir (); + if (!path || path[0] == '\0') + { + path = "/"; + } + + if (statvfs (path, &fs) != 0) + { + return NULL; + } + + block_size = fs.f_frsize != 0 ? (guint64) fs.f_frsize : (guint64) fs.f_bsize; + total = (guint64) fs.f_blocks * block_size; + available = (guint64) fs.f_bavail * block_size; + usage = format_usage (total, available); + return usage; +} + +char * +sysinfo_backend_get_uptime (void) +{ + char *contents; + char *end = NULL; + double uptime; + + contents = read_trimmed_file ("/proc/uptime"); + if (!contents) + { + return NULL; + } + + uptime = g_ascii_strtod (contents, &end); + if (end == contents || uptime <= 0.0) + { + g_free (contents); + return NULL; + } + + g_free (contents); + return sysinfo_format_uptime ((gint64) uptime); +} + +static char * +read_driver_name (const char *interface_path) +{ + char *driver_path; + char *target; + char *name; + + driver_path = g_build_filename (interface_path, "device", "driver", NULL); + target = g_file_read_link (driver_path, NULL); + g_free (driver_path); + if (!target) + { + return NULL; + } + + name = g_path_get_basename (target); + g_free (target); + return name; +} + +char * +sysinfo_backend_get_network (void) +{ + GDir *dir; + const char *entry; + GPtrArray *adapters; + char *result; + + ensure_pci_snapshot (); + dir = g_dir_open ("/sys/class/net", 0, NULL); + if (!dir) + { + return NULL; + } + + adapters = g_ptr_array_new_with_free_func (g_free); + while ((entry = g_dir_read_name (dir)) != NULL) + { + char *interface_path; + char *device_path; + char *operstate_path; + char *operstate; + char *wireless_path; + char *vendor_path; + char *device_id_path; + char *driver; + const char *hardware_name = NULL; + char *key = NULL; + char *label; + guint vendor; + guint device; + gboolean wireless; + + if (strcmp (entry, "lo") == 0) + { + continue; + } + + interface_path = g_build_filename ("/sys/class/net", entry, NULL); + device_path = g_build_filename (interface_path, "device", NULL); + if (!g_file_test (device_path, G_FILE_TEST_EXISTS)) + { + g_free (device_path); + g_free (interface_path); + continue; + } + + operstate_path = g_build_filename (interface_path, "operstate", NULL); + operstate = read_trimmed_file (operstate_path); + g_free (operstate_path); + if (!operstate || g_ascii_strcasecmp (operstate, "up") != 0) + { + g_free (operstate); + g_free (device_path); + g_free (interface_path); + continue; + } + g_free (operstate); + + wireless_path = g_build_filename (interface_path, "wireless", NULL); + wireless = g_file_test (wireless_path, G_FILE_TEST_IS_DIR); + g_free (wireless_path); + + vendor_path = g_build_filename (device_path, "vendor", NULL); + device_id_path = g_build_filename (device_path, "device", NULL); + if (read_hex_file (vendor_path, &vendor) && read_hex_file (device_id_path, &device)) + { + key = g_strdup_printf ("%04x:%04x", vendor, device); + hardware_name = g_hash_table_lookup (snapshot.pci_names, key); + } + g_free (vendor_path); + g_free (device_id_path); + + driver = read_driver_name (interface_path); + if (hardware_name) + { + label = g_strdup_printf ("%s: %s (%s)", wireless ? "Wi-Fi" : "Ethernet", hardware_name, entry); + } + else if (driver) + { + label = g_strdup_printf ("%s: %s (%s)", wireless ? "Wi-Fi" : "Ethernet", driver, entry); + } + else + { + label = g_strdup_printf ("%s: %s", wireless ? "Wi-Fi" : "Ethernet", entry); + } + + ptr_array_add_unique (adapters, label); + g_free (label); + g_free (driver); + g_free (key); + g_free (device_path); + g_free (interface_path); + } + g_dir_close (dir); + + result = join_ptr_array (adapters, ", "); + g_ptr_array_free (adapters, TRUE); + return result; +} + +static const char * +sysinfo_detect_toolkit (void) +{ +#if defined(USE_GTK_FRONTEND) + return "GTK3"; +#else + return NULL; +#endif +} + +static const char * +sysinfo_detect_display_backend (void) +{ + const char *backend = NULL; + const char *gdk_backend = g_getenv ("GDK_BACKEND"); + const char *session = g_getenv ("XDG_SESSION_TYPE"); + const gboolean session_wayland = session && g_ascii_strcasecmp (session, "wayland") == 0; + +#if defined(USE_GTK_FRONTEND) + { + GdkDisplay *display = gdk_display_get_default (); + if (display) + { + const char *type_name = G_OBJECT_TYPE_NAME (display); + if (type_name) + { + if (g_strrstr (type_name, "Wayland")) + { + backend = "Wayland"; + } + else if (g_strrstr (type_name, "X11")) + { + backend = "X11"; + } + } + } + } +#endif + + if (!backend && gdk_backend) + { + if (g_strrstr (gdk_backend, "wayland")) + { + backend = "Wayland"; + } + else if (g_strrstr (gdk_backend, "x11")) + { + backend = "X11"; + } + } + + if (!backend) + { + const gboolean has_wayland = g_getenv ("WAYLAND_DISPLAY") != NULL; + const gboolean has_x11 = g_getenv ("DISPLAY") != NULL; + + if (has_wayland && !has_x11) + { + backend = "Wayland"; + } + else if (has_x11 && !has_wayland) + { + backend = "X11"; + } + else if (session_wayland) + { + backend = "Wayland"; + } + } + + if (backend && g_strcmp0 (backend, "X11") == 0 && session_wayland) + { + return "XWayland"; + } + + return backend; +} + +char * +sysinfo_backend_get_ui (void) +{ + const char *toolkit = sysinfo_detect_toolkit (); + const char *display = sysinfo_detect_display_backend (); + + if (toolkit && display) + { + return g_strdup_printf ("%s / %s", toolkit, display); + } + if (toolkit) + { + return g_strdup (toolkit); + } + if (display) + { + return g_strdup (display); + } + + return NULL; +} diff --git a/plugins/sysinfo/win32/backend.c b/plugins/sysinfo/win32/backend.c index 19d60da5..823775ac 100644 --- a/plugins/sysinfo/win32/backend.c +++ b/plugins/sysinfo/win32/backend.c @@ -1,28 +1,33 @@ -/* ZoiteChat - * Copyright (c) 2011-2012 Berke Viktor. +/* + * Modern Windows SysInfo backend for ZoiteChat. * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. + * Avoids WMI in the plugin hot path and uses native Win32/DXGI APIs. */ -#include +#ifndef _WIN32_WINNT +#define _WIN32_WINNT 0x0601 +#elif _WIN32_WINNT < 0x0601 +#undef _WIN32_WINNT +#define _WIN32_WINNT 0x0601 +#endif + #include -#include +#include +#include +#include +#include +#include + +#ifdef _MSC_VER +#pragma comment(lib, "advapi32.lib") +#pragma comment(lib, "dxgi.lib") +#pragma comment(lib, "dxguid.lib") +#pragma comment(lib, "iphlpapi.lib") +#pragma comment(lib, "winmm.lib") +#endif +#include +#include +#include #include @@ -30,63 +35,543 @@ #include "config.h" #endif -#include "../../../src/common/sysinfo/sysinfo.h" - #include "../format.h" +#include "../sysinfo-backend.h" -static char *get_memory_info (void); +#define SYSINFO_SEP " \xC2\xB7 " -char * -sysinfo_backend_get_sound (void) +typedef struct { - return NULL; -} + char *os; + char *cpu; + char *gpu; + char *sound; +} WinStaticSnapshot; -char * -sysinfo_backend_get_network (void) +static WinStaticSnapshot snapshot; +static gsize os_initialized = 0; +static gsize cpu_initialized = 0; +static gsize gpu_initialized = 0; +static gsize sound_initialized = 0; + +static char *wide_to_utf8 (const WCHAR *value); +static char *read_registry_string (HKEY root, const WCHAR *subkey, const WCHAR *value_name); +static gboolean read_registry_dword (HKEY root, const WCHAR *subkey, const WCHAR *value_name, DWORD *value); +static const char *get_native_arch (void); +static DWORD get_windows_build_number (void); +static char *build_os_string (void); +static DWORD count_physical_cores (void); +static char *build_cpu_string (void); +static char *build_gpu_string (void); +static char *build_sound_string (void); +static void ensure_os_snapshot (void); +static void ensure_cpu_snapshot (void); +static void ensure_gpu_snapshot (void); +static void ensure_sound_snapshot (void); +static char *format_usage (guint64 total, guint64 available); +static char *join_ptr_array (GPtrArray *items, const char *separator); +static void ptr_array_add_unique (GPtrArray *items, const char *value); +static gboolean adapter_looks_virtual (const char *name); + +static char * +wide_to_utf8 (const WCHAR *value) { - return NULL; -} - -char * -sysinfo_backend_get_uptime (void) -{ - return sysinfo_format_uptime (GetTickCount64 () / 1000); -} - -char * -sysinfo_backend_get_disk (void) -{ - guint64 hdd_capacity; - guint64 hdd_free_space; - - sysinfo_get_hdd_info (&hdd_capacity, &hdd_free_space); - - if (hdd_capacity != 0) + if (!value || value[0] == L'\0') { - return sysinfo_format_disk(hdd_capacity, hdd_free_space); + return NULL; } - return NULL; + return g_utf16_to_utf8 ((const gunichar2 *) value, -1, NULL, NULL, NULL); +} + +static char * +read_registry_string (HKEY root, const WCHAR *subkey, const WCHAR *value_name) +{ + HKEY key; + DWORD type = 0; + DWORD size = 0; + WCHAR *buffer; + char *result = NULL; + LONG status; + + status = RegOpenKeyExW (root, subkey, 0, KEY_READ | KEY_WOW64_64KEY, &key); + if (status != ERROR_SUCCESS) + { + return NULL; + } + + status = RegQueryValueExW (key, value_name, NULL, &type, NULL, &size); + if (status != ERROR_SUCCESS || (type != REG_SZ && type != REG_EXPAND_SZ) || size < sizeof (WCHAR)) + { + RegCloseKey (key); + return NULL; + } + + buffer = g_malloc0 ((gsize) size + sizeof (WCHAR)); + status = RegQueryValueExW (key, value_name, NULL, &type, (LPBYTE) buffer, &size); + if (status == ERROR_SUCCESS) + { + result = wide_to_utf8 (buffer); + if (result) + { + g_strstrip (result); + } + } + + g_free (buffer); + RegCloseKey (key); + return result; +} + +static gboolean +read_registry_dword (HKEY root, const WCHAR *subkey, const WCHAR *value_name, DWORD *value) +{ + HKEY key; + DWORD type = 0; + DWORD size = sizeof (*value); + LONG status; + + status = RegOpenKeyExW (root, subkey, 0, KEY_READ | KEY_WOW64_64KEY, &key); + if (status != ERROR_SUCCESS) + { + return FALSE; + } + + status = RegQueryValueExW (key, value_name, NULL, &type, (LPBYTE) value, &size); + RegCloseKey (key); + return status == ERROR_SUCCESS && type == REG_DWORD; +} + +static const char * +get_native_arch (void) +{ + SYSTEM_INFO info; + + GetNativeSystemInfo (&info); + switch (info.wProcessorArchitecture) + { + case PROCESSOR_ARCHITECTURE_AMD64: + return "x64"; + case PROCESSOR_ARCHITECTURE_ARM64: + return "ARM64"; + case PROCESSOR_ARCHITECTURE_INTEL: + return "x86"; + default: + return "unknown-arch"; + } +} + +static DWORD +get_windows_build_number (void) +{ + typedef LONG (WINAPI *RtlGetVersionFn) (PRTL_OSVERSIONINFOW); + HMODULE ntdll; + RtlGetVersionFn rtl_get_version; + RTL_OSVERSIONINFOW version; + DWORD build = 0; + + ntdll = GetModuleHandleW (L"ntdll.dll"); + if (ntdll) + { + rtl_get_version = (RtlGetVersionFn) GetProcAddress (ntdll, "RtlGetVersion"); + if (rtl_get_version) + { + ZeroMemory (&version, sizeof (version)); + version.dwOSVersionInfoSize = sizeof (version); + if (rtl_get_version (&version) == 0) + { + build = version.dwBuildNumber; + } + } + } + + return build; +} + +static char * +build_os_string (void) +{ + static const WCHAR current_version_key[] = L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion"; + char *product; + char *display_version; + char *registry_build; + char *fixed_product = NULL; + char *result; + DWORD ubr = 0; + DWORD build; + guint64 parsed_build = 0; + + product = read_registry_string (HKEY_LOCAL_MACHINE, current_version_key, L"ProductName"); + display_version = read_registry_string (HKEY_LOCAL_MACHINE, current_version_key, L"DisplayVersion"); + registry_build = read_registry_string (HKEY_LOCAL_MACHINE, current_version_key, L"CurrentBuildNumber"); + read_registry_dword (HKEY_LOCAL_MACHINE, current_version_key, L"UBR", &ubr); + + build = get_windows_build_number (); + if (registry_build) + { + parsed_build = g_ascii_strtoull (registry_build, NULL, 10); + if (parsed_build != 0) + { + build = (DWORD) parsed_build; + } + } + + if (!product) + { + product = g_strdup (build >= 22000 ? "Windows 11" : "Windows"); + } + else if (build >= 22000 && g_str_has_prefix (product, "Windows 10")) + { + fixed_product = g_strdup_printf ("Windows 11%s", product + strlen ("Windows 10")); + g_free (product); + product = fixed_product; + } + + if (display_version && build != 0) + { + result = g_strdup_printf ("%s %s" SYSINFO_SEP "build %lu.%lu" SYSINFO_SEP "%s", + product, display_version, (unsigned long) build, (unsigned long) ubr, get_native_arch ()); + } + else if (build != 0) + { + result = g_strdup_printf ("%s" SYSINFO_SEP "build %lu.%lu" SYSINFO_SEP "%s", + product, (unsigned long) build, (unsigned long) ubr, get_native_arch ()); + } + else + { + result = g_strdup_printf ("%s" SYSINFO_SEP "%s", product, get_native_arch ()); + } + + g_free (product); + g_free (display_version); + g_free (registry_build); + return result; +} + +static DWORD +count_physical_cores (void) +{ + DWORD length = 0; + PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX buffer; + BYTE *cursor; + BYTE *end; + DWORD cores = 0; + + GetLogicalProcessorInformationEx (RelationProcessorCore, NULL, &length); + if (GetLastError () != ERROR_INSUFFICIENT_BUFFER || length == 0) + { + return 0; + } + + buffer = g_malloc0 (length); + if (!GetLogicalProcessorInformationEx (RelationProcessorCore, buffer, &length)) + { + g_free (buffer); + return 0; + } + + cursor = (BYTE *) buffer; + end = cursor + length; + while (cursor < end) + { + PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX info = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX) cursor; + + if (info->Size == 0) + { + break; + } + if (info->Relationship == RelationProcessorCore) + { + cores++; + } + cursor += info->Size; + } + + g_free (buffer); + return cores; +} + +static char * +build_cpu_string (void) +{ + static const WCHAR cpu_key[] = L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0"; + char *name; + DWORD cores; + DWORD threads; + SYSTEM_INFO info; + char *result; + + name = read_registry_string (HKEY_LOCAL_MACHINE, cpu_key, L"ProcessorNameString"); + if (!name) + { + name = g_strdup ("Unknown CPU"); + } + + cores = count_physical_cores (); + threads = GetActiveProcessorCount (ALL_PROCESSOR_GROUPS); + if (threads == 0) + { + GetNativeSystemInfo (&info); + threads = info.dwNumberOfProcessors; + } + if (cores == 0) + { + cores = threads; + } + + result = g_strdup_printf ("%s" SYSINFO_SEP "%luC/%luT", + name, (unsigned long) cores, (unsigned long) threads); + g_free (name); + return result; +} + +static char * +join_ptr_array (GPtrArray *items, const char *separator) +{ + GString *joined; + guint i; + + if (!items || items->len == 0) + { + return NULL; + } + + joined = g_string_new (NULL); + for (i = 0; i < items->len; i++) + { + if (i != 0) + { + g_string_append (joined, separator); + } + g_string_append (joined, g_ptr_array_index (items, i)); + } + return g_string_free (joined, FALSE); +} + +static void +ptr_array_add_unique (GPtrArray *items, const char *value) +{ + guint i; + + if (!value || value[0] == '\0') + { + return; + } + + for (i = 0; i < items->len; i++) + { + if (g_ascii_strcasecmp (g_ptr_array_index (items, i), value) == 0) + { + return; + } + } + g_ptr_array_add (items, g_strdup (value)); +} + +static char * +build_gpu_string (void) +{ + IDXGIFactory1 *factory = NULL; + GPtrArray *adapters; + UINT index; + HRESULT hr; + char *result; + + hr = CreateDXGIFactory1 (&IID_IDXGIFactory1, (void **) &factory); + if (FAILED (hr) || !factory) + { + return NULL; + } + + adapters = g_ptr_array_new_with_free_func (g_free); + for (index = 0; ; index++) + { + IDXGIAdapter1 *adapter = NULL; + DXGI_ADAPTER_DESC1 desc; + char *name; + char *label; + + hr = factory->lpVtbl->EnumAdapters1 (factory, index, &adapter); + if (hr == DXGI_ERROR_NOT_FOUND) + { + break; + } + if (FAILED (hr) || !adapter) + { + continue; + } + + ZeroMemory (&desc, sizeof (desc)); + hr = adapter->lpVtbl->GetDesc1 (adapter, &desc); + adapter->lpVtbl->Release (adapter); + if (FAILED (hr) || (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)) + { + continue; + } + + name = wide_to_utf8 (desc.Description); + if (!name) + { + continue; + } + g_strstrip (name); + + if ((guint64) desc.DedicatedVideoMemory >= (512ULL * 1024ULL * 1024ULL)) + { + char *vram = g_format_size_full ((guint64) desc.DedicatedVideoMemory, G_FORMAT_SIZE_IEC_UNITS); + label = g_strdup_printf ("%s (%s VRAM)", name, vram); + g_free (vram); + } + else + { + label = g_strdup (name); + } + + ptr_array_add_unique (adapters, label); + g_free (label); + g_free (name); + } + + factory->lpVtbl->Release (factory); + result = join_ptr_array (adapters, ", "); + g_ptr_array_free (adapters, TRUE); + return result; +} + +static char * +build_sound_string (void) +{ + UINT count; + UINT i; + GPtrArray *devices; + char *result; + + count = waveOutGetNumDevs (); + if (count == 0) + { + return NULL; + } + + devices = g_ptr_array_new_with_free_func (g_free); + for (i = 0; i < count; i++) + { + WAVEOUTCAPSW caps; + char *name; + + ZeroMemory (&caps, sizeof (caps)); + if (waveOutGetDevCapsW ((UINT_PTR) i, &caps, sizeof (caps)) != MMSYSERR_NOERROR) + { + continue; + } + + name = wide_to_utf8 (caps.szPname); + if (name) + { + g_strstrip (name); + ptr_array_add_unique (devices, name); + g_free (name); + } + } + + result = join_ptr_array (devices, ", "); + g_ptr_array_free (devices, TRUE); + return result; +} + +static void +ensure_os_snapshot (void) +{ + if (g_once_init_enter (&os_initialized)) + { + snapshot.os = build_os_string (); + g_once_init_leave (&os_initialized, 1); + } +} + +static void +ensure_cpu_snapshot (void) +{ + if (g_once_init_enter (&cpu_initialized)) + { + snapshot.cpu = build_cpu_string (); + g_once_init_leave (&cpu_initialized, 1); + } +} + +static void +ensure_gpu_snapshot (void) +{ + if (g_once_init_enter (&gpu_initialized)) + { + snapshot.gpu = build_gpu_string (); + g_once_init_leave (&gpu_initialized, 1); + } +} + +static void +ensure_sound_snapshot (void) +{ + if (g_once_init_enter (&sound_initialized)) + { + snapshot.sound = build_sound_string (); + g_once_init_leave (&sound_initialized, 1); + } +} + +static char * +format_usage (guint64 total, guint64 available) +{ + guint64 used; + char *used_fmt; + char *total_fmt; + char *result; + double percent; + + if (total == 0) + { + return NULL; + } + + if (available > total) + { + available = total; + } + used = total - available; + percent = ((double) used / (double) total) * 100.0; + used_fmt = g_format_size_full (used, G_FORMAT_SIZE_IEC_UNITS); + total_fmt = g_format_size_full (total, G_FORMAT_SIZE_IEC_UNITS); + result = g_strdup_printf ("%s / %s used (%.0f%%)", used_fmt, total_fmt, percent); + g_free (used_fmt); + g_free (total_fmt); + return result; +} + +char * +sysinfo_backend_get_os (void) +{ + ensure_os_snapshot (); + return g_strdup (snapshot.os); } char * sysinfo_backend_get_cpu (void) { - return sysinfo_get_cpu (); -} - -char * -sysinfo_backend_get_memory (void) -{ - /* Memory information is always loaded dynamically since it includes the current amount of free memory */ - return get_memory_info (); + ensure_cpu_snapshot (); + return g_strdup (snapshot.cpu); } char * sysinfo_backend_get_gpu (void) { - return sysinfo_get_gpu (); + ensure_gpu_snapshot (); + return g_strdup (snapshot.gpu); +} + +char * +sysinfo_backend_get_sound (void) +{ + ensure_sound_snapshot (); + return g_strdup (snapshot.sound); } char * @@ -96,43 +581,178 @@ sysinfo_backend_get_chipset (void) } char * -sysinfo_backend_get_os (void) +sysinfo_backend_get_memory (void) { - return sysinfo_get_os (); -} + MEMORYSTATUSEX memory; -static char *get_memory_info (void) -{ - MEMORYSTATUSEX meminfo = { 0 }; - meminfo.dwLength = sizeof (meminfo); - - if (!GlobalMemoryStatusEx (&meminfo)) + ZeroMemory (&memory, sizeof (memory)); + memory.dwLength = sizeof (memory); + if (!GlobalMemoryStatusEx (&memory)) { return NULL; } - return sysinfo_format_memory (meminfo.ullTotalPhys, meminfo.ullAvailPhys); + return format_usage ((guint64) memory.ullTotalPhys, (guint64) memory.ullAvailPhys); } -static const char *sysinfo_detect_toolkit(void) +char * +sysinfo_backend_get_disk (void) { -#if defined(USE_GTK_FRONTEND) - return "GTK3"; -#else - return NULL; -#endif + WCHAR windows_dir[MAX_PATH]; + WCHAR volume_path[MAX_PATH]; + ULARGE_INTEGER available; + ULARGE_INTEGER total; + ULARGE_INTEGER total_free; + char *usage; + char *volume_utf8; + char *result; + + if (GetWindowsDirectoryW (windows_dir, G_N_ELEMENTS (windows_dir)) == 0) + { + return NULL; + } + if (!GetVolumePathNameW (windows_dir, volume_path, G_N_ELEMENTS (volume_path))) + { + return NULL; + } + if (!GetDiskFreeSpaceExW (volume_path, &available, &total, &total_free)) + { + return NULL; + } + + usage = format_usage ((guint64) total.QuadPart, (guint64) available.QuadPart); + if (!usage) + { + return NULL; + } + + volume_utf8 = wide_to_utf8 (volume_path); + if (!volume_utf8) + { + return usage; + } + g_strchomp (volume_utf8); + result = g_strdup_printf ("%s" SYSINFO_SEP "%s", usage, volume_utf8); + g_free (volume_utf8); + g_free (usage); + return result; +} + +char * +sysinfo_backend_get_uptime (void) +{ + return sysinfo_format_uptime ((gint64) (GetTickCount64 () / 1000ULL)); +} + +static gboolean +adapter_looks_virtual (const char *name) +{ + char *lower; + gboolean result; + + if (!name) + { + return FALSE; + } + + lower = g_ascii_strdown (name, -1); + result = strstr (lower, "virtual") != NULL || + strstr (lower, "hyper-v") != NULL || + strstr (lower, "vmware") != NULL || + strstr (lower, "virtualbox") != NULL || + strstr (lower, "tap-windows") != NULL || + strstr (lower, "wireguard") != NULL || + strstr (lower, "vpn") != NULL; + g_free (lower); + return result; +} + +char * +sysinfo_backend_get_network (void) +{ + ULONG size = 16 * 1024; + ULONG status; + IP_ADAPTER_ADDRESSES *addresses; + IP_ADAPTER_ADDRESSES *adapter; + GPtrArray *physical; + GPtrArray *fallback; + GPtrArray *selected; + char *result; + + addresses = g_malloc0 (size); + status = GetAdaptersAddresses (AF_UNSPEC, + GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER, + NULL, addresses, &size); + if (status == ERROR_BUFFER_OVERFLOW) + { + g_free (addresses); + addresses = g_malloc0 (size); + status = GetAdaptersAddresses (AF_UNSPEC, + GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER, + NULL, addresses, &size); + } + if (status != NO_ERROR) + { + g_free (addresses); + return NULL; + } + + physical = g_ptr_array_new_with_free_func (g_free); + fallback = g_ptr_array_new_with_free_func (g_free); + for (adapter = addresses; adapter != NULL; adapter = adapter->Next) + { + char *description; + char *friendly; + const char *name; + const char *type; + char *label; + + if (adapter->OperStatus != IfOperStatusUp || adapter->PhysicalAddressLength == 0) + { + continue; + } + if (adapter->IfType != IF_TYPE_ETHERNET_CSMACD && adapter->IfType != IF_TYPE_IEEE80211) + { + continue; + } + + description = wide_to_utf8 (adapter->Description); + friendly = wide_to_utf8 (adapter->FriendlyName); + name = description && description[0] ? description : friendly; + if (!name) + { + g_free (description); + g_free (friendly); + continue; + } + + type = adapter->IfType == IF_TYPE_IEEE80211 ? "Wi-Fi" : "Ethernet"; + label = g_strdup_printf ("%s: %s", type, name); + ptr_array_add_unique (fallback, label); + if (!adapter_looks_virtual (name)) + { + ptr_array_add_unique (physical, label); + } + + g_free (label); + g_free (description); + g_free (friendly); + } + g_free (addresses); + + selected = physical->len != 0 ? physical : fallback; + result = join_ptr_array (selected, ", "); + g_ptr_array_free (physical, TRUE); + g_ptr_array_free (fallback, TRUE); + return result; } char * sysinfo_backend_get_ui (void) { - const char *toolkit = sysinfo_detect_toolkit(); - - /* On Windows we don't have X11/Wayland. Keep it simple. */ - if (toolkit) - { - return g_strdup_printf ("Windows / %s", toolkit); - } - +#if defined(USE_GTK_FRONTEND) + return g_strdup ("Windows / GTK3"); +#else return g_strdup ("Windows"); +#endif } From 3318b641f3b58663a5c9108828a4af435064c514 Mon Sep 17 00:00:00 2001 From: deepend-tildeclub Date: Thu, 3 Sep 2026 17:21:00 -0600 Subject: [PATCH 02/15] fix Win32 IP Helper includes for sysinfo --- plugins/sysinfo/win32/backend.c | 1 + 1 file changed, 1 insertion(+) diff --git a/plugins/sysinfo/win32/backend.c b/plugins/sysinfo/win32/backend.c index 823775ac..ccaecc1f 100644 --- a/plugins/sysinfo/win32/backend.c +++ b/plugins/sysinfo/win32/backend.c @@ -11,6 +11,7 @@ #define _WIN32_WINNT 0x0601 #endif +#include #include #include #include From 225fb8621c9beb600151eb62deed56c416ef648e Mon Sep 17 00:00:00 2001 From: deepend-tildeclub Date: Thu, 3 Sep 2026 18:00:20 -0600 Subject: [PATCH 03/15] enable storage information --- plugins/sysinfo/sysinfo.c | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/plugins/sysinfo/sysinfo.c b/plugins/sysinfo/sysinfo.c index fa46a5c8..54aff7ea 100644 --- a/plugins/sysinfo/sysinfo.c +++ b/plugins/sysinfo/sysinfo.c @@ -68,11 +68,7 @@ static hwinfo hwinfos[] = { {"os", "OS", sysinfo_backend_get_os}, {"cpu", "CPU", sysinfo_backend_get_cpu}, {"memory", "Memory", sysinfo_backend_get_memory}, -#if defined(__linux__) - {"storage", "Storage", sysinfo_backend_get_disk, FALSE}, -#else - {"storage", "Storage", sysinfo_backend_get_disk, TRUE}, -#endif + {"storage", "Storage", sysinfo_backend_get_disk}, {"gpu", "GPU", sysinfo_backend_get_gpu}, {"chipset", "Chipset", sysinfo_backend_get_chipset, TRUE}, {"sound", "Sound", sysinfo_backend_get_sound, TRUE}, From d1a14ef56c22daff60c6c28b47dba2e836f9bdeb Mon Sep 17 00:00:00 2001 From: deepend Date: Fri, 11 Sep 2026 03:37:28 -0600 Subject: [PATCH 04/15] fix application crash + other fixes --- plugins/sysinfo/meson.build | 19 ++++++-- plugins/sysinfo/unix/modern-backend.c | 62 +++++++++++++++++++++------ plugins/sysinfo/win32/backend.c | 17 +++++--- 3 files changed, 77 insertions(+), 21 deletions(-) diff --git a/plugins/sysinfo/meson.build b/plugins/sysinfo/meson.build index 420d28c4..2e31c14e 100644 --- a/plugins/sysinfo/meson.build +++ b/plugins/sysinfo/meson.build @@ -12,7 +12,7 @@ sysinfo_includes = [] sysinfo_cargs = ['-DHAVE_CONFIG_H'] system = host_machine.system() -if system == 'linux' or system == 'gnu' or system.startswith('gnu/') +if system == 'linux' if get_option('gtk-frontend') sysinfo_deps += dependency('gtk+-3.0', version: '>= 3.22') endif @@ -26,7 +26,20 @@ if system == 'linux' or system == 'gnu' or system.startswith('gnu/') sysinfo_includes += 'unix' sysinfo_sources += 'unix/modern-backend.c' -elif system == 'freebsd' + sysinfo_test_deps = [libgio_dep] + sysinfo_test_cargs = [] + if libpci.found() + sysinfo_test_deps += libpci + sysinfo_test_cargs += '-DHAVE_LIBPCI' + endif + sysinfo_backend_tests = executable('sysinfo_backend_tests', + ['tests/test-linux-backend.c', 'format.c'], + dependencies: sysinfo_test_deps, + c_args: sysinfo_test_cargs, + ) + test('Sysinfo Backend Tests', sysinfo_backend_tests, protocol: 'tap') + +elif system == 'freebsd' or system == 'gnu' or system.startswith('gnu/') sysinfo_includes += ['shared', 'unix'] sysinfo_sources += [ 'shared/df.c', @@ -41,7 +54,7 @@ elif system == 'freebsd' sysinfo_cargs += '-DHAVE_LIBPCI' sysinfo_sources += 'unix/pci.c' - picidsdir = libpci.get_pkgconfig_variable('idsdir') + picidsdir = libpci.get_variable(pkgconfig: 'idsdir') pciids = join_paths(picidsdir, 'pci.ids') sysinfo_cargs += '-DPCIIDS_FILE="@0@"'.format(pciids) endif diff --git a/plugins/sysinfo/unix/modern-backend.c b/plugins/sysinfo/unix/modern-backend.c index 56425036..0840a8dd 100644 --- a/plugins/sysinfo/unix/modern-backend.c +++ b/plugins/sysinfo/unix/modern-backend.c @@ -217,21 +217,29 @@ read_os_pretty_name (void) { char *pretty = NULL; - /* Flatpak exposes the host os-release here. Prefer it over the runtime. */ - if (g_file_test ("/run/host/etc/os-release", G_FILE_TEST_IS_REGULAR)) + /* Flatpak always exposes this file, without host filesystem access. */ + pretty = read_pretty_name_from_os_release ("/run/host/os-release"); + if (!pretty) { pretty = read_pretty_name_from_os_release ("/run/host/etc/os-release"); } + /* Keep the plugin buildable with the project's GLib 2.36 minimum. */ +#if GLIB_CHECK_VERSION(2, 64, 0) if (!pretty) { pretty = g_get_os_info (G_OS_INFO_KEY_PRETTY_NAME); } +#endif if (!pretty) { pretty = read_pretty_name_from_os_release ("/etc/os-release"); } + if (!pretty) + { + pretty = read_pretty_name_from_os_release ("/usr/lib/os-release"); + } return pretty ? pretty : g_strdup ("Linux"); } @@ -334,11 +342,30 @@ count_physical_cores (void) char *package_id; char *core_id; char *key; + char *online_path; + char *online; + const char *suffix; if (!g_str_has_prefix (entry, "cpu") || !g_ascii_isdigit (entry[3])) { continue; } + for (suffix = entry + 3; g_ascii_isdigit (*suffix); suffix++) + ; + if (*suffix != '\0') + continue; + + /* sysconf counts online threads; exclude offline cores as well. + * CPUs that cannot be offlined (usually CPU0) have no online file. */ + online_path = g_build_filename ("/sys/devices/system/cpu", entry, "online", NULL); + online = read_trimmed_file (online_path); + g_free (online_path); + if (g_strcmp0 (online, "0") == 0) + { + g_free (online); + continue; + } + g_free (online); package_path = g_build_filename ("/sys/devices/system/cpu", entry, "topology", "physical_package_id", NULL); core_path = g_build_filename ("/sys/devices/system/cpu", entry, "topology", "core_id", NULL); @@ -347,11 +374,14 @@ count_physical_cores (void) g_free (package_path); g_free (core_path); - if (!package_id || !core_id) + if (!package_id || !core_id || package_id[0] == '-' || core_id[0] == '-') { g_free (package_id); g_free (core_id); - continue; + /* Partial or unknown topology cannot give a reliable core count. */ + g_hash_table_destroy (cores); + g_dir_close (dir); + return 0; } key = g_strdup_printf ("%s:%s", package_id, core_id); @@ -379,17 +409,18 @@ build_cpu_string (void) logical = logical_long > 0 ? (guint) logical_long : 0; physical = count_physical_cores (); - if (physical == 0) - { - physical = logical; - } - if (physical != 0 && logical != 0) { char *result = g_strdup_printf ("%s" SYSINFO_SEP "%uC/%uT", model, physical, logical); g_free (model); return result; } + if (logical != 0) + { + char *result = g_strdup_printf ("%s" SYSINFO_SEP "%uT", model, logical); + g_free (model); + return result; + } return model; } @@ -536,9 +567,13 @@ scan_pci_devices (void) chipsets = g_ptr_array_new_with_free_func (g_free); #ifdef HAVE_LIBPCI - pacc = pci_alloc (); - if (pacc) + /* We only need name lookup: autodetection can exit the client if sysfs + * is hidden in a sandbox and libpci tries privileged access methods. + * Explicit sysfs initialization installs callbacks without probing. */ + if (pci_lookup_method ("linux-sysfs") >= 0) { + pacc = pci_alloc (); + pacc->method = pci_lookup_method ("linux-sysfs"); pci_init (pacc); } #endif @@ -825,7 +860,10 @@ sysinfo_backend_get_disk (void) guint64 available; char *usage; - path = g_get_home_dir (); + /* Flatpak's home itself can be tmpfs; its data directory is persistent + * storage on the host filesystem that actually holds the app's data. */ + path = g_file_test ("/.flatpak-info", G_FILE_TEST_IS_REGULAR) + ? g_get_user_data_dir () : g_get_home_dir (); if (!path || path[0] == '\0') { path = "/"; diff --git a/plugins/sysinfo/win32/backend.c b/plugins/sysinfo/win32/backend.c index ccaecc1f..c12b6699 100644 --- a/plugins/sysinfo/win32/backend.c +++ b/plugins/sysinfo/win32/backend.c @@ -315,13 +315,16 @@ build_cpu_string (void) GetNativeSystemInfo (&info); threads = info.dwNumberOfProcessors; } - if (cores == 0) + if (cores != 0) { - cores = threads; + result = g_strdup_printf ("%s" SYSINFO_SEP "%luC/%luT", + name, (unsigned long) cores, (unsigned long) threads); + } + else + { + /* Logical processor count cannot establish the physical core count. */ + result = g_strdup_printf ("%s" SYSINFO_SEP "%luT", name, (unsigned long) threads); } - - result = g_strdup_printf ("%s" SYSINFO_SEP "%luC/%luT", - name, (unsigned long) cores, (unsigned long) threads); g_free (name); return result; } @@ -399,7 +402,9 @@ build_gpu_string (void) } if (FAILED (hr) || !adapter) { - continue; + /* A failed enumeration is not another adapter. Retrying every + * index can freeze the client indefinitely after a device error. */ + break; } ZeroMemory (&desc, sizeof (desc)); From 96117decd6527b0ad11bd441ae1e7965052ea38f Mon Sep 17 00:00:00 2001 From: deepend Date: Fri, 11 Sep 2026 20:45:19 -0600 Subject: [PATCH 05/15] fix build warnings --- plugins/sysinfo/meson.build | 13 ------------- plugins/sysinfo/unix/modern-backend.c | 2 +- 2 files changed, 1 insertion(+), 14 deletions(-) diff --git a/plugins/sysinfo/meson.build b/plugins/sysinfo/meson.build index 2e31c14e..f64be5e2 100644 --- a/plugins/sysinfo/meson.build +++ b/plugins/sysinfo/meson.build @@ -26,19 +26,6 @@ if system == 'linux' sysinfo_includes += 'unix' sysinfo_sources += 'unix/modern-backend.c' - sysinfo_test_deps = [libgio_dep] - sysinfo_test_cargs = [] - if libpci.found() - sysinfo_test_deps += libpci - sysinfo_test_cargs += '-DHAVE_LIBPCI' - endif - sysinfo_backend_tests = executable('sysinfo_backend_tests', - ['tests/test-linux-backend.c', 'format.c'], - dependencies: sysinfo_test_deps, - c_args: sysinfo_test_cargs, - ) - test('Sysinfo Backend Tests', sysinfo_backend_tests, protocol: 'tap') - elif system == 'freebsd' or system == 'gnu' or system.startswith('gnu/') sysinfo_includes += ['shared', 'unix'] sysinfo_sources += [ diff --git a/plugins/sysinfo/unix/modern-backend.c b/plugins/sysinfo/unix/modern-backend.c index 0840a8dd..da804ddb 100644 --- a/plugins/sysinfo/unix/modern-backend.c +++ b/plugins/sysinfo/unix/modern-backend.c @@ -225,7 +225,7 @@ read_os_pretty_name (void) } /* Keep the plugin buildable with the project's GLib 2.36 minimum. */ -#if GLIB_CHECK_VERSION(2, 64, 0) +#if GLIB_CHECK_VERSION(2, 64, 0) && GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_64 if (!pretty) { pretty = g_get_os_info (G_OS_INFO_KEY_PRETTY_NAME); From 3abcb33d4f340aa3a45bd3fbd62e3f7675801f49 Mon Sep 17 00:00:00 2001 From: deepend Date: Fri, 4 Dec 2026 18:23:36 -0600 Subject: [PATCH 06/15] share formatting and array helpers --- plugins/sysinfo/format.c | 78 +++++++++++++++++++++++++ plugins/sysinfo/format.h | 3 + plugins/sysinfo/unix/modern-backend.c | 83 +-------------------------- plugins/sysinfo/win32/backend.c | 77 +------------------------ 4 files changed, 87 insertions(+), 154 deletions(-) diff --git a/plugins/sysinfo/format.c b/plugins/sysinfo/format.c index 311e7cdc..4cef68c8 100644 --- a/plugins/sysinfo/format.c +++ b/plugins/sysinfo/format.c @@ -88,3 +88,81 @@ sysinfo_format_disk (guint64 total, guint64 free) g_free (used_fmt); return ret; } + +char * +sysinfo_format_usage (guint64 total, guint64 available) +{ + guint64 used; + char *used_fmt; + char *total_fmt; + char *result; + double percent; + + if (total == 0) + { + return NULL; + } + + if (available > total) + { + available = total; + } + used = total - available; + percent = ((double) used / (double) total) * 100.0; + + used_fmt = g_format_size_full (used, G_FORMAT_SIZE_IEC_UNITS); + total_fmt = g_format_size_full (total, G_FORMAT_SIZE_IEC_UNITS); + result = g_strdup_printf ("%s / %s used (%.0f%%)", used_fmt, total_fmt, percent); + g_free (used_fmt); + g_free (total_fmt); + return result; +} + +char * +sysinfo_join_ptr_array (GPtrArray *items, const char *separator) +{ + GString *joined; + guint i; + + if (!items || items->len == 0) + { + return NULL; + } + + joined = g_string_new (NULL); + for (i = 0; i < items->len; i++) + { + const char *item = g_ptr_array_index (items, i); + + if (i != 0) + { + g_string_append (joined, separator); + } + g_string_append (joined, item); + } + + return g_string_free (joined, FALSE); +} + +void +sysinfo_ptr_array_add_unique (GPtrArray *items, const char *value, gboolean ignore_case) +{ + guint i; + + if (!value || value[0] == '\0') + { + return; + } + + for (i = 0; i < items->len; i++) + { + const char *existing = g_ptr_array_index (items, i); + if (ignore_case ? g_ascii_strcasecmp (existing, value) == 0 : + g_strcmp0 (existing, value) == 0) + { + return; + } + } + + g_ptr_array_add (items, g_strdup (value)); +} diff --git a/plugins/sysinfo/format.h b/plugins/sysinfo/format.h index 0da474d3..a84e1d35 100644 --- a/plugins/sysinfo/format.h +++ b/plugins/sysinfo/format.h @@ -24,5 +24,8 @@ char *sysinfo_format_uptime(gint64 uptime); char *sysinfo_format_memory(guint64 totalmem, guint64 freemem); char *sysinfo_format_disk(guint64 total, guint64 free); +char *sysinfo_format_usage (guint64 total, guint64 available); +char *sysinfo_join_ptr_array (GPtrArray *items, const char *separator); +void sysinfo_ptr_array_add_unique (GPtrArray *items, const char *value, gboolean ignore_case); #endif diff --git a/plugins/sysinfo/unix/modern-backend.c b/plugins/sysinfo/unix/modern-backend.c index da804ddb..e3e99742 100644 --- a/plugins/sysinfo/unix/modern-backend.c +++ b/plugins/sysinfo/unix/modern-backend.c @@ -48,8 +48,8 @@ static gsize sound_initialized = 0; static char *read_trimmed_file (const char *path); static gboolean read_hex_file (const char *path, guint *value); -static char *join_ptr_array (GPtrArray *items, const char *separator); -static void ptr_array_add_unique (GPtrArray *items, const char *value); +#define join_ptr_array sysinfo_join_ptr_array +#define ptr_array_add_unique(items, value) sysinfo_ptr_array_add_unique ((items), (value), FALSE) static char *read_os_pretty_name (void); static char *read_cpu_model (void); static guint count_physical_cores (void); @@ -60,7 +60,7 @@ static void ensure_os_snapshot (void); static void ensure_cpu_snapshot (void); static void ensure_pci_snapshot (void); static void ensure_sound_snapshot (void); -static char *format_usage (guint64 total, guint64 available); +#define format_usage sysinfo_format_usage static char *read_driver_name (const char *interface_path); static char * @@ -110,54 +110,6 @@ read_hex_file (const char *path, guint *value) return TRUE; } -static char * -join_ptr_array (GPtrArray *items, const char *separator) -{ - GString *joined; - guint i; - - if (!items || items->len == 0) - { - return NULL; - } - - joined = g_string_new (NULL); - for (i = 0; i < items->len; i++) - { - const char *item = g_ptr_array_index (items, i); - - if (i != 0) - { - g_string_append (joined, separator); - } - g_string_append (joined, item); - } - - return g_string_free (joined, FALSE); -} - -static void -ptr_array_add_unique (GPtrArray *items, const char *value) -{ - guint i; - - if (!value || value[0] == '\0') - { - return; - } - - for (i = 0; i < items->len; i++) - { - const char *existing = g_ptr_array_index (items, i); - if (g_strcmp0 (existing, value) == 0) - { - return; - } - } - - g_ptr_array_add (items, g_strdup (value)); -} - static char * unquote_os_release_value (const char *value) { @@ -727,35 +679,6 @@ ensure_sound_snapshot (void) } } -static char * -format_usage (guint64 total, guint64 available) -{ - guint64 used; - char *used_fmt; - char *total_fmt; - char *result; - double percent; - - if (total == 0) - { - return NULL; - } - - if (available > total) - { - available = total; - } - used = total - available; - percent = ((double) used / (double) total) * 100.0; - - used_fmt = g_format_size_full (used, G_FORMAT_SIZE_IEC_UNITS); - total_fmt = g_format_size_full (total, G_FORMAT_SIZE_IEC_UNITS); - result = g_strdup_printf ("%s / %s used (%.0f%%)", used_fmt, total_fmt, percent); - g_free (used_fmt); - g_free (total_fmt); - return result; -} - char * sysinfo_backend_get_os (void) { diff --git a/plugins/sysinfo/win32/backend.c b/plugins/sysinfo/win32/backend.c index c12b6699..7ae96349 100644 --- a/plugins/sysinfo/win32/backend.c +++ b/plugins/sysinfo/win32/backend.c @@ -69,9 +69,9 @@ static void ensure_os_snapshot (void); static void ensure_cpu_snapshot (void); static void ensure_gpu_snapshot (void); static void ensure_sound_snapshot (void); -static char *format_usage (guint64 total, guint64 available); -static char *join_ptr_array (GPtrArray *items, const char *separator); -static void ptr_array_add_unique (GPtrArray *items, const char *value); +#define format_usage sysinfo_format_usage +#define join_ptr_array sysinfo_join_ptr_array +#define ptr_array_add_unique(items, value) sysinfo_ptr_array_add_unique ((items), (value), TRUE) static gboolean adapter_looks_virtual (const char *name); static char * @@ -329,49 +329,6 @@ build_cpu_string (void) return result; } -static char * -join_ptr_array (GPtrArray *items, const char *separator) -{ - GString *joined; - guint i; - - if (!items || items->len == 0) - { - return NULL; - } - - joined = g_string_new (NULL); - for (i = 0; i < items->len; i++) - { - if (i != 0) - { - g_string_append (joined, separator); - } - g_string_append (joined, g_ptr_array_index (items, i)); - } - return g_string_free (joined, FALSE); -} - -static void -ptr_array_add_unique (GPtrArray *items, const char *value) -{ - guint i; - - if (!value || value[0] == '\0') - { - return; - } - - for (i = 0; i < items->len; i++) - { - if (g_ascii_strcasecmp (g_ptr_array_index (items, i), value) == 0) - { - return; - } - } - g_ptr_array_add (items, g_strdup (value)); -} - static char * build_gpu_string (void) { @@ -524,34 +481,6 @@ ensure_sound_snapshot (void) } } -static char * -format_usage (guint64 total, guint64 available) -{ - guint64 used; - char *used_fmt; - char *total_fmt; - char *result; - double percent; - - if (total == 0) - { - return NULL; - } - - if (available > total) - { - available = total; - } - used = total - available; - percent = ((double) used / (double) total) * 100.0; - used_fmt = g_format_size_full (used, G_FORMAT_SIZE_IEC_UNITS); - total_fmt = g_format_size_full (total, G_FORMAT_SIZE_IEC_UNITS); - result = g_strdup_printf ("%s / %s used (%.0f%%)", used_fmt, total_fmt, percent); - g_free (used_fmt); - g_free (total_fmt); - return result; -} - char * sysinfo_backend_get_os (void) { From 42efb59ee06efb7d444213157f3fa8f40eadc805 Mon Sep 17 00:00:00 2001 From: deepend Date: Fri, 4 Dec 2026 18:24:57 -0600 Subject: [PATCH 07/15] fix release+refresh hardware caches --- plugins/sysinfo/osx/backend.m | 12 ++++++-- plugins/sysinfo/sysinfo-backend.h | 2 ++ plugins/sysinfo/sysinfo.c | 14 +++++++--- plugins/sysinfo/unix/backend.c | 6 ++++ plugins/sysinfo/unix/modern-backend.c | 40 +++++++++++++++++++-------- plugins/sysinfo/win32/backend.c | 38 +++++++++++++++++-------- 6 files changed, 82 insertions(+), 30 deletions(-) diff --git a/plugins/sysinfo/osx/backend.m b/plugins/sysinfo/osx/backend.m index 5929ed02..7a64d16a 100644 --- a/plugins/sysinfo/osx/backend.m +++ b/plugins/sysinfo/osx/backend.m @@ -99,10 +99,19 @@ get_os_fallback (void) return g_strdup_printf ("OS X %ld.%ld.%ld", version.majorVersion, version.minorVersion, version.patchVersion); #endif } +static char *os_str; +static char *gpu_str; + +void +sysinfo_backend_reset_cache (void) +{ + g_clear_pointer (&os_str, g_free); + g_clear_pointer (&gpu_str, g_free); +} + char * sysinfo_backend_get_os(void) { - static char *os_str = NULL; if (!os_str) { os_str = get_os(); @@ -250,7 +259,6 @@ get_gpu(void) char * sysinfo_backend_get_gpu(void) { - static char *gpu_str = NULL; if (!gpu_str) gpu_str = get_gpu(); diff --git a/plugins/sysinfo/sysinfo-backend.h b/plugins/sysinfo/sysinfo-backend.h index c54bd6b7..55a10b98 100644 --- a/plugins/sysinfo/sysinfo-backend.h +++ b/plugins/sysinfo/sysinfo-backend.h @@ -21,6 +21,8 @@ #ifndef SYSINFO_BACKEND_H #define SYSINFO_BACKEND_H +/* Called on the same client thread as the getters. Safe to call repeatedly. */ +void sysinfo_backend_reset_cache (void); char *sysinfo_backend_get_os(void); char *sysinfo_backend_get_disk(void); char *sysinfo_backend_get_memory(void); diff --git a/plugins/sysinfo/sysinfo.c b/plugins/sysinfo/sysinfo.c index 54aff7ea..2ddb06cf 100644 --- a/plugins/sysinfo/sysinfo.c +++ b/plugins/sysinfo/sysinfo.c @@ -41,7 +41,7 @@ static zoitechat_plugin *ph; static char name[] = "Sysinfo"; static char desc[] = "Display info about your hardware and OS"; static char version[] = "2.0"; -static char sysinfo_help[] = "SysInfo Usage:\n /SYSINFO [-e|-o] [CLIENT|UI|OS|CPU|RAM|MEMORY|STORAGE|DISK|GPU|VGA|CHIPSET|SOUND|NETWORK|ETHERNET|UPTIME], print various details about your system or print a summary without arguments\n /SYSINFO SET \n"; +static char sysinfo_help[] = "SysInfo Usage:\n /SYSINFO [-e|-o] [CLIENT|UI|OS|CPU|RAM|MEMORY|STORAGE|DISK|GPU|VGA|CHIPSET|SOUND|NETWORK|ETHERNET|UPTIME], print various details about your system or print a summary without arguments\n /SYSINFO SET \n /SYSINFO REFRESH - clear cached hardware information\n"; typedef struct { @@ -241,10 +241,15 @@ sysinfo_cb (char *word[], char *word_eol[], void *userdata) announce = FALSE; cmd = word[2+offset]; - if (!g_ascii_strcasecmp ("SET", cmd)) - sysinfo_set_pref (word[3+offset], word_eol[4+offset]); - else if (!cmd || !cmd[0]) + if (!cmd || !cmd[0]) print_summary (announce); + else if (!g_ascii_strcasecmp ("REFRESH", cmd)) + { + sysinfo_backend_reset_cache (); + zoitechat_print (ph, _("Sysinfo: Hardware cache cleared.")); + } + else if (!g_ascii_strcasecmp ("SET", cmd)) + sysinfo_set_pref (word[3+offset], word_eol[4+offset]); else print_info (cmd, announce); @@ -269,6 +274,7 @@ zoitechat_plugin_init (zoitechat_plugin *plugin_handle, char **plugin_name, char int zoitechat_plugin_deinit (void) { + sysinfo_backend_reset_cache (); zoitechat_command (ph, "MENU DEL \"Window/Send System Info\""); zoitechat_command (ph, "MENU DEL \"Window/Display System Info\""); zoitechat_printf (ph, _("%s plugin unloaded\n"), name); diff --git a/plugins/sysinfo/unix/backend.c b/plugins/sysinfo/unix/backend.c index 3c7c4ae6..920aa30b 100644 --- a/plugins/sysinfo/unix/backend.c +++ b/plugins/sysinfo/unix/backend.c @@ -175,6 +175,12 @@ char *sysinfo_backend_get_uptime(void) return sysinfo_format_uptime (uptime); } +/* The legacy Unix backend does not cache hardware snapshots. */ +void +sysinfo_backend_reset_cache (void) +{ +} + char *sysinfo_backend_get_network(void) { char ethernet_card[bsize]; diff --git a/plugins/sysinfo/unix/modern-backend.c b/plugins/sysinfo/unix/modern-backend.c index e3e99742..6240a259 100644 --- a/plugins/sysinfo/unix/modern-backend.c +++ b/plugins/sysinfo/unix/modern-backend.c @@ -40,11 +40,27 @@ typedef struct GHashTable *pci_names; } LinuxStaticSnapshot; +/* Sysinfo callbacks and plugin teardown run on the client thread. */ static LinuxStaticSnapshot snapshot; -static gsize os_initialized = 0; -static gsize cpu_initialized = 0; -static gsize pci_initialized = 0; -static gsize sound_initialized = 0; +static gboolean os_initialized; +static gboolean cpu_initialized; +static gboolean pci_initialized; +static gboolean sound_initialized; + +void +sysinfo_backend_reset_cache (void) +{ + g_clear_pointer (&snapshot.os, g_free); + g_clear_pointer (&snapshot.cpu, g_free); + g_clear_pointer (&snapshot.gpu, g_free); + g_clear_pointer (&snapshot.chipset, g_free); + g_clear_pointer (&snapshot.sound, g_free); + g_clear_pointer (&snapshot.pci_names, g_hash_table_unref); + os_initialized = FALSE; + cpu_initialized = FALSE; + pci_initialized = FALSE; + sound_initialized = FALSE; +} static char *read_trimmed_file (const char *path); static gboolean read_hex_file (const char *path, guint *value); @@ -642,40 +658,40 @@ build_os_string (void) static void ensure_os_snapshot (void) { - if (g_once_init_enter (&os_initialized)) + if (!os_initialized) { snapshot.os = build_os_string (); - g_once_init_leave (&os_initialized, 1); + os_initialized = TRUE; } } static void ensure_cpu_snapshot (void) { - if (g_once_init_enter (&cpu_initialized)) + if (!cpu_initialized) { snapshot.cpu = build_cpu_string (); - g_once_init_leave (&cpu_initialized, 1); + cpu_initialized = TRUE; } } static void ensure_pci_snapshot (void) { - if (g_once_init_enter (&pci_initialized)) + if (!pci_initialized) { scan_pci_devices (); - g_once_init_leave (&pci_initialized, 1); + pci_initialized = TRUE; } } static void ensure_sound_snapshot (void) { - if (g_once_init_enter (&sound_initialized)) + if (!sound_initialized) { snapshot.sound = build_sound_string (); - g_once_init_leave (&sound_initialized, 1); + sound_initialized = TRUE; } } diff --git a/plugins/sysinfo/win32/backend.c b/plugins/sysinfo/win32/backend.c index 7ae96349..8cec67c4 100644 --- a/plugins/sysinfo/win32/backend.c +++ b/plugins/sysinfo/win32/backend.c @@ -49,11 +49,25 @@ typedef struct char *sound; } WinStaticSnapshot; +/* Sysinfo callbacks and plugin teardown run on the client thread. */ static WinStaticSnapshot snapshot; -static gsize os_initialized = 0; -static gsize cpu_initialized = 0; -static gsize gpu_initialized = 0; -static gsize sound_initialized = 0; +static gboolean os_initialized; +static gboolean cpu_initialized; +static gboolean gpu_initialized; +static gboolean sound_initialized; + +void +sysinfo_backend_reset_cache (void) +{ + g_clear_pointer (&snapshot.os, g_free); + g_clear_pointer (&snapshot.cpu, g_free); + g_clear_pointer (&snapshot.gpu, g_free); + g_clear_pointer (&snapshot.sound, g_free); + os_initialized = FALSE; + cpu_initialized = FALSE; + gpu_initialized = FALSE; + sound_initialized = FALSE; +} static char *wide_to_utf8 (const WCHAR *value); static char *read_registry_string (HKEY root, const WCHAR *subkey, const WCHAR *value_name); @@ -444,40 +458,40 @@ build_sound_string (void) static void ensure_os_snapshot (void) { - if (g_once_init_enter (&os_initialized)) + if (!os_initialized) { snapshot.os = build_os_string (); - g_once_init_leave (&os_initialized, 1); + os_initialized = TRUE; } } static void ensure_cpu_snapshot (void) { - if (g_once_init_enter (&cpu_initialized)) + if (!cpu_initialized) { snapshot.cpu = build_cpu_string (); - g_once_init_leave (&cpu_initialized, 1); + cpu_initialized = TRUE; } } static void ensure_gpu_snapshot (void) { - if (g_once_init_enter (&gpu_initialized)) + if (!gpu_initialized) { snapshot.gpu = build_gpu_string (); - g_once_init_leave (&gpu_initialized, 1); + gpu_initialized = TRUE; } } static void ensure_sound_snapshot (void) { - if (g_once_init_enter (&sound_initialized)) + if (!sound_initialized) { snapshot.sound = build_sound_string (); - g_once_init_leave (&sound_initialized, 1); + sound_initialized = TRUE; } } From 4db044814c29acaa4280e4304f3be83433bb122a Mon Sep 17 00:00:00 2001 From: deepend Date: Fri, 4 Dec 2026 18:25:54 -0600 Subject: [PATCH 08/15] preserve storage privacy+preference --- plugins/sysinfo/sysinfo.c | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/plugins/sysinfo/sysinfo.c b/plugins/sysinfo/sysinfo.c index 2ddb06cf..aa2d6690 100644 --- a/plugins/sysinfo/sysinfo.c +++ b/plugins/sysinfo/sysinfo.c @@ -68,7 +68,7 @@ static hwinfo hwinfos[] = { {"os", "OS", sysinfo_backend_get_os}, {"cpu", "CPU", sysinfo_backend_get_cpu}, {"memory", "Memory", sysinfo_backend_get_memory}, - {"storage", "Storage", sysinfo_backend_get_disk}, + {"storage", "Storage", sysinfo_backend_get_disk, TRUE}, {"gpu", "GPU", sysinfo_backend_get_gpu}, {"chipset", "Chipset", sysinfo_backend_get_chipset, TRUE}, {"sound", "Sound", sysinfo_backend_get_sound, TRUE}, @@ -192,19 +192,19 @@ sysinfo_set_pref (char *key, char *value) return; } - if (!strcmp (key, "announce")) + if (!g_ascii_strcasecmp (key, "announce")) { - sysinfo_set_pref_real (key, value, DEFAULT_ANNOUNCE); + sysinfo_set_pref_real ("announce", value, DEFAULT_ANNOUNCE); return; } - else if (g_str_has_prefix (key, "hide_")) + else if (!g_ascii_strncasecmp (key, "hide_", 5)) { const char *normalized = normalize_info_name (key + 5); int i; for (i = 0; hwinfos[i].name != NULL; i++) { - if (!strcmp (normalized, hwinfos[i].name)) + if (!g_ascii_strcasecmp (normalized, hwinfos[i].name)) { char canonical[32]; From 594e997a0dad7bdc0974d713969a4482f34d615b Mon Sep 17 00:00:00 2001 From: deepend Date: Fri, 4 Dec 2026 18:26:41 -0600 Subject: [PATCH 09/15] fix Linux storage reporting --- plugins/sysinfo/meson.build | 2 +- plugins/sysinfo/unix/modern-backend.c | 31 --- plugins/sysinfo/unix/storage.c | 294 ++++++++++++++++++++++++++ plugins/sysinfo/unix/storage.h | 11 + 4 files changed, 306 insertions(+), 32 deletions(-) create mode 100644 plugins/sysinfo/unix/storage.c create mode 100644 plugins/sysinfo/unix/storage.h diff --git a/plugins/sysinfo/meson.build b/plugins/sysinfo/meson.build index f64be5e2..d8cb7da3 100644 --- a/plugins/sysinfo/meson.build +++ b/plugins/sysinfo/meson.build @@ -24,7 +24,7 @@ if system == 'linux' endif sysinfo_includes += 'unix' - sysinfo_sources += 'unix/modern-backend.c' + sysinfo_sources += ['unix/modern-backend.c', 'unix/storage.c'] elif system == 'freebsd' or system == 'gnu' or system.startswith('gnu/') sysinfo_includes += ['shared', 'unix'] diff --git a/plugins/sysinfo/unix/modern-backend.c b/plugins/sysinfo/unix/modern-backend.c index 6240a259..8d074ddf 100644 --- a/plugins/sysinfo/unix/modern-backend.c +++ b/plugins/sysinfo/unix/modern-backend.c @@ -789,37 +789,6 @@ sysinfo_backend_get_memory (void) return memory; } -char * -sysinfo_backend_get_disk (void) -{ - const char *path; - struct statvfs fs; - guint64 block_size; - guint64 total; - guint64 available; - char *usage; - - /* Flatpak's home itself can be tmpfs; its data directory is persistent - * storage on the host filesystem that actually holds the app's data. */ - path = g_file_test ("/.flatpak-info", G_FILE_TEST_IS_REGULAR) - ? g_get_user_data_dir () : g_get_home_dir (); - if (!path || path[0] == '\0') - { - path = "/"; - } - - if (statvfs (path, &fs) != 0) - { - return NULL; - } - - block_size = fs.f_frsize != 0 ? (guint64) fs.f_frsize : (guint64) fs.f_bsize; - total = (guint64) fs.f_blocks * block_size; - available = (guint64) fs.f_bavail * block_size; - usage = format_usage (total, available); - return usage; -} - char * sysinfo_backend_get_uptime (void) { diff --git a/plugins/sysinfo/unix/storage.c b/plugins/sysinfo/unix/storage.c new file mode 100644 index 00000000..086be1fc --- /dev/null +++ b/plugins/sysinfo/unix/storage.c @@ -0,0 +1,294 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* Report mounted local filesystem capacity without probing network mounts. */ +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(__has_include) +# if __has_include() +# include +# endif +#endif + +#include +#include "../format.h" +#include "../sysinfo-backend.h" +#include "storage.h" + +typedef struct +{ + guint64 total; + guint64 available; +} StorageUsage; + +static char * +decode_mount_field (const char *field) +{ + GString *value = g_string_new (NULL); + const char *p; + + for (p = field; *p; p++) + { + /* mountinfo escapes whitespace and backslashes as octal. */ + if (*p == '\\' && p[1] && p[2] && p[3] && + p[1] >= '0' && p[1] <= '3' && + p[2] >= '0' && p[2] <= '7' && p[3] >= '0' && p[3] <= '7') + { + guint code = (p[1] - '0') * 64 + (p[2] - '0') * 8 + p[3] - '0'; + if (code == 0) + { + g_string_free (value, TRUE); + return NULL; + } + g_string_append_c (value, (char) code); + p += 3; + } + else + g_string_append_c (value, *p); + } + return g_string_free (value, FALSE); +} + +gboolean +sysinfo_linux_mountinfo_parse (const char *line, char **device, + char **mountpoint, char **filesystem, char **source) +{ + char **fields; + guint i, n; + gboolean valid = FALSE; + + *device = *mountpoint = *filesystem = *source = NULL; + fields = g_strsplit (line, " ", -1); + n = g_strv_length (fields); + for (i = 6; i + 3 < n; i++) + { + if (strcmp (fields[i], "-") != 0) + continue; + if (!strchr (fields[2], ':') || fields[4][0] != '/' || !fields[i + 1][0]) + break; + *mountpoint = decode_mount_field (fields[4]); + *source = decode_mount_field (fields[i + 2]); + if (*mountpoint && *source) + { + *device = g_strdup (fields[2]); + *filesystem = g_strdup (fields[i + 1]); + valid = TRUE; + } + else + { + g_clear_pointer (mountpoint, g_free); + g_clear_pointer (source, g_free); + } + break; + } + g_strfreev (fields); + return valid; +} + +static gboolean +local_filesystem (const char *filesystem) +{ + /* A conservative list avoids statvfs on NFS, SMB, autofs and remote FUSE. + * fuseblk is accepted only when a real block device is verified below. */ + static const char *types[] = { + "ext2", "ext3", "ext4", "xfs", "btrfs", "bcachefs", "f2fs", + "jfs", "reiserfs", "nilfs2", "vfat", "msdos", "exfat", "ntfs", + "ntfs3", "fuseblk", "hfs", "hfsplus", "ufs", "minix", "zfs", NULL + }; + guint i; + for (i = 0; types[i]; i++) + if (strcmp (types[i], filesystem) == 0) + return TRUE; + return FALSE; +} + +static gboolean +read_usage (const char *path, StorageUsage *usage) +{ + struct statvfs fs; + guint64 block_size; + + if (statvfs (path, &fs) != 0) + return FALSE; + block_size = fs.f_frsize ? (guint64) fs.f_frsize : (guint64) fs.f_bsize; + if (!block_size || !fs.f_blocks || (guint64) fs.f_blocks > G_MAXUINT64 / block_size) + return FALSE; + usage->total = (guint64) fs.f_blocks * block_size; + usage->available = MIN ((guint64) fs.f_bavail, (guint64) fs.f_blocks) * block_size; + return TRUE; +} + +static char * +filesystem_key (const char *device, const char *mountpoint, + const char *filesystem, const char *source) +{ + struct stat st; + char *id, *sys_path, *target, *name; + gboolean block_source = FALSE; + + if (strcmp (filesystem, "zfs") == 0) + { + /* Datasets share their pool; don't add its capacity repeatedly. */ + const char *slash = strchr (source, '/'); + return source[0] && source[0] != '/' ? + g_strdup_printf ("zfs:%.*s", (int) (slash ? (gsize) (slash - source) : strlen (source)), source) : NULL; + } + + /* A bind mount shares the device number. Btrfs subvolumes can have + * separate synthetic device numbers, so prefer the source block device. */ + if (g_str_has_prefix (source, "/dev/") && stat (source, &st) == 0 && S_ISBLK (st.st_mode)) + { + id = g_strdup_printf ("%u:%u", (unsigned int) major (st.st_rdev), + (unsigned int) minor (st.st_rdev)); + block_source = TRUE; + } + else + id = g_strdup (device); + + sys_path = g_build_filename ("/sys/dev/block", id, NULL); + target = g_file_read_link (sys_path, NULL); + g_free (sys_path); + if (!target && !block_source) + { + g_free (id); + return NULL; + } + name = g_path_get_basename (target ? target : source); + g_free (target); + if (g_str_has_prefix (name, "loop") || g_str_has_prefix (name, "ram") || + g_str_has_prefix (name, "zram") || g_str_has_prefix (name, "fd") || + g_str_has_prefix (name, "sr")) + { + g_free (name); + g_free (id); + return NULL; + } + g_free (name); + +#ifdef BTRFS_IOC_FS_INFO + if (strcmp (filesystem, "btrfs") == 0) + { + /* The filesystem UUID is shared by all subvolumes and members of + * a multi-device filesystem (unlike st_dev or statfs.f_fsid). */ + int fd = open (mountpoint, O_RDONLY); + if (fd >= 0) + { + struct btrfs_ioctl_fs_info_args info = {0}; + if (ioctl (fd, BTRFS_IOC_FS_INFO, &info) == 0) + { + GString *uuid = g_string_new ("btrfs:"); + guint i; + for (i = 0; i < sizeof (info.fsid); i++) + g_string_append_printf (uuid, "%02x", (unsigned int) info.fsid[i]); + g_free (id); + id = g_string_free (uuid, FALSE); + } + close (fd); + } + } +#else + (void) mountpoint; +#endif + return id; +} + +static char * +format_scoped_usage (const StorageUsage *usage, const char *scope) +{ + char *formatted = sysinfo_format_usage (usage->total, usage->available); + char *result; + if (!formatted) + return NULL; + result = g_strdup_printf ("%s (%s)", formatted, scope); + g_free (formatted); + return result; +} + +char * +sysinfo_backend_get_disk (void) +{ + const gboolean flatpak = g_file_test ("/.flatpak-info", G_FILE_TEST_IS_REGULAR); + const char *path = flatpak ? g_get_user_data_dir () : g_get_home_dir (); + StorageUsage aggregate = {0, 0}; + char *mountinfo = NULL; + + /* Flatpak sees a sandbox mount namespace, not all host disks. */ + if (!flatpak && g_file_get_contents ("/proc/self/mountinfo", &mountinfo, NULL, NULL)) + { + GHashTable *volumes = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free); + char **lines = g_strsplit (mountinfo, "\n", -1); + guint i; + GHashTableIter iter; + gpointer value; + + for (i = 0; lines[i]; i++) + { + char *device, *mountpoint, *filesystem, *source; + char *key = NULL; + StorageUsage usage; + struct stat st; + char *actual_device = NULL; + + if (!sysinfo_linux_mountinfo_parse (lines[i], &device, &mountpoint, &filesystem, &source)) + continue; + /* A covered mount must not be measured as the filesystem on top of it. */ + if (local_filesystem (filesystem) && stat (mountpoint, &st) == 0) + { + actual_device = g_strdup_printf ("%u:%u", (unsigned int) major (st.st_dev), + (unsigned int) minor (st.st_dev)); + if (strcmp (device, actual_device) == 0) + key = filesystem_key (device, mountpoint, filesystem, source); + } + if (key && read_usage (mountpoint, &usage)) + { + StorageUsage *previous = g_hash_table_lookup (volumes, key); + /* Quotas may expose different sizes on the same filesystem. + * Keep one observation rather than adding shared capacity. */ + if (!previous || usage.total > previous->total || + (usage.total == previous->total && usage.available > previous->available)) + { + StorageUsage *copy = g_new (StorageUsage, 1); + *copy = usage; + g_hash_table_replace (volumes, key, copy); + key = NULL; + } + } + g_free (actual_device); + g_free (key); + g_free (device); + g_free (mountpoint); + g_free (filesystem); + g_free (source); + } + g_hash_table_iter_init (&iter, volumes); + while (g_hash_table_iter_next (&iter, NULL, &value)) + { + const StorageUsage *usage = value; + if (usage->total > G_MAXUINT64 - aggregate.total) + { + aggregate.total = 0; + break; + } + aggregate.total += usage->total; + aggregate.available += usage->available; + } + g_hash_table_unref (volumes); + g_strfreev (lines); + g_free (mountinfo); + if (aggregate.total) + return format_scoped_usage (&aggregate, "mounted local filesystems"); + } + + /* Containers and unusual filesystems may not expose block identities. + * Do not describe this limited view as the whole machine's capacity. */ + if (!path || !path[0]) + path = "/"; + if (!read_usage (path, &aggregate)) + return NULL; + return format_scoped_usage (&aggregate, flatpak ? "app data filesystem" : "home filesystem"); +} diff --git a/plugins/sysinfo/unix/storage.h b/plugins/sysinfo/unix/storage.h new file mode 100644 index 00000000..14e3ea9a --- /dev/null +++ b/plugins/sysinfo/unix/storage.h @@ -0,0 +1,11 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#ifndef SYSINFO_LINUX_STORAGE_H +#define SYSINFO_LINUX_STORAGE_H + +#include + +/* The returned strings are owned by the caller. */ +gboolean sysinfo_linux_mountinfo_parse (const char *line, char **device, + char **mountpoint, char **filesystem, char **source); + +#endif From 487b7d8721f5a93192df1b290c9dc9c79ddc6bcd Mon Sep 17 00:00:00 2001 From: deepend Date: Fri, 4 Dec 2026 18:27:33 -0600 Subject: [PATCH 10/15] Windows fixed volume reporting --- plugins/sysinfo/win32/backend.c | 107 +++++++++++++++++++++++--------- 1 file changed, 79 insertions(+), 28 deletions(-) diff --git a/plugins/sysinfo/win32/backend.c b/plugins/sysinfo/win32/backend.c index 8cec67c4..958472ca 100644 --- a/plugins/sysinfo/win32/backend.c +++ b/plugins/sysinfo/win32/backend.c @@ -544,49 +544,100 @@ sysinfo_backend_get_memory (void) return format_usage ((guint64) memory.ullTotalPhys, (guint64) memory.ullAvailPhys); } -char * -sysinfo_backend_get_disk (void) +static char * +get_system_volume_usage (void) { WCHAR windows_dir[MAX_PATH]; WCHAR volume_path[MAX_PATH]; - ULARGE_INTEGER available; - ULARGE_INTEGER total; - ULARGE_INTEGER total_free; - char *usage; - char *volume_utf8; - char *result; + ULARGE_INTEGER available, total, total_free; + UINT length; + char *usage, *result; - if (GetWindowsDirectoryW (windows_dir, G_N_ELEMENTS (windows_dir)) == 0) - { + length = GetWindowsDirectoryW (windows_dir, G_N_ELEMENTS (windows_dir)); + if (!length || length >= G_N_ELEMENTS (windows_dir)) return NULL; - } if (!GetVolumePathNameW (windows_dir, volume_path, G_N_ELEMENTS (volume_path))) - { return NULL; - } - if (!GetDiskFreeSpaceExW (volume_path, &available, &total, &total_free)) - { + if (GetDriveTypeW (volume_path) != DRIVE_FIXED || + !GetDiskFreeSpaceExW (volume_path, &available, &total, &total_free)) return NULL; - } - usage = format_usage ((guint64) total.QuadPart, (guint64) available.QuadPart); if (!usage) - { return NULL; - } - - volume_utf8 = wide_to_utf8 (volume_path); - if (!volume_utf8) - { - return usage; - } - g_strchomp (volume_utf8); - result = g_strdup_printf ("%s" SYSINFO_SEP "%s", usage, volume_utf8); - g_free (volume_utf8); + result = g_strdup_printf ("%s (system volume only)", usage); g_free (usage); return result; } +char * +sysinfo_backend_get_disk (void) +{ + DWORD drives = GetLogicalDrives (); + DWORD previous_mode = 0; + BOOL error_mode_changed; + guint i; + guint64 total = 0, available = 0; + GHashTable *seen = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL); + char *usage, *result; + + /* Offline or empty local devices must not open a system error dialog. */ + error_mode_changed = SetThreadErrorMode (GetThreadErrorMode () | SEM_FAILCRITICALERRORS, &previous_mode); + for (i = 0; i < 26; i++) + { + WCHAR root[] = L"A:\\"; + WCHAR volume[MAX_PATH]; + ULARGE_INTEGER caller_free, caller_total, total_free; + char *key; + + if (!(drives & (1UL << i))) + continue; + root[0] = (WCHAR) (L'A' + i); + /* Don't query mapped network shares or removable media. */ + if (GetDriveTypeW (root) != DRIVE_FIXED) + continue; + /* A stable volume GUID deduplicates aliases. SUBST paths without a + * volume GUID are deliberately skipped rather than double-counted. */ + if (!GetVolumeNameForVolumeMountPointW (root, volume, G_N_ELEMENTS (volume))) + continue; + key = wide_to_utf8 (volume); + if (!key) + continue; + { + char *lower = g_ascii_strdown (key, -1); + g_free (key); + key = lower; + } + if (g_hash_table_contains (seen, key) || + !GetDiskFreeSpaceExW (root, &caller_free, &caller_total, &total_free) || + !caller_total.QuadPart) + { + g_free (key); + continue; + } + if ((guint64) caller_total.QuadPart > G_MAXUINT64 - total) + { + g_free (key); + total = 0; + break; + } + g_hash_table_add (seen, key); + total += (guint64) caller_total.QuadPart; + available += MIN ((guint64) caller_free.QuadPart, (guint64) caller_total.QuadPart); + } + g_hash_table_unref (seen); + usage = format_usage (total, available); + if (!usage) + result = get_system_volume_usage (); + else + { + result = g_strdup_printf ("%s (fixed volumes)", usage); + g_free (usage); + } + if (error_mode_changed) + SetThreadErrorMode (previous_mode, NULL); + return result; +} + char * sysinfo_backend_get_uptime (void) { From 27f5730f5038897e5d0cf6f905ad843bd0db9ba0 Mon Sep 17 00:00:00 2001 From: deepend Date: Fri, 4 Dec 2026 18:28:37 -0600 Subject: [PATCH 11/15] fix CPU frequency+linux memory fallback --- plugins/sysinfo/meson.build | 2 +- plugins/sysinfo/unix/memory.c | 104 +++++++++++++++++++++++ plugins/sysinfo/unix/memory.h | 8 ++ plugins/sysinfo/unix/modern-backend.c | 118 +++++++++++++++----------- plugins/sysinfo/win32/backend.c | 11 +++ 5 files changed, 192 insertions(+), 51 deletions(-) create mode 100644 plugins/sysinfo/unix/memory.c create mode 100644 plugins/sysinfo/unix/memory.h diff --git a/plugins/sysinfo/meson.build b/plugins/sysinfo/meson.build index d8cb7da3..58ea89a4 100644 --- a/plugins/sysinfo/meson.build +++ b/plugins/sysinfo/meson.build @@ -24,7 +24,7 @@ if system == 'linux' endif sysinfo_includes += 'unix' - sysinfo_sources += ['unix/modern-backend.c', 'unix/storage.c'] + sysinfo_sources += ['unix/modern-backend.c', 'unix/storage.c', 'unix/memory.c'] elif system == 'freebsd' or system == 'gnu' or system.startswith('gnu/') sysinfo_includes += ['shared', 'unix'] diff --git a/plugins/sysinfo/unix/memory.c b/plugins/sysinfo/unix/memory.c new file mode 100644 index 00000000..ee76e3b0 --- /dev/null +++ b/plugins/sysinfo/unix/memory.c @@ -0,0 +1,104 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#include +#include +#include +#include "../format.h" +#include "memory.h" + +enum +{ + MEM_TOTAL, MEM_AVAILABLE, MEM_FREE, BUFFERS, CACHED, + S_RECLAIMABLE, SHMEM, SWAP_TOTAL, SWAP_FREE, FIELD_COUNT +}; + +static gboolean +parse_kib (const char *text, guint64 *value) +{ + char *end; + guint64 parsed; + while (g_ascii_isspace (*text)) + text++; + if (!g_ascii_isdigit (*text)) + return FALSE; + errno = 0; + parsed = g_ascii_strtoull (text, &end, 10); + if (errno || parsed > G_MAXUINT64 / 1024) + return FALSE; + while (g_ascii_isspace (*end)) + end++; + if (strncmp (end, "kB", 2) != 0) + return FALSE; + end += 2; + while (g_ascii_isspace (*end)) + end++; + if (*end) + return FALSE; + *value = parsed; + return TRUE; +} + +char * +sysinfo_linux_format_meminfo (const char *contents) +{ + static const char *keys[FIELD_COUNT] = { + "MemTotal:", "MemAvailable:", "MemFree:", "Buffers:", "Cached:", + "SReclaimable:", "Shmem:", "SwapTotal:", "SwapFree:" + }; + guint64 values[FIELD_COUNT] = {0}; + gboolean present[FIELD_COUNT] = {FALSE}; + char **lines; + guint i, j; + guint64 available; + char *memory; + gboolean estimated = FALSE; + + if (!contents) + return NULL; + lines = g_strsplit (contents, "\n", -1); + for (i = 0; lines[i]; i++) + { + for (j = 0; j < FIELD_COUNT; j++) + { + if (g_str_has_prefix (lines[i], keys[j])) + { + present[j] = parse_kib (lines[i] + strlen (keys[j]), &values[j]); + break; + } + } + } + g_strfreev (lines); + if (!present[MEM_TOTAL] || !values[MEM_TOTAL]) + return NULL; + if (present[MEM_AVAILABLE]) + available = values[MEM_AVAILABLE]; + else if (present[MEM_FREE]) + { + /* Older kernels lack MemAvailable. This estimate excludes shared + * memory from the reclaimable-cache sum and is labelled as such. */ + available = values[MEM_FREE] + values[BUFFERS] + values[CACHED] + values[S_RECLAIMABLE]; + available -= MIN (available, values[SHMEM]); + estimated = TRUE; + } + else + return NULL; + available = MIN (available, values[MEM_TOTAL]); + memory = sysinfo_format_usage (values[MEM_TOTAL] * 1024, available * 1024); + if (memory && estimated) + { + char *labelled = g_strdup_printf ("%s (estimated available)", memory); + g_free (memory); + memory = labelled; + } + if (memory && present[SWAP_TOTAL] && present[SWAP_FREE] && values[SWAP_TOTAL]) + { + char *swap = sysinfo_format_usage (values[SWAP_TOTAL] * 1024, values[SWAP_FREE] * 1024); + if (swap) + { + char *result = g_strdup_printf ("%s \xC2\xB7 Swap: %s", memory, swap); + g_free (memory); + g_free (swap); + return result; + } + } + return memory; +} diff --git a/plugins/sysinfo/unix/memory.h b/plugins/sysinfo/unix/memory.h new file mode 100644 index 00000000..66ed5783 --- /dev/null +++ b/plugins/sysinfo/unix/memory.h @@ -0,0 +1,8 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#ifndef SYSINFO_LINUX_MEMORY_H +#define SYSINFO_LINUX_MEMORY_H + +/* Parse a /proc/meminfo snapshot; the caller owns the returned string. */ +char *sysinfo_linux_format_meminfo (const char *contents); + +#endif diff --git a/plugins/sysinfo/unix/modern-backend.c b/plugins/sysinfo/unix/modern-backend.c index 8d074ddf..ae079dbd 100644 --- a/plugins/sysinfo/unix/modern-backend.c +++ b/plugins/sysinfo/unix/modern-backend.c @@ -27,6 +27,7 @@ #include "../format.h" #include "../sysinfo-backend.h" +#include "memory.h" #define SYSINFO_SEP " \xC2\xB7 " @@ -702,10 +703,73 @@ sysinfo_backend_get_os (void) return g_strdup (snapshot.os); } +static double +read_cpu_frequency_mhz (const char **kind) +{ + static const char *paths[] = { + "/sys/devices/system/cpu/cpu0/cpufreq/base_frequency", + "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq" + }; + guint i; + FILE *fp; + char line[1024]; + + for (i = 0; i < G_N_ELEMENTS (paths); i++) + { + char *text = read_trimmed_file (paths[i]); + char *end; + guint64 khz; + if (!text) + continue; + errno = 0; + khz = g_ascii_strtoull (text, &end, 10); + if (!errno && end != text && !*end && khz > 0 && khz <= 100000000) + { + g_free (text); + *kind = i == 0 ? "CPU0 base" : "CPU0 max"; + return (double) khz / 1000.0; + } + g_free (text); + } + fp = fopen ("/proc/cpuinfo", "r"); + if (!fp) + return 0; + while (fgets (line, sizeof (line), fp)) + { + char *colon = strchr (line, ':'); + if (colon) + { + char *end; + double mhz; + *colon = '\0'; + if (g_ascii_strcasecmp (g_strstrip (line), "cpu MHz") != 0) + continue; + mhz = g_ascii_strtod (colon + 1, &end); + if (end != colon + 1 && mhz > 0 && mhz <= 100000) + { + fclose (fp); + *kind = "sampled"; + return mhz; + } + } + } + fclose (fp); + return 0; +} + char * sysinfo_backend_get_cpu (void) { + const char *kind = NULL; + double mhz; ensure_cpu_snapshot (); + if (!snapshot.cpu) + return NULL; + mhz = read_cpu_frequency_mhz (&kind); + if (mhz >= 1000) + return g_strdup_printf ("%s" SYSINFO_SEP "%s %.2f GHz", snapshot.cpu, kind, mhz / 1000.0); + if (mhz > 0) + return g_strdup_printf ("%s" SYSINFO_SEP "%s %.0f MHz", snapshot.cpu, kind, mhz); return g_strdup (snapshot.cpu); } @@ -733,59 +797,13 @@ sysinfo_backend_get_sound (void) char * sysinfo_backend_get_memory (void) { - FILE *fp; - char line[512]; - guint64 mem_total_kib = 0; - guint64 mem_available_kib = 0; - guint64 swap_total_kib = 0; - guint64 swap_free_kib = 0; + char *contents = NULL; char *memory; - fp = fopen ("/proc/meminfo", "r"); - if (!fp) - { + if (!g_file_get_contents ("/proc/meminfo", &contents, NULL, NULL)) return NULL; - } - - while (fgets (line, sizeof (line), fp) != NULL) - { - if (g_str_has_prefix (line, "MemTotal:")) - { - mem_total_kib = g_ascii_strtoull (line + strlen ("MemTotal:"), NULL, 10); - } - else if (g_str_has_prefix (line, "MemAvailable:")) - { - mem_available_kib = g_ascii_strtoull (line + strlen ("MemAvailable:"), NULL, 10); - } - else if (g_str_has_prefix (line, "SwapTotal:")) - { - swap_total_kib = g_ascii_strtoull (line + strlen ("SwapTotal:"), NULL, 10); - } - else if (g_str_has_prefix (line, "SwapFree:")) - { - swap_free_kib = g_ascii_strtoull (line + strlen ("SwapFree:"), NULL, 10); - } - } - fclose (fp); - - if (mem_total_kib == 0) - { - return NULL; - } - - memory = format_usage (mem_total_kib * 1024, mem_available_kib * 1024); - if (memory && swap_total_kib != 0) - { - char *swap = format_usage (swap_total_kib * 1024, swap_free_kib * 1024); - if (swap) - { - char *result = g_strdup_printf ("%s" SYSINFO_SEP "Swap: %s", memory, swap); - g_free (memory); - g_free (swap); - return result; - } - } - + memory = sysinfo_linux_format_meminfo (contents); + g_free (contents); return memory; } diff --git a/plugins/sysinfo/win32/backend.c b/plugins/sysinfo/win32/backend.c index 958472ca..5e67eae4 100644 --- a/plugins/sysinfo/win32/backend.c +++ b/plugins/sysinfo/win32/backend.c @@ -505,7 +505,18 @@ sysinfo_backend_get_os (void) char * sysinfo_backend_get_cpu (void) { + static const WCHAR cpu_key[] = L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0"; + DWORD mhz = 0; ensure_cpu_snapshot (); + if (!snapshot.cpu) + return NULL; + /* The registry's reported MHz is not a guaranteed live or turbo clock. */ + if (read_registry_dword (HKEY_LOCAL_MACHINE, cpu_key, L"~MHz", &mhz) && mhz && mhz <= 100000) + { + if (mhz >= 1000) + return g_strdup_printf ("%s" SYSINFO_SEP "reported %.2f GHz", snapshot.cpu, (double) mhz / 1000.0); + return g_strdup_printf ("%s" SYSINFO_SEP "reported %lu MHz", snapshot.cpu, (unsigned long) mhz); + } return g_strdup (snapshot.cpu); } From 5c8036ad80f45c66709c57e4867faefba335cb34 Mon Sep 17 00:00:00 2001 From: deepend Date: Fri, 4 Dec 2026 18:29:17 -0600 Subject: [PATCH 12/15] improve hardware probes+ legacy cleanup --- plugins/sysinfo/unix/modern-backend.c | 27 ++++++++++++++++----------- plugins/sysinfo/unix/pci.c | 27 ++++++++++++++++++++------- 2 files changed, 36 insertions(+), 18 deletions(-) diff --git a/plugins/sysinfo/unix/modern-backend.c b/plugins/sysinfo/unix/modern-backend.c index ae079dbd..304777b2 100644 --- a/plugins/sysinfo/unix/modern-backend.c +++ b/plugins/sysinfo/unix/modern-backend.c @@ -116,7 +116,7 @@ read_hex_file (const char *path, guint *value) errno = 0; parsed = g_ascii_strtoull (contents, &end, 16); - if (errno != 0 || end == contents) + if (errno != 0 || end == contents || *end != '\0' || parsed > G_MAXUINT || contents[0] == '-') { g_free (contents); return FALSE; @@ -535,19 +535,22 @@ scan_pci_devices (void) gpus = g_ptr_array_new_with_free_func (g_free); chipsets = g_ptr_array_new_with_free_func (g_free); + dir = g_dir_open ("/sys/bus/pci/devices", 0, NULL); #ifdef HAVE_LIBPCI - /* We only need name lookup: autodetection can exit the client if sysfs - * is hidden in a sandbox and libpci tries privileged access methods. - * Explicit sysfs initialization installs callbacks without probing. */ - if (pci_lookup_method ("linux-sysfs") >= 0) + /* Only initialize the explicit sysfs method when PCI is visible. Never + * use autodetection or ask libpci to probe/configure a device. */ + if (dir) { - pacc = pci_alloc (); - pacc->method = pci_lookup_method ("linux-sysfs"); - pci_init (pacc); + int method = pci_lookup_method ("linux-sysfs"); + if (method >= 0) + { + pacc = pci_alloc (); + pacc->method = method; + pci_init (pacc); + } } #endif - dir = g_dir_open ("/sys/bus/pci/devices", 0, NULL); if (dir) { while ((entry = g_dir_read_name (dir)) != NULL) @@ -614,8 +617,9 @@ scan_pci_devices (void) g_free (gpu_name); } } - else if (class_subclass == 0x0600) + else if (class_subclass == 0x0600 || class_subclass == 0x0601) { + /* Include host bridges and ISA/LPC bridges. */ ptr_array_add_unique (chipsets, name); } @@ -821,7 +825,8 @@ sysinfo_backend_get_uptime (void) } uptime = g_ascii_strtod (contents, &end); - if (end == contents || uptime <= 0.0) + /* Comparisons also reject NaN, infinity and out-of-range conversions. */ + if (end == contents || !(uptime >= 0.0 && uptime < (double) G_MAXINT64)) { g_free (contents); return NULL; diff --git a/plugins/sysinfo/unix/pci.c b/plugins/sysinfo/unix/pci.c index fac2f76e..229d3ed5 100644 --- a/plugins/sysinfo/unix/pci.c +++ b/plugins/sysinfo/unix/pci.c @@ -51,12 +51,18 @@ static struct device *scan_device(struct pci_dev *p) d = g_new0 (struct device, 1); d->dev = p; if (!pci_read_block(p, 0, d->config, how_much)) - exit(1); + { + g_free (d); + return NULL; + } if (how_much < 128 && (d->config[PCI_HEADER_TYPE] & 0x7f) == PCI_HEADER_TYPE_CARDBUS) { /* For cardbus bridges, we need to fetch 64 bytes more to get the full standard header... */ if (!pci_read_block(p, 64, d->config+64, 64)) - exit(1); + { + g_free (d); + return NULL; + } how_much = 128; } d->config_cnt = how_much; @@ -116,6 +122,14 @@ int pci_find_by_class(u16 *class, char *vendor, char *device) } pci_cleanup(pacc); + pacc = NULL; + /* Free the cached configuration buffers after libpci is done with them. */ + while (first_dev) + { + d = first_dev; + first_dev = d->next; + g_free (d); + } return nomatch; } @@ -142,8 +156,7 @@ void pci_find_fullname(char *fullname, char *vendor, char *device) position = strstr(buffer, vendor); position += 6; g_strlcpy(vendorname, position, sizeof (vendorname)); - position = strstr(vendorname, "\n"); - *(position) = '\0'; + g_strchomp (vendorname); break; } } @@ -155,9 +168,9 @@ void pci_find_fullname(char *fullname, char *vendor, char *device) position += 6; g_strlcpy(devicename, position, sizeof (devicename)); position = strstr(devicename, " ("); - if (position == NULL) - position = strstr(devicename, "\n"); - *(position) = '\0'; + if (position) + *position = '\0'; + g_strchomp (devicename); cardfound = 1; break; } From 81709c72356aa27f58e01f92859e485ecc12c704 Mon Sep 17 00:00:00 2001 From: deepend Date: Fri, 4 Dec 2026 18:30:22 -0600 Subject: [PATCH 13/15] fix macOS build/resource ownership --- meson_options.txt | 2 +- plugins/sysinfo/meson.build | 1 + plugins/sysinfo/osx/backend.m | 33 ++++++++++++++++++++------------- 3 files changed, 22 insertions(+), 14 deletions(-) diff --git a/meson_options.txt b/meson_options.txt index b175ad0f..82e9f268 100644 --- a/meson_options.txt +++ b/meson_options.txt @@ -67,7 +67,7 @@ option('with-python', type: 'string', value: 'python3', description: 'Python scripting plugin. value is pkg-config name to use or "false"' ) option('with-sysinfo', type: 'boolean', - description: 'System information plugin, requires libpci on Unix' + description: 'System information plugin (optional libpci for PCI names on Unix)' ) option('with-upd', type: 'boolean', description: 'Update plugin, Windows only' diff --git a/plugins/sysinfo/meson.build b/plugins/sysinfo/meson.build index 58ea89a4..6f9d0abb 100644 --- a/plugins/sysinfo/meson.build +++ b/plugins/sysinfo/meson.build @@ -54,6 +54,7 @@ elif system == 'darwin' sysinfo_includes += 'shared' sysinfo_sources += 'shared/df.c' add_languages('objc') + sysinfo_deps += dependency('appleframeworks', modules: ['Cocoa', 'IOKit']) sysinfo_sources += 'osx/backend.m' elif system == 'windows' diff --git a/plugins/sysinfo/osx/backend.m b/plugins/sysinfo/osx/backend.m index 7a64d16a..16041029 100644 --- a/plugins/sysinfo/osx/backend.m +++ b/plugins/sysinfo/osx/backend.m @@ -23,6 +23,8 @@ */ #import +#include +#include #include #include @@ -38,6 +40,7 @@ #include "format.h" #include "df.h" +#include "sysinfo-backend.h" static char * get_os (void) @@ -48,10 +51,7 @@ get_os (void) return NULL; NSString *version = [systemversion objectForKey:@"ProductUserVisibleVersion"]; if (!version) - { - [build release]; return NULL; - } NSDictionary *profiler = [NSDictionary dictionaryWithContentsOfFile:[@"~/Library/Preferences/com.apple.SystemProfiler.plist" stringByExpandingTildeInPath]]; NSDictionary *names = [profiler objectForKey:@"OS Names"]; @@ -65,18 +65,11 @@ get_os (void) break; } } - [build release]; - + /* Dictionary values are borrowed; releasing them would over-release. */ if (!os_name) - { - [version release]; return NULL; - } - char *ret = g_strdup_printf ("%s %s", [os_name UTF8String], [version UTF8String]); - [version release]; - - return ret; + return g_strdup_printf ("%s %s", [os_name UTF8String], [version UTF8String]); } static char * @@ -219,9 +212,14 @@ get_gpu(void) } const void *class = CFDictionaryGetValue(serviceDictionary, @"class-code"); - if (!class || *(guint32*)CFDataGetBytePtr(class) != 0x30000) /* DISPLAY_VGA */ + guint32 class_code = 0; + if (class && CFGetTypeID (class) == CFDataGetTypeID () && + CFDataGetLength (class) >= sizeof (class_code)) + memcpy (&class_code, CFDataGetBytePtr (class), sizeof (class_code)); + if (GUINT32_FROM_LE (class_code) != 0x30000) /* DISPLAY_VGA */ { CFRelease(serviceDictionary); + IOObjectRelease (serviceObject); continue; } @@ -237,7 +235,9 @@ get_gpu(void) } CFRelease(serviceDictionary); + IOObjectRelease (serviceObject); } + IOObjectRelease (entry_iterator); if (gpu_list->len == 0) { @@ -265,6 +265,13 @@ sysinfo_backend_get_gpu(void) return g_strdup (gpu_str); } +char * +sysinfo_backend_get_chipset (void) +{ + /* No chipset detector exists in the legacy macOS backend. */ + return NULL; +} + char * sysinfo_backend_get_sound(void) { From 38e7a5c7639d7e1f8a07518f43ef4eef14e2a12b Mon Sep 17 00:00:00 2001 From: deepend Date: Fri, 4 Dec 2026 19:23:49 -0600 Subject: [PATCH 14/15] linux boot drive capacity --- plugins/sysinfo/unix/storage.c | 422 ++++++++++++++------------------- plugins/sysinfo/unix/storage.h | 5 +- 2 files changed, 182 insertions(+), 245 deletions(-) diff --git a/plugins/sysinfo/unix/storage.c b/plugins/sysinfo/unix/storage.c index 086be1fc..d6f0420b 100644 --- a/plugins/sysinfo/unix/storage.c +++ b/plugins/sysinfo/unix/storage.c @@ -1,294 +1,232 @@ /* SPDX-License-Identifier: GPL-2.0-or-later */ -/* Report mounted local filesystem capacity without probing network mounts. */ +/* Whole capacity of the disk backing the boot filesystem. */ +#define _XOPEN_SOURCE 700 #include -#include +#include #include -#include #include -#include #include -#include - -#if defined(__has_include) -# if __has_include() -# include -# endif -#endif - #include -#include "../format.h" #include "../sysinfo-backend.h" #include "storage.h" -typedef struct +static gboolean +read_capacity (const char *entry, guint64 *capacity) { - guint64 total; - guint64 available; -} StorageUsage; - -static char * -decode_mount_field (const char *field) -{ - GString *value = g_string_new (NULL); - const char *p; - - for (p = field; *p; p++) - { - /* mountinfo escapes whitespace and backslashes as octal. */ - if (*p == '\\' && p[1] && p[2] && p[3] && - p[1] >= '0' && p[1] <= '3' && - p[2] >= '0' && p[2] <= '7' && p[3] >= '0' && p[3] <= '7') - { - guint code = (p[1] - '0') * 64 + (p[2] - '0') * 8 + p[3] - '0'; - if (code == 0) - { - g_string_free (value, TRUE); - return NULL; - } - g_string_append_c (value, (char) code); - p += 3; - } - else - g_string_append_c (value, *p); - } - return g_string_free (value, FALSE); -} - -gboolean -sysinfo_linux_mountinfo_parse (const char *line, char **device, - char **mountpoint, char **filesystem, char **source) -{ - char **fields; - guint i, n; + char *path = g_build_filename (entry, "size", NULL); + char *contents = NULL; + char *end; + guint64 sectors; gboolean valid = FALSE; - *device = *mountpoint = *filesystem = *source = NULL; - fields = g_strsplit (line, " ", -1); - n = g_strv_length (fields); - for (i = 6; i + 3 < n; i++) + if (g_file_get_contents (path, &contents, NULL, NULL)) { - if (strcmp (fields[i], "-") != 0) - continue; - if (!strchr (fields[2], ':') || fields[4][0] != '/' || !fields[i + 1][0]) - break; - *mountpoint = decode_mount_field (fields[4]); - *source = decode_mount_field (fields[i + 2]); - if (*mountpoint && *source) + g_strstrip (contents); + if (g_ascii_isdigit (contents[0])) { - *device = g_strdup (fields[2]); - *filesystem = g_strdup (fields[i + 1]); - valid = TRUE; + errno = 0; + sectors = g_ascii_strtoull (contents, &end, 10); + /* Linux reports size in 512-byte sectors, including 4Kn disks. */ + if (!errno && *end == '\0' && sectors && sectors <= G_MAXUINT64 / 512) + { + *capacity = sectors * 512; + valid = TRUE; + } } - else - { - g_clear_pointer (mountpoint, g_free); - g_clear_pointer (source, g_free); - } - break; } - g_strfreev (fields); + g_free (contents); + g_free (path); return valid; } static gboolean -local_filesystem (const char *filesystem) +has_entry (const char *entry, const char *name) { - /* A conservative list avoids statvfs on NFS, SMB, autofs and remote FUSE. - * fuseblk is accepted only when a real block device is verified below. */ - static const char *types[] = { - "ext2", "ext3", "ext4", "xfs", "btrfs", "bcachefs", "f2fs", - "jfs", "reiserfs", "nilfs2", "vfat", "msdos", "exfat", "ntfs", - "ntfs3", "fuseblk", "hfs", "hfsplus", "ufs", "minix", "zfs", NULL - }; - guint i; - for (i = 0; types[i]; i++) - if (strcmp (types[i], filesystem) == 0) - return TRUE; - return FALSE; + char *path = g_build_filename (entry, name, NULL); + gboolean present = g_file_test (path, G_FILE_TEST_EXISTS); + g_free (path); + return present; +} + +/* Resolve the kernel device link before walking from a partition to its + * parent. Never infer the parent by stripping digits from a device name. */ +static gboolean +resolve_disk (const char *entry, char **disk, guint depth) +{ + char *resolved = realpath (entry, NULL); + char *slaves = NULL; + GDir *dir = NULL; + const char *name; + gboolean valid = FALSE; + + if (!resolved || depth >= 32) + goto done; + if (has_entry (resolved, "partition")) + { + char *parent = g_path_get_dirname (resolved); + valid = resolve_disk (parent, disk, depth + 1); + g_free (parent); + goto done; + } + + /* Follow LUKS/LVM/MD layers. Multiple distinct underlying disks are + * ambiguous, so don't arbitrarily choose one of them. */ + slaves = g_build_filename (resolved, "slaves", NULL); + dir = g_dir_open (slaves, 0, NULL); + if (dir && (name = g_dir_read_name (dir)) != NULL) + { + do + { + char *child = g_build_filename (slaves, name, NULL); + valid = resolve_disk (child, disk, depth + 1); + g_free (child); + if (!valid) + goto done; + } while ((name = g_dir_read_name (dir)) != NULL); + goto done; + } + name = strrchr (resolved, '/'); + name = name ? name + 1 : resolved; + if (g_str_has_prefix (name, "loop") || g_str_has_prefix (name, "ram") || + g_str_has_prefix (name, "zram") || g_str_has_prefix (name, "sr") || + g_str_has_prefix (name, "fd") || g_str_has_prefix (name, "dm-") || + g_str_has_prefix (name, "md") || !has_entry (resolved, "device")) + goto done; + if (!*disk) + *disk = g_strdup (resolved); + valid = strcmp (*disk, resolved) == 0; + +done: + if (dir) + g_dir_close (dir); + g_free (slaves); + free (resolved); + return valid; +} + +static guint +boot_mount_priority (const char *mountpoint) +{ + if (strcmp (mountpoint, "/boot") == 0) + return 4; + if (strcmp (mountpoint, "/boot/efi") == 0) + return 3; + if (strcmp (mountpoint, "/efi") == 0) + return 2; + if (strcmp (mountpoint, "/") == 0) + return 1; + return 0; } static gboolean -read_usage (const char *path, StorageUsage *usage) +valid_device_number (const char *id) { - struct statvfs fs; - guint64 block_size; - - if (statvfs (path, &fs) != 0) + const char *p = id; + if (!g_ascii_isdigit (*p)) return FALSE; - block_size = fs.f_frsize ? (guint64) fs.f_frsize : (guint64) fs.f_bsize; - if (!block_size || !fs.f_blocks || (guint64) fs.f_blocks > G_MAXUINT64 / block_size) + while (g_ascii_isdigit (*p)) + p++; + if (*p++ != ':' || !g_ascii_isdigit (*p)) return FALSE; - usage->total = (guint64) fs.f_blocks * block_size; - usage->available = MIN ((guint64) fs.f_bavail, (guint64) fs.f_blocks) * block_size; - return TRUE; + while (g_ascii_isdigit (*p)) + p++; + return *p == '\0'; } static char * -filesystem_key (const char *device, const char *mountpoint, - const char *filesystem, const char *source) +resolve_mount_device (const char *sysfs, const char *id, const char *source) { + char *entry = NULL; struct stat st; - char *id, *sys_path, *target, *name; - gboolean block_source = FALSE; - if (strcmp (filesystem, "zfs") == 0) + /* Btrfs and some other filesystems expose a synthetic mount device + * number. Prefer a verified source block device in that case. */ + if (valid_device_number (id)) { - /* Datasets share their pool; don't add its capacity repeatedly. */ - const char *slash = strchr (source, '/'); - return source[0] && source[0] != '/' ? - g_strdup_printf ("zfs:%.*s", (int) (slash ? (gsize) (slash - source) : strlen (source)), source) : NULL; + entry = g_build_filename (sysfs, "dev", "block", id, NULL); + if (g_file_test (entry, G_FILE_TEST_EXISTS)) + return entry; + g_free (entry); } - - /* A bind mount shares the device number. Btrfs subvolumes can have - * separate synthetic device numbers, so prefer the source block device. */ if (g_str_has_prefix (source, "/dev/") && stat (source, &st) == 0 && S_ISBLK (st.st_mode)) { - id = g_strdup_printf ("%u:%u", (unsigned int) major (st.st_rdev), + char *number = g_strdup_printf ("%u:%u", (unsigned int) major (st.st_rdev), (unsigned int) minor (st.st_rdev)); - block_source = TRUE; + entry = g_build_filename (sysfs, "dev", "block", number, NULL); + g_free (number); + return entry; } - else - id = g_strdup (device); - - sys_path = g_build_filename ("/sys/dev/block", id, NULL); - target = g_file_read_link (sys_path, NULL); - g_free (sys_path); - if (!target && !block_source) - { - g_free (id); - return NULL; - } - name = g_path_get_basename (target ? target : source); - g_free (target); - if (g_str_has_prefix (name, "loop") || g_str_has_prefix (name, "ram") || - g_str_has_prefix (name, "zram") || g_str_has_prefix (name, "fd") || - g_str_has_prefix (name, "sr")) - { - g_free (name); - g_free (id); - return NULL; - } - g_free (name); - -#ifdef BTRFS_IOC_FS_INFO - if (strcmp (filesystem, "btrfs") == 0) - { - /* The filesystem UUID is shared by all subvolumes and members of - * a multi-device filesystem (unlike st_dev or statfs.f_fsid). */ - int fd = open (mountpoint, O_RDONLY); - if (fd >= 0) - { - struct btrfs_ioctl_fs_info_args info = {0}; - if (ioctl (fd, BTRFS_IOC_FS_INFO, &info) == 0) - { - GString *uuid = g_string_new ("btrfs:"); - guint i; - for (i = 0; i < sizeof (info.fsid); i++) - g_string_append_printf (uuid, "%02x", (unsigned int) info.fsid[i]); - g_free (id); - id = g_string_free (uuid, FALSE); - } - close (fd); - } - } -#else - (void) mountpoint; -#endif - return id; + /* A sandbox may hide /dev nodes but still expose kernel block names. + * Only accept a direct /dev/, never guess a mapper/UUID alias. */ + if (g_str_has_prefix (source, "/dev/") && source[5] && + strcmp (source + 5, ".") != 0 && strcmp (source + 5, "..") != 0 && + !strchr (source + 5, '/') && !strchr (source + 5, '\\')) + return g_build_filename (sysfs, "class", "block", source + 5, NULL); + return NULL; } -static char * -format_scoped_usage (const StorageUsage *usage, const char *scope) +char * +sysinfo_linux_boot_disk (const char *sysfs, const char *mountinfo) { - char *formatted = sysinfo_format_usage (usage->total, usage->available); - char *result; - if (!formatted) - return NULL; - result = g_strdup_printf ("%s (%s)", formatted, scope); - g_free (formatted); + char **lines = g_strsplit (mountinfo, "\n", -1); + char *entry = NULL, *disk = NULL, *result = NULL; + guint priority = 0, i; + guint64 capacity; + gboolean ambiguous = FALSE; + + for (i = 0; lines[i]; i++) + { + char **fields = g_strsplit (lines[i], " ", -1); + guint count = g_strv_length (fields), rank, j; + + if (count < 10 || !(rank = boot_mount_priority (fields[4])) || rank < priority) + { + g_strfreev (fields); + continue; + } + for (j = 6; j + 3 < count; j++) + if (strcmp (fields[j], "-") == 0) + { + char *candidate = resolve_mount_device (sysfs, fields[2], fields[j + 2]); + if (rank > priority) + { + g_free (entry); + entry = candidate; + priority = rank; + ambiguous = FALSE; + } + else + { + if (g_strcmp0 (entry, candidate) != 0) + ambiguous = TRUE; + g_free (candidate); + } + break; + } + g_strfreev (fields); + } + g_strfreev (lines); + + if (!ambiguous && entry && resolve_disk (entry, &disk, 0) && + read_capacity (disk, &capacity)) + result = g_format_size (capacity); + g_free (disk); + g_free (entry); return result; } char * sysinfo_backend_get_disk (void) { - const gboolean flatpak = g_file_test ("/.flatpak-info", G_FILE_TEST_IS_REGULAR); - const char *path = flatpak ? g_get_user_data_dir () : g_get_home_dir (); - StorageUsage aggregate = {0, 0}; char *mountinfo = NULL; + char *result; - /* Flatpak sees a sandbox mount namespace, not all host disks. */ - if (!flatpak && g_file_get_contents ("/proc/self/mountinfo", &mountinfo, NULL, NULL)) - { - GHashTable *volumes = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free); - char **lines = g_strsplit (mountinfo, "\n", -1); - guint i; - GHashTableIter iter; - gpointer value; - - for (i = 0; lines[i]; i++) - { - char *device, *mountpoint, *filesystem, *source; - char *key = NULL; - StorageUsage usage; - struct stat st; - char *actual_device = NULL; - - if (!sysinfo_linux_mountinfo_parse (lines[i], &device, &mountpoint, &filesystem, &source)) - continue; - /* A covered mount must not be measured as the filesystem on top of it. */ - if (local_filesystem (filesystem) && stat (mountpoint, &st) == 0) - { - actual_device = g_strdup_printf ("%u:%u", (unsigned int) major (st.st_dev), - (unsigned int) minor (st.st_dev)); - if (strcmp (device, actual_device) == 0) - key = filesystem_key (device, mountpoint, filesystem, source); - } - if (key && read_usage (mountpoint, &usage)) - { - StorageUsage *previous = g_hash_table_lookup (volumes, key); - /* Quotas may expose different sizes on the same filesystem. - * Keep one observation rather than adding shared capacity. */ - if (!previous || usage.total > previous->total || - (usage.total == previous->total && usage.available > previous->available)) - { - StorageUsage *copy = g_new (StorageUsage, 1); - *copy = usage; - g_hash_table_replace (volumes, key, copy); - key = NULL; - } - } - g_free (actual_device); - g_free (key); - g_free (device); - g_free (mountpoint); - g_free (filesystem); - g_free (source); - } - g_hash_table_iter_init (&iter, volumes); - while (g_hash_table_iter_next (&iter, NULL, &value)) - { - const StorageUsage *usage = value; - if (usage->total > G_MAXUINT64 - aggregate.total) - { - aggregate.total = 0; - break; - } - aggregate.total += usage->total; - aggregate.available += usage->available; - } - g_hash_table_unref (volumes); - g_strfreev (lines); - g_free (mountinfo); - if (aggregate.total) - return format_scoped_usage (&aggregate, "mounted local filesystems"); - } - - /* Containers and unusual filesystems may not expose block identities. - * Do not describe this limited view as the whole machine's capacity. */ - if (!path || !path[0]) - path = "/"; - if (!read_usage (path, &aggregate)) + /* The sandbox root is not the host boot filesystem. Without a trusted + * host mount table there is no reliable way to identify its boot disk. */ + if (g_file_test ("/.flatpak-info", G_FILE_TEST_IS_REGULAR) || + !g_file_get_contents ("/proc/self/mountinfo", &mountinfo, NULL, NULL)) return NULL; - return format_scoped_usage (&aggregate, flatpak ? "app data filesystem" : "home filesystem"); + result = sysinfo_linux_boot_disk ("/sys", mountinfo); + g_free (mountinfo); + return result; } diff --git a/plugins/sysinfo/unix/storage.h b/plugins/sysinfo/unix/storage.h index 14e3ea9a..684afca1 100644 --- a/plugins/sysinfo/unix/storage.h +++ b/plugins/sysinfo/unix/storage.h @@ -4,8 +4,7 @@ #include -/* The returned strings are owned by the caller. */ -gboolean sysinfo_linux_mountinfo_parse (const char *line, char **device, - char **mountpoint, char **filesystem, char **source); +/* Returns the whole boot disk size, or NULL if it cannot be identified. */ +char *sysinfo_linux_boot_disk (const char *sysfs, const char *mountinfo); #endif From 3394faae0441898c1a444866971223909d38fbe3 Mon Sep 17 00:00:00 2001 From: deepend Date: Fri, 4 Dec 2026 19:24:34 -0600 Subject: [PATCH 15/15] Windows boot drive capacity --- plugins/sysinfo/win32/backend.c | 121 +++++++++++++------------------- 1 file changed, 50 insertions(+), 71 deletions(-) diff --git a/plugins/sysinfo/win32/backend.c b/plugins/sysinfo/win32/backend.c index 5e67eae4..267af9c2 100644 --- a/plugins/sysinfo/win32/backend.c +++ b/plugins/sysinfo/win32/backend.c @@ -18,6 +18,7 @@ #include #include #include +#include #ifdef _MSC_VER #pragma comment(lib, "advapi32.lib") @@ -555,94 +556,72 @@ sysinfo_backend_get_memory (void) return format_usage ((guint64) memory.ullTotalPhys, (guint64) memory.ullAvailPhys); } -static char * -get_system_volume_usage (void) +static gboolean +get_boot_disk_number (DWORD *number) { WCHAR windows_dir[MAX_PATH]; WCHAR volume_path[MAX_PATH]; - ULARGE_INTEGER available, total, total_free; + WCHAR volume_name[MAX_PATH]; UINT length; - char *usage, *result; + HANDLE volume; + VOLUME_DISK_EXTENTS extents; + DWORD returned; + gboolean valid = FALSE; + /* Windows calls the volume containing Windows the boot volume. Resolve + * it to a volume GUID instead of assuming Windows is installed on C:. */ length = GetWindowsDirectoryW (windows_dir, G_N_ELEMENTS (windows_dir)); - if (!length || length >= G_N_ELEMENTS (windows_dir)) - return NULL; - if (!GetVolumePathNameW (windows_dir, volume_path, G_N_ELEMENTS (volume_path))) - return NULL; - if (GetDriveTypeW (volume_path) != DRIVE_FIXED || - !GetDiskFreeSpaceExW (volume_path, &available, &total, &total_free)) - return NULL; - usage = format_usage ((guint64) total.QuadPart, (guint64) available.QuadPart); - if (!usage) - return NULL; - result = g_strdup_printf ("%s (system volume only)", usage); - g_free (usage); - return result; + if (!length || length >= G_N_ELEMENTS (windows_dir) || + !GetVolumePathNameW (windows_dir, volume_path, G_N_ELEMENTS (volume_path)) || + GetDriveTypeW (volume_path) != DRIVE_FIXED || + !GetVolumeNameForVolumeMountPointW (volume_path, volume_name, G_N_ELEMENTS (volume_name))) + return FALSE; + length = lstrlenW (volume_name); + if (!length || volume_name[length - 1] != L'\\') + return FALSE; + volume_name[length - 1] = L'\0'; + volume = CreateFileW (volume_name, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, + NULL, OPEN_EXISTING, 0, NULL); + if (volume == INVALID_HANDLE_VALUE) + return FALSE; + /* Refuse spanned volumes rather than choosing an arbitrary disk. */ + if (DeviceIoControl (volume, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, NULL, 0, + &extents, sizeof (extents), &returned, NULL) && returned >= sizeof (extents) && + extents.NumberOfDiskExtents == 1) + { + *number = extents.Extents[0].DiskNumber; + valid = TRUE; + } + CloseHandle (volume); + return valid; } char * sysinfo_backend_get_disk (void) { - DWORD drives = GetLogicalDrives (); - DWORD previous_mode = 0; + DWORD number, returned, previous_mode = 0; BOOL error_mode_changed; - guint i; - guint64 total = 0, available = 0; - GHashTable *seen = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL); - char *usage, *result; + DISK_GEOMETRY_EX geometry; + HANDLE disk; + char *path, *result = NULL; - /* Offline or empty local devices must not open a system error dialog. */ error_mode_changed = SetThreadErrorMode (GetThreadErrorMode () | SEM_FAILCRITICALERRORS, &previous_mode); - for (i = 0; i < 26; i++) + if (get_boot_disk_number (&number)) { - WCHAR root[] = L"A:\\"; - WCHAR volume[MAX_PATH]; - ULARGE_INTEGER caller_free, caller_total, total_free; - char *key; - - if (!(drives & (1UL << i))) - continue; - root[0] = (WCHAR) (L'A' + i); - /* Don't query mapped network shares or removable media. */ - if (GetDriveTypeW (root) != DRIVE_FIXED) - continue; - /* A stable volume GUID deduplicates aliases. SUBST paths without a - * volume GUID are deliberately skipped rather than double-counted. */ - if (!GetVolumeNameForVolumeMountPointW (root, volume, G_N_ELEMENTS (volume))) - continue; - key = wide_to_utf8 (volume); - if (!key) - continue; + /* The PhysicalDrive handle describes the complete disk, not a + * partition or filesystem. Request metadata access only. */ + path = g_strdup_printf ("\\\\.\\PhysicalDrive%lu", (unsigned long) number); + disk = CreateFileA (path, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, + NULL, OPEN_EXISTING, 0, NULL); + g_free (path); + if (disk != INVALID_HANDLE_VALUE) { - char *lower = g_ascii_strdown (key, -1); - g_free (key); - key = lower; + if (DeviceIoControl (disk, IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, NULL, 0, + &geometry, sizeof (geometry), &returned, NULL) && + returned >= FIELD_OFFSET (DISK_GEOMETRY_EX, Data) && geometry.DiskSize.QuadPart > 0) + result = g_format_size ((guint64) geometry.DiskSize.QuadPart); + CloseHandle (disk); } - if (g_hash_table_contains (seen, key) || - !GetDiskFreeSpaceExW (root, &caller_free, &caller_total, &total_free) || - !caller_total.QuadPart) - { - g_free (key); - continue; - } - if ((guint64) caller_total.QuadPart > G_MAXUINT64 - total) - { - g_free (key); - total = 0; - break; - } - g_hash_table_add (seen, key); - total += (guint64) caller_total.QuadPart; - available += MIN ((guint64) caller_free.QuadPart, (guint64) caller_total.QuadPart); - } - g_hash_table_unref (seen); - usage = format_usage (total, available); - if (!usage) - result = get_system_volume_usage (); - else - { - result = g_strdup_printf ("%s (fixed volumes)", usage); - g_free (usage); } if (error_mode_changed) SetThreadErrorMode (previous_mode, NULL);