diff --git a/install.sh b/install.sh new file mode 100644 index 0000000..911be64 --- /dev/null +++ b/install.sh @@ -0,0 +1,629 @@ +#!/usr/bin/env bash +#============================================================================== +# Zoraxy DHCP Server — All-in-One Installer +# Installs dnsmasq + NAT/routing + dhcp-lease-manager Zoraxy plugin +# +# Usage: curl -sSL https://git.lohmar.co.uk/cclohmar/zoraxy-dhcp/raw/branch/main/install.sh | sudo bash +# or: sudo bash install.sh +#============================================================================== +set -euo pipefail + +# --- Colors ---------------------------------------------------------------- +RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m' +BLUE='\033[0;34m'; CYAN='\033[0;36m'; BOLD='\033[1m'; NC='\033[0m' + +# --- Globals --------------------------------------------------------------- +PLUGIN_REPO="https://git.lohmar.co.uk/cclohmar/zoraxy-dhcp.git" +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +CONFIG_SAVE="/root/.dnsmasq-setup.conf" + +# User-provided values (populated by prompts or saved config) +IFACE=""; RANGE_START=""; RANGE_END=""; NETMASK="" +LEASE_TIME=""; GATEWAY_IP=""; DNS_SERVERS="" + +# Detected values +ZORAXY_MODE="" # baremetal | docker | fresh +ZORAXY_CONF_DIR="" # /opt/zoraxy/conf or docker mount source +ZORAXY_PLUGIN_DIR="" # /opt/zoraxy/plugins or docker mount source + +#============================================================================== +# UTILITY FUNCTIONS +#============================================================================== + +log() { echo -e "${GREEN}[+]${NC} $*"; } +warn() { echo -e "${YELLOW}[!]${NC} $*"; } +err() { echo -e "${RED}[✗]${NC} $*"; } +info() { echo -e "${CYAN}[i]${NC} $*"; } + +banner() { + echo -e "${GREEN}========================================${NC}" + echo -e "${GREEN} Zoraxy DHCP Server — Auto Installer ${NC}" + echo -e "${GREEN}========================================${NC}" + echo "" +} + +ensure_root() { + if [[ $EUID -ne 0 ]]; then + warn "This script requires root privileges. Restarting with sudo..." + sudo bash "$0" "$@" + exit $? + fi +} + +#============================================================================== +# OS DETECTION +#============================================================================== + +detect_os() { + if [ -f /etc/os-release ]; then + . /etc/os-release + OS_ID="$ID" + OS_VERSION="${VERSION_ID:-unknown}" + elif [ -f /etc/alpine-release ]; then + OS_ID="alpine" + OS_VERSION="$(cat /etc/alpine-release)" + else + err "Cannot detect OS. Unsupported system." + exit 1 + fi + log "Detected: ${BOLD}$OS_ID${NC} $OS_VERSION" +} + +#============================================================================== +# DEPENDENCY INSTALLATION +#============================================================================== + +install_deps() { + log "Installing dependencies..." + + case "$OS_ID" in + debian|ubuntu|raspbian|linuxmint) + apt-get update -qq + apt-get install -y -qq dnsmasq iptables jq git curl wget golang-go + ;; + rhel|centos|fedora|rocky|almalinux|amzn) + if command -v dnf &>/dev/null; then + dnf install -y dnsmasq iptables jq git curl wget golang + else + yum install -y epel-release + yum install -y dnsmasq iptables jq git curl wget golang + fi + ;; + alpine) + apk add --no-cache dnsmasq iptables jq git curl wget go + ;; + opensuse*|sles) + zypper install -y dnsmasq iptables jq git curl wget go + ;; + arch|manjaro) + pacman -S --noconfirm dnsmasq iptables jq git curl wget go + ;; + *) + err "Unsupported OS: $OS_ID" + warn "Attempting to continue — you may need to install deps manually." + ;; + esac + + # Ensure Go is on PATH if installed to a non-standard location + export PATH="$PATH:/usr/local/go/bin:$(go env GOPATH 2>/dev/null)/bin" + if ! command -v go &>/dev/null; then + err "Go not found after install. Please install Go manually." + exit 1 + fi + log "Dependencies installed Go: $(go version | awk '{print $3}')" +} + +#============================================================================== +# INTERACTIVE CONFIGURATION +#============================================================================== + +detect_defaults() { + # Auto-detect primary network interface + IFACE_DEFAULT=$(ip route get 1.1.1.1 2>/dev/null | awk '{print $5; exit}') + [ -z "$IFACE_DEFAULT" ] && IFACE_DEFAULT="eth0" + + # Auto-detect gateway + GATEWAY_DEFAULT=$(ip route get 1.1.1.1 2>/dev/null | awk '{print $3; exit}') + [ -z "$GATEWAY_DEFAULT" ] && GATEWAY_DEFAULT="10.2.0.10" + + # Auto-detect DNS from resolv.conf + DNS_DEFAULT=$(grep '^nameserver' /etc/resolv.conf 2>/dev/null | awk '{print $2}' | tr '\n' ',' | sed 's/,$//') + [ -z "$DNS_DEFAULT" ] && DNS_DEFAULT="1.1.1.1,8.8.8.8" +} + +prompt_config() { + echo "" + echo -e "${BOLD}─────────────────────────────────────────${NC}" + echo -e "${BOLD} Network Configuration${NC}" + echo -e "${BOLD}─────────────────────────────────────────${NC}" + echo "" + + detect_defaults + + # Network interface + read -p " Network interface [$IFACE_DEFAULT]: " IFACE + IFACE="${IFACE:-$IFACE_DEFAULT}" + + # DHCP range + echo "" + echo " DHCP IP Range" + read -p " Start IP [10.2.0.100]: " RANGE_START + RANGE_START="${RANGE_START:-10.2.0.100}" + read -p " End IP [10.2.0.150]: " RANGE_END + RANGE_END="${RANGE_END:-10.2.0.150}" + read -p " Subnet mask [255.255.255.0]: " NETMASK + NETMASK="${NETMASK:-255.255.255.0}" + read -p " Lease time [12h]: " LEASE_TIME + LEASE_TIME="${LEASE_TIME:-12h}" + + # Gateway & DNS + echo "" + read -p " Gateway IP [$GATEWAY_DEFAULT]: " GATEWAY_IP + GATEWAY_IP="${GATEWAY_IP:-$GATEWAY_DEFAULT}" + read -p " DNS servers (comma-separated) [$DNS_DEFAULT]: " DNS_SERVERS + DNS_SERVERS="${DNS_SERVERS:-$DNS_DEFAULT}" + + # Save for reference + cat > "$CONFIG_SAVE" << EOF +# DHCP Setup Configuration — saved $(date) +IFACE="$IFACE" +RANGE_START="$RANGE_START" +RANGE_END="$RANGE_END" +NETMASK="$NETMASK" +LEASE_TIME="$LEASE_TIME" +GATEWAY_IP="$GATEWAY_IP" +DNS_SERVERS="$DNS_SERVERS" +EOF + log "Configuration saved to $CONFIG_SAVE" +} + +show_config_summary() { + echo "" + echo -e "${BOLD}─────────────────────────────────────────${NC}" + echo -e "${BOLD} Configuration Summary${NC}" + echo -e "${BOLD}─────────────────────────────────────────${NC}" + echo " Interface: $IFACE" + echo " DHCP Range: $RANGE_START - $RANGE_END / $NETMASK" + echo " Lease time: $LEASE_TIME" + echo " Gateway: $GATEWAY_IP" + echo " DNS: $DNS_SERVERS" + echo " Zoraxy mode: ${ZORAXY_MODE:-detecting...}" + echo " Config dir: ${ZORAXY_CONF_DIR:-detecting...}" + echo -e "${BOLD}─────────────────────────────────────────${NC}" + echo "" +} + +#============================================================================== +# DNSMASQ + NAT SETUP +#============================================================================== + +setup_dnsmasq() { + local dhcp_conf_dir="$ZORAXY_CONF_DIR/dhcp" + local dhcp_conf_file="$dhcp_conf_dir/dnsmasq.conf" + local dhcp_leases_file="$dhcp_conf_dir/dnsmasq.leases" + + log "Setting up dnsmasq..." + + # Create dhcp config directory inside Zoraxy's conf + mkdir -p "$dhcp_conf_dir" + + # Write the DHCP configuration + cat > "$dhcp_conf_file" << EOF +# Zoraxy DHCP Server Configuration +# Managed by: install.sh — regenerated on re-run + +# Bind to the DHCP interface +interface=$IFACE +bind-interfaces + +# DHCP range +dhcp-range=$RANGE_START,$RANGE_END,$NETMASK,$LEASE_TIME + +# Gateway +dhcp-option=3,$GATEWAY_IP + +# DNS servers +EOF + + # Add each DNS server as a separate dhcp-option line + IFS=',' read -ra DNS_ARRAY <<< "$DNS_SERVERS" + for dns in "${DNS_ARRAY[@]}"; do + echo "dhcp-option=6,$dns" >> "$dhcp_conf_file" + done + + # Lease file location + echo "" >> "$dhcp_conf_file" + echo "dhcp-leasefile=$dhcp_leases_file" >> "$dhcp_conf_file" + + # Create empty lease file if not present + touch "$dhcp_leases_file" + + # Make main dnsmasq.conf include our config + if [ -f /etc/dnsmasq.conf ]; then + # Backup original + if [ ! -f /etc/dnsmasq.conf.bak ]; then + cp /etc/dnsmasq.conf /etc/dnsmasq.conf.bak + log "Backed up original dnsmasq.conf → /etc/dnsmasq.conf.bak" + fi + fi + + # Write a clean main config that includes our DHCP config + cat > /etc/dnsmasq.conf << EOF +# Main dnsmasq configuration +# DHCP config managed by Zoraxy dhcp-lease-manager plugin +conf-file=$dhcp_conf_file +EOF + + log "dnsmasq configured conf: $dhcp_conf_file" +} + +setup_nat_routing() { + log "Setting up NAT / IP forwarding..." + + # Enable IP forwarding + if ! grep -q '^net.ipv4.ip_forward=1' /etc/sysctl.conf 2>/dev/null; then + echo "net.ipv4.ip_forward=1" >> /etc/sysctl.conf + fi + sysctl -w net.ipv4.ip_forward=1 >/dev/null 2>&1 + + # Routing script + cat > /usr/local/sbin/zoraxy-dhcp-routing << 'ROUTING_EOF' +#!/bin/bash +# Gateway NAT — managed by Zoraxy DHCP installer +iptables -t nat -C POSTROUTING -o eth0 -j MASQUERADE 2>/dev/null || \ + iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE +ROUTING_EOF + chmod +x /usr/local/sbin/zoraxy-dhcp-routing + + # systemd oneshot service + cat > /etc/systemd/system/zoraxy-dhcp-routing.service << EOF +[Unit] +Description=Zoraxy DHCP NAT Routing +After=network-pre.target +Before=network.target + +[Service] +Type=oneshot +ExecStart=/usr/local/sbin/zoraxy-dhcp-routing +RemainAfterExit=yes + +[Install] +WantedBy=multi-user.target +EOF + + systemctl daemon-reload + systemctl enable zoraxy-dhcp-routing 2>/dev/null || true + systemctl start zoraxy-dhcp-routing 2>/dev/null || true + log "NAT routing service installed" + + # Start/enable dnsmasq + systemctl enable dnsmasq 2>/dev/null || true + systemctl restart dnsmasq 2>/dev/null || service dnsmasq restart 2>/dev/null || true + log "dnsmasq restarted" +} + +#============================================================================== +# ZORAXY DETECTION +#============================================================================== + +detect_zoraxy() { + echo "" + log "Detecting Zoraxy installation..." + + # --- Check Docker --- + if command -v docker &>/dev/null && docker info &>/dev/null 2>&1; then + local zoraxy_container + zoraxy_container=$(docker ps --format '{{.Names}} {{.Image}}' 2>/dev/null | grep -i zoraxy | head -1 | awk '{print $1}') + if [ -n "$zoraxy_container" ]; then + ZORAXY_MODE="docker" + info "Found Zoraxy in Docker container: ${BOLD}$zoraxy_container${NC}" + + # Find the config mount + ZORAXY_CONF_DIR=$(docker inspect "$zoraxy_container" --format '{{range .Mounts}}{{if eq .Destination "/opt/zoraxy/conf"}}{{.Source}}{{end}}{{end}}' 2>/dev/null) + + # Try plugin dir as well (may be a subpath of conf or separate mount) + local plugin_mount + plugin_mount=$(docker inspect "$zoraxy_container" --format '{{range .Mounts}}{{if eq .Destination "/opt/zoraxy/plugins"}}{{.Source}}{{end}}{{end}}' 2>/dev/null) + + if [ -n "$plugin_mount" ]; then + ZORAXY_PLUGIN_DIR="$plugin_mount" + elif [ -n "$ZORAXY_CONF_DIR" ]; then + ZORAXY_PLUGIN_DIR="$ZORAXY_CONF_DIR/../plugins" + mkdir -p "$ZORAXY_PLUGIN_DIR" + fi + + if [ -z "$ZORAXY_CONF_DIR" ]; then + warn "Could not detect Zoraxy config mount in container." + warn "You may need to manually configure the plugin path." + read -rp " Enter Zoraxy conf directory on host: " ZORAXY_CONF_DIR + fi + + return 0 + fi + fi + + # --- Check Bare Metal --- + if systemctl is-active --quiet zoraxy 2>/dev/null; then + ZORAXY_MODE="baremetal" + info "Found active Zoraxy service (systemd)" + elif [ -f /opt/zoraxy/zoraxy ] && [ -x /opt/zoraxy/zoraxy ]; then + ZORAXY_MODE="baremetal" + info "Found Zoraxy binary at /opt/zoraxy/zoraxy" + elif pgrep -f zoraxy >/dev/null 2>&1; then + ZORAXY_MODE="baremetal" + info "Found running Zoraxy process" + fi + + if [ "$ZORAXY_MODE" = "baremetal" ]; then + ZORAXY_CONF_DIR="/opt/zoraxy/conf" + ZORAXY_PLUGIN_DIR="/opt/zoraxy/plugins" + return 0 + fi + + # --- Not Found — ask user --- + echo "" + warn "No existing Zoraxy installation detected." + echo "" + echo " Options:" + echo " [1] Fresh install — I'll install Zoraxy for you" + echo " [2] Provide path — Zoraxy is installed at a custom location" + echo " [3] Skip — I'll handle Zoraxy/plugin setup myself" + echo "" + + local choice + while true; do + read -rp " Choose [1]: " choice + choice="${choice:-1}" + case "$choice" in + 1) + ZORAXY_MODE="fresh" + install_zoraxy_fresh + ZORAXY_CONF_DIR="/opt/zoraxy/conf" + ZORAXY_PLUGIN_DIR="/opt/zoraxy/plugins" + break + ;; + 2) + ZORAXY_MODE="custom" + read -rp " Zoraxy conf directory: " ZORAXY_CONF_DIR + read -rp " Zoraxy plugins directory: " ZORAXY_PLUGIN_DIR + break + ;; + 3) + ZORAXY_MODE="skip" + warn "Plugin installation skipped." + warn "Run this script again after Zoraxy is set up." + exit 0 + ;; + *) warn "Invalid choice. Enter 1, 2, or 3." ;; + esac + done +} + +#============================================================================== +# FRESH ZORAXY INSTALL +#============================================================================== + +install_zoraxy_fresh() { + log "Installing Zoraxy (fresh install)..." + + local arch; arch=$(uname -m) + local binary + case "$arch" in + x86_64) binary="zoraxy_linux_amd64" ;; + aarch64) binary="zoraxy_linux_arm64" ;; + armv7l) binary="zoraxy_linux_arm" ;; + *) err "Unsupported architecture: $arch"; exit 1 ;; + esac + + info "Architecture: $arch → $binary" + + # Download latest release + local latest_url + latest_url=$(curl -s https://api.github.com/repos/tobychui/zoraxy/releases/latest \ + | jq -r ".assets[] | select(.name | contains(\"$binary\")) | .browser_download_url" 2>/dev/null) + + if [ -z "$latest_url" ] || [ "$latest_url" = "null" ]; then + err "Failed to fetch Zoraxy download URL. Check your internet connection." + exit 1 + fi + + # Create directories + mkdir -p /opt/zoraxy/conf /opt/zoraxy/plugins /opt/zoraxy/logs + + # Download and install + log "Downloading Zoraxy..." + curl -sSL -o /tmp/zoraxy "$latest_url" + mv /tmp/zoraxy /opt/zoraxy/zoraxy + chmod +x /opt/zoraxy/zoraxy + + # Create system user + if ! id zoraxy &>/dev/null; then + useradd --system --no-create-home --shell /usr/sbin/nologin zoraxy + fi + chown -R zoraxy:zoraxy /opt/zoraxy + + # systemd service + cat > /etc/systemd/system/zoraxy.service << 'ZORAXY_SVC' +[Unit] +Description=Zoraxy Reverse Proxy +After=network.target + +[Service] +Type=simple +User=zoraxy +Group=zoraxy +WorkingDirectory=/opt/zoraxy +ExecStart=/opt/zoraxy/zoraxy -plugin=/opt/zoraxy/plugins +Restart=on-failure +RestartSec=5 + +[Install] +WantedBy=multi-user.target +ZORAXY_SVC + + systemctl daemon-reload + systemctl enable zoraxy + systemctl start zoraxy + + sleep 2 + if systemctl is-active --quiet zoraxy; then + log "Zoraxy installed and running." + else + err "Zoraxy service failed to start. Check: journalctl -u zoraxy -e" + fi +} + +#============================================================================== +# PLUGIN INSTALLATION +#============================================================================== + +install_plugin() { + log "Installing dhcp-lease-manager plugin..." + + local plugin_dir="$ZORAXY_PLUGIN_DIR/dhcp-lease-manager" + + # Clone / pull the plugin repo + if [ -d "$plugin_dir/.git" ]; then + info "Plugin repo exists, pulling latest..." + git -C "$plugin_dir" pull origin main 2>/dev/null || true + else + mkdir -p "$(dirname "$plugin_dir")" + git clone "$PLUGIN_REPO" "$plugin_dir" 2>/dev/null || { + err "Failed to clone plugin repo: $PLUGIN_REPO" + exit 1 + } + fi + + # Build the plugin + info "Building plugin binary..." + (cd "$plugin_dir" && go build -o dhcp-lease-manager .) || { + err "Plugin build failed. Check Go installation." + exit 1 + } + + # Ensure plugin has correct ownership + if id zoraxy &>/dev/null; then + chown -R zoraxy:zoraxy "$plugin_dir" + fi + + # --- Permissions: group-based access --- + log "Setting up permissions..." + + local group="dnsmasq-edit" + local conf_file="$ZORAXY_CONF_DIR/dhcp/dnsmasq.conf" + local leases_file="$ZORAXY_CONF_DIR/dhcp/dnsmasq.leases" + + # Create group + getent group "$group" >/dev/null || groupadd "$group" + + # Add zoraxy user to group (if it exists) + if id zoraxy &>/dev/null && ! groups zoraxy 2>/dev/null | grep -qw "$group"; then + usermod -a -G "$group" zoraxy + fi + + # Set group ownership on dhcp files + chgrp -R "$group" "$ZORAXY_CONF_DIR/dhcp" 2>/dev/null || true + chmod -R g+rw "$ZORAXY_CONF_DIR/dhcp" 2>/dev/null || true + + # Set group on plugin binary dir + chgrp -R "$group" "$plugin_dir" 2>/dev/null || true + + # Sudoers for reload + local sudoers_file="/etc/sudoers.d/dnsmasq-edit" + if [ ! -f "$sudoers_file" ]; then + cat > "$sudoers_file" << 'SUDO_EOF' +# Allow dnsmasq-edit group to reload dnsmasq without a password +%dnsmasq-edit ALL=(root) NOPASSWD: /usr/bin/systemctl reload dnsmasq, /usr/bin/systemctl restart dnsmasq, /usr/sbin/service dnsmasq reload, /usr/sbin/service dnsmasq restart +SUDO_EOF + chmod 0440 "$sudoers_file" + fi + + log "Plugin installed at: $plugin_dir" +} + +#============================================================================== +# VERIFICATION +#============================================================================== + +verify() { + echo "" + echo -e "${BOLD}─────────────────────────────────────────${NC}" + echo -e "${BOLD} Verification${NC}" + echo -e "${BOLD}─────────────────────────────────────────${NC}" + + # dnsmasq + if systemctl is-active --quiet dnsmasq 2>/dev/null; then + log "dnsmasq: ${GREEN}running${NC}" + elif service dnsmasq status &>/dev/null; then + log "dnsmasq: ${GREEN}running${NC}" + else + warn "dnsmasq: ${RED}not running${NC} — check: systemctl status dnsmasq" + fi + + # Plugin binary + if [ -x "$ZORAXY_PLUGIN_DIR/dhcp-lease-manager/dhcp-lease-manager" ]; then + log "plugin: ${GREEN}built${NC}" + else + warn "plugin: ${RED}missing${NC}" + fi + + # IP forwarding + if [ "$(cat /proc/sys/net/ipv4/ip_forward)" = "1" ]; then + log "forward: ${GREEN}enabled${NC}" + else + warn "forward: ${RED}disabled${NC}" + fi +} + +#============================================================================== +# MAIN +#============================================================================== + +main() { + banner + ensure_root "$@" + detect_os + install_deps + prompt_config + detect_zoraxy + show_config_summary + setup_dnsmasq + setup_nat_routing + install_plugin + verify + + echo "" + echo -e "${GREEN}========================================${NC}" + echo -e "${GREEN} ✅ Installation Complete!${NC}" + echo -e "${GREEN}========================================${NC}" + echo "" + echo -e " ${BOLD}DHCP Configuration${NC}" + echo -e " File: $ZORAXY_CONF_DIR/dhcp/dnsmasq.conf" + echo -e " Leases: $ZORAXY_CONF_DIR/dhcp/dnsmasq.leases" + echo "" + echo -e " ${BOLD}Plugin${NC}" + echo -e " Path: $ZORAXY_PLUGIN_DIR/dhcp-lease-manager/" + echo -e " UI: /plugin.ui/dhcp-lease-manager/" + + if [ "$ZORAXY_MODE" = "docker" ]; then + echo "" + echo -e " ${YELLOW}⚠ Docker detected:${NC}" + echo -e " You may need to restart the Zoraxy container to discover the plugin." + echo -e " docker restart " + else + echo "" + echo -e " ${BOLD}Next Steps${NC}" + echo -e " 1. Restart Zoraxy: systemctl restart zoraxy" + echo -e " 2. Open Zoraxy UI → Plugins → enable 'DHCP Lease Manager'" + echo -e " 3. Access at: /plugin.ui/dhcp-lease-manager/" + fi + echo "" + + if [ "$ZORAXY_MODE" = "docker" ] || [ "$ZORAXY_MODE" = "baremetal" ]; then + info "The zoraxy user may need to re-login for group changes to apply." + info "Run: sudo -u zoraxy newgrp dnsmasq-edit" + fi +} + +# --- Run ------------------------------------------------------------------- +main "$@" diff --git a/server.go b/server.go index 9bf275f..d9612df 100644 --- a/server.go +++ b/server.go @@ -19,9 +19,10 @@ import ( // --------------------------------------------------------------------------- var ( - // Default paths — can be changed via environment variables. - leasesFile = envOrDefault("LEASE_FILE", "/var/lib/misc/dnsmasq.leases") - confFile = envOrDefault("CONF_FILE", "/etc/dnsmasq.conf") + // Default paths — all under Zoraxy's unified config directory. + // Override via environment: LEASE_FILE, CONF_FILE, RELOAD_CMD, RELOAD_ARGS + leasesFile = envOrDefault("LEASE_FILE", "/opt/zoraxy/conf/dhcp/dnsmasq.leases") + confFile = envOrDefault("CONF_FILE", "/opt/zoraxy/conf/dhcp/dnsmasq.conf") reloadCmd = envOrDefault("RELOAD_CMD", "sudo") reloadArgs = strings.Fields(envOrDefault("RELOAD_ARGS", "systemctl reload dnsmasq")) ) @@ -37,7 +38,7 @@ func envOrDefault(key, fallback string) string { // dnsmasq interaction // --------------------------------------------------------------------------- -// parseLeases reads and parses /var/lib/misc/dnsmasq.leases. +// parseLeases reads the dnsmasq lease file (default: /opt/zoraxy/conf/dhcp/dnsmasq.leases). func parseLeases() ([]Lease, error) { f, err := os.Open(leasesFile) if err != nil {