Files
mcde/lib/McdeSys/linux.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

742 lines
21 KiB
C

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