Files
mcde/lib/McdeSys/linux.c
T
lotherkandClaude Opus 5.5 dffeaf9b17 mcde: Wi-Fi in System Settings: the networks in reach, joining one
McdeSys implements mcde_sys_wifi_scan and mcde_sys_wifi_join.  NetBSD
does what sysinst does (src/usr.sbin/sysinst/net.c): a network block in
/etc/wpa_supplicant.conf -- a new file gets the example's ctrl_interface
for the wheel group, so wpa_cli answers users -- and wpa_supplicant,
wpa_supplicant_flags and dhcpcd in rc.conf, each line replaced or added;
then both are restarted.  Scanning asks wpa_cli scan_results, else
ifconfig -v IF list scan (root).  Linux uses nmcli.  The sources are in
docs/reference/wifi.txt.

The Network pane lists the networks of the first Wi-Fi card with signal
and lock, scanned once the pane is drawn.  Join... opens a terminal where
su asks for the administrator's password and dtsystemsettings -join-wifi
IF SSID-HEX asks for the network's password without echo: the name goes
as hexadecimal, the password on no command line of MCDE's (nmcli takes it
on its own on Linux; said in linux.c).

Measured on the Linux host: test_sysinfo finds 5 networks on wlp0s20f3
(read only); the pane lists them on Xvfb; -join-wifi as a user refuses
with "Only the administrator can join" and refuses a bad name.  Not
measured: joining (never on this host), NetBSD scanning and joining
(no Wi-Fi in the build VM).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 08:37:38 +00:00

532 lines
15 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, nmcli(1) for Wi-Fi.
*/
#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;
}
/* ---- Wi-Fi: NetworkManager's nmcli(1). "device wifi list" in terse form
* (-t: fields split by ':', a ':' inside escaped as "\:"), "device wifi
* connect SSID password P ifname IF" (a system-wide profile, DHCP, at every
* boot). The password is on nmcli's command line for the seconds it runs:
* nmcli has no other way for a new network (its passwd-file is for
* "connection up" of a profile that exists); only root runs this. */
static const char *const nmcliPaths[] = { "/usr/bin/nmcli", NULL };
/* the next field of a terse nmcli line, unescaped; *P moves past it */
static char *
TerseField(char **p)
{
char *start = *p, *r = *p, *w = *p;
if (start == NULL)
return NULL;
while (*r != '\0' && *r != ':') {
if (*r == '\\' && r[1] != '\0')
r++;
*w++ = *r++;
}
*p = *r == ':' ? r + 1 : NULL;
*w = '\0';
return start;
}
int
mcde_sys_wifi_scan(const char *ifname, McdeSysWifi *nets, size_t max)
{
static char out[16384];
const char *nm = mcde_sys_which(nmcliPaths);
char *argv[10], *line, *last = NULL;
int n = 0, i;
if (nm == NULL)
return mcde_sys_fail(MCDE_SYS_ENOTSUP, "NetworkManager (nmcli) "
"is not there.");
argv[0] = (char *) nm;
argv[1] = "-t";
argv[2] = "-f";
argv[3] = "SSID,SIGNAL,SECURITY";
argv[4] = "device";
argv[5] = "wifi";
argv[6] = "list";
argv[7] = "ifname";
argv[8] = (char *) ifname;
argv[9] = NULL;
if (mcde_sys_capture(argv, out, sizeof out) != MCDE_SYS_OK)
return -1;
for (line = strtok_r(out, "\n", &last); line != NULL &&
(size_t) n < max; line = strtok_r(NULL, "\n", &last)) {
char *p = line, *ssid = TerseField(&p), *sig = TerseField(&p);
char *sec = TerseField(&p);
if (ssid == NULL || ssid[0] == '\0' || sig == NULL)
continue;
for (i = 0; i < n; i++)
if (strcmp(nets[i].ssid, ssid) == 0)
break;
if (i < n) {
if (atoi(sig) > nets[i].signal)
nets[i].signal = atoi(sig);
continue;
}
snprintf(nets[n].ssid, sizeof nets[n].ssid, "%s", ssid);
nets[n].signal = atoi(sig);
nets[n].secured = sec != NULL && sec[0] != '\0' &&
strcmp(sec, "--") != 0;
n++;
}
return n;
}
int
mcde_sys_wifi_join(const char *ifname, const char *ssid,
const char *passphrase)
{
const char *nm = mcde_sys_which(nmcliPaths);
char *argv[12];
int n = 0;
if (geteuid() != 0)
return mcde_sys_fail(MCDE_SYS_EPERM, "Only the administrator "
"can join a Wi-Fi network.");
if (nm == NULL)
return mcde_sys_fail(MCDE_SYS_ENOTSUP, "NetworkManager (nmcli) "
"is not there.");
if (ifname == NULL || ssid == NULL || ssid[0] == '\0' ||
strlen(ssid) > 32)
return mcde_sys_fail(MCDE_SYS_EINVAL, "The network name cannot "
"be used.");
argv[n++] = (char *) nm;
argv[n++] = "device";
argv[n++] = "wifi";
argv[n++] = "connect";
argv[n++] = (char *) ssid;
if (passphrase != NULL) {
argv[n++] = "password";
argv[n++] = (char *) passphrase;
}
argv[n++] = "ifname";
argv[n++] = (char *) ifname;
argv[n] = NULL;
return mcde_sys_run(argv);
}
/* ---- 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);
}