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/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/meson.build b/plugins/sysinfo/meson.build index c95ebc01..6f9d0abb 100644 --- a/plugins/sysinfo/meson.build +++ b/plugins/sysinfo/meson.build @@ -6,50 +6,67 @@ 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' + 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', 'unix/storage.c', 'unix/memory.c'] + +elif system == 'freebsd' or system == 'gnu' or system.startswith('gnu/') + 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_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 + +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' + 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/osx/backend.m b/plugins/sysinfo/osx/backend.m index 5929ed02..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 * @@ -99,10 +92,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(); @@ -210,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; } @@ -228,7 +235,9 @@ get_gpu(void) } CFRelease(serviceDictionary); + IOObjectRelease (serviceObject); } + IOObjectRelease (entry_iterator); if (gpu_list->len == 0) { @@ -250,13 +259,19 @@ get_gpu(void) char * sysinfo_backend_get_gpu(void) { - static char *gpu_str = NULL; if (!gpu_str) gpu_str = get_gpu(); 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) { 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 21c50bbb..aa2d6690 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 /SYSINFO REFRESH - clear cached hardware information\n"; typedef struct { @@ -70,9 +70,9 @@ static hwinfo hwinfos[] = { {"memory", "Memory", sysinfo_backend_get_memory}, {"storage", "Storage", sysinfo_backend_get_disk, TRUE}, {"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 +115,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) @@ -176,19 +192,24 @@ 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 (key + 5, hwinfos[i].name)) + if (!g_ascii_strcasecmp (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; } } @@ -220,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); @@ -248,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/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 new file mode 100644 index 00000000..304777b2 --- /dev/null +++ b/plugins/sysinfo/unix/modern-backend.c @@ -0,0 +1,1058 @@ +/* + * 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" +#include "memory.h" + +#define SYSINFO_SEP " \xC2\xB7 " + +typedef struct +{ + char *os; + char *cpu; + char *gpu; + char *chipset; + char *sound; + GHashTable *pci_names; +} LinuxStaticSnapshot; + +/* Sysinfo callbacks and plugin teardown run on the client thread. */ +static LinuxStaticSnapshot snapshot; +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); +#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); +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); +#define format_usage sysinfo_format_usage +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 || *end != '\0' || parsed > G_MAXUINT || contents[0] == '-') + { + g_free (contents); + return FALSE; + } + + *value = (guint) parsed; + g_free (contents); + return TRUE; +} + +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 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) && GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_64 + 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"); +} + +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; + 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); + 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 || package_id[0] == '-' || core_id[0] == '-') + { + g_free (package_id); + g_free (core_id); + /* 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); + 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 && 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; +} + + +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); + + dir = g_dir_open ("/sys/bus/pci/devices", 0, NULL); +#ifdef HAVE_LIBPCI + /* Only initialize the explicit sysfs method when PCI is visible. Never + * use autodetection or ask libpci to probe/configure a device. */ + if (dir) + { + int method = pci_lookup_method ("linux-sysfs"); + if (method >= 0) + { + pacc = pci_alloc (); + pacc->method = method; + pci_init (pacc); + } + } +#endif + + 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 || class_subclass == 0x0601) + { + /* Include host bridges and ISA/LPC bridges. */ + 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 (!os_initialized) + { + snapshot.os = build_os_string (); + os_initialized = TRUE; + } +} + +static void +ensure_cpu_snapshot (void) +{ + if (!cpu_initialized) + { + snapshot.cpu = build_cpu_string (); + cpu_initialized = TRUE; + } +} + +static void +ensure_pci_snapshot (void) +{ + if (!pci_initialized) + { + scan_pci_devices (); + pci_initialized = TRUE; + } +} + +static void +ensure_sound_snapshot (void) +{ + if (!sound_initialized) + { + snapshot.sound = build_sound_string (); + sound_initialized = TRUE; + } +} + +char * +sysinfo_backend_get_os (void) +{ + ensure_os_snapshot (); + 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); +} + +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) +{ + char *contents = NULL; + char *memory; + + if (!g_file_get_contents ("/proc/meminfo", &contents, NULL, NULL)) + return NULL; + memory = sysinfo_linux_format_meminfo (contents); + g_free (contents); + return memory; +} + +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); + /* 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; + } + + 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/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; } diff --git a/plugins/sysinfo/unix/storage.c b/plugins/sysinfo/unix/storage.c new file mode 100644 index 00000000..d6f0420b --- /dev/null +++ b/plugins/sysinfo/unix/storage.c @@ -0,0 +1,232 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* Whole capacity of the disk backing the boot filesystem. */ +#define _XOPEN_SOURCE 700 +#include +#include +#include +#include +#include +#include +#include "../sysinfo-backend.h" +#include "storage.h" + +static gboolean +read_capacity (const char *entry, guint64 *capacity) +{ + char *path = g_build_filename (entry, "size", NULL); + char *contents = NULL; + char *end; + guint64 sectors; + gboolean valid = FALSE; + + if (g_file_get_contents (path, &contents, NULL, NULL)) + { + g_strstrip (contents); + if (g_ascii_isdigit (contents[0])) + { + 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; + } + } + } + g_free (contents); + g_free (path); + return valid; +} + +static gboolean +has_entry (const char *entry, const char *name) +{ + 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 +valid_device_number (const char *id) +{ + const char *p = id; + if (!g_ascii_isdigit (*p)) + return FALSE; + while (g_ascii_isdigit (*p)) + p++; + if (*p++ != ':' || !g_ascii_isdigit (*p)) + return FALSE; + while (g_ascii_isdigit (*p)) + p++; + return *p == '\0'; +} + +static char * +resolve_mount_device (const char *sysfs, const char *id, const char *source) +{ + char *entry = NULL; + struct stat st; + + /* 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)) + { + entry = g_build_filename (sysfs, "dev", "block", id, NULL); + if (g_file_test (entry, G_FILE_TEST_EXISTS)) + return entry; + g_free (entry); + } + if (g_str_has_prefix (source, "/dev/") && stat (source, &st) == 0 && S_ISBLK (st.st_mode)) + { + char *number = g_strdup_printf ("%u:%u", (unsigned int) major (st.st_rdev), + (unsigned int) minor (st.st_rdev)); + entry = g_build_filename (sysfs, "dev", "block", number, NULL); + g_free (number); + return entry; + } + /* 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; +} + +char * +sysinfo_linux_boot_disk (const char *sysfs, const char *mountinfo) +{ + 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) +{ + char *mountinfo = NULL; + char *result; + + /* 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; + 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 new file mode 100644 index 00000000..684afca1 --- /dev/null +++ b/plugins/sysinfo/unix/storage.h @@ -0,0 +1,10 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#ifndef SYSINFO_LINUX_STORAGE_H +#define SYSINFO_LINUX_STORAGE_H + +#include + +/* 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 diff --git a/plugins/sysinfo/win32/backend.c b/plugins/sysinfo/win32/backend.c index 19d60da5..267af9c2 100644 --- a/plugins/sysinfo/win32/backend.c +++ b/plugins/sysinfo/win32/backend.c @@ -1,28 +1,35 @@ -/* 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 +#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 +37,502 @@ #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; + +/* Sysinfo callbacks and plugin teardown run on the client thread. */ +static WinStaticSnapshot snapshot; +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; } -char * -sysinfo_backend_get_network (void) +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); +#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 * +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) + { + 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); + } + g_free (name); + return result; +} + +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) + { + /* A failed enumeration is not another adapter. Retrying every + * index can freeze the client indefinitely after a device error. */ + break; + } + + 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 (!os_initialized) + { + snapshot.os = build_os_string (); + os_initialized = TRUE; + } +} + +static void +ensure_cpu_snapshot (void) +{ + if (!cpu_initialized) + { + snapshot.cpu = build_cpu_string (); + cpu_initialized = TRUE; + } +} + +static void +ensure_gpu_snapshot (void) +{ + if (!gpu_initialized) + { + snapshot.gpu = build_gpu_string (); + gpu_initialized = TRUE; + } +} + +static void +ensure_sound_snapshot (void) +{ + if (!sound_initialized) + { + snapshot.sound = build_sound_string (); + sound_initialized = TRUE; + } +} + +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 (); + 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); } 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 +542,207 @@ 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) +static gboolean +get_boot_disk_number (DWORD *number) { -#if defined(USE_GTK_FRONTEND) - return "GTK3"; -#else - return NULL; -#endif + WCHAR windows_dir[MAX_PATH]; + WCHAR volume_path[MAX_PATH]; + WCHAR volume_name[MAX_PATH]; + UINT length; + 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) || + !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 number, returned, previous_mode = 0; + BOOL error_mode_changed; + DISK_GEOMETRY_EX geometry; + HANDLE disk; + char *path, *result = NULL; + + error_mode_changed = SetThreadErrorMode (GetThreadErrorMode () | SEM_FAILCRITICALERRORS, &previous_mode); + if (get_boot_disk_number (&number)) + { + /* 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) + { + 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 (error_mode_changed) + SetThreadErrorMode (previous_mode, NULL); + 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 }