67 lines
2.0 KiB
Bash
Executable File
67 lines
2.0 KiB
Bash
Executable File
#!/usr/bin/env bash
|
|
#
|
|
# bt-netconfig - apply Ethernet configuration via NetworkManager.
|
|
#
|
|
# Usage:
|
|
# bt-netconfig <iface> dhcp
|
|
# bt-netconfig <iface> static <address> <prefix> [gateway] [dns_csv]
|
|
#
|
|
# Intended to be invoked through sudo by the (unprivileged) web configurator.
|
|
# Keep this script tightly scoped: it only touches the connection bound to the
|
|
# requested ethernet interface.
|
|
set -euo pipefail
|
|
|
|
err() { echo "bt-netconfig: $*" >&2; exit 1; }
|
|
|
|
[ "$#" -ge 2 ] || err "usage: bt-netconfig <iface> <dhcp|static> ..."
|
|
|
|
IFACE="$1"
|
|
MODE="$2"
|
|
|
|
# Validate interface name (defence in depth; the web side validates too).
|
|
[[ "$IFACE" =~ ^[A-Za-z0-9_.:-]{1,32}$ ]] || err "invalid interface name"
|
|
|
|
command -v nmcli >/dev/null 2>&1 || err "nmcli not found"
|
|
|
|
# Resolve (or create) a connection profile bound to this interface.
|
|
CON="$(nmcli -t -f GENERAL.CONNECTION device show "$IFACE" 2>/dev/null \
|
|
| sed 's/^GENERAL.CONNECTION://')"
|
|
|
|
if [ -z "$CON" ] || [ "$CON" = "--" ]; then
|
|
CON="buttontask-$IFACE"
|
|
if ! nmcli -t -f NAME connection show | grep -Fxq "$CON"; then
|
|
nmcli connection add type ethernet ifname "$IFACE" con-name "$CON" >/dev/null
|
|
fi
|
|
fi
|
|
|
|
case "$MODE" in
|
|
dhcp)
|
|
nmcli connection modify "$CON" \
|
|
ipv4.method auto \
|
|
ipv4.addresses "" \
|
|
ipv4.gateway "" \
|
|
ipv4.dns ""
|
|
;;
|
|
static)
|
|
[ "$#" -ge 4 ] || err "static requires <address> <prefix>"
|
|
ADDR="$3"
|
|
PREFIX="$4"
|
|
GW="${5:-}"
|
|
DNS="${6:-}"
|
|
[[ "$PREFIX" =~ ^[0-9]{1,2}$ ]] && [ "$PREFIX" -ge 1 ] && [ "$PREFIX" -le 32 ] \
|
|
|| err "invalid prefix"
|
|
nmcli connection modify "$CON" \
|
|
ipv4.method manual \
|
|
ipv4.addresses "${ADDR}/${PREFIX}" \
|
|
ipv4.gateway "$GW" \
|
|
ipv4.dns "$DNS"
|
|
;;
|
|
*)
|
|
err "mode must be dhcp or static"
|
|
;;
|
|
esac
|
|
|
|
# Re-apply the connection so changes take effect.
|
|
nmcli connection up "$CON" >/dev/null
|
|
echo "applied $MODE on $IFACE ($CON)"
|