Files
mcde/lib/McdeSys/linux.c
T
lotherkandClaude Opus 5.5 451aac7fe4 mcde: the battery in the bar
McdeSys gets mcde_sys_battery: all batteries as one, charging, mains,
minutes left.  NetBSD reads the envsys(4) dictionary of /dev/sysmon as
envstat(8) does (acpibat "present", "charge", "charging", "discharge
rate"; acpiacad "connected"), Linux /sys/class/power_supply (energy_* or
charge_*, status, Mains/USB online).  The sources are in
docs/reference/battery.txt.

dtbar shows a fourth icon, only when there is a battery: full, half, low
(red), charging; its menu says the charge, the power source and the time
left.  The status bar is 30 pixels an icon.

Measured: on the Linux host test_sysinfo says "battery 76% ac", as
/sys/class/power_supply/BAT0/capacity and AC/online do; the menu on Xvfb
(build/mcde-shots/battery-menu.png) says "Battery: 76 %", "Power Source:
Power Adapter".  The NetBSD backend compiles and runs in the build VM,
which has no battery (envstat: no drivers registered): only the
no-battery case is measured there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 07:01:18 +00:00

426 lines
12 KiB
C

/*
* linux.c -- MCDE: the Linux backend of McdeSys
*
* Copyright (c) 2026 The Makronix project. GNU LGPL 2.0 or later, as CDE.
*
* The system's own ways: /etc/os-release (os-release(5)) for the system,
* /proc/cpuinfo for the processor, /sys/class/dmi/id for the machine,
* /proc/self/mounts for the startup disk; power through systemctl(1) where
* the system has it, else shutdown(8); /sys/class/net and iw(8) for Wi-Fi,
* amixer(1) when no sound server runs, bluetoothctl(1) for Bluetooth,
* /sys/class/power_supply for the battery.
*/
#define _POSIX_C_SOURCE 200809L
#include <dirent.h>
#include <grp.h>
#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <Mcde/McdeSys.h>
#include "private.h"
const char *
mcde_sys_backend(void)
{
return "linux";
}
static int
FirstLine(const char *file, char *buf, size_t len)
{
FILE *fp = fopen(file, "r");
char *e;
if (fp == NULL)
return 0;
buf[0] = '\0';
if (fgets(buf, (int) len, fp) == NULL)
buf[0] = '\0';
fclose(fp);
if ((e = strchr(buf, '\n')) != NULL)
*e = '\0';
return buf[0] != '\0';
}
void
mcde_sys_info_backend(McdeSysInfo *info)
{
char vendor[64], product[64], dev[256], mnt[256], line[600];
FILE *fp;
/* the system's own name and version; common.c put the kernel's there,
* which is no version of a Linux system */
if (mcde_sys_file_value("/etc/os-release", "NAME=", info->system,
sizeof info->system)) {
info->version[0] = '\0';
if (!mcde_sys_file_value("/etc/os-release", "VERSION=",
info->version, sizeof info->version) &&
!mcde_sys_file_value("/etc/os-release", "VERSION_ID=",
info->version, sizeof info->version))
(void) mcde_sys_file_value("/etc/os-release",
"VERSION_CODENAME=", info->version,
sizeof info->version);
}
(void) mcde_sys_file_value("/proc/cpuinfo", "model name", info->cpu,
sizeof info->cpu);
if (FirstLine("/sys/class/dmi/id/sys_vendor", vendor, sizeof vendor) &&
FirstLine("/sys/class/dmi/id/product_name", product, sizeof product))
snprintf(info->model, sizeof info->model, "%s %s", vendor,
product);
if ((fp = fopen("/proc/self/mounts", "r")) != NULL) {
while (fgets(line, sizeof line, fp) != NULL)
if (sscanf(line, "%255s %255s", dev, mnt) == 2 &&
strcmp(mnt, "/") == 0)
snprintf(info->disk, sizeof info->disk, "%s", dev);
fclose(fp);
}
}
int
mcde_sys_power(McdeSysPower what)
{
static char *sd[3][4] = {
{ "/usr/bin/systemctl", "suspend", NULL, NULL },
{ "/usr/bin/systemctl", "reboot", NULL, NULL },
{ "/usr/bin/systemctl", "poweroff", NULL, NULL },
};
static char *classic[3][4] = {
{ "/usr/sbin/pm-suspend", NULL, NULL, NULL },
{ "/sbin/shutdown", "-r", "now", NULL },
{ "/sbin/shutdown", "-h", "now", NULL },
};
if ((int) what < 0 || (int) what > 2)
return mcde_sys_fail(MCDE_SYS_EINVAL, "Unknown power action.");
if (access(sd[what][0], X_OK) == 0)
return mcde_sys_run(sd[what]);
return mcde_sys_run(classic[what]);
}
/* ---- network: Wi-Fi is what has /sys/class/net/<if>/wireless; iw(8) names
* the network joined */
McdeSysNetKind
mcde_sys_if_kind(const char *name, char *ssid, size_t len)
{
static const char *const iw[] = { "/usr/sbin/iw", "/sbin/iw", NULL };
char path[256], out[1024], *s, *e;
const char *p;
ssid[0] = '\0';
snprintf(path, sizeof path, "/sys/class/net/%s/wireless", name);
if (access(path, F_OK) == 0) {
char *argv[] = { NULL, "dev", (char *) name, "link", NULL };
if ((p = mcde_sys_which(iw)) != NULL) {
argv[0] = (char *) p;
if (mcde_sys_capture(argv, out, sizeof out) == MCDE_SYS_OK &&
(s = strstr(out, "SSID: ")) != NULL) {
s += 6;
if ((e = strchr(s, '\n')) != NULL)
*e = '\0';
snprintf(ssid, len, "%s", s);
}
}
return MCDE_NET_WIFI;
}
snprintf(path, sizeof path, "/sys/class/net/%s/device", name);
return access(path, F_OK) == 0 ? MCDE_NET_WIRED : MCDE_NET_OTHER;
}
/* ---- sound without a sound server: ALSA's amixer(1), control Master */
static const char *const amixerPaths[] = { "/usr/bin/amixer", NULL };
int
mcde_sys_mixer_get(int *percent, int *muted)
{
const char *p = mcde_sys_which(amixerPaths);
char out[2048], *s;
char *argv[] = { NULL, "get", "Master", NULL };
if (p == NULL)
return mcde_sys_fail(MCDE_SYS_ENOTSUP, "No sound server and no "
"mixer.");
argv[0] = (char *) p;
/* "Mono: Playback 40 [63%] [-24.00dB] [on]" */
if (mcde_sys_capture(argv, out, sizeof out) != MCDE_SYS_OK ||
(s = strchr(out, '[')) == NULL)
return mcde_sys_fail(MCDE_SYS_EFAIL, "The mixer tells no volume.");
*percent = atoi(s + 1);
*muted = strstr(out, "[off]") != NULL;
return MCDE_SYS_OK;
}
int
mcde_sys_mixer_set(int percent)
{
const char *p = mcde_sys_which(amixerPaths);
char val[16];
char *argv[] = { NULL, "-q", "set", "Master", val, NULL };
if (p == NULL)
return mcde_sys_fail(MCDE_SYS_ENOTSUP, "No mixer.");
argv[0] = (char *) p;
snprintf(val, sizeof val, "%d%%", percent);
return mcde_sys_run(argv);
}
int
mcde_sys_mixer_mute(int muted)
{
const char *p = mcde_sys_which(amixerPaths);
char *argv[] = { NULL, "-q", "set", "Master", NULL, NULL };
if (p == NULL)
return mcde_sys_fail(MCDE_SYS_ENOTSUP, "No mixer.");
argv[0] = (char *) p;
argv[4] = muted ? "mute" : "unmute";
return mcde_sys_run(argv);
}
/* ---- Bluetooth: BlueZ's bluetoothctl(1); the controllers are in
* /sys/class/bluetooth */
static const char *const btctlPaths[] = { "/usr/bin/bluetoothctl", NULL };
int
mcde_sys_bluetooth(McdeSysBluetooth *bt)
{
const char *p = mcde_sys_which(btctlPaths);
char out[2048];
char *argv[] = { NULL, "show", NULL };
DIR *d;
struct dirent *de;
memset(bt, 0, sizeof *bt);
if ((d = opendir("/sys/class/bluetooth")) != NULL) {
while ((de = readdir(d)) != NULL)
if (strncmp(de->d_name, "hci", 3) == 0) {
snprintf(bt->name, sizeof bt->name, "%s",
de->d_name);
bt->present = 1;
break;
}
closedir(d);
}
if (!bt->present || p == NULL)
return MCDE_SYS_OK;
argv[0] = (char *) p;
if (mcde_sys_capture(argv, out, sizeof out) == MCDE_SYS_OK)
bt->on = strstr(out, "Powered: yes") != NULL;
return MCDE_SYS_OK;
}
int
mcde_sys_bluetooth_power(int on)
{
const char *p = mcde_sys_which(btctlPaths);
char *argv[] = { NULL, "power", NULL, NULL };
if (p == NULL)
return mcde_sys_fail(MCDE_SYS_ENOTSUP, "bluetoothctl is not there.");
argv[0] = (char *) p;
argv[2] = on ? "on" : "off";
return mcde_sys_run(argv);
}
/* ---- the battery: /sys/class/power_supply (the kernel's
* Documentation/ABI/testing/sysfs-class-power, docs/reference/battery.txt):
* a supply of type Battery has energy_now/energy_full in uWh and power_now in
* uW, or charge_now/charge_full in uAh and current_now in uA, and status
* Charging, Discharging, Full, Not charging; one of type Mains (or USB, a
* charger at the USB-C port) has online */
static long
Supply(const char *dir, const char *name)
{
char path[512], buf[64];
snprintf(path, sizeof path, "%s/%s", dir, name);
if (!FirstLine(path, buf, sizeof buf))
return -1;
return strtol(buf, NULL, 10);
}
int
mcde_sys_battery(McdeSysBattery *bat)
{
DIR *d;
struct dirent *de;
char dir[512], path[600], kind[32], status[32];
long long now = 0, full = 0, rate = 0;
long v, f, r;
int n = 0, capsum = 0, discharging = 0;
memset(bat, 0, sizeof *bat);
bat->minutes = -1;
if ((d = opendir("/sys/class/power_supply")) == NULL)
return MCDE_SYS_OK;
while ((de = readdir(d)) != NULL) {
if (de->d_name[0] == '.')
continue;
snprintf(dir, sizeof dir, "/sys/class/power_supply/%s",
de->d_name);
snprintf(path, sizeof path, "%s/type", dir);
if (!FirstLine(path, kind, sizeof kind))
continue;
if (strcmp(kind, "Mains") == 0 || strcmp(kind, "USB") == 0) {
if (Supply(dir, "online") == 1)
bat->ac = 1;
continue;
}
if (strcmp(kind, "Battery") != 0 || Supply(dir, "present") == 0)
continue;
/* a device's battery (a mouse) has scope Device: not ours */
snprintf(path, sizeof path, "%s/scope", dir);
if (FirstLine(path, status, sizeof status) &&
strcmp(status, "Device") == 0)
continue;
n++;
v = Supply(dir, "energy_now");
f = Supply(dir, "energy_full");
r = Supply(dir, "power_now");
if (v < 0 || f <= 0) {
v = Supply(dir, "charge_now");
f = Supply(dir, "charge_full");
r = Supply(dir, "current_now");
}
if (v >= 0 && f > 0) {
now += v;
full += f;
if (r > 0)
rate += r;
} else if ((v = Supply(dir, "capacity")) >= 0)
capsum += (int) v;
snprintf(path, sizeof path, "%s/status", dir);
if (FirstLine(path, status, sizeof status)) {
if (strcmp(status, "Charging") == 0)
bat->charging = 1;
else if (strcmp(status, "Discharging") == 0)
discharging = 1;
}
}
closedir(d);
bat->present = n > 0;
if (full > 0)
bat->percent = (int) ((now * 100 + full / 2) / full);
else if (n > 0)
bat->percent = capsum / n;
if (bat->percent > 100)
bat->percent = 100;
if (bat->charging)
bat->ac = 1;
if (discharging && rate > 0 && full > 0)
bat->minutes = (int) (now * 60 / rate);
return MCDE_SYS_OK;
}
/* ---- users: the group sudo administers (Debian; wheel where there is no
* sudo group); chpasswd(8) takes the password on its standard input,
* gpasswd(1) adds to and removes from a group */
const char *
mcde_sys_admin_group(void)
{
return getgrnam("sudo") != NULL ? "sudo" : "wheel";
}
const char *
mcde_sys_default_shell(void)
{
return "/bin/bash";
}
int
mcde_sys_user_set_password(const char *login, const char *password)
{
char *argv[] = { "/usr/sbin/chpasswd", NULL };
char input[512];
if (getpwnam(login) == NULL)
return mcde_sys_fail(MCDE_SYS_ENOENT, "There is no account "
"\"%s\".", login);
if (geteuid() != 0)
return mcde_sys_fail(MCDE_SYS_EPERM, "Only the administrator "
"can set a password: unlock first.");
if (strchr(password, '\n') != NULL || (size_t) snprintf(input,
sizeof input, "%s:%s\n", login, password) >= sizeof input)
return mcde_sys_fail(MCDE_SYS_EINVAL, "That password cannot be "
"used.");
return mcde_sys_run_input(argv, input);
}
int
mcde_sys_user_set_admin(const char *login, int admin)
{
char *argv[] = { "/usr/bin/gpasswd", NULL, (char *) login, NULL, NULL };
if (getpwnam(login) == NULL)
return mcde_sys_fail(MCDE_SYS_ENOENT, "There is no account "
"\"%s\".", login);
if (geteuid() != 0)
return mcde_sys_fail(MCDE_SYS_EPERM, "Only the administrator "
"can change that: unlock first.");
argv[1] = admin ? "-a" : "-d";
argv[3] = (char *) mcde_sys_admin_group();
return mcde_sys_run(argv);
}
/* ---- software update: the system's own package sources, through
* apt-get(8) where the system has it ("-s": only what it would do) */
static char aptget[] = "/usr/bin/apt-get";
int
mcde_sys_update_check(McdeSysUpdate *u)
{
static char out[65536];
char *argv[] = { aptget, "-s", "upgrade", NULL };
char *s;
McdeSysInfo i;
memset(u, 0, sizeof *u);
u->packages = -1;
(void) mcde_sys_info(&i);
snprintf(u->current, sizeof u->current, "%s %s", i.system, i.version);
if (access(aptget, X_OK) != 0) {
snprintf(u->note, sizeof u->note, "This system has no package "
"tool McdeSys knows.");
return MCDE_SYS_OK;
}
snprintf(u->source, sizeof u->source, "the package sources of apt");
if (mcde_sys_capture(argv, out, sizeof out) != MCDE_SYS_OK)
return mcde_sys_fail(MCDE_SYS_EFAIL, "apt-get cannot tell what "
"is new.");
/* "12 upgraded, 0 newly installed, 0 to remove and 3 not upgraded." */
for (s = out; (s = strstr(s, " upgraded,")) != NULL; s++) {
char *b = s;
while (b > out && b[-1] >= '0' && b[-1] <= '9')
b--;
if (b < s) {
u->packages = atoi(b);
break;
}
}
if (u->packages == 0)
snprintf(u->note, sizeof u->note, "The system is up to date.");
return MCDE_SYS_OK;
}
int
mcde_sys_update_apply(void)
{
char *update[] = { aptget, "-q", "update", NULL };
char *upgrade[] = { aptget, "-y", "-q", "upgrade", NULL };
int r;
if (geteuid() != 0)
return mcde_sys_fail(MCDE_SYS_EPERM, "Only the administrator can "
"update the computer: unlock first.");
if ((r = mcde_sys_run(update)) != MCDE_SYS_OK)
return r;
return mcde_sys_run(upgrade);
}