Files
mcde/lib/McdeSys/netbsd.c
T
lotherk 777bd7c8e6 McdeSys: netbsd.c in the catalog, German measured (t0282)
The NetBSD backend's 79 mcde_sys_fail calls are catalogued now: 43 new
messages (144-186) for its own sentences plus the numbers that already
existed for the same texts (cannot write, out of memory, no such service,
the administrator sentences, no account, no network card, the comments, the
lock as set/clear two messages, unknown power action).  The new ones: did
not start, count/list the processes, ntp.conf and /etc/myname, read/read with
strerror, beside a file, the touchpad administrator/no touchpad/setting could
not be written, DRVGETEVENT, PKG_PATH, salt, the update source (not set, does
not answer, not allowed), the Wi-Fi scan/renew administrator sentences,
secure virtual memory, mdnsd, processes change too fast, outputs.master, the
Wi-Fi name/password rule, hashing, the server not installed (with a name),
swap encryption unknown/sysctl, the system's CPU times/disk counters/
interfaces/memory/number of processors, no place for state/value, cgd, npf,
too many settings, dhcpcd renew/start.  German copy in
programs/localized/de_DE.UTF-8/msg/mcdesys.msg with the same numbers.

netbsd.c is not compiled on this Linux host: it passes
x86_64--netbsd-gcc -std=gnu11 -fsyntax-only -Wall with the tree's sysroot.
The catalog itself was measured through mcde_sys_msg (the function the
backend calls), LANG=C vs LANG=de_DE.UTF-8:
154 "Changing the touchpad needs the administrator." / "Das Touchpad zu
ändern braucht den Administrator.",
165 "... (a password has 8 to 63 characters, no quotes)." / "... (ein
Passwort hat 8 bis 63 Zeichen, keine Anführungszeichen).",
176 "The update source is not allowed: ..." / "Die Update-Quelle ist nicht
erlaubt: ...".
make mcde-linux MCDE_DIRS="install lib/McdeSys" and "install
programs/localized/C/msg" exit=0; "check lib/McdeSys": # FAIL: 0, exit=0;
MCDE_DIRS=plist: ok.
2026-11-16 11:57:25 +00:00

2249 lines
68 KiB
C

/*
* netbsd.c -- MCDE: the NetBSD backend of McdeSys (and so Makronix's)
*
* License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree.
*
* The system's own ways: sysctl(3) for the processor and the machine,
* /etc/release (src/etc/Makefile, etc-release: "Makronix VERSION NAME/MACHINE
* (based on NetBSD ...)") for the system, statvfs(2)'s f_mntfromname for the
* startup disk, shutdown(8) and zzz(8) for power, the SIOCG80211NWID ioctl
* for Wi-Fi, mixerctl(1) when no sound server runs, btconfig(8) for
* Bluetooth, the envsys(4) dictionary for the battery, wpa_supplicant(8) as
* sysinst sets it up for Wi-Fi.
*/
#define _NETBSD_SOURCE
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <grp.h>
#include <paths.h>
#include <pwd.h>
#include <stdio.h>
#include <sys/utsname.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include <sys/param.h>
#include <sys/proc.h>
#include <sys/extattr.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/statvfs.h>
#include <sys/sysctl.h>
#include <sys/sched.h>
#include <sys/iostat.h>
#include <uvm/uvm_extern.h>
#include <sys/envsys.h>
#include <net/if.h>
#include <net/if_dl.h>
#include <ifaddrs.h>
#include <net80211/ieee80211_ioctl.h>
#include <prop/proplib.h>
#include <sys/drvctlio.h>
#include <sys/select.h>
#include <sys/time.h>
#include <dns_sd.h>
#include <Mcde/McdeSys.h>
#include "private.h"
const char *
mcde_sys_backend(void)
{
return "netbsd";
}
static int
Sysctl(const char *name, char *buf, size_t len)
{
size_t n = len;
if (sysctlbyname(name, buf, &n, NULL, 0) != 0 || n == 0)
return 0;
buf[n < len ? n : len - 1] = '\0';
return buf[0] != '\0';
}
void
mcde_sys_info_backend(McdeSysInfo *info)
{
char line[256], vendor[64], product[64];
struct statvfs vfs;
FILE *fp;
/* the first line of /etc/release names the system */
if ((fp = fopen("/etc/release", "r")) != NULL) {
if (fgets(line, sizeof line, fp) != NULL) {
char sys[64], ver[64], name[64];
if (sscanf(line, "%63s %63s %63[^/ ]", sys, ver, name) == 3) {
snprintf(info->system, sizeof info->system, "%s", sys);
snprintf(info->version, sizeof info->version,
"%s (%s)", ver, name);
}
}
fclose(fp);
}
if (!Sysctl("machdep.cpu_brand", info->cpu, sizeof info->cpu))
(void) Sysctl("hw.model", info->cpu, sizeof info->cpu);
if (Sysctl("machdep.dmi.system-vendor", vendor, sizeof vendor) &&
Sysctl("machdep.dmi.system-product", product, sizeof product))
snprintf(info->model, sizeof info->model, "%s %s", vendor,
product);
if (statvfs("/", &vfs) == 0)
snprintf(info->disk, sizeof info->disk, "%s", vfs.f_mntfromname);
/* sysconf(3) has no processor count under _POSIX_C_SOURCE here */
if (info->cpus < 1) {
int n = 0;
size_t len = sizeof n;
if (sysctlbyname("hw.ncpuonline", &n, &len, NULL, 0) == 0)
info->cpus = n;
}
}
int
mcde_sys_power(McdeSysPower what)
{
static char *sleep_[] = { "/usr/sbin/zzz", NULL };
static char *restart[] = { "/sbin/shutdown", "-r", "now", NULL };
static char *halt[] = { "/sbin/shutdown", "-p", "now", NULL };
switch (what) {
case MCDE_POWER_SLEEP:
return mcde_sys_run(sleep_);
case MCDE_POWER_RESTART:
return mcde_sys_run(restart);
case MCDE_POWER_SHUTDOWN:
return mcde_sys_run(halt);
}
return mcde_sys_fail(MCDE_SYS_EINVAL, mcde_sys_msg(MSG_LX_POWER_ACTION, "Unknown power action."));
}
/* ---- network: an interface that answers SIOCG80211NWID is Wi-Fi, and the
* answer is the network joined (ifconfig(8) asks the same way) */
McdeSysNetKind
mcde_sys_if_kind(const char *name, char *ssid, size_t len)
{
struct ieee80211_nwid nwid;
struct ifreq ifr;
int s;
ssid[0] = '\0';
if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
return MCDE_NET_OTHER;
memset(&ifr, 0, sizeof ifr);
memset(&nwid, 0, sizeof nwid);
strlcpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
ifr.ifr_data = (void *) &nwid;
if (ioctl(s, SIOCG80211NWID, &ifr) == 0) {
size_t n = nwid.i_len < len - 1 ? nwid.i_len : len - 1;
memcpy(ssid, nwid.i_nwid, n);
ssid[n] = '\0';
close(s);
return MCDE_NET_WIFI;
}
close(s);
return MCDE_NET_WIRED;
}
/* ---- sound without a sound server: mixerctl(1), outputs.master (0..255) */
static char mixerctl[] = "/usr/bin/mixerctl";
/* the base system's player for the audio(4) device: audioplay(1) */
const char *
mcde_sys_player(void)
{
static const char *const paths[] = { "/usr/bin/audioplay", NULL };
return mcde_sys_which(paths);
}
int
mcde_sys_mixer_get(int *percent, int *muted)
{
char out[128];
char *v[] = { mixerctl, "-n", "outputs.master", NULL };
char *m[] = { mixerctl, "-n", "outputs.master.mute", NULL };
if (mcde_sys_capture_limited(v, out, sizeof out,
MCDE_SYS_STATUS_SECONDS) != MCDE_SYS_OK)
return mcde_sys_fail(MCDE_SYS_ENOTSUP, mcde_sys_msg(MSG_NB_MIXER_NO_MASTER, "The mixer has no outputs.master."));
*percent = (atoi(out) * 100 + 127) / 255; /* "l,r": the left */
*muted = mcde_sys_capture_limited(m, out, sizeof out,
MCDE_SYS_STATUS_SECONDS) == MCDE_SYS_OK &&
strncmp(out, "on", 2) == 0;
return MCDE_SYS_OK;
}
int
mcde_sys_mixer_set(int percent)
{
char val[64];
char *argv[] = { mixerctl, "-q", "-w", val, NULL };
int v = (percent * 255 + 50) / 100;
snprintf(val, sizeof val, "outputs.master=%d,%d", v, v);
return mcde_sys_run(argv);
}
int
mcde_sys_mixer_mute(int muted)
{
char val[64];
char *argv[] = { mixerctl, "-q", "-w", val, NULL };
snprintf(val, sizeof val, "outputs.master.mute=%s", muted ? "on" : "off");
return mcde_sys_run(argv);
}
/* ---- Bluetooth: btconfig(8); "ubt0: bdaddr ... flags=0x3<UP,RUNNING>" */
static char btconfig[] = "/usr/sbin/btconfig";
int
mcde_sys_bluetooth(McdeSysBluetooth *bt)
{
char out[2048], *colon;
char *argv[] = { btconfig, NULL };
memset(bt, 0, sizeof *bt);
if (mcde_sys_capture_limited(argv, out, sizeof out,
MCDE_SYS_STATUS_SECONDS) != MCDE_SYS_OK ||
(colon = strchr(out, ':')) == NULL)
return MCDE_SYS_OK;
*colon = '\0';
snprintf(bt->name, sizeof bt->name, "%s", out);
bt->present = 1;
bt->on = strstr(colon + 1, "<UP") != NULL;
return MCDE_SYS_OK;
}
int
mcde_sys_bluetooth_power(int on)
{
McdeSysBluetooth bt;
char *argv[] = { btconfig, NULL, NULL, NULL };
(void) mcde_sys_bluetooth(&bt);
if (!bt.present)
return mcde_sys_fail(MCDE_SYS_ENOENT, mcde_sys_msg(MSG_NB_NO_BLUETOOTH, "There is no Bluetooth controller."));
argv[1] = bt.name;
argv[2] = on ? "up" : "down";
return mcde_sys_run(argv);
}
/* ---- the battery: the envsys(4) dictionary of /dev/sysmon, read as
* envstat(8) reads it (src/usr.sbin/envstat/envstat.c:527): acpibat(4)
* publishes "present", "charge" (uWh, max-value the last full charge),
* "charging" and "discharge rate" (uW); acpiacad(4) "connected"
* (src/sys/dev/acpi/acpi_bat.c:710, acpi_acad.c:262;
* docs/reference/battery.txt). A sensor in state "invalid" says nothing. */
static int
Sensor(prop_array_t sensors, const char *desc, int64_t *cur, int64_t *max)
{
prop_object_iterator_t it;
prop_object_t s, o;
int found = 0;
if ((it = prop_array_iterator(sensors)) == NULL)
return 0;
while ((s = prop_object_iterator_next(it)) != NULL) {
o = prop_dictionary_get(s, "description");
if (o == NULL || !prop_string_equals_string(o, desc))
continue;
o = prop_dictionary_get(s, "state");
if (o != NULL && prop_string_equals_string(o, "invalid"))
break;
if ((o = prop_dictionary_get(s, "cur-value")) == NULL)
break;
*cur = prop_number_signed_value(o);
if (max != NULL) {
o = prop_dictionary_get(s, "max-value");
*max = o != NULL ? prop_number_signed_value(o) : 0;
}
found = 1;
break;
}
prop_object_iterator_release(it);
return found;
}
/* a Macintosh keyboard: every macppc machine has one (ADB or USB, akbd(4)
* or ukbd(4)), elsewhere an Apple USB device (vendor 0x05ac) that is a
* keyboard, as usbdevs(8) -v names it */
int
mcde_sys_keyboard_is_mac(void)
{
static char out[16384];
char *argv[] = { "/usr/sbin/usbdevs", "-v", NULL };
struct utsname u;
char *line, *last = NULL;
if (uname(&u) == 0 && strcmp(u.machine, "macppc") == 0)
return 1;
if (mcde_sys_capture(argv, out, sizeof out) != MCDE_SYS_OK)
return 0;
for (line = strtok_r(out, "\n", &last); line != NULL;
line = strtok_r(NULL, "\n", &last))
if ((strstr(line, "Apple") != NULL ||
strstr(line, "0x05ac") != NULL) &&
strstr(line, "eyboard") != NULL)
return 1;
return 0;
}
/* the touchpad: pms(4)/synaptics(4) and its hw.synaptics.* sysctls (they are
* CTLFLAG_READWRITE, so writing needs root) */
static int
SysctlReadInt(const char *name, int *v)
{
size_t n = sizeof *v;
return sysctlbyname(name, v, &n, NULL, 0) == 0 && n == sizeof *v;
}
static int
SysctlWriteInt(const char *name, int v)
{
if (sysctlbyname(name, NULL, NULL, &v, sizeof v) == 0)
return MCDE_SYS_OK;
if (errno == EPERM || errno == EACCES)
return mcde_sys_fail(MCDE_SYS_EPERM, mcde_sys_msg(MSG_NB_TOUCHPAD_EPERM, "Changing the touchpad needs the administrator."));
if (errno == ENOENT)
return mcde_sys_fail(MCDE_SYS_ENOTSUP, mcde_sys_msg(MSG_NB_NO_TOUCHPAD, "This system has no touchpad settings."));
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_NB_TOUCHPAD_FAIL, "The touchpad setting %s could not be written (%s)."), name, strerror(errno));
}
int
mcde_sys_touchpad_get(McdeSysTouchpad *t)
{
int tap, fingers, vert = 0, horiz = 0;
if (t == NULL)
return MCDE_SYS_EINVAL;
if (!SysctlReadInt("hw.synaptics.tap_to_click", &tap) ||
!SysctlReadInt("hw.synaptics.two_fingers_emulation", &fingers))
return mcde_sys_fail(MCDE_SYS_ENOTSUP, mcde_sys_msg(MSG_NB_NO_TOUCHPAD, "This system has no touchpad settings."));
(void) SysctlReadInt("hw.synaptics.vert_scroll_percent", &vert);
(void) SysctlReadInt("hw.synaptics.horizontal_scroll_percent",
&horiz);
t->tap = tap != 0;
t->fingers = fingers < 0 ? 0 : (fingers > 2 ? 2 : fingers);
t->scroll = vert > 0 || horiz > 0;
return MCDE_SYS_OK;
}
int
mcde_sys_touchpad_set(const McdeSysTouchpad *t)
{
int r;
if (t == NULL || t->fingers < 0 || t->fingers > 2)
return MCDE_SYS_EINVAL;
if ((r = SysctlWriteInt("hw.synaptics.tap_to_click",
t->tap != 0)) != MCDE_SYS_OK)
return r;
if ((r = SysctlWriteInt("hw.synaptics.two_fingers_emulation",
t->fingers)) != MCDE_SYS_OK)
return r;
/* a strip at the pad's edge scrolls; the default is none at all */
if ((r = SysctlWriteInt("hw.synaptics.vert_scroll_percent",
t->scroll ? 7 : 0)) != MCDE_SYS_OK)
return r;
return SysctlWriteInt("hw.synaptics.horizontal_scroll_percent",
t->scroll ? 7 : 0);
}
int
mcde_sys_battery(McdeSysBattery *bat)
{
prop_dictionary_t dict;
prop_object_iterator_t it;
prop_object_t key;
prop_array_t sensors;
const char *dev;
int64_t cur, max, now = 0, full = 0, rate = 0;
int fd, n = 0, discharging = 0;
memset(bat, 0, sizeof *bat);
bat->minutes = -1;
if ((fd = open(_PATH_SYSMON, O_RDONLY)) == -1)
return MCDE_SYS_OK;
if (prop_dictionary_recv_ioctl(fd, ENVSYS_GETDICTIONARY, &dict) != 0) {
close(fd);
return MCDE_SYS_OK;
}
close(fd);
if ((it = prop_dictionary_iterator(dict)) == NULL) {
prop_object_release(dict);
return MCDE_SYS_OK;
}
while ((key = prop_object_iterator_next(it)) != NULL) {
dev = prop_dictionary_keysym_value(key);
sensors = prop_dictionary_get_keysym(dict, key);
if (prop_object_type(sensors) != PROP_TYPE_ARRAY)
continue;
if (strncmp(dev, "acpiacad", 8) == 0) {
if (Sensor(sensors, "connected", &cur, NULL) && cur)
bat->ac = 1;
continue;
}
if (strncmp(dev, "acpibat", 7) != 0 ||
!Sensor(sensors, "present", &cur, NULL) || !cur)
continue;
n++;
if (Sensor(sensors, "charge", &cur, &max) && max > 0) {
now += cur;
full += max;
}
if (Sensor(sensors, "charging", &cur, NULL) && cur)
bat->charging = 1;
else if (Sensor(sensors, "discharge rate", &cur, NULL) &&
cur > 0) {
discharging = 1;
rate += cur;
}
}
prop_object_iterator_release(it);
prop_object_release(dict);
bat->present = n > 0;
if (full > 0)
bat->percent = (int) ((now * 100 + full / 2) / full);
if (bat->percent > 100)
bat->percent = 100;
if (bat->charging)
bat->ac = 1;
if (discharging && !bat->ac && rate > 0)
bat->minutes = (int) (now * 60 / rate);
return MCDE_SYS_OK;
}
/* ---- Wi-Fi: as the installer does it (src/usr.sbin/sysinst/net.c:
* a network block in /etc/wpa_supplicant.conf, wpa_supplicant and dhcpcd in
* rc.conf); the networks in reach from wpa_cli(8) when wpa_supplicant runs,
* else from ifconfig(8) "list scan" (root). docs/reference/wifi.txt. */
#define WPA_CONF "/etc/wpa_supplicant.conf"
#define RC_CONF "/etc/rc.conf"
static char wpacli[] = "/usr/sbin/wpa_cli";
static char ifconfigp[] = "/sbin/ifconfig";
/* signal in dBm (wpa_cli) or the driver's RSSI (ifconfig) as 0..100 */
static int
SignalPercent(int v)
{
if (v < 0)
v = 2 * (v + 100);
return v < 0 ? 0 : v > 100 ? 100 : v;
}
static int
AddNet(McdeSysWifi *nets, int n, size_t max, const char *ssid, int signal,
int secured)
{
int i;
if (ssid[0] == '\0')
return n;
for (i = 0; i < n; i++)
if (strcmp(nets[i].ssid, ssid) == 0) {
if (signal > nets[i].signal)
nets[i].signal = signal;
return n;
}
if ((size_t) n >= max)
return n;
snprintf(nets[n].ssid, sizeof nets[n].ssid, "%s", ssid);
nets[n].signal = signal;
nets[n].secured = secured;
return n + 1;
}
int
mcde_sys_wifi_scan(const char *ifname, McdeSysWifi *nets, size_t max)
{
static char out[16384];
char *argv[6], *line, *last = NULL;
int n = 0;
/* wpa_cli: "bssid / frequency / signal level / flags / ssid", tabs */
argv[0] = wpacli;
argv[1] = "-i";
argv[2] = (char *) ifname;
argv[3] = "scan_results";
argv[4] = NULL;
if (mcde_sys_capture(argv, out, sizeof out) == MCDE_SYS_OK &&
strstr(out, "bssid") != NULL) {
for (line = strtok_r(out, "\n", &last); line != NULL;
line = strtok_r(NULL, "\n", &last)) {
char *f[5], *l2 = NULL;
int k;
f[0] = strtok_r(line, "\t", &l2);
for (k = 1; k < 5; k++)
f[k] = strtok_r(NULL, "\t", &l2);
if (f[4] == NULL || strchr(f[0], ':') == NULL)
continue;
n = AddNet(nets, n, max, f[4],
SignalPercent(atoi(f[2])),
strstr(f[3], "WPA") != NULL ||
strstr(f[3], "WEP") != NULL);
}
return n;
}
/* ifconfig -v IF list scan: "SSID BSSID CHAN RATE S:N INT CAPS",
* the SSID padded; the interface must be up (root) */
if (geteuid() != 0)
return mcde_sys_fail(MCDE_SYS_EPERM, mcde_sys_msg(MSG_NB_WIFI_SCAN_EPERM, "Only the administrator can look for Wi-Fi networks while none is joined."));
argv[0] = ifconfigp;
argv[1] = (char *) ifname;
argv[2] = "up";
argv[3] = NULL;
(void) mcde_sys_run(argv);
argv[1] = "-v";
argv[2] = (char *) ifname;
argv[3] = "list";
argv[4] = "scan";
argv[5] = NULL;
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 *p, *bssid = NULL, *sn, *caps, ssid[64];
int rssi = 0;
/* the BSSID: 17 characters, colons at 2, 5, 8, 11, 14 */
for (p = line; *p != '\0' && strlen(p) >= 17; p++)
if (p[2] == ':' && p[5] == ':' && p[8] == ':' &&
p[11] == ':' && p[14] == ':' &&
(p == line || p[-1] == ' ')) {
bssid = p;
break;
}
if (bssid == NULL || bssid == line)
continue;
snprintf(ssid, sizeof ssid, "%.*s", (int) (bssid - line), line);
while (ssid[0] != '\0' && ssid[strlen(ssid) - 1] == ' ')
ssid[strlen(ssid) - 1] = '\0';
if ((sn = strchr(bssid + 17, ':')) != NULL) {
char *q = sn;
while (q > bssid + 17 && q[-1] != ' ')
q--;
rssi = atoi(q);
}
/* the capabilities are the last word: P is privacy */
caps = strrchr(line, ' ');
n = AddNet(nets, n, max, ssid, SignalPercent(rssi),
caps != NULL && strchr(caps, 'P') != NULL);
}
return n;
}
/* VAR=VALUE in FILE: the line of VAR replaced, or added at the end; the
* file's mode is kept and it is renamed over the old one, so a half-written
* configuration is never read (rc.conf and sysctl.conf both) */
static int
KeySet(const char *file, const char *var, const char *value)
{
char line[1024], tmp[1024];
size_t vlen = strlen(var);
struct stat st;
FILE *from, *to;
int fd, done = 0;
if (stat(file, &st) != 0 || (from = fopen(file, "r")) == NULL)
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_NB_READ, "Cannot read %s."), file);
(void)snprintf(tmp, sizeof tmp, "%s.mcdeXXXXXX", file);
if ((fd = mkstemp(tmp)) < 0 || (to = fdopen(fd, "w")) == NULL) {
fclose(from);
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_NB_WRITE_BESIDE, "Cannot write beside %s."),
file);
}
while (fgets(line, sizeof line, from) != NULL) {
if (strncmp(line, var, vlen) == 0 && line[vlen] == '=') {
if (!done)
fprintf(to, "%s=%s\n", var, value);
done = 1;
continue;
}
fputs(line, to);
}
fclose(from);
if (!done)
fprintf(to, "%s=%s\n", var, value);
if (fchmod(fd, st.st_mode & 07777) != 0 || fclose(to) != 0 ||
rename(tmp, file) != 0) {
unlink(tmp);
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_SHR_WRITE, "Cannot write %s."), file);
}
return MCDE_SYS_OK;
}
/* VAR=VALUE in rc.conf */
static int
RcConfSet(const char *var, const char *value)
{
return KeySet(RC_CONF, var, value);
}
int
mcde_sys_wifi_join(const char *ifname, const char *ssid,
const char *passphrase)
{
char flags[256];
struct stat st;
FILE *fp;
int fresh;
char *argv[4];
if (geteuid() != 0)
return mcde_sys_fail(MCDE_SYS_EPERM, mcde_sys_msg(MSG_LX_WIFI_EPERM, "Only the administrator can join a Wi-Fi network."));
if (!mcde_sys_wifi_config_ok(ifname, ssid, passphrase))
return mcde_sys_fail(MCDE_SYS_EINVAL, mcde_sys_msg(MSG_NB_WIFI_BAD, "The network name or the password cannot be used (a password has 8 to 63 characters, no quotes)."));
fresh = stat(WPA_CONF, &st) != 0;
if ((fp = fopen(WPA_CONF, "a")) == NULL)
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_SHR_WRITE, "Cannot write %s."),
WPA_CONF);
(void) fchmod(fileno(fp), 0600);
/* the example's head (share/examples/wpa_supplicant): wpa_cli for
* the wheel group, which lets System Settings see the networks */
if (fresh)
fprintf(fp, "ctrl_interface=/var/run/wpa_supplicant/\n"
"ctrl_interface_group=wheel\n");
fprintf(fp, "\n# Added by MCDE System Settings\nnetwork={\n"
"\tssid=\"%s\"\n", ssid);
if (passphrase != NULL)
fprintf(fp, "\tpsk=\"%s\"\n", passphrase);
else
fprintf(fp, "\tkey_mgmt=NONE\n");
fprintf(fp, "\tscan_ssid=1\n}\n");
if (fclose(fp) != 0)
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_SHR_WRITE, "Cannot write %s."),
WPA_CONF);
/* sysinst's lines (net.c:1203-1209) */
snprintf(flags, sizeof flags,
"\"-B -s -i %s -D bsd -c " WPA_CONF "\"", ifname);
if (RcConfSet("wpa_supplicant", "YES") != MCDE_SYS_OK ||
RcConfSet("wpa_supplicant_flags", flags) != MCDE_SYS_OK ||
RcConfSet("dhcpcd", "YES") != MCDE_SYS_OK)
return MCDE_SYS_EFAIL;
/* now: wpa_supplicant (re)started with the new network, dhcpcd for
* the address */
argv[0] = "/etc/rc.d/wpa_supplicant";
argv[1] = "restart";
argv[2] = NULL;
if (mcde_sys_run(argv) != MCDE_SYS_OK) {
argv[1] = "start";
if (mcde_sys_run(argv) != MCDE_SYS_OK)
return MCDE_SYS_EFAIL;
}
argv[0] = "/etc/rc.d/dhcpcd";
argv[1] = "restart";
if (mcde_sys_run(argv) != MCDE_SYS_OK) {
argv[1] = "start";
(void) mcde_sys_run(argv);
}
return MCDE_SYS_OK;
}
/* ---- the settings of an interface: one block per interface in
* dhcpcd.conf(5), dhcpcd=YES in rc.conf -- what ifconfig.if(5) recommends
* ("it is instead recommended that dhcpcd is set to true in rc.conf(5) and
* any per interface configuration or restriction is done in
* dhcpcd.conf(5)"). A static address sysinst wrote into /etc/ifconfig.IF
* (net.c:1168) is read as "Manually" and moved into the block when the
* settings are applied. docs/reference/netconfig.txt. */
#define DHCPCD_CONF "/etc/dhcpcd.conf"
static char dhcpcdp[] = "/sbin/dhcpcd";
static char routep[] = "/sbin/route";
static char rcdhcpcd[] = "/etc/rc.d/dhcpcd";
/* VAR=VALUE of rc.conf (the last one wins, as sh reads it), unquoted */
static int
RcConfGet(const char *var, char *buf, size_t len)
{
char line[1024];
size_t vlen = strlen(var);
FILE *fp = fopen(RC_CONF, "r");
int found = 0;
buf[0] = '\0';
if (fp == NULL)
return 0;
while (fgets(line, sizeof line, fp) != NULL) {
char *v, *e;
if (strncmp(line, var, vlen) != 0 || line[vlen] != '=')
continue;
v = line + vlen + 1;
v[strcspn(v, "#\n")] = '\0';
while (*v == '"' || *v == '\'')
v++;
e = v + strlen(v);
while (e > v && (e[-1] == '"' || e[-1] == '\'' || e[-1] == ' '))
*--e = '\0';
snprintf(buf, len, "%s", v);
found = 1;
}
fclose(fp);
return found;
}
static int
Yes(const char *v)
{
return strcasecmp(v, "yes") == 0 || strcasecmp(v, "true") == 0 ||
strcasecmp(v, "on") == 0 || strcmp(v, "1") == 0;
}
/* "ADDR/PREFIX" into ADDR and a dotted netmask (IPv4) */
static void
SplitCidr(const char *v, char *addr, size_t alen, char *mask, size_t mlen)
{
const char *slash = strchr(v, '/');
snprintf(addr, alen, "%.*s", slash != NULL ? (int) (slash - v) :
(int) strlen(v), v);
if (slash != NULL)
mcde_sys_net_mask(atoi(slash + 1), mask, mlen);
}
/* the words of V (blanks between them) into DST */
static int
Words(char *v, char *dst, size_t width, int max)
{
char *w, *last = NULL;
int n = 0;
for (w = strtok_r(v, " \t", &last); w != NULL && n < max;
w = strtok_r(NULL, " \t", &last))
snprintf(dst + (size_t) n++ * width, width, "%s", w);
return n;
}
/* is LINE of an ifconfig.IF an IPv4 address: "inet ADDR ..." or sysinst's
* "ADDR netmask MASK" */
static int
StaticLine(const char *line, char *addr, size_t alen, char *mask,
size_t mlen)
{
char a[64] = "", m[64] = "", w[16] = "";
if (sscanf(line, "inet %63s netmask %63s", a, m) == 2 ||
(sscanf(line, "%63s %15s %63s", a, w, m) == 3 &&
strcmp(w, "netmask") == 0 && strchr(a, '.') != NULL)) {
snprintf(addr, alen, "%s", a);
snprintf(mask, mlen, "%s", m);
return 1;
}
return 0;
}
int
mcde_sys_net_config_backend(const char *ifname, McdeSysNetConfig *c)
{
char path[256], line[512], out[4096], v[256], *l, *last = NULL;
struct ifaddrs *all, *a;
FILE *fp;
int in = 0, have4 = 0, dhcpLine = 0;
char *argv[5];
/* the Ethernet ID: the link-level address getifaddrs gives */
if (getifaddrs(&all) == 0) {
for (a = all; a != NULL; a = a->ifa_next) {
struct sockaddr_dl *dl;
unsigned char *m;
if (a->ifa_addr == NULL || a->ifa_addr->sa_family !=
AF_LINK || strcmp(a->ifa_name, ifname) != 0)
continue;
dl = (struct sockaddr_dl *) a->ifa_addr;
if (dl->sdl_alen != 6)
continue;
m = (unsigned char *) LLADDR(dl);
snprintf(c->mac, sizeof c->mac,
"%02x:%02x:%02x:%02x:%02x:%02x", m[0], m[1], m[2],
m[3], m[4], m[5]);
}
freeifaddrs(all);
}
/* the media, as ifconfig(8) prints it */
argv[0] = ifconfigp;
argv[1] = (char *) ifname;
argv[2] = NULL;
if (mcde_sys_capture(argv, out, sizeof out) == MCDE_SYS_OK)
for (l = strtok_r(out, "\n", &last); l != NULL;
l = strtok_r(NULL, "\n", &last))
if ((l = strstr(l, "media: ")) != NULL) {
snprintf(c->media, sizeof c->media, "%s", l + 7);
break;
}
/* the router now: route(8) get default, if it goes out here */
argv[0] = routep;
argv[1] = "-n";
argv[2] = "get";
argv[3] = "default";
argv[4] = NULL;
if (mcde_sys_capture(argv, out, sizeof out) == MCDE_SYS_OK) {
char gw[64] = "", ifn[64] = "";
last = NULL;
for (l = strtok_r(out, "\n", &last); l != NULL;
l = strtok_r(NULL, "\n", &last)) {
(void) sscanf(l, " gateway: %63s", gw);
(void) sscanf(l, " interface: %63s", ifn);
}
if (strcmp(ifn, ifname) == 0)
snprintf(c->cur_router, sizeof c->cur_router, "%s", gw);
}
/* the block of the interface in dhcpcd.conf */
c->ipv4 = MCDE_IPV4_DHCP;
c->ipv6 = MCDE_IPV6_AUTO;
if ((fp = fopen(DHCPCD_CONF, "r")) != NULL) {
while (fgets(line, sizeof line, fp) != NULL) {
char *t = line + strspn(line, " \t");
t[strcspn(t, "#\r\n")] = '\0';
if (strncmp(t, "interface ", 10) == 0) {
in = strcmp(t + 10 + strspn(t + 10, " \t"),
ifname) == 0;
continue;
}
if (!in)
continue;
if (strcmp(t, "noipv4") == 0) {
c->ipv4 = MCDE_IPV4_OFF;
have4 = 1;
} else if (strcmp(t, "noipv6") == 0)
c->ipv6 = MCDE_IPV6_OFF;
else if (sscanf(t, "inform %255s", v) == 1) {
c->ipv4 = MCDE_IPV4_DHCP_MANUAL;
SplitCidr(v, c->address, sizeof c->address,
c->netmask, sizeof c->netmask);
have4 = 1;
} else if (sscanf(t, "clientid %63s", v) == 1)
snprintf(c->clientid, sizeof c->clientid, "%s",
v);
else if (sscanf(t, "static ip_address=%255s", v) == 1) {
c->ipv4 = MCDE_IPV4_MANUAL;
SplitCidr(v, c->address, sizeof c->address,
c->netmask, sizeof c->netmask);
have4 = 1;
} else if (sscanf(t, "static routers=%47s", v) == 1)
snprintf(c->router, sizeof c->router, "%s", v);
else if (sscanf(t, "static ip6_address=%255s", v) == 1) {
char *slash = strchr(v, '/');
c->ipv6 = MCDE_IPV6_MANUAL;
if (slash != NULL) {
*slash = '\0';
c->prefix6 = atoi(slash + 1);
}
snprintf(c->address6, sizeof c->address6, "%s",
v);
} else if (strncmp(t, "static domain_name_servers=",
27) == 0)
c->ndns = Words(t + 27, c->dns[0],
sizeof c->dns[0], MCDE_NET_DNS_MAX);
else if (strncmp(t, "static domain_search=", 21) == 0)
c->nsearch = Words(t + 21, c->search[0],
sizeof c->search[0], MCDE_NET_DNS_MAX);
}
fclose(fp);
}
/* sysinst's static address in ifconfig.IF, defaultroute in rc.conf */
snprintf(path, sizeof path, "/etc/ifconfig.%s", ifname);
if (!have4 && (fp = fopen(path, "r")) != NULL) {
while (fgets(line, sizeof line, fp) != NULL) {
line[strcspn(line, "#\r\n")] = '\0';
if (strcmp(line, "dhcp") == 0)
dhcpLine = 1;
else if (StaticLine(line, c->address, sizeof c->address,
c->netmask, sizeof c->netmask)) {
c->ipv4 = MCDE_IPV4_MANUAL;
have4 = 1;
(void) RcConfGet("defaultroute", c->router,
sizeof c->router);
}
}
fclose(fp);
}
/* no address configured and no dhcpcd: the interface gets none */
if (!have4 && !dhcpLine && (!RcConfGet("dhcpcd", v, sizeof v) ||
!Yes(v)))
c->ipv4 = MCDE_IPV4_OFF;
return MCDE_SYS_OK;
}
/* FILE with the lines between "# MCDE network IF begin" and "... end"
* replaced by BLOCK (taken out when BLOCK is empty); kept mode, renamed
* into place */
static int
ReplaceBlock(const char *file, const char *ifname, const char *block)
{
char line[1024], begin[96], end[96], tmp[256];
struct stat st;
FILE *from, *to;
int fd, skip = 0;
mode_t mode = 0644;
snprintf(begin, sizeof begin, "# MCDE network %s begin\n", ifname);
snprintf(end, sizeof end, "# MCDE network %s end\n", ifname);
snprintf(tmp, sizeof tmp, "%s.mcdeXXXXXX", file);
if (stat(file, &st) == 0)
mode = st.st_mode & 07777;
if ((fd = mkstemp(tmp)) < 0 || (to = fdopen(fd, "w")) == NULL)
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_NB_WRITE_BESIDE, "Cannot write beside %s."),
file);
if ((from = fopen(file, "r")) != NULL) {
while (fgets(line, sizeof line, from) != NULL) {
if (strcmp(line, begin) == 0) {
skip = 1;
continue;
}
if (skip) {
if (strcmp(line, end) == 0)
skip = 0;
continue;
}
fputs(line, to);
}
fclose(from);
}
if (block[0] != '\0')
fprintf(to, "%s%s%s", begin, block, end);
if (fchmod(fd, mode) != 0 || fclose(to) != 0 || rename(tmp, file) != 0) {
unlink(tmp);
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_SHR_WRITE, "Cannot write %s."), file);
}
return MCDE_SYS_OK;
}
/* /etc/ifconfig.IF without its IPv4 addresses and "dhcp" (dhcpcd.conf has
* them now), "up" kept or added; 1 when an address was taken out */
static int
StripIfconfig(const char *ifname, int *removed)
{
char path[256], tmp[300], line[512], a[64], m[64];
FILE *from, *to;
int fd, up = 0;
*removed = 0;
snprintf(path, sizeof path, "/etc/ifconfig.%s", ifname);
snprintf(tmp, sizeof tmp, "%s.mcdeXXXXXX", path);
if ((fd = mkstemp(tmp)) < 0 || (to = fdopen(fd, "w")) == NULL)
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_NB_WRITE_BESIDE, "Cannot write beside %s."),
path);
if ((from = fopen(path, "r")) != NULL) {
while (fgets(line, sizeof line, from) != NULL) {
char bare[512];
snprintf(bare, sizeof bare, "%s", line);
bare[strcspn(bare, "#\r\n")] = '\0';
if (StaticLine(bare, a, sizeof a, m, sizeof m)) {
*removed = 1;
continue;
}
if (strcmp(bare, "dhcp") == 0)
continue;
if (strcmp(bare, "up") == 0)
up = 1;
fputs(line, to);
}
fclose(from);
}
if (!up)
fputs("up\n", to);
if (fchmod(fd, 0644) != 0 || fclose(to) != 0 || rename(tmp, path) != 0) {
unlink(tmp);
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_SHR_WRITE, "Cannot write %s."), path);
}
return MCDE_SYS_OK;
}
int
mcde_sys_net_configure_backend(const char *ifname, const McdeSysNetConfig *c)
{
char block[2048], flags[512], nflags[600];
size_t at = 0;
int i, removed;
char *argv[4];
#define ADD(...) (at += (size_t) snprintf(block + at, \
at < sizeof block ? sizeof block - at : 0, __VA_ARGS__))
block[0] = '\0';
ADD("interface %s\n", ifname);
switch (c->ipv4) {
case MCDE_IPV4_OFF:
ADD("noipv4\n");
break;
case MCDE_IPV4_MANUAL:
ADD("static ip_address=%s/%d\n", c->address,
mcde_sys_net_prefix(c->netmask));
if (c->router[0] != '\0')
ADD("static routers=%s\n", c->router);
break;
case MCDE_IPV4_DHCP_MANUAL:
ADD("inform %s/%d\n", c->address,
mcde_sys_net_prefix(c->netmask));
break;
default:
break;
}
if (c->clientid[0] != '\0' && c->ipv4 != MCDE_IPV4_OFF &&
c->ipv4 != MCDE_IPV4_MANUAL)
ADD("clientid %s\n", c->clientid);
if (c->ipv6 == MCDE_IPV6_OFF)
ADD("noipv6\n");
else if (c->ipv6 == MCDE_IPV6_MANUAL)
ADD("static ip6_address=%s/%d\n", c->address6, c->prefix6);
if (c->ndns > 0) {
ADD("static domain_name_servers=");
for (i = 0; i < c->ndns; i++)
ADD("%s%s", i > 0 ? " " : "", c->dns[i]);
ADD("\n");
}
if (c->nsearch > 0) {
ADD("static domain_search=");
for (i = 0; i < c->nsearch; i++)
ADD("%s%s", i > 0 ? " " : "", c->search[i]);
ADD("\n");
}
#undef ADD
if (at >= sizeof block)
return mcde_sys_fail(MCDE_SYS_EINVAL, mcde_sys_msg(MSG_NB_TOO_MANY, "Too many settings."));
/* "interface IF" alone says nothing: no block then */
if (strchr(strchr(block, '\n') + 1, '\n') == NULL)
block[0] = '\0';
if (ReplaceBlock(DHCPCD_CONF, ifname, block) != MCDE_SYS_OK ||
StripIfconfig(ifname, &removed) != MCDE_SYS_OK)
return MCDE_SYS_EFAIL;
/* sysinst's defaultroute belonged to the address just moved */
if (removed && RcConfSet("defaultroute", "\"\"") != MCDE_SYS_OK)
return MCDE_SYS_EFAIL;
if (RcConfSet("dhcpcd", "YES") != MCDE_SYS_OK)
return MCDE_SYS_EFAIL;
/* sysinst's dhcpcd_flags="-qM wm0" restricts dhcpcd to wm0: then this
* interface joins the list */
if (RcConfGet("dhcpcd_flags", flags, sizeof flags)) {
char copy[512], *w, *last = NULL;
int names = 0, mine = 0;
snprintf(copy, sizeof copy, "%s", flags);
for (w = strtok_r(copy, " \t", &last); w != NULL;
w = strtok_r(NULL, " \t", &last))
if (w[0] != '-') {
names = 1;
mine |= strcmp(w, ifname) == 0;
}
if (names && !mine) {
snprintf(nflags, sizeof nflags, "\"%s %s\"", flags,
ifname);
if (RcConfSet("dhcpcd_flags", nflags) != MCDE_SYS_OK)
return MCDE_SYS_EFAIL;
}
}
/* now: a running dhcpcd reads the file again and binds the interface
* anew (dhcpcd(8) -n); else it is started as the boot does */
argv[0] = rcdhcpcd;
argv[1] = "status";
argv[2] = NULL;
if (mcde_sys_run(argv) == MCDE_SYS_OK)
return mcde_sys_net_renew(ifname);
argv[1] = "start";
if (mcde_sys_run(argv) != MCDE_SYS_OK)
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_NB_DHCP_START, "dhcpcd did not start (/etc/rc.d/dhcpcd start)."));
return MCDE_SYS_OK;
}
int
mcde_sys_net_renew(const char *ifname)
{
char *argv[] = { dhcpcdp, "-n", (char *) ifname, NULL };
if (!mcde_sys_net_ifname_ok(ifname))
return mcde_sys_fail(MCDE_SYS_EINVAL, mcde_sys_msg(MSG_LX_NO_CARD, "There is no network card of that name."));
if (geteuid() != 0)
return mcde_sys_fail(MCDE_SYS_EPERM, mcde_sys_msg(MSG_NB_RENEW_EPERM, "Only the administrator can renew the lease: click the lock first."));
if (mcde_sys_run(argv) != MCDE_SYS_OK)
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_NB_DHCP_RENEW, "dhcpcd did not renew the lease of %s."), ifname);
return MCDE_SYS_OK;
}
/* ---- users: wheel administers (su(1) takes only wheel); the password is
* hashed here, as passwd(1) does, with pw_gensalt(3) and crypt(3), and only
* the hash goes to usermod(8) -- the password itself is on no command line */
const char *
mcde_sys_admin_group(void)
{
return "wheel";
}
const char *
mcde_sys_default_shell(void)
{
return "/bin/ksh";
}
static char usermod[] = "/usr/sbin/usermod";
int
mcde_sys_user_set_password(const char *login, const char *password)
{
char salt[128], *hash;
char *argv[] = { usermod, "-p", NULL, NULL, NULL };
if (getpwnam(login) == NULL)
return mcde_sys_fail(MCDE_SYS_ENOENT, mcde_sys_msg(MSG_USR_NOT_FOUND, "There is no account \"%s\"."), login);
if (geteuid() != 0)
return mcde_sys_fail(MCDE_SYS_EPERM, mcde_sys_msg(MSG_LX_PW_EPERM, "Only the administrator can set a password: unlock first."));
if (pw_gensalt(salt, sizeof salt, "argon2id", NULL) != 0 &&
pw_gensalt(salt, sizeof salt, "blowfish", "10") != 0)
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_NB_NO_SALT, "No salt for the password."));
if ((hash = crypt(password, salt)) == NULL)
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_NB_HASH_FAIL, "The password cannot be hashed."));
argv[2] = hash;
argv[3] = (char *) login;
return mcde_sys_run(argv);
}
/* Out of a group: NetBSD has no tool that removes a member (usermod -G only
* appends, groupmod has no members: user.c, measured 2026-11-10), so the
* line of the group is rewritten the way user.c's append_group() writes
* /etc/group: a temporary file beside it, then rename(2). */
static int
RemoveFromGroup(const char *login, const char *group)
{
char line[4096], tmp[] = "/etc/group.mcdeXXXXXX";
size_t glen = strlen(group);
struct stat st;
FILE *from, *to;
int fd, changed = 0;
if (stat(_PATH_GROUP, &st) != 0 || (from = fopen(_PATH_GROUP, "r")) == NULL)
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_NB_READ, "Cannot read %s."),
_PATH_GROUP);
if ((fd = mkstemp(tmp)) < 0 || (to = fdopen(fd, "w")) == NULL) {
fclose(from);
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_NB_WRITE_BESIDE, "Cannot write beside %s."),
_PATH_GROUP);
}
while (fgets(line, sizeof line, from) != NULL) {
char *members, *m, *next, out[4096];
size_t at;
int first = 1;
/* "wheel:*:0:root,tester,mcdet2" */
if (strncmp(line, group, glen) != 0 || line[glen] != ':' ||
(members = strrchr(line, ':')) == NULL) {
fputs(line, to);
continue;
}
members++;
members[strcspn(members, "\n")] = '\0';
at = (size_t) (members - line);
memcpy(out, line, at);
out[at] = '\0';
for (m = members; m != NULL && *m != '\0'; m = next) {
next = strchr(m, ',');
if (next != NULL)
*next++ = '\0';
if (strcmp(m, login) == 0) {
changed = 1;
continue;
}
at += (size_t) snprintf(out + at, sizeof out - at, "%s%s",
first ? "" : ",", m);
first = 0;
}
fprintf(to, "%s\n", out);
}
fclose(from);
if (fchmod(fd, st.st_mode & 07777) != 0 ||
fchown(fd, st.st_uid, st.st_gid) != 0 || fclose(to) != 0 ||
rename(tmp, _PATH_GROUP) != 0) {
unlink(tmp);
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_SHR_WRITE, "Cannot write %s."),
_PATH_GROUP);
}
(void) changed;
return MCDE_SYS_OK;
}
int
mcde_sys_user_set_admin(const char *login, int admin)
{
char *argv[] = { usermod, "-G", "wheel", NULL, NULL };
if (getpwnam(login) == NULL)
return mcde_sys_fail(MCDE_SYS_ENOENT, mcde_sys_msg(MSG_USR_NOT_FOUND, "There is no account \"%s\"."), login);
if (geteuid() != 0)
return mcde_sys_fail(MCDE_SYS_EPERM, mcde_sys_msg(MSG_LX_CHANGE_EPERM, "Only the administrator can change that: unlock first."));
if (!admin)
return RemoveFromGroup(login, "wheel");
if (mcde_sys_user_is_admin(login))
return MCDE_SYS_OK;
argv[3] = (char *) login; /* usermod -G appends (user.c) */
return mcde_sys_run(argv);
}
/* ---- software update: /etc/makronix/update names the source, a Makronix
* release directory (the one build.sh makes, with the sets and the
* packages); its RELEASE file has the first line of the release's
* /etc/release. sysupgrade(8) (pkgsrc sysutils/sysupgrade) brings the
* system, pkg_add -uu (pkg_add(1), base) the packages. */
static const char updateConf[] = "/etc/makronix/update";
static int
UpdateSource(char *url, size_t len)
{
char line[512];
FILE *fp = fopen(updateConf, "r");
int found = 0;
url[0] = '\0';
if (fp == NULL)
return 0;
while (!found && fgets(line, sizeof line, fp) != NULL) {
line[strcspn(line, "\r\n")] = '\0';
if (line[0] == '\0' || line[0] == '#')
continue;
snprintf(url, len, "%s", line);
found = 1;
}
fclose(fp);
return found;
}
int
mcde_sys_update_check(McdeSysUpdate *u)
{
char url[512], out[512], *e;
char *argv[] = { "/usr/bin/ftp", "-V", "-o", "-", url, NULL };
McdeSysInfo i;
memset(u, 0, sizeof *u);
u->packages = -1;
(void) mcde_sys_info(&i);
snprintf(u->current, sizeof u->current, "%s", i.version);
if (!UpdateSource(u->source, sizeof u->source)) {
snprintf(u->note, sizeof u->note, "No update source is set "
"(%s).", updateConf);
return MCDE_SYS_OK;
}
if (!mcde_sys_update_source_ok(u->source)) {
/* not even asked: http:// could be answered by anyone */
snprintf(u->note, sizeof u->note, "The update source is not "
"allowed: it must be a directory, file:/// or https:// "
"(%s).", updateConf);
return MCDE_SYS_OK;
}
snprintf(url, sizeof url, "%s/RELEASE", u->source);
if (mcde_sys_capture(argv, out, sizeof out) != MCDE_SYS_OK)
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_NB_SOURCE_NO_ANSWER, "The update source does not answer: %s"), u->source);
/* "Makronix 0.99.10 NAME/amd64 (based on NetBSD ...)" */
if ((e = strchr(out, '\n')) != NULL)
*e = '\0';
{
char sys[64], ver[64], name[64];
if (sscanf(out, "%63s %63s %63[^/ ]", sys, ver, name) == 3)
snprintf(u->available, sizeof u->available, "%s (%s)",
ver, name);
else
snprintf(u->available, sizeof u->available, "%s", out);
}
if (strcmp(u->available, u->current) == 0)
snprintf(u->note, sizeof u->note, "The system is up to date.");
return MCDE_SYS_OK;
}
int
mcde_sys_update_apply(void)
{
static char out[65536];
char url[512], pkgpath[600];
char *sysupgrade[] = { MCDE_PKG_PREFIX "/sbin/sysupgrade", "auto", url,
NULL };
char *pkginfo[] = { "/usr/sbin/pkg_info", NULL };
char *argv[520];
char *line, *next;
int n = 0, r;
if (geteuid() != 0)
return mcde_sys_fail(MCDE_SYS_EPERM, mcde_sys_msg(MSG_LX_UPDATE_EPERM, "Only the administrator can update the computer: unlock first."));
if (!UpdateSource(url, sizeof url))
return mcde_sys_fail(MCDE_SYS_ENOENT, mcde_sys_msg(MSG_NB_NO_SOURCE, "No update source is set (%s)."), updateConf);
/* sysupgrade unpacks the sets as root and checks nothing, pkg_add
* -uu trusts the packages it is given: only a source nobody on the
* way can change (t0078, docs/reference/update-verification.txt) */
if (!mcde_sys_update_source_ok(url))
return mcde_sys_fail(MCDE_SYS_EINVAL, mcde_sys_msg(MSG_NB_SOURCE_BAD, "The update source is not allowed: it must be a directory, file:/// or https:// (%s)."), updateConf);
if ((r = mcde_sys_run(sysupgrade)) != MCDE_SYS_OK)
return r;
/* the installed packages, by name ("vim-9.2.1202 comment" -> vim),
* updated from the packages of the release: pkg_add -uu */
snprintf(pkgpath, sizeof pkgpath, "%s/packages/All", url);
if (setenv("PKG_PATH", pkgpath, 1) != 0)
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_NB_NO_PKGPATH, "No PKG_PATH."));
if ((r = mcde_sys_capture(pkginfo, out, sizeof out)) != MCDE_SYS_OK)
return r;
argv[n++] = "/usr/sbin/pkg_add";
argv[n++] = "-uu";
for (line = out; line != NULL && *line != '\0' &&
n < (int) (sizeof argv / sizeof argv[0]) - 1; line = next) {
char *sp, *dash;
next = strchr(line, '\n');
if (next != NULL)
*next++ = '\0';
if ((sp = strpbrk(line, " \t")) != NULL)
*sp = '\0';
if ((dash = strrchr(line, '-')) != NULL && dash != line)
*dash = '\0';
if (line[0] != '\0')
argv[n++] = line;
}
argv[n] = NULL;
if (n == 2)
return MCDE_SYS_OK;
return mcde_sys_run(argv);
}
/* ---- a process's arguments: sysctl kern.proc_args.PID.argv, NUL
* separated (sysctl(7): KERN_PROC_ARGS, KERN_PROC_ARGV) */
int
mcde_sys_process_args(pid_t pid, char *buf, size_t len)
{
int mib[4] = { CTL_KERN, KERN_PROC_ARGS, (int) pid, KERN_PROC_ARGV };
size_t n = len - 1;
if (sysctl(mib, 4, buf, &n, NULL, 0) != 0 || n == 0)
return -1;
if (buf[n - 1] != '\0')
buf[n++] = '\0';
return (int) n;
}
/* ---- a process's state: sysctl(7) KERN_PROC2 for one pid */
int
mcde_sys_process_stopped_backend(pid_t pid)
{
int mib[6];
struct kinfo_proc2 kp;
size_t len = sizeof kp;
memset(&kp, 0, sizeof kp);
mib[0] = CTL_KERN;
mib[1] = KERN_PROC2;
mib[2] = KERN_PROC_PID;
mib[3] = (int) pid;
mib[4] = (int) sizeof kp;
mib[5] = 1;
if (sysctl(mib, 6, &kp, &len, NULL, 0) != 0 || len < sizeof kp)
return -1;
if (kp.p_stat == SSTOP || kp.p_stat == SZOMB)
return 1;
return 0;
}
/* ---- the processes: sysctl(7) KERN_PROC2 for all of them, as libkvm's
* kvm_getproc2 asks (src/lib/libkvm/kvm_proc.c): a first call without a
* buffer gives the size, the second fills it; ENOMEM means more processes
* came meanwhile, ask again. Memory is in pages (kinfo_proc2, sysctl.h);
* the CPU time is ps(1)'s TIME (p_rtime_sec and p_rtime_usec, src/bin/ps/
* print.c). The state: p_realstat is the process's (SSTOP, SZOMB, SIDL),
* p_stat that of an LWP (kern_proc.c: "overridden by LWP status"). */
int
mcde_sys_processes_backend(McdeSysProcess **out, size_t *n)
{
int mib[6], tries;
struct kinfo_proc2 *kp = NULL;
McdeSysProcess *v;
size_t size = 0, cnt, i;
long page = sysconf(_SC_PAGESIZE);
if (page <= 0)
page = 4096;
mib[0] = CTL_KERN;
mib[1] = KERN_PROC2;
mib[2] = KERN_PROC_ALL;
mib[3] = 0;
mib[4] = (int) sizeof *kp;
for (tries = 0; tries < 5; tries++) {
mib[5] = 0;
if (sysctl(mib, 6, NULL, &size, NULL, 0) != 0) {
free(kp);
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_NB_PROC_COUNT, "Cannot count the processes: %s."), strerror(errno));
}
size += 16 * sizeof *kp; /* processes that start meanwhile */
free(kp);
if ((kp = malloc(size)) == NULL)
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_NO_MEMORY, "Out of memory."));
mib[5] = (int) (size / sizeof *kp);
if (sysctl(mib, 6, kp, &size, NULL, 0) == 0)
break;
if (errno != ENOMEM) {
free(kp);
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_NB_PROC_LIST, "Cannot list the processes: %s."), strerror(errno));
}
}
if (tries == 5) {
free(kp);
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_NB_PROC_FAST, "The list of processes changes too fast."));
}
cnt = size / sizeof *kp;
if ((v = malloc((cnt > 0 ? cnt : 1) * sizeof *v)) == NULL) {
free(kp);
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_NO_MEMORY, "Out of memory."));
}
for (i = 0; i < cnt; i++) {
const struct kinfo_proc2 *k = &kp[i];
McdeSysProcess *p = &v[i];
struct passwd *pw = getpwuid((uid_t) k->p_uid);
memset(p, 0, sizeof *p);
p->pid = k->p_pid;
p->ppid = k->p_ppid;
p->uid = k->p_uid;
if (pw != NULL)
snprintf(p->user, sizeof p->user, "%s", pw->pw_name);
else
snprintf(p->user, sizeof p->user, "%lu", p->uid);
snprintf(p->comm, sizeof p->comm, "%s", k->p_comm);
if (k->p_realstat == SZOMB || k->p_realstat == SDEAD)
p->state = 'Z';
else if (k->p_realstat == SSTOP)
p->state = 'T';
else if (k->p_realstat == SIDL)
p->state = 'I';
else
switch (k->p_stat) {
case LSRUN:
case LSONPROC:
p->state = 'R';
break;
case LSSLEEP:
p->state = 'S';
break;
case LSSTOP:
case LSSUSPENDED:
p->state = 'T';
break;
case LSZOMB:
p->state = 'Z';
break;
case LSIDL:
p->state = 'I';
break;
default:
p->state = '?';
}
p->nlwp = (int) k->p_nlwps;
p->rss = k->p_vm_rssize > 0 ?
(unsigned long long) k->p_vm_rssize * (unsigned long long) page : 0;
p->vsz = k->p_vm_vsize > 0 ?
(unsigned long long) k->p_vm_vsize * (unsigned long long) page : 0;
p->cpu_ms = (unsigned long long) k->p_rtime_sec * 1000ULL +
(unsigned long long) k->p_rtime_usec / 1000ULL;
}
free(kp);
*out = v;
*n = cnt;
return MCDE_SYS_OK;
}
/* ---- a file's comment: EXTATTR_NAMESPACE_USER, "mcde.comment" */
int
mcde_sys_file_comment_get_backend(const char *path, char *buf, size_t len)
{
ssize_t n;
buf[0] = '\0';
n = extattr_get_file(path, EXTATTR_NAMESPACE_USER, "mcde.comment", buf,
len - 1);
if (n < 0) {
if (errno == ENOATTR)
return MCDE_SYS_OK;
if (errno == ENOTSUP || errno == EOPNOTSUPP)
return mcde_sys_fail(MCDE_SYS_ENOTSUP, mcde_sys_msg(MSG_LX_NO_COMMENTS, "This file system keeps no comments."));
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_LX_COMMENT_READ, "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 (extattr_delete_file(path, EXTATTR_NAMESPACE_USER,
"mcde.comment") != 0 && errno != ENOATTR &&
errno != ENOTSUP)
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_LX_COMMENT_REMOVE, "Cannot remove the comment: %s."), strerror(errno));
return MCDE_SYS_OK;
}
if (extattr_set_file(path, EXTATTR_NAMESPACE_USER, "mcde.comment", text,
strlen(text)) < 0) {
if (errno == ENOTSUP || errno == EOPNOTSUPP)
return mcde_sys_fail(MCDE_SYS_ENOTSUP, mcde_sys_msg(MSG_LX_NO_COMMENTS, "This file system keeps no comments."));
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_LX_COMMENT_WRITE, "Cannot write the comment: %s."), strerror(errno));
}
return MCDE_SYS_OK;
}
/* ---- the immutable flag: chflags(2), UF_IMMUTABLE */
int
mcde_sys_file_locked_get_backend(const char *path, int *locked)
{
struct stat st;
*locked = 0;
if (stat(path, &st) != 0)
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_NB_READ2, "Cannot read %s: %s."), path,
strerror(errno));
*locked = (st.st_flags & UF_IMMUTABLE) != 0;
return MCDE_SYS_OK;
}
int
mcde_sys_file_locked_set_backend(const char *path, int locked)
{
struct stat st;
if (stat(path, &st) != 0)
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_NB_READ2, "Cannot read %s: %s."), path,
strerror(errno));
if (chflags(path, locked ? (st.st_flags | UF_IMMUTABLE) :
(st.st_flags & ~UF_IMMUTABLE)) != 0)
return mcde_sys_fail(MCDE_SYS_EPERM, locked ?
mcde_sys_msg(MSG_LX_LOCK_SET, "Cannot set the lock: %s.") :
mcde_sys_msg(MSG_LX_LOCK_CLEAR, "Cannot clear the lock: %s."),
strerror(errno));
return MCDE_SYS_OK;
}
/* ---- the computer's name: /etc/myname and hostname(1) (root) */
int
mcde_sys_hostname_set_backend(const char *name)
{
FILE *fp;
char *argv[3];
if ((fp = fopen("/etc/myname", "w")) == NULL)
return mcde_sys_fail(MCDE_SYS_EPERM, mcde_sys_msg(MSG_NB_MYNAME, "Cannot write /etc/myname: %s."), strerror(errno));
fprintf(fp, "%s\n", name);
fclose(fp);
argv[0] = (char *) "/bin/hostname";
argv[1] = (char *) name;
argv[2] = NULL;
return mcde_sys_run(argv);
}
/* ---- NTP: the base system's ntpd, "ntpd=YES" in rc.conf and the pool
* line of ntp.conf(5) */
#define NTP_CONF "/etc/ntp.conf"
static int
NtpServerGet(char *buf, size_t len)
{
FILE *fp;
char line[512];
if (buf == NULL || len == 0)
return MCDE_SYS_OK;
buf[0] = '\0';
if ((fp = fopen(NTP_CONF, "r")) == NULL)
return MCDE_SYS_OK;
while (fgets(line, sizeof line, fp) != NULL) {
char *p = line, *v = NULL;
size_t i = 0;
while (*p == ' ' || *p == '\t')
p++;
if (strncmp(p, "pool ", 5) == 0)
v = p + 5;
else if (strncmp(p, "server ", 7) == 0)
v = p + 7;
if (v == NULL)
continue;
while (*v == ' ' || *v == '\t')
v++;
while (*v != '\0' && !isspace((unsigned char) *v) &&
i + 1 < len)
buf[i++] = *v++;
buf[i] = '\0';
break;
}
fclose(fp);
return MCDE_SYS_OK;
}
int
mcde_sys_ntp_get_backend(int *on, char *server, size_t len)
{
char v[32];
*on = 0;
if (RcConfGet("ntpd", v, sizeof v))
*on = strcasecmp(v, "YES") == 0;
return NtpServerGet(server, len);
}
/* the pool line of ntp.conf: SERVERS before it stay, the new line goes
* where the first pool or server line was (at the end if there was none) */
static int
NtpConfSet(const char *server)
{
char line[512], tmp[] = "/etc/ntp.conf.mcdeXXXXXX";
FILE *in, *out;
int fd, have = 0, done = 0;
if ((in = fopen(NTP_CONF, "r")) == NULL)
in = NULL;
if ((fd = mkstemp(tmp)) < 0)
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_NB_NTP_TMP, "Cannot make a new ntp.conf: %s."), strerror(errno));
if ((out = fdopen(fd, "w")) == NULL) {
close(fd);
unlink(tmp);
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_NB_NTP_WRITE, "Cannot write ntp.conf."));
}
if (in != NULL) {
while (fgets(line, sizeof line, in) != NULL) {
char *p = line;
while (*p == ' ' || *p == '\t')
p++;
if (!done && (strncmp(p, "pool ", 5) == 0 ||
strncmp(p, "server ", 7) == 0)) {
fprintf(out, "pool %s iburst\n", server);
done = 1;
continue;
}
fputs(line, out);
}
fclose(in);
}
if (!done)
fprintf(out, "pool %s iburst\n", server);
if (fclose(out) != 0 || chmod(tmp, 0644) != 0 ||
rename(tmp, NTP_CONF) != 0) {
unlink(tmp);
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_NB_NTP_REPLACE, "Cannot replace ntp.conf: %s."), strerror(errno));
}
(void) have;
return MCDE_SYS_OK;
}
int
mcde_sys_ntp_set_backend(int on, const char *server)
{
char *argv[3];
int r;
if (RcConfSet("ntpd", on ? "YES" : "NO") != MCDE_SYS_OK)
return mcde_sys_error() != NULL ? MCDE_SYS_EFAIL : MCDE_SYS_EFAIL;
if (on && server != NULL && server[0] != '\0') {
if (NtpConfSet(server) != MCDE_SYS_OK)
return MCDE_SYS_EFAIL;
}
argv[0] = (char *) "/etc/rc.d/ntpd";
argv[1] = (char *) (on ? "restart" : "stop");
argv[2] = NULL;
r = mcde_sys_run(argv);
if (r != MCDE_SYS_OK && on)
return r;
return MCDE_SYS_OK;
}
/* ---- sharing: rc.conf and the rc.d scripts (rc.subr(8)); the servers of
* pkgsrc bring their scripts in share/examples/rc.d, copied to /etc/rc.d
* when first switched on, as PKG_RCD_SCRIPTS=YES would
* (docs/reference/sharing.txt) */
static const struct {
const char *vars[5]; /* rc.conf switches, the first one tells */
const char *scripts[5]; /* rc.d scripts, in start order */
const char *main; /* the one whose status tells "running" */
const char *binary; /* there when installed */
} services[MCDE_SHARE_COUNT] = {
[MCDE_SHARE_SSH] = { { "sshd" }, { "sshd" }, "sshd",
"/usr/sbin/sshd" },
[MCDE_SHARE_SMB] = { { "samba" }, { "samba" }, "samba",
MCDE_PKG_PREFIX "/sbin/smbd" },
/* rpcbind is switched on, never off: others may need it. statd
* and lockd share one script, nfslocking (src/etc/rc.d/nfslocking) */
[MCDE_SHARE_NFS] = { { "nfs_server", "mountd", "statd", "lockd",
"rpcbind" }, { "rpcbind", "mountd", "nfsd", "nfslocking" }, "nfsd",
"/usr/sbin/nfsd" },
[MCDE_SHARE_AFP] = { { "netatalk" }, { "netatalk" }, "netatalk",
MCDE_PKG_PREFIX "/sbin/netatalk" },
[MCDE_SHARE_APPLETALK] = { { "atalkd", "papd" }, { "atalkd", "papd" },
"atalkd", MCDE_PKG_PREFIX "/sbin/atalkd" },
};
static int
RcScript(const char *name, const char *how)
{
char path[128];
char *argv[3];
snprintf(path, sizeof path, "/etc/rc.d/%s", name);
if (access(path, X_OK) != 0)
return MCDE_SYS_ENOENT;
argv[0] = path;
argv[1] = (char *) how;
argv[2] = NULL;
return mcde_sys_run(argv);
}
/* a pkgsrc rc.d script into /etc/rc.d, if it is only an example yet */
static void
InstallScript(const char *name)
{
char from[160], to[128], buf[4096];
FILE *in, *out;
size_t n;
snprintf(to, sizeof to, "/etc/rc.d/%s", name);
snprintf(from, sizeof from, MCDE_PKG_PREFIX "/share/examples/rc.d/%s",
name);
if (access(to, F_OK) == 0 || (in = fopen(from, "r")) == NULL)
return;
if ((out = fopen(to, "w")) != NULL) {
while ((n = fread(buf, 1, sizeof buf, in)) > 0)
(void) fwrite(buf, 1, n, out);
(void) fchmod(fileno(out), 0555);
fclose(out);
}
fclose(in);
}
int
mcde_sys_service_state(McdeSysShareService s, McdeSysServiceState *st)
{
char cmd[256];
char *argv[4];
memset(st, 0, sizeof *st);
if ((int) s < 0 || s >= MCDE_SHARE_COUNT)
return mcde_sys_fail(MCDE_SYS_EINVAL, mcde_sys_msg(MSG_LX_NO_SERVICE, "No such service."));
st->installed = access(services[s].binary, X_OK) == 0;
if (!st->installed)
return MCDE_SYS_OK;
/* rc.subr reads rc.conf and the defaults as the boot does */
snprintf(cmd, sizeof cmd, ". /etc/rc.subr; load_rc_config %s; "
"checkyesno %s", services[s].vars[0], services[s].vars[0]);
argv[0] = "/bin/sh";
argv[1] = "-c";
argv[2] = cmd;
argv[3] = NULL;
st->enabled = mcde_sys_run(argv) == MCDE_SYS_OK;
st->running = RcScript(services[s].main, "onestatus") == MCDE_SYS_OK;
return MCDE_SYS_OK;
}
int
mcde_sys_service_set(McdeSysShareService s, int on)
{
int i, r = MCDE_SYS_OK;
if ((int) s < 0 || s >= MCDE_SHARE_COUNT)
return mcde_sys_fail(MCDE_SYS_EINVAL, mcde_sys_msg(MSG_LX_NO_SERVICE, "No such service."));
if (geteuid() != 0)
return mcde_sys_fail(MCDE_SYS_EPERM, mcde_sys_msg(MSG_LX_SERVICE_EPERM, "Only the administrator can switch a service."));
if (access(services[s].binary, X_OK) != 0)
return mcde_sys_fail(MCDE_SYS_ENOENT, mcde_sys_msg(MSG_NB_SERVER_MISSING, "The server is not installed (%s)."), services[s].binary);
for (i = 0; i < 5 && services[s].vars[i] != NULL; i++) {
/* rpcbind: on with NFS, left as it is when NFS goes off */
if (!on && strcmp(services[s].vars[i], "rpcbind") == 0)
continue;
if (RcConfSet(services[s].vars[i], on ? "YES" : "NO") !=
MCDE_SYS_OK)
return MCDE_SYS_EFAIL;
}
/* mountd does not start without /etc/exports (rc.d/mountd: "is not
* readable", measured): the file with the shares there are */
if (on && s == MCDE_SHARE_NFS && access("/etc/exports", F_OK) != 0) {
FILE *fp = fopen("/etc/exports", "w");
if (fp != NULL)
fclose(fp);
}
if (on) {
for (i = 0; i < 5 && services[s].scripts[i] != NULL; i++) {
InstallScript(services[s].scripts[i]);
if (RcScript(services[s].scripts[i], "onestatus") !=
MCDE_SYS_OK &&
RcScript(services[s].scripts[i], "start") !=
MCDE_SYS_OK)
r = mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_NB_DID_NOT_START, "%s did not start."), services[s].scripts[i]);
}
} else {
for (i = 4; i >= 0; i--)
if (services[s].scripts[i] != NULL &&
strcmp(services[s].scripts[i], "rpcbind") != 0)
(void) RcScript(services[s].scripts[i],
"onestop");
}
return r;
}
const char *
mcde_sys_exports_file(void)
{
return "/etc/exports";
}
const char *
mcde_sys_smb_conf(void)
{
return access(services[MCDE_SHARE_SMB].binary, X_OK) == 0 ?
MCDE_PKG_SYSCONFDIR "/samba/smb.conf" : NULL;
}
const char *
mcde_sys_afp_conf(void)
{
return access(services[MCDE_SHARE_AFP].binary, X_OK) == 0 ?
MCDE_PKG_SYSCONFDIR "/afp.conf" : NULL;
}
/* exports(5): the folder to every host, root mapped to nobody */
void
mcde_sys_export_line(const char *path, char *buf, size_t len)
{
snprintf(buf, len, "%s -maproot=nobody", path);
}
void
mcde_sys_shares_reload(void)
{
/* mountd reads /etc/exports again on reload (rc.d/mountd) */
if (RcScript("mountd", "onestatus") == MCDE_SYS_OK)
(void) RcScript("mountd", "reload");
if (RcScript("samba", "onestatus") == MCDE_SYS_OK)
(void) RcScript("samba", "restart");
if (RcScript("netatalk", "onestatus") == MCDE_SYS_OK)
(void) RcScript("netatalk", "restart");
}
/* ---- the network: DNS-SD through mdnsd (dns_sd.h, libdns_sd in base):
* one DNSServiceBrowse per kind, a DNSServiceResolve per service found,
* their sockets read with select(2) until the time is up
* (docs/reference/dns-sd.txt) */
#define MAX_RESOLVES 64
static const struct {
const char *type;
int kind;
} browseTypes[] = {
{ "_smb._tcp", MCDE_NET_HAS_SMB },
{ "_afpovertcp._tcp", MCDE_NET_HAS_AFP },
{ "_nfs._tcp", MCDE_NET_HAS_NFS },
{ "_ssh._tcp", MCDE_NET_HAS_SSH },
{ "_sftp-ssh._tcp", MCDE_NET_HAS_SSH },
{ "_workstation._tcp", MCDE_NET_HAS_ANY },
};
#define NTYPES (sizeof browseTypes / sizeof browseTypes[0])
typedef struct {
McdeSysNetHost *hosts;
size_t max;
int n;
DNSServiceRef res[MAX_RESOLVES];
int kind[MAX_RESOLVES];
char name[MAX_RESOLVES][128];
int nres;
} BrowseState;
static BrowseState *browse;
static void DNSSD_API
Resolved(DNSServiceRef ref, DNSServiceFlags flags, uint32_t ifindex,
DNSServiceErrorType err, const char *fullname, const char *hosttarget,
uint16_t port, uint16_t txtLen, const unsigned char *txt, void *ctx)
{
int i = (int) (intptr_t) ctx;
(void) ref; (void) flags; (void) ifindex; (void) fullname;
(void) port; (void) txtLen; (void) txt;
if (err != kDNSServiceErr_NoError || browse == NULL || i < 0 ||
i >= browse->nres)
return;
browse->n = mcde_sys_net_add(browse->hosts, browse->n, browse->max,
browse->name[i], hosttarget, browse->kind[i]);
}
static void DNSSD_API
Found(DNSServiceRef ref, DNSServiceFlags flags, uint32_t ifindex,
DNSServiceErrorType err, const char *name, const char *regtype,
const char *domain, void *ctx)
{
int kind = (int) (intptr_t) ctx, i;
(void) ref;
if (err != kDNSServiceErr_NoError || !(flags & kDNSServiceFlagsAdd) ||
browse == NULL || browse->nres >= MAX_RESOLVES)
return;
i = browse->nres;
browse->kind[i] = kind;
snprintf(browse->name[i], sizeof browse->name[i], "%s", name);
if (DNSServiceResolve(&browse->res[i], 0, ifindex, name, regtype,
domain, Resolved, (void *) (intptr_t) i) == kDNSServiceErr_NoError)
browse->nres++;
}
int
mcde_sys_net_browse(McdeSysNetHost *hosts, size_t max, int timeout_ms)
{
static BrowseState st;
DNSServiceRef refs[NTYPES];
struct timeval end, now;
size_t t;
int i, started = 0;
memset(&st, 0, sizeof st);
st.hosts = hosts;
st.max = max;
browse = &st;
for (t = 0; t < NTYPES; t++) {
refs[t] = NULL;
if (DNSServiceBrowse(&refs[t], 0, 0, browseTypes[t].type, NULL,
Found, (void *) (intptr_t) browseTypes[t].kind) ==
kDNSServiceErr_NoError)
started++;
else
refs[t] = NULL;
}
if (started == 0) {
browse = NULL;
return mcde_sys_fail(MCDE_SYS_ENOTSUP, mcde_sys_msg(MSG_NB_NO_MDNSD, "The computers on the network cannot be looked for: mdnsd does not run (mdnsd=YES in rc.conf)."));
}
gettimeofday(&end, NULL);
end.tv_sec += timeout_ms / 1000;
end.tv_usec += (timeout_ms % 1000) * 1000;
if (end.tv_usec >= 1000000) {
end.tv_sec++;
end.tv_usec -= 1000000;
}
for (;;) {
fd_set fds;
struct timeval left;
int maxfd = -1;
gettimeofday(&now, NULL);
left.tv_sec = end.tv_sec - now.tv_sec;
left.tv_usec = end.tv_usec - now.tv_usec;
if (left.tv_usec < 0) {
left.tv_sec--;
left.tv_usec += 1000000;
}
if (left.tv_sec < 0)
break;
FD_ZERO(&fds);
for (t = 0; t < NTYPES; t++)
if (refs[t] != NULL) {
int fd = DNSServiceRefSockFD(refs[t]);
FD_SET(fd, &fds);
if (fd > maxfd)
maxfd = fd;
}
for (i = 0; i < st.nres; i++) {
int fd = DNSServiceRefSockFD(st.res[i]);
FD_SET(fd, &fds);
if (fd > maxfd)
maxfd = fd;
}
if (select(maxfd + 1, &fds, NULL, NULL, &left) <= 0)
break;
for (t = 0; t < NTYPES; t++)
if (refs[t] != NULL &&
FD_ISSET(DNSServiceRefSockFD(refs[t]), &fds))
(void) DNSServiceProcessResult(refs[t]);
for (i = 0; i < st.nres; i++)
if (FD_ISSET(DNSServiceRefSockFD(st.res[i]), &fds))
(void) DNSServiceProcessResult(st.res[i]);
}
for (t = 0; t < NTYPES; t++)
if (refs[t] != NULL)
DNSServiceRefDeallocate(refs[t]);
for (i = 0; i < st.nres; i++)
DNSServiceRefDeallocate(st.res[i]);
browse = NULL;
return st.n;
}
/* ---- security: swap encryption, cgd, the packet filter ------------------ */
#define SYSCTL_CONF "/etc/sysctl.conf"
#define CGD_CONF "/etc/cgd/cgd.conf"
#define NPF_CONF "/etc/npf.conf"
int
mcde_sys_swap_encrypt_get(int *on)
{
char buf[32], *argv[4];
if (on == NULL)
return mcde_sys_fail(MCDE_SYS_EINVAL, mcde_sys_msg(MSG_NB_NO_VALUE_ROOM, "There is no place for the value."));
argv[0] = (char *) "/sbin/sysctl";
argv[1] = (char *) "-n";
argv[2] = (char *) "vm.swap_encrypt";
argv[3] = NULL;
if (mcde_sys_capture(argv, buf, sizeof buf) != MCDE_SYS_OK)
return mcde_sys_fail(MCDE_SYS_ENOTSUP, mcde_sys_msg(MSG_NB_SWAP_UNKNOWN, "The system does not say whether memory is encrypted in swap."));
*on = atoi(buf) != 0;
return MCDE_SYS_OK;
}
int
mcde_sys_swap_encrypt_set(int on)
{
char val[32], *argv[4];
if (geteuid() != 0)
return mcde_sys_fail(MCDE_SYS_EPERM, mcde_sys_msg(MSG_NB_SWAP_EPERM, "Secure virtual memory needs the administrator."));
(void)snprintf(val, sizeof val, "vm.swap_encrypt=%d", on ? 1 : 0);
argv[0] = (char *) "/sbin/sysctl";
argv[1] = (char *) "-w";
argv[2] = val;
argv[3] = NULL;
if (mcde_sys_run(argv) != MCDE_SYS_OK)
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_NB_SWAP_SYSCTL, "sysctl(8) did not take vm.swap_encrypt."));
/* and after the next start: /etc/sysctl.conf */
return KeySet(SYSCTL_CONF, "vm.swap_encrypt", on ? "1" : "0");
}
int
mcde_sys_cgd_volumes(char (*vols)[MCDE_SYS_CGD_ENTRY_LEN], size_t max)
{
char line[256];
FILE *fp = fopen(CGD_CONF, "r");
int n = 0;
if (fp == NULL)
return mcde_sys_fail(MCDE_SYS_ENOTSUP, mcde_sys_msg(MSG_NB_NO_CGD, "This system has no cgd(4) configuration (%s)."), CGD_CONF);
while (vols != NULL && n < (int)max &&
fgets(line, sizeof line, fp) != NULL) {
char *p = line;
line[strcspn(line, "\r\n")] = '\0';
while (*p == ' ' || *p == '\t')
p++;
if (*p == '\0' || *p == '#')
continue;
(void)snprintf(vols[n], MCDE_SYS_CGD_ENTRY_LEN, "%s", p);
n++;
}
fclose(fp);
return n;
}
int
mcde_sys_firewall_get(int *on, char *conf, size_t len)
{
char v[32];
if (on == NULL || conf == NULL)
return mcde_sys_fail(MCDE_SYS_EINVAL, mcde_sys_msg(MSG_NB_NO_STATE_ROOM, "There is no place for the state."));
if (access("/sbin/npfctl", X_OK) != 0)
return mcde_sys_fail(MCDE_SYS_ENOTSUP, mcde_sys_msg(MSG_NB_NO_NPF, "This system has no npf(7) (/sbin/npfctl)."));
(void)snprintf(conf, len, "%s", NPF_CONF);
/* rc.conf's npf=YES starts it at boot (rc.d/npf reads it) */
*on = RcConfGet("npf", v, sizeof v) && strcasecmp(v, "YES") == 0;
return MCDE_SYS_OK;
}
/* ---- the load of the computer. The CPU ticks: kern.cp_time given room for
* every processor returns CPUSTATES counters for each, in the order of the
* CP_ constants (sys/kern/init_sysctl.c, sysctl_kern_cptime: "alternately, you
* can pass an additional mib number and get cp_time for that particular
* processor"; a buffer of the size of one processor's counters gets the sum).
* The memory: vm.uvmexp2, struct uvmexp_sysctl in pages, as top(1) reads it
* (src/external/bsd/top/dist/machine/m_netbsd.c). */
int
mcde_sys_cpu_times_backend(McdeSysCpu **out, size_t *n)
{
int mib[2], ncpu = 0, i;
size_t len = sizeof ncpu;
uint64_t *t;
McdeSysCpu *v;
mib[0] = CTL_HW;
mib[1] = HW_NCPU;
if (sysctl(mib, 2, &ncpu, &len, NULL, 0) != 0 || ncpu < 1)
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_NB_NO_NCPU, "The system tells no number of processors."));
len = (size_t) ncpu * CPUSTATES * sizeof(uint64_t);
if ((t = malloc(len)) == NULL || (v = calloc((size_t) ncpu,
sizeof *v)) == NULL) {
free(t);
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_NO_MEMORY, "Out of memory."));
}
mib[0] = CTL_KERN;
mib[1] = KERN_CP_TIME;
if (sysctl(mib, 2, t, &len, NULL, 0) != 0 ||
len != (size_t) ncpu * CPUSTATES * sizeof(uint64_t)) {
free(t);
free(v);
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_NB_NO_CPUTIMES, "The system tells no CPU times: %s."), strerror(errno));
}
for (i = 0; i < ncpu; i++) {
v[i].user = t[i * CPUSTATES + CP_USER];
v[i].nice = t[i * CPUSTATES + CP_NICE];
v[i].system = t[i * CPUSTATES + CP_SYS];
v[i].idle = t[i * CPUSTATES + CP_IDLE];
v[i].other = t[i * CPUSTATES + CP_INTR];
}
free(t);
*out = v;
*n = (size_t) ncpu;
return MCDE_SYS_OK;
}
int
mcde_sys_memory_backend(McdeSysMemory *m)
{
struct uvmexp_sysctl u;
int mib[2];
size_t len = sizeof u;
unsigned long long ps;
mib[0] = CTL_VM;
mib[1] = VM_UVMEXP2;
if (sysctl(mib, 2, &u, &len, NULL, 0) != 0)
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_NB_NO_MEMORY, "The system tells no memory: %s."), strerror(errno));
ps = (unsigned long long) u.pagesize;
m->total = (unsigned long long) u.npages * ps;
m->free = (unsigned long long) u.free * ps;
/* what is only a copy of a file or of a program's text can be dropped */
m->cached = ((unsigned long long) u.filepages +
(unsigned long long) u.execpages) * ps;
m->swap_total = (unsigned long long) u.swpages * ps;
m->swap_used = (unsigned long long) u.swpginuse * ps;
return MCDE_SYS_OK;
}
/* The network counters: the link-level address of each interface carries its
* struct if_data (getifaddrs(3); net/if.h). The disks: sysctl hw.iostats, an
* array of struct io_sysctl, asked for its size first and then for the array
* (usr.bin/vmstat/drvstats.c); type IOSTAT_DISK is a disk, rbytes and wbytes
* what was read and written, rxfer and wxfer the transfers. */
int
mcde_sys_net_io_backend(McdeSysNetIo **out, size_t *n)
{
struct ifaddrs *ifap, *ifa;
McdeSysNetIo *v = NULL, *nv;
size_t cnt = 0, cap = 0;
if (getifaddrs(&ifap) != 0)
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_NB_NO_IFACES, "The system tells no interfaces: %s."), strerror(errno));
for (ifa = ifap; ifa != NULL; ifa = ifa->ifa_next) {
const struct if_data *d;
if (ifa->ifa_addr == NULL || ifa->ifa_addr->sa_family !=
AF_LINK || ifa->ifa_data == NULL)
continue;
d = (const struct if_data *) ifa->ifa_data;
if (cnt == cap) {
cap = cap != 0 ? cap * 2 : 8;
if ((nv = realloc(v, cap * sizeof *v)) == NULL) {
free(v);
freeifaddrs(ifap);
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_NO_MEMORY, "Out of memory."));
}
v = nv;
}
memset(&v[cnt], 0, sizeof v[cnt]);
snprintf(v[cnt].name, sizeof v[cnt].name, "%s", ifa->ifa_name);
v[cnt].rx_bytes = d->ifi_ibytes;
v[cnt].tx_bytes = d->ifi_obytes;
v[cnt].rx_packets = d->ifi_ipackets;
v[cnt].tx_packets = d->ifi_opackets;
cnt++;
}
freeifaddrs(ifap);
*out = v;
*n = cnt;
return MCDE_SYS_OK;
}
int
mcde_sys_disk_io_backend(McdeSysDiskIo **out, size_t *n)
{
int mib[3];
size_t size = 0, count, i, cnt = 0;
struct io_sysctl *drives;
McdeSysDiskIo *v;
mib[0] = CTL_HW;
mib[1] = HW_IOSTATS;
mib[2] = sizeof(struct io_sysctl);
if (sysctl(mib, 3, NULL, &size, NULL, 0) == -1)
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_NB_NO_DISKCOUNTERS, "The system tells no disk counters: %s."), strerror(errno));
if (size == 0)
return MCDE_SYS_OK;
/* a drive may arrive between the two calls: room for a few more */
size += 4 * sizeof(struct io_sysctl);
if ((drives = malloc(size)) == NULL)
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_NO_MEMORY, "Out of memory."));
if (sysctl(mib, 3, drives, &size, NULL, 0) == -1) {
free(drives);
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_NB_NO_DISKCOUNTERS, "The system tells no disk counters: %s."), strerror(errno));
}
count = size / sizeof(struct io_sysctl);
if ((v = calloc(count != 0 ? count : 1, sizeof *v)) == NULL) {
free(drives);
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_NO_MEMORY, "Out of memory."));
}
for (i = 0; i < count; i++) {
if (drives[i].type != IOSTAT_DISK)
continue;
snprintf(v[cnt].name, sizeof v[cnt].name, "%s", drives[i].name);
v[cnt].read_bytes = drives[i].rbytes;
v[cnt].write_bytes = drives[i].wbytes;
v[cnt].read_ops = drives[i].rxfer;
v[cnt].write_ops = drives[i].wxfer;
cnt++;
}
free(drives);
*out = v;
*n = cnt;
return MCDE_SYS_OK;
}
/* events.c: one queued autoconfig event from drvctl(4). The property list
* of DRVGETEVENT carries "event" ("device-attach" or "device-detach"),
* "device" and "parent" (devpubd(8) reads it the same way); the line the
* caller gets is "device-attach sd0". A descriptor opened O_NONBLOCK says
* EWOULDBLOCK while the queue is empty. */
int
mcde_sys_disk_event_read_backend(int fd, char *buf, size_t len)
{
prop_dictionary_t ev;
const char *event = NULL, *device = NULL;
if (prop_dictionary_recv_ioctl(fd, DRVGETEVENT, &ev) != 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK)
return 0;
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_NB_DRVGETEVENT, "DRVGETEVENT: %s."),
strerror(errno));
}
(void) prop_dictionary_get_string(ev, "event", &event);
(void) prop_dictionary_get_string(ev, "device", &device);
snprintf(buf, len, "%s %s", event != NULL ? event : "event",
device != NULL ? device : "");
prop_object_release(ev);
return 1;
}