Merge pull request #381 from ZoiteChat/sysinfo-update

bring sysinfo into 2026
This commit is contained in:
deepend-tildeclub authored and GitHub committed 2026-12-04 19:41:24 -06:00
commit b7b73ecf28
15 files changed
+2335 -152

No files matched your search

+1 -1
View File
@@ -67,7 +67,7 @@ option('with-python', type: 'string', value: 'python3',
description: 'Python scripting plugin. value is pkg-config name to use or "false"' description: 'Python scripting plugin. value is pkg-config name to use or "false"'
) )
option('with-sysinfo', type: 'boolean', 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', option('with-upd', type: 'boolean',
description: 'Update plugin, Windows only' description: 'Update plugin, Windows only'
+78
View File
@@ -88,3 +88,81 @@ sysinfo_format_disk (guint64 total, guint64 free)
g_free (used_fmt); g_free (used_fmt);
return ret; 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));
}
+3
View File
@@ -24,5 +24,8 @@
char *sysinfo_format_uptime(gint64 uptime); char *sysinfo_format_uptime(gint64 uptime);
char *sysinfo_format_memory(guint64 totalmem, guint64 freemem); char *sysinfo_format_memory(guint64 totalmem, guint64 freemem);
char *sysinfo_format_disk(guint64 total, guint64 free); 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 #endif
+51 -34
View File
@@ -6,50 +6,67 @@ sysinfo_sources = [
sysinfo_deps = [ sysinfo_deps = [
libgio_dep, libgio_dep,
zoitechat_plugin_dep, zoitechat_plugin_dep,
common_sysinfo_deps,
] ]
sysinfo_includes = [] sysinfo_includes = []
sysinfo_cargs = ['-DHAVE_CONFIG_H'] sysinfo_cargs = ['-DHAVE_CONFIG_H']
system = host_machine.system() system = host_machine.system()
if system == 'linux' or system == 'gnu' or system.startswith('gnu/') or system == 'darwin' or system == 'freebsd' if system == 'linux'
sysinfo_includes += 'shared' if get_option('gtk-frontend')
sysinfo_sources += [ sysinfo_deps += dependency('gtk+-3.0', version: '>= 3.22')
'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'
endif 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 += [ sysinfo_sources += [
'win32/backend.c', 'shared/df.c',
'../../src/common/sysinfo/win32/backend.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 else
error('sysinfo: Unknown system?') error('sysinfo: Unknown system?')
endif endif
+30 -15
View File
@@ -23,6 +23,8 @@
*/ */
#import <Cocoa/Cocoa.h> #import <Cocoa/Cocoa.h>
#include <IOKit/IOKitLib.h>
#include <string.h>
#include <sys/sysctl.h> #include <sys/sysctl.h>
#include <mach/mach.h> #include <mach/mach.h>
@@ -38,6 +40,7 @@
#include "format.h" #include "format.h"
#include "df.h" #include "df.h"
#include "sysinfo-backend.h"
static char * static char *
get_os (void) get_os (void)
@@ -48,10 +51,7 @@ get_os (void)
return NULL; return NULL;
NSString *version = [systemversion objectForKey:@"ProductUserVisibleVersion"]; NSString *version = [systemversion objectForKey:@"ProductUserVisibleVersion"];
if (!version) if (!version)
{
[build release];
return NULL; return NULL;
}
NSDictionary *profiler = [NSDictionary dictionaryWithContentsOfFile:[@"~/Library/Preferences/com.apple.SystemProfiler.plist" stringByExpandingTildeInPath]]; NSDictionary *profiler = [NSDictionary dictionaryWithContentsOfFile:[@"~/Library/Preferences/com.apple.SystemProfiler.plist" stringByExpandingTildeInPath]];
NSDictionary *names = [profiler objectForKey:@"OS Names"]; NSDictionary *names = [profiler objectForKey:@"OS Names"];
@@ -65,18 +65,11 @@ get_os (void)
break; break;
} }
} }
[build release]; /* Dictionary values are borrowed; releasing them would over-release. */
if (!os_name) if (!os_name)
{
[version release];
return NULL; return NULL;
}
char *ret = g_strdup_printf ("%s %s", [os_name UTF8String], [version UTF8String]); return g_strdup_printf ("%s %s", [os_name UTF8String], [version UTF8String]);
[version release];
return ret;
} }
static char * 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); return g_strdup_printf ("OS X %ld.%ld.%ld", version.majorVersion, version.minorVersion, version.patchVersion);
#endif #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 * char *
sysinfo_backend_get_os(void) sysinfo_backend_get_os(void)
{ {
static char *os_str = NULL;
if (!os_str) if (!os_str)
{ {
os_str = get_os(); os_str = get_os();
@@ -210,9 +212,14 @@ get_gpu(void)
} }
const void *class = CFDictionaryGetValue(serviceDictionary, @"class-code"); 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); CFRelease(serviceDictionary);
IOObjectRelease (serviceObject);
continue; continue;
} }
@@ -228,7 +235,9 @@ get_gpu(void)
} }
CFRelease(serviceDictionary); CFRelease(serviceDictionary);
IOObjectRelease (serviceObject);
} }
IOObjectRelease (entry_iterator);
if (gpu_list->len == 0) if (gpu_list->len == 0)
{ {
@@ -250,13 +259,19 @@ get_gpu(void)
char * char *
sysinfo_backend_get_gpu(void) sysinfo_backend_get_gpu(void)
{ {
static char *gpu_str = NULL;
if (!gpu_str) if (!gpu_str)
gpu_str = get_gpu(); gpu_str = get_gpu();
return g_strdup (gpu_str); return g_strdup (gpu_str);
} }
char *
sysinfo_backend_get_chipset (void)
{
/* No chipset detector exists in the legacy macOS backend. */
return NULL;
}
char * char *
sysinfo_backend_get_sound(void) sysinfo_backend_get_sound(void)
{ {
+2
View File
@@ -21,6 +21,8 @@
#ifndef SYSINFO_BACKEND_H #ifndef SYSINFO_BACKEND_H
#define 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_os(void);
char *sysinfo_backend_get_disk(void); char *sysinfo_backend_get_disk(void);
char *sysinfo_backend_get_memory(void); char *sysinfo_backend_get_memory(void);
+40 -13
View File
@@ -40,8 +40,8 @@ static zoitechat_plugin *ph;
static char name[] = "Sysinfo"; static char name[] = "Sysinfo";
static char desc[] = "Display info about your hardware and OS"; static char desc[] = "Display info about your hardware and OS";
static char version[] = "1.0"; static char version[] = "2.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 <variable>\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 <variable>\n /SYSINFO REFRESH - clear cached hardware information\n";
typedef struct typedef struct
{ {
@@ -70,9 +70,9 @@ static hwinfo hwinfos[] = {
{"memory", "Memory", sysinfo_backend_get_memory}, {"memory", "Memory", sysinfo_backend_get_memory},
{"storage", "Storage", sysinfo_backend_get_disk, TRUE}, {"storage", "Storage", sysinfo_backend_get_disk, TRUE},
{"gpu", "GPU", sysinfo_backend_get_gpu}, {"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}, {"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}, {"uptime", "Uptime", sysinfo_backend_get_uptime},
{NULL, NULL}, {NULL, NULL},
}; };
@@ -115,14 +115,30 @@ print_summary (gboolean announce)
g_free (output); 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 static void
print_info (char *info, gboolean announce) print_info (char *info, gboolean announce)
{ {
const char *normalized = normalize_info_name (info);
int i; int i;
for (i = 0; hwinfos[i].name != NULL; 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(); char *str = hwinfos[i].callback();
if (str) if (str)
@@ -176,19 +192,24 @@ sysinfo_set_pref (char *key, char *value)
return; 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; 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; int i;
for (i = 0; hwinfos[i].name != NULL; 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; return;
} }
} }
@@ -220,10 +241,15 @@ sysinfo_cb (char *word[], char *word_eol[], void *userdata)
announce = FALSE; announce = FALSE;
cmd = word[2+offset]; cmd = word[2+offset];
if (!g_ascii_strcasecmp ("SET", cmd)) if (!cmd || !cmd[0])
sysinfo_set_pref (word[3+offset], word_eol[4+offset]);
else if (!cmd || !cmd[0])
print_summary (announce); 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 else
print_info (cmd, announce); print_info (cmd, announce);
@@ -248,6 +274,7 @@ zoitechat_plugin_init (zoitechat_plugin *plugin_handle, char **plugin_name, char
int int
zoitechat_plugin_deinit (void) zoitechat_plugin_deinit (void)
{ {
sysinfo_backend_reset_cache ();
zoitechat_command (ph, "MENU DEL \"Window/Send System Info\""); zoitechat_command (ph, "MENU DEL \"Window/Send System Info\"");
zoitechat_command (ph, "MENU DEL \"Window/Display System Info\""); zoitechat_command (ph, "MENU DEL \"Window/Display System Info\"");
zoitechat_printf (ph, _("%s plugin unloaded\n"), name); zoitechat_printf (ph, _("%s plugin unloaded\n"), name);
+6
View File
@@ -175,6 +175,12 @@ char *sysinfo_backend_get_uptime(void)
return sysinfo_format_uptime (uptime); 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 *sysinfo_backend_get_network(void)
{ {
char ethernet_card[bsize]; char ethernet_card[bsize];
+104
View File
@@ -0,0 +1,104 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
#include <errno.h>
#include <string.h>
#include <glib.h>
#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;
}
+8
View File
@@ -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
File diff suppressed because it is too large. Load diff
+20 -7
View File
@@ -51,12 +51,18 @@ static struct device *scan_device(struct pci_dev *p)
d = g_new0 (struct device, 1); d = g_new0 (struct device, 1);
d->dev = p; d->dev = p;
if (!pci_read_block(p, 0, d->config, how_much)) 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) 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... */ /* 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)) if (!pci_read_block(p, 64, d->config+64, 64))
exit(1); {
g_free (d);
return NULL;
}
how_much = 128; how_much = 128;
} }
d->config_cnt = how_much; d->config_cnt = how_much;
@@ -116,6 +122,14 @@ int pci_find_by_class(u16 *class, char *vendor, char *device)
} }
pci_cleanup(pacc); 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; return nomatch;
} }
@@ -142,8 +156,7 @@ void pci_find_fullname(char *fullname, char *vendor, char *device)
position = strstr(buffer, vendor); position = strstr(buffer, vendor);
position += 6; position += 6;
g_strlcpy(vendorname, position, sizeof (vendorname)); g_strlcpy(vendorname, position, sizeof (vendorname));
position = strstr(vendorname, "\n"); g_strchomp (vendorname);
*(position) = '\0';
break; break;
} }
} }
@@ -155,9 +168,9 @@ void pci_find_fullname(char *fullname, char *vendor, char *device)
position += 6; position += 6;
g_strlcpy(devicename, position, sizeof (devicename)); g_strlcpy(devicename, position, sizeof (devicename));
position = strstr(devicename, " ("); position = strstr(devicename, " (");
if (position == NULL) if (position)
position = strstr(devicename, "\n"); *position = '\0';
*(position) = '\0'; g_strchomp (devicename);
cardfound = 1; cardfound = 1;
break; break;
} }
+232
View File
@@ -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 <errno.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/sysmacros.h>
#include <glib.h>
#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/<name>, 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;
}
+10
View File
@@ -0,0 +1,10 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
#ifndef SYSINFO_LINUX_STORAGE_H
#define SYSINFO_LINUX_STORAGE_H
#include <glib.h>
/* 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
+692 -82
View File
@@ -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 * Avoids WMI in the plugin hot path and uses native Win32/DXGI APIs.
* 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.
*/ */
#include <stdio.h> #ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0601
#elif _WIN32_WINNT < 0x0601
#undef _WIN32_WINNT
#define _WIN32_WINNT 0x0601
#endif
#include <winsock2.h>
#include <windows.h> #include <windows.h>
#include <wbemidl.h> #include <winternl.h>
#include <dxgi.h>
#include <iphlpapi.h>
#include <ipifcons.h>
#include <mmsystem.h>
#include <winioctl.h>
#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 <stdint.h>
#include <stdio.h>
#include <string.h>
#include <glib.h> #include <glib.h>
@@ -30,63 +37,502 @@
#include "config.h" #include "config.h"
#endif #endif
#include "../../../src/common/sysinfo/sysinfo.h"
#include "../format.h" #include "../format.h"
#include "../sysinfo-backend.h"
static char *get_memory_info (void); #define SYSINFO_SEP " \xC2\xB7 "
char * typedef struct
sysinfo_backend_get_sound (void)
{ {
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 * static char *wide_to_utf8 (const WCHAR *value);
sysinfo_backend_get_network (void) 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; if (!value || value[0] == L'\0')
}
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)
{ {
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 * char *
sysinfo_backend_get_cpu (void) sysinfo_backend_get_cpu (void)
{ {
return sysinfo_get_cpu (); static const WCHAR cpu_key[] = L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0";
} DWORD mhz = 0;
ensure_cpu_snapshot ();
char * if (!snapshot.cpu)
sysinfo_backend_get_memory (void) return NULL;
{ /* The registry's reported MHz is not a guaranteed live or turbo clock. */
/* Memory information is always loaded dynamically since it includes the current amount of free memory */ if (read_registry_dword (HKEY_LOCAL_MACHINE, cpu_key, L"~MHz", &mhz) && mhz && mhz <= 100000)
return get_memory_info (); {
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 * char *
sysinfo_backend_get_gpu (void) 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 * char *
@@ -96,43 +542,207 @@ sysinfo_backend_get_chipset (void)
} }
char * char *
sysinfo_backend_get_os (void) sysinfo_backend_get_memory (void)
{ {
return sysinfo_get_os (); MEMORYSTATUSEX memory;
}
static char *get_memory_info (void) ZeroMemory (&memory, sizeof (memory));
{ memory.dwLength = sizeof (memory);
MEMORYSTATUSEX meminfo = { 0 }; if (!GlobalMemoryStatusEx (&memory))
meminfo.dwLength = sizeof (meminfo);
if (!GlobalMemoryStatusEx (&meminfo))
{ {
return NULL; 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) WCHAR windows_dir[MAX_PATH];
return "GTK3"; WCHAR volume_path[MAX_PATH];
#else WCHAR volume_name[MAX_PATH];
return NULL; UINT length;
#endif 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 * char *
sysinfo_backend_get_ui (void) sysinfo_backend_get_ui (void)
{ {
const char *toolkit = sysinfo_detect_toolkit(); #if defined(USE_GTK_FRONTEND)
return g_strdup ("Windows / GTK3");
/* On Windows we don't have X11/Wayland. Keep it simple. */ #else
if (toolkit)
{
return g_strdup_printf ("Windows / %s", toolkit);
}
return g_strdup ("Windows"); return g_strdup ("Windows");
#endif
} }