Assemble source-integrated VoHive

This commit is contained in:
windloom committed 2026-07-06 04:30:39 +08:00
commit de689a554d
984 files changed
+255607

No files matched your search

+21
View File
@@ -0,0 +1,21 @@
.git
.github
.gitignore
go.work
**/*.log
**/*.db
**/*.sqlite
**/*.sqlite3
logs
data
tmp
dist
web/node_modules
web/dist
internal/web/dist
**/.DS_Store
+181
View File
@@ -0,0 +1,181 @@
name: Build Release Binaries
on:
push:
tags:
- 'v*'
workflow_dispatch:
inputs:
version:
description: 'Version string used when manually triggered'
required: false
default: 'dev'
enable_upx:
description: 'Enable UPX compression (true/false)'
required: false
default: 'false'
permissions:
contents: write
concurrency:
group: binary-release-${{ github.ref }}
cancel-in-progress: false
jobs:
frontend:
name: Build frontend assets
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
cache-dependency-path: web/package-lock.json
- name: Build frontend assets
shell: bash
run: |
npm ci --prefix web
npm run build --prefix web
- name: Upload frontend dist
uses: actions/upload-artifact@v4
with:
name: web-dist
path: web/dist
if-no-files-found: error
retention-days: 1
build:
name: Build ${{ matrix.artifact_arch }}
runs-on: ubuntu-latest
needs: frontend
strategy:
fail-fast: false
matrix:
include:
- goarch: amd64
goarm: ''
artifact_arch: amd64
- goarch: arm64
goarm: ''
artifact_arch: arm64
- goarch: arm
goarm: '7'
artifact_arch: armv7
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version-file: go.mod
cache: true
- name: Prepare build vars
id: vars
shell: bash
run: |
if [[ "${GITHUB_REF_TYPE}" == "tag" ]]; then
VERSION="${GITHUB_REF_NAME}"
else
VERSION="${{ github.event.inputs.version || 'dev' }}"
fi
BUILDTIME="$(date -u +'%Y-%m-%dT%H:%M:%SZ')"
ENABLE_UPX_RAW="${{ github.event.inputs.enable_upx || 'false' }}"
case "${ENABLE_UPX_RAW}" in
true|1|yes|on) ENABLE_UPX=1 ;;
*) ENABLE_UPX=0 ;;
esac
echo "version=${VERSION}" >> "${GITHUB_OUTPUT}"
echo "buildtime=${BUILDTIME}" >> "${GITHUB_OUTPUT}"
echo "enable_upx=${ENABLE_UPX}" >> "${GITHUB_OUTPUT}"
- name: Download frontend dist
uses: actions/download-artifact@v4
with:
name: web-dist
path: web/dist
- name: Sync frontend dist for embed
shell: bash
run: |
rm -rf internal/web/dist
mkdir -p internal/web
cp -R web/dist internal/web/dist
- name: Build binary
shell: bash
run: |
mkdir -p dist
GOWORK=off CGO_ENABLED=0 GOOS=linux GOARCH=${{ matrix.goarch }} GOARM=${{ matrix.goarm }} \
go build -trimpath -buildvcs=false -tags "with_utls nomsgpack" \
-ldflags "-s -w -X 'github.com/iniwex5/vohive/internal/global.Version=${{ steps.vars.outputs.version }}' -X 'github.com/iniwex5/vohive/internal/global.BuildTime=${{ steps.vars.outputs.buildtime }}'" \
-o dist/vo-hive ./cmd/vohive
- name: Install UPX
if: ${{ steps.vars.outputs.enable_upx == '1' }}
shell: bash
run: |
sudo apt-get update
sudo apt-get install -y upx-ucl || sudo apt-get install -y upx
- name: Compress with UPX
if: ${{ steps.vars.outputs.enable_upx == '1' }}
shell: bash
run: |
upx --best --lzma dist/vo-hive || upx -9 dist/vo-hive
- name: Package artifact
shell: bash
run: |
OUT="vohive_${{ steps.vars.outputs.version }}_linux_${{ matrix.artifact_arch }}"
mkdir -p out
cp dist/vo-hive "out/${OUT}"
sha256sum "out/${OUT}" > "out/${OUT}.sha256"
- name: Upload artifact
uses: actions/upload-artifact@v4
with:
name: binaries-${{ matrix.artifact_arch }}
path: out/*
retention-days: 3
release:
name: Publish release assets
runs-on: ubuntu-latest
needs: build
if: github.event_name == 'workflow_dispatch' || startsWith(github.ref, 'refs/tags/v')
steps:
- name: Prepare release vars
id: release_vars
shell: bash
run: |
if [[ "${GITHUB_REF_TYPE}" == "tag" ]]; then
RELEASE_VERSION="${GITHUB_REF_NAME}"
else
RELEASE_VERSION="${{ github.event.inputs.version || 'dev' }}"
fi
echo "release_version=${RELEASE_VERSION}" >> "${GITHUB_OUTPUT}"
- name: Download all artifacts
uses: actions/download-artifact@v4
with:
pattern: binaries-*
merge-multiple: true
path: dist
- name: Publish to this GitHub Release
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ steps.release_vars.outputs.release_version }}
files: dist/*
fail_on_unmatched_files: true
overwrite_files: true
+74
View File
@@ -0,0 +1,74 @@
name: docker-build
on:
workflow_dispatch:
inputs:
platforms:
description: build platforms
required: false
default: linux/amd64,linux/arm64
push:
description: push image
required: false
default: "false"
enable_upx:
description: enable UPX compression (true/false)
required: false
default: "false"
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- uses: actions/checkout@v4
- uses: docker/setup-qemu-action@v3
if: ${{ contains(inputs.platforms, 'arm') || contains(inputs.platforms, 'ppc') || contains(inputs.platforms, 's390') || contains(inputs.platforms, 'riscv') }}
with:
platforms: all
- uses: docker/setup-buildx-action@v3
- uses: docker/login-action@v3
if: ${{ inputs.push == 'true' }}
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Prepare build args
id: vars
shell: bash
run: |
VERSION="dev-${GITHUB_SHA::7}"
BUILDTIME="$(date -u +'%Y-%m-%dT%H:%M:%SZ')"
REVISION="${GITHUB_SHA}"
ENABLE_UPX_RAW="${{ inputs.enable_upx }}"
case "${ENABLE_UPX_RAW}" in
false|0|no|off) ENABLE_UPX=0 ;;
*) ENABLE_UPX=1 ;;
esac
echo "version=${VERSION}" >> "${GITHUB_OUTPUT}"
echo "buildtime=${BUILDTIME}" >> "${GITHUB_OUTPUT}"
echo "revision=${REVISION}" >> "${GITHUB_OUTPUT}"
echo "enable_upx=${ENABLE_UPX}" >> "${GITHUB_OUTPUT}"
- uses: docker/build-push-action@v6
with:
context: .
file: Dockerfile.github
platforms: ${{ inputs.platforms }}
push: ${{ inputs.push == 'true' }}
tags: ghcr.io/${{ github.repository }}/vohive:dev
provenance: false
sbom: false
cache-from: type=gha
cache-to: type=gha,mode=max
build-args: |
VERSION=${{ steps.vars.outputs.version }}
BUILDTIME=${{ steps.vars.outputs.buildtime }}
REVISION=${{ steps.vars.outputs.revision }}
ENABLE_UPX=${{ steps.vars.outputs.enable_upx }}
+88
View File
@@ -0,0 +1,88 @@
name: Build and Push Docker Image
on:
push:
tags:
- 'v*'
workflow_dispatch:
inputs:
enable_upx:
description: enable UPX compression (true/false)
required: false
default: "false"
env:
DOCKER_IMAGE: skyhotspur/vohive
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Login to DockerHub
if: github.event_name != 'pull_request'
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Extract metadata (tags, labels)
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.DOCKER_IMAGE }}
tags: |
# 语义化精确版本标签 (例如 v1.0.0 会被转换为 1.0.0)
type=semver,pattern={{version}},enable=${{ startsWith(github.ref, 'refs/tags/v') }}
# 手动触发时只推 sha 标签,避免覆盖 latest
type=sha,prefix=sha-,format=short,enable=${{ github.event_name == 'workflow_dispatch' }}
- name: Prepare build args
id: vars
shell: bash
run: |
if [[ "${GITHUB_REF_TYPE}" == "tag" ]]; then
VERSION="${GITHUB_REF_NAME}"
else
VERSION="sha-${GITHUB_SHA::7}"
fi
BUILDTIME="$(date -u +'%Y-%m-%dT%H:%M:%SZ')"
REVISION="${GITHUB_SHA}"
if [[ "${GITHUB_EVENT_NAME}" == "workflow_dispatch" ]]; then
ENABLE_UPX_RAW="${{ github.event.inputs.enable_upx }}"
else
ENABLE_UPX_RAW="false"
fi
case "${ENABLE_UPX_RAW}" in
false|0|no|off) ENABLE_UPX=0 ;;
*) ENABLE_UPX=1 ;;
esac
echo "version=${VERSION}" >> "${GITHUB_OUTPUT}"
echo "buildtime=${BUILDTIME}" >> "${GITHUB_OUTPUT}"
echo "revision=${REVISION}" >> "${GITHUB_OUTPUT}"
echo "enable_upx=${ENABLE_UPX}" >> "${GITHUB_OUTPUT}"
- name: Build and push
uses: docker/build-push-action@v5
with:
context: .
file: ./Dockerfile.github
platforms: linux/amd64,linux/arm64
push: ${{ github.event_name != 'pull_request' }}
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max
build-args: |
VERSION=${{ steps.vars.outputs.version }}
BUILDTIME=${{ steps.vars.outputs.buildtime }}
REVISION=${{ steps.vars.outputs.revision }}
ENABLE_UPX=${{ steps.vars.outputs.enable_upx }}
+40
View File
@@ -0,0 +1,40 @@
name: Web CI
on:
pull_request:
paths:
- 'web/**'
- '.github/workflows/web-ci.yml'
push:
branches:
- main
paths:
- 'web/**'
- '.github/workflows/web-ci.yml'
workflow_dispatch:
jobs:
web-check:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
cache-dependency-path: web/package-lock.json
- name: Install dependencies
run: npm ci --prefix web
- name: Lint
run: npm run lint --prefix web
- name: Typecheck
run: npm run typecheck --prefix web
- name: Build
run: npm run build --prefix web
+65
View File
@@ -0,0 +1,65 @@
# 构建产物
/vo-hive
/mbimprobe
*.exe
*.dll
*.so
*.dylib
# 数据和日志目录
/data/
/logs/
*.db
*.db-journal
*.log
# 前端构建产物 (由 npm run build 生成)
/web/dist/
/web/node_modules/
/web-reader/dist/
/web-reader/node_modules/
/internal/web/dist/
/dist/*
/raspberry-backups/
# IDE 和编辑器
.idea/
.vscode/
.agent/
.shared/
*.swp
*.swo
*~
# 系统文件
.DS_Store
Thumbs.db
# 配置文件 (包含敏感信息)
/config/config.yaml
/config/*.yaml
!config/config.example.yaml
# 测试覆盖率
coverage.out
*.cover
*.coverprofile
# 临时文件
*.tmp
*.temp
.cache/
/server
/reader
vohive.code-workspace
PushNotification.pdf
Quectel_LTE_Standard_UAC_应用指导_V1.0.pdf
# macOS AppleDouble metadata
**/._*
.superpowers/*
.codex
.worktrees/
Quectel_EC2xEG2xEG9xEM05_Series_AT_Commands_Manual_V2.2.pdf
Quectel_EC2xEG2xEG9xEM05_Series_QCFG_AT_Commands_Manual_V1.6.pdf
410sim自动激活脚本/*
+90
View File
@@ -0,0 +1,90 @@
# VoHive Docker Hub 镜像
镜像地址:`skyhotspur/vohive`
支持架构:
- `linux/amd64`
- `linux/arm64`
## 快速启动
```bash
mkdir -p vohive/{config,data,logs}
cd vohive
```
创建 `config/config.yaml`:
```yaml
server:
port: 7575
debug: false
web:
username: admin
password: admin
devices: []
proxy:
instances: []
vowifi:
enabled: false
```
创建 `docker-compose.yml`:
```yaml
services:
vohive:
image: skyhotspur/vohive:${VOHIVE_TAG:-1.5.5}
container_name: vohive
restart: unless-stopped
network_mode: host
privileged: true
volumes:
- ./config:/app/config
- ./data:/app/data
- ./logs:/app/logs
- /dev:/dev
environment:
TZ: Asia/Shanghai
CONFIG_PATH: /app/config/config.yaml
```
启动:
```bash
docker compose up -d
```
Web 入口:`http://YOUR_IP:7575`
默认账号:`admin` / `admin`
首次登录后请立即修改密码。
## 更新镜像
```bash
docker pull "skyhotspur/vohive:${VOHIVE_TAG:-1.5.5}"
docker compose up -d
```
应用内二进制热更新在这个源码整合构建中已禁用。Docker 部署请通过拉取新镜像升级。
## 配置说明
| 路径 | 说明 |
| --- | --- |
| `/app/config` | 配置文件目录 |
| `/app/data` | SQLite 数据与运行数据 |
| `/app/logs` | 日志目录 |
容器默认时区为 `Asia/Shanghai`。Compose 文件也显式设置了同一时区,方便在不同运行方式下保持一致。
## 许可证提示
本仓库是源码整合树,不是单一 MIT 许可项目。根项目来自 PolyForm Noncommercial 1.0.0,`third_party/vowifi-go` 为 AGPL-3.0,其它第三方源码按各自许可证授权。发布公开二进制或 Docker 镜像前,请先确认组合分发的许可证义务。
+101
View File
@@ -0,0 +1,101 @@
# GitHub Actions 多架构构建专用 Dockerfile
# 构建阶段 1: 前端构建 (Frontend)
# 使用 --platform=$BUILDPLATFORM 强制在构建机本地架构(通常是amd64)运行
# 避免在 arm64 构建时使用 QEMU 模拟,大幅提升速度且产物跨平台通用
FROM --platform=$BUILDPLATFORM node:20-alpine AS frontend-builder
ARG BUILDPLATFORM
WORKDIR /app/web
COPY web/package*.json ./
# 挂载 npm 缓存,加速依赖安装
RUN --mount=type=cache,target=/root/.npm,id=npm-${BUILDPLATFORM},sharing=locked \
npm ci
COPY web/ .
RUN npm run build
# 构建阶段 2: 后端构建 (Backend)
FROM --platform=$BUILDPLATFORM golang:1.26.4-alpine AS backend-builder
ARG BUILDPLATFORM
ARG VERSION=unknown
ARG BUILDTIME=unknown
ARG REVISION=unknown
ARG ENABLE_UPX=0
WORKDIR /app
ENV PATH="/usr/local/go/bin:${PATH}"
# 使用镜像内置的已修复 Go 工具链,避免构建时隐式下载工具链
ENV GOTOOLCHAIN=local
ENV GOWORK=off
# 安装构建依赖
RUN apk add --no-cache git
# 复制 go mod 文件
COPY go.mod go.sum ./
COPY third_party ./third_party
# 挂载 Go 模块缓存,加速依赖下载
ARG TARGETOS
ARG TARGETARCH
RUN --mount=type=cache,target=/go/pkg/mod,id=gomod-${TARGETOS}-${TARGETARCH},sharing=locked \
go mod download
# 复制源代码
COPY . .
# 复制构建好的前端资源到 internal/web/dist 以便嵌入
COPY --from=frontend-builder /app/web/dist ./internal/web/dist/
# 验证前端资源已复制
RUN ls -la internal/web/dist/ && echo "Frontend assets copied successfully"
# 整理依赖并编译二进制
# 挂载 Go 构建缓存和模块缓存,加速重复构建
RUN --mount=type=cache,target=/root/.cache/go-build,id=gobuild-${TARGETOS}-${TARGETARCH},sharing=locked \
--mount=type=cache,target=/go/pkg/mod,id=gomod-${TARGETOS}-${TARGETARCH},sharing=locked \
go mod tidy && \
BUILD_TIME="${BUILDTIME}" && \
if [ -z "${BUILD_TIME}" ] || [ "${BUILD_TIME}" = "unknown" ]; then \
BUILD_TIME="$(date -u +'%Y-%m-%dT%H:%M:%SZ')"; \
fi && \
CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} \
go build -trimpath -buildvcs=false -tags "with_utls nomsgpack" -ldflags "-s -w -X 'github.com/iniwex5/vohive/internal/global.Version=${VERSION}' -X 'github.com/iniwex5/vohive/internal/global.BuildTime=${BUILD_TIME}'" -o vo-hive ./cmd/vohive && \
if [ "${ENABLE_UPX}" = "1" ] || [ "${ENABLE_UPX}" = "true" ]; then \
echo "UPX enabled, compressing binary..."; \
(apk add --no-cache upx >/dev/null 2>&1 || apk add --no-cache upx-ucl >/dev/null 2>&1 || true); \
if command -v upx >/dev/null 2>&1; then \
upx --best --lzma /app/vo-hive; \
else \
echo "UPX package not available, skip compression."; \
fi; \
else \
echo "UPX disabled."; \
fi && \
ls -lh /app/vo-hive
# 运行阶段 (Runtime)
FROM alpine:latest
ARG REVISION=unknown
WORKDIR /app
LABEL org.opencontainers.image.revision=${REVISION}
# 运行时依赖
# - ca-certificates / tzdata: 基础 HTTPS 与时区支持
RUN apk add --no-cache ca-certificates tzdata
# 复制二进制文件
COPY --from=backend-builder /app/vo-hive .
# 创建配置和数据目录
RUN mkdir -p config data logs
# 暴露端口
EXPOSE 7575
# 默认配置路径环境变量
ENV CONFIG_PATH=/app/config/config.yaml
ENV TZ=Asia/Shanghai
# 入口点
ENTRYPOINT ["./vo-hive"]
CMD ["-c", "/app/config/config.yaml"]
+101
View File
@@ -0,0 +1,101 @@
# GitHub Actions 多架构构建专用 Dockerfile
# 构建阶段 1: 前端构建 (Frontend)
# 使用 --platform=$BUILDPLATFORM 强制在构建机本地架构(通常是amd64)运行
# 避免在 arm64 构建时使用 QEMU 模拟,大幅提升速度且产物跨平台通用
FROM --platform=$BUILDPLATFORM node:20-alpine AS frontend-builder
ARG BUILDPLATFORM
WORKDIR /app/web
COPY web/package*.json ./
# 挂载 npm 缓存,加速依赖安装
RUN --mount=type=cache,target=/root/.npm,id=npm-${BUILDPLATFORM},sharing=locked \
npm ci
COPY web/ .
RUN npm run build
# 构建阶段 2: 后端构建 (Backend)
FROM --platform=$BUILDPLATFORM golang:1.26.4-alpine AS backend-builder
ARG BUILDPLATFORM
ARG VERSION=unknown
ARG BUILDTIME=unknown
ARG REVISION=unknown
ARG ENABLE_UPX=0
WORKDIR /app
ENV PATH="/usr/local/go/bin:${PATH}"
# 使用镜像内置的已修复 Go 工具链,避免构建时隐式下载工具链
ENV GOTOOLCHAIN=local
ENV GOWORK=off
# 安装构建依赖
RUN apk add --no-cache git
# 复制 go mod 文件
COPY go.mod go.sum ./
COPY third_party ./third_party
# 挂载 Go 模块缓存,加速依赖下载
ARG TARGETOS
ARG TARGETARCH
RUN --mount=type=cache,target=/go/pkg/mod,id=gomod-${TARGETOS}-${TARGETARCH},sharing=locked \
go mod download
# 复制源代码
COPY . .
# 复制构建好的前端资源到 internal/web/dist 以便嵌入
COPY --from=frontend-builder /app/web/dist ./internal/web/dist/
# 验证前端资源已复制
RUN ls -la internal/web/dist/ && echo "Frontend assets copied successfully"
# 整理依赖并编译二进制
# 挂载 Go 构建缓存和模块缓存,加速重复构建
RUN --mount=type=cache,target=/root/.cache/go-build,id=gobuild-${TARGETOS}-${TARGETARCH},sharing=locked \
--mount=type=cache,target=/go/pkg/mod,id=gomod-${TARGETOS}-${TARGETARCH},sharing=locked \
go mod tidy && \
BUILD_TIME="${BUILDTIME}" && \
if [ -z "${BUILD_TIME}" ] || [ "${BUILD_TIME}" = "unknown" ]; then \
BUILD_TIME="$(date -u +'%Y-%m-%dT%H:%M:%SZ')"; \
fi && \
CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} \
go build -trimpath -buildvcs=false -tags "with_utls nomsgpack" -ldflags "-s -w -X 'github.com/iniwex5/vohive/internal/global.Version=${VERSION}' -X 'github.com/iniwex5/vohive/internal/global.BuildTime=${BUILD_TIME}'" -o vo-hive ./cmd/vohive && \
if [ "${ENABLE_UPX}" = "1" ] || [ "${ENABLE_UPX}" = "true" ]; then \
echo "UPX enabled, compressing binary..."; \
(apk add --no-cache upx >/dev/null 2>&1 || apk add --no-cache upx-ucl >/dev/null 2>&1 || true); \
if command -v upx >/dev/null 2>&1; then \
upx --best --lzma /app/vo-hive; \
else \
echo "UPX package not available, skip compression."; \
fi; \
else \
echo "UPX disabled."; \
fi && \
ls -lh /app/vo-hive
# 运行阶段 (Runtime)
FROM alpine:latest
ARG REVISION=unknown
WORKDIR /app
LABEL org.opencontainers.image.revision=${REVISION}
# 运行时依赖
# - ca-certificates / tzdata: 基础 HTTPS 与时区支持
RUN apk add --no-cache ca-certificates tzdata
# 复制二进制文件
COPY --from=backend-builder /app/vo-hive .
# 创建配置和数据目录
RUN mkdir -p config data logs
# 暴露端口
EXPOSE 7575
# 默认配置路径环境变量
ENV CONFIG_PATH=/app/config/config.yaml
ENV TZ=Asia/Shanghai
# 入口点
ENTRYPOINT ["./vo-hive"]
CMD ["-c", "/app/config/config.yaml"]
+137
View File
@@ -0,0 +1,137 @@
# PolyForm Noncommercial License 1.0.0
<https://polyformproject.org/licenses/noncommercial/1.0.0>
## Acceptance
In order to get any license under these terms, you must agree
to them as both strict obligations and conditions to all
your licenses.
## Copyright License
The licensor grants you a copyright license for the
software to do everything you might do with the software
that would otherwise infringe the licensor's copyright
in it for any permitted purpose. However, you may
only distribute the software according to [Distribution
License](#distribution-license) and make changes or new works
based on the software according to [Changes and New Works
License](#changes-and-new-works-license).
## Distribution License
The licensor grants you an additional copyright license
to distribute copies of the software. Your license
to distribute covers distributing the software with
changes and new works permitted by [Changes and New Works
License](#changes-and-new-works-license).
## Notices
You must ensure that anyone who gets a copy of any part of
the software from you also gets a copy of these terms or the
URL for them above, as well as copies of any plain-text lines
beginning with `Required Notice:` that the licensor provided
with the software. For example:
> Required Notice: Copyright iniwex5 (https://github.com/iniwex5/vohive)
## Changes and New Works License
The licensor grants you an additional copyright license to
make changes and new works based on the software for any
permitted purpose.
## Patent License
The licensor grants you a patent license for the software that
covers patent claims the licensor can license, or becomes able
to license, that you would infringe by using the software.
## Noncommercial Purposes
Any noncommercial purpose is a permitted purpose.
## Personal Uses
Personal use for research, experiment, and testing for
the benefit of public knowledge, personal study, private
entertainment, hobby projects, amateur pursuits, or religious
observance, without any anticipated commercial application,
is use for a permitted purpose.
## Noncommercial Organizations
Use by any charitable organization, educational institution,
public research organization, public safety or health
organization, environmental protection organization, or
government institution is use for a permitted purpose
regardless of the source of funding or obligations resulting
from the funding.
## Fair Use
You may have "fair use" rights for the software under the
law. These terms do not limit them.
## No Other Rights
These terms do not allow you to sublicense or transfer any of
your licenses to anyone else, or prevent the licensor from
granting licenses to anyone else. These terms do not imply
any other licenses.
## Patent Defense
If you make any written claim that the software infringes or
contributes to infringement of any patent, your patent license
for the software granted under these terms ends immediately. If
your company makes such a claim, your patent license ends
immediately for work on behalf of your company.
## Violations
The first time you are notified in writing that you have
violated any of these terms, or done anything with the software
not covered by your licenses, your licenses can nonetheless
continue if you come into full compliance with these terms,
and take practical steps to correct past violations, within
32 days of receiving notice. Otherwise, all your licenses
end immediately.
## No Liability
***As far as the law allows, the software comes as is, without
any warranty or condition, and the licensor will not be liable
to you for any damages arising out of these terms or the use
or nature of the software, under any kind of legal claim.***
## Definitions
The **licensor** is the individual or entity offering these
terms, and the **software** is the software the licensor makes
available under these terms.
**You** refers to the individual or entity agreeing to these
terms.
**Your company** is any legal entity, sole proprietorship,
or other kind of organization that you work for, plus all
organizations that have control over, are under the control of,
or are under common control with that organization. **Control**
means ownership of substantially all the assets of an entity,
or the power to direct its management and policies by vote,
contract, or otherwise. Control can be direct or indirect.
**Your licenses** are all the licenses granted to you for the
software under these terms.
**Use** means anything you do with the software requiring one
of your licenses.
**Trademark** means trademarks, service marks, and similar rights.
---
Required Notice: Copyright iniwex5 (https://github.com/iniwex5/vohive)
+55
View File
@@ -0,0 +1,55 @@
BINARY_NAME ?= vohive
GO_TAGS ?= with_utls nomsgpack
GOOS ?= linux
CGO_ENABLED ?= 0
VERSION ?= $(shell git describe --tags --always 2>/dev/null || echo "unknown")
VERSION_TAG = $(if $(filter v%,$(VERSION)),$(VERSION),v$(VERSION))
BUILD_TIME ?= $(shell date "+%Y-%m-%d %H:%M:%S")
DIST_DIR ?= dist
MAIN_PACKAGE ?= ./cmd/vohive
LDFLAGS = -s -w -X 'github.com/iniwex5/vohive/internal/global.Version=$(VERSION)' -X 'github.com/iniwex5/vohive/internal/global.BuildTime=$(BUILD_TIME)'
GO_BUILD = go build -trimpath -buildvcs=false -tags "$(GO_TAGS)" -ldflags "$(LDFLAGS)"
AMD64_OUT = $(DIST_DIR)/$(BINARY_NAME)_$(VERSION_TAG)_linux_amd64
ARM64_OUT = $(DIST_DIR)/$(BINARY_NAME)_$(VERSION_TAG)_linux_arm64
ARMV7_OUT = $(DIST_DIR)/$(BINARY_NAME)_$(VERSION_TAG)_linux_armv7
UPX ?= $(shell command -v upx || command -v upx-ucl)
UPX_FLAGS ?= --best --lzma
.PHONY: all build build-amd64 build-arm64 build-armv7 build-all frontend-dist clean
all: build-all
build: build-amd64
build-all: build-amd64 build-arm64 build-armv7
frontend-dist:
npm ci --prefix web
npm run build --prefix web
rm -rf internal/web/dist
mkdir -p internal/web
cp -R web/dist internal/web/dist
build-amd64: frontend-dist
@test -n "$(UPX)" || { echo "错误: 需要安装 upx"; exit 1; }
mkdir -p $(DIST_DIR)
CGO_ENABLED=$(CGO_ENABLED) GOOS=$(GOOS) GOARCH=amd64 $(GO_BUILD) -o $(AMD64_OUT) $(MAIN_PACKAGE)
$(UPX) $(UPX_FLAGS) $(AMD64_OUT)
build-arm64: frontend-dist
@test -n "$(UPX)" || { echo "错误: 需要安装 upx"; exit 1; }
mkdir -p $(DIST_DIR)
CGO_ENABLED=$(CGO_ENABLED) GOOS=$(GOOS) GOARCH=arm64 $(GO_BUILD) -o $(ARM64_OUT) $(MAIN_PACKAGE)
$(UPX) $(UPX_FLAGS) $(ARM64_OUT)
build-armv7: frontend-dist
@test -n "$(UPX)" || { echo "错误: 需要安装 upx"; exit 1; }
mkdir -p $(DIST_DIR)
CGO_ENABLED=$(CGO_ENABLED) GOOS=$(GOOS) GOARCH=arm GOARM=7 $(GO_BUILD) -o $(ARMV7_OUT) $(MAIN_PACKAGE)
$(UPX) $(UPX_FLAGS) $(ARMV7_OUT)
clean:
go clean
rm -rf $(DIST_DIR)
+100
View File
@@ -0,0 +1,100 @@
# VoHive
> Windloom source integration tree: this repository vendors the visible
> project-level VoHive source dependencies under `third_party/` and builds
> without the unavailable upstream `github.com/iniwex5/vowifi-go` repository.
> See [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) for source origins,
> license notes, and build-chain details.
## Local source build
```bash
npm ci --prefix web
npm run build --prefix web
rm -rf internal/web/dist
mkdir -p internal/web
cp -R web/dist internal/web/dist
GOWORK=off CGO_ENABLED=0 GOOS=linux GOARCH=amd64 \
go build -trimpath -buildvcs=false -tags "with_utls nomsgpack" \
-o dist/vohive-open_linux_amd64 ./cmd/vohive
GOWORK=off CGO_ENABLED=0 GOOS=linux GOARCH=arm64 \
go build -trimpath -buildvcs=false -tags "with_utls nomsgpack" \
-o dist/vohive-open_linux_arm64 ./cmd/vohive
```
## Docker
```bash
mkdir -p vohive/{config,data,logs}
cp config/config.example.yaml vohive/config/config.yaml
cd vohive
```
Use the compose file from this repository, or create one with:
```yaml
services:
vohive:
image: skyhotspur/vohive:${VOHIVE_TAG:-1.5.5}
container_name: vohive
restart: unless-stopped
network_mode: host
privileged: true
volumes:
- ./config:/app/config
- ./data:/app/data
- ./logs:/app/logs
- /dev:/dev
environment:
TZ: Asia/Shanghai
CONFIG_PATH: /app/config/config.yaml
```
Default login: `admin` / `admin`. Change the password after first login. Set
`VOHIVE_TAG` before running Compose when you want a specific image tag.
[![License: PolyForm Noncommercial 1.0.0](https://img.shields.io/badge/License-PolyForm--Noncommercial--1.0.0-blue.svg)](https://polyformproject.org/licenses/noncommercial/1.0.0)
[![Go](https://img.shields.io/badge/Go-1.26%2B-00ADD8?logo=go)](go.mod)
[![Vue 3](https://img.shields.io/badge/Vue-3-42b883?logo=vue.js)](web/package.json)
> 面向高通 4G/LTE/5G 模组(Quectel EC20/EC25/EC21/EG25/EM20 等)的综合管理与代理服务平台。
VoHive 把模组热插拔管理、SOCKS5/HTTP 代理编排、短信收发、VoWiFi/IMS 通话、eSIM 全生命周期管理整合到一个服务里,并提供一套现代化的响应式 Web 管理后台。
## 核心特性
| 模块 | 说明 |
| --- | --- |
| 多模组并发管理 | USB 热插拔自动发现(ttyUSB 等)、多设备实时状态监控 |
| 轻量级代理引擎 | 内建 SOCKS5 / HTTP 代理内核,支持多实例并发;基于 `SO_BINDTODEVICE` 按设备网卡严格绑定出站流量 |
| 通信与短信中心 | 统一界面/API 处理 AT 短信收发、会话与联系人管理、USSD 交互,短信落库可查 |
| eSIM 管理 | 通过 AT 指令通道直接管理 eSIM 芯片,支持 Profile 下载、启用/停用、重命名、删除 |
| 全渠道通知 | 重要短信及系统告警可推送至 Telegram、Email、PushPlus、Bark、飞书(Lark/Feishu)、QQ 等 |
| 多架构构建 | 原生支持 amd64 / arm64 / arm7 跨平台编译,路由器到边缘节点均可部署 |
## 典型应用场景
- **私有 IP 代理池**:单主机挂载多张物理 SIM 卡或多张 eSIM,每张网卡对应独立的 SOCKS5/HTTP 实例,组建自己的移动网络代理。
- **统一接码/验证码中心**:Web 界面或 API 并行收发多卡短信,并通过 Webhook/Bot 实时推送到个人终端。
- **VoWiFi 零信号通信**:地下室、弱覆盖场景下,借助宽带网络隧道建立 IMS 连接,保证业务不掉线。
## 架构与技术栈
- **Backend**:Go 1.26+(Gin、GORM、Viper、euicc-go)
- **Frontend**:Vue 3 + Vite + TailwindCSS + Element Plus
- **Database**:SQLite(`vohive.db`)
- **CI/CD**:GitHub Actions 自动化多架构 Docker 镜像构建与发布
## 免责声明
- **用途定位**:本项目主要面向个人学习、技术研究与功能测试场景,不建议直接用于生产环境或关键业务系统;由此产生的部署及使用风险由使用者自行承担。
- **非官方项目**:VoHive 为第三方独立开发的开源软件,与 Quectel(高通模组厂商)、高通公司及其他任何模组/芯片厂商均无官方关联、授权或合作关系,亦不对模组硬件本身的功能、质量或安全性负责。
- **合规使用**:使用本项目搭建的服务时,请自行确保符合所在地区的法律法规及电信运营商的服务条款,不得用于任何违法违规用途。因违规使用造成的一切法律责任由使用者自行承担,与本项目作者及贡献者无关。
- **无担保**:本软件按"现状"提供,不附带任何明示或暗示的担保,包括但不限于适销性、特定用途适用性及不侵权担保。因使用或无法使用本软件(含数据丢失、设备异常、业务中断等)造成的任何直接或间接损失,作者及贡献者不承担任何责任。
## License
本源码整合树不是单一许可项目。根项目基于 [PolyForm Noncommercial License 1.0.0](LICENSE),`third_party/vowifi-go` 使用 AGPL-3.0,`third_party/quectel-qmi-go`、`third_party/netlink`、`third_party/qqbot` 等组件按各自许可证授权。发布公开二进制或 Docker 镜像前,请先确认组合分发的许可证义务;详情见 [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md)。
+48
View File
@@ -0,0 +1,48 @@
# Third-party source notices
This repository is a source-complete integration tree for local builds of VoHive.
It keeps the visible project-level source dependencies in `third_party/` so the
build no longer depends on the unavailable `github.com/iniwex5/vowifi-go`
repository or on release-only VoHive binaries.
## Included source trees
| Path | Upstream | Commit checked | License |
| --- | --- | --- | --- |
| `.` | `https://github.com/giszh86/vohive` | `f240894e763cf7f0cf74c88562bb9b55f0d573b1` | PolyForm Noncommercial 1.0.0 |
| `third_party/netlink` | `https://github.com/iniwex5/netlink` | module cache `v1.3.3` | MIT |
| `third_party/qqbot` | `https://github.com/iniwex5/qqbot` | module cache `v1.0.1` | MIT |
| `third_party/quectel-qmi-go` | `https://github.com/iniwex5/quectel-qmi-go` | `aaada14395c19ee4c8b4b15a373f41bd2ed14cf0` (`v0.6.0`) | MIT |
| `third_party/vowifi-go` | `https://github.com/boa-z/vowifi-go` | `23459976796fb43b024c479b19b6edf8baf379d4` | AGPL-3.0 |
The original `github.com/iniwex5/vowifi-go v1.1.2` module was not publicly
accessible at the time this integration tree was assembled. The replacement
under `third_party/vowifi-go` is an independent open implementation that uses
the same module path for compatibility.
## Build notes
The root `go.mod` uses local `replace` directives:
```go
replace (
github.com/iniwex5/netlink => ./third_party/netlink
github.com/iniwex5/qqbot => ./third_party/qqbot
github.com/iniwex5/quectel-qmi-go => ./third_party/quectel-qmi-go
github.com/iniwex5/vowifi-go => ./third_party/vowifi-go
)
```
In-app binary self-updates are disabled for this integration tree. Release
binaries and Docker images should be updated through repository releases or
container image rollout.
UPX compression is disabled by default in `Dockerfile.github` to keep produced
binaries easier to inspect.
## License compatibility note
The root project license and the included AGPL-3.0 VoWiFi implementation carry
different obligations. This file documents the source origins; it does not grant
additional rights or resolve license compatibility for public combined binary or
container distribution.
+306
View File
@@ -0,0 +1,306 @@
// Command mbimprobe is a throwaway real-device harness. NOT part of the build.
package main
import (
"context"
"crypto/rand"
"fmt"
"os"
"time"
"encoding/hex"
dev "github.com/iniwex5/vohive/internal/device"
mbimcore "github.com/iniwex5/vohive/internal/mbim"
)
func main() {
mode := "probe"
if len(os.Args) > 1 {
mode = os.Args[1]
}
if mode == "scan" {
runScan()
return
}
if mode == "uicc" {
runUICC()
return
}
if mode == "auth" {
runAuth()
return
}
if mode == "simauth" {
runSimAuth()
return
}
runProbe()
}
// runSimAuth 验证"逻辑通道 + APDU"链路:用已知能开的 ISD-R 完整 AID 开出通道,
// 然后在通道上发真 APDU 选 USIM(部分 AID),确认 APDU 传输可用 + USIM 可选中。
// 两点成立 → 逻辑通道 AKA 可行(复用现有 APDU AUTHENTICATE 逻辑)。
// runSimAuth 验证智能选卡与 MBIM 逻辑通道 AKA。
// 直接获取 QMI 暴露的长 AID,打开逻辑通道并尝试发送 0x88 AUTHENTICATE 指令。
func runSimAuth() {
node := "/dev/cdc-wdm2"
if len(os.Args) > 2 {
node = os.Args[2]
}
octx, ocancel := context.WithTimeout(context.Background(), 10*time.Second)
defer ocancel()
m := mbimcore.New(node, "auto")
if err := m.Open(octx); err != nil {
fmt.Println("Open 失败:", err)
os.Exit(1)
}
defer m.Close()
fmt.Println("== 测试智能选卡与逻辑通道 APDU (MBIM AKA) ==")
aidStr, source, err := m.ResolveLogicalChannelAID("usim", "")
if err != nil {
fmt.Println("智能选卡提取 USIM 失败:", err)
return
}
fmt.Printf("成功提取 USIM 长 AID: %s (Source: %s)\n", aidStr, source)
aid, _ := hex.DecodeString(aidStr)
ctx, cancel := context.WithTimeout(context.Background(), 12*time.Second)
defer cancel()
ch, err := m.OpenChannel(ctx, aid)
if err != nil {
fmt.Printf("OpenChannel(USIM) 失败: %v\n", err)
return
}
fmt.Printf("OpenChannel(USIM) OK channel=%d\n", ch)
defer m.CloseChannel(ctx, ch)
// 伪造全 0 的 RAND 和 AUTN 发送 AKA
randBytes := make([]byte, 16)
autnBytes := make([]byte, 16)
// CLA(含通道号), INS(0x88), P1(0x00), P2(0x81), Lc(0x22), Data...
cla := byte(ch) & 0x03
apdu := []byte{cla, 0x88, 0x00, 0x81, 0x22, 0x10}
apdu = append(apdu, randBytes...)
apdu = append(apdu, 0x10)
apdu = append(apdu, autnBytes...)
fmt.Printf("发送 3G AKA 鉴权 APDU: %X\n", apdu)
resp, err := m.TransmitAPDU(ctx, ch, apdu)
if err != nil {
fmt.Println("TransmitAPDU(AKA) 失败:", err)
return
}
fmt.Printf("TransmitAPDU(AKA) 响应: %X\n", resp)
if len(resp) >= 2 && resp[len(resp)-2] == 0x98 && resp[len(resp)-1] == 0x62 {
fmt.Println("验证成功:收到 9862(MAC Failure)!底层逻辑通道鉴权完全打通。")
} else if len(resp) >= 2 && resp[len(resp)-2] == 0x61 {
fmt.Println("验证成功:收到 61xx!有响应数据。底层逻辑通道鉴权完全打通。")
} else {
fmt.Println("收到其他响应,可能是通道状态或指令参数不支持。")
}
}
// runAuth 判别这颗模组的 MBIM AUTH 服务是真可用还是 stub。
// - AUTH_SIM(2G GSM):无 AUTN/MAC,功能正常的子系统对任意 RAND 都返回 SRES/Kc;
// 报错 → 整个 AUTH 服务是 stub。
// - AUTH_AKA(随机 RAND/AUTN):预期 status=0x23(35,INCORRECT_AUTN),作基线对照。
func runAuth() {
node := "/dev/cdc-wdm2"
if len(os.Args) > 2 {
node = os.Args[2]
}
octx, ocancel := context.WithTimeout(context.Background(), 10*time.Second)
defer ocancel()
m := mbimcore.New(node, "auto")
if err := m.Open(octx); err != nil {
fmt.Println("Open 失败:", err)
os.Exit(1)
}
defer m.Close()
fmt.Println("== MBIM Open 成功,测试 AUTH 服务可用性 ==")
r16 := func() []byte {
b := make([]byte, 16)
_, _ = rand.Read(b)
return b
}
ctx1, c1 := context.WithTimeout(context.Background(), 8*time.Second)
sres, kc, err := m.AuthSIM(ctx1, r16())
c1()
if err != nil {
fmt.Printf("AUTH_SIM(2G): 报错 -> %v\n", err)
fmt.Println(" 判定: AUTH 服务大概率是 stub(连无 MAC 校验的 GSM 鉴权都失败)")
} else {
fmt.Printf("AUTH_SIM(2G): OK SRES=0x%08x Kc=0x%016x\n", sres, kc)
fmt.Println(" 判定: AUTH 子系统是工作的 → AKA 的 status=35 不是 stub,需查应用上下文(USIM/ISIM)")
}
ctx2, c2 := context.WithTimeout(context.Background(), 8*time.Second)
_, _, _, _, akaErr := m.CalculateAKA(ctx2, r16(), r16())
c2()
if akaErr != nil {
fmt.Printf("AUTH_AKA(随机): %v (基线:随机 AUTN 必然 MAC 失败,预期 0x23/35)\n", akaErr)
} else {
fmt.Println("AUTH_AKA(随机): 竟然成功? 异常,随机 AUTN 不应通过 MAC")
}
}
func runScan() {
// 复现 API handleDeviceMgmtDiscovered 的发现路径:QMI+fallback 合并。
fmt.Println("== DiscoverCompatibleModemsFromQMI(nil) [= /devices/discovered 路径] ==")
list, err := dev.DiscoverCompatibleModemsFromQMI(nil)
if err != nil {
fmt.Println("发现错误:", err)
return
}
if len(list) == 0 {
fmt.Println("(未发现兼容 modem)")
return
}
for i, m := range list {
fmt.Printf("[%d] mode=%s transport=%s vid:pid=%04x:%04x driver=%s\n",
i, m.Mode, m.TransportType, m.VendorID, m.ProductID, m.DriverName)
fmt.Printf(" control=%s net=%s usb=%s netcap=%v IMEI=%s AT=%v\n",
m.ControlPath, m.NetInterface, m.USBPath, m.NetworkCapable, m.IMEI, m.ATPorts)
if m.Mode == "mbim" {
enriched, imei := dev.EnrichDiscoveredCompatibleModem(m, dev.CompatibleModemEnrichOptions{
EnableATProbe: true,
ATProbeTimeout: 900 * time.Millisecond,
})
fmt.Printf(" [enrich] AT口=%s IMEI=%q (enrichment 未崩溃)\n", enriched.ATPort, imei)
}
}
}
func runUICC() {
node := "/dev/cdc-wdm2"
if len(os.Args) > 2 {
node = os.Args[2]
}
octx, ocancel := context.WithTimeout(context.Background(), 10*time.Second)
defer ocancel()
m := mbimcore.New(node, "auto")
if err := m.Open(octx); err != nil {
fmt.Println("Open 失败:", err)
os.Exit(1)
}
defer m.Close()
fmt.Println("== MBIM Open 成功(走 mbim-proxy,不与现有进程抢占设备),测试 UICC 逻辑通道 ==")
// 尝试直接通过 QMI over MBIM 隧道获取长 AID 列表
fmt.Println("== 尝试通过原生 QMI over MBIM 隧道获取所有应用信息 ==")
qmiCtx, qmiCancel := context.WithTimeout(context.Background(), 5*time.Second)
apps, qmiErr := m.QMIUIMApplicationList(qmiCtx)
qmiCancel()
if qmiErr != nil {
fmt.Printf("QMIUIMApplicationList 失败: %v\n", qmiErr)
} else {
appTypeNames := map[uint8]string{1: "SIM(2G)", 2: "USIM(3G/4G/5G)", 3: "RUIM", 4: "CSIM", 5: "ISIM"}
for i, app := range apps {
name := appTypeNames[app.Type]
if name == "" {
name = fmt.Sprintf("Unknown(%d)", app.Type)
}
fmt.Printf(" 发现应用[%d]: 类型=%-14s AID=%X\n", i, name, app.AID)
}
}
fmt.Println("==================================================")
// ISD-R AID (eSIM) 和 USIM 选 MF 的最小尝试
cases := []struct {
name string
aid []byte
}{
{"ISD-R(eSIM)", []byte{0xA0, 0x00, 0x00, 0x05, 0x59, 0x10, 0x10, 0xFF, 0xFF, 0xFF, 0xFF, 0x89, 0x00, 0x00, 0x01, 0x00}},
{"USIM Partial(7)", []byte{0xA0, 0x00, 0x00, 0x00, 0x87, 0x10, 0x02}},
{"USIM Fake(16)", []byte{0xA0, 0x00, 0x00, 0x00, 0x87, 0x10, 0x02, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}},
{"空AID(基础通道)", nil},
}
for _, c := range cases {
ctx, cancel := context.WithTimeout(context.Background(), 6*time.Second)
ch, err := m.OpenChannel(ctx, c.aid)
if err != nil {
fmt.Printf("%-16s OpenChannel 失败: %v\n", c.name, err)
cancel()
continue
}
fmt.Printf("%-16s OpenChannel OK channel=%d\n", c.name, ch)
_ = m.CloseChannel(ctx, ch)
cancel()
}
}
func runProbe() {
node := "/dev/cdc-wdm2"
if len(os.Args) > 2 {
node = os.Args[2]
}
octx, ocancel := context.WithTimeout(context.Background(), 10*time.Second)
defer ocancel()
m := mbimcore.New(node, "direct")
if err := m.Open(octx); err != nil {
fmt.Println("Open 失败:", err)
os.Exit(1)
}
defer m.Close()
fmt.Println("== MBIM Open 成功 ==")
step := func(name string, fn func(context.Context) string) {
ctx, cancel := context.WithTimeout(context.Background(), 6*time.Second)
defer cancel()
done := make(chan string, 1)
go func() { done <- fn(ctx) }()
select {
case s := <-done:
fmt.Printf("%-14s %s\n", name+":", s)
case <-ctx.Done():
fmt.Printf("%-14s 超时/无响应\n", name+":")
}
}
step("DeviceCaps", func(ctx context.Context) string {
c, err := m.DeviceCaps(ctx)
if err != nil {
return "ERR " + err.Error()
}
return fmt.Sprintf("IMEI=%s FW=%s", c.DeviceID, c.FirmwareInfo)
})
step("Subscriber", func(ctx context.Context) string {
s, err := m.SubscriberReady(ctx)
if err != nil {
return "ERR " + err.Error()
}
return fmt.Sprintf("ready=%d IMSI=%s ICCID=%s", s.ReadyState, s.IMSI, s.ICCID)
})
step("Register", func(ctx context.Context) string {
r, err := m.RegisterState(ctx)
if err != nil {
return "ERR " + err.Error()
}
return fmt.Sprintf("state=%d provider=%q MCC=%s MNC=%s", r.RegisterState, r.ProviderName, r.MCC, r.MNC)
})
step("Signal", func(ctx context.Context) string {
s, err := m.SignalState(ctx)
if err != nil {
return "ERR " + err.Error()
}
return fmt.Sprintf("unknown=%v rssi=%d dBm=%d", s.Unknown, s.RSSI, s.DBM)
})
step("Packet", func(ctx context.Context) string {
p, err := m.PacketService(ctx)
if err != nil {
return "ERR " + err.Error()
}
return fmt.Sprintf("state=%d", p.State)
})
step("Radio", func(ctx context.Context) string {
r, err := m.RadioState(ctx)
if err != nil {
return "ERR " + err.Error()
}
return fmt.Sprintf("hw=%d sw=%d", r.Hardware, r.Software)
})
}
+277
View File
@@ -0,0 +1,277 @@
package main
import (
"context"
"errors"
"flag"
"log"
"log/slog"
"net/http"
"os"
"os/signal"
"path/filepath"
"syscall"
"time"
"github.com/iniwex5/vohive/internal/api"
"github.com/iniwex5/vohive/internal/config"
"github.com/iniwex5/vohive/internal/db"
"github.com/iniwex5/vohive/internal/device"
"github.com/iniwex5/vohive/internal/notify"
proxyserver "github.com/iniwex5/vohive/internal/proxy/server"
"github.com/iniwex5/vohive/internal/proxy/traffic"
"github.com/iniwex5/vohive/internal/upstreamproxy"
"github.com/iniwex5/vowifi-go/runtimehost/carrier"
"github.com/iniwex5/vowifi-go/runtimehost/voicehost"
"github.com/iniwex5/vohive/internal/web"
"github.com/iniwex5/vohive/pkg/logger"
)
func main() {
// Parse flags
var configPath string
var backendOnly bool
flag.StringVar(&configPath, "c", "config/config.yaml", "config file path")
flag.BoolVar(&backendOnly, "backend-only", false, "run as backend-only (disable embedded web UI)")
flag.Parse()
// 1. 加载配置
if err := config.InitGlobalManager(configPath); err != nil {
log.Fatalf("初始化配置管理器失败: %v", err)
}
cfg := config.GetConfig()
// 2. 初始化日志
logger.Setup(logger.LogConfig{
Debug: cfg.Server.Debug,
Filename: "logs/app.log",
})
// 将内置 slog 重定向到已就绪的系统日志框架
slog.SetDefault(slog.New(logger.NewSlogHandler(logger.ZapLogger())))
logger.Info("VoHive 模组管理器启动中...")
go func() {
disclaimer := `
======================================================================
【VoHive 免责与使用声明】
1. 本软件仅供个人技术测试与研究交流,严禁任何商业用途。
2. 严禁将本软件用于任何非法或违规场景。
3. 本软件涉及底层通信操作,因测试产生的硬件、资费或网络风险由用户自行承担。
4. 作者不对使用本软件造成的任何直接或间接损失负责。
======================================================================`
logger.Warn(disclaimer)
ticker := time.NewTicker(24 * time.Hour)
defer ticker.Stop()
for range ticker.C {
logger.Warn(disclaimer)
}
}()
loadResult, err := carrier.LoadCarrierOverrides("")
if err != nil {
carrier.ClearCarrierOverrides()
logger.Warn("加载 carrier_overrides 失败,回退内置运营商配置",
"path", loadResult.Path,
"err", err)
} else if loadResult.Missing {
//logger.Info("carrier_overrides 文件不存在,使用内置运营商配置", "path", loadResult.Path)
} else {
logger.Info("carrier_overrides 已加载", "path", loadResult.Path, "entries", loadResult.Count)
}
// 3. 初始化数据库
dbPath := "data/vohive.db"
if err := db.Init(dbPath); err != nil {
log.Fatalf("初始化数据库失败: %v", err)
}
dbResolvedPath := dbPath
if absPath, err := filepath.Abs(dbPath); err == nil {
dbResolvedPath = absPath
}
logger.Info("数据库已初始化", "path", dbPath, "resolved_path", dbResolvedPath)
countryResult := upstreamproxy.InitCountryTable(context.Background(), upstreamproxy.CountryTableOptions{
CachePath: upstreamproxy.DefaultCountryTableCachePath,
})
if countryResult.Err != nil {
logger.Warn("MCC/MNC 国家表不可用,VoWiFi 国家代理规则将按未知国家直连",
"path", countryResult.CachePath,
"source_url", countryResult.SourceURL,
"source", countryResult.Source,
"err", countryResult.Err)
} else {
logger.Info("MCC/MNC 国家表已加载",
"path", countryResult.CachePath,
"source", countryResult.Source,
"rows", countryResult.RowCount,
"countries", countryResult.Countries)
}
go func() {
need, err := db.NeedBackfillSMSContacts()
if err != nil {
logger.Error("短信联系人回填检查失败", "err", err)
return
}
if !need {
return
}
logger.Info("开始短信联系人回填")
if err := db.BackfillSMSPeerAndContacts(1000); err != nil {
logger.Error("短信联系人回填失败", "err", err)
return
}
logger.Info("短信联系人回填完成")
}()
// 4. 初始化设备池
pool := device.NewPool(cfg)
pool.SetPolicyResolver(db.CardPolicyResolver{})
// 6. 初始化代理实例管理器
proxyMgr := proxyserver.NewManager()
logger.Info("代理实例管理器已初始化")
// 7. 初始化语音网关
// voiceGW 始终创建,用于管理 VoWiFi Agent(SimulateCall 等)。
var notifyMgr *notify.Manager
voiceGW := voicehost.NewGateway()
pool.SetVoiceGateway(voiceGW)
if err := voiceGW.Start(context.Background()); err != nil {
logger.Error("语音网关启动失败", "err", err)
} else {
logger.Info("语音网关已启动")
// 通知管理器初始化
var err error
notifyMgr, err = notify.NewManager(cfg, pool)
if err != nil {
logger.Warn("通知管理器初始化异常", "err", err)
} else {
pool.SetNotifier(notifyMgr)
voiceGW.SetNotifier(notifyMgr)
}
}
// 5. 启动工作器 (代理, 短信, 健康检查)
_ = pool.StartAll()
trafficSampler := traffic.New(traffic.Options{Pool: pool, Mgr: proxyMgr})
trafficSampler.Start()
realtimeTraffic := traffic.NewRealtimeManager(traffic.RealtimeOptions{Pool: pool})
// 7. 启动 API 服务器
// 准备静态文件系统
var staticFS http.FileSystem
if backendOnly {
logger.Info("启用纯后端模式(未挂载前端静态资源)")
} else {
distFS, err := web.GetFS()
if err != nil {
log.Fatalf("无法加载嵌入的 Web 文件: %v", err)
}
staticFS = http.FS(distFS)
}
// 通知管理器如果在上方未初始化,在这里兜底(防止 VoiceGW 未配置/启动的场景)
if notifyMgr == nil {
var err error
notifyMgr, err = notify.NewManager(cfg, pool)
if err != nil {
logger.Warn("通知管理器初始化异常", "err", err)
} else {
pool.SetNotifier(notifyMgr)
if voiceGW != nil {
voiceGW.SetNotifier(notifyMgr)
}
}
}
apiServer := api.New(cfg, pool, staticFS, proxyMgr, voiceGW, notifyMgr, configPath)
apiServer.SetRealtimeTraffic(realtimeTraffic)
syncProxyConfigs := func(reason, deviceID string) {
if err := apiServer.SyncProxyConfigs(); err != nil {
logger.Warn("同步代理配置失败", "reason", reason, "device_id", deviceID, "err", err)
return
}
logger.Debug("代理配置已同步", "reason", reason, "device_id", deviceID)
}
pool.OnDataConnected(func(deviceID string) {
syncProxyConfigs("qmi_data_connected", deviceID)
})
// 启动后同步代理配置到实例管理器
go func() {
time.Sleep(500 * time.Millisecond) // 等待 API 服务器初始化
syncProxyConfigs("startup", "")
}()
apiErrCh := make(chan error, 1)
go func() {
if err := apiServer.Run(); err != nil && !errors.Is(err, http.ErrServerClosed) {
apiErrCh <- err
}
}()
logger.Info("所有服务已启动")
quit := make(chan os.Signal, 2)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
defer signal.Stop(quit)
// 8. 等待关闭信号
var sig os.Signal
select {
case sig = <-quit:
logger.Info("收到关闭信号", "signal", sig.String())
case err := <-apiErrCh:
logger.Error("API 服务器失败", "err", err)
}
logger.Info("正在优雅关闭所有服务...")
// 9. 优雅关闭
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 10*time.Second)
defer shutdownCancel()
done := make(chan struct{})
go func() {
if err := apiServer.Shutdown(shutdownCtx); err != nil {
logger.Error("关闭 API 服务器时出错", "err", err)
}
if notifyMgr != nil {
notifyMgr.Close()
}
trafficSampler.Stop()
if err := proxyMgr.Shutdown(shutdownCtx); err != nil {
logger.Error("关闭代理实例时出错", "err", err)
}
// 关闭语音网关
if voiceGW != nil {
if err := voiceGW.Stop(); err != nil {
logger.Error("关闭语音网关时出错", "err", err)
}
}
if err := pool.Shutdown(); err != nil {
logger.Error("关闭工作器池时出错", "err", err)
}
close(done)
}()
select {
case <-done:
case <-quit:
case <-time.After(12 * time.Second):
logger.Warn("关闭超时,强制退出")
}
logger.Info("再见!")
}
+18
View File
@@ -0,0 +1,18 @@
server:
debug: false
port: 7575
web:
username: admin
password: admin
devices: []
proxy:
instances: []
vowifi:
enabled: false
webhook:
enabled: false
+15
View File
@@ -0,0 +1,15 @@
services:
vohive:
image: skyhotspur/vohive:${VOHIVE_TAG:-1.5.5}
container_name: vohive
restart: unless-stopped
network_mode: host
privileged: true
volumes:
- ./config:/app/config
- ./data:/app/data
- ./logs:/app/logs
- /dev:/dev
environment:
TZ: Asia/Shanghai
CONFIG_PATH: /app/config/config.yaml
+108
View File
@@ -0,0 +1,108 @@
module github.com/iniwex5/vohive
go 1.26.4
replace (
github.com/iniwex5/netlink => ./third_party/netlink
github.com/iniwex5/qqbot => ./third_party/qqbot
github.com/iniwex5/quectel-qmi-go => ./third_party/quectel-qmi-go
github.com/iniwex5/vowifi-go => ./third_party/vowifi-go
)
require (
github.com/damonto/euicc-go v1.1.3-0.20260628013808-8d873a2dfc98
github.com/gin-gonic/gin v1.11.0
github.com/glebarez/sqlite v1.11.0
github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1
github.com/iniwex5/netlink v1.3.3
github.com/iniwex5/qqbot v1.0.1
github.com/iniwex5/quectel-qmi-go v0.6.0
github.com/iniwex5/vowifi-go v1.1.2
github.com/larksuite/oapi-sdk-go/v3 v3.5.3
github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible
github.com/miekg/dns v1.1.67
github.com/spf13/viper v1.21.0
github.com/stretchr/testify v1.11.1
github.com/things-go/go-socks5 v0.1.1
github.com/warthog618/sms v0.3.0
go.bug.st/serial v1.6.4
go.uber.org/zap v1.27.1
go.yaml.in/yaml/v3 v3.0.4
golang.org/x/crypto v0.49.0
golang.org/x/sync v0.20.0
golang.org/x/sys v0.46.0
gopkg.in/yaml.v3 v3.0.1
gorm.io/gorm v1.30.5
)
require (
github.com/bytedance/sonic v1.14.0 // indirect
github.com/bytedance/sonic/loader v0.3.0 // indirect
github.com/cloudwego/base64x v0.1.6 // indirect
github.com/creack/goselect v0.1.2 // indirect
github.com/damonto/uicc-go v0.0.0-20260622025011-5cf36d6c8626 // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/emiago/sipgo v1.4.0 // indirect
github.com/fsnotify/fsnotify v1.9.0 // indirect
github.com/gabriel-vasile/mimetype v1.4.8 // indirect
github.com/gin-contrib/sse v1.1.0 // indirect
github.com/glebarez/go-sqlite v1.21.2 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.27.0 // indirect
github.com/go-viper/mapstructure/v2 v2.4.0 // indirect
github.com/gobwas/httphead v0.1.0 // indirect
github.com/gobwas/pool v0.2.1 // indirect
github.com/gobwas/ws v1.4.0 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/goccy/go-yaml v1.18.0 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/google/pprof v0.0.0-20231101202521-4ca4178f5c7a // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/gorilla/websocket v1.5.3 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/jonboulle/clockwork v0.5.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/lestrrat-go/strftime v1.2.0 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
github.com/pion/logging v0.2.4 // indirect
github.com/pion/randutil v0.1.0 // indirect
github.com/pion/rtcp v1.2.16 // indirect
github.com/pion/rtp v1.10.2 // indirect
github.com/pion/srtp/v3 v3.0.12 // indirect
github.com/pion/transport/v4 v4.0.2 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/quic-go/qpack v0.6.0 // indirect
github.com/quic-go/quic-go v0.57.0 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/rogpeppe/go-internal v1.13.1 // indirect
github.com/sagikazarmark/locafero v0.11.0 // indirect
github.com/sirupsen/logrus v1.9.4 // indirect
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect
github.com/spf13/afero v1.15.0 // indirect
github.com/spf13/cast v1.10.0 // indirect
github.com/spf13/pflag v1.0.10 // indirect
github.com/subosito/gotenv v1.6.0 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.3.0 // indirect
github.com/vishvananda/netns v0.0.5 // indirect
go.uber.org/multierr v1.11.0 // indirect
golang.org/x/arch v0.20.0 // indirect
golang.org/x/mod v0.34.0 // indirect
golang.org/x/net v0.52.0 // indirect
golang.org/x/text v0.36.0 // indirect
golang.org/x/tools v0.43.0 // indirect
google.golang.org/protobuf v1.36.11 // indirect
modernc.org/libc v1.22.5 // indirect
modernc.org/mathutil v1.5.0 // indirect
modernc.org/memory v1.5.0 // indirect
modernc.org/sqlite v1.23.1 // indirect
)
+249
View File
@@ -0,0 +1,249 @@
github.com/bytedance/sonic v1.14.0 h1:/OfKt8HFw0kh2rj8N0F6C/qPGRESq0BbaNZgcNXXzQQ=
github.com/bytedance/sonic v1.14.0/go.mod h1:WoEbx8WTcFJfzCe0hbmyTGrfjt8PzNEBdxlNUO24NhA=
github.com/bytedance/sonic/loader v0.3.0 h1:dskwH8edlzNMctoruo8FPTJDF3vLtDT0sXZwvZJyqeA=
github.com/bytedance/sonic/loader v0.3.0/go.mod h1:N8A3vUdtUebEY2/VQC0MyhYeKUFosQU6FxH2JmUe6VI=
github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=
github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
github.com/creack/goselect v0.1.2 h1:2DNy14+JPjRBgPzAd1thbQp4BSIihxcBf0IXhQXDRa0=
github.com/creack/goselect v0.1.2/go.mod h1:a/NhLweNvqIYMuxcMOuWY516Cimucms3DglDzQP3hKY=
github.com/damonto/euicc-go v1.1.3-0.20260628013808-8d873a2dfc98 h1:n2VA/WOWZCYjcd90zAuH+PlZpDjiEeXfIO1rMbIEsfM=
github.com/damonto/euicc-go v1.1.3-0.20260628013808-8d873a2dfc98/go.mod h1:L2YqXCb1ESnL1ZlqkQ7t/bVrcqrgt1hCwdzWrVzgYN0=
github.com/damonto/uicc-go v0.0.0-20260622025011-5cf36d6c8626 h1:jcUx6ygMhU27ca9qn0qX3rZCa1956YYJcn/1NUhX8XQ=
github.com/damonto/uicc-go v0.0.0-20260622025011-5cf36d6c8626/go.mod h1:4il4tcO0GJ2Bn8827RWDiMxNOnQpEApy3pwKliaR9uc=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/emiago/sipgo v1.4.0 h1:IRiwIUu4H97gC+vq2zsm3iWe/j08LPExFZRe3kfY0f0=
github.com/emiago/sipgo v1.4.0/go.mod h1:DuwAxBZhKMqIzQFPGZb1MVAGU6Wuxj64oTOhd5dx/FY=
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
github.com/gabriel-vasile/mimetype v1.4.8 h1:FfZ3gj38NjllZIeJAmMhr+qKL8Wu+nOoI3GqacKw1NM=
github.com/gabriel-vasile/mimetype v1.4.8/go.mod h1:ByKUIKGjh1ODkGM1asKUbQZOLGrPjydw3hYPU2YU9t8=
github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w=
github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM=
github.com/gin-gonic/gin v1.11.0 h1:OW/6PLjyusp2PPXtyxKHU0RbX6I/l28FTdDlae5ueWk=
github.com/gin-gonic/gin v1.11.0/go.mod h1:+iq/FyxlGzII0KHiBGjuNn4UNENUlKbGlNmc+W50Dls=
github.com/glebarez/go-sqlite v1.21.2 h1:3a6LFC4sKahUunAmynQKLZceZCOzUthkRkEAl9gAXWo=
github.com/glebarez/go-sqlite v1.21.2/go.mod h1:sfxdZyhQjTM2Wry3gVYWaW072Ri1WMdWJi0k6+3382k=
github.com/glebarez/sqlite v1.11.0 h1:wSG0irqzP6VurnMEpFGer5Li19RpIRi2qvQz++w0GMw=
github.com/glebarez/sqlite v1.11.0/go.mod h1:h8/o8j5wiAsqSPoWELDUdJXhjAhsVliSn7bWZjOhrgQ=
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.27.0 h1:w8+XrWVMhGkxOaaowyKH35gFydVHOvC0/uWoy2Fzwn4=
github.com/go-playground/validator/v10 v10.27.0/go.mod h1:I5QpIEbmr8On7W0TktmJAumgzX4CA1XNl4ZmDuVHKKo=
github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1 h1:wG8n/XJQ07TmjbITcGiUaOtXxdrINDz1b0J1w0SzqDc=
github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1/go.mod h1:A2S0CWkNylc2phvKXWBBdD3K0iGnDBGbzRpISP2zBl8=
github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs=
github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
github.com/gobwas/httphead v0.1.0 h1:exrUm0f4YX0L7EBwZHuCF4GDp8aJfVeBrlLQrs6NqWU=
github.com/gobwas/httphead v0.1.0/go.mod h1:O/RXo79gxV8G+RqlR/otEwx4Q36zl9rqC5u12GKvMCM=
github.com/gobwas/pool v0.2.1 h1:xfeeEhW7pwmX8nuLVlqbzVc7udMDrwetjEv+TZIz1og=
github.com/gobwas/pool v0.2.1/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw=
github.com/gobwas/ws v1.4.0 h1:CTaoG1tojrh4ucGPcoJFiAQUAsEWekEWvLy7GsVNqGs=
github.com/gobwas/ws v1.4.0/go.mod h1:G3gNqMNtPppf5XUz7O4shetPpcZ1VJ7zt18dlUeakrc=
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/goccy/go-yaml v1.18.0 h1:8W7wMFS12Pcas7KU+VVkaiCng+kG8QiFeFwzFb+rwuw=
github.com/goccy/go-yaml v1.18.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/pprof v0.0.0-20231101202521-4ca4178f5c7a h1:fEBsGL/sjAuJrgah5XqmmYsTLzJp/TO9Lhy39gkverk=
github.com/google/pprof v0.0.0-20231101202521-4ca4178f5c7a/go.mod h1:czg5+yv1E0ZGTi6S6vVK1mke0fV+FaUhNGcd6VRS9Ik=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/jonboulle/clockwork v0.5.0 h1:Hyh9A8u51kptdkR+cqRpT1EebBwTn1oK9YfGYbdFz6I=
github.com/jonboulle/clockwork v0.5.0/go.mod h1:3mZlmanh0g2NDKO5TWZVJAfofYk64M7XN3SzBPjZF60=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/larksuite/oapi-sdk-go/v3 v3.5.3 h1:xvf8Dv29kBXC5/DNDCLhHkAFW8l/0LlQJimO5Zn+JUk=
github.com/larksuite/oapi-sdk-go/v3 v3.5.3/go.mod h1:ZEplY+kwuIrj/nqw5uSCINNATcH3KdxSN7y+UxYY5fI=
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/lestrrat-go/envload v0.0.0-20180220234015-a3eb8ddeffcc h1:RKf14vYWi2ttpEmkA4aQ3j4u9dStX2t4M8UM6qqNsG8=
github.com/lestrrat-go/envload v0.0.0-20180220234015-a3eb8ddeffcc/go.mod h1:kopuH9ugFRkIXf3YoqHKyrJ9YfUFsckUU9S7B+XP+is=
github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible h1:Y6sqxHMyB1D2YSzWkLibYKgg+SwmyFU9dF2hn6MdTj4=
github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible/go.mod h1:ZQnN8lSECaebrkQytbHj4xNgtg8CR7RYXnPok8e0EHA=
github.com/lestrrat-go/strftime v1.2.0 h1:8fAUYOeaJKCuLzNvUWBAo8t6I6hkFfodDTndEzJIun0=
github.com/lestrrat-go/strftime v1.2.0/go.mod h1:GtsIA/7ddIGJjEdfadUafEb1sbutvlvpMdPCMglykYo=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/miekg/dns v1.1.67 h1:kg0EHj0G4bfT5/oOys6HhZw4vmMlnoZ+gDu8tJ/AlI0=
github.com/miekg/dns v1.1.67/go.mod h1:fujopn7TB3Pu3JM69XaawiU0wqjpL9/8xGop5UrTPps=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
github.com/pion/logging v0.2.4 h1:tTew+7cmQ+Mc1pTBLKH2puKsOvhm32dROumOZ655zB8=
github.com/pion/logging v0.2.4/go.mod h1:DffhXTKYdNZU+KtJ5pyQDjvOAh/GsNSyv1lbkFbe3so=
github.com/pion/randutil v0.1.0 h1:CFG1UdESneORglEsnimhUjf33Rwjubwj6xfiOXBa3mA=
github.com/pion/randutil v0.1.0/go.mod h1:XcJrSMMbbMRhASFVOlj/5hQial/Y8oH/HVo7TBZq+j8=
github.com/pion/rtcp v1.2.16 h1:fk1B1dNW4hsI78XUCljZJlC4kZOPk67mNRuQ0fcEkSo=
github.com/pion/rtcp v1.2.16/go.mod h1:/as7VKfYbs5NIb4h6muQ35kQF/J0ZVNz2Z3xKoCBYOo=
github.com/pion/rtp v1.10.2 h1:l+f6tTDcAH6xwepaAoW791ddhuYsJlqRATOzirO04Mo=
github.com/pion/rtp v1.10.2/go.mod h1:Au8fc6cEByy8RLTwKTQTEeQqDB/SJDxwL4mZuxYA5Pk=
github.com/pion/srtp/v3 v3.0.12 h1:U7V17bckl7sI4mb3sepiojByDuBY0wNCqQE+6IlQBbc=
github.com/pion/srtp/v3 v3.0.12/go.mod h1:EeZOi/sd6glM1EXapg051gdNWO9yWT1YSsgQ4SlJkns=
github.com/pion/transport/v4 v4.0.2 h1:ifYlPqNwsy6aKQ9y8yzxXlHae5431ZrH2avkD/Rn6Tk=
github.com/pion/transport/v4 v4.0.2/go.mod h1:06hFI+jCFcok2X2MekVufNZ/uzNZXivGBPfviSVcjgM=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=
github.com/quic-go/quic-go v0.57.0 h1:AsSSrrMs4qI/hLrKlTH/TGQeTMY0ib1pAOX7vA3AdqE=
github.com/quic-go/quic-go v0.57.0/go.mod h1:ly4QBAjHA2VhdnxhojRsCUOeJwKYg+taDlos92xb1+s=
github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=
github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=
github.com/sagikazarmark/locafero v0.11.0 h1:1iurJgmM9G3PA/I+wWYIOw/5SyBtxapeHDcg+AAIFXc=
github.com/sagikazarmark/locafero v0.11.0/go.mod h1:nVIGvgyzw595SUSUE6tvCp3YYTeHs15MvlmU87WwIik=
github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w=
github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g=
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 h1:+jumHNA0Wrelhe64i8F6HNlS8pkoyMv5sreGx2Ry5Rw=
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8/go.mod h1:3n1Cwaq1E1/1lhQhtRK2ts/ZwZEhjcQeJQ1RuC6Q/8U=
github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I=
github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg=
github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY=
github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo=
github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=
github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU=
github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
github.com/things-go/go-socks5 v0.1.1 h1:48hy9cHEXPKeG91G/g4n8zW4uynzPUQy/FkcrJ7r5AY=
github.com/things-go/go-socks5 v0.1.1/go.mod h1:1YBHVYG7Oli5ae+Pwkp630cPAwY1pjUPmohO1n0Emg0=
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
github.com/ugorji/go/codec v1.3.0 h1:Qd2W2sQawAfG8XSvzwhBeoGq71zXOC/Q1E9y/wUcsUA=
github.com/ugorji/go/codec v1.3.0/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
github.com/vishvananda/netns v0.0.5 h1:DfiHV+j8bA32MFM7bfEunvT8IAqQ/NzSJHtcmW5zdEY=
github.com/vishvananda/netns v0.0.5/go.mod h1:SpkAiCQRtJ6TvvxPnOSyH3BMl6unz3xZlaprSwhNNJM=
github.com/warthog618/sms v0.3.0 h1:LYAb5ngmu2qjNExgji3B7xi2tIZ9+DsuE9pC5xs4wwc=
github.com/warthog618/sms v0.3.0/go.mod h1:+bYZGeBxu003sxD5xhzsrIPBAjPBzTABsRTwSpd7ld4=
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
go.bug.st/serial v1.6.4 h1:7FmqNPgVp3pu2Jz5PoPtbZ9jJO5gnEnZIvnI1lzve8A=
go.bug.st/serial v1.6.4/go.mod h1:nofMJxTeNVny/m6+KaafC6vJGj3miwQZ6vW4BZUGJPI=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.uber.org/mock v0.5.2 h1:LbtPTcP8A5k9WPXj54PPPbjcI4Y6lhyOZXn+VS7wNko=
go.uber.org/mock v0.5.2/go.mod h1:wLlUxC2vVTPTaE3UD51E0BGOAElKrILxhVSDYQLld5o=
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=
go.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/arch v0.20.0 h1:dx1zTU0MAE98U+TQ8BLl7XsJbgze2WnNKF/8tGp/Q6c=
golang.org/x/arch v0.20.0/go.mod h1:bdwinDaKcfZUGpH09BB7ZmOfhalA8lQdzl62l8gGWsk=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.49.0 h1:+Ng2ULVvLHnJ/ZFEq4KdcDd/cfjrrjjNSXNzxg0Y4U4=
golang.org/x/crypto v0.49.0/go.mod h1:ErX4dUh2UM+CFYiXZRTcMpEcN8b/1gxEuv3nODoYtCA=
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.34.0 h1:xIHgNUUnW6sYkcM5Jleh05DvLOtwc6RitGHbDk4akRI=
golang.org/x/mod v0.34.0/go.mod h1:ykgH52iCZe79kzLLMhyCUzhMci+nQj+0XkbXpNYtVjY=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.52.0 h1:He/TN1l0e4mmR3QqHMT2Xab3Aj3L9qjbhRm78/6jrW0=
golang.org/x/net v0.52.0/go.mod h1:R1MAz7uMZxVMualyPXb+VaqGSa3LIaUqk0eEt3w36Sw=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw=
golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.36.0 h1:JfKh3XmcRPqZPKevfXVpI1wXPTqbkE5f7JA92a55Yxg=
golang.org/x/text v0.36.0/go.mod h1:NIdBknypM8iqVmPiuco0Dh6P5Jcdk8lJL0CUebqK164=
golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI=
golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/tools v0.43.0 h1:12BdW9CeB3Z+J/I/wj34VMl8X+fEXBxVR90JeMX5E7s=
golang.org/x/tools v0.43.0/go.mod h1:uHkMso649BX2cZK6+RpuIPXS3ho2hZo4FVwfoy1vIk0=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/gorm v1.30.5 h1:dvEfYwxL+i+xgCNSGGBT1lDjCzfELK8fHZxL3Ee9X0s=
gorm.io/gorm v1.30.5/go.mod h1:8Z33v652h4//uMA76KjeDH8mJXPm1QNCYrMeatR0DOE=
modernc.org/libc v1.22.5 h1:91BNch/e5B0uPbJFgqbxXuOnxBQjlS//icfQEGmvyjE=
modernc.org/libc v1.22.5/go.mod h1:jj+Z7dTNX8fBScMVNRAYZ/jF91K8fdT2hYMThc3YjBY=
modernc.org/mathutil v1.5.0 h1:rV0Ko/6SfM+8G+yKiyI830l3Wuz1zRutdslNoQ0kfiQ=
modernc.org/mathutil v1.5.0/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E=
modernc.org/memory v1.5.0 h1:N+/8c5rE6EqugZwHii4IFsaJ7MUhoWX07J5tC/iI5Ds=
modernc.org/memory v1.5.0/go.mod h1:PkUhL0Mugw21sHPeskwZW4D6VscE/GQJOnIpCnW6pSU=
modernc.org/sqlite v1.23.1 h1:nrSBg4aRQQwq59JpvGEQ15tNxoO5pX/kUjcRNwSAGQM=
modernc.org/sqlite v1.23.1/go.mod h1:OrDj17Mggn6MhE+iPbBNf7RGKODDE9NFT0f3EwDzJqk=
+9
View File
@@ -0,0 +1,9 @@
go 1.26.4
use (
.
./third_party/netlink
./third_party/qqbot
./third_party/quectel-qmi-go
./third_party/vowifi-go
)
+940
View File
@@ -0,0 +1,940 @@
package apduarbiter
import (
"context"
"errors"
"fmt"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/iniwex5/vohive/pkg/logger"
)
var ErrAPDUBusy = errors.New("apdu busy")
type LeaseType string
const (
LeaseTypeSession LeaseType = "session"
LeaseTypeOneShot LeaseType = "oneshot"
LeaseTypeTransport LeaseType = "transport"
LeaseTypeBarrier LeaseType = "barrier"
)
type TransportScope string
const (
TransportScopeExclusive TransportScope = "exclusive"
TransportScopeQMIChannel TransportScope = "qmi_channel"
)
type APDUClass string
const (
APDUClassEUICCWrite APDUClass = "EUICCWrite"
APDUClassEUICCRead APDUClass = "EUICCRead"
APDUClassUSIMAKA APDUClass = "USIMAKA"
APDUClassSMSC APDUClass = "SMSC"
APDUClassSwitchBarrier APDUClass = "SwitchBarrier"
APDUClassRecovery APDUClass = "Recovery"
)
const transportPriorityAging = 500 * time.Millisecond
type Options struct {
// MaxLeaseHold 是单条 APDU transport lease 的无进展 watchdog 超时。
// 持有方应在长耗时单条 APDU 前后调用 Touch;logical channel 生命周期不应再持有该 lease。
MaxLeaseHold time.Duration
// MaxSessions 是 legacy 兼容字段,仅服务旧 AcquireSession 接口。
// 新生产路径应使用 AcquireTransport,默认单设备同一时刻只允许一个 active transport APDU。
MaxSessions int
// MaxQMITransports 限制 QMI logical-channel transport 并发数量。
// 只有显式使用 TransportScopeQMIChannel 的 QMI channel APDU 会使用该并发窗口。
MaxQMITransports int
}
type Request struct {
Owner string
Mode string
Class APDUClass
Channel int
Scope TransportScope
}
type BarrierPolicy struct {
BlockedClasses []APDUClass
}
type Stats struct {
WaitRequests uint64
Acquires uint64
WaitTimeouts uint64
ForcedReleases uint64
CurrentQueue int
ActiveSessions int
ActiveOneshot bool
ActiveTransport bool
ActiveTransports int
ActiveBarriers int
CurrentQueueType string
}
type SnapshotEntry struct {
ID uint64
Owner string
Mode string
Class APDUClass
Channel int
Scope TransportScope
LeaseType LeaseType
WaitMS int64
HoldMS int64
}
type Snapshot struct {
Active []SnapshotEntry
Queue []SnapshotEntry
}
type waitKind string
const (
waitKindLease waitKind = "lease"
waitKindBarrier waitKind = "barrier"
)
type waitTicket struct {
id uint64
owner string
mode string
class APDUClass
channel int
scope TransportScope
leaseType LeaseType
kind waitKind
blocked map[APDUClass]bool
enqueued time.Time
}
type activeLease struct {
waitTicket
acquiredAt time.Time
expiresAt time.Time
timer *time.Timer
}
type activeBarrier struct {
waitTicket
acquiredAt time.Time
}
type Arbiter struct {
// 64 位 atomic 变量必须放在头部
seq uint64
deviceID string
opts Options
mu sync.Mutex
queue []waitTicket
activeSessions []*activeLease
activeOneshot *activeLease
activeTransports []*activeLease
activeBarriers []*activeBarrier
simAuthReady simAuthReadyState
notifyC chan struct{}
waitRequests atomic.Uint64
acquires atomic.Uint64
waitTimeouts atomic.Uint64
forcedReleases atomic.Uint64
}
type Lease struct {
arbiter *Arbiter
id uint64
owner string
mode string
class APDUClass
channel int
scope TransportScope
leaseType LeaseType
once sync.Once
}
type Barrier struct {
arbiter *Arbiter
id uint64
owner string
mode string
class APDUClass
once sync.Once
}
func New(deviceID string, opts Options) *Arbiter {
if opts.MaxLeaseHold <= 0 {
opts.MaxLeaseHold = 2 * time.Minute
}
if opts.MaxSessions <= 0 {
opts.MaxSessions = 1
}
if opts.MaxQMITransports <= 0 {
opts.MaxQMITransports = 1
}
return &Arbiter{
deviceID: strings.TrimSpace(deviceID),
opts: opts,
notifyC: make(chan struct{}),
}
}
func (a *Arbiter) AcquireTransport(ctx context.Context, req Request) (*Lease, error) {
return a.acquire(ctx, normalizeRequest(req, LeaseTypeTransport), LeaseTypeTransport)
}
func (a *Arbiter) BeginBarrier(ctx context.Context, req Request, policy BarrierPolicy) (*Barrier, error) {
if ctx == nil {
ctx = context.Background()
}
req.Owner = normalizeOwner(req.Owner)
req.Mode = normalizeMode(req.Mode)
if req.Class == "" {
req.Class = APDUClassSwitchBarrier
}
blocked := make(map[APDUClass]bool)
for _, class := range policy.BlockedClasses {
class = normalizeClass(class, LeaseTypeOneShot)
if class != "" {
blocked[class] = true
}
}
if len(blocked) == 0 {
blocked[APDUClassUSIMAKA] = true
blocked[APDUClassSMSC] = true
}
ticket := waitTicket{
id: atomic.AddUint64(&a.seq, 1),
owner: req.Owner,
mode: req.Mode,
class: req.Class,
channel: req.Channel,
scope: TransportScopeExclusive,
leaseType: LeaseTypeBarrier,
kind: waitKindBarrier,
blocked: blocked,
enqueued: time.Now(),
}
a.mu.Lock()
a.queue = append(a.queue, ticket)
a.waitRequests.Add(1)
a.logEvent(ticket, "barrier_wait", len(a.queue), 0, 0, "")
a.signalLocked()
for {
if a.canAcquireBarrierLocked(ticket) {
a.removeTicketLocked(ticket.id)
a.activeBarriers = append(a.activeBarriers, &activeBarrier{
waitTicket: ticket,
acquiredAt: time.Now(),
})
a.acquires.Add(1)
waitMs := time.Since(ticket.enqueued).Milliseconds()
a.logEvent(ticket, "barrier_enter", len(a.queue), waitMs, 0, "")
a.signalLocked()
a.mu.Unlock()
return &Barrier{
arbiter: a,
id: ticket.id,
owner: ticket.owner,
mode: ticket.mode,
class: ticket.class,
}, nil
}
waitC := a.notifyC
a.mu.Unlock()
select {
case <-ctx.Done():
a.mu.Lock()
if a.removeTicketLocked(ticket.id) {
a.waitTimeouts.Add(1)
a.logEvent(ticket, "timeout", len(a.queue), time.Since(ticket.enqueued).Milliseconds(), 0, ctx.Err().Error())
a.signalLocked()
}
a.mu.Unlock()
return nil, fmt.Errorf("%w: barrier owner=%s mode=%s class=%s: %v", ErrAPDUBusy, ticket.owner, ticket.mode, ticket.class, ctx.Err())
case <-waitC:
a.mu.Lock()
}
}
}
func (a *Arbiter) AcquireSession(ctx context.Context, owner, mode string) (*Lease, error) {
return a.acquire(ctx, Request{Owner: owner, Mode: mode}, LeaseTypeSession)
}
func (a *Arbiter) AcquireOneShot(ctx context.Context, owner, mode string) (*Lease, error) {
return a.acquire(ctx, Request{Owner: owner, Mode: mode}, LeaseTypeOneShot)
}
func (a *Arbiter) WaitIdle(ctx context.Context) error {
if ctx == nil {
ctx = context.Background()
}
for {
a.mu.Lock()
idle := a.isIdleLocked()
waitC := a.notifyC
a.mu.Unlock()
if idle {
return nil
}
select {
case <-ctx.Done():
return fmt.Errorf("%w: wait idle: %v", ErrAPDUBusy, ctx.Err())
case <-waitC:
}
}
}
func (a *Arbiter) IsIdle() bool {
a.mu.Lock()
defer a.mu.Unlock()
return a.isIdleLocked()
}
func (a *Arbiter) Stats() Stats {
a.mu.Lock()
defer a.mu.Unlock()
queueType := ""
if len(a.queue) > 0 {
queueType = string(a.queue[0].kind)
}
return Stats{
WaitRequests: a.waitRequests.Load(),
Acquires: a.acquires.Load(),
WaitTimeouts: a.waitTimeouts.Load(),
ForcedReleases: a.forcedReleases.Load(),
CurrentQueue: len(a.queue),
ActiveSessions: len(a.activeSessions),
ActiveOneshot: a.activeOneshot != nil,
ActiveTransport: len(a.activeTransports) > 0,
ActiveTransports: len(a.activeTransports),
ActiveBarriers: len(a.activeBarriers),
CurrentQueueType: queueType,
}
}
func (a *Arbiter) Snapshot() Snapshot {
a.mu.Lock()
defer a.mu.Unlock()
now := time.Now()
active := make([]SnapshotEntry, 0, len(a.activeSessions)+len(a.activeTransports)+len(a.activeBarriers)+1)
for _, session := range a.activeSessions {
active = append(active, snapshotActiveLease(session, now))
}
if a.activeOneshot != nil {
active = append(active, snapshotActiveLease(a.activeOneshot, now))
}
for _, transport := range a.activeTransports {
active = append(active, snapshotActiveLease(transport, now))
}
for _, barrier := range a.activeBarriers {
active = append(active, SnapshotEntry{
ID: barrier.id,
Owner: barrier.owner,
Mode: barrier.mode,
Class: barrier.class,
Channel: barrier.channel,
Scope: barrier.scope,
LeaseType: LeaseTypeBarrier,
HoldMS: now.Sub(barrier.acquiredAt).Milliseconds(),
})
}
queue := make([]SnapshotEntry, 0, len(a.queue))
for _, ticket := range a.queue {
queue = append(queue, SnapshotEntry{
ID: ticket.id,
Owner: ticket.owner,
Mode: ticket.mode,
Class: ticket.class,
Channel: ticket.channel,
Scope: ticket.scope,
LeaseType: ticket.leaseType,
WaitMS: now.Sub(ticket.enqueued).Milliseconds(),
})
}
return Snapshot{Active: active, Queue: queue}
}
func (l *Lease) Touch() bool {
if l == nil || l.arbiter == nil {
return false
}
return l.arbiter.touch(l.id, l.leaseType)
}
func (l *Lease) Active() bool {
if l == nil || l.arbiter == nil {
return false
}
return l.arbiter.isActive(l.id, l.leaseType)
}
func (l *Lease) Release() {
if l == nil || l.arbiter == nil {
return
}
l.once.Do(func() {
l.arbiter.release(l.id, l.leaseType, "release")
})
}
func (b *Barrier) Release() {
if b == nil || b.arbiter == nil {
return
}
b.once.Do(func() {
b.arbiter.releaseBarrier(b.id)
})
}
func (a *Arbiter) acquire(ctx context.Context, req Request, leaseType LeaseType) (*Lease, error) {
if ctx == nil {
ctx = context.Background()
}
req = normalizeRequest(req, leaseType)
ticket := waitTicket{
id: atomic.AddUint64(&a.seq, 1),
owner: req.Owner,
mode: req.Mode,
class: req.Class,
channel: req.Channel,
scope: req.Scope,
leaseType: leaseType,
kind: waitKindLease,
enqueued: time.Now(),
}
a.mu.Lock()
a.queue = append(a.queue, ticket)
a.waitRequests.Add(1)
a.logEvent(ticket, "wait", len(a.queue), 0, 0, "")
a.signalLocked()
for {
if a.canAcquireLeaseLocked(ticket) {
a.removeTicketLocked(ticket.id)
active := &activeLease{
waitTicket: ticket,
acquiredAt: time.Now(),
}
if a.opts.MaxLeaseHold > 0 {
active.expiresAt = active.acquiredAt.Add(a.opts.MaxLeaseHold)
leaseID := ticket.id
lType := leaseType
active.timer = time.AfterFunc(a.opts.MaxLeaseHold, func() {
a.releaseExpired(leaseID, lType)
})
}
a.addActiveLocked(active)
a.acquires.Add(1)
waitMs := time.Since(ticket.enqueued).Milliseconds()
a.logEvent(ticket, "acquire", len(a.queue), waitMs, 0, "")
a.signalLocked()
a.mu.Unlock()
return &Lease{
arbiter: a,
id: ticket.id,
owner: ticket.owner,
mode: ticket.mode,
class: ticket.class,
channel: ticket.channel,
scope: ticket.scope,
leaseType: leaseType,
}, nil
}
waitC := a.notifyC
a.mu.Unlock()
select {
case <-ctx.Done():
a.mu.Lock()
if a.removeTicketLocked(ticket.id) {
a.waitTimeouts.Add(1)
a.logEvent(ticket, "timeout", len(a.queue), time.Since(ticket.enqueued).Milliseconds(), 0, ctx.Err().Error())
a.signalLocked()
}
a.mu.Unlock()
return nil, fmt.Errorf("%w: owner=%s mode=%s class=%s channel=%d: %v", ErrAPDUBusy, ticket.owner, ticket.mode, ticket.class, ticket.channel, ctx.Err())
case <-waitC:
a.mu.Lock()
}
}
}
func (a *Arbiter) canAcquireLeaseLocked(ticket waitTicket) bool {
if ticket.kind != waitKindLease {
return false
}
if a.isBlockedByActiveBarrierLocked(ticket.class) {
return false
}
if a.hasPendingBarrierAheadLocked(ticket) {
return false
}
switch ticket.leaseType {
case LeaseTypeSession:
return a.queueHeadIsLocked(ticket.id) && a.activeOneshot == nil && !a.hasActiveTransportLocked() && len(a.activeSessions) < a.opts.MaxSessions
case LeaseTypeOneShot:
return a.queueHeadIsLocked(ticket.id) && len(a.activeSessions) == 0 && a.activeOneshot == nil && !a.hasActiveTransportLocked()
case LeaseTypeTransport:
if len(a.activeSessions) > 0 || a.activeOneshot != nil {
return false
}
return a.selectedTransportLocked() == ticket.id
default:
return false
}
}
func (a *Arbiter) canAcquireBarrierLocked(ticket waitTicket) bool {
if ticket.kind != waitKindBarrier {
return false
}
if a.hasActiveTransportLocked() || len(a.activeSessions) > 0 || a.activeOneshot != nil {
return false
}
return a.selectedBarrierLocked() == ticket.id
}
func (a *Arbiter) selectedBarrierLocked() uint64 {
for _, ticket := range a.queue {
if ticket.kind == waitKindBarrier {
return ticket.id
}
}
return 0
}
func (a *Arbiter) selectedTransportLocked() uint64 {
var oldestEligible *waitTicket
var oldestAgedNonAKA *waitTicket
var oldestAKA *waitTicket
now := time.Now()
for i := range a.queue {
ticket := &a.queue[i]
if ticket.kind == waitKindBarrier {
break
}
if ticket.leaseType != LeaseTypeTransport {
break
}
if a.isBlockedByActiveBarrierLocked(ticket.class) {
continue
}
if !a.canAcquireTransportNowLocked(*ticket) {
if a.transportWaitGatesQueueLocked(*ticket) {
break
}
continue
}
if oldestEligible == nil {
oldestEligible = ticket
}
if ticket.class == APDUClassUSIMAKA {
if oldestAKA == nil {
oldestAKA = ticket
}
continue
}
if oldestAgedNonAKA == nil && now.Sub(ticket.enqueued) >= transportPriorityAging {
oldestAgedNonAKA = ticket
}
}
switch {
case oldestAgedNonAKA != nil:
return oldestAgedNonAKA.id
case oldestAKA != nil:
return oldestAKA.id
case oldestEligible != nil:
return oldestEligible.id
default:
return 0
}
}
func (a *Arbiter) canAcquireTransportNowLocked(ticket waitTicket) bool {
if ticket.leaseType != LeaseTypeTransport {
return false
}
if ticket.scope != TransportScopeQMIChannel {
return !a.hasActiveTransportLocked()
}
if a.hasActiveExclusiveTransportLocked() {
return false
}
if a.activeQMITransportCountLocked() >= a.opts.MaxQMITransports {
return false
}
return !a.hasActiveTransportOnChannelLocked(ticket.channel)
}
func (a *Arbiter) transportWaitGatesQueueLocked(ticket waitTicket) bool {
if ticket.leaseType != LeaseTypeTransport {
return true
}
if ticket.scope != TransportScopeQMIChannel {
return true
}
if a.hasActiveExclusiveTransportLocked() || a.activeQMITransportCountLocked() >= a.opts.MaxQMITransports {
return true
}
return false
}
func (a *Arbiter) hasPendingBarrierAheadLocked(ticket waitTicket) bool {
for _, queued := range a.queue {
if queued.id == ticket.id {
return false
}
if queued.kind != waitKindBarrier {
continue
}
if queued.blocked[ticket.class] {
return true
}
}
return false
}
func (a *Arbiter) isBlockedByActiveBarrierLocked(class APDUClass) bool {
for _, barrier := range a.activeBarriers {
if barrier.blocked[class] {
return true
}
}
return false
}
func (a *Arbiter) queueHeadIsLocked(ticketID uint64) bool {
return len(a.queue) > 0 && a.queue[0].id == ticketID
}
func (a *Arbiter) addActiveLocked(active *activeLease) {
switch active.leaseType {
case LeaseTypeSession:
a.activeSessions = append(a.activeSessions, active)
case LeaseTypeOneShot:
a.activeOneshot = active
case LeaseTypeTransport:
a.activeTransports = append(a.activeTransports, active)
}
}
func (a *Arbiter) touch(leaseID uint64, leaseType LeaseType) bool {
if a.opts.MaxLeaseHold <= 0 {
return a.isActive(leaseID, leaseType)
}
a.mu.Lock()
defer a.mu.Unlock()
active := a.findActiveLocked(leaseID, leaseType)
if active == nil {
return false
}
active.expiresAt = time.Now().Add(a.opts.MaxLeaseHold)
if active.timer == nil {
lType := leaseType
active.timer = time.AfterFunc(a.opts.MaxLeaseHold, func() {
a.releaseExpired(leaseID, lType)
})
return true
}
active.timer.Reset(a.opts.MaxLeaseHold)
return true
}
func (a *Arbiter) release(leaseID uint64, leaseType LeaseType, reason string) {
a.mu.Lock()
defer a.mu.Unlock()
released := a.removeActiveLocked(leaseID, leaseType)
if released == nil {
return
}
if released.timer != nil {
released.timer.Stop()
}
holdMs := time.Since(released.acquiredAt).Milliseconds()
phase := "release"
if reason == "force-timeout" {
phase = "force-release"
a.forcedReleases.Add(1)
}
a.logEvent(released.waitTicket, phase, len(a.queue), 0, holdMs, reason)
a.signalLocked()
}
func (a *Arbiter) releaseBarrier(barrierID uint64) {
a.mu.Lock()
defer a.mu.Unlock()
for i, barrier := range a.activeBarriers {
if barrier.id != barrierID {
continue
}
a.activeBarriers = append(a.activeBarriers[:i], a.activeBarriers[i+1:]...)
holdMs := time.Since(barrier.acquiredAt).Milliseconds()
a.logEvent(barrier.waitTicket, "barrier_leave", len(a.queue), 0, holdMs, "")
a.signalLocked()
return
}
}
func (a *Arbiter) releaseExpired(leaseID uint64, leaseType LeaseType) {
a.mu.Lock()
defer a.mu.Unlock()
active := a.findActiveLocked(leaseID, leaseType)
if active == nil {
return
}
if !active.expiresAt.IsZero() {
if remaining := time.Until(active.expiresAt); remaining > 0 {
if active.timer != nil {
active.timer.Reset(remaining)
}
return
}
}
released := a.removeActiveLocked(leaseID, leaseType)
if released == nil {
return
}
if released.timer != nil {
released.timer.Stop()
}
a.forcedReleases.Add(1)
holdMs := time.Since(released.acquiredAt).Milliseconds()
a.logEvent(released.waitTicket, "force-release", len(a.queue), 0, holdMs, "force-timeout")
a.signalLocked()
}
func (a *Arbiter) isActive(leaseID uint64, leaseType LeaseType) bool {
a.mu.Lock()
defer a.mu.Unlock()
return a.findActiveLocked(leaseID, leaseType) != nil
}
func (a *Arbiter) findActiveLocked(leaseID uint64, leaseType LeaseType) *activeLease {
switch leaseType {
case LeaseTypeSession:
for _, s := range a.activeSessions {
if s.id == leaseID {
return s
}
}
case LeaseTypeOneShot:
if a.activeOneshot != nil && a.activeOneshot.id == leaseID {
return a.activeOneshot
}
case LeaseTypeTransport:
for _, t := range a.activeTransports {
if t.id == leaseID {
return t
}
}
}
return nil
}
func (a *Arbiter) removeActiveLocked(leaseID uint64, leaseType LeaseType) *activeLease {
switch leaseType {
case LeaseTypeSession:
for i, s := range a.activeSessions {
if s.id == leaseID {
a.activeSessions = append(a.activeSessions[:i], a.activeSessions[i+1:]...)
return s
}
}
case LeaseTypeOneShot:
if a.activeOneshot != nil && a.activeOneshot.id == leaseID {
released := a.activeOneshot
a.activeOneshot = nil
return released
}
case LeaseTypeTransport:
for i, t := range a.activeTransports {
if t.id == leaseID {
a.activeTransports = append(a.activeTransports[:i], a.activeTransports[i+1:]...)
return t
}
}
}
return nil
}
func (a *Arbiter) removeTicketLocked(ticketID uint64) bool {
for i := range a.queue {
if a.queue[i].id != ticketID {
continue
}
a.queue = append(a.queue[:i], a.queue[i+1:]...)
return true
}
return false
}
func (a *Arbiter) isIdleLocked() bool {
return a.activeOneshot == nil &&
len(a.activeTransports) == 0 &&
len(a.activeSessions) == 0 &&
len(a.activeBarriers) == 0 &&
len(a.queue) == 0
}
func (a *Arbiter) hasActiveTransportLocked() bool {
return len(a.activeTransports) > 0
}
func (a *Arbiter) hasActiveExclusiveTransportLocked() bool {
for _, transport := range a.activeTransports {
if transport.scope != TransportScopeQMIChannel {
return true
}
}
return false
}
func (a *Arbiter) activeQMITransportCountLocked() int {
count := 0
for _, transport := range a.activeTransports {
if transport.scope == TransportScopeQMIChannel {
count++
}
}
return count
}
func (a *Arbiter) hasActiveTransportOnChannelLocked(channel int) bool {
for _, transport := range a.activeTransports {
if transport.scope == TransportScopeQMIChannel && transport.channel == channel {
return true
}
}
return false
}
func (a *Arbiter) signalLocked() {
close(a.notifyC)
a.notifyC = make(chan struct{})
}
func shouldLogEvent(phase string, queueLen int, waitMs int64, holdMs int64) bool {
if phase == "timeout" || phase == "force-release" || strings.HasPrefix(phase, "barrier_") {
return true
}
if waitMs > 0 || holdMs >= 500 || queueLen > 1 {
return true
}
return false
}
func (a *Arbiter) logEvent(ticket waitTicket, phase string, queueLen int, waitMs int64, holdMs int64, reason string) {
if !shouldLogEvent(phase, queueLen, waitMs, holdMs) {
return
}
fields := []any{
"device", a.deviceID,
"owner", ticket.owner,
"mode", ticket.mode,
"class", string(ticket.class),
"channel", ticket.channel,
"scope", string(ticket.scope),
"lease_type", string(ticket.leaseType),
"phase", phase,
"queue_len", queueLen,
"wait_ms", waitMs,
"hold_ms", holdMs,
}
if reason != "" {
fields = append(fields, "reason", reason)
}
switch phase {
case "timeout", "force-release":
logger.Warn("APDU 仲裁事件", fields...)
default:
logger.Debug("APDU 仲裁事件", fields...)
}
}
func snapshotActiveLease(active *activeLease, now time.Time) SnapshotEntry {
return SnapshotEntry{
ID: active.id,
Owner: active.owner,
Mode: active.mode,
Class: active.class,
Channel: active.channel,
Scope: active.scope,
LeaseType: active.leaseType,
HoldMS: now.Sub(active.acquiredAt).Milliseconds(),
}
}
func normalizeRequest(req Request, leaseType LeaseType) Request {
req.Owner = normalizeOwner(req.Owner)
req.Mode = normalizeMode(req.Mode)
req.Class = normalizeClass(req.Class, leaseType)
req.Scope = normalizeTransportScope(req.Scope, req.Mode, req.Channel, leaseType)
return req
}
func normalizeTransportScope(scope TransportScope, mode string, channel int, leaseType LeaseType) TransportScope {
if leaseType != LeaseTypeTransport {
return TransportScopeExclusive
}
if scope == TransportScopeQMIChannel && mode == "QMI" && channel > 0 {
return TransportScopeQMIChannel
}
return TransportScopeExclusive
}
func normalizeClass(class APDUClass, leaseType LeaseType) APDUClass {
if class != "" {
return class
}
switch leaseType {
case LeaseTypeTransport:
return APDUClassEUICCWrite
case LeaseTypeOneShot:
return APDUClassUSIMAKA
default:
return APDUClassEUICCWrite
}
}
func normalizeOwner(owner string) string {
owner = strings.TrimSpace(owner)
if owner == "" {
return "unknown"
}
return owner
}
func normalizeMode(mode string) string {
mode = strings.ToUpper(strings.TrimSpace(mode))
if mode == "" {
return "UNKNOWN"
}
return mode
}
+781
View File
@@ -0,0 +1,781 @@
package apduarbiter
import (
"context"
"errors"
"sync"
"sync/atomic"
"testing"
"time"
)
func TestArbiterFIFO(t *testing.T) {
arb := New("dev-1", Options{})
first, err := arb.AcquireSession(context.Background(), "first", "AT")
if err != nil {
t.Fatalf("AcquireSession(first) failed: %v", err)
}
defer first.Release()
order := make(chan string, 2)
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
lease, acquireErr := arb.AcquireSession(context.Background(), "second", "AT")
if acquireErr != nil {
t.Errorf("AcquireSession(second) failed: %v", acquireErr)
return
}
order <- "second"
lease.Release()
}()
time.Sleep(20 * time.Millisecond)
go func() {
defer wg.Done()
lease, acquireErr := arb.AcquireSession(context.Background(), "third", "AT")
if acquireErr != nil {
t.Errorf("AcquireSession(third) failed: %v", acquireErr)
return
}
order <- "third"
lease.Release()
}()
time.Sleep(80 * time.Millisecond)
first.Release()
wg.Wait()
close(order)
got := make([]string, 0, 2)
for entry := range order {
got = append(got, entry)
}
if len(got) != 2 {
t.Fatalf("unexpected order length: %d", len(got))
}
if got[0] != "second" || got[1] != "third" {
t.Fatalf("unexpected FIFO order: %v", got)
}
}
func TestArbiterTimeout(t *testing.T) {
arb := New("dev-1", Options{})
lease, err := arb.AcquireSession(context.Background(), "holder", "QMI")
if err != nil {
t.Fatalf("AcquireSession(holder) failed: %v", err)
}
defer lease.Release()
ctx, cancel := context.WithTimeout(context.Background(), 40*time.Millisecond)
defer cancel()
_, err = arb.AcquireSession(ctx, "waiter", "QMI")
if err == nil {
t.Fatal("expected timeout error, got nil")
}
if !errors.Is(err, ErrAPDUBusy) {
t.Fatalf("expected ErrAPDUBusy, got %v", err)
}
}
func TestArbiterWaitIdle(t *testing.T) {
arb := New("dev-1", Options{})
lease, err := arb.AcquireSession(context.Background(), "holder", "AT")
if err != nil {
t.Fatalf("AcquireSession(holder) failed: %v", err)
}
done := make(chan struct{})
go func() {
defer close(done)
time.Sleep(60 * time.Millisecond)
lease.Release()
}()
ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
defer cancel()
if err := arb.WaitIdle(ctx); err != nil {
t.Fatalf("WaitIdle failed: %v", err)
}
<-done
}
func TestTransportUSIMAKAAcquiresBetweenEUICCTransports(t *testing.T) {
arb := New("dev-1", Options{})
first, err := arb.AcquireTransport(context.Background(), Request{
Owner: "download",
Mode: "QMI",
Class: APDUClassEUICCWrite,
})
if err != nil {
t.Fatalf("AcquireTransport(first) error=%v", err)
}
order := make(chan string, 2)
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
go func() {
lease, acquireErr := arb.AcquireTransport(ctx, Request{Owner: "download-next", Mode: "QMI", Class: APDUClassEUICCWrite})
if acquireErr != nil {
t.Errorf("AcquireTransport(euicc) error=%v", acquireErr)
return
}
order <- "euicc"
lease.Release()
}()
time.Sleep(20 * time.Millisecond)
go func() {
lease, acquireErr := arb.AcquireTransport(ctx, Request{Owner: "vowifi_aka", Mode: "QMI", Class: APDUClassUSIMAKA})
if acquireErr != nil {
t.Errorf("AcquireTransport(aka) error=%v", acquireErr)
return
}
order <- "aka"
lease.Release()
}()
time.Sleep(40 * time.Millisecond)
first.Release()
select {
case got := <-order:
if got != "aka" {
t.Fatalf("first acquired transport=%q want aka", got)
}
case <-time.After(time.Second):
t.Fatal("timed out waiting for first transport")
}
select {
case got := <-order:
if got != "euicc" {
t.Fatalf("second acquired transport=%q want euicc", got)
}
case <-time.After(time.Second):
t.Fatal("timed out waiting for second transport")
}
}
func TestTransportPriorityAgingPreventsEUICCStarvation(t *testing.T) {
arb := New("dev-1", Options{})
first, err := arb.AcquireTransport(context.Background(), Request{
Owner: "holder",
Mode: "QMI",
Class: APDUClassEUICCWrite,
})
if err != nil {
t.Fatalf("AcquireTransport(first) error=%v", err)
}
order := make(chan string, 2)
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
go func() {
lease, acquireErr := arb.AcquireTransport(ctx, Request{Owner: "aged-euicc", Mode: "QMI", Class: APDUClassEUICCWrite})
if acquireErr != nil {
t.Errorf("AcquireTransport(euicc) error=%v", acquireErr)
return
}
order <- "euicc"
lease.Release()
}()
time.Sleep(transportPriorityAging + 80*time.Millisecond)
go func() {
lease, acquireErr := arb.AcquireTransport(ctx, Request{Owner: "vowifi_aka", Mode: "QMI", Class: APDUClassUSIMAKA})
if acquireErr != nil {
t.Errorf("AcquireTransport(aka) error=%v", acquireErr)
return
}
order <- "aka"
lease.Release()
}()
time.Sleep(40 * time.Millisecond)
first.Release()
select {
case got := <-order:
if got != "euicc" {
t.Fatalf("first acquired transport=%q want euicc", got)
}
case <-time.After(time.Second):
t.Fatal("timed out waiting for first transport")
}
}
func TestQMIChannelTransportsAcquireConcurrentlyAcrossChannels(t *testing.T) {
arb := New("dev-1", Options{MaxQMITransports: 3})
first, err := arb.AcquireTransport(context.Background(), Request{
Owner: "profile-a",
Mode: "QMI",
Class: APDUClassEUICCWrite,
Channel: 2,
Scope: TransportScopeQMIChannel,
})
if err != nil {
t.Fatalf("AcquireTransport(first) error=%v", err)
}
defer first.Release()
ctx, cancel := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancel()
second, err := arb.AcquireTransport(ctx, Request{
Owner: "profile-b",
Mode: "QMI",
Class: APDUClassEUICCWrite,
Channel: 3,
Scope: TransportScopeQMIChannel,
})
if err != nil {
t.Fatalf("AcquireTransport(second different channel) error=%v", err)
}
defer second.Release()
if stats := arb.Stats(); stats.ActiveTransports != 2 {
t.Fatalf("ActiveTransports=%d want 2: %+v", stats.ActiveTransports, stats)
}
}
func TestQMIChannelTransportSerializesSameChannel(t *testing.T) {
arb := New("dev-1", Options{MaxQMITransports: 3})
first, err := arb.AcquireTransport(context.Background(), Request{
Owner: "profile-a",
Mode: "QMI",
Class: APDUClassEUICCWrite,
Channel: 2,
Scope: TransportScopeQMIChannel,
})
if err != nil {
t.Fatalf("AcquireTransport(first) error=%v", err)
}
defer first.Release()
acquired := make(chan struct{})
done := make(chan struct{})
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
go func() {
defer close(done)
lease, acquireErr := arb.AcquireTransport(ctx, Request{
Owner: "profile-a-next",
Mode: "QMI",
Class: APDUClassEUICCWrite,
Channel: 2,
Scope: TransportScopeQMIChannel,
})
if acquireErr != nil {
t.Errorf("AcquireTransport(waiter) error=%v", acquireErr)
return
}
close(acquired)
lease.Release()
}()
select {
case <-acquired:
t.Fatal("same-channel QMI transport acquired while channel was active")
case <-time.After(80 * time.Millisecond):
}
first.Release()
select {
case <-acquired:
case <-time.After(time.Second):
t.Fatal("same-channel QMI transport did not acquire after release")
}
<-done
}
func TestExclusiveTransportWaitsForActiveQMIChannelTransport(t *testing.T) {
arb := New("dev-1", Options{MaxQMITransports: 3})
first, err := arb.AcquireTransport(context.Background(), Request{
Owner: "profile-a",
Mode: "QMI",
Class: APDUClassEUICCWrite,
Channel: 2,
Scope: TransportScopeQMIChannel,
})
if err != nil {
t.Fatalf("AcquireTransport(first) error=%v", err)
}
defer first.Release()
acquired := make(chan struct{})
done := make(chan struct{})
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
go func() {
defer close(done)
lease, acquireErr := arb.AcquireTransport(ctx, Request{
Owner: "qmi_channel_close",
Mode: "QMI",
Class: APDUClassRecovery,
Channel: 2,
})
if acquireErr != nil {
t.Errorf("AcquireTransport(exclusive) error=%v", acquireErr)
return
}
close(acquired)
lease.Release()
}()
select {
case <-acquired:
t.Fatal("exclusive transport acquired while QMI channel transport was active")
case <-time.After(80 * time.Millisecond):
}
first.Release()
select {
case <-acquired:
case <-time.After(time.Second):
t.Fatal("exclusive transport did not acquire after active QMI transport release")
}
<-done
}
func TestQueuedExclusiveTransportGatesLaterQMIChannelTransport(t *testing.T) {
arb := New("dev-1", Options{MaxQMITransports: 3})
first, err := arb.AcquireTransport(context.Background(), Request{
Owner: "profile-a",
Mode: "QMI",
Class: APDUClassEUICCWrite,
Channel: 2,
Scope: TransportScopeQMIChannel,
})
if err != nil {
t.Fatalf("AcquireTransport(first) error=%v", err)
}
defer first.Release()
exclusiveAcquired := make(chan struct{})
releaseExclusive := make(chan struct{})
exclusiveDone := make(chan struct{})
qmiAcquired := make(chan struct{})
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
go func() {
defer close(exclusiveDone)
lease, acquireErr := arb.AcquireTransport(ctx, Request{
Owner: "qmi_channel_close",
Mode: "QMI",
Class: APDUClassRecovery,
Channel: 2,
})
if acquireErr != nil {
t.Errorf("AcquireTransport(exclusive) error=%v", acquireErr)
return
}
close(exclusiveAcquired)
<-releaseExclusive
lease.Release()
}()
time.Sleep(20 * time.Millisecond)
go func() {
lease, acquireErr := arb.AcquireTransport(ctx, Request{
Owner: "profile-b",
Mode: "QMI",
Class: APDUClassEUICCWrite,
Channel: 3,
Scope: TransportScopeQMIChannel,
})
if acquireErr != nil {
return
}
close(qmiAcquired)
lease.Release()
}()
select {
case <-qmiAcquired:
t.Fatal("later QMI channel transport passed queued exclusive transport")
case <-time.After(80 * time.Millisecond):
}
first.Release()
select {
case <-exclusiveAcquired:
case <-time.After(time.Second):
t.Fatal("exclusive transport did not acquire after active QMI transport release")
}
select {
case <-qmiAcquired:
t.Fatal("later QMI channel transport acquired while exclusive transport was active")
case <-time.After(80 * time.Millisecond):
}
close(releaseExclusive)
<-exclusiveDone
select {
case <-qmiAcquired:
case <-time.After(time.Second):
t.Fatal("later QMI channel transport did not acquire after exclusive transport release")
}
}
func TestSwitchBarrierBlocksUSIMAKAAndAllowsEUICC(t *testing.T) {
arb := New("dev-1", Options{})
first, err := arb.AcquireTransport(context.Background(), Request{Owner: "holder", Mode: "QMI", Class: APDUClassEUICCWrite})
if err != nil {
t.Fatalf("AcquireTransport(first) error=%v", err)
}
barrierCh := make(chan *Barrier, 1)
errCh := make(chan error, 1)
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
go func() {
barrier, beginErr := arb.BeginBarrier(ctx, Request{Owner: "switch", Mode: "QMI", Class: APDUClassSwitchBarrier}, BarrierPolicy{})
if beginErr != nil {
errCh <- beginErr
return
}
barrierCh <- barrier
}()
waitForQueuedClass(t, arb, APDUClassSwitchBarrier, LeaseTypeBarrier)
akaAcquired := make(chan struct{})
go func() {
lease, acquireErr := arb.AcquireTransport(ctx, Request{Owner: "vowifi_aka", Mode: "QMI", Class: APDUClassUSIMAKA})
if acquireErr != nil {
return
}
close(akaAcquired)
lease.Release()
}()
first.Release()
var barrier *Barrier
select {
case barrier = <-barrierCh:
case err := <-errCh:
t.Fatalf("BeginBarrier() error=%v", err)
case <-time.After(time.Second):
t.Fatal("timed out waiting for barrier")
}
defer barrier.Release()
select {
case <-akaAcquired:
t.Fatal("USIMAKA acquired while switch barrier was active")
default:
}
euicc, err := arb.AcquireTransport(ctx, Request{Owner: "switch-apdu", Mode: "QMI", Class: APDUClassEUICCWrite})
if err != nil {
t.Fatalf("EUICC transport under barrier error=%v", err)
}
euicc.Release()
select {
case <-akaAcquired:
t.Fatal("USIMAKA acquired after unrelated EUICC transport while barrier active")
default:
}
barrier.Release()
select {
case <-akaAcquired:
case <-time.After(time.Second):
t.Fatal("USIMAKA did not acquire after barrier release")
}
}
func waitForQueuedClass(t *testing.T, arb *Arbiter, class APDUClass, leaseType LeaseType) {
t.Helper()
deadline := time.Now().Add(time.Second)
for {
for _, entry := range arb.Snapshot().Queue {
if entry.Class == class && entry.LeaseType == leaseType {
return
}
}
if time.Now().After(deadline) {
t.Fatalf("timed out waiting for queued class=%s lease_type=%s", class, leaseType)
}
time.Sleep(time.Millisecond)
}
}
func TestSnapshotReportsTransportAndBarrier(t *testing.T) {
arb := New("dev-1", Options{})
barrier, err := arb.BeginBarrier(context.Background(), Request{Owner: "switch", Mode: "QMI", Class: APDUClassSwitchBarrier}, BarrierPolicy{})
if err != nil {
t.Fatalf("BeginBarrier() error=%v", err)
}
defer barrier.Release()
lease, err := arb.AcquireTransport(context.Background(), Request{Owner: "switch-apdu", Mode: "QMI", Class: APDUClassEUICCWrite, Channel: 2})
if err != nil {
t.Fatalf("AcquireTransport() error=%v", err)
}
defer lease.Release()
snap := arb.Snapshot()
if len(snap.Active) != 2 {
t.Fatalf("active entries=%d want 2: %+v", len(snap.Active), snap.Active)
}
}
func TestLeaseTouchExtendsSessionWatchdog(t *testing.T) {
arb := New("dev-1", Options{MaxLeaseHold: 40 * time.Millisecond})
lease, err := arb.AcquireSession(context.Background(), "holder", "QMI")
if err != nil {
t.Fatalf("AcquireSession(holder) failed: %v", err)
}
defer lease.Release()
acquired := make(chan struct{})
done := make(chan struct{})
ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
defer cancel()
go func() {
defer close(done)
waiter, acquireErr := arb.AcquireOneShot(ctx, "waiter", "AT")
if acquireErr != nil {
return
}
close(acquired)
waiter.Release()
}()
deadline := time.After(130 * time.Millisecond)
ticker := time.NewTicker(15 * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-ticker.C:
lease.Touch()
case <-deadline:
goto touchedEnough
}
}
touchedEnough:
select {
case <-acquired:
t.Fatal("oneshot acquired while session lease was being touched")
default:
}
stats := arb.Stats()
if stats.ForcedReleases != 0 {
t.Fatalf("ForcedReleases=%d want 0", stats.ForcedReleases)
}
if stats.ActiveSessions != 1 || stats.ActiveOneshot {
t.Fatalf("unexpected stats after touch: %+v", stats)
}
lease.Release()
select {
case <-acquired:
case <-time.After(150 * time.Millisecond):
t.Fatal("oneshot did not acquire after session release")
}
<-done
}
func TestLeaseTouchExtendsOneShotWatchdog(t *testing.T) {
arb := New("dev-1", Options{MaxLeaseHold: 40 * time.Millisecond})
lease, err := arb.AcquireOneShot(context.Background(), "holder", "AT")
if err != nil {
t.Fatalf("AcquireOneShot(holder) failed: %v", err)
}
defer lease.Release()
deadline := time.After(130 * time.Millisecond)
ticker := time.NewTicker(15 * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-ticker.C:
lease.Touch()
case <-deadline:
stats := arb.Stats()
if stats.ForcedReleases != 0 {
t.Fatalf("ForcedReleases=%d want 0", stats.ForcedReleases)
}
if !stats.ActiveOneshot || stats.ActiveSessions != 0 {
t.Fatalf("unexpected stats after touch: %+v", stats)
}
return
}
}
}
func TestLeaseWatchdogForceReleasesWithoutTouch(t *testing.T) {
tests := []struct {
name string
acquire func(*Arbiter) (*Lease, error)
}{
{
name: "session",
acquire: func(arb *Arbiter) (*Lease, error) {
return arb.AcquireSession(context.Background(), "holder", "QMI")
},
},
{
name: "oneshot",
acquire: func(arb *Arbiter) (*Lease, error) {
return arb.AcquireOneShot(context.Background(), "holder", "AT")
},
},
{
name: "transport",
acquire: func(arb *Arbiter) (*Lease, error) {
return arb.AcquireTransport(context.Background(), Request{Owner: "holder", Mode: "QMI", Class: APDUClassEUICCWrite})
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
arb := New("dev-1", Options{MaxLeaseHold: 30 * time.Millisecond})
lease, err := tt.acquire(arb)
if err != nil {
t.Fatalf("acquire failed: %v", err)
}
defer lease.Release()
ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond)
defer cancel()
if err := arb.WaitIdle(ctx); err != nil {
t.Fatalf("WaitIdle() error=%v", err)
}
stats := arb.Stats()
if stats.ForcedReleases != 1 {
t.Fatalf("ForcedReleases=%d want 1", stats.ForcedReleases)
}
if stats.ActiveSessions != 0 || stats.ActiveOneshot || stats.ActiveTransport {
t.Fatalf("unexpected active lease stats: %+v", stats)
}
if lease.Active() {
t.Fatal("lease.Active()=true after watchdog force release, want false")
}
if lease.Touch() {
t.Fatal("lease.Touch()=true after watchdog force release, want false")
}
})
}
}
func TestShouldLogEvent(t *testing.T) {
tests := []struct {
name string
phase string
queueLen int
waitMs int64
holdMs int64
want bool
}{
{name: "suppress zero wait acquire", phase: "acquire", queueLen: 0, waitMs: 0, holdMs: 0, want: false},
{name: "suppress short release", phase: "release", queueLen: 0, waitMs: 0, holdMs: 27, want: false},
{name: "log waited event", phase: "acquire", queueLen: 0, waitMs: 1, holdMs: 0, want: true},
{name: "suppress ordinary qmi release", phase: "release", queueLen: 0, waitMs: 0, holdMs: 95, want: false},
{name: "log long hold release", phase: "release", queueLen: 0, waitMs: 0, holdMs: 500, want: true},
{name: "log deeper queue", phase: "wait", queueLen: 2, waitMs: 0, holdMs: 0, want: true},
{name: "always log timeout", phase: "timeout", queueLen: 0, waitMs: 0, holdMs: 0, want: true},
{name: "always log force release", phase: "force-release", queueLen: 0, waitMs: 0, holdMs: 0, want: true},
{name: "boundary suppress single queued wait", phase: "wait", queueLen: 1, waitMs: 0, holdMs: 0, want: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := shouldLogEvent(tt.phase, tt.queueLen, tt.waitMs, tt.holdMs)
if got != tt.want {
t.Fatalf("shouldLogEvent(%q, %d, %d, %d) = %v, want %v", tt.phase, tt.queueLen, tt.waitMs, tt.holdMs, got, tt.want)
}
})
}
}
func TestSIMAuthReadyGateCoalescesConcurrentProbes(t *testing.T) {
arb := New("dev-1", Options{})
started := make(chan struct{}, 1)
release := make(chan struct{})
errs := make(chan error, 2)
var probes atomic.Int32
probe := func(ctx context.Context) error {
probes.Add(1)
select {
case started <- struct{}{}:
default:
}
select {
case <-ctx.Done():
return ctx.Err()
case <-release:
return nil
}
}
for i := 0; i < 2; i++ {
go func() {
errs <- arb.WaitSIMAuthReady(context.Background(), probe)
}()
}
select {
case <-started:
case <-time.After(time.Second):
t.Fatal("SIMAuth probe did not start")
}
time.Sleep(20 * time.Millisecond)
close(release)
for i := 0; i < 2; i++ {
select {
case err := <-errs:
if err != nil {
t.Fatalf("WaitSIMAuthReady() error=%v", err)
}
case <-time.After(time.Second):
t.Fatal("WaitSIMAuthReady() did not return")
}
}
if got := probes.Load(); got != 1 {
t.Fatalf("probe count=%d want 1", got)
}
if err := arb.WaitSIMAuthReady(context.Background(), func(context.Context) error {
probes.Add(1)
return nil
}); err != nil {
t.Fatalf("cached WaitSIMAuthReady() error=%v", err)
}
if got := probes.Load(); got != 1 {
t.Fatalf("probe count after cached wait=%d want 1", got)
}
}
func TestSIMAuthReadyGateInvalidationForcesNewProbe(t *testing.T) {
arb := New("dev-1", Options{})
var probes atomic.Int32
probe := func(context.Context) error {
probes.Add(1)
return nil
}
if err := arb.WaitSIMAuthReady(context.Background(), probe); err != nil {
t.Fatalf("first WaitSIMAuthReady() error=%v", err)
}
if err := arb.WaitSIMAuthReady(context.Background(), probe); err != nil {
t.Fatalf("cached WaitSIMAuthReady() error=%v", err)
}
if got := probes.Load(); got != 1 {
t.Fatalf("probe count before invalidate=%d want 1", got)
}
arb.InvalidateSIMAuthReady("switch")
if err := arb.WaitSIMAuthReady(context.Background(), probe); err != nil {
t.Fatalf("post-invalidate WaitSIMAuthReady() error=%v", err)
}
if got := probes.Load(); got != 2 {
t.Fatalf("probe count after invalidate=%d want 2", got)
}
}
+115
View File
@@ -0,0 +1,115 @@
package apduarbiter
import (
"context"
"errors"
"fmt"
"strings"
"github.com/iniwex5/vohive/pkg/logger"
)
var ErrSIMAuthNotReady = errors.New("simauth not ready")
type SIMAuthReadyProbe func(context.Context) error
type simAuthReadyState struct {
generation uint64
ready bool
probing bool
waitC chan struct{}
lastErr error
reason string
}
func (a *Arbiter) InvalidateSIMAuthReady(reason string) {
if a == nil {
return
}
reason = strings.TrimSpace(reason)
if reason == "" {
reason = "unknown"
}
a.mu.Lock()
a.simAuthReady.generation++
a.simAuthReady.ready = false
a.simAuthReady.lastErr = nil
a.simAuthReady.reason = reason
generation := a.simAuthReady.generation
probing := a.simAuthReady.probing
a.mu.Unlock()
logger.Debug("SIMAuth readiness invalidated",
"device", a.deviceID,
"reason", reason,
"generation", generation,
"probing", probing)
}
func (a *Arbiter) WaitSIMAuthReady(ctx context.Context, probe SIMAuthReadyProbe) error {
if a == nil {
return fmt.Errorf("%w: arbiter nil", ErrSIMAuthNotReady)
}
if probe == nil {
return fmt.Errorf("%w: probe nil", ErrSIMAuthNotReady)
}
if ctx == nil {
ctx = context.Background()
}
for {
if err := ctx.Err(); err != nil {
return fmt.Errorf("%w: %v", ErrSIMAuthNotReady, err)
}
a.mu.Lock()
if a.simAuthReady.ready {
a.mu.Unlock()
return nil
}
if a.simAuthReady.probing {
waitC := a.simAuthReady.waitC
if waitC == nil {
waitC = make(chan struct{})
a.simAuthReady.waitC = waitC
}
a.mu.Unlock()
select {
case <-ctx.Done():
return fmt.Errorf("%w: %v", ErrSIMAuthNotReady, ctx.Err())
case <-waitC:
continue
}
}
generation := a.simAuthReady.generation
waitC := make(chan struct{})
a.simAuthReady.probing = true
a.simAuthReady.waitC = waitC
a.mu.Unlock()
err := probe(ctx)
a.mu.Lock()
stale := a.simAuthReady.generation != generation
if !stale {
a.simAuthReady.ready = err == nil
a.simAuthReady.lastErr = err
}
if a.simAuthReady.waitC == waitC {
close(waitC)
a.simAuthReady.waitC = nil
}
a.simAuthReady.probing = false
a.mu.Unlock()
if err != nil {
return fmt.Errorf("%w: %v", ErrSIMAuthNotReady, err)
}
if stale {
continue
}
return nil
}
}
+64
View File
@@ -0,0 +1,64 @@
package api
import (
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
"github.com/iniwex5/vohive/internal/config"
)
// 登录限流必须按真实客户端 IP 计数,而不是按客户端可随意伪造的
// X-Forwarded-For 头计数,否则暴力破解限流形同虚设。
func TestLoginRateLimitIgnoresSpoofedForwardedFor(t *testing.T) {
gin.SetMode(gin.TestMode)
s := &Server{
auth: config.WebConfig{Username: "admin", Password: "correct-horse-battery-staple"},
loginAttempts: make(map[string]loginAttempt),
}
r := s.newRouter()
body := `{"username":"admin","password":"wrong"}`
for i := 0; i < 10; i++ {
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/auth/login", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Forwarded-For", fmt.Sprintf("10.0.0.%d", i)) // 每次伪造不同的来源 IP
req.RemoteAddr = "192.0.2.1:54321" // 真实连接对端始终相同
r.ServeHTTP(w, req)
if w.Code != http.StatusUnauthorized {
t.Fatalf("attempt %d: code=%d want 401, body=%s", i, w.Code, w.Body.String())
}
}
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/auth/login", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Forwarded-For", "10.0.0.99") // 第 11 次,依然是新的伪造 IP
req.RemoteAddr = "192.0.2.1:54321"
r.ServeHTTP(w, req)
if w.Code != http.StatusTooManyRequests {
t.Fatalf("11th attempt: code=%d want 429 —— 限流应按真实 RemoteAddr 计数,不应被伪造的 X-Forwarded-For 绕过, body=%s", w.Code, w.Body.String())
}
}
func TestCheckPasswordPlaintextFallbackStillMatchesCorrectly(t *testing.T) {
if !checkPassword("plain-secret", "plain-secret") {
t.Fatal("相同的明文密码应当匹配")
}
if checkPassword("plain-secret", "wrong-secret") {
t.Fatal("不同明文密码不应匹配")
}
if checkPassword("plain-secret", "plain-secre") {
t.Fatal("长度不同的明文密码不应匹配")
}
if checkPassword("plain-secret", "") {
t.Fatal("空密码不应匹配非空存储密码")
}
}
+106
View File
@@ -0,0 +1,106 @@
package api
import (
"errors"
"fmt"
"net/http"
"github.com/gin-gonic/gin"
"github.com/iniwex5/vohive/internal/db"
)
// patchCardPolicyForDevice 解析设备当前 ICCID,对 card_policies 行执行原地修改并落库。
// mutate 在 resolve 后的副本上改字段(source 会被强制为 "user")。
// applied=false 且 err=nil 表示设备当前无 ICCID(离线/未识别),跳过落库。
func (s *Server) patchCardPolicyForDevice(deviceID string, mutate func(*db.CardPolicy)) (iccid string, applied bool, err error) {
worker := s.pool.GetWorker(deviceID)
if worker == nil {
return "", false, fmt.Errorf("设备未找到")
}
iccid = worker.CurrentICCID()
if iccid == "" {
return "", false, nil
}
p, err := db.ResolveCardPolicy(iccid)
if err != nil {
return iccid, false, fmt.Errorf("获取卡策略失败: %w", err)
}
mutate(&p)
p.Source = "user"
db.NormalizeCardPolicy(&p)
if err := db.UpsertCardPolicy(p); err != nil {
return iccid, false, fmt.Errorf("保存卡策略失败: %w", err)
}
return iccid, true, nil
}
func (s *Server) handleGetCardPolicy(c *gin.Context) {
iccid := c.Param("iccid")
pol, err := db.GetCardPolicy(iccid)
if errors.Is(err, db.ErrCardPolicyNotFound) {
// 未建档则返回默认模板(不落库,读端点保持只读语义)
c.JSON(http.StatusOK, db.DefaultCardPolicy(iccid))
return
}
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, pol)
}
func (s *Server) handleListCardPolicies(c *gin.Context) {
var out []db.CardPolicy
if db.DB != nil {
if err := db.DB.Order("updated_at desc").Find(&out).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
}
c.JSON(http.StatusOK, gin.H{"policies": out})
}
func (s *Server) handlePutCardPolicy(c *gin.Context) {
iccid := c.Param("iccid")
var req struct {
NetworkEnabled *bool `json:"network_enabled"`
VoWiFiEnabled *bool `json:"vowifi_enabled"`
AirplaneEnabled *bool `json:"airplane_enabled"`
IPVersion string `json:"ip_version"`
APN string `json:"apn"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// 查出当前策略(查不到则用默认值)
pol, err := db.GetCardPolicy(iccid)
if err != nil {
pol = db.DefaultCardPolicy(iccid)
}
if req.NetworkEnabled != nil {
pol.NetworkEnabled = *req.NetworkEnabled
}
if req.VoWiFiEnabled != nil {
pol.VoWiFiEnabled = *req.VoWiFiEnabled
}
if req.AirplaneEnabled != nil {
pol.AirplaneEnabled = *req.AirplaneEnabled
}
if req.IPVersion != "" {
pol.IPVersion = req.IPVersion
}
if req.APN != "" {
pol.APN = req.APN
}
pol.Source = "user"
if err := db.UpsertCardPolicy(pol); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, pol)
}
+274
View File
@@ -0,0 +1,274 @@
package api
import (
"encoding/json"
"net/http"
"net/http/httptest"
"path/filepath"
"reflect"
"strings"
"testing"
"unsafe"
"github.com/gin-gonic/gin"
"github.com/iniwex5/vohive/internal/config"
"github.com/iniwex5/vohive/internal/db"
"github.com/iniwex5/vohive/internal/device"
)
// injectWorker 通过 unsafe 反射将 worker 注入到 pool 的内部 workers map,
// 用于无需完整启动流程的测试场景。
func injectWorker(p *device.Pool, w *device.Worker) {
pv := reflect.ValueOf(p).Elem().FieldByName("workers")
m := reflect.NewAt(pv.Type(), unsafe.Pointer(pv.UnsafeAddr())).Elem()
m.SetMapIndex(reflect.ValueOf(w.ID), reflect.ValueOf(w))
}
func openTestDB(t *testing.T) {
t.Helper()
if err := db.Init(filepath.Join(t.TempDir(), "test.db")); err != nil {
t.Fatalf("Init() error=%v", err)
}
t.Cleanup(func() {
if db.DB != nil {
if sqlDB, err := db.DB.DB(); err == nil && sqlDB != nil {
_ = sqlDB.Close()
}
}
})
}
func TestGetCardPolicyEndpoint(t *testing.T) {
gin.SetMode(gin.TestMode)
openTestDB(t)
_ = db.UpsertCardPolicy(db.CardPolicy{ICCID: "8986004", NetworkEnabled: true, IPVersion: "v4", Source: "user"})
s := &Server{}
r := gin.Default()
r.GET("/api/cards/:iccid/policy", s.handleGetCardPolicy)
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/cards/8986004/policy", nil)
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("code=%d body=%s", w.Code, w.Body.String())
}
var got db.CardPolicy
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
t.Fatal(err)
}
if !got.NetworkEnabled {
t.Fatalf("payload 错: %+v", got)
}
}
func TestPutCardPolicyEndpoint(t *testing.T) {
gin.SetMode(gin.TestMode)
openTestDB(t)
s := &Server{
pool: device.NewPool(&config.Config{}),
}
r := gin.Default()
r.PUT("/api/cards/:iccid/policy", s.handlePutCardPolicy)
body := `{"network_enabled":true,"vowifi_enabled":true,"ip_version":"v4v6","apn":"ims"}`
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPut, "/api/cards/8986005/policy", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("code=%d body=%s", w.Code, w.Body.String())
}
got, _ := db.GetCardPolicy("8986005")
if !got.NetworkEnabled || !got.VoWiFiEnabled || got.IPVersion != "v4v6" || got.APN != "ims" {
t.Fatalf("未成功更新: %+v", got)
}
}
// TestPatchCardPolicyForDevice 验证 patchCardPolicyForDevice helper 正确解析 ICCID 并落库。
func TestPatchCardPolicyForDevice(t *testing.T) {
gin.SetMode(gin.TestMode)
openTestDB(t)
p := device.NewPool(&config.Config{})
w := &device.Worker{ID: "wwan-patch"}
setNestedPrivateField(t, w, []string{"state", "Identity", "ICCID"}, "8986patch001")
injectWorker(p, w)
s := &Server{pool: p}
iccid, applied, err := s.patchCardPolicyForDevice("wwan-patch", func(pol *db.CardPolicy) {
pol.NetworkEnabled = true
pol.IPVersion = "v4v6"
pol.APN = "ims"
})
if err != nil {
t.Fatalf("error=%v", err)
}
if !applied {
t.Fatalf("expected applied=true")
}
if iccid != "8986patch001" {
t.Fatalf("iccid=%q", iccid)
}
got, err := db.GetCardPolicy("8986patch001")
if err != nil {
t.Fatal(err)
}
if !got.NetworkEnabled || got.IPVersion != "v4v6" || got.APN != "ims" {
t.Fatalf("card policy mismatch: %+v", got)
}
if got.Source != "user" {
t.Fatalf("source=%q want user", got.Source)
}
}
// TestPatchCardPolicyForDeviceNoICCID 验证设备无 ICCID 时 applied=false 且不报错。
func TestPatchCardPolicyForDeviceNoICCID(t *testing.T) {
gin.SetMode(gin.TestMode)
openTestDB(t)
p := device.NewPool(&config.Config{})
w := &device.Worker{ID: "wwan-nocard"}
// 不设置 ICCID,模拟无卡状态
injectWorker(p, w)
s := &Server{pool: p}
iccid, applied, err := s.patchCardPolicyForDevice("wwan-nocard", func(pol *db.CardPolicy) {
pol.NetworkEnabled = true
})
if err != nil {
t.Fatalf("error=%v", err)
}
if applied {
t.Fatalf("expected applied=false when no ICCID")
}
if iccid != "" {
t.Fatalf("iccid=%q want empty", iccid)
}
}
// TestPatchCardPolicyVoWiFiKeepsAirplaneIntent 验证开 VoWiFi 不再强制 airplane=true:
// airplane 反映用户的纯飞行意图,独立于 vowifi。
func TestPatchCardPolicyVoWiFiKeepsAirplaneIntent(t *testing.T) {
gin.SetMode(gin.TestMode)
openTestDB(t)
p := device.NewPool(&config.Config{})
w := &device.Worker{ID: "wwan-vowifi"}
setNestedPrivateField(t, w, []string{"state", "Identity", "ICCID"}, "8986vowifi01")
injectWorker(p, w)
s := &Server{pool: p}
// 从在线开 VoWiFi(飞行意图为 false):airplane 应保持 false,不被强制为 true。
_, _, err := s.patchCardPolicyForDevice("wwan-vowifi", vowifiEnablePolicyMutation)
if err != nil {
t.Fatalf("error=%v", err)
}
got, _ := db.GetCardPolicy("8986vowifi01")
if !got.VoWiFiEnabled || got.AirplaneEnabled {
t.Fatalf("开 VoWiFi 不应强制 airplane=true: vowifi=%v airplane=%v", got.VoWiFiEnabled, got.AirplaneEnabled)
}
}
// TestVoWiFiToggleCyclePreservesAirplaneIntent 复现并锁定 bug 修复:
// 先开飞行 → 开 VoWiFi → 关 VoWiFi,应回退到飞行(airplane 意图被保留)。
func TestVoWiFiToggleCyclePreservesAirplaneIntent(t *testing.T) {
gin.SetMode(gin.TestMode)
openTestDB(t)
p := device.NewPool(&config.Config{})
w := &device.Worker{ID: "wwan-cycle"}
setNestedPrivateField(t, w, []string{"state", "Identity", "ICCID"}, "8986cycle001")
injectWorker(p, w)
s := &Server{pool: p}
// 1) 用户先开飞行
if _, _, err := s.patchCardPolicyForDevice("wwan-cycle", func(pol *db.CardPolicy) {
pol.AirplaneEnabled = true
pol.VoWiFiEnabled = false
pol.NetworkEnabled = false
}); err != nil {
t.Fatalf("开飞行 error=%v", err)
}
// 2) 开 VoWiFi(落库副作用:只置 vowifi)
if _, _, err := s.patchCardPolicyForDevice("wwan-cycle", vowifiEnablePolicyMutation); err != nil {
t.Fatalf("开 vowifi error=%v", err)
}
mid, _ := db.GetCardPolicy("8986cycle001")
if !mid.VoWiFiEnabled || !mid.AirplaneEnabled {
t.Fatalf("开 VoWiFi 期间飞行意图应保留: %+v", mid)
}
// 3) 关 VoWiFi(落库副作用:只清 vowifi),应回退到飞行
if _, _, err := s.patchCardPolicyForDevice("wwan-cycle", vowifiDisablePolicyMutation); err != nil {
t.Fatalf("关 vowifi error=%v", err)
}
got, _ := db.GetCardPolicy("8986cycle001")
if got.VoWiFiEnabled || !got.AirplaneEnabled {
t.Fatalf("关 VoWiFi 后应回退到飞行模式: vowifi=%v airplane=%v", got.VoWiFiEnabled, got.AirplaneEnabled)
}
}
// TestPatchCardPolicyAirplaneMutualExclusion 验证“开飞行模式”落库时与 network/vowifi 互斥
// (等价于 handleDeviceMgmtSetFlightMode 开飞行时的落库副作用)。
func TestPatchCardPolicyAirplaneMutualExclusion(t *testing.T) {
gin.SetMode(gin.TestMode)
openTestDB(t)
// 预置:network 开着、vowifi 开着
_ = db.UpsertCardPolicy(db.CardPolicy{ICCID: "8986air001", NetworkEnabled: true, VoWiFiEnabled: true, Source: "user"})
p := device.NewPool(&config.Config{})
w := &device.Worker{ID: "wwan-air"}
setNestedPrivateField(t, w, []string{"state", "Identity", "ICCID"}, "8986air001")
injectWorker(p, w)
s := &Server{pool: p}
// 开飞行:airplane=on,且互斥关 network/vowifi
_, applied, err := s.patchCardPolicyForDevice("wwan-air", func(pol *db.CardPolicy) {
pol.AirplaneEnabled = true
pol.VoWiFiEnabled = false
pol.NetworkEnabled = false
})
if err != nil || !applied {
t.Fatalf("applied=%v err=%v", applied, err)
}
got, _ := db.GetCardPolicy("8986air001")
if !got.AirplaneEnabled || got.NetworkEnabled || got.VoWiFiEnabled {
t.Fatalf("开飞行应互斥关 network/vowifi: %+v", got)
}
}
func TestPutCardPolicyAirplaneField(t *testing.T) {
gin.SetMode(gin.TestMode)
openTestDB(t)
// 预置一行 network=true,验证只 PUT airplane 时 network 不被指针语义覆盖
_ = db.UpsertCardPolicy(db.CardPolicy{ICCID: "8986air777", NetworkEnabled: true, IPVersion: "v4", Source: "user"})
s := &Server{pool: device.NewPool(&config.Config{})}
r := gin.Default()
r.PUT("/api/cards/:iccid/policy", s.handlePutCardPolicy)
body := `{"airplane_enabled":true}`
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPut, "/api/cards/8986air777/policy", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("code=%d body=%s", w.Code, w.Body.String())
}
got, _ := db.GetCardPolicy("8986air777")
if !got.AirplaneEnabled {
t.Fatalf("airplane 未写入: %+v", got)
}
if !got.NetworkEnabled {
t.Fatalf("未传的 network 被错误覆盖: %+v", got)
}
}
+54
View File
@@ -0,0 +1,54 @@
package api
import (
"errors"
"net/http"
"github.com/gin-gonic/gin"
"github.com/iniwex5/vohive/internal/e911"
)
func e911ErrorStatus(err error) int {
switch {
case errors.Is(err, e911.ErrNotSupported), errors.Is(err, e911.ErrProviderUnavailable):
return http.StatusBadRequest
case errors.Is(err, e911.ErrIdentityUnavailable):
return http.StatusConflict
case errors.Is(err, e911.ErrChallengeIncomplete):
return http.StatusNotImplemented
case errors.Is(err, e911.ErrCarrierWebsheetAbsent):
return http.StatusBadGateway
default:
return http.StatusInternalServerError
}
}
func e911ErrorCode(err error) string {
switch {
case errors.Is(err, e911.ErrNotSupported):
return "e911_not_supported"
case errors.Is(err, e911.ErrIdentityUnavailable):
return "e911_identity_unavailable"
case errors.Is(err, e911.ErrProviderUnavailable):
return "e911_provider_unavailable"
case errors.Is(err, e911.ErrChallengeIncomplete):
return "e911_challenge_not_implemented"
case errors.Is(err, e911.ErrCarrierWebsheetAbsent):
return "e911_websheet_unavailable"
default:
return "e911_start_failed"
}
}
func (s *Server) handleDeviceE911Websheet(c *gin.Context) {
coord := &e911.Coordinator{
Pool: s.pool,
Websheets: s.websheets,
}
info, err := coord.StartWebsheet(c.Request.Context(), deviceIDParam(c))
if err != nil {
c.JSON(e911ErrorStatus(err), gin.H{"status": "error", "code": e911ErrorCode(err), "message": err.Error()})
return
}
c.JSON(http.StatusCreated, info)
}
+28
View File
@@ -0,0 +1,28 @@
package api
import (
"errors"
"net/http"
"testing"
"github.com/iniwex5/vohive/internal/e911"
)
func TestE911ErrorStatus(t *testing.T) {
tests := []struct {
err error
want int
}{
{err: e911.ErrNotSupported, want: http.StatusBadRequest},
{err: e911.ErrProviderUnavailable, want: http.StatusBadRequest},
{err: e911.ErrIdentityUnavailable, want: http.StatusConflict},
{err: e911.ErrChallengeIncomplete, want: http.StatusNotImplemented},
{err: e911.ErrCarrierWebsheetAbsent, want: http.StatusBadGateway},
{err: errors.New("boom"), want: http.StatusInternalServerError},
}
for _, tt := range tests {
if got := e911ErrorStatus(tt.err); got != tt.want {
t.Fatalf("e911ErrorStatus(%v)=%d want %d", tt.err, got, tt.want)
}
}
}
File diff suppressed because it is too large. Load diff
+60
View File
@@ -0,0 +1,60 @@
package api
import (
"errors"
"testing"
"github.com/iniwex5/vohive/internal/config"
)
func TestEnsureAddDeviceIMEIBackfillsWhenEmpty(t *testing.T) {
cfg := config.DeviceConfig{ID: "ec20-1", ControlDevice: "/dev/cdc-wdm2"}
probe := func(controlPath string) (string, error) {
if controlPath != "/dev/cdc-wdm2" {
t.Fatalf("probe got %q", controlPath)
}
return "864388041069422", nil
}
got, err := ensureAddDeviceIMEI(cfg, probe)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if got.ModemIMEI != "864388041069422" {
t.Fatalf("ModemIMEI = %q, want probed value", got.ModemIMEI)
}
}
func TestEnsureAddDeviceIMEIRejectsWhenProbeFails(t *testing.T) {
cfg := config.DeviceConfig{ID: "ec20-1", ControlDevice: "/dev/cdc-wdm2"}
probe := func(string) (string, error) { return "", errors.New("timeout") }
if _, err := ensureAddDeviceIMEI(cfg, probe); err == nil {
t.Fatal("expected error when probe fails, got nil")
}
}
func TestEnsureAddDeviceIMEIRejectsWhenProbeEmpty(t *testing.T) {
cfg := config.DeviceConfig{ID: "ec20-1", ControlDevice: "/dev/cdc-wdm2"}
probe := func(string) (string, error) { return " ", nil }
if _, err := ensureAddDeviceIMEI(cfg, probe); err == nil {
t.Fatal("expected error when probe returns blank, got nil")
}
}
func TestEnsureAddDeviceIMEILeavesExistingIMEIAndATOnly(t *testing.T) {
withIMEI := config.DeviceConfig{ID: "ec20-1", ControlDevice: "/dev/cdc-wdm2", ModemIMEI: "864388041069422"}
probeFail := func(string) (string, error) {
t.Fatal("probe must not run when IMEI present")
return "", nil
}
if got, err := ensureAddDeviceIMEI(withIMEI, probeFail); err != nil || got.ModemIMEI != "864388041069422" {
t.Fatalf("with-IMEI: got %+v err %v", got, err)
}
atOnly := config.DeviceConfig{ID: "at-1", ATPort: "/dev/ttyUSB2"}
if _, err := ensureAddDeviceIMEI(atOnly, probeFail); err != nil {
t.Fatalf("AT-only must not be enforced: %v", err)
}
}
+144
View File
@@ -0,0 +1,144 @@
package api
import (
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/iniwex5/vohive/internal/backend"
"github.com/iniwex5/vohive/internal/config"
"github.com/iniwex5/vohive/internal/device"
"github.com/iniwex5/vohive/internal/modem"
)
type fakeManualATSession struct {
resp string
err error
cmd string
timeout time.Duration
closed bool
closeErr error
}
func (s *fakeManualATSession) Execute(cmd string, timeout time.Duration) (string, error) {
s.cmd = cmd
s.timeout = timeout
return s.resp, s.err
}
func (s *fakeManualATSession) Close() error {
s.closed = true
return s.closeErr
}
func TestExecuteManualATOnPortUsesTransientSerialSession(t *testing.T) {
orig := openManualATSession
defer func() { openManualATSession = orig }()
fake := &fakeManualATSession{resp: "OK\r\n"}
var gotPort string
openManualATSession = func(port string) (manualATSession, error) {
gotPort = port
return fake, nil
}
resp, err := executeManualATOnPort("/dev/ttyUSB2", "AT+CSQ", 7*time.Second)
if err != nil {
t.Fatalf("executeManualATOnPort() error = %v", err)
}
if resp != "OK\r\n" {
t.Fatalf("executeManualATOnPort() resp = %q, want OK", resp)
}
if gotPort != "/dev/ttyUSB2" {
t.Fatalf("open port = %q, want /dev/ttyUSB2", gotPort)
}
if fake.cmd != "AT+CSQ" || fake.timeout != 7*time.Second {
t.Fatalf("Execute() got cmd=%q timeout=%s", fake.cmd, fake.timeout)
}
if !fake.closed {
t.Fatal("manual AT session was not closed")
}
}
func TestExecuteManualATOnPortRejectsEmptyPort(t *testing.T) {
if _, err := executeManualATOnPort(" ", "AT", time.Second); err == nil {
t.Fatal("executeManualATOnPort() error = nil, want empty-port error")
}
}
func TestExecuteManualATOnPortReturnsOpenError(t *testing.T) {
orig := openManualATSession
defer func() { openManualATSession = orig }()
openManualATSession = func(port string) (manualATSession, error) {
return nil, errors.New("busy")
}
if _, err := executeManualATOnPort("/dev/ttyUSB2", "AT", time.Second); err == nil || err.Error() != "打开 AT 端口 /dev/ttyUSB2 失败: busy" {
t.Fatalf("executeManualATOnPort() error = %v", err)
}
}
func TestHandleDeviceMgmtExecuteATUsesTransientSessionForMBIMBackend(t *testing.T) {
gin.SetMode(gin.TestMode)
orig := openManualATSession
defer func() { openManualATSession = orig }()
fake := &fakeManualATSession{resp: "OK\r\n"}
var gotPort string
openManualATSession = func(port string) (manualATSession, error) {
gotPort = port
return fake, nil
}
p := device.NewPool(&config.Config{})
be := &ussdDeviceBackendStub{mode: backend.BackendMBIM}
setNestedPrivateField(t, p, []string{"workers"}, map[string]*device.Worker{
"dev-mbim": {
ID: "dev-mbim",
Config: config.DeviceConfig{ID: "dev-mbim", DeviceBackend: backend.BackendMBIM, ATPort: "/dev/ttyUSB9"},
Backend: be,
},
})
server := &Server{pool: p}
rec := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(rec)
ctx.Params = gin.Params{{Key: "device_id", Value: "dev-mbim"}}
ctx.Request = httptest.NewRequest(http.MethodPost, "/devices/dev-mbim/actions/at", strings.NewReader(`{"cmd":"AT+CSQ","timeout_ms":7000}`))
ctx.Request.Header.Set("Content-Type", "application/json")
server.handleDeviceMgmtExecuteAT(ctx)
if rec.Code != http.StatusOK {
t.Fatalf("status=%d want=%d body=%s", rec.Code, http.StatusOK, rec.Body.String())
}
if gotPort != "/dev/ttyUSB9" {
t.Fatalf("open port = %q, want /dev/ttyUSB9", gotPort)
}
if fake.cmd != "AT+CSQ" || fake.timeout != 7*time.Second {
t.Fatalf("Execute() got cmd=%q timeout=%s", fake.cmd, fake.timeout)
}
if !fake.closed {
t.Fatal("manual AT session was not closed")
}
if !strings.Contains(rec.Body.String(), `"response":"OK\r\n"`) {
t.Fatalf("body=%s want AT response", rec.Body.String())
}
}
func TestManualATPortForWorkerFallsBackToModemPort(t *testing.T) {
m, err := modem.New(config.DeviceConfig{ID: "d", DeviceBackend: "qmi", ManagePort: "/dev/ttyUSB2"})
if err != nil {
t.Fatalf("modem.New() error = %v", err)
}
// worker.Config 路径全空(零路径),只有 Modem 内存里有端口。
w := &device.Worker{ID: "d", Config: config.DeviceConfig{ID: "d", DeviceBackend: "qmi"}, Modem: m}
if got := manualATPortForWorker(w); got != "/dev/ttyUSB2" {
t.Fatalf("manualATPortForWorker() = %q, want /dev/ttyUSB2", got)
}
}
@@ -0,0 +1,32 @@
package api
import (
"strings"
"testing"
"github.com/iniwex5/vohive/internal/config"
)
func TestValidateDeviceBackendConfigMBIM(t *testing.T) {
// 零路径架构: control_device 由运行时从 IMEI 发现,不再是保存前置条件。
// mbim 配置无论是否含 control_device 均合法。
for _, b := range []string{"mbim", "MBIM"} {
if err := validateDeviceBackendConfig(config.DeviceConfig{DeviceBackend: b}); err != nil {
t.Fatalf("backend=%q 应合法,却返回: %v", b, err)
}
if err := validateDeviceBackendConfig(config.DeviceConfig{DeviceBackend: b, ControlDevice: "/dev/cdc-wdm2"}); err != nil {
t.Fatalf("backend=%q+control_device 应合法,却返回: %v", b, err)
}
}
err := validateDeviceBackendConfig(config.DeviceConfig{DeviceBackend: "foo"})
if err == nil || !strings.Contains(err.Error(), "mbim") {
t.Fatalf("非法值错误信息应列出 mbim,实际: %v", err)
}
for _, b := range []string{"", "at", "qmi"} {
if err := validateDeviceBackendConfig(config.DeviceConfig{DeviceBackend: b}); err != nil {
t.Fatalf("backend=%q 应合法,却返回: %v", b, err)
}
}
}
@@ -0,0 +1,88 @@
package api
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
"github.com/iniwex5/vohive/internal/config"
"github.com/iniwex5/vohive/internal/db"
"github.com/iniwex5/vohive/internal/device"
)
func TestCardPolicyFromDeviceConfigMapping(t *testing.T) {
cfg := config.DeviceConfig{
NetworkEnabled: true, VoWiFiEnabled: true, IPVersion: "v4v6", APN: "ims",
}
pol := cardPolicyFromDeviceConfig("ICC9", cfg)
if pol.ICCID != "ICC9" || !pol.NetworkEnabled || !pol.VoWiFiEnabled {
t.Fatalf("映射错: %+v", pol)
}
if pol.IPVersion != "v4v6" || pol.APN != "ims" || pol.Source != "user" {
t.Fatalf("映射错: %+v", pol)
}
}
// 策略跟卡走后,保存设备配置必须是策略中性的:
// 不得用 DTO 回传的(GET config 恒零的)策略字段覆盖 card_policies。
// 策略只能经 PUT /cards/:iccid/policy 修改。
func TestUpdateDeviceDoesNotClobberCardPolicy(t *testing.T) {
gin.SetMode(gin.TestMode)
initPolicyTestDB(t)
iccid := "8986008888888888888"
if err := db.DB.Create(&db.Device{IMEI: "imei-x", Alias: "wwan9", CurrentICCID: &iccid}).Error; err != nil {
t.Fatal(err)
}
// 预置一条用户态卡策略:vowifi 开启、用户飞行意图开启、network 关闭、双栈。
if err := db.UpsertCardPolicy(db.CardPolicy{
ICCID: iccid, VoWiFiEnabled: true, AirplaneEnabled: true, IPVersion: "v4v6", APN: "ims", Source: "user",
}); err != nil {
t.Fatal(err)
}
path := writeDeviceMgmtLimitConfig(t, `
server:
port: ":7575"
devices:
- id: wwan9
interface: wwan9
`)
if err := config.InitGlobalManager(path); err != nil {
t.Fatalf("InitGlobalManager() error = %v", err)
}
server := &Server{pool: device.NewPool(&config.Config{}), configPath: path}
// 仅改设备名称;DTO 不携带策略(等价于前端配置页不再编辑策略,策略字段恒零)。
// 旧实现会把 network=false/vowifi=false/ip="" 透写从而清空卡策略。
body := `{"config":{"id":"wwan9","name":"renamed"}}`
rec := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(rec)
ctx.Params = gin.Params{{Key: "device_id", Value: "wwan9"}}
ctx.Request = httptest.NewRequest(http.MethodPut, "/devices/wwan9", strings.NewReader(body))
ctx.Request.Header.Set("Content-Type", "application/json")
server.handleDeviceMgmtUpdateDevice(ctx)
if rec.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// 卡策略必须原样保留,未被设备保存清空。
got, err := db.GetCardPolicy(iccid)
if err != nil {
t.Fatalf("卡策略丢失: %v", err)
}
if !got.VoWiFiEnabled || !got.AirplaneEnabled {
t.Fatalf("卡策略被设备保存清空: %+v", got)
}
if got.NetworkEnabled {
t.Fatalf("不变式被破坏(vowifi 开应 network 关): %+v", got)
}
if got.IPVersion != "v4v6" || got.APN != "ims" {
t.Fatalf("卡策略内容被改写: %+v", got)
}
}
+247
View File
@@ -0,0 +1,247 @@
package api
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"github.com/gin-gonic/gin"
"github.com/iniwex5/vohive/internal/config"
"github.com/iniwex5/vohive/internal/device"
)
// 不同 IMEI 落在已配置设备的旧路径上,不再是"冲突":新模组就是一台可正常添加的设备,
// 旧配置离线(身份锚定后路径不再有否决权)。
func TestHandleDeviceMgmtDiscoveredDifferentIMEIIsPlainAddable(t *testing.T) {
gin.SetMode(gin.TestMode)
path := writeDeviceMgmtDiscoveryConfig(t, `
server:
port: ":7575"
devices:
- id: old-device
modem_imei: "111111111111111"
control_device: /dev/cdc-wdm0
interface: wwan0
usb_path: /sys/bus/usb/devices/1-1
at_port: /dev/ttyUSB2
device_backend: qmi
`)
if err := config.InitGlobalManager(path); err != nil {
t.Fatalf("InitGlobalManager() error = %v", err)
}
restoreDiscoveryStubs(t)
discoverQMIForMgmtFn = func() ([]device.QMIDevice, error) { return nil, nil }
discoverCompatibleModemsFromQMIFn = func([]device.QMIDevice) ([]device.CompatibleModem, error) {
return []device.CompatibleModem{{
ControlPath: "/dev/cdc-wdm0",
NetInterface: "wwan0",
USBPath: "/sys/bus/usb/devices/1-1",
ATPorts: []string{"/dev/ttyUSB2"},
ATPort: "/dev/ttyUSB2",
Mode: "qmi",
NetworkCapable: true,
}}, nil
}
enrichDiscoveredCompatibleModemFn = func(dev device.CompatibleModem, opts device.CompatibleModemEnrichOptions) (device.CompatibleModem, string) {
dev.IMEI = "222222222222222"
return dev, "222222222222222"
}
got := requestDiscoveredDevices(t, &Server{pool: device.NewPool(&config.Config{}), configPath: path})
if len(got.Devices) != 1 {
t.Fatalf("devices len = %d, want 1", len(got.Devices))
}
d := got.Devices[0]
if d.Configured {
t.Fatalf("Configured = true, want false: %+v", d)
}
if d.Degraded {
t.Fatalf("Degraded = true, want false (IMEI is readable): %+v", d)
}
if d.IMEI != "222222222222222" {
t.Fatalf("IMEI = %q, want new device IMEI", d.IMEI)
}
}
// 探不到 IMEI 的硬件(如 MBIM 挂死返回垃圾)归 degraded:不可直接添加,UI 需提示。
func TestHandleDeviceMgmtDiscoveredMarksDegradedWhenIMEIUnreadable(t *testing.T) {
gin.SetMode(gin.TestMode)
path := writeDeviceMgmtDiscoveryConfig(t, `
server:
port: ":7575"
devices: []
`)
if err := config.InitGlobalManager(path); err != nil {
t.Fatalf("InitGlobalManager() error = %v", err)
}
restoreDiscoveryStubs(t)
discoverQMIForMgmtFn = func() ([]device.QMIDevice, error) { return nil, nil }
discoverCompatibleModemsFromQMIFn = func([]device.QMIDevice) ([]device.CompatibleModem, error) {
return []device.CompatibleModem{{
ControlPath: "/dev/cdc-wdm1",
NetInterface: "wwan3",
USBPath: "/sys/bus/usb/devices/1-9",
Mode: "mbim",
}}, nil
}
enrichDiscoveredCompatibleModemFn = func(dev device.CompatibleModem, opts device.CompatibleModemEnrichOptions) (device.CompatibleModem, string) {
return dev, "" // AT/QMI 探不到 IMEI
}
probeIMEIViaMBIMForMgmtFn = func(string) (string, error) { return "", fmt.Errorf("mbim hung") } // MBIM 也读不到
got := requestDiscoveredDevices(t, &Server{pool: device.NewPool(&config.Config{}), configPath: path})
if len(got.Devices) != 1 {
t.Fatalf("devices len = %d, want 1", len(got.Devices))
}
d := got.Devices[0]
if d.Configured || !d.Degraded {
t.Fatalf("want Configured=false Degraded=true, got %+v", d)
}
}
func TestHandleDeviceMgmtDiscoveredMarksConfiguredForSameIMEI(t *testing.T) {
gin.SetMode(gin.TestMode)
path := writeDeviceMgmtDiscoveryConfig(t, `
server:
port: ":7575"
devices:
- id: old-device
modem_imei: "111111111111111"
control_device: /dev/cdc-wdm0
interface: wwan0
usb_path: /sys/bus/usb/devices/1-1
at_port: /dev/ttyUSB2
device_backend: qmi
`)
if err := config.InitGlobalManager(path); err != nil {
t.Fatalf("InitGlobalManager() error = %v", err)
}
restoreDiscoveryStubs(t)
discoverQMIForMgmtFn = func() ([]device.QMIDevice, error) { return nil, nil }
discoverCompatibleModemsFromQMIFn = func([]device.QMIDevice) ([]device.CompatibleModem, error) {
return []device.CompatibleModem{{
ControlPath: "/dev/cdc-wdm0",
NetInterface: "wwan0",
USBPath: "/sys/bus/usb/devices/1-1",
ATPorts: []string{"/dev/ttyUSB2"},
ATPort: "/dev/ttyUSB2",
Mode: "qmi",
}}, nil
}
enrichDiscoveredCompatibleModemFn = func(dev device.CompatibleModem, opts device.CompatibleModemEnrichOptions) (device.CompatibleModem, string) {
dev.IMEI = "111111111111111"
return dev, "111111111111111"
}
got := requestDiscoveredDevices(t, &Server{pool: device.NewPool(&config.Config{}), configPath: path})
d := got.Devices[0]
if !d.Configured || d.ConfiguredID != "old-device" {
t.Fatalf("configured fields = %+v, want configured old-device", d)
}
if d.Degraded {
t.Fatalf("Degraded = true, want false: %+v", d)
}
}
// TestHandleDeviceMgmtDiscoveredLegacyPathConfigDegrades verifies that after the
// zero-path migration, a device configured with only path fields (no IMEI) can no
// longer be matched by legacyPathMatch because the migration scrubs those keys from
// disk on Load(). The discovered device appears as Degraded — this is the accepted
// behavioral risk of Option A (unconditional deprecation).
func TestHandleDeviceMgmtDiscoveredLegacyPathConfigDegrades(t *testing.T) {
gin.SetMode(gin.TestMode)
path := writeDeviceMgmtDiscoveryConfig(t, `
server:
port: ":7575"
devices:
- id: legacy-device
control_device: /dev/cdc-wdm0
interface: wwan0
usb_path: /sys/bus/usb/devices/1-1
at_port: /dev/ttyUSB2
device_backend: qmi
`)
if err := config.InitGlobalManager(path); err != nil {
t.Fatalf("InitGlobalManager() error = %v", err)
}
restoreDiscoveryStubs(t)
discoverQMIForMgmtFn = func() ([]device.QMIDevice, error) { return nil, nil }
discoverCompatibleModemsFromQMIFn = func([]device.QMIDevice) ([]device.CompatibleModem, error) {
return []device.CompatibleModem{{
ControlPath: "/dev/cdc-wdm0",
NetInterface: "wwan0",
USBPath: "/sys/bus/usb/devices/1-1",
ATPorts: []string{"/dev/ttyUSB2"},
ATPort: "/dev/ttyUSB2",
Mode: "qmi",
}}, nil
}
enrichDiscoveredCompatibleModemFn = func(dev device.CompatibleModem, opts device.CompatibleModemEnrichOptions) (device.CompatibleModem, string) {
return dev, ""
}
got := requestDiscoveredDevices(t, &Server{pool: device.NewPool(&config.Config{}), configPath: path})
d := got.Devices[0]
// 零路径迁移后:磁盘路径键已删,legacyPathMatch 无法命中,设备归入 degraded。
if d.Configured {
t.Fatalf("device should not be matched after path migration, got: %+v", d)
}
if !d.Degraded {
t.Fatalf("device should be degraded (no IMEI, no matched config), got: %+v", d)
}
}
type discoveredDevicesResponse struct {
Devices []discoveredDevice `json:"devices"`
}
func requestDiscoveredDevices(t *testing.T, srv *Server) discoveredDevicesResponse {
t.Helper()
recorder := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(recorder)
ctx.Request = httptest.NewRequest(http.MethodGet, "/api/devices/discovered?with_imei=1", nil)
srv.handleDeviceMgmtDiscovered(ctx)
if recorder.Code != http.StatusOK {
t.Fatalf("status = %d, want 200 body=%s", recorder.Code, recorder.Body.String())
}
var resp discoveredDevicesResponse
if err := json.Unmarshal(recorder.Body.Bytes(), &resp); err != nil {
t.Fatalf("response JSON error = %v body=%s", err, recorder.Body.String())
}
return resp
}
func restoreDiscoveryStubs(t *testing.T) {
t.Helper()
origDiscoverQMI := discoverQMIForMgmtFn
origDiscoverCompat := discoverCompatibleModemsFromQMIFn
origEnrich := enrichDiscoveredCompatibleModemFn
origProbeMBIM := probeIMEIViaMBIMForMgmtFn
t.Cleanup(func() {
discoverQMIForMgmtFn = origDiscoverQMI
discoverCompatibleModemsFromQMIFn = origDiscoverCompat
enrichDiscoveredCompatibleModemFn = origEnrich
probeIMEIViaMBIMForMgmtFn = origProbeMBIM
})
}
func writeDeviceMgmtDiscoveryConfig(t *testing.T, content string) string {
t.Helper()
path := filepath.Join(t.TempDir(), "config.yaml")
if err := os.WriteFile(path, []byte(strings.TrimSpace(content)+"\n"), 0o600); err != nil {
t.Fatalf("WriteFile() error = %v", err)
}
return path
}
@@ -0,0 +1,52 @@
package api
import (
"context"
"strings"
"testing"
"github.com/iniwex5/vohive/internal/config"
"github.com/iniwex5/vohive/internal/device"
"github.com/iniwex5/vohive/internal/modem"
)
func TestFlightModeSuccessMessageUsesRequestedState(t *testing.T) {
tests := []struct {
name string
enabled bool
want string
}{
{name: "enable", enabled: true, want: "飞行模式已开启"},
{name: "disable", enabled: false, want: "飞行模式已关闭"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := flightModeSuccessMessage(tt.enabled); got != tt.want {
t.Fatalf("flightModeSuccessMessage(%v)=%q want %q", tt.enabled, got, tt.want)
}
})
}
}
func TestSetWorkerFlightModeFailsWhenBackendMissingEvenWithATModem(t *testing.T) {
m, err := modem.New(config.DeviceConfig{
ID: "dev-qmi",
DeviceBackend: "qmi",
ATPort: "/dev/ttyUSB-test",
})
if err != nil {
t.Fatalf("modem.New() error = %v", err)
}
_, _, err = setWorkerFlightMode(context.Background(), &device.Worker{Modem: m}, false)
if err == nil {
t.Fatal("setWorkerFlightMode() error = nil, want backend initialization error")
}
if !strings.Contains(err.Error(), "设备后端未初始化") {
t.Fatalf("setWorkerFlightMode() error = %q, want backend initialization error", err.Error())
}
if strings.Contains(err.Error(), "AT 管理器") || strings.Contains(err.Error(), "AT 端口") {
t.Fatalf("setWorkerFlightMode() error = %q, must not come from legacy AT fallback", err.Error())
}
}
@@ -0,0 +1,36 @@
package api
import (
"testing"
"github.com/iniwex5/vohive/internal/config"
)
func TestValidateManagedNetworkConfigRejectsBadIPVersion(t *testing.T) {
err := validateManagedNetworkConfig(config.DeviceConfig{
ID: "dev-ipv",
IPVersion: "v9",
})
if err == nil {
t.Fatal("validateManagedNetworkConfig() error = nil, want invalid ip_version")
}
}
func TestDeviceConfigForAddDropsDevicePolicyFields(t *testing.T) {
cfg := deviceConfigForAdd(config.DeviceConfig{
ID: "dev-1",
APN: "ims",
IPVersion: "bad",
NetworkEnabled: true,
VoWiFiEnabled: true,
AirplaneEnabled: true,
SMSEnabled: false,
})
if cfg.APN != "" || cfg.IPVersion != "" || cfg.NetworkEnabled || cfg.VoWiFiEnabled || cfg.AirplaneEnabled {
t.Fatalf("设备添加不应保留卡策略字段: %+v", cfg)
}
if !cfg.SMSEnabled {
t.Fatal("SMS 应保持系统不变量 true")
}
}
@@ -0,0 +1,89 @@
package api
import (
"encoding/json"
"strings"
"testing"
"time"
"github.com/iniwex5/vohive/internal/config"
"github.com/iniwex5/vohive/internal/device"
"github.com/iniwex5/vohive/internal/modem"
"github.com/iniwex5/vowifi-go/runtimehost"
)
func TestApplyLifecycleToOfflineOverviewItemKeepsRecoveryVisible(t *testing.T) {
pool := device.NewPool(&config.Config{})
pool.MarkLifecycleRecovery("dev1", device.LifecyclePhaseUSBWait, "manual_reboot", 3*time.Minute)
server := &Server{pool: pool}
item := deviceMgmtOverviewLiteItem{
ID: "dev1",
Running: false,
Healthy: false,
ControlOnline: false,
}
server.applyLifecycleToOverviewLiteItem(&item, nil, config.DeviceConfig{ID: "dev1"})
if item.LifecyclePhase != string(device.LifecyclePhaseUSBWait) {
t.Fatalf("LifecyclePhase=%q want %q", item.LifecyclePhase, device.LifecyclePhaseUSBWait)
}
if !item.PhysicalPresent {
t.Fatal("PhysicalPresent=false want true during active recovery")
}
if item.WorkerRunning {
t.Fatal("WorkerRunning=true want false")
}
}
func TestApplyLifecycleToListItemDerivesRadioRegistered(t *testing.T) {
pool := device.NewPool(&config.Config{})
pool.MarkLifecycleRecovery("dev1", device.LifecyclePhaseQMIStarting, "startup", 3*time.Minute)
server := &Server{pool: pool}
item := deviceMgmtListItem{
ID: "dev1",
Running: true,
Healthy: true,
ControlOnline: true,
NetworkConnected: true,
Modem: deviceMgmtListModem{RegStatus: 5},
}
server.applyLifecycleToListItem(&item, true, config.DeviceConfig{ID: "dev1"})
if !item.RadioRegistered {
t.Fatal("RadioRegistered=false want true for reg status 5")
}
if !item.DataConnected {
t.Fatal("DataConnected=false want true when network is connected")
}
if item.LifecyclePhase != string(device.LifecyclePhaseOnline) {
t.Fatalf("LifecyclePhase=%q want %q", item.LifecyclePhase, device.LifecyclePhaseOnline)
}
}
func TestVoWiFiRuntimeDTOExportsSIMReadyOnly(t *testing.T) {
dto := runtimeStateToDTO(runtimehost.State{
Phase: runtimehost.PhaseSIMReady,
DeviceID: "dev1",
SIMReady: true,
LastReason: "sim_ready",
}, modem.DeviceStatus{IMSI: "001010123456789"})
if !dto.SIMReady {
t.Fatalf("SIMReady=false in dto=%+v", dto)
}
body, err := json.Marshal(dto)
if err != nil {
t.Fatalf("Marshal() err=%v", err)
}
raw := string(body)
if !strings.Contains(raw, `"sim_ready":true`) {
t.Fatalf("json=%s, want sim_ready=true", raw)
}
if strings.Contains(raw, "radio_ready") {
t.Fatalf("json=%s should not contain radio_ready", raw)
}
}
@@ -0,0 +1,52 @@
package api
import (
"testing"
"github.com/iniwex5/vohive/internal/config"
)
// 重构后策略字段(network/vowifi/airplane/ip/apn/sms)只存在于运行时投影(w.Config),
// 不再来自 config.yaml(persisted)。overviewDisplayConfig 必须从 runtime 取这些字段,
// 否则概览 UI 会对所有设备显示 off。
func TestOverviewDisplayConfigTakesPolicyFromRuntime(t *testing.T) {
runtime := config.DeviceConfig{
ID: "wwan0",
Interface: "wwan0",
NetworkEnabled: true,
VoWiFiEnabled: true,
AirplaneEnabled: true,
IPVersion: "v4v6",
APN: "ims",
SMSEnabled: true,
}
persisted := config.DeviceConfig{
ID: "wwan0",
Interface: "", // 持久化里硬件路径为空,应被 runtime 覆盖
// 策略字段全为零值(重构后 yaml 不再加载)
}
got := overviewDisplayConfig(runtime, persisted, true)
if !got.NetworkEnabled || !got.VoWiFiEnabled || !got.AirplaneEnabled {
t.Fatalf("策略开关应取自 runtime: %+v", got)
}
if got.IPVersion != "v4v6" || got.APN != "ims" {
t.Fatalf("ip/apn 应取自 runtime: %+v", got)
}
if got.Interface != "wwan0" {
t.Fatalf("硬件路径仍应取自 runtime: %+v", got)
}
}
// 回归:SMS 是系统不变量(恒开),即使 runtime/persisted 都为 false,
// overviewDisplayConfig 也必须返回 sms_enabled=true,否则短信中心设备会被过滤消失。
func TestOverviewDisplayConfigSMSAlwaysEnabled(t *testing.T) {
runtime := config.DeviceConfig{ID: "wwan0", Interface: "wwan0", SMSEnabled: false}
persisted := config.DeviceConfig{ID: "wwan0", SMSEnabled: false}
got := overviewDisplayConfig(runtime, persisted, true)
if !got.SMSEnabled {
t.Fatalf("SMS 应恒为 true(不变量),got=%+v", got)
}
}
@@ -0,0 +1,184 @@
package api
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/gin-gonic/gin"
proxytraffic "github.com/iniwex5/vohive/internal/proxy/traffic"
)
func TestOverviewStreamEmitVersionIgnoresRuntimeUpdatedAt(t *testing.T) {
last := newOverviewStreamEmitVersion(deviceMgmtOverviewLiteItem{
VoWiFiActive: true,
VoWiFiRuntime: &voWiFiRuntimeDTO{
Phase: "registering",
TunnelReady: true,
IMSReady: false,
SMSReady: false,
LastErrorClass: "",
UpdatedAt: time.Unix(1, 0),
},
})
curr := newOverviewStreamEmitVersion(deviceMgmtOverviewLiteItem{
VoWiFiActive: true,
VoWiFiRuntime: &voWiFiRuntimeDTO{
Phase: "registering",
TunnelReady: true,
IMSReady: false,
SMSReady: false,
LastErrorClass: "",
UpdatedAt: time.Unix(2, 0),
},
})
if !shouldSkipOverviewStatePush(&last, curr) {
t.Fatal("state push was not skipped when only UpdatedAt changed")
}
}
func TestOverviewStreamEmitVersionTracksRuntimeBusinessState(t *testing.T) {
baseItem := deviceMgmtOverviewLiteItem{
VoWiFiActive: true,
VoWiFiRuntime: &voWiFiRuntimeDTO{
Phase: "registering",
TunnelReady: true,
},
}
base := newOverviewStreamEmitVersion(baseItem)
tests := []struct {
name string
item deviceMgmtOverviewLiteItem
}{
{
name: "phase changed",
item: deviceMgmtOverviewLiteItem{VoWiFiActive: true, VoWiFiRuntime: &voWiFiRuntimeDTO{Phase: "ready", TunnelReady: true}},
},
{
name: "tunnel changed",
item: deviceMgmtOverviewLiteItem{VoWiFiActive: true, VoWiFiRuntime: &voWiFiRuntimeDTO{Phase: "registering", TunnelReady: false}},
},
{
name: "ims changed",
item: deviceMgmtOverviewLiteItem{VoWiFiActive: true, VoWiFiRuntime: &voWiFiRuntimeDTO{Phase: "registering", TunnelReady: true, IMSReady: true}},
},
{
name: "sms changed",
item: deviceMgmtOverviewLiteItem{VoWiFiActive: true, VoWiFiRuntime: &voWiFiRuntimeDTO{Phase: "registering", TunnelReady: true, SMSReady: true}},
},
{
name: "last error class changed",
item: deviceMgmtOverviewLiteItem{VoWiFiActive: true, VoWiFiRuntime: &voWiFiRuntimeDTO{Phase: "registering", TunnelReady: true, LastErrorClass: "ims_register_failed"}},
},
{
name: "active changed",
item: deviceMgmtOverviewLiteItem{VoWiFiActive: false, VoWiFiRuntime: &voWiFiRuntimeDTO{Phase: "registering", TunnelReady: true}},
},
{
name: "runtime disappeared",
item: deviceMgmtOverviewLiteItem{VoWiFiActive: true},
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
curr := newOverviewStreamEmitVersion(tc.item)
if shouldSkipOverviewStatePush(&base, curr) {
t.Fatal("state push was skipped despite business state change")
}
})
}
empty := newOverviewStreamEmitVersion(deviceMgmtOverviewLiteItem{VoWiFiActive: true})
appeared := newOverviewStreamEmitVersion(baseItem)
if shouldSkipOverviewStatePush(&empty, appeared) {
t.Fatal("state push was skipped when runtime state appeared")
}
}
func TestOverviewDetailLiveRefreshRequestedDefaultsToCache(t *testing.T) {
gin.SetMode(gin.TestMode)
tests := []struct {
name string
url string
want bool
}{
{name: "absent", url: "/devices/dev1/overview", want: false},
{name: "refresh false", url: "/devices/dev1/overview?refresh=false", want: false},
{name: "refresh true", url: "/devices/dev1/overview?refresh=true", want: true},
{name: "refresh one", url: "/devices/dev1/overview?refresh=1", want: true},
{name: "live true", url: "/devices/dev1/overview?live=true", want: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
recorder := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(recorder)
ctx.Request = httptest.NewRequest(http.MethodGet, tt.url, nil)
if got := overviewDetailLiveRefreshRequested(ctx); got != tt.want {
t.Fatalf("overviewDetailLiveRefreshRequested()=%v want %v", got, tt.want)
}
})
}
}
func TestOverviewTrafficStreamStateFollowsNetworkConnectivity(t *testing.T) {
sub := &fakeRealtimeTrafficSubscriber{}
state := overviewTrafficStreamState{
subscriber: sub,
deviceID: "dev-a",
ctx: context.Background(),
}
if ch := state.sync(deviceMgmtOverviewLiteItem{NetworkEnabled: false, NetworkConnected: false}); ch != nil {
t.Fatalf("channel=%v want nil when network disabled", ch)
}
if sub.subscribeCalls != 0 {
t.Fatalf("subscribeCalls=%d want 0 before network is active", sub.subscribeCalls)
}
ch := state.sync(deviceMgmtOverviewLiteItem{NetworkEnabled: true, NetworkConnected: true})
if ch == nil {
t.Fatal("expected traffic channel when network is connected")
}
again := state.sync(deviceMgmtOverviewLiteItem{NetworkEnabled: true, NetworkConnected: true})
if again != ch {
t.Fatal("expected connected sync to reuse existing traffic subscription")
}
if sub.subscribeCalls != 1 {
t.Fatalf("subscribeCalls=%d want 1 after repeated connected sync", sub.subscribeCalls)
}
if ch := state.sync(deviceMgmtOverviewLiteItem{NetworkEnabled: true, NetworkConnected: false}); ch != nil {
t.Fatalf("channel=%v want nil after network disconnects", ch)
}
if sub.unsubscribeCalls != 1 {
t.Fatalf("unsubscribeCalls=%d want 1 after network disconnects", sub.unsubscribeCalls)
}
if ch := state.sync(deviceMgmtOverviewLiteItem{NetworkEnabled: true, NetworkConnected: true}); ch == nil {
t.Fatal("expected traffic channel after network reconnects")
}
if sub.subscribeCalls != 2 {
t.Fatalf("subscribeCalls=%d want 2 after reconnect", sub.subscribeCalls)
}
}
type fakeRealtimeTrafficSubscriber struct {
subscribeCalls int
unsubscribeCalls int
}
func (f *fakeRealtimeTrafficSubscriber) Subscribe(ctx context.Context, deviceID string) (<-chan proxytraffic.RealtimeSnapshot, func()) {
f.subscribeCalls++
ch := make(chan proxytraffic.RealtimeSnapshot)
return ch, func() {
f.unsubscribeCalls++
}
}
+40
View File
@@ -0,0 +1,40 @@
package api
import (
"testing"
"github.com/iniwex5/vohive/internal/config"
)
// 零路径持久化后,持久化 config 不再含 control_device/interface 等路径;
// 总览展示必须用 worker 运行时 config 的路径与策略投影,意图字段(name/backend)仍取持久化值。
func TestOverviewDisplayConfigPrefersRuntimePaths(t *testing.T) {
runtime := config.DeviceConfig{
ID: "wwan0", ModemIMEI: "863212060398051", DeviceBackend: "qmi",
Interface: "wwan0", ControlDevice: "/dev/cdc-wdm0", ATPort: "/dev/ttyUSB2",
QMIDevice: "/dev/cdc-wdm0", USBPath: "/sys/bus/usb/devices/1-4",
VoWiFiEnabled: true, // 策略跟卡走,存在于运行时投影
}
persisted := config.DeviceConfig{
ID: "wwan0", Name: "主卡", ModemIMEI: "863212060398051", DeviceBackend: "qmi",
}
got := overviewDisplayConfig(runtime, persisted, true)
if got.Name != "主卡" || !got.VoWiFiEnabled || got.DeviceBackend != "qmi" {
t.Fatalf("intent fields lost: %+v", got)
}
if got.ControlDevice != "/dev/cdc-wdm0" || got.Interface != "wwan0" ||
got.ATPort != "/dev/ttyUSB2" || got.QMIDevice != "/dev/cdc-wdm0" ||
got.USBPath != "/sys/bus/usb/devices/1-4" {
t.Fatalf("runtime paths not applied: %+v", got)
}
}
func TestOverviewDisplayConfigNoPersistedReturnsRuntime(t *testing.T) {
runtime := config.DeviceConfig{ID: "x", ControlDevice: "/dev/cdc-wdm1", Interface: "wwan1"}
got := overviewDisplayConfig(runtime, config.DeviceConfig{}, false)
if got.ControlDevice != "/dev/cdc-wdm1" || got.Interface != "wwan1" {
t.Fatalf("expected runtime config, got %+v", got)
}
}
+752
View File
@@ -0,0 +1,752 @@
package api
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"path/filepath"
"reflect"
"strings"
"testing"
"unsafe"
sgp22 "github.com/damonto/euicc-go/v2"
"github.com/gin-gonic/gin"
"github.com/iniwex5/vohive/internal/apduarbiter"
"github.com/iniwex5/vohive/internal/config"
"github.com/iniwex5/vohive/internal/db"
"github.com/iniwex5/vohive/internal/device"
"github.com/iniwex5/vohive/internal/esim"
"github.com/iniwex5/vohive/internal/modem"
"golang.org/x/sync/singleflight"
)
func initDeviceMgmtPhoneTestDB(t *testing.T) {
t.Helper()
dbPath := filepath.Join(t.TempDir(), "device_mgmt_phone.db")
if err := db.Init(dbPath); err != nil {
t.Fatalf("db.Init() error=%v", err)
}
t.Cleanup(func() { db.DB = nil })
}
func setNestedPrivateField(t *testing.T, target any, fieldPath []string, value any) {
t.Helper()
field := reflect.ValueOf(target).Elem()
for _, name := range fieldPath {
field = field.FieldByName(name)
if !field.IsValid() {
t.Fatalf("field path %v not found", fieldPath)
}
}
reflect.NewAt(field.Type(), unsafe.Pointer(field.UnsafeAddr())).Elem().Set(reflect.ValueOf(value))
}
func mgrTestSetProfilesLoader(t *testing.T, mgr *esim.Manager, loader func() ([]esim.EUICCProfiles, error)) {
t.Helper()
setNestedPrivateField(t, mgr, []string{"profilesLoader"}, loader)
}
func mgrTestSetOverviewCache(t *testing.T, mgr *esim.Manager, overview *esim.EsimOverview) {
t.Helper()
setNestedPrivateField(t, mgr, []string{"overviewCache"}, overview)
}
func newTestEsimManager() *esim.Manager {
mgr := &esim.Manager{}
field := reflect.ValueOf(mgr).Elem().FieldByName("sf")
reflect.NewAt(field.Type(), unsafe.Pointer(field.UnsafeAddr())).Elem().Set(reflect.ValueOf(&singleflight.Group{}))
return mgr
}
func containsAll(s string, parts ...string) bool {
for _, part := range parts {
if !strings.Contains(s, part) {
return false
}
}
return true
}
func TestBuildOverviewLiteItemIncludesLocalPhone(t *testing.T) {
initDeviceMgmtPhoneTestDB(t)
if err := db.UpdateSIMCardModemPhoneNumberByIMSI("imsi-overview-1", "+8613800138000"); err != nil {
t.Fatalf("UpdateSIMCardModemPhoneNumberByIMSI() error=%v", err)
}
if err := db.UpdateSIMCardVoWiFiPhoneNumberByIMSI("imsi-overview-1", "+8613900139000"); err != nil {
t.Fatalf("UpdateSIMCardVoWiFiPhoneNumberByIMSI() error=%v", err)
}
p := device.NewPool(&config.Config{})
w := &device.Worker{ID: "dev-1"}
server := &Server{pool: p}
item := server.buildOverviewLiteItemFromWorker(
w,
config.DeviceConfig{ID: "dev-1", Name: "Device 1", VoWiFiEnabled: true},
modem.DeviceStatus{IMSI: "imsi-overview-1"},
nil,
)
if item.LocalPhone != "+8613900139000" {
t.Fatalf("LocalPhone=%q want=+8613900139000", item.LocalPhone)
}
}
func TestBuildOverviewLiteItemUsesCachedIMSIFallbackForLocalPhone(t *testing.T) {
initDeviceMgmtPhoneTestDB(t)
if err := db.UpdateSIMCardVoWiFiPhoneNumberByIMSI("imsi-cached-1", "+8613911111111"); err != nil {
t.Fatalf("UpdateSIMCardVoWiFiPhoneNumberByIMSI() error=%v", err)
}
p := device.NewPool(&config.Config{})
w := &device.Worker{ID: "dev-cached-1"}
setNestedPrivateField(t, w, []string{"state", "Identity", "IMSI"}, "imsi-cached-1")
setNestedPrivateField(t, w, []string{"state", "Identity", "Ready"}, true)
server := &Server{pool: p}
item := server.buildOverviewLiteItemFromWorker(
w,
config.DeviceConfig{ID: "dev-cached-1", Name: "Device Cached", VoWiFiEnabled: false},
modem.DeviceStatus{},
nil,
)
if item.LocalPhone != "+8613911111111" {
t.Fatalf("LocalPhone=%q want=+8613911111111 when cached IMSI exists", item.LocalPhone)
}
}
func TestBuildOverviewLiteItemSuppressesCachedIMSIDuringIdentityTransition(t *testing.T) {
initDeviceMgmtPhoneTestDB(t)
if err := db.UpdateSIMCardVoWiFiPhoneNumberByIMSI("old-imsi", "+12133316760"); err != nil {
t.Fatalf("UpdateSIMCardVoWiFiPhoneNumberByIMSI() error=%v", err)
}
p := device.NewPool(&config.Config{})
w := &device.Worker{ID: "dev-switching-1"}
setNestedPrivateField(t, w, []string{"state", "Identity", "IMSI"}, "old-imsi")
setNestedPrivateField(t, w, []string{"state", "Identity", "Ready"}, false)
setNestedPrivateField(t, w, []string{"state", "Identity", "Phase"}, "transitioning")
server := &Server{pool: p}
item := server.buildOverviewLiteItemFromWorker(
w,
config.DeviceConfig{ID: "dev-switching-1", Name: "Device Switching", VoWiFiEnabled: false},
modem.DeviceStatus{},
nil,
)
if item.LocalPhone != "" {
t.Fatalf("LocalPhone=%q want empty while SIM identity is transitioning", item.LocalPhone)
}
}
func TestBuildOverviewLiteItemIncludesActiveEsimProfileName(t *testing.T) {
mgr := newTestEsimManager()
mgrTestSetOverviewCache(t, mgr, &esim.EsimOverview{
Profiles: []esim.EUICCProfiles{{
EID: "eid-a",
AIDHex: "A000",
Profiles: []esim.ProfileItem{
{ICCID: "iccid-disabled", Name: "Disabled", State: 0, StateText: "未启用"},
{ICCID: "iccid-enabled", Name: "China Mobile", State: 1, StateText: "已启用"},
},
}},
})
p := device.NewPool(&config.Config{})
w := &device.Worker{ID: "dev-esim", EsimMgr: mgr}
server := &Server{pool: p}
item := server.buildOverviewLiteItemFromWorker(
w,
config.DeviceConfig{ID: "dev-esim", Name: "Device eSIM"},
modem.DeviceStatus{},
nil,
)
if item.ActiveESIMProfileName != "China Mobile" {
t.Fatalf("ActiveESIMProfileName=%q want=China Mobile", item.ActiveESIMProfileName)
}
}
func TestBuildOverviewLiteItemSeparatesControlOnlineFromDataNetwork(t *testing.T) {
p := device.NewPool(&config.Config{})
w := &device.Worker{ID: "dev-qmi"}
setNestedPrivateField(t, w, []string{"state", "Runtime", "Ready"}, true)
setNestedPrivateField(t, w, []string{"state", "Meta", "Healthy"}, true)
server := &Server{pool: p}
item := server.buildOverviewLiteItemFromWorker(
w,
config.DeviceConfig{ID: "dev-qmi", Name: "QMI Device", NetworkEnabled: false},
modem.DeviceStatus{RegStatus: 2},
nil,
)
if !item.Healthy {
t.Fatal("Healthy=false, want true for backward-compatible control plane health")
}
if !item.ControlOnline {
t.Fatal("ControlOnline=false, want true when control plane is healthy")
}
if item.NetworkEnabled {
t.Fatal("NetworkEnabled=true, want false for data switch off")
}
if item.NetworkConnected {
t.Fatal("NetworkConnected=true, want false when data plane is disconnected")
}
if item.RegistrationStateLabel != "searching" {
t.Fatalf("RegistrationStateLabel=%q want searching", item.RegistrationStateLabel)
}
}
func TestRegistrationStateLabel(t *testing.T) {
tests := []struct {
name string
reg int
want string
}{
{name: "home", reg: 1, want: "registered"},
{name: "roaming", reg: 5, want: "registered"},
{name: "searching", reg: 2, want: "searching"},
{name: "denied", reg: 3, want: "denied"},
{name: "unknown", reg: 0, want: "unknown"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := registrationStateLabel(tt.reg); got != tt.want {
t.Fatalf("registrationStateLabel(%d)=%q want %q", tt.reg, got, tt.want)
}
})
}
}
func TestBuildOverviewLiteItemDoesNotTriggerEsimScanWhenActiveProfileCacheMissing(t *testing.T) {
mgr := newTestEsimManager()
setNestedPrivateField(t, mgr, []string{"overviewLoader"}, func() (*esim.EsimOverview, error) {
t.Fatal("buildOverviewLiteItemFromWorker() should not trigger overview loader when cache is empty")
return nil, nil
})
p := device.NewPool(&config.Config{})
w := &device.Worker{ID: "dev-esim", EsimMgr: mgr}
server := &Server{pool: p}
item := server.buildOverviewLiteItemFromWorker(
w,
config.DeviceConfig{ID: "dev-esim", Name: "Device eSIM"},
modem.DeviceStatus{},
nil,
)
if item.ActiveESIMProfileName != "" {
t.Fatalf("ActiveESIMProfileName=%q want empty when cache is missing", item.ActiveESIMProfileName)
}
}
func TestHandleEsimListProfilesRefreshUsesProfilesRefreshPath(t *testing.T) {
gin.SetMode(gin.TestMode)
mgr := newTestEsimManager()
mgrTestSetProfilesLoader(t, mgr, func() ([]esim.EUICCProfiles, error) {
return []esim.EUICCProfiles{{
EID: "eid-a",
AIDHex: "A000",
Profiles: []esim.ProfileItem{{ICCID: "iccid-a2", State: 1, StateText: "已启用"}},
}}, nil
})
mgrTestSetOverviewCache(t, mgr, &esim.EsimOverview{
ChipInfo: &esim.EUICCChipInfo{SkuName: "chip"},
Profiles: []esim.EUICCProfiles{{
EID: "eid-a",
AIDHex: "A000",
Profiles: []esim.ProfileItem{{ICCID: "iccid-a1", State: 1, StateText: "已启用"}},
}},
})
p := device.NewPool(&config.Config{})
setNestedPrivateField(t, p, []string{"workers"}, map[string]*device.Worker{
"dev-esim": {ID: "dev-esim", EsimMgr: mgr},
})
server := &Server{pool: p}
recorder := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(recorder)
ctx.Params = gin.Params{{Key: "id", Value: "dev-esim"}}
ctx.Request = httptest.NewRequest(http.MethodGet, "/devices/dev-esim/esim/profiles?refresh=true", nil)
server.handleEsimListProfiles(ctx)
if recorder.Code != http.StatusOK {
t.Fatalf("status=%d want=%d body=%s", recorder.Code, http.StatusOK, recorder.Body.String())
}
if body := recorder.Body.String(); body == "" || !containsAll(body, "iccid-a2", "A000") {
t.Fatalf("body=%q want refreshed profiles payload", body)
}
}
func TestHandleEsimGetOverviewRefreshUsesFullRefreshPath(t *testing.T) {
gin.SetMode(gin.TestMode)
mgr := newTestEsimManager()
mgrTestSetOverviewCache(t, mgr, &esim.EsimOverview{
ChipInfo: &esim.EUICCChipInfo{SkuName: "before"},
Profiles: []esim.EUICCProfiles{{
EID: "eid-old",
AIDHex: "OLD",
Profiles: []esim.ProfileItem{{ICCID: "iccid-old", State: 1, StateText: "已启用"}},
}},
})
setNestedPrivateField(t, mgr, []string{"overviewLoader"}, func() (*esim.EsimOverview, error) {
return &esim.EsimOverview{
ChipInfo: &esim.EUICCChipInfo{SkuName: "after"},
Profiles: []esim.EUICCProfiles{{
EID: "eid-new",
AIDHex: "NEW",
Profiles: []esim.ProfileItem{{ICCID: "iccid-new", State: 1, StateText: "已启用"}},
}},
}, nil
})
p := device.NewPool(&config.Config{})
setNestedPrivateField(t, p, []string{"workers"}, map[string]*device.Worker{
"dev-esim": {ID: "dev-esim", EsimMgr: mgr},
})
server := &Server{pool: p}
recorder := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(recorder)
ctx.Params = gin.Params{{Key: "id", Value: "dev-esim"}}
ctx.Request = httptest.NewRequest(http.MethodGet, "/devices/dev-esim/esim?refresh=true", nil)
server.handleEsimGetOverview(ctx)
if recorder.Code != http.StatusOK {
t.Fatalf("status=%d want=%d body=%s", recorder.Code, http.StatusOK, recorder.Body.String())
}
if body := recorder.Body.String(); body == "" || !containsAll(body, "after", "iccid-new", "NEW") {
t.Fatalf("body=%q want fully refreshed overview payload", body)
}
}
func TestHandleEsimGetOverviewRefreshPreservesBusyContractOnRefreshFailure(t *testing.T) {
gin.SetMode(gin.TestMode)
for _, tc := range []struct {
name string
err error
}{
{name: "operation in progress", err: esim.ErrOperationInProgress},
{name: "apdu busy", err: apduarbiter.ErrAPDUBusy},
} {
t.Run(tc.name, func(t *testing.T) {
mgr := newTestEsimManager()
setNestedPrivateField(t, mgr, []string{"overviewLoader"}, func() (*esim.EsimOverview, error) {
return nil, tc.err
})
p := device.NewPool(&config.Config{})
setNestedPrivateField(t, p, []string{"workers"}, map[string]*device.Worker{
"dev-esim": {ID: "dev-esim", EsimMgr: mgr},
})
server := &Server{pool: p}
recorder := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(recorder)
ctx.Params = gin.Params{{Key: "id", Value: "dev-esim"}}
ctx.Request = httptest.NewRequest(http.MethodGet, "/devices/dev-esim/esim?refresh=true", nil)
server.handleEsimGetOverview(ctx)
if recorder.Code != http.StatusConflict {
t.Fatalf("status=%d want=%d body=%s", recorder.Code, http.StatusConflict, recorder.Body.String())
}
if got := recorder.Header().Get("Retry-After"); got != "2" {
t.Fatalf("Retry-After=%q want=2", got)
}
if body := recorder.Body.String(); body == "" || !containsAll(body, `"busy":true`, `"code":"ESIM_BUSY"`, `"reason":"refresh_overview"`, tc.err.Error()) {
t.Fatalf("body=%q want busy refresh-overview contract", body)
}
})
}
}
func TestHandleEsimGetOverviewRefreshPreservesResponseSemanticsWhenGetFailsAfterRefresh(t *testing.T) {
gin.SetMode(gin.TestMode)
internalErr := errors.New("overview load failed")
for _, tc := range []struct {
name string
getErr error
wantStatus int
wantParts []string
}{
{
name: "busy after refresh",
getErr: esim.ErrOperationInProgress,
wantStatus: http.StatusConflict,
wantParts: []string{`"busy":true`, `"code":"ESIM_BUSY"`, `"reason":"get_overview"`, esim.ErrOperationInProgress.Error()},
},
{
name: "internal after refresh",
getErr: internalErr,
wantStatus: http.StatusInternalServerError,
wantParts: []string{internalErr.Error()},
},
} {
t.Run(tc.name, func(t *testing.T) {
mgr := newTestEsimManager()
var calls int
setNestedPrivateField(t, mgr, []string{"overviewLoader"}, func() (*esim.EsimOverview, error) {
calls++
if calls == 1 {
setNestedPrivateField(t, mgr, []string{"overviewGeneration"}, uint64(2))
return &esim.EsimOverview{ChipInfo: &esim.EUICCChipInfo{SkuName: "refreshed"}}, nil
}
return nil, tc.getErr
})
p := device.NewPool(&config.Config{})
setNestedPrivateField(t, p, []string{"workers"}, map[string]*device.Worker{
"dev-esim": {ID: "dev-esim", EsimMgr: mgr},
})
server := &Server{pool: p}
recorder := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(recorder)
ctx.Params = gin.Params{{Key: "id", Value: "dev-esim"}}
ctx.Request = httptest.NewRequest(http.MethodGet, "/devices/dev-esim/esim?refresh=true", nil)
server.handleEsimGetOverview(ctx)
if recorder.Code != tc.wantStatus {
t.Fatalf("status=%d want=%d body=%s", recorder.Code, tc.wantStatus, recorder.Body.String())
}
if tc.wantStatus == http.StatusConflict {
if got := recorder.Header().Get("Retry-After"); got != "2" {
t.Fatalf("Retry-After=%q want=2", got)
}
}
if body := recorder.Body.String(); body == "" || !containsAll(body, tc.wantParts...) {
t.Fatalf("body=%q want parts=%v", body, tc.wantParts)
}
})
}
}
func TestEsimDeleteSuccessBodyIncludesWarningFields(t *testing.T) {
body := esimDeleteSuccessBody(esim.DeleteProfileResult{
Warning: "Profile 已删除,但删除通知发送未完全确认",
WarningCode: "delete_notification_not_observed",
SpaceDelta: &esim.SpaceDelta{
Direction: esim.SpaceDeltaDirectionReleased,
Bytes: 4096,
},
})
if body["status"] != "ok" || body["message"] != "Profile 删除成功" {
t.Fatalf("body=%v want ok delete success base fields", body)
}
if body["warning"] != "Profile 已删除,但删除通知发送未完全确认" {
t.Fatalf("warning=%v want propagated warning", body["warning"])
}
if body["warning_code"] != "delete_notification_not_observed" {
t.Fatalf("warning_code=%v want propagated warning_code", body["warning_code"])
}
spaceDelta, ok := body["space_delta"].(*esim.SpaceDelta)
if !ok || spaceDelta == nil || spaceDelta.Direction != esim.SpaceDeltaDirectionReleased || spaceDelta.Bytes != 4096 {
t.Fatalf("space_delta=%#v want released/4096", body["space_delta"])
}
}
func TestEsimDeleteSuccessBodyOmitsSpaceDeltaWhenUnavailable(t *testing.T) {
body := esimDeleteSuccessBody(esim.DeleteProfileResult{})
if _, ok := body["space_delta"]; ok {
t.Fatalf("body=%v want space_delta omitted", body)
}
}
func TestFormatEsimDownloadDoneEventIncludesSpaceDelta(t *testing.T) {
event := formatEsimDownloadDoneEvent(esim.DownloadProfileResult{
SpaceDelta: &esim.SpaceDelta{
Direction: esim.SpaceDeltaDirectionConsumed,
Bytes: 8192,
},
})
if !containsAll(event, `"step":"done"`, `"msg":"Profile 下载完成"`, `"pct":100`, `"space_delta":{"direction":"consumed","bytes":8192}`) {
t.Fatalf("event=%q want done payload with space_delta", event)
}
}
func TestFormatEsimDownloadDoneEventIncludesWarningFields(t *testing.T) {
event := formatEsimDownloadDoneEvent(esim.DownloadProfileResult{
Warning: "Profile 下载完成,但通知未完全确认",
WarningCode: "download_notification_handle_failed",
})
if !containsAll(event, `"step":"done"`, `"msg":"Profile 下载完成"`, `"pct":100`, `"warning":"Profile 下载完成,但通知未完全确认"`, `"warning_code":"download_notification_handle_failed"`) {
t.Fatalf("event=%q want done payload with warning fields", event)
}
}
func TestWriteEsimDownloadDoneEventWritesSingleWarningDoneFrame(t *testing.T) {
recorder := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(recorder)
writeEsimDownloadDoneEvent(ctx, esim.DownloadProfileResult{
Warning: "Profile 下载完成,但通知未完全确认",
WarningCode: "download_notification_handle_failed",
})
body := recorder.Body.String()
if !containsAll(body, `data: {"step":"done"`, `"warning":"Profile 下载完成,但通知未完全确认"`, `"warning_code":"download_notification_handle_failed"`) {
t.Fatalf("body=%q want SSE done frame with warning fields", body)
}
}
func TestFormatEsimDownloadErrorEventKeepsLegacyFieldsAndAddsCode(t *testing.T) {
event := formatEsimDownloadErrorEvent(esim.NewDownloadProfileError(sgp22.LoadBoundProfilePackageError{
BPPCommandID: 5,
ErrorReason: 10,
}))
if !containsAll(event,
`"step":"error"`,
`"msg":"下载失败: eUICC 安装 profile 时空间不足,请删除未使用的 profile 后重试"`,
`"pct":-1`,
`"code":"euicc_insufficient_memory"`,
`"details":"loadProfileElements,installFailedDueToInsufficientMemoryForProfile"`,
) {
t.Fatalf("event=%q want legacy error fields plus code/details", event)
}
}
func TestFormatEsimDownloadErrorEventSupportsPlainError(t *testing.T) {
event := formatEsimDownloadErrorEvent(errors.New("network down"))
if !containsAll(event, `"step":"error"`, `"msg":"下载失败: network down"`, `"pct":-1`) {
t.Fatalf("event=%q want legacy plain error fields", event)
}
if strings.Contains(event, `"code"`) || strings.Contains(event, `"details"`) {
t.Fatalf("event=%q should not include structured fields for plain errors", event)
}
}
func TestWriteEsimDeleteSuccessJSONWritesWarningFields(t *testing.T) {
recorder := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(recorder)
writeEsimDeleteSuccessJSON(ctx, esim.DeleteProfileResult{
Warning: "Profile 已删除,但删除通知发送未完全确认",
WarningCode: "delete_notification_not_observed",
})
if recorder.Code != http.StatusOK {
t.Fatalf("status=%d want=%d body=%s", recorder.Code, http.StatusOK, recorder.Body.String())
}
if body := recorder.Body.String(); body == "" || !containsAll(body, `"status":"ok"`, `"message":"Profile 删除成功"`, `"warning":"Profile 已删除,但删除通知发送未完全确认"`, `"warning_code":"delete_notification_not_observed"`) {
t.Fatalf("body=%q want success-with-warning delete payload", body)
}
}
func TestEsimDownloadExecPropagatesWarningResult(t *testing.T) {
var gotIMEI string
result, err := esimDownloadExec(func(ctx context.Context, aidHex, smdp, matchingID, confirmationCode, imei string, progressFn esim.DownloadProgressFn) (esim.DownloadProfileResult, error) {
gotIMEI = imei
return esim.DownloadProfileResult{
Warning: "Profile 下载完成,但通知未完全确认",
WarningCode: "download_notification_handle_failed",
}, nil
}, context.Background(), "A000", "example.com", "", "", "350225641234561", nil)
if err != nil {
t.Fatalf("esimDownloadExec() error=%v", err)
}
if result.WarningCode != "download_notification_handle_failed" {
t.Fatalf("result=%#v want warning result passthrough", result)
}
if gotIMEI != "350225641234561" {
t.Fatalf("imei=%q want forwarded custom IMEI", gotIMEI)
}
}
func TestEsimDeleteExecPropagatesWarningResult(t *testing.T) {
result, err := esimDeleteExec(func(string, string) (esim.DeleteProfileResult, error) {
return esim.DeleteProfileResult{
Warning: "Profile 已删除,但删除通知发送未完全确认",
WarningCode: "delete_notification_not_observed",
}, nil
}, "8986001234567890123", "A000")
if err != nil {
t.Fatalf("esimDeleteExec() error=%v", err)
}
if result.WarningCode != "delete_notification_not_observed" {
t.Fatalf("result=%#v want warning result passthrough", result)
}
}
func TestEsimNotificationsHTTPStatusMapsStructuredErrors(t *testing.T) {
cases := []struct {
name string
err error
want int
}{
{name: "busy", err: esim.ErrOperationInProgress, want: http.StatusConflict},
{name: "invalid sequence", err: esim.NewNotificationError(esim.NotificationErrorInvalidSequence, "bad seq", nil), want: http.StatusBadRequest},
{name: "invalid aid", err: esim.NewNotificationError(esim.NotificationErrorInvalidAIDHex, "bad aid", nil), want: http.StatusBadRequest},
{name: "not found", err: esim.NewNotificationError(esim.NotificationErrorNotFound, "missing", nil), want: http.StatusNotFound},
{name: "internal", err: esim.NewNotificationError(esim.NotificationErrorInternal, "boom", nil), want: http.StatusInternalServerError},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := esimNotificationHTTPStatus(tc.err); got != tc.want {
t.Fatalf("status=%d want=%d", got, tc.want)
}
})
}
}
func TestEsimNotificationExecHelpersPropagateResults(t *testing.T) {
items, err := esimNotificationListExec(func(string) ([]esim.NotificationItem, error) {
return []esim.NotificationItem{{SequenceNumber: 11, Event: "install", ICCID: "8986001234567890123", Address: "install.example.com", AIDHex: "A000", CanRetry: true}}, nil
}, "A000")
if err != nil {
t.Fatalf("esimNotificationListExec() error=%v", err)
}
if len(items) != 1 || items[0].SequenceNumber != 11 || items[0].Event != "install" {
t.Fatalf("items=%#v want passthrough notification item", items)
}
if err := esimNotificationRetryExec(func(sequence int64, aidHex string) error {
if sequence != 11 || aidHex != "A000" {
t.Fatalf("sequence=%d aidHex=%q want 11/A000", sequence, aidHex)
}
return nil
}, 11, "A000"); err != nil {
t.Fatalf("esimNotificationRetryExec() error=%v", err)
}
}
func TestHandleEsimNotificationListUsesJSONContract(t *testing.T) {
gin.SetMode(gin.TestMode)
oldExec := esimNotificationListExec
defer func() { esimNotificationListExec = oldExec }()
mgr := newTestEsimManager()
p := device.NewPool(&config.Config{})
setNestedPrivateField(t, p, []string{"workers"}, map[string]*device.Worker{
"dev-esim": {ID: "dev-esim", EsimMgr: mgr},
})
server := &Server{pool: p}
esimNotificationListExec = func(_ func(string) ([]esim.NotificationItem, error), aidHex string) ([]esim.NotificationItem, error) {
if aidHex != "A000" {
t.Fatalf("aidHex=%q want A000", aidHex)
}
return []esim.NotificationItem{{SequenceNumber: 11, Event: "install", ICCID: "8986001234567890123", Address: "install.example.com", AIDHex: "A000", CanRetry: true}}, nil
}
recorder := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(recorder)
ctx.Params = gin.Params{{Key: "device_id", Value: "dev-esim"}}
ctx.Request = httptest.NewRequest(http.MethodGet, "/devices/dev-esim/esim/notifications?aid_hex=A000", nil)
server.handleEsimListNotifications(ctx)
if recorder.Code != http.StatusOK {
t.Fatalf("status=%d want=%d body=%s", recorder.Code, http.StatusOK, recorder.Body.String())
}
if body := recorder.Body.String(); body == "" || !containsAll(body, `"items"`, `"sequence_number":11`, `"event":"install"`, `"aid_hex":"A000"`, `"can_retry":true`) {
t.Fatalf("body=%q want notification list payload", body)
}
}
func TestHandleEsimNotificationListPassesEmptyAidForCurrentCardDefault(t *testing.T) {
gin.SetMode(gin.TestMode)
oldExec := esimNotificationListExec
defer func() { esimNotificationListExec = oldExec }()
mgr := newTestEsimManager()
p := device.NewPool(&config.Config{})
setNestedPrivateField(t, p, []string{"workers"}, map[string]*device.Worker{
"dev-esim": {ID: "dev-esim", EsimMgr: mgr},
})
server := &Server{pool: p}
esimNotificationListExec = func(_ func(string) ([]esim.NotificationItem, error), aidHex string) ([]esim.NotificationItem, error) {
if aidHex != "" {
t.Fatalf("aidHex=%q want empty current-card default", aidHex)
}
return []esim.NotificationItem{{SequenceNumber: 11, Event: "install", AIDHex: "A000", CanRetry: true}}, nil
}
recorder := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(recorder)
ctx.Params = gin.Params{{Key: "device_id", Value: "dev-esim"}}
ctx.Request = httptest.NewRequest(http.MethodGet, "/devices/dev-esim/esim/notifications", nil)
server.handleEsimListNotifications(ctx)
if recorder.Code != http.StatusOK {
t.Fatalf("status=%d want=%d body=%s", recorder.Code, http.StatusOK, recorder.Body.String())
}
}
func TestHandleEsimRetryNotificationMapsStatusCodes(t *testing.T) {
gin.SetMode(gin.TestMode)
oldExec := esimNotificationRetryExec
defer func() { esimNotificationRetryExec = oldExec }()
cases := []struct {
name string
err error
wantStatus int
wantParts []string
}{
{name: "success", err: nil, wantStatus: http.StatusOK, wantParts: []string{`"status":"ok"`, `"message":"通知重试发送成功"`}},
{name: "busy", err: esim.ErrOperationInProgress, wantStatus: http.StatusConflict, wantParts: []string{`"busy":true`, `"code":"ESIM_BUSY"`, `"reason":"retry_notification"`}},
{name: "invalid", err: esim.NewNotificationError(esim.NotificationErrorInvalidSequence, "bad seq", nil), wantStatus: http.StatusBadRequest, wantParts: []string{`bad seq`}},
{name: "not found", err: esim.NewNotificationError(esim.NotificationErrorNotFound, "missing", nil), wantStatus: http.StatusNotFound, wantParts: []string{`missing`}},
{name: "internal", err: esim.NewNotificationError(esim.NotificationErrorInternal, "boom", nil), wantStatus: http.StatusInternalServerError, wantParts: []string{`boom`}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
mgr := newTestEsimManager()
p := device.NewPool(&config.Config{})
setNestedPrivateField(t, p, []string{"workers"}, map[string]*device.Worker{
"dev-esim": {ID: "dev-esim", EsimMgr: mgr},
})
server := &Server{pool: p}
esimNotificationRetryExec = func(_ func(int64, string) error, sequence int64, aidHex string) error {
if sequence != 11 || aidHex != "A000" {
t.Fatalf("sequence=%d aidHex=%q want 11/A000", sequence, aidHex)
}
return tc.err
}
recorder := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(recorder)
ctx.Params = gin.Params{{Key: "device_id", Value: "dev-esim"}, {Key: "sequence", Value: "11"}}
ctx.Request = httptest.NewRequest(http.MethodPost, "/devices/dev-esim/esim/notifications/11/actions/retry?aid_hex=A000", nil)
server.handleEsimRetryNotification(ctx)
if recorder.Code != tc.wantStatus {
t.Fatalf("status=%d want=%d body=%s", recorder.Code, tc.wantStatus, recorder.Body.String())
}
if tc.wantStatus == http.StatusConflict {
if got := recorder.Header().Get("Retry-After"); got != "2" {
t.Fatalf("Retry-After=%q want=2", got)
}
}
if body := recorder.Body.String(); body == "" || !containsAll(body, tc.wantParts...) {
t.Fatalf("body=%q want parts=%v", body, tc.wantParts)
}
})
}
}
+114
View File
@@ -0,0 +1,114 @@
package api
import (
"testing"
"github.com/iniwex5/vohive/internal/config"
)
func TestDeviceConfigDTOPreservesQMIProxyFields(t *testing.T) {
cfg := config.DeviceConfig{
ID: "dev-qmi",
QMIUseProxy: true,
QMIProxyPath: "custom-qmi-proxy",
QMIProxyExecutable: "/opt/vohive/bin/qmi-proxy",
}
dto := deviceConfigToDTO(cfg)
if dto.QMIUseProxy == nil || !*dto.QMIUseProxy {
t.Fatal("dto.QMIUseProxy=nil/false, want true")
}
if dto.QMIProxyPath == nil || *dto.QMIProxyPath != cfg.QMIProxyPath {
t.Fatalf("dto.QMIProxyPath=%v, want %q", dto.QMIProxyPath, cfg.QMIProxyPath)
}
if dto.QMIProxyExecutable == nil || *dto.QMIProxyExecutable != cfg.QMIProxyExecutable {
t.Fatalf("dto.QMIProxyExecutable=%v, want %q", dto.QMIProxyExecutable, cfg.QMIProxyExecutable)
}
roundTrip := deviceConfigFromDTO(dto)
if !roundTrip.QMIUseProxy {
t.Fatal("roundTrip.QMIUseProxy=false, want true")
}
if roundTrip.QMIProxyPath != cfg.QMIProxyPath {
t.Fatalf("roundTrip.QMIProxyPath=%q, want %q", roundTrip.QMIProxyPath, cfg.QMIProxyPath)
}
if roundTrip.QMIProxyExecutable != cfg.QMIProxyExecutable {
t.Fatalf("roundTrip.QMIProxyExecutable=%q, want %q", roundTrip.QMIProxyExecutable, cfg.QMIProxyExecutable)
}
}
func TestDeviceConfigDTOPreservesIPVersion(t *testing.T) {
cfg := config.DeviceConfig{
ID: "dev-ipv",
IPVersion: "v4v6",
}
dto := deviceConfigToDTO(cfg)
if dto.IPVersion != "v4v6" {
t.Fatalf("dto.IPVersion=%q, want v4v6", dto.IPVersion)
}
roundTrip := deviceConfigFromDTO(dto)
if roundTrip.IPVersion != "v4v6" {
t.Fatalf("roundTrip.IPVersion=%q, want v4v6", roundTrip.IPVersion)
}
}
func TestDeviceConfigFromDTOWithBasePreservesOmittedQMIProxyFields(t *testing.T) {
base := config.DeviceConfig{
ID: "dev-qmi",
Name: "old name",
ControlDevice: "/dev/cdc-wdm0",
QMIUseProxy: true,
QMIProxyPath: "qmi-proxy",
QMIProxyExecutable: "/usr/libexec/qmi-proxy",
}
cfg := deviceConfigFromDTOWithBase(deviceConfigDTO{
ID: "dev-qmi",
Name: "new name",
ControlDevice: "/dev/cdc-wdm0",
}, &base)
if cfg.Name != "new name" {
t.Fatalf("Name=%q, want %q", cfg.Name, "new name")
}
if !cfg.QMIUseProxy {
t.Fatal("QMIUseProxy=false, want preserved true")
}
if cfg.QMIProxyPath != base.QMIProxyPath {
t.Fatalf("QMIProxyPath=%q, want %q", cfg.QMIProxyPath, base.QMIProxyPath)
}
if cfg.QMIProxyExecutable != base.QMIProxyExecutable {
t.Fatalf("QMIProxyExecutable=%q, want %q", cfg.QMIProxyExecutable, base.QMIProxyExecutable)
}
}
func TestDeviceConfigFromDTOWithBaseAppliesExplicitQMIProxyFields(t *testing.T) {
base := config.DeviceConfig{
ID: "dev-qmi",
QMIUseProxy: true,
QMIProxyPath: "qmi-proxy",
QMIProxyExecutable: "/usr/libexec/qmi-proxy",
}
useProxy := false
proxyPath := ""
proxyExecutable := ""
cfg := deviceConfigFromDTOWithBase(deviceConfigDTO{
ID: "dev-qmi",
QMIUseProxy: &useProxy,
QMIProxyPath: &proxyPath,
QMIProxyExecutable: &proxyExecutable,
}, &base)
if cfg.QMIUseProxy {
t.Fatal("QMIUseProxy=true, want explicit false")
}
if cfg.QMIProxyPath != "" {
t.Fatalf("QMIProxyPath=%q, want empty", cfg.QMIProxyPath)
}
if cfg.QMIProxyExecutable != "" {
t.Fatalf("QMIProxyExecutable=%q, want empty", cfg.QMIProxyExecutable)
}
}
+73
View File
@@ -0,0 +1,73 @@
package api
import "github.com/iniwex5/vohive/internal/config"
func deviceConfigRequiresRestart(old config.DeviceConfig, next config.DeviceConfig) bool {
if config.NormalizeIMEI(old.ModemIMEI) != config.NormalizeIMEI(next.ModemIMEI) {
return true
}
if old.USBPath != next.USBPath {
return true
}
if old.Interface != next.Interface {
return true
}
if old.ProxyPort != next.ProxyPort {
return true
}
if old.ATPort != next.ATPort {
return true
}
if old.ControlDevice != next.ControlDevice {
return true
}
if config.NormalizeESIMTransport(old.ESIMTransport) != config.NormalizeESIMTransport(next.ESIMTransport) {
return true
}
if old.BaudRate != next.BaudRate {
return true
}
if old.DataBits != next.DataBits {
return true
}
if old.StopBits != next.StopBits {
return true
}
if old.Parity != next.Parity {
return true
}
if old.APN != next.APN {
return true
}
if old.IPVersion != next.IPVersion {
return true
}
// 后端模式变更(at↔qmi↔auto)需要重建 Worker
if old.DeviceBackend != next.DeviceBackend {
return true
}
if qmiProxyConfigChanged(old, next) {
return true
}
return false
}
func qmiProxyConfigChanged(old config.DeviceConfig, next config.DeviceConfig) bool {
if old.QMIUseProxy != next.QMIUseProxy {
return true
}
if old.QMIProxyPath != next.QMIProxyPath {
return true
}
if old.QMIProxyExecutable != next.QMIProxyExecutable {
return true
}
return false
}
func managedNetworkConfigChanged(old, next config.DeviceConfig) bool {
return old.APN != next.APN ||
old.Interface != next.Interface ||
old.ControlDevice != next.ControlDevice ||
old.IPVersion != next.IPVersion
}
+128
View File
@@ -0,0 +1,128 @@
package api
import (
"testing"
"github.com/iniwex5/vohive/internal/config"
)
func TestDeviceConfigRequiresRestartWhenQMIProxyConfigChanges(t *testing.T) {
base := config.DeviceConfig{
ID: "dev-qmi",
ControlDevice: "/dev/cdc-wdm0",
DeviceBackend: "qmi",
QMIUseProxy: true,
QMIProxyPath: "qmi-proxy",
QMIProxyExecutable: "/usr/libexec/qmi-proxy",
}
tests := []struct {
name string
edit func(*config.DeviceConfig)
}{
{
name: "use proxy toggled",
edit: func(next *config.DeviceConfig) {
next.QMIUseProxy = false
},
},
{
name: "proxy path changed",
edit: func(next *config.DeviceConfig) {
next.QMIProxyPath = "custom-qmi-proxy"
},
},
{
name: "proxy executable changed",
edit: func(next *config.DeviceConfig) {
next.QMIProxyExecutable = "/opt/qmi-proxy"
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
next := base
tt.edit(&next)
if !deviceConfigRequiresRestart(base, next) {
t.Fatal("deviceConfigRequiresRestart()=false, want true")
}
})
}
}
func TestDeviceConfigRequiresRestartIgnoresIMEIFormatOnly(t *testing.T) {
old := config.DeviceConfig{ModemIMEI: "864388041069422"}
next := config.DeviceConfig{ModemIMEI: " 864388041069422"}
if deviceConfigRequiresRestart(old, next) {
t.Fatal("format-only IMEI difference must not require restart")
}
if deviceConfigRequiresRestart(config.DeviceConfig{}, config.DeviceConfig{}) {
t.Fatal("two empty IMEIs must not require restart")
}
diff := config.DeviceConfig{ModemIMEI: "864513045234397"}
if !deviceConfigRequiresRestart(old, diff) {
t.Fatal("different modem IMEI must require restart")
}
imeisv := config.DeviceConfig{ModemIMEI: "8643880410694201"}
if deviceConfigRequiresRestart(old, imeisv) {
t.Fatal("IMEISV-only IMEI difference must not require restart")
}
}
func TestDeviceConfigMBIMManagedNetworkChangesRequiresRebuild(t *testing.T) {
base := config.DeviceConfig{
APN: "internet",
Interface: "wwan0",
ControlDevice: "/dev/cdc-wdm0",
IPVersion: "ipv4",
}
tests := []struct {
name string
edit func(*config.DeviceConfig)
}{
{
name: "APN changed",
edit: func(next *config.DeviceConfig) {
next.APN = "fast.t-mobile.com"
},
},
{
name: "Interface changed",
edit: func(next *config.DeviceConfig) {
next.Interface = "wwan1"
},
},
{
name: "ControlDevice changed",
edit: func(next *config.DeviceConfig) {
next.ControlDevice = "/dev/cdc-wdm1"
},
},
{
name: "IPVersion changed",
edit: func(next *config.DeviceConfig) {
next.IPVersion = "ipv4v6"
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
next := base
tt.edit(&next)
if !managedNetworkConfigChanged(base, next) {
t.Fatalf("managedNetworkConfigChanged()=false, want true for %s", tt.name)
}
})
}
if managedNetworkConfigChanged(base, base) {
t.Fatal("managedNetworkConfigChanged()=true for identical configs, want false")
}
}
@@ -0,0 +1,17 @@
package api
import (
"os"
"path/filepath"
"strings"
"testing"
)
func writeDeviceMgmtLimitConfig(t *testing.T, content string) string {
t.Helper()
path := filepath.Join(t.TempDir(), "config.yaml")
if err := os.WriteFile(path, []byte(strings.TrimSpace(content)+"\n"), 0o600); err != nil {
t.Fatalf("WriteFile() error = %v", err)
}
return path
}
+426
View File
@@ -0,0 +1,426 @@
package api
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/iniwex5/vohive/internal/backend"
"github.com/iniwex5/vohive/internal/config"
"github.com/iniwex5/vohive/internal/device"
)
type ussdDeviceBackendStub struct {
mode string
imei string
rebootErr error
rebooted bool
}
var _ backend.DeviceBackend = (*ussdDeviceBackendStub)(nil)
func (s *ussdDeviceBackendStub) GetIMEI(ctx context.Context) (string, error) { return s.imei, nil }
func (s *ussdDeviceBackendStub) GetIMSI(ctx context.Context) (string, error) { return "", nil }
func (s *ussdDeviceBackendStub) GetICCID(ctx context.Context) (string, error) { return "", nil }
func (s *ussdDeviceBackendStub) GetMSISDN(ctx context.Context) (string, error) { return "", nil }
func (s *ussdDeviceBackendStub) GetRevision(ctx context.Context) (string, error) { return "", nil }
func (s *ussdDeviceBackendStub) GetSignalInfo(ctx context.Context) (*backend.SignalInfo, error) {
return nil, nil
}
func (s *ussdDeviceBackendStub) GetServingSystem(ctx context.Context) (*backend.ServingSystem, error) {
return nil, nil
}
func (s *ussdDeviceBackendStub) IsSimInserted(ctx context.Context) (bool, error) { return true, nil }
func (s *ussdDeviceBackendStub) GetNativeMCCMNC(ctx context.Context) (string, string, error) {
return "", "", nil
}
func (s *ussdDeviceBackendStub) GetNativeSPN(ctx context.Context) (string, error) { return "", nil }
func (s *ussdDeviceBackendStub) GetSIMMetadata(ctx context.Context) (*backend.SIMMetadata, error) {
return nil, nil
}
func (s *ussdDeviceBackendStub) SendSMS(ctx context.Context, to, body string) error { return nil }
func (s *ussdDeviceBackendStub) ReadSMS(ctx context.Context, index int) (*backend.SMS, error) {
return nil, nil
}
func (s *ussdDeviceBackendStub) DeleteSMS(ctx context.Context, index int) error { return nil }
func (s *ussdDeviceBackendStub) ListSMS(ctx context.Context) ([]backend.SMSSummary, error) {
return nil, nil
}
func (s *ussdDeviceBackendStub) DeleteAllSMS(ctx context.Context) error { return nil }
func (s *ussdDeviceBackendStub) SetOperatingMode(ctx context.Context, mode backend.OperatingMode) error {
return nil
}
func (s *ussdDeviceBackendStub) GetOperatingMode(ctx context.Context) (backend.OperatingMode, error) {
return backend.ModeOnline, nil
}
func (s *ussdDeviceBackendStub) Reboot(ctx context.Context) error {
s.rebooted = true
return s.rebootErr
}
func (s *ussdDeviceBackendStub) OpenLogicalChannel(ctx context.Context, aid string) (int, error) {
return 0, nil
}
func (s *ussdDeviceBackendStub) CloseLogicalChannel(ctx context.Context, channelID int) error {
return nil
}
func (s *ussdDeviceBackendStub) TransmitAPDU(ctx context.Context, channelID int, command string) (string, error) {
return "", nil
}
func (s *ussdDeviceBackendStub) TransmitBasicAPDU(ctx context.Context, command string) (string, error) {
return "", nil
}
func (s *ussdDeviceBackendStub) Mode() string {
if s.mode == "" {
return backend.BackendAT
}
return s.mode
}
func (s *ussdDeviceBackendStub) Close() error { return nil }
type ussdProviderBackendStub struct {
ussdDeviceBackendStub
command string
timeout time.Duration
continueInput string
continueTimeout time.Duration
cancelCalled bool
}
var _ backend.USSDProvider = (*ussdProviderBackendStub)(nil)
func (s *ussdProviderBackendStub) ExecuteUSSD(ctx context.Context, command string, timeout time.Duration) (*backend.USSDResult, error) {
s.command = command
s.timeout = timeout
return &backend.USSDResult{Status: 0, Text: "ok", RawText: "ok", DCS: 15}, nil
}
func (s *ussdProviderBackendStub) ContinueUSSD(ctx context.Context, input string, timeout time.Duration) (*backend.USSDResult, error) {
s.continueInput = input
s.continueTimeout = timeout
return &backend.USSDResult{Status: 0, Text: "continued", RawText: "continued", DCS: 15}, nil
}
func (s *ussdProviderBackendStub) CancelUSSD(ctx context.Context) error {
s.cancelCalled = true
return nil
}
func TestHandleDeviceMgmtExecuteUSSDUsesBackendProvider(t *testing.T) {
gin.SetMode(gin.TestMode)
p := device.NewPool(&config.Config{})
be := &ussdProviderBackendStub{ussdDeviceBackendStub: ussdDeviceBackendStub{mode: backend.BackendQMI}}
setNestedPrivateField(t, p, []string{"workers"}, map[string]*device.Worker{
"dev-qmi": {ID: "dev-qmi", Backend: be},
})
server := &Server{pool: p}
rec := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(rec)
ctx.Params = gin.Params{{Key: "device_id", Value: "dev-qmi"}}
ctx.Request = httptest.NewRequest(http.MethodPost, "/devices/dev-qmi/actions/ussd", strings.NewReader(`{"command":" *100# ","timeout_ms":7000}`))
ctx.Request.Header.Set("Content-Type", "application/json")
server.handleDeviceMgmtExecuteUSSD(ctx)
if rec.Code != http.StatusOK {
t.Fatalf("status=%d want=%d body=%s", rec.Code, http.StatusOK, rec.Body.String())
}
if be.command != "*100#" || be.timeout != 7*time.Second {
t.Fatalf("provider got command=%q timeout=%s", be.command, be.timeout)
}
var body struct {
Status string `json:"status"`
Result backend.USSDResult `json:"result"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("response JSON error=%v body=%s", err, rec.Body.String())
}
if body.Status != "ok" || body.Result.Text != "ok" {
t.Fatalf("response=%+v want ok result", body)
}
}
func TestHandleDeviceMgmtExecuteUSSDDefaultsToStandardNetworkTimeout(t *testing.T) {
gin.SetMode(gin.TestMode)
p := device.NewPool(&config.Config{})
be := &ussdProviderBackendStub{ussdDeviceBackendStub: ussdDeviceBackendStub{mode: backend.BackendQMI}}
setNestedPrivateField(t, p, []string{"workers"}, map[string]*device.Worker{
"dev-qmi": {ID: "dev-qmi", Backend: be},
})
server := &Server{pool: p}
rec := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(rec)
ctx.Params = gin.Params{{Key: "device_id", Value: "dev-qmi"}}
ctx.Request = httptest.NewRequest(http.MethodPost, "/devices/dev-qmi/actions/ussd", strings.NewReader(`{"command":"*100#"}`))
ctx.Request.Header.Set("Content-Type", "application/json")
server.handleDeviceMgmtExecuteUSSD(ctx)
if rec.Code != http.StatusOK {
t.Fatalf("status=%d want=%d body=%s", rec.Code, http.StatusOK, rec.Body.String())
}
if be.timeout != 45*time.Second {
t.Fatalf("provider timeout=%s want 45s default", be.timeout)
}
}
func TestHandleDeviceMgmtExecuteUSSDRejectsUnsupportedBackend(t *testing.T) {
gin.SetMode(gin.TestMode)
p := device.NewPool(&config.Config{})
be := &ussdDeviceBackendStub{mode: backend.BackendQMI}
setNestedPrivateField(t, p, []string{"workers"}, map[string]*device.Worker{
"dev-qmi": {ID: "dev-qmi", Backend: be},
})
server := &Server{pool: p}
rec := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(rec)
ctx.Params = gin.Params{{Key: "device_id", Value: "dev-qmi"}}
ctx.Request = httptest.NewRequest(http.MethodPost, "/devices/dev-qmi/actions/ussd", strings.NewReader(`{"command":"*100#"}`))
ctx.Request.Header.Set("Content-Type", "application/json")
server.handleDeviceMgmtExecuteUSSD(ctx)
if rec.Code != http.StatusBadRequest {
t.Fatalf("status=%d want=%d body=%s", rec.Code, http.StatusBadRequest, rec.Body.String())
}
if !strings.Contains(rec.Body.String(), "当前设备后端不支持 USSD") {
t.Fatalf("body=%s want capability error", rec.Body.String())
}
}
func TestHandleDeviceMgmtContinueUSSDUsesBackendProviderWhenVoWiFiInactive(t *testing.T) {
gin.SetMode(gin.TestMode)
p := device.NewPool(&config.Config{})
be := &ussdProviderBackendStub{ussdDeviceBackendStub: ussdDeviceBackendStub{mode: backend.BackendMBIM}}
setNestedPrivateField(t, p, []string{"workers"}, map[string]*device.Worker{
"dev-mbim": {ID: "dev-mbim", Backend: be},
})
server := &Server{pool: p}
rec := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(rec)
ctx.Params = gin.Params{{Key: "device_id", Value: "dev-mbim"}}
ctx.Request = httptest.NewRequest(http.MethodPost, "/devices/dev-mbim/actions/ussd/continue", strings.NewReader(`{"session_id":"cs","input":" 1 ","timeout_ms":8000}`))
ctx.Request.Header.Set("Content-Type", "application/json")
server.handleDeviceMgmtContinueUSSD(ctx)
if rec.Code != http.StatusOK {
t.Fatalf("status=%d want=%d body=%s", rec.Code, http.StatusOK, rec.Body.String())
}
if be.continueInput != "1" || be.continueTimeout != 8*time.Second {
t.Fatalf("provider got input=%q timeout=%s", be.continueInput, be.continueTimeout)
}
if !strings.Contains(rec.Body.String(), `"channel":"cs"`) {
t.Fatalf("body=%s want CS channel", rec.Body.String())
}
}
func TestHandleDeviceMgmtCancelUSSDUsesBackendProviderWhenVoWiFiInactive(t *testing.T) {
gin.SetMode(gin.TestMode)
p := device.NewPool(&config.Config{})
be := &ussdProviderBackendStub{ussdDeviceBackendStub: ussdDeviceBackendStub{mode: backend.BackendMBIM}}
setNestedPrivateField(t, p, []string{"workers"}, map[string]*device.Worker{
"dev-mbim": {ID: "dev-mbim", Backend: be},
})
server := &Server{pool: p}
rec := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(rec)
ctx.Params = gin.Params{{Key: "device_id", Value: "dev-mbim"}}
ctx.Request = httptest.NewRequest(http.MethodPost, "/devices/dev-mbim/actions/ussd/cancel", strings.NewReader(`{"session_id":"cs"}`))
ctx.Request.Header.Set("Content-Type", "application/json")
server.handleDeviceMgmtCancelUSSD(ctx)
if rec.Code != http.StatusOK {
t.Fatalf("status=%d want=%d body=%s", rec.Code, http.StatusOK, rec.Body.String())
}
if !be.cancelCalled {
t.Fatal("provider CancelUSSD was not called")
}
}
// TestShouldUseATFirstRebootSkipsForQMIBackend 测试 QMI 模式设备重启不应优先走 AT+CFUN,
// 应直接使用 QMI ModeReset(backend.Reboot),仅 AT 模式设备才保留 AT 优先路径。
func TestShouldUseATFirstRebootSkipsForQMIBackend(t *testing.T) {
if shouldUseATFirstReboot(backend.BackendQMI) {
t.Fatal("shouldUseATFirstReboot(qmi) = true, want false — QMI 模式应直接走 QMI ModeReset")
}
if !shouldUseATFirstReboot(backend.BackendAT) {
t.Fatal("shouldUseATFirstReboot(at) = false, want true — AT 模式应保留 AT 优先路径")
}
}
func TestHandleDeviceMgmtRebootDoesNotScheduleRecoveryOnQMITransportFailure(t *testing.T) {
gin.SetMode(gin.TestMode)
p := device.NewPool(&config.Config{})
be := &ussdDeviceBackendStub{
mode: backend.BackendQMI,
rebootErr: errors.New("write failed: write unix @->@qmi-proxy: write: broken pipe"),
}
worker := &device.Worker{ID: "dev-qmi", Backend: be}
setNestedPrivateField(t, p, []string{"workers"}, map[string]*device.Worker{
"dev-qmi": worker,
})
server := &Server{pool: p}
rec := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(rec)
ctx.Params = gin.Params{{Key: "device_id", Value: "dev-qmi"}}
ctx.Request = httptest.NewRequest(http.MethodPost, "/devices/dev-qmi/actions/reboot", nil)
server.handleDeviceMgmtReboot(ctx)
if rec.Code != http.StatusInternalServerError {
t.Fatalf("status=%d want=%d body=%s", rec.Code, http.StatusInternalServerError, rec.Body.String())
}
if strings.Contains(rec.Body.String(), "已转入控制面恢复") {
t.Fatalf("body=%s should not report recovery", rec.Body.String())
}
snapshot := worker.HealthSnapshot()
if snapshot.State == device.HealthStateReprobing {
t.Fatalf("health state=%s should not enter recovery", snapshot.State)
}
}
func TestHandleDeviceMgmtRebootDoesNotScheduleRecoveryWhenQMIControlNotReady(t *testing.T) {
gin.SetMode(gin.TestMode)
p := device.NewPool(&config.Config{})
be := &ussdDeviceBackendStub{
mode: backend.BackendQMI,
rebootErr: errors.New("QMI 服务未就绪: DMS"),
}
worker := &device.Worker{ID: "dev-qmi", Backend: be}
setNestedPrivateField(t, p, []string{"workers"}, map[string]*device.Worker{
"dev-qmi": worker,
})
server := &Server{pool: p}
rec := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(rec)
ctx.Params = gin.Params{{Key: "device_id", Value: "dev-qmi"}}
ctx.Request = httptest.NewRequest(http.MethodPost, "/devices/dev-qmi/actions/reboot", nil)
server.handleDeviceMgmtReboot(ctx)
if rec.Code != http.StatusInternalServerError {
t.Fatalf("status=%d want=%d body=%s", rec.Code, http.StatusInternalServerError, rec.Body.String())
}
if strings.Contains(rec.Body.String(), "已转入控制面恢复") {
t.Fatalf("body=%s should not report recovery", rec.Body.String())
}
snapshot := worker.HealthSnapshot()
if snapshot.State == device.HealthStateReprobing {
t.Fatalf("health state=%s should not enter recovery", snapshot.State)
}
lifecycle := p.LifecycleSnapshot("dev-qmi")
if lifecycle.Phase == device.LifecyclePhaseRebooting {
t.Fatalf("lifecycle phase=%s should not remain rebooting after failed reboot command", lifecycle.Phase)
}
}
func TestHandleDeviceMgmtRebootDoesNotEnterRebootingWhenCommandFails(t *testing.T) {
gin.SetMode(gin.TestMode)
p := device.NewPool(&config.Config{})
be := &ussdDeviceBackendStub{
mode: backend.BackendAT,
rebootErr: errors.New("AT channel unavailable"),
}
setNestedPrivateField(t, p, []string{"workers"}, map[string]*device.Worker{
"dev-at": {ID: "dev-at", Backend: be},
})
server := &Server{pool: p}
rec := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(rec)
ctx.Params = gin.Params{{Key: "device_id", Value: "dev-at"}}
ctx.Request = httptest.NewRequest(http.MethodPost, "/devices/dev-at/actions/reboot", nil)
server.handleDeviceMgmtReboot(ctx)
if rec.Code != http.StatusInternalServerError {
t.Fatalf("status=%d want=%d body=%s", rec.Code, http.StatusInternalServerError, rec.Body.String())
}
lifecycle := p.LifecycleSnapshot("dev-at")
if lifecycle.Phase == device.LifecyclePhaseRebooting {
t.Fatalf("lifecycle phase=%s should not be set before reboot command succeeds", lifecycle.Phase)
}
}
func TestHandleDeviceMgmtRebootRejectsMismatchedQMIIdentity(t *testing.T) {
gin.SetMode(gin.TestMode)
p := device.NewPool(&config.Config{})
be := &ussdDeviceBackendStub{
mode: backend.BackendQMI,
imei: "222222222222222",
}
worker := &device.Worker{
ID: "dev-qmi",
Config: config.DeviceConfig{
ID: "dev-qmi",
ModemIMEI: "111111111111111",
DeviceBackend: backend.BackendQMI,
},
Backend: be,
}
setNestedPrivateField(t, p, []string{"workers"}, map[string]*device.Worker{
"dev-qmi": worker,
})
server := &Server{pool: p}
rec := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(rec)
ctx.Params = gin.Params{{Key: "device_id", Value: "dev-qmi"}}
ctx.Request = httptest.NewRequest(http.MethodPost, "/devices/dev-qmi/actions/reboot", nil)
server.handleDeviceMgmtReboot(ctx)
if rec.Code != http.StatusConflict {
t.Fatalf("status=%d want=%d body=%s", rec.Code, http.StatusConflict, rec.Body.String())
}
if be.rebooted {
t.Fatal("backend Reboot was called despite IMEI mismatch")
}
if !strings.Contains(rec.Body.String(), "设备路径已漂移") {
t.Fatalf("body=%s want identity drift message", rec.Body.String())
}
}
func TestHandleDeviceMgmtReconnectVoWiFiReturnsRestartError(t *testing.T) {
gin.SetMode(gin.TestMode)
path := writeDeviceMgmtLimitConfig(t, `
server:
port: ":7575"
devices:
- id: dev-missing-worker
interface: wwan0
vowifi_enabled: true
`)
if err := config.InitGlobalManager(path); err != nil {
t.Fatalf("InitGlobalManager() error = %v", err)
}
server := &Server{pool: device.NewPool(&config.Config{}), configPath: path}
rec := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(rec)
ctx.Params = gin.Params{{Key: "device_id", Value: "dev-missing-worker"}}
ctx.Request = httptest.NewRequest(http.MethodPost, "/devices/dev-missing-worker/vowifi/actions/reconnect", nil)
server.handleDeviceMgmtReconnectVoWiFi(ctx)
if rec.Code != http.StatusInternalServerError {
t.Fatalf("status=%d want=%d body=%s", rec.Code, http.StatusInternalServerError, rec.Body.String())
}
if !strings.Contains(rec.Body.String(), "VoWiFi 重连失败") {
t.Fatalf("body=%s want reconnect failure", rec.Body.String())
}
}
+200
View File
@@ -0,0 +1,200 @@
package api
import (
"errors"
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/iniwex5/vohive/internal/backend"
"github.com/iniwex5/vohive/internal/config"
"github.com/iniwex5/vohive/internal/device"
"github.com/iniwex5/vohive/pkg/logger"
)
type operatorScanResponse struct {
ScanID string `json:"scan_id"`
Status string `json:"status"`
StartedAt time.Time `json:"started_at"`
UpdatedAt time.Time `json:"updated_at"`
Complete bool `json:"complete"`
Retryable bool `json:"retryable"`
Message string `json:"message"`
Error string `json:"error,omitempty"`
Candidates []backend.OperatorCandidate `json:"candidates"`
}
func operatorSelectionErrorStatus(err error) int {
switch {
case errors.Is(err, device.ErrVoWiFiActive), errors.Is(err, device.ErrESIMSwitching):
return http.StatusConflict
case errors.Is(err, device.ErrOperatorSelectionNotSupported):
return http.StatusBadRequest
case errors.Is(err, device.ErrBackendNotAvailable):
return http.StatusServiceUnavailable
default:
return http.StatusInternalServerError
}
}
func (s *Server) handleDeviceMgmtOperatorScan(c *gin.Context) {
deviceID := deviceIDParam(c)
w := s.pool.GetWorker(deviceID)
if w == nil {
c.JSON(http.StatusNotFound, gin.H{"error": "设备未找到或已离线"})
return
}
if err := validateOperatorScanWorker(w); err != nil {
logger.Error("扫描运营商失败", "device", deviceID, "err", err)
c.JSON(operatorSelectionErrorStatus(err), gin.H{"error": "扫描失败: " + err.Error()})
return
}
status, body := operatorScanHTTPStatusAndBody(w.StartOrGetOperatorScan(c.Request.Context()))
c.JSON(status, body)
}
func (s *Server) handleDeviceMgmtOperatorScanStream(c *gin.Context) {
c.Header("Content-Type", "text/event-stream")
c.Header("Cache-Control", "no-cache")
c.Header("Connection", "keep-alive")
deviceID := deviceIDParam(c)
w := s.pool.GetWorker(deviceID)
if w == nil {
c.SSEvent("operator_scan", operatorScanResponse{
Status: string(device.OperatorScanStatusFailed),
UpdatedAt: time.Now(),
Retryable: false,
Message: "设备未找到或已离线",
Error: "device_not_found",
})
c.Writer.Flush()
return
}
if err := validateOperatorScanWorker(w); err != nil {
c.SSEvent("operator_scan", operatorScanResponse{
Status: string(device.OperatorScanStatusFailed),
UpdatedAt: time.Now(),
Retryable: false,
Message: "扫描失败: " + err.Error(),
Error: err.Error(),
})
c.Writer.Flush()
return
}
notify := c.Writer.CloseNotify()
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
send := func(result device.OperatorScanResult) bool {
_, body := operatorScanHTTPStatusAndBody(result)
c.SSEvent("operator_scan", body)
c.Writer.Flush()
return operatorScanSSEShouldContinue(result)
}
if !send(w.StartOrGetOperatorScan(c.Request.Context())) {
return
}
for {
select {
case <-notify:
return
case <-c.Request.Context().Done():
return
case <-s.shutdownCh:
return
case <-ticker.C:
if !send(w.GetOperatorScanSnapshot()) {
return
}
}
}
}
func validateOperatorScanWorker(w *device.Worker) error {
if w == nil {
return device.ErrWorkerNil
}
if w.Backend == nil {
return device.ErrBackendNotAvailable
}
if _, ok := w.Backend.(backend.OperatorSelectionProvider); !ok {
return device.ErrOperatorSelectionNotSupported
}
return nil
}
func operatorScanSSEShouldContinue(result device.OperatorScanResult) bool {
return result.Status == device.OperatorScanStatusRunning
}
func operatorScanHTTPStatusAndBody(result device.OperatorScanResult) (int, operatorScanResponse) {
status := http.StatusOK
if result.Status == device.OperatorScanStatusRunning && len(result.Candidates) == 0 {
status = http.StatusAccepted
}
return status, operatorScanResponse{
ScanID: result.ScanID,
Status: string(result.Status),
StartedAt: result.StartedAt,
UpdatedAt: result.UpdatedAt,
Complete: result.Complete,
Retryable: result.Retryable,
Message: result.Message,
Error: result.Err,
Candidates: result.Candidates,
}
}
func (s *Server) handleDeviceMgmtGetOperatorSelection(c *gin.Context) {
deviceID := deviceIDParam(c)
w := s.pool.GetWorker(deviceID)
if w == nil {
c.JSON(http.StatusNotFound, gin.H{"error": "设备未找到或已离线"})
return
}
sel, err := w.GetOperatorSelection(c.Request.Context())
if err != nil {
logger.Error("读取运营商选择配置失败", "device", deviceID, "err", err)
c.JSON(operatorSelectionErrorStatus(err), gin.H{"error": "读取失败: " + err.Error()})
return
}
c.JSON(http.StatusOK, sel)
}
func (s *Server) handleDeviceMgmtSetOperatorSelection(c *gin.Context) {
deviceID := deviceIDParam(c)
var req backend.SetOperatorSelectionRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "参数无效"})
return
}
w := s.pool.GetWorker(deviceID)
if w == nil {
c.JSON(http.StatusNotFound, gin.H{"error": "设备未找到或已离线"})
return
}
sel, err := w.SetOperatorSelection(c.Request.Context(), req)
if err != nil {
logger.Error("设置运营商失败", "device", deviceID, "err", err)
c.JSON(operatorSelectionErrorStatus(err), gin.H{"error": "设置失败: " + err.Error()})
return
}
// Persist to file
if err := config.UpdateDeviceInFile(s.configPath, deviceID, w.Config); err != nil {
logger.Error("写入设备配置失败 (operator selection)", "device", deviceID, "err", err)
}
c.JSON(http.StatusOK, sel)
}
@@ -0,0 +1,110 @@
package api
import (
"errors"
"net/http"
"testing"
"time"
"github.com/iniwex5/vohive/internal/backend"
"github.com/iniwex5/vohive/internal/device"
)
func TestOperatorSelectionErrorStatusMapsBusyStatesToConflict(t *testing.T) {
tests := []struct {
name string
err error
want int
}{
{name: "vowifi active", err: device.ErrVoWiFiActive, want: http.StatusConflict},
{name: "esim switching", err: device.ErrESIMSwitching, want: http.StatusConflict},
{name: "unsupported", err: device.ErrOperatorSelectionNotSupported, want: http.StatusBadRequest},
{name: "backend missing", err: device.ErrBackendNotAvailable, want: http.StatusServiceUnavailable},
{name: "generic", err: errors.New("qmi failed"), want: http.StatusInternalServerError},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := operatorSelectionErrorStatus(tt.err); got != tt.want {
t.Fatalf("operatorSelectionErrorStatus(%v)=%d want %d", tt.err, got, tt.want)
}
})
}
}
func TestOperatorScanHTTPStatusAndBodyRunningWithoutCandidatesReturnsAccepted(t *testing.T) {
now := time.Now()
status, body := operatorScanHTTPStatusAndBody(device.OperatorScanResult{
ScanID: "scan-1",
Status: device.OperatorScanStatusRunning,
StartedAt: now,
UpdatedAt: now,
Message: "扫描进行中",
})
if status != http.StatusAccepted {
t.Fatalf("status=%d want %d", status, http.StatusAccepted)
}
if body.Status != string(device.OperatorScanStatusRunning) {
t.Fatalf("body status=%q", body.Status)
}
}
func TestOperatorScanHTTPStatusAndBodyRetryableFailureReturnsOK(t *testing.T) {
now := time.Now()
status, body := operatorScanHTTPStatusAndBody(device.OperatorScanResult{
ScanID: "scan-2",
Status: device.OperatorScanStatusFailed,
StartedAt: now,
UpdatedAt: now,
Retryable: true,
Message: "扫描超时或模组忙,请稍后重试",
Err: "context deadline exceeded",
})
if status != http.StatusOK {
t.Fatalf("status=%d want %d", status, http.StatusOK)
}
if !body.Retryable {
t.Fatal("retryable=false want true")
}
if body.Message != "扫描超时或模组忙,请稍后重试" {
t.Fatalf("message=%q", body.Message)
}
}
func TestOperatorScanHTTPStatusAndBodyCompleteKeepsCandidates(t *testing.T) {
now := time.Now()
status, body := operatorScanHTTPStatusAndBody(device.OperatorScanResult{
ScanID: "scan-3",
Status: device.OperatorScanStatusComplete,
StartedAt: now,
UpdatedAt: now,
Complete: true,
Message: "扫描完成",
Candidates: []backend.OperatorCandidate{{PLMN: "46000", OperatorName: "CMCC", Status: "available"}},
})
if status != http.StatusOK {
t.Fatalf("status=%d want %d", status, http.StatusOK)
}
if len(body.Candidates) != 1 {
t.Fatalf("len(candidates)=%d want 1", len(body.Candidates))
}
}
func TestOperatorScanSSEShouldContinueOnlyForRunning(t *testing.T) {
tests := []struct {
name string
result device.OperatorScanResult
want bool
}{
{name: "running", result: device.OperatorScanResult{Status: device.OperatorScanStatusRunning}, want: true},
{name: "complete", result: device.OperatorScanResult{Status: device.OperatorScanStatusComplete}, want: false},
{name: "failed", result: device.OperatorScanResult{Status: device.OperatorScanStatusFailed}, want: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := operatorScanSSEShouldContinue(tt.result); got != tt.want {
t.Fatalf("operatorScanSSEShouldContinue(%s)=%v want %v", tt.result.Status, got, tt.want)
}
})
}
}
+68
View File
@@ -0,0 +1,68 @@
package api
import (
"errors"
"github.com/iniwex5/vohive/internal/config"
"github.com/iniwex5/vohive/internal/db"
)
// cardPolicyFromDeviceConfig 把设备保存 DTO 解析出的策略字段映射为 card_policies 行。
// SMS 不入策略(恒开),source 标记为 user(人工编辑)。不变式由 db.UpsertCardPolicy 归一。
func cardPolicyFromDeviceConfig(iccid string, cfg config.DeviceConfig) db.CardPolicy {
return db.CardPolicy{
ICCID: iccid,
NetworkEnabled: cfg.NetworkEnabled,
VoWiFiEnabled: cfg.VoWiFiEnabled,
AirplaneEnabled: cfg.AirplaneEnabled,
IPVersion: cfg.IPVersion,
APN: cfg.APN,
Source: "user",
}
}
// currentEffectiveDevicePolicy 返回设备保存前的旧有效策略(用于开关转换判断):
// 在线取 worker 投影(已是有效值),离线退回 card_policies 解析。同时返回解析到的 ICCID。
func (s *Server) currentEffectiveDevicePolicy(deviceID string) (iccid string, network, vowifi bool, ipVersion, apn string) {
if s.pool != nil {
if w := s.pool.GetWorker(deviceID); w != nil {
return w.CurrentICCID(), w.Config.NetworkEnabled, w.Config.VoWiFiEnabled, w.Config.IPVersion, w.Config.APN
}
}
off := resolveOfflineDevicePolicy(deviceID)
return db.CurrentICCIDForDevice(deviceID), off.NetworkEnabled, off.VoWiFiEnabled, off.IPVersion, off.APN
}
// offlineDevicePolicy 是离线设备(无运行中 worker)用于展示的有效卡策略。
type offlineDevicePolicy struct {
NetworkEnabled bool
VoWiFiEnabled bool
SMSEnabled bool
IPVersion string
APN string
}
// resolveOfflineDevicePolicy 解析离线设备的有效策略用于 UI 展示:
// device → 当前 ICCID → card_policies。无 ICCID 或无策略记录时返回安全默认。
// SMS 恒为启用(写死系统语义),与 card_policies 无关。
func resolveOfflineDevicePolicy(deviceID string) offlineDevicePolicy {
out := offlineDevicePolicy{SMSEnabled: true, IPVersion: "v4"}
iccid := db.CurrentICCIDForDevice(deviceID)
if iccid == "" {
return out
}
pol, err := db.GetCardPolicy(iccid)
if err != nil {
if errors.Is(err, db.ErrCardPolicyNotFound) {
return out
}
return out
}
out.NetworkEnabled = pol.NetworkEnabled
out.VoWiFiEnabled = pol.VoWiFiEnabled
if pol.IPVersion != "" {
out.IPVersion = pol.IPVersion
}
out.APN = pol.APN
return out
}
@@ -0,0 +1,53 @@
package api
import (
"path/filepath"
"testing"
"github.com/iniwex5/vohive/internal/db"
)
func initPolicyTestDB(t *testing.T) {
t.Helper()
if err := db.Init(filepath.Join(t.TempDir(), "policy.db")); err != nil {
t.Fatalf("db.Init() error=%v", err)
}
t.Cleanup(func() {
if db.DB != nil {
if sqlDB, err := db.DB.DB(); err == nil && sqlDB != nil {
_ = sqlDB.Close()
}
db.DB = nil
}
})
}
func TestResolveOfflineDevicePolicyFromCard(t *testing.T) {
initPolicyTestDB(t)
iccid := "8986007777777777777"
if err := db.DB.Create(&db.Device{IMEI: "imei-1", Alias: "wwan0", CurrentICCID: &iccid}).Error; err != nil {
t.Fatal(err)
}
if err := db.UpsertCardPolicy(db.CardPolicy{ICCID: iccid, NetworkEnabled: true, VoWiFiEnabled: true, IPVersion: "v4v6", Source: "user"}); err != nil {
t.Fatal(err)
}
got := resolveOfflineDevicePolicy("wwan0")
if !got.NetworkEnabled || !got.VoWiFiEnabled {
t.Fatalf("应取卡策略: %+v", got)
}
if got.IPVersion != "v4v6" || !got.SMSEnabled {
t.Fatalf("ip/sms 错: %+v", got)
}
}
func TestResolveOfflineDevicePolicyNoCardSafeDefault(t *testing.T) {
initPolicyTestDB(t)
got := resolveOfflineDevicePolicy("unknown-device")
if got.NetworkEnabled || got.VoWiFiEnabled {
t.Fatalf("无卡应全关: %+v", got)
}
if !got.SMSEnabled || got.IPVersion != "v4" {
t.Fatalf("默认应 sms=on/ip=v4: %+v", got)
}
}
+68
View File
@@ -0,0 +1,68 @@
package api
import (
"strings"
"time"
"github.com/iniwex5/vohive/internal/db"
"github.com/iniwex5/vohive/internal/proxy/server"
)
const (
deviceTrafficStatusOK = "ok"
deviceTrafficStatusWaitingSample = "waiting_sample"
deviceTrafficStatusStale = "stale"
)
const deviceTrafficStaleAfter = 150 * time.Second
type deviceTrafficMeta struct {
Interface string `json:"interface"`
PeriodStart *time.Time `json:"period_start,omitempty"`
AgeSeconds int64 `json:"age_seconds,omitempty"`
Status string `json:"status"`
}
func buildTrafficOverviewFields(iface string, delta db.LatestMinuteDeltas, now time.Time) (map[string]string, map[string]int64, *deviceTrafficMeta) {
iface = strings.TrimSpace(iface)
if iface == "" {
return nil, nil, nil
}
meta := &deviceTrafficMeta{
Interface: iface,
Status: deviceTrafficStatusWaitingSample,
}
if delta.PeriodStart.IsZero() {
return nil, nil, meta
}
age := now.Sub(delta.PeriodStart)
if age < 0 {
age = 0
}
meta.PeriodStart = &delta.PeriodStart
meta.AgeSeconds = int64(age.Seconds())
meta.Status = deviceTrafficStatusOK
if age > deviceTrafficStaleAfter {
meta.Status = deviceTrafficStatusStale
}
rx := delta.RxBytes
tx := delta.TxBytes
if rx < 0 {
rx = 0
}
if tx < 0 {
tx = 0
}
rate := float64(rx+tx) / 60.0
return map[string]string{
"rx": server.FormatBytes(rx),
"tx": server.FormatBytes(tx),
"rate": server.FormatBytes(int64(rate)) + "/s",
}, map[string]int64{
"bytes_received": rx,
"bytes_sent": tx,
}, meta
}
+54
View File
@@ -0,0 +1,54 @@
package api
import (
"testing"
"time"
"github.com/iniwex5/vohive/internal/db"
)
func TestBuildTrafficOverviewFieldsDistinguishesWaitingZeroAndStale(t *testing.T) {
now := time.Date(2026, time.May, 26, 10, 35, 0, 0, time.UTC)
t.Run("waiting sample", func(t *testing.T) {
traffic, raw, meta := buildTrafficOverviewFields("wwan0", db.LatestMinuteDeltas{}, now)
if traffic != nil || raw != nil {
t.Fatalf("traffic=%v raw=%v want nil while waiting for first sample", traffic, raw)
}
if meta == nil || meta.Status != "waiting_sample" || meta.Interface != "wwan0" {
t.Fatalf("meta=%+v want waiting_sample for wwan0", meta)
}
})
t.Run("zero traffic sample", func(t *testing.T) {
periodStart := now.Add(-time.Minute)
traffic, raw, meta := buildTrafficOverviewFields("wwan0", db.LatestMinuteDeltas{
PeriodStart: periodStart,
RxBytes: 0,
TxBytes: 0,
}, now)
if traffic["rx"] != "0 B" || traffic["tx"] != "0 B" || traffic["rate"] != "0 B/s" {
t.Fatalf("traffic=%v want formatted zero values", traffic)
}
if raw["bytes_received"] != 0 || raw["bytes_sent"] != 0 {
t.Fatalf("raw=%v want zero byte counters", raw)
}
if meta == nil || meta.Status != "ok" || meta.PeriodStart == nil || !meta.PeriodStart.Equal(periodStart) || meta.AgeSeconds != 60 {
t.Fatalf("meta=%+v want ok zero sample metadata", meta)
}
})
t.Run("stale sample", func(t *testing.T) {
traffic, raw, meta := buildTrafficOverviewFields("wwan0", db.LatestMinuteDeltas{
PeriodStart: now.Add(-5 * time.Minute),
RxBytes: 100,
TxBytes: 50,
}, now)
if traffic["rx"] != "100 B" || raw["bytes_sent"] != 50 {
t.Fatalf("traffic=%v raw=%v want stale sample to keep byte values", traffic, raw)
}
if meta == nil || meta.Status != "stale" || meta.AgeSeconds != 300 {
t.Fatalf("meta=%+v want stale metadata", meta)
}
})
}
+202
View File
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
@@ -0,0 +1,2 @@
swagger-ui
Copyright 2020-2021 SmartBear Software Inc.
@@ -0,0 +1,2 @@
/*! For license information please see swagger-ui-bundle.js.LICENSE.txt */
!function webpackUniversalModuleDefinition(s,o){"object"==typeof exports&&"object"==typeof module?module.exports=o():"function"==typeof define&&define.amd?define([],o):"object"==typeof exports?exports.SwaggerUIBundle=o():s.SwaggerUIBundle=o()}(this,(()=>(()=>{var s={67526(s,o){"use strict";o.byteLength=function byteLength(s){var o=getLens(s),i=o[0],a=o[1];return 3*(i+a)/4-a},o.toByteArray=function toByteArray(s){var o,i,_=getLens(s),w=_[0],x=_[1],C=new u(function _byteLength(s,o,i){return 3*(o+i)/4-i}(0,w,x)),j=0,L=x>0?w-4:w;for(i=0;i<L;i+=4)o=a[s.charCodeAt(i)]<<18|a[s.charCodeAt(i+1)]<<12|a[s.charCodeAt(i+2)]<<6|a[s.charCodeAt(i+3)],C[j++]=o>>16&255,C[j++]=o>>8&255,C[j++]=255&o;2===x&&(o=a[s.charCodeAt(i)]<<2|a[s.charCodeAt(i+1)]>>4,C[j++]=255&o);1===x&&(o=a[s.charCodeAt(i)]<<10|a[s.charCodeAt(i+1)]<<4|a[s.charCodeAt(i+2)]>>2,C[j++]=o>>8&255,C[j++]=255&o);return C},o.fromByteArray=function fromByteArray(s){for(var o,a=s.length,u=a%3,_=[],w=16383,x=0,C=a-u;x<C;x+=w)_.push(encodeChunk(s,x,x+w>C?C:x+w));1===u?(o=s[a-1],_.push(i[o>>2]+i[o<<4&63]+"==")):2===u&&(o=(s[a-2]<<8)+s[a-1],_.push(i[o>>10]+i[o>>4&63]+i[o<<2&63]+"="));return _.join("")};for(var i=[],a=[],u="undefined"!=typeof Uint8Array?Uint8Array:Array,_="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",w=0;w<64;++w)i[w]=_[w],a[_.charCodeAt(w)]=w;function getLens(s){var o=s.length;if(o%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var i=s.indexOf("=");return-1===i&&(i=o),[i,i===o?0:4-i%4]}function encodeChunk(s,o,a){for(var u,_,w=[],x=o;x<a;x+=3)u=(s[x]<<16&16711680)+(s[x+1]<<8&65280)+(255&s[x+2]),w.push(i[(_=u)>>18&63]+i[_>>12&63]+i[_>>6&63]+i[63&_]);return w.join("")}a["-".charCodeAt(0)]=62,a["_".charCodeAt(0)]=63},48287(s,o,i){"use strict";const a=i(67526),u=i(251),_="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;o.Buffer=Buffer,o.SlowBuffer=function SlowBuffer(s){+s!=s&&(s=0);return Buffer.alloc(+s)},o.INSPECT_MAX_BYTES=50;const w=2147483647;function createBuffer(s){if(s>w)throw new RangeError('The value "'+s+'" is invalid for option "size"');const o=new Uint8Array(s);return Object.setPrototypeOf(o,Buffer.prototype),o}function Buffer(s,o,i){if("number"==typeof s){if("string"==typeof o)throw new TypeError('The "string" argument must be of type string. Received type number');return allocUnsafe(s)}return from(s,o,i)}function from(s,o,i){if("string"==typeof s)return function fromString(s,o){"string"==typeof o&&""!==o||(o="utf8");if(!Buffer.isEncoding(o))throw new TypeError("Unknown encoding: "+o);const i=0|byteLength(s,o);let a=createBuffer(i);const u=a.write(s,o);u!==i&&(a=a.slice(0,u));return a}(s,o);if(ArrayBuffer.isView(s))return function fromArrayView(s){if(isInstance(s,Uint8Array)){const o=new Uint8Array(s);return fromArrayBuffer(o.buffer,o.byteOffset,o.byteLength)}return fromArrayLike(s)}(s);if(null==s)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof s);if(isInstance(s,ArrayBuffer)||s&&isInstance(s.buffer,ArrayBuffer))return fromArrayBuffer(s,o,i);if("undefined"!=typeof SharedArrayBuffer&&(isInstance(s,SharedArrayBuffer)||s&&isInstance(s.buffer,SharedArrayBuffer)))return fromArrayBuffer(s,o,i);if("number"==typeof s)throw new TypeError('The "value" argument must not be of type number. Received type number');const a=s.valueOf&&s.valueOf();if(null!=a&&a!==s)return Buffer.from(a,o,i);const u=function fromObject(s){if(Buffer.isBuffer(s)){const o=0|checked(s.length),i=createBuffer(o);return 0===i.length||s.copy(i,0,0,o),i}if(void 0!==s.length)return"number"!=typeof s.length||numberIsNaN(s.length)?createBuffer(0):fromArrayLike(s);if("Buffer"===s.type&&Array.isArray(s.data))return fromArrayLike(s.data)}(s);if(u)return u;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof s[Symbol.toPrimitive])return Buffer.from(s[Symbol.toPrimitive]("string"),o,i);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof s)}function assertSize(s){if("number"!=typeof s)throw new TypeError('"size" argument must be of type number');if(s<0)throw new RangeError('The value "'+s+'" is invalid for option "size"')}function allocUnsafe(s){return assertSize(s),createBuffer(s<0?0:0|checked(s))}function fromArrayLike(s){const o=s.length<0?0:0|checked(s.length),i=createBuffer(o);for(let a=0;a<o;a+=1)i[a]=255&s[a];return i}function fromArrayBuffer(s,o,i){if(o<0||s.byteLength<o)throw new RangeError('"offset" is outside of buffer bounds');if(s.byteLength<o+(i||0))throw new RangeError('"length" is outside of buffer bounds');let a;return a=void 0===o&&void 0===i?new Uint8Array(s):void 0===i?new Uint8Array(s,o):new Uint8Array(s,o,i),Object.setPrototypeOf(a,Buffer.prototype),a}function checked(s){if(s>=w)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+w.toString(16)+" Line truncated
@@ -0,0 +1,106 @@
/*!
Copyright (c) 2018 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
/*!
* @description Recursive object extending
* @author Viacheslav Lotsmanov <lotsmanov89@gmail.com>
* @license MIT
*
* The MIT License (MIT)
*
* Copyright (c) 2013-2018 Viacheslav Lotsmanov
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <https://feross.org>
* @license MIT
*/
/*!
* https://github.com/Starcounter-Jack/JSON-Patch
* (c) 2017-2021 Joachim Wester
* MIT license
*/
/*!
* https://github.com/Starcounter-Jack/JSON-Patch
* (c) 2017-2022 Joachim Wester
* MIT licensed
*/
/*!
* repeat-string <https://github.com/jonschlinkert/repeat-string>
*
* Copyright (c) 2014-2015, Jon Schlinkert.
* Licensed under the MIT License.
*/
/*! @license DOMPurify 3.3.2 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.3.2/LICENSE */
/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
/*! js-yaml 4.1.1 https://github.com/nodeca/js-yaml @license MIT */
/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
/**
* @license React
* react-dom.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* @license React
* react.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* @license React
* scheduler.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* @license React
* use-sync-external-store-with-selector.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
@@ -0,0 +1,2 @@
/*! For license information please see swagger-ui-standalone-preset.js.LICENSE.txt */
!function webpackUniversalModuleDefinition(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.SwaggerUIStandalonePreset=e():t.SwaggerUIStandalonePreset=e()}(this,(()=>(()=>{var t={7526(t,e){"use strict";e.byteLength=function byteLength(t){var e=getLens(t),r=e[0],n=e[1];return 3*(r+n)/4-n},e.toByteArray=function toByteArray(t){var e,r,i=getLens(t),a=i[0],s=i[1],u=new o(function _byteLength(t,e,r){return 3*(e+r)/4-r}(0,a,s)),c=0,f=s>0?a-4:a;for(r=0;r<f;r+=4)e=n[t.charCodeAt(r)]<<18|n[t.charCodeAt(r+1)]<<12|n[t.charCodeAt(r+2)]<<6|n[t.charCodeAt(r+3)],u[c++]=e>>16&255,u[c++]=e>>8&255,u[c++]=255&e;2===s&&(e=n[t.charCodeAt(r)]<<2|n[t.charCodeAt(r+1)]>>4,u[c++]=255&e);1===s&&(e=n[t.charCodeAt(r)]<<10|n[t.charCodeAt(r+1)]<<4|n[t.charCodeAt(r+2)]>>2,u[c++]=e>>8&255,u[c++]=255&e);return u},e.fromByteArray=function fromByteArray(t){for(var e,n=t.length,o=n%3,i=[],a=16383,s=0,u=n-o;s<u;s+=a)i.push(encodeChunk(t,s,s+a>u?u:s+a));1===o?(e=t[n-1],i.push(r[e>>2]+r[e<<4&63]+"==")):2===o&&(e=(t[n-2]<<8)+t[n-1],i.push(r[e>>10]+r[e>>4&63]+r[e<<2&63]+"="));return i.join("")};for(var r=[],n=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0;a<64;++a)r[a]=i[a],n[i.charCodeAt(a)]=a;function getLens(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");return-1===r&&(r=e),[r,r===e?0:4-r%4]}function encodeChunk(t,e,n){for(var o,i,a=[],s=e;s<n;s+=3)o=(t[s]<<16&16711680)+(t[s+1]<<8&65280)+(255&t[s+2]),a.push(r[(i=o)>>18&63]+r[i>>12&63]+r[i>>6&63]+r[63&i]);return a.join("")}n["-".charCodeAt(0)]=62,n["_".charCodeAt(0)]=63},8287(t,e,r){"use strict";const n=r(7526),o=r(251),i="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=Buffer,e.SlowBuffer=function SlowBuffer(t){+t!=t&&(t=0);return Buffer.alloc(+t)},e.INSPECT_MAX_BYTES=50;const a=2147483647;function createBuffer(t){if(t>a)throw new RangeError('The value "'+t+'" is invalid for option "size"');const e=new Uint8Array(t);return Object.setPrototypeOf(e,Buffer.prototype),e}function Buffer(t,e,r){if("number"==typeof t){if("string"==typeof e)throw new TypeError('The "string" argument must be of type string. Received type number');return allocUnsafe(t)}return from(t,e,r)}function from(t,e,r){if("string"==typeof t)return function fromString(t,e){"string"==typeof e&&""!==e||(e="utf8");if(!Buffer.isEncoding(e))throw new TypeError("Unknown encoding: "+e);const r=0|byteLength(t,e);let n=createBuffer(r);const o=n.write(t,e);o!==r&&(n=n.slice(0,o));return n}(t,e);if(ArrayBuffer.isView(t))return function fromArrayView(t){if(isInstance(t,Uint8Array)){const e=new Uint8Array(t);return fromArrayBuffer(e.buffer,e.byteOffset,e.byteLength)}return fromArrayLike(t)}(t);if(null==t)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(isInstance(t,ArrayBuffer)||t&&isInstance(t.buffer,ArrayBuffer))return fromArrayBuffer(t,e,r);if("undefined"!=typeof SharedArrayBuffer&&(isInstance(t,SharedArrayBuffer)||t&&isInstance(t.buffer,SharedArrayBuffer)))return fromArrayBuffer(t,e,r);if("number"==typeof t)throw new TypeError('The "value" argument must not be of type number. Received type number');const n=t.valueOf&&t.valueOf();if(null!=n&&n!==t)return Buffer.from(n,e,r);const o=function fromObject(t){if(Buffer.isBuffer(t)){const e=0|checked(t.length),r=createBuffer(e);return 0===r.length||t.copy(r,0,0,e),r}if(void 0!==t.length)return"number"!=typeof t.length||numberIsNaN(t.length)?createBuffer(0):fromArrayLike(t);if("Buffer"===t.type&&Array.isArray(t.data))return fromArrayLike(t.data)}(t);if(o)return o;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof t[Symbol.toPrimitive])return Buffer.from(t[Symbol.toPrimitive]("string"),e,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t)}function assertSize(t){if("number"!=typeof t)throw new TypeError('"size" argument must be of type number');if(t<0)throw new RangeError('The value "'+t+'" is invalid for option "size"')}function allocUnsafe(t){return assertSize(t),createBuffer(t<0?0:0|checked(t))}function fromArrayLike(t){const e=t.length<0?0:0|checked(t.length),r=createBuffer(e);for(let n=0;n<e;n+=1)r[n]=255&t[n];return r}function fromArrayBuffer(t,e,r){if(e<0||t.byteLength<e)throw new RangeError('"offset" is outside of buffer bounds');if(t.byteLength<e+(r||0))throw new RangeError('"length" is outside of buffer bounds');let n;return n=void 0===e&&void 0===r?new Uint8Array(t):void 0===r?new Uint8Array(t,e):new Uint8Array(t,e,r),Object.setPrototypeOf(n,Buffer.prototype),n}function checked(t){if(t>=a)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Line truncated
@@ -0,0 +1,22 @@
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <https://feross.org>
* @license MIT
*/
/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
/*! js-yaml 4.1.1 https://github.com/nodeca/js-yaml @license MIT */
/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
/**
* @license React
* react.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
@@ -0,0 +1,3 @@
.swagger-ui{color:#3b4151;container-name:swagger-ui;container-type:inline-size;/*! normalize.css v7.0.0 | MIT License | github.com/necolas/normalize.css */font-family:sans-serif}.swagger-ui html{line-height:1.15;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%}.swagger-ui body{margin:0}.swagger-ui article,.swagger-ui aside,.swagger-ui footer,.swagger-ui header,.swagger-ui nav,.swagger-ui section{display:block}.swagger-ui h1{font-size:2em;margin:.67em 0}.swagger-ui figcaption,.swagger-ui figure,.swagger-ui main{display:block}.swagger-ui figure{margin:1em 40px}.swagger-ui hr{box-sizing:content-box;height:0;overflow:visible}.swagger-ui pre{font-family:monospace,monospace;font-size:1em}.swagger-ui a{background-color:transparent;-webkit-text-decoration-skip:objects}.swagger-ui abbr[title]{border-bottom:none;text-decoration:underline;-webkit-text-decoration:underline dotted;text-decoration:underline dotted}.swagger-ui b,.swagger-ui strong{font-weight:inherit;font-weight:bolder}.swagger-ui code,.swagger-ui kbd,.swagger-ui samp{font-family:monospace,monospace;font-size:1em}.swagger-ui dfn{font-style:italic}.swagger-ui mark{background-color:#ff0;color:#000}.swagger-ui small{font-size:80%}.swagger-ui sub,.swagger-ui sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}.swagger-ui sub{bottom:-.25em}.swagger-ui sup{top:-.5em}.swagger-ui audio,.swagger-ui video{display:inline-block}.swagger-ui audio:not([controls]){display:none;height:0}.swagger-ui img{border-style:none}.swagger-ui svg:not(:root){overflow:hidden}.swagger-ui button,.swagger-ui input,.swagger-ui optgroup,.swagger-ui select,.swagger-ui textarea{font-family:sans-serif;font-size:100%;line-height:1.15;margin:0}.swagger-ui button,.swagger-ui input{overflow:visible}.swagger-ui button,.swagger-ui select{text-transform:none}.swagger-ui [type=reset],.swagger-ui [type=submit],.swagger-ui button,.swagger-ui html [type=button]{-webkit-appearance:button}.swagger-ui [type=button]::-moz-focus-inner,.swagger-ui [type=reset]::-moz-focus-inner,.swagger-ui [type=submit]::-moz-focus-inner,.swagger-ui button::-moz-focus-inner{border-style:none;padding:0}.swagger-ui [type=button]:-moz-focusring,.swagger-ui [type=reset]:-moz-focusring,.swagger-ui [type=submit]:-moz-focusring,.swagger-ui button:-moz-focusring{outline:1px dotted ButtonText}.swagger-ui fieldset{padding:.35em .75em .625em}.swagger-ui legend{box-sizing:border-box;color:inherit;display:table;max-width:100%;padding:0;white-space:normal}.swagger-ui progress{display:inline-block;vertical-align:baseline}.swagger-ui textarea{overflow:auto}.swagger-ui [type=checkbox],.swagger-ui [type=radio]{box-sizing:border-box;padding:0}.swagger-ui [type=number]::-webkit-inner-spin-button,.swagger-ui [type=number]::-webkit-outer-spin-button{height:auto}.swagger-ui [type=search]{-webkit-appearance:textfield;outline-offset:-2px}.swagger-ui [type=search]::-webkit-search-cancel-button,.swagger-ui [type=search]::-webkit-search-decoration{-webkit-appearance:none}.swagger-ui ::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}.swagger-ui details,.swagger-ui menu{display:block}.swagger-ui summary{display:list-item}.swagger-ui canvas{display:inline-block}.swagger-ui [hidden],.swagger-ui template{display:none}.swagger-ui .debug *{outline:1px solid gold}.swagger-ui .debug-white *{outline:1px solid #fff}.swagger-ui .debug-black *{outline:1px solid #000}.swagger-ui .debug-grid{background:transparent url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAYAAADED76LAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyhpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNi1jMTExIDc5LjE1ODMyNSwgMjAxNS8wOS8xMC0wMToxMDoyMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6MTRDOTY4N0U2N0VFMTFFNjg2MzZDQjkwNkQ4MjgwMEIiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6MTRDOTY4N0Q2N0VFMTFFNjg2MzZDQjkwNkQ4MjgwMEIiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIDIwMTUgKE1hY2ludG9zaCkiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDo3NjcyQkQ3NjY3QzUxMUU2QjJCQ0UyNDA4MTAwMjE3MSIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDo3NjcyQkQ3NzY3QzUxMUU2QjJCQ0UyNDA4MTAwMjE3MSIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/PsBS+GMAAAAjSURBVHjaYvz//z8DLsD4gcGXiYEAGBIKGBne//fFpwAgwAB98AaF2pjlUQAAAABJRU5ErkJggg==) repeat 0 0}.swagger-ui .debug-grid-16{background:transparent url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyhpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpLine truncated
/*# sourceMappingURL=swagger-ui.css.map*/
+455
View File
@@ -0,0 +1,455 @@
package api
import (
"embed"
"encoding/json"
"fmt"
"io/fs"
"net/http"
"path"
"strings"
"sync"
"github.com/gin-gonic/gin"
yaml "gopkg.in/yaml.v3"
)
const (
apiDocsUIPath = "/api/docs"
apiOpenAPIYAMLPath = "/api/openapi.yaml"
apiOpenAPIJSONPath = "/api/openapi.json"
)
type apiDocsLinks struct {
SwaggerUI string `json:"swagger_ui"`
OpenAPIYAML string `json:"openapi_yaml"`
OpenAPIJSON string `json:"openapi_json"`
}
//go:embed openapi.vohive.yaml
var openAPISpecYAML []byte
//go:embed all:docs_assets/swagger-ui
var swaggerUIAssetEmbedFS embed.FS
var (
openAPISpecJSONOnce sync.Once
openAPISpecJSON []byte
openAPISpecJSONErr error
)
func currentAPIDocsLinks() apiDocsLinks {
return apiDocsLinks{
SwaggerUI: apiDocsUIPath,
OpenAPIYAML: apiOpenAPIYAMLPath,
OpenAPIJSON: apiOpenAPIJSONPath,
}
}
func loadOpenAPISpecJSON() ([]byte, error) {
openAPISpecJSONOnce.Do(func() {
var raw any
if err := yaml.Unmarshal(openAPISpecYAML, &raw); err != nil {
openAPISpecJSONErr = fmt.Errorf("parse openapi yaml: %w", err)
return
}
encoded, err := json.Marshal(normalizeYAMLValue(raw))
if err != nil {
openAPISpecJSONErr = fmt.Errorf("marshal openapi json: %w", err)
return
}
openAPISpecJSON = encoded
})
if openAPISpecJSONErr != nil {
return nil, openAPISpecJSONErr
}
return openAPISpecJSON, nil
}
func normalizeYAMLValue(v any) any {
switch typed := v.(type) {
case map[string]any:
out := make(map[string]any, len(typed))
for k, inner := range typed {
out[k] = normalizeYAMLValue(inner)
}
return out
case map[any]any:
out := make(map[string]any, len(typed))
for k, inner := range typed {
out[fmt.Sprint(k)] = normalizeYAMLValue(inner)
}
return out
case []any:
out := make([]any, len(typed))
for i, inner := range typed {
out[i] = normalizeYAMLValue(inner)
}
return out
default:
return v
}
}
func (s *Server) handleOpenAPIYAML(c *gin.Context) {
c.Data(http.StatusOK, "application/yaml; charset=utf-8", openAPISpecYAML)
}
func (s *Server) handleOpenAPIJSON(c *gin.Context) {
payload, err := loadOpenAPISpecJSON()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": "生成 OpenAPI JSON 失败: " + err.Error()})
return
}
c.Data(http.StatusOK, "application/json; charset=utf-8", payload)
}
func (s *Server) handleDocsAsset(c *gin.Context) {
assetPath := strings.TrimPrefix(c.Param("filepath"), "/")
if assetPath == "" {
c.String(http.StatusNotFound, "Not Found")
return
}
assetPath = path.Clean(assetPath)
if assetPath == "." || strings.HasPrefix(assetPath, "../") {
c.String(http.StatusNotFound, "Not Found")
return
}
content, err := fs.ReadFile(swaggerUIAssetEmbedFS, path.Join("docs_assets/swagger-ui", assetPath))
if err != nil {
c.String(http.StatusNotFound, "Not Found")
return
}
c.Data(http.StatusOK, docsAssetContentType(assetPath), content)
}
func docsAssetContentType(assetPath string) string {
switch strings.ToLower(path.Ext(assetPath)) {
case ".css":
return "text/css; charset=utf-8"
case ".js":
return "application/javascript; charset=utf-8"
case ".png":
return "image/png"
case ".svg":
return "image/svg+xml"
case ".txt", ".map":
return "text/plain; charset=utf-8"
default:
return "application/octet-stream"
}
}
func (s *Server) handleAPIDocs(c *gin.Context) {
c.Header("Cache-Control", "no-store")
c.Data(http.StatusOK, "text/html; charset=utf-8", []byte(apiDocsHTML))
}
const apiDocsHTML = `<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<title>VoHive API Docs</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" type="image/png" sizes="32x32" href="/api/docs/assets/favicon-32x32.png" />
<link rel="icon" type="image/png" sizes="16x16" href="/api/docs/assets/favicon-16x16.png" />
<link rel="stylesheet" href="/api/docs/assets/swagger-ui.css" />
<style>
:root {
color-scheme: light;
--bg: #f4f7fb;
--panel: #ffffff;
--panel-2: #e9eef7;
--text: #132238;
--muted: #62748a;
--accent: #0f766e;
--accent-strong: #115e59;
--border: #dbe5f0;
--danger: #b42318;
}
* { box-sizing: border-box; }
body {
margin: 0;
font-family: "Iowan Old Style", "Palatino Linotype", "Book Antiqua", Georgia, serif;
background:
radial-gradient(circle at top left, rgba(15, 118, 110, 0.12), transparent 24%),
radial-gradient(circle at top right, rgba(31, 41, 55, 0.08), transparent 18%),
linear-gradient(180deg, #f7fbff 0%, var(--bg) 100%);
color: var(--text);
min-height: 100vh;
}
.page {
width: min(1400px, calc(100vw - 32px));
margin: 0 auto;
padding: 28px 0 36px;
}
.hero {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
gap: 20px;
align-items: start;
margin-bottom: 20px;
padding: 24px;
border: 1px solid rgba(255,255,255,0.55);
border-radius: 24px;
background: rgba(255,255,255,0.86);
box-shadow: 0 24px 50px rgba(15, 23, 42, 0.08);
backdrop-filter: blur(12px);
}
.eyebrow {
display: inline-flex;
align-items: center;
gap: 8px;
padding: 7px 12px;
border-radius: 999px;
background: rgba(15, 118, 110, 0.10);
color: var(--accent-strong);
font-size: 12px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
h1 {
margin: 14px 0 10px;
font-size: clamp(32px, 5vw, 54px);
line-height: 0.95;
letter-spacing: -0.04em;
}
.subtitle {
max-width: 760px;
margin: 0;
color: var(--muted);
font-size: 15px;
line-height: 1.6;
}
.hero-actions {
display: flex;
gap: 10px;
flex-wrap: wrap;
justify-content: flex-end;
}
.btn {
appearance: none;
border: 0;
border-radius: 999px;
padding: 12px 18px;
font-size: 14px;
font-weight: 700;
cursor: pointer;
text-decoration: none;
transition: transform .18s ease, box-shadow .18s ease, background .18s ease;
}
.btn:hover { transform: translateY(-1px); }
.btn-primary {
background: linear-gradient(135deg, #0f766e 0%, #115e59 100%);
color: #fff;
box-shadow: 0 12px 28px rgba(15, 118, 110, 0.24);
}
.btn-secondary {
background: rgba(15, 23, 42, 0.06);
color: var(--text);
}
.status-card {
margin-bottom: 18px;
border-radius: 20px;
border: 1px solid var(--border);
background: rgba(255,255,255,0.9);
padding: 18px 20px;
box-shadow: 0 18px 36px rgba(15, 23, 42, 0.05);
}
.status-card[hidden] { display: none; }
.status-title {
margin: 0 0 6px;
font-size: 18px;
font-weight: 700;
}
.status-message {
margin: 0;
color: var(--muted);
line-height: 1.7;
white-space: pre-line;
}
.status-card.error .status-title { color: var(--danger); }
.status-card.ready .status-title { color: var(--accent-strong); }
.status-meta {
margin-top: 12px;
display: flex;
flex-wrap: wrap;
gap: 10px;
color: var(--muted);
font-size: 12px;
}
.status-pill {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 6px 10px;
border-radius: 999px;
background: var(--panel-2);
}
#swagger-ui {
border-radius: 24px;
overflow: hidden;
background: var(--panel);
border: 1px solid rgba(219,229,240,0.9);
box-shadow: 0 28px 60px rgba(15, 23, 42, 0.08);
}
.swagger-ui .topbar { display: none; }
@media (max-width: 900px) {
.page { width: min(100vw - 18px, 1400px); padding-top: 14px; }
.hero { grid-template-columns: 1fr; padding: 18px; }
.hero-actions { justify-content: flex-start; }
}
</style>
</head>
<body>
<div class="page">
<section class="hero">
<div>
<div class="eyebrow">VoHive OpenAPI</div>
<h1>主服务 API 文档</h1>
<p class="subtitle">文档页会直接读取当前浏览器里的 VoHive 登录 token,并自动注入到 Swagger UI 的请求里。你可以在这里浏览接口、查看 schema、直接试调用。</p>
</div>
<div class="hero-actions">
<a class="btn btn-secondary" href="/#/settings">返回系统设置</a>
<a class="btn btn-primary" href="/#/login">前往登录</a>
</div>
</section>
<section id="status-card" class="status-card" aria-live="polite">
<h2 id="status-title" class="status-title">正在准备 API 文档</h2>
<p id="status-message" class="status-message">正在检查当前浏览器的登录状态。</p>
<div id="status-meta" class="status-meta"></div>
</section>
<div id="swagger-ui"></div>
</div>
<script src="/api/docs/assets/swagger-ui-bundle.js"></script>
<script src="/api/docs/assets/swagger-ui-standalone-preset.js"></script>
<script>
(function () {
var OPENAPI_JSON_URL = '/api/openapi.json';
var LOGIN_URL = '/#/login';
var SETTINGS_URL = '/#/settings';
var token = '';
var statusCard = document.getElementById('status-card');
var statusTitle = document.getElementById('status-title');
var statusMessage = document.getElementById('status-message');
var statusMeta = document.getElementById('status-meta');
var swaggerRoot = document.getElementById('swagger-ui');
function setStatus(kind, title, message, meta) {
statusCard.className = 'status-card ' + (kind || '');
statusTitle.textContent = title;
statusMessage.textContent = message;
statusMeta.innerHTML = '';
(meta || []).forEach(function (item) {
var pill = document.createElement('span');
pill.className = 'status-pill';
pill.textContent = item;
statusMeta.appendChild(pill);
});
}
function showLoginHint(reason) {
swaggerRoot.innerHTML = '';
setStatus(
'error',
'当前还没有可用的登录 token',
reason + '\n\n请先在 VoHive Web 控制台完成登录,然后重新打开这个页面。',
['文档页本身公开可访问', 'OpenAPI 规格仍需 Bearer 鉴权']
);
}
function showLoadError(message, status) {
swaggerRoot.innerHTML = '';
var meta = [];
if (status) {
meta.push('HTTP ' + status);
}
meta.push('规格源 ' + OPENAPI_JSON_URL);
setStatus('error', 'OpenAPI 规格加载失败', message, meta);
}
try {
token = String(localStorage.getItem('token') || '').trim();
} catch (err) {
token = '';
}
if (!token) {
showLoginHint('当前浏览器本地存储中没有发现 token。');
return;
}
setStatus('ready', '正在加载 OpenAPI 规格', '已检测到登录 token,正在向主服务请求受保护的 OpenAPI JSON。', ['Bearer token 已就绪']);
fetch(OPENAPI_JSON_URL, {
headers: {
Authorization: 'Bearer ' + token
},
credentials: 'same-origin'
})
.then(function (res) {
if (!res.ok) {
var err = new Error(res.status === 401 ? '当前登录状态已失效,请重新登录后再打开文档页。' : '主服务返回了异常状态,暂时无法加载文档。');
err.status = res.status;
throw err;
}
return res.json();
})
.then(function (spec) {
setStatus('ready', 'OpenAPI 已就绪', '文档已载入。下面的 Try it out 请求会自动附带当前 Bearer token。', ['规格源 ' + OPENAPI_JSON_URL, 'Try it out 已注入 Authorization']);
window.ui = SwaggerUIBundle({
spec: spec,
dom_id: '#swagger-ui',
deepLinking: true,
persistAuthorization: true,
displayRequestDuration: true,
tryItOutEnabled: true,
presets: [SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset],
layout: 'BaseLayout',
requestInterceptor: function (req) {
req.headers = req.headers || {};
if (!req.headers.Authorization) {
req.headers.Authorization = 'Bearer ' + token;
}
return req;
},
onComplete: function () {
try {
window.ui.preauthorizeApiKey('BearerAuth', token);
} catch (err) {
console.warn('[VoHive Docs] preauthorizeApiKey failed', err);
}
try {
window.ui.authActions.authorize({
BearerAuth: {
name: 'BearerAuth',
schema: {
type: 'http',
scheme: 'bearer',
bearerFormat: 'SessionToken'
},
value: token
}
});
} catch (err) {
console.warn('[VoHive Docs] authActions.authorize failed', err);
}
}
});
})
.catch(function (err) {
if (err && err.status === 401) {
showLoginHint('当前 token 已过期或无效。');
return;
}
showLoadError(err && err.message ? err.message : '未知错误', err && err.status ? err.status : '');
});
})();
</script>
</body>
</html>`
File diff suppressed because it is too large. Load diff
+22
View File
@@ -0,0 +1,22 @@
package api
import (
"os"
"testing"
"gopkg.in/yaml.v3"
)
func TestOpenAPIVoHiveYAMLValid(t *testing.T) {
data, err := os.ReadFile("openapi.vohive.yaml")
if err != nil {
t.Fatalf("read openapi.vohive.yaml: %v", err)
}
var doc map[string]any
if err := yaml.Unmarshal(data, &doc); err != nil {
t.Fatalf("openapi.vohive.yaml is invalid YAML: %v", err)
}
if doc["openapi"] == "" {
t.Fatalf("openapi.vohive.yaml missing openapi version")
}
}
+35
View File
@@ -0,0 +1,35 @@
package api
import (
"strings"
"github.com/gin-gonic/gin"
)
func firstPathParam(c *gin.Context, names ...string) string {
if c == nil {
return ""
}
for _, name := range names {
if v := strings.TrimSpace(c.Param(name)); v != "" {
return v
}
}
return ""
}
func deviceIDParam(c *gin.Context) string {
return firstPathParam(c, "device_id", "id")
}
func upstreamProxyIDParam(c *gin.Context) string {
return firstPathParam(c, "proxy_id", "id")
}
func countryCodeParam(c *gin.Context) string {
return firstPathParam(c, "country_code", "country")
}
func proxyInstanceIDParam(c *gin.Context) string {
return firstPathParam(c, "instance_id", "id")
}
+377
View File
@@ -0,0 +1,377 @@
package api
import (
"context"
"errors"
"net/http"
"strings"
"time"
"github.com/iniwex5/vohive/internal/config"
"github.com/iniwex5/vohive/internal/proxy/server"
"github.com/iniwex5/vohive/pkg/logger"
"github.com/gin-gonic/gin"
)
// proxyOverviewResponse API 响应:代理配置概览
type proxyOverviewResponse struct {
Instances []proxyInstanceDTO `json:"instances"`
Devices []proxyDeviceDTO `json:"devices"`
Status []server.InstanceStatus `json:"status"`
}
// proxyInstanceDTO 代理实例 DTO
type proxyInstanceDTO struct {
ID string `json:"id"`
Name string `json:"name"`
DeviceID string `json:"device_id"`
Enabled bool `json:"enabled"`
Mode string `json:"mode"`
ListenAddr string `json:"listen_addr"`
ListenPort int `json:"listen_port"`
AuthEnabled bool `json:"auth_enabled"`
Username string `json:"username"`
Password string `json:"password,omitempty"`
}
// proxyDeviceDTO 设备 DTO
type proxyDeviceDTO struct {
ID string `json:"id"`
Name string `json:"name"`
Interface string `json:"interface"`
}
// proxyConfigRequest 更新代理配置请求
type proxyConfigRequest struct {
Instances []config.ProxyInstance `json:"instances"`
}
// handleProxyOverview 获取代理配置概览
func (s *Server) handleProxyOverview(c *gin.Context) {
ctx := c.Request.Context()
resp := proxyOverviewResponse{
Instances: make([]proxyInstanceDTO, 0),
Devices: make([]proxyDeviceDTO, 0),
Status: nil,
}
instances, err := s.proxyRepo.List(ctx)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": "加载实例失败: " + err.Error()})
return
}
resp.Instances = make([]proxyInstanceDTO, 0, len(instances))
for _, inst := range instances {
resp.Instances = append(resp.Instances, instanceToDTO(inst, true))
}
{
managed := config.ListDevices()
resp.Devices = make([]proxyDeviceDTO, 0, len(managed))
for _, d := range managed {
name := d.Name
if name == "" {
name = d.ID
}
resp.Devices = append(resp.Devices, proxyDeviceDTO{
ID: d.ID,
Name: name,
Interface: d.Interface,
})
}
}
if s.proxyMgr != nil {
resp.Status = s.proxyMgr.ListStatus()
}
c.JSON(http.StatusOK, resp)
}
func (s *Server) handleProxyInstanceGet(c *gin.Context) {
ctx := c.Request.Context()
id := proxyInstanceIDParam(c)
inst, err := s.proxyRepo.Get(ctx, id)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": "加载实例失败: " + err.Error()})
return
}
if inst == nil {
c.JSON(http.StatusNotFound, gin.H{"status": "error", "message": "实例不存在: " + id})
return
}
c.JSON(http.StatusOK, instanceToDTO(*inst, false))
}
// handleProxyUpdateConfig 更新代理配置
func (s *Server) handleProxyUpdateConfig(c *gin.Context) {
ctx := c.Request.Context()
var req proxyConfigRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": "参数错误: " + err.Error()})
return
}
oldInstMap := make(map[string]config.ProxyInstance)
oldInstances, err := s.proxyRepo.List(ctx)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": "读取旧配置失败: " + err.Error()})
return
}
for _, oldInst := range oldInstances {
oldInstMap[oldInst.ID] = oldInst
}
normalizedInstances := make([]config.ProxyInstance, 0, len(req.Instances))
for _, inst := range req.Instances {
var oldInst *config.ProxyInstance
if old, ok := oldInstMap[inst.ID]; ok {
oldCopy := old
oldInst = &oldCopy
}
normalized, err := normalizeProxyInstanceForSave(inst, oldInst)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": err.Error()})
return
}
normalizedInstances = append(normalizedInstances, normalized)
}
if err := s.proxyRepo.ReplaceAll(ctx, normalizedInstances); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": "写入数据库失败: " + err.Error()})
return
}
if err := s.SyncProxyConfigs(); err != nil {
c.JSON(http.StatusOK, gin.H{"status": "ok", "applied": false, "warning": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "ok", "applied": true})
}
func restoreProxySecrets(inst *config.ProxyInstance, oldInst config.ProxyInstance) {
if inst == nil {
return
}
if inst.Password == "******" {
inst.Password = oldInst.Password
}
}
func normalizeProxyInstanceForSave(inst config.ProxyInstance, oldInst *config.ProxyInstance) (config.ProxyInstance, error) {
if strings.TrimSpace(inst.ID) == "" {
return config.ProxyInstance{}, errors.New("实例 id 不能为空")
}
if strings.TrimSpace(inst.DeviceID) == "" {
return config.ProxyInstance{}, errors.New("device_id 不能为空")
}
mode, err := normalizeProxyMode(inst.Mode)
if err != nil {
return config.ProxyInstance{}, err
}
inst.Mode = mode
if inst.ListenPort <= 0 || inst.ListenPort > 65535 {
return config.ProxyInstance{}, errors.New("listen_port 无效")
}
if strings.TrimSpace(inst.ListenAddr) == "" {
inst.ListenAddr = "0.0.0.0"
}
if oldInst != nil {
restoreProxySecrets(&inst, *oldInst)
}
if !inst.AuthEnabled {
inst.Username = ""
inst.Password = ""
return inst, nil
}
inst.Username = strings.TrimSpace(inst.Username)
inst.Password = strings.TrimSpace(inst.Password)
if inst.Username == "" || inst.Password == "" {
return config.ProxyInstance{}, errors.New("启用认证时 username/password 不能为空")
}
return inst, nil
}
func normalizeProxyMode(mode string) (string, error) {
m := strings.ToLower(strings.TrimSpace(mode))
if m == "" {
return server.ModeSocks5, nil
}
switch m {
case server.ModeSocks5, server.ModeHTTP:
return m, nil
default:
return "", errors.New("mode 仅支持 socks5 或 http")
}
}
// handleProxyInstanceStart 启动代理实例
func (s *Server) handleProxyInstanceStart(c *gin.Context) {
id := proxyInstanceIDParam(c)
if s.proxyMgr == nil {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": "代理管理未启用"})
return
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := s.proxyMgr.Start(ctx, id); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "ok"})
}
// handleProxyInstanceStop 停止代理实例
func (s *Server) handleProxyInstanceStop(c *gin.Context) {
id := proxyInstanceIDParam(c)
if s.proxyMgr == nil {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": "代理管理未启用"})
return
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := s.proxyMgr.Stop(ctx, id); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "ok"})
}
// handleProxyInstanceRestart 重启代理实例
func (s *Server) handleProxyInstanceRestart(c *gin.Context) {
id := proxyInstanceIDParam(c)
if s.proxyMgr == nil {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": "代理管理未启用"})
return
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := s.proxyMgr.Restart(ctx, id); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "ok"})
}
// SyncProxyConfigs 同步代理配置到实例管理器
func (s *Server) SyncProxyConfigs() error {
if s.proxyMgr == nil {
return nil
}
s.proxySyncMu.Lock()
defer s.proxySyncMu.Unlock()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
cfgs, err := s.buildProxyConfigs(ctx)
if err != nil {
return err
}
return s.proxyMgr.ApplyConfigs(ctx, cfgs)
}
func (s *Server) buildProxyConfigs(ctx context.Context) ([]server.InstanceConfig, error) {
deviceInterface := make(map[string]string)
{
managed := config.ListDevices()
for _, d := range managed {
iface := strings.TrimSpace(d.Interface)
if iface != "" {
deviceInterface[d.ID] = iface
}
}
}
for _, w := range s.pool.GetAllWorkers() {
if w == nil {
continue
}
iface := strings.TrimSpace(w.Config.Interface)
if iface != "" {
deviceInterface[w.ID] = iface
}
}
instances, err := s.proxyRepo.List(ctx)
if err != nil {
return nil, err
}
out := make([]server.InstanceConfig, 0, len(instances))
for _, inst := range instances {
if strings.TrimSpace(inst.DeviceID) == "" {
return nil, errors.New("device_id 不能为空")
}
mode, err := normalizeProxyMode(inst.Mode)
if err != nil {
return nil, err
}
inst.Mode = mode
if strings.TrimSpace(inst.ListenAddr) == "" {
inst.ListenAddr = "0.0.0.0"
}
if inst.ListenPort <= 0 || inst.ListenPort > 65535 {
return nil, errors.New("listen_port 无效")
}
if inst.AuthEnabled {
if strings.TrimSpace(inst.Username) == "" || strings.TrimSpace(inst.Password) == "" {
return nil, errors.New("启用认证时 username/password 不能为空")
}
}
iface := strings.TrimSpace(deviceInterface[inst.DeviceID])
if iface == "" {
return nil, errors.New("device_id 无效: " + inst.DeviceID)
}
logger.Info("代理实例绑定信息",
"instance_id", inst.ID,
"mode", inst.Mode,
"device_id", inst.DeviceID,
"bind_interface", iface,
)
out = append(out, server.InstanceConfig{
ID: inst.ID,
Mode: inst.Mode,
Enabled: inst.Enabled,
ListenAddr: inst.ListenAddr,
ListenPort: inst.ListenPort,
Interface: iface,
AuthEnabled: inst.AuthEnabled,
Username: inst.Username,
Password: inst.Password,
})
}
return out, nil
}
func instanceToDTO(inst config.ProxyInstance, mask bool) proxyInstanceDTO {
mode := strings.ToLower(strings.TrimSpace(inst.Mode))
if mode == "" {
mode = server.ModeSocks5
}
return proxyInstanceDTO{
ID: inst.ID,
Name: inst.Name,
DeviceID: inst.DeviceID,
Enabled: inst.Enabled,
Mode: mode,
ListenAddr: inst.ListenAddr,
ListenPort: inst.ListenPort,
AuthEnabled: inst.AuthEnabled,
Username: inst.Username,
Password: maybeMaskSecret(inst.Password, mask),
}
}
func maybeMaskSecret(v string, mask bool) string {
if !mask {
return v
}
if strings.TrimSpace(v) == "" {
return ""
}
return "******"
}
+275
View File
@@ -0,0 +1,275 @@
package api
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"github.com/iniwex5/vohive/internal/config"
"github.com/iniwex5/vohive/internal/data/repo"
"github.com/iniwex5/vohive/internal/db"
"github.com/iniwex5/vohive/internal/device"
"github.com/gin-gonic/gin"
)
type staticProxyInstanceRepo struct {
instances []config.ProxyInstance
}
func (r staticProxyInstanceRepo) List(context.Context) ([]config.ProxyInstance, error) {
out := append([]config.ProxyInstance(nil), r.instances...)
return out, nil
}
func (r staticProxyInstanceRepo) Get(_ context.Context, id string) (*config.ProxyInstance, error) {
for _, inst := range r.instances {
if inst.ID == id {
instCopy := inst
return &instCopy, nil
}
}
return nil, nil
}
func (r staticProxyInstanceRepo) ReplaceAll(_ context.Context, instances []config.ProxyInstance) error {
r.instances = append([]config.ProxyInstance(nil), instances...)
return nil
}
func initProxyTestConfig(t *testing.T, body string) {
t.Helper()
path := filepath.Join(t.TempDir(), "config.yaml")
if err := os.WriteFile(path, []byte(body), 0600); err != nil {
t.Fatalf("WriteFile() error = %v", err)
}
if err := config.InitGlobalManager(path); err != nil {
t.Fatalf("InitGlobalManager() error = %v", err)
}
}
func TestNormalizeProxyInstanceForSaveValidation(t *testing.T) {
_, err := normalizeProxyInstanceForSave(config.ProxyInstance{
ID: "inst-1",
DeviceID: "",
ListenAddr: "0.0.0.0",
ListenPort: 1080,
}, nil)
if err == nil {
t.Fatalf("expected device_id validation error")
}
_, err = normalizeProxyInstanceForSave(config.ProxyInstance{
ID: "inst-2",
DeviceID: "dev-1",
ListenAddr: "0.0.0.0",
ListenPort: 1080,
Mode: "socks5",
AuthEnabled: true,
Username: "",
Password: "pass",
}, nil)
if err == nil {
t.Fatalf("expected auth credential validation error")
}
_, err = normalizeProxyInstanceForSave(config.ProxyInstance{
ID: "inst-3",
DeviceID: "dev-1",
ListenAddr: "0.0.0.0",
ListenPort: 8080,
Mode: "ftp",
}, nil)
if err == nil {
t.Fatalf("expected mode validation error")
}
}
func TestNormalizeProxyInstanceForSaveAuthOffClearsCredentials(t *testing.T) {
out, err := normalizeProxyInstanceForSave(config.ProxyInstance{
ID: "inst-1",
DeviceID: "dev-1",
ListenAddr: "",
ListenPort: 1080,
Mode: "",
AuthEnabled: false,
Username: "abc",
Password: "def",
}, nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if out.ListenAddr != "0.0.0.0" {
t.Fatalf("listen_addr default mismatch: got=%q", out.ListenAddr)
}
if out.Mode != "socks5" {
t.Fatalf("mode default mismatch: got=%q want=socks5", out.Mode)
}
if out.Username != "" || out.Password != "" {
t.Fatalf("expected credentials cleared when auth disabled")
}
}
func TestNormalizeProxyInstanceForSaveRestoresMaskedPassword(t *testing.T) {
old := &config.ProxyInstance{Password: "secret-pass"}
out, err := normalizeProxyInstanceForSave(config.ProxyInstance{
ID: "inst-1",
DeviceID: "dev-1",
ListenAddr: "0.0.0.0",
ListenPort: 1080,
Mode: "http",
AuthEnabled: true,
Username: "user",
Password: "******",
}, old)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if out.Password != "secret-pass" {
t.Fatalf("password restore mismatch: got=%q", out.Password)
}
}
func TestProxyOverviewReadsInstancesFromDatabaseAcrossServerInstances(t *testing.T) {
gin.SetMode(gin.TestMode)
dbPath := filepath.Join(t.TempDir(), "proxy_overview.db")
if err := db.Init(dbPath); err != nil {
t.Fatalf("Init() error = %v", err)
}
t.Cleanup(func() {
db.DB = nil
})
saveServer := &Server{
fullCfg: &config.Config{},
proxyRepo: repo.NewDBRepo(),
loginAttempts: make(map[string]loginAttempt),
}
body := `{"instances":[{"id":"proxy-db-1","name":"DB Proxy","device_id":"dev-1","enabled":true,"mode":"socks5","listen_addr":"127.0.0.1","listen_port":10800,"auth_enabled":false}]}`
saveRecorder := httptest.NewRecorder()
saveCtx, _ := gin.CreateTestContext(saveRecorder)
saveCtx.Request = httptest.NewRequest(http.MethodPut, "/api/proxy-instances/config", strings.NewReader(body))
saveCtx.Request.Header.Set("Content-Type", "application/json")
saveServer.handleProxyUpdateConfig(saveCtx)
if saveRecorder.Code != http.StatusOK {
t.Fatalf("save status code mismatch: got=%d want=%d body=%s", saveRecorder.Code, http.StatusOK, saveRecorder.Body.String())
}
overviewServer := &Server{
fullCfg: &config.Config{},
proxyRepo: repo.NewDBRepo(),
loginAttempts: make(map[string]loginAttempt),
}
overviewRecorder := httptest.NewRecorder()
overviewCtx, _ := gin.CreateTestContext(overviewRecorder)
overviewCtx.Request = httptest.NewRequest(http.MethodGet, "/api/proxy-instances/overview", nil)
overviewServer.handleProxyOverview(overviewCtx)
if overviewRecorder.Code != http.StatusOK {
t.Fatalf("overview status code mismatch: got=%d want=%d body=%s", overviewRecorder.Code, http.StatusOK, overviewRecorder.Body.String())
}
var payload struct {
Instances []struct {
ID string `json:"id"`
Name string `json:"name"`
DeviceID string `json:"device_id"`
ListenPort int `json:"listen_port"`
} `json:"instances"`
}
if err := json.Unmarshal(overviewRecorder.Body.Bytes(), &payload); err != nil {
t.Fatalf("unmarshal overview response failed: %v", err)
}
if len(payload.Instances) != 1 {
t.Fatalf("instances count mismatch: got=%d want=1", len(payload.Instances))
}
inst := payload.Instances[0]
if inst.ID != "proxy-db-1" || inst.Name != "DB Proxy" || inst.DeviceID != "dev-1" || inst.ListenPort != 10800 {
t.Fatalf("unexpected instance payload: %+v", inst)
}
}
func TestBuildProxyConfigsAllowsInterfaceWithoutGlobalIPv4(t *testing.T) {
initProxyTestConfig(t, `devices:
- id: dev-lo
name: Loopback
`)
// 零路径架构: interface 由运行时解析并存在 worker.Config.Interface 里,不从文件读取。
p := device.NewPool(&config.Config{})
setNestedPrivateField(t, p, []string{"workers"}, map[string]*device.Worker{
"dev-lo": {ID: "dev-lo", Config: config.DeviceConfig{ID: "dev-lo", Interface: "lo"}},
})
s := &Server{
pool: p,
proxyRepo: staticProxyInstanceRepo{instances: []config.ProxyInstance{
{
ID: "proxy-lo",
DeviceID: "dev-lo",
Enabled: true,
Mode: "socks5",
ListenAddr: "127.0.0.1",
ListenPort: 10801,
},
}},
}
cfgs, err := s.buildProxyConfigs(context.Background())
if err != nil {
t.Fatalf("buildProxyConfigs() error = %v", err)
}
if len(cfgs) != 1 {
t.Fatalf("config count mismatch: got=%d want=1", len(cfgs))
}
if cfgs[0].Interface != "lo" {
t.Fatalf("interface mismatch: got=%q want=lo", cfgs[0].Interface)
}
}
func TestBuildProxyConfigsAllowsMissingRuntimeInterface(t *testing.T) {
const missingIface = "vohive-missing-proxy-iface"
initProxyTestConfig(t, `devices:
- id: dev-missing
name: Missing Interface
`)
// 零路径架构: interface 由运行时解析并存在 worker.Config.Interface 里,不从文件读取。
// 即使接口不存在于系统(如测试环境),buildProxyConfigs 只需能查到 interface 名即可。
p := device.NewPool(&config.Config{})
setNestedPrivateField(t, p, []string{"workers"}, map[string]*device.Worker{
"dev-missing": {ID: "dev-missing", Config: config.DeviceConfig{ID: "dev-missing", Interface: missingIface}},
})
s := &Server{
pool: p,
proxyRepo: staticProxyInstanceRepo{instances: []config.ProxyInstance{
{
ID: "proxy-missing-iface",
DeviceID: "dev-missing",
Enabled: true,
Mode: "http",
ListenAddr: "127.0.0.1",
ListenPort: 10802,
},
}},
}
cfgs, err := s.buildProxyConfigs(context.Background())
if err != nil {
t.Fatalf("buildProxyConfigs() error = %v", err)
}
if len(cfgs) != 1 {
t.Fatalf("config count mismatch: got=%d want=1", len(cfgs))
}
if cfgs[0].Interface != missingIface {
t.Fatalf("interface mismatch: got=%q want=%s", cfgs[0].Interface, missingIface)
}
}
+86
View File
@@ -0,0 +1,86 @@
package api
import (
"net/http"
"strings"
"github.com/gin-gonic/gin"
"github.com/iniwex5/vohive/internal/db"
)
type enabledPatchRequest struct {
Enabled *bool `json:"enabled"`
}
type networkPatchRequest struct {
Enabled *bool `json:"enabled"`
IPVersion string `json:"ip_version"`
APN string `json:"apn"`
}
func (s *Server) handleDeviceNetworkPatch(c *gin.Context) {
var req networkPatchRequest
if err := c.ShouldBindJSON(&req); err != nil || req.Enabled == nil {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": "enabled 为必填项"})
return
}
deviceID := deviceIDParam(c)
if *req.Enabled {
// 落库:network_enabled=true + ip_version + apn(APN/IP 供下次连接生效)
ipVersion := strings.TrimSpace(req.IPVersion)
apn := strings.TrimSpace(req.APN)
iccid, _, _ := s.patchCardPolicyForDevice(deviceID, func(p *db.CardPolicy) {
p.NetworkEnabled = true
if ipVersion != "" {
p.IPVersion = ipVersion
}
p.APN = apn
})
// 同步 w.Config,使概览读到最新值(QMI APN 在下次连接时生效)
if iccid != "" {
s.pool.SetWorkerNetworkPolicy(deviceID, true, ipVersion, apn)
}
s.handleDeviceMgmtStartNetwork(c)
return
}
// enabled=false:落库 network_enabled=false
s.patchCardPolicyForDevice(deviceID, func(p *db.CardPolicy) {
p.NetworkEnabled = false
})
s.handleDeviceMgmtStopNetwork(c)
}
func (s *Server) handleDeviceVoWiFiPatch(c *gin.Context) {
var req enabledPatchRequest
if err := c.ShouldBindJSON(&req); err != nil || req.Enabled == nil {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": "enabled 为必填项"})
return
}
deviceID := deviceIDParam(c)
if *req.Enabled {
// 落库:仅置 vowifi_enabled=true。不碰 airplane_enabled——它是用户的纯飞行
// 意图,作为关闭 VoWiFi 后的回退依据;VoWiFi 接管射频由运行时投影派生。
s.patchCardPolicyForDevice(deviceID, vowifiEnablePolicyMutation)
// 同步 w.Config,使概览即时切到 VoWiFi 模式面板(EnableVoWiFi 不碰 Config)。
s.pool.SetWorkerVoWiFiPolicy(deviceID, true)
s.handleVoWiFiEnable(c)
return
}
// 落库:仅清 vowifi_enabled=false,保留 airplane_enabled(用户飞行意图)。
// 关闭 VoWiFi 后 DisableVoWiFi 会按当前卡策略重投影:之前是飞行则回飞行,否则回在线。
s.patchCardPolicyForDevice(deviceID, vowifiDisablePolicyMutation)
s.pool.SetWorkerVoWiFiPolicy(deviceID, false)
s.handleVoWiFiDisable(c)
}
// vowifiEnablePolicyMutation 开 VoWiFi 的落库副作用:只置 vowifi,飞行意图保持不变。
func vowifiEnablePolicyMutation(p *db.CardPolicy) { p.VoWiFiEnabled = true }
// vowifiDisablePolicyMutation 关 VoWiFi 的落库副作用:只清 vowifi,保留用户飞行意图以便回退。
func vowifiDisablePolicyMutation(p *db.CardPolicy) { p.VoWiFiEnabled = false }
File diff suppressed because it is too large. Load diff
+349
View File
@@ -0,0 +1,349 @@
package api
import (
"net/http"
"strings"
"github.com/iniwex5/vohive/internal/config"
"github.com/iniwex5/vohive/pkg/logger"
"github.com/gin-gonic/gin"
)
type notificationSettingsResponse struct {
Telegram struct {
Enabled bool `json:"enabled"`
BotToken string `json:"bot_token"`
ChatID int64 `json:"chat_id"`
AdminID int64 `json:"admin_id"`
BaseURL string `json:"base_url"`
Proxy string `json:"proxy"`
} `json:"telegram"`
Feishu struct {
Enabled bool `json:"enabled"`
AppID string `json:"app_id"`
AppSecret string `json:"app_secret"`
ChatIDs []string `json:"chat_ids"`
} `json:"feishu"`
QQ struct {
Enabled bool `json:"enabled"`
AppID string `json:"app_id"`
AppSecret string `json:"app_secret"`
GroupIDs string `json:"group_ids"`
DirectIDs string `json:"direct_ids"`
} `json:"qq"`
Webhook struct {
Enabled bool `json:"enabled"`
URLs []string `json:"urls"`
Secret string `json:"secret"`
TimeoutMs int `json:"timeout_ms"`
RetryMax int `json:"retry_max"`
TextTemplate string `json:"text_template"`
Headers map[string]string `json:"headers,omitempty"`
} `json:"webhook"`
Weixin struct {
Enabled bool `json:"enabled"`
BaseURL string `json:"base_url"`
AllowedUserIDs []string `json:"allowed_user_ids"`
} `json:"weixin"`
Bark struct {
Enabled bool `json:"enabled"`
URLs []string `json:"urls"`
Group string `json:"group"`
Icon string `json:"icon"`
Level string `json:"level"`
} `json:"bark"`
Email struct {
Enabled bool `json:"enabled"`
UseSSL bool `json:"use_ssl"`
SMTPHost string `json:"smtp_host"`
SMTPPort int `json:"smtp_port"`
Username string `json:"username"`
Password string `json:"password"`
FromAddress string `json:"from_address"`
ToAddresses []string `json:"to_addresses"`
} `json:"email"`
Pushplus struct {
Enabled bool `json:"enabled"`
Token string `json:"token"`
Topic string `json:"topic"`
Channel string `json:"channel"`
} `json:"pushplus"`
}
type updateNotificationSettingsRequest struct {
Telegram struct {
Enabled bool `json:"enabled"`
BotToken string `json:"bot_token"`
ChatID int64 `json:"chat_id"`
AdminID int64 `json:"admin_id"`
BaseURL string `json:"base_url"`
Proxy string `json:"proxy"` // HTTP 代理
} `json:"telegram"`
Feishu struct {
Enabled bool `json:"enabled"`
AppID string `json:"app_id"`
AppSecret string `json:"app_secret"`
ChatIDs []string `json:"chat_ids"`
} `json:"feishu"`
QQ struct {
Enabled bool `json:"enabled"`
AppID string `json:"app_id"`
AppSecret string `json:"app_secret"`
GroupIDs string `json:"group_ids"`
DirectIDs string `json:"direct_ids"`
} `json:"qq"`
Webhook struct {
Enabled bool `json:"enabled"`
URLs []string `json:"urls"`
Secret string `json:"secret"`
TimeoutMs int `json:"timeout_ms"`
RetryMax int `json:"retry_max"`
TextTemplate string `json:"text_template"`
Headers map[string]string `json:"headers,omitempty"`
} `json:"webhook"`
Bark struct {
Enabled bool `json:"enabled"`
URLs []string `json:"urls"`
Group string `json:"group"`
Icon string `json:"icon"`
Level string `json:"level"`
} `json:"bark"`
Email struct {
Enabled bool `json:"enabled"`
UseSSL bool `json:"use_ssl"`
SMTPHost string `json:"smtp_host"`
SMTPPort int `json:"smtp_port"`
Username string `json:"username"`
Password string `json:"password"`
FromAddress string `json:"from_address"`
ToAddresses []string `json:"to_addresses"`
} `json:"email"`
Pushplus struct {
Enabled bool `json:"enabled"`
Token string `json:"token"`
Topic string `json:"topic"`
Channel string `json:"channel"`
} `json:"pushplus"`
}
func (s *Server) handleGetNotificationSettings(c *gin.Context) {
var resp notificationSettingsResponse
resp.Telegram.Enabled = s.fullCfg.Telegram.Enabled
resp.Telegram.BotToken = s.fullCfg.Telegram.BotToken
resp.Telegram.ChatID = s.fullCfg.Telegram.ChatID
resp.Telegram.AdminID = s.fullCfg.Telegram.AdminID
resp.Telegram.BaseURL = s.fullCfg.Telegram.BaseURL
resp.Telegram.Proxy = s.fullCfg.Telegram.Proxy
resp.Feishu.Enabled = s.fullCfg.Feishu.Enabled
resp.Feishu.AppID = s.fullCfg.Feishu.AppID
resp.Feishu.AppSecret = s.fullCfg.Feishu.AppSecret
resp.Feishu.ChatIDs = s.fullCfg.Feishu.ChatIDs
resp.QQ.Enabled = s.fullCfg.QQ.Enabled
resp.QQ.AppID = s.fullCfg.QQ.AppID
resp.QQ.AppSecret = s.fullCfg.QQ.AppSecret
resp.QQ.GroupIDs = s.fullCfg.QQ.GroupIDs
resp.QQ.DirectIDs = s.fullCfg.QQ.DirectIDs
resp.Webhook.Enabled = s.fullCfg.Webhook.Enabled
resp.Webhook.URLs = s.fullCfg.Webhook.URLs
resp.Webhook.Secret = s.fullCfg.Webhook.Secret
resp.Webhook.TimeoutMs = s.fullCfg.Webhook.TimeoutMs
resp.Webhook.RetryMax = s.fullCfg.Webhook.RetryMax
resp.Webhook.TextTemplate = s.fullCfg.Webhook.TextTemplate
resp.Webhook.Headers = s.fullCfg.Webhook.Headers
resp.Bark.Enabled = s.fullCfg.Bark.Enabled
resp.Bark.URLs = s.fullCfg.Bark.URLs
resp.Bark.Group = s.fullCfg.Bark.Group
resp.Bark.Icon = s.fullCfg.Bark.Icon
resp.Bark.Level = s.fullCfg.Bark.Level
resp.Email.Enabled = s.fullCfg.Email.Enabled
resp.Email.UseSSL = s.fullCfg.Email.UseSSL
resp.Email.SMTPHost = s.fullCfg.Email.SMTPHost
resp.Email.SMTPPort = s.fullCfg.Email.SMTPPort
resp.Email.Username = s.fullCfg.Email.Username
resp.Email.Password = s.fullCfg.Email.Password
resp.Email.FromAddress = s.fullCfg.Email.FromAddress
resp.Email.ToAddresses = append([]string(nil), s.fullCfg.Email.ToAddresses...)
resp.Pushplus.Enabled = s.fullCfg.Pushplus.Enabled
resp.Pushplus.Token = s.fullCfg.Pushplus.Token
resp.Pushplus.Topic = s.fullCfg.Pushplus.Topic
resp.Pushplus.Channel = s.fullCfg.Pushplus.Channel
c.JSON(http.StatusOK, resp)
}
func (s *Server) handleUpdateNotificationSettings(c *gin.Context) {
var req updateNotificationSettingsRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": "参数错误"})
return
}
tg := config.TelegramConfig{
Enabled: req.Telegram.Enabled,
BotToken: strings.TrimSpace(req.Telegram.BotToken),
ChatID: req.Telegram.ChatID,
AdminID: req.Telegram.AdminID,
BaseURL: strings.TrimSpace(req.Telegram.BaseURL),
Proxy: strings.TrimSpace(req.Telegram.Proxy),
}
var fsChatIDs []string
for _, id := range req.Feishu.ChatIDs {
id = strings.TrimSpace(id)
if id != "" {
fsChatIDs = append(fsChatIDs, id)
}
}
fs := config.FeishuConfig{
Enabled: req.Feishu.Enabled,
AppID: strings.TrimSpace(req.Feishu.AppID),
AppSecret: strings.TrimSpace(req.Feishu.AppSecret),
ChatIDs: fsChatIDs,
}
qq := config.QQConfig{
Enabled: req.QQ.Enabled,
AppID: strings.TrimSpace(req.QQ.AppID),
AppSecret: strings.TrimSpace(req.QQ.AppSecret),
GroupIDs: strings.TrimSpace(req.QQ.GroupIDs),
DirectIDs: strings.TrimSpace(req.QQ.DirectIDs),
}
whURLs := make([]string, 0, len(req.Webhook.URLs))
for _, u := range req.Webhook.URLs {
u = strings.TrimSpace(u)
if u == "" {
continue
}
whURLs = append(whURLs, u)
}
wh := config.WebhookConfig{
Enabled: req.Webhook.Enabled,
URLs: whURLs,
Secret: strings.TrimSpace(req.Webhook.Secret),
TimeoutMs: req.Webhook.TimeoutMs,
RetryMax: req.Webhook.RetryMax,
TextTemplate: req.Webhook.TextTemplate,
Headers: req.Webhook.Headers,
}
barkURLs := make([]string, 0, len(req.Bark.URLs))
for _, u := range req.Bark.URLs {
u = strings.TrimSpace(u)
if u == "" {
continue
}
barkURLs = append(barkURLs, u)
}
barkCfg := config.BarkConfig{
Enabled: req.Bark.Enabled,
URLs: barkURLs,
Group: strings.TrimSpace(req.Bark.Group),
Icon: strings.TrimSpace(req.Bark.Icon),
Level: strings.TrimSpace(req.Bark.Level),
}
emailTo := make([]string, 0, len(req.Email.ToAddresses))
for _, a := range req.Email.ToAddresses {
a = strings.TrimSpace(a)
if a != "" {
emailTo = append(emailTo, a)
}
}
em := config.EmailConfig{
Enabled: req.Email.Enabled,
UseSSL: req.Email.UseSSL,
SMTPHost: strings.TrimSpace(req.Email.SMTPHost),
SMTPPort: req.Email.SMTPPort,
Username: strings.TrimSpace(req.Email.Username),
Password: strings.TrimSpace(req.Email.Password),
FromAddress: strings.TrimSpace(req.Email.FromAddress),
ToAddresses: emailTo,
}
pp := config.PushplusConfig{
Enabled: req.Pushplus.Enabled,
Token: strings.TrimSpace(req.Pushplus.Token),
Topic: strings.TrimSpace(req.Pushplus.Topic),
Channel: strings.TrimSpace(req.Pushplus.Channel),
}
if tg.Enabled {
if tg.BotToken == "" || tg.ChatID == 0 {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": "Telegram 启用时必须填写 bot_token 与 chat_id"})
return
}
}
if fs.Enabled {
if fs.AppID == "" || fs.AppSecret == "" {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": "飞书启用时必须填写 app_id 与 app_secret"})
return
}
}
if qq.Enabled {
if qq.AppID == "" || qq.AppSecret == "" {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": "QQ 启用时必须填写 app_id 与 app_secret"})
return
}
}
if wh.Enabled && len(wh.URLs) == 0 {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": "Webhook 启用时至少需要一个 URL"})
return
}
if barkCfg.Enabled && len(barkCfg.URLs) == 0 {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": "Bark 启用时至少需要一个 URL"})
return
}
if em.Enabled && (em.SMTPHost == "" || em.FromAddress == "" || len(em.ToAddresses) == 0) {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": "Email 启用时必须填写 SMTP Host、发件人及收件人"})
return
}
if pp.Enabled && pp.Token == "" {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": "Pushplus 启用时必须填写 Token"})
return
}
if err := config.UpdateNotificationInFile(s.configPath, tg, fs, qq, wh, barkCfg, em, pp); err != nil {
logger.Error("写入通知配置失败", "err", err)
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": "写入配置文件失败: " + err.Error()})
return
}
s.fullCfg.Telegram = tg
s.fullCfg.Feishu = fs
s.fullCfg.QQ = qq
s.fullCfg.Webhook = wh
s.fullCfg.Bark = barkCfg
s.fullCfg.Email = em
s.fullCfg.Pushplus = pp
if s.notifyMgr != nil {
if err := s.notifyMgr.UpdateConfig(s.fullCfg); err != nil {
logger.Error("应用通知配置失败", "err", err)
c.JSON(http.StatusOK, gin.H{
"status": "ok",
"applied": false,
"warning": "通知配置已写入,但运行时初始化失败: " + err.Error(),
})
return
}
}
c.JSON(http.StatusOK, gin.H{"status": "ok", "applied": true})
}
+92
View File
@@ -0,0 +1,92 @@
package api
import (
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/iniwex5/vohive/internal/config"
"github.com/iniwex5/vohive/internal/notify"
)
type testBarkRequest struct {
Enabled bool `json:"enabled"`
URLs []string `json:"urls"`
Group string `json:"group"`
Icon string `json:"icon"`
Level string `json:"level"`
}
type testBarkResponse struct {
OK bool `json:"ok"`
Message string `json:"message"`
FailedURLs []string `json:"failed_urls,omitempty"`
}
func (s *Server) handleTestBarkNotification(c *gin.Context) {
var req testBarkRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"message": "参数错误"})
return
}
if !req.Enabled {
c.JSON(http.StatusBadRequest, gin.H{"message": "请先启用 Bark 后再测试"})
return
}
urls := make([]string, 0, len(req.URLs))
for _, u := range req.URLs {
trimmed := strings.TrimSpace(u)
if trimmed == "" {
continue
}
urls = append(urls, trimmed)
}
if len(urls) == 0 {
c.JSON(http.StatusBadRequest, gin.H{"message": "至少需要一个有效的 Bark URL"})
return
}
ch, err := notify.NewBarkChannel(config.BarkConfig{
Enabled: true,
URLs: urls,
Group: strings.TrimSpace(req.Group),
Icon: strings.TrimSpace(req.Icon),
Level: strings.TrimSpace(req.Level),
})
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"message": "初始化 Bark 测试发送器失败: " + err.Error()})
return
}
if ch == nil {
c.JSON(http.StatusInternalServerError, gin.H{"message": "Bark 测试发送器未初始化"})
return
}
defer ch.Close()
now := time.Now()
ctx := notify.NotificationContext{
Event: "bark_test",
Text: "这是一条 Bark 测试通知",
DeviceID: "test_device_001",
DeviceName: "测试设备",
Timestamp: now,
}
result, sendErr := ch.SendWithContextDetailed(ctx)
if sendErr != nil {
c.JSON(http.StatusOK, testBarkResponse{
OK: false,
Message: "测试通知发送失败: " + sendErr.Error(),
FailedURLs: result.FailedURLs,
})
return
}
c.JSON(http.StatusOK, testBarkResponse{
OK: true,
Message: "测试通知已发送",
})
}
+87
View File
@@ -0,0 +1,87 @@
package api
import (
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/iniwex5/vohive/internal/config"
"github.com/iniwex5/vohive/internal/notify"
)
type testEmailRequest struct {
Enabled bool `json:"enabled"`
UseSSL bool `json:"use_ssl"`
SMTPHost string `json:"smtp_host"`
SMTPPort int `json:"smtp_port"`
Username string `json:"username"`
Password string `json:"password"`
FromAddress string `json:"from_address"`
ToAddresses []string `json:"to_addresses"`
}
func (s *Server) handleTestEmailNotification(c *gin.Context) {
var req testEmailRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"message": "参数错误"})
return
}
if !req.Enabled {
c.JSON(http.StatusBadRequest, gin.H{"message": "请先启用 Email 后再测试"})
return
}
toAddrs := make([]string, 0, len(req.ToAddresses))
for _, a := range req.ToAddresses {
trimmed := strings.TrimSpace(a)
if trimmed == "" {
continue
}
toAddrs = append(toAddrs, trimmed)
}
if len(toAddrs) == 0 {
c.JSON(http.StatusBadRequest, gin.H{"message": "至少需要一个有效的收件人地址"})
return
}
ch, err := notify.NewEmailChannel(config.EmailConfig{
Enabled: true,
UseSSL: req.UseSSL,
SMTPHost: strings.TrimSpace(req.SMTPHost),
SMTPPort: req.SMTPPort,
Username: strings.TrimSpace(req.Username),
Password: strings.TrimSpace(req.Password),
FromAddress: strings.TrimSpace(req.FromAddress),
ToAddresses: toAddrs,
})
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"message": "初始化 Email 测试发送器失败: " + err.Error()})
return
}
now := time.Now()
ctx := notify.NotificationContext{
Event: "测试",
Text: "这是一条来自 Vohive 的邮件测试通知,收到说明您的邮件配置正确!",
DeviceID: "test_device_001",
DeviceName: "测试设备",
Timestamp: now,
}
sendErr := ch.SendWithContext(ctx)
if sendErr != nil {
c.JSON(http.StatusOK, gin.H{
"ok": false,
"message": "测试邮件发送失败: " + sendErr.Error(),
})
return
}
c.JSON(http.StatusOK, gin.H{
"ok": true,
"message": "测试邮件已发送",
})
}
+105
View File
@@ -0,0 +1,105 @@
package api
import (
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/iniwex5/vohive/internal/config"
"github.com/iniwex5/vohive/internal/notify"
)
type testWebhookRequest struct {
Enabled bool `json:"enabled"`
URLs []string `json:"urls"`
Secret string `json:"secret"`
TimeoutMs int `json:"timeout_ms"`
RetryMax int `json:"retry_max"`
TextTemplate string `json:"text_template"`
Headers map[string]string `json:"headers,omitempty"`
}
type testWebhookResponse struct {
OK bool `json:"ok"`
Message string `json:"message"`
FailedURLs []string `json:"failed_urls,omitempty"`
}
func (s *Server) handleTestWebhookNotification(c *gin.Context) {
var req testWebhookRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"message": "参数错误"})
return
}
if !req.Enabled {
c.JSON(http.StatusBadRequest, gin.H{"message": "请先启用 Webhook 后再测试"})
return
}
urls := make([]string, 0, len(req.URLs))
for _, u := range req.URLs {
trimmed := strings.TrimSpace(u)
if trimmed == "" {
continue
}
urls = append(urls, trimmed)
}
if len(urls) == 0 {
c.JSON(http.StatusBadRequest, gin.H{"message": "至少需要一个有效的 Webhook URL"})
return
}
if req.TimeoutMs < 1000 || req.TimeoutMs > 60000 {
c.JSON(http.StatusBadRequest, gin.H{"message": "timeout_ms 必须在 1000-60000 之间"})
return
}
if req.RetryMax < 0 || req.RetryMax > 10 {
c.JSON(http.StatusBadRequest, gin.H{"message": "retry_max 必须在 0-10 之间"})
return
}
ch, err := notify.NewWebhookChannel(config.WebhookConfig{
Enabled: true,
URLs: urls,
Secret: strings.TrimSpace(req.Secret),
TimeoutMs: req.TimeoutMs,
RetryMax: req.RetryMax,
TextTemplate: req.TextTemplate,
Headers: req.Headers,
})
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"message": "初始化 Webhook 测试发送器失败: " + err.Error()})
return
}
if ch == nil {
c.JSON(http.StatusInternalServerError, gin.H{"message": "Webhook 测试发送器未初始化"})
return
}
defer ch.Close()
now := time.Now()
ctx := notify.NotificationContext{
Event: "webhook_test",
Text: "这是一条 Webhook 测试通知",
DeviceID: "test_device_001",
DeviceName: "测试设备",
Timestamp: now,
}
result, sendErr := ch.SendWithContextDetailed(ctx)
if sendErr != nil {
c.JSON(http.StatusOK, testWebhookResponse{
OK: false,
Message: "测试通知发送失败: " + sendErr.Error(),
FailedURLs: result.FailedURLs,
})
return
}
c.JSON(http.StatusOK, testWebhookResponse{
OK: true,
Message: "测试通知已发送",
})
}
+49
View File
@@ -0,0 +1,49 @@
package api
import "testing"
func TestSMSInboxIMSIDefaultsToCachedValueWithoutLiveRead(t *testing.T) {
source := &smsIMSIProbe{cached: " 001010000000001 "}
got := smsInboxIMSI(source, false)
if got != "001010000000001" {
t.Fatalf("smsInboxIMSI() = %q, want cached IMSI", got)
}
if source.liveCalls != 0 {
t.Fatalf("GetIMSI live calls = %d, want 0", source.liveCalls)
}
}
func TestSMSInboxIMSIAllowsLiveFallbackOnlyOnExplicitRefresh(t *testing.T) {
source := &smsIMSIProbe{live: " 001010000000002 "}
if got := smsInboxIMSI(source, false); got != "" {
t.Fatalf("smsInboxIMSI(no refresh) = %q, want empty cached value", got)
}
if source.liveCalls != 0 {
t.Fatalf("GetIMSI live calls without refresh = %d, want 0", source.liveCalls)
}
if got := smsInboxIMSI(source, true); got != "001010000000002" {
t.Fatalf("smsInboxIMSI(refresh) = %q, want live fallback", got)
}
if source.liveCalls != 1 {
t.Fatalf("GetIMSI live calls with refresh = %d, want 1", source.liveCalls)
}
}
type smsIMSIProbe struct {
cached string
live string
liveCalls int
}
func (p *smsIMSIProbe) GetCachedIMSI() string {
return p.cached
}
func (p *smsIMSIProbe) GetIMSI() string {
p.liveCalls++
return p.live
}
+133
View File
@@ -0,0 +1,133 @@
package api
import (
"errors"
"net/http"
"os"
"os/exec"
"time"
"github.com/gin-gonic/gin"
"github.com/iniwex5/vohive/internal/config"
"github.com/iniwex5/vohive/internal/updater"
"github.com/iniwex5/vohive/pkg/logger"
)
var errNotFound = errors.New("not found")
// resolveUninstallTargets 计算自毁流程需要清理的数据目录和配置文件路径。
// 配置文件路径必须来自运行时实际加载的路径(config.GetConfigPath()),
// 不能假定其固定位于进程工作目录下的 "config" 子目录——
// OpenWrt 部署通过 -c 显式传入 /etc/vohive/config.yaml,与工作目录无关,
// 用硬编码相对路径删除会删错地方(实际等于什么都没删)。
// configPath 为空(配置管理器未初始化)时不返回任何配置文件路径,避免误删。
func resolveUninstallTargets(configPath string) (dataDir string, configFile string) {
return "data", configPath
}
// detectServiceStopCommands 根据当前部署形态返回应执行的"停止 + 禁用自启"命令。
// systemd 的 Restart=always 和 OpenWrt procd 的 respawn 都只在进程
// "非主动" 退出时才会重新拉起;只要在自毁前显式请求服务管理器停止/禁用,
// 即使后续删除可执行文件失败(例如只读 squashfs),也不会被重新拉起。
// 仅靠"删掉自己导致 exec 失败"这种副作用来阻止重启是不可靠的。
func detectServiceStopCommands(lookPath func(string) (string, error), statFile func(string) bool) [][]string {
var cmds [][]string
if statFile("/etc/init.d/vohive") {
cmds = append(cmds, []string{"/etc/init.d/vohive", "disable"})
cmds = append(cmds, []string{"/etc/init.d/vohive", "stop"})
return cmds
}
if _, err := lookPath("systemctl"); err == nil {
cmds = append(cmds, []string{"systemctl", "disable", "--now", "vohive"})
}
return cmds
}
// handleCheckUpdate 检查系统更新
func (s *Server) handleCheckUpdate(c *gin.Context) {
info, err := updater.CheckUpdate()
if err != nil {
logger.Error("检查系统更新失败", "err", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, info)
}
// handleApplyUpdate 应用系统更新
func (s *Server) handleApplyUpdate(c *gin.Context) {
if err := updater.ApplyUpdate(); err != nil {
status := http.StatusInternalServerError
if errors.Is(err, updater.ErrDisabled) {
status = http.StatusConflict
} else {
logger.Error("应用更新失败", "err", err)
}
c.JSON(status, gin.H{
"status": "error",
"message": err.Error(),
})
return
}
c.JSON(http.StatusOK, gin.H{"message": "正在后台下载更新,系统稍后将自动重启..."})
}
// handleUninstall 自毁/卸载接口,用于用户拒绝免责声明时
// 必须登录后才能调用——这是真正会删数据、删配置、删自身可执行文件并
// os.Exit(0) 的破坏性操作,绝不能允许未鉴权请求触发。
func (s *Server) handleUninstall(c *gin.Context) {
if !s.isAuthenticatedRequest(c, time.Now()) {
c.JSON(http.StatusUnauthorized, gin.H{
"status": "error",
"code": "unauthorized",
"message": "未授权",
"request_id": requestID(c),
})
return
}
logger.Warn("用户拒绝了免责声明,正在触发自毁/卸载逻辑")
c.JSON(http.StatusOK, gin.H{"message": "正在卸载软件..."})
// 在后台异步执行自毁,以免请求无法返回
go func() {
time.Sleep(1 * time.Second)
// 先主动通知服务管理器停止 + 禁用自启,确保即使后面的文件删除
// 失败(只读文件系统等),systemd Restart=always / procd respawn
// 也不会把进程重新拉起来。命令异步触发(Start 不 Wait),
// 避免对"停止自己"这条命令的等待造成死锁。
for _, args := range detectServiceStopCommands(exec.LookPath, fileExists) {
cmd := exec.Command(args[0], args[1:]...)
if err := cmd.Start(); err != nil {
logger.Warn("通知服务管理器停止失败", "cmd", args, "err", err)
continue
}
go cmd.Wait()
}
dataDir, configFile := resolveUninstallTargets(config.GetConfigPath())
if err := os.RemoveAll(dataDir); err != nil {
logger.Warn("清理数据目录失败", "dir", dataDir, "err", err)
}
if configFile != "" {
if err := os.Remove(configFile); err != nil && !os.IsNotExist(err) {
logger.Warn("清理配置文件失败", "file", configFile, "err", err)
}
}
if executable, err := os.Executable(); err == nil {
if err := os.Remove(executable); err != nil {
logger.Warn("删除可执行文件失败", "file", executable, "err", err)
}
}
logger.Warn("自毁流程结束,退出进程")
os.Exit(0)
}()
}
func fileExists(path string) bool {
_, err := os.Stat(path)
return err == nil
}
+150
View File
@@ -0,0 +1,150 @@
package api
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"net/http"
"net/http/httptest"
"strconv"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/iniwex5/vohive/internal/config"
)
// resolveUninstallTargets 必须使用运行时实际加载的配置文件路径,
// 而不是硬编码相对路径 "config"——后者在 OpenWrt 部署下(通过 -c 传入
// /etc/vohive/config.yaml,与进程工作目录无关)永远指向一个不存在的目录,
// 导致真实配置文件从未被清理。
func TestResolveUninstallTargetsUsesActualConfigPath(t *testing.T) {
dataDir, configFile := resolveUninstallTargets("/etc/vohive/config.yaml")
if dataDir != "data" {
t.Fatalf("dataDir = %q, want %q", dataDir, "data")
}
if configFile != "/etc/vohive/config.yaml" {
t.Fatalf("configFile = %q, want %q", configFile, "/etc/vohive/config.yaml")
}
}
func TestResolveUninstallTargetsSkipsConfigWhenPathUnknown(t *testing.T) {
// 配置管理器尚未初始化时 config.GetConfigPath() 返回空字符串,
// 此时绝不能删除任何路径(避免误删进程当前工作目录)。
_, configFile := resolveUninstallTargets("")
if configFile != "" {
t.Fatalf("configFile = %q, want empty when config path unknown", configFile)
}
}
// detectServiceStopCommands 决定自毁前应主动通知哪个服务管理器停止+禁用自启,
// 这样即使删除可执行文件失败(例如只读文件系统),supervisor 也不会把进程重新拉起来,
// 而不是像原来那样仅依赖"删掉自己导致 exec 失败"这种脆弱的副作用。
func TestDetectServiceStopCommandsPrefersOpenWrtInitScript(t *testing.T) {
statFile := func(path string) bool { return path == "/etc/init.d/vohive" }
lookPath := func(name string) (string, error) { return "/usr/bin/systemctl", nil }
cmds := detectServiceStopCommands(lookPath, statFile)
if len(cmds) != 2 {
t.Fatalf("len(cmds) = %d, want 2 (disable + stop), got %v", len(cmds), cmds)
}
if cmds[0][0] != "/etc/init.d/vohive" || cmds[0][1] != "disable" {
t.Fatalf("cmds[0] = %v, want [/etc/init.d/vohive disable]", cmds[0])
}
if cmds[1][0] != "/etc/init.d/vohive" || cmds[1][1] != "stop" {
t.Fatalf("cmds[1] = %v, want [/etc/init.d/vohive stop]", cmds[1])
}
}
func TestDetectServiceStopCommandsFallsBackToSystemd(t *testing.T) {
statFile := func(path string) bool { return false }
lookPath := func(name string) (string, error) {
if name == "systemctl" {
return "/usr/bin/systemctl", nil
}
return "", errNotFound
}
cmds := detectServiceStopCommands(lookPath, statFile)
if len(cmds) != 1 {
t.Fatalf("len(cmds) = %d, want 1, got %v", len(cmds), cmds)
}
want := []string{"systemctl", "disable", "--now", "vohive"}
if len(cmds[0]) != len(want) {
t.Fatalf("cmds[0] = %v, want %v", cmds[0], want)
}
for i := range want {
if cmds[0][i] != want[i] {
t.Fatalf("cmds[0] = %v, want %v", cmds[0], want)
}
}
}
func TestDetectServiceStopCommandsEmptyWhenNoSupervisorDetected(t *testing.T) {
statFile := func(path string) bool { return false }
lookPath := func(name string) (string, error) { return "", errNotFound }
cmds := detectServiceStopCommands(lookPath, statFile)
if len(cmds) != 0 {
t.Fatalf("cmds = %v, want empty when neither systemd nor openwrt detected", cmds)
}
}
func TestHandleUninstallRejectsUnauthenticatedRequest(t *testing.T) {
gin.SetMode(gin.TestMode)
s := &Server{auth: config.WebConfig{Username: "admin", Password: "secret"}}
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodPost, "/api/system/uninstall", nil)
s.handleUninstall(c)
if w.Code != http.StatusUnauthorized {
t.Fatalf("code=%d body=%s, want 401 —— uninstall 必须要求登录后才能调用", w.Code, w.Body.String())
}
}
func TestNewRouterRequiresAuthForUninstall(t *testing.T) {
gin.SetMode(gin.TestMode)
s := &Server{auth: config.WebConfig{Username: "admin", Password: "secret"}}
r := s.newRouter()
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/system/uninstall", nil)
r.ServeHTTP(w, req)
if w.Code != http.StatusUnauthorized {
t.Fatalf("code=%d body=%s, want 401", w.Code, w.Body.String())
}
}
func TestHandleApplyUpdateReportsDisabled(t *testing.T) {
gin.SetMode(gin.TestMode)
s := &Server{auth: config.WebConfig{Username: "admin", Password: "secret"}}
r := s.newRouter()
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/system/update/apply", nil)
req.Header.Set("Authorization", "Bearer "+testSessionToken(t, "secret", time.Now().Add(time.Hour)))
r.ServeHTTP(w, req)
if w.Code != http.StatusConflict {
t.Fatalf("code=%d body=%s, want 409 when updater is disabled", w.Code, w.Body.String())
}
}
func testSessionToken(t *testing.T, password string, exp time.Time) string {
t.Helper()
expStr := strconv.FormatInt(exp.Unix(), 10)
h := hmac.New(sha256.New, []byte(password))
h.Write([]byte(expStr))
sig := hex.EncodeToString(h.Sum(nil))
return base64.StdEncoding.EncodeToString([]byte(expStr + "." + sig))
}
+33
View File
@@ -0,0 +1,33 @@
package api
import (
"net/http"
"strings"
"time"
"github.com/iniwex5/vohive/internal/db"
"github.com/gin-gonic/gin"
)
func (s *Server) handleTrafficAnalysis(c *gin.Context) {
rng := c.Query("range")
if rng == "" {
rng = "day"
}
deviceID := strings.TrimSpace(c.Query("device_id"))
now := time.Now()
buckets, chartData, err := db.GetTrafficAnalysisWithChart(rng, deviceID, now)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{
"status": "ok",
"range": rng,
"buckets": buckets,
"chart": chartData,
})
}
+277
View File
@@ -0,0 +1,277 @@
package api
import (
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/iniwex5/vohive/internal/db"
"github.com/iniwex5/vohive/internal/upstreamproxy"
)
// ── 前置代理管理 API(主服务) ──
func normalizeUpstreamProxyPayload(existing *db.UpstreamProxy, req db.UpstreamProxy) db.UpstreamProxy {
out := req
out.ID = strings.TrimSpace(out.ID)
out.Name = strings.TrimSpace(out.Name)
out.Addr = strings.TrimSpace(out.Addr)
out.Username = strings.TrimSpace(out.Username)
out.Password = strings.TrimSpace(out.Password)
if existing != nil {
out.CreatedAt = existing.CreatedAt
if out.Password == "" {
out.Password = existing.Password
}
}
return out
}
func probeUpstreamProxyConfig(c *gin.Context, proxy db.UpstreamProxy) (upstreamproxy.ProbeResult, error) {
return upstreamproxy.ProbeSOCKS5(c.Request.Context(), upstreamproxy.ProbeConfig{
ProxyAddr: proxy.Addr,
Username: proxy.Username,
Password: proxy.Password,
Timeout: 5 * time.Second,
})
}
// handleListUpstreamProxies 获取所有前置代理实例
func (s *Server) handleListUpstreamProxies(c *gin.Context) {
proxies, err := db.ListUpstreamProxies()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": err.Error()})
return
}
// 密码脱敏
for i := range proxies {
proxies[i].Password = maskSecret(proxies[i].Password)
}
c.JSON(http.StatusOK, proxies)
}
// handleCreateUpstreamProxy 创建前置代理实例
func (s *Server) handleCreateUpstreamProxy(c *gin.Context) {
var req db.UpstreamProxy
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": "参数解析失败: " + err.Error()})
return
}
req = normalizeUpstreamProxyPayload(nil, req)
if req.ID == "" {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": "id 不能为空"})
return
}
if req.Addr == "" {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": "addr 不能为空"})
return
}
result, probeErr := probeUpstreamProxyConfig(c, req)
if probeErr != nil {
c.JSON(http.StatusBadGateway, gin.H{
"status": "error",
"message": "前置代理探测失败: " + result.FailureSummary(),
"result": result,
})
return
}
if err := db.UpsertUpstreamProxy(req); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{
"status": "ok",
"message": "前置代理已保存,并已通过探测",
"result": result,
})
}
// handleUpdateUpstreamProxy 更新前置代理实例
func (s *Server) handleUpdateUpstreamProxy(c *gin.Context) {
id := upstreamProxyIDParam(c)
var req db.UpstreamProxy
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": "参数解析失败: " + err.Error()})
return
}
existing, err := db.GetUpstreamProxyByID(id)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": err.Error()})
return
}
if existing == nil {
c.JSON(http.StatusNotFound, gin.H{"status": "error", "message": "前置代理不存在"})
return
}
req.ID = id
req = normalizeUpstreamProxyPayload(existing, req)
if req.Addr == "" {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": "addr 不能为空"})
return
}
result, probeErr := probeUpstreamProxyConfig(c, req)
if probeErr != nil {
c.JSON(http.StatusBadGateway, gin.H{
"status": "error",
"message": "前置代理探测失败: " + result.FailureSummary(),
"result": result,
})
return
}
if err := db.UpsertUpstreamProxy(req); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{
"status": "ok",
"message": "前置代理已更新,并已通过探测",
"result": result,
})
}
// handleDeleteUpstreamProxy 删除前置代理实例
func (s *Server) handleDeleteUpstreamProxy(c *gin.Context) {
id := upstreamProxyIDParam(c)
if err := db.DeleteUpstreamProxy(id); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "ok", "message": "前置代理已删除"})
}
// handleProbeUpstreamProxy 探测前置代理是否支持标准 Socks5 + UDP Associate。
func (s *Server) handleProbeUpstreamProxy(c *gin.Context) {
id := upstreamProxyIDParam(c)
proxy, err := db.GetUpstreamProxyByID(id)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": err.Error()})
return
}
if proxy == nil {
c.JSON(http.StatusNotFound, gin.H{"status": "error", "message": "前置代理不存在"})
return
}
result, probeErr := upstreamproxy.ProbeSOCKS5(c.Request.Context(), upstreamproxy.ProbeConfig{
ProxyAddr: proxy.Addr,
Username: proxy.Username,
Password: proxy.Password,
Timeout: 5 * time.Second,
})
if probeErr != nil {
c.JSON(http.StatusBadGateway, gin.H{
"status": "error",
"message": "前置代理探测失败: " + result.FailureSummary(),
"result": result,
})
return
}
c.JSON(http.StatusOK, gin.H{
"status": "ok",
"message": "前置代理探测成功",
"result": result,
})
}
type upstreamProxyCountryRuleResponse struct {
CountryCode string `json:"country_code"`
CountryName string `json:"country_name"`
MCCs []string `json:"mccs"`
UpstreamProxyID string `json:"upstream_proxy_id"`
Enabled bool `json:"enabled"`
UpdatedAt time.Time `json:"updated_at"`
}
func buildUpstreamProxyCountryRuleResponse(rule db.UpstreamProxyCountryRule) upstreamProxyCountryRuleResponse {
display := upstreamproxy.CountryRuleDisplay(rule.CountryCode)
return upstreamProxyCountryRuleResponse{
CountryCode: display.CountryCode,
CountryName: display.CountryName,
MCCs: display.MCCs,
UpstreamProxyID: strings.TrimSpace(rule.UpstreamProxyID),
Enabled: rule.Enabled,
UpdatedAt: rule.UpdatedAt,
}
}
func (s *Server) handleListUpstreamProxyCountries(c *gin.Context) {
if !upstreamproxy.CountryTableReady() {
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "mcc_mnc_table_unavailable"})
return
}
c.JSON(http.StatusOK, upstreamproxy.ListCountryDisplays())
}
func (s *Server) handleListUpstreamProxyCountryRules(c *gin.Context) {
rules, err := db.ListUpstreamProxyCountryRules()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": err.Error()})
return
}
out := make([]upstreamProxyCountryRuleResponse, 0, len(rules))
for _, rule := range rules {
out = append(out, buildUpstreamProxyCountryRuleResponse(rule))
}
c.JSON(http.StatusOK, out)
}
func (s *Server) handleUpsertUpstreamProxyCountryRule(c *gin.Context) {
if !upstreamproxy.CountryTableReady() {
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "mcc_mnc_table_unavailable"})
return
}
countryCode := upstreamproxy.NormalizeCountryCode(countryCodeParam(c))
if _, ok := upstreamproxy.MCCsForCountryCode(countryCode); !ok {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": "国家代码不在 MCC/MNC 表中"})
return
}
var req struct {
UpstreamProxyID string `json:"upstream_proxy_id"`
Enabled bool `json:"enabled"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": "参数解析失败: " + err.Error()})
return
}
proxy, err := db.GetUpstreamProxyByID(req.UpstreamProxyID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": err.Error()})
return
}
if proxy == nil {
c.JSON(http.StatusNotFound, gin.H{"status": "error", "message": "前置代理不存在"})
return
}
rule := db.UpstreamProxyCountryRule{
CountryCode: countryCode,
UpstreamProxyID: proxy.ID,
Enabled: req.Enabled,
}
if err := db.UpsertUpstreamProxyCountryRule(rule); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": err.Error()})
return
}
rule.UpstreamProxyID = proxy.ID
rule.CountryCode = countryCode
c.JSON(http.StatusOK, buildUpstreamProxyCountryRuleResponse(rule))
}
func (s *Server) handleDeleteUpstreamProxyCountryRule(c *gin.Context) {
countryCode := upstreamproxy.NormalizeCountryCode(countryCodeParam(c))
if err := db.DeleteUpstreamProxyCountryRule(countryCode); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"ok": true})
}
// maskSecret 将密码脱敏为 **** 格式
func maskSecret(s string) string {
if s == "" {
return ""
}
return "****"
}
@@ -0,0 +1,124 @@
package api
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"github.com/gin-gonic/gin"
"github.com/iniwex5/vohive/internal/db"
"github.com/iniwex5/vohive/internal/upstreamproxy"
)
func loadAPICountryTableFixture(t *testing.T) {
t.Helper()
cachePath := filepath.Join(t.TempDir(), "mcc-mnc-table.json")
rows := `[
{"mcc":"310","mnc":"260","iso":"us","country":"United States","country_code":"US","network":"T-Mobile"},
{"mcc":"262","mnc":"01","iso":"de","country":"Germany","country_code":"DE","network":"Telekom"}
]`
if err := os.WriteFile(cachePath, []byte(rows), 0o644); err != nil {
t.Fatalf("WriteFile() error=%v", err)
}
result := upstreamproxy.InitCountryTable(context.Background(), upstreamproxy.CountryTableOptions{CachePath: cachePath})
if result.Err != nil {
t.Fatalf("InitCountryTable() error=%v", result.Err)
}
}
func newUpstreamProxyCountryRulesTestServer(t *testing.T) *Server {
t.Helper()
gin.SetMode(gin.TestMode)
if err := db.Init(filepath.Join(t.TempDir(), "api.db")); err != nil {
t.Fatalf("db.Init() error=%v", err)
}
t.Cleanup(func() { db.DB = nil })
return &Server{}
}
func TestUpstreamProxyCountriesAPIListsLoadedCountries(t *testing.T) {
loadAPICountryTableFixture(t)
server := newUpstreamProxyCountryRulesTestServer(t)
req := httptest.NewRequest(http.MethodGet, "/api/upstream-proxy-countries", nil)
rr := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rr)
c.Request = req
server.handleListUpstreamProxyCountries(c)
if rr.Code != http.StatusOK {
t.Fatalf("GET status=%d body=%s", rr.Code, rr.Body.String())
}
var countries []map[string]any
if err := json.Unmarshal(rr.Body.Bytes(), &countries); err != nil {
t.Fatalf("json.Unmarshal() error=%v", err)
}
if len(countries) != 2 || countries[0]["country_code"] != "DE" || countries[1]["country_code"] != "US" {
t.Fatalf("countries=%+v, want DE then US", countries)
}
}
func TestUpstreamProxyCountryRulesAPIUpsertsAndListsUS(t *testing.T) {
loadAPICountryTableFixture(t)
server := newUpstreamProxyCountryRulesTestServer(t)
if err := db.UpsertUpstreamProxy(db.UpstreamProxy{ID: "proxy-us", Addr: "127.0.0.1:1080", Enabled: true}); err != nil {
t.Fatalf("UpsertUpstreamProxy() error=%v", err)
}
req := httptest.NewRequest(http.MethodPut, "/api/upstream-proxy-country-rules/us", strings.NewReader(`{"upstream_proxy_id":"proxy-us","enabled":true}`))
req.Header.Set("Content-Type", "application/json")
rr := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rr)
c.Request = req
c.Params = gin.Params{{Key: "country_code", Value: "us"}}
server.handleUpsertUpstreamProxyCountryRule(c)
if rr.Code != http.StatusOK {
t.Fatalf("PUT status=%d body=%s", rr.Code, rr.Body.String())
}
req = httptest.NewRequest(http.MethodGet, "/api/upstream-proxy-country-rules", nil)
rr = httptest.NewRecorder()
c, _ = gin.CreateTestContext(rr)
c.Request = req
server.handleListUpstreamProxyCountryRules(c)
if rr.Code != http.StatusOK {
t.Fatalf("GET status=%d body=%s", rr.Code, rr.Body.String())
}
var rules []map[string]any
if err := json.Unmarshal(rr.Body.Bytes(), &rules); err != nil {
t.Fatalf("json.Unmarshal() error=%v body=%s", err, rr.Body.String())
}
if len(rules) != 1 || rules[0]["country_code"] != "US" || rules[0]["country_name"] != "United States" {
t.Fatalf("rules=%+v", rules)
}
}
func TestUpstreamProxyCountryRulesAPIRejectsUnknownCountryAndMissingProxy(t *testing.T) {
loadAPICountryTableFixture(t)
server := newUpstreamProxyCountryRulesTestServer(t)
req := httptest.NewRequest(http.MethodPut, "/api/upstream-proxy-country-rules/ZZ", strings.NewReader(`{"upstream_proxy_id":"proxy-us","enabled":true}`))
req.Header.Set("Content-Type", "application/json")
rr := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rr)
c.Request = req
c.Params = gin.Params{{Key: "country_code", Value: "ZZ"}}
server.handleUpsertUpstreamProxyCountryRule(c)
if rr.Code != http.StatusBadRequest {
t.Fatalf("unknown country status=%d body=%s", rr.Code, rr.Body.String())
}
req = httptest.NewRequest(http.MethodPut, "/api/upstream-proxy-country-rules/US", strings.NewReader(`{"upstream_proxy_id":"missing","enabled":true}`))
req.Header.Set("Content-Type", "application/json")
rr = httptest.NewRecorder()
c, _ = gin.CreateTestContext(rr)
c.Request = req
c.Params = gin.Params{{Key: "country_code", Value: "US"}}
server.handleUpsertUpstreamProxyCountryRule(c)
if rr.Code != http.StatusNotFound {
t.Fatalf("missing proxy status=%d body=%s", rr.Code, rr.Body.String())
}
}
+133
View File
@@ -0,0 +1,133 @@
package api
import (
"errors"
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/iniwex5/vohive/internal/websheet"
)
func (s *Server) registerWebsheetRoutes(api *gin.RouterGroup) {
api.GET("/websheets/:id", s.handleWebsheetBootstrap)
api.GET("/websheets/:id/proxy", s.handleWebsheetProxy)
api.POST("/websheets/:id/proxy", s.handleWebsheetProxy)
api.PUT("/websheets/:id/proxy", s.handleWebsheetProxy)
api.PATCH("/websheets/:id/proxy", s.handleWebsheetProxy)
api.DELETE("/websheets/:id/proxy", s.handleWebsheetProxy)
api.GET("/websheets/:id/proxy/*target", s.handleWebsheetProxy)
api.POST("/websheets/:id/proxy/*target", s.handleWebsheetProxy)
api.PUT("/websheets/:id/proxy/*target", s.handleWebsheetProxy)
api.PATCH("/websheets/:id/proxy/*target", s.handleWebsheetProxy)
api.DELETE("/websheets/:id/proxy/*target", s.handleWebsheetProxy)
api.POST("/websheets/:id/callback", s.handleWebsheetCallback)
api.POST("/websheets/:id/done", s.handleWebsheetDone)
}
func (s *Server) websheetSession(c *gin.Context) (*websheet.Session, error) {
if s.websheets == nil {
return nil, websheet.ErrNotFound
}
return s.websheets.Get(c.Param("id"))
}
func (s *Server) authorizedWebsheetSession(c *gin.Context) (*websheet.Session, error) {
session, err := s.websheetSession(c)
if err != nil {
return nil, err
}
if err := session.Authorize(c.Request); err != nil {
if errors.Is(err, websheet.ErrUnauthorized) && s.isAuthenticatedRequest(c, time.Now()) {
return session, nil
}
return nil, err
}
return session, nil
}
func (s *Server) handleWebsheetBootstrap(c *gin.Context) {
session, err := s.authorizedWebsheetSession(c)
if err != nil {
respondWebsheetError(c, err)
return
}
if err := session.ServeBootstrap(c.Writer, c.Request); err != nil {
respondWebsheetError(c, err)
}
}
func (s *Server) handleWebsheetProxy(c *gin.Context) {
session, err := s.authorizedWebsheetSession(c)
if err != nil {
respondWebsheetError(c, err)
return
}
if err := session.Proxy(c.Writer, c.Request); err != nil {
respondWebsheetError(c, err)
}
}
func (s *Server) handleWebsheetCallback(c *gin.Context) {
session, err := s.authorizedWebsheetSession(c)
if err != nil {
respondWebsheetError(c, err)
return
}
var callback websheet.Callback
if err := c.ShouldBindJSON(&callback); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "code": "websheet_callback_invalid", "message": err.Error()})
return
}
session.Callback(callback)
if isTerminalWebsheetCallback(callback) {
session.Done()
}
c.JSON(http.StatusOK, gin.H{"status": "ok"})
}
func isTerminalWebsheetCallback(callback websheet.Callback) bool {
value := strings.ToLower(strings.TrimSpace(firstNonEmpty(callback.Event, callback.Method, callback.ResultCode)))
if value == "" {
return true
}
return !strings.Contains(value, "phoneservicesaccountstatuschanged")
}
func firstNonEmpty(values ...string) string {
for _, value := range values {
if strings.TrimSpace(value) != "" {
return value
}
}
return ""
}
func (s *Server) handleWebsheetDone(c *gin.Context) {
session, err := s.authorizedWebsheetSession(c)
if err != nil {
respondWebsheetError(c, err)
return
}
session.Done()
if s.websheets != nil {
s.websheets.Delete(c.Param("id"))
}
c.JSON(http.StatusOK, gin.H{"status": "ok"})
}
func respondWebsheetError(c *gin.Context, err error) {
switch {
case errors.Is(err, websheet.ErrNotFound):
c.JSON(http.StatusNotFound, gin.H{"status": "error", "code": "websheet_not_found", "message": err.Error()})
case errors.Is(err, websheet.ErrExpired):
c.JSON(http.StatusGone, gin.H{"status": "error", "code": "websheet_expired", "message": err.Error()})
case errors.Is(err, websheet.ErrUnsafeURL):
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "code": "websheet_unsafe_url", "message": err.Error()})
case errors.Is(err, websheet.ErrUnauthorized):
c.JSON(http.StatusUnauthorized, gin.H{"status": "error", "code": "websheet_unauthorized", "message": err.Error()})
default:
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "code": "websheet_proxy_failed", "message": err.Error()})
}
}
+125
View File
@@ -0,0 +1,125 @@
package api
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/iniwex5/vohive/internal/config"
"github.com/iniwex5/vohive/internal/websheet"
)
func TestRespondWebsheetErrorMapsStatuses(t *testing.T) {
tests := []struct {
err error
want int
}{
{err: websheet.ErrNotFound, want: http.StatusNotFound},
{err: websheet.ErrExpired, want: http.StatusGone},
{err: websheet.ErrUnsafeURL, want: http.StatusBadRequest},
{err: websheet.ErrUnauthorized, want: http.StatusUnauthorized},
{err: errors.New("boom"), want: http.StatusInternalServerError},
}
for _, tt := range tests {
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
respondWebsheetError(c, tt.err)
if rec.Code != tt.want {
t.Fatalf("respondWebsheetError(%v)=%d want %d", tt.err, rec.Code, tt.want)
}
}
}
func TestWebsheetBootstrapUsesSessionTokenOutsideGlobalAuth(t *testing.T) {
gin.SetMode(gin.TestMode)
broker := websheet.New(websheet.Config{AllowPrivateHosts: true})
session, err := broker.Create(context.Background(), websheet.Request{URL: "https://203.0.113.10/start"})
if err != nil {
t.Fatal(err)
}
server := &Server{
auth: config.WebConfig{Password: "secret"},
websheets: broker,
}
router := gin.New()
api := router.Group("/api")
server.registerWebsheetRoutes(api)
api.Use(server.authMiddleware())
api.GET("/protected", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"status": "ok"})
})
valid := httptest.NewRecorder()
validReq := httptest.NewRequest(http.MethodGet, session.Info().EmbedURL, nil)
router.ServeHTTP(valid, validReq)
if valid.Code == http.StatusUnauthorized {
t.Fatalf("bootstrap with websheet token returned auth 401: %s", valid.Body.String())
}
if valid.Code != http.StatusFound {
t.Fatalf("bootstrap with websheet token status=%d want %d body=%s", valid.Code, http.StatusFound, valid.Body.String())
}
missing := httptest.NewRecorder()
missingReq := httptest.NewRequest(http.MethodGet, "/api/websheets/"+session.Info().ID, nil)
router.ServeHTTP(missing, missingReq)
if missing.Code != http.StatusUnauthorized {
t.Fatalf("bootstrap without websheet token status=%d want %d body=%s", missing.Code, http.StatusUnauthorized, missing.Body.String())
}
protected := httptest.NewRecorder()
protectedReq := httptest.NewRequest(http.MethodGet, "/api/protected", nil)
router.ServeHTTP(protected, protectedReq)
if protected.Code != http.StatusUnauthorized {
t.Fatalf("protected route status=%d want %d", protected.Code, http.StatusUnauthorized)
}
}
func TestWebsheetCallbackMarksTerminalSessionDone(t *testing.T) {
gin.SetMode(gin.TestMode)
broker := websheet.New(websheet.Config{AllowPrivateHosts: true})
session, err := broker.Create(context.Background(), websheet.Request{URL: "https://203.0.113.10/start"})
if err != nil {
t.Fatal(err)
}
server := &Server{websheets: broker}
router := gin.New()
api := router.Group("/api")
server.registerWebsheetRoutes(api)
req := httptest.NewRequest(http.MethodPost, "/api/websheets/"+session.Info().ID+"/callback?token="+websheetToken(session), strings.NewReader(`{
"source":"vowifi",
"event":"entitlementChanged",
"method":"e911AddressValidated",
"resultCode":"success"
}`))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("callback status=%d body=%s", rec.Code, rec.Body.String())
}
waitCtx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
if err := session.WaitDone(waitCtx); err != nil {
t.Fatalf("session was not marked done after terminal callback: %v", err)
}
}
func websheetToken(session *websheet.Session) string {
parts := strings.SplitN(session.Info().EmbedURL, "token=", 2)
if len(parts) != 2 {
return ""
}
return parts[1]
}
+283
View File
@@ -0,0 +1,283 @@
package backend
import (
"context"
"fmt"
"time"
"github.com/iniwex5/vohive/internal/modem"
"github.com/iniwex5/vohive/pkg/smscodec"
)
// ATBackend AT 后端适配器 — 纯包装层,委托给现有 modem.Manager
// 不修改 modem.Manager 的任何一行代码
type ATBackend struct {
modem *modem.Manager
}
// NewATBackend 创建 AT 后端适配器
func NewATBackend(m *modem.Manager) *ATBackend {
return &ATBackend{modem: m}
}
// Mode 返回后端模式标识
func (a *ATBackend) Mode() string { return "at" }
// Close AT 后端无需额外清理(modem.Manager 由 Worker 管理生命周期)
func (a *ATBackend) Close() error { return nil }
// Modem 返回底层 modem.Manager(供需要直接访问 AT 通道的调用方使用,如 AT+QCFG)
func (a *ATBackend) Modem() *modem.Manager { return a.modem }
// ============================================================================
// DeviceInfoProvider 实现
// ============================================================================
func (a *ATBackend) GetIMEI(ctx context.Context) (string, error) {
return a.modem.QueryIMEI()
}
func (a *ATBackend) GetIMSI(ctx context.Context) (string, error) {
return a.modem.QueryIMSI()
}
// GetIMSILive AT 模式下 IMSI 本身即实时读取。
func (a *ATBackend) GetIMSILive(ctx context.Context) (string, error) {
return a.modem.QueryIMSI()
}
func (a *ATBackend) GetICCID(ctx context.Context) (string, error) {
return a.modem.QueryICCID()
}
func (a *ATBackend) GetMSISDN(ctx context.Context) (string, error) {
return a.modem.QueryMSISDN()
}
// GetICCIDLive AT 模式下 ICCID 本身即实时读取。
func (a *ATBackend) GetICCIDLive(ctx context.Context) (string, error) {
return a.modem.QueryICCID()
}
func (a *ATBackend) GetRevision(ctx context.Context) (string, error) {
return a.modem.QueryFirmware()
}
func (a *ATBackend) GetSignalInfo(ctx context.Context) (*SignalInfo, error) {
info := &SignalInfo{}
// AT+CSQ → RSSI/dBm
if _, dbm, err := a.modem.QueryCSQ(); err == nil {
info.RSSI = dbm
}
// AT+QENG="servingcell" → RSRP/RSRQ/SINR
if cell, err := a.modem.QueryServingCellLTEInfo(); err == nil {
info.RSRP = cell.RSRP
info.RSRQ = cell.RSRQ
info.SINR = cell.SINR
}
return info, nil
}
func (a *ATBackend) GetServingSystem(ctx context.Context) (*ServingSystem, error) {
ss := &ServingSystem{}
// AT+CREG? → 注册状态、LAC、CellID
if regStatus, regText, lac, cellID, err := a.modem.QueryRegistration(); err == nil {
ss.RegStatus = regStatus
ss.RegStatusText = regText
ss.LAC = lac
ss.CellID = cellID
}
// AT+COPS? → 运营商
if operator, err := a.modem.QueryOperator(); err == nil {
ss.Operator = operator
}
// AT+QNWINFO → 网络模式 / 双工方式 / 频段 / 信道
if mode, duplex, band, channel, err := a.modem.QueryNetworkRadio(); err == nil {
ss.NetworkMode = mode
ss.NetworkDuplex = duplex
ss.RadioBand = band
ss.RadioChannel = channel
}
return ss, nil
}
func (a *ATBackend) IsSimInserted(ctx context.Context) (bool, error) {
return a.modem.QuerySIMInserted()
}
func (a *ATBackend) GetNativeMCCMNC(ctx context.Context) (mcc, mnc string, err error) {
return a.modem.QueryNativeMCCMNC()
}
func (a *ATBackend) GetNativeSPN(ctx context.Context) (string, error) {
return a.modem.QueryNativeSPN()
}
func (a *ATBackend) GetNativeSPNLive(ctx context.Context) (string, error) {
return a.modem.QueryNativeSPN()
}
func (a *ATBackend) GetSIMMetadata(ctx context.Context) (*SIMMetadata, error) {
meta, err := a.modem.QuerySIMMetadata()
return mapModemSIMMetadata(meta), err
}
func (a *ATBackend) GetSIMMetadataLive(ctx context.Context) (*SIMMetadata, error) {
return a.GetSIMMetadata(ctx)
}
func mapModemSIMMetadata(meta *modem.SIMMetadata) *SIMMetadata {
if meta == nil {
return nil
}
out := &SIMMetadata{
NativeMCC: meta.NativeMCC,
NativeMNC: meta.NativeMNC,
GID1: meta.GID1,
GID2: meta.GID2,
}
if len(meta.PNN) > 0 {
out.PNN = make([]PNNRecord, 0, len(meta.PNN))
for _, rec := range meta.PNN {
out.PNN = append(out.PNN, PNNRecord(rec))
}
}
if len(meta.OPL) > 0 {
out.OPL = make([]OPLRecord, 0, len(meta.OPL))
for _, rec := range meta.OPL {
out.OPL = append(out.OPL, OPLRecord(rec))
}
}
if meta.SIMServiceTable != nil {
out.ServiceTable = (*SIMServiceTable)(meta.SIMServiceTable)
}
return out
}
// GetSMSC 读取短信中心号码(AT+CSCA?)。
func (a *ATBackend) GetSMSC(ctx context.Context) (string, error) {
return a.modem.QuerySMSC()
}
// ============================================================================
// SMSProvider 实现
// ============================================================================
func (a *ATBackend) SendSMS(ctx context.Context, to, body string) error {
return a.SendSMSWithOptions(ctx, to, body, smscodec.SubmitOptions{})
}
func (a *ATBackend) SendSMSWithOptions(ctx context.Context, to, body string, opts smscodec.SubmitOptions) error {
return a.modem.SendSMSWithOptions(to, body, opts)
}
func (a *ATBackend) ReadSMS(ctx context.Context, index int) (*SMS, error) {
// 委托给 modem 读取 PDU 并解码
pdu, err := a.modem.SMSReadPDU(fmt.Sprintf("%d", index))
if err != nil {
return nil, err
}
if pdu == "" {
return nil, fmt.Errorf("短信 %d 不存在或为空", index)
}
// 返回原始 PDU 数据; 完整解码由上层处理
return &SMS{
Index: index,
Content: pdu, // PDU 原文
}, nil
}
func (a *ATBackend) DeleteSMS(ctx context.Context, index int) error {
cmd := fmt.Sprintf("AT+CMGD=%d", index)
_, err := a.modem.ExecuteAT(cmd, 5*time.Second)
return err
}
func (a *ATBackend) ListSMS(ctx context.Context) ([]SMSSummary, error) {
pdus, err := a.modem.SMSListAllPDU()
if err != nil {
return nil, err
}
// 返回 PDU 数量的概要;实际索引需解析 +CMGL 响应
result := make([]SMSSummary, 0, len(pdus))
for i := range pdus {
result = append(result, SMSSummary{Index: i})
}
return result, nil
}
func (a *ATBackend) DeleteAllSMS(ctx context.Context) error {
return a.modem.SMSDeleteAll()
}
// ============================================================================
// USSDProvider 实现
// ============================================================================
func (a *ATBackend) ExecuteUSSD(ctx context.Context, command string, timeout time.Duration) (*USSDResult, error) {
result, err := a.modem.ExecuteUSSD(command, timeout)
if err != nil {
return nil, err
}
return modemUSSDResult(result), nil
}
func (a *ATBackend) CancelUSSD(ctx context.Context) error {
a.modem.CancelUSSD()
return nil
}
// ============================================================================
// OperatingModeController 实现
// ============================================================================
func (a *ATBackend) SetOperatingMode(ctx context.Context, mode OperatingMode) error {
cmd := fmt.Sprintf("AT+CFUN=%d", int(mode))
_, err := a.modem.ExecuteAT(cmd, 5*time.Second)
return err
}
func (a *ATBackend) GetOperatingMode(ctx context.Context) (OperatingMode, error) {
resp, err := a.modem.ExecuteATSilent("AT+CFUN?", 2*time.Second)
if err != nil {
return ModeOnline, err
}
// 解析 +CFUN: N
var mode int
if _, err := fmt.Sscanf(resp, "+CFUN: %d", &mode); err != nil {
return ModeOnline, fmt.Errorf("解析 CFUN 响应失败: %s", resp)
}
return OperatingMode(mode), nil
}
func (a *ATBackend) Reboot(ctx context.Context) error {
_, err := a.modem.ExecuteAT("AT+CFUN=1,1", 5*time.Second)
return err
}
// ============================================================================
// SIMAuthProvider 实现
// ============================================================================
func (a *ATBackend) OpenLogicalChannel(ctx context.Context, aid string) (int, error) {
return a.modem.OpenSIMAuthLogicalChannel(aid)
}
func (a *ATBackend) ResolveSIMAuthAID(ctx context.Context, app string, fallbackAID string) (string, string, error) {
return a.modem.ResolveSIMAuthAID(app, fallbackAID)
}
func (a *ATBackend) CloseLogicalChannel(ctx context.Context, channelID int) error {
return a.modem.CloseSIMAuthLogicalChannel(channelID)
}
func (a *ATBackend) TransmitAPDU(ctx context.Context, channelID int, command string) (string, error) {
return a.modem.TransmitAPDU(channelID, command)
}
+139
View File
@@ -0,0 +1,139 @@
package backend
import (
"context"
)
// ============================================================================
// OperatorSelectionProvider 实现
// ============================================================================
func (a *ATBackend) ScanOperators(ctx context.Context) ([]OperatorCandidate, error) {
entries, err := a.modem.ScanOperators()
if err != nil {
return nil, err
}
var candidates []OperatorCandidate
for _, entry := range entries {
var status string
switch entry.Status {
case 1:
status = "available"
case 2:
status = "current"
case 3:
status = "forbidden"
default:
status = "unknown"
}
rat := atActToRAT(entry.Act)
var rats []OperatorAccessTechnology
if rat != OperatorRATUnknown {
rats = []OperatorAccessTechnology{rat}
}
candidate := OperatorCandidate{
PLMN: entry.PLMN,
OperatorName: entry.LongName,
ShortName: entry.ShortName,
Status: status,
RATs: rats,
}
// Normalize PLMN (to get MCC, MNC, etc.)
normalized, err := NormalizePLMNSelection(entry.PLMN)
if err == nil {
candidate.MCC = normalized.MCC
candidate.MNC = normalized.MNC
candidate.MNCLength = normalized.MNCLength
candidate.IncludesPCSDigit = normalized.IncludesPCSDigit
}
candidates = append(candidates, candidate)
}
return candidates, nil
}
func (a *ATBackend) GetOperatorSelection(ctx context.Context) (OperatorSelection, error) {
state, err := a.modem.QueryOperatorSelection()
if err != nil {
return OperatorSelection{}, err
}
sel := OperatorSelection{}
if state.Mode == 0 {
sel.Mode = OperatorSelectionAutomatic
} else if state.Mode == 1 {
sel.Mode = OperatorSelectionManual
sel.PLMN = state.PLMN
sel.RAT = atActToRAT(state.Act)
normalized, err := NormalizePLMNSelection(state.PLMN)
if err == nil {
sel.MCC = normalized.MCC
sel.MNC = normalized.MNC
sel.MNCLength = normalized.MNCLength
sel.IncludesPCSDigit = normalized.IncludesPCSDigit
}
} else {
// Other modes like manual/automatic fallback
sel.Mode = OperatorSelectionManual
sel.PLMN = state.PLMN
}
return sel, nil
}
func (a *ATBackend) SetOperatorSelection(ctx context.Context, req SetOperatorSelectionRequest) (OperatorSelection, error) {
if err := ValidateSetOperatorSelectionRequest(req); err != nil {
return OperatorSelection{}, err
}
if req.Mode == OperatorSelectionAutomatic {
if err := a.modem.SetOperatorAutomatic(); err != nil {
return OperatorSelection{}, err
}
return OperatorSelection{Mode: OperatorSelectionAutomatic}, nil
}
act := ratToATAct(req.RAT)
hasAct := req.RAT != OperatorRATUnknown
if err := a.modem.SetOperatorManual(req.PLMN, act, hasAct); err != nil {
return OperatorSelection{}, err
}
return a.GetOperatorSelection(ctx)
}
func atActToRAT(act int) OperatorAccessTechnology {
switch act {
case 0:
return OperatorRATGSM
case 2:
return OperatorRATWCDMA
case 7:
return OperatorRATLTE
case 10:
return OperatorRATNR5G
default:
return OperatorRATUnknown
}
}
func ratToATAct(rat OperatorAccessTechnology) int {
switch rat {
case OperatorRATGSM:
return 0
case OperatorRATWCDMA:
return 2
case OperatorRATLTE:
return 7
case OperatorRATNR5G:
return 10
default:
return 0
}
}
+17
View File
@@ -0,0 +1,17 @@
// Package backend 定义 VoHive 设备后端的统一抽象层。
// AT 和 QMI 是平等的两种后端实现,通过配置开关 device_backend 选择。
package backend
// DeviceBackend 顶层聚合接口 — 所有后端模式(at/qmi/auto)均实现此接口
type DeviceBackend interface {
DeviceInfoProvider
SMSProvider
OperatingModeController
SIMAuthProvider
// Mode 返回当前后端模式标识: "at" | "qmi"
Mode() string
// Close 释放后端持有的资源(QMI service 连接等)
Close() error
}
+9
View File
@@ -0,0 +1,9 @@
package backend
// 编译期接口合规性检查(确保所有后端实现都满足 DeviceBackend 接口)
var (
_ DeviceBackend = (*ATBackend)(nil)
_ DeviceBackend = (*QMIBackend)(nil)
_ USSDProvider = (*ATBackend)(nil)
_ USSDProvider = (*QMIBackend)(nil)
)
+11
View File
@@ -0,0 +1,11 @@
package backend
import "context"
// DiscoveryProvider 设备发现接口
type DiscoveryProvider interface {
// ProbeIMEI 通过指定端口探测设备 IMEI
// AT 实现:打开 ttyUSB → AT+GSN
// QMI 实现:打开 cdc-wdm → DMS.GetDeviceSerialNumbers
ProbeIMEI(ctx context.Context, port string) (string, error)
}
+76
View File
@@ -0,0 +1,76 @@
package backend
import (
"fmt"
"strings"
"github.com/iniwex5/vohive/internal/modem"
"github.com/iniwex5/vohive/pkg/logger"
)
// 后端模式常量
const (
BackendAT = "at"
BackendQMI = "qmi"
BackendMBIM = "mbim"
)
// NormalizeBackendMode 标准化后端模式字符串
func NormalizeBackendMode(in string) string {
switch strings.ToLower(strings.TrimSpace(in)) {
case "", BackendAT:
return BackendAT // 默认 AT 模式
case BackendQMI:
return BackendQMI
case BackendMBIM:
return BackendMBIM
default:
return BackendAT
}
}
// ValidateBackendMode 验证后端模式是否有效
func ValidateBackendMode(in string) error {
switch NormalizeBackendMode(in) {
case BackendAT, BackendQMI, BackendMBIM:
return nil
default:
return fmt.Errorf("无效的 device_backend 值: %q (可选: at, qmi, mbim)", in)
}
}
// NewBackend 根据配置模式创建对应后端实例的工厂方法
// mode: "at" | "qmi"
// controlPath: QMI 控制设备路径(qmi 模式必须)
// m: modem.Manager(at 模式必须)
// source: QMI Core 资源源(qmi 模式必须)
func NewBackend(mode, controlPath string, m *modem.Manager, source QMISource, mbimSource MBIMSource) (DeviceBackend, error) {
mode = NormalizeBackendMode(mode)
switch mode {
case BackendAT:
if m == nil {
return nil, fmt.Errorf("AT 模式需要 modem.Manager")
}
logger.Info("[backend] 使用 AT 后端模式")
return NewATBackend(m), nil
case BackendQMI:
b, err := NewQMIBackend(controlPath, source)
if err != nil {
return nil, fmt.Errorf("QMI 后端初始化失败: %w", err)
}
logger.Info("[backend] 使用 QMI 后端模式", "control_path", controlPath)
return b, nil
case BackendMBIM:
if mbimSource == nil {
return nil, fmt.Errorf("MBIM 模式需要 MBIMSource")
}
logger.Info("[backend] 使用 MBIM 后端模式", "control_path", controlPath)
return NewMBIMBackend(controlPath, mbimSource), nil
default:
return nil, fmt.Errorf("不支持的后端模式: %s", mode)
}
}
+60
View File
@@ -0,0 +1,60 @@
package backend
import "context"
// DeviceInfoProvider 设备信息查询接口(状态查询主线)
type DeviceInfoProvider interface {
// GetIMEI 获取设备 IMEI
// AT 实现:AT+CGSN
// QMI 实现:DMS.GetDeviceSerialNumbers
GetIMEI(ctx context.Context) (string, error)
// GetIMSI 获取 SIM 卡 IMSI
// AT 实现:AT+CIMI
// QMI 实现:UIM.GetIMSI
GetIMSI(ctx context.Context) (string, error)
// GetICCID 获取 SIM 卡 ICCID
// AT 实现:AT+QCCID
// QMI 实现:UIM.GetICCID
GetICCID(ctx context.Context) (string, error)
// GetMSISDN 获取本机号码。
// AT 实现:AT+CNUM
// QMI 实现:DMS.GetMSISDN
GetMSISDN(ctx context.Context) (string, error)
// GetRevision 获取固件版本
// AT 实现:AT+CGMR
// QMI 实现:DMS.GetDeviceRevision
GetRevision(ctx context.Context) (string, error)
// GetSignalInfo 获取信号质量信息
// AT 实现:AT+CSQ + AT+QENG="servingcell"
// QMI 实现:NAS.GetSignalStrength + NAS.GetSignalInfo
GetSignalInfo(ctx context.Context) (*SignalInfo, error)
// GetServingSystem 获取网络注册状态和服务系统信息
// AT 实现:AT+CREG? + AT+COPS?
// QMI 实现:NAS.GetServingSystem
GetServingSystem(ctx context.Context) (*ServingSystem, error)
// IsSimInserted 判断 SIM 卡是否已插入
// AT 实现:AT+QSIMSTAT? / AT+CPIN?
// QMI 实现:DMS.GetSIMStatus
IsSimInserted(ctx context.Context) (bool, error)
// GetNativeMCCMNC 获取 SIM 归属 MCC 和 MNC(区别于当前驻留网络)。
// 实现必须基于 IMSI + EF_AD
GetNativeMCCMNC(ctx context.Context) (mcc string, mnc string, err error)
// GetNativeSPN 读取 SIM EF_SPN 服务提供商名称(区别于当前驻留网络 operator)。
// AT 实现:AT+CRSM 读取 EF_SPN
// QMI 实现:UIM.ReadTransparent读取 EF_SPN
GetNativeSPN(ctx context.Context) (string, error)
// GetSIMMetadata 读取 SIM/eSIM profile 的原生元数据。
// AT 实现:AT+CRSM 读取 EF_AD/GID/PNN/OPL/SST/UST
// QMI 实现:UIM.ReadTransparent/ReadRecord 读取对应 EF
GetSIMMetadata(ctx context.Context) (*SIMMetadata, error)
}
+292
View File
@@ -0,0 +1,292 @@
package backend
import (
"context"
"fmt"
"strconv"
"strings"
"github.com/iniwex5/quectel-qmi-go/pkg/manager"
"github.com/iniwex5/vohive/internal/modem"
"github.com/iniwex5/vohive/pkg/mbim"
)
// MBIMBackend implements DeviceBackend over an MBIM modem.
type MBIMBackend struct {
source MBIMSource
controlPath string
}
var _ DeviceBackend = (*MBIMBackend)(nil)
func NewMBIMBackend(controlPath string, source MBIMSource) *MBIMBackend {
return &MBIMBackend{source: source, controlPath: controlPath}
}
func (b *MBIMBackend) Mode() string { return BackendMBIM }
func (b *MBIMBackend) Close() error { return nil }
func (b *MBIMBackend) GetIMEI(ctx context.Context) (string, error) {
caps, err := b.source.DeviceCaps(ctx)
if err != nil {
return "", err
}
return caps.DeviceID, nil
}
func (b *MBIMBackend) GetIMSI(ctx context.Context) (string, error) {
sub, err := b.source.SubscriberReady(ctx)
if err != nil {
return "", err
}
return sub.IMSI, nil
}
func (b *MBIMBackend) GetICCID(ctx context.Context) (string, error) {
sub, err := b.source.SubscriberReady(ctx)
if err != nil {
return "", err
}
return sub.ICCID, nil
}
func (b *MBIMBackend) GetMSISDN(ctx context.Context) (string, error) {
sub, err := b.source.SubscriberReady(ctx)
if err != nil {
return "", err
}
if sub.MSISDN != "" {
return sub.MSISDN, nil
}
return b.readMSISDNFromEF(ctx), nil
}
func (b *MBIMBackend) GetRevision(ctx context.Context) (string, error) {
caps, err := b.source.DeviceCaps(ctx)
if err != nil {
return "", err
}
return caps.FirmwareInfo, nil
}
func (b *MBIMBackend) IsSimInserted(ctx context.Context) (bool, error) {
sub, err := b.source.SubscriberReady(ctx)
if err != nil {
return false, err
}
return sub.ReadyState != 2, nil
}
func (b *MBIMBackend) GetSignalInfo(ctx context.Context) (*SignalInfo, error) {
s, err := b.source.SignalState(ctx)
if err != nil {
return nil, err
}
info := &SignalInfo{}
if !s.Unknown {
info.RSSI = s.DBM
}
// MBIMEx 2.0 信号:RSRP/SINR(SNR)。RSRQ 在 MBIM(Ex) 协议中无对应字段,保持空。
if s.HasRSRP {
info.RSRP = s.RSRP
}
if s.HasSNR {
info.SINR = s.SNR
}
return info, nil
}
func (b *MBIMBackend) GetServingSystem(ctx context.Context) (*ServingSystem, error) {
rs, err := b.source.RegisterState(ctx)
if err != nil {
return nil, err
}
ss := &ServingSystem{
Operator: mbimOperatorDisplay(rs.ProviderName, rs.MCC, rs.MNC),
MCC: atou16(rs.MCC),
MNC: atou16(rs.MNC),
}
ss.RegStatus, ss.RegStatusText = mapMBIMRegisterState(rs.RegisterState)
if ps, err := b.source.PacketService(ctx); err == nil {
ss.PSAttached = ps.State == 2
ss.NetworkMode = mbimDataClassToNetworkMode(ps.HighestClass)
}
return ss, nil
}
func mbimOperatorDisplay(name, mcc, mnc string) string {
if trimmed := strings.TrimSpace(name); trimmed != "" {
return trimmed
}
if len(mcc) != 3 || (len(mnc) != 2 && len(mnc) != 3) {
return ""
}
plmn := mcc + mnc
if display, ok := modem.LookupServingOperatorNameFromPLMN(plmn); ok {
return display
}
return plmn
}
// mbimDataClassToNetworkMode 把 MBIM_DATA_CLASS 位掩码映射为面板用的接入技术字符串,
// 取已就绪的最高制式。频段/信道(RadioBand/RadioChannel)在标准 MBIM/MBIMEx 里
// 没有承载 CID,故此处不填,保持空。
func mbimDataClassToNetworkMode(dataClass uint32) string {
const (
dcGPRS = 0x00000001
dcEDGE = 0x00000002
dcUMTS = 0x00000004
dcHSDPA = 0x00000008
dcHSUPA = 0x00000010
dcLTE = 0x00000020
dc5GNSA = 0x00000040
dc5GSA = 0x00000080
)
switch {
case dataClass&(dc5GNSA|dc5GSA) != 0:
return "NR5G"
case dataClass&dcLTE != 0:
return "LTE"
case dataClass&(dcUMTS|dcHSDPA|dcHSUPA) != 0:
return "UMTS"
case dataClass&(dcGPRS|dcEDGE) != 0:
return "GSM"
default:
return ""
}
}
func (b *MBIMBackend) GetNativeMCCMNC(ctx context.Context) (string, string, error) {
// 优先用 HomeProvider 的 PLMN:模组按正确的 MNC 长度给出(5 或 6 位)。
if hp, err := b.source.HomeProvider(ctx); err == nil {
if mcc, mnc, ok := splitMBIMPLMN(hp.PLMN); ok {
return mcc, mnc, nil
}
}
// 兜底:与 QMI 同一套规则——IMSI + EF_AD 的 MNC 长度;EF_AD 读不到(如此固件
// USIM ADF 逻辑通道开不了)时,HomeMCCMNCFromIMSIAndEFAD 会用 IMSI+MCC 表
// 推断 MNC 长度(如 310→3 位),避免把 3 位 MNC 截成 2 位。
sub, err := b.source.SubscriberReady(ctx)
if err != nil {
return "", "", err
}
efAD, _ := b.source.ReadSIMEF(ctx, efAD, 0)
mcc, mnc, _, _, err := modem.HomeMCCMNCFromIMSIAndEFAD(sub.IMSI, efAD)
if err != nil {
return "", "", err
}
return mcc, mnc, nil
}
// splitMBIMPLMN 把 MBIM ProviderId(PLMN 字符串)拆成 MCC + 变长 MNC。
func splitMBIMPLMN(plmn string) (mcc, mnc string, ok bool) {
if len(plmn) < 5 || len(plmn) > 6 {
return "", "", false
}
return plmn[:3], plmn[3:], true
}
func (b *MBIMBackend) GetNativeSPN(ctx context.Context) (string, error) {
return b.readNativeSPN(ctx)
}
func (b *MBIMBackend) GetSIMMetadata(ctx context.Context) (*SIMMetadata, error) {
return b.readSIMMetadata(ctx)
}
func (b *MBIMBackend) GetOperatingMode(ctx context.Context) (OperatingMode, error) {
rs, err := b.source.RadioState(ctx)
if err != nil {
return ModeLowPower, err
}
if rs.Software == mbim.RadioOn {
return ModeOnline, nil
}
return ModeLowPower, nil
}
func (b *MBIMBackend) SetOperatingMode(ctx context.Context, mode OperatingMode) error {
sw := mbim.RadioOff
if mode == ModeOnline {
sw = mbim.RadioOn
}
_, err := b.source.SetRadioState(ctx, sw)
return err
}
func (b *MBIMBackend) AttachPacketService(ctx context.Context) error {
_, err := b.source.SetPacketService(ctx, mbim.PacketServiceAttach)
return err
}
func (b *MBIMBackend) DetachPacketService(ctx context.Context) error {
_, err := b.source.SetPacketService(ctx, mbim.PacketServiceDetach)
return err
}
func (b *MBIMBackend) RequestCoreRecovery(reason string) bool {
type coreRecoveryRequester interface {
RequestCoreRecovery(reason string) bool
}
if b == nil || b.source == nil {
return false
}
requester, ok := b.source.(coreRecoveryRequester)
return ok && requester.RequestCoreRecovery(reason)
}
func (b *MBIMBackend) WaitCoreReady(ctx context.Context) error {
type coreReadyWaiter interface {
WaitCoreReady(ctx context.Context) error
}
if b == nil || b.source == nil {
return fmt.Errorf("mbim_source_not_available")
}
waiter, ok := b.source.(coreReadyWaiter)
if !ok {
return fmt.Errorf("mbim_core_ready_wait_not_supported")
}
return waiter.WaitCoreReady(ctx)
}
func (b *MBIMBackend) Reboot(ctx context.Context) error {
caps := b.source.Capability()
if caps == nil || !caps.DeviceResetUsable() {
return fmt.Errorf("mbim device reset not supported")
}
return b.source.DeviceReset(ctx)
}
func (b *MBIMBackend) GetUIMReadiness(ctx context.Context) (manager.UIMReadiness, error) {
return b.source.GetUIMReadiness(ctx)
}
func (b *MBIMBackend) UIMPowerOffSIM(ctx context.Context, slot uint8) error {
return b.source.UIMPowerOffSIM(ctx, slot)
}
func (b *MBIMBackend) UIMPowerOnSIM(ctx context.Context, slot uint8) error {
return b.source.UIMPowerOnSIM(ctx, slot)
}
func atou16(s string) uint16 {
n, _ := strconv.Atoi(s)
return uint16(n)
}
func mapMBIMRegisterState(s uint32) (int, string) {
switch s {
case 3:
return 1, "registered-home"
case 4, 5:
return 5, "registered-roaming"
case 2:
return 2, "searching"
case 6:
return 3, "denied"
case 1:
return 0, "not-registered"
default:
return 4, "unknown"
}
}
+31
View File
@@ -0,0 +1,31 @@
package backend
import (
"context"
"errors"
"time"
"github.com/iniwex5/vohive/pkg/mbim"
)
// CalculateAKA computes AKA via the MBIM Auth service.
// Returns res, ik, ck, auts, err
func (b *MBIMBackend) CalculateAKA(ctx context.Context, rand16, autn16 []byte) (res, ik, ck, auts []byte, err error) {
ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
defer cancel()
res, ik, ck, auts, err = b.source.CalculateAKA(ctx, rand16, autn16)
if err != nil && isAuthAKAUnsupported(err) {
if caps := b.source.Capability(); caps != nil {
caps.MarkAuthAKADead()
}
}
return res, ik, ck, auts, err
}
func isAuthAKAUnsupported(err error) bool {
var se *mbim.StatusError
// Only MBIM_STATUS_NO_DEVICE_SUPPORT (9) means the feature is absent.
// MBIM_STATUS_AUTH_SYNC_FAILURE (35) is a legitimate authentication result
// (SQN mismatch) and must NOT disable the Auth service.
return errors.As(err, &se) && se.Status == 9
}
@@ -0,0 +1,7 @@
package backend
import "github.com/iniwex5/vohive/pkg/mbim"
func (b *MBIMBackend) Capability() *mbim.Capabilities {
return b.source.Capability()
}
+24
View File
@@ -0,0 +1,24 @@
package backend
import "context"
// Live identity readers — satisfy device.liveSIMIdentityReader / liveSIMSPNReader /
// liveSIMMetadataReader so the worker's refreshIdentityLive populates ICCID/IMSI/
// SPN/metadata for MBIM devices. For MBIM every query is already a live
// SubscriberReady, so these delegate to the non-Live variants.
func (b *MBIMBackend) GetIMSILive(ctx context.Context) (string, error) {
return b.GetIMSI(ctx)
}
func (b *MBIMBackend) GetICCIDLive(ctx context.Context) (string, error) {
return b.GetICCID(ctx)
}
func (b *MBIMBackend) GetNativeSPNLive(ctx context.Context) (string, error) {
return b.GetNativeSPN(ctx)
}
func (b *MBIMBackend) GetSIMMetadataLive(ctx context.Context) (*SIMMetadata, error) {
return b.GetSIMMetadata(ctx)
}
+47
View File
@@ -0,0 +1,47 @@
package backend
import (
"context"
"encoding/hex"
"fmt"
)
func (b *MBIMBackend) OpenLogicalChannel(ctx context.Context, aid string) (int, error) {
aidBytes, err := hex.DecodeString(aid)
if err != nil {
return 0, fmt.Errorf("mbim: invalid AID hex %q: %w", aid, err)
}
ch, err := b.source.OpenChannel(ctx, aidBytes)
if err != nil {
return 0, err
}
return int(ch), nil
}
func (b *MBIMBackend) CloseLogicalChannel(ctx context.Context, channelID int) error {
return b.source.CloseChannel(ctx, uint32(channelID))
}
func (b *MBIMBackend) TransmitAPDU(ctx context.Context, channelID int, command string) (string, error) {
cmd, err := hex.DecodeString(command)
if err != nil {
return "", fmt.Errorf("mbim: invalid APDU hex: %w", err)
}
resp, err := b.source.TransmitAPDU(ctx, uint32(channelID), cmd)
if err != nil {
return "", err
}
return hex.EncodeToString(resp), nil
}
// ResolveSIMAuthAID 把短前缀(USIM/ISIM ADF AID 前 7 字节)解析成完整 AID:这张卡
// 在 MBIM 下不接受用短 AID 开逻辑通道(UICC_OPEN_CHANNEL status=0x87430002
// SelectFailed),必须先拿到完整 AID。
// 现在使用底层的 QMI over MBIM 隧道技术,直接获取真实 USIM/ISIM 列表。
func (b *MBIMBackend) ResolveSIMAuthAID(ctx context.Context, app string, fallbackAID string) (string, string, error) {
aid, source, err := b.source.ResolveLogicalChannelAID(app, fallbackAID)
if err != nil {
return fallbackAID, "fallback_on_error", fmt.Errorf("%w: mbim qmi tunnel resolve %s AID: %v", ErrSIMAuthAIDNotReady, app, err)
}
return aid, source, nil
}
+127
View File
@@ -0,0 +1,127 @@
package backend
import (
"context"
"encoding/hex"
"strings"
"github.com/iniwex5/vohive/internal/modem"
)
// SIM EF file identifiers (3GPP TS 31.102 / 51.011).
const (
efSPN uint16 = 0x6F46
efAD uint16 = 0x6FAD
efGID1 uint16 = 0x6F3E
efGID2 uint16 = 0x6F3F
efPNN uint16 = 0x6FC5
efOPL uint16 = 0x6FC6
efUST uint16 = 0x6F38 // USIM Service Table
efMSISDN uint16 = 0x6F40
)
// readNativeSPN reads and decodes EF_SPN via the MBIM UICC channel.
func (b *MBIMBackend) readNativeSPN(ctx context.Context) (string, error) {
data, err := b.source.ReadSIMEF(ctx, efSPN, 0)
if err != nil {
return "", err
}
if len(data) == 0 {
return "", nil
}
spn, derr := modem.DecodeEFSPN(data)
if derr != nil {
return "", nil // unreadable SPN is not a hard error
}
return spn, nil
}
func (b *MBIMBackend) readSIMMetadata(ctx context.Context) (*SIMMetadata, error) {
mcc, mnc, err := b.GetNativeMCCMNC(ctx)
if err != nil {
return nil, err
}
meta := &SIMMetadata{NativeMCC: mcc, NativeMNC: mnc}
if ad, _ := b.source.ReadSIMEF(ctx, efAD, 0); len(ad) >= 4 {
mncLen := int(ad[3])
if mncLen == 2 || mncLen == 3 {
if len(mnc) > mncLen {
meta.NativeMNC = mnc[:mncLen]
}
}
}
if gid1, _ := b.source.ReadSIMEF(ctx, efGID1, 0); len(gid1) > 0 {
meta.GID1 = hex.EncodeToString(trimFF(gid1))
}
if gid2, _ := b.source.ReadSIMEF(ctx, efGID2, 0); len(gid2) > 0 {
meta.GID2 = hex.EncodeToString(trimFF(gid2))
}
var pnn []PNNRecord
for i := 1; ; i++ {
rec, err := b.source.ReadSIMRecordEF(ctx, efPNN, uint32(i))
if err != nil || len(rec) == 0 {
break
}
if p, ok := modem.DecodePNNRecord(i, rec); ok {
pnn = append(pnn, PNNRecord(p))
}
}
if len(pnn) > 0 {
meta.PNN = pnn
}
var opl []OPLRecord
for i := 1; ; i++ {
rec, err := b.source.ReadSIMRecordEF(ctx, efOPL, uint32(i))
if err != nil || len(rec) == 0 {
break
}
if o, ok := modem.DecodeOPLRecord(i, rec); ok {
opl = append(opl, OPLRecord(o))
}
}
if len(opl) > 0 {
meta.OPL = opl
}
if ust, _ := b.source.ReadSIMEF(ctx, efUST, 0); len(ust) > 0 {
if st := modem.DecodeSIMServiceTable("UST", ust); st != nil {
meta.ServiceTable = &SIMServiceTable{
Kind: st.Kind,
RawHex: st.RawHex,
EnabledServices: append([]int(nil), st.EnabledServices...),
}
}
}
return meta, nil
}
// trimFF drops trailing 0xFF padding bytes from a raw EF read.
func trimFF(b []byte) []byte {
n := len(b)
for n > 0 && b[n-1] == 0xFF {
n--
}
return b[:n]
}
// readMSISDNFromEF reads EF_MSISDN and decodes the dialing number.
func (b *MBIMBackend) readMSISDNFromEF(ctx context.Context) string {
rec, err := b.source.ReadSIMEF(ctx, efMSISDN, 0)
if err != nil || len(rec) < 14 {
return ""
}
// The 14-byte trailer is at the end of the record.
tail := rec[len(rec)-14:]
length := int(tail[0])
if length < 1 || length > 11 {
return ""
}
// tail[1] = TON/NPI; dialing BCD is tail[2 : 2+(length-1)].
bcd := tail[2 : 2+(length-1)]
number := modem.DecodeSwappedBCD(bcd)
return strings.TrimRight(number, "f")
}
@@ -0,0 +1,238 @@
package backend
import (
"context"
"encoding/hex"
"errors"
"strings"
"testing"
"github.com/iniwex5/vohive/pkg/mbim"
)
func mbimResetCapableForTest() *mbim.Capabilities {
return &mbim.Capabilities{
Services: mbim.DeviceServices{Elements: []mbim.DeviceServiceElement{
{
Service: mbim.UUIDMSBasicConnectExtensions,
CIDs: []uint32{mbim.CIDMSBasicConnectExtDeviceReset},
},
}},
}
}
func TestMBIMRebootIssuesDeviceReset(t *testing.T) {
src := &fakeMBIMSource{capability: mbimResetCapableForTest()}
b := NewMBIMBackend("", src)
if err := b.Reboot(context.Background()); err != nil {
t.Fatalf("Reboot() error = %v", err)
}
if !src.resetCalled {
t.Fatal("Reboot() did not call DeviceReset")
}
}
func TestMBIMRebootPropagatesError(t *testing.T) {
wantErr := errors.New("boom")
src := &fakeMBIMSource{capability: mbimResetCapableForTest(), resetErr: wantErr}
b := NewMBIMBackend("", src)
if err := b.Reboot(context.Background()); !errors.Is(err, wantErr) {
t.Fatalf("Reboot() error = %v, want %v", err, wantErr)
}
}
func TestMBIMRebootRequiresDeviceResetCapability(t *testing.T) {
src := &fakeMBIMSource{}
b := NewMBIMBackend("", src)
err := b.Reboot(context.Background())
if err == nil || !strings.Contains(err.Error(), "not supported") {
t.Fatalf("Reboot() error = %v, want not supported", err)
}
if src.resetCalled {
t.Fatal("Reboot() called DeviceReset without advertised reset capability")
}
}
func TestMBIMGetNativeSPNDecodesEFSPN(t *testing.T) {
src := &fakeMBIMSource{}
src.efFn = func(fileID uint16) ([]byte, error) {
if fileID == 0x6F46 {
// byte0 display flag, then ASCII "CMCC".
return []byte{0x01, 'C', 'M', 'C', 'C', 0xFF, 0xFF}, nil
}
return nil, nil
}
b := NewMBIMBackend("", src)
got, err := b.GetNativeSPN(context.Background())
if err != nil {
t.Fatalf("GetNativeSPN() error = %v", err)
}
if got != "CMCC" {
t.Fatalf("GetNativeSPN() = %q, want CMCC", got)
}
}
func TestMBIMGetNativeSPNEmptyWhenEFEmpty(t *testing.T) {
src := &fakeMBIMSource{}
src.efFn = func(uint16) ([]byte, error) { return nil, nil }
b := NewMBIMBackend("", src)
got, err := b.GetNativeSPN(context.Background())
if err != nil {
t.Fatalf("GetNativeSPN() error = %v", err)
}
if got != "" {
t.Fatalf("GetNativeSPN() = %q, want empty", got)
}
}
func mbimSubscriberWithIMSI(imsi string) mbim.SubscriberReady {
return mbim.SubscriberReady{IMSI: imsi, ReadyState: 1}
}
func TestMBIMGetSIMMetadataFillsGIDAndMNCLength(t *testing.T) {
src := &fakeMBIMSource{
sub: mbimSubscriberWithIMSI("460001234567890"),
}
src.efFn = func(fileID uint16) ([]byte, error) {
switch fileID {
case efAD:
// EF_AD: byte0..2 admin, byte3 = MNC length (2).
return []byte{0x00, 0x00, 0x00, 0x02}, nil
case efGID1:
return []byte{0xA1, 0xB2}, nil
case efGID2:
return []byte{0xC3}, nil
default:
return nil, nil
}
}
b := NewMBIMBackend("", src)
meta, err := b.GetSIMMetadata(context.Background())
if err != nil {
t.Fatalf("GetSIMMetadata() error = %v", err)
}
if meta == nil {
t.Fatal("GetSIMMetadata() = nil")
}
if meta.NativeMCC != "460" || meta.NativeMNC != "00" {
t.Fatalf("MCC/MNC = %s/%s", meta.NativeMCC, meta.NativeMNC)
}
if hex.EncodeToString([]byte{0xA1, 0xB2}) != meta.GID1 {
t.Fatalf("GID1 = %q", meta.GID1)
}
if meta.GID2 != "c3" {
t.Fatalf("GID2 = %q, want c3", meta.GID2)
}
}
func TestMBIMGetSIMMetadataFillsPNNOPLAndUST(t *testing.T) {
src := &fakeMBIMSource{
sub: mbimSubscriberWithIMSI("460001234567890"),
}
src.efFn = func(fileID uint16) ([]byte, error) {
switch fileID {
case efUST:
// Enable service 1 and 2 (byte 1 = 0x03)
return []byte{0x03, 0x00, 0x00}, nil
default:
return nil, nil
}
}
src.efRecFn = func(fileID uint16, rec uint32) ([]byte, error) {
if fileID == efPNN {
if rec == 1 {
data := append([]byte{0x43, 0x04}, []byte("TEST")...)
return append(data, 0xFF, 0xFF), nil
}
}
if fileID == efOPL {
if rec == 1 {
// Mock OPL Record 1: PLMN 46000, PNN ID 1.
// Format: PLMN (3 bytes), LAC Start (2), LAC End (2), PNN ID (1)
// 46000 = 64 00 00
return []byte{0x64, 0xF0, 0x00, 0x00, 0x00, 0xFF, 0xFE, 0x01, 0xFF}, nil
}
}
return nil, errors.New("not found")
}
b := NewMBIMBackend("", src)
meta, err := b.GetSIMMetadata(context.Background())
if err != nil {
t.Fatalf("GetSIMMetadata() error = %v", err)
}
if meta.ServiceTable == nil || meta.ServiceTable.Kind != "UST" {
t.Fatalf("ServiceTable = %+v", meta.ServiceTable)
}
if len(meta.PNN) != 1 {
t.Fatalf("PNN = %+v, want len=1", meta.PNN)
}
if meta.PNN[0].FullName != "TEST" {
t.Fatalf("PNN[0].FullName = %q, want TEST", meta.PNN[0].FullName)
}
if len(meta.OPL) != 1 {
t.Fatalf("OPL = %+v, want len=1", meta.OPL)
}
if meta.OPL[0].PLMN != "46000" || meta.OPL[0].LACStart != 0 || meta.OPL[0].LACEnd != 0xFFFE || meta.OPL[0].PNNRecord != 1 {
t.Fatalf("OPL[0] = %+v, want PLMN=46000 LAC=0-65534 PNNRecord=1", meta.OPL[0])
}
}
func TestMBIMGetMSISDNFallsBackToEF(t *testing.T) {
src := &fakeMBIMSource{} // SubscriberReady.MSISDN empty by default
src.efFn = func(fileID uint16) ([]byte, error) {
if fileID == efMSISDN {
// EF_MSISDN record tail: ... [len][TON/NPI][dialing BCD...]
// length=0x07, TON/NPI=0x91 (international), number 8613800100500.
return buildEFMSISDNRecord("8613800100500"), nil
}
return nil, nil
}
b := NewMBIMBackend("", src)
got, err := b.GetMSISDN(context.Background())
if err != nil {
t.Fatalf("GetMSISDN() error = %v", err)
}
if got != "8613800100500" {
t.Fatalf("GetMSISDN() = %q, want 8613800100500", got)
}
}
// buildEFMSISDNRecord builds a minimal EF_MSISDN record with the dialing number
// stored as swapped BCD in the standard 14-byte trailer.
func buildEFMSISDNRecord(number string) []byte {
// Layout (TS 51.011 EF_MSISDN): [Alpha...][Length(1)][TON/NPI(1)][Dialing(10)][CCP(1)][Ext(1)]
// We emit only the 14-byte trailer (alpha identifier length 0).
rec := make([]byte, 14)
bcd := encodeSwappedBCDForTest(number)
rec[0] = byte(len(bcd) + 1) // length of BCD + TON/NPI byte
rec[1] = 0x91 // international
copy(rec[2:12], bcd)
for i := 2 + len(bcd); i < 12; i++ {
rec[i] = 0xFF
}
rec[12], rec[13] = 0xFF, 0xFF
return rec
}
func encodeSwappedBCDForTest(num string) []byte {
digits := []byte(num)
out := make([]byte, (len(digits)+1)/2)
for i := 0; i < len(digits); i++ {
nib := digits[i] - '0'
if i%2 == 0 {
out[i/2] = nib
} else {
out[i/2] |= nib << 4
}
}
if len(digits)%2 == 1 {
out[len(out)-1] |= 0xF0
}
return out
}
+68
View File
@@ -0,0 +1,68 @@
package backend
import (
"context"
"encoding/hex"
"fmt"
"github.com/iniwex5/vohive/pkg/logger"
"github.com/iniwex5/vohive/pkg/smscodec"
)
func (b *MBIMBackend) SendSMS(ctx context.Context, to, body string) error {
return b.SendSMSWithOptions(ctx, to, body, smscodec.SubmitOptions{})
}
func (b *MBIMBackend) SendSMSWithOptions(ctx context.Context, to, body string, opts smscodec.SubmitOptions) error {
tpdus, _, err := smscodec.BuildSubmitTPDUsWithOptions(to, body, opts)
if err != nil {
return fmt.Errorf("PDU 编码失败: %w", err)
}
if len(tpdus) == 0 {
return fmt.Errorf("PDU 编码结果为空")
}
for i, tpdu := range tpdus {
pdu := append([]byte{0x00}, tpdu...)
if _, err := b.source.SendSMS(ctx, pdu); err != nil {
return fmt.Errorf("发送第 %d/%d 段失败: %w", i+1, len(tpdus), err)
}
}
logger.Info("MBIM 短信发送成功", "to", to, "parts", len(tpdus))
return nil
}
func (b *MBIMBackend) ReadSMS(ctx context.Context, index int) (*SMS, error) {
rec, err := b.source.ReadSMS(ctx, uint32(index))
if err != nil {
return nil, err
}
return &SMS{Index: index, Content: hex.EncodeToString(rec.PDU)}, nil
}
func (b *MBIMBackend) DeleteSMS(ctx context.Context, index int) error {
return b.source.DeleteSMS(ctx, uint32(index))
}
func (b *MBIMBackend) ListSMS(ctx context.Context) ([]SMSSummary, error) {
recs, err := b.source.ListSMS(ctx)
if err != nil {
return nil, err
}
out := make([]SMSSummary, 0, len(recs))
for _, r := range recs {
out = append(out, SMSSummary{Index: int(r.Index), Tag: int(r.Status)})
}
return out, nil
}
func (b *MBIMBackend) DeleteAllSMS(ctx context.Context) error {
return b.source.DeleteAllSMS(ctx)
}
func (b *MBIMBackend) GetSMSC(ctx context.Context) (string, error) {
return b.source.GetSMSC(ctx)
}
func (b *MBIMBackend) SetSMSC(ctx context.Context, smsc string) error {
return b.source.SetSMSC(ctx, smsc)
}
+723
View File
@@ -0,0 +1,723 @@
package backend
import (
"context"
"fmt"
"testing"
"time"
qmimanager "github.com/iniwex5/quectel-qmi-go/pkg/manager"
"github.com/iniwex5/vohive/pkg/mbim"
"github.com/iniwex5/vohive/pkg/smscodec"
"github.com/warthog618/sms/encoding/tpdu"
)
type fakeMBIMSource struct {
caps mbim.Caps
capability *mbim.Capabilities
sub mbim.SubscriberReady
reg mbim.RegisterState
setReg mbim.RegisterState
sig mbim.SignalState
pkt mbim.PacketService
packetAction mbim.PacketServiceAction
packetSet mbim.PacketService
packetErr error
radio mbim.RadioState
setSw mbim.RadioSwitch
providers []mbim.Provider
homeProvider mbim.Provider
homeProviderErr error
setRegisterAction uint32
setRegisterPLMN string
uimReadiness qmimanager.UIMReadiness
uimReadinessErr error
powerOffCalls int
powerOnCalls int
sendFn func(pdu []byte) (uint32, error)
listFn func() ([]mbim.SMSRecord, error)
openFn func([]byte) (uint32, error)
apduFn func(uint32, []byte) ([]byte, error)
smscFn func(context.Context) (string, error)
setSMSCArg string
efFn func(uint16) ([]byte, error)
efRecFn func(uint16, uint32) ([]byte, error)
aidFn func([]byte) ([]byte, error)
resetCalled bool
resetErr error
ussdResult mbim.USSDResult
ussdErr error
ussdCommand string
ussdTimeout time.Duration
ussdContinueInput string
ussdContinueTimeout time.Duration
cancelUSSD bool
cancelErr error
akaRES []byte
akaCK []byte
akaIK []byte
akaErr error
}
func (f *fakeMBIMSource) ReadSIMRecordEF(_ context.Context, fileID uint16, record uint32) ([]byte, error) {
if f.efRecFn != nil {
return f.efRecFn(fileID, record)
}
return nil, nil
}
func (f *fakeMBIMSource) CalculateAKA(_ context.Context, rand, autn []byte) (res, ik, ck, auts []byte, err error) {
return f.akaRES, f.akaIK, f.akaCK, nil, f.akaErr
}
func (f *fakeMBIMSource) ControlDevice() string { return "/dev/cdc-wdm0" }
func (f *fakeMBIMSource) DeviceCaps(context.Context) (mbim.Caps, error) { return f.caps, nil }
func (f *fakeMBIMSource) SubscriberReady(context.Context) (mbim.SubscriberReady, error) {
return f.sub, nil
}
func (f *fakeMBIMSource) RegisterState(context.Context) (mbim.RegisterState, error) {
return f.reg, nil
}
func (f *fakeMBIMSource) GetRegisterState(context.Context) (mbim.RegisterState, error) {
return f.reg, nil
}
func (f *fakeMBIMSource) VisibleProviders(context.Context) ([]mbim.Provider, error) {
return f.providers, nil
}
func (f *fakeMBIMSource) HomeProvider(context.Context) (mbim.Provider, error) {
return f.homeProvider, f.homeProviderErr
}
func (f *fakeMBIMSource) GetUIMReadiness(context.Context) (qmimanager.UIMReadiness, error) {
return f.uimReadiness, f.uimReadinessErr
}
func (f *fakeMBIMSource) UIMPowerOffSIM(context.Context, uint8) error {
f.powerOffCalls++
return nil
}
func (f *fakeMBIMSource) UIMPowerOnSIM(context.Context, uint8) error {
f.powerOnCalls++
return nil
}
// 原运营商应取 HomeProvider 的 PLMN(MNC 长度正确,3 位 → 6 位),而不是 IMSI 截 2 位。
func TestMBIMBackendGetNativeMCCMNCUsesHomeProviderLength(t *testing.T) {
src := &fakeMBIMSource{
sub: mbim.SubscriberReady{IMSI: "310840131414639"}, // IMSI[3:5]="84"(错)
homeProvider: mbim.Provider{PLMN: "310840"}, // 正确 3 位 MNC
}
b := NewMBIMBackend("", src)
mcc, mnc, err := b.GetNativeMCCMNC(context.Background())
if err != nil {
t.Fatalf("GetNativeMCCMNC: %v", err)
}
if mcc != "310" || mnc != "840" {
t.Fatalf("GetNativeMCCMNC = (%q,%q), want (310,840)", mcc, mnc)
}
}
// 真机场景:HomeProvider 拿不到、USIM ADF 也开不了(EF_AD 读失败),
// 仍应靠 IMSI+MCC 表得到正确的 3 位 MNC(310→280),而不是截成 2 位。
func TestMBIMBackendGetNativeMCCMNCUsesMCCTableWhenNoHomeProviderNoEFAD(t *testing.T) {
src := &fakeMBIMSource{
sub: mbim.SubscriberReady{IMSI: "310280233688494"},
homeProviderErr: fmt.Errorf("home provider unavailable"),
efFn: func(uint16) ([]byte, error) { return nil, fmt.Errorf("UICC_OPEN_CHANNEL status=0x87430002") },
}
b := NewMBIMBackend("", src)
mcc, mnc, err := b.GetNativeMCCMNC(context.Background())
if err != nil {
t.Fatalf("GetNativeMCCMNC: %v", err)
}
if mcc != "310" || mnc != "280" {
t.Fatalf("GetNativeMCCMNC = (%q,%q), want (310,280)", mcc, mnc)
}
}
// HomeProvider 不可用时,退回 IMSI(取 2 位 MNC),保证不 panic、有兜底。
func TestMBIMBackendGetNativeMCCMNCFallsBackToIMSI(t *testing.T) {
src := &fakeMBIMSource{
sub: mbim.SubscriberReady{IMSI: "460001234567890"},
homeProviderErr: fmt.Errorf("home provider unavailable"),
}
b := NewMBIMBackend("", src)
mcc, mnc, err := b.GetNativeMCCMNC(context.Background())
if err != nil {
t.Fatalf("GetNativeMCCMNC: %v", err)
}
if mcc != "460" || mnc != "00" {
t.Fatalf("GetNativeMCCMNC fallback = (%q,%q), want (460,00)", mcc, mnc)
}
}
func (f *fakeMBIMSource) SetRegister(_ context.Context, action uint32, plmn string) (mbim.RegisterState, error) {
f.setRegisterAction = action
f.setRegisterPLMN = plmn
if f.setReg.ProviderID != "" || f.setReg.RegisterState != 0 {
return f.setReg, nil
}
return f.reg, nil
}
func (f *fakeMBIMSource) SignalState(context.Context) (mbim.SignalState, error) {
return f.sig, nil
}
func (f *fakeMBIMSource) PacketService(context.Context) (mbim.PacketService, error) {
return f.pkt, nil
}
func (f *fakeMBIMSource) SetPacketService(_ context.Context, action mbim.PacketServiceAction) (mbim.PacketService, error) {
f.packetAction = action
return f.packetSet, f.packetErr
}
func (f *fakeMBIMSource) RadioState(context.Context) (mbim.RadioState, error) { return f.radio, nil }
func (f *fakeMBIMSource) SetRadioState(_ context.Context, sw mbim.RadioSwitch) (mbim.RadioState, error) {
f.setSw = sw
return mbim.RadioState{Software: sw}, nil
}
func (f *fakeMBIMSource) Snapshot() mbim.Snapshot { return mbim.Snapshot{} }
func (f *fakeMBIMSource) Capability() *mbim.Capabilities { return f.capability }
func (f *fakeMBIMSource) SendSMS(_ context.Context, pdu []byte) (uint32, error) {
if f.sendFn != nil {
return f.sendFn(pdu)
}
return 0, nil
}
func (f *fakeMBIMSource) ReadSMS(context.Context, uint32) (mbim.SMSRecord, error) {
return mbim.SMSRecord{}, nil
}
func (f *fakeMBIMSource) ListSMS(context.Context) ([]mbim.SMSRecord, error) {
if f.listFn != nil {
return f.listFn()
}
return nil, nil
}
func (f *fakeMBIMSource) DeleteSMS(context.Context, uint32) error { return nil }
func (f *fakeMBIMSource) DeleteAllSMS(context.Context) error { return nil }
func (f *fakeMBIMSource) GetSMSC(ctx context.Context) (string, error) {
if f.smscFn != nil {
return f.smscFn(ctx)
}
return "", nil
}
func (f *fakeMBIMSource) SetSMSC(_ context.Context, smsc string) error {
f.setSMSCArg = smsc
return nil
}
func (f *fakeMBIMSource) ExecuteUSSD(_ context.Context, command string, timeout time.Duration) (mbim.USSDResult, error) {
f.ussdCommand = command
f.ussdTimeout = timeout
return f.ussdResult, f.ussdErr
}
func (f *fakeMBIMSource) ContinueUSSD(_ context.Context, input string, timeout time.Duration) (mbim.USSDResult, error) {
f.ussdContinueInput = input
f.ussdContinueTimeout = timeout
return f.ussdResult, f.ussdErr
}
func (f *fakeMBIMSource) CancelUSSD(context.Context) error {
f.cancelUSSD = true
return f.cancelErr
}
func (f *fakeMBIMSource) OpenChannel(_ context.Context, aid []byte) (uint32, error) {
if f.openFn != nil {
return f.openFn(aid)
}
return 0, nil
}
func (f *fakeMBIMSource) CloseChannel(context.Context, uint32) error { return nil }
func (f *fakeMBIMSource) TransmitAPDU(_ context.Context, ch uint32, cmd []byte) ([]byte, error) {
if f.apduFn != nil {
return f.apduFn(ch, cmd)
}
return nil, nil
}
func (f *fakeMBIMSource) ReadSIMEF(_ context.Context, fileID uint16, _ int) ([]byte, error) {
if f.efFn != nil {
return f.efFn(fileID)
}
return nil, nil
}
func (f *fakeMBIMSource) ResolveAppAID(_ context.Context, prefix []byte) ([]byte, error) {
if f.aidFn != nil {
return f.aidFn(prefix)
}
return nil, fmt.Errorf("ResolveAppAID 未配置")
}
func (f *fakeMBIMSource) ResolveLogicalChannelAID(app string, fallback string) (string, string, error) {
if f.aidFn != nil {
prefix := []byte{0xA0, 0x00, 0x00, 0x00, 0x87, 0x10, 0x02}
if app == "isim" {
prefix = []byte{0xA0, 0x00, 0x00, 0x00, 0x87, 0x10, 0x04}
}
res, err := f.aidFn(prefix)
if err != nil {
return fallback, "fallback_on_error", err
}
return fmt.Sprintf("%X", res), "mock", nil
}
return fallback, "mock", nil
}
func (f *fakeMBIMSource) DeviceReset(context.Context) error {
f.resetCalled = true
return f.resetErr
}
// liveIdentityReader mirrors device.liveSIMIdentityReader/liveSIMSPNReader/
// liveSIMMetadataReader so we assert MBIMBackend satisfies the contract the
// worker's refreshIdentityLive relies on (regression guard for empty ICCID/IMSI).
type liveIdentityReader interface {
GetICCIDLive(ctx context.Context) (string, error)
GetIMSILive(ctx context.Context) (string, error)
GetNativeSPNLive(ctx context.Context) (string, error)
GetSIMMetadataLive(ctx context.Context) (*SIMMetadata, error)
}
func TestMBIMBackendLiveIdentity(t *testing.T) {
src := &fakeMBIMSource{
sub: mbim.SubscriberReady{ReadyState: 1, IMSI: "310840131414639", ICCID: "89103000000589140892"},
}
var b any = NewMBIMBackend("", src)
reader, ok := b.(liveIdentityReader)
if !ok {
t.Fatal("MBIMBackend 未实现 live 身份接口(会导致面板 ICCID/IMSI 为空)")
}
if iccid, _ := reader.GetICCIDLive(context.Background()); iccid != "89103000000589140892" {
t.Fatalf("GetICCIDLive = %q", iccid)
}
if imsi, _ := reader.GetIMSILive(context.Background()); imsi != "310840131414639" {
t.Fatalf("GetIMSILive = %q", imsi)
}
}
func TestMBIMBackendIdentity(t *testing.T) {
src := &fakeMBIMSource{
caps: mbim.Caps{DeviceID: "356938035643809"},
sub: mbim.SubscriberReady{ReadyState: 1, IMSI: "460001234567890", ICCID: "8986001234", MSISDN: "13800138000"},
}
b := NewMBIMBackend("", src)
if b.Mode() != BackendMBIM {
t.Fatalf("Mode = %q", b.Mode())
}
if imei, _ := b.GetIMEI(context.Background()); imei != "356938035643809" {
t.Fatalf("IMEI = %q", imei)
}
if imsi, _ := b.GetIMSI(context.Background()); imsi != "460001234567890" {
t.Fatalf("IMSI = %q", imsi)
}
ok, _ := b.IsSimInserted(context.Background())
if !ok {
t.Fatal("ReadyState=1 should be inserted")
}
}
func TestMBIMDataClassToNetworkMode(t *testing.T) {
cases := []struct {
dataClass uint32
want string
}{
{0x00, ""},
{0x01, "GSM"}, // GPRS
{0x02, "GSM"}, // EDGE
{0x04, "UMTS"}, // UMTS
{0x08, "UMTS"}, // HSDPA
{0x10, "UMTS"}, // HSUPA
{0x20, "LTE"}, // LTE
{0x40, "NR5G"}, // 5G NSA
{0x80, "NR5G"}, // 5G SA
{0x20 | 0x08, "LTE"}, // 取最高 RAT
{0x40 | 0x20, "NR5G"},
}
for _, c := range cases {
if got := mbimDataClassToNetworkMode(c.dataClass); got != c.want {
t.Errorf("mbimDataClassToNetworkMode(0x%x) = %q, want %q", c.dataClass, got, c.want)
}
}
}
func TestMBIMBackendServingSystemAndSignal(t *testing.T) {
src := &fakeMBIMSource{
reg: mbim.RegisterState{RegisterState: 3, ProviderName: "CMCC", MCC: "460", MNC: "00"},
sig: mbim.SignalState{RSSI: 20, DBM: -73},
pkt: mbim.PacketService{State: 2, HighestClass: 0x20},
}
b := NewMBIMBackend("", src)
ss, err := b.GetServingSystem(context.Background())
if err != nil {
t.Fatalf("GetServingSystem: %v", err)
}
if ss.RegStatus != 1 || ss.Operator != "CMCC" || ss.MCC != 460 || ss.MNC != 0 || !ss.PSAttached {
t.Fatalf("serving = %+v", ss)
}
if ss.NetworkMode != "LTE" {
t.Fatalf("NetworkMode = %q, want LTE", ss.NetworkMode)
}
si, err := b.GetSignalInfo(context.Background())
if err != nil {
t.Fatalf("GetSignalInfo: %v", err)
}
if si.RSSI != -73 {
t.Fatalf("RSSI = %d, want -73", si.RSSI)
}
if ss.LAC != "" || ss.CellID != "" || ss.RadioBand != "" || ss.RadioChannel != 0 {
t.Fatalf("MBIM serving system should not fabricate LAC/CellID/Band/Channel: %+v", ss)
}
if si.RSRQ != 0 {
t.Fatalf("MBIM signal info should not fabricate RSRQ: %+v", si)
}
}
func TestMBIMBackendAttachPacketServiceDelegates(t *testing.T) {
src := &fakeMBIMSource{packetSet: mbim.PacketService{State: 2}}
b := NewMBIMBackend("", src)
if err := b.AttachPacketService(context.Background()); err != nil {
t.Fatalf("AttachPacketService: %v", err)
}
if src.packetAction != mbim.PacketServiceAttach {
t.Fatalf("packet action=%d want attach", src.packetAction)
}
}
func TestMBIMBackendServingSystemFallsBackToPLMNOperatorName(t *testing.T) {
src := &fakeMBIMSource{
reg: mbim.RegisterState{RegisterState: 3, ProviderName: "", MCC: "460", MNC: "00"},
pkt: mbim.PacketService{State: 2, HighestClass: 0x20},
}
b := NewMBIMBackend("", src)
ss, err := b.GetServingSystem(context.Background())
if err != nil {
t.Fatalf("GetServingSystem: %v", err)
}
if ss.Operator == "" {
t.Fatalf("Operator empty, want PLMN fallback name or PLMN display: %+v", ss)
}
if ss.RadioBand != "" || ss.RadioChannel != 0 || ss.NetworkDuplex != "" {
t.Fatalf("MBIM must not fabricate band/channel/duplex: %+v", ss)
}
}
func TestMBIMBackendSignalInfoFillsRsrpSinrFromV2(t *testing.T) {
src := &fakeMBIMSource{
sig: mbim.SignalState{RSSI: 99, Unknown: true, RSRP: -85, HasRSRP: true, SNR: 10, HasSNR: true},
}
b := NewMBIMBackend("", src)
si, err := b.GetSignalInfo(context.Background())
if err != nil {
t.Fatalf("GetSignalInfo: %v", err)
}
if si.RSRP != -85 {
t.Fatalf("RSRP = %d, want -85", si.RSRP)
}
if si.SINR != 10 {
t.Fatalf("SINR = %d, want 10", si.SINR)
}
}
func TestMBIMBackendOperatingMode(t *testing.T) {
src := &fakeMBIMSource{radio: mbim.RadioState{Software: mbim.RadioOn}}
b := NewMBIMBackend("", src)
mode, _ := b.GetOperatingMode(context.Background())
if mode != ModeOnline {
t.Fatalf("mode = %d, want online", mode)
}
if err := b.SetOperatingMode(context.Background(), ModeLowPower); err != nil {
t.Fatalf("Set: %v", err)
}
if src.setSw != mbim.RadioOff {
t.Fatal("ModeLowPower should turn radio off")
}
}
func TestMBIMBackendSendSMS(t *testing.T) {
var sent [][]byte
src := &fakeMBIMSource{}
src.sendFn = func(pdu []byte) (uint32, error) { sent = append(sent, pdu); return 1, nil }
b := NewMBIMBackend("", src)
if err := b.SendSMS(context.Background(), "+8613800138000", "hello"); err != nil {
t.Fatalf("SendSMS: %v", err)
}
if len(sent) == 0 {
t.Fatal("no PDU sent")
}
if sent[0][0] != 0x00 {
t.Fatalf("PDU first byte should be SMSC length 0x00, got 0x%02x", sent[0][0])
}
}
func TestMBIMBackendSendSMSWithOptionsForcesUCS2(t *testing.T) {
var sent [][]byte
src := &fakeMBIMSource{}
src.sendFn = func(pdu []byte) (uint32, error) { sent = append(sent, pdu); return 1, nil }
b := NewMBIMBackend("", src)
if err := b.SendSMSWithOptions(context.Background(), "10086", "hello", smscodec.SubmitOptions{Encoding: smscodec.SMSEncodingUCS2}); err != nil {
t.Fatalf("SendSMSWithOptions: %v", err)
}
if len(sent) != 1 {
t.Fatalf("send count = %d, want 1", len(sent))
}
if len(sent[0]) < 2 || sent[0][0] != 0x00 {
t.Fatalf("unexpected PDU with SMSC header: %x", sent[0])
}
pdu := &tpdu.TPDU{Direction: tpdu.MO}
if err := pdu.UnmarshalBinary(sent[0][1:]); err != nil {
t.Fatalf("UnmarshalBinary() error = %v", err)
}
if pdu.DCS != tpdu.DcsUCS2Data {
t.Fatalf("DCS=0x%02x want 0x%02x", byte(pdu.DCS), byte(tpdu.DcsUCS2Data))
}
}
func TestMBIMBackendCapabilityDelegates(t *testing.T) {
want := &mbim.Capabilities{UICCChannelOK: true}
src := &fakeMBIMSource{capability: want}
b := NewMBIMBackend("", src)
if b.Capability() != want {
t.Fatal("Capability 应透传 source 的能力对象")
}
}
func TestMBIMBackendGetUIMReadinessDelegates(t *testing.T) {
src := &fakeMBIMSource{
uimReadiness: qmimanager.UIMReadiness{
TransportReady: true,
ControlReady: true,
UIMReady: true,
ActiveSlot: 1,
SlotKnown: true,
ICCID: "8986001234",
Reason: qmimanager.UIMReadinessReady,
},
}
b := NewMBIMBackend("", src)
got, err := b.GetUIMReadiness(context.Background())
if err != nil {
t.Fatalf("GetUIMReadiness: %v", err)
}
if got.ActiveSlot != 1 || got.ICCID != "8986001234" {
t.Fatalf("got=%+v", got)
}
}
func TestMBIMBackendUIMPowerDelegates(t *testing.T) {
src := &fakeMBIMSource{}
b := NewMBIMBackend("", src)
if err := b.UIMPowerOffSIM(context.Background(), 1); err != nil {
t.Fatalf("UIMPowerOffSIM: %v", err)
}
if err := b.UIMPowerOnSIM(context.Background(), 1); err != nil {
t.Fatalf("UIMPowerOnSIM: %v", err)
}
if src.powerOffCalls != 1 || src.powerOnCalls != 1 {
t.Fatalf("off=%d on=%d", src.powerOffCalls, src.powerOnCalls)
}
}
func TestMBIMBackendCalculateAKAMarksDeadOnNoDeviceSupport(t *testing.T) {
caps := &mbim.Capabilities{Services: mbim.DeviceServices{
Elements: []mbim.DeviceServiceElement{{Service: mbim.UUIDAuth, CIDs: []uint32{1}}},
}}
src := &fakeMBIMSource{
capability: caps,
akaErr: &mbim.StatusError{Op: "AUTH_AKA", Status: 9}, // NO_DEVICE_SUPPORT
}
b := NewMBIMBackend("", src)
if !caps.AuthAKAUsable() {
t.Fatal("前置:应可用")
}
_, _, _, _, err := b.CalculateAKA(context.Background(), make([]byte, 16), make([]byte, 16))
if err == nil {
t.Fatal("应返回错误")
}
if caps.AuthAKAUsable() {
t.Fatal("status=9(NO_DEVICE_SUPPORT) 后应熔断")
}
}
func TestMBIMBackendCalculateAKADoesNotMarkDeadOnSyncFailure(t *testing.T) {
caps := &mbim.Capabilities{Services: mbim.DeviceServices{
Elements: []mbim.DeviceServiceElement{{Service: mbim.UUIDAuth, CIDs: []uint32{1}}},
}}
src := &fakeMBIMSource{
capability: caps,
akaErr: &mbim.StatusError{Op: "AUTH_AKA", Status: 35}, // AUTH_SYNC_FAILURE
}
b := NewMBIMBackend("", src)
_, _, _, _, err := b.CalculateAKA(context.Background(), make([]byte, 16), make([]byte, 16))
if err == nil {
t.Fatal("应返回错误")
}
if !caps.AuthAKAUsable() {
t.Fatal("status=35(AUTH_SYNC_FAILURE) 是合法认证响应,不应熔断 Auth 服务")
}
}
func TestMBIMBackendListSMS(t *testing.T) {
src := &fakeMBIMSource{listFn: func() ([]mbim.SMSRecord, error) {
return []mbim.SMSRecord{{Index: 3, Status: 1, PDU: []byte{0xAA}}}, nil
}}
b := NewMBIMBackend("", src)
list, err := b.ListSMS(context.Background())
if err != nil {
t.Fatalf("ListSMS: %v", err)
}
if len(list) != 1 || list[0].Index != 3 || list[0].Tag != 1 {
t.Fatalf("list = %+v", list)
}
}
func TestMBIMBackendGetSMSCDelegates(t *testing.T) {
src := &fakeMBIMSource{
smscFn: func(context.Context) (string, error) {
return "+8613800138000", nil
},
}
var _ SMSCProvider = (*MBIMBackend)(nil)
b := NewMBIMBackend("", src)
smsc, err := b.GetSMSC(context.Background())
if err != nil {
t.Fatalf("GetSMSC: %v", err)
}
if smsc != "+8613800138000" {
t.Fatalf("SMSC = %q, want %q", smsc, "+8613800138000")
}
}
func TestMBIMBackendSetSMSCDelegates(t *testing.T) {
src := &fakeMBIMSource{}
b := NewMBIMBackend("", src)
if err := b.SetSMSC(context.Background(), "+8613800138000"); err != nil {
t.Fatalf("SetSMSC: %v", err)
}
if src.setSMSCArg != "+8613800138000" {
t.Fatalf("setSMSCArg = %q, want %q", src.setSMSCArg, "+8613800138000")
}
}
func TestMBIMBackendSIMAuthDelegates(t *testing.T) {
src := &fakeMBIMSource{
openFn: func(aid []byte) (uint32, error) { return 1, nil },
apduFn: func(ch uint32, cmd []byte) ([]byte, error) { return []byte{0x90, 0x00}, nil },
}
b := NewMBIMBackend("", src)
ch, err := b.OpenLogicalChannel(context.Background(), "A0000000871002")
if err != nil {
t.Fatalf("OpenLogicalChannel: %v", err)
}
if ch != 1 {
t.Fatalf("channel = %d", ch)
}
resp, err := b.TransmitAPDU(context.Background(), ch, "00A40004023F00")
if err != nil {
t.Fatalf("TransmitAPDU: %v", err)
}
if resp != "9000" {
t.Fatalf("resp = %q, want 9000", resp)
}
}
// ResolveSIMAuthAID 让 backend.SIMAuthAIDResolver 在 MBIM 下也可用:VoWiFi 的
// ReadISIMIdentity(外部 vowifi-go 模块)与 ATAKAProvider 风格的逻辑通道读取都依赖
// 这个接口拿完整 AID,而不是直接用拒绝短 AID 的卡上 fallback 短 AID 去开通道。
func TestMBIMBackendResolveSIMAuthAIDUSIM(t *testing.T) {
full := []byte{0xA0, 0x00, 0x00, 0x00, 0x87, 0x10, 0x02, 0xFF, 0xFF, 0xFF, 0xFF, 0x89, 0x07, 0x09, 0x00, 0x00}
src := &fakeMBIMSource{aidFn: func(prefix []byte) ([]byte, error) {
want := []byte{0xA0, 0x00, 0x00, 0x00, 0x87, 0x10, 0x02}
if !bytesEqual(prefix, want) {
t.Fatalf("prefix = % X, want % X", prefix, want)
}
return full, nil
}}
b := NewMBIMBackend("", src)
aid, source, err := b.ResolveSIMAuthAID(context.Background(), "usim", "A0000000871002")
if err != nil {
t.Fatalf("ResolveSIMAuthAID: %v", err)
}
if aid != "A0000000871002FFFFFFFF8907090000" {
t.Fatalf("aid = %q", aid)
}
if source == "" {
t.Fatalf("source should not be empty")
}
}
func TestMBIMBackendResolveSIMAuthAIDISIM(t *testing.T) {
full := []byte{0xA0, 0x00, 0x00, 0x00, 0x87, 0x10, 0x04, 0xFF, 0xFF, 0xFF, 0xFF, 0x89, 0x07, 0x09, 0x00, 0x00}
src := &fakeMBIMSource{aidFn: func(prefix []byte) ([]byte, error) {
want := []byte{0xA0, 0x00, 0x00, 0x00, 0x87, 0x10, 0x04}
if !bytesEqual(prefix, want) {
t.Fatalf("prefix = % X, want % X", prefix, want)
}
return full, nil
}}
b := NewMBIMBackend("", src)
aid, _, err := b.ResolveSIMAuthAID(context.Background(), "isim", "A0000000871004")
if err != nil {
t.Fatalf("ResolveSIMAuthAID: %v", err)
}
if aid != "A0000000871004FFFFFFFF8907090000" {
t.Fatalf("aid = %q", aid)
}
}
func TestMBIMBackendResolveSIMAuthAIDFailsWhenUnresolved(t *testing.T) {
src := &fakeMBIMSource{aidFn: func([]byte) ([]byte, error) {
return nil, fmt.Errorf("mbim: UICC_APPLICATION_LIST status=0x9")
}}
b := NewMBIMBackend("", src)
if _, _, err := b.ResolveSIMAuthAID(context.Background(), "usim", "A0000000871002"); err == nil {
t.Fatalf("expected error when AID cannot be resolved")
}
}
func bytesEqual(a, b []byte) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}
func TestNormalizeAndValidateMBIM(t *testing.T) {
if NormalizeBackendMode("MBIM") != BackendMBIM {
t.Fatalf("normalize mbim failed: %q", NormalizeBackendMode("MBIM"))
}
if err := ValidateBackendMode("mbim"); err != nil {
t.Fatalf("validate mbim should pass: %v", err)
}
}
func TestNewBackendMBIM(t *testing.T) {
src := &fakeMBIMSource{caps: mbim.Caps{DeviceID: "123"}}
be, err := NewBackend(BackendMBIM, "/dev/cdc-wdm0", nil, nil, src)
if err != nil {
t.Fatalf("NewBackend(mbim): %v", err)
}
if be.Mode() != BackendMBIM {
t.Fatalf("mode = %q", be.Mode())
}
}
func TestMBIMBackendCalculateAKA(t *testing.T) {
b := &MBIMBackend{source: &fakeMBIMSource{
akaRES: []byte("res"),
akaCK: []byte("ck"),
akaIK: []byte("ik"),
}}
res, ik, ck, auts, err := b.CalculateAKA(context.Background(), make([]byte, 16), make([]byte, 16))
if err != nil {
t.Fatalf("CalculateAKA: %v", err)
}
if string(res) != "res" || string(ck) != "ck" || string(ik) != "ik" || len(auts) > 0 {
t.Fatalf("Unexpected AKA result: res=%v, ck=%v, ik=%v, auts=%v", res, ck, ik, auts)
}
}
+37
View File
@@ -0,0 +1,37 @@
package backend
import (
"context"
"time"
"github.com/iniwex5/vohive/pkg/mbim"
)
func (b *MBIMBackend) ExecuteUSSD(ctx context.Context, command string, timeout time.Duration) (*USSDResult, error) {
result, err := b.source.ExecuteUSSD(ctx, command, timeout)
if err != nil {
return nil, err
}
return mbimUSSDResult(result), nil
}
func (b *MBIMBackend) ContinueUSSD(ctx context.Context, input string, timeout time.Duration) (*USSDResult, error) {
result, err := b.source.ContinueUSSD(ctx, input, timeout)
if err != nil {
return nil, err
}
return mbimUSSDResult(result), nil
}
func mbimUSSDResult(result mbim.USSDResult) *USSDResult {
return &USSDResult{
Status: int(result.Response),
Text: result.Text,
RawText: result.RawHex,
DCS: int(result.DCS),
}
}
func (b *MBIMBackend) CancelUSSD(ctx context.Context) error {
return b.source.CancelUSSD(ctx)
}
@@ -0,0 +1,77 @@
package backend
import (
"context"
"testing"
"time"
"github.com/iniwex5/vohive/pkg/mbim"
)
func TestMBIMBackendUSSDProviderConformance(t *testing.T) {
var _ USSDProvider = (*MBIMBackend)(nil)
}
func TestMBIMBackendExecuteUSSDMapsResult(t *testing.T) {
src := &fakeMBIMSource{
ussdResult: mbim.USSDResult{
Response: mbim.USSDRespNoActionRequired,
DCS: 0x0F,
Text: "balance 10",
RawHex: "c2f29b0c4a87e520f4",
},
}
b := NewMBIMBackend("", src)
got, err := b.ExecuteUSSD(context.Background(), "*100#", 2*time.Second)
if err != nil {
t.Fatalf("ExecuteUSSD: %v", err)
}
if got.Status != int(mbim.USSDRespNoActionRequired) || got.DCS != 0x0F {
t.Fatalf("ExecuteUSSD() = %+v", got)
}
if got.Text != "balance 10" || got.RawText != "c2f29b0c4a87e520f4" {
t.Fatalf("ExecuteUSSD() = %+v, want mapped text/raw hex", got)
}
if src.ussdCommand != "*100#" || src.ussdTimeout != 2*time.Second {
t.Fatalf("source saw command=%q timeout=%v", src.ussdCommand, src.ussdTimeout)
}
}
func TestMBIMBackendContinueUSSDMapsResult(t *testing.T) {
src := &fakeMBIMSource{
ussdResult: mbim.USSDResult{
Response: mbim.USSDRespNoActionRequired,
DCS: 0x0F,
Text: "continued",
RawHex: "e8329bfd06",
},
}
b := NewMBIMBackend("", src)
got, err := b.ContinueUSSD(context.Background(), "1", 3*time.Second)
if err != nil {
t.Fatalf("ContinueUSSD: %v", err)
}
if got.Status != int(mbim.USSDRespNoActionRequired) || got.DCS != 0x0F {
t.Fatalf("ContinueUSSD() = %+v", got)
}
if got.Text != "continued" || got.RawText != "e8329bfd06" {
t.Fatalf("ContinueUSSD() = %+v, want mapped text/raw hex", got)
}
if src.ussdContinueInput != "1" || src.ussdContinueTimeout != 3*time.Second {
t.Fatalf("source saw input=%q timeout=%v", src.ussdContinueInput, src.ussdContinueTimeout)
}
}
func TestMBIMBackendCancelUSSDDelegates(t *testing.T) {
src := &fakeMBIMSource{}
b := NewMBIMBackend("", src)
if err := b.CancelUSSD(context.Background()); err != nil {
t.Fatalf("CancelUSSD: %v", err)
}
if !src.cancelUSSD {
t.Fatal("CancelUSSD did not delegate to MBIM source")
}
}
@@ -0,0 +1,87 @@
package backend
import (
"context"
"github.com/iniwex5/vohive/pkg/mbim"
)
func (b *MBIMBackend) ScanOperators(ctx context.Context) ([]OperatorCandidate, error) {
// MBIM VISIBLE_PROVIDERS is a single command/response scan. Unlike QMI NAS
// incremental scans, it does not expose partial candidates, so the device SSE
// path should report "running" until this method returns.
providers, err := b.source.VisibleProviders(ctx)
if err != nil {
return nil, err
}
out := make([]OperatorCandidate, 0, len(providers))
for _, provider := range providers {
candidate := OperatorCandidate{
PLMN: provider.PLMN,
OperatorName: provider.Name,
Status: mbimProviderStatus(provider.State),
RATs: mbimProviderRATs(provider.CellularClass),
}
if normalized, err := NormalizePLMNSelection(candidate.PLMN); err == nil {
candidate.MCC = normalized.MCC
candidate.MNC = normalized.MNC
candidate.MNCLength = normalized.MNCLength
candidate.IncludesPCSDigit = normalized.IncludesPCSDigit
}
out = append(out, candidate)
}
return out, nil
}
func (b *MBIMBackend) GetOperatorSelection(ctx context.Context) (OperatorSelection, error) {
rs, err := b.source.GetRegisterState(ctx)
if err != nil {
return OperatorSelection{}, err
}
if rs.RegisterMode != mbim.RegisterModeManual {
return OperatorSelection{Mode: OperatorSelectionAutomatic}, nil
}
sel, err := NormalizeManualOperatorSelection(rs.ProviderID, OperatorRATUnknown, nil)
if err != nil {
return OperatorSelection{}, err
}
sel.OperatorName = rs.ProviderName
return sel, nil
}
func (b *MBIMBackend) SetOperatorSelection(ctx context.Context, req SetOperatorSelectionRequest) (OperatorSelection, error) {
sel, err := NormalizeSetOperatorSelectionRequest(req)
if err != nil {
return OperatorSelection{}, err
}
if sel.Mode == OperatorSelectionAutomatic {
if _, err := b.source.SetRegister(ctx, mbim.RegisterActionAutomatic, ""); err != nil {
return OperatorSelection{}, err
}
return OperatorSelection{Mode: OperatorSelectionAutomatic}, nil
}
if _, err := b.source.SetRegister(ctx, mbim.RegisterActionManual, sel.PLMN); err != nil {
return OperatorSelection{}, err
}
return sel, nil
}
func mbimProviderStatus(state uint32) string {
switch {
case state&(1<<4) != 0:
return "current"
case state&(1<<1) != 0:
return "forbidden"
case state&(1<<3) != 0:
return "available"
default:
return "unknown"
}
}
func mbimProviderRATs(class uint32) []OperatorAccessTechnology {
if class&mbim.CellularClassGSM != 0 {
return []OperatorAccessTechnology{OperatorRATGSM}
}
return nil
}
@@ -0,0 +1,115 @@
package backend
import (
"context"
"testing"
"github.com/iniwex5/vohive/pkg/mbim"
)
func TestMBIMBackendImplementsOperatorSelectionProvider(t *testing.T) {
var _ OperatorSelectionProvider = (*MBIMBackend)(nil)
}
func TestMBIMBackendScanOperatorsMapsVisibleProviders(t *testing.T) {
src := &fakeMBIMSource{providers: []mbim.Provider{{
PLMN: "310260",
Name: "T-Mobile",
State: 1<<4 | 1<<3,
CellularClass: mbim.CellularClassGSM,
RSSI: 17,
}}}
b := NewMBIMBackend("", src)
candidates, err := b.ScanOperators(context.Background())
if err != nil {
t.Fatalf("ScanOperators: %v", err)
}
if len(candidates) != 1 {
t.Fatalf("candidate len = %d, want 1", len(candidates))
}
got := candidates[0]
if got.PLMN != "310260" || got.MCC != "310" || got.MNC != "260" || got.OperatorName != "T-Mobile" {
t.Fatalf("candidate identity = %+v", got)
}
if got.Status != "current" {
t.Fatalf("status = %q, want current", got.Status)
}
if len(got.RATs) != 1 || got.RATs[0] != OperatorRATGSM {
t.Fatalf("RATs = %+v, want gsm", got.RATs)
}
}
func TestMBIMBackendSetOperatorSelectionManualDelegatesRegisterSet(t *testing.T) {
src := &fakeMBIMSource{}
b := NewMBIMBackend("", src)
sel, err := b.SetOperatorSelection(context.Background(), SetOperatorSelectionRequest{
Mode: OperatorSelectionManual,
PLMN: "310260",
RAT: OperatorRATGSM,
})
if err != nil {
t.Fatalf("SetOperatorSelection: %v", err)
}
if src.setRegisterAction != mbim.RegisterActionManual || src.setRegisterPLMN != "310260" {
t.Fatalf("set register = action:%d plmn:%q", src.setRegisterAction, src.setRegisterPLMN)
}
if sel.Mode != OperatorSelectionManual || sel.PLMN != "310260" || sel.RAT != OperatorRATGSM {
t.Fatalf("selection = %+v", sel)
}
}
func TestMBIMBackendSetOperatorSelectionAutomaticDelegatesRegisterSet(t *testing.T) {
src := &fakeMBIMSource{}
b := NewMBIMBackend("", src)
sel, err := b.SetOperatorSelection(context.Background(), SetOperatorSelectionRequest{Mode: OperatorSelectionAutomatic})
if err != nil {
t.Fatalf("SetOperatorSelection: %v", err)
}
if src.setRegisterAction != mbim.RegisterActionAutomatic || src.setRegisterPLMN != "" {
t.Fatalf("set register = action:%d plmn:%q", src.setRegisterAction, src.setRegisterPLMN)
}
if sel.Mode != OperatorSelectionAutomatic {
t.Fatalf("selection = %+v, want automatic", sel)
}
}
func TestMBIMBackendGetOperatorSelectionMapsRegisterState(t *testing.T) {
src := &fakeMBIMSource{reg: mbim.RegisterState{
RegisterMode: mbim.RegisterModeManual,
ProviderID: "46000",
ProviderName: "CMCC",
MCC: "460",
MNC: "00",
}}
b := NewMBIMBackend("", src)
sel, err := b.GetOperatorSelection(context.Background())
if err != nil {
t.Fatalf("GetOperatorSelection: %v", err)
}
if sel.Mode != OperatorSelectionManual || sel.PLMN != "46000" || sel.OperatorName != "CMCC" {
t.Fatalf("selection = %+v", sel)
}
}
func TestMBIMBackendGetOperatorSelectionMapsAutomaticRegisterMode(t *testing.T) {
src := &fakeMBIMSource{reg: mbim.RegisterState{
RegisterMode: mbim.RegisterModeAutomatic,
ProviderID: "310260",
ProviderName: "T-Mobile",
MCC: "310",
MNC: "260",
}}
b := NewMBIMBackend("", src)
sel, err := b.GetOperatorSelection(context.Background())
if err != nil {
t.Fatalf("GetOperatorSelection: %v", err)
}
if sel.Mode != OperatorSelectionAutomatic || sel.PLMN != "" {
t.Fatalf("selection = %+v, want automatic without PLMN", sel)
}
}
+54
View File
@@ -0,0 +1,54 @@
package backend
import (
"context"
"time"
"github.com/iniwex5/quectel-qmi-go/pkg/manager"
"github.com/iniwex5/vohive/pkg/mbim"
)
// MBIMSource is the adapter surface MBIMBackend needs from internal/mbim.
type MBIMSource interface {
ControlDevice() string
DeviceCaps(ctx context.Context) (mbim.Caps, error)
SubscriberReady(ctx context.Context) (mbim.SubscriberReady, error)
RegisterState(ctx context.Context) (mbim.RegisterState, error)
VisibleProviders(ctx context.Context) ([]mbim.Provider, error)
HomeProvider(ctx context.Context) (mbim.Provider, error)
GetRegisterState(ctx context.Context) (mbim.RegisterState, error)
SetRegister(ctx context.Context, action uint32, plmn string) (mbim.RegisterState, error)
SignalState(ctx context.Context) (mbim.SignalState, error)
PacketService(ctx context.Context) (mbim.PacketService, error)
SetPacketService(ctx context.Context, action mbim.PacketServiceAction) (mbim.PacketService, error)
RadioState(ctx context.Context) (mbim.RadioState, error)
SetRadioState(ctx context.Context, sw mbim.RadioSwitch) (mbim.RadioState, error)
DeviceReset(ctx context.Context) error
Snapshot() mbim.Snapshot
Capability() *mbim.Capabilities
SendSMS(ctx context.Context, pdu []byte) (uint32, error)
ReadSMS(ctx context.Context, index uint32) (mbim.SMSRecord, error)
ListSMS(ctx context.Context) ([]mbim.SMSRecord, error)
DeleteSMS(ctx context.Context, index uint32) error
DeleteAllSMS(ctx context.Context) error
GetSMSC(ctx context.Context) (string, error)
SetSMSC(ctx context.Context, smsc string) error
ExecuteUSSD(ctx context.Context, command string, timeout time.Duration) (mbim.USSDResult, error)
ContinueUSSD(ctx context.Context, input string, timeout time.Duration) (mbim.USSDResult, error)
CancelUSSD(ctx context.Context) error
OpenChannel(ctx context.Context, aid []byte) (uint32, error)
CloseChannel(ctx context.Context, channel uint32) error
TransmitAPDU(ctx context.Context, channel uint32, command []byte) ([]byte, error)
ReadSIMEF(ctx context.Context, fileID uint16, readLen int) ([]byte, error)
ReadSIMRecordEF(ctx context.Context, fileID uint16, recordNumber uint32) ([]byte, error)
ResolveLogicalChannelAID(app string, fallback string) (string, string, error)
GetUIMReadiness(ctx context.Context) (manager.UIMReadiness, error)
UIMPowerOffSIM(ctx context.Context, slot uint8) error
UIMPowerOnSIM(ctx context.Context, slot uint8) error
CalculateAKA(ctx context.Context, rand, autn []byte) (res, ik, ck, auts []byte, err error)
}
Loaded 100 of 984 files, more files were not shown because too many files have changed in this diff. Show more