#!/bin/sh # Vectra on an OpenWrt router: one installer for every architecture. # # wget -qO- https://vctl.io/i | sh # # or, to keep the file (options go after it, or after `sh -s --` in the pipe): # # wget -O /tmp/vectra https://vctl.io/i && sh /tmp/vectra # # sh /tmp/vectra install, or update what is installed # sh /tmp/vectra --standby install, but leave Vectra off: whatever carries the # traffic now (PassWall2, the old Vectra agent) keeps # it until `vectra on` # sh /tmp/vectra --check only the checks: nothing on the router changes # sh /tmp/vectra --uninstall remove Vectra (add --purge to forget the router's # Vectra identity and settings too) # --yes do not ask (a router with PassWall2: Vectra takes # over the traffic, `vectra off` gives it back; after # a day of Vectra's VPN, Vectra removes PassWall2) # --force go on below the memory floor (tests only: the # router may run out of memory) # --json say it as JSON lines, ASCII codes only (with # --check: what an operator reads through the panel) # --brand ID the router's brand until its subscription names # one: vectra | bloopcat | none. Without it a # router with no brand yet is labelled vectra # (this is Vectra's installer) and a label put on # earlier stays; a BloopCat router passes # --brand bloopcat; none = no brand (the router # names no service) # # Exit code: 0 done, nothing to warn of (--check: also with advice, named); # 2 done, with warnings (said in the summary, by code); 1 not done — refused # before any change, failed, or Vectra installed to carry the traffic and not # running; 3 an option it does not know. (Before 0.7.0-r14 a refusal was 2.) # # OpenWrt 23.05 or 24.10 with opkg, and OpenWrt 25.xx with apk: the same # packages, built twice (.ipk and .apk), from the same signed Vectra feed — each # with its key baked in below. On 25.xx the feed is apk's tagged repository # @vectra: vectra-controller-pro, xray-core, vectra-geodata and vectra-reporter # come from it only, whatever version of the same name OpenWrt's feeds carry. # # Nothing changes before every check has passed: the router, its memory and # storage, the clock, the network, the feeds, other proxy stacks. Then: the # signed Vectra feed is added (its key is baked into this file), dnsmasq is # replaced by dnsmasq-full without a moment the network has no DHCP or DNS # (both packages are downloaded first; if dnsmasq-full does not come up, the old # dnsmasq is put back), and vectra-controller-pro is installed with xray-core # and the geo data (an xray put on the router by hand becomes the xray-core # package of its own version first: nothing replaces it with another). The # end is checked, not assumed: the service runs, the # "vectra" ubus object answers, xray accepts the geo data, LuCI serves the page. # A download from the feeds that fails is tried again, three times in all. # Everything opkg says goes to /tmp/vectra-install.log. # # This file is a template until scripts/sign-pro-feed.sh bakes the block below # (the feed, its key, the architectures and versions it holds). For tests the # VECTRA_FEED, VECTRA_FEED_KEY, VECTRA_FEED_KEY_ID, VECTRA_ARCHS, # VECTRA_VERSION, VECTRA_XRAY_MIN, VECTRA_APK_KEY and VECTRA_APK_ARCHS # variables stand in for it. # >>> baked by sign-pro-feed.sh BAKED_FEED_URL='https://api.vctl.io/artifacts/openwrt/pro' BAKED_FEED_KEY='RWQpoZjXW6WODlEEan0DL28nZ7ks+8S9dvHBwo5G0ooQdVHzTbCNg9q/' BAKED_FEED_KEY_ID='29a198d75ba58e0e' BAKED_ARCHS='aarch64_cortex-a53' BAKED_VERSION='0.7.0-r73' BAKED_XRAY_MIN='26.11.9' BAKED_APK_KEY='MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEtleecMwHXfHNPYbHoILtVOv4m3f9WsOCvSHLwMUayGMHhSeUBiSBzqqh4ZoFAuulPtH17fcGAuybuvFjXLYxpg==' BAKED_APK_ARCHS='aarch64_cortex-a53' # <<< baked FEED_URL="${VECTRA_FEED:-$BAKED_FEED_URL}" FEED_KEY="${VECTRA_FEED_KEY:-$BAKED_FEED_KEY}" FEED_KEY_ID="${VECTRA_FEED_KEY_ID:-$BAKED_FEED_KEY_ID}" ARCHS="${VECTRA_ARCHS:-$BAKED_ARCHS}" VERSION="${VECTRA_VERSION:-$BAKED_VERSION}" XRAY_MIN="${VECTRA_XRAY_MIN:-$BAKED_XRAY_MIN}" # The apk feed (OpenWrt 25.xx): its ECDSA public key (the PEM's body, one line) # and the architectures it holds, under $FEED_URL/apk//packages.adb. APK_KEY="${VECTRA_APK_KEY:-$BAKED_APK_KEY}" APK_ARCHS="${VECTRA_APK_ARCHS:-$BAKED_APK_ARCHS}" # OpenWrt's own feeds through Vectra's caching proxy, for a router that cannot # reach downloads.openwrt.org (a broken ISP IPv6 is the usual cause). OPENWRT_MIRROR="${VECTRA_OPENWRT_MIRROR:-}" # 256 MB routers report 230-250 MB. Below that xray and vctl run the router out # of memory, and the owner is left without internet. MIN_RAM_KB="${VECTRA_MIN_RAM_KB:-196608}" # opkg downloads into /tmp (RAM): the largest package, xray, is about 10 MB. MIN_TMP_KB=24576 # Storage left over after the install, for configs, logs and updates. MARGIN_KB=4096 # What Vectra's own update asks to find free on /overlay # (internal/jobsafety, StorageOverlayFloorMB): below it, Connect's «Обновить» # is refused until room is made. UPDATE_FLOOR_KB=16384 # Official indexes carry no Installed-Size; an unpacked package takes about # three times its download (a gzipped tar). UNPACK_FACTOR=3 # TLS needs a clock later than this (2026-01-01). CLOCK_FLOOR=1767225600 # The feeds (downloads.openwrt.org above all) go away for a minute now and # then: on 2026-10-04 for about 40 s, and a router whose installer was fine was # left with DNSMASQ_DEPENDENCY. A step that downloads is tried three times, # this many seconds apart (40 s in all: the outage of that day). Whole # seconds, and nothing else: anything else is the default ("0 0" for tests). RETRY_DELAYS="$(printf '%s\n' "${VECTRA_RETRY_DELAYS:-10 30}" | awk 'NR > 1 { exit 1 } { for (i = 1; i <= NF; i++) { if ($i !~ /^[0-9]+$/) exit 1; printf "%s%d", (i > 1 ? " " : ""), $i } }')" && [ -n "$RETRY_DELAYS" ] || RETRY_DELAYS="10 30" # All the pauses of one run together: a router whose feeds stay away is # refused (or failed) as before, after two minutes at most, not after ten. RETRY_BUDGET=120 # How long, in seconds, the dnsmasq swap may leave the network without a # dnsmasq that answers. It runs from the old one's stop to dnsmasq-full # answering or, if that fails, to the old one being back. Stages share it: a # third for dnsmasq-full, then the way back from the package, then from the # files, then dnsmasq run by hand. Each start still gets a floor of its own, # counted from that start (dnsmasq-full and the package 20 s, the files 15 s, # by hand 10 s), so a slow router's opkg is not counted against its dnsmasq. # The total goes past the deadline only by those floors. DNS_DEADLINE="$(printf '%s\n' "${VECTRA_DNS_DEADLINE:-120}" | awk 'NR == 1 && /^[0-9]+$/ && $1 >= 15 { print $1 + 0 }')" [ -n "$DNS_DEADLINE" ] || DNS_DEADLINE=120 DNS_T0=0 CFG_PKG=vectra-controller-pro PKG=vectra-controller-pro GEO_PKG=vectra-geodata REP_PKG=vectra-reporter NFQWS_PKG=vectra-nfqws FEED_NAME=vectra_pro CUSTOMFEEDS=/etc/opkg/customfeeds.conf DISTFEEDS="${VECTRA_DISTFEEDS:-/etc/opkg/distfeeds.conf}" LOG=/tmp/vectra-install.log WORK=/tmp/vectra-install KEYS=/etc/opkg/keys SELF_COPY=/etc/vectra-controller-pro/vectra-install.sh GEO_OWN=/usr/share/vectra-controller-pro/geo # The dnsmasq the swap replaces, kept for the way back: on flash when there is # room (a reboot does not lose it), in RAM otherwise. On a router the swap left # broken it stays there for the owner. Each run has its own directory, so a # later run never takes away what an earlier one left. SAVED_RUN="$(date +%Y%m%d-%H%M%S)-$$" SAVED_FLASH="/root/vectra-dnsmasq-saved/$SAVED_RUN" SAVED_RAM="/tmp/vectra-dnsmasq-saved/$SAVED_RUN" SAVED="$SAVED_RAM" OPKG_INFO=/usr/lib/opkg/info OPKG_STATUS=/usr/lib/opkg/status # Where opkg keeps the feeds' lists, and its feed configuration. LISTS="${VECTRA_OPKG_LISTS:-/var/opkg-lists}" OPKG_CONFS="${VECTRA_OPKG_CONFS:-/etc/opkg.conf /etc/opkg/*.conf}" # The package manager: opkg (OpenWrt 23.05, 24.10) or apk (25.xx), as # check_router finds it. Every helper that asks about packages asks the one # the router has. PM=opkg # apk's: the installed database (read, as opkg's status file is), the feed as # a tagged repository, its key, and OpenWrt's own feeds. APK_DB="${VECTRA_APK_DB:-/lib/apk/db/installed}" APK_TAG=vectra APK_REPOS="${VECTRA_APK_REPOS:-/etc/apk/repositories.d}" APK_REPO_LIST="$APK_REPOS/vectra-pro.list" APK_KEYS="${VECTRA_APK_KEYS:-/etc/apk/keys}" APK_KEY_FILE="$APK_KEYS/vectra-pro.pem" APK_WORLD="${VECTRA_APK_WORLD:-/etc/apk/world}" # The usign key of the feed's opkg half, for vctl: the catalog and the geo set # are signed with it, beside the channel's Packages, on 25.xx as on 24.10 — and # a 25.xx router has no /etc/opkg/keys (vctl's apkFeedKeysDir). APK_USIGN_KEYS="${VECTRA_APK_USIGN_KEYS:-/etc/vectra-controller-pro/feed-keys}" # The feed's index as this run fetched and verified it (feed_field reads it). APK_INDEX="" # The old Vectra agent Vectra goes next to: one that knows it — it reads the # router's identity Vectra seals, and does not start beside a running Vectra — # from this release on, which installs this marker. LEGACY_AGENT_MIN=0.1.13-r45 LEGACY_AGENT_MARKER="${VECTRA_LEGACY_AGENT_MARKER:-/usr/share/vectra-controller/vault-read-v1}" # Other proxy stacks: two transparent proxies fight over the same traffic. # PassWall2 is the one vctl knows how to take over (and give back). CONFLICTS="podkop luci-app-podkop openclash luci-app-openclash homeproxy luci-app-homeproxy v2raya luci-app-v2raya nikki luci-app-nikki mihomo luci-app-mihomo ssclash luci-app-ssclash luci-app-passwall" # DPI helpers do not proxy, but they rewrite the same traffic. DPI_TOOLS="zapret luci-app-zapret youtubeUnblock luci-app-youtubeUnblock byedpi" MODE=install STANDBY=0 YES=0 FORCE=0 PURGE=0 JSON=0 # --brand: vectra, bloopcat or none; empty when not given (set_brand). BRAND= # The warnings of this run, by code: an install that ends with any exits 2 # (--check: 0, they are advice). FAILURES: what the end's checks found # broken where Vectra was to carry the traffic — the install exits 1. WARNINGS="" FAILURES="" # In --check, the refusal --standby lifts (the old agent): said, and the rest # checked as with --standby — one run says everything. BLOCKER="" # ----------------------------------------------------------------- output ---- # The installer's own address, for the commands it suggests: a run from a pipe # has no file of itself to name. INSTALL_URL=https://vctl.io/i # Vectra's look, on a terminal only: the brand's cyan, marks instead of +/-, # the summary in its colour. The log, --json and a run whose output is piped or # read by the panel get the plain text, byte for byte as before. NO_COLOR or # TERM=dumb turn it off. C_ACC="" C_OK="" C_WARN="" C_BAD="" C_DIM="" C_B="" C_OFF="" M_STEP="==>" M_OK=" +" M_NOTE=" -" M_WARN=" !" M_BAD=" !" if [ -t 1 ] && [ -z "${NO_COLOR:-}" ] && [ "${TERM:-dumb}" != dumb ]; then e="$(printf '\033')" C_ACC="${e}[38;5;80m" C_OK="${e}[38;5;78m" C_WARN="${e}[38;5;221m" C_BAD="${e}[38;5;203m" C_DIM="${e}[2m" C_B="${e}[1m" C_OFF="${e}[0m" M_STEP=" $C_ACC◆$C_OFF" M_OK=" $C_OK✓$C_OFF" M_NOTE=" $C_DIM·" M_WARN=" $C_WARN!$C_OFF" M_BAD=" $C_BAD✗$C_OFF" unset e fi # With --json the text goes to the log only, and stdout gets JSON lines. say() { [ "$JSON" = 1 ] || printf '%s\n' "$*" printf '%s\n' "$*" >> "$LOG" } # show : one line, dressed for the terminal. show() { [ "$JSON" = 1 ] || printf '%s\n' "$1" printf '%s\n' "$2" >> "$LOG" } # verdict : a line that sums up, in its colour and bold. verdict() { show "$1$C_B$2$C_OFF" "$2"; } step() { say ""; show "$M_STEP $C_B$*$C_OFF" "==> $*"; } ok() { show "$M_OK $*" " + $*"; } note() { show "$M_NOTE $*$C_OFF" " - $*"; } warn() { # : the run goes on, and ends with exit 2 WARNINGS="$WARNINGS $1" show "$M_WARN $2" " ! $2" jcheck warn "$1" } # banner: who runs, what, when — the brand's mark on a terminal, one line in the # log (and wherever the output is not a terminal). banner() { line="VCTL для OpenWrt${VERSION:+ $VERSION} — $(date)" if [ -z "$C_OFF" ] || [ "$JSON" = 1 ]; then say "$line" return 0 fi case "$MODE" in check) what="проверка роутера" ;; uninstall) what="удаление" ;; *) what="установка на роутер" ;; esac printf '\n %s▌%s %sV C T L%s\n %s▌%s %s%s · %s%s\n' \ "$C_ACC" "$C_OFF" "$C_B$C_ACC" "$C_OFF" "$C_ACC" "$C_OFF" "$C_DIM" "$what" "$(date '+%d.%m.%Y %H:%M')" "$C_OFF" printf '%s\n' "$line" >> "$LOG" } # self_file: this run has its own file (`sh /tmp/vectra`), not a pipe — whose # $0 is the shell's name, and a file of that name may be in the directory. self_file() { [ -f "$0" ] && grep -q '^# >>> baked by sign-pro-feed.sh' "$0" 2> /dev/null; } # uninstall_hint: how to remove Vectra later — the copy of this file kept on the # router, or (a run from a pipe left no file) the same pipe. uninstall_hint() { if self_file && mkdir -p /etc/vectra-controller-pro && cp "$0" "$SELF_COPY" 2> /dev/null; then say " Удалить: sh $SELF_COPY --uninstall" else say " Удалить: wget -qO- $INSTALL_URL | sh -s -- --uninstall" fi } refuse() { # : nothing was changed say "" verdict "$C_BAD" "Установка не выполнена: $2" say "На роутере ничего не изменено. Подробности: $LOG" say "Итог: не установлено, $1 (код 1)." jcheck refuse "$1" result refused 1 "$1" cleanup exit 1 } fail() { # : something was changed; say what state the router is in say "" verdict "$C_BAD" "ОШИБКА: $2" say "Подробности: $LOG" say "Итог: не установлено, $1 (код 1)." jcheck fail "$1" result failed 1 "$1" cleanup exit 1 } broken() { # : the end's check failed — the run exits 1 FAILURES="$FAILURES $1" show "$M_BAD $2" " ! $2" jcheck fail "$1" } # conclude : the summary, and the exit code it means — 1 # something the end's checks found broken; 2 with warnings (named by code); # 0 nothing to warn of. --check's warnings are advice: it exits 0, naming # them. conclude() { say "" if [ -n "$FAILURES" ]; then verdict "$C_BAD" "Итог: $1, но не работает:$FAILURES${WARNINGS:+; предупреждения:$WARNINGS} (код 1). Что это значит — выше; подробности: $LOG" result failed 1 "${FAILURES# }" exit 1 fi if [ -z "$WARNINGS" ]; then verdict "$C_OK" "Итог: $1, без предупреждений (код 0)." result ok 0 exit 0 fi if [ "$MODE" = check ]; then verdict "$C_OK" "Итог: $1, с замечаниями:$WARNINGS (код 0). Что они значат — выше." result ok 0 exit 0 fi verdict "$C_WARN" "Итог: $1, с предупреждениями:$WARNINGS (код 2). Что они значат — выше; подробности: $LOG" result warnings 2 exit 2 } # --json: one JSON object a line, ASCII only and short, so that each passes # the panel's output filter whole — {"check":CODE,"level":ok|warn|refuse|fail} # (with "value" where there is one) for what was found, and last # {"result":ok|warnings|refused|failed,"exit":N,...}. The codes are the # contract; the Russian text is in the log. jline() { [ "$JSON" = 1 ] && printf '{%s}\n' "$1" return 0 } jval() { printf '%s' "$1" | tr -cd ' -~' | cut -c 1-120 | sed 's/[\\"]/\\&/g'; } jcheck() { # [value] if [ -n "${3:-}" ]; then jline "\"check\":\"$2\",\"level\":\"$1\",\"value\":\"$(jval "$3")\"" else jline "\"check\":\"$2\",\"level\":\"$1\"" fi } result() { # [CODE]: the last line of --json w="" for c in $WARNINGS; do w="$w${w:+,}\"$c\""; done jline "\"result\":\"$1\",\"exit\":$2,\"mode\":\"$MODE\"${3:+,\"code\":\"$3\"},\"warnings\":[$w]" } run() { # a command whose output goes to the log only printf '$ %s\n' "$*" >> "$LOG" "$@" >> "$LOG" 2>&1 } # retry : run (its output to the log), and run again (RETRY_DELAYS) # while it fails on a download. Only for steps a second run takes up where the # first stopped — opkg update, download, install, upgrade; fetch — never for # one that changes the router otherwise (the dnsmasq swap: its remove, its # installs and the way back, which need no network). opkg fails for many # reasons, and only its "Failed to download" is the network: a signature, a # package that does not unpack or a postinst that fails is said at once, not # hidden behind a second try. opkg runs wget quiet, so its 404 and a CDN's 503 # read the same ("wget returned 8"): both are tried again — a package in a list # just downloaded is rarely missing, and an outage often answers 5xx. fetch # says the status: a 4xx is final, anything else (no connection, TLS, a # timeout, a 5xx) is tried again. # RT_UNTIL: a command that says the step got what this run needs from it even # though it failed — opkg update fails whenever any feed does (a third party's # that is down for good, too), and that is no reason to wait. RT_UNTIL="" RT_SPENT=0 retry() { rt_of=1 for rt_wait in $RETRY_DELAYS; do rt_of=$((rt_of + 1)); done rt_n=1 for rt_wait in $RETRY_DELAYS -; do rt_at=$(($(cat "$LOG" 2> /dev/null | wc -c))) printf '$ %s\n' "$*" >> "$LOG" "$@" >> "$LOG" 2>&1 rt_rc=$? [ "$rt_rc" = 0 ] && return 0 [ "$rt_wait" != - ] || return "$rt_rc" tail -c "+$((rt_at + 1))" "$LOG" > "$WORK/attempt.log" if [ "$1" = fetch ]; then grep -q -e 'HTTP error 4' "$WORK/attempt.log" && return "$rt_rc" else # apk: "WARNING: updating and opening : " (apk update), # "ERROR: : network error|temporary error" (a package's download). grep -q -e 'Failed to download' -e 'wget returned' -e 'WARNING: updating and opening' -e 'network error' -e 'temporary error' -e 'DNS lookup error' "$WORK/attempt.log" || return "$rt_rc" fi [ -n "$RT_UNTIL" ] && $RT_UNTIL && return "$rt_rc" if [ $((RT_SPENT + rt_wait)) -gt "$RETRY_BUDGET" ]; then printf '# a download failed (exit %s); the %s s of retries are spent\n' "$rt_rc" "$RETRY_BUDGET" >> "$LOG" return "$rt_rc" fi RT_SPENT=$((RT_SPENT + rt_wait)) rt_n=$((rt_n + 1)) printf '# a download failed (exit %s): attempt %s/%s in %s s\n' "$rt_rc" "$rt_n" "$rt_of" "$rt_wait" >> "$LOG" note "Сервер пакетов не ответил — повторяю ($rt_n/$rt_of)…" sleep "$rt_wait" done } # ---------------------------------------------------------------- helpers ---- # a.b.c[-rN] compared numerically, part by part: 0 if $1 >= $2. version_ge() { awk -v a="$1" -v b="$2" 'BEGIN { n = split(a, x, /[^0-9]+/); m = split(b, y, /[^0-9]+/) k = n > m ? n : m for (i = 1; i <= k; i++) { p = (i <= n && x[i] != "") ? x[i] + 0 : 0 q = (i <= m && y[i] != "") ? y[i] + 0 : 0 if (p > q) exit 0 if (p < q) exit 1 } exit 0 }' } # apk: what is installed is read from its database, as opkg's status file is # (P: name, V: version); a package is available when apk's policy for it # names a version a repository has — the tagged one included. apk_db_version() { awk -v p="$1" '/^P:/ { n = substr($0, 3) } /^V:/ && n == p { print substr($0, 3); exit } /^$/ { n = "" }' "$APK_DB" 2> /dev/null; } apk_available() { apk policy "$1" 2> /dev/null | awk '/^ [^ ]/ { v = 1 } /^ / && v && $0 !~ /lib\/apk\/db\/installed$/ { found = 1 } END { exit !found }'; } installed() { if [ "$PM" = apk ]; then [ -n "$(apk_db_version "$1")" ]; else opkg list-installed "$1" 2>/dev/null | grep -q "^$1 - "; fi } installed_version() { if [ "$PM" = apk ]; then apk_db_version "$1"; else opkg list-installed "$1" 2>/dev/null | sed -n "s/^$1 - //p" | head -n 1; fi } available() { if [ "$PM" = apk ]; then apk_available "$1"; else opkg list "$1" 2>/dev/null | grep -q "^$1 - "; fi } # have_all : each installed already, or in a feed's list. have_all() { for hv in "$@"; do installed "$hv" || available "$hv" || return 1; done } field() { if [ "$PM" = apk ]; then # Size only (check_storage): apk names it File-Size. af="$2" [ "$af" = Size ] && af=File-Size apk query --available --fields "$(echo "$af" | tr 'A-Z' 'a-z')" "$1" 2> /dev/null | sed -n "s/^$af: //p" | head -n 1 return fi opkg info "$1" 2>/dev/null | sed -n "s/^$2: //p" | head -n 1 } # A field of a package in the Vectra feed's own list (opkg info lists every # feed's version of a package, in no order that says which is which). opkg keeps # the list as it downloaded it: gzipped. On apk, the feed's packages.adb as # this run fetched and verified it (apk_fetch_index), dumped by apk itself: # Version, Depends (written back as opkg writes it, "a (>= 1), b"), Size and # Installed-Size. feed_field() { if [ "$PM" = apk ]; then [ -n "$APK_INDEX" ] && [ -f "$APK_INDEX" ] || return 0 apk adbdump "$APK_INDEX" 2> /dev/null | awk -v p="$1" -v f="$2" ' /^ - name: / { cur = substr($0, 11); dep = 0; next } cur != p { next } /^ [a-z-]+:/ { dep = 0 } f == "Version" && /^ version: / { print substr($0, 14); exit } f == "Size" && /^ file-size: / { print substr($0, 16); exit } f == "Installed-Size" && /^ installed-size: / { print substr($0, 21); exit } f == "Depends" && /^ depends:/ { dep = 1; next } f == "Depends" && dep && /^ - / { d = substr($0, 9) if (match(d, /[<>=~]/)) d = substr(d, 1, RSTART - 1) " (" substr(d, RSTART, (substr(d, RSTART + 1, 1) ~ /[<>=]/) ? 2 : 1) " " substr(d, RSTART + ((substr(d, RSTART + 1, 1) ~ /[<>=]/) ? 2 : 1)) ")" out = out sep d; sep = ", " } END { if (f == "Depends" && out != "") print out } ' return fi l="$LISTS/$FEED_NAME" { zcat "$l" 2> /dev/null || cat "$l" 2> /dev/null; } | awk -v p="$1" -v f="$2" ' /^Package: / { cur = substr($0, 10) } cur == p && index($0, f ": ") == 1 { print substr($0, length(f) + 3); exit } ' } # pkg_candidates : " " for every # feed list that carries it, as opkg update downloaded them. pkg_candidates() { for l in "$LISTS"/*; do [ -f "$l" ] || continue case "$l" in *.sig) continue ;; esac { zcat "$l" 2> /dev/null || cat "$l" 2> /dev/null; } | awk -v p="$1" -v feed="${l##*/}" ' /^Package: / { cur = substr($0, 10); v = f = s = "" } cur == p && /^Version: / { v = substr($0, 10) } cur == p && /^Filename: / { f = substr($0, 11) } cur == p && /^SHA256sum: / { s = substr($0, 12) } /^$/ { if (cur == p && v != "" && f != "") print feed, v, f, s; cur = "" } END { if (cur == p && v != "" && f != "") print feed, v, f, s } ' done } # feed_url : the URL of the feed opkg knows by that name. # shellcheck disable=SC2086 # OPKG_CONFS is a list, and a glob feed_url() { cat $OPKG_CONFS 2> /dev/null | awk -v n="$1" '($1 == "src/gz" || $1 == "src") && $2 == n { print $3; exit }'; } free_kb() { df -k "$1" 2>/dev/null | awk 'NR == 2 { print $4; exit }'; } # xray_released: the old xray binary is let go between Vectra's xray-core # and the rest of the install — nothing runs it, or the vctl that does is one # whose configs the new xray takes (0.7.0-r29 and later) and is restarted # onto it (release_old_xray); not with --standby, where Vectra stays off. XRAY_RELEASE_MIN=0.7.0-r29 xray_released() { pidof xray > /dev/null 2>&1 || return 0 [ "$STANDBY" != 1 ] && "/etc/init.d/$CFG_PKG" running > /dev/null 2>&1 && rv="$(installed_version "$PKG")" && [ -n "$rv" ] && version_ge "$rv" "$XRAY_RELEASE_MIN" } # release_old_xray restarts the vctl that runs onto the new xray, so the old # binary's room on the flash comes back before vctl's own opkg, which counts # its Installed-Size against what is free. XRAY_RESTARTED="" release_old_xray() { [ -n "$XRAY_REPLACED" ] && pidof xray > /dev/null 2>&1 && xray_released || return 0 (unset VECTRA_SKIP_POSTINST_RESTART; run "/etc/init.d/$CFG_PKG" restart) wait_for 30 "/etc/init.d/$CFG_PKG" running XRAY_RESTARTED=1 note "VCTL перезапущена на новом xray: место прежнего освобождено" } # store_compresses: the flash packages land on compresses what it stores # (UBIFS, JFFS2: the /overlay of a squashfs router). store_compresses() { case "$(awk -v m="$STORE" '$2 == m { t = $3 } END { print t }' "${VECTRA_PROC_MOUNTS:-/proc/mounts}" 2> /dev/null)" in ubifs | jffs2) return 0 ;; esac return 1 } # Where packages land: /overlay on a squashfs router, / otherwise. storage_path() { if grep -q ' /overlay ' /proc/mounts 2>/dev/null; then echo /overlay; else echo /; fi } service_running() { [ -x "/etc/init.d/$1" ] && "/etc/init.d/$1" running > /dev/null 2>&1; } wait_for() { # n="$1" shift while [ "$n" -gt 0 ]; do "$@" > /dev/null 2>&1 && return 0 sleep 1 n=$((n - 1)) done return 1 } fetch() { # : uclient-fetch (wget) with TLS, as opkg itself fetches # Not quiet: its "HTTP error 404" in the log is what tells retry a 4xx. wget -T 20 -O "$2" "$1" >> "$LOG" 2>&1 } # The xray vctl runs: /usr/bin/xray (vctl-xray-wrapper execs it), the one # xray-core installs; any other on PATH only where there is none. XRAY_BIN="${VECTRA_XRAY_BIN:-/usr/bin/xray}" xray_version() { if [ -x "$XRAY_BIN" ]; then "$XRAY_BIN" version; else xray version; fi 2> /dev/null | awk 'NR == 1 { print $2; exit }' } lan_address() { a="$(uci -q get network.lan.ipaddr)" echo "${a%%/*}" } # --------------------------------------------------------------- cleanup ---- DISTFEEDS_SWAPPED=0 FEED_ADDED=0 KEY_ADDED=0 USIGN_ADDED=0 INSTALLED_SOMETHING=0 DNSMASQ_KEEP=0 SAVED_MADE=0 # The package that runs the router's dnsmasq (check_dnsmasq), the one the swap # replaces: dnsmasq or dnsmasq-dhcpv6. DNSMASQ_PKG="" OLD="" cleanup() { # OpenWrt's own feeds go back to their mirrors: the proxy was for this run. if [ "$DISTFEEDS_SWAPPED" = 1 ] && [ -f "$WORK/distfeeds.conf.orig" ]; then cp "$WORK/distfeeds.conf.orig" "$DISTFEEDS" && DISTFEEDS_SWAPPED=0 fi # A run that installed nothing leaves no trace of the Vectra feed either. if [ "$INSTALLED_SOMETHING" = 0 ]; then [ "$FEED_ADDED" = 1 ] && remove_feed [ "$USIGN_ADDED" = 1 ] && rm -f "$APK_USIGN_KEYS/$FEED_KEY_ID" if [ "$KEY_ADDED" = 1 ]; then if [ "$PM" = apk ]; then grep -q "@$APK_TAG" "$APK_WORLD" 2> /dev/null || rm -f "$APK_KEY_FILE" else rm -f "$KEYS/$FEED_KEY_ID" fi fi fi rm -rf "$WORK/pkgs" "$WORK/attempt.log" # Only what this run kept: a copy an earlier run left for the owner stays. if [ "$SAVED_MADE" = 1 ] && [ "$DNSMASQ_KEEP" != 1 ]; then rm -rf "$SAVED_RAM" "$SAVED_FLASH" rmdir "${SAVED_RAM%/*}" "${SAVED_FLASH%/*}" 2> /dev/null fi } remove_feed() { if [ "$PM" = apk ]; then if [ -f "$WORK/vectra-pro.list.orig" ]; then cat "$WORK/vectra-pro.list.orig" > "$APK_REPO_LIST" elif ! grep -q "@$APK_TAG" "$APK_WORLD" 2> /dev/null; then rm -f "$APK_REPO_LIST" fi return 0 fi [ -f "$CUSTOMFEEDS" ] || return 0 grep -v "^src/gz $FEED_NAME " "$CUSTOMFEEDS" > "$WORK/customfeeds.conf" 2>/dev/null cat "$WORK/customfeeds.conf" > "$CUSTOMFEEDS" } # ---------------------------------------------------------------- checks ---- ARCH="" RELEASE="" STORE="" TAKEOVER="" check_router() { step "Роутер" [ "$(id -u 2>/dev/null)" = 0 ] || refuse NOT_ROOT "запустите установщик от root." [ -f /etc/openwrt_release ] || refuse NOT_OPENWRT "это не OpenWrt (нет /etc/openwrt_release)." # shellcheck disable=SC1091 . /etc/openwrt_release RELEASE="${DISTRIB_RELEASE:-?}" ok "${DISTRIB_DESCRIPTION:-OpenWrt $RELEASE}, ${DISTRIB_TARGET:-?}" # opkg on 23.05 and 24.10, apk from 25.xx on: the build of Vectra for it. if command -v opkg > /dev/null 2>&1; then PM=opkg elif command -v apk > /dev/null 2>&1 && [ -f "$APK_DB" ]; then PM=apk else refuse NO_OPKG "на роутере нет ни opkg, ни apk." fi case "$PM:$RELEASE" in opkg:23.05* | opkg:24.10*) ;; apk:25.*) ;; *:SNAPSHOT*) refuse OPENWRT_SNAPSHOT "это снапшот OpenWrt: поддерживаются выпуски 23.05, 24.10 и 25.12." ;; apk:*) refuse OPENWRT_RELEASE "OpenWrt $RELEASE с apk не поддерживается: нужен 25.12 (или 23.05, 24.10 с opkg)." ;; *) refuse OPENWRT_RELEASE "OpenWrt $RELEASE не поддерживается: нужен 23.05, 24.10 или 25.12 (nftables и dnsmasq с nftset)." ;; esac [ -x /sbin/fw4 ] || refuse NO_FIREWALL4 "нет firewall4 (nftables): VCTL работает только с ним." if [ "$PM" = apk ]; then DISTFEEDS="${VECTRA_DISTFEEDS:-$APK_REPOS/distfeeds.list}" # apk's own architectures (/etc/apk/arch), the router's first. [ -n "$APK_KEY" ] && [ -n "$APK_ARCHS" ] || refuse NO_APK_FEED "в этом установщике нет фида VCTL для OpenWrt $RELEASE (apk). Скачайте свежий установщик: wget -qO- $INSTALL_URL | sh" router_archs="$(grep -v -x -e noarch -e all "${VECTRA_APK_ARCH_FILE:-/etc/apk/arch}" 2> /dev/null)" for a in $router_archs; do for b in $APK_ARCHS; do [ "$a" = "$b" ] && { ARCH="$a"; break 2; } done done [ -n "$ARCH" ] || refuse ARCH_UNSUPPORTED "архитектура роутера ($(echo $router_archs)) не поддерживается: для неё нет сборки VCTL для OpenWrt $RELEASE." ok "архитектура $ARCH, пакеты apk (OpenWrt $RELEASE)" else # The first architecture opkg prefers that the feed has. for a in $(opkg print-architecture 2>/dev/null | awk '$1 == "arch" && $2 != "all" && $2 != "noarch" { print $3, $2 }' | sort -rn | awk '{ print $2 }'); do for b in $ARCHS; do [ "$a" = "$b" ] && { ARCH="$a"; break 2; } done done [ -n "$ARCH" ] || refuse ARCH_UNSUPPORTED "архитектура роутера ($(opkg print-architecture 2>/dev/null | awk '$2 != "all" && $2 != "noarch" { printf "%s ", $2 }')) не поддерживается: для неё нет сборки VCTL." ok "архитектура $ARCH" fi jcheck ok PACKAGE_MANAGER "$PM" mem="$(awk '/^MemTotal:/ { print $2; exit }' /proc/meminfo)" if [ "${mem:-0}" -lt "$MIN_RAM_KB" ]; then [ "$FORCE" = 1 ] || refuse RAM_TOO_LOW "оперативной памяти $((mem / 1024)) МБ, нужно не меньше $((MIN_RAM_KB / 1024)) МБ (роутер на 256 МБ): иначе xray и VCTL исчерпают память и интернет пропадёт." warn RAM_BELOW_FLOOR_FORCED "памяти $((mem / 1024)) МБ, ниже порога $((MIN_RAM_KB / 1024)) МБ — продолжаю по --force" else ok "память $((mem / 1024)) МБ" fi tmp="$(free_kb /tmp)" [ "${tmp:-0}" -ge "$MIN_TMP_KB" ] || refuse TMP_TOO_SMALL "в /tmp свободно $((${tmp:-0} / 1024)) МБ, нужно $((MIN_TMP_KB / 1024)) МБ для загрузки пакетов." STORE="$(storage_path)" } check_clock() { now="$(date +%s)" if [ "$now" -lt "$CLOCK_FLOOR" ]; then note "часы роутера отстают ($(date)); синхронизирую" for p in 0.openwrt.pool.ntp.org 1.openwrt.pool.ntp.org time.google.com; do run ntpd -n -q -p "$p" && break done now="$(date +%s)" [ "$now" -ge "$CLOCK_FLOOR" ] || refuse CLOCK_UNSYNCED "часы роутера показывают $(date) и не синхронизируются по NTP: без верного времени не работает TLS." fi ok "часы: $(date)" } # check_legacy_agent: the old Vectra agent (vectra-controller-agent) runs # the router. Vectra goes next to it, off (--standby): two controllers would # check in to the panel as the same router and take the same traffic; `vectra # on` later stops and disables the agent and PassWall2, noting whom `vectra # off` gives the traffic back to. And only next to an agent that knows Vectra # (LEGACY_AGENT_MIN). check_legacy_agent() { av="$(installed_version vectra-controller-agent)" if [ ! -f "$LEGACY_AGENT_MARKER" ] && ! version_ge "${av:-0}" "$LEGACY_AGENT_MIN"; then refuse LEGACY_AGENT_TOO_OLD "на роутере прежний агент VCTL vectra-controller-agent ${av:-?}, а VCTL встаёт только рядом с $LEGACY_AGENT_MIN или новее. Более старый не знает о VCTL: его сторож может запустить его рядом с работающей VCTL, и он не прочитает личность роутера, которую VCTL хранит запечатанной — после vectra off он не связался бы с панелью. Сначала обновите агента (панель: обновление контроллера, канал stable), затем запустите установщик снова." fi if [ "$STANDBY" = 1 ]; then ok "прежний агент VCTL $av: VCTL встанет рядом с ним выключенной" jcheck ok LEGACY_AGENT "$av" return 0 fi why="на роутере работает прежний агент VCTL (vectra-controller-agent $av), поэтому нужен --standby: VCTL встанет рядом с ним выключенной, а он и PassWall2 продолжат работать. Без --standby на роутере оказались бы два контроллера: они отмечались бы в панели как один и тот же роутер и забирали бы один и тот же трафик. Переключение — потом, командой vectra on: она остановит агента и PassWall2 и запомнит, кому вернуть трафик (vectra off). Установка: sh $0 --standby" [ "$MODE" = check ] || refuse LEGACY_AGENT_NEEDS_STANDBY "$why" BLOCKER=LEGACY_AGENT_NEEDS_STANDBY say " ! $why" jcheck refuse LEGACY_AGENT_NEEDS_STANDBY "$av" note "остальное проверяю так, как для --standby" STANDBY=1 } check_conflicts() { step "Другие прокси на роутере" installed vectra-controller-agent && check_legacy_agent found="" for p in $CONFLICTS; do installed "$p" && found="$found $p"; done for s in sing-box xray; do # The package alone is harmless: OpenWrt's xray-core and sing-box enable # an init script that starts nothing until configured (PassWall and # podkop run the binary themselves). A service that runs is not. service_running "$s" && found="$found $s(служба)" done [ -z "$found" ] || refuse PROXY_CONFLICT "установлено:$found. Два прозрачных прокси на одном роутере мешают друг другу. Удалите или выключите их и запустите установщик снова." for p in $DPI_TOOLS; do installed "$p" && warn DPI_TOOL "$p установлен: он меняет тот же трафик; если сайты перестанут открываться, выключите его" done check_passwall_xray "$XRAY_MIN" if [ "$STANDBY" = 1 ]; then ok "режим --standby: VCTL встанет выключенной, трафик никто не забирает" elif installed luci-app-passwall2 || [ -x /etc/init.d/passwall2 ]; then TAKEOVER=passwall2 jcheck ok PASSWALL_TAKEOVER say " PassWall2: VCTL заберёт у него трафик (PassWall2 остановится)." say " Вернуть ему трафик: vectra off." say " До привязки роутера к аккаунту интернет пойдёт напрямую, без VPN;" say " после привязки (код появится на странице VPN) — через VCTL." say " Через сутки работы VPN VCTL удалит PassWall2 сама" say " (настройки сохранятся в /etc/vectra-controller-pro/backup);" say " после этого vectra off оставит интернет без VPN." if [ "$MODE" = check ]; then note "--check ничего не меняет; установка спросит, забирать ли трафик (или --yes)" elif [ "$YES" != 1 ]; then [ "$JSON" != 1 ] && [ -t 0 ] || refuse PASSWALL_NEEDS_YES "на роутере PassWall2. Запустите с --yes (wget -qO- $INSTALL_URL | sh -s -- --yes), если VCTL должна забрать у него трафик." printf ' Продолжить? [y/N] ' read -r answer case "$answer" in y | Y | yes | д | Д | да) ;; *) refuse CANCELLED "отменено." ;; esac fi else ok "не найдено" fi } # check_dnsmasq: the dnsmasq the swap will replace, before anything changes — # which package runs it (dnsmasq or dnsmasq-dhcpv6; another one the installer # does not take apart), and that the owner runs it: enabled and running. A # router whose DNS and DHCP another program does (AdGuard Home, dnsmasq # switched off) is refused, not given a dnsmasq the owner turned off. check_dnsmasq() { installed dnsmasq-full && return 0 step "DNS и DHCP роутера" DNSMASQ_PKG="" for p in dnsmasq dnsmasq-dhcpv6; do installed "$p" && { DNSMASQ_PKG="$p"; break; } done if [ -z "$DNSMASQ_PKG" ]; then if [ "$PM" = apk ]; then owner="$(apk info --who-owns /usr/sbin/dnsmasq 2> /dev/null | sed -n 's/^.* is owned by \(.*\)-[^-]*-r[0-9]*$/\1/p' | head -n 1)" else owner="$(opkg search /usr/sbin/dnsmasq 2> /dev/null | sed -n 's/ - .*//p' | head -n 1)" fi [ -n "$owner" ] && refuse DNSMASQ_UNKNOWN_PACKAGE "dnsmasq на роутере из пакета $owner: установщик заменяет на dnsmasq-full только dnsmasq и dnsmasq-dhcpv6. Замените его на dnsmasq-full сами и запустите установщик снова." [ -e /usr/sbin/dnsmasq ] && refuse DNSMASQ_UNKNOWN_PACKAGE "dnsmasq на роутере поставлен не пакетом: установщик не знает, как вернуть его, если dnsmasq-full не заработает. Поставьте dnsmasq-full сами и запустите установщик снова." refuse DNSMASQ_ABSENT "на роутере нет dnsmasq: DNS и DHCP делает другая программа. VCTL работает через dnsmasq-full как DNS роутера, а ставить его рядом с чужим DNS/DHCP установщик не будет." fi if ! /etc/init.d/dnsmasq enabled > /dev/null 2>&1 || ! /etc/init.d/dnsmasq running > /dev/null 2>&1; then refuse DNSMASQ_NOT_ACTIVE "$DNSMASQ_PKG выключен (не запущен или убран из автозапуска): DNS и DHCP, видимо, делает другая программа (например, AdGuard Home). VCTL работает через dnsmasq-full как DNS роутера, а установщик не включает то, что выключил владелец." fi ok "$DNSMASQ_PKG $(installed_version "$DNSMASQ_PKG") работает; его заменит dnsmasq-full" jcheck ok DNSMASQ "$DNSMASQ_PKG" } # ----------------------------------------------------------------- feeds ---- # select_pkg_family: pick the clean `vctl` package family on fresh installs # (or when `vctl` is already installed), while keeping `vectra-controller-pro` # on routers that already have the legacy package installed or on older feeds # that do not yet offer `vctl`. select_pkg_family() { if installed vectra-controller-pro; then PKG=vectra-controller-pro GEO_PKG=vectra-geodata REP_PKG=vectra-reporter NFQWS_PKG=vectra-nfqws elif installed vctl || available vctl; then PKG=vctl GEO_PKG=vctl-geodata REP_PKG=vctl-reporter NFQWS_PKG=vctl-nfqws else PKG=vectra-controller-pro GEO_PKG=vectra-geodata REP_PKG=vectra-reporter NFQWS_PKG=vectra-nfqws fi COMPANIONS="$GEO_PKG $REP_PKG" } # add_feed_apk: the apk feed (OpenWrt 25.xx) — its key in /etc/apk/keys, the # feed as the tagged repository @vectra (a package of it is installed only when # asked for by that tag, and then only from it), its index fetched and # verified against that key alone before apk update, which verifies it again # and drops a repository whose signature does not check out. add_feed_apk() { mkdir -p "$APK_KEYS" "$APK_REPOS" "$WORK" pem="$(printf -- '-----BEGIN PUBLIC KEY-----\n%s\n-----END PUBLIC KEY-----\n' "$APK_KEY")" if [ -f "$APK_KEY_FILE" ]; then [ "$(sed '/^-----/d' "$APK_KEY_FILE" | tr -d '\n')" = "$APK_KEY" ] || refuse FEED_KEY_CLASH "в $APK_KEYS уже лежит другой ключ vectra-pro.pem." else printf '%s\n' "$pem" > "$APK_KEY_FILE" KEY_ADDED=1 fi mkdir -p "$APK_USIGN_KEYS" if [ -f "$APK_USIGN_KEYS/$FEED_KEY_ID" ]; then [ "$(sed -n 2p "$APK_USIGN_KEYS/$FEED_KEY_ID")" = "$FEED_KEY" ] || refuse FEED_KEY_CLASH "в $APK_USIGN_KEYS уже лежит другой ключ с номером $FEED_KEY_ID." else printf 'untrusted comment: VCTL feed\n%s\n' "$FEED_KEY" > "$APK_USIGN_KEYS/$FEED_KEY_ID" USIGN_ADDED=1 fi line="@$APK_TAG $FEED_URL/apk/$ARCH/packages.adb" if [ "$(cat "$APK_REPO_LIST" 2> /dev/null)" != "$line" ]; then # Another feed's line (another channel, an older installer) is kept to # put back: a run that installs nothing must not leave a world that # names @vectra without its repository — apk then refuses everything. [ -f "$APK_REPO_LIST" ] && cp "$APK_REPO_LIST" "$WORK/vectra-pro.list.orig" echo "$line" > "$APK_REPO_LIST" FEED_ADDED=1 fi apk_fetch_index || refuse FEED_UNREACHABLE "фид VCTL недоступен ($FEED_URL). Проверьте интернет и DNS роутера: nslookup ${FEED_URL#*://}" mkdir -p "$WORK/apk-keys" cp "$APK_KEY_FILE" "$WORK/apk-keys/" run apk --keys-dir "$WORK/apk-keys" verify "$APK_INDEX" || refuse FEED_UNVERIFIED "индекс фида VCTL не прошёл проверку подписи ключом VCTL (apk verify, см. лог)." note "apk update (до минуты)" OPENWRT_NEED="dnsmasq-full kmod-nft-tproxy kmod-nft-socket kmod-nft-nat" [ "$LUCI" = 1 ] && OPENWRT_NEED="$OPENWRT_NEED luci" RT_UNTIL=feeds_ready retry apk update RT_UNTIL="" select_pkg_family available "$PKG" || refuse FEED_UNVERIFIED "фид VCTL не прошёл проверку подписи или пуст (apk update, см. лог)." ok "фид VCTL $FEED_URL/apk/$ARCH (@$APK_TAG), подпись ключом VCTL" # shellcheck disable=SC2086 # a list of packages if ! have_all $OPENWRT_NEED; then [ -n "$(openwrt_feeds_down)" ] || openwrt_missing use_openwrt_mirror || { [ -n "$(openwrt_feeds_down)" ] || openwrt_missing; refuse OPENWRT_FEEDS_UNREACHABLE "фиды OpenWrt недоступны (не скачались:$(openwrt_feeds_down)) и прокси VCTL тоже. Проверьте DNS и IPv6 на WAN."; } fi ok "фиды OpenWrt" } # apk_fetch_index: the feed's packages.adb, as apk will read it, into $WORK. apk_fetch_index() { APK_INDEX="$WORK/vectra-packages.adb" retry fetch "$FEED_URL/apk/$ARCH/packages.adb" "$APK_INDEX" && [ -s "$APK_INDEX" ] } add_feed() { step "Фиды" if [ "$PM" = apk ]; then [ -n "$FEED_URL" ] && [ -n "$APK_KEY" ] && [ -n "$FEED_KEY" ] && [ -n "$FEED_KEY_ID" ] || refuse NO_FEED_KEY "этот файл — шаблон без ключа фида. Скачайте установщик: wget -qO- $INSTALL_URL | sh (роутер BloopCat: ... | sh -s -- --brand bloopcat; роутер без бренда: --brand none)" add_feed_apk return fi [ -n "$FEED_URL" ] && [ -n "$FEED_KEY" ] && [ -n "$FEED_KEY_ID" ] || refuse NO_FEED_KEY "этот файл — шаблон без ключа фида. Скачайте установщик: wget -qO- $INSTALL_URL | sh (роутер BloopCat: ... | sh -s -- --brand bloopcat; роутер без бренда: --brand none)" mkdir -p "$KEYS" "$WORK" if [ -f "$KEYS/$FEED_KEY_ID" ]; then [ "$(sed -n 2p "$KEYS/$FEED_KEY_ID")" = "$FEED_KEY" ] || refuse FEED_KEY_CLASH "в $KEYS уже лежит другой ключ с номером $FEED_KEY_ID." else printf 'untrusted comment: VCTL feed\n%s\n' "$FEED_KEY" > "$KEYS/$FEED_KEY_ID" KEY_ADDED=1 fi line="src/gz $FEED_NAME $FEED_URL/$ARCH" touch "$CUSTOMFEEDS" if ! grep -qx "$line" "$CUSTOMFEEDS"; then remove_feed echo "$line" >> "$CUSTOMFEEDS" FEED_ADDED=1 fi retry fetch "$FEED_URL/$ARCH/Packages.sig" "$WORK/Packages.sig" || refuse FEED_UNREACHABLE "фид VCTL недоступен ($FEED_URL). Проверьте интернет и DNS роутера: nslookup ${FEED_URL#*://}" note "opkg update (до минуты)" # What this run takes from OpenWrt's feeds. OPENWRT_NEED="dnsmasq-full kmod-nft-tproxy kmod-nft-socket kmod-nft-nat" [ "$LUCI" = 1 ] && OPENWRT_NEED="$OPENWRT_NEED luci" RT_UNTIL=feeds_ready retry opkg update RT_UNTIL="" # Vectra's feed must be there, and verified: opkg drops a list whose # signature does not check out. select_pkg_family available "$PKG" || refuse FEED_UNVERIFIED "фид VCTL не прошёл проверку подписи или пуст (opkg update, см. лог)." ok "фид VCTL $FEED_URL/$ARCH, подпись ключом $FEED_KEY_ID" # shellcheck disable=SC2086 # a list of packages if ! have_all $OPENWRT_NEED; then # Every OpenWrt feed answered and a package is still missing: the # mirror would not have it either. [ -n "$(openwrt_feeds_down)" ] || openwrt_missing use_openwrt_mirror || { [ -n "$(openwrt_feeds_down)" ] || openwrt_missing; refuse OPENWRT_FEEDS_UNREACHABLE "фиды OpenWrt недоступны (не скачались списки:$(openwrt_feeds_down)) и прокси VCTL тоже. Проверьте DNS и IPv6 на WAN."; } fi ok "фиды OpenWrt" } # openwrt_mirror: OpenWrt's feeds through Vectra's caching proxy — the one # given (OPENWRT_MIRROR), else /openwrt-cache on the Vectra feed's host. openwrt_mirror() { if [ -n "$OPENWRT_MIRROR" ]; then echo "$OPENWRT_MIRROR" else echo "$(echo "$FEED_URL" | sed -n 's#^\(https\{0,1\}://[^/]*\)/.*#\1#p')/openwrt-cache" fi } use_openwrt_mirror() { [ -f "$DISTFEEDS" ] && grep -q 'downloads.openwrt.org' "$DISTFEEDS" || return 1 mirror="$(openwrt_mirror)" note "downloads.openwrt.org недоступен; беру фиды OpenWrt через $mirror" cp "$DISTFEEDS" "$WORK/distfeeds.conf.orig" || return 1 DISTFEEDS_SWAPPED=1 sed -e "s#https\{0,1\}://downloads.openwrt.org#$mirror#g" "$WORK/distfeeds.conf.orig" > "$DISTFEEDS" || return 1 RT_UNTIL=openwrt_ready retry "$PM" update RT_UNTIL="" openwrt_ready } # After an opkg update that failed: is what this run needs there? Vectra's # feed, and OpenWrt's either whole or not there at all — none of it is what a # router that cannot reach downloads.openwrt.org sees, and the mirror is the # next step for that, not a wait (a Cudy behind a broken IPv6). # shellcheck disable=SC2086 # a list of packages openwrt_ready() { have_all $OPENWRT_NEED; } # The OpenWrt feeds (distfeeds.conf) whose list opkg update did not get. openwrt_feeds_down() { if [ "$PM" = apk ]; then # apk says which repository it could not update: "WARNING: updating # and opening : " — of this run's last apk update. [ -f "$DISTFEEDS" ] || return 0 last="$(awk '/^\$ apk update/ { n = NR } END { print n + 0 }' "$LOG" 2> /dev/null)" for u in $(grep -v '^#' "$DISTFEEDS" | awk 'NF { print $NF }'); do tail -n "+${last:-1}" "$LOG" 2> /dev/null | grep -F "$u" | grep -q -e 'WARNING: updating' -e 'ERROR' && printf ' %s' "$u" done return 0 fi [ -f "$DISTFEEDS" ] || return 0 for fd in $(awk '($1 == "src/gz" || $1 == "src") { print $2 }' "$DISTFEEDS"); do [ -s "$LISTS/$fd" ] || printf ' %s' "$fd" done } # openwrt_missing: OpenWrt's feeds answered, and what this run needs is not in # them — a kmod built for another kernel (a firmware built by hand, a # snapshot), not an outage. # shellcheck disable=SC2086 # a list of packages openwrt_missing() { om="" for p in $OPENWRT_NEED; do installed "$p" || available "$p" || om="$om $p"; done refuse OPENWRT_PACKAGE_MISSING "в фидах OpenWrt нет нужных VCTL пакетов:$om. Фиды ответили — пакетов в них нет; обычно это модули ядра (kmod) для прошивки, собранной не официально, или снапшота. Нужна официальная прошивка OpenWrt 23.05, 24.10 или 25.12." } feeds_ready() { have_all "$PKG" || have_all vctl || return 1 have_all dnsmasq-full || return 0 openwrt_ready } # ------------------------------------------------------------------ plan ---- # One xray per vctl: the xray-core of Vectra's own feed, the one this vctl # depends on and is proven with (build-pro-feed.sh ships the version # openwrt/Makefile names; the feed's xray-core is that version, and # XRAY_MIN, baked from the feed, too). After the install the router's xray is # that package and that package's binary — never another feed's xray-core, # which opkg would take for the Depends when it is newer, nor a binary swapped # in by hand over opkg's record (the four vctl routers ran 26.10.17 over # xray-core 26.7.28-r1 from 2026-10-21). So the file from Vectra's list goes # in by itself first (install_xray_pin): over an older package as an # upgrade, over the same version with another binary as a reinstall, over a # newer one as a downgrade; then vctl's Depends is met and opkg pulls no # other xray. # # PassWall2 shares /usr/bin/xray. Before 26.9.9-2 it writes outbound # proxySettings (and repeats ruleTags), which xray refuses since 26.9.8: on # such an xray PassWall2 carries nothing. So, with such a PassWall2: # - --standby (PassWall2 keeps the router) is refused, and nothing changes: # update PassWall2 to 26.9.9-2 or newer first, or let Vectra take over; # - a takeover goes on, and says that a way back to PassWall2 (vectra off) # leaves the router's internet without VPN — the init script then keeps # PassWall2 switched off rather than start it on an xray it breaks on — # until PassWall2 is updated. PASSWALL_XRAY_OK=26.9.9-2 XRAY_REFUSES_PROXYSETTINGS=26.9.8 XRAY_PIN="" XRAY_PIN_HOW="" XRAY_REPLACED="" # A router with no xray at all before Vectra: the xray-core it puts in is # Vectra's to take away again (--uninstall), and this file says so. (Installed # from a file, it is no dependency opkg's --autoremove takes.) XRAY_FRESH="" XRAY_RECORD="${VECTRA_XRAY_RECORD:-/etc/vectra-controller-pro/.xray-core-by-vectra}" # Under /usr/lib, not /etc: keep.d carries /etc/vectra-controller-pro over a # sysupgrade, whose image has no kmod-tcp-bbr, and a record that outlived its # package would read as the owner's removal for good. BBR_RECORD_LEGACY is # where r41-r44 kept it (cmd/vctl/tune_bbr.go: bbrRecord, bbrRecordLegacy). BBR_RECORD="${VECTRA_BBR_RECORD:-/usr/lib/vectra-controller-pro/kmod-tcp-bbr-by-vectra}" BBR_RECORD_LEGACY="${VECTRA_BBR_RECORD_LEGACY:-/etc/vectra-controller-pro/.kmod-tcp-bbr-by-vectra}" # The owner's removal, made durable: written where a record meets no package, # and in /etc/vectra-controller-pro, which keep.d carries over a sysupgrade. BBR_OPTOUT="${VECTRA_BBR_OPTOUT:-/etc/vectra-controller-pro/.kmod-tcp-bbr-removed-by-owner}" # The packet desync's two packages (add_desync; cmd/vctl/desync_install.go has # the same names): what Vectra put there, a package a line, and the owner's # removal made durable — as BBR_RECORD and BBR_OPTOUT, and for their reasons. DESYNC_RECORD="${VECTRA_DESYNC_RECORD:-/usr/lib/vectra-controller-pro/desync-by-vectra}" DESYNC_OPTOUT="${VECTRA_DESYNC_OPTOUT:-/etc/vectra-controller-pro/.desync-removed-by-owner}" DESYNC_BIN="${VECTRA_DESYNC_BIN:-/usr/bin/vctl-nfqws}" DESYNC_SYS_MODULE="${VECTRA_DESYNC_SYS_MODULE:-/sys/module}" DESYNC_MODULES="${VECTRA_DESYNC_MODULES:-/lib/modules}" # The owner's DPI tools no package lists (zapret is mostly installed by its # own script), and the ones that run. DESYNC_OWN_PATHS="${VECTRA_DESYNC_OWN_PATHS:-/opt/zapret /etc/init.d/zapret /etc/init.d/zapret2 /etc/init.d/youtubeUnblock /etc/init.d/byedpi}" DESYNC_OWN_COMMS="nfqws nfqws2 youtubeUnblock ciadpi byedpi tpws" # What the overlay must have free: vctl's own update floor (jobsafety's # ControllerUpdateOverlayFloorMB, 4 MiB) plus what the two packages write # (desyncWriteKB) — an optional package never takes the next update's room. DESYNC_FLOOR_KB=4608 # The owner's own sysctl files, where vctl's tune reads them (tune.userSysctl). SYSCTL_FILES="${VECTRA_SYSCTL_FILES:-/etc/sysctl.d/*.conf /etc/sysctl.conf}" TCP_CC_AVAILABLE="${VECTRA_TCP_CC_AVAILABLE:-/proc/sys/net/ipv4/tcp_available_congestion_control}" # check_passwall_xray : in check_conflicts, before # a takeover is asked for. check_passwall_xray() { [ -n "$1" ] || return 0 pw="$(installed_version luci-app-passwall2)" [ -n "$pw" ] || return 0 version_ge "$1" "$XRAY_REFUSES_PROXYSETTINGS" || return 0 version_ge "$pw" "$PASSWALL_XRAY_OK" && return 0 why="PassWall2 $pw пишет в конфиг xray поле proxySettings, а xray $1, под который собрана эта VCTL, с 26.9.8 такой конфиг не запускает. xray на роутере один для обоих (/usr/bin/xray)" if [ "$STANDBY" = 1 ]; then if installed vectra-controller-agent; then refuse PASSWALL_TOO_OLD_FOR_XRAY "$why: с --standby PassWall2 остался бы вести трафик на xray, на котором он не работает. Сначала обновите PassWall2 до $PASSWALL_XRAY_OK или новее (на роутере с прежним агентом VCTL ставится только с --standby), потом запустите установщик снова." fi refuse PASSWALL_TOO_OLD_FOR_XRAY "$why: с --standby PassWall2 остался бы вести трафик на xray, на котором он не работает. Обновите PassWall2 до $PASSWALL_XRAY_OK или новее и запустите установщик снова — или ставьте без --standby, тогда VCTL заберёт трафик себе." fi warn PASSWALL_HANDBACK_WITHOUT_VPN "$why. VCTL заберёт трафик; vectra off вернёт роутеру интернет без VPN (PassWall2 останется выключенным), пока PassWall2 не обновлён до $PASSWALL_XRAY_OK или новее." } # apk_world_tagged : the world asks for from the @vectra repository. apk_world_tagged() { grep -q -e "^$1@$APK_TAG\$" -e "^$1@${APK_TAG}[<>=~]" "$APK_WORLD" 2> /dev/null; } plan_xray() { step "xray" fv="$(feed_field xray-core Version)" [ -n "$fv" ] || refuse XRAY_NOT_IN_FEED "в фиде VCTL нет xray-core: этой версии VCTL нужен xray $XRAY_MIN из её фида." fbase="$(echo "$fv" | sed 's/-r\{0,1\}[0-9]*$//')" [ -z "$XRAY_MIN" ] || [ "$fbase" = "$XRAY_MIN" ] || refuse XRAY_FEED_MISMATCH "в фиде VCTL xray-core $fv, а эта версия VCTL собрана под xray $XRAY_MIN: фид и установщик из разных выпусков." xb="$(command -v xray 2> /dev/null)" pv="$(installed_version xray-core)" xv="$(xray_version)" # apk: the same version from OpenWrt's feeds is not Vectra's (another # build): Vectra's is the one the world asks for from @vectra. if [ "$pv" = "$fv" ] && [ "$xv" = "$fbase" ] && { [ "$PM" != apk ] || apk_world_tagged xray-core; }; then ok "xray $xv — пакет xray-core $pv из фида VCTL" jcheck ok XRAY_VECTRA "$fv" return 0 fi if [ "$PM" = apk ]; then # apk installs it from the tagged repository, checked against the # signed index: nothing to download and check here. XRAY_PIN="$APK_TAG $fv" if [ -z "$pv" ]; then XRAY_PIN_HOW=install [ -n "$xb" ] || XRAY_FRESH=1 ok "${xb:+xray $xv без пакета: }встанет xray-core $fv из фида VCTL" elif [ "$pv" = "$fv" ]; then XRAY_PIN_HOW=reinstall ok "xray-core $pv${xv:+ (xray $xv)} не из фида VCTL или заменён вручную: встанет xray-core $fv из фида VCTL" elif version_ge "$pv" "$fv"; then XRAY_PIN_HOW=downgrade ok "xray-core $pv новее того, под который собрана VCTL: встанет $fv из её фида" else XRAY_PIN_HOW=install ok "xray-core $pv${xv:+ (xray $xv)} -> $fv из фида VCTL" fi jcheck ok XRAY_PIN "$fv $XRAY_PIN_HOW" return 0 fi XRAY_PIN="$(pkg_candidates xray-core | awk -v f="$FEED_NAME" -v v="$fv" '$1 == f && $2 == v { print; exit }')" [ -n "$XRAY_PIN" ] || refuse XRAY_NOT_IN_FEED "в списке фида VCTL нет файла xray-core $fv." # shellcheck disable=SC2086 # the plan's fields set -- $XRAY_PIN # Only what its feed's signed list vouches for: a list with no SHA256sum # for it leaves nothing to check the download against. [ -n "${4:-}" ] || refuse XRAY_PIN_CHECKSUM "в списке фида VCTL нет SHA256 для xray-core $2: установщик не ставит то, что нечем проверить; xray не тронут." if [ -z "$pv" ]; then XRAY_PIN_HOW=install [ -n "$xb" ] || XRAY_FRESH=1 ok "${xb:+xray $xv без пакета: }встанет xray-core $fv из фида VCTL" elif [ "$pv" = "$fv" ]; then XRAY_PIN_HOW=reinstall ok "xray ${xv:-не запускается} поверх пакета xray-core $pv (заменён вручную): пакет встанет заново, xray станет его" elif version_ge "$pv" "$fv"; then XRAY_PIN_HOW=downgrade ok "xray-core $pv новее того, под который собрана VCTL: встанет $fv из её фида" else XRAY_PIN_HOW=install ok "xray-core $pv${xv:+ (xray $xv)} -> $fv из фида VCTL" fi jcheck ok XRAY_PIN "$fv $XRAY_PIN_HOW" } check_storage() { step "Место" need=0 # Vectra's own packages by what they state, the rest estimated. On flash # that compresses, by their Size × 1.4, as xray below: vctl's 11.3 MB # Installed-Size is a 4.7 MB package, and the Installed-Size sum (18 MB # with the margin 22) refused units whose 44 MB rootfs_data holds 10-14 MB # free beside PassWall2, where the three take about 10 MB. Never below the # largest Installed-Size of them, though: opkg checks each package against # the room left before it unpacks it, and vctl's own check comes first. # xray-core whenever plan_xray puts it in, beside the old binary: the # xray that runs holds that one until it restarts, so it frees nothing. # On flash that compresses (UBIFS, JFFS2) the new one takes about the # package's own Size — on an AX3000T's UBIFS the 13.3 MB package took # 14.1 MB, and the install's low point was 18.5 MB down — so 1.4 × Size; # its Installed-Size elsewhere. (opkg's own check counts the whole # Installed-Size: install_xray_pin gives it --force-space.) It goes in # first; when the old one is let go before the rest (xray_released), the # room is the larger of the two steps, else their sum. xray_kb=0 biggest=0 for p in $PKG xray-core $GEO_PKG $REP_PKG; do v="$(feed_field "$p" Version)" iv="$(installed_version "$p")" if [ "$p" = xray-core ]; then [ -n "$XRAY_PIN" ] || continue if store_compresses && s="$(feed_field xray-core Size)" && [ -n "$s" ]; then xray_kb=$((s * 14 / 10 / 1024)) else s="$(feed_field xray-core Installed-Size)" xray_kb=$((${s:-0} / 1024)) fi continue elif [ -n "$iv" ] && version_ge "$iv" "$v"; then continue fi s="$(feed_field "$p" Installed-Size)" [ $((${s:-0} / 1024)) -gt "$biggest" ] && biggest=$((${s:-0} / 1024)) if store_compresses && z="$(feed_field "$p" Size)" && [ -n "$z" ]; then need=$((need + z * 14 / 10 / 1024)) else need=$((need + ${s:-0} / 1024)) fi done [ "$biggest" -gt "$need" ] && need="$biggest" for p in dnsmasq-full kmod-nft-tproxy kmod-nft-socket kmod-nft-nat rpcd-mod-iwinfo procd-ujail jsonfilter jshn ca-bundle luci-base; do installed "$p" && continue s="$(field "$p" Size)" need=$((need + ${s:-0} * UNPACK_FACTOR / 1024)) done [ "$LUCI" = 1 ] && need=$((need + 2048)) if xray_released; then [ "$xray_kb" -gt "$need" ] && need="$xray_kb" else need=$((need + xray_kb)) fi have="$(free_kb "$STORE")" if [ "${have:-0}" -lt $((need + MARGIN_KB)) ]; then refuse STORAGE_TOO_SMALL "на $STORE свободно $((${have:-0} / 1024)) МБ, нужно около $(((need + MARGIN_KB) / 1024)) МБ (xray — самый большой пакет, около 30 МБ)." fi ok "нужно около $((need / 1024)) МБ, свободно $((have / 1024)) МБ на $STORE" jcheck ok STORAGE "need_mb=$((need / 1024)) free_mb=$((have / 1024))" after=$((have - need)) if [ "$after" -lt "$UPDATE_FLOOR_KB" ]; then warn OVERLAY_AFTER_BELOW_UPDATE_FLOOR "после установки на $STORE останется около $((after / 1024)) МБ — меньше $((UPDATE_FLOOR_KB / 1024)) МБ, которых требует обновление VCTL: «Обновить» будет отказывать, пока место не освободится (например, когда VCTL удалит PassWall2 — через сутки после включения)" fi } # --------------------------------------------------------------- install ---- # fetch_xray_pin downloads Vectra's xray-core as plan_xray chose, checked # against its feed's list, before anything changes: a download that fails # changes nothing. install_xray_pin puts it in later, just before vctl — # after the dnsmasq swap, so a takeover that stops on the way leaves the xray # a PassWall2 runs as it was. XRAY_FILE="" fetch_xray_pin() { [ -n "$XRAY_PIN" ] || return 0 [ "$PM" = apk ] && return 0 # shellcheck disable=SC2086 # the plan's fields set -- $XRAY_PIN base="$(feed_url "$1")" [ -n "$base" ] || refuse XRAY_PIN_DOWNLOAD "не найден адрес фида $1, где лежит xray-core $2." rm -rf "$WORK/xray" mkdir -p "$WORK/xray" f="$WORK/xray/${3##*/}" retry fetch "$base/$3" "$f" || refuse XRAY_PIN_DOWNLOAD "не удалось скачать xray-core $2 ($base/$3)." if [ "$(sha256sum "$f" 2> /dev/null | awk '{ print $1 }')" != "$4" ]; then refuse XRAY_PIN_CHECKSUM "xray-core $2 скачался не тот: sha256 не совпадает со списком фида $1." fi XRAY_FILE="$f" } # Free page cache before heavy package unpacks on low-RAM routers (< 80 MB). reclaim_low_ram() { if [ -r /proc/meminfo ] && [ -w /proc/sys/vm/drop_caches ]; then _avail="$(awk '/^MemAvailable:/ { print $2; exit }' /proc/meminfo 2> /dev/null || echo 0)" case "$_avail" in ''|*[!0-9]*) _avail=0 ;; esac if [ "$_avail" -gt 0 ] && [ "$_avail" -lt 81920 ]; then sync echo 3 > /proc/sys/vm/drop_caches 2> /dev/null || true fi fi } # install_xray_pin installs it, by itself, before vctl: its --force-reinstall # (or --force-downgrade) is never vctl's — opkg's reinstall removes the # installed package first, and vctl's removal hands the router back. And it # removes xray-core before it unpacks the new one: one that fails after that # leaves no xray, so a plain install puts it back. install_xray_pin() { [ -n "$XRAY_FILE" ] || [ "$PM" = apk ] || return 0 [ -n "$XRAY_PIN" ] || return 0 # shellcheck disable=SC2086 # the plan's fields set -- $XRAY_PIN step "xray-core $2 из фида VCTL" INSTALLED_SOMETHING=1 if [ "$PM" = apk ]; then # From @vectra: over another build of the same version as a replacement, # over a newer one as a downgrade — the world allows no other. Over its # own package with a binary swapped by hand: reinstalled (apk fix). if [ "$XRAY_PIN_HOW" = reinstall ] && apk_world_tagged xray-core; then retry apk fix --reinstall xray-core else retry apk add "xray-core@$APK_TAG" fi || fail XRAY_PIN_INSTALL "apk add xray-core@$APK_TAG не прошёл (см. лог); на роутере xray-core ${pv:-не установлен}$(installed xray-core && echo " $(installed_version xray-core)"). VCTL не установлена." XRAY_FILE=apk fi how="" case "$XRAY_PIN_HOW" in reinstall) how=--force-reinstall ;; downgrade) how=--force-downgrade ;; esac # --force-space: opkg counts xray-core's whole Installed-Size, whatever # the flash compresses; check_storage measured the room it needs. reclaim_low_ram # shellcheck disable=SC2086 # no flag, or one if [ "$PM" = apk ]; then : elif ! retry opkg install --force-space $how "$XRAY_FILE"; then [ -n "$how" ] && ! installed xray-core && run opkg install --force-space "$XRAY_FILE" installed xray-core || fail XRAY_PIN_INSTALL "opkg install xray-core $2 не прошёл, и xray-core на роутере нет (см. лог). VCTL не установлена; запустите установщик снова — он поставит xray-core из своего фида." [ "$(installed_version xray-core)" = "$2" ] || fail XRAY_PIN_INSTALL "opkg install xray-core $2 не прошёл (см. лог); на роутере остался xray-core $(installed_version xray-core). VCTL не установлена." fi # Free the ~12 MB xray-core .ipk from tmpfs immediately before opkg stages vctl. rm -rf "$WORK/xray" XRAY_FILE="" reclaim_low_ram xv="$(xray_version)" # apk: OpenWrt's xray-core of the same version reads the same: Vectra's is # the one the world asks for from @vectra. [ "$PM" != apk ] || apk_world_tagged xray-core || fail XRAY_PIN_INSTALL "после apk add xray-core не из фида VCTL (в world нет xray-core@$APK_TAG, см. лог). VCTL не установлена." [ "$(installed_version xray-core)" = "$2" ] && [ "$xv" = "$(echo "$2" | sed 's/-r\{0,1\}[0-9]*$//')" ] || fail XRAY_PIN_INSTALL "после $PM install на роутере xray-core $(installed_version xray-core), xray ${xv:-не запускается}, а не $2 из фида VCTL (см. лог). VCTL не установлена." XRAY_REPLACED=1 [ -z "$XRAY_FRESH" ] || { mkdir -p "${XRAY_RECORD%/*}" && true > "$XRAY_RECORD"; } 2> /dev/null ok "xray $xv — пакет xray-core $2 из фида VCTL" } # The swap of dnsmasq for dnsmasq-full, and its way back, which needs no # network. Before anything is removed, the dnsmasq that runs now is kept twice: # - its package, with everything it depends on already on the router, so opkg # can put it back; # - its files as they are on the router, with opkg's record of them, put back # by hand when opkg cannot. # It goes on flash when there is room, so the way back survives a reboot. # "Works" is checked, not assumed. Each start is of the system dnsmasq only, # afresh, with no leftover of it holding port 53, and it must answer # (DNS_CHECK). Otherwise the way back is taken and checked the same way. From # the moment the old dnsmasq stops to a dnsmasq that answers, everything # shares one deadline (DNS_DEADLINE): one try per stage, each with its share. swap_dnsmasq() { installed dnsmasq-full && { ok "dnsmasq-full уже стоит"; return 0; } OLD="$DNSMASQ_PKG" [ -n "$OLD" ] || fail DNSMASQ_ABSENT "не найден пакет dnsmasq, который нужно заменить (проверка не выполнялась). dnsmasq не тронут." step "$OLD -> dnsmasq-full" if [ "$PM" = apk ]; then swap_dnsmasq_apk return fi rm -rf "$WORK/pkgs" mkdir -p "$WORK/pkgs" # Its libraries first: they do not clash with dnsmasq. for d in $(depends_of "$(field dnsmasq-full Depends)"); do installed "$d" || retry opkg install "$d" || fail DNSMASQ_DEPENDENCY "не удалось поставить $d (зависимость dnsmasq-full). $OLD не тронут." done INSTALLED_SOMETHING=1 download dnsmasq-full || fail DNSMASQ_DOWNLOAD "не удалось скачать dnsmasq-full. $OLD не тронут." full="" for f in "$WORK"/pkgs/dnsmasq-full_*.ipk; do [ -f "$f" ] && full="$f"; done [ -n "$full" ] || fail DNSMASQ_DOWNLOAD "dnsmasq-full не скачался. $OLD не тронут." download "$OLD" || fail DNSMASQ_DOWNLOAD "не удалось скачать $OLD (для отката). $OLD не тронут." old="" for f in "$WORK/pkgs/${OLD}"_*.ipk; do [ -f "$f" ] && old="$f"; done [ -n "$old" ] || fail DNSMASQ_DOWNLOAD "$OLD (для отката) не скачался. $OLD не тронут." # Putting it back must not need the network: what it depends on is on # the router before anything is removed. A package whose control cannot # be read (or names no dependency: dnsmasq needs at least libc) is not # one to count on. deps="$(ipk_field "$old" Depends)" [ -n "$deps" ] || fail DNSMASQ_DOWNLOAD "скачанный $OLD (для отката) не читается или пуст (нет Depends): откат на него не гарантирован. $OLD не тронут." for d in $(depends_of "$deps"); do installed "$d" || retry opkg install "$d" || fail DNSMASQ_DEPENDENCY "не удалось поставить $d (зависимость $OLD, для отката). $OLD не тронут." done [ "$(ipk_field "$old" Version)" = "$(installed_version "$OLD")" ] || printf '# the feed has %s %s, the router %s: the way back puts the feed'"'"'s back first, the router'"'"'s files if that fails\n' "$OLD" "$(ipk_field "$old" Version)" "$(installed_version "$OLD")" >> "$LOG" save_dnsmasq "$old" || fail DNSMASQ_DOWNLOAD "не удалось сохранить прежний $OLD для отката (место в /tmp?). $OLD не тронут." old="$SAVED/${old##*/}" note "прежний $OLD $(installed_version "$OLD") сохранён для отката: $SAVED" [ -f /etc/config/dhcp ] && cp /etc/config/dhcp "$WORK/dhcp.before" # What "works" means here is what worked before: a dnsmasq that answered # must answer again; one that only hands out addresses (another DNS server # on the router) must run again. DNS_CHECK=dnsmasq_runs dns_answers && DNS_CHECK=dns_answers DNS_T0="$(date +%s)" if ! run opkg remove "$OLD"; then installed "$OLD" && dnsmasq_up 1 3 20 && fail DNSMASQ_REMOVE "opkg remove $OLD не прошёл; $OLD работает как прежде." dnsmasq_back fi if run opkg install "$full" && restore_dhcp && dnsmasq_up 1 3 20; then ok "dnsmasq-full $(installed_version dnsmasq-full): DHCP и DNS работают (без DNS $(($(date +%s) - DNS_T0)) с)" return 0 fi say " ! dnsmasq-full не поднялся; возвращаю прежний $OLD" dnsmasq_back } # swap_dnsmasq_apk: the same swap with apk. dnsmasq-full provides dnsmasq, # and one `apk add dnsmasq-full` purges the old one and installs it in a single # commit; --cache-predownload has every package downloaded before that commit # starts, so a download that fails leaves the old dnsmasq as it was. The way # back is the old package's file (apk fetch, from the signed index), kept as # the opkg path keeps it, and installed again with no network. swap_dnsmasq_apk() { rm -rf "$WORK/pkgs" "$WORK/apk-cache" mkdir -p "$WORK/pkgs" "$WORK/apk-cache" INSTALLED_SOMETHING=1 # The installed version where the feeds still have it, else their newest. download "$OLD=$(installed_version "$OLD")" || download "$OLD" || fail DNSMASQ_DOWNLOAD "не удалось скачать $OLD (для отката). $OLD не тронут." old="" for f in "$WORK/pkgs/${OLD}"-[0-9]*.apk; do [ -f "$f" ] && old="$f"; done [ -n "$old" ] || fail DNSMASQ_DOWNLOAD "$OLD (для отката) не скачался. $OLD не тронут." save_dnsmasq "$old" || fail DNSMASQ_DOWNLOAD "не удалось сохранить прежний $OLD для отката (место в /tmp?). $OLD не тронут." old="$SAVED/${old##*/}" sv="${old##*/$OLD-}" note "прежний $OLD (установлен $(installed_version "$OLD"), для отката сохранён ${sv%.apk}): $SAVED" [ -f /etc/config/dhcp ] && cp /etc/config/dhcp "$WORK/dhcp.before" DNS_CHECK=dnsmasq_runs dns_answers && DNS_CHECK=dns_answers DNS_T0="$(date +%s)" if retry apk --cache-dir "$WORK/apk-cache" add --cache-predownload dnsmasq-full; then rm -rf "$WORK/apk-cache" if restore_dhcp && dnsmasq_up 1 3 20; then ok "dnsmasq-full $(installed_version dnsmasq-full): DHCP и DNS работают (без DNS $(($(date +%s) - DNS_T0)) с)" return 0 fi else rm -rf "$WORK/apk-cache" # Nothing committed: the old dnsmasq never stopped. installed "$OLD" && ! installed dnsmasq-full && fail DNSMASQ_DOWNLOAD "не удалось поставить dnsmasq-full (apk add, см. лог). $OLD не тронут." fi say " ! dnsmasq-full не поднялся; возвращаю прежний $OLD" dnsmasq_back } # dnsmasq_back: the way back, and the end of the run. Said loudly when even it # leaves the router without the dnsmasq it had. dnsmasq_back() { if rollback_dnsmasq; then fail DNSMASQ_FULL_ROLLED_BACK "dnsmasq-full не заработал; прежний $OLD возвращён и работает (без DNS было $(($(date +%s) - DNS_T0)) с). VCTL не установлена." fi DNSMASQ_KEEP=1 back="opkg install --force-reinstall $old" [ "$PM" = apk ] && back="apk add --allow-untrusted $old" where="$SAVED" case "$SAVED" in /tmp/*) where="$SAVED — в памяти: после перезагрузки его не будет, сохраните заранее" ;; esac if dnsmasq_rescue; then fail DNSMASQ_FULL_BROKEN "dnsmasq-full не заработал, и прежний $OLD не запускается как служба. Запущен временный dnsmasq: DHCP и DNS работают, но только до перезагрузки роутера. Подключитесь кабелем и выполните: kill \$(cat /var/run/dnsmasq-rescue.pid); $back && /etc/init.d/dnsmasq enable && /etc/init.d/dnsmasq restart (пакет и файлы прежнего dnsmasq: $where)" fi fail DNSMASQ_FULL_BROKEN "dnsmasq-full не заработал, и прежний $OLD не вернулся: у устройств в сети может не быть DHCP/DNS. Подключитесь кабелем и выполните: $back && /etc/init.d/dnsmasq enable && /etc/init.d/dnsmasq restart (пакет и файлы прежнего dnsmasq: $where)" } # rollback_dnsmasq: dnsmasq-full gone, and the dnsmasq that was there back and # answering, from its package or else from its files. No network. It starts # again what it stops: the old dnsmasq is always there to put back (the # checks refused a router without one). rollback_dnsmasq() { dnsmasq_stop if [ "$PM" = apk ]; then # dnsmasq-full out of the world by hand (`apk del` would have apk fetch # a dnsmasq for the "dnsmasq" the world still asks for): then the old # file replaces it in one commit, with no network. The world names the # file by its hash after that; it is "dnsmasq" again. if [ -f "$APK_WORLD" ]; then grep -v -x 'dnsmasq-full' "$APK_WORLD" > "$WORK/world" && cat "$WORK/world" > "$APK_WORLD" fi if run apk add --allow-untrusted "$old"; then sed -i 's/^dnsmasq><.*$/dnsmasq/' "$APK_WORLD" 2> /dev/null restore_dhcp && dnsmasq_up 2 3 20 && return 0 fi return 1 fi installed dnsmasq-full && { run opkg remove dnsmasq-full || run opkg remove --force-depends dnsmasq-full; } run opkg install "$old" && restore_dhcp && dnsmasq_up 2 3 20 && return 0 say " ! opkg не вернул прежний $OLD; восстанавливаю его файлы, сохранённые до замены" restore_saved_dnsmasq && restore_dhcp && dnsmasq_up 5 6 15 } restore_dhcp() { if [ -f "$WORK/dhcp.before" ]; then cp "$WORK/dhcp.before" /etc/config/dhcp fi rm -f /etc/config/dhcp-opkg /etc/config/dhcp.apk-new return 0 } # download : opkg download into $WORK/pkgs. Run in this shell, not a # subshell, so retry's pauses count against this run's budget. Then back to # the directory it ran from ($0 may be relative to it). download() { dl_from="$(pwd)" cd "$WORK/pkgs" || return 1 if [ "$PM" = apk ]; then retry apk fetch "$1" else retry opkg download "$1" fi dl_rc=$? cd "$dl_from" || cd / return "$dl_rc" } # The dependencies of a package, by name: "a, b (>= 1)" -> a b. libc is # always there, and opkg lists it under another name on some releases. depends_of() { echo "$1" | tr ',' '\n' | sed 's/ *(.*//; s/^ *//; s/ *$//' | grep -v -e '^libc$' -e '^$'; } # A field of a downloaded package's control. ipk_field() { tar -xzOf "$1" ./control.tar.gz 2> /dev/null | tar -xzOf - ./control 2> /dev/null | sed -n "s/^$2: //p" | head -n 1; } # save_dnsmasq : the package for the way back, and the installed $OLD's # files as they are now with opkg's record of it. Built in /tmp, then moved to # flash ($SAVED_FLASH) when there is room, so it survives a reboot. save_dnsmasq() { SAVED_MADE=1 rm -rf "$SAVED_RAM" "$SAVED_FLASH" SAVED="$SAVED_RAM" if [ "$PM" = apk ]; then # The package only: apk has no record to put back by hand. mkdir -p "$SAVED" && cp "$1" "$SAVED/" || return 1 else mkdir -p "$SAVED" && [ -f "$OPKG_INFO/$OLD.list" ] && cp "$1" "$SAVED/" || return 1 { cat "$OPKG_INFO/$OLD.list" ls "$OPKG_INFO/$OLD".* } | while read -r f; do if [ -e "$f" ] || [ -L "$f" ]; then echo "${f#/}"; fi done > "$SAVED/files" grep -qx 'usr/sbin/dnsmasq' "$SAVED/files" && tar -czf "$SAVED/files.tar.gz" -C / -T "$SAVED/files" || return 1 awk -v p="$OLD" '/^Package: / { k = ($2 == p) } k' "$OPKG_STATUS" > "$SAVED/status" grep -qx "Package: $OLD" "$SAVED/status" || return 1 fi sv_kb="$(du -sk "$SAVED" | awk '{ print $1; exit }')" if mkdir -p "$SAVED_FLASH" && [ "$(free_kb "$SAVED_FLASH")" -ge $((${sv_kb:-0} + MARGIN_KB)) ] 2> /dev/null && cp -a "$SAVED/." "$SAVED_FLASH/"; then rm -rf "$SAVED" rmdir "${SAVED_RAM%/*}" 2> /dev/null SAVED="$SAVED_FLASH" else rm -rf "$SAVED_FLASH" rmdir "${SAVED_FLASH%/*}" 2> /dev/null printf '# no room on flash for the way back (%s KB): kept in RAM only\n' "$sv_kb" >> "$LOG" fi return 0 } # restore_saved_dnsmasq: what save_dnsmasq kept, back in place, under opkg's # own record of it. For when opkg cannot put the package back. restore_saved_dnsmasq() { [ -s "$SAVED/files.tar.gz" ] && [ -s "$SAVED/status" ] || return 1 dnsmasq_stop installed dnsmasq-full && run opkg remove --force-depends dnsmasq-full installed "$OLD" && run opkg remove --force-depends "$OLD" run tar -xzf "$SAVED/files.tar.gz" -C / || return 1 grep -qx "Package: $OLD" "$OPKG_STATUS" || { echo; cat "$SAVED/status"; } >> "$OPKG_STATUS" } # The system dnsmasq's processes: the instances procd runs for /etc/config/dhcp # (each reads the configuration its init script writes, -C # /var/etc/dnsmasq.conf.
; the jail wrapper around one says so too), # and the one dnsmasq_rescue starts with that file. Not PassWall2's copies, # which read their own files under /tmp/etc/passwall2. By name and command # line, not `pgrep -x dnsmasq`: BusyBox's pgrep -x matches argv[0], # "/usr/sbin/dnsmasq" as procd starts it, and finds only the jail wrapper or # an init script that happens to run. A process that has exited and is not # yet reaped does not count. dnsmasq_pids() { for p in $(pidof dnsmasq); do case "$(cut -d ' ' -f 3 "/proc/$p/stat" 2> /dev/null)" in "" | Z | X) continue ;; esac tr '\0' ' ' < "/proc/$p/cmdline" 2> /dev/null | grep -q -e ' -C /var/etc/dnsmasq\.conf\.' && echo "$p" done } dnsmasq_runs() { [ -n "$(dnsmasq_pids)" ]; } no_dnsmasq() { ! dnsmasq_runs; } # dnsmasq answers from /etc/hosts itself: no upstream (a WAN whose DNS is down) # can make this fail. An answer has a Name: line; the Server: header alone, # printed even when nothing answers, does not count. A second at most per try. dns_answers() { dnsmasq_runs || return 1 nslookup -timeout=1 -retry=1 localhost 127.0.0.1 2> /dev/null | grep -q '^Name:' } # dns_by : the time (date +%s) a stage of the swap has # until. That is its share of DNS_DEADLINE from the moment the old dnsmasq # stopped, and at least s from now (the start it waits on). dns_by() { db=$((DNS_T0 + DNS_DEADLINE * $1 / $2)) dn=$(($(date +%s) + $3)) [ "$db" -ge "$dn" ] || db="$dn" echo "$db" } # until_time