diff --git a/.gitignore b/.gitignore index 7a13053..e413e5e 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,5 @@ .DS_Store __pycache__/ +tools/core/work/ +tools/core/dist/ diff --git a/README.md b/README.md index 7d2ec0b..2a9726f 100644 --- a/README.md +++ b/README.md @@ -170,15 +170,21 @@ RU-адреса, без OpenVPN, Tailscale, торрентов и `PUSH`; сво | `ru-inside` напрямую, остальные `.ru` через RU | ✓ | ✓ | ✓ | | торренты (порты 20000–20199) | ✓ | ✓ | — | | OpenVPN | напрямую | через `OVPN-EXIT` (RU-нода) | — | -| Tailscale | напрямую | напрямую* | — | +| Tailscale | напрямую | через `MY` (свои hysteria2), без них напрямую* | — | -\* Встроенный Tailscale в mihomo v1.19.32 через прокси не работает: при `dialer-proxy` -он открывает UDP-сокет без адреса назначения, а любой прокси mihomo (socks5, hysteria2, -ss, …) сначала пытается его разрезолвить и падает — в логе -`magicsock: Rebind IPv4 failed: failed to bind any ports (tried [0])`. Переменные -`HTTPS_PROXY` встроенный Tailscale тоже не читает (в форке собран без `useproxy`). -Поэтому на белых списках Tailscale не поднимется; `TS_EXIT=1` (группа `TS-EXIT`) упирается -в ту же ошибку и оставлен на случай исправления в mihomo. +\* Встроенный Tailscale в официальном mihomo через прокси не работает: при `dialer-proxy` +он открывает UDP-сокет без адреса назначения, и любой прокси mihomo падает на его +резолве (`magicsock: Rebind IPv4 failed: failed to bind any ports`, +[MetaCubeX/mihomo#3142](https://github.com/MetaCubeX/mihomo/issues/3142)). Поэтому kit +ставит своё ядро `v1.19.32-ts1` — официальный v1.19.32 с правкой +`tools/core/tailscale-packet-listener.patch`: UDP-сокет открывается на роутере, а +control-сервер и DERP идут по TCP через `dialer-proxy`. На белых списках прямой UDP не +проходит, и Tailscale работает через DERP — медленнее прямого соединения, но работает. + +Сборка ядра: `tools/core/build.sh v1.19.32 ts1` → `tools/core/dist/*.gz` → релиз +`core-v1.19.32-ts1` в репозитории kit (`MIHOMO_VERSION` / `MIHOMO_BASE` в +`router/mihomo-kit.sh`). Если ядро не скачалось, `fix` оставляет текущее и запускает +nikki. Когда исправление появится в mihomo, вернуть официальный релиз. ## Если что-то не работает diff --git a/router/mihomo-kit.sh b/router/mihomo-kit.sh index 3e70810..9847187 100755 --- a/router/mihomo-kit.sh +++ b/router/mihomo-kit.sh @@ -36,7 +36,11 @@ TPL_DIR="${TPL_DIR:-$KIT_DIR/templates}" NIKKI_DIR="${NIKKI_DIR:-/etc/nikki}" PROFILES_D="$NIKKI_DIR/profiles.d" PROFILES_OUT="$NIKKI_DIR/profiles" -: "${MIHOMO_VERSION:=v1.19.32}" +: "${MIHOMO_VERSION:=v1.19.32-ts1}" +# where mihomo-linux--.gz is downloaded from. -ts1: own build with +# tools/core/*.patch (Tailscale through dialer-proxy, MetaCubeX/mihomo#3142) in the +# kit repo's releases; back to upstream (MetaCubeX/mihomo releases) once it is fixed there. +: "${MIHOMO_BASE:=https://git.sam-hub.net/sam/mihomo-kit/releases/download/core-$MIHOMO_VERSION}" : "${KIT_URL:=https://git.sam-hub.net/sam/mihomo-kit/archive/main.tar.gz}" log() { echo "$*" >&2; } @@ -608,12 +612,21 @@ core_update() { armv7l) arch=armv7 ;; mips) arch=mips-softfloat ;; mipsel | mipsle) arch=mipsle-softfloat ;; - *) die "unknown arch $(uname -m), set the core manually" ;; + *) + log "warning: unknown arch $(uname -m), set the core manually" + return 1 + ;; esac - url="https://github.com/MetaCubeX/mihomo/releases/download/$MIHOMO_VERSION/mihomo-linux-$arch-$MIHOMO_VERSION.gz" + url="$MIHOMO_BASE/mihomo-linux-$arch-$MIHOMO_VERSION.gz" log "updating mihomo core ${cur:-none} -> $MIHOMO_VERSION" - curl -fL -o /tmp/mihomo.gz "$url" || die "download failed: $url" - gunzip -f /tmp/mihomo.gz && chmod +x /tmp/mihomo || die "unpack failed" + # a failed download keeps the current core: fix/update still start nikki + rm -f /tmp/mihomo.gz /tmp/mihomo + if ! curl -fL -o /tmp/mihomo.gz "$url" || ! gunzip -f /tmp/mihomo.gz || ! chmod +x /tmp/mihomo || + [ "$(/tmp/mihomo -v 2>/dev/null | awk '{print $3; exit}')" != "$MIHOMO_VERSION" ]; then + rm -f /tmp/mihomo.gz /tmp/mihomo + log "warning: core $MIHOMO_VERSION not installed (download or check failed: $url), keeping ${cur:-the current one}" + return 1 + fi bin=$(command -v mihomo || echo /usr/bin/mihomo) [ -f "$bin" ] && cp "$bin" "$bin.bak" mv /tmp/mihomo "$bin" @@ -743,7 +756,7 @@ cmd_install() { cmd_fix() { /etc/init.d/nikki stop 2>/dev/null - core_update + core_update || true patch_init fix_reserved wan_metrics diff --git a/templates/proxies/20-tailscale.yaml b/templates/proxies/20-tailscale.yaml index 35ea386..a85fe83 100644 --- a/templates/proxies/20-tailscale.yaml +++ b/templates/proxies/20-tailscale.yaml @@ -9,3 +9,6 @@ udp: true accept-routes: true dialer-proxy: TS-EXIT #@ts_exit + # street: control and DERP over TCP through own servers (MY -> hysteria2 -> MY-EXIT); #@street,hy2,!ts_exit + # needs the kit's core (v1.19.32-ts1, tools/core/*.patch, MetaCubeX/mihomo#3142) #@street,hy2,!ts_exit + dialer-proxy: MY #@street,hy2,!ts_exit diff --git a/tools/core/build.sh b/tools/core/build.sh new file mode 100755 index 0000000..25bcfaf --- /dev/null +++ b/tools/core/build.sh @@ -0,0 +1,40 @@ +#!/bin/sh +# Build the mihomo core with the kit's patches (tools/core/*.patch) for the +# architectures router/mihomo-kit.sh core_update knows. Needs git and Go. +# tools/core/build.sh v1.19.32 ts1 -> dist/mihomo-linux--v1.19.32-ts1.gz +# Upload the .gz files to a release and set MIHOMO_VERSION / MIHOMO_BASE in +# router/mihomo-kit.sh. Drop this once upstream has the fixes. +set -eu +tag=${1:?usage: tools/core/build.sh } +suffix=${2:?usage: tools/core/build.sh } +version=$tag-$suffix +cd "$(dirname "$0")" +here=$(pwd) +work=$here/work +dist=$here/dist +rm -rf "$work" +mkdir -p "$work" "$dist" +git clone -q --depth 1 --branch "$tag" https://github.com/MetaCubeX/mihomo.git "$work/mihomo" +cd "$work/mihomo" +for p in "$here"/*.patch; do + git apply "$p" + echo "applied ${p##*/}" +done +buildtime=$(date -u '+%a %b %d %H:%M:%S UTC %Y') +# +for t in arm64:arm64: amd64:amd64: armv7:arm:GOARM=7 mips-softfloat:mips:GOMIPS=softfloat \ + mipsle-softfloat:mipsle:GOMIPS=softfloat; do + name=${t%%:*} + rest=${t#*:} + goarch=${rest%%:*} + extra=${rest#*:} + out=$dist/mihomo-linux-$name-$version + # same flags as the upstream Makefile + env CGO_ENABLED=0 GOOS=linux GOARCH="$goarch" $extra go build -tags with_gvisor -trimpath \ + -ldflags "-X 'github.com/metacubex/mihomo/constant.Version=$version' \ + -X 'github.com/metacubex/mihomo/constant.BuildTime=$buildtime' -w -s -buildid=" \ + -o "$out" . + gzip -9 -f "$out" + echo "built ${out##*/}.gz" +done +rm -rf "$work" diff --git a/tools/core/tailscale-packet-listener.patch b/tools/core/tailscale-packet-listener.patch new file mode 100644 index 0000000..d5dc6a0 --- /dev/null +++ b/tools/core/tailscale-packet-listener.patch @@ -0,0 +1,27 @@ +diff --git a/adapter/outbound/tailscale.go b/adapter/outbound/tailscale.go +index 2d487da..d12648f 100644 +--- a/adapter/outbound/tailscale.go ++++ b/adapter/outbound/tailscale.go +@@ -145,6 +145,13 @@ func NewTailscale(option TailscaleOption) (*Tailscale, error) { + backendInitCh: make(chan struct{}), + } + outbound.dialer = option.NewDialer(outbound.DialOptions()) ++ // mihomo-kit patch (MetaCubeX/mihomo#3142): through dialer-proxy magicsock cannot bind its ++ // UDP socket (no destination, ResolveUDP of an empty host fails). Bind it on the system dialer ++ // instead; control and DERP still go over TCP through dialer-proxy. ++ var packetDialer C.Dialer = outbound.dialer ++ if option.DialerProxy != "" { ++ packetDialer = dialer.NewDialer(outbound.DialOptions()...) ++ } + outbound.server = &tsnet.Server{ + Dir: option.StateDir, + Hostname: option.Hostname, +@@ -159,7 +166,7 @@ func NewTailscale(option TailscaleOption) (*Tailscale, error) { + }, + SystemPacketListener: func(ctx context.Context, network, address string) (net.PacketConn, error) { + log.Debugln("[Tailscale](%s) SystemPacketListener: start listen %s %s", option.Name, network, address) +- pc, err := outbound.dialer.ListenPacket(ctx, network, address, netip.AddrPort{}) ++ pc, err := packetDialer.ListenPacket(ctx, network, address, netip.AddrPort{}) + log.Debugln("[Tailscale](%s) SystemPacketListener: finish listen %s %s, err: %v", option.Name, network, address, err) + return pc, err + }, diff --git a/web/index.html b/web/index.html index 9b97af4..1343234 100644 --- a/web/index.html +++ b/web/index.html @@ -502,7 +502,7 @@ const TEMPLATES = { "providers/10-sub.each.yaml": " ${SUB_NAME}:\n type: http\n url: \"${SUB_URL}\"\n path: ./providers/${SUB_NAME}.yaml\n interval: 3600\n proxy: ${@SUB_PROXY}\n exclude-filter: \"(?i)app not supported|приложение не|свяжитесь\"\n header:\n User-Agent: [\"${SUB_UA}\"]\n ${@@SUB_HEADERS}\n health-check:\n enable: true\n url: \"https://www.gstatic.com/generate_204\"\n interval: 300\n timeout: 3000\n lazy: false\n", "providers/20-openvpn.yaml": " # OpenVPN: file written on the router by bmstu-otp.sh (fresh TOTP in the\n # password). No health-check here: a dead tunnel would be redialed with a\n # stale OTP; the cron watchdog (bmstu-otp.sh check) handles it.\n ${OVPN_PROVIDER}:\n type: file\n path: ./providers/${OVPN_PROVIDER}.yaml\n health-check:\n enable: false\n override: #@street\n dialer-proxy: OVPN-EXIT #@street\n", "proxies/10-boot.each.yaml": " - name: ${SEED_NAME}\n type: vless\n server: ${SEED_SERVER}\n port: ${SEED_PORT}\n uuid: ${SEED_UUID}\n network: tcp\n udp: true\n tls: true\n flow: xtls-rprx-vision\n servername: ${SEED_SNI}\n client-fingerprint: firefox\n reality-opts:\n public-key: ${SEED_PBK}\n short-id: ${SEED_SID}\n", - "proxies/20-tailscale.yaml": " # Tailscale: userspace node, starts on first use. First login: open the URL\n # from the nikki log (\"To start this tsnet server ... go to: ...\"), then\n # disable key expiry for this node. Needs TS_FORCE_NOISE_443=true in the\n # mihomo environment (mihomo-kit.sh fix).\n - name: tailscale\n type: tailscale\n hostname: ${TS_HOSTNAME}\n state-dir: ./tailscale\n udp: true\n accept-routes: true\n dialer-proxy: TS-EXIT #@ts_exit\n", + "proxies/20-tailscale.yaml": " # Tailscale: userspace node, starts on first use. First login: open the URL\n # from the nikki log (\"To start this tsnet server ... go to: ...\"), then\n # disable key expiry for this node. Needs TS_FORCE_NOISE_443=true in the\n # mihomo environment (mihomo-kit.sh fix).\n - name: tailscale\n type: tailscale\n hostname: ${TS_HOSTNAME}\n state-dir: ./tailscale\n udp: true\n accept-routes: true\n dialer-proxy: TS-EXIT #@ts_exit\n # street: control and DERP over TCP through own servers (MY -> hysteria2 -> MY-EXIT); #@street,hy2,!ts_exit\n # needs the kit's core (v1.19.32-ts1, tools/core/*.patch, MetaCubeX/mihomo#3142) #@street,hy2,!ts_exit\n dialer-proxy: MY #@street,hy2,!ts_exit\n", "proxies/30-hy2.each.yaml": " - name: ${HY2_NAME}\n type: hysteria2\n server: ${HY2_SERVER}\n port: ${HY2_PORT}\n password: \"${HY2_PASSWORD}\"\n obfs: ${@HY2_OBFS}\n obfs-password: \"${@@HY2_OBFS_PASSWORD}\"\n sni: ${@HY2_SNI}\n skip-cert-verify: ${HY2_INSECURE}\n up: \"${@@HY2_UP}\"\n down: \"${@@HY2_DOWN}\"\n udp: true\n dialer-proxy: MY-EXIT #@hy2_exit\n", "rules/10-tailscale.yaml": " # Tailscale: tailnet IPs and MagicDNS names (resolved by tailscale itself)\n - IP-CIDR,100.64.0.0/10,TAILSCALE,no-resolve\n - DOMAIN-SUFFIX,ts.net,TAILSCALE\n - DOMAIN-SUFFIX,${@TS_DOMAINS},TAILSCALE\n", "rules/20-openvpn.yaml": " # OpenVPN server itself must not go into its own tunnel\n - IP-CIDR,${@OVPN_SERVER_IPS}/32,DIRECT,no-resolve #@home\n - IP-CIDR,${@OVPN_SERVER_IPS}/32,OVPN-EXIT,no-resolve #@street\n - DOMAIN,${OVPN_SERVER_HOST},DIRECT #@home\n - DOMAIN,${OVPN_SERVER_HOST},OVPN-EXIT #@street\n # networks pushed by the server (before the private-range DIRECT rules)\n - IP-CIDR,${@OVPN_ROUTES},${OVPN_GROUP},no-resolve\n",