Files
mcde/lib/McdeSys/common.c
T
lotherkandClaude Opus 5.5 385f366abd mcde: McdeSys finds the computers on the network and connects to them
mcde_sys_net_browse lists the computers that announce SMB, AFP, NFS, SSH
or just themselves by DNS-SD: on NetBSD through mdnsd with dns_sd.h from
base (DNSServiceBrowse per type, DNSServiceResolve per service, select
until the time is up; docs/reference/dns-sd.txt), on Linux with
avahi-browse -atrpk (its \DDD escapes decoded).  mcde_sys_net_shares
lists NFS exports (showmount -e) and SMB shares (smbclient -g -N -L);
mcde_sys_net_mount connects sftp:// (sshfs, a password on its standard
input), nfs:// (mount_nfs / mount.nfs) and afp:// (afpfs-ng's mount_afp)
to a folder; mcde_sys_net_unmount (fusermount -u, else umount).  Host
and user names are checked before they reach a command line.

mcde_sys_capture_limited ends a child after a time: showmount waited
minutes for an rpcbind that was not there (measured in the build VM);
the share lists wait 8 seconds.

Measured: on the Linux host 4 computers with their services (KITT,
N95 with SMB; two laptops with SMB and SSH), the local SMB share and NFS
export listed, a host name with ';' refused.  In the build VM: it builds
with -ldns_sd; without mdnsd a clear message; with mdnsd started the
browse ran and found none (qemu's user network carries no multicast);
showmount gave up after 8 s.  Mounting is not measured yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 12:47:12 +00:00

477 lines
12 KiB
C

/*
* common.c -- MCDE: the parts of McdeSys that are the same on every system
*
* Copyright (c) 2026 The Makronix project. GNU LGPL 2.0 or later, as CDE.
*
* POSIX only: the error text, running a system tool, and the fields of
* McdeSysInfo that uname(3), sysconf(3), statvfs(3) and gethostname(3) give.
* What differs between systems is in the backend (netbsd.c, linux.c), behind
* the two functions in private.h.
*/
#define _POSIX_C_SOURCE 200809L
/* symlink(2), for the time zone: NetBSD declares it only for X/Open 500 and
* up or _NETBSD_SOURCE (src/include/unistd.h:249); X/Open 700 is POSIX 2008
* with it, on NetBSD and on glibc alike */
#define _XOPEN_SOURCE 700
#include <errno.h>
#include <limits.h>
#include <stdlib.h>
#include <fcntl.h>
#include <poll.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/statvfs.h>
#include <sys/types.h>
#include <sys/utsname.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#include <Mcde/McdeSys.h>
#include "private.h"
static char lastError[256] = "";
const char *
mcde_sys_error(void)
{
return lastError;
}
int
mcde_sys_fail(int status, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vsnprintf(lastError, sizeof lastError, fmt, ap);
va_end(ap);
return status;
}
/* A program that ignores SIGCHLD (to have no zombies) gets no exit status
* from waitpid(2) -- POSIX: the children are reaped at once. While McdeSys
* waits for a tool, SIGCHLD is the default; the caller's way comes back. */
static void
ChildSignal(struct sigaction *saved, int restore)
{
struct sigaction dfl;
if (restore) {
(void) sigaction(SIGCHLD, saved, NULL);
return;
}
memset(&dfl, 0, sizeof dfl);
dfl.sa_handler = SIG_DFL;
sigemptyset(&dfl.sa_mask);
(void) sigaction(SIGCHLD, &dfl, saved);
}
int
mcde_sys_run(char *const argv[])
{
struct sigaction saved;
pid_t pid;
int st;
if (access(argv[0], X_OK) != 0)
return mcde_sys_fail(MCDE_SYS_ENOTSUP, "%s is not there.",
argv[0]);
ChildSignal(&saved, 0);
pid = fork();
if (pid < 0) {
ChildSignal(&saved, 1);
return mcde_sys_fail(MCDE_SYS_EFAIL, "Cannot start %s: %s.",
argv[0], strerror(errno));
}
if (pid == 0) {
execv(argv[0], argv);
_exit(127);
}
while (waitpid(pid, &st, 0) < 0)
if (errno != EINTR) {
ChildSignal(&saved, 1);
return mcde_sys_fail(MCDE_SYS_EFAIL, "%s: %s.", argv[0],
strerror(errno));
}
ChildSignal(&saved, 1);
if (WIFEXITED(st) && WEXITSTATUS(st) == 0)
return MCDE_SYS_OK;
return mcde_sys_fail(MCDE_SYS_EFAIL, "%s did not succeed (status %d).",
argv[0], WIFEXITED(st) ? WEXITSTATUS(st) : -1);
}
int
mcde_sys_run_input(char *const argv[], const char *input)
{
struct sigaction saved;
size_t len = strlen(input), done = 0;
int fd[2], st = -1;
ssize_t w;
pid_t pid;
if (access(argv[0], X_OK) != 0)
return mcde_sys_fail(MCDE_SYS_ENOTSUP, "%s is not there.",
argv[0]);
if (pipe(fd) != 0)
return mcde_sys_fail(MCDE_SYS_EFAIL, "No pipe: %s.",
strerror(errno));
ChildSignal(&saved, 0);
pid = fork();
if (pid < 0) {
ChildSignal(&saved, 1);
close(fd[0]);
close(fd[1]);
return mcde_sys_fail(MCDE_SYS_EFAIL, "Cannot start %s: %s.",
argv[0], strerror(errno));
}
if (pid == 0) {
dup2(fd[0], 0);
close(fd[0]);
close(fd[1]);
execv(argv[0], argv);
_exit(127);
}
close(fd[0]);
/* a secret goes through the pipe, never on a command line (ps(1)) */
while (done < len) {
w = write(fd[1], input + done, len - done);
if (w < 0 && errno == EINTR)
continue;
if (w <= 0)
break;
done += (size_t) w;
}
close(fd[1]);
while (waitpid(pid, &st, 0) < 0)
if (errno != EINTR)
break;
ChildSignal(&saved, 1);
if (st != -1 && WIFEXITED(st) && WEXITSTATUS(st) == 0)
return MCDE_SYS_OK;
return mcde_sys_fail(MCDE_SYS_EFAIL, "%s did not succeed (status %d).",
argv[0], st != -1 && WIFEXITED(st) ? WEXITSTATUS(st) : -1);
}
const char *
mcde_sys_which(const char *const *paths)
{
for (; *paths != NULL; paths++)
if (access(*paths, X_OK) == 0)
return *paths;
return NULL;
}
/* SECONDS > 0: the child is ended when it takes longer (a tool that asks
* the network -- showmount waited minutes for an rpcbind that was not
* there, measured) */
static int
Capture(char *const argv[], char *buf, size_t len, int seconds)
{
struct sigaction saved;
int fd[2], st, nul, late = 0;
size_t got = 0;
ssize_t r;
pid_t pid;
time_t end = seconds > 0 ? time(NULL) + seconds : 0;
buf[0] = '\0';
if (access(argv[0], X_OK) != 0)
return mcde_sys_fail(MCDE_SYS_ENOTSUP, "%s is not there.",
argv[0]);
if (pipe(fd) != 0)
return mcde_sys_fail(MCDE_SYS_EFAIL, "No pipe: %s.",
strerror(errno));
ChildSignal(&saved, 0);
pid = fork();
if (pid < 0) {
ChildSignal(&saved, 1);
close(fd[0]);
close(fd[1]);
return mcde_sys_fail(MCDE_SYS_EFAIL, "Cannot start %s: %s.",
argv[0], strerror(errno));
}
if (pid == 0) {
dup2(fd[1], 1);
if ((nul = open("/dev/null", O_WRONLY)) >= 0)
dup2(nul, 2);
close(fd[0]);
close(fd[1]);
execv(argv[0], argv);
_exit(127);
}
close(fd[1]);
/* read to the end, keep what fits: a child left with a full pipe would
* never exit, and waitpid would wait for it for ever */
for (;;) {
char scratch[512];
if (end != 0) {
struct pollfd pfd;
time_t left = end - time(NULL);
int pr;
pfd.fd = fd[0];
pfd.events = POLLIN;
pr = left > 0 ? poll(&pfd, 1, (int) left * 1000) : 0;
if (pr < 0 && errno == EINTR)
continue;
if (pr <= 0) {
late = 1;
kill(pid, SIGKILL);
break;
}
}
if (got + 1 < len)
r = read(fd[0], buf + got, len - 1 - got);
else
r = read(fd[0], scratch, sizeof scratch);
if (r < 0 && errno == EINTR)
continue;
if (r <= 0)
break;
if (got + 1 < len)
got += (size_t) r;
}
buf[got] = '\0';
close(fd[0]);
st = -1;
while (waitpid(pid, &st, 0) < 0)
if (errno != EINTR)
break;
ChildSignal(&saved, 1);
if (late)
return mcde_sys_fail(MCDE_SYS_EFAIL, "%s did not answer within "
"%d seconds.", argv[0], seconds);
if (st != -1 && WIFEXITED(st) && WEXITSTATUS(st) == 0)
return MCDE_SYS_OK;
return mcde_sys_fail(MCDE_SYS_EFAIL, "%s did not succeed (status %d).",
argv[0], WIFEXITED(st) ? WEXITSTATUS(st) : -1);
}
int
mcde_sys_capture(char *const argv[], char *buf, size_t len)
{
return Capture(argv, buf, len, 0);
}
int
mcde_sys_capture_limited(char *const argv[], char *buf, size_t len,
int seconds)
{
return Capture(argv, buf, len, seconds);
}
/* the first line of FILE that starts with KEY, the rest of it in BUF */
int
mcde_sys_file_value(const char *file, const char *key, char *buf, size_t len)
{
char line[512];
size_t k = strlen(key);
FILE *fp = fopen(file, "r");
int found = 0;
if (fp == NULL)
return 0;
while (!found && fgets(line, sizeof line, fp) != NULL) {
char *v, *e;
if (strncmp(line, key, k) != 0)
continue;
v = line + k;
while (*v == ' ' || *v == '\t' || *v == ':' || *v == '=' ||
*v == '"')
v++;
e = v + strlen(v);
while (e > v && (e[-1] == '\n' || e[-1] == '"' ||
e[-1] == ' ' || e[-1] == '\t'))
*--e = '\0';
snprintf(buf, len, "%s", v);
found = 1;
}
fclose(fp);
return found;
}
int
mcde_sys_hostname_get(char *name, size_t len)
{
if (gethostname(name, len) != 0)
return mcde_sys_fail(MCDE_SYS_EFAIL, "No host name: %s.",
strerror(errno));
name[len - 1] = '\0';
return MCDE_SYS_OK;
}
int
mcde_sys_info(McdeSysInfo *info)
{
struct utsname u;
struct statvfs vfs;
long pages = -1, pagesize = -1;
memset(info, 0, sizeof *info);
if (uname(&u) == 0) {
snprintf(info->kernel, sizeof info->kernel, "%s %s", u.sysname,
u.release);
snprintf(info->system, sizeof info->system, "%s", u.sysname);
snprintf(info->version, sizeof info->version, "%s", u.release);
snprintf(info->model, sizeof info->model, "%s", u.machine);
}
(void) mcde_sys_hostname_get(info->hostname, sizeof info->hostname);
#ifdef _SC_NPROCESSORS_ONLN
info->cpus = (int) sysconf(_SC_NPROCESSORS_ONLN);
#endif
#ifdef _SC_PHYS_PAGES
pages = sysconf(_SC_PHYS_PAGES);
#endif
pagesize = sysconf(_SC_PAGESIZE);
if (pages > 0 && pagesize > 0)
info->memory = (unsigned long long) pages *
(unsigned long long) pagesize;
if (statvfs("/", &vfs) == 0) {
info->diskSize = (unsigned long long) vfs.f_blocks * vfs.f_frsize;
info->diskFree = (unsigned long long) vfs.f_bavail * vfs.f_frsize;
}
mcde_sys_info_backend(info);
return MCDE_SYS_OK;
}
/* ---- the time zone: /etc/localtime, a link into the zoneinfo directory
* (src/usr.sbin/sysinst/util.c makes it so: unlink, symlink); the zones of
* zone1970.tab (tzfile(5), the tz database's own list) */
#define ZONEINFO "/usr/share/zoneinfo"
#define LOCALTIME "/etc/localtime"
int
mcde_sys_timezone_get(char *zone, size_t len)
{
char target[PATH_MAX];
ssize_t n = readlink(LOCALTIME, target, sizeof target - 1);
const char *z;
snprintf(zone, len, "UTC");
if (n <= 0)
return MCDE_SYS_OK;
target[n] = '\0';
if ((z = strstr(target, "zoneinfo/")) != NULL)
snprintf(zone, len, "%s", z + strlen("zoneinfo/"));
return MCDE_SYS_OK;
}
static int
ZoneCompare(const void *a, const void *b)
{
return strcmp((const char *) a, (const char *) b);
}
int
mcde_sys_timezones(char (*zones)[MCDE_SYS_ZONE_LEN], size_t max)
{
FILE *fp = fopen(ZONEINFO "/zone1970.tab", "r");
char line[512];
size_t n = 0;
if (fp == NULL && (fp = fopen(ZONEINFO "/zone.tab", "r")) == NULL)
return mcde_sys_fail(MCDE_SYS_ENOENT, "No list of time zones "
"in %s.", ZONEINFO);
/* CODES <tab> COORDINATES <tab> TZ [<tab> COMMENTS] */
while (n < max && fgets(line, sizeof line, fp) != NULL) {
char *f, *last = NULL;
if (line[0] == '#' || strtok_r(line, "\t\n", &last) == NULL ||
strtok_r(NULL, "\t\n", &last) == NULL ||
(f = strtok_r(NULL, "\t\n", &last)) == NULL ||
strlen(f) >= MCDE_SYS_ZONE_LEN)
continue;
snprintf(zones[n++], MCDE_SYS_ZONE_LEN, "%s", f);
}
fclose(fp);
if (n < max)
snprintf(zones[n++], MCDE_SYS_ZONE_LEN, "UTC");
qsort(zones, n, sizeof zones[0], ZoneCompare);
return (int) n;
}
int
mcde_sys_timezone_set(const char *zone)
{
char target[PATH_MAX], tmp[64];
struct stat st;
FILE *fp;
if (zone == NULL || zone[0] == '\0' || zone[0] == '/' ||
strstr(zone, "..") != NULL ||
strlen(zone) >= MCDE_SYS_ZONE_LEN)
return mcde_sys_fail(MCDE_SYS_EINVAL, "\"%s\" is no time zone.",
zone != NULL ? zone : "");
snprintf(target, sizeof target, ZONEINFO "/%s", zone);
if (stat(target, &st) != 0 || !S_ISREG(st.st_mode))
return mcde_sys_fail(MCDE_SYS_ENOENT, "There is no time zone "
"\"%s\".", zone);
if (geteuid() != 0)
return mcde_sys_fail(MCDE_SYS_EPERM, "Only the administrator "
"can change the time zone.");
/* a new link beside the old one, renamed over it: /etc/localtime is
* never missing (sysinst unlinks first, at install time) */
snprintf(tmp, sizeof tmp, LOCALTIME ".%ld", (long) getpid());
(void) unlink(tmp);
if (symlink(target, tmp) != 0)
return mcde_sys_fail(MCDE_SYS_EFAIL, "Cannot link %s: %s.", tmp,
strerror(errno));
if (rename(tmp, LOCALTIME) != 0) {
int e = errno;
(void) unlink(tmp);
return mcde_sys_fail(MCDE_SYS_EFAIL, "Cannot replace %s: %s.",
LOCALTIME, strerror(e));
}
/* Debian keeps the name in /etc/timezone as well; only where it is */
if (stat("/etc/timezone", &st) == 0 &&
(fp = fopen("/etc/timezone", "w")) != NULL) {
fprintf(fp, "%s\n", zone);
fclose(fp);
}
return MCDE_SYS_OK;
}
/* ---- a process's command line: the backend gives the arguments, NUL
* separated (mcde_sys_process_args); here they are quoted for sh(1) */
int
mcde_sys_process_command(pid_t pid, char *buf, size_t len)
{
static char args[8192];
size_t n = 0, i;
int got = mcde_sys_process_args(pid, args, sizeof args);
if (got <= 0 || len < 3)
return mcde_sys_fail(MCDE_SYS_ENOENT, "No command line for "
"process %ld.", (long) pid);
for (i = 0; i < (size_t) got && n + 6 < len; ) {
const char *a = args + i;
size_t al = strlen(a), k;
if (n > 0)
buf[n++] = ' ';
buf[n++] = '\'';
for (k = 0; k < al && n + 6 < len; k++) {
if (a[k] == '\'') {
/* ' -> '\'' */
memcpy(buf + n, "'\\''", 4);
n += 4;
} else
buf[n++] = a[k];
}
buf[n++] = '\'';
i += al + 1;
}
buf[n] = '\0';
return MCDE_SYS_OK;
}