Files
mcde/lib/McdeSys/linux.c
T
lotherk 7e5ae467cd MCDE dtfile: Get Info, the window with the sections (t0101)
File > Get Info (Cmd+I) opens the reference's Info window instead of the
CDE permissions dialog: the name, its size and date, then sections that
open and close with a click -- General (kind, size, on disk, where,
created, modified, locked), Permissions (owner, group, everyone: read and
write, read only, none), Comment (an extended attribute) and Preview (the
miniature of McdeThumb).  One window per file manager: Cmd+I again replaces
what it shows and the sections keep their state.  The old "Change
Permissions..." item stays in the menu, without the key.

Two new McdeSys calls, because a program does not touch the file system's
specialties itself (ext/src/mcde/AGENTS.md): mcde_sys_file_comment_get/set
(user.mcde.comment on Linux, EXTATTR_NAMESPACE_USER "mcde.comment" on
NetBSD, MCDE_SYS_ENOTSUP where there are none) and
mcde_sys_file_locked_get/set (FS_IMMUTABLE_FL on Linux, chflags(2)
UF_IMMUTABLE on NetBSD; a normal user may not set it on Linux, the box then
stays as it was).  "Created" says "not known" where POSIX has no birth time
(Linux); NetBSD shows st_birthtime.

Measured under Xvfb with xdotool: Cmd+I on Bild.png opens the window with
General/Permissions/Comment/Preview (docs/screenshots/leopard/
finder-get-info-mcde.png, the comment read back from the attribute); the
Owner menu to "Read only" on a 0664 file leaves -r--rw-r-- (chmod 0464);
the Comment field saved "Wichtig" and
python3 -c "os.getxattr(..., 'user.mcde.comment')" returns b'Wichtig';
clicking "General" collapses it to ">" and the sections below move up.

Open: "Open with" and the label colours of the reference are not there yet
(the action list and a user.dt mapping are a task of their own); the
program's icon is missing in the development session (t0194, no data
types), the sections are ASCII arrows, and dtwm places the window at the
corner (the picture moves it with xdotool).
2026-11-14 07:21:00 +00:00

1173 lines
32 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 <errno.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/xattr.h>
#include <linux/fs.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.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 };
/* ALSA's player when no sound server runs */
const char *
mcde_sys_player(void)
{
static const char *const paths[] = { "/usr/bin/aplay", "/bin/aplay",
NULL };
return mcde_sys_which(paths);
}
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);
}
/* a Macintosh keyboard: an input device of vendor 0x05ac (Apple) with a
* keyboard handler, in /proc/bus/input/devices */
int
mcde_sys_keyboard_is_mac(void)
{
FILE *f = fopen("/proc/bus/input/devices", "r");
char line[512];
int apple = 0, found = 0;
if (f == NULL)
return 0;
while (fgets(line, sizeof line, f) != NULL) {
if (line[0] == 'I' && line[1] == ':')
apple = strstr(line, "Vendor=05ac") != NULL;
else if (apple && line[0] == 'H' && line[1] == ':' &&
strstr(line, "kbd") != NULL)
found = 1;
}
fclose(f);
return found;
}
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);
}
/* ---- the settings of an interface: NetworkManager keeps them in the
* connection profile of the device ("nmcli -t -g ... connection show"),
* what the device has now comes from the kernel (/proc/net/route,
* /sys/class/net). docs/reference/netconfig.txt in the Makronix tree. */
/* "\:" and "\\" of nmcli's terse output back to ':' and '\' */
static void
NmUnescape(char *s)
{
char *r = s, *w = s;
while (*r != '\0') {
if (*r == '\\' && r[1] != '\0')
r++;
*w++ = *r++;
}
*w = '\0';
}
/* the next line of BUF (cut there); *P moves past it, NULL at the end */
static char *
NextLine(char **p)
{
char *start = *p, *nl;
if (start == NULL)
return NULL;
if ((nl = strchr(start, '\n')) != NULL) {
*nl = '\0';
*p = nl + 1;
} else
*p = NULL;
return start;
}
/* the connection profile NetworkManager uses for IFNAME into NAME */
static int
NmConnection(const char *ifname, char *name, size_t len)
{
const char *nm = mcde_sys_which(nmcliPaths);
char out[512], *p = out, *line;
char *argv[] = { NULL, "-t", "-g", "GENERAL.CONNECTION", "device",
"show", (char *) ifname, NULL };
if (nm == NULL)
return mcde_sys_fail(MCDE_SYS_ENOTSUP, "NetworkManager (nmcli) "
"is not installed: the settings cannot be changed here.");
argv[0] = (char *) nm;
if (mcde_sys_capture(argv, out, sizeof out) != MCDE_SYS_OK ||
(line = NextLine(&p)) == NULL || line[0] == '\0')
return mcde_sys_fail(MCDE_SYS_ENOENT, "NetworkManager has no "
"settings for %s.", ifname);
NmUnescape(line);
snprintf(name, len, "%s", line);
return MCDE_SYS_OK;
}
/* the items of a list as nmcli prints it (',' between them) into DST */
static int
Items(char *list, char (*dst)[48], int max)
{
char *item, *last = NULL;
int n = 0;
for (item = strtok_r(list, ",", &last); item != NULL && n < max;
item = strtok_r(NULL, ",", &last)) {
while (*item == ' ')
item++;
if (*item != '\0')
snprintf(dst[n++], sizeof dst[0], "%s", item);
}
return n;
}
static void
SysfsLine(const char *ifname, const char *what, char *buf, size_t len)
{
char path[256];
snprintf(path, sizeof path, "/sys/class/net/%s/%s", ifname, what);
buf[0] = '\0';
(void) mcde_sys_file_value(path, "", buf, len);
}
int
mcde_sys_net_config_backend(const char *ifname, McdeSysNetConfig *c)
{
const char *nm = mcde_sys_which(nmcliPaths);
char conn[256], out[4096], *p = out, *f[8], speed[32], duplex[32];
char line[256];
FILE *fp;
int i, r;
char *argv[] = { NULL, "-t", "-g", "ipv4.method,ipv4.addresses,"
"ipv4.gateway,ipv4.dns,ipv4.dns-search,ipv4.dhcp-client-id,"
"ipv6.method,ipv6.addresses", "connection", "show", conn, NULL };
SysfsLine(ifname, "address", c->mac, sizeof c->mac);
SysfsLine(ifname, "speed", speed, sizeof speed);
SysfsLine(ifname, "duplex", duplex, sizeof duplex);
if (atoi(speed) > 0)
snprintf(c->media, sizeof c->media, "%d Mbit/s%s%s",
atoi(speed), duplex[0] != '\0' ? ", " : "", duplex);
/* /proc/net/route: Iface Destination Gateway ..., hexadecimal in
* the kernel's byte order; the default route has destination 0 */
if ((fp = fopen("/proc/net/route", "r")) != NULL) {
while (fgets(line, sizeof line, fp) != NULL) {
char name[64];
unsigned int dst, gw;
struct in_addr a;
if (sscanf(line, "%63s %x %x", name, &dst, &gw) == 3 &&
strcmp(name, ifname) == 0 && dst == 0 && gw != 0) {
a.s_addr = gw;
inet_ntop(AF_INET, &a, c->cur_router,
sizeof c->cur_router);
break;
}
}
fclose(fp);
}
if ((r = NmConnection(ifname, conn, sizeof conn)) != MCDE_SYS_OK)
return r;
argv[0] = (char *) nm;
if (mcde_sys_capture(argv, out, sizeof out) != MCDE_SYS_OK)
return mcde_sys_fail(MCDE_SYS_EFAIL, "nmcli does not tell the "
"settings of \"%s\".", conn);
for (i = 0; i < 8; i++) {
if ((f[i] = NextLine(&p)) == NULL)
f[i] = "";
NmUnescape(f[i]);
}
/* 0 method, 1 addresses, 2 gateway, 3 dns, 4 search, 5 client id,
* 6 ipv6 method, 7 ipv6 addresses */
if (strcmp(f[0], "manual") == 0)
c->ipv4 = MCDE_IPV4_MANUAL;
else if (strcmp(f[0], "disabled") == 0)
c->ipv4 = MCDE_IPV4_OFF;
else
c->ipv4 = f[1][0] != '\0' ? MCDE_IPV4_DHCP_MANUAL :
MCDE_IPV4_DHCP;
if (f[1][0] != '\0') {
char *slash, *comma;
if ((comma = strchr(f[1], ',')) != NULL)
*comma = '\0';
if ((slash = strchr(f[1], '/')) != NULL) {
*slash = '\0';
mcde_sys_net_mask(atoi(slash + 1), c->netmask,
sizeof c->netmask);
}
snprintf(c->address, sizeof c->address, "%s", f[1]);
}
snprintf(c->router, sizeof c->router, "%s", f[2]);
c->ndns = Items(f[3], c->dns, MCDE_NET_DNS_MAX);
{
char *item, *last = NULL;
for (item = strtok_r(f[4], ",", &last); item != NULL &&
c->nsearch < MCDE_NET_DNS_MAX;
item = strtok_r(NULL, ",", &last))
snprintf(c->search[c->nsearch++], sizeof c->search[0],
"%s", item);
}
snprintf(c->clientid, sizeof c->clientid, "%s", f[5]);
c->ipv6 = strcmp(f[6], "manual") == 0 ? MCDE_IPV6_MANUAL :
strcmp(f[6], "disabled") == 0 ? MCDE_IPV6_OFF : MCDE_IPV6_AUTO;
if (f[7][0] != '\0') {
char *slash, *comma;
if ((comma = strchr(f[7], ',')) != NULL)
*comma = '\0';
if ((slash = strchr(f[7], '/')) != NULL) {
*slash = '\0';
c->prefix6 = atoi(slash + 1);
}
snprintf(c->address6, sizeof c->address6, "%s", f[7]);
}
return MCDE_SYS_OK;
}
/* N strings WIDTH bytes apart from LIST, joined by ',' into BUF */
static void
Join(const char *list, int n, size_t width, char *buf, size_t len)
{
size_t at = 0;
int i;
buf[0] = '\0';
for (i = 0; i < n && at < len; i++)
at += (size_t) snprintf(buf + at, len - at, "%s%s",
i > 0 ? "," : "", list + (size_t) i * width);
}
int
mcde_sys_net_configure_backend(const char *ifname, const McdeSysNetConfig *c)
{
const char *nm = mcde_sys_which(nmcliPaths);
char conn[256], addr4[80] = "", addr6[96] = "", dns[256], search[512];
const char *m4, *m6;
char *argv[24];
int n = 0, r;
if ((r = NmConnection(ifname, conn, sizeof conn)) != MCDE_SYS_OK)
return r;
switch (c->ipv4) {
case MCDE_IPV4_MANUAL:
m4 = "manual";
break;
case MCDE_IPV4_OFF:
m4 = "disabled";
break;
default:
m4 = "auto"; /* with an address: DHCP with manual address */
break;
}
if (c->ipv4 == MCDE_IPV4_MANUAL || c->ipv4 == MCDE_IPV4_DHCP_MANUAL)
snprintf(addr4, sizeof addr4, "%s/%d", c->address,
mcde_sys_net_prefix(c->netmask));
m6 = c->ipv6 == MCDE_IPV6_MANUAL ? "manual" :
c->ipv6 == MCDE_IPV6_OFF ? "disabled" : "auto";
if (c->ipv6 == MCDE_IPV6_MANUAL)
snprintf(addr6, sizeof addr6, "%s/%d", c->address6, c->prefix6);
Join(c->dns[0], c->ndns, sizeof c->dns[0], dns, sizeof dns);
Join(c->search[0], c->nsearch, sizeof c->search[0], search,
sizeof search);
argv[n++] = (char *) nm;
argv[n++] = "connection";
argv[n++] = "modify";
argv[n++] = conn;
argv[n++] = "ipv4.method";
argv[n++] = (char *) m4;
argv[n++] = "ipv4.addresses";
argv[n++] = addr4;
argv[n++] = "ipv4.gateway";
argv[n++] = c->ipv4 == MCDE_IPV4_MANUAL ? (char *) c->router : "";
argv[n++] = "ipv4.dns";
argv[n++] = dns;
argv[n++] = "ipv4.dns-search";
argv[n++] = search;
argv[n++] = "ipv4.dhcp-client-id";
argv[n++] = (char *) c->clientid;
argv[n++] = "ipv6.method";
argv[n++] = (char *) m6;
argv[n++] = "ipv6.addresses";
argv[n++] = addr6;
argv[n] = NULL;
if (mcde_sys_run(argv) != MCDE_SYS_OK)
return mcde_sys_fail(MCDE_SYS_EFAIL, "NetworkManager did not "
"take the settings.");
return mcde_sys_net_renew(ifname);
}
/* the profile activated again: NetworkManager asks DHCP anew and applies
* what was changed */
int
mcde_sys_net_renew(const char *ifname)
{
const char *nm = mcde_sys_which(nmcliPaths);
char conn[256];
char *argv[] = { NULL, "connection", "up", conn, NULL };
int r;
if (!mcde_sys_net_ifname_ok(ifname))
return mcde_sys_fail(MCDE_SYS_EINVAL, "There is no network "
"card of that name.");
if ((r = NmConnection(ifname, conn, sizeof conn)) != MCDE_SYS_OK)
return r;
argv[0] = (char *) nm;
if (mcde_sys_run(argv) != MCDE_SYS_OK)
return mcde_sys_fail(MCDE_SYS_EFAIL, "NetworkManager could not "
"bring \"%s\" up again.", conn);
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);
}
/* ---- a process's arguments: /proc/PID/cmdline, NUL separated (proc(5)) */
int
mcde_sys_process_args(pid_t pid, char *buf, size_t len)
{
char path[64];
FILE *fp;
size_t n;
snprintf(path, sizeof path, "/proc/%ld/cmdline", (long) pid);
if ((fp = fopen(path, "r")) == NULL)
return -1;
n = fread(buf, 1, len - 1, fp);
fclose(fp);
if (n == 0)
return -1;
if (buf[n - 1] != '\0')
buf[n++] = '\0';
return (int) n;
}
/* ---- a process's state: /proc/PID/stat, its third field (proc(5)) */
int
mcde_sys_process_stopped_backend(pid_t pid)
{
char path[64], buf[1024], *p;
FILE *fp;
snprintf(path, sizeof path, "/proc/%ld/stat", (long) pid);
if ((fp = fopen(path, "r")) == NULL)
return -1;
if (fgets(buf, sizeof buf, fp) == NULL) {
fclose(fp);
return -1;
}
fclose(fp);
/* "PID (name) S ..." -- the name may hold spaces and ')' */
if ((p = strrchr(buf, ')')) == NULL || p[1] != ' ' || p[2] == '\0')
return -1;
switch (p[2]) {
case 'T': /* stopped */
case 't': /* traced and stopped */
case 'Z': /* zombie */
return 1;
default:
return 0;
}
}
/* ---- a file's comment: the extended attribute user.mcde.comment
* (xattr(7)); ENOTSUP when the file system has none, ENODATA when there is
* no comment yet */
int
mcde_sys_file_comment_get_backend(const char *path, char *buf, size_t len)
{
ssize_t n;
buf[0] = '\0';
n = getxattr(path, "user.mcde.comment", buf, len - 1);
if (n < 0) {
if (errno == ENODATA)
return MCDE_SYS_OK;
if (errno == ENOTSUP || errno == EOPNOTSUPP)
return mcde_sys_fail(MCDE_SYS_ENOTSUP, "This file system "
"keeps no comments.");
return mcde_sys_fail(MCDE_SYS_EFAIL, "Cannot read the comment: "
"%s.", strerror(errno));
}
buf[n] = '\0';
return MCDE_SYS_OK;
}
int
mcde_sys_file_comment_set_backend(const char *path, const char *text)
{
if (text[0] == '\0') {
if (removexattr(path, "user.mcde.comment") != 0 &&
errno != ENODATA && errno != ENOTSUP)
return mcde_sys_fail(MCDE_SYS_EFAIL, "Cannot remove the "
"comment: %s.", strerror(errno));
return MCDE_SYS_OK;
}
if (setxattr(path, "user.mcde.comment", text, strlen(text), 0) != 0) {
if (errno == ENOTSUP || errno == EOPNOTSUPP)
return mcde_sys_fail(MCDE_SYS_ENOTSUP, "This file system "
"keeps no comments.");
return mcde_sys_fail(MCDE_SYS_EFAIL, "Cannot write the comment: "
"%s.", strerror(errno));
}
return MCDE_SYS_OK;
}
/* ---- the immutable flag (chattr(1) i): FS_IOC_GETFLAGS/SETFLAGS */
int
mcde_sys_file_locked_get_backend(const char *path, int *locked)
{
int fd, flags = 0;
*locked = 0;
if ((fd = open(path, O_RDONLY)) < 0)
return mcde_sys_fail(MCDE_SYS_EFAIL, "Cannot open %s: %s.", path,
strerror(errno));
if (ioctl(fd, FS_IOC_GETFLAGS, &flags) == 0)
*locked = (flags & FS_IMMUTABLE_FL) != 0;
close(fd);
return MCDE_SYS_OK;
}
int
mcde_sys_file_locked_set_backend(const char *path, int locked)
{
int fd, flags = 0;
if ((fd = open(path, O_RDONLY)) < 0)
return mcde_sys_fail(MCDE_SYS_EFAIL, "Cannot open %s: %s.", path,
strerror(errno));
if (ioctl(fd, FS_IOC_GETFLAGS, &flags) != 0) {
close(fd);
return mcde_sys_fail(MCDE_SYS_ENOTSUP, "This file system has no "
"lock.");
}
if (locked)
flags |= FS_IMMUTABLE_FL;
else
flags &= ~FS_IMMUTABLE_FL;
if (ioctl(fd, FS_IOC_SETFLAGS, &flags) != 0) {
int err = errno;
close(fd);
return mcde_sys_fail(MCDE_SYS_EPERM, "Cannot %s the lock: %s.",
locked ? "set" : "clear", strerror(err));
}
close(fd);
return MCDE_SYS_OK;
}
/* ---- sharing: systemd's units, switched with systemctl(1); Debian's names
* (ssh, smbd and nmbd, nfs-server, netatalk). AppleTalk has no server on
* Linux distributions any more. */
static const char *const systemctlPaths[] = { "/usr/bin/systemctl",
"/bin/systemctl", NULL };
static const struct {
const char *units[3];
const char *binary;
} services[MCDE_SHARE_COUNT] = {
[MCDE_SHARE_SSH] = { { "ssh", NULL }, "/usr/sbin/sshd" },
[MCDE_SHARE_SMB] = { { "smbd", "nmbd", NULL }, "/usr/sbin/smbd" },
[MCDE_SHARE_NFS] = { { "nfs-server", NULL }, "/usr/sbin/rpc.nfsd" },
[MCDE_SHARE_AFP] = { { "netatalk", NULL }, "/usr/sbin/netatalk" },
[MCDE_SHARE_APPLETALK] = { { NULL }, NULL },
};
static int
Systemctl(const char *a, const char *b, const char *unit)
{
const char *sc = mcde_sys_which(systemctlPaths);
char *argv[6];
int n = 0;
if (sc == NULL)
return MCDE_SYS_ENOTSUP;
argv[n++] = (char *) sc;
argv[n++] = (char *) a;
if (b != NULL)
argv[n++] = (char *) b;
argv[n++] = (char *) unit;
argv[n] = NULL;
return mcde_sys_run(argv);
}
int
mcde_sys_service_state(McdeSysShareService s, McdeSysServiceState *st)
{
memset(st, 0, sizeof *st);
if ((int) s < 0 || s >= MCDE_SHARE_COUNT)
return mcde_sys_fail(MCDE_SYS_EINVAL, "No such service.");
if (services[s].binary == NULL ||
access(services[s].binary, X_OK) != 0)
return MCDE_SYS_OK;
st->installed = 1;
st->enabled = Systemctl("is-enabled", "-q", services[s].units[0]) ==
MCDE_SYS_OK;
st->running = Systemctl("is-active", "-q", services[s].units[0]) ==
MCDE_SYS_OK;
return MCDE_SYS_OK;
}
int
mcde_sys_service_set(McdeSysShareService s, int on)
{
int i;
if ((int) s < 0 || s >= MCDE_SHARE_COUNT)
return mcde_sys_fail(MCDE_SYS_EINVAL, "No such service.");
if (geteuid() != 0)
return mcde_sys_fail(MCDE_SYS_EPERM, "Only the administrator "
"can switch a service.");
if (services[s].binary == NULL || access(services[s].binary, X_OK) != 0)
return mcde_sys_fail(MCDE_SYS_ENOENT, "The server is not "
"installed.");
for (i = 0; i < 3 && services[s].units[i] != NULL; i++)
if (Systemctl(on ? "enable" : "disable", "--now",
services[s].units[i]) != MCDE_SYS_OK)
return MCDE_SYS_EFAIL;
return MCDE_SYS_OK;
}
const char *
mcde_sys_exports_file(void)
{
return access(services[MCDE_SHARE_NFS].binary, X_OK) == 0 ?
"/etc/exports" : NULL;
}
const char *
mcde_sys_smb_conf(void)
{
return access(services[MCDE_SHARE_SMB].binary, X_OK) == 0 ?
"/etc/samba/smb.conf" : NULL;
}
const char *
mcde_sys_afp_conf(void)
{
return access(services[MCDE_SHARE_AFP].binary, X_OK) == 0 ?
"/etc/netatalk/afp.conf" : NULL;
}
/* exports(5) of nfs-utils: every host, read and write, root squashed */
void
mcde_sys_export_line(const char *path, char *buf, size_t len)
{
snprintf(buf, len, "%s *(rw,sync,no_subtree_check,root_squash)", path);
}
void
mcde_sys_shares_reload(void)
{
static const char *const exportfsPaths[] = { "/usr/sbin/exportfs",
NULL };
const char *ef = mcde_sys_which(exportfsPaths);
if (ef != NULL) {
char *argv[] = { (char *) ef, "-ra", NULL };
(void) mcde_sys_run(argv);
}
if (Systemctl("is-active", "-q", "smbd") == MCDE_SYS_OK)
(void) Systemctl("reload-or-restart", NULL, "smbd");
if (Systemctl("is-active", "-q", "netatalk") == MCDE_SYS_OK)
(void) Systemctl("reload-or-restart", NULL, "netatalk");
}
/* ---- the network: avahi-browse(1) -- -a every type, -t end when the list
* is complete, -r resolved, -p parsable: "=;IF;PROTO;NAME;TYPE;DOMAIN;
* HOST;ADDRESS;PORT;TXT" (names escaped as \DDD) */
static const char *const avahiPaths[] = { "/usr/bin/avahi-browse", NULL };
/* avahi's \DDD (a decimal byte) back into the byte: "\032" is a blank */
static void
Unescape(char *s)
{
char *w = s;
while (*s != '\0') {
if (s[0] == '\\' && s[1] >= '0' && s[1] <= '9' &&
s[2] >= '0' && s[2] <= '9' && s[3] >= '0' && s[3] <= '9') {
*w++ = (char) ((s[1] - '0') * 100 + (s[2] - '0') * 10 +
(s[3] - '0'));
s += 4;
} else if (s[0] == '\\' && s[1] != '\0') {
*w++ = s[1];
s += 2;
} else
*w++ = *s++;
}
*w = '\0';
}
int
mcde_sys_net_browse(McdeSysNetHost *hosts, size_t max, int timeout_ms)
{
static char out[65536];
const char *ab = mcde_sys_which(avahiPaths);
char *argv[] = { NULL, "-a", "-t", "-r", "-p", "-k", NULL };
char *line, *last = NULL;
int n = 0;
(void) timeout_ms;
if (ab == NULL)
return mcde_sys_fail(MCDE_SYS_ENOTSUP, "avahi-browse is not "
"there.");
argv[0] = (char *) ab;
if (mcde_sys_capture(argv, out, sizeof out) != MCDE_SYS_OK)
return -1;
for (line = strtok_r(out, "\n", &last); line != NULL;
line = strtok_r(NULL, "\n", &last)) {
char *f[8], *l2 = NULL;
int k, kind = 0;
if (line[0] != '=')
continue;
f[0] = strtok_r(line, ";", &l2);
for (k = 1; k < 8; k++)
f[k] = strtok_r(NULL, ";", &l2);
if (f[6] == NULL)
continue;
if (strcmp(f[4], "_smb._tcp") == 0)
kind = MCDE_NET_HAS_SMB;
else if (strcmp(f[4], "_afpovertcp._tcp") == 0)
kind = MCDE_NET_HAS_AFP;
else if (strcmp(f[4], "_nfs._tcp") == 0)
kind = MCDE_NET_HAS_NFS;
else if (strcmp(f[4], "_ssh._tcp") == 0 ||
strcmp(f[4], "_sftp-ssh._tcp") == 0)
kind = MCDE_NET_HAS_SSH;
else if (strcmp(f[4], "_workstation._tcp") == 0)
kind = MCDE_NET_HAS_ANY;
else
continue;
Unescape(f[3]);
n = mcde_sys_net_add(hosts, n, max, f[3], f[6], kind);
}
return n;
}