#!/bin/sh # AUTO-GENERATED by scripts/build_installers.py from scripts/modules/ — DO NOT EDIT MANUALLY. # ═════════════════════════════════════════════════════════════════════════════ # 🌌 CubeX Universal Deployer · 次世代双擎高可用旁路网关一键极速安装程序 # Target Version: v10.2.1 # Supported Hosts: PVE (LXC), 通用 Linux, 飞牛 fnOS, OpenWrt Docker, 爱快 KVM 虚拟机 (注: 爱快原生容器走后台导 .tar.gz; RouterOS 用 setup-routeros-v7.rsc) # ═════════════════════════════════════════════════════════════════════════════ set -e # CubeX POSIX sh Common Module (Sourced/Inlined by build_installers.py) # Zero bashisms: no [[, no arrays, no pipefail, no <<<, no read -p, no local keyword. CYAN='\033[0;36m' GREEN='\033[0;32m' YELLOW='\033[1;33m' PURPLE='\033[0;35m' BLUE='\033[0;34m' RED='\033[0;31m' NC='\033[0m' BOLD='\033[1m' CUBEX_DEFAULT_TAG="v10.2.1" CUBEX_GH_MIRRORS="https://gh-proxy.com DIRECT https://ghfast.top https://ghproxy.net https://gh.ddlc.top" CUBEX_FASTEST_MIRROR="" msg() { printf '%b\n' "$*"; } prompt_read() { _pr_prompt="$1" printf '%s' "$_pr_prompt" if [ -r /dev/tty ]; then read -r REPLY /dev/null 2>&1; then if timeout 1 true >/dev/null 2>&1; then timeout "$_prt_secs" "$@" >/dev/null 2>&1 || true else timeout -t "$_prt_secs" "$@" >/dev/null 2>&1 || true fi else "$@" >/dev/null 2>&1 || true fi } detect_target_arch() { _dta_arch=$(uname -m 2>/dev/null || echo "unknown") case "$_dta_arch" in x86_64|amd64) TARGET_ARCH="amd64" ;; aarch64|arm64) TARGET_ARCH="arm64" ;; armv7l|armv7|armhf) TARGET_ARCH="armv7" ;; *) msg "${RED}❌ 不支持的 CPU 架构: $_dta_arch (仅支持 x86_64 / arm64 / armv7l)${NC}" exit 1 ;; esac } ensure_linux_base_tools() { if ! command -v curl >/dev/null 2>&1 || ! command -v unzip >/dev/null 2>&1 || ! command -v iptables >/dev/null 2>&1; then msg "${YELLOW}📦 检测到缺少基础工具 (curl / unzip / iptables),正在自动安装依赖...${NC}" if command -v apt-get >/dev/null 2>&1; then pkg_run_timeout 10 apt-get -o Acquire::http::Timeout=5 -o Acquire::https::Timeout=5 update -y pkg_run_timeout 20 apt-get -o Acquire::http::Timeout=5 -o Acquire::https::Timeout=5 install -y curl ca-certificates unzip iptables iproute2 procps elif command -v apk >/dev/null 2>&1; then pkg_run_timeout 10 apk update pkg_run_timeout 20 apk add --no-cache curl ca-certificates unzip iptables iproute2 procps elif command -v opkg >/dev/null 2>&1; then pkg_run_timeout 10 opkg update pkg_run_timeout 20 opkg install curl ca-certificates ca-bundle unzip iptables ip-full procps-ng-pgrep elif command -v dnf >/dev/null 2>&1; then pkg_run_timeout 20 dnf install -y curl ca-certificates unzip iptables iproute procps-ng elif command -v yum >/dev/null 2>&1; then pkg_run_timeout 20 yum install -y curl ca-certificates unzip iptables iproute procps-ng fi fi } cubex_pick_latest_file() { _cplf_list="" for _cplf_f in "$@"; do [ -n "$_cplf_f" ] && [ -f "$_cplf_f" ] || continue _cplf_key=$(printf '%s\n' "$_cplf_f" | awk ' { s = $0 if (match(s, /[vV]?[0-9]+\.[0-9]+(\.[0-9]+)?/)) { v = substr(s, RSTART, RLENGTH) gsub(/^[vV]/, "", v) n = split(v, a, ".") printf "%06d.%06d.%06d %s\n", (n>=1?a[1]:0), (n>=2?a[2]:0), (n>=3?a[3]:0), s } else { printf "000000.000000.000000 %s\n", s } }') if [ -z "$_cplf_list" ]; then _cplf_list="$_cplf_key" else _cplf_list="${_cplf_list} ${_cplf_key}" fi done [ -n "$_cplf_list" ] || return 0 printf '%s\n' "$_cplf_list" | sort | tail -n 1 | cut -d' ' -f2- } _cubex_http_get() { _chg_url="$1" _chg_timeout="${2:-8}" if command -v curl >/dev/null 2>&1; then curl -4 --http1.1 -fsSL --connect-timeout 4 -m "$_chg_timeout" "$_chg_url" 2>/dev/null || return 1 return 0 elif command -v wget >/dev/null 2>&1; then wget -q -T "$_chg_timeout" -O - "$_chg_url" 2>/dev/null || return 1 return 0 fi return 1 } zip_is_valid() { _ziv_zf="$1" [ -s "$_ziv_zf" ] || return 1 if command -v unzip >/dev/null 2>&1; then unzip -t "$_ziv_zf" >/dev/null 2>&1 return $? elif command -v python3 >/dev/null 2>&1; then python3 -c 'import sys,zipfile; z=zipfile.ZipFile(sys.argv[1]); sys.exit(1 if z.testzip() else 0)' "$_ziv_zf" >/dev/null 2>&1 return $? fi return 1 } gzip_is_valid() { _giv_gf="$1" [ -s "$_giv_gf" ] || return 1 gzip -t "$_giv_gf" >/dev/null 2>&1 return $? } elf_is_valid() { _eiv_bf="$1" [ -s "$_eiv_bf" ] || return 1 head -c 4 "$_eiv_bf" 2>/dev/null | grep -q "ELF" return $? } zip_extract_pkg() { _zep_zf="$1" _zep_dst="$2" _zep_preserve="$3" if command -v unzip >/dev/null 2>&1; then if [ "$_zep_preserve" = "1" ]; then unzip -q -o "$_zep_zf" -x "data/*" "etc/config.*" -d "$_zep_dst" 2>/dev/null || true else unzip -q -o "$_zep_zf" -d "$_zep_dst" 2>/dev/null || true fi elif command -v python3 >/dev/null 2>&1; then python3 -c ' import sys, os, zipfile, fnmatch zf, dst, preserve = sys.argv[1], sys.argv[2], sys.argv[3] == "1" with zipfile.ZipFile(zf, "r") as z: for m in z.infolist(): name = m.filename.replace("\\", "/").strip("/") if not name: continue if preserve and (fnmatch.fnmatch(name, "data/*") or fnmatch.fnmatch(name, "etc/config.*")): continue t = os.path.join(dst, name) if m.is_dir() or name.endswith("/"): os.makedirs(t, exist_ok=True) else: os.makedirs(os.path.dirname(t), exist_ok=True) with z.open(m) as s, open(t, "wb") as d: d.write(s.read()) if m.external_attr > 0: os.chmod(t, (m.external_attr >> 16) & 0o777) ' "$_zep_zf" "$_zep_dst" "$_zep_preserve" 2>/dev/null || true fi } cubex_probe_fastest_mirror() { if [ -n "$CUBEX_FASTEST_MIRROR" ]; then return 0 fi for _pfm_m in $CUBEX_GH_MIRRORS; do if [ "$_pfm_m" = "DIRECT" ]; then _pfm_probe="https://raw.githubusercontent.com/zyeyefyass/CubeX/main/meta.json" else _pfm_probe="${_pfm_m}/https://raw.githubusercontent.com/zyeyefyass/CubeX/main/meta.json" fi if command -v curl >/dev/null 2>&1; then if curl -4 --http1.1 -fsSL --connect-timeout 3 -m 4 "$_pfm_probe" >/dev/null 2>&1; then CUBEX_FASTEST_MIRROR="$_pfm_m" return 0 fi elif command -v wget >/dev/null 2>&1; then if wget -q -T 4 -O /dev/null "$_pfm_probe" >/dev/null 2>&1; then CUBEX_FASTEST_MIRROR="$_pfm_m" return 0 fi fi done return 0 } cubex_ordered_mirrors() { if [ -n "$CUBEX_FASTEST_MIRROR" ]; then _com_list="$CUBEX_FASTEST_MIRROR" for _com_m in $CUBEX_GH_MIRRORS; do if [ "$_com_m" != "$CUBEX_FASTEST_MIRROR" ]; then _com_list="${_com_list} ${_com_m}" fi done printf '%s\n' "$_com_list" else printf '%s\n' "$CUBEX_GH_MIRRORS" fi } cubex_resolve_latest_tag() { _rlt_custom="$1" if [ -n "$_rlt_custom" ]; then REL_TAG="$_rlt_custom" return 0 fi REL_TAG="" cubex_probe_fastest_mirror for _rlt_m in $(cubex_ordered_mirrors); do _rlt_prefix="" if [ "$_rlt_m" != "DIRECT" ]; then _rlt_prefix="${_rlt_m}/" fi # 1. Preferred: raw meta.json via domestic mirrors (works with curl or BusyBox wget, avoids api.github.com blocking) _rlt_meta=$(_cubex_http_get "${_rlt_prefix}https://raw.githubusercontent.com/zyeyefyass/CubeX/main/meta.json" 6 || true) if [ -n "$_rlt_meta" ]; then _rlt_cand=$(printf '%s\n' "$_rlt_meta" | grep -o '"version": *"[^"]*"' | head -n1 | cut -d'"' -f4 | grep -E '^v?[0-9]+' || true) if [ -n "$_rlt_cand" ]; then case "$_rlt_cand" in v*) REL_TAG="$_rlt_cand" ;; *) REL_TAG="v${_rlt_cand}" ;; esac return 0 fi fi # 2. Fallback: GitHub API releases/latest (curl or wget) _rlt_json=$(_cubex_http_get "${_rlt_prefix}https://api.github.com/repos/zyeyefyass/CubeX/releases/latest" 8 || true) if [ -n "$_rlt_json" ]; then _rlt_cand=$(printf '%s\n' "$_rlt_json" | grep -o '"tag_name": *"[^"]*"' | head -n1 | cut -d'"' -f4 | grep -E '^v[0-9]+' || true) if [ -n "$_rlt_cand" ]; then REL_TAG="$_rlt_cand" return 0 fi fi # 3. Fallback: GitHub releases/latest redirect Location header (curl) if command -v curl >/dev/null 2>&1; then _rlt_cand=$(curl -4 --http1.1 -sSL --connect-timeout 3 -m 5 -I "${_rlt_prefix}https://github.com/zyeyefyass/CubeX/releases/latest" 2>/dev/null | grep -i "^location:" | grep -oE 'tag/v[0-9][^/ \r\n]*' | cut -d/ -f2 | tr -d '\r\n' | grep -E '^v[0-9]+' || true) if [ -n "$_rlt_cand" ]; then REL_TAG="$_rlt_cand" return 0 fi fi done [ -z "$REL_TAG" ] && REL_TAG="$CUBEX_DEFAULT_TAG" } cubex_sha256_file() { _csf_f="$1" [ -f "$_csf_f" ] || return 1 if command -v sha256sum >/dev/null 2>&1; then sha256sum "$_csf_f" 2>/dev/null | awk '{print $1}' | tr 'A-F' 'a-f' return 0 elif command -v openssl >/dev/null 2>&1; then openssl dgst -sha256 "$_csf_f" 2>/dev/null | awk '{print $NF}' | tr 'A-F' 'a-f' return 0 elif command -v python3 >/dev/null 2>&1; then python3 -c 'import hashlib,sys;print(hashlib.sha256(open(sys.argv[1],"rb").read()).hexdigest().lower())' "$_csf_f" 2>/dev/null return 0 fi return 1 } cubex_verify_sha256() { _cvs_file="$1" _cvs_expected=$(printf '%s' "$2" | tr 'A-F' 'a-f' | tr -d ' \r\n') [ -n "$_cvs_expected" ] || return 0 _cvs_actual=$(cubex_sha256_file "$_cvs_file" || true) [ -n "$_cvs_actual" ] || return 0 [ "$_cvs_actual" = "$_cvs_expected" ] } cubex_fetch_expected_sha256() { _cfes_tag="$1" _cfes_name="$2" [ -n "$_cfes_tag" ] && [ -n "$_cfes_name" ] || return 0 _cfes_url="https://github.com/zyeyefyass/CubeX/releases/download/${_cfes_tag}/SHA256SUMS" for _cfes_m in $(cubex_ordered_mirrors); do if [ "$_cfes_m" != "DIRECT" ]; then _cfes_link="${_cfes_m}/${_cfes_url}" else _cfes_link="${_cfes_url}" fi _cfes_body=$(_cubex_http_get "$_cfes_link" 6 || true) if [ -n "$_cfes_body" ]; then _cfes_hash=$(printf '%s\n' "$_cfes_body" | awk -v fn="$_cfes_name" '$2 == fn || $2 == ("*" fn) { print $1; exit }' | tr 'A-F' 'a-f') if [ -n "$_cfes_hash" ]; then printf '%s\n' "$_cfes_hash" return 0 fi fi done return 0 } cubex_is_html_error_page() { _cih_file="$1" [ -s "$_cih_file" ] || return 0 if head -c 512 "$_cih_file" 2>/dev/null | grep -qiE '/dev/null 2>&1 && return 0 [ -x "/usr/sbin/$1" ] || [ -x "/sbin/$1" ] || [ -x "/usr/local/sbin/$1" ] || [ -x "/usr/bin/$1" ] || [ -x "/bin/$1" ] } cubex_preflight_check_deps() { _cpcd_missing="" if ! command -v curl >/dev/null 2>&1 && ! command -v wget >/dev/null 2>&1; then _cpcd_missing="${_cpcd_missing} curl/wget" fi if ! command -v tar >/dev/null 2>&1; then _cpcd_missing="${_cpcd_missing} tar" fi if ! cubex_has_cmd ip; then _cpcd_missing="${_cpcd_missing} iproute2(ip)" fi if ! cubex_has_cmd nft && ! cubex_has_cmd iptables; then _cpcd_missing="${_cpcd_missing} nftables/iptables" fi if [ ! -f /etc/ssl/certs/ca-certificates.crt ] && [ ! -f /etc/ssl/cert.pem ] && [ ! -f /etc/pki/tls/certs/ca-bundle.crt ]; then _cpcd_missing="${_cpcd_missing} ca-certificates" fi if [ -n "$_cpcd_missing" ]; then msg "${YELLOW}⚠️ [依赖预检] 检测到宿主机缺少组件:${_cpcd_missing}${NC}" msg "${YELLOW} 👉 建议安装: Debian/Ubuntu: apt-get install -y curl tar ca-certificates iproute2 nftables | Alpine: apk add curl tar ca-certificates iproute2 nftables | OpenWrt: opkg install curl tar ca-bundle ip-full nftables${NC}" fi return 0 } cubex_download_with_mirrors() { _dwm_raw_url="$1" _dwm_dest="$2" _dwm_validator="$3" _dwm_max_time="${4:-1200}" _dwm_show_prog="${5:-0}" _dwm_expected_sha="${6:-}" _dwm_tmp="${_dwm_dest}.dl.$$" if [ -z "$_dwm_expected_sha" ] && [ -n "${REL_TAG:-}" ]; then _dwm_fname=$(basename "$_dwm_raw_url") _dwm_expected_sha=$(cubex_fetch_expected_sha256 "$REL_TAG" "$_dwm_fname" || true) fi cubex_probe_fastest_mirror for _dwm_m in $(cubex_ordered_mirrors); do if [ "$_dwm_m" != "DIRECT" ]; then _dwm_link="${_dwm_m}/${_dwm_raw_url}" msg "${CYAN} [镜像尝试] 正在连接: ${_dwm_m}...${NC}" else _dwm_link="${_dwm_raw_url}" msg "${CYAN} [官方直连] 正在连接: GitHub...${NC}" fi rm -f "$_dwm_tmp" "${_dwm_dest}.dl."* 2>/dev/null || true if command -v curl >/dev/null 2>&1; then if [ "$_dwm_show_prog" = "1" ]; then curl -4 --http1.1 -f -# -L --connect-timeout 8 --speed-limit 5120 --speed-time 20 --retry 1 --retry-delay 2 --retry-max-time 45 -m "$_dwm_max_time" -o "$_dwm_tmp" "$_dwm_link" 2>&1 || true else curl -4 --http1.1 -fsSL --connect-timeout 8 --speed-limit 5120 --speed-time 20 --retry 1 --retry-delay 2 --retry-max-time 45 -m "$_dwm_max_time" -o "$_dwm_tmp" "$_dwm_link" 2>/dev/null || true fi elif command -v wget >/dev/null 2>&1; then wget -q -T 30 -O "$_dwm_tmp" "$_dwm_link" 2>/dev/null || true fi if cubex_is_html_error_page "$_dwm_tmp"; then rm -f "$_dwm_tmp" 2>/dev/null || true continue fi _dwm_valid=0 if [ -n "$_dwm_validator" ]; then if "$_dwm_validator" "$_dwm_tmp"; then _dwm_valid=1 fi elif [ -s "$_dwm_tmp" ]; then _dwm_valid=1 fi if [ "$_dwm_valid" -eq 1 ] && [ -n "$_dwm_expected_sha" ]; then if ! cubex_verify_sha256 "$_dwm_tmp" "$_dwm_expected_sha"; then msg "${YELLOW} ⚠️ SHA256 校验未通过,丢弃异常下载并切换下一镜像...${NC}" _dwm_valid=0 fi fi if [ "$_dwm_valid" -eq 1 ]; then mv -f "$_dwm_tmp" "$_dwm_dest" msg "${GREEN} ✓ 下载成功并通过完整性校验!${NC}" return 0 fi rm -f "$_dwm_tmp" 2>/dev/null || true done return 1 } cubex_resolve_fnos_dir() { if [ -d "/vol1/1000/docker/cubex" ]; then printf '%s\n' "/vol1/1000/docker/cubex" elif [ -d "/vol1/1000/cubex" ]; then printf '%s\n' "/vol1/1000/cubex" elif [ -d "/vol1/1000" ]; then printf '%s\n' "/vol1/1000/docker/cubex" elif [ -d "/vol1" ]; then printf '%s\n' "/vol1/docker/cubex" elif [ -d "/vol2" ]; then printf '%s\n' "/vol2/docker/cubex" else printf '%s\n' "/var/lib/cubex" fi } cubex_copy_missing_tree() { _ccmt_src="$1" _ccmt_dst="$2" [ -d "$_ccmt_src" ] || return 0 mkdir -p "$_ccmt_dst" 2>/dev/null || return 0 (cd "$_ccmt_src" && find . -type d 2>/dev/null) | while IFS= read -r _ccmt_d; do [ "$_ccmt_d" = "." ] && continue mkdir -p "${_ccmt_dst}/${_ccmt_d#./}" 2>/dev/null || true done (cd "$_ccmt_src" && find . \( -type f -o -type l \) 2>/dev/null) | while IFS= read -r _ccmt_f; do _ccmt_rel="${_ccmt_f#./}" [ -n "$_ccmt_rel" ] || continue if [ ! -e "${_ccmt_dst}/${_ccmt_rel}" ]; then mkdir -p "$(dirname "${_ccmt_dst}/${_ccmt_rel}")" 2>/dev/null || true cp -p "${_ccmt_src}/${_ccmt_rel}" "${_ccmt_dst}/${_ccmt_rel}" 2>/dev/null || cp "${_ccmt_src}/${_ccmt_rel}" "${_ccmt_dst}/${_ccmt_rel}" 2>/dev/null || true fi done } # Create timestamped rollback snapshot before migrating legacy data/etc into v10 single store cubex_backup_before_v10_migration() { _cbm_work="$1" _cbm_store="$2" [ -n "$_cbm_work" ] && [ -n "$_cbm_store" ] || return 0 _cbm_ts=$(date -u +"%Y%m%d-%H%M%S" 2>/dev/null || echo "backup") _cbm_snap="${_cbm_store}/migrations/pre-v10-${_cbm_ts}" _cbm_has_legacy=0 [ -d "${_cbm_work}/data" ] && [ ! -L "${_cbm_work}/data" ] && _cbm_has_legacy=1 [ -d "${_cbm_work}/etc" ] && [ ! -L "${_cbm_work}/etc" ] && _cbm_has_legacy=1 if [ "$_cbm_has_legacy" -eq 0 ]; then return 0 fi if [ -f "${_cbm_work}/data/config.ir.json" ] && [ -f "${_cbm_store}/data/config.ir.json" ]; then msg "${YELLOW}⚠️ 检测到双路径冲突风险: ${_cbm_work}/data 与 ${_cbm_store}/data 均存在 config.ir.json,将优先保留单卷 store 并生成回滚快照。${NC}" fi mkdir -p "$_cbm_snap" 2>/dev/null || return 1 if [ -d "${_cbm_work}/data" ] && [ ! -L "${_cbm_work}/data" ]; then cubex_copy_missing_tree "${_cbm_work}/data" "${_cbm_snap}/data" fi if [ -d "${_cbm_work}/etc" ] && [ ! -L "${_cbm_work}/etc" ]; then cubex_copy_missing_tree "${_cbm_work}/etc" "${_cbm_snap}/etc" fi if [ -f "${_cbm_work}/install.manifest.json" ] && [ ! -L "${_cbm_work}/install.manifest.json" ]; then cp -p "${_cbm_work}/install.manifest.json" "${_cbm_snap}/install.manifest.json" 2>/dev/null || cp "${_cbm_work}/install.manifest.json" "${_cbm_snap}/install.manifest.json" 2>/dev/null || true fi if [ -f "${_cbm_work}/bin/cubexd" ]; then mkdir -p "${_cbm_snap}/bin" 2>/dev/null || true cp -p "${_cbm_work}/bin/cubexd" "${_cbm_snap}/bin/cubexd" 2>/dev/null || true fi if [ ! -f "${_cbm_store}/install.manifest.json" ]; then printf '%s\n' "legacy_dual" > "${_cbm_snap}/.pre_v10_mode" 2>/dev/null || true fi CUBEX_LAST_MIGRATION_SNAP="$_cbm_snap" return 0 } cubex_rollback_v10_migration() { _crm_snap="$1" _crm_work="$2" [ -n "$_crm_snap" ] && [ -d "$_crm_snap" ] && [ -n "$_crm_work" ] || return 1 if [ -d "${_crm_snap}/data" ]; then [ -L "${_crm_work}/data" ] && rm -f "${_crm_work}/data" 2>/dev/null || true mkdir -p "${_crm_work}/data" 2>/dev/null || true cp -rf "${_crm_snap}/data/." "${_crm_work}/data/" 2>/dev/null || true fi if [ -d "${_crm_snap}/etc" ]; then [ -L "${_crm_work}/etc" ] && rm -f "${_crm_work}/etc" 2>/dev/null || true mkdir -p "${_crm_work}/etc" 2>/dev/null || true cp -rf "${_crm_snap}/etc/." "${_crm_work}/etc/" 2>/dev/null || true fi if [ -f "${_crm_snap}/install.manifest.json" ]; then [ -L "${_crm_work}/install.manifest.json" ] && rm -f "${_crm_work}/install.manifest.json" 2>/dev/null || true cp -f "${_crm_snap}/install.manifest.json" "${_crm_work}/install.manifest.json" 2>/dev/null || true fi if [ -f "${_crm_snap}/bin/cubexd" ]; then mkdir -p "${_crm_work}/bin" 2>/dev/null || true cp -f "${_crm_snap}/bin/cubexd" "${_crm_work}/bin/cubexd" 2>/dev/null || true chmod 755 "${_crm_work}/bin/cubexd" 2>/dev/null || true fi if [ -f "${_crm_snap}/.pre_v10_mode" ]; then rm -f "${_crm_work}/store/install.manifest.json" 2>/dev/null || true rm -rf "${_crm_work}/store/data" "${_crm_work}/store/etc" 2>/dev/null || true fi return 0 } cubex_converge_single_store_links() { _ccsl_work="$1" _ccsl_store="$2" [ -n "$_ccsl_work" ] && [ -n "$_ccsl_store" ] || return 1 mkdir -p "${_ccsl_store}/data" "${_ccsl_store}/etc/rules" 2>/dev/null || true if [ -d "${_ccsl_work}/data" ] && [ ! -L "${_ccsl_work}/data" ]; then cubex_copy_missing_tree "${_ccsl_work}/data" "${_ccsl_store}/data" if [ -d "${_ccsl_store}/data" ]; then rm -rf "${_ccsl_work}/data" 2>/dev/null || true fi fi if [ ! -e "${_ccsl_work}/data" ] && [ ! -L "${_ccsl_work}/data" ]; then ln -s "store/data" "${_ccsl_work}/data" 2>/dev/null || ln -s "${_ccsl_store}/data" "${_ccsl_work}/data" 2>/dev/null || true fi if [ -d "${_ccsl_work}/etc" ] && [ ! -L "${_ccsl_work}/etc" ]; then cubex_copy_missing_tree "${_ccsl_work}/etc" "${_ccsl_store}/etc" if [ -d "${_ccsl_store}/etc" ]; then rm -rf "${_ccsl_work}/etc" 2>/dev/null || true fi fi if [ ! -e "${_ccsl_work}/etc" ] && [ ! -L "${_ccsl_work}/etc" ]; then ln -s "store/etc" "${_ccsl_work}/etc" 2>/dev/null || ln -s "${_ccsl_store}/etc" "${_ccsl_work}/etc" 2>/dev/null || true fi return 0 } cubex_cleanup_legacy_service_units() { if command -v systemctl >/dev/null 2>&1 && [ -d /etc/systemd/system ]; then if [ -f /etc/systemd/system/cubexd.service ]; then systemctl stop cubexd >/dev/null 2>&1 || true systemctl disable cubexd >/dev/null 2>&1 || true rm -f /etc/systemd/system/cubexd.service 2>/dev/null || true systemctl daemon-reload >/dev/null 2>&1 || true fi fi if command -v rc-service >/dev/null 2>&1 || [ -f /etc/init.d/cubexd ]; then if [ -f /etc/init.d/cubexd ]; then rc-service cubexd stop >/dev/null 2>&1 || true command -v rc-update >/dev/null 2>&1 && rc-update del cubexd default >/dev/null 2>&1 || true rm -f /etc/init.d/cubexd 2>/dev/null || true fi fi return 0 } cubex_extract_native_into_store() { _ceni_zf="$1" _ceni_idir="$2" _ceni_store="$3" [ -f "$_ceni_zf" ] && [ -n "$_ceni_idir" ] && [ -n "$_ceni_store" ] || return 1 _ceni_stage="/tmp/cubex_stage_$$" rm -rf "$_ceni_stage" 2>/dev/null || true mkdir -p "$_ceni_stage" "$_ceni_idir/bin" "${_ceni_store}/data" "${_ceni_store}/etc/rules" || return 1 zip_extract_pkg "$_ceni_zf" "$_ceni_stage" "0" _ceni_root="$_ceni_stage" if [ ! -d "${_ceni_root}/bin" ]; then for _ceni_sub in "$_ceni_stage"/*; do if [ -d "${_ceni_sub}/bin" ]; then _ceni_root="$_ceni_sub" break fi done fi if [ -d "${_ceni_root}/bin" ]; then for _ceni_bf in "${_ceni_root}/bin/"*; do [ -f "$_ceni_bf" ] || continue _ceni_bn=$(basename "$_ceni_bf") rm -f "${_ceni_idir}/bin/${_ceni_bn}" 2>/dev/null || true cp -f "$_ceni_bf" "${_ceni_idir}/bin/${_ceni_bn}" 2>/dev/null || true done chmod +x "${_ceni_idir}/bin/"* 2>/dev/null || true fi for _ceni_meta in meta.json README.md LICENSE docker-compose.yml; do [ -f "${_ceni_root}/${_ceni_meta}" ] && cp -f "${_ceni_root}/${_ceni_meta}" "${_ceni_idir}/${_ceni_meta}" 2>/dev/null || true done if [ -d "${_ceni_root}/etc/rules" ]; then cp -rf "${_ceni_root}/etc/rules/." "${_ceni_store}/etc/rules/" 2>/dev/null || true fi for _ceni_gf in GeoIP.dat geosite.dat; do [ -f "${_ceni_root}/etc/${_ceni_gf}" ] && cp -f "${_ceni_root}/etc/${_ceni_gf}" "${_ceni_store}/etc/${_ceni_gf}" 2>/dev/null || true done for _ceni_cfg in config.yaml config.json; do if [ -f "${_ceni_root}/etc/${_ceni_cfg}" ] && [ ! -e "${_ceni_store}/etc/${_ceni_cfg}" ]; then cp -f "${_ceni_root}/etc/${_ceni_cfg}" "${_ceni_store}/etc/${_ceni_cfg}" 2>/dev/null || true fi done if [ -f "${_ceni_root}/data/config.ir.json" ] && [ ! -s "${_ceni_store}/data/config.ir.json" ]; then cp -f "${_ceni_root}/data/config.ir.json" "${_ceni_store}/data/config.ir.json" 2>/dev/null || true fi rm -rf "$_ceni_stage" 2>/dev/null || true return 0 } cubex_json_escape() { printf '%s\n' "$1" | sed 's/\\/\\\\/g; s/"/\\"/g' | tr -d '\r\n' } cubex_manifest_get() { _cmg_file="$1" _cmg_key="$2" [ -f "$_cmg_file" ] || return 0 sed -n "s/.*\"${_cmg_key}\"[[:space:]]*:[[:space:]]*\"\([^\"]*\)\".*/\1/p; s/.*\"${_cmg_key}\"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p" "$_cmg_file" 2>/dev/null | head -n 1 } # Atomically write InstallManifest v10.0 JSON (strictly aligned with internal/config/store_layout.go) # Args: manifest_path version platform_id deploy_method install_dir storage_mode store_dir data_dir etc_dir listen_port [network_mode] cubex_write_install_manifest() { _cwim_path="$1" _cwim_ver="${2:-${REL_TAG:-${CUBEX_DEFAULT_TAG}}}" _cwim_plat="${3:-linux}" _cwim_method="${4:-native}" _cwim_idir="${5:-/opt/cubex}" _cwim_smode="${6:-single_store}" _cwim_sdir="${7:-}" _cwim_ddir="${8:-${_cwim_idir}/data}" _cwim_edir="${9:-${_cwim_idir}/etc}" _cwim_port="${10:-2026}" _cwim_net="${11:-host}" [ -n "$_cwim_path" ] || return 1 case "$_cwim_port" in ''|*[!0-9]*) _cwim_port=2026 ;; esac if [ "$_cwim_port" -le 0 ] || [ "$_cwim_port" -gt 65535 ]; then _cwim_port=2026 fi _cwim_parent=$(dirname "$_cwim_path") mkdir -p "$_cwim_parent" 2>/dev/null || return 1 _cwim_now=$(date -u +"%Y-%m-%dT%H:%M:%SZ" 2>/dev/null || echo "unknown") _cwim_installed_at="" if [ -f "$_cwim_path" ]; then _cwim_installed_at=$(cubex_manifest_get "$_cwim_path" "installed_at") fi [ -n "$_cwim_installed_at" ] || _cwim_installed_at="$_cwim_now" _cwim_ver_e=$(cubex_json_escape "$_cwim_ver") _cwim_plat_e=$(cubex_json_escape "$_cwim_plat") _cwim_method_e=$(cubex_json_escape "$_cwim_method") _cwim_idir_e=$(cubex_json_escape "$_cwim_idir") _cwim_smode_e=$(cubex_json_escape "$_cwim_smode") _cwim_sdir_e=$(cubex_json_escape "$_cwim_sdir") _cwim_ddir_e=$(cubex_json_escape "$_cwim_ddir") _cwim_edir_e=$(cubex_json_escape "$_cwim_edir") _cwim_net_e=$(cubex_json_escape "$_cwim_net") _cwim_inst_e=$(cubex_json_escape "$_cwim_installed_at") _cwim_upd_e=$(cubex_json_escape "$_cwim_now") _cwim_tmp="${_cwim_path}.tmp.$$" { printf '{\n' printf ' "schema_version": "10.0",\n' printf ' "version": "%s",\n' "$_cwim_ver_e" printf ' "platform_id": "%s",\n' "$_cwim_plat_e" printf ' "deploy_method": "%s",\n' "$_cwim_method_e" printf ' "install_dir": "%s",\n' "$_cwim_idir_e" printf ' "storage_mode": "%s",\n' "$_cwim_smode_e" if [ -n "$_cwim_sdir_e" ]; then printf ' "store_dir": "%s",\n' "$_cwim_sdir_e" fi printf ' "data_dir": "%s",\n' "$_cwim_ddir_e" printf ' "etc_dir": "%s",\n' "$_cwim_edir_e" printf ' "listen_port": %s,\n' "$_cwim_port" if [ -n "$_cwim_net_e" ]; then printf ' "network_mode": "%s",\n' "$_cwim_net_e" fi printf ' "installed_at": "%s",\n' "$_cwim_inst_e" printf ' "updated_at": "%s"\n' "$_cwim_upd_e" printf '}\n' } > "$_cwim_tmp" || { rm -f "$_cwim_tmp" 2>/dev/null || true return 1 } chmod 644 "$_cwim_tmp" 2>/dev/null || true mv -f "$_cwim_tmp" "$_cwim_path" } _cubex_extract_loaded_image_ref() { _cel_out="$1" printf '%s\n' "$_cel_out" | awk ' /^Loaded image:[[:space:]]*/ { sub(/^Loaded image:[[:space:]]*/, ""); gsub(/^[[:space:]]+|[[:space:]]+$/, ""); print; exit } /^Loaded image ID:[[:space:]]*/ { sub(/^Loaded image ID:[[:space:]]*/, ""); gsub(/^[[:space:]]+|[[:space:]]+$/, ""); print; exit } ' } cubex_pull_or_load_docker_image() { _cpdi_arch="$1" _cpdi_pkg="${2:-}" _cpdi_ver="${3:-}" _cpdi_offline="${4:-0}" _cpdi_target="${5:-}" _cpdi_loaded=0 # 锁定精确版本标签(防国内镜像加速站缓存陈旧 :latest 导致旧版抢占宿主机 :80) _cpdi_tag_ver="${_cpdi_ver:-${REL_TAG:-}}" if [ -z "$_cpdi_tag_ver" ] && [ "$_cpdi_offline" -ne 1 ]; then cubex_resolve_latest_tag "" _cpdi_tag_ver="${REL_TAG:-${CUBEX_DEFAULT_TAG}}" fi [ -z "$_cpdi_tag_ver" ] && _cpdi_tag_ver="${CUBEX_DEFAULT_TAG}" case "$_cpdi_tag_ver" in [0-9]*) _cpdi_tag_ver="v${_cpdi_tag_ver}" ;; esac _cpdi_exact_target="fyasshole/cubex:${_cpdi_tag_ver}" if [ -z "$_cpdi_target" ] || [ "$_cpdi_target" = "fyasshole/cubex:latest" ]; then _cpdi_target="$_cpdi_exact_target" fi # 1. Explicit --pkg tarball or local offline docker archive _cpdi_tar="" if [ -n "$_cpdi_pkg" ]; then if [ ! -f "$_cpdi_pkg" ] || [ ! -r "$_cpdi_pkg" ] || ! gzip_is_valid "$_cpdi_pkg"; then msg "${RED}❌ 指定的离线镜像包不存在、不可读或 gzip 校验失败: ${_cpdi_pkg}${NC}" >&2 return 1 fi _cpdi_tar="$_cpdi_pkg" else _cpdi_sd="${CURRENT_SCRIPT_DIR:-.}" _cpdi_tar=$(cubex_pick_latest_file \ ./CubeX-*-docker-"${_cpdi_arch}".tar.gz \ "${_cpdi_sd}/CubeX-"*"-docker-${_cpdi_arch}.tar.gz" \ "${_cpdi_sd}/../dist/release/CubeX-"*"-docker-${_cpdi_arch}.tar.gz" \ /tmp/CubeX-*-docker-"${_cpdi_arch}".tar.gz \ /root/CubeX-*-docker-"${_cpdi_arch}".tar.gz) fi if [ -n "$_cpdi_tar" ] && [ -f "$_cpdi_tar" ] && gzip_is_valid "$_cpdi_tar"; then msg "${GREEN}📦 [离线镜像] 发现本地 Docker 归档 (${_cpdi_tar}),正在校验并载入...${NC}" _cpdi_load_out=$(docker load -i "$_cpdi_tar" 2>&1) && _cpdi_load_rc=0 || _cpdi_load_rc=$? if [ "$_cpdi_load_rc" -eq 0 ]; then _cpdi_tag=$(_cubex_extract_loaded_image_ref "$_cpdi_load_out" || true) if [ -z "$_cpdi_tag" ]; then _cpdi_tag=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -E "^(cubex|fyasshole/cubex|ghcr\.io/zyeyefyass/cubex):(${_cpdi_tag_ver}|latest)$" | head -n 1 || true) fi if [ -n "$_cpdi_tag" ]; then docker tag "$_cpdi_tag" "$_cpdi_exact_target" 2>/dev/null || true docker tag "$_cpdi_tag" "fyasshole/cubex:latest" 2>/dev/null || true docker tag "$_cpdi_tag" "cubex:latest" 2>/dev/null || true docker tag "$_cpdi_tag" "$_cpdi_target" 2>/dev/null || true fi docker image inspect "$_cpdi_target" >/dev/null 2>&1 && _cpdi_loaded=1 fi fi # 2. Domestic Docker Registry Mirrors -> Official Registry (严格锁定版本标签,杜绝旧版 :latest 缓存串包) if [ "$_cpdi_loaded" -eq 0 ] && [ "$_cpdi_offline" -ne 1 ]; then for _cpdi_reg in \ "docker.1ms.green/fyasshole/cubex:${_cpdi_tag_ver}" \ "docker.xuanyuan.me/fyasshole/cubex:${_cpdi_tag_ver}" \ "m.daocloud.io/docker.io/fyasshole/cubex:${_cpdi_tag_ver}" \ "fyasshole/cubex:${_cpdi_tag_ver}" \ "ghcr.io/zyeyefyass/cubex:${_cpdi_tag_ver}" do msg "${CYAN} -> 尝试拉取精确版本镜像: ${_cpdi_reg} ...${NC}" _cpdi_pull_ok=0 if command -v timeout >/dev/null 2>&1; then if timeout 1 true >/dev/null 2>&1; then timeout 45 docker pull "$_cpdi_reg" >/dev/null 2>&1 && _cpdi_pull_ok=1 else timeout -t 45 docker pull "$_cpdi_reg" >/dev/null 2>&1 && _cpdi_pull_ok=1 fi else docker pull "$_cpdi_reg" >/dev/null 2>&1 && _cpdi_pull_ok=1 fi if [ "$_cpdi_pull_ok" -eq 1 ]; then docker tag "$_cpdi_reg" "$_cpdi_exact_target" 2>/dev/null || true docker tag "$_cpdi_reg" "fyasshole/cubex:latest" 2>/dev/null || true docker tag "$_cpdi_reg" "cubex:latest" 2>/dev/null || true docker tag "$_cpdi_reg" "$_cpdi_target" 2>/dev/null || true if docker image inspect "$_cpdi_target" >/dev/null 2>&1; then msg "${GREEN} ✓ 精确版本镜像拉取就绪: ${_cpdi_reg} -> ${_cpdi_target}${NC}" _cpdi_loaded=1 break fi fi done fi # 3. GitHub Release .tar.gz via domestic mirrors if [ "$_cpdi_loaded" -eq 0 ] && [ "$_cpdi_offline" -ne 1 ]; then msg "${YELLOW} -> 在线 Registry 拉取受阻或加速站尚未同步 ${_cpdi_tag_ver},切换为 GitHub Release 离线镜像包下载...${NC}" cubex_resolve_latest_tag "$_cpdi_ver" _cpdi_tag_ver="${REL_TAG:-${_cpdi_tag_ver}}" _cpdi_exact_target="fyasshole/cubex:${_cpdi_tag_ver}" _cpdi_tmp_tar="/tmp/cubex-docker-${_cpdi_arch}.tar.gz" _cpdi_raw_url="https://github.com/zyeyefyass/CubeX/releases/download/${REL_TAG}/CubeX-${REL_TAG}-docker-${_cpdi_arch}.tar.gz" if cubex_download_with_mirrors "$_cpdi_raw_url" "$_cpdi_tmp_tar" "gzip_is_valid" "1200" "1"; then _cpdi_load_out=$(docker load -i "$_cpdi_tmp_tar" 2>&1) && _cpdi_load_rc=0 || _cpdi_load_rc=$? if [ "$_cpdi_load_rc" -eq 0 ]; then rm -f "$_cpdi_tmp_tar" _cpdi_tag=$(_cubex_extract_loaded_image_ref "$_cpdi_load_out" || true) if [ -z "$_cpdi_tag" ]; then _cpdi_tag=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -E "^(cubex|fyasshole/cubex|ghcr\.io/zyeyefyass/cubex):(${_cpdi_tag_ver}|latest)$" | head -n 1 || true) fi if [ -n "$_cpdi_tag" ]; then docker tag "$_cpdi_tag" "$_cpdi_exact_target" 2>/dev/null || true docker tag "$_cpdi_tag" "fyasshole/cubex:latest" 2>/dev/null || true docker tag "$_cpdi_tag" "cubex:latest" 2>/dev/null || true docker tag "$_cpdi_tag" "$_cpdi_target" 2>/dev/null || true fi docker image inspect "$_cpdi_target" >/dev/null 2>&1 && _cpdi_loaded=1 fi fi rm -f "$_cpdi_tmp_tar" 2>/dev/null || true fi # 4. Offline mode fallback: reuse preloaded local image if already present (prefer exact version) if [ "$_cpdi_loaded" -eq 0 ] && [ "$_cpdi_offline" -eq 1 ]; then _cpdi_tag="" for _cpdi_cand in "$_cpdi_exact_target" "$_cpdi_target" "fyasshole/cubex:latest" "cubex:latest"; do if [ -n "$_cpdi_cand" ] && docker image inspect "$_cpdi_cand" >/dev/null 2>&1; then _cpdi_tag="$_cpdi_cand" break fi done if [ -n "$_cpdi_tag" ]; then docker tag "$_cpdi_tag" "$_cpdi_exact_target" 2>/dev/null || true docker tag "$_cpdi_tag" "fyasshole/cubex:latest" 2>/dev/null || true docker tag "$_cpdi_tag" "cubex:latest" 2>/dev/null || true docker tag "$_cpdi_tag" "$_cpdi_target" 2>/dev/null || true docker image inspect "$_cpdi_target" >/dev/null 2>&1 && _cpdi_loaded=1 fi fi [ "$_cpdi_loaded" -eq 1 ] } cubex_write_unix_uninstaller() { _cwuu_dir="$1" _cwuu_mode="${2:-native}" _cwuu_cname="${3:-cubex}" _cwuu_manifest="${4:-}" [ -n "$_cwuu_dir" ] || return 1 mkdir -p "$_cwuu_dir" cat < "${_cwuu_dir}/uninstall.sh" #!/bin/sh set -e PURGE_DATA=0 for _ua in "\$@"; do case "\$_ua" in --purge) PURGE_DATA=1 ;; -h|--help) printf '%s\n' "Usage: sh uninstall.sh [--purge]" exit 0 ;; esac done [ "\$(id -u)" -eq 0 ] || { printf '%s\n' "Error: uninstall.sh must be run as root." >&2; exit 1; } INSTALL_DIR="${_cwuu_dir}" DEPLOY_MODE="${_cwuu_mode}" CONTAINER_NAME="${_cwuu_cname}" MANIFEST_HINT="${_cwuu_manifest}" EOF cat <<'EOF' >> "${_cwuu_dir}/uninstall.sh" _u_manifest="" for _mc in "$MANIFEST_HINT" "${INSTALL_DIR}/install.manifest.json" "${INSTALL_DIR}/store/install.manifest.json"; do if [ -n "$_mc" ] && [ -f "$_mc" ]; then _u_manifest="$_mc" break fi done if [ -n "$_u_manifest" ]; then _m_idir=$(sed -n 's/.*"install_dir"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$_u_manifest" 2>/dev/null | head -n 1 || true) _m_method=$(sed -n 's/.*"deploy_method"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$_u_manifest" 2>/dev/null | head -n 1 || true) if [ -n "$_m_idir" ] && [ "$_m_idir" != "/" ] && [ "$_m_idir" != "/app" ] && [ -d "$_m_idir" ]; then INSTALL_DIR="$_m_idir" fi [ -n "$_m_method" ] && DEPLOY_MODE="$_m_method" fi if [ -z "$INSTALL_DIR" ] || [ "$INSTALL_DIR" = "/" ]; then printf '%s\n' "Error: refusing invalid INSTALL_DIR='$INSTALL_DIR'." >&2 exit 1 fi if command -v docker >/dev/null 2>&1; then if [ -f "${INSTALL_DIR}/docker-compose.yml" ]; then (cd "$INSTALL_DIR" && (docker compose down >/dev/null 2>&1 || docker-compose down >/dev/null 2>&1 || true)) fi docker stop "$CONTAINER_NAME" >/dev/null 2>&1 || true docker rm "$CONTAINER_NAME" >/dev/null 2>&1 || true fi if command -v systemctl >/dev/null 2>&1; then systemctl stop cubex cubexd >/dev/null 2>&1 || true systemctl disable cubex cubexd >/dev/null 2>&1 || true rm -f /etc/systemd/system/cubex.service /etc/systemd/system/cubexd.service 2>/dev/null || true systemctl daemon-reload >/dev/null 2>&1 || true fi if command -v rc-service >/dev/null 2>&1 || [ -f /etc/init.d/cubex ] || [ -f /etc/init.d/cubexd ]; then rc-service cubex stop >/dev/null 2>&1 || true rc-service cubexd stop >/dev/null 2>&1 || true rc-update del cubex default >/dev/null 2>&1 || true rc-update del cubexd default >/dev/null 2>&1 || true rm -f /etc/init.d/cubex /etc/init.d/cubexd 2>/dev/null || true fi pkill -x cubexd >/dev/null 2>&1 || killall cubexd >/dev/null 2>&1 || true pkill -x mihomo >/dev/null 2>&1 || killall mihomo >/dev/null 2>&1 || true pkill -x sing-box >/dev/null 2>&1 || killall sing-box >/dev/null 2>&1 || true rm -f /usr/local/bin/cubex /usr/bin/cubex /etc/sysctl.d/99-cubex.conf 2>/dev/null || true if command -v nft >/dev/null 2>&1; then nft delete table inet cubex >/dev/null 2>&1 || true nft delete table inet cubex_symbiotic >/dev/null 2>&1 || true fi if command -v ip >/dev/null 2>&1; then while ip rule del table 2022 >/dev/null 2>&1; do :; done for _u_tdev in cubex-tun cubex-tun-a cubex-tun-b $(ip -o link show 2>/dev/null | awk -F': ' '{print $2}' | cut -d@ -f1 | grep -E '^cubex-tun' || true); do while ip rule del iif "$_u_tdev" >/dev/null 2>&1; do :; done done for _u_pref in $(ip rule show 2>/dev/null | awk -F: '/suppress_prefixlength 0|from all nop/ {gsub(/^[[:space:]]+/,"",$1); if ($1+0 >= 9000 && $1+0 <= 9020) print $1}'); do ip rule del pref "$_u_pref" >/dev/null 2>&1 || true done while ip -6 rule del table 2022 >/dev/null 2>&1; do :; done for _u_pref6 in $(ip -6 rule show 2>/dev/null | awk -F: '/suppress_prefixlength 0|from all nop/ {gsub(/^[[:space:]]+/,"",$1); if ($1+0 >= 9000 && $1+0 <= 9020) print $1}'); do ip -6 rule del pref "$_u_pref6" >/dev/null 2>&1 || true done ip route flush table 2022 >/dev/null 2>&1 || true ip -6 route flush table 2022 >/dev/null 2>&1 || true for _u_tdev in cubex-tun cubex-tun-a cubex-tun-b $(ip -o link show 2>/dev/null | awk -F': ' '{print $2}' | cut -d@ -f1 | grep -E '^cubex-tun' || true); do for _u_cidr in 198.18.0.0/15 198.18.0.0/16 198.19.0.0/16; do ip route del "$_u_cidr" dev "$_u_tdev" >/dev/null 2>&1 || true done ip -6 route del fc00::/18 dev "$_u_tdev" >/dev/null 2>&1 || true ip link del "$_u_tdev" >/dev/null 2>&1 || true done for _u_cidr in 198.18.0.0/15 198.18.0.0/16 198.19.0.0/16; do ip route del "$_u_cidr" >/dev/null 2>&1 || true done ip -6 route del fc00::/18 >/dev/null 2>&1 || true fi rm -rf /run/cubex 2>/dev/null || true if command -v conntrack >/dev/null 2>&1; then for _u_ct in 198.18.0.0/15 198.18.0.0/16 198.19.0.0/16; do conntrack -D -d "$_u_ct" >/dev/null 2>&1 || true conntrack -D -s "$_u_ct" >/dev/null 2>&1 || true done fi if command -v iptables >/dev/null 2>&1; then while iptables -t nat -C POSTROUTING -j MASQUERADE >/dev/null 2>&1; do iptables -t nat -D POSTROUTING -j MASQUERADE >/dev/null 2>&1 || break done iptables -t nat -D OUTPUT -p udp --dport 53 -j CUBEX_DNS >/dev/null 2>&1 || true iptables -t nat -F CUBEX_DNS >/dev/null 2>&1 || true iptables -t nat -X CUBEX_DNS >/dev/null 2>&1 || true fi if [ -f /etc/resolv.conf ] && [ ! -L /etc/resolv.conf ]; then _u_ns=$(awk '/^[[:space:]]*nameserver[[:space:]]+/ {print $2}' /etc/resolv.conf 2>/dev/null || true) _u_ext=$(printf '%s\n' "$_u_ns" | grep -Ev '^(127\.0\.0\.1|::1)?$' || true) if [ -n "$_u_ns" ] && [ -z "$_u_ext" ]; then _u_gw=$(ip route show default 2>/dev/null | awk '/default/ {print $3; exit}' || true) { [ -n "$_u_gw" ] && printf 'nameserver %s\n' "$_u_gw" printf 'nameserver 223.5.5.5\nnameserver 119.29.29.29\n' } > /etc/resolv.conf 2>/dev/null || true fi fi rm -rf "${INSTALL_DIR}/bin" 2>/dev/null || true rm -f "${INSTALL_DIR}/meta.json" "${INSTALL_DIR}/uninstall.sh" "${INSTALL_DIR}/install.manifest.json" "${INSTALL_DIR}/store/install.manifest.json" 2>/dev/null || true if [ "$PURGE_DATA" -eq 1 ]; then for _u_netcfg in /etc/dhcpcd.conf /etc/dhcp/dhclient.conf; do if [ -f "$_u_netcfg" ] && grep -q '# cubex-managed' "$_u_netcfg" 2>/dev/null; then if awk 'BEGIN{skip=0} skip==1{skip=0; next} /^# cubex-managed-next$/{skip=1; next} /# cubex-managed/{next} {print}' "$_u_netcfg" > "${_u_netcfg}.cubex_tmp" 2>/dev/null; then mv "${_u_netcfg}.cubex_tmp" "$_u_netcfg" 2>/dev/null || rm -f "${_u_netcfg}.cubex_tmp" 2>/dev/null || true else rm -f "${_u_netcfg}.cubex_tmp" 2>/dev/null || true fi fi rm -f "${_u_netcfg}.cubex.bak" 2>/dev/null || true done if [ -f /etc/resolv.conf.cubex.bak ]; then if [ -f /etc/resolv.conf ] && [ ! -L /etc/resolv.conf ] && grep -q '# cubex-managed' /etc/resolv.conf 2>/dev/null; then mv -f /etc/resolv.conf.cubex.bak /etc/resolv.conf 2>/dev/null || true fi rm -f /etc/resolv.conf.cubex.bak 2>/dev/null || true fi _u_resolved_changed=0 for _u_resdrop in /etc/systemd/resolved.conf.d/99-cubex.conf /etc/systemd/resolved.conf.d/99-cubex-dns.conf; do if [ -f "$_u_resdrop" ]; then rm -f "$_u_resdrop" 2>/dev/null || true _u_resolved_changed=1 fi done if [ "$_u_resolved_changed" -eq 1 ]; then if command -v systemctl >/dev/null 2>&1 && systemctl is-active --quiet systemd-resolved 2>/dev/null; then systemctl restart systemd-resolved >/dev/null 2>&1 || true fi fi if command -v systemctl >/dev/null 2>&1 && systemctl is-active --quiet dhcpcd 2>/dev/null; then systemctl reload-or-restart dhcpcd >/dev/null 2>&1 || true fi rm -rf "${INSTALL_DIR}/store" "${INSTALL_DIR}/data" "${INSTALL_DIR}/etc" "${INSTALL_DIR}/rules" "${INSTALL_DIR}/logs" "${INSTALL_DIR}/docker-compose.yml" 2>/dev/null || true rm -f "${INSTALL_DIR}/README.md" "${INSTALL_DIR}/LICENSE" "${INSTALL_DIR}/install.sh" /var/log/cubex.log /var/log/cubex.err /var/log/cubexd.log /var/log/cubexd.err 2>/dev/null || true if [ -L /opt/CubeX ]; then _link_target=$(readlink /opt/CubeX 2>/dev/null || true) [ "$_link_target" = "$INSTALL_DIR" ] && rm -f /opt/CubeX 2>/dev/null || true fi rmdir "${INSTALL_DIR}" 2>/dev/null || true printf '%s\n' "[CubeX] Uninstall complete (persistent config and data purged)." else rmdir "${INSTALL_DIR}" 2>/dev/null || true printf '%s\n' "[CubeX] Uninstall complete. Persistent config/data preserved in ${INSTALL_DIR} (pass --purge to delete)." fi EOF chmod 755 "${_cwuu_dir}/uninstall.sh" 2>/dev/null || true } _cubex_exec_uninstaller() { _ceu_sh="$1" _ceu_purge="${2:-0}" if [ "$_ceu_purge" -eq 1 ]; then exec sh "$_ceu_sh" --purge else exec sh "$_ceu_sh" fi } _cubex_resolve_host_dir_from_manifest() { _crhm_mf="$1" _crhm_parent=$(dirname "$_crhm_mf") _crhm_base=$(basename "$_crhm_parent") if [ "$_crhm_base" = "store" ]; then _crhm_grand=$(dirname "$_crhm_parent") if [ -f "${_crhm_grand}/docker-compose.yml" ] || [ -f "${_crhm_grand}/uninstall.sh" ] || [ -d "${_crhm_grand}/bin" ]; then printf '%s\n' "$_crhm_grand" return 0 fi fi _crhm_idir=$(cubex_manifest_get "$_crhm_mf" "install_dir") if [ -n "$_crhm_idir" ] && [ "$_crhm_idir" != "/" ] && [ "$_crhm_idir" != "/app" ] && [ -d "$_crhm_idir" ]; then printf '%s\n' "$_crhm_idir" return 0 fi printf '%s\n' "$_crhm_parent" } cubex_run_uninstall() { _cru_plat="$1" _cru_dir="${2:-}" _cru_purge="${3:-0}" if [ "$(id -u)" -ne 0 ]; then msg "${RED}❌ 错误: 卸载操作需要 root 超级用户权限。${NC}" exit 1 fi if [ "$_cru_plat" = "pve" ]; then run_platform_pve_uninstall return 0 fi # 1. Manifest-first discovery when explicit --dir or platform default has install.manifest.json if [ -n "$_cru_dir" ]; then for _cru_dmf in "${_cru_dir}/install.manifest.json" "${_cru_dir}/store/install.manifest.json"; do if [ -f "$_cru_dmf" ]; then _cru_hdir=$(_cubex_resolve_host_dir_from_manifest "$_cru_dmf") _cru_method=$(cubex_manifest_get "$_cru_dmf" "deploy_method") [ -f "${_cru_hdir}/uninstall.sh" ] && _cubex_exec_uninstaller "${_cru_hdir}/uninstall.sh" "$_cru_purge" cubex_write_unix_uninstaller "$_cru_hdir" "${_cru_method:-native}" "cubex" "$_cru_dmf" _cubex_exec_uninstaller "${_cru_hdir}/uninstall.sh" "$_cru_purge" fi done if [ -f "${_cru_dir}/uninstall.sh" ]; then _cubex_exec_uninstaller "${_cru_dir}/uninstall.sh" "$_cru_purge" fi fi # 2. Platform-scoped install.manifest.json + uninstall.sh discovery _cru_cands="" case "$_cru_plat" in openwrt-docker|openwrt) _cru_cands="/etc/cubex /opt/cubex" ;; fnos) _cru_cands="/vol1/1000/docker/cubex /vol1/1000/cubex $(cubex_resolve_fnos_dir) /vol1/@appdata/cubex" ;; *) _cru_cands="/opt/cubex /opt/CubeX /etc/cubex /vol1/1000/docker/cubex /vol1/1000/cubex $(cubex_resolve_fnos_dir) /vol1/@appdata/cubex" ;; esac for _cru_base in $_cru_cands; do [ -n "$_cru_base" ] || continue for _cru_mf in "${_cru_base}/install.manifest.json" "${_cru_base}/store/install.manifest.json"; do if [ -f "$_cru_mf" ]; then _cru_hdir=$(_cubex_resolve_host_dir_from_manifest "$_cru_mf") _cru_method=$(cubex_manifest_get "$_cru_mf" "deploy_method") [ -f "${_cru_hdir}/uninstall.sh" ] && _cubex_exec_uninstaller "${_cru_hdir}/uninstall.sh" "$_cru_purge" cubex_write_unix_uninstaller "$_cru_hdir" "${_cru_method:-native}" "cubex" "$_cru_mf" _cubex_exec_uninstaller "${_cru_hdir}/uninstall.sh" "$_cru_purge" fi done if [ -f "${_cru_base}/uninstall.sh" ]; then _cubex_exec_uninstaller "${_cru_base}/uninstall.sh" "$_cru_purge" fi done # 3. Second-pass purge/cleanup when uninstall.sh was already removed (idempotent re-uninstall) if [ -n "$_cru_dir" ] && [ -d "$_cru_dir" ]; then cubex_write_unix_uninstaller "$_cru_dir" "native" "cubex" _cubex_exec_uninstaller "${_cru_dir}/uninstall.sh" "$_cru_purge" fi for _cru_base in $_cru_cands; do [ -n "$_cru_base" ] && [ -d "$_cru_base" ] || continue if [ -d "${_cru_base}/store" ] || [ -d "${_cru_base}/data" ] || [ -d "${_cru_base}/etc" ] || [ -f "${_cru_base}/docker-compose.yml" ]; then cubex_write_unix_uninstaller "$_cru_base" "native" "cubex" _cubex_exec_uninstaller "${_cru_base}/uninstall.sh" "$_cru_purge" fi done # Fallback idempotent cleanup if uninstall.sh was not previously written _cru_fallback_dir="${_cru_dir:-/opt/cubex}" cubex_write_unix_uninstaller "$_cru_fallback_dir" "native" "cubex" _cubex_exec_uninstaller "${_cru_fallback_dir}/uninstall.sh" "$_cru_purge" } detect_host_topology_and_platform() { DETECTED_HOST="linux" DETECTED_HOST_NAME="Linux 通用宿主环境" DEFAULT_INSTALL_DIR="/opt/cubex" IS_CONTAINER=0 if [ -f "/.dockerenv" ] || [ -f "/run/.containerenv" ]; then IS_CONTAINER=1 elif command -v systemd-detect-virt >/dev/null 2>&1; then _dht_virt=$(systemd-detect-virt 2>/dev/null || true) case "$_dht_virt" in lxc|docker|podman|openvz|container) IS_CONTAINER=1 ;; esac elif grep -qaE 'container=(lxc|docker|podman)' /proc/1/environ 2>/dev/null || grep -qE '/(lxc|docker)/' /proc/1/cgroup 2>/dev/null; then IS_CONTAINER=1 fi if [ -f "/etc/fnos-release" ] || [ -d "/usr/trim" ] || grep -qi "fnos" /etc/os-release 2>/dev/null; then DETECTED_HOST="fnos" DETECTED_HOST_NAME="飞牛 fnOS 专属 NAS 环境" DEFAULT_INSTALL_DIR=$(cubex_resolve_fnos_dir) elif [ -n "${ROUTEROS:-}" ] || [ -d "/nova" ] || grep -qi "routeros" /etc/os-release 2>/dev/null; then DETECTED_HOST="routeros" DETECTED_HOST_NAME="MikroTik RouterOS v7.x 容器沙盒" DEFAULT_INSTALL_DIR="/app" elif [ "$IS_CONTAINER" -eq 0 ] && { [ -d "/etc/pve" ] || command -v pveversion >/dev/null 2>&1; }; then DETECTED_HOST="pve" DETECTED_HOST_NAME="Proxmox VE (PVE) 物理宿主机" DEFAULT_INSTALL_DIR="/opt/cubex" elif [ -f "/etc/istoreos_version" ] || [ -f "/etc/openwrt_release" ]; then DETECTED_HOST="openwrt" if [ -f "/etc/istoreos_version" ]; then DETECTED_HOST_NAME="iStoreOS 软路由环境" else DETECTED_HOST_NAME="OpenWrt 软路由环境" fi DEFAULT_INSTALL_DIR="/opt/cubex" fi DEFAULT_GW=$(ip route show default 2>/dev/null | awk '/default/ {print $3}' | head -n 1) IS_IKUAI_GATEWAY=0 IS_IKUAI_HOST=0 if [ -n "$DEFAULT_GW" ]; then GW_PROBE="" GW_BODY="" if command -v curl >/dev/null 2>&1; then GW_PROBE=$(curl -s -m 2 -I "http://$DEFAULT_GW/" 2>/dev/null || true) GW_BODY=$(curl -s -m 2 "http://$DEFAULT_GW/" 2>/dev/null || true) elif command -v wget >/dev/null 2>&1; then GW_BODY=$(wget -q -T 2 -O - "http://$DEFAULT_GW/" 2>/dev/null || true) fi if printf '%s %s\n' "$GW_PROBE" "$GW_BODY" | grep -qi "ikuai"; then IS_IKUAI_GATEWAY=1 fi fi if [ "$IS_IKUAI_GATEWAY" -eq 1 ]; then if [ -f "/.dockerenv" ] || [ -f "/run/.containerenv" ]; then IS_IKUAI_HOST=1 DETECTED_HOST="ikuai_docker" DETECTED_HOST_NAME="爱快 iKuai Docker 插件沙盒容器" elif [ "$DETECTED_HOST" = "linux" ]; then VIRT_TYPE="" if command -v systemd-detect-virt >/dev/null 2>&1; then VIRT_TYPE=$(systemd-detect-virt 2>/dev/null || true) fi if [ "$VIRT_TYPE" = "kvm" ] || [ "$VIRT_TYPE" = "qemu" ] || grep -qi "qemu" /sys/class/dmi/id/sys_vendor 2>/dev/null; then IS_IKUAI_HOST=1 DETECTED_HOST="ikuai_vm" DETECTED_HOST_NAME="爱快 iKuai 内置 KVM 虚拟机" fi fi fi } cubex_detect_memory_tier() { _cdmt_kb=0 if [ -r /sys/fs/cgroup/memory.max ]; then _cdmt_cg2=$(cat /sys/fs/cgroup/memory.max 2>/dev/null | tr -d ' \r\n' || true) case "$_cdmt_cg2" in ''|max|*[!0-9]*) ;; *) _cdmt_v=$((_cdmt_cg2 / 1024)) if [ "$_cdmt_v" -gt 0 ]; then _cdmt_kb="$_cdmt_v" fi ;; esac fi if [ -r /sys/fs/cgroup/memory/memory.limit_in_bytes ]; then _cdmt_cg1=$(cat /sys/fs/cgroup/memory/memory.limit_in_bytes 2>/dev/null | tr -d ' \r\n' || true) case "$_cdmt_cg1" in ''|*[!0-9]*) ;; *) if [ "${#_cdmt_cg1}" -lt 15 ]; then _cdmt_v=$((_cdmt_cg1 / 1024)) if [ "$_cdmt_v" -gt 0 ] && { [ "$_cdmt_kb" -eq 0 ] || [ "$_cdmt_v" -lt "$_cdmt_kb" ]; }; then _cdmt_kb="$_cdmt_v" fi fi ;; esac fi if [ -r /proc/meminfo ]; then _cdmt_proc=$(awk '/^MemTotal:/ {print $2; exit}' /proc/meminfo 2>/dev/null || true) case "$_cdmt_proc" in ''|*[!0-9]*) ;; *) if [ "$_cdmt_proc" -gt 0 ] && { [ "$_cdmt_kb" -eq 0 ] || [ "$_cdmt_proc" -lt "$_cdmt_kb" ]; }; then _cdmt_kb="$_cdmt_proc" fi ;; esac fi if [ "$_cdmt_kb" -le 0 ]; then _cdmt_kb=1048576 fi TOTAL_MEM_KB="$_cdmt_kb" if [ "$TOTAL_MEM_KB" -le 300000 ]; then HOST_GOMEMLIMIT="64MiB" HOST_GOGC="50" elif [ "$TOTAL_MEM_KB" -le 600000 ]; then HOST_GOMEMLIMIT="120MiB" HOST_GOGC="50" elif [ "$TOTAL_MEM_KB" -le 1500000 ]; then HOST_GOMEMLIMIT="256MiB" HOST_GOGC="80" elif [ "$TOTAL_MEM_KB" -le 3000000 ]; then HOST_GOMEMLIMIT="512MiB" HOST_GOGC="100" else HOST_GOMEMLIMIT="1024MiB" HOST_GOGC="100" fi } apply_linux_netstack_tuning() { cubex_detect_memory_tier sysctl -w net.ipv4.ip_forward=1 >/dev/null 2>&1 || true sysctl -w net.ipv6.conf.all.forwarding=1 >/dev/null 2>&1 || true sysctl -w net.ipv4.conf.all.rp_filter=0 >/dev/null 2>&1 || true sysctl -w net.ipv4.conf.default.rp_filter=0 >/dev/null 2>&1 || true CUBEX_IP_FORWARD_PERSISTED=0 if [ -d /etc/sysctl.d ] || mkdir -p /etc/sysctl.d 2>/dev/null; then if { printf '# CubeX managed IPv4/IPv6 transparent gateway sysctl baseline\n' printf 'net.ipv4.ip_forward=1\n' printf 'net.ipv6.conf.all.forwarding=1\n' printf 'net.ipv4.conf.all.rp_filter=0\n' printf 'net.ipv4.conf.default.rp_filter=0\n' } > /etc/sysctl.d/99-cubex.conf 2>/dev/null; then CUBEX_IP_FORWARD_PERSISTED=1 sysctl -p /etc/sysctl.d/99-cubex.conf >/dev/null 2>&1 || true fi fi CUBEX_IP_FORWARD_VALUE=$(cat /proc/sys/net/ipv4/ip_forward 2>/dev/null | tr -d ' \t\r\n' || echo "") if [ "$TOTAL_MEM_KB" -le 600000 ]; then sysctl -w net.core.somaxconn=4096 >/dev/null 2>&1 || true sysctl -w net.core.netdev_max_backlog=8192 >/dev/null 2>&1 || true sysctl -w net.ipv4.tcp_rmem="4096 87380 4194304" >/dev/null 2>&1 || true sysctl -w net.ipv4.tcp_wmem="4096 65536 4194304" >/dev/null 2>&1 || true sysctl -w net.ipv4.tcp_max_syn_backlog=4096 >/dev/null 2>&1 || true sysctl -w net.ipv4.tcp_max_tw_buckets=65536 >/dev/null 2>&1 || true elif [ "$TOTAL_MEM_KB" -le 1500000 ]; then sysctl -w net.core.somaxconn=8192 >/dev/null 2>&1 || true sysctl -w net.core.netdev_max_backlog=16384 >/dev/null 2>&1 || true sysctl -w net.ipv4.tcp_rmem="8192 262144 8388608" >/dev/null 2>&1 || true sysctl -w net.ipv4.tcp_wmem="8192 262144 8388608" >/dev/null 2>&1 || true sysctl -w net.ipv4.tcp_max_syn_backlog=8192 >/dev/null 2>&1 || true sysctl -w net.ipv4.tcp_max_tw_buckets=262144 >/dev/null 2>&1 || true elif [ "$TOTAL_MEM_KB" -le 3000000 ]; then sysctl -w net.core.somaxconn=12288 >/dev/null 2>&1 || true sysctl -w net.core.netdev_max_backlog=24576 >/dev/null 2>&1 || true sysctl -w net.ipv4.tcp_rmem="16384 524288 16777216" >/dev/null 2>&1 || true sysctl -w net.ipv4.tcp_wmem="16384 524288 16777216" >/dev/null 2>&1 || true sysctl -w net.ipv4.tcp_max_syn_backlog=12288 >/dev/null 2>&1 || true sysctl -w net.ipv4.tcp_max_tw_buckets=524288 >/dev/null 2>&1 || true else sysctl -w net.core.somaxconn=16384 >/dev/null 2>&1 || true sysctl -w net.core.netdev_max_backlog=32768 >/dev/null 2>&1 || true sysctl -w net.ipv4.tcp_rmem="16384 1048576 33554432" >/dev/null 2>&1 || true sysctl -w net.ipv4.tcp_wmem="16384 1048576 33554432" >/dev/null 2>&1 || true sysctl -w net.ipv4.tcp_max_syn_backlog=16384 >/dev/null 2>&1 || true sysctl -w net.ipv4.tcp_max_tw_buckets=1440000 >/dev/null 2>&1 || true fi sysctl -w net.ipv4.ip_local_port_range="10240 65535" >/dev/null 2>&1 || true sysctl -w net.ipv4.tcp_window_scaling=1 >/dev/null 2>&1 || true sysctl -w net.ipv4.tcp_timestamps=1 >/dev/null 2>&1 || true sysctl -w net.ipv4.tcp_sack=1 >/dev/null 2>&1 || true sysctl -w net.ipv4.tcp_fastopen=3 >/dev/null 2>&1 || true sysctl -w net.ipv4.tcp_slow_start_after_idle=0 >/dev/null 2>&1 || true sysctl -w net.ipv4.tcp_fin_timeout=10 >/dev/null 2>&1 || true sysctl -w net.ipv4.tcp_tw_reuse=1 >/dev/null 2>&1 || true if modprobe tcp_bbr >/dev/null 2>&1; then sysctl -w net.core.default_qdisc=fq >/dev/null 2>&1 || true sysctl -w net.ipv4.tcp_congestion_control=bbr >/dev/null 2>&1 || true fi if [ "$IS_IKUAI_GATEWAY" -eq 1 ] || [ "$IS_IKUAI_HOST" -eq 1 ]; then msg "${PURPLE}🚀 [爱快专属优化] 检测到爱快环境,正在注入爱快旁路四项底层加固...${NC}" sysctl -w net.ipv4.conf.all.rp_filter=0 >/dev/null 2>&1 || true sysctl -w net.ipv4.conf.default.rp_filter=0 >/dev/null 2>&1 || true for _alnt_dev in /proc/sys/net/ipv4/conf/*; do [ -d "$_alnt_dev" ] && echo 0 > "$_alnt_dev/rp_filter" 2>/dev/null || true done sysctl -w net.ipv4.conf.all.arp_ignore=1 >/dev/null 2>&1 || true sysctl -w net.ipv4.conf.all.arp_announce=2 >/dev/null 2>&1 || true sysctl -w net.ipv4.conf.default.arp_ignore=1 >/dev/null 2>&1 || true sysctl -w net.ipv4.conf.default.arp_announce=2 >/dev/null 2>&1 || true sysctl -w net.ipv4.conf.all.send_redirects=0 >/dev/null 2>&1 || true sysctl -w net.ipv4.conf.default.send_redirects=0 >/dev/null 2>&1 || true sysctl -w net.ipv4.conf.all.accept_redirects=0 >/dev/null 2>&1 || true sysctl -w net.ipv4.conf.default.accept_redirects=0 >/dev/null 2>&1 || true if command -v iptables >/dev/null 2>&1; then iptables -t mangle -C POSTROUTING -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu 2>/dev/null || \ iptables -t mangle -A POSTROUTING -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu 2>/dev/null || true fi msg "${GREEN} ✓ 爱快非对称路由直通 (rp_filter=0) 已生效${NC}" msg "${GREEN} ✓ 爱快 ARP 抑风暴与防漂移 (arp_ignore=1/arp_announce=2) 已就绪${NC}" msg "${GREEN} ✓ 爱快 PPPoE 自动 MSS 钳制已加载 (解决网页与测速截断卡顿)${NC}" msg "${GREEN} ✓ 爱快 ICMP 环路抑制已就绪${NC}" fi if [ ! -c /dev/net/tun ]; then mkdir -p /dev/net 2>/dev/null || true mknod /dev/net/tun c 10 200 2>/dev/null || true chmod 666 /dev/net/tun 2>/dev/null || true fi modprobe tun 2>/dev/null || true } check_resolv_self_loop() { RESOLV_LOOP_MATCHES="" RESOLV_SAFE_GW="${DEFAULT_GW:-223.5.5.5}" if [ "$RESOLV_SAFE_GW" = "$LOCAL_IP" ] || [ -z "$RESOLV_SAFE_GW" ]; then RESOLV_SAFE_GW="223.5.5.5" fi if [ -r /etc/resolv.conf ]; then HOST_ALL_IPS=$(ip -o addr show 2>/dev/null | awk '{print $4}' | cut -d/ -f1 | tr '\n' ' ') RESOLV_NAMESERVERS=$(awk '/^[[:space:]]*nameserver[[:space:]]+/ {print $2}' /etc/resolv.conf 2>/dev/null || true) for _crsl_ns in $RESOLV_NAMESERVERS; do _crsl_clean="${_crsl_ns%%#*}" _crsl_nozone="${_crsl_clean%%%*}" case "$_crsl_nozone" in 127.*|::1|0.0.0.0|::|"$LOCAL_IP") RESOLV_LOOP_MATCHES="${RESOLV_LOOP_MATCHES} ${_crsl_clean}" ;; *) for _crsl_hip in $HOST_ALL_IPS; do if [ "$_crsl_nozone" = "$_crsl_hip" ]; then RESOLV_LOOP_MATCHES="${RESOLV_LOOP_MATCHES} ${_crsl_clean}" break fi done ;; esac done fi } _cadf_backup_once() { _cbo_file="$1" if [ -f "$_cbo_file" ] && [ ! -e "${_cbo_file}.cubex.bak" ]; then cp -p "$_cbo_file" "${_cbo_file}.cubex.bak" 2>/dev/null || cp "$_cbo_file" "${_cbo_file}.cubex.bak" 2>/dev/null || true fi } cubex_apply_dns_self_loop_fix() { _cadf_gw="${RESOLV_SAFE_GW:-${DEFAULT_GW:-223.5.5.5}}" if [ "$_cadf_gw" = "$LOCAL_IP" ] || [ -z "$_cadf_gw" ]; then _cadf_gw="223.5.5.5" fi _cadf_changed=0 if [ -f /etc/dhcpcd.conf ] || command -v dhcpcd >/dev/null 2>&1; then if [ -f /etc/dhcpcd.conf ] && grep -Eq '^[[:space:]]*nohook[[:space:]].*resolv\.conf' /etc/dhcpcd.conf 2>/dev/null; then msg "${CYAN} ℹ️ /etc/dhcpcd.conf 已包含 nohook resolv.conf,跳过重复追加。${NC}" elif [ -f /etc/dhcpcd.conf ] && grep -Fq '# cubex-managed' /etc/dhcpcd.conf 2>/dev/null; then msg "${CYAN} ℹ️ /etc/dhcpcd.conf 已存在 # cubex-managed 标记,跳过重复追加。${NC}" else _cadf_backup_once /etc/dhcpcd.conf if printf '\n# cubex-managed-next\nnohook resolv.conf\n' >> /etc/dhcpcd.conf 2>/dev/null; then msg "${GREEN} ✓ 已幂等写入 /etc/dhcpcd.conf (nohook resolv.conf # cubex-managed)${NC}" _cadf_changed=1 if command -v systemctl >/dev/null 2>&1 && systemctl is-active --quiet dhcpcd 2>/dev/null; then systemctl reload-or-restart dhcpcd >/dev/null 2>&1 || true elif command -v service >/dev/null 2>&1; then service dhcpcd restart >/dev/null 2>&1 || true fi else msg "${YELLOW} ⚠️ 无法写入 /etc/dhcpcd.conf,请手动按指引配置。${NC}" fi fi fi if [ -f /etc/dhcp/dhclient.conf ] || { command -v dhclient >/dev/null 2>&1 && [ -d /etc/dhcp ]; }; then if [ -f /etc/dhcp/dhclient.conf ] && grep -Eq '^[[:space:]]*supersede[[:space:]]+domain-name-servers' /etc/dhcp/dhclient.conf 2>/dev/null; then msg "${CYAN} ℹ️ /etc/dhcp/dhclient.conf 已配置 supersede domain-name-servers,跳过重复追加。${NC}" elif [ -f /etc/dhcp/dhclient.conf ] && grep -Fq '# cubex-managed' /etc/dhcp/dhclient.conf 2>/dev/null; then msg "${CYAN} ℹ️ /etc/dhcp/dhclient.conf 已存在 # cubex-managed 标记,跳过重复追加。${NC}" else _cadf_backup_once /etc/dhcp/dhclient.conf if printf '\n# cubex-managed-next\nsupersede domain-name-servers %s, 223.5.5.5;\n' "$_cadf_gw" >> /etc/dhcp/dhclient.conf 2>/dev/null; then msg "${GREEN} ✓ 已幂等写入 /etc/dhcp/dhclient.conf (supersede domain-name-servers # cubex-managed)${NC}" _cadf_changed=1 else msg "${YELLOW} ⚠️ 无法写入 /etc/dhcp/dhclient.conf,请手动按指引配置。${NC}" fi fi fi if command -v nmcli >/dev/null 2>&1 && nmcli -t -f RUNNING general 2>/dev/null | grep -qi running; then _cadf_nm_updated=0 for _cadf_nm_uuid in $(nmcli -t -f UUID connection show --active 2>/dev/null || true); do [ -z "$_cadf_nm_uuid" ] && continue _cadf_nm_cur=$(nmcli -g ipv4.dns connection show "$_cadf_nm_uuid" 2>/dev/null || true) _cadf_nm_ign=$(nmcli -g ipv4.ignore-auto-dns connection show "$_cadf_nm_uuid" 2>/dev/null || true) if [ "$_cadf_nm_ign" != "yes" ] || [ -z "$_cadf_nm_cur" ] || printf '%s\n' "$_cadf_nm_cur" | grep -Eq "(^|[,[:space:]])(127\.0\.0\.1|${LOCAL_IP})([,[:space:]]|$)"; then if nmcli connection modify "$_cadf_nm_uuid" ipv4.dns "${_cadf_gw},223.5.5.5" ipv4.ignore-auto-dns yes >/dev/null 2>&1; then nmcli connection up "$_cadf_nm_uuid" >/dev/null 2>&1 || true _cadf_nm_updated=1 _cadf_changed=1 fi fi done if [ "$_cadf_nm_updated" -eq 1 ]; then msg "${GREEN} ✓ 已通过 NetworkManager (nmcli) 固化活跃连接上游 DNS (${_cadf_gw}, 223.5.5.5)${NC}" fi fi if command -v systemctl >/dev/null 2>&1 && systemctl is-active --quiet systemd-resolved 2>/dev/null; then if mkdir -p /etc/systemd/resolved.conf.d 2>/dev/null; then if { printf '# cubex-managed systemd-resolved anti-loop upstream\n' printf '[Resolve]\n' printf 'DNS=%s 223.5.5.5\n' "$_cadf_gw" printf 'FallbackDNS=119.29.29.29\n' } > /etc/systemd/resolved.conf.d/99-cubex.conf 2>/dev/null; then systemctl restart systemd-resolved >/dev/null 2>&1 || true msg "${GREEN} ✓ 已幂等写入 /etc/systemd/resolved.conf.d/99-cubex.conf 并重载 systemd-resolved${NC}" _cadf_changed=1 fi fi fi if [ -f /etc/resolv.conf ] && [ ! -L /etc/resolv.conf ]; then if [ -n "$RESOLV_LOOP_MATCHES" ] || [ "${CUBEX_FIX_DNS_EXPLICIT:-0}" = "1" ]; then _cadf_backup_once /etc/resolv.conf if { printf '# cubex-managed resolv.conf (do not use chattr +i)\n' printf 'nameserver %s\n' "$_cadf_gw" printf 'nameserver 223.5.5.5\n' printf 'nameserver 119.29.29.29\n' } > /etc/resolv.conf 2>/dev/null; then msg "${GREEN} ✓ 已更新 /etc/resolv.conf 为独立上游 DNS (${_cadf_gw}, 223.5.5.5, 119.29.29.29)${NC}" _cadf_changed=1 else msg "${YELLOW} ⚠️ 无法覆写 /etc/resolv.conf(可能为只读或符号链接),请检查权限或使用上述持久化方案。${NC}" fi fi fi [ "$_cadf_changed" -eq 1 ] && check_resolv_self_loop || true } cubex_verify_panel_alive() { _cvpa_host="${1:-127.0.0.1}" _cvpa_port="${2:-2026}" _cvpa_max="${3:-15}" _cvpa_exec_prefix="${4:-}" _cvpa_i=0 while [ "$_cvpa_i" -lt "$_cvpa_max" ]; do if [ -z "$_cvpa_exec_prefix" ]; then if command -v curl >/dev/null 2>&1; then if curl -fsS -m 2 "http://127.0.0.1:${_cvpa_port}/api/health" >/dev/null 2>&1 || \ curl -fsS -m 2 "http://${_cvpa_host}:${_cvpa_port}/api/health" >/dev/null 2>&1; then return 0 fi elif command -v wget >/dev/null 2>&1; then if wget -q -T 2 -O - "http://127.0.0.1:${_cvpa_port}/api/health" >/dev/null 2>&1 || \ wget -q -T 2 -O - "http://${_cvpa_host}:${_cvpa_port}/api/health" >/dev/null 2>&1; then return 0 fi elif command -v nc >/dev/null 2>&1; then if nc -z -w 1 127.0.0.1 "$_cvpa_port" >/dev/null 2>&1; then return 0 fi fi else if [ "$_cvpa_host" != "127.0.0.1" ] && [ -n "$_cvpa_host" ]; then if command -v curl >/dev/null 2>&1 && curl -fsS -m 2 "http://${_cvpa_host}:${_cvpa_port}/api/health" >/dev/null 2>&1; then return 0 elif command -v wget >/dev/null 2>&1 && wget -q -T 2 -O - "http://${_cvpa_host}:${_cvpa_port}/api/health" >/dev/null 2>&1; then return 0 fi fi if $_cvpa_exec_prefix sh -c 'if command -v curl >/dev/null 2>&1; then curl -fsS -m 2 http://127.0.0.1:'"$_cvpa_port"'/api/health >/dev/null 2>&1; elif command -v wget >/dev/null 2>&1; then wget -q -T 2 -O - http://127.0.0.1:'"$_cvpa_port"'/api/health >/dev/null 2>&1; elif command -v nc >/dev/null 2>&1; then nc -z -w 1 127.0.0.1 '"$_cvpa_port"' >/dev/null 2>&1; else exit 1; fi' >/dev/null 2>&1; then return 0 fi fi sleep 1 _cvpa_i=$((_cvpa_i + 1)) done return 1 } # CubeX 飞牛 fnOS 专属 Docker 部署模块 (POSIX sh) run_platform_fnos() { msg "${CYAN}=================================================================${NC}" msg "${CYAN} 🌌 CubeX ${CUSTOM_VER:-${REL_TAG:-${CUBEX_DEFAULT_TAG}}} · 飞牛 fnOS 专属宿主共生透明网关部署${NC}" msg "${CYAN} 🛡️ 网关与DNS统一协同 · 全家终端零改动 · 全链路自愈${NC}" msg "${CYAN}=================================================================${NC}" if [ "$(id -u)" -ne 0 ]; then msg "${RED}❌ 请使用 root 权限或 sudo 运行此脚本!${NC}" exit 1 fi if ! command -v docker >/dev/null 2>&1; then msg "${RED}❌ 未检测到 Docker 环境,请先在飞牛应用中心安装 Docker!${NC}" exit 1 fi detect_target_arch cubex_preflight_check_deps _fnos_port="${PORT:-${CUBEX_PORT:-2026}}" _fnos_def_route=$(ip route show default 2>/dev/null | head -n 1 || true) _fnos_gw=$(printf '%s\n' "$_fnos_def_route" | awk '{print $3}' || true) _fnos_iface=$(printf '%s\n' "$_fnos_def_route" | awk '{print $5}' || true) _fnos_host_ip="" if [ -n "$_fnos_iface" ]; then _fnos_host_ip=$(ip -4 addr show "$_fnos_iface" 2>/dev/null | awk '/inet /{print $2}' | cut -d/ -f1 | head -n 1 || true) fi if [ -z "$_fnos_host_ip" ]; then _fnos_host_ip=$(ip route get 1.1.1.1 2>/dev/null | awk '{for(i=1;i<=NF;i++)if($i=="src")print $(i+1)}' | head -n 1 || true) fi msg "${GREEN}✓ 动态网络探查成功:${NC}" msg " * 飞牛 NAS IP : ${YELLOW}${_fnos_host_ip:-自动获取}${NC}" msg " * 主路由网关 IP : ${YELLOW}${_fnos_gw:-自动获取}${NC}" msg " * 物理网络接口 : ${YELLOW}${_fnos_iface:-默认}${NC}" if [ -n "${CUSTOM_DIR:-}" ]; then _fnos_storage="$CUSTOM_DIR" else _fnos_storage=$(cubex_resolve_fnos_dir) fi msg " * 数据持久化路径: ${YELLOW}${_fnos_storage} (v10 单卷 -> /app/store)${NC}" mkdir -p "${_fnos_storage}/etc/rules" "${_fnos_storage}/data" # Legacy dual-volume upgrade detection: if existing container mapped /app/etc or /app/data elsewhere, preserve non-destructively if docker ps -a --format '{{.Names}}' | grep -Eq '^cubex$'; then cubex_backup_before_v10_migration "$_fnos_storage" "$_fnos_storage" || true _fnos_old_etc=$(docker inspect -f '{{range .Mounts}}{{if eq .Destination "/app/etc"}}{{.Source}}{{end}}{{end}}' cubex 2>/dev/null || true) _fnos_old_data=$(docker inspect -f '{{range .Mounts}}{{if eq .Destination "/app/data"}}{{.Source}}{{end}}{{end}}' cubex 2>/dev/null || true) if [ -n "$_fnos_old_etc" ] && [ -d "$_fnos_old_etc" ] && [ "$_fnos_old_etc" != "${_fnos_storage}/etc" ]; then msg "${CYAN}📦 检测到旧版 /app/etc 挂载 (${_fnos_old_etc}),正在无损汇入单卷目录...${NC}" cubex_copy_missing_tree "$_fnos_old_etc" "${_fnos_storage}/etc" fi if [ -n "$_fnos_old_data" ] && [ -d "$_fnos_old_data" ] && [ "$_fnos_old_data" != "${_fnos_storage}/data" ]; then msg "${CYAN}📦 检测到旧版 /app/data 挂载 (${_fnos_old_data}),正在无损汇入单卷目录...${NC}" cubex_copy_missing_tree "$_fnos_old_data" "${_fnos_storage}/data" fi fi if [ ! -c /dev/net/tun ]; then msg "${YELLOW}🔧 正在初始化 /dev/net/tun 虚拟网卡通道...${NC}" mkdir -p /dev/net mknod /dev/net/tun c 10 200 2>/dev/null || true chmod 666 /dev/net/tun 2>/dev/null || true fi modprobe tun 2>/dev/null || true _fnos_tag="${CUSTOM_VER:-${REL_TAG:-}}" if [ -z "$_fnos_tag" ] && [ "${OFFLINE_MODE:-0}" -ne 1 ]; then cubex_resolve_latest_tag "" _fnos_tag="${REL_TAG:-${CUBEX_DEFAULT_TAG}}" fi [ -z "$_fnos_tag" ] && _fnos_tag="${CUBEX_DEFAULT_TAG}" case "$_fnos_tag" in [0-9]*) _fnos_tag="v${_fnos_tag}" ;; esac _fnos_img="fyasshole/cubex:${_fnos_tag}" msg "${GREEN}🚀 正在准备运行镜像 ${_fnos_img} (离线包 -> 精确版本 Registry -> GitHub 镜像)...${NC}" if ! cubex_pull_or_load_docker_image "$TARGET_ARCH" "${CUSTOM_PKG:-}" "$_fnos_tag" "${OFFLINE_MODE:-0}" "$_fnos_img"; then msg "${RED}❌ 无法获取 CubeX 运行镜像!(已保留现有运行容器不变)${NC}" msg "${YELLOW}💡 建议: 请上传 CubeX-*-docker-${TARGET_ARCH}.tar.gz 至 /tmp 后通过 --pkg=... 或 --offline 安装。${NC}" exit 1 fi if docker ps -a --format '{{.Names}}' | grep -Eq '^cubex$'; then msg "${YELLOW}🔄 新镜像已就绪,正在平滑替换现有 CubeX 容器...${NC}" docker stop cubex >/dev/null 2>&1 || true docker rm cubex >/dev/null 2>&1 || true fi cubex_write_install_manifest \ "${_fnos_storage}/install.manifest.json" \ "${REL_TAG:-${CUBEX_DEFAULT_TAG}}" \ "fnos" \ "docker" \ "${_fnos_storage}" \ "single_store" \ "/app/store" \ "/app/store/data" \ "/app/store/etc" \ "${_fnos_port}" \ "host" cubex_detect_memory_tier msg "${GREEN}🚀 正在启动 CubeX 宿主共生容器 (自适应内存配额: GOMEMLIMIT=${HOST_GOMEMLIMIT}, GOGC=${HOST_GOGC})...${NC}" docker run -d \ --name cubex \ --restart always \ --net=host \ --privileged \ --cap-add=NET_ADMIN \ --cap-add=NET_RAW \ --device /dev/net/tun:/dev/net/tun \ -v "${_fnos_storage}:/app/store" \ -v /etc/localtime:/etc/localtime:ro \ -e TZ=Asia/Shanghai \ -e CUBEX_ENV=production \ -e CUBEX_STORAGE_MODE=single_store \ -e CUBEX_HOST_PLATFORM=fnos \ -e CUBEX_DEPLOY_METHOD=docker \ -e GOMEMLIMIT="${HOST_GOMEMLIMIT}" \ -e GOGC="${HOST_GOGC}" \ -e CUBEX_PORT=${_fnos_port} \ -e CUBEX_LISTEN=:${_fnos_port} \ "${_fnos_img}" cubex_write_unix_uninstaller "$_fnos_storage" "docker" "cubex" "${_fnos_storage}/install.manifest.json" if ! cubex_verify_panel_alive "${_fnos_host_ip:-127.0.0.1}" "$_fnos_port" "15" "docker exec cubex"; then msg "${RED}=================================================================${NC}" msg "${RED}❌ [存活校验失败] 飞牛 fnOS 容器已启动但 ${_fnos_port} 端口未就绪!${NC}" msg "${YELLOW}--- 最近 20 行容器日志 ---${NC}" docker logs --tail 20 cubex 2>&1 || true msg "${RED}=================================================================${NC}" exit 1 fi msg "\n${GREEN}=================================================================${NC}" msg "${GREEN} 🎉 恭喜!CubeX ${REL_TAG:-${CUBEX_DEFAULT_TAG}} 在飞牛 fnOS 上启动成功!${NC}" msg "${GREEN}=================================================================${NC}" msg "👉 Web 控制台访问入口: ${CYAN}http://${_fnos_host_ip:-127.0.0.1}:${_fnos_port}${NC}" msg "👉 干净卸载器已落盘 : ${YELLOW}sh ${_fnos_storage}/uninstall.sh [--purge]${NC}" _fnos_5666_ok=0 if command -v curl >/dev/null 2>&1 && curl -fsS -m 2 -o /dev/null "http://127.0.0.1:5666/" 2>/dev/null; then _fnos_5666_ok=1 elif command -v ss >/dev/null 2>&1 && ss -ltn 2>/dev/null | grep -Eq ':5666[[:space:]]'; then _fnos_5666_ok=1 fi if [ "$_fnos_5666_ok" -eq 1 ]; then msg "👉 飞牛管理页存活检查: ${GREEN}http://${_fnos_host_ip:-127.0.0.1}:5666 运行正常(CubeX 严守不占用 :80/:5666)${NC}" else msg "${YELLOW}⚠️ 检测到飞牛管理页 :5666 当前未监听(若升级前曾误用旧版镜像占用了 :80,请执行:systemctl restart trim_nginx 即可恢复飞牛桌面)${NC}" fi msg "👉 主路由联动两步法:" msg " 1. 登录控制台【宿主共生】输入 RouterOS / 爱快凭据,点击一键自愈;" msg " 2. 全屋终端保持默认 DHCP,网关+DNS全指主路由,永不断线!" } # CubeX OpenWrt / iStoreOS Docker Macvlan 部署模块 (POSIX sh) run_platform_openwrt_docker() { msg "${CYAN}========================================================================${NC}" msg "${CYAN}🌌 正在启动 CubeX 宿主共生零感网络系统 · OpenWrt Docker 自动化编排流水线${NC}" msg "${CYAN}========================================================================${NC}" detect_target_arch cubex_preflight_check_deps ARCH="$TARGET_ARCH" OW_PORT="${PORT:-${CUBEX_PORT:-2026}}" case "$OW_PORT" in ''|*[!0-9]*) msg "${RED}❌ 无效端口号: ${OW_PORT}${NC}" >&2 exit 1 ;; esac msg "${GREEN}✅ [1/6 硬件识别] 检测到宿主架构: $(uname -m) ➔ 匹配运行镜像架构: ${ARCH}${NC}" msg "${CYAN}🔍 [2/6 Docker检测] 正在巡检 OpenWrt Docker 服务与守护进程...${NC}" if ! command -v docker >/dev/null 2>&1; then msg "${YELLOW}⚠️ 未检测到 Docker 命令行工具,正在尝试自动安装...${NC}" if command -v apk >/dev/null 2>&1; then msg "${CYAN} -> 识别到新一代 apk 包管理器 (OpenWrt 24+ / iStoreOS 25+),正在执行 apk 安装...${NC}" apk update apk add dockerd docker docker-compose luci-app-dockerman curl ca-certificates 2>/dev/null || apk add dockerd docker 2>/dev/null || true elif command -v opkg >/dev/null 2>&1; then msg "${CYAN} -> 识别到 opkg 包管理器,正在执行 opkg 安装...${NC}" if [ -f /etc/opkg/distfeeds.conf ]; then sed -i 's/downloads.openwrt.org/mirrors.tuna.tsinghua.edu.cn\/openwrt/g' /etc/opkg/distfeeds.conf 2>/dev/null || true fi opkg update opkg install dockerd docker luci-app-dockerman curl ca-certificates ca-bundle 2>/dev/null || opkg install dockerd docker 2>/dev/null || true fi fi if ! docker info >/dev/null 2>&1; then msg "${YELLOW}⚠️ Docker 守护进程尚未处于活跃状态,正在自动启用并拉起服务...${NC}" if [ -f /etc/init.d/dockerd ]; then /etc/init.d/dockerd enable >/dev/null 2>&1 || true /etc/init.d/dockerd start >/dev/null 2>&1 || true fi if command -v uci >/dev/null 2>&1; then uci -q set dockerd.globals.log_level='warn' 2>/dev/null || true uci -q commit dockerd 2>/dev/null || true fi for _ow_i in 1 2 3 4 5 6 7 8 9 10; do docker info >/dev/null 2>&1 && break sleep 1 done fi if ! docker info >/dev/null 2>&1; then msg "${RED}❌ Docker 守护进程无法自动启动!${NC}" msg "${RED} 请在 OpenWrt/iStoreOS 后台【Docker】或【系统服务】中手动开启 Docker 服务后重新运行本脚本。${NC}" exit 1 fi msg "${GREEN}✅ [2/6 Docker就绪] OpenWrt Docker 守护进程运行正常${NC}" LAN_IF="br-lan" if ! ip link show "$LAN_IF" >/dev/null 2>&1; then LAN_IF=$(uci -q get network.lan.device 2>/dev/null || true) fi if [ -z "$LAN_IF" ] || ! ip link show "$LAN_IF" >/dev/null 2>&1; then LAN_IF=$(ip route show default 2>/dev/null | awk '{for(i=1;i<=NF;i++) if($i=="dev") print $(i+1)}' | head -n 1) fi if [ -z "$LAN_IF" ] || ! ip link show "$LAN_IF" >/dev/null 2>&1; then LAN_IF=$(ip -4 addr show 2>/dev/null | grep -E 'inet [0-9.]+' | grep -v '127.0.0.1' | awk '{print $NF}' | head -n 1) fi [ -z "$LAN_IF" ] && LAN_IF="eth0" ROUTER_IP=$(uci -q get network.lan.ipaddr 2>/dev/null || ip -4 addr show "$LAN_IF" 2>/dev/null | grep -oE 'inet [0-9.]+' | awk '{print $2}' | head -n 1) if [ -z "$ROUTER_IP" ]; then ROUTER_IP=$(ip route show default 2>/dev/null | awk '{print $3}' | head -n 1) fi if [ -z "$ROUTER_IP" ]; then msg "${RED}❌ 无法自动嗅探局域网主网关与子网,请检查网络配置或网卡连接!${NC}" exit 1 fi IP_PREFIX=$(printf '%s\n' "$ROUTER_IP" | cut -d. -f1-3) SUBNET="${IP_PREFIX}.0/24" DEF_ROUTE_DEV=$(ip route show default 2>/dev/null | awk '{for(i=1;i<=NF;i++) if($i=="dev") print $(i+1)}' | head -n 1) UPSTREAM_GW=$(ip route show default 2>/dev/null | awk '{print $3}' | head -n 1) UPSTREAM_PREFIX=$(printf '%s\n' "$UPSTREAM_GW" | cut -d. -f1-3) if [ -n "$UPSTREAM_GW" ] && [ "$UPSTREAM_PREFIX" = "$IP_PREFIX" ] && [ "$UPSTREAM_GW" != "$ROUTER_IP" ] && ! printf '%s\n' "$DEF_ROUTE_DEV" | grep -qE '^(ppp|wan)'; then MACVLAN_GW="$UPSTREAM_GW" msg "${GREEN}✅ [3/6 模式识别] 当前 OpenWrt 处于旁路由底座,上级物理主网关为: ${UPSTREAM_GW}${NC}" else MACVLAN_GW="$ROUTER_IP" msg "${GREEN}✅ [3/6 模式识别] 当前 OpenWrt 处于主路由底座 (WAN 出口: ${DEF_ROUTE_DEV:-pppoe-wan}),主网关为: ${ROUTER_IP}${NC}" fi NET_NAME="cubex-macvlan" CONTAINER_NAME="cubex" OW_DATA_DIR="${CUSTOM_DIR:-/etc/cubex}" EXISTING_CUBEX_IP=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' "$CONTAINER_NAME" 2>/dev/null || true) msg "${CYAN}📦 [4/6 镜像准备] 正在准备 CubeX 运行镜像 (离线包 -> 国内 Registry -> GitHub 镜像)...${NC}" IMAGE="cubex:latest" if ! cubex_pull_or_load_docker_image "$ARCH" "${CUSTOM_PKG:-}" "${CUSTOM_VER:-}" "${OFFLINE_MODE:-0}" "$IMAGE"; then msg "${RED}❌ 无法获取 CubeX 运行镜像!(已保留现有运行容器不变)${NC}" msg "${YELLOW}💡 建议解决方式:${NC}" msg " 1. 检查路由器是否能正常连接网络;" msg " 2. 或下载 CubeX-*-docker-${ARCH}.tar.gz 传至 /tmp 后执行: sh install.sh --platform=openwrt-docker --pkg=/tmp/CubeX-*-docker-${ARCH}.tar.gz" exit 1 fi if docker ps -a --format '{{.Names}}' | grep -Eq "^${CONTAINER_NAME}$"; then _ow_old_etc=$(docker inspect -f '{{range .Mounts}}{{if eq .Destination "/app/etc"}}{{.Source}}{{end}}{{end}}' "$CONTAINER_NAME" 2>/dev/null || true) _ow_old_data=$(docker inspect -f '{{range .Mounts}}{{if eq .Destination "/app/data"}}{{.Source}}{{end}}{{end}}' "$CONTAINER_NAME" 2>/dev/null || true) if [ -n "$_ow_old_etc" ] && [ -d "$_ow_old_etc" ] && [ "$_ow_old_etc" != "${OW_DATA_DIR}/etc" ]; then cubex_copy_missing_tree "$_ow_old_etc" "${OW_DATA_DIR}/etc" fi if [ -n "$_ow_old_data" ] && [ -d "$_ow_old_data" ] && [ "$_ow_old_data" != "${OW_DATA_DIR}/data" ]; then cubex_copy_missing_tree "$_ow_old_data" "${OW_DATA_DIR}/data" fi fi docker rm -f "$CONTAINER_NAME" >/dev/null 2>&1 || true if docker network inspect "$NET_NAME" >/dev/null 2>&1; then docker network rm "$NET_NAME" >/dev/null 2>&1 || true fi CUBEX_IP="" if [ -n "$EXISTING_CUBEX_IP" ] && [ "$(printf '%s\n' "$EXISTING_CUBEX_IP" | cut -d. -f1-3)" = "$IP_PREFIX" ] && [ "$EXISTING_CUBEX_IP" != "$ROUTER_IP" ] && [ "$EXISTING_CUBEX_IP" != "$UPSTREAM_GW" ]; then CUBEX_IP="$EXISTING_CUBEX_IP" else for _ow_cand in 11 12 13 14 15 211 212 213; do TEST_IP="${IP_PREFIX}.${_ow_cand}" if [ "$TEST_IP" != "$ROUTER_IP" ] && [ "$TEST_IP" != "$UPSTREAM_GW" ]; then if ! ping -c 1 -W 1 "$TEST_IP" >/dev/null 2>&1; then CUBEX_IP="$TEST_IP" break fi fi done fi [ -z "$CUBEX_IP" ] && CUBEX_IP="${IP_PREFIX}.11" SHIM_IP="${IP_PREFIX}.228" [ "$SHIM_IP" = "$CUBEX_IP" ] && SHIM_IP="${IP_PREFIX}.229" msg "${GREEN}✅ [4/6 自动配赋] 分配 CubeX 独立物理 IP: ${CUBEX_IP} (Macvlan 网关: ${MACVLAN_GW})${NC}" msg "${CYAN}🔧 [5/6 网络编排] 准备 Macvlan 隔离网络 (${NET_NAME} 绑定 ${LAN_IF})...${NC}" if docker network inspect "$NET_NAME" >/dev/null 2>&1; then msg "${GREEN} -> 检测到已存在 Macvlan 网络 (${NET_NAME}),自动复用现有网络配置${NC}" else docker network create -d macvlan \ --subnet="$SUBNET" \ --gateway="$MACVLAN_GW" \ -o parent="$LAN_IF" \ "$NET_NAME" fi if ! ip link show macvlan-shim >/dev/null 2>&1; then ip link add macvlan-shim link "$LAN_IF" type macvlan mode bridge fi bridge link set dev "$LAN_IF" hairpin on 2>/dev/null || true ip addr flush dev macvlan-shim 2>/dev/null || true ip addr add "${SHIM_IP}/24" dev macvlan-shim ip link set macvlan-shim up ip route replace "${CUBEX_IP}/32" dev macvlan-shim src "$SHIM_IP" 2>/dev/null || ip route add "${CUBEX_IP}/32" dev macvlan-shim 2>/dev/null || true sysctl -w net.ipv4.conf.all.rp_filter=0 >/dev/null 2>&1 || true sysctl -w net.ipv4.conf.default.rp_filter=0 >/dev/null 2>&1 || true sysctl -w "net.ipv4.conf.macvlan-shim.rp_filter=0" >/dev/null 2>&1 || true sysctl -w "net.ipv4.conf.${LAN_IF}.rp_filter=0" >/dev/null 2>&1 || true if command -v uci >/dev/null 2>&1; then uci -q delete network.cubex_shim || true uci set network.cubex_shim=interface uci set network.cubex_shim.device='macvlan-shim' uci set network.cubex_shim.proto='static' uci set network.cubex_shim.ipaddr="$SHIM_IP" uci set network.cubex_shim.netmask='255.255.255.0' uci -q delete network.cubex_shim_route || true uci set network.cubex_shim_route=route uci set network.cubex_shim_route.interface='cubex_shim' uci set network.cubex_shim_route.target="$CUBEX_IP" uci set network.cubex_shim_route.netmask='255.255.255.255' uci commit network 2>/dev/null || true uci -q del_list firewall.@zone[0].device='macvlan-shim' || true uci add_list firewall.@zone[0].device='macvlan-shim' 2>/dev/null || true uci -q del_list firewall.@zone[0].network='cubex_shim' || true uci add_list firewall.@zone[0].network='cubex_shim' 2>/dev/null || true uci -q delete firewall.cubex_dnat || true uci set firewall.cubex_dnat=redirect uci set firewall.cubex_dnat.name="CubeX-Panel-${OW_PORT}" uci set firewall.cubex_dnat.src='lan' uci set firewall.cubex_dnat.src_dport="$OW_PORT" uci set firewall.cubex_dnat.dest='lan' uci set firewall.cubex_dnat.dest_ip="$CUBEX_IP" uci set firewall.cubex_dnat.dest_port="$OW_PORT" uci set firewall.cubex_dnat.proto='tcp' uci set firewall.cubex_dnat.target='DNAT' uci -q delete firewall.cubex_hairpin || true uci set firewall.cubex_hairpin=nat uci set firewall.cubex_hairpin.name='CubeX-Hairpin-NAT' uci set firewall.cubex_hairpin.src='lan' uci set firewall.cubex_hairpin.dest_ip="$CUBEX_IP" uci set firewall.cubex_hairpin.dest_port="$OW_PORT" uci set firewall.cubex_hairpin.proto='tcp' uci set firewall.cubex_hairpin.target='MASQUERADE' uci commit firewall 2>/dev/null || true if [ "$(uci -q get firewall.@defaults[0].flow_offloading)" = "1" ] || [ "$(uci -q get firewall.@defaults[0].flow_offloading_hw)" = "1" ]; then msg "${YELLOW} -> 检测到 OpenWrt 开启了 Flow Offloading (加速流表),注入豁免规则以确保 100% 规则分流...${NC}" mkdir -p /etc/nftables.d 2>/dev/null || true cat << 'NFT_EOF' > /etc/nftables.d/10-cubex-offload-exempt.nft chain cubex_flow_exempt { type filter hook forward priority -5; policy accept; ip daddr 198.18.0.0/15 counter return ip saddr 198.18.0.0/15 counter return } NFT_EOF nft insert rule inet fw4 forward ip daddr 198.18.0.0/15 counter return 2>/dev/null || true nft insert rule inet fw4 forward ip saddr 198.18.0.0/15 counter return 2>/dev/null || true fi /etc/init.d/firewall reload >/dev/null 2>&1 || true fi if [ -f /etc/rc.local ]; then sed -i '/^# BEGIN CUBEX$/,/^# END CUBEX$/d' /etc/rc.local 2>/dev/null || true sed -i '/macvlan-shim/d' /etc/rc.local 2>/dev/null || true sed -i '/cubex.*ip route/d' /etc/rc.local 2>/dev/null || true RC_TMP="/tmp/rc.local.cubex.$$" grep -v '^exit 0$' /etc/rc.local > "$RC_TMP" 2>/dev/null || true cat << RCEOF >> "$RC_TMP" # BEGIN CUBEX ip link add macvlan-shim link ${LAN_IF} type macvlan mode bridge 2>/dev/null || true ip addr add ${SHIM_IP}/24 dev macvlan-shim 2>/dev/null || true ip link set macvlan-shim up 2>/dev/null || true ip route replace ${CUBEX_IP}/32 dev macvlan-shim 2>/dev/null || true docker exec cubex ip route replace ${ROUTER_IP}/32 via ${SHIM_IP} dev eth0 2>/dev/null || true # END CUBEX exit 0 RCEOF mv "$RC_TMP" /etc/rc.local chmod +x /etc/rc.local 2>/dev/null || true fi mkdir -p "${OW_DATA_DIR}/data" "${OW_DATA_DIR}/etc/rules" cubex_write_install_manifest \ "${OW_DATA_DIR}/install.manifest.json" \ "${REL_TAG:-${CUBEX_DEFAULT_TAG}}" \ "openwrt" \ "macvlan" \ "${OW_DATA_DIR}" \ "single_store" \ "/app/store" \ "/app/store/data" \ "/app/store/etc" \ "${OW_PORT}" \ "macvlan" modprobe tun 2>/dev/null || true if [ ! -c /dev/net/tun ]; then mkdir -p /dev/net 2>/dev/null || true mknod /dev/net/tun c 10 200 2>/dev/null || true chmod 666 /dev/net/tun 2>/dev/null || true fi DEV_TUN_OPT="" [ -c /dev/net/tun ] && DEV_TUN_OPT="--device=/dev/net/tun" cubex_detect_memory_tier msg "${CYAN}📦 [5/6 容器拉起] 正在拉起 CubeX 容器 (${CONTAINER_NAME} @ ${CUBEX_IP} 使用镜像: ${IMAGE}, 内存配额: ${HOST_GOMEMLIMIT})...${NC}" docker run -d \ --name "$CONTAINER_NAME" \ --restart=always \ --net="$NET_NAME" \ --ip="$CUBEX_IP" \ --cap-add=NET_ADMIN \ --cap-add=NET_RAW \ $DEV_TUN_OPT \ -e TZ=Asia/Shanghai \ -e CUBEX_PORT="${OW_PORT}" \ -e CUBEX_LISTEN=":${OW_PORT}" \ -e CUBEX_STORAGE_MODE=single_store \ -e CUBEX_HOST_PLATFORM=openwrt \ -e CUBEX_DEPLOY_METHOD=macvlan \ -e CUBEX_NETWORK_MODE=macvlan \ -e GOMEMLIMIT="${HOST_GOMEMLIMIT}" \ -e GOGC="${HOST_GOGC}" \ -v "${OW_DATA_DIR}:/app/store" \ "$IMAGE" sleep 2 docker exec "$CONTAINER_NAME" ip route add "${ROUTER_IP}/32" via "$SHIM_IP" dev eth0 2>/dev/null || true msg "${CYAN}⚡ [6/6 一键自愈] 正在下发 OpenWrt UCI 策略路由与防火墙加固...${NC}" ip route replace 198.18.0.0/15 via "$CUBEX_IP" dev "$LAN_IF" 2>/dev/null || ip route replace 198.18.0.0/15 via "$CUBEX_IP" 2>/dev/null || true uci -q delete network.cubex_fakeip || true uci set network.cubex_fakeip=route uci set network.cubex_fakeip.interface='lan' uci set network.cubex_fakeip.target='198.18.0.0' uci set network.cubex_fakeip.netmask='255.254.0.0' uci set network.cubex_fakeip.gateway="$CUBEX_IP" uci commit network uci -q delete dhcp.@dnsmasq[0].rebind_domain 2>/dev/null || true uci add_list dhcp.@dnsmasq[0].rebind_domain='198.18.0.0/15' uci set dhcp.@dnsmasq[0].rebind_protection='0' uci -q delete dhcp.@dnsmasq[0].server 2>/dev/null || true uci add_list dhcp.@dnsmasq[0].server="${CUBEX_IP}" uci set dhcp.@dnsmasq[0].noresolv='1' for _ow_opt in $(uci -q get dhcp.lan.dhcp_option 2>/dev/null); do case "$_ow_opt" in 6,*) uci -q del_list dhcp.lan.dhcp_option="$_ow_opt" ;; esac done uci add_list dhcp.lan.dhcp_option="6,${CUBEX_IP}" uci commit dhcp /etc/init.d/dnsmasq reload >/dev/null 2>&1 || /etc/init.d/dnsmasq restart >/dev/null 2>&1 || true uci set dhcp.lan.dns_service='0' 2>/dev/null || true uci -q delete dhcp.lan.dns 2>/dev/null || true uci set dhcp.lan.ra_dns='0' 2>/dev/null || true uci commit dhcp 2>/dev/null || true /etc/init.d/odhcpd enable >/dev/null 2>&1 || true /etc/init.d/odhcpd reload >/dev/null 2>&1 || /etc/init.d/odhcpd restart >/dev/null 2>&1 || true sysctl -w net.ipv4.ip_forward=1 >/dev/null 2>&1 || true sysctl -w net.ipv4.conf.all.rp_filter=0 >/dev/null 2>&1 || true uci set firewall.@zone[0].forward='ACCEPT' 2>/dev/null || true uci -q delete firewall.cubex_bypass || true uci set firewall.cubex_bypass=rule uci set firewall.cubex_bypass.name='CubeX-Bypass-Forward' uci set firewall.cubex_bypass.src='*' uci set firewall.cubex_bypass.dest='*' uci set firewall.cubex_bypass.proto='all' uci set firewall.cubex_bypass.target='ACCEPT' uci -q delete firewall.cubex_dns_redir_udp || true uci set firewall.cubex_dns_redir_udp=redirect uci set firewall.cubex_dns_redir_udp.name='CubeX-DNS-Redirect-UDP' uci set firewall.cubex_dns_redir_udp.src='lan' uci set firewall.cubex_dns_redir_udp.src_dport='53' uci set firewall.cubex_dns_redir_udp.dest='lan' uci set firewall.cubex_dns_redir_udp.dest_ip="$CUBEX_IP" uci set firewall.cubex_dns_redir_udp.dest_port='53' uci set firewall.cubex_dns_redir_udp.proto='udp' uci set firewall.cubex_dns_redir_udp.target='DNAT' uci set firewall.cubex_dns_redir_udp.enabled='1' uci -q delete firewall.cubex_dns_redir_tcp || true uci set firewall.cubex_dns_redir_tcp=redirect uci set firewall.cubex_dns_redir_tcp.name='CubeX-DNS-Redirect-TCP' uci set firewall.cubex_dns_redir_tcp.src='lan' uci set firewall.cubex_dns_redir_tcp.src_dport='53' uci set firewall.cubex_dns_redir_tcp.dest='lan' uci set firewall.cubex_dns_redir_tcp.dest_ip="$CUBEX_IP" uci set firewall.cubex_dns_redir_tcp.dest_port='53' uci set firewall.cubex_dns_redir_tcp.proto='tcp' uci set firewall.cubex_dns_redir_tcp.target='DNAT' uci set firewall.cubex_dns_redir_tcp.enabled='1' uci commit firewall 2>/dev/null || true if [ "$(uci -q get firewall.@defaults[0].flow_offloading)" = "1" ] || [ "$(uci -q get firewall.@defaults[0].flow_offloading_hw)" = "1" ]; then mkdir -p /etc/nftables.d 2>/dev/null || true cat << 'NFT_EOF' > /etc/nftables.d/10-cubex-offload-exempt.nft chain cubex_flow_exempt { type filter hook forward priority -5; policy accept; ip daddr 198.18.0.0/15 counter return ip saddr 198.18.0.0/15 counter return } NFT_EOF nft insert rule inet fw4 forward ip daddr 198.18.0.0/15 counter return 2>/dev/null || true nft insert rule inet fw4 forward ip saddr 198.18.0.0/15 counter return 2>/dev/null || true fi iptables -C FORWARD -d 198.18.0.0/15 -j ACCEPT 2>/dev/null || iptables -I FORWARD 1 -d 198.18.0.0/15 -j ACCEPT 2>/dev/null || true iptables -C FORWARD -s 198.18.0.0/15 -j ACCEPT 2>/dev/null || iptables -I FORWARD 1 -s 198.18.0.0/15 -j ACCEPT 2>/dev/null || true /etc/init.d/firewall reload >/dev/null 2>&1 || true cat << EOF > /usr/bin/cubex-watchdog.sh #!/bin/sh CUBEX_IP="${CUBEX_IP}" CUBEX_PORT="${OW_PORT}" BACKUP_DNS="223.5.5.5" CONTAINER_NAME="${CONTAINER_NAME}" EOF cat << 'EOF' >> /usr/bin/cubex-watchdog.sh _wd_probe_http() { _wph_url="$1" if command -v curl >/dev/null 2>&1; then curl -fsS --connect-timeout 1 -m 1 "$_wph_url" >/dev/null 2>&1 return $? elif command -v wget >/dev/null 2>&1; then if wget --version 2>&1 | grep -qi "GNU Wget"; then wget -q -t 1 -T 1 -O - "$_wph_url" >/dev/null 2>&1 return $? fi if command -v timeout >/dev/null 2>&1; then timeout 2 wget -q -T 1 -O - "$_wph_url" >/dev/null 2>&1 || timeout -t 2 wget -q -T 1 -O - "$_wph_url" >/dev/null 2>&1 return $? fi wget -q -T 1 -O - "$_wph_url" >/dev/null 2>&1 return $? fi return 1 } while true; do _wd_alive=0 if _wd_probe_http "http://${CUBEX_IP}:${CUBEX_PORT}/api/health" || \ docker exec "${CONTAINER_NAME}" sh -c 'if command -v curl >/dev/null 2>&1; then curl -fsS --connect-timeout 1 -m 1 http://127.0.0.1:'"${CUBEX_PORT}"'/api/health >/dev/null 2>&1; elif command -v wget >/dev/null 2>&1; then wget -q -T 1 -O - http://127.0.0.1:'"${CUBEX_PORT}"'/api/health >/dev/null 2>&1; else exit 1; fi' >/dev/null 2>&1; then _wd_alive=1 fi _wd_route=$(ip route show 198.18.0.0/15 2>/dev/null || true) _wd_opts=$(uci -q get dhcp.lan.dhcp_option 2>/dev/null || true) _wd_redir=$(uci -q get firewall.cubex_dns_redir_udp.enabled 2>/dev/null || true) [ -z "$_wd_redir" ] && _wd_redir="1" if [ "$_wd_alive" -eq 1 ]; then _need_restore=0 case "$_wd_route" in *"via ${CUBEX_IP}"*) ;; *) _need_restore=1 ;; esac case " $_wd_opts " in *" 6,${CUBEX_IP} "*) ;; *) _need_restore=1 ;; esac [ "$_wd_redir" = "0" ] && _need_restore=1 if [ "$_need_restore" -eq 1 ]; then logger -t cubex-watchdog "🛡️ CubeX Gateway revived! Restoring Fake-IP route and DNS to ${CUBEX_IP}" ip route del 198.18.0.0/16 2>/dev/null || true ip route del 198.19.0.0/16 2>/dev/null || true ip route replace 198.18.0.0/15 via "${CUBEX_IP}" 2>/dev/null || true if command -v conntrack >/dev/null 2>&1; then for _w_ct in 198.18.0.0/15 198.18.0.0/16 198.19.0.0/16; do conntrack -D -d "$_w_ct" >/dev/null 2>&1 || true conntrack -D -s "$_w_ct" >/dev/null 2>&1 || true done fi for _opt in $_wd_opts; do case "$_opt" in 6,*) uci -q del_list dhcp.lan.dhcp_option="$_opt" || true ;; esac done uci add_list dhcp.lan.dhcp_option="6,${CUBEX_IP}" uci -q delete dhcp.@dnsmasq[0].server 2>/dev/null || true uci add_list dhcp.@dnsmasq[0].server="${CUBEX_IP}" uci set dhcp.@dnsmasq[0].noresolv='1' uci set firewall.cubex_dns_redir_udp.enabled='1' 2>/dev/null || true uci set firewall.cubex_dns_redir_tcp.enabled='1' 2>/dev/null || true uci commit dhcp 2>/dev/null || true uci commit firewall 2>/dev/null || true /etc/init.d/dnsmasq reload >/dev/null 2>&1 || true /etc/init.d/firewall reload >/dev/null 2>&1 || true fi else _need_failover=0 case "$_wd_route" in *blackhole*) ;; *) _need_failover=1 ;; esac case " $_wd_opts " in *" 6,${CUBEX_IP} "*) _need_failover=1 ;; esac [ "$_wd_redir" != "0" ] && _need_failover=1 if [ "$_need_failover" -eq 1 ]; then logger -t cubex-watchdog "🚨 CubeX Gateway DOWN! 0-second failover: cutting Fake-IP route and switching to ${BACKUP_DNS}" ip route del 198.18.0.0/16 2>/dev/null || true ip route del 198.19.0.0/16 2>/dev/null || true ip route replace blackhole 198.18.0.0/15 2>/dev/null || true if command -v conntrack >/dev/null 2>&1; then for _w_ct in 198.18.0.0/15 198.18.0.0/16 198.19.0.0/16; do conntrack -D -d "$_w_ct" >/dev/null 2>&1 || true conntrack -D -s "$_w_ct" >/dev/null 2>&1 || true done fi for _opt in $_wd_opts; do case "$_opt" in 6,*) uci -q del_list dhcp.lan.dhcp_option="$_opt" || true ;; esac done uci add_list dhcp.lan.dhcp_option="6,${BACKUP_DNS}" uci -q delete dhcp.@dnsmasq[0].server 2>/dev/null || true uci add_list dhcp.@dnsmasq[0].server="${BACKUP_DNS}" uci set dhcp.@dnsmasq[0].noresolv='0' uci set firewall.cubex_dns_redir_udp.enabled='0' 2>/dev/null || true uci set firewall.cubex_dns_redir_tcp.enabled='0' 2>/dev/null || true uci commit dhcp 2>/dev/null || true uci commit firewall 2>/dev/null || true /etc/init.d/dnsmasq reload >/dev/null 2>&1 || true /etc/init.d/firewall reload >/dev/null 2>&1 || true fi fi sleep 2 done EOF chmod +x /usr/bin/cubex-watchdog.sh cat << 'EOF' > /etc/init.d/cubex-watchdog #!/bin/sh /etc/rc.common START=95 STOP=10 USE_PROCD=1 start_service() { procd_open_instance procd_set_param command /usr/bin/cubex-watchdog.sh procd_set_param respawn 3600 5 0 procd_set_param stdout 1 procd_set_param stderr 1 procd_close_instance } EOF chmod +x /etc/init.d/cubex-watchdog /etc/init.d/cubex-watchdog enable >/dev/null 2>&1 || true /etc/init.d/cubex-watchdog restart >/dev/null 2>&1 || true mkdir -p "${OW_DATA_DIR}" cat < "${OW_DATA_DIR}/uninstall.sh" #!/bin/sh set -e PURGE_DATA=0 for _ua in "\$@"; do case "\$_ua" in --purge) PURGE_DATA=1 ;; -h|--help) printf '%s\n' "Usage: sh ${OW_DATA_DIR}/uninstall.sh [--purge]" exit 0 ;; esac done [ "\$(id -u)" -eq 0 ] || { printf '%s\n' "Error: uninstall.sh must be run as root." >&2; exit 1; } OW_DATA_DIR="${OW_DATA_DIR}" CONTAINER_NAME="${CONTAINER_NAME}" NET_NAME="${NET_NAME}" EOF cat <<'EOF' >> "${OW_DATA_DIR}/uninstall.sh" if [ -f "${OW_DATA_DIR}/install.manifest.json" ]; then _ow_mf_dir=$(sed -n 's/.*"install_dir"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "${OW_DATA_DIR}/install.manifest.json" 2>/dev/null | head -n 1 || true) if [ -n "$_ow_mf_dir" ] && [ "$_ow_mf_dir" != "/" ] && [ "$_ow_mf_dir" != "/app" ] && [ -d "$_ow_mf_dir" ]; then OW_DATA_DIR="$_ow_mf_dir" fi fi if [ -x /etc/init.d/cubex-watchdog ]; then /etc/init.d/cubex-watchdog stop >/dev/null 2>&1 || true /etc/init.d/cubex-watchdog disable >/dev/null 2>&1 || true fi rm -f /etc/init.d/cubex-watchdog /usr/bin/cubex-watchdog.sh 2>/dev/null || true if command -v docker >/dev/null 2>&1; then docker rm -f "$CONTAINER_NAME" >/dev/null 2>&1 || true docker network rm "$NET_NAME" >/dev/null 2>&1 || true fi ip link del macvlan-shim 2>/dev/null || true if [ -f /etc/rc.local ]; then sed -i '/^# BEGIN CUBEX$/,/^# END CUBEX$/d' /etc/rc.local 2>/dev/null || true fi _NFT_REMOVED=0 [ -f /etc/nftables.d/10-cubex-offload-exempt.nft ] && _NFT_REMOVED=1 rm -f /etc/nftables.d/10-cubex-offload-exempt.nft 2>/dev/null || true if command -v uci >/dev/null 2>&1; then _FW_CHG=0 for _fk in cubex_bypass cubex_dnat cubex_hairpin cubex_dns_redir_udp cubex_dns_redir_tcp cubex_tproxy; do if uci -q get "firewall.${_fk}" >/dev/null 2>&1; then uci -q delete "firewall.${_fk}" || true _FW_CHG=1 fi done uci -q del_list firewall.@zone[0].device='macvlan-shim' 2>/dev/null && _FW_CHG=1 || true uci -q del_list firewall.@zone[0].network='cubex_shim' 2>/dev/null && _FW_CHG=1 || true [ "$_FW_CHG" -eq 1 ] && uci commit firewall >/dev/null 2>&1 || true if [ "$_FW_CHG" -eq 1 ] || [ "$_NFT_REMOVED" -eq 1 ]; then /etc/init.d/firewall reload >/dev/null 2>&1 || true fi for _nk in cubex_fakeip cubex_shim cubex_shim_route; do uci -q delete "network.${_nk}" 2>/dev/null || true done uci commit network >/dev/null 2>&1 || true /etc/init.d/network reload >/dev/null 2>&1 || true uci -q del_list dhcp.@dnsmasq[0].rebind_domain='198.18.0.0/15' 2>/dev/null || true uci -q delete dhcp.@dnsmasq[0].server 2>/dev/null || true uci set dhcp.@dnsmasq[0].noresolv='0' 2>/dev/null || true for _opt in $(uci -q get dhcp.lan.dhcp_option 2>/dev/null); do case "$_opt" in 6,*) uci -q del_list dhcp.lan.dhcp_option="$_opt" || true ;; esac done uci commit dhcp >/dev/null 2>&1 || true /etc/init.d/dnsmasq reload >/dev/null 2>&1 || true fi if command -v ip >/dev/null 2>&1; then while ip rule del table 2022 >/dev/null 2>&1; do :; done for _ow_tdev in cubex-tun cubex-tun-a cubex-tun-b $(ip -o link show 2>/dev/null | awk -F': ' '{print $2}' | cut -d@ -f1 | grep -E '^cubex-tun' || true); do while ip rule del iif "$_ow_tdev" >/dev/null 2>&1; do :; done done while ip -6 rule del table 2022 >/dev/null 2>&1; do :; done ip route flush table 2022 >/dev/null 2>&1 || true ip -6 route flush table 2022 >/dev/null 2>&1 || true for _ow_tdev in cubex-tun cubex-tun-a cubex-tun-b $(ip -o link show 2>/dev/null | awk -F': ' '{print $2}' | cut -d@ -f1 | grep -E '^cubex-tun' || true); do for _ow_cidr in 198.18.0.0/15 198.18.0.0/16 198.19.0.0/16; do ip route del "$_ow_cidr" dev "$_ow_tdev" >/dev/null 2>&1 || true done ip -6 route del fc00::/18 dev "$_ow_tdev" >/dev/null 2>&1 || true ip link del "$_ow_tdev" >/dev/null 2>&1 || true done for _ow_cidr in 198.18.0.0/15 198.18.0.0/16 198.19.0.0/16; do ip route del "$_ow_cidr" 2>/dev/null || true done ip -6 route del fc00::/18 2>/dev/null || true fi if command -v conntrack >/dev/null 2>&1; then for _ow_ct in 198.18.0.0/15 198.18.0.0/16 198.19.0.0/16; do conntrack -D -d "$_ow_ct" >/dev/null 2>&1 || true conntrack -D -s "$_ow_ct" >/dev/null 2>&1 || true done fi if command -v nft >/dev/null 2>&1; then nft delete table inet cubex >/dev/null 2>&1 || true nft delete table inet cubex_symbiotic >/dev/null 2>&1 || true nft delete chain inet fw4 cubex_flow_exempt 2>/dev/null || true for _nh in $(nft -a list chain inet fw4 forward 2>/dev/null | awk '/198\.18\.0\.0\/15|198\.18\.0\.0\/16|198\.19\.0\.0\/16/ && /return/ {for(i=1;i<=NF;i++) if($i=="handle") print $(i+1)}'); do nft delete rule inet fw4 forward handle "$_nh" 2>/dev/null || true done fi if command -v iptables >/dev/null 2>&1; then for _ow_fw in 198.18.0.0/15 198.18.0.0/16 198.19.0.0/16; do iptables -D FORWARD -d "$_ow_fw" -j ACCEPT 2>/dev/null || true iptables -D FORWARD -s "$_ow_fw" -j ACCEPT 2>/dev/null || true done fi rm -f "${OW_DATA_DIR}/uninstall.sh" "${OW_DATA_DIR}/install.manifest.json" 2>/dev/null || true if [ "$PURGE_DATA" -eq 1 ]; then rm -rf "${OW_DATA_DIR}" 2>/dev/null || true printf '%s\n' "[CubeX] OpenWrt Docker uninstall complete (data purged)." else printf '%s\n' "[CubeX] OpenWrt Docker uninstall complete. Config/data preserved in ${OW_DATA_DIR} (pass --purge to delete)." fi EOF chmod 755 "${OW_DATA_DIR}/uninstall.sh" if ! cubex_verify_panel_alive "${CUBEX_IP}" "${OW_PORT}" "15" "docker exec ${CONTAINER_NAME}"; then msg "${RED}========================================================================${NC}" msg "${RED}❌ [存活校验失败] 容器 ${CONTAINER_NAME} 的 ${OW_PORT} 控制端口未就绪!${NC}" msg "${YELLOW}--- 最近 20 行容器日志 ---${NC}" docker logs --tail 20 "${CONTAINER_NAME}" 2>&1 || true msg "${RED}========================================================================${NC}" exit 1 fi msg "${GREEN}========================================================================${NC}" msg "${GREEN}🎉 恭喜!CubeX OpenWrt Docker 宿主共生系统已全自动部署并加固完毕!${NC}" msg "${GREEN}👉 CubeX Web 控制台驾驶舱: http://${CUBEX_IP}:${OW_PORT}${NC}" msg "${GREEN}👉 主路由 OpenWrt 网关管理: http://${ROUTER_IP}${NC}" msg "${GREEN}👉 干净卸载器已落盘 : sh ${OW_DATA_DIR}/uninstall.sh [--purge]${NC}" msg "${YELLOW}💡 提示: 进入 CubeX 控制台联动主路由时,【宿主/主路由 IP】填写 OpenWrt IP (${ROUTER_IP}),切勿误填 CubeX 自身 IP (${CUBEX_IP})!${NC}" msg "${GREEN}🛡️ 全屋设备无需任何手动设置,已自动继承透明代理、去广告与0秒逃生!${NC}" msg "${GREEN}========================================================================${NC}" } # CubeX Linux / 通用宿主 (Docker 与 Native Systemd/OpenRC) 部署模块 (POSIX sh) run_platform_linux() { clear 2>/dev/null || true cat << "EOF" ██████╗██╗ ██╗██████╗ ███████╗██╗ ██╗ ██╔════╝██║ ██║██╔══██╗██╔════╝╚██╗██╔╝ ██║ ██║ ██║██████╔╝█████╗ ╚███╔╝ ██║ ██║ ██║██╔══██╗██╔══╝ ██╔██╗ ╚██████╗╚██████╔╝██████╔╝███████╗██╔╝ ██╗ ╚═════╝ ╚═════╝ ╚═════╝ ╚══════╝╚═╝ ╚═╝ 🌌 次世代双擎高可用旁路网关系统 · 软路由的天花板 [Engine: Mihomo × sing-box v1.14+] EOF echo "" if [ "$(id -u)" -ne 0 ]; then msg "${RED}❌ 错误: 此安装脚本需要 root 超级用户权限执行。${NC}" msg "${YELLOW}👉 请使用: sudo sh $0${NC}" exit 1 fi cubex_preflight_check_deps detect_target_arch msg "${GREEN}🔍 检测到处理器架构: ${BOLD}${TARGET_ARCH}${NC}" ensure_linux_base_tools detect_host_topology_and_platform msg "${CYAN}🖥️ 检测到宿主平台: ${BOLD}${DETECTED_HOST_NAME}${NC}" msg "${BLUE}📁 自动匹配推荐部署路径: ${BOLD}${DEFAULT_INSTALL_DIR}${NC}" if [ "$IS_IKUAI_GATEWAY" -eq 1 ]; then msg "${PURPLE}🚀 嗅探到上级主路由为: ${BOLD}爱快 iKuai 企业级路由 (${DEFAULT_GW})${NC}" msg "${CYAN}💡 【爱快宿主共生建议】: 部署完成后,在 CubeX 驾驶舱【宿主共生凭据】中填入爱快 IP (${DEFAULT_GW}) 与管理密码,系统将全自动下发 198.18.0.0/15 静态回指与透明分流(终端网关与 DHCP DNS 保持指向爱快主路由)!${NC}" fi [ -n "$CUSTOM_DIR" ] && DEFAULT_INSTALL_DIR="$CUSTOM_DIR" INSTALL_DIR="${DEFAULT_INSTALL_DIR}" if [ "$AUTO_CONFIRM" -eq 0 ]; then if [ ! -t 0 ] || [ ! -e /dev/tty ]; then AUTO_CONFIRM=1 fi fi if [ "$AUTO_CONFIRM" -eq 0 ]; then echo "" msg "${BOLD}请选择或确认安装目录:${NC} (直接回车保持默认)" prompt_read "安装路径 [${DEFAULT_INSTALL_DIR}]: " INPUT_DIR="$REPLY" if [ -n "$INPUT_DIR" ]; then CLEAN_DIR=$(printf '%s\n' "$INPUT_DIR" | tr -d '\r\n' | grep -E '^/[a-zA-Z0-9_\.\/-]+$' || true) if [ -n "$CLEAN_DIR" ]; then INSTALL_DIR="$CLEAN_DIR" else INSTALL_DIR="$DEFAULT_INSTALL_DIR" fi fi if [ "$DETECTED_HOST" = "fnos" ]; then msg "${GREEN}✨ 已应用飞牛推荐持久化目录: ${INSTALL_DIR}${NC}" fi if [ -z "$DEPLOY_MODE" ]; then echo "" msg "${BOLD}请选择运行部署模式:${NC}" msg " ${CYAN}1) Docker 容器化部署 (推荐 · 隔离性好 · 通用 Linux / 飞牛 NAS 适用)${NC}" msg " ${PURPLE}2) 原生单二进制 Systemd/OpenRC 守护部署 (纯粹裸跑 · 极致轻量低开销 · 极客首选)${NC}" prompt_read "请输入选项 [1/2, 默认 1]: " case "$REPLY" in 2) DEPLOY_MODE="native" ;; *) DEPLOY_MODE="docker" ;; esac fi else if [ -z "$DEPLOY_MODE" ]; then if command -v docker >/dev/null 2>&1; then DEPLOY_MODE="docker" else DEPLOY_MODE="native" fi fi fi msg "\n${YELLOW}⚙️ [1/4] 执行宿主底层网络协议栈加固 (开启内核转发与网络缓冲区优化)...${NC}" apply_linux_netstack_tuning msg "${YELLOW}📁 [2/4] 初始化目录与数据包释放 (${INSTALL_DIR})...${NC}" if [ "$INSTALL_DIR" = "/opt/cubex" ]; then if [ -L /opt/cubex ]; then rm -f /opt/cubex 2>/dev/null || true fi mkdir -p /opt/cubex/bin /opt/cubex/etc/rules /opt/cubex/data if [ -d /opt/CubeX ] && [ ! -L /opt/CubeX ]; then cubex_copy_missing_tree /opt/CubeX/data /opt/cubex/data cubex_copy_missing_tree /opt/CubeX/etc /opt/cubex/etc [ -d /opt/CubeX/store ] && cubex_copy_missing_tree /opt/CubeX/store /opt/cubex/store [ -f /opt/CubeX/install.manifest.json ] && [ ! -f /opt/cubex/install.manifest.json ] && cp -f /opt/CubeX/install.manifest.json /opt/cubex/install.manifest.json 2>/dev/null || true mv /opt/CubeX "/opt/CubeX.migrated.$(date +%s)" 2>/dev/null || true fi [ -e /opt/CubeX ] || ln -s /opt/cubex /opt/CubeX 2>/dev/null || true else mkdir -p "$INSTALL_DIR/bin" "$INSTALL_DIR/etc/rules" "$INSTALL_DIR/data" fi _pl_script_dir=$(dirname -- "$0" 2>/dev/null || printf '%s\n' ".") CURRENT_SCRIPT_DIR=$(cd "$_pl_script_dir" 2>/dev/null && pwd -P || pwd -P) _pl_install_etc_abs="" if [ -d "$INSTALL_DIR/etc" ]; then _pl_install_etc_abs=$(cd "$INSTALL_DIR/etc" 2>/dev/null && pwd -P || true) fi SRC_ETC="" for _pl_cand in "$CURRENT_SCRIPT_DIR/../etc" "$CURRENT_SCRIPT_DIR/etc" "./etc"; do [ -d "$_pl_cand" ] || continue _pl_cand_abs=$(cd "$_pl_cand" 2>/dev/null && pwd -P || true) [ -n "$_pl_cand_abs" ] || continue _pl_cand_parent=$(dirname -- "$_pl_cand_abs" 2>/dev/null || true) case "$_pl_cand_abs" in "/"|"/etc") continue ;; esac if [ "$_pl_cand_parent" = "/" ]; then continue fi if [ -n "$_pl_install_etc_abs" ] && [ "$_pl_cand_abs" = "$_pl_install_etc_abs" ]; then continue fi if [ -d "$_pl_cand_abs/rules" ] && { \ [ -f "$_pl_cand_parent/meta.json" ] || \ [ -f "$_pl_cand_parent/bin/cubexd" ] || \ [ -f "$_pl_cand_parent/data/config.ir.json" ] || \ [ -f "$_pl_cand_abs/GeoIP.dat" ] || \ [ -f "$_pl_cand_abs/geosite.dat" ]; }; then SRC_ETC="$_pl_cand_abs" break fi done if [ -n "$SRC_ETC" ]; then for _pl_item in "$SRC_ETC"/*; do [ -e "$_pl_item" ] || continue _pl_base=$(basename "$_pl_item") case "$_pl_base" in config.yaml|config.json) [ -e "$INSTALL_DIR/etc/$_pl_base" ] || cp -r "$_pl_item" "$INSTALL_DIR/etc/" ;; *) cp -r "$_pl_item" "$INSTALL_DIR/etc/" ;; esac done fi if [ "$DETECTED_HOST" = "fnos" ]; then chown -R 1000:1000 "$INSTALL_DIR" 2>/dev/null || true fi if [ "$DEPLOY_MODE" = "docker" ]; then msg "${YELLOW}🐳 [3/4] 正在配置 Docker 容器化主旁一体网关...${NC}" if ! command -v docker >/dev/null 2>&1; then msg "${RED}⚠️ 检测到当前系统未安装 Docker,正在自动降级为原生单二进制守护部署...${NC}" DEPLOY_MODE="native" fi fi APP_PORT="${PORT:-${CUBEX_PORT:-2026}}" if command -v ss >/dev/null 2>&1; then if ss -tuln | grep -q ":${APP_PORT} "; then if docker ps 2>/dev/null | grep -q "cubex" || (command -v systemctl >/dev/null 2>&1 && (systemctl is-active --quiet cubex 2>/dev/null || systemctl is-active --quiet cubexd 2>/dev/null)) || pgrep -x cubexd >/dev/null 2>&1; then msg "${CYAN}💡 检测到已有 CubeX 运行于端口 ${APP_PORT},将执行平滑替换升级...${NC}" else msg "${YELLOW}⚠️ 宿主端口 ${APP_PORT} 已被其他应用占用,启动智能空闲端口探查...${NC}" while ss -tuln | grep -q ":${APP_PORT} "; do APP_PORT=$((APP_PORT + 1)) done msg "${GREEN}✅ 自动切换至空闲可用端口: ${APP_PORT}${NC}" fi fi fi MANIFEST_PATH="${INSTALL_DIR}/install.manifest.json" if [ "$DEPLOY_MODE" = "docker" ]; then DOCKER_STORE_DIR="${INSTALL_DIR}/store" MANIFEST_PATH="${DOCKER_STORE_DIR}/install.manifest.json" cubex_backup_before_v10_migration "$INSTALL_DIR" "$DOCKER_STORE_DIR" || true mkdir -p "${DOCKER_STORE_DIR}/data" "${DOCKER_STORE_DIR}/etc/rules" if docker ps -a --format '{{.Names}}' | grep -Eq '^cubex$'; then _pl_old_etc=$(docker inspect -f '{{range .Mounts}}{{if eq .Destination "/app/etc"}}{{.Source}}{{end}}{{end}}' cubex 2>/dev/null || true) _pl_old_data=$(docker inspect -f '{{range .Mounts}}{{if eq .Destination "/app/data"}}{{.Source}}{{end}}{{end}}' cubex 2>/dev/null || true) if [ -n "$_pl_old_etc" ] && [ -d "$_pl_old_etc" ] && [ "$_pl_old_etc" != "${DOCKER_STORE_DIR}/etc" ]; then cubex_copy_missing_tree "$_pl_old_etc" "${DOCKER_STORE_DIR}/etc" fi if [ -n "$_pl_old_data" ] && [ -d "$_pl_old_data" ] && [ "$_pl_old_data" != "${DOCKER_STORE_DIR}/data" ]; then cubex_copy_missing_tree "$_pl_old_data" "${DOCKER_STORE_DIR}/data" fi fi cubex_converge_single_store_links "$INSTALL_DIR" "$DOCKER_STORE_DIR" || true _pl_tag="${CUSTOM_VER:-${REL_TAG:-}}" if [ -z "$_pl_tag" ] && [ "${OFFLINE_MODE:-0}" -ne 1 ]; then cubex_resolve_latest_tag "" _pl_tag="${REL_TAG:-${CUBEX_DEFAULT_TAG}}" fi [ -z "$_pl_tag" ] && _pl_tag="${CUBEX_DEFAULT_TAG}" case "$_pl_tag" in [0-9]*) _pl_tag="v${_pl_tag}" ;; esac _pl_img="fyasshole/cubex:${_pl_tag}" msg "${CYAN}💡 正在准备精确版本 Docker 镜像 ${_pl_img} (本地离线包 -> 国内 Registry -> GitHub Release)...${NC}" if ! cubex_pull_or_load_docker_image "$TARGET_ARCH" "${CUSTOM_PKG:-}" "$_pl_tag" "${OFFLINE_MODE:-0}" "$_pl_img"; then msg "${RED}❌ 无法获取 CubeX Docker 运行镜像!(已保留现有运行容器不变)${NC}" msg "${YELLOW}💡 建议: 请检查网络或下载 CubeX-*-docker-${TARGET_ARCH}.tar.gz 后通过 --pkg= 指定离线安装。${NC}" exit 1 fi if [ -n "${CUSTOM_VER:-}" ] && [ -z "${REL_TAG:-}" ]; then REL_TAG="$CUSTOM_VER" fi cubex_write_install_manifest \ "${MANIFEST_PATH}" \ "${REL_TAG:-${CUBEX_DEFAULT_TAG}}" \ "linux" \ "docker" \ "${INSTALL_DIR}" \ "single_store" \ "/app/store" \ "/app/store/data" \ "/app/store/etc" \ "${APP_PORT}" \ "host" cat < "$INSTALL_DIR/docker-compose.yml" services: cubex: image: ${_pl_img} container_name: cubex restart: unless-stopped network_mode: host cap_add: - NET_ADMIN - NET_BIND_SERVICE - SYS_MODULE devices: - /dev/net/tun:/dev/net/tun volumes: - ./store:/app/store - /etc/timezone:/etc/timezone:ro - /etc/localtime:/etc/localtime:ro environment: - TZ=Asia/Shanghai - CUBEX_PORT=${APP_PORT} - CUBEX_LISTEN=:${APP_PORT} - CUBEX_STORAGE_MODE=single_store - CUBEX_HOST_PLATFORM=${DETECTED_HOST} - CUBEX_DEPLOY_METHOD=docker - GOMEMLIMIT=${HOST_GOMEMLIMIT} - GOGC=${HOST_GOGC} logging: driver: "json-file" options: max-size: "10m" max-file: "3" EOF msg "${GREEN}✅ 已生成 docker-compose.yml 配置文件 (v10 单卷 /app/store · 内存配额: ${HOST_GOMEMLIMIT})${NC}" cd "$INSTALL_DIR" if command -v docker-compose >/dev/null 2>&1; then docker-compose down 2>/dev/null || true docker-compose up -d elif docker compose version >/dev/null 2>&1; then docker compose down 2>/dev/null || true docker compose up -d else docker stop cubex 2>/dev/null || true docker rm cubex 2>/dev/null || true docker run -d \ --name cubex \ --restart unless-stopped \ --network host \ --cap-add NET_ADMIN \ --cap-add NET_BIND_SERVICE \ --device /dev/net/tun:/dev/net/tun \ -v "$DOCKER_STORE_DIR:/app/store" \ -e TZ=Asia/Shanghai \ -e CUBEX_PORT=${APP_PORT} \ -e CUBEX_LISTEN=:${APP_PORT} \ -e CUBEX_STORAGE_MODE=single_store \ -e CUBEX_HOST_PLATFORM=${DETECTED_HOST} \ -e CUBEX_DEPLOY_METHOD=docker \ -e GOMEMLIMIT=${HOST_GOMEMLIMIT} \ -e GOGC=${HOST_GOGC} \ "${_pl_img}" || true fi else msg "${PURPLE}⚡ [3/4] 正在配置原生单二进制 Systemd/OpenRC 守护进程 (v10 单卷存储)...${NC}" NATIVE_STORE_DIR="${INSTALL_DIR}/store" MANIFEST_PATH="${NATIVE_STORE_DIR}/install.manifest.json" if [ -f "${INSTALL_DIR}/install.manifest.json" ] && [ ! -f "${MANIFEST_PATH}" ]; then mkdir -p "${NATIVE_STORE_DIR}" 2>/dev/null || true cp -p "${INSTALL_DIR}/install.manifest.json" "${MANIFEST_PATH}" 2>/dev/null || true fi cubex_backup_before_v10_migration "$INSTALL_DIR" "$NATIVE_STORE_DIR" || true mkdir -p "${NATIVE_STORE_DIR}/data" "${NATIVE_STORE_DIR}/etc/rules" 2>/dev/null || true NEED_DOWNLOAD=1 LOCAL_ZIP="" if [ -n "${CUSTOM_PKG:-}" ]; then if [ ! -f "$CUSTOM_PKG" ] || [ ! -r "$CUSTOM_PKG" ] || ! zip_is_valid "$CUSTOM_PKG"; then msg "${RED}❌ 指定的离线发布包不存在、不可读或 CRC 校验损坏: ${CUSTOM_PKG}${NC}" >&2 exit 1 fi LOCAL_ZIP="$CUSTOM_PKG" else LOCAL_ZIP=$(cubex_pick_latest_file \ "$CURRENT_SCRIPT_DIR/../dist/release/CubeX-"*"-linux-$TARGET_ARCH.zip" \ "$CURRENT_SCRIPT_DIR/../dist/CubeX-"*"-linux-$TARGET_ARCH.zip" \ "./dist/release/CubeX-"*"-linux-$TARGET_ARCH.zip" \ "./dist/CubeX-"*"-linux-$TARGET_ARCH.zip" \ "/root/CubeX-"*"-linux-$TARGET_ARCH.zip" \ "/tmp/CubeX-"*"-linux-$TARGET_ARCH.zip") fi if [ -n "$LOCAL_ZIP" ] && [ -f "$LOCAL_ZIP" ] && zip_is_valid "$LOCAL_ZIP"; then msg "${GREEN}📦 发现本地发行归档包 (${LOCAL_ZIP}),直接 0 秒解压部署...${NC}" if command -v systemctl >/dev/null 2>&1; then systemctl stop cubex cubexd 2>/dev/null || true; fi if command -v rc-service >/dev/null 2>&1; then rc-service cubex stop 2>/dev/null || rc-service cubexd stop 2>/dev/null || true; fi pkill -x cubexd 2>/dev/null || killall cubexd 2>/dev/null || true pkill -x mihomo 2>/dev/null || killall mihomo 2>/dev/null || true pkill -x sing-box 2>/dev/null || killall sing-box 2>/dev/null || true cubex_converge_single_store_links "$INSTALL_DIR" "$NATIVE_STORE_DIR" || true cubex_extract_native_into_store "$LOCAL_ZIP" "$INSTALL_DIR" "$NATIVE_STORE_DIR" NEED_DOWNLOAD=0 elif [ -f "$CURRENT_SCRIPT_DIR/../dist/cubexd-linux-$TARGET_ARCH" ]; then if command -v systemctl >/dev/null 2>&1; then systemctl stop cubex cubexd 2>/dev/null || true; fi if command -v rc-service >/dev/null 2>&1; then rc-service cubex stop 2>/dev/null || rc-service cubexd stop 2>/dev/null || true; fi pkill -x cubexd 2>/dev/null || killall cubexd 2>/dev/null || true pkill -x mihomo 2>/dev/null || killall mihomo 2>/dev/null || true pkill -x sing-box 2>/dev/null || killall sing-box 2>/dev/null || true cubex_converge_single_store_links "$INSTALL_DIR" "$NATIVE_STORE_DIR" || true rm -f "$INSTALL_DIR/bin/cubexd" 2>/dev/null || true cp "$CURRENT_SCRIPT_DIR/../dist/cubexd-linux-$TARGET_ARCH" "$INSTALL_DIR/bin/cubexd" NEED_DOWNLOAD=0 fi if [ "$NEED_DOWNLOAD" -eq 1 ] && [ "${OFFLINE_MODE:-0}" -ne 1 ]; then msg "${CYAN}🌐 正在从 GitHub Releases 加速源拉取最新完整发布包 (无损迁入 store 单卷存储)...${NC}" cubex_resolve_latest_tag "${CUSTOM_VER:-}" ZIP_NAME="CubeX-${REL_TAG}-linux-${TARGET_ARCH}.zip" ZIP_URL="https://github.com/zyeyefyass/CubeX/releases/download/${REL_TAG}/${ZIP_NAME}" TMP_ZIP="/tmp/${ZIP_NAME}" if [ -s "$TMP_ZIP" ] && zip_is_valid "$TMP_ZIP"; then msg "${GREEN}📦 发现本地已缓存的完整归档: ${TMP_ZIP},秒级解压部署...${NC}" else msg "${CYAN} -> 正在通过国内多级高速镜像源智能轮询下载 ${ZIP_NAME} (无代理极速拉取)...${NC}" cubex_download_with_mirrors "$ZIP_URL" "$TMP_ZIP" "zip_is_valid" "1200" "0" || true fi if [ -s "$TMP_ZIP" ] && zip_is_valid "$TMP_ZIP"; then if command -v systemctl >/dev/null 2>&1; then systemctl stop cubex cubexd 2>/dev/null || true; fi if command -v rc-service >/dev/null 2>&1; then rc-service cubex stop 2>/dev/null || rc-service cubexd stop 2>/dev/null || true; fi pkill -x cubexd 2>/dev/null || killall cubexd 2>/dev/null || true pkill -x mihomo 2>/dev/null || killall mihomo 2>/dev/null || true pkill -x sing-box 2>/dev/null || killall sing-box 2>/dev/null || true cubex_converge_single_store_links "$INSTALL_DIR" "$NATIVE_STORE_DIR" || true cubex_extract_native_into_store "$TMP_ZIP" "$INSTALL_DIR" "$NATIVE_STORE_DIR" msg "${GREEN}✅ 完整归档已成功释放至 ${INSTALL_DIR} (单卷 store: ${NATIVE_STORE_DIR})${NC}" else msg "${RED}❌ 完整离线包 (${ZIP_NAME}) 全部镜像源拉取失败!(已保留现有服务与配置不变)${NC}" msg "${YELLOW}👉 国内无代理环境离线部署指引:${NC}" msg " 1. 从 GitHub Releases(或国内镜像)下载完整发布包: ${BOLD}${ZIP_NAME}${NC}" msg " 2. 将其上传放置到宿主机 ${BOLD}/tmp/${ZIP_NAME}${NC} 或 ${BOLD}/root/${ZIP_NAME}${NC}" msg " 3. 执行离线安装: ${CYAN}sh install.sh --platform=linux --native --pkg=/tmp/${ZIP_NAME} --offline${NC}" exit 1 fi fi cubex_converge_single_store_links "$INSTALL_DIR" "$NATIVE_STORE_DIR" || true if [ -f "${INSTALL_DIR}/install.manifest.json" ] && [ ! -L "${INSTALL_DIR}/install.manifest.json" ]; then rm -f "${INSTALL_DIR}/install.manifest.json" 2>/dev/null || true fi chmod +x "$INSTALL_DIR/bin/"* 2>/dev/null || true if [ ! -f "$INSTALL_DIR/bin/cubexd" ] || [ ! -s "$INSTALL_DIR/bin/cubexd" ]; then msg "${RED}❌ 致命错误: 未能获取到有效的 cubexd 控制面二进制文件,请检查网络连接或权限后重试。${NC}" exit 1 fi if [ ! -f "$INSTALL_DIR/bin/sing-box" ] && [ ! -f "$INSTALL_DIR/bin/mihomo" ]; then msg "${RED}❌ 致命错误: 双引擎核心文件 (sing-box / mihomo) 均缺失!${NC}" msg "${YELLOW}👉 解决建议: 请检查宿主网络/镜像源连接,或将完整的 CubeX-*-linux-${TARGET_ARCH}.zip 放置于 /tmp/ 目录后重新运行。${NC}" exit 1 elif [ ! -f "$INSTALL_DIR/bin/sing-box" ] || [ ! -f "$INSTALL_DIR/bin/mihomo" ]; then msg "${YELLOW}⚠️ 警告: 检测到仅存在单一代理内核 (mihomo=$([ -f "$INSTALL_DIR/bin/mihomo" ] && echo OK || echo MISSING), sing-box=$([ -f "$INSTALL_DIR/bin/sing-box" ] && echo OK || echo MISSING)),双核热切换将受限!${NC}" fi mkdir -p /usr/local/bin 2>/dev/null || true if [ -f "$INSTALL_DIR/bin/cubex" ]; then ln -sf "$INSTALL_DIR/bin/cubex" /usr/local/bin/cubex 2>/dev/null || cp "$INSTALL_DIR/bin/cubex" /usr/local/bin/cubex 2>/dev/null || true chmod +x /usr/local/bin/cubex 2>/dev/null || true fi cubex_cleanup_legacy_service_units if command -v systemctl >/dev/null 2>&1 && [ -d /etc/systemd/system ]; then mkdir -p "$NATIVE_STORE_DIR/data/logs" 2>/dev/null || true cat < /etc/systemd/system/cubex.service [Unit] Description=CubeX Dual-Engine Cyber Gateway Daemon After=network.target network-online.target Wants=network-online.target [Service] Type=simple User=root WorkingDirectory=$INSTALL_DIR ExecStart=$INSTALL_DIR/bin/cubexd -dir $INSTALL_DIR -listen :${APP_PORT} StandardOutput=journal StandardError=journal SyslogIdentifier=cubexd Restart=always RestartSec=2s LimitNOFILE=65535 Environment=CUBEX_STORAGE_MODE=single_store Environment=CUBEX_STORE_DIR=${NATIVE_STORE_DIR} Environment=GOMEMLIMIT=${HOST_GOMEMLIMIT} Environment=GOGC=${HOST_GOGC} [Install] WantedBy=multi-user.target EOF systemctl daemon-reload systemctl enable cubex >/dev/null 2>&1 || true systemctl restart cubex || true msg "${GREEN}✅ systemd 服务已注册并启动 (/etc/systemd/system/cubex.service, 单卷: ${NATIVE_STORE_DIR}, 软上限: ${HOST_GOMEMLIMIT})${NC}" elif command -v rc-service >/dev/null 2>&1 || [ -d /etc/init.d ]; then cat < /etc/init.d/cubex #!/sbin/openrc-run name="cubex" description="CubeX System Control Plane Daemon" command="$INSTALL_DIR/bin/cubexd" command_args="-dir $INSTALL_DIR -listen :${APP_PORT}" directory="$INSTALL_DIR" supervisor="supervise-daemon" respawn_max=0 output_log="/var/log/cubex.log" error_log="/var/log/cubex.err" export CUBEX_STORAGE_MODE="single_store" export CUBEX_STORE_DIR="${NATIVE_STORE_DIR}" export GOMEMLIMIT="${HOST_GOMEMLIMIT}" export GOGC="${HOST_GOGC}" export GODEBUG="madvdontneed=1" export TZ="Asia/Shanghai" depend() { need net after firewall } EOF chmod 755 /etc/init.d/cubex command -v rc-update >/dev/null 2>&1 && rc-update add cubex default >/dev/null 2>&1 || true command -v rc-service >/dev/null 2>&1 && { rc-service cubex restart >/dev/null 2>&1 || rc-service cubex start >/dev/null 2>&1 || true; } msg "${GREEN}✅ OpenRC 服务已注册并启动 (/etc/init.d/cubex, 单卷: ${NATIVE_STORE_DIR}, 软上限: ${HOST_GOMEMLIMIT})${NC}" else CUBEX_STORAGE_MODE=single_store CUBEX_STORE_DIR="${NATIVE_STORE_DIR}" GOMEMLIMIT="${HOST_GOMEMLIMIT}" GOGC="${HOST_GOGC}" GODEBUG="madvdontneed=1" nohup "$INSTALL_DIR/bin/cubexd" -dir "$INSTALL_DIR" -listen ":${APP_PORT}" /var/log/cubex.log 2>&1 & msg "${GREEN}✅ 后台守护进程已拉起 (PID: $!, 软上限: ${HOST_GOMEMLIMIT})${NC}" fi if [ -n "${CUSTOM_VER:-}" ] && [ -z "${REL_TAG:-}" ]; then REL_TAG="$CUSTOM_VER" elif [ -z "${REL_TAG:-}" ] && [ -f "${INSTALL_DIR}/meta.json" ]; then REL_TAG=$(cubex_manifest_get "${INSTALL_DIR}/meta.json" "version" || true) fi cubex_write_install_manifest \ "${MANIFEST_PATH}" \ "${REL_TAG:-${CUBEX_DEFAULT_TAG}}" \ "linux" \ "native" \ "${INSTALL_DIR}" \ "single_store" \ "${NATIVE_STORE_DIR}" \ "${NATIVE_STORE_DIR}/data" \ "${NATIVE_STORE_DIR}/etc" \ "${APP_PORT}" \ "host" fi msg "${YELLOW}🔗 [4/4] 注册全局管理快捷指令 (cubex)...${NC}" mkdir -p /usr/local/bin 2>/dev/null || true CLI_INSTALLED=0 for _pl_cli in "$INSTALL_DIR/bin/cubex" "$CURRENT_SCRIPT_DIR/../dist/cubex-linux-$TARGET_ARCH" "$CURRENT_SCRIPT_DIR/dist/cubex-linux-$TARGET_ARCH" "./dist/cubex-linux-$TARGET_ARCH"; do if [ -f "$_pl_cli" ]; then ln -sf "$_pl_cli" /usr/local/bin/cubex 2>/dev/null || cp "$_pl_cli" /usr/local/bin/cubex 2>/dev/null || true chmod +x /usr/local/bin/cubex 2>/dev/null || true CLI_INSTALLED=1 break fi done if [ "$CLI_INSTALLED" -eq 0 ]; then cat < /usr/local/bin/cubex #!/bin/sh APP_PORT="${APP_PORT}" EOF cat << 'EOF' >> /usr/local/bin/cubex ACTION="$1" case "$ACTION" in status) if command -v docker >/dev/null 2>&1 && docker ps --format '{{.Names}}' | grep -q '^cubex$'; then docker ps --filter "name=cubex" elif command -v systemctl >/dev/null 2>&1; then systemctl status cubex --no-pager fi curl -s http://127.0.0.1:${APP_PORT}/api/v1/system/status | grep -o '"version":[^,]*' || true ;; restart) echo "🔄 正在重启 CubeX 守护进程..." if command -v docker >/dev/null 2>&1 && docker ps -a --format '{{.Names}}' | grep -q '^cubex$'; then docker restart cubex elif command -v systemctl >/dev/null 2>&1; then systemctl restart cubex fi echo "✅ 重启指令已下发" ;; log|logs) if command -v docker >/dev/null 2>&1 && docker ps -a --format '{{.Names}}' | grep -q '^cubex$'; then docker logs -f --tail 100 cubex elif command -v journalctl >/dev/null 2>&1; then journalctl -u cubex -f -n 100 fi ;; reload) echo "🔄 热重载分流策略与规则..." curl -s -X POST http://127.0.0.1:${APP_PORT}/api/v1/system/reload-config echo "" ;; ikuai) echo "🌐 爱快 iKuai 宿主联动中枢" curl -s -X POST http://127.0.0.1:${APP_PORT}/api/v1/host/auto-setup echo "" ;; *) echo "🌌 CubeX 命令行控制中心" echo "用法: cubex {status|restart|log|reload|ikuai}" ;; esac EOF chmod +x /usr/local/bin/cubex 2>/dev/null || true fi LOCAL_IP=$(ip route get 1.1.1.1 2>/dev/null | awk '{for(i=1;i<=NF;i++)if($i=="src")print $(i+1)}' || hostname -i 2>/dev/null | awk '{print $1}' || echo "127.0.0.1") check_resolv_self_loop CUBEX_FIX_DNS_EXPLICIT=0 if [ "${CUBEX_FIX_DNS:-}" = "1" ]; then CUBEX_FIX_DNS_EXPLICIT=1 elif [ -z "${CUBEX_FIX_DNS:-}" ] && [ "${IS_CONTAINER:-0}" -eq 0 ]; then CUBEX_FIX_DNS=1 msg "${CYAN}🛡️ [Linux 旁路由默认加固] 自动识别活跃网络栈并执行防 DNS 自环加固(保留 .cubex.bak 备份,传 CUBEX_FIX_DNS=0 可跳过)${NC}" fi if [ "${CUBEX_FIX_DNS:-0}" = "1" ]; then msg "${CYAN}🔧 正在执行宿主 DNS 防覆盖自动加固...${NC}" cubex_apply_dns_self_loop_fix fi cubex_write_unix_uninstaller "$INSTALL_DIR" "$DEPLOY_MODE" "cubex" "$MANIFEST_PATH" if ! cubex_verify_panel_alive "$LOCAL_IP" "${APP_PORT:-2026}" "15"; then echo "" msg "${RED}═════════════════════════════════════════════════════════════════════════${NC}" msg "${BOLD}${RED}❌ [存活校验失败] cubexd 控制面未在 :${APP_PORT:-2026} 端口监听就绪!${NC}" msg "${YELLOW}请排查以下最近 20 行运行日志:${NC}" if command -v docker >/dev/null 2>&1 && docker ps -a --format '{{.Names}}' | grep -q '^cubex$'; then docker logs --tail 20 cubex 2>&1 || true elif command -v journalctl >/dev/null 2>&1 && systemctl list-units --type=service 2>/dev/null | grep -q cubex; then journalctl -u cubex -n 20 --no-pager 2>&1 || true elif [ -f /var/log/cubex.log ] || [ -f /var/log/cubex.err ]; then tail -n 20 /var/log/cubex.log /var/log/cubex.err 2>/dev/null || true else tail -n 20 "${INSTALL_DIR}/data/cubexd.log" 2>/dev/null || true fi msg "${RED}═════════════════════════════════════════════════════════════════════════${NC}" if [ -n "${CUBEX_LAST_MIGRATION_SNAP:-}" ] && [ -d "${CUBEX_LAST_MIGRATION_SNAP}" ]; then msg "${YELLOW}⏪ 检测到首次迁移启动异常,正在从快照自动执行原子回滚 (${CUBEX_LAST_MIGRATION_SNAP})...${NC}" if cubex_rollback_v10_migration "$CUBEX_LAST_MIGRATION_SNAP" "$INSTALL_DIR"; then if command -v systemctl >/dev/null 2>&1 && [ -f /etc/systemd/system/cubex.service ]; then sed -i '/CUBEX_STORAGE_MODE=single_store/d; /CUBEX_STORE_DIR=/d' /etc/systemd/system/cubex.service 2>/dev/null || true systemctl daemon-reload >/dev/null 2>&1 || true systemctl restart cubex >/dev/null 2>&1 || true elif command -v rc-service >/dev/null 2>&1 && [ -f /etc/init.d/cubex ]; then sed -i '/CUBEX_STORAGE_MODE=/d; /CUBEX_STORE_DIR=/d' /etc/init.d/cubex 2>/dev/null || true rc-service cubex restart >/dev/null 2>&1 || true fi msg "${GREEN}✅ 快照回滚成功,已恢复迁移前 data/、etc/ 与守护二进制状态。${NC}" fi fi exit 1 fi echo "" msg "${GREEN}═════════════════════════════════════════════════════════════════════════${NC}" msg "${BOLD}${GREEN}🎉 恭喜!CubeX · 次世代双擎高可用旁路网关部署成功!${NC}" msg "${GREEN}═════════════════════════════════════════════════════════════════════════${NC}" msg " 🌐 ${BOLD}Web 控制驾驶舱:${NC} ${CYAN}http://${LOCAL_IP}:${APP_PORT}${NC}" msg " 🖥️ ${BOLD}已识别宿主底座:${NC} ${PURPLE}${DETECTED_HOST_NAME}${NC}" msg " 📁 ${BOLD}持久化工作目录:${NC} ${BLUE}${INSTALL_DIR}${NC}" msg " ⚡ ${BOLD}双核心代理架构:${NC} ${GREEN}Mihomo Meta ⇄ sing-box v1.14+ (毫秒级零断网热切)${NC}" msg " 🛡️ ${BOLD}权威规则数据库:${NC} ${CYAN}217heidai MRS 广告拦截 + 隐私反追踪 + 0 明文 DNS 阻断${NC}" msg " 💾 ${BOLD}宿主自适应内存:${NC} ${YELLOW}GOMEMLIMIT=${HOST_GOMEMLIMIT} (物理内存分级防护)${NC}" _cubex_ipfwd_now=$(cat /proc/sys/net/ipv4/ip_forward 2>/dev/null | tr -d ' \t\r\n' || echo "${CUBEX_IP_FORWARD_VALUE:-}") if [ "$_cubex_ipfwd_now" = "1" ]; then if [ "${CUBEX_IP_FORWARD_PERSISTED:-0}" = "1" ] || [ -f /etc/sysctl.d/99-cubex.conf ]; then msg " 🔀 ${BOLD}IPv4 透明转发:${NC} ${GREEN}已开启 (net.ipv4.ip_forward=1) 并持久化至 /etc/sysctl.d/99-cubex.conf${NC}" else msg " 🔀 ${BOLD}IPv4 透明转发:${NC} ${GREEN}已临时开启 (net.ipv4.ip_forward=1)${NC} ${YELLOW}(建议执行 echo 'net.ipv4.ip_forward=1' > /etc/sysctl.d/99-cubex.conf 持久化)${NC}" fi else msg " 🔀 ${BOLD}IPv4 透明转发:${NC} ${RED}未开启 (当前值: ${_cubex_ipfwd_now:-未知})${NC} ${YELLOW}— 旁路由需执行:${NC}" msg " ${YELLOW}sysctl -w net.ipv4.ip_forward=1 && mkdir -p /etc/sysctl.d && printf 'net.ipv4.ip_forward=1\\nnet.ipv4.conf.all.rp_filter=0\\n' > /etc/sysctl.d/99-cubex.conf && sysctl --system${NC}" fi echo "" msg "${BOLD}常用运维指令:${NC}" msg " • 查看运行状态: ${YELLOW}cubex status${NC}" msg " • 追踪实时日志: ${YELLOW}cubex log${NC}" msg " • 重启网关服务: ${YELLOW}cubex restart${NC}" msg " • 热重载分流配置: ${YELLOW}cubex reload${NC}" msg " • 干净卸载命令: ${YELLOW}sh ${INSTALL_DIR}/uninstall.sh [--purge]${NC}" if [ "$IS_IKUAI_GATEWAY" -eq 1 ]; then echo "" msg "${PURPLE}═════════════════════════════════════════════════════════════════════════${NC}" msg "${BOLD}${PURPLE}🚀 【爱快 iKuai 宿主联动中枢就绪】(已嗅探到上级爱快主路由: ${DEFAULT_GW})${NC}" msg "${PURPLE}═════════════════════════════════════════════════════════════════════════${NC}" msg " 💡 爱快旁路由拓扑核心:需在爱快中将 ${BOLD}198.18.0.0/15${NC} 静态回指路由指向 CubeX (${LOCAL_IP})" msg " 🔧 ${BOLD}全自动一键配置步骤:${NC}" msg " 1. 浏览器打开: ${CYAN}http://${LOCAL_IP}:${APP_PORT}${NC}" msg " 2. 进入左侧导航【宿主共生凭据】,选择【爱快 iKuai】" msg " 3. 填入爱快地址 (${DEFAULT_GW}) 与 Web 管理密码" msg " 4. 点击【一键自愈与规则加固】,系统自动写入 198.18.0.0/15 静态回指并配置主路由透明分流(终端网关与 DHCP DNS 保持指向爱快)!" msg " 💻 也可在当前终端执行: ${CYAN}cubex ikuai${NC} 触发自动同步" else echo "" msg "${CYAN}═════════════════════════════════════════════════════════════════════════${NC}" msg "${BOLD}${CYAN}🧭 【从零配置主路由器指引】(请保持主路由作为局域网默认网关不变)${NC}" msg "${CYAN}═════════════════════════════════════════════════════════════════════════${NC}" msg " ① ${BOLD}首选可视化向导:${NC} 浏览器打开 ${CYAN}http://${LOCAL_IP}:${APP_PORT}/deploy${NC},按向导选择主路由型号完成配置" msg " ② ${BOLD}RouterOS / 爱快 / OpenWrt:${NC} 直接在 ${CYAN}/deploy${NC} 页面点选一键共生自愈(全屋默认网关与主路由网络拓扑保持不变)" msg " ③ ${BOLD}小米 / 华硕 / TP-Link 等普通硬路由:${NC}" msg " • ${YELLOW}重要: 请保持主路由作为局域网默认网关不变(切勿将默认网关改为 ${LOCAL_IP})!${NC}" msg " • 在主路由「静态路由」添加两条回指路由指向 CubeX (${BOLD}${LOCAL_IP}${NC})(支持 CIDR /15 则填 ${BOLD}198.18.0.0/15${NC}):" msg " - 目标网段 ${BOLD}198.18.0.0${NC} | 掩码 ${BOLD}255.255.0.0${NC} | 下一跳 ${BOLD}${LOCAL_IP}${NC}" msg " - 目标网段 ${BOLD}198.19.0.0${NC} | 掩码 ${BOLD}255.255.0.0${NC} | 下一跳 ${BOLD}${LOCAL_IP}${NC}" msg " • 将主路由 LAN 口「DHCP 首选 DNS」指向 ${BOLD}${LOCAL_IP}${NC}(备选 DNS 建议留空)" fi if [ -n "$RESOLV_LOOP_MATCHES" ]; then echo "" msg "${RED}═════════════════════════════════════════════════════════════════════════${NC}" msg "${BOLD}${RED}⚠️ [DNS 防自环告警] 检测到 /etc/resolv.conf 指向本机或回环地址:${RESOLV_LOOP_MATCHES}${NC}" msg "${YELLOW} • 风险说明: 旁路由模式下若宿主机自身 DNS 指向自己,DHCP 续租覆盖极易引发 DNS 自环死锁!${NC}" msg "${YELLOW} • 引擎兜底: CubeX 将自动弃用 dns-local 并安全回退至 ${RESOLV_SAFE_GW},防止断网。${NC}" msg "${BOLD}${RED} • 严禁使用 chattr +i 锁死 /etc/resolv.conf(会破坏系统网络服务与系统升级)!${NC}" msg "${CYAN} • 按当前宿主机活跃网络栈匹配的修复命令(或设 CUBEX_FIX_DNS=1 自动幂等写入):${NC}" if [ -f /etc/dhcpcd.conf ] || command -v dhcpcd >/dev/null 2>&1; then msg " • ${BOLD}dhcpcd:${NC} ${YELLOW}grep -q 'nohook resolv.conf' /etc/dhcpcd.conf || printf '\\n# cubex-managed-next\\nnohook resolv.conf\\n' >> /etc/dhcpcd.conf && (systemctl restart dhcpcd || service dhcpcd restart)${NC}" fi if [ -f /etc/dhcp/dhclient.conf ] || { command -v dhclient >/dev/null 2>&1 && [ -d /etc/dhcp ]; }; then msg " • ${BOLD}dhclient:${NC} ${YELLOW}grep -q 'supersede domain-name-servers' /etc/dhcp/dhclient.conf || printf '\\n# cubex-managed-next\\nsupersede domain-name-servers ${RESOLV_SAFE_GW}, 223.5.5.5;\\n' >> /etc/dhcp/dhclient.conf${NC}" fi if command -v nmcli >/dev/null 2>&1 && nmcli -t -f RUNNING general 2>/dev/null | grep -qi running; then msg " • ${BOLD}NetworkManager:${NC} ${YELLOW}nmcli con mod <连接名> ipv4.dns \"${RESOLV_SAFE_GW} 223.5.5.5\" ipv4.ignore-auto-dns yes && nmcli con up <连接名>${NC}" fi if command -v systemctl >/dev/null 2>&1 && systemctl is-active --quiet systemd-resolved 2>/dev/null; then msg " • ${BOLD}systemd-resolved:${NC} ${YELLOW}mkdir -p /etc/systemd/resolved.conf.d && printf '[Resolve]\\nDNS=${RESOLV_SAFE_GW} 223.5.5.5\\n' > /etc/systemd/resolved.conf.d/99-cubex.conf && systemctl restart systemd-resolved${NC}" fi msg " • ${BOLD}直接写入 /etc/resolv.conf(通用最小化 Debian/ifupdown):${NC} ${YELLOW}printf 'nameserver ${RESOLV_SAFE_GW}\\nnameserver 223.5.5.5\\n' > /etc/resolv.conf${NC}" msg "${RED}═════════════════════════════════════════════════════════════════════════${NC}" if [ "${CUBEX_FIX_DNS:-0}" != "1" ] && [ "${AUTO_CONFIRM:-0}" -eq 0 ] && [ -r /dev/tty ]; then prompt_read "是否立即自动写入防 DHCP 覆盖配置并修复 /etc/resolv.conf? [y/N]: " case "$REPLY" in y|Y|yes|YES) cubex_apply_dns_self_loop_fix ;; esac fi else echo "" msg "${CYAN}💡 [防 DNS 自环排查与固化指引] 本机 /etc/resolv.conf 已通过安全校验;如需后续复查可运行 ${YELLOW}cat /etc/resolv.conf${CYAN}(确保不含 127.0.0.1 或 ${LOCAL_IP},勿用 chattr +i)。${NC}" if [ -f /etc/dhcpcd.conf ] || command -v dhcpcd >/dev/null 2>&1; then msg " • ${BOLD}已检测到 dhcpcd:${NC} ${YELLOW}grep -q 'nohook resolv.conf' /etc/dhcpcd.conf || printf '\\n# cubex-managed-next\\nnohook resolv.conf\\n' >> /etc/dhcpcd.conf${NC}" elif [ -f /etc/dhcp/dhclient.conf ] || { command -v dhclient >/dev/null 2>&1 && [ -d /etc/dhcp ]; }; then msg " • ${BOLD}已检测到 dhclient:${NC} ${YELLOW}grep -q 'supersede domain-name-servers' /etc/dhcp/dhclient.conf || printf '\\n# cubex-managed-next\\nsupersede domain-name-servers ${RESOLV_SAFE_GW}, 223.5.5.5;\\n' >> /etc/dhcp/dhclient.conf${NC}" elif command -v nmcli >/dev/null 2>&1 && nmcli -t -f RUNNING general 2>/dev/null | grep -qi running; then msg " • ${BOLD}已检测到 NetworkManager:${NC} ${YELLOW}nmcli con mod <连接名> ipv4.dns \"${RESOLV_SAFE_GW} 223.5.5.5\" ipv4.ignore-auto-dns yes && nmcli con up <连接名>${NC}" elif command -v systemctl >/dev/null 2>&1 && systemctl is-active --quiet systemd-resolved 2>/dev/null; then msg " • ${BOLD}已检测到 systemd-resolved:${NC} ${YELLOW}mkdir -p /etc/systemd/resolved.conf.d && printf '[Resolve]\\nDNS=${RESOLV_SAFE_GW} 223.5.5.5\\n' > /etc/systemd/resolved.conf.d/99-cubex.conf && systemctl restart systemd-resolved${NC}" else msg " • ${BOLD}通用固定 DNS:${NC} 若为最小化 Debian (/etc/network/interfaces 或 systemd-networkd),可在网卡配置中固定 ${YELLOW}dns-nameservers ${RESOLV_SAFE_GW} 223.5.5.5${NC}。" fi fi msg "${GREEN}═════════════════════════════════════════════════════════════════════════${NC}" } # CubeX PVE LXC (CT) 容器宿主一键编排部署模块 (Strict POSIX sh) run_platform_pve_host() { msg "${CYAN}${BOLD}" cat << 'EOF' ______ __ _ __ / ____/_ __/ /_ ___ | |/ / / / / / / / __ \/ _ \| / / /___/ /_/ / /_/ / __/ | \____/\__,_/_.___/\___/_/|_| PVE LXC 极速原生容器一键部署总线 (POSIX 加固版) EOF msg "${NC}" if [ "$(id -u)" -ne 0 ]; then msg "${RED}[ERROR] 请使用 root 权限执行 PVE 宿主机部署。${NC}" exit 1 fi cubex_preflight_check_deps if ! command -v pveversion >/dev/null 2>&1 && [ ! -d /etc/pve ]; then msg "${RED}[ERROR] 检测到当前系统非 Proxmox VE 宿主机!${NC}" msg "本脚本专为 PVE 物理宿主机设计,用于秒级编排高性能 Alpine LXC 旁路由沙盒。" exit 1 fi PVE_VER=$(pveversion 2>/dev/null || echo "Proxmox VE") msg "${GREEN}✓ Proxmox VE 环境自检通过: ${PVE_VER}${NC}" APP_PORT="${PORT:-${CUBEX_PORT:-2026}}" SYS_ARCH=$(uname -m 2>/dev/null || echo "x86_64") case "$SYS_ARCH" in x86_64|amd64) PVE_ARCH="amd64" ;; aarch64|arm64) PVE_ARCH="arm64" ;; *) PVE_ARCH="amd64" ;; esac NEXT_ID=107 if [ -n "${CUSTOM_VMID:-}" ]; then NEXT_ID="$CUSTOM_VMID" else while pct status "$NEXT_ID" >/dev/null 2>&1 || [ -f "/etc/pve/lxc/${NEXT_ID}.conf" ] || [ -f "/etc/pve/qemu-server/${NEXT_ID}.conf" ]; do NEXT_ID=$((NEXT_ID + 1)) done fi DEFAULT_STORAGE=$(pvesm status -content rootdir 2>/dev/null | awk 'NR>1 {print $1}' | head -n1 || true) if [ -z "$DEFAULT_STORAGE" ]; then if pvesm status -storage local-lvm >/dev/null 2>&1; then DEFAULT_STORAGE="local-lvm" elif pvesm status -storage local-zfs >/dev/null 2>&1; then DEFAULT_STORAGE="local-zfs" else DEFAULT_STORAGE="local" fi fi GW_IP=$(ip route | awk '/^default/ {print $3; exit}' 2>/dev/null || true) if [ -z "$GW_IP" ]; then GW_IP=$(ip route get 1.1.1.1 2>/dev/null | awk '{for(i=1;i<=NF;i++) if($i=="via") {print $(i+1); exit}}' || true) fi if [ -n "${CUSTOM_GW:-}" ]; then GW_IP="$CUSTOM_GW" fi if [ -n "${CUSTOM_BRIDGE:-}" ]; then PVE_BRIDGE="$CUSTOM_BRIDGE" else PVE_BRIDGE=$(ip route show default 2>/dev/null | awk '{for(i=1;i<=NF;i++) if($i=="dev") {print $(i+1); exit}}' || true) fi if [ -z "$PVE_BRIDGE" ] || ! ip link show "$PVE_BRIDGE" >/dev/null 2>&1; then PVE_BRIDGE="vmbr0" fi HOST_IP=$(ip -4 addr show "$PVE_BRIDGE" 2>/dev/null | awk '/inet /{print $2}' | cut -d/ -f1 | head -n1 || true) if [ -z "$HOST_IP" ]; then HOST_IP=$(hostname -I 2>/dev/null | awk '{print $1}' || true) fi SUBNET_PREFIX=$(printf '%s\n' "$GW_IP" | cut -d'.' -f1-3) if [ -z "$SUBNET_PREFIX" ] && [ -n "$HOST_IP" ]; then SUBNET_PREFIX=$(printf '%s\n' "$HOST_IP" | cut -d'.' -f1-3) GW_IP="${SUBNET_PREFIX}.1" fi if [ -z "$SUBNET_PREFIX" ]; then msg "${RED}❌ 无法自动探查 PVE 局域网段与物理网关!请通过参数手动指定: --gw=<网关IP> --ip=<容器IP/24>${NC}" exit 1 fi DEFAULT_CT_IP="" if [ -n "${CUSTOM_IP:-}" ]; then DEFAULT_CT_IP="$CUSTOM_IP" else for _cand in 107 207 227 77 88 17 27 37 47 7; do CHECK_IP="${SUBNET_PREFIX}.${_cand}" if [ "$CHECK_IP" != "$GW_IP" ] && [ "$CHECK_IP" != "$HOST_IP" ]; then IP_IN_USE=0 if ping -c 1 -W 1 "$CHECK_IP" >/dev/null 2>&1; then IP_IN_USE=1 elif ip neigh show "$CHECK_IP" 2>/dev/null | grep -qiE "REACHABLE|STALE|DELAY|PROBE|PERMANENT"; then IP_IN_USE=1 elif command -v arping >/dev/null 2>&1 && arping -f -c 1 -w 1 -I "$PVE_BRIDGE" "$CHECK_IP" >/dev/null 2>&1; then IP_IN_USE=1 fi if [ "$IP_IN_USE" -eq 0 ]; then DEFAULT_CT_IP="${CHECK_IP}/24" break fi fi done if [ -z "$DEFAULT_CT_IP" ]; then DEFAULT_CT_IP="${SUBNET_PREFIX}.107/24" fi fi if [ "${AUTO_CONFIRM:-0}" -eq 0 ]; then if [ ! -t 0 ] || [ ! -r /dev/tty ]; then AUTO_CONFIRM=1 fi fi if [ "${AUTO_CONFIRM:-0}" -eq 0 ]; then msg "\n${YELLOW}${BOLD}⚙️ 请配置 CubeX LXC 容器基础参数 (直接回车保持默认):${NC}" prompt_read "容器 VMID [默认: $NEXT_ID]: "; CT_ID="$REPLY" prompt_read "容器静态 IP (CIDR 格式) [默认: $DEFAULT_CT_IP]: "; CT_IP="$REPLY" prompt_read "上级主路由网关 IP [默认: $GW_IP]: "; CT_GW="$REPLY" prompt_read "LXC 存储池 [默认: $DEFAULT_STORAGE]: "; CT_STORAGE="$REPLY" prompt_read "分配内存 (MB) [推荐 256~512MB, 默认: 256]: "; CT_MEM="$REPLY" prompt_read "分配磁盘大小 (GB) [推荐 2~4GB, 默认: 2]: "; CT_DISK="$REPLY" prompt_read "容器主机名 [默认: cubex-gateway]: "; CT_NAME="$REPLY" CT_ID=${CT_ID:-$NEXT_ID} CT_IP=${CT_IP:-$DEFAULT_CT_IP} CT_GW=${CT_GW:-$GW_IP} CT_STORAGE=${CT_STORAGE:-$DEFAULT_STORAGE} CT_MEM=${CT_MEM:-256} CT_DISK=${CT_DISK:-2} CT_NAME=${CT_NAME:-cubex-gateway} else CT_ID="$NEXT_ID" CT_IP="$DEFAULT_CT_IP" CT_GW="$GW_IP" CT_STORAGE="$DEFAULT_STORAGE" CT_MEM=256 CT_DISK=2 CT_NAME="cubex-gateway" msg "${GREEN}✓ 已启用非交互极速模式,自动匹配参数: VMID=$CT_ID, IP=$CT_IP, GW=$CT_GW, Storage=$CT_STORAGE${NC}" fi case "$CT_ID" in ''|*[!0-9]*) CT_ID="$NEXT_ID" ;; esac case "$CT_MEM" in ''|*[!0-9]*) CT_MEM=256 ;; esac case "$CT_DISK" in ''|*[!0-9]*) CT_DISK=2 ;; esac if ! printf '%s\n' "$CT_IP" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/[0-9]+$'; then if printf '%s\n' "$CT_IP" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$'; then CT_IP="${CT_IP}/24" else CT_IP="$DEFAULT_CT_IP" fi fi if ! printf '%s\n' "$CT_GW" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$'; then CT_GW="$GW_IP" fi case "$CT_NAME" in ''|*[!a-zA-Z0-9_-]*) CT_NAME="cubex-gateway" ;; esac if ! pvesm status -storage "$CT_STORAGE" -content rootdir >/dev/null 2>&1; then msg "${YELLOW}⚠️ 存储池 ${CT_STORAGE} 不支持容器 rootdir,自动修正为可用存储池: ${DEFAULT_STORAGE}${NC}" CT_STORAGE="$DEFAULT_STORAGE" fi if [ -n "$CT_GW" ] && printf '%s\n' "$CT_GW" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$'; then DNS_ARG="--nameserver $CT_GW" else DNS_ARG="--nameserver 223.5.5.5" fi IS_UPGRADE=0 if pct status "$CT_ID" >/dev/null 2>&1 || [ -f "/etc/pve/lxc/${CT_ID}.conf" ]; then msg "${BLUE}🔍 发现已存在容器 CT ${CT_ID},正在执行静态磁盘挂载安全探测...${NC}" CT_CUR_STATUS=$(pct status "$CT_ID" 2>/dev/null | awk '{print $2}') MOUNT_DIR="" MOUNT_PATH="" CLEANUP_LXC_MOUNT() { if [ -n "$MOUNT_DIR" ]; then pct unmount "$CT_ID" >/dev/null 2>&1 || true MOUNT_DIR="" fi } trap CLEANUP_LXC_MOUNT EXIT INT TERM CUBEX_EXISTS=0 if [ "$CT_CUR_STATUS" = "running" ]; then if pct exec "$CT_ID" -- test -f /opt/cubex/bin/cubexd >/dev/null 2>&1 || \ pct exec "$CT_ID" -- test -f /opt/CubeX/bin/cubexd >/dev/null 2>&1 || \ pct exec "$CT_ID" -- test -f /opt/cubex/install.manifest.json >/dev/null 2>&1 || \ pct exec "$CT_ID" -- test -d /opt/cubex/data >/dev/null 2>&1 || \ pct exec "$CT_ID" -- test -d /opt/CubeX/data >/dev/null 2>&1; then CUBEX_EXISTS=1 fi else MOUNT_RAW=$(pct mount "$CT_ID" 2>/dev/null || true) if [ -n "$MOUNT_RAW" ]; then MOUNT_DIR="1" MOUNT_PATH=$(printf '%s\n' "$MOUNT_RAW" | grep -oE "/[^[:space:]'\"]+" | head -n1 || true) [ -z "$MOUNT_PATH" ] && [ -d "/var/lib/lxc/${CT_ID}/rootfs" ] && MOUNT_PATH="/var/lib/lxc/${CT_ID}/rootfs" fi if [ -n "$MOUNT_PATH" ] && [ -d "$MOUNT_PATH" ]; then if [ -f "$MOUNT_PATH/opt/cubex/bin/cubexd" ] || [ -f "$MOUNT_PATH/opt/CubeX/bin/cubexd" ] || \ [ -f "$MOUNT_PATH/opt/cubex/install.manifest.json" ] || \ [ -d "$MOUNT_PATH/opt/cubex/data" ] || [ -d "$MOUNT_PATH/opt/CubeX/data" ]; then CUBEX_EXISTS=1 fi fi if [ -n "$MOUNT_DIR" ]; then pct unmount "$CT_ID" >/dev/null 2>&1 || true MOUNT_DIR="" fi fi trap - EXIT INT TERM if [ "$CUBEX_EXISTS" -eq 1 ]; then msg "${GREEN}💡 检测到容器 CT ${CT_ID} 已运行 CubeX,进入保留用户订阅与规则的平滑升级模式...${NC}" IS_UPGRADE=1 pct start "$CT_ID" >/dev/null 2>&1 || true else msg "${RED}❌ 检测到容器 CT ${CT_ID} 已存在,但未检测到 CubeX 核心文件或配置目录!${NC}" msg "${YELLOW}🛡️ [安全保护] 为防止误删除您的关键业务数据,已阻断自动销毁。${NC}" msg "${YELLOW}如确认该容器无用且需完全清空重装,请在 PVE 宿主终端手动执行:${NC}" msg "${CYAN} pct stop ${CT_ID} && pct destroy ${CT_ID} --purge 1${NC}" msg "${YELLOW}然后再重新运行本脚本进行全新部署。${NC}" exit 1 fi fi CT_CLEAN_IP=$(printf '%s\n' "$CT_IP" | cut -d'/' -f1) msg "\n${CYAN}🔧 [1/5] 加固 PVE 宿主机网络与内核模块 (加载 tun / xt_TPROXY)...${NC}" modprobe tun 2>/dev/null || true modprobe xt_TPROXY 2>/dev/null || true modprobe xt_socket 2>/dev/null || true modprobe xt_mark 2>/dev/null || true sysctl -w net.ipv4.ip_forward=1 >/dev/null 2>&1 || true if [ "$IS_UPGRADE" -eq 0 ]; then msg "\n${CYAN}📦 [2/5] 探查并匹配 Alpine Linux LXC 模板 (${PVE_ARCH})...${NC}" TPL_STORAGE=$(pvesm status -content vztmpl 2>/dev/null | awk 'NR>1 && $3=="active" {print $1}' | head -n1 || true) if [ -z "$TPL_STORAGE" ]; then TPL_STORAGE=$(pvesm status -content vztmpl 2>/dev/null | awk 'NR>1 {print $1}' | head -n1 || true) fi TPL_STORAGE="${TPL_STORAGE:-local}" TEMPLATE="" LOCAL_TEMPLATES=$(pveam list "$TPL_STORAGE" 2>/dev/null | grep -i 'alpine' | grep "${PVE_ARCH}" | awk '{print $1}' | tail -n1 || true) if [ -n "$LOCAL_TEMPLATES" ]; then TEMPLATE=$(basename "$LOCAL_TEMPLATES") msg "${GREEN}✓ 发现本地已缓存的 Alpine 模板 (${TPL_STORAGE}): ${TEMPLATE}${NC}" fi if [ -z "$TEMPLATE" ]; then if [ "${OFFLINE_MODE:-0}" -eq 1 ]; then msg "${RED}❌ [离线模式] 本地存储池 ${TPL_STORAGE} 未发现 Alpine ${PVE_ARCH} 模板!${NC}" msg "${YELLOW}💡 请先将 alpine-*-default_*_${PVE_ARCH}.tar.xz 放入 /var/lib/vz/template/cache/ 后重试。${NC}" exit 1 fi msg "${BLUE}正在更新并检索官方 Alpine 模板清单 (${PVE_ARCH})...${NC}" pveam update >/dev/null 2>&1 || true TEMPLATE=$(pveam available -section system 2>/dev/null | grep -i 'alpine' | grep "${PVE_ARCH}" | tail -n1 | awk '{print $2}' || true) if [ -z "$TEMPLATE" ]; then TEMPLATE="alpine-3.20-default_20240606_${PVE_ARCH}.tar.xz" fi if ! pveam list "$TPL_STORAGE" 2>/dev/null | grep -q "$TEMPLATE"; then msg "${BLUE}正在下载 Alpine 模板到 ${TPL_STORAGE}: ${TEMPLATE}...${NC}" if ! pveam download "$TPL_STORAGE" "$TEMPLATE"; then msg "${RED}❌ [模板下载失败] pveam download ${TPL_STORAGE} ${TEMPLATE} 失败!${NC}" msg "${YELLOW}💡 离线/无代理排查建议:${NC}" msg " 1. 检查宿主机 DNS、时间同步 (chronyc/date) 或执行 'pveam update && pveam available | grep alpine';" msg " 2. 离线导入: 将 alpine-3.20-default_*_${PVE_ARCH}.tar.xz 上传至 /var/lib/vz/template/cache/ 后重跑本脚本。" exit 1 fi fi fi msg "\n${CYAN}🚀 [3/5] 正在创建 CubeX LXC 原生容器 (CT $CT_ID)...${NC}" pct create "$CT_ID" "${TPL_STORAGE}:vztmpl/$TEMPLATE" \ --ostype alpine \ --hostname "$CT_NAME" \ --cores 2 \ --memory "$CT_MEM" \ --swap 256 \ --rootfs "${CT_STORAGE}:${CT_DISK}" \ --net0 "name=eth0,bridge=${PVE_BRIDGE},ip=${CT_IP},gw=${CT_GW},type=veth,firewall=0" \ $DNS_ARG \ --features nesting=1,keyctl=1 \ --unprivileged 0 \ --onboot 1 \ --start 0 msg "${CYAN}🔧 [4/5] 注入宿主内核 TUN 设备直通与 cgroup 白名单...${NC}" CONF_FILE="/etc/pve/lxc/${CT_ID}.conf" sed -i 's/firewall=1/firewall=0/g' "$CONF_FILE" 2>/dev/null || true pve-firewall restart 2>/dev/null || true if [ -f /sys/fs/cgroup/cgroup.controllers ]; then LXC_CGROUP_TUN="lxc.cgroup2.devices.allow: c 10:200 rwm" else LXC_CGROUP_TUN="lxc.cgroup.devices.allow: c 10:200 rwm" fi cat << EOF >> "$CONF_FILE" # === CubeX Native TUN & Acceleration Direct Pass === ${LXC_CGROUP_TUN} lxc.mount.entry: /dev/net/tun dev/net/tun none bind,create=file EOF pct start "$CT_ID" msg " -> ${BLUE}等待容器网卡与链路协商就绪...${NC}" for _pve_i in 1 2 3 4 5 6 7 8; do if pct exec "$CT_ID" -- ping -c 1 -W 1 "$CT_GW" >/dev/null 2>&1; then break fi sleep 1 done msg "\n${CYAN}🔄 [5/5] 容器内部全自动初始化(首次部署约需 30~60 秒,请耐心等待)...${NC}" msg " -> ${BOLD}[5.1/5.4] 正在配置容器 DNS 与国内极速镜像源...${NC}" pct exec "$CT_ID" -- sh -s "$CT_GW" << 'EOF' set -e CT_GW="$1" if [ -n "$CT_GW" ]; then echo "nameserver $CT_GW" > /etc/resolv.conf fi echo "nameserver 223.5.5.5" >> /etc/resolv.conf echo "nameserver 119.29.29.29" >> /etc/resolv.conf echo "nameserver 114.114.114.114" >> /etc/resolv.conf ALPINE_VER=$(cat /etc/alpine-release 2>/dev/null | cut -d. -f1,2) if [ -n "$ALPINE_VER" ]; then BRANCH="v${ALPINE_VER}" else BRANCH="latest-stable" fi cat << REPO > /etc/apk/repositories http://mirrors.aliyun.com/alpine/${BRANCH}/main http://mirrors.aliyun.com/alpine/${BRANCH}/community REPO EOF msg " -> ${BOLD}[5.2/5.4] 正在安装底层网络与系统依赖 (iptables / iproute2 / curl / ca-certificates)...${NC}" pct exec "$CT_ID" -- sh -s "${OFFLINE_MODE:-0}" << 'EOF' set -e _PVE_OFFLINE="${1:-0}" ALPINE_VER=$(cat /etc/alpine-release 2>/dev/null | cut -d. -f1,2) BRANCH="v${ALPINE_VER:-latest-stable}" MIRRORS="mirrors.aliyun.com mirrors.ustc.edu.cn mirrors.tuna.tsinghua.edu.cn mirrors.cloud.tencent.com dl-cdn.alpinelinux.org" INSTALLED=0 if [ "$_PVE_OFFLINE" -ne 1 ]; then for M in $MIRRORS; do cat << REPO > /etc/apk/repositories http://${M}/alpine/${BRANCH}/main http://${M}/alpine/${BRANCH}/community REPO if (command -v timeout >/dev/null 2>&1 && { timeout 10 apk update --quiet 2>/dev/null || timeout -t 10 apk update --quiet 2>/dev/null; }) || (! command -v timeout >/dev/null 2>&1 && apk update --quiet 2>/dev/null); then break fi sleep 1 done for attempt in 1 2; do if (command -v timeout >/dev/null 2>&1 && { timeout 25 apk add --no-cache curl ca-certificates iptables ip6tables nftables iproute2 tzdata unzip 2>/dev/null || timeout -t 25 apk add --no-cache curl ca-certificates iptables ip6tables nftables iproute2 tzdata unzip 2>/dev/null; }) || (! command -v timeout >/dev/null 2>&1 && apk add --no-cache curl ca-certificates iptables ip6tables nftables iproute2 tzdata unzip 2>/dev/null); then INSTALLED=1 break fi echo "正在重试依赖安装 ($attempt/2)..." sleep 1 done fi if [ "$INSTALLED" -ne 1 ]; then if [ "$_PVE_OFFLINE" -eq 1 ] && { command -v wget >/dev/null 2>&1 || command -v curl >/dev/null 2>&1; }; then echo "⚠️ [离线模式] 容器无外网,跳过在线 apk 依赖安装(保留 BusyBox wget),后续连网后请执行: apk add curl iptables nftables iproute2" elif ! command -v iptables >/dev/null 2>&1 || { ! command -v curl >/dev/null 2>&1 && ! command -v wget >/dev/null 2>&1; }; then echo "❌ [依赖安装失败] 容器内 apk add 失败且关键依赖 (iptables / curl) 缺失!" cat /etc/resolv.conf 2>/dev/null || true exit 1 fi fi sed -i 's|http://|https://|g' /etc/apk/repositories 2>/dev/null || true if [ -L /opt/cubex ]; then rm -f /opt/cubex 2>/dev/null || true fi mkdir -p /opt/cubex/bin /opt/cubex/data /opt/cubex/etc/rules [ -e /opt/CubeX ] || ln -s /opt/cubex /opt/CubeX 2>/dev/null || true EOF msg " -> ${BOLD}[5.3/5.4] 正在配置 OpenRC 系统级守护进程 (含自适应 GOMEMLIMIT 防爆保护)...${NC}" if [ "$CT_MEM" -le 300 ]; then _PVE_GOMEM="64MiB" _PVE_GOGC="50" elif [ "$CT_MEM" -le 600 ]; then _PVE_GOMEM="120MiB" _PVE_GOGC="50" elif [ "$CT_MEM" -le 1500 ]; then _PVE_GOMEM="256MiB" _PVE_GOGC="80" elif [ "$CT_MEM" -le 3000 ]; then _PVE_GOMEM="512MiB" _PVE_GOGC="100" else _PVE_GOMEM="1024MiB" _PVE_GOGC="100" fi pct exec "$CT_ID" -- sh -s "$APP_PORT" "$_PVE_GOMEM" "$_PVE_GOGC" << 'EOF' set -e _P="$1" _GM="${2:-64MiB}" _GC="${3:-50}" cat << INIT > /etc/init.d/cubexd #!/sbin/openrc-run name="cubexd" description="CubeX System Control Plane Daemon" command="/opt/cubex/bin/cubexd" command_args="-dir /opt/cubex -listen :${_P}" directory="/opt/cubex" supervisor="supervise-daemon" respawn_delay=2 respawn_max=0 output_log="/var/log/cubexd.log" error_log="/var/log/cubexd.err" export CUBEX_STORAGE_MODE="single_store" export CUBEX_STORE_DIR="/opt/cubex/store" export GOMEMLIMIT="${_GM}" export GOGC="${_GC}" export GODEBUG="madvdontneed=1" export TZ="Asia/Shanghai" depend() { need net after firewall } INIT chmod 755 /etc/init.d/cubexd if ! head -n 1 /etc/init.d/cubexd | grep -q "openrc-run"; then sed -i '1s|^|#!/sbin/openrc-run\n|' /etc/init.d/cubexd || true fi rc-update add cubexd default >/dev/null 2>&1 EOF else msg "\n${CYAN}🔄 [3/5] 原地升级容器内二进制与规则集 (统一小写 /opt/cubex 并无损兼容迁移历史 /opt/CubeX)...${NC}" pct exec "$CT_ID" -- sh -s << 'MIGRATE_EOF' if [ -L /opt/cubex ]; then rm -f /opt/cubex 2>/dev/null || true fi mkdir -p /opt/cubex/bin /opt/cubex/data /opt/cubex/etc/rules if [ -d /opt/CubeX ] && [ ! -L /opt/CubeX ]; then for sub in data etc; do if [ -d "/opt/CubeX/$sub" ]; then (cd "/opt/CubeX/$sub" && find . -type d 2>/dev/null) | while IFS= read -r _d; do [ "$_d" = "." ] && continue mkdir -p "/opt/cubex/$sub/${_d#./}" 2>/dev/null || true done (cd "/opt/CubeX/$sub" && find . \( -type f -o -type l \) 2>/dev/null) | while IFS= read -r _f; do _rel="${_f#./}" [ -n "$_rel" ] || continue if [ ! -e "/opt/cubex/$sub/$_rel" ]; then mkdir -p "$(dirname "/opt/cubex/$sub/$_rel")" 2>/dev/null || true cp -p "/opt/CubeX/$sub/$_rel" "/opt/cubex/$sub/$_rel" 2>/dev/null || cp "/opt/CubeX/$sub/$_rel" "/opt/cubex/$sub/$_rel" 2>/dev/null || true fi done fi done if [ -d /opt/CubeX/rules ]; then cp -rn /opt/CubeX/rules/. /opt/cubex/etc/rules/ 2>/dev/null || cp -r /opt/CubeX/rules/. /opt/cubex/etc/rules/ 2>/dev/null || true fi [ -f /opt/CubeX/install.manifest.json ] && [ ! -f /opt/cubex/install.manifest.json ] && cp -f /opt/CubeX/install.manifest.json /opt/cubex/install.manifest.json 2>/dev/null || true mv /opt/CubeX "/opt/CubeX.migrated.$(date +%s)" 2>/dev/null || true fi [ -e /opt/CubeX ] || ln -s /opt/cubex /opt/CubeX 2>/dev/null || true if [ -f /etc/init.d/cubexd ] && grep -q "/opt/CubeX" /etc/init.d/cubexd 2>/dev/null; then sed -i 's|/opt/CubeX/|/opt/cubex/|g; s|directory="/opt/CubeX"|directory="/opt/cubex"|g' /etc/init.d/cubexd 2>/dev/null || true fi if [ -f /etc/init.d/cubex ]; then rc-service cubex stop >/dev/null 2>&1 || true rc-update del cubex default >/dev/null 2>&1 || true rm -f /etc/init.d/cubex 2>/dev/null || true fi if { [ -d /opt/cubex/data ] && [ ! -L /opt/cubex/data ]; } || { [ -d /opt/cubex/etc ] && [ ! -L /opt/cubex/etc ]; }; then _snap="/opt/cubex/store/migrations/pre-v10-$(date -u +%Y%m%d-%H%M%S 2>/dev/null || echo backup)" mkdir -p "$_snap" /opt/cubex/store/data /opt/cubex/store/etc/rules 2>/dev/null || true for _sub in data etc; do if [ -d "/opt/cubex/$_sub" ] && [ ! -L "/opt/cubex/$_sub" ]; then cp -rn "/opt/cubex/$_sub/." "$_snap/$_sub/" 2>/dev/null || cp -r "/opt/cubex/$_sub/." "$_snap/$_sub/" 2>/dev/null || true cp -rn "/opt/cubex/$_sub/." "/opt/cubex/store/$_sub/" 2>/dev/null || cp -r "/opt/cubex/$_sub/." "/opt/cubex/store/$_sub/" 2>/dev/null || true fi done [ -f /opt/cubex/install.manifest.json ] && [ ! -L /opt/cubex/install.manifest.json ] && cp -p /opt/cubex/install.manifest.json "$_snap/install.manifest.json" 2>/dev/null || true fi MIGRATE_EOF fi msg " -> ${BOLD}[5.4/5.4] 正在拉取并释放 CubeX ${CUSTOM_VER:-latest} 双核完整发布包 (${PVE_ARCH})...${NC}" CHOSEN_ZIP="" if [ -n "${CUSTOM_PKG:-}" ]; then if [ ! -f "$CUSTOM_PKG" ] || [ ! -r "$CUSTOM_PKG" ] || ! zip_is_valid "$CUSTOM_PKG"; then msg "${RED}❌ 指定的离线发布包不存在、不可读或 CRC 校验损坏: ${CUSTOM_PKG}${NC}" >&2 exit 1 fi CHOSEN_ZIP="$CUSTOM_PKG" else _pve_sd="${CURRENT_SCRIPT_DIR:-.}" if [ -n "${CUSTOM_VER:-}" ]; then LOCAL_PKG=$(cubex_pick_latest_file \ "${_pve_sd}/../dist/release/CubeX-${CUSTOM_VER}"*"-linux-${PVE_ARCH}.zip" \ "dist/release/CubeX-${CUSTOM_VER}"*"-linux-${PVE_ARCH}.zip" \ "/tmp/CubeX-${CUSTOM_VER}"*"-linux-${PVE_ARCH}.zip" \ "/root/CubeX-${CUSTOM_VER}"*"-linux-${PVE_ARCH}.zip") else LOCAL_PKG=$(cubex_pick_latest_file \ "${_pve_sd}/../dist/release/CubeX-"*"-linux-${PVE_ARCH}.zip" \ "dist/release/CubeX-"*"-linux-${PVE_ARCH}.zip" \ "/tmp/CubeX-"*"-linux-${PVE_ARCH}.zip" \ "/root/CubeX-"*"-linux-${PVE_ARCH}.zip") fi if [ -n "$LOCAL_PKG" ] && [ -s "$LOCAL_PKG" ]; then if zip_is_valid "$LOCAL_PKG"; then CHOSEN_ZIP="$LOCAL_PKG" else msg "${YELLOW}⚠️ 本地缓存包损坏或格式异常,已拦截拒绝使用: ${LOCAL_PKG}${NC}" fi fi fi if [ -z "$CHOSEN_ZIP" ] && [ "${OFFLINE_MODE:-0}" -ne 1 ]; then msg "${BLUE}🌐 正在由 PVE 宿主机拉取完整发布包 (${PVE_ARCH} 双内核 + 105套规则集 + 控制面)...${NC}" cubex_resolve_latest_tag "${CUSTOM_VER:-}" ZIP_NAME="CubeX-${REL_TAG}-linux-${PVE_ARCH}.zip" TMP_ZIP="/tmp/${ZIP_NAME}" rm -f "$TMP_ZIP" if cubex_download_with_mirrors "https://github.com/zyeyefyass/CubeX/releases/download/${REL_TAG}/${ZIP_NAME}" "$TMP_ZIP" "zip_is_valid" "1200" "1"; then CHOSEN_ZIP="$TMP_ZIP" fi fi UNPACKED_OK=0 if [ -n "$CHOSEN_ZIP" ] && [ -s "$CHOSEN_ZIP" ]; then msg "${GREEN}✓ 宿主机完整发布包就绪 (${CHOSEN_ZIP}),执行宿主规范化解压与推入...${NC}" UNPACK_TMP="/tmp/cubex_unpack_$$" rm -rf "$UNPACK_TMP" && mkdir -p "$UNPACK_TMP" UNPACKED=0 if command -v python3 >/dev/null 2>&1; then if python3 -c ' import sys, zipfile, os zpath, outdir = sys.argv[1], sys.argv[2] with zipfile.ZipFile(zpath, "r") as z: for m in z.infolist(): clean_name = m.filename.replace(chr(92), "/").strip("/") if not clean_name: continue target = os.path.join(outdir, clean_name) if m.is_dir() or clean_name.endswith("/"): os.makedirs(target, exist_ok=True) else: os.makedirs(os.path.dirname(target), exist_ok=True) with z.open(m) as src, open(target, "wb") as dst: dst.write(src.read()) if m.external_attr > 0: os.chmod(target, (m.external_attr >> 16) & 0o777) ' "$CHOSEN_ZIP" "$UNPACK_TMP" 2>/dev/null; then UNPACKED=1 fi fi if [ "$UNPACKED" -eq 0 ] && command -v unzip >/dev/null 2>&1; then if unzip -q -o "$CHOSEN_ZIP" -d "$UNPACK_TMP/"; then UNPACKED=1 fi fi UNPACK_ROOT="$UNPACK_TMP" if [ "$UNPACKED" -eq 1 ] && [ ! -d "$UNPACK_ROOT/bin" ]; then for _pve_sub in "$UNPACK_TMP"/*; do if [ -d "$_pve_sub/bin" ]; then UNPACK_ROOT="$_pve_sub" break fi done fi if [ "$UNPACKED" -eq 1 ] && [ -d "$UNPACK_ROOT/bin" ]; then msg " -> ${BLUE}正在推送双核引擎、控制面、105套规则集与 Geodata 至容器内部...${NC}" pct exec "$CT_ID" -- rc-service cubexd stop >/dev/null 2>&1 || true pct exec "$CT_ID" -- sh -c 'pkill -x cubexd 2>/dev/null || killall cubexd 2>/dev/null || true; pkill -x mihomo 2>/dev/null || killall mihomo 2>/dev/null || true; pkill -x sing-box 2>/dev/null || killall sing-box 2>/dev/null || true' >/dev/null 2>&1 || true pct exec "$CT_ID" -- mkdir -p /opt/cubex/bin /opt/cubex/etc/rules /opt/cubex/data /usr/local/bin [ -f "$UNPACK_ROOT/bin/cubexd" ] && pct push "$CT_ID" "$UNPACK_ROOT/bin/cubexd" /opt/cubex/bin/cubexd -perms 755 [ -f "$UNPACK_ROOT/bin/cubex" ] && pct push "$CT_ID" "$UNPACK_ROOT/bin/cubex" /opt/cubex/bin/cubex -perms 755 [ -f "$UNPACK_ROOT/bin/sing-box" ] && pct push "$CT_ID" "$UNPACK_ROOT/bin/sing-box" /opt/cubex/bin/sing-box -perms 755 [ -f "$UNPACK_ROOT/bin/mihomo" ] && pct push "$CT_ID" "$UNPACK_ROOT/bin/mihomo" /opt/cubex/bin/mihomo -perms 755 if [ -d "$UNPACK_ROOT/etc/rules" ]; then tar -C "$UNPACK_ROOT/etc/rules" -cf - . | pct exec "$CT_ID" -- tar -xf - -C /opt/cubex/etc/rules/ 2>/dev/null || true elif [ -d "$UNPACK_ROOT/rules" ]; then tar -C "$UNPACK_ROOT/rules" -cf - . | pct exec "$CT_ID" -- tar -xf - -C /opt/cubex/etc/rules/ 2>/dev/null || true fi [ -f "$UNPACK_ROOT/etc/GeoIP.dat" ] && pct push "$CT_ID" "$UNPACK_ROOT/etc/GeoIP.dat" /opt/cubex/etc/GeoIP.dat -perms 644 [ -f "$UNPACK_ROOT/etc/geosite.dat" ] && pct push "$CT_ID" "$UNPACK_ROOT/etc/geosite.dat" /opt/cubex/etc/geosite.dat -perms 644 [ -f "$UNPACK_ROOT/meta.json" ] && pct push "$CT_ID" "$UNPACK_ROOT/meta.json" /opt/cubex/meta.json -perms 644 if [ -f "$UNPACK_ROOT/data/config.ir.json" ]; then if ! pct exec "$CT_ID" -- test -s /opt/cubex/data/config.ir.json >/dev/null 2>&1; then pct push "$CT_ID" "$UNPACK_ROOT/data/config.ir.json" /opt/cubex/data/config.ir.json -perms 644 fi fi pct exec "$CT_ID" -- sh -c 'ln -sf /opt/cubex/bin/cubex /usr/local/bin/cubex 2>/dev/null || true; [ -e /opt/CubeX ] || ln -s /opt/cubex /opt/CubeX 2>/dev/null || true' rm -rf "$UNPACK_TMP" UNPACKED_OK=1 msg "${GREEN}✓ 发布包直推完成 (免容器内部网络,零依赖解压)!${NC}" fi fi if [ "$UNPACKED_OK" -eq 0 ] && [ "${OFFLINE_MODE:-0}" -ne 1 ]; then msg "${RED}❌ 完整离线包 (CubeX-${REL_TAG:-latest}-linux-${PVE_ARCH}.zip) 全部镜像源拉取失败!(已中止写入,未损坏现有容器)${NC}" msg "${YELLOW}👉 国内无代理环境离线部署指引:${NC}" msg " 1. 从 GitHub Releases(或国内镜像)下载完整发布包: ${BOLD}CubeX-${REL_TAG:-latest}-linux-${PVE_ARCH}.zip${NC}" msg " 2. 将其上传放置到 PVE 宿主机 ${BOLD}/tmp/${NC} 或 ${BOLD}/root/${NC} 目录" msg " 3. 重新执行离线安装: ${CYAN}sh install.sh --platform=pve --pkg=/tmp/CubeX-${REL_TAG:-latest}-linux-${PVE_ARCH}.zip --offline${NC}" exit 1 fi if [ "$UNPACKED_OK" -eq 0 ]; then if [ -f "dist/cubexd-linux-${PVE_ARCH}" ]; then msg "${BLUE}注入本地最新构建的控制面: dist/cubexd-linux-${PVE_ARCH}...${NC}" pct push "$CT_ID" "dist/cubexd-linux-${PVE_ARCH}" /opt/cubex/bin/cubexd -perms 755 elif [ -f "/opt/cubex/bin/cubexd" ]; then pct push "$CT_ID" /opt/cubex/bin/cubexd /opt/cubex/bin/cubexd -perms 755 fi fi pct exec "$CT_ID" -- sh -s << 'EOF' if [ ! -f /opt/cubex/bin/cubexd ] || [ ! -s /opt/cubex/bin/cubexd ]; then echo "❌ 致命错误: 未能获取到有效的 cubexd 控制面二进制文件,请检查网络后重试!" exit 1 fi if [ ! -f /opt/cubex/bin/sing-box ] && [ ! -f /opt/cubex/bin/mihomo ]; then echo "❌ 致命错误: 双引擎核心文件 (sing-box / mihomo) 均缺失!" echo "👉 严重警告: 控制面在没有代理内核的情况下无法转发任何网络流量!请确保网络正常或放置发布包至宿主机 /tmp/ 后重试!" exit 1 elif [ ! -f /opt/cubex/bin/sing-box ] || [ ! -f /opt/cubex/bin/mihomo ]; then echo "⚠️ 警告: 容器内仅检测到单一代理内核 (mihomo=$([ -f /opt/cubex/bin/mihomo ] && echo OK || echo MISSING), sing-box=$([ -f /opt/cubex/bin/sing-box ] && echo OK || echo MISSING)),双核热切换将受限!" fi [ -e /opt/CubeX ] || ln -s /opt/cubex /opt/CubeX 2>/dev/null || true EOF if [ -n "${CUSTOM_VER:-}" ] && [ -z "${REL_TAG:-}" ]; then REL_TAG="$CUSTOM_VER" fi # 在容器内落盘 /opt/cubex/store/install.manifest.json(并软链 /opt/cubex/install.manifest.json)与 /opt/cubex/uninstall.sh pct exec "$CT_ID" -- sh -s "${REL_TAG:-${CUBEX_DEFAULT_TAG}}" "${APP_PORT}" << 'EOF' _PVE_VER="$1" _PVE_PORT="$2" _PVE_NOW=$(date -u +"%Y-%m-%dT%H:%M:%SZ" 2>/dev/null || echo "unknown") _PVE_INST="$_PVE_NOW" for _mf_cand in /opt/cubex/store/install.manifest.json /opt/cubex/install.manifest.json; do if [ -f "$_mf_cand" ]; then _OLD_INST=$(sed -n 's/.*"installed_at"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$_mf_cand" 2>/dev/null | head -n 1 || true) if [ -n "$_OLD_INST" ]; then _PVE_INST="$_OLD_INST" break fi fi done mkdir -p /opt/cubex/store/data /opt/cubex/store/etc/rules for _sub in data etc; do if [ -d "/opt/cubex/$_sub" ] && [ ! -L "/opt/cubex/$_sub" ]; then cp -rn "/opt/cubex/$_sub/." "/opt/cubex/store/$_sub/" 2>/dev/null || cp -r "/opt/cubex/$_sub/." "/opt/cubex/store/$_sub/" 2>/dev/null || true rm -rf "/opt/cubex/$_sub" 2>/dev/null || true fi [ -e "/opt/cubex/$_sub" ] || ln -s "store/$_sub" "/opt/cubex/$_sub" 2>/dev/null || true done cat << MEOF > /opt/cubex/store/install.manifest.json.tmp { "schema_version": "10.0", "version": "${_PVE_VER}", "platform_id": "pve_lxc", "deploy_method": "lxc", "install_dir": "/opt/cubex", "storage_mode": "single_store", "store_dir": "/opt/cubex/store", "data_dir": "/opt/cubex/store/data", "etc_dir": "/opt/cubex/store/etc", "listen_port": ${_PVE_PORT}, "network_mode": "lxc", "installed_at": "${_PVE_INST}", "updated_at": "${_PVE_NOW}" } MEOF chmod 644 /opt/cubex/store/install.manifest.json.tmp 2>/dev/null || true mv -f /opt/cubex/store/install.manifest.json.tmp /opt/cubex/store/install.manifest.json rm -f /opt/cubex/install.manifest.json 2>/dev/null || true ln -sf store/install.manifest.json /opt/cubex/install.manifest.json 2>/dev/null || true cat << 'UEOF' > /opt/cubex/uninstall.sh #!/bin/sh set -e PURGE_DATA=0 for _ua in "$@"; do case "$_ua" in --purge) PURGE_DATA=1 ;; -h|--help) printf '%s\n' "Usage: sh /opt/cubex/uninstall.sh [--purge]" exit 0 ;; esac done [ "$(id -u)" -eq 0 ] || { printf '%s\n' "Error: uninstall.sh must be run as root." >&2; exit 1; } INSTALL_DIR="/opt/cubex" for _mc in /opt/cubex/store/install.manifest.json /opt/cubex/install.manifest.json; do if [ -f "$_mc" ]; then _m_idir=$(sed -n 's/.*"install_dir"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$_mc" 2>/dev/null | head -n 1 || true) [ -n "$_m_idir" ] && [ "$_m_idir" != "/" ] && [ -d "$_m_idir" ] && INSTALL_DIR="$_m_idir" && break fi done rc-service cubexd stop >/dev/null 2>&1 || rc-service cubex stop >/dev/null 2>&1 || true rc-update del cubexd default >/dev/null 2>&1 || rc-update del cubex default >/dev/null 2>&1 || true pkill -x cubexd >/dev/null 2>&1 || killall cubexd >/dev/null 2>&1 || true pkill -x mihomo >/dev/null 2>&1 || killall mihomo >/dev/null 2>&1 || true pkill -x sing-box >/dev/null 2>&1 || killall sing-box >/dev/null 2>&1 || true rm -f /etc/init.d/cubexd /etc/init.d/cubex /usr/local/bin/cubex /usr/bin/cubex /etc/sysctl.d/99-cubex.conf 2>/dev/null || true if command -v nft >/dev/null 2>&1; then nft delete table inet cubex >/dev/null 2>&1 || true nft delete table inet cubex_symbiotic >/dev/null 2>&1 || true fi if command -v ip >/dev/null 2>&1; then while ip rule del table 2022 >/dev/null 2>&1; do :; done for _u_tdev in cubex-tun cubex-tun-a cubex-tun-b $(ip -o link show 2>/dev/null | awk -F': ' '{print $2}' | cut -d@ -f1 | grep -E '^cubex-tun' || true); do while ip rule del iif "$_u_tdev" >/dev/null 2>&1; do :; done done for _u_pref in $(ip rule show 2>/dev/null | awk -F: '/suppress_prefixlength 0|from all nop/ {gsub(/^[[:space:]]+/,"",$1); if ($1+0 >= 9000 && $1+0 <= 9020) print $1}'); do ip rule del pref "$_u_pref" >/dev/null 2>&1 || true done while ip -6 rule del table 2022 >/dev/null 2>&1; do :; done for _u_pref6 in $(ip -6 rule show 2>/dev/null | awk -F: '/suppress_prefixlength 0|from all nop/ {gsub(/^[[:space:]]+/,"",$1); if ($1+0 >= 9000 && $1+0 <= 9020) print $1}'); do ip -6 rule del pref "$_u_pref6" >/dev/null 2>&1 || true done ip route flush table 2022 >/dev/null 2>&1 || true ip -6 route flush table 2022 >/dev/null 2>&1 || true for _u_tdev in cubex-tun cubex-tun-a cubex-tun-b $(ip -o link show 2>/dev/null | awk -F': ' '{print $2}' | cut -d@ -f1 | grep -E '^cubex-tun' || true); do for _u_cidr in 198.18.0.0/15 198.18.0.0/16 198.19.0.0/16; do ip route del "$_u_cidr" dev "$_u_tdev" >/dev/null 2>&1 || true done ip -6 route del fc00::/18 dev "$_u_tdev" >/dev/null 2>&1 || true ip link del "$_u_tdev" >/dev/null 2>&1 || true done for _u_cidr in 198.18.0.0/15 198.18.0.0/16 198.19.0.0/16; do ip route del "$_u_cidr" >/dev/null 2>&1 || true done ip -6 route del fc00::/18 >/dev/null 2>&1 || true fi if command -v conntrack >/dev/null 2>&1; then for _u_ct in 198.18.0.0/15 198.18.0.0/16 198.19.0.0/16; do conntrack -D -d "$_u_ct" >/dev/null 2>&1 || true conntrack -D -s "$_u_ct" >/dev/null 2>&1 || true done fi if command -v iptables >/dev/null 2>&1; then while iptables -t nat -C POSTROUTING -j MASQUERADE >/dev/null 2>&1; do iptables -t nat -D POSTROUTING -j MASQUERADE >/dev/null 2>&1 || break done iptables -t nat -D OUTPUT -p udp --dport 53 -j CUBEX_DNS >/dev/null 2>&1 || true iptables -t nat -F CUBEX_DNS >/dev/null 2>&1 || true iptables -t nat -X CUBEX_DNS >/dev/null 2>&1 || true fi if [ -f /etc/resolv.conf ] && [ ! -L /etc/resolv.conf ]; then _u_ns=$(awk '/^[[:space:]]*nameserver[[:space:]]+/ {print $2}' /etc/resolv.conf 2>/dev/null || true) _u_ext=$(printf '%s\n' "$_u_ns" | grep -Ev '^(127\.0\.0\.1|::1)?$' || true) if [ -n "$_u_ns" ] && [ -z "$_u_ext" ]; then _u_gw=$(ip route show default 2>/dev/null | awk '/default/ {print $3; exit}' || true) { [ -n "$_u_gw" ] && printf 'nameserver %s\n' "$_u_gw" printf 'nameserver 223.5.5.5\nnameserver 119.29.29.29\n' } > /etc/resolv.conf 2>/dev/null || true fi fi rm -rf "${INSTALL_DIR}/bin" 2>/dev/null || true rm -f "${INSTALL_DIR}/meta.json" "${INSTALL_DIR}/install.manifest.json" "${INSTALL_DIR}/store/install.manifest.json" "${INSTALL_DIR}/uninstall.sh" 2>/dev/null || true if [ "$PURGE_DATA" -eq 1 ]; then rm -rf "${INSTALL_DIR}/store" "${INSTALL_DIR}/data" "${INSTALL_DIR}/etc" "${INSTALL_DIR}/rules" "${INSTALL_DIR}/logs" 2>/dev/null || true rm -f "${INSTALL_DIR}/README.md" "${INSTALL_DIR}/LICENSE" "${INSTALL_DIR}/install.sh" "${INSTALL_DIR}/docker-compose.yml" /var/log/cubexd.log /var/log/cubexd.err /var/log/cubex.log /var/log/cubex.err 2>/dev/null || true if [ -L /opt/CubeX ]; then rm -f /opt/CubeX 2>/dev/null || true fi rmdir "${INSTALL_DIR}" 2>/dev/null || true printf '%s\n' "[CubeX] CT uninstall complete (persistent config and data purged)." else rmdir "${INSTALL_DIR}" 2>/dev/null || true printf '%s\n' "[CubeX] CT uninstall complete. Config/data preserved in ${INSTALL_DIR} (pass --purge to delete)." fi UEOF chmod 755 /opt/cubex/uninstall.sh EOF pct exec "$CT_ID" -- sh -c ' chmod 755 /opt/cubex/bin/* 2>/dev/null || true if [ -f /etc/init.d/cubex ]; then rc-service cubex stop >/dev/null 2>&1 || true rc-update del cubex default >/dev/null 2>&1 || true rm -f /etc/init.d/cubex 2>/dev/null || true fi if [ -f /etc/init.d/cubexd ] && ! grep -q "CUBEX_STORAGE_MODE=" /etc/init.d/cubexd 2>/dev/null; then sed -i "/^export GOMEMLIMIT=/i export CUBEX_STORAGE_MODE=\"single_store\"\nexport CUBEX_STORE_DIR=\"/opt/cubex/store\"" /etc/init.d/cubexd 2>/dev/null || true fi if [ ! -f /etc/init.d/cubexd ] || ! head -n 1 /etc/init.d/cubexd | grep -q "openrc-run"; then sed -i "1s|^|#!/sbin/openrc-run\n|" /etc/init.d/cubexd 2>/dev/null || true chmod 755 /etc/init.d/cubexd 2>/dev/null || true fi rc-update add cubexd default >/dev/null 2>&1 || true ' msg "${CYAN}🚀 正在启动 CubeX 守护进程并验证 :${APP_PORT} 服务监听就绪...${NC}" pct exec "$CT_ID" -- rc-service cubexd restart >/dev/null 2>&1 || pct exec "$CT_ID" -- rc-service cubexd start >/dev/null 2>&1 || true if cubex_verify_panel_alive "$CT_CLEAN_IP" "$APP_PORT" "15" "pct exec ${CT_ID} --"; then cat << PVECLI > /usr/local/bin/cubex 2>/dev/null || true #!/bin/sh pct exec "$CT_ID" -- /opt/cubex/bin/cubex "\$@" PVECLI chmod +x /usr/local/bin/cubex 2>/dev/null || true if [ "$IS_UPGRADE" -eq 1 ]; then msg "\n${GREEN}${BOLD}═════════════════════════════════════════════════════════════════${NC}" msg "${GREEN}${BOLD}🎉 恭喜!CT ${CT_ID} 原地升级完成!现有订阅、节点与规则配置 100% 完整保留!${NC}" msg "${GREEN}${BOLD}═════════════════════════════════════════════════════════════════${NC}" msg " 📌 容器 ID : ${BOLD}${CT_ID} (${CT_NAME})${NC}" msg " 🌐 旁路由 IP : ${BOLD}${CT_CLEAN_IP}${NC}" msg " 🖥️ Web 控制台 : ${CYAN}${BOLD}http://${CT_CLEAN_IP}:${APP_PORT}${NC}" msg " 🧹 卸载指引 : ${YELLOW}sh install.sh --platform=pve --vmid=${CT_ID} --uninstall [--purge]${NC}" msg "${GREEN}${BOLD}═════════════════════════════════════════════════════════════════${NC}\n" else msg "\n${GREEN}${BOLD}═════════════════════════════════════════════════════════════════${NC}" msg "${GREEN}${BOLD}🎉 恭喜!CubeX 宿主共生透明代理网关已在 PVE LXC 容器成功部署运行!${NC}" msg "${GREEN}${BOLD}═════════════════════════════════════════════════════════════════${NC}" msg " 📌 容器 ID : ${BOLD}${CT_ID} (${CT_NAME})${NC}" msg " 🌐 旁路由 IP : ${BOLD}${CT_CLEAN_IP}${NC}" msg " 🖥️ Web 控制台 : ${CYAN}${BOLD}http://${CT_CLEAN_IP}:${APP_PORT}${NC}" msg " ⚡ 底座优势 : 原生共享宿主物理内核,内存仅需 70MB,启动 < 1 秒" msg " 🛡️ 访问安全 : 开箱即用 · 局域网直连免密 (亦可在控制台设置访问密钥)" msg " 🧹 卸载指引 : ${YELLOW}sh install.sh --platform=pve --vmid=${CT_ID} --uninstall [--purge]${NC}" msg "\n${YELLOW}💡 下一步联动指引:${NC}" msg " 1. 打开浏览器直接访问 Web 控制台: ${CYAN}http://${CT_CLEAN_IP}:${APP_PORT}${NC}" msg " 2. 进入【⚙️ 宿主共生与系统运维】,输入主路由(如 RouterOS / 爱快)的 IP 与凭据" msg " 3. 点击【⚡ 一键全栈自愈】,CubeX 将自动完成策略路由表创建、Fake-IP 回指与 0 秒逃生编排!" msg "${GREEN}${BOLD}═════════════════════════════════════════════════════════════════${NC}\n" fi else msg "\n${RED}${BOLD}═════════════════════════════════════════════════════════════════${NC}" msg "${RED}${BOLD}❌ [存活校验失败] CT ${CT_ID} 内的 CubeX 控制台 (:${APP_PORT}) 未就绪,拒绝连接!${NC}" msg "${RED}${BOLD}═════════════════════════════════════════════════════════════════${NC}" msg "${YELLOW}--- 服务状态 (rc-service cubexd status) ---${NC}" pct exec "$CT_ID" -- rc-service cubexd status 2>&1 || true msg "${YELLOW}--- 端口监听 (ss / netstat) ---${NC}" pct exec "$CT_ID" -- sh -c 'ss -tulnp 2>/dev/null || netstat -tulnp 2>/dev/null || true' msg "${YELLOW}--- 最近 20 行运行日志 (/var/log/cubexd.log & .err) ---${NC}" pct exec "$CT_ID" -- sh -c 'tail -n 20 /var/log/cubexd.log /var/log/cubexd.err 2>/dev/null || true' msg "${YELLOW}👉 可手动排查: pct enter ${CT_ID} && /opt/cubex/bin/cubexd -dir /opt/cubex -listen :${APP_PORT}${NC}" exit 1 fi } run_platform_pve_uninstall() { if [ "$(id -u)" -ne 0 ]; then msg "${RED}[ERROR] 请使用 root 权限执行 PVE 卸载。${NC}" exit 1 fi _pve_uid="${CUSTOM_VMID:-}" if [ -z "$_pve_uid" ] && command -v pct >/dev/null 2>&1; then _pve_matches="" _pve_match_cnt=0 for _cid in $(pct list 2>/dev/null | awk 'NR>1 {print $1}'); do _pve_hit=0 if [ -f "/etc/pve/lxc/${_cid}.conf" ] && grep -qi 'cubex' "/etc/pve/lxc/${_cid}.conf" 2>/dev/null; then _pve_hit=1 elif [ "$(pct status "$_cid" 2>/dev/null | awk '{print $2}')" = "running" ]; then if pct exec "$_cid" -- test -f /opt/cubex/bin/cubexd >/dev/null 2>&1 || \ pct exec "$_cid" -- test -f /opt/CubeX/bin/cubexd >/dev/null 2>&1 || \ pct exec "$_cid" -- test -f /opt/cubex/install.manifest.json >/dev/null 2>&1 || \ pct exec "$_cid" -- test -f /opt/cubex/uninstall.sh >/dev/null 2>&1 || \ pct exec "$_cid" -- test -f /opt/CubeX/uninstall.sh >/dev/null 2>&1; then _pve_hit=1 fi fi if [ "$_pve_hit" -eq 1 ]; then _pve_matches="${_pve_matches} ${_cid}" _pve_match_cnt=$((_pve_match_cnt + 1)) fi done if [ "$_pve_match_cnt" -eq 0 ]; then msg "${RED}❌ 未找到运行或已安装的 CubeX PVE LXC 容器,可通过 --vmid= 显式指定。${NC}" >&2 exit 1 elif [ "$_pve_match_cnt" -gt 1 ]; then msg "${RED}❌ 检测到多台 CubeX 容器 (VMID:${_pve_matches}),已阻断自动卸载!请显式传入 --vmid= 指定目标容器。${NC}" >&2 exit 1 else _pve_uid=$(printf '%s\n' "$_pve_matches" | awk '{print $1}') if [ ! -t 0 ] || [ ! -r /dev/tty ]; then msg "${RED}❌ 非交互模式下未指定 --vmid,已拒绝盲删单一容器 CT ${_pve_uid},请显式传入 --vmid=${_pve_uid}!${NC}" >&2 exit 1 fi if [ "${AUTO_CONFIRM:-0}" -ne 1 ]; then prompt_read "检测到唯一 CubeX 容器 CT ${_pve_uid},确认卸载? [y/N]: " case "$REPLY" in y|Y|yes|YES) ;; *) msg "${YELLOW}已取消卸载 CT ${_pve_uid}。${NC}" exit 1 ;; esac fi fi fi if [ -z "$_pve_uid" ]; then msg "${RED}❌ 未找到运行 CubeX 的 PVE LXC 容器,可通过 --vmid= 显式指定。${NC}" >&2 exit 1 fi msg "${YELLOW}🧹 正在清理 PVE LXC 容器 CT ${_pve_uid} 中的 CubeX...${NC}" if pct exec "$_pve_uid" -- test -f /opt/cubex/uninstall.sh >/dev/null 2>&1; then if [ "${PURGE_MODE:-0}" -eq 1 ]; then pct exec "$_pve_uid" -- sh /opt/cubex/uninstall.sh --purge else pct exec "$_pve_uid" -- sh /opt/cubex/uninstall.sh fi elif pct exec "$_pve_uid" -- test -f /opt/CubeX/uninstall.sh >/dev/null 2>&1; then if [ "${PURGE_MODE:-0}" -eq 1 ]; then pct exec "$_pve_uid" -- sh /opt/CubeX/uninstall.sh --purge else pct exec "$_pve_uid" -- sh /opt/CubeX/uninstall.sh fi else pct exec "$_pve_uid" -- sh -s "${PURGE_MODE:-0}" << 'EOF' _p="$1" rc-service cubexd stop >/dev/null 2>&1 || rc-service cubex stop >/dev/null 2>&1 || true rc-update del cubexd default >/dev/null 2>&1 || rc-update del cubex default >/dev/null 2>&1 || true pkill -x cubexd >/dev/null 2>&1 || killall cubexd >/dev/null 2>&1 || true pkill -x mihomo >/dev/null 2>&1 || killall mihomo >/dev/null 2>&1 || true pkill -x sing-box >/dev/null 2>&1 || killall sing-box >/dev/null 2>&1 || true rm -f /etc/init.d/cubexd /etc/init.d/cubex /usr/local/bin/cubex /usr/bin/cubex /etc/sysctl.d/99-cubex.conf 2>/dev/null || true if command -v nft >/dev/null 2>&1; then nft delete table inet cubex >/dev/null 2>&1 || true nft delete table inet cubex_symbiotic >/dev/null 2>&1 || true fi if command -v ip >/dev/null 2>&1; then while ip rule del table 2022 >/dev/null 2>&1; do :; done for _f_tdev in cubex-tun cubex-tun-a cubex-tun-b $(ip -o link show 2>/dev/null | awk -F': ' '{print $2}' | cut -d@ -f1 | grep -E '^cubex-tun' || true); do while ip rule del iif "$_f_tdev" >/dev/null 2>&1; do :; done done while ip -6 rule del table 2022 >/dev/null 2>&1; do :; done ip route flush table 2022 >/dev/null 2>&1 || true ip -6 route flush table 2022 >/dev/null 2>&1 || true for _f_tdev in cubex-tun cubex-tun-a cubex-tun-b $(ip -o link show 2>/dev/null | awk -F': ' '{print $2}' | cut -d@ -f1 | grep -E '^cubex-tun' || true); do for _f_cidr in 198.18.0.0/15 198.18.0.0/16 198.19.0.0/16; do ip route del "$_f_cidr" dev "$_f_tdev" >/dev/null 2>&1 || true done ip -6 route del fc00::/18 dev "$_f_tdev" >/dev/null 2>&1 || true ip link del "$_f_tdev" >/dev/null 2>&1 || true done for _f_cidr in 198.18.0.0/15 198.18.0.0/16 198.19.0.0/16; do ip route del "$_f_cidr" >/dev/null 2>&1 || true done ip -6 route del fc00::/18 >/dev/null 2>&1 || true fi if command -v conntrack >/dev/null 2>&1; then for _f_ct in 198.18.0.0/15 198.18.0.0/16 198.19.0.0/16; do conntrack -D -d "$_f_ct" >/dev/null 2>&1 || true conntrack -D -s "$_f_ct" >/dev/null 2>&1 || true done fi if command -v iptables >/dev/null 2>&1; then while iptables -t nat -C POSTROUTING -j MASQUERADE >/dev/null 2>&1; do iptables -t nat -D POSTROUTING -j MASQUERADE >/dev/null 2>&1 || break done iptables -t nat -D OUTPUT -p udp --dport 53 -j CUBEX_DNS >/dev/null 2>&1 || true iptables -t nat -F CUBEX_DNS >/dev/null 2>&1 || true iptables -t nat -X CUBEX_DNS >/dev/null 2>&1 || true fi rm -rf /opt/cubex/bin /opt/CubeX/bin 2>/dev/null || true rm -f /opt/cubex/install.manifest.json /opt/cubex/store/install.manifest.json /opt/CubeX/install.manifest.json /opt/cubex/meta.json /opt/CubeX/meta.json 2>/dev/null || true if [ "$_p" = "1" ]; then rm -rf /opt/cubex /opt/CubeX 2>/dev/null || true rm -f /var/log/cubexd.log /var/log/cubexd.err /var/log/cubex.log /var/log/cubex.err 2>/dev/null || true fi EOF fi rm -f /usr/local/bin/cubex 2>/dev/null || true msg "${GREEN}✅ PVE CT ${_pve_uid} 卸载清理完成。${NC}" } # ───────────────────────────────────────────────────────────────────────────── # 统一命令行入口与多平台分发 # ───────────────────────────────────────────────────────────────────────────── AUTO_CONFIRM=0 DEPLOY_MODE="" PLATFORM_OVERRIDE="auto" CUSTOM_DIR="" CUSTOM_VER="" CUSTOM_IP="" CUSTOM_VMID="" CUSTOM_GW="" CUSTOM_BRIDGE="" CUSTOM_PKG="" OFFLINE_MODE=0 UNINSTALL_MODE=0 PURGE_MODE=0 PORT="${PORT:-}" print_install_usage() { cat << 'USAGE_EOF' CubeX Universal Installer (v10.2.1) Usage: sh install.sh [options] --platform= auto | linux | pve | fnos | openwrt-docker (default: auto) --docker Use Docker deployment mode (Linux/OpenWrt) --native Use native binary daemon mode --dir= Custom install / data directory --version= Target release tag (e.g. v10.2.1) --pkg= Local offline .zip or docker .tar.gz package path --offline Offline mode (do not fetch from remote registries/mirrors) --port= Web console listen port (default: 2026) --ip= PVE CT static IP/CIDR (e.g. /24) --vmid= PVE CT VMID (e.g. 110) --gw= PVE CT gateway IP --bridge= PVE bridge name (default: auto / vmbr0) --uninstall Cleanly uninstall CubeX --purge With --uninstall, also remove persistent config/data -y | --yes Non-interactive mode -h | --help Show this help message USAGE_EOF } for _arg in "$@"; do case "$_arg" in -y|--yes|--silent|--non-interactive) AUTO_CONFIRM=1 ;; --docker) DEPLOY_MODE="docker" ;; --native) DEPLOY_MODE="native" ;; --platform=*) PLATFORM_OVERRIDE="${_arg#*=}" ;; --dir=*) CUSTOM_DIR="${_arg#*=}" ;; --version=*|-v=*) CUSTOM_VER="${_arg#*=}" ;; --ip=*) CUSTOM_IP="${_arg#*=}" ;; --vmid=*|--ctid=*) CUSTOM_VMID="${_arg#*=}" ;; --gw=*) CUSTOM_GW="${_arg#*=}" ;; --bridge=*) CUSTOM_BRIDGE="${_arg#*=}" ;; --port=*) PORT="${_arg#*=}" ;; --pkg=*) CUSTOM_PKG="${_arg#*=}" ;; --offline) OFFLINE_MODE=1 ;; --uninstall) UNINSTALL_MODE=1 ;; --purge) PURGE_MODE=1 ;; -h|--help) print_install_usage exit 0 ;; *) msg "${RED}❌ 未知参数: $_arg${NC}" >&2 print_install_usage >&2 exit 2 ;; esac done if [ -n "$CUSTOM_PKG" ]; then if [ ! -f "$CUSTOM_PKG" ] || [ ! -r "$CUSTOM_PKG" ] || [ ! -s "$CUSTOM_PKG" ]; then msg "${RED}❌ 指定的离线安装包不存在、不可读或为空: $CUSTOM_PKG${NC}" >&2 exit 1 fi fi [ -z "$CUSTOM_VER" ] && CUSTOM_VER="${CUBEX_VERSION:-}" REL_TAG="v10.2.1" CURRENT_SCRIPT_DIR="$(cd "$(dirname "$0")" 2>/dev/null && pwd || pwd)" if [ "$UNINSTALL_MODE" -eq 1 ]; then if [ "$PLATFORM_OVERRIDE" = "auto" ] || [ -z "$PLATFORM_OVERRIDE" ]; then detect_host_topology_and_platform case "$DETECTED_HOST" in pve) PLATFORM_OVERRIDE="pve" ;; openwrt) PLATFORM_OVERRIDE="openwrt-docker" ;; fnos) PLATFORM_OVERRIDE="fnos" ;; *) PLATFORM_OVERRIDE="linux" ;; esac fi cubex_run_uninstall "$PLATFORM_OVERRIDE" "${CUSTOM_DIR:-}" "${PURGE_MODE:-0}" exit 0 fi case "$PLATFORM_OVERRIDE" in fnos) run_platform_fnos ;; openwrt-docker|openwrt) run_platform_openwrt_docker ;; pve) run_platform_pve_host ;; linux) run_platform_linux ;; auto|"") detect_host_topology_and_platform case "$DETECTED_HOST" in pve) run_platform_pve_host ;; fnos) if [ "$DEPLOY_MODE" = "native" ]; then run_platform_linux else run_platform_fnos fi ;; openwrt) if [ "$DEPLOY_MODE" = "native" ]; then msg "${YELLOW}💡 OpenWrt / iStoreOS 原生模式请使用 Releases 中的离线 .run 自包含安装包: cubex_istoreos__.run${NC}" exit 0 fi run_platform_openwrt_docker ;; *) run_platform_linux ;; esac ;; *) msg "${RED}❌ 未知平台参数: $PLATFORM_OVERRIDE (支持 auto/linux/pve/fnos/openwrt-docker)${NC}" exit 1 ;; esac