11 Commits
Author SHA1 Message Date
MengMengCode 400f08c6c7 Enforce hard limits and hide unavailable task paths 2026-08-12 17:24:39 +08:00
MengMengCode 1380ffb419 Update Readme.md 2026-08-12 17:09:06 +08:00
MengMengCode 45b15b245f Update Readme.md 2026-08-12 16:57:16 +08:00
MengMengCode 2780dd96de Make EC20 eSIM channels coexist with VoWiFi 2026-08-12 16:56:30 +08:00
MengMengCode 2922d6a275 Wait for OpenWrt service shutdown during upgrades 2026-08-12 16:36:04 +08:00
MengMengCode 288e856fdb Stabilize OpenWrt modem startup and upgrades 2026-08-12 16:30:22 +08:00
MengMengCode f17d925c4c Fix static ARM builds and OpenWrt VoWiFi setup 2026-08-12 15:58:02 +08:00
Meng MengandGitHub 296f963885 Merge pull request #3 from MengMengCode/dependabot/go_modules/go_modules-a3c8a40308
build(deps): bump golang.org/x/crypto from 0.41.0 to 0.52.0 in the go_modules group across 1 directory
2026-08-12 02:38:34 +08:00
dependabot[bot]andGitHub 1b9546a73d build(deps): bump golang.org/x/crypto
Bumps the go_modules group with 1 update in the / directory: [golang.org/x/crypto](https://github.com/golang/crypto).


Updates `golang.org/x/crypto` from 0.41.0 to 0.52.0
- [Commits](https://github.com/golang/crypto/compare/v0.41.0...v0.52.0)

---
updated-dependencies:
- dependency-name: golang.org/x/crypto
  dependency-version: 0.52.0
  dependency-type: direct:production
  dependency-group: go_modules
...

Signed-off-by: dependabot[bot] <[email protected]>
2026-08-11 18:35:30 +00:00
MengMengCode 22487dbb1f Add PC/SC backend support for USB SIM readers
- Implemented a new `unsupportedBackend` in `backend_stub.go` to handle unsupported platforms.
- Created a `Service` struct in `service.go` to manage interactions with smart cards, including session management and identity reading.
- Added methods for reading identity, checking readiness, and authenticating with USIM applications.
- Introduced a `scriptedCard` for testing purposes in `service_test.go` to simulate card responses.
- Defined necessary types and error handling in `types.go` for better clarity and usability.
- Developed a `PCSCAdapter` in `vowifi/pcsc_adapter.go` to integrate PC/SC service with Wi-Fi calling functionalities.
- Added a new SVG icon for USB SIM readers in `public/sim-reader.svg`.
- Implemented tests to ensure correct functionality and error handling in various scenarios.
2026-08-12 02:33:32 +08:00
Meng MengandGitHub f9bb38aabe Add star history badge to README 2026-08-11 23:52:46 +08:00
82 changed files with 5318 additions and 191 deletions
+8
View File
@@ -110,6 +110,14 @@ jobs:
-o "$OUTPUT" \
./cmd/vocat
chmod 0755 "$OUTPUT"
if readelf -l "$OUTPUT" | grep -q 'Requesting program interpreter'; then
echo "ERROR: $OUTPUT unexpectedly requires a dynamic loader" >&2
readelf -l "$OUTPUT" >&2
exit 1
fi
if [ "${{ matrix.goarch }}" = "amd64" ]; then
"$OUTPUT" version
fi
- name: Upload ${{ matrix.target }}
uses: actions/upload-artifact@v4
with:
+25 -7
View File
@@ -22,7 +22,7 @@
<img alt="GitHub Actions" src="https://img.shields.io/badge/GitHub_Actions-Release-2088FF?style=flat-square&logo=githubactions&logoColor=white">
</p>
**English** | [简体中文](docs/README.zh-CN.md)
**English** | [العربية](docs/README.ar.md) | [简体中文](docs/README.zh-CN.md) | [繁體中文](docs/README.zh-TW.md) | [Français](docs/README.fr.md) | [Русский](docs/README.ru.md) | [Español](docs/README.es.md) | [日本語](docs/README.ja.md)
Vocat is an open-source web control panel and engineering toolkit for Quectel EC20/EC25-class cellular modems. It combines modem discovery, live radio status, AT and USSD terminals, SMS, WiFi Calling, eSIM management, network selection, proxy routing, notifications, audit logs, and release automation in one self-contained service.
@@ -46,7 +46,7 @@ The backend is written in Go, the interface is built with React and TypeScript,
| Card policy | ICCID-based WiFi Calling and flight-mode behavior with immediate policy application. |
| Proxy routing | Upstream SOCKS routing, device bindings, country rules, TCP reachability checks, and UDP Associate checks for WiFi Calling data paths. |
| Notifications | New inbound SMS forwarding through Telegram, Bark, email, Pushplus, and signed webhooks. Each SMS is delivered as an individual notification. |
| Telegram bot | Device status, installed-profile listing and switching, WiFi Calling controls, SMS sending, timed dialing with automatic hang-up, call status, answer, and hang-up commands. Sensitive actions require administrator confirmation. |
| Telegram bot | Device status, installed-profile listing and switching, WiFi Calling controls, and SMS sending. Sensitive actions require administrator confirmation. |
| Operations | Authentication, CSRF protection, access policies, audit events, live logs, log retention, health checks, responsive layout, dark mode, and English/Chinese application UI. |
| Distribution | Static Linux binaries, systemd installation script, self-update with SHA-256 verification, Docker image, GHCR publishing, and GitHub Actions release builds. |
@@ -65,10 +65,24 @@ Available features depend on the module firmware, USB composition, SIM/eSIM capa
### One-click Linux installation
As root (including OpenWrt/Kwrt, where `sudo` is normally absent):
```bash
curl -fsSL https://raw.githubusercontent.com/MengMengCode/VoCat/master/scripts/install.sh | bash
```
From a normal user on a distribution with sudo:
```bash
curl -fsSL https://raw.githubusercontent.com/MengMengCode/VoCat/master/scripts/install.sh | sudo bash
```
Check the host's VoWiFi/XFRM prerequisites without installing VoCat:
```bash
curl -fsSL https://raw.githubusercontent.com/MengMengCode/VoCat/master/scripts/install.sh | bash -s -- --check-env
```
Install a specific version:
```bash
@@ -76,6 +90,12 @@ curl -fsSL https://raw.githubusercontent.com/MengMengCode/VoCat/master/scripts/i
sudo bash install.sh 0.0.2
```
VoWiFi IMS requires Linux XFRM/IPsec. On OpenWrt/Kwrt the installer attempts
to install matching `ip-full`, `kmod-ipsec`, `kmod-ipsec4/6`,
`kmod-crypto-authenc`, AES-CBC and SHA1 packages from the firmware's own feed.
If matching kernel modules are unavailable, use a firmware that includes them;
never force-install kmods built for a different kernel.
The installer:
- detects `amd64`, `386`, `arm64`, `aarch64`, or `armv7`;
@@ -187,13 +207,9 @@ When Telegram notifications are enabled and both Chat ID and Admin ID are config
/switch <device> <iccid>
/wfc <device> <status|on|off|reconnect>
/sms <device> <number> <message>
/call <device> <number> <seconds>
/calls <device>
/answer <device>
/hangup <device>
```
Profile switching, SMS submission, and dialing use one-time confirmation buttons. Timed dialing performs the modem call action and automatically hangs up after 1600 seconds; it does not capture or process call audio. The bot does not expose eSIM download, delete, or rename commands.
Profile switching and SMS submission use one-time confirmation buttons. The bot does not expose eSIM download, delete, or rename commands.
## Updating
@@ -316,3 +332,5 @@ cd web && npm run build
## License
See [LICENSE](LICENSE).
[![MengMengCode/VoCat Star History](https://mengmeng.meteor-history.com/api/embed/MengMengCode/VoCat.svg?sig=sdeXRVxAoY3yLWgXL7JViY2USYIN3t9neJ6ScPvgUAo&theme=light&style=xkcd&color=dd4528&background=ffffff&textColor=000000&width=900&height=600&lineWidth=3&showTitle=true&showLegend=true&showDots=false&v=0.0.14)](https://meteor-history.com)
+45
View File
@@ -0,0 +1,45 @@
//go:build linux
package main
import (
"errors"
"fmt"
"os"
"path/filepath"
"golang.org/x/sys/unix"
)
func lockServerInstance(databasePath string) (*os.File, error) {
// The modem, PC/SC reader, XFRM policies and listener are host resources,
// not database resources. Lock per OS user so a diagnostic instance using a
// different VOCAT_DATABASE_PATH cannot silently steal the same AT port from
// the managed service. Prefer /run because systemd's PrivateTmp would
// otherwise hide the managed service's lock from a manually started process.
// The UID-specific directory still permits intentionally isolated users to
// operate independently; development hosts without writable /run fall back
// to TempDir.
uid := os.Geteuid()
directory := filepath.Join("/run", fmt.Sprintf("vocat-%d", uid))
if uid == 0 {
directory = "/run/vocat"
}
if err := os.MkdirAll(directory, 0o700); err != nil {
directory = os.TempDir()
}
path := filepath.Join(directory, "vocat-server.lock")
fd, err := unix.Open(path, unix.O_CREAT|unix.O_RDWR|unix.O_CLOEXEC|unix.O_NOFOLLOW, 0o600)
if err != nil {
return nil, fmt.Errorf("open server instance lock: %w", err)
}
file := os.NewFile(uintptr(fd), path)
if err := unix.Flock(fd, unix.LOCK_EX|unix.LOCK_NB); err != nil {
_ = file.Close()
if errors.Is(err, unix.EWOULDBLOCK) || errors.Is(err, unix.EAGAIN) {
return nil, errors.New("another vocat server already controls this host's modem resources")
}
return nil, fmt.Errorf("lock server instance: %w", err)
}
return file, nil
}
+26
View File
@@ -0,0 +1,26 @@
//go:build linux
package main
import (
"path/filepath"
"strings"
"testing"
)
func TestServerInstanceLockRejectsSecondProcess(t *testing.T) {
firstDatabase := filepath.Join(t.TempDir(), "vocat.db")
first, err := lockServerInstance(firstDatabase)
if err != nil {
t.Fatal(err)
}
defer first.Close()
secondDatabase := filepath.Join(t.TempDir(), "other.db")
second, err := lockServerInstance(secondDatabase)
if second != nil {
second.Close()
}
if err == nil || !strings.Contains(err.Error(), "already controls this host") {
t.Fatalf("second lock error = %v", err)
}
}
+12
View File
@@ -0,0 +1,12 @@
//go:build !linux
package main
import (
"os"
"path/filepath"
)
func lockServerInstance(databasePath string) (*os.File, error) {
return os.OpenFile(filepath.Join(filepath.Dir(databasePath), ".vocat.lock"), os.O_CREATE|os.O_RDWR, 0o600)
}
+136 -9
View File
@@ -27,6 +27,7 @@ import (
"vocat/internal/extensions"
"vocat/internal/httpsmode"
"vocat/internal/loghub"
"vocat/internal/pcsc"
"vocat/internal/server"
"vocat/internal/store"
"vocat/internal/update"
@@ -111,6 +112,11 @@ func run(logger *slog.Logger, logs *loghub.Hub) error {
if err != nil {
return fmt.Errorf("load configuration: %w", err)
}
instanceLock, err := lockServerInstance(cfg.DatabasePath)
if err != nil {
return err
}
defer instanceLock.Close()
if cfg.UsesDefaultCredentials() {
logger.Warn(
"default admin credentials are active; set VOCAT_ADMIN_PASSWORD before exposing the service",
@@ -184,7 +190,8 @@ func run(logger *slog.Logger, logs *loghub.Hub) error {
return err
}
deviceManager, err := device.NewManager(device.Options{})
cardReaders := pcsc.New()
deviceManager, err := device.NewManager(device.Options{CardReaders: cardReaders})
if err != nil {
return fmt.Errorf("create device manager: %w", err)
}
@@ -220,6 +227,7 @@ func run(logger *slog.Logger, logs *loghub.Hub) error {
logger,
database,
deviceManager,
cardReaders,
)
if err != nil {
return fmt.Errorf("configure VoWiFi runtime: %w", err)
@@ -362,6 +370,12 @@ func configureDeviceBackends(
if mapErr != nil {
continue
}
if config.DeviceType == store.DeviceTypeUSBSIMReader {
if err := manager.SetSIMPin(entry.ID, config.SIMPIN); err != nil {
logger.Warn("configure USB SIM reader", "device_id", config.ID, "error", err)
}
continue
}
if err := manager.SetBackend(entry.ID, config.DeviceBackend); err != nil {
logger.Warn("configure device backend", "device_id", config.ID, "backend", config.DeviceBackend, "error", err)
}
@@ -384,6 +398,9 @@ func restoreDefaultCellularRadios(
}
mapper := integration.ATMapper{Store: database, Devices: manager}
for _, config := range configs {
if config.DeviceType == store.DeviceTypeUSBSIMReader {
continue
}
if config.VoWiFiEnabled {
continue
}
@@ -431,6 +448,9 @@ func restoreConfiguredCellularData(
}
mapper := integration.ATMapper{Store: database, Devices: manager}
for _, config := range configs {
if config.DeviceType == store.DeviceTypeUSBSIMReader {
continue
}
if !config.NetworkEnabled || config.VoWiFiEnabled {
continue
}
@@ -482,6 +502,9 @@ func disableAllDeveloperCellularData(
}
mapper := integration.ATMapper{Store: database, Devices: manager}
for _, config := range configs {
if config.DeviceType == store.DeviceTypeUSBSIMReader {
continue
}
entry, err := mapper.Get(config.ID)
if err != nil {
continue
@@ -536,12 +559,13 @@ func configureVoWiFiRuntime(
logger *slog.Logger,
database *store.Store,
deviceManager *device.Manager,
cardReaders *pcsc.Service,
) (*vowifiruntime.Manager, error) {
mapper := integration.ATMapper{
Store: database,
Devices: deviceManager,
}
adapter, err := vowifi.NewEC20Adapter(mapper, vowifi.EC20AdapterOptions{
ec20Adapter, err := vowifi.NewEC20Adapter(mapper, vowifi.EC20AdapterOptions{
// The test deployment is deliberately non-cellular. VoWiFi teardown
// may restore CFUN, but it must never reactivate a PDP context.
RestoreCellularData: false,
@@ -556,6 +580,16 @@ func configureVoWiFiRuntime(
if err != nil {
return nil, err
}
pcscAdapter, err := vowifi.NewPCSCAdapter(cardReaders, func(ctx context.Context, deviceID string) (pcsc.Selector, string, error) {
config, resolveErr := database.Device(ctx, strings.TrimSpace(deviceID))
if resolveErr != nil {
return pcsc.Selector{}, "", resolveErr
}
return pcsc.Selector{USBPath: config.USBPath, ReaderName: config.ControlDevice}, config.SIMPIN, nil
})
if err != nil {
return nil, err
}
projector := integration.StateProjector{
Store: database,
Devices: mapper,
@@ -568,6 +602,10 @@ func configureVoWiFiRuntime(
if err != nil {
return nil, fmt.Errorf("load device %q VoWiFi config: %w", deviceID, err)
}
adapter := vowifiDeviceAdapter(ec20Adapter)
if deviceConfig.DeviceType == store.DeviceTypeUSBSIMReader {
adapter = pcscAdapter
}
return newVoWiFiOrchestrator(deviceConfig, database, adapter)
},
})
@@ -584,12 +622,18 @@ func configureVoWiFiRuntime(
}
if deviceConfig.VoWiFiEnabled {
if entry, mapErr := mapper.Get(deviceConfig.ID); mapErr == nil {
flightContext, cancelFlight := context.WithTimeout(ctx, 10*time.Second)
_, flightErr := deviceManager.SetFlight(flightContext, entry.ID, true)
cancelFlight()
flightErr := protectVoWiFiStartupRadio(ctx, deviceManager, entry.ID)
if flightErr != nil {
_ = manager.Close(context.Background())
return nil, fmt.Errorf("protect device %q before VoWiFi startup: %w", deviceConfig.ID, flightErr)
// A modem can be temporarily unavailable while OpenWrt/procd is
// restarting the service (notably after loading XFRM modules). Do
// not take the Web/API service down with it: the orchestrator below
// remains fail-closed and its runtime manager retries until CFUN=4
// can be established.
logger.Warn(
"VoWiFi startup radio protection deferred to automatic retry",
"device_id", deviceConfig.ID,
"error", flightErr,
)
}
}
if _, err := manager.RequestEnabled(deviceConfig.ID, true); err != nil {
@@ -601,10 +645,66 @@ func configureVoWiFiRuntime(
return manager, nil
}
const (
vowifiStartupRadioAttempts = 3
vowifiStartupRadioDelay = time.Second
)
type flightModeSetter interface {
SetFlight(context.Context, string, bool) (device.FlightResult, error)
}
func protectVoWiFiStartupRadio(ctx context.Context, manager flightModeSetter, physicalID string) error {
return protectVoWiFiStartupRadioWithRetry(
ctx,
manager,
physicalID,
vowifiStartupRadioAttempts,
vowifiStartupRadioDelay,
)
}
func protectVoWiFiStartupRadioWithRetry(
ctx context.Context,
manager flightModeSetter,
physicalID string,
attempts int,
delay time.Duration,
) error {
var lastErr error
for attempt := 0; attempt < attempts; attempt++ {
flightContext, cancel := context.WithTimeout(ctx, 10*time.Second)
_, lastErr = manager.SetFlight(flightContext, physicalID, true)
cancel()
if lastErr == nil {
return nil
}
if attempt+1 == attempts {
break
}
timer := time.NewTimer(delay)
select {
case <-ctx.Done():
if !timer.Stop() {
<-timer.C
}
return errors.Join(lastErr, ctx.Err())
case <-timer.C:
}
}
return lastErr
}
type vowifiDeviceAdapter interface {
vowifi.SIMIdentityReader
vowifi.AKAProvider
vowifi.RadioController
}
func newVoWiFiOrchestrator(
deviceConfig store.Device,
database *store.Store,
adapter *vowifi.EC20Adapter,
adapter vowifiDeviceAdapter,
) (*vowifi.Orchestrator, error) {
apn := deviceConfig.APN
if apn == "" {
@@ -734,9 +834,18 @@ func provisionDiscoveredDevices(
candidate := discovered.Candidate
backend := "at"
control := candidate.ATPort.OpenPath()
deviceType := store.DeviceTypePCIeEC20EC25
esimTransport := backend
if candidate.QMIControl != "" {
backend = "qmi"
control = candidate.QMIControl
esimTransport = backend
}
if candidate.HardwareKind == pcsc.HardwareKind {
backend = "pcsc"
control = candidate.ReaderName
deviceType = store.DeviceTypeUSBSIMReader
esimTransport = "pcsc"
}
name := candidate.Product
if name == "" || strings.EqualFold(name, "Android") {
@@ -745,6 +854,7 @@ func provisionDiscoveredDevices(
if err := database.UpsertDevice(ctx, store.Device{
ID: discovered.ID,
Name: name,
DeviceType: deviceType,
Interface: candidate.NetworkInterface,
ControlDevice: control,
ATPort: candidate.ATPort.OpenPath(),
@@ -755,7 +865,7 @@ func provisionDiscoveredDevices(
StopBits: 1,
Parity: "none",
DeviceBackend: backend,
ESIMTransport: backend,
ESIMTransport: esimTransport,
NetworkEnabled: false,
SMSEnabled: true,
VoWiFiEnabled: true,
@@ -931,6 +1041,7 @@ func reconcileCardPolicies(
manager *device.Manager,
vowifiManager *vowifiruntime.Manager,
) {
observedCards := make(map[string]string)
reconcile := func() {
policies, policyListErr := database.ListCardPolicies(ctx)
if policyListErr == nil {
@@ -953,12 +1064,26 @@ func reconcileCardPolicies(
for _, config := range configs {
entry, mapErr := mapper.Get(config.ID)
if mapErr != nil || entry.Snapshot == nil {
if config.DeviceType == store.DeviceTypeUSBSIMReader && observedCards[config.ID] != "missing" {
if state, stateErr := vowifiManager.State(config.ID); stateErr == nil && state.ICCID != "" {
_, _ = vowifiManager.RequestReconnect(config.ID)
}
observedCards[config.ID] = "missing"
}
continue
}
iccid := strings.TrimSpace(entry.Snapshot.ICCID)
if iccid == "" {
if config.DeviceType == store.DeviceTypeUSBSIMReader && observedCards[config.ID] != "missing" {
if state, stateErr := vowifiManager.State(config.ID); stateErr == nil && state.ICCID != "" {
_, _ = vowifiManager.RequestReconnect(config.ID)
}
observedCards[config.ID] = "missing"
}
continue
}
previousObserved := observedCards[config.ID]
observedCards[config.ID] = iccid
policy, policyErr := database.CardPolicy(ctx, iccid)
if policyErr != nil {
continue
@@ -1001,6 +1126,8 @@ func reconcileCardPolicies(
_, _ = vowifiManager.RequestEnabled(config.ID, true)
case state.ICCID != "" && !strings.EqualFold(strings.TrimSpace(state.ICCID), iccid):
_, _ = vowifiManager.RequestReconnect(config.ID)
case config.DeviceType == store.DeviceTypeUSBSIMReader && previousObserved == "missing":
_, _ = vowifiManager.RequestReconnect(config.ID)
}
continue
}
+56
View File
@@ -0,0 +1,56 @@
package main
import (
"context"
"errors"
"testing"
"vocat/internal/device"
)
type startupFlightSetter struct {
errors []error
calls int
id string
}
func (setter *startupFlightSetter) SetFlight(
_ context.Context,
id string,
enabled bool,
) (device.FlightResult, error) {
setter.calls++
setter.id = id
if !enabled {
return device.FlightResult{}, errors.New("expected flight mode to be enabled")
}
if setter.calls <= len(setter.errors) {
return device.FlightResult{}, setter.errors[setter.calls-1]
}
return device.FlightResult{CurrentMode: 4, FlightMode: true, RadioOff: true}, nil
}
func TestProtectVoWiFiStartupRadioRetriesTransientFailure(t *testing.T) {
transient := errors.New("modem is reopening")
setter := &startupFlightSetter{errors: []error{transient, transient}}
if err := protectVoWiFiStartupRadioWithRetry(
context.Background(), setter, "quectel-1", 3, 0,
); err != nil {
t.Fatalf("protect startup radio: %v", err)
}
if setter.calls != 3 || setter.id != "quectel-1" {
t.Fatalf("SetFlight calls = %d, id = %q", setter.calls, setter.id)
}
}
func TestProtectVoWiFiStartupRadioReturnsLastFailure(t *testing.T) {
first := errors.New("first")
last := errors.New("last")
setter := &startupFlightSetter{errors: []error{first, last}}
err := protectVoWiFiStartupRadioWithRetry(
context.Background(), setter, "quectel-1", 2, 0,
)
if !errors.Is(err, last) || setter.calls != 2 {
t.Fatalf("protect startup radio = %v after %d calls", err, setter.calls)
}
}
+334
View File
@@ -0,0 +1,334 @@
<p align="center">
<img src="../web/public/favicon.svg" width="96" alt="Vocat">
</p>
<h1 align="center">VoCat</h1>
<p align="center">
<img alt="Go" src="https://img.shields.io/badge/Go-1.25-00ADD8?style=flat-square&logo=go&logoColor=white">
<img alt="React" src="https://img.shields.io/badge/React-19-61DAFB?style=flat-square&logo=react&logoColor=111111">
<img alt="TypeScript" src="https://img.shields.io/badge/TypeScript-5.8-3178C6?style=flat-square&logo=typescript&logoColor=white">
<img alt="Vite" src="https://img.shields.io/badge/Vite-7-646CFF?style=flat-square&logo=vite&logoColor=white">
<img alt="Tailwind CSS" src="https://img.shields.io/badge/Tailwind_CSS-3-06B6D4?style=flat-square&logo=tailwindcss&logoColor=white">
<img alt="SQLite" src="https://img.shields.io/badge/SQLite-Embedded-003B57?style=flat-square&logo=sqlite&logoColor=white">
</p>
<p align="center">
<img alt="Linux" src="https://img.shields.io/badge/Linux-amd64_%7C_386_%7C_arm64_%7C_aarch64_%7C_armv7-FCC624?style=flat-square&logo=linux&logoColor=111111">
<img alt="Docker" src="https://img.shields.io/badge/Docker-Multi--Arch-2496ED?style=flat-square&logo=docker&logoColor=white">
<img alt="WiFi Calling" src="https://img.shields.io/badge/WiFi_Calling-IMS_SMS-7B1FA2?style=flat-square">
<img alt="eSIM" src="https://img.shields.io/badge/eSIM-LPA_%2F_eUICC-009688?style=flat-square">
<img alt="Telegram" src="https://img.shields.io/badge/Telegram-Bot-26A5E4?style=flat-square&logo=telegram&logoColor=white">
<img alt="GitHub Actions" src="https://img.shields.io/badge/GitHub_Actions-Release-2088FF?style=flat-square&logo=githubactions&logoColor=white">
</p>
[English](../README.md) | **العربية** | [简体中文](README.zh-CN.md) | [繁體中文](README.zh-TW.md) | [Français](README.fr.md) | [Русский](README.ru.md) | [Español](README.es.md) | [日本語](README.ja.md)
Vocat هي لوحة تحكم ويب مفتوحة المصدر ومجموعة أدوات هندسية لمودمات Quectel الخلوية من فئة EC20/EC25. تجمع في خدمة واحدة مكتفية ذاتيًا بين اكتشاف المودم، وحالة الراديو المباشرة، وطرفيات AT وUSSD، والرسائل القصيرة SMS، وWiFi Calling، وإدارة eSIM، واختيار الشبكة، والتوجيه عبر البروكسي، والإشعارات، وسجلات التدقيق، وأتمتة الإصدارات.
الواجهة الخلفية مكتوبة بلغة Go، والواجهة مبنية باستخدام React وTypeScript، وتُضمَّن واجهة الإنتاج الأمامية داخل الملف الثنائي لـ Go. يحتوي ملف تنفيذي واحد على تطبيق الويب ويستخدم SQLite للحالة الدائمة.
<p align="center">
<img src="../img/image.png">
<img src="../img/image-1.png">
</p>
## الميزات
| المجال | ما يوفره Vocat |
| --- | --- |
| إدارة الأجهزة | اكتشاف تلقائي عبر المنفذ التسلسلي/USB، دعم عدة مودمات، أسماء أجهزة مألوفة، تحديثات مباشرة للنظرة العامة، إعادة تشغيل الوحدة، وضع الطيران، وضوابط وضع شبكة USB. |
| الراديو والشبكة | حالة التسجيل، المشغّل، مقاييس الإشارة، RSRP/RSRQ/SINR، وضع الشبكة، النطاق، القناة، فحص المشغّلين، والاختيار التلقائي أو اليدوي للشبكة. |
| AT وUSSD | طرفية AT تفاعلية، سجل الأوامر، استجابات المودم الخام، تدفقات بدء/متابعة/إلغاء USSD، والإبلاغ الواضح عن أخطاء المودم. |
| الرسائل القصيرة | إرسال مباشر للرسائل الخلوية ورسائل IMS، المزامنة الواردة، التعامل مع الرسائل متعددة الأجزاء، تقارير التسليم، سجل المحادثات، حالة عدم القراءة، الطوابع الزمنية، وحالة التسليم لكل رسالة. |
| WiFi Calling | إنشاء نفق IKEv2/ePDG، مصادقة EAP-AKA، تسجيل IMS، رسائل IMS القصيرة، ضوابط إعادة الاتصال، تشخيصات الحالة، والتوجيه لكل جهاز. |
| eSIM وeUICC | اكتشاف eUICC، ومعلومات EID والإنتاج، والبيانات الوصفية للشهادات، وجرد متعدد لـ eUICC، وقائمة الملفات الشخصية المثبتة، وعمليات التمكين/التعطيل/التبديل، وعمليات التنزيل وإعادة التسمية والحذف عندما تدعمها البطاقة. |
| سياسة البطاقة | سلوك WiFi Calling ووضع الطيران بناءً على ICCID مع تطبيق فوري للسياسة. |
| التوجيه عبر البروكسي | توجيه SOCKS صاعد، ربط الأجهزة، قواعد الدول، فحوصات الوصول عبر TCP، وفحوصات UDP Associate لمسارات بيانات WiFi Calling. |
| الإشعارات | إعادة توجيه الرسائل القصيرة الواردة الجديدة عبر Telegram وBark والبريد الإلكتروني وPushplus وwebhooks الموقّعة. يتم تسليم كل رسالة كإشعار منفصل. |
| بوت Telegram | حالة الجهاز، قائمة الملفات الشخصية المثبتة وتبديلها، ضوابط WiFi Calling، وإرسال الرسائل القصيرة. تتطلب الإجراءات الحساسة تأكيد المسؤول. |
| العمليات | المصادقة، الحماية من CSRF، سياسات الوصول، أحداث التدقيق، السجلات المباشرة، الاحتفاظ بالسجلات، فحوصات الصحة، تخطيط متجاوب، الوضع الداكن، وواجهة مستخدم بالإنجليزية/الصينية. |
| التوزيع | ملفات Linux الثنائية الثابتة، سكربت تثبيت systemd، تحديث ذاتي مع التحقق من SHA-256، صورة Docker، النشر إلى GHCR، وبنى إصدارات GitHub Actions. |
## الأجهزة المدعومة
يستهدف Vocat وحدات Quectel المبنية على Qualcomm والتي توفر واجهات AT وQMI والمنفذ التسلسلي وشبكة USB المتوافقة، بما في ذلك:
- Quectel EC20
- Quectel EC25
- عائلة Quectel EG25
- وحدات EG600 المتوافقة وذات الصلة
تعتمد الميزات المتاحة على برنامج الوحدة الثابت (firmware)، وتكوين USB، وقدرات SIM/eSIM، وتعريفات المضيف، والشبكة اللاسلكية، وإعدادات المشغّل.
## التثبيت
### تثبيت Linux بنقرة واحدة
بصفتك root (بما في ذلك OpenWrt/Kwrt، حيث يكون `sudo` غير موجود عادةً):
```bash
curl -fsSL https://raw.githubusercontent.com/MengMengCode/VoCat/master/scripts/install.sh | bash
```
من مستخدم عادي على توزيعة تحتوي على sudo:
```bash
curl -fsSL https://raw.githubusercontent.com/MengMengCode/VoCat/master/scripts/install.sh | sudo bash
```
تحقق من متطلبات VoWiFi/XFRM على المضيف دون تثبيت VoCat:
```bash
curl -fsSL https://raw.githubusercontent.com/MengMengCode/VoCat/master/scripts/install.sh | bash -s -- --check-env
```
تثبيت إصدار محدد:
```bash
curl -fsSL https://raw.githubusercontent.com/MengMengCode/VoCat/master/scripts/install.sh -o install.sh
sudo bash install.sh 0.0.2
```
يتطلب VoWiFi IMS وجود Linux XFRM/IPsec. على OpenWrt/Kwrt يحاول المثبّت
تثبيت الحزم المطابقة `ip-full` و`kmod-ipsec` و`kmod-ipsec4/6`
و`kmod-crypto-authenc` وAES-CBC وSHA1 من مستودع البرنامج الثابت نفسه.
إذا لم تكن وحدات النواة المطابقة متاحة، فاستخدم برنامجًا ثابتًا يتضمنها؛
ولا تفرض أبدًا تثبيت kmods مبنية لنواة مختلفة.
المثبّت:
- يكتشف `amd64` أو `386` أو `arm64` أو `aarch64` أو `armv7`؛
- ينزّل الملف الثنائي المطابق من GitHub Release؛
- يتحقق منه مقابل `SHA256SUMS`؛
- يثبّت Vocat في `/opt/vocat`؛
- ينشئ خدمة systemd محصّنة بوصول الأجهزة والشبكة الذي يتطلبه Vocat؛
- يخزّن إعدادات وقت التشغيل في `/etc/vocat/env`؛
- يولّد كلمة مرور مسؤول أولية عشوائية عند التثبيت الأول.
بعد التثبيت، افتح:
```text
http://<عنوان-الخادم>:7575
```
### التثبيت اليدوي للملف الثنائي
نزّل الملف الثنائي المطابق و`SHA256SUMS` من GitHub Releases:
| المنصة | ملف الإصدار |
| --- | --- |
| Linux x86-64 | `vocat-linux-amd64` |
| Linux x86 32-بت | `vocat-linux-386` |
| Linux ARM64 | `vocat-linux-arm64` |
| Linux AArch64 | `vocat-linux-aarch64` |
| Linux ARMv7 | `vocat-linux-armv7` |
تحقق منه وثبّته:
```bash
sha256sum -c SHA256SUMS --ignore-missing
sudo install -d -m 0755 /opt/vocat/bin /opt/vocat/data
sudo install -m 0755 vocat-linux-amd64 /opt/vocat/bin/vocat
sudo env \
VOCAT_DATABASE_PATH=/opt/vocat/data/vocat.db \
VOCAT_ADMIN_PASSWORD=change-this-password \
/opt/vocat/bin/vocat serve
```
يشغّل هذا الأمر اليدوي Vocat في المقدمة. استخدم `vocat serve` حتى
يبدأ العملية الخادم مباشرةً؛ إن تشغيل `vocat` دون وسائط بصفتك root
على TTY يفتح بدلاً من ذلك قائمة الإدارة التفاعلية. استخدم المثبّت بنقرة
واحدة عند الحاجة إلى خدمة systemd مُدارة وإعادة تشغيل تلقائية.
### Docker
لمضيف Linux الذي يجب أن يكتشف كل مودم Quectel مدعوم متصل ويواصل
رؤية أحداث التوصيل الساخن لـ USB، شغّل Vocat في وضع الوصول إلى الأجهزة:
```bash
docker pull ghcr.io/mengmengcode/vocat:latest
docker run -d \
--name vocat \
--restart unless-stopped \
--network host \
--privileged \
--user 0:0 \
-e VOCAT_ADMIN_PASSWORD=change-this-password \
-v vocat-data:/opt/vocat/data \
-v /dev:/dev \
-v /sys:/sys:ro \
ghcr.io/mengmengcode/vocat:latest
```
افتح `http://<عنوان-الخادم>:7575` بعد بدء الحاوية. شبكة المضيف
مطلوبة حتى تبقى واجهات شبكة QMI مرئية لـ Vocat، بينما الوصول المميّز إلى الأجهزة
مطلوب للمنافذ التسلسلية، وعقد تحكم QMI، وواجهات TUN، وإعدادات الشبكة، والأجهزة
المضافة بعد بدء الحاوية. يجعل تركيب `/dev` العقد الجديدة `ttyUSB*` و`ttyACM*` و`cdc-wdm*`
مرئية دون إعادة إنشاء الحاوية.
يمنح هذا الوضع عمدًا Vocat وصولاً واسعًا إلى أجهزة المضيف ومكدس الشبكة.
استخدمه فقط على مضيف Linux موثوق. يتعرف الاكتشاف التلقائي حاليًا على مودمات
Quectel USB المدعومة (معرّف الشركة المصنعة USB `2c7c`)، وليس على ماركات مودم عشوائية.
إن تركيب العقد الفردية فقط باستخدام `--device`، مثل `/dev/ttyUSB2` و`/dev/cdc-wdm0`،
يحصر الحاوية في تلك العقد الثابتة ولا يوفر اكتشافًا كاملاً متعدد الأجهزة أو بالتوصيل الساخن.
تُنشر صورة GHCR لـ `linux/amd64` و`linux/arm64`.
## الإعدادات
يقرأ Vocat ملف إعدادات JSON اختياريًا من `VOCAT_CONFIG`، ثم يطبق متغيرات البيئة `VOCAT_*`. متغيرات البيئة لها الأولوية.
| متغير البيئة | الافتراضي | الوصف |
| --- | --- | --- |
| `VOCAT_ADDR` | `0.0.0.0:7575` | عنوان الاستماع HTTP. |
| `VOCAT_DATABASE_PATH` | `./data/vocat.db` | مسار قاعدة بيانات SQLite. |
| `VOCAT_ADMIN_USERNAME` | `admin` | اسم مستخدم المسؤول الأولي. |
| `VOCAT_ADMIN_PASSWORD` | `admin` | كلمة مرور المسؤول الأولية. غيّرها قبل تعريض الخدمة للوصول. |
| `VOCAT_SESSION_TTL` | `24h` | مدة صلاحية جلسة المصادقة. |
| `VOCAT_SECURE_COOKIES` | `false` | يضع علامة آمنة على ملفات تعريف ارتباط الجلسة عند استخدام HTTPS. |
| `VOCAT_SHUTDOWN_TIMEOUT` | `10s` | مهلة الإيقاف السلس. |
| `VOCAT_MAX_REQUEST_BODY_BYTES` | `1048576` | الحد الأقصى لحجم جسم طلب API. |
| `VOCAT_REPO` | `MengMengCode/VoCat` | مستودع GitHub الموثوق الذي يستخدمه المحدّث الذاتي، بصيغة `owner/name`. |
| `GITHUB_TOKEN` | فارغ | رمز GitHub اختياري للمستودعات الخاصة أو حدود API أعلى. |
لا تخزّن رموز Telegram، أو كلمات مرور SMTP، أو أسرار webhook، أو بيانات اعتماد SIM، أو بيانات خاصة أخرى في المستودع. قم بإعدادها عبر إعدادات التطبيق أو ملفات البيئة المحمية.
## بوت Telegram
عند تفعيل إشعارات Telegram وإعداد كلٍّ من Chat ID وAdmin ID، يدعم البوت:
```text
/status [الجهاز]
/esim <الجهاز>
/switch <الجهاز> <iccid>
/wfc <الجهاز> <status|on|off|reconnect>
/sms <الجهاز> <الرقم> <الرسالة>
```
تستخدم عمليتا تبديل الملفات الشخصية وإرسال الرسائل القصيرة أزرار تأكيد لمرة واحدة. لا يعرض البوت أوامر تنزيل أو حذف أو إعادة تسمية eSIM.
## التحديث
تحقق من وجود GitHub Release أحدث:
```bash
vocat update --check --repo MengMengCode/VoCat
```
ثبّت أحدث إصدار:
```bash
sudo vocat update --repo MengMengCode/VoCat
```
ينزّل المحدّث الملف الثنائي المطابق لبنية Linux الحالية، ويتحقق منه باستخدام `SHA256SUMS` المنشور، ويستبدل الملف التنفيذي بشكل ذري، ويعيد تشغيل خدمة systemd `vocat` عند توفرها.
لتثبيتات Docker:
```bash
docker pull ghcr.io/mengmengcode/vocat:latest
```
أعد إنشاء الحاوية بعد سحب الصورة الجديدة.
## التطوير
المتطلبات:
- Go 1.25 أو أحدث
- Node.js 20 أو أحدث
- npm
تشغيل خادم تطوير الواجهة الأمامية:
```bash
cd web
npm install
npm run dev
```
بناء الواجهة الأمامية المضمّنة وتشغيل الواجهة الخلفية:
```bash
cd web
npm run build
cd ..
go run ./cmd/vocat
```
تشغيل جميع الاختبارات:
```bash
go test ./...
```
بناء ملف ثنائي للإنتاج:
```bash
go build -trimpath -ldflags "-s -w" -o vocat ./cmd/vocat
```
## أتمتة الإصدارات
يؤدي دفع وسم الإصدار إلى بدء سير عملَي GitHub Actions:
- `release-binaries` يبني وينشر ملفات `amd64` و`386` و`arm64` و`aarch64` و`armv7` الثنائية مع `SHA256SUMS`.
- `docker` يبني وينشر صورة متعددة البنى إلى GitHub Container Registry.
```bash
git tag v0.2.0
git push origin v0.2.0
```
## بنية المشروع
```text
cmd/vocat/ نقطة دخول التطبيق وCLI
internal/device/ اكتشاف المودم والتحكم في الأجهزة
internal/modem/ جلسة AT ومعالجة الاستجابات
internal/server/ واجهة HTTP API والإشعارات وخادم الويب المضمّن
internal/store/ التخزين الدائم SQLite
internal/update/ المحدّث الذاتي لـ GitHub Release
internal/vowifi/ بيئة تشغيل IKE وEAP-AKA وIMS وWiFi Calling
scripts/install.sh مثبّت ومحدّث Linux
web/src/ الواجهة الأمامية React وTypeScript
.github/workflows/ أتمتة إصدارات الملفات الثنائية وDocker
```
## الاستخدام المسؤول
يمكن أن تؤثر عمليات المودم الخلوي وeSIM في خدمة المشترك، والملفات الشخصية المخزنة، وتسجيل الشبكة، وحالة الأجهزة. احتفظ بنسخ احتياطية، وراجع الإجراءات المدمّرة بعناية، واستخدم البرنامج فقط في بيئات قانونية يُسمح لك فيها بتشغيل الأجهزة وموارد الشبكة المتصلة.
لا يتجاوز Vocat مصادقة المشغّل، أو سياسة الشبكة، أو أمان الأجهزة، أو متطلبات الثقة لـ eSIM. إن دعم عملية ما يعني أن Vocat يمكن أن يطلبها من المودم أو eUICC؛ وقد يرفضها الجهاز أو الملف الشخصي أو الشبكة أو المشغّل مع ذلك.
## المساهمة
نرحّب بالمسائل (issues) وطلبات السحب (pull requests). حافظ على التغييرات مركّزة، وأضِف الاختبارات حيثما أمكن، وتجنّب إيداع بيانات الاعتماد أو بيانات المشتركين، ووثّق بوضوح السلوك الخاص بالأجهزة.
قبل إرسال تغيير:
```bash
go test ./...
cd web && npm run build
```
## شكر وتقدير
- [Nodeseek.com](https://www.nodeseek.com) — مجتمع مكرّس للخوادم
- [Linux.do](https://linux.do) — مجتمع تقني ملهم
- [iniwex5](https://github.com/iniwex5) — إرشادات الأسلوب والوظائف
## ادعُني إلى فنجان قهوة
| الشبكة | العنوان |
| ------- | ------- |
| USDT-TRON (TRC20) | `TQQAbboBoU8h5xX4YCA1rqWJU2WjK3seSg` |
| USDT-BSC (BEP20) | `0xdbfcd4a462550d6ff06d09cbd89026c6b145d9c4` |
| USDT-Polygon | `0xdbfcd4a462550d6ff06d09cbd89026c6b145d9c4` |
## الرخصة
انظر [LICENSE](../LICENSE).
[![MengMengCode/VoCat Star History](https://mengmeng.meteor-history.com/api/embed/MengMengCode/VoCat.svg?sig=sdeXRVxAoY3yLWgXL7JViY2USYIN3t9neJ6ScPvgUAo&theme=light&style=xkcd&color=dd4528&background=ffffff&textColor=000000&width=900&height=600&lineWidth=3&showTitle=true&showLegend=true&showDots=false&v=0.0.14)](https://meteor-history.com)
+336
View File
@@ -0,0 +1,336 @@
<p align="center">
<img src="../web/public/favicon.svg" width="96" alt="Vocat">
</p>
<h1 align="center">VoCat</h1>
<p align="center">
<img alt="Go" src="https://img.shields.io/badge/Go-1.25-00ADD8?style=flat-square&logo=go&logoColor=white">
<img alt="React" src="https://img.shields.io/badge/React-19-61DAFB?style=flat-square&logo=react&logoColor=111111">
<img alt="TypeScript" src="https://img.shields.io/badge/TypeScript-5.8-3178C6?style=flat-square&logo=typescript&logoColor=white">
<img alt="Vite" src="https://img.shields.io/badge/Vite-7-646CFF?style=flat-square&logo=vite&logoColor=white">
<img alt="Tailwind CSS" src="https://img.shields.io/badge/Tailwind_CSS-3-06B6D4?style=flat-square&logo=tailwindcss&logoColor=white">
<img alt="SQLite" src="https://img.shields.io/badge/SQLite-Embedded-003B57?style=flat-square&logo=sqlite&logoColor=white">
</p>
<p align="center">
<img alt="Linux" src="https://img.shields.io/badge/Linux-amd64_%7C_386_%7C_arm64_%7C_aarch64_%7C_armv7-FCC624?style=flat-square&logo=linux&logoColor=111111">
<img alt="Docker" src="https://img.shields.io/badge/Docker-Multi--Arch-2496ED?style=flat-square&logo=docker&logoColor=white">
<img alt="WiFi Calling" src="https://img.shields.io/badge/WiFi_Calling-IMS_SMS-7B1FA2?style=flat-square">
<img alt="eSIM" src="https://img.shields.io/badge/eSIM-LPA_%2F_eUICC-009688?style=flat-square">
<img alt="Telegram" src="https://img.shields.io/badge/Telegram-Bot-26A5E4?style=flat-square&logo=telegram&logoColor=white">
<img alt="GitHub Actions" src="https://img.shields.io/badge/GitHub_Actions-Release-2088FF?style=flat-square&logo=githubactions&logoColor=white">
</p>
[English](../README.md) | [العربية](README.ar.md) | [简体中文](README.zh-CN.md) | [繁體中文](README.zh-TW.md) | [Français](README.fr.md) | [Русский](README.ru.md) | **Español** | [日本語](README.ja.md)
Vocat es un panel de control web de código abierto y un conjunto de herramientas de ingeniería para módems celulares Quectel de clase EC20/EC25. Combina, en un único servicio autocontenido, el descubrimiento de módems, el estado de radio en vivo, terminales AT y USSD, SMS, WiFi Calling, gestión de eSIM, selección de red, enrutamiento por proxy, notificaciones, registros de auditoría y automatización de versiones.
El backend está escrito en Go, la interfaz está construida con React y TypeScript, y el frontend de producción está incrustado en el binario de Go. Un único ejecutable contiene la aplicación web y utiliza SQLite para el estado persistente.
<p align="center">
<img src="../img/image.png">
<img src="../img/image-1.png">
</p>
## Funcionalidades
| Área | Lo que proporciona Vocat |
| --- | --- |
| Gestión de dispositivos | Descubrimiento serie/USB automático, soporte para múltiples módems, nombres de dispositivo amigables, actualizaciones en vivo de la vista general, reinicio del módulo, modo avión y controles del modo de red USB. |
| Radio y red | Estado de registro, operador, métricas de señal, RSRP/RSRQ/SINR, modo de red, banda, canal, búsqueda de operadores y selección de red automática o manual. |
| AT y USSD | Terminal AT interactivo, historial de comandos, respuestas sin procesar del módem, flujos de inicio/continuación/cancelación de USSD y reporte claro de errores del módem. |
| SMS | Envío directo de SMS celulares e IMS, sincronización entrante, manejo multiparte, informes de entrega, historial de conversaciones, estado de no leído, marcas de tiempo y estado de entrega por mensaje. |
| WiFi Calling | Establecimiento de túnel IKEv2/ePDG, autenticación EAP-AKA, registro IMS, SMS IMS, controles de reconexión, diagnósticos de estado y enrutamiento por dispositivo. |
| eSIM y eUICC | Descubrimiento de eUICC, EID e información de producción, metadatos de certificados, inventario multi-eUICC, lista de perfiles instalados, operaciones de habilitar/deshabilitar/cambiar, y operaciones de descarga, renombrado y eliminación cuando la tarjeta lo admite. |
| Política de tarjeta | Comportamiento de WiFi Calling y modo avión basado en ICCID con aplicación inmediata de la política. |
| Enrutamiento por proxy | Enrutamiento SOCKS ascendente, vinculaciones de dispositivos, reglas por país, comprobaciones de accesibilidad TCP y comprobaciones UDP Associate para las rutas de datos de WiFi Calling. |
| Notificaciones | Reenvío de nuevos SMS entrantes a través de Telegram, Bark, correo electrónico, Pushplus y webhooks firmados. Cada SMS se entrega como una notificación individual. |
| Bot de Telegram | Estado del dispositivo, lista y cambio de perfiles instalados, controles de WiFi Calling y envío de SMS. Las acciones sensibles requieren confirmación del administrador. |
| Operaciones | Autenticación, protección CSRF, políticas de acceso, eventos de auditoría, registros en vivo, retención de registros, comprobaciones de salud, diseño adaptable, modo oscuro e interfaz de usuario en inglés/chino. |
| Distribución | Binarios estáticos de Linux, script de instalación systemd, autoactualización con verificación SHA-256, imagen Docker, publicación en GHCR y compilaciones de versión de GitHub Actions. |
## Hardware compatible
Vocat está dirigido a módulos Quectel basados en Qualcomm que exponen interfaces AT, QMI, serie y de red USB compatibles, incluyendo:
- Quectel EC20
- Quectel EC25
- Familia Quectel EG25
- Módulos EG600 compatibles y relacionados
Las funciones disponibles dependen del firmware del módulo, la composición USB, las capacidades SIM/eSIM, los controladores del host, la red de radio y la configuración del operador.
## Instalación
### Instalación en Linux con un clic
Como root (incluyendo OpenWrt/Kwrt, donde `sudo` normalmente está ausente):
```bash
curl -fsSL https://raw.githubusercontent.com/MengMengCode/VoCat/master/scripts/install.sh | bash
```
Desde un usuario normal en una distribución con sudo:
```bash
curl -fsSL https://raw.githubusercontent.com/MengMengCode/VoCat/master/scripts/install.sh | sudo bash
```
Comprobar los prerrequisitos de VoWiFi/XFRM del host sin instalar VoCat:
```bash
curl -fsSL https://raw.githubusercontent.com/MengMengCode/VoCat/master/scripts/install.sh | bash -s -- --check-env
```
Instalar una versión específica:
```bash
curl -fsSL https://raw.githubusercontent.com/MengMengCode/VoCat/master/scripts/install.sh -o install.sh
sudo bash install.sh 0.0.2
```
VoWiFi IMS requiere Linux XFRM/IPsec. En OpenWrt/Kwrt el instalador intenta
instalar los paquetes coincidentes `ip-full`, `kmod-ipsec`, `kmod-ipsec4/6`,
`kmod-crypto-authenc`, AES-CBC y SHA1 desde el propio feed del firmware.
Si no hay módulos de kernel coincidentes disponibles, use un firmware que los incluya;
nunca fuerce la instalación de kmods compilados para un kernel diferente.
El instalador:
- detecta `amd64`, `386`, `arm64`, `aarch64` o `armv7`;
- descarga el binario de GitHub Release correspondiente;
- lo verifica contra `SHA256SUMS`;
- instala Vocat en `/opt/vocat`;
- crea un servicio systemd reforzado con el acceso a hardware y red requerido por Vocat;
- almacena la configuración en tiempo de ejecución en `/etc/vocat/env`;
- genera una contraseña de administrador inicial aleatoria en la primera instalación.
Después de la instalación, abra:
```text
http://<dirección-del-servidor>:7575
```
### Instalación manual del binario
Descargue el binario correspondiente y `SHA256SUMS` desde GitHub Releases:
| Plataforma | Archivo de versión |
| --- | --- |
| Linux x86-64 | `vocat-linux-amd64` |
| Linux x86 32 bits | `vocat-linux-386` |
| Linux ARM64 | `vocat-linux-arm64` |
| Linux AArch64 | `vocat-linux-aarch64` |
| Linux ARMv7 | `vocat-linux-armv7` |
Verifíquelo e instálelo:
```bash
sha256sum -c SHA256SUMS --ignore-missing
sudo install -d -m 0755 /opt/vocat/bin /opt/vocat/data
sudo install -m 0755 vocat-linux-amd64 /opt/vocat/bin/vocat
sudo env \
VOCAT_DATABASE_PATH=/opt/vocat/data/vocat.db \
VOCAT_ADMIN_PASSWORD=change-this-password \
/opt/vocat/bin/vocat serve
```
Este comando manual ejecuta Vocat en primer plano. Use `vocat serve` para que el
proceso inicie el servidor directamente; ejecutar `vocat` sin argumentos como root
en un TTY abre en su lugar el menú de gestión interactivo. Use el instalador de
un clic cuando se requiera un servicio systemd gestionado y reinicio automático.
### Docker
Para un host Linux que debe descubrir cada módem Quectel compatible conectado y
seguir viendo los eventos de conexión en caliente USB, ejecute Vocat en modo de acceso a hardware:
```bash
docker pull ghcr.io/mengmengcode/vocat:latest
docker run -d \
--name vocat \
--restart unless-stopped \
--network host \
--privileged \
--user 0:0 \
-e VOCAT_ADMIN_PASSWORD=change-this-password \
-v vocat-data:/opt/vocat/data \
-v /dev:/dev \
-v /sys:/sys:ro \
ghcr.io/mengmengcode/vocat:latest
```
Abra `http://<dirección-del-servidor>:7575` después de que el contenedor se inicie. La red del host
es necesaria para que las interfaces de red QMI permanezcan visibles para Vocat, mientras que el
acceso privilegiado a dispositivos es necesario para los puertos serie, los nodos de control QMI,
las interfaces TUN, la configuración de red y los dispositivos añadidos después de que el contenedor
se inicie. El montaje bind de `/dev` hace visibles los nuevos nodos `ttyUSB*`, `ttyACM*` y `cdc-wdm*`
sin recrear el contenedor.
Este modo otorga intencionadamente a Vocat un amplio acceso a los dispositivos y a la pila de red
del host. Úselo solo en un host Linux de confianza. El descubrimiento automático identifica
actualmente los módems USB Quectel compatibles (ID de fabricante USB `2c7c`), no marcas de módems
arbitrarias. Mapear solo nodos individuales con `--device`, como `/dev/ttyUSB2` y `/dev/cdc-wdm0`,
limita el contenedor a esos nodos fijos y no proporciona un descubrimiento completo de múltiples
dispositivos o de conexión en caliente.
La imagen GHCR se publica para `linux/amd64` y `linux/arm64`.
## Configuración
Vocat lee un archivo de configuración JSON opcional desde `VOCAT_CONFIG` y luego aplica las variables de entorno `VOCAT_*`. Las variables de entorno tienen prioridad.
| Variable de entorno | Predeterminado | Descripción |
| --- | --- | --- |
| `VOCAT_ADDR` | `0.0.0.0:7575` | Dirección de escucha HTTP. |
| `VOCAT_DATABASE_PATH` | `./data/vocat.db` | Ruta de la base de datos SQLite. |
| `VOCAT_ADMIN_USERNAME` | `admin` | Nombre de usuario administrador inicial. |
| `VOCAT_ADMIN_PASSWORD` | `admin` | Contraseña de administrador inicial. Cámbiela antes de exponer el servicio. |
| `VOCAT_SESSION_TTL` | `24h` | Duración de la sesión de autenticación. |
| `VOCAT_SECURE_COOKIES` | `false` | Marca las cookies de sesión como seguras cuando se usa HTTPS. |
| `VOCAT_SHUTDOWN_TIMEOUT` | `10s` | Tiempo de espera de apagado ordenado. |
| `VOCAT_MAX_REQUEST_BODY_BYTES` | `1048576` | Tamaño máximo del cuerpo de solicitud de la API. |
| `VOCAT_REPO` | `MengMengCode/VoCat` | Repositorio de GitHub de confianza usado por el autoactualizador, en formato `owner/name`. |
| `GITHUB_TOKEN` | vacío | Token de GitHub opcional para repositorios privados o límites de API más altos. |
No almacene tokens de Telegram, contraseñas SMTP, secretos de webhook, credenciales SIM u otros datos privados en el repositorio. Configúrelos a través de los ajustes de la aplicación o archivos de entorno protegidos.
## Bot de Telegram
Cuando las notificaciones de Telegram están habilitadas y tanto el Chat ID como el Admin ID están configurados, el bot admite:
```text
/status [dispositivo]
/esim <dispositivo>
/switch <dispositivo> <iccid>
/wfc <dispositivo> <status|on|off|reconnect>
/sms <dispositivo> <número> <mensaje>
```
El cambio de perfil y el envío de SMS usan botones de confirmación de un solo uso. El bot no expone comandos de descarga, eliminación o renombrado de eSIM.
## Actualización
Comprobar si hay una GitHub Release más reciente:
```bash
vocat update --check --repo MengMengCode/VoCat
```
Instalar la última versión:
```bash
sudo vocat update --repo MengMengCode/VoCat
```
El actualizador descarga el binario que coincide con la arquitectura Linux actual, lo verifica con el `SHA256SUMS` publicado, reemplaza el ejecutable de forma atómica y reinicia el servicio systemd `vocat` cuando está disponible.
Para instalaciones Docker:
```bash
docker pull ghcr.io/mengmengcode/vocat:latest
```
Recrear el contenedor después de descargar la nueva imagen.
## Desarrollo
Requisitos:
- Go 1.25 o más reciente
- Node.js 20 o más reciente
- npm
Ejecutar el servidor de desarrollo del frontend:
```bash
cd web
npm install
npm run dev
```
Compilar el frontend incrustado e iniciar el backend:
```bash
cd web
npm run build
cd ..
go run ./cmd/vocat
```
Ejecutar todas las pruebas:
```bash
go test ./...
```
Compilar un binario de producción:
```bash
go build -trimpath -ldflags "-s -w" -o vocat ./cmd/vocat
```
## Automatización de versiones
Hacer push de una etiqueta de versión inicia dos flujos de trabajo de GitHub Actions:
- `release-binaries` compila y publica los binarios `amd64`, `386`, `arm64`, `aarch64` y `armv7` más `SHA256SUMS`.
- `docker` compila y publica una imagen multiarquitectura en GitHub Container Registry.
```bash
git tag v0.2.0
git push origin v0.2.0
```
## Estructura del proyecto
```text
cmd/vocat/ Punto de entrada de la aplicación y CLI
internal/device/ Descubrimiento de módems y control de dispositivos
internal/modem/ Sesión AT y manejo de respuestas
internal/server/ API HTTP, notificaciones y servidor web incrustado
internal/store/ Persistencia SQLite
internal/update/ Autoactualizador de GitHub Release
internal/vowifi/ Runtime de IKE, EAP-AKA, IMS y WiFi Calling
scripts/install.sh Instalador y actualizador de Linux
web/src/ Frontend en React y TypeScript
.github/workflows/ Automatización de versiones de binarios y Docker
```
## Uso responsable
Las operaciones con módems celulares y eSIM pueden afectar el servicio del abonado, los perfiles almacenados, el registro de red y el estado del hardware. Mantenga copias de seguridad, revise con cuidado las acciones destructivas y use el software solo en entornos legales donde tenga permiso para operar el hardware y los recursos de red conectados.
Vocat no elude la autenticación del operador, la política de red, la seguridad del hardware ni los requisitos de confianza de eSIM. El soporte de una operación significa que Vocat puede solicitarla al módem o al eUICC; el dispositivo, el perfil, la red o el operador aún pueden rechazarla.
## Contribuir
Las incidencias y pull requests son bienvenidas. Mantenga los cambios enfocados, incluya pruebas cuando sea práctico, evite confirmar credenciales o datos de abonados, y documente claramente el comportamiento específico del hardware.
Antes de enviar un cambio:
```bash
go test ./...
cd web && npm run build
```
## Agradecimientos
- [Nodeseek.com](https://www.nodeseek.com) — Una comunidad dedicada a los servidores
- [Linux.do](https://linux.do) — Una comunidad tecnológica inspiradora
- [iniwex5](https://github.com/iniwex5) — Guías de estilo y funcionalidad
## Invítame a un café
| Red | Dirección |
| ------- | ------- |
| USDT-TRON (TRC20) | `TQQAbboBoU8h5xX4YCA1rqWJU2WjK3seSg` |
| USDT-BSC (BEP20) | `0xdbfcd4a462550d6ff06d09cbd89026c6b145d9c4` |
| USDT-Polygon | `0xdbfcd4a462550d6ff06d09cbd89026c6b145d9c4` |
## Licencia
Consulte [LICENSE](../LICENSE).
[![MengMengCode/VoCat Star History](https://mengmeng.meteor-history.com/api/embed/MengMengCode/VoCat.svg?sig=sdeXRVxAoY3yLWgXL7JViY2USYIN3t9neJ6ScPvgUAo&theme=light&style=xkcd&color=dd4528&background=ffffff&textColor=000000&width=900&height=600&lineWidth=3&showTitle=true&showLegend=true&showDots=false&v=0.0.14)](https://meteor-history.com)
+336
View File
@@ -0,0 +1,336 @@
<p align="center">
<img src="../web/public/favicon.svg" width="96" alt="Vocat">
</p>
<h1 align="center">VoCat</h1>
<p align="center">
<img alt="Go" src="https://img.shields.io/badge/Go-1.25-00ADD8?style=flat-square&logo=go&logoColor=white">
<img alt="React" src="https://img.shields.io/badge/React-19-61DAFB?style=flat-square&logo=react&logoColor=111111">
<img alt="TypeScript" src="https://img.shields.io/badge/TypeScript-5.8-3178C6?style=flat-square&logo=typescript&logoColor=white">
<img alt="Vite" src="https://img.shields.io/badge/Vite-7-646CFF?style=flat-square&logo=vite&logoColor=white">
<img alt="Tailwind CSS" src="https://img.shields.io/badge/Tailwind_CSS-3-06B6D4?style=flat-square&logo=tailwindcss&logoColor=white">
<img alt="SQLite" src="https://img.shields.io/badge/SQLite-Embedded-003B57?style=flat-square&logo=sqlite&logoColor=white">
</p>
<p align="center">
<img alt="Linux" src="https://img.shields.io/badge/Linux-amd64_%7C_386_%7C_arm64_%7C_aarch64_%7C_armv7-FCC624?style=flat-square&logo=linux&logoColor=111111">
<img alt="Docker" src="https://img.shields.io/badge/Docker-Multi--Arch-2496ED?style=flat-square&logo=docker&logoColor=white">
<img alt="WiFi Calling" src="https://img.shields.io/badge/WiFi_Calling-IMS_SMS-7B1FA2?style=flat-square">
<img alt="eSIM" src="https://img.shields.io/badge/eSIM-LPA_%2F_eUICC-009688?style=flat-square">
<img alt="Telegram" src="https://img.shields.io/badge/Telegram-Bot-26A5E4?style=flat-square&logo=telegram&logoColor=white">
<img alt="GitHub Actions" src="https://img.shields.io/badge/GitHub_Actions-Release-2088FF?style=flat-square&logo=githubactions&logoColor=white">
</p>
[English](../README.md) | [العربية](README.ar.md) | [简体中文](README.zh-CN.md) | [繁體中文](README.zh-TW.md) | **Français** | [Русский](README.ru.md) | [Español](README.es.md) | [日本語](README.ja.md)
Vocat est un panneau de contrôle web open-source et une boîte à outils d'ingénierie pour les modems cellulaires Quectel de classe EC20/EC25. Il réunit, dans un service autonome unique, la découverte de modems, l'état radio en direct, les terminaux AT et USSD, les SMS, la WiFi Calling, la gestion eSIM, la sélection de réseau, le routage par proxy, les notifications, les journaux d'audit et l'automatisation des versions.
Le backend est écrit en Go, l'interface est construite avec React et TypeScript, et le frontend de production est intégré dans le binaire Go. Un seul exécutable contient l'application web et utilise SQLite pour l'état persistant.
<p align="center">
<img src="../img/image.png">
<img src="../img/image-1.png">
</p>
## Fonctionnalités
| Domaine | Ce que Vocat fournit |
| --- | --- |
| Gestion des appareils | Découverte série/USB automatique, prise en charge de plusieurs modems, noms d'appareils conviviaux, mises à jour en direct de la vue d'ensemble, redémarrage du module, mode avion et contrôles du mode réseau USB. |
| Radio et réseau | État d'enregistrement, opérateur, métriques de signal, RSRP/RSRQ/SINR, mode réseau, bande, canal, recherche d'opérateurs et sélection de réseau automatique ou manuelle. |
| AT et USSD | Terminal AT interactif, historique des commandes, réponses brutes du modem, flux de démarrage/poursuite/annulation USSD et rapport d'erreurs modem clair. |
| SMS | Envoi direct de SMS cellulaires et IMS, synchronisation entrante, gestion des messages multiparties, rapports de livraison, historique des conversations, état non lu, horodatages et statut de livraison par message. |
| WiFi Calling | Établissement de tunnel IKEv2/ePDG, authentification EAP-AKA, enregistrement IMS, SMS IMS, contrôles de reconnexion, diagnostics d'état et routage par appareil. |
| eSIM et eUICC | Découverte eUICC, EID et informations de production, métadonnées de certificat, inventaire multi-eUICC, liste des profils installés, opérations d'activation/désactivation/commutation, ainsi que téléchargement, renommage et suppression lorsque la carte le permet. |
| Politique de carte | Comportement WiFi Calling et mode avion basé sur l'ICCID avec application immédiate de la politique. |
| Routage par proxy | Routage SOCKS amont, liaisons d'appareils, règles par pays, vérifications d'accessibilité TCP et vérifications UDP Associate pour les chemins de données WiFi Calling. |
| Notifications | Transfert des nouveaux SMS entrants via Telegram, Bark, e-mail, Pushplus et webhooks signés. Chaque SMS est livré comme une notification individuelle. |
| Bot Telegram | État de l'appareil, liste et commutation des profils installés, contrôles WiFi Calling et envoi de SMS. Les actions sensibles nécessitent une confirmation de l'administrateur. |
| Exploitation | Authentification, protection CSRF, politiques d'accès, événements d'audit, journaux en direct, rétention des journaux, vérifications de santé, mise en page réactive, mode sombre et interface utilisateur en anglais/chinois. |
| Distribution | Binaires Linux statiques, script d'installation systemd, auto-mise à jour avec vérification SHA-256, image Docker, publication GHCR et builds de version GitHub Actions. |
## Matériel pris en charge
Vocat cible les modules Quectel à base Qualcomm qui exposent des interfaces AT, QMI, série et réseau USB compatibles, notamment :
- Quectel EC20
- Quectel EC25
- Famille Quectel EG25
- Modules EG600 compatibles et apparentés
Les fonctionnalités disponibles dépendent du firmware du module, de la composition USB, des capacités SIM/eSIM, des pilotes hôtes, du réseau radio et de la configuration de l'opérateur.
## Installation
### Installation Linux en un clic
En tant que root (y compris OpenWrt/Kwrt, où `sudo` est normalement absent) :
```bash
curl -fsSL https://raw.githubusercontent.com/MengMengCode/VoCat/master/scripts/install.sh | bash
```
Depuis un utilisateur normal sur une distribution disposant de sudo :
```bash
curl -fsSL https://raw.githubusercontent.com/MengMengCode/VoCat/master/scripts/install.sh | sudo bash
```
Vérifier les prérequis VoWiFi/XFRM de l'hôte sans installer VoCat :
```bash
curl -fsSL https://raw.githubusercontent.com/MengMengCode/VoCat/master/scripts/install.sh | bash -s -- --check-env
```
Installer une version spécifique :
```bash
curl -fsSL https://raw.githubusercontent.com/MengMengCode/VoCat/master/scripts/install.sh -o install.sh
sudo bash install.sh 0.0.2
```
VoWiFi IMS nécessite Linux XFRM/IPsec. Sur OpenWrt/Kwrt, le programme d'installation tente
d'installer les paquets correspondants `ip-full`, `kmod-ipsec`, `kmod-ipsec4/6`,
`kmod-crypto-authenc`, AES-CBC et SHA1 depuis le dépôt du firmware lui-même.
Si des modules noyau correspondants ne sont pas disponibles, utilisez un firmware qui les inclut ;
ne forcez jamais l'installation de kmods compilés pour un noyau différent.
Le programme d'installation :
- détecte `amd64`, `386`, `arm64`, `aarch64` ou `armv7` ;
- télécharge le binaire GitHub Release correspondant ;
- le vérifie par rapport à `SHA256SUMS` ;
- installe Vocat sous `/opt/vocat` ;
- crée un service systemd renforcé disposant des accès matériel et réseau requis par Vocat ;
- stocke la configuration d'exécution dans `/etc/vocat/env` ;
- génère un mot de passe administrateur initial aléatoire lors de la première installation.
Après l'installation, ouvrez :
```text
http://<adresse-du-serveur>:7575
```
### Installation manuelle du binaire
Téléchargez le binaire correspondant et `SHA256SUMS` depuis GitHub Releases :
| Plateforme | Fichier de version |
| --- | --- |
| Linux x86-64 | `vocat-linux-amd64` |
| Linux x86 32 bits | `vocat-linux-386` |
| Linux ARM64 | `vocat-linux-arm64` |
| Linux AArch64 | `vocat-linux-aarch64` |
| Linux ARMv7 | `vocat-linux-armv7` |
Vérifiez-le et installez-le :
```bash
sha256sum -c SHA256SUMS --ignore-missing
sudo install -d -m 0755 /opt/vocat/bin /opt/vocat/data
sudo install -m 0755 vocat-linux-amd64 /opt/vocat/bin/vocat
sudo env \
VOCAT_DATABASE_PATH=/opt/vocat/data/vocat.db \
VOCAT_ADMIN_PASSWORD=change-this-password \
/opt/vocat/bin/vocat serve
```
Cette commande manuelle exécute Vocat au premier plan. Utilisez `vocat serve` pour que le
processus démarre directement le serveur ; exécuter `vocat` sans argument en tant que root
sur un TTY ouvre plutôt le menu de gestion interactif. Utilisez le programme d'installation
en un clic lorsqu'un service systemd géré et un redémarrage automatique sont requis.
### Docker
Pour un hôte Linux qui doit découvrir chaque modem Quectel pris en charge connecté et
continuer à voir les événements de branchement à chaud USB, exécutez Vocat en mode d'accès matériel :
```bash
docker pull ghcr.io/mengmengcode/vocat:latest
docker run -d \
--name vocat \
--restart unless-stopped \
--network host \
--privileged \
--user 0:0 \
-e VOCAT_ADMIN_PASSWORD=change-this-password \
-v vocat-data:/opt/vocat/data \
-v /dev:/dev \
-v /sys:/sys:ro \
ghcr.io/mengmengcode/vocat:latest
```
Ouvrez `http://<adresse-du-serveur>:7575` après le démarrage du conteneur. Le réseau de l'hôte
est requis pour que les interfaces réseau QMI restent visibles par Vocat, tandis que l'accès
privilégié aux périphériques est requis pour les ports série, les nœuds de contrôle QMI, les
interfaces TUN, la configuration réseau et les périphériques ajoutés après le démarrage du
conteneur. Le montage bind de `/dev` rend les nouveaux nœuds `ttyUSB*`, `ttyACM*` et `cdc-wdm*`
visibles sans recréer le conteneur.
Ce mode donne intentionnellement à Vocat un large accès aux périphériques et à la pile réseau
de l'hôte. Ne l'utilisez que sur un hôte Linux de confiance. La découverte automatique
identifie actuellement les modems USB Quectel pris en charge (ID fabricant USB `2c7c`), et non
des marques de modems arbitraires. Le mappage de nœuds individuels uniquement avec `--device`,
comme `/dev/ttyUSB2` et `/dev/cdc-wdm0`, limite le conteneur à ces nœuds fixes et ne fournit
pas une découverte multi-périphériques ou à chaud complète.
L'image GHCR est publiée pour `linux/amd64` et `linux/arm64`.
## Configuration
Vocat lit un fichier de configuration JSON optionnel depuis `VOCAT_CONFIG`, puis applique les variables d'environnement `VOCAT_*`. Les variables d'environnement ont la priorité.
| Variable d'environnement | Par défaut | Description |
| --- | --- | --- |
| `VOCAT_ADDR` | `0.0.0.0:7575` | Adresse d'écoute HTTP. |
| `VOCAT_DATABASE_PATH` | `./data/vocat.db` | Chemin de la base de données SQLite. |
| `VOCAT_ADMIN_USERNAME` | `admin` | Nom d'utilisateur administrateur initial. |
| `VOCAT_ADMIN_PASSWORD` | `admin` | Mot de passe administrateur initial. Modifiez-le avant d'exposer le service. |
| `VOCAT_SESSION_TTL` | `24h` | Durée de vie de la session d'authentification. |
| `VOCAT_SECURE_COOKIES` | `false` | Marque les cookies de session comme sécurisés lorsque HTTPS est utilisé. |
| `VOCAT_SHUTDOWN_TIMEOUT` | `10s` | Délai d'arrêt gracieux. |
| `VOCAT_MAX_REQUEST_BODY_BYTES` | `1048576` | Taille maximale du corps de requête API. |
| `VOCAT_REPO` | `MengMengCode/VoCat` | Dépôt GitHub de confiance utilisé par l'auto-updater, au format `owner/name`. |
| `GITHUB_TOKEN` | vide | Jeton GitHub optionnel pour les dépôts privés ou des limites d'API plus élevées. |
Ne stockez pas de jetons Telegram, mots de passe SMTP, secrets de webhook, identifiants SIM ou autres données privées dans le dépôt. Configurez-les via les paramètres de l'application ou des fichiers d'environnement protégés.
## Bot Telegram
Lorsque les notifications Telegram sont activées et que le Chat ID et l'Admin ID sont configurés, le bot prend en charge :
```text
/status [appareil]
/esim <appareil>
/switch <appareil> <iccid>
/wfc <appareil> <status|on|off|reconnect>
/sms <appareil> <numéro> <message>
```
La commutation de profil et l'envoi de SMS utilisent des boutons de confirmation à usage unique. Le bot n'expose pas les commandes de téléchargement, de suppression ou de renommage eSIM.
## Mise à jour
Vérifier l'existence d'une GitHub Release plus récente :
```bash
vocat update --check --repo MengMengCode/VoCat
```
Installer la dernière version :
```bash
sudo vocat update --repo MengMengCode/VoCat
```
L'updater télécharge le binaire correspondant à l'architecture Linux actuelle, le vérifie avec le `SHA256SUMS` publié, remplace l'exécutable de manière atomique et redémarre le service systemd `vocat` lorsqu'il est disponible.
Pour les installations Docker :
```bash
docker pull ghcr.io/mengmengcode/vocat:latest
```
Recréez le conteneur après avoir tiré la nouvelle image.
## Développement
Prérequis :
- Go 1.25 ou plus récent
- Node.js 20 ou plus récent
- npm
Lancer le serveur de développement frontend :
```bash
cd web
npm install
npm run dev
```
Construire le frontend intégré et démarrer le backend :
```bash
cd web
npm run build
cd ..
go run ./cmd/vocat
```
Exécuter tous les tests :
```bash
go test ./...
```
Construire un binaire de production :
```bash
go build -trimpath -ldflags "-s -w" -o vocat ./cmd/vocat
```
## Automatisation des versions
Pousser un tag de version déclenche deux workflows GitHub Actions :
- `release-binaries` construit et publie les binaires `amd64`, `386`, `arm64`, `aarch64` et `armv7` ainsi que `SHA256SUMS`.
- `docker` construit et publie une image multi-architecture vers GitHub Container Registry.
```bash
git tag v0.2.0
git push origin v0.2.0
```
## Structure du projet
```text
cmd/vocat/ Point d'entrée de l'application et CLI
internal/device/ Découverte de modems et contrôle des appareils
internal/modem/ Session AT et gestion des réponses
internal/server/ API HTTP, notifications et serveur web intégré
internal/store/ Persistance SQLite
internal/update/ Auto-updater GitHub Release
internal/vowifi/ Runtime IKE, EAP-AKA, IMS et WiFi Calling
scripts/install.sh Installeur et updater Linux
web/src/ Frontend React et TypeScript
.github/workflows/ Automatisation des versions binaires et Docker
```
## Utilisation responsable
Les opérations sur les modems cellulaires et les eSIM peuvent affecter le service de l'abonné, les profils stockés, l'enregistrement réseau et l'état du matériel. Effectuez des sauvegardes, examinez attentivement les actions destructrices et n'utilisez le logiciel que dans des environnements légaux où vous êtes autorisé à exploiter le matériel et les ressources réseau connectés.
Vocat ne contourne ni l'authentification de l'opérateur, ni la politique réseau, ni la sécurité matérielle, ni les exigences de confiance eSIM. La prise en charge d'une opération signifie que Vocat peut la demander au modem ou à l'eUICC ; l'appareil, le profil, le réseau ou l'opérateur peut toujours la refuser.
## Contribution
Les issues et pull requests sont les bienvenues. Gardez des changements ciblés, incluez des tests lorsque c'est possible, évitez de committer des identifiants ou des données d'abonnés, et documentez clairement les comportements spécifiques au matériel.
Avant de soumettre un changement :
```bash
go test ./...
cd web && npm run build
```
## Remerciements
- [Nodeseek.com](https://www.nodeseek.com) — Une communauté dédiée aux serveurs
- [Linux.do](https://linux.do) — Une communauté technologique inspirante
- [iniwex5](https://github.com/iniwex5) — Directives de style et de fonctionnalité
## Offrez-moi un café
| Réseau | Adresse |
| ------- | ------- |
| USDT-TRON (TRC20) | `TQQAbboBoU8h5xX4YCA1rqWJU2WjK3seSg` |
| USDT-BSC (BEP20) | `0xdbfcd4a462550d6ff06d09cbd89026c6b145d9c4` |
| USDT-Polygon | `0xdbfcd4a462550d6ff06d09cbd89026c6b145d9c4` |
## Licence
Voir [LICENSE](../LICENSE).
[![MengMengCode/VoCat Star History](https://mengmeng.meteor-history.com/api/embed/MengMengCode/VoCat.svg?sig=sdeXRVxAoY3yLWgXL7JViY2USYIN3t9neJ6ScPvgUAo&theme=light&style=xkcd&color=dd4528&background=ffffff&textColor=000000&width=900&height=600&lineWidth=3&showTitle=true&showLegend=true&showDots=false&v=0.0.14)](https://meteor-history.com)
+318
View File
@@ -0,0 +1,318 @@
<p align="center">
<img src="../web/public/favicon.svg" width="96" alt="Vocat">
</p>
<h1 align="center">VoCat</h1>
<p align="center">
<img alt="Go" src="https://img.shields.io/badge/Go-1.25-00ADD8?style=flat-square&logo=go&logoColor=white">
<img alt="React" src="https://img.shields.io/badge/React-19-61DAFB?style=flat-square&logo=react&logoColor=111111">
<img alt="TypeScript" src="https://img.shields.io/badge/TypeScript-5.8-3178C6?style=flat-square&logo=typescript&logoColor=white">
<img alt="Vite" src="https://img.shields.io/badge/Vite-7-646CFF?style=flat-square&logo=vite&logoColor=white">
<img alt="Tailwind CSS" src="https://img.shields.io/badge/Tailwind_CSS-3-06B6D4?style=flat-square&logo=tailwindcss&logoColor=white">
<img alt="SQLite" src="https://img.shields.io/badge/SQLite-Embedded-003B57?style=flat-square&logo=sqlite&logoColor=white">
</p>
<p align="center">
<img alt="Linux" src="https://img.shields.io/badge/Linux-amd64_%7C_386_%7C_arm64_%7C_aarch64_%7C_armv7-FCC624?style=flat-square&logo=linux&logoColor=111111">
<img alt="Docker" src="https://img.shields.io/badge/Docker-Multi--Arch-2496ED?style=flat-square&logo=docker&logoColor=white">
<img alt="WiFi Calling" src="https://img.shields.io/badge/WiFi_Calling-IMS_SMS-7B1FA2?style=flat-square">
<img alt="eSIM" src="https://img.shields.io/badge/eSIM-LPA_%2F_eUICC-009688?style=flat-square">
<img alt="Telegram" src="https://img.shields.io/badge/Telegram-Bot-26A5E4?style=flat-square&logo=telegram&logoColor=white">
<img alt="GitHub Actions" src="https://img.shields.io/badge/GitHub_Actions-Release-2088FF?style=flat-square&logo=githubactions&logoColor=white">
</p>
[English](../README.md) | [العربية](README.ar.md) | [简体中文](README.zh-CN.md) | [繁體中文](README.zh-TW.md) | [Français](README.fr.md) | [Русский](README.ru.md) | [Español](README.es.md) | **日本語**
Vocat は、Quectel EC20/EC25 クラスのセルラーモデム向けのオープンソース Web コントロールパネル兼エンジニアリングツールキットです。モデムの検出、ライブの無線ステータス、AT / USSD ターミナル、SMS、WiFi Calling、eSIM 管理、ネットワーク選択、プロキシルーティング、通知、監査ログ、リリース自動化を、自己完結型の単一サービスに統合しています。
バックエンドは Go で書かれ、インターフェースは React と TypeScript で構築され、本番フロントエンドは Go バイナリに埋め込まれています。単一の実行ファイルに Web アプリケーション全体が含まれ、永続的な状態には SQLite を使用します。
<p align="center">
<img src="../img/image.png">
<img src="../img/image-1.png">
</p>
## 機能
| 領域 | Vocat が提供する機能 |
| --- | --- |
| デバイス管理 | シリアル/USB の自動検出、複数モデムのサポート、わかりやすいデバイス名、概要のライブ更新、モジュールの再起動、機内モード、USB ネットワークモードの制御。 |
| 無線とネットワーク | 登録ステータス、オペレーター、信号指標、RSRP/RSRQ/SINR、ネットワークモード、バンド、チャネル、オペレータースキャン、自動または手動のネットワーク選択。 |
| AT と USSD | 対話型 AT ターミナル、コマンド履歴、モデムの生出力、USSD の開始/継続/キャンセルフロー、明確なモデムエラーレポート。 |
| SMS | セルラーおよび IMS SMS の直接送信、受信同期、マルチパート処理、配信レポート、会話履歴、未読状態、タイムスタンプ、メッセージごとの配信ステータス。 |
| WiFi Calling | IKEv2/ePDG トンネルの確立、EAP-AKA 認証、IMS 登録、IMS SMS、再接続制御、ステータス診断、デバイスごとのルーティング。 |
| eSIM と eUICC | eUICC の検出、EID と製造情報、証明書メタデータ、複数 eUICC のインベントリ、インストール済みプロファイルの一覧、有効化/無効化/切り替え操作、およびカードが対応している場合のダウンロード、名前変更、削除操作。 |
| カードポリシー | ICCID ベースの WiFi Calling および機内モードの動作で、ポリシーが即時に適用されます。 |
| プロキシルーティング | アップストリーム SOCKS ルーティング、デバイスバインディング、国別ルール、TCP 到達性チェック、WiFi Calling データパス向けの UDP Associate チェック。 |
| 通知 | Telegram、Bark、メール、Pushplus、署名付き Webhook を介した新着 SMS の転送。各 SMS は個別の通知として配信されます。 |
| Telegram ボット | デバイスステータス、インストール済みプロファイルの一覧と切り替え、WiFi Calling 制御、SMS 送信。機密性の高い操作には管理者の確認が必要です。 |
| 運用 | 認証、CSRF 保護、アクセスポリシー、監査イベント、ライブログ、ログ保持、ヘルスチェック、レスポンシブレイアウト、ダークモード、英語/中国語のアプリケーション UI。 |
| 配布 | 静的 Linux バイナリ、systemd インストールスクリプト、SHA-256 検証付きの自己更新、Docker イメージ、GHCR 公開、GitHub Actions リリースビルド。 |
## 対応ハードウェア
Vocat は、互換性のある AT、QMI、シリアル、USB ネットワークインターフェースを公開する Qualcomm ベースの Quectel モジュールを対象としています。対象には以下が含まれます:
- Quectel EC20
- Quectel EC25
- Quectel EG25 ファミリー
- 互換性のある EG600 および関連モジュール
利用可能な機能は、モジュールのファームウェア、USB 構成、SIM/eSIM の機能、ホストドライバー、無線ネットワーク、キャリア設定によって異なります。
## インストール
### ワンクリック Linux インストール
root として(`sudo` が通常存在しない OpenWrt/Kwrt を含む):
```bash
curl -fsSL https://raw.githubusercontent.com/MengMengCode/VoCat/master/scripts/install.sh | bash
```
sudo を持つディストリビューションの一般ユーザーから:
```bash
curl -fsSL https://raw.githubusercontent.com/MengMengCode/VoCat/master/scripts/install.sh | sudo bash
```
VoCat をインストールせずに、ホストの VoWiFi/XFRM 前提条件を確認する:
```bash
curl -fsSL https://raw.githubusercontent.com/MengMengCode/VoCat/master/scripts/install.sh | bash -s -- --check-env
```
特定のバージョンをインストールする:
```bash
curl -fsSL https://raw.githubusercontent.com/MengMengCode/VoCat/master/scripts/install.sh -o install.sh
sudo bash install.sh 0.0.2
```
VoWiFi IMS には Linux XFRM/IPsec が必要です。OpenWrt/Kwrt では、インストーラーはファームウェア自身のフィードから、一致する `ip-full``kmod-ipsec``kmod-ipsec4/6``kmod-crypto-authenc`、AES-CBC、SHA1 パッケージのインストールを試みます。一致するカーネルモジュールが利用できない場合は、それらを含むファームウェアを使用してください。別のカーネル向けにビルドされた kmod を強制的にインストールしてはいけません。
インストーラーは次を行います:
- `amd64``386``arm64``aarch64``armv7` を検出します;
- 一致する GitHub Release バイナリをダウンロードします;
- `SHA256SUMS` と照合して検証します;
- Vocat を `/opt/vocat` にインストールします;
- Vocat が必要とするハードウェアおよびネットワークアクセスを持つ強化された systemd サービスを作成します;
- 実行時設定を `/etc/vocat/env` に保存します;
- 初回インストール時にランダムな初期管理者パスワードを生成します。
インストール後、次を開きます:
```text
http://<サーバーアドレス>:7575
```
### 手動バイナリインストール
一致するバイナリと `SHA256SUMS` を GitHub Releases からダウンロードします:
| プラットフォーム | リリースファイル |
| --- | --- |
| Linux x86-64 | `vocat-linux-amd64` |
| Linux x86 32 ビット | `vocat-linux-386` |
| Linux ARM64 | `vocat-linux-arm64` |
| Linux AArch64 | `vocat-linux-aarch64` |
| Linux ARMv7 | `vocat-linux-armv7` |
検証してインストールします:
```bash
sha256sum -c SHA256SUMS --ignore-missing
sudo install -d -m 0755 /opt/vocat/bin /opt/vocat/data
sudo install -m 0755 vocat-linux-amd64 /opt/vocat/bin/vocat
sudo env \
VOCAT_DATABASE_PATH=/opt/vocat/data/vocat.db \
VOCAT_ADMIN_PASSWORD=change-this-password \
/opt/vocat/bin/vocat serve
```
この手動コマンドは Vocat をフォアグラウンドで実行します。プロセスがサーバーを直接起動するように `vocat serve` を使用してください。TTY で root として引数なしで `vocat` を実行すると、代わりに対話型管理メニューが開きます。管理対象の systemd サービスと自動再起動が必要な場合は、ワンクリックインストーラーを使用してください。
### Docker
接続されているすべてのサポート対象 Quectel モデムを検出し、USB ホットプラグイベントを継続的に認識する必要がある Linux ホストでは、Vocat をハードウェアアクセスモードで実行します:
```bash
docker pull ghcr.io/mengmengcode/vocat:latest
docker run -d \
--name vocat \
--restart unless-stopped \
--network host \
--privileged \
--user 0:0 \
-e VOCAT_ADMIN_PASSWORD=change-this-password \
-v vocat-data:/opt/vocat/data \
-v /dev:/dev \
-v /sys:/sys:ro \
ghcr.io/mengmengcode/vocat:latest
```
コンテナの起動後に `http://<サーバーアドレス>:7575` を開きます。QMI ネットワークインターフェースが Vocat から見えるようにするにはホストネットワークが必要であり、シリアルポート、QMI 制御ノード、TUN インターフェース、ネットワーク設定、コンテナ起動後に追加されたデバイスには特権デバイスアクセスが必要です。`/dev` バインドマウントにより、コンテナを再作成せずに新しい `ttyUSB*``ttyACM*``cdc-wdm*` ノードが見えるようになります。
このモードは意図的に Vocat にホストのデバイスとネットワークスタックへの広範なアクセスを付与します。信頼できる Linux ホストでのみ使用してください。自動検出は現在、サポート対象の Quectel USB モデム(USB ベンダー ID `2c7c`)のみを識別し、任意のモデムブランドは識別しません。`--device``/dev/ttyUSB2``/dev/cdc-wdm0` などの個別ノードのみをマッピングすると、コンテナはそれらの固定ノードに限定され、完全なマルチデバイスまたはホットプラグ検出は提供されません。
GHCR イメージは `linux/amd64``linux/arm64` 向けに公開されています。
## 設定
Vocat は `VOCAT_CONFIG` からオプションの JSON 設定ファイルを読み込み、次に `VOCAT_*` 環境変数を適用します。環境変数が優先されます。
| 環境変数 | デフォルト | 説明 |
| --- | --- | --- |
| `VOCAT_ADDR` | `0.0.0.0:7575` | HTTP リッスンアドレス。 |
| `VOCAT_DATABASE_PATH` | `./data/vocat.db` | SQLite データベースパス。 |
| `VOCAT_ADMIN_USERNAME` | `admin` | 初期管理者ユーザー名。 |
| `VOCAT_ADMIN_PASSWORD` | `admin` | 初期管理者パスワード。サービスを公開する前に変更してください。 |
| `VOCAT_SESSION_TTL` | `24h` | 認証セッションの有効期間。 |
| `VOCAT_SECURE_COOKIES` | `false` | HTTPS 使用時にセッション Cookie をセキュアとしてマークします。 |
| `VOCAT_SHUTDOWN_TIMEOUT` | `10s` | グレースフルシャットダウンのタイムアウト。 |
| `VOCAT_MAX_REQUEST_BODY_BYTES` | `1048576` | API リクエストボディの最大サイズ。 |
| `VOCAT_REPO` | `MengMengCode/VoCat` | 自己更新機能が使用する信頼された GitHub リポジトリ(`owner/name` 形式)。 |
| `GITHUB_TOKEN` | 空 | プライベートリポジトリやより高い API レート制限のためのオプションの GitHub トークン。 |
Telegram トークン、SMTP パスワード、Webhook シークレット、SIM 認証情報、その他のプライベートデータをリポジトリに保存しないでください。アプリケーション設定または保護された環境ファイルを通じて設定してください。
## Telegram ボット
Telegram 通知が有効で、Chat ID と Admin ID の両方が設定されている場合、ボットは以下をサポートします:
```text
/status [デバイス]
/esim <デバイス>
/switch <デバイス> <iccid>
/wfc <デバイス> <status|on|off|reconnect>
/sms <デバイス> <番号> <メッセージ>
```
プロファイルの切り替えと SMS の送信には、ワンタイム確認ボタンが使用されます。ボットは eSIM のダウンロード、削除、名前変更コマンドを公開しません。
## 更新
より新しい GitHub Release を確認する:
```bash
vocat update --check --repo MengMengCode/VoCat
```
最新リリースをインストールする:
```bash
sudo vocat update --repo MengMengCode/VoCat
```
アップデーターは、現在の Linux アーキテクチャに一致するバイナリをダウンロードし、公開された `SHA256SUMS` で検証し、実行ファイルをアトミックに置き換え、利用可能な場合は `vocat` systemd サービスを再起動します。
Docker インストールの場合:
```bash
docker pull ghcr.io/mengmengcode/vocat:latest
```
新しいイメージをプルした後、コンテナを再作成します。
## 開発
要件:
- Go 1.25 以降
- Node.js 20 以降
- npm
フロントエンド開発サーバーを実行する:
```bash
cd web
npm install
npm run dev
```
埋め込みフロントエンドをビルドしてバックエンドを起動する:
```bash
cd web
npm run build
cd ..
go run ./cmd/vocat
```
すべてのテストを実行する:
```bash
go test ./...
```
本番バイナリをビルドする:
```bash
go build -trimpath -ldflags "-s -w" -o vocat ./cmd/vocat
```
## リリース自動化
バージョンタグをプッシュすると、2 つの GitHub Actions ワークフローが開始されます:
- `release-binaries``amd64``386``arm64``aarch64``armv7` バイナリと `SHA256SUMS` をビルドして公開します。
- `docker` はマルチアーキテクチャイメージをビルドして GitHub Container Registry に公開します。
```bash
git tag v0.2.0
git push origin v0.2.0
```
## プロジェクト構成
```text
cmd/vocat/ アプリケーションのエントリポイントと CLI
internal/device/ モデム検出とデバイス制御
internal/modem/ AT セッションと応答処理
internal/server/ HTTP API、通知、埋め込み Web サーバー
internal/store/ SQLite 永続化
internal/update/ GitHub Release 自己更新機能
internal/vowifi/ IKE、EAP-AKA、IMS、WiFi Calling ランタイム
scripts/install.sh Linux インストーラーとアップデーター
web/src/ React と TypeScript のフロントエンド
.github/workflows/ バイナリと Docker のリリース自動化
```
## 責任ある使用
セルラーモデムおよび eSIM の操作は、加入者サービス、保存されたプロファイル、ネットワーク登録、ハードウェア状態に影響を与える可能性があります。バックアップを保持し、破壊的な操作を慎重に確認し、接続されたハードウェアとネットワークリソースを操作することが許可されている合法的な環境でのみソフトウェアを使用してください。
Vocat は、キャリア認証、ネットワークポリシー、ハードウェアセキュリティ、eSIM の信頼要件をバイパスしません。操作のサポートは、Vocat がモデムまたは eUICC にそれを要求できることを意味します。デバイス、プロファイル、ネットワーク、またはキャリアがそれを拒否する場合があります。
## コントリビューション
Issue や Pull Request を歓迎します。変更は焦点を絞り、可能な場合はテストを含め、認証情報や加入者データをコミットしないようにし、ハードウェア固有の動作を明確に文書化してください。
変更を提出する前に:
```bash
go test ./...
cd web && npm run build
```
## 謝辞
- [Nodeseek.com](https://www.nodeseek.com) — サーバーに特化したコミュニティ
- [Linux.do](https://linux.do) — 刺激的なテックコミュニティ
- [iniwex5](https://github.com/iniwex5) — スタイルと機能のガイドライン
## コーヒーをおごってください
| ネットワーク | アドレス |
| ------- | ------- |
| USDT-TRON (TRC20) | `TQQAbboBoU8h5xX4YCA1rqWJU2WjK3seSg` |
| USDT-BSC (BEP20) | `0xdbfcd4a462550d6ff06d09cbd89026c6b145d9c4` |
| USDT-Polygon | `0xdbfcd4a462550d6ff06d09cbd89026c6b145d9c4` |
## ライセンス
[LICENSE](../LICENSE) を参照してください。
[![MengMengCode/VoCat Star History](https://mengmeng.meteor-history.com/api/embed/MengMengCode/VoCat.svg?sig=sdeXRVxAoY3yLWgXL7JViY2USYIN3t9neJ6ScPvgUAo&theme=light&style=xkcd&color=dd4528&background=ffffff&textColor=000000&width=900&height=600&lineWidth=3&showTitle=true&showLegend=true&showDots=false&v=0.0.14)](https://meteor-history.com)
+335
View File
@@ -0,0 +1,335 @@
<p align="center">
<img src="../web/public/favicon.svg" width="96" alt="Vocat">
</p>
<h1 align="center">VoCat</h1>
<p align="center">
<img alt="Go" src="https://img.shields.io/badge/Go-1.25-00ADD8?style=flat-square&logo=go&logoColor=white">
<img alt="React" src="https://img.shields.io/badge/React-19-61DAFB?style=flat-square&logo=react&logoColor=111111">
<img alt="TypeScript" src="https://img.shields.io/badge/TypeScript-5.8-3178C6?style=flat-square&logo=typescript&logoColor=white">
<img alt="Vite" src="https://img.shields.io/badge/Vite-7-646CFF?style=flat-square&logo=vite&logoColor=white">
<img alt="Tailwind CSS" src="https://img.shields.io/badge/Tailwind_CSS-3-06B6D4?style=flat-square&logo=tailwindcss&logoColor=white">
<img alt="SQLite" src="https://img.shields.io/badge/SQLite-Embedded-003B57?style=flat-square&logo=sqlite&logoColor=white">
</p>
<p align="center">
<img alt="Linux" src="https://img.shields.io/badge/Linux-amd64_%7C_386_%7C_arm64_%7C_aarch64_%7C_armv7-FCC624?style=flat-square&logo=linux&logoColor=111111">
<img alt="Docker" src="https://img.shields.io/badge/Docker-Multi--Arch-2496ED?style=flat-square&logo=docker&logoColor=white">
<img alt="WiFi Calling" src="https://img.shields.io/badge/WiFi_Calling-IMS_SMS-7B1FA2?style=flat-square">
<img alt="eSIM" src="https://img.shields.io/badge/eSIM-LPA_%2F_eUICC-009688?style=flat-square">
<img alt="Telegram" src="https://img.shields.io/badge/Telegram-Bot-26A5E4?style=flat-square&logo=telegram&logoColor=white">
<img alt="GitHub Actions" src="https://img.shields.io/badge/GitHub_Actions-Release-2088FF?style=flat-square&logo=githubactions&logoColor=white">
</p>
[English](../README.md) | [العربية](README.ar.md) | [简体中文](README.zh-CN.md) | [繁體中文](README.zh-TW.md) | [Français](README.fr.md) | **Русский** | [Español](README.es.md) | [日本語](README.ja.md)
Vocat — это веб-панель управления с открытым исходным кодом и набор инженерных инструментов для сотовых модемов Quectel класса EC20/EC25. Она объединяет в одном автономном сервисе обнаружение модемов, состояние радиосвязи в реальном времени, терминалы AT и USSD, SMS, WiFi Calling, управление eSIM, выбор сети, маршрутизацию через прокси, уведомления, журналы аудита и автоматизацию релизов.
Бэкенд написан на Go, интерфейс построен на React и TypeScript, а производственный фронтенд встроен в бинарный файл Go. Один исполняемый файл содержит веб-приложение и использует SQLite для постоянного хранения состояния.
<p align="center">
<img src="../img/image.png">
<img src="../img/image-1.png">
</p>
## Возможности
| Область | Что предоставляет Vocat |
| --- | --- |
| Управление устройствами | Автоматическое обнаружение по последовательному порту/USB, поддержка нескольких модемов, понятные имена устройств, обновление обзора в реальном времени, перезапуск модуля, авиарежим и управление режимом USB-сети. |
| Радио и сеть | Статус регистрации, оператор, метрики сигнала, RSRP/RSRQ/SINR, режим сети, диапазон, канал, сканирование операторов и автоматический или ручной выбор сети. |
| AT и USSD | Интерактивный AT-терминал, история команд, необработанные ответы модема, потоки запуска/продолжения/отмены USSD и понятные сообщения об ошибках модема. |
| SMS | Прямая отправка сотовых и IMS SMS, входящая синхронизация, обработка составных сообщений, отчёты о доставке, история диалогов, статус непрочитанных, метки времени и статус доставки каждого сообщения. |
| WiFi Calling | Установка туннеля IKEv2/ePDG, аутентификация EAP-AKA, регистрация IMS, IMS SMS, управление переподключением, диагностика состояния и маршрутизация по устройствам. |
| eSIM и eUICC | Обнаружение eUICC, EID и производственная информация, метаданные сертификатов, инвентарь нескольких eUICC, список установленных профилей, операции включения/отключения/переключения, а также загрузка, переименование и удаление при поддержке картой. |
| Политика карты | Поведение WiFi Calling и авиарежима на основе ICCID с немедленным применением политики. |
| Маршрутизация через прокси | Восходящая маршрутизация SOCKS, привязки устройств, правила по странам, проверки доступности TCP и проверки UDP Associate для путей передачи данных WiFi Calling. |
| Уведомления | Пересылка новых входящих SMS через Telegram, Bark, электронную почту, Pushplus и подписанные вебхуки. Каждое SMS доставляется как отдельное уведомление. |
| Telegram-бот | Статус устройства, список и переключение установленных профилей, управление WiFi Calling и отправка SMS. Чувствительные действия требуют подтверждения администратора. |
| Эксплуатация | Аутентификация, защита CSRF, политики доступа, события аудита, журналы в реальном времени, хранение журналов, проверки работоспособности, адаптивная вёрстка, тёмный режим и интерфейс на английском/китайском. |
| Дистрибуция | Статические бинарные файлы Linux, скрипт установки systemd, самообновление с проверкой SHA-256, образ Docker, публикация в GHCR и сборки релизов GitHub Actions. |
## Поддерживаемое оборудование
Vocat ориентирован на модули Quectel на базе Qualcomm, которые предоставляют совместимые интерфейсы AT, QMI, последовательный порт и USB-сеть, включая:
- Quectel EC20
- Quectel EC25
- Семейство Quectel EG25
- Совместимые модули EG600 и родственные
Доступные функции зависят от прошивки модуля, конфигурации USB, возможностей SIM/eSIM, драйверов хоста, радиосети и настроек оператора.
## Установка
### Установка в Linux одной командой
От имени root (включая OpenWrt/Kwrt, где `sudo` обычно отсутствует):
```bash
curl -fsSL https://raw.githubusercontent.com/MengMengCode/VoCat/master/scripts/install.sh | bash
```
От обычного пользователя в дистрибутиве с sudo:
```bash
curl -fsSL https://raw.githubusercontent.com/MengMengCode/VoCat/master/scripts/install.sh | sudo bash
```
Проверить предварительные требования VoWiFi/XFRM на хосте без установки VoCat:
```bash
curl -fsSL https://raw.githubusercontent.com/MengMengCode/VoCat/master/scripts/install.sh | bash -s -- --check-env
```
Установить конкретную версию:
```bash
curl -fsSL https://raw.githubusercontent.com/MengMengCode/VoCat/master/scripts/install.sh -o install.sh
sudo bash install.sh 0.0.2
```
VoWiFi IMS требует Linux XFRM/IPsec. В OpenWrt/Kwrt установщик пытается
установить соответствующие пакеты `ip-full`, `kmod-ipsec`, `kmod-ipsec4/6`,
`kmod-crypto-authenc`, AES-CBC и SHA1 из собственного репозитория прошивки.
Если соответствующие модули ядра недоступны, используйте прошивку, которая их включает;
никогда не устанавливайте принудительно kmod, собранные для другого ядра.
Установщик:
- определяет `amd64`, `386`, `arm64`, `aarch64` или `armv7`;
- загружает соответствующий бинарный файл GitHub Release;
- проверяет его по `SHA256SUMS`;
- устанавливает Vocat в `/opt/vocat`;
- создаёт усиленный сервис systemd с доступом к оборудованию и сети, необходимым Vocat;
- хранит конфигурацию времени выполнения в `/etc/vocat/env`;
- генерирует случайный начальный пароль администратора при первой установке.
После установки откройте:
```text
http://<адрес-сервера>:7575
```
### Ручная установка бинарного файла
Загрузите соответствующий бинарный файл и `SHA256SUMS` из GitHub Releases:
| Платформа | Файл релиза |
| --- | --- |
| Linux x86-64 | `vocat-linux-amd64` |
| Linux x86 32-бит | `vocat-linux-386` |
| Linux ARM64 | `vocat-linux-arm64` |
| Linux AArch64 | `vocat-linux-aarch64` |
| Linux ARMv7 | `vocat-linux-armv7` |
Проверьте и установите его:
```bash
sha256sum -c SHA256SUMS --ignore-missing
sudo install -d -m 0755 /opt/vocat/bin /opt/vocat/data
sudo install -m 0755 vocat-linux-amd64 /opt/vocat/bin/vocat
sudo env \
VOCAT_DATABASE_PATH=/opt/vocat/data/vocat.db \
VOCAT_ADMIN_PASSWORD=change-this-password \
/opt/vocat/bin/vocat serve
```
Эта ручная команда запускает Vocat в переднем плане. Используйте `vocat serve`, чтобы
процесс сразу запустил сервер; запуск `vocat` без аргументов от имени root
в TTY вместо этого открывает интерактивное меню управления. Используйте установку
одной командой, когда требуется управляемый сервис systemd и автоматический перезапуск.
### Docker
Для хоста Linux, который должен обнаруживать каждый подключённый поддерживаемый модем Quectel и
продолжать видеть события горячего подключения USB, запустите Vocat в режиме доступа к оборудованию:
```bash
docker pull ghcr.io/mengmengcode/vocat:latest
docker run -d \
--name vocat \
--restart unless-stopped \
--network host \
--privileged \
--user 0:0 \
-e VOCAT_ADMIN_PASSWORD=change-this-password \
-v vocat-data:/opt/vocat/data \
-v /dev:/dev \
-v /sys:/sys:ro \
ghcr.io/mengmengcode/vocat:latest
```
Откройте `http://<адрес-сервера>:7575` после запуска контейнера. Сеть хоста
необходима, чтобы сетевые интерфейсы QMI оставались видимыми для Vocat, а привилегированный
доступ к устройствам необходим для последовательных портов, узлов управления QMI, интерфейсов
TUN, настройки сети и устройств, добавленных после запуска контейнера. Монтирование `/dev`
делает новые узлы `ttyUSB*`, `ttyACM*` и `cdc-wdm*` видимыми без пересоздания контейнера.
Этот режим намеренно предоставляет Vocat широкий доступ к устройствам и сетевому стеку
хоста. Используйте его только на доверенном хосте Linux. Автоматическое обнаружение
в настоящее время определяет поддерживаемые USB-модемы Quectel (USB vendor ID `2c7c`), а не
произвольные марки модемов. Монтирование только отдельных узлов с помощью `--device`, таких как
`/dev/ttyUSB2` и `/dev/cdc-wdm0`, ограничивает контейнер этими фиксированными узлами и не
обеспечивает полное обнаружение нескольких устройств или горячего подключения.
Образ GHCR публикуется для `linux/amd64` и `linux/arm64`.
## Конфигурация
Vocat читает необязательный JSON-файл конфигурации из `VOCAT_CONFIG`, затем применяет переменные окружения `VOCAT_*`. Переменные окружения имеют приоритет.
| Переменная окружения | По умолчанию | Описание |
| --- | --- | --- |
| `VOCAT_ADDR` | `0.0.0.0:7575` | Адрес прослушивания HTTP. |
| `VOCAT_DATABASE_PATH` | `./data/vocat.db` | Путь к базе данных SQLite. |
| `VOCAT_ADMIN_USERNAME` | `admin` | Начальное имя пользователя администратора. |
| `VOCAT_ADMIN_PASSWORD` | `admin` | Начальный пароль администратора. Смените его перед публикацией сервиса. |
| `VOCAT_SESSION_TTL` | `24h` | Время жизни сессии аутентификации. |
| `VOCAT_SECURE_COOKIES` | `false` | Помечает cookie сессии как безопасные при использовании HTTPS. |
| `VOCAT_SHUTDOWN_TIMEOUT` | `10s` | Тайм-аут корректного завершения работы. |
| `VOCAT_MAX_REQUEST_BODY_BYTES` | `1048576` | Максимальный размер тела запроса API. |
| `VOCAT_REPO` | `MengMengCode/VoCat` | Доверенный репозиторий GitHub, используемый самообновлятором, в формате `owner/name`. |
| `GITHUB_TOKEN` | пусто | Необязательный токен GitHub для приватных репозиториев или более высоких лимитов API. |
Не храните токены Telegram, пароли SMTP, секреты вебхуков, учётные данные SIM или другие приватные данные в репозитории. Настраивайте их через параметры приложения или защищённые файлы окружения.
## Telegram-бот
Когда уведомления Telegram включены и настроены Chat ID и Admin ID, бот поддерживает:
```text
/status [устройство]
/esim <устройство>
/switch <устройство> <iccid>
/wfc <устройство> <status|on|off|reconnect>
/sms <устройство> <номер> <сообщение>
```
Переключение профилей и отправка SMS используют одноразовые кнопки подтверждения. Бот не предоставляет команды загрузки, удаления или переименования eSIM.
## Обновление
Проверить наличие более нового GitHub Release:
```bash
vocat update --check --repo MengMengCode/VoCat
```
Установить последний релиз:
```bash
sudo vocat update --repo MengMengCode/VoCat
```
Обновлятор загружает бинарный файл, соответствующий текущей архитектуре Linux, проверяет его по опубликованному `SHA256SUMS`, атомарно заменяет исполняемый файл и перезапускает сервис systemd `vocat`, когда он доступен.
Для установок Docker:
```bash
docker pull ghcr.io/mengmengcode/vocat:latest
```
Пересоздайте контейнер после загрузки нового образа.
## Разработка
Требования:
- Go 1.25 или новее
- Node.js 20 или новее
- npm
Запустить сервер разработки фронтенда:
```bash
cd web
npm install
npm run dev
```
Собрать встроенный фронтенд и запустить бэкенд:
```bash
cd web
npm run build
cd ..
go run ./cmd/vocat
```
Запустить все тесты:
```bash
go test ./...
```
Собрать производственный бинарный файл:
```bash
go build -trimpath -ldflags "-s -w" -o vocat ./cmd/vocat
```
## Автоматизация релизов
Отправка тега версии запускает два рабочих процесса GitHub Actions:
- `release-binaries` собирает и публикует бинарные файлы `amd64`, `386`, `arm64`, `aarch64` и `armv7` вместе с `SHA256SUMS`.
- `docker` собирает и публикует мультиархитектурный образ в GitHub Container Registry.
```bash
git tag v0.2.0
git push origin v0.2.0
```
## Структура проекта
```text
cmd/vocat/ Точка входа приложения и CLI
internal/device/ Обнаружение модемов и управление устройствами
internal/modem/ Сессия AT и обработка ответов
internal/server/ HTTP API, уведомления и встроенный веб-сервер
internal/store/ Постоянное хранение SQLite
internal/update/ Самообновлятор GitHub Release
internal/vowifi/ Среда выполнения IKE, EAP-AKA, IMS и WiFi Calling
scripts/install.sh Установщик и обновлятор Linux
web/src/ Фронтенд на React и TypeScript
.github/workflows/ Автоматизация релизов бинарных файлов и Docker
```
## Ответственное использование
Операции с сотовыми модемами и eSIM могут влиять на обслуживание абонента, сохранённые профили, регистрацию в сети и состояние оборудования. Делайте резервные копии, внимательно проверяйте деструктивные действия и используйте программное обеспечение только в законных средах, где вам разрешено работать с подключённым оборудованием и сетевыми ресурсами.
Vocat не обходит аутентификацию оператора, сетевую политику, аппаратную безопасность или требования доверия eSIM. Поддержка операции означает, что Vocat может запросить её у модема или eUICC; устройство, профиль, сеть или оператор всё равно могут её отклонить.
## Участие в разработке
Мы приветствуем issues и pull request'ы. Делайте изменения сфокусированными, по возможности добавляйте тесты, избегайте коммита учётных данных или данных абонентов и чётко документируйте поведение, специфичное для оборудования.
Перед отправкой изменения:
```bash
go test ./...
cd web && npm run build
```
## Благодарности
- [Nodeseek.com](https://www.nodeseek.com) — Сообщество, посвящённое серверам
- [Linux.do](https://linux.do) — Вдохновляющее технологическое сообщество
- [iniwex5](https://github.com/iniwex5) — Руководства по стилю и функциональности
## Угостите меня кофе
| Сеть | Адрес |
| ------- | ------- |
| USDT-TRON (TRC20) | `TQQAbboBoU8h5xX4YCA1rqWJU2WjK3seSg` |
| USDT-BSC (BEP20) | `0xdbfcd4a462550d6ff06d09cbd89026c6b145d9c4` |
| USDT-Polygon | `0xdbfcd4a462550d6ff06d09cbd89026c6b145d9c4` |
## Лицензия
См. [LICENSE](../LICENSE).
[![MengMengCode/VoCat Star History](https://mengmeng.meteor-history.com/api/embed/MengMengCode/VoCat.svg?sig=sdeXRVxAoY3yLWgXL7JViY2USYIN3t9neJ6ScPvgUAo&theme=light&style=xkcd&color=dd4528&background=ffffff&textColor=000000&width=900&height=600&lineWidth=3&showTitle=true&showLegend=true&showDots=false&v=0.0.14)](https://meteor-history.com)
+19 -7
View File
@@ -22,7 +22,7 @@
<img alt="GitHub Actions" src="https://img.shields.io/badge/GitHub_Actions-Release-2088FF?style=flat-square&logo=githubactions&logoColor=white">
</p>
[English](../README.md) | **简体中文**
[English](../README.md) | [العربية](README.ar.md) | **简体中文** | [繁體中文](README.zh-TW.md) | [Français](README.fr.md) | [Русский](README.ru.md) | [Español](README.es.md) | [日本語](README.ja.md)
Vocat 是一款面向 Quectel EC20/EC25 系列蜂窝模组的开源 Web 控制面板与工程工具套件。它在一个自包含的服务中整合了模组发现、实时射频状态、AT 与 USSD 终端、短信、WiFi Calling(WiFi 通话)、eSIM 管理、网络选择、代理路由、通知、审计日志以及发布自动化。
@@ -46,7 +46,7 @@ Vocat 是一款面向 Quectel EC20/EC25 系列蜂窝模组的开源 Web 控制
| 卡策略 | 基于 ICCID 的 WiFi Calling 与飞行模式行为,策略即时应用。 |
| 代理路由 | 上游 SOCKS 路由、设备绑定、国家规则、TCP 可达性检查以及面向 WiFi Calling 数据路径的 UDP Associate 检查。 |
| 通知 | 通过 Telegram、Bark、邮件、Pushplus 以及签名 Webhook 转发新入站短信,每条短信单独推送。 |
| Telegram 机器人 | 设备状态、已安装配置文件列表与切换、WiFi Calling 控制短信发送、定时拨号并自动挂断、通话状态、接听与挂断命令。敏感操作需要管理员确认。 |
| Telegram 机器人 | 设备状态、已安装配置文件列表与切换、WiFi Calling 控制以及短信发送。敏感操作需要管理员确认。 |
| 运维 | 鉴权、CSRF 防护、访问策略、审计事件、实时日志、日志留存、健康检查、响应式布局、深色模式以及中英文应用界面。 |
| 分发 | 静态 Linux 二进制、systemd 安装脚本、带 SHA-256 校验的自更新、Docker 镜像、GHCR 发布以及 GitHub Actions 发布构建。 |
@@ -65,10 +65,24 @@ Vocat 面向基于高通芯片、并暴露兼容 AT、QMI、串口与 USB 网络
### Linux 一键安装
已是 root(包括默认没有 `sudo` 的 OpenWrt/Kwrt):
```bash
curl -fsSL https://raw.githubusercontent.com/MengMengCode/VoCat/master/scripts/install.sh | bash
```
普通 Linux 用户且系统装有 sudo
```bash
curl -fsSL https://raw.githubusercontent.com/MengMengCode/VoCat/master/scripts/install.sh | sudo bash
```
只检查 VoWiFi/XFRM 环境,不安装 VoCat
```bash
curl -fsSL https://raw.githubusercontent.com/MengMengCode/VoCat/master/scripts/install.sh | bash -s -- --check-env
```
安装指定版本:
```bash
@@ -76,6 +90,8 @@ curl -fsSL https://raw.githubusercontent.com/MengMengCode/VoCat/master/scripts/i
sudo bash install.sh 0.0.2
```
VoWiFi IMS 必须使用 Linux XFRM/IPsec。OpenWrt/Kwrt 上安装脚本会从当前固件自己的软件源尝试安装严格匹配的 `ip-full``kmod-ipsec``kmod-ipsec4/6``kmod-crypto-authenc`、AES-CBC 和 SHA1 组件。若软件源没有与当前内核匹配的模块,必须更换包含这些组件的固件,禁止强装其他内核版本的 kmod。
安装程序会:
- 检测 `amd64``386``arm64``armv7` 架构;
@@ -172,13 +188,9 @@ Vocat 先从 `VOCAT_CONFIG` 读取可选的 JSON 配置文件,再应用 `VOCAT_*
/switch <设备> <iccid>
/wfc <设备> <status|on|off|reconnect>
/sms <设备> <号码> <内容>
/call <设备> <号码> <秒数>
/calls <设备>
/answer <设备>
/hangup <设备>
```
配置文件切换短信提交与拨号使用一次性确认按钮。定时拨号会执行模组拨号动作,并在 1–600 秒后自动挂断;不会捕获或处理通话音频。机器人不暴露 eSIM 下载、删除或重命名命令。
配置文件切换短信提交使用一次性确认按钮。机器人不暴露 eSIM 下载、删除或重命名命令。
## 更新
+318
View File
@@ -0,0 +1,318 @@
<p align="center">
<img src="../web/public/favicon.svg" width="96" alt="Vocat">
</p>
<h1 align="center">VoCat</h1>
<p align="center">
<img alt="Go" src="https://img.shields.io/badge/Go-1.25-00ADD8?style=flat-square&logo=go&logoColor=white">
<img alt="React" src="https://img.shields.io/badge/React-19-61DAFB?style=flat-square&logo=react&logoColor=111111">
<img alt="TypeScript" src="https://img.shields.io/badge/TypeScript-5.8-3178C6?style=flat-square&logo=typescript&logoColor=white">
<img alt="Vite" src="https://img.shields.io/badge/Vite-7-646CFF?style=flat-square&logo=vite&logoColor=white">
<img alt="Tailwind CSS" src="https://img.shields.io/badge/Tailwind_CSS-3-06B6D4?style=flat-square&logo=tailwindcss&logoColor=white">
<img alt="SQLite" src="https://img.shields.io/badge/SQLite-Embedded-003B57?style=flat-square&logo=sqlite&logoColor=white">
</p>
<p align="center">
<img alt="Linux" src="https://img.shields.io/badge/Linux-amd64_%7C_386_%7C_arm64_%7C_aarch64_%7C_armv7-FCC624?style=flat-square&logo=linux&logoColor=111111">
<img alt="Docker" src="https://img.shields.io/badge/Docker-Multi--Arch-2496ED?style=flat-square&logo=docker&logoColor=white">
<img alt="WiFi Calling" src="https://img.shields.io/badge/WiFi_Calling-IMS_SMS-7B1FA2?style=flat-square">
<img alt="eSIM" src="https://img.shields.io/badge/eSIM-LPA_%2F_eUICC-009688?style=flat-square">
<img alt="Telegram" src="https://img.shields.io/badge/Telegram-Bot-26A5E4?style=flat-square&logo=telegram&logoColor=white">
<img alt="GitHub Actions" src="https://img.shields.io/badge/GitHub_Actions-Release-2088FF?style=flat-square&logo=githubactions&logoColor=white">
</p>
[English](../README.md) | [العربية](README.ar.md) | [简体中文](README.zh-CN.md) | **繁體中文** | [Français](README.fr.md) | [Русский](README.ru.md) | [Español](README.es.md) | [日本語](README.ja.md)
Vocat 是一款面向 Quectel EC20/EC25 系列行動通訊模組的開源 Web 控制面板與工程工具套件。它在單一自包含的服務中整合了模組探索、即時射頻狀態、AT 與 USSD 終端、簡訊、WiFi Calling(WiFi 通話)、eSIM 管理、網路選擇、代理路由、通知、稽核日誌以及發佈自動化。
後端使用 Go 撰寫,介面採用 React 與 TypeScript 建構,生產環境前端被嵌入進 Go 二進位檔中。單一可執行檔即包含完整的 Web 應用,並使用 SQLite 進行持久化儲存。
<p align="center">
<img src="../img/image.png">
<img src="../img/image-1.png">
</p>
## 功能
| 領域 | Vocat 提供的能力 |
| --- | --- |
| 裝置管理 | 自動序列埠/USB 探索、多模組支援、裝置友善名稱、概覽即時更新、模組重新啟動、飛航模式以及 USB 網路卡模式控制。 |
| 射頻與網路 | 註冊狀態、電信業者、訊號指標、RSRP/RSRQ/SINR、網路模式、頻段、通道、電信業者掃描以及自動/手動選網。 |
| AT 與 USSD | 互動式 AT 終端、指令歷史、原始模組回應、USSD 發起/繼續/取消流程以及清晰的模組錯誤回報。 |
| 簡訊 | 行動通訊與 IMS 簡訊直接傳送、接收同步、長簡訊合併、送達報告、對話歷史、未讀狀態、時間戳以及逐則訊息的送達狀態。 |
| WiFi Calling | IKEv2/ePDG 隧道建立、EAP-AKA 驗證、IMS 註冊、IMS 簡訊、重新連線控制、狀態診斷以及依裝置路由。 |
| eSIM 與 eUICC | eUICC 探索、EID 與生產資訊、憑證中繼資料、多 eUICC 清單、已安裝設定檔列表、啟用/停用/切換操作,以及在卡片支援時進行下載、重新命名與刪除。 |
| 卡片策略 | 基於 ICCID 的 WiFi Calling 與飛航模式行為,策略即時套用。 |
| 代理路由 | 上游 SOCKS 路由、裝置綁定、國家規則、TCP 可達性檢查以及面向 WiFi Calling 資料路徑的 UDP Associate 檢查。 |
| 通知 | 透過 Telegram、Bark、電子郵件、Pushplus 以及簽章 Webhook 轉發新接收簡訊,每則簡訊個別推送。 |
| Telegram 機器人 | 裝置狀態、已安裝設定檔列表與切換、WiFi Calling 控制以及簡訊傳送。敏感操作需要管理員確認。 |
| 維運 | 驗證、CSRF 防護、存取策略、稽核事件、即時日誌、日誌保留、健康檢查、響應式版面、深色模式以及中英文應用介面。 |
| 發佈 | 靜態 Linux 二進位檔、systemd 安裝腳本、具 SHA-256 校驗的自我更新、Docker 映像、GHCR 發佈以及 GitHub Actions 發佈建置。 |
## 支援的硬體
Vocat 面向基於高通晶片、並暴露相容 AT、QMI、序列埠與 USB 網路介面的 Quectel 模組,包括:
- Quectel EC20
- Quectel EC25
- Quectel EG25 系列
- 相容的 EG600 及相關模組
可用功能取決於模組韌體、USB 複合裝置配置、SIM/eSIM 能力、主機驅動、無線網路以及電信業者配置。
## 安裝
### Linux 一鍵安裝
已是 root(包括預設沒有 `sudo` 的 OpenWrt/Kwrt):
```bash
curl -fsSL https://raw.githubusercontent.com/MengMengCode/VoCat/master/scripts/install.sh | bash
```
一般 Linux 使用者且系統裝有 sudo
```bash
curl -fsSL https://raw.githubusercontent.com/MengMengCode/VoCat/master/scripts/install.sh | sudo bash
```
只檢查 VoWiFi/XFRM 環境,不安裝 VoCat
```bash
curl -fsSL https://raw.githubusercontent.com/MengMengCode/VoCat/master/scripts/install.sh | bash -s -- --check-env
```
安裝指定版本:
```bash
curl -fsSL https://raw.githubusercontent.com/MengMengCode/VoCat/master/scripts/install.sh -o install.sh
sudo bash install.sh 0.0.2
```
VoWiFi IMS 必須使用 Linux XFRM/IPsec。OpenWrt/Kwrt 上安裝腳本會從目前韌體自己的軟體源嘗試安裝嚴格匹配的 `ip-full``kmod-ipsec``kmod-ipsec4/6``kmod-crypto-authenc`、AES-CBC 和 SHA1 元件。若軟體源沒有與目前核心匹配的模組,必須更換包含這些元件的韌體,禁止強裝其他核心版本的 kmod。
安裝程式會:
- 偵測 `amd64``386``arm64``aarch64``armv7` 架構;
- 下載對應的 GitHub Release 二進位檔;
- 對照 `SHA256SUMS` 進行校驗;
- 將 Vocat 安裝到 `/opt/vocat`;
- 建立具有 Vocat 所需硬體與網路存取權限的強化版 systemd 服務;
- 將執行時配置存放在 `/etc/vocat/env`;
- 首次安裝時產生隨機初始管理員密碼。
安裝完成後開啟:
```text
http://<伺服器位址>:7575
```
### 手動二進位安裝
從 GitHub Releases 下載對應的二進位檔與 `SHA256SUMS`:
| 平台 | 發佈檔案 |
| --- | --- |
| Linux x86-64 | `vocat-linux-amd64` |
| Linux x86 32 位元 | `vocat-linux-386` |
| Linux ARM64 | `vocat-linux-arm64` |
| Linux AArch64 | `vocat-linux-aarch64` |
| Linux ARMv7 | `vocat-linux-armv7` |
校驗並安裝:
```bash
sha256sum -c SHA256SUMS --ignore-missing
sudo install -d -m 0755 /opt/vocat/bin /opt/vocat/data
sudo install -m 0755 vocat-linux-amd64 /opt/vocat/bin/vocat
sudo env \
VOCAT_DATABASE_PATH=/opt/vocat/data/vocat.db \
VOCAT_ADMIN_PASSWORD=change-this-password \
/opt/vocat/bin/vocat serve
```
該手動指令會在前台執行 Vocat。請使用 `vocat serve` 以直接啟動伺服器;在 TTY 下以 root 執行無參數的 `vocat` 會進入互動式管理選單。如需託管的 systemd 服務與自動重新啟動,請使用一鍵安裝腳本。
### Docker
如果 Linux 主機需要探索每一個接入的受支援 Quectel 模組,並持續感知 USB 熱插拔事件,請以硬體存取模式執行 Vocat:
```bash
docker pull ghcr.io/mengmengcode/vocat:latest
docker run -d \
--name vocat \
--restart unless-stopped \
--network host \
--privileged \
--user 0:0 \
-e VOCAT_ADMIN_PASSWORD=change-this-password \
-v vocat-data:/opt/vocat/data \
-v /dev:/dev \
-v /sys:/sys:ro \
ghcr.io/mengmengcode/vocat:latest
```
容器啟動後開啟 `http://<伺服器位址>:7575`。主機網路是必需的,這樣 QMI 網路介面才能對 Vocat 可見;而特權裝置存取是序列埠、QMI 控制節點、TUN 介面、網路配置以及容器啟動後新增裝置所必需的。`/dev` 掛載使新的 `ttyUSB*``ttyACM*``cdc-wdm*` 節點無需重建容器即可見。
該模式有意賦予 Vocat 對主機裝置與網路堆疊的廣泛存取權限,僅在受信任的 Linux 主機上使用。自動探索目前僅識別受支援的 Quectel USB 模組(USB 廠商 ID `2c7c`),不識別任意品牌的模組。僅用 `--device` 映射單一節點(例如 `/dev/ttyUSB2``/dev/cdc-wdm0`)會將容器限定在這些固定節點上,無法提供完整的多裝置或熱插拔探索。
GHCR 映像發佈為 `linux/amd64``linux/arm64`
## 配置
Vocat 先從 `VOCAT_CONFIG` 讀取可選的 JSON 配置檔,再套用 `VOCAT_*` 環境變數。環境變數優先級更高。
| 環境變數 | 預設值 | 說明 |
| --- | --- | --- |
| `VOCAT_ADDR` | `0.0.0.0:7575` | HTTP 監聽位址。 |
| `VOCAT_DATABASE_PATH` | `./data/vocat.db` | SQLite 資料庫路徑。 |
| `VOCAT_ADMIN_USERNAME` | `admin` | 初始管理員使用者名稱。 |
| `VOCAT_ADMIN_PASSWORD` | `admin` | 初始管理員密碼。暴露服務前請務必修改。 |
| `VOCAT_SESSION_TTL` | `24h` | 驗證工作階段有效期。 |
| `VOCAT_SECURE_COOKIES` | `false` | 在使用 HTTPS 時將工作階段 Cookie 標記為安全。 |
| `VOCAT_SHUTDOWN_TIMEOUT` | `10s` | 優雅關閉逾時時間。 |
| `VOCAT_MAX_REQUEST_BODY_BYTES` | `1048576` | API 請求主體最大位元組數。 |
| `VOCAT_REPO` | `MengMengCode/VoCat` | 自我更新器使用的受信任 GitHub 倉庫,格式為 `owner/name`。 |
| `GITHUB_TOKEN` | 空 | 可選的 GitHub token,用於私有倉庫或更高的 API 限額。 |
請勿將 Telegram token、SMTP 密碼、Webhook 金鑰、SIM 憑證或其他私密資料存放在倉庫中。請透過應用設定或受保護的環境檔來配置它們。
## Telegram 機器人
啟用 Telegram 通知並配置好 Chat ID 與 Admin ID 後,機器人支援:
```text
/status [裝置]
/esim <裝置>
/switch <裝置> <iccid>
/wfc <裝置> <status|on|off|reconnect>
/sms <裝置> <號碼> <內容>
```
設定檔切換與簡訊提交使用一次性確認按鈕。機器人不暴露 eSIM 下載、刪除或重新命名命令。
## 更新
檢查是否有更新的 GitHub Release:
```bash
vocat update --check --repo MengMengCode/VoCat
```
安裝最新發佈版:
```bash
sudo vocat update --repo MengMengCode/VoCat
```
更新器會下載與目前 Linux 架構匹配的二進位檔,使用已發佈的 `SHA256SUMS` 進行校驗,原子性地替換可執行檔,並在可用時重新啟動 `vocat` systemd 服務。
Docker 安裝的更新方式:
```bash
docker pull ghcr.io/mengmengcode/vocat:latest
```
拉取新映像後重建容器。
## 開發
依賴要求:
- Go 1.25 或更新版本
- Node.js 20 或更新版本
- npm
執行前端開發伺服器:
```bash
cd web
npm install
npm run dev
```
建構嵌入的前端並啟動後端:
```bash
cd web
npm run build
cd ..
go run ./cmd/vocat
```
執行全部測試:
```bash
go test ./...
```
建構生產二進位檔:
```bash
go build -trimpath -ldflags "-s -w" -o vocat ./cmd/vocat
```
## 發佈自動化
推送版本標籤會觸發兩個 GitHub Actions 工作流程:
- `release-binaries` 建構並發佈 `amd64``386``arm64``aarch64``armv7` 二進位檔及 `SHA256SUMS`
- `docker` 建構並向 GitHub Container Registry 發佈多架構映像。
```bash
git tag v0.2.0
git push origin v0.2.0
```
## 專案結構
```text
cmd/vocat/ 應用入口與 CLI
internal/device/ 模組探索與裝置控制
internal/modem/ AT 工作階段與回應處理
internal/server/ HTTP API、通知與內嵌 Web 伺服器
internal/store/ SQLite 持久化
internal/update/ GitHub Release 自我更新器
internal/vowifi/ IKE、EAP-AKA、IMS 與 WiFi Calling 執行時
scripts/install.sh Linux 安裝與更新腳本
web/src/ React 與 TypeScript 前端
.github/workflows/ 二進位檔與 Docker 發佈自動化
```
## 合規使用
行動通訊模組與 eSIM 操作可能影響用戶服務、已儲存的設定檔、網路註冊以及硬體狀態。請做好備份,謹慎審視破壞性操作,並僅在您被允許操作所連接的硬體與網路資源的合法環境中使用本軟體。
Vocat 不會繞過電信業者驗證、網路策略、硬體安全或 eSIM 信任要求。支援某項操作意味著 Vocat 能夠向模組或 eUICC 發起該請求;但裝置、設定檔、網路或電信業者仍可能拒絕。
## 貢獻
歡迎提交 Issue 與 Pull Request。請保持改動聚焦,在可行處附帶測試,避免提交憑證或用戶資料,並清晰地說明硬體相關行為。
提交改動前:
```bash
go test ./...
cd web && npm run build
```
## 致謝
- [Nodeseek.com](https://www.nodeseek.com) — 專注伺服器的社群
- [Linux.do](https://linux.do) — 富有啟發的技術社群
- [iniwex5](https://github.com/iniwex5) — 風格與功能指南
## 請我喝杯咖啡
| 網路 | 位址 |
| ------- | ------- |
| USDT-TRON (TRC20) | `TQQAbboBoU8h5xX4YCA1rqWJU2WjK3seSg` |
| USDT-BSC (BEP20) | `0xdbfcd4a462550d6ff06d09cbd89026c6b145d9c4` |
| USDT-Polygon | `0xdbfcd4a462550d6ff06d09cbd89026c6b145d9c4` |
## 授權條款
參見 [LICENSE](../LICENSE)。
[![MengMengCode/VoCat Star History](https://mengmeng.meteor-history.com/api/embed/MengMengCode/VoCat.svg?sig=sdeXRVxAoY3yLWgXL7JViY2USYIN3t9neJ6ScPvgUAo&theme=light&style=xkcd&color=dd4528&background=ffffff&textColor=000000&width=900&height=600&lineWidth=3&showTitle=true&showLegend=true&showDots=false&v=0.0.14)](https://meteor-history.com)
+2 -2
View File
@@ -5,9 +5,9 @@ go 1.25.0
require (
github.com/coder/websocket v1.8.15
go.bug.st/serial v1.6.4
golang.org/x/crypto v0.41.0
golang.org/x/crypto v0.52.0
golang.org/x/sys v0.47.0
golang.org/x/term v0.34.0
golang.org/x/term v0.43.0
modernc.org/sqlite v1.38.2
)
+6 -6
View File
@@ -18,12 +18,12 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
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/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
go.bug.st/serial v1.6.4 h1:7FmqNPgVp3pu2Jz5PoPtbZ9jJO5gnEnZIvnI1lzve8A=
go.bug.st/serial v1.6.4/go.mod h1:nofMJxTeNVny/m6+KaafC6vJGj3miwQZ6vW4BZUGJPI=
golang.org/x/crypto v0.41.0 h1:WKYxWedPGCTVVl5+WHSSrOBT0O8lx32+zxmHxijgXp4=
golang.org/x/crypto v0.41.0/go.mod h1:pO5AFd7FA68rFak7rOAGVuygIISepHftHnr8dr6+sUc=
golang.org/x/crypto v0.52.0 h1:RMs7fP2rXdep0CftQlK8Uf+kibLm7qkCcradZWYz988=
golang.org/x/crypto v0.52.0/go.mod h1:1QgfPxDqh0T2M/elOJtp9RvuR95kVjir0e6/BvEmGbc=
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b h1:M2rDM6z3Fhozi9O7NWsxAkg/yqS/lQJ6PmkyIV3YP+o=
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b/go.mod h1:3//PLf8L/X+8b4vuAfHzxeRUl04Adcb341+IGKfnqS8=
golang.org/x/mod v0.25.0 h1:n7a+ZbQKQA/Ysbyb0/6IbB1H/X41mKgbhfv7AfG/44w=
@@ -33,8 +33,8 @@ golang.org/x/sync v0.15.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/term v0.34.0 h1:O/2T7POpk0ZZ7MAzMeWFSg6S5IpWd/RXDlM9hgM3DR4=
golang.org/x/term v0.34.0/go.mod h1:5jC53AEywhIVebHgPVeg0mj8OD3VO9OzclacVrqpaAw=
golang.org/x/term v0.43.0 h1:S4RLU2sB31O/NCl+zFN9Aru9A/Cq2aqKpTZJ6B+DwT4=
golang.org/x/term v0.43.0/go.mod h1:lrhlHNdQJHO+1qVYiHfFKVuVioJIheAc3fBSMFYEIsk=
golang.org/x/tools v0.34.0 h1:qIpSLOxeCYGg9TrcJokLBG4KFA6d795g0xkBkiESGlo=
golang.org/x/tools v0.34.0/go.mod h1:pAP9OwEaY1CAW3HOmg3hLZC5Z0CCmzjAF2UQMSqNARg=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
+10 -4
View File
@@ -27,9 +27,9 @@ const (
DeviceLimitSettingKey = "developer.device_limit"
SMSHourlyLimitKey = "developer.sms_hourly_limit"
DefaultDeviceLimit = 5
MaxDeviceLimit = 128
MaxDeviceLimit = 10
DefaultSMSHourlyLimit = 10
MaxSMSHourlyLimit = 1000
MaxSMSHourlyLimit = 20
)
func DeviceLimit(ctx context.Context, database *store.Store, enabled bool) int {
@@ -43,9 +43,12 @@ func DeviceLimit(ctx context.Context, database *store.Store, enabled bool) int {
var document struct {
Limit int `json:"limit"`
}
if json.Unmarshal(setting.Value, &document) != nil || document.Limit < 1 || document.Limit > MaxDeviceLimit {
if json.Unmarshal(setting.Value, &document) != nil || document.Limit < 1 {
return DefaultDeviceLimit
}
if document.Limit > MaxDeviceLimit {
return MaxDeviceLimit
}
return document.Limit
}
@@ -70,9 +73,12 @@ func SMSHourlyLimit(ctx context.Context, database *store.Store) int {
var document struct {
Limit int `json:"limit"`
}
if json.Unmarshal(setting.Value, &document) != nil || document.Limit < 1 || document.Limit > MaxSMSHourlyLimit {
if json.Unmarshal(setting.Value, &document) != nil || document.Limit < 1 {
return DefaultSMSHourlyLimit
}
if document.Limit > MaxSMSHourlyLimit {
return MaxSMSHourlyLimit
}
return document.Limit
}
+29 -5
View File
@@ -19,10 +19,10 @@ func TestResetExperimentalRestoresDefaults(t *testing.T) {
t.Fatal(err)
}
defer database.Close()
if err := SetDeviceLimit(ctx, database, 24); err != nil {
if err := SetDeviceLimit(ctx, database, 8); err != nil {
t.Fatal(err)
}
if err := SetSMSHourlyLimit(ctx, database, 42); err != nil {
if err := SetSMSHourlyLimit(ctx, database, 18); err != nil {
t.Fatal(err)
}
enabled, _ := json.Marshal(map[string]bool{"enabled": true})
@@ -92,10 +92,34 @@ func TestSetSMSHourlyLimitValidatesRange(t *testing.T) {
if SetSMSHourlyLimit(ctx, database, 0) == nil || SetSMSHourlyLimit(ctx, database, MaxSMSHourlyLimit+1) == nil {
t.Fatal("out-of-range SMS hourly limit was accepted")
}
if err := SetSMSHourlyLimit(ctx, database, 25); err != nil {
if err := SetSMSHourlyLimit(ctx, database, 15); err != nil {
t.Fatal(err)
}
if got := SMSHourlyLimit(ctx, database); got != 25 {
t.Fatalf("SMS hourly limit = %d, want 25", got)
if got := SMSHourlyLimit(ctx, database); got != 15 {
t.Fatalf("SMS hourly limit = %d, want 15", got)
}
}
func TestStoredLimitsAboveHardMaximumAreClamped(t *testing.T) {
ctx := context.Background()
database, err := store.Open(ctx, filepath.Join(t.TempDir(), "vocat.db"))
if err != nil {
t.Fatal(err)
}
defer database.Close()
for key, limit := range map[string]int{
DeviceLimitSettingKey: 99,
SMSHourlyLimitKey: 99,
} {
value, _ := json.Marshal(map[string]int{"limit": limit})
if err := database.UpsertAppSetting(ctx, store.AppSetting{Key: key, Value: value}); err != nil {
t.Fatal(err)
}
}
if got := DeviceLimit(ctx, database, true); got != MaxDeviceLimit {
t.Fatalf("device limit = %d, want %d", got, MaxDeviceLimit)
}
if got := SMSHourlyLimit(ctx, database); got != MaxSMSHourlyLimit {
t.Fatalf("SMS hourly limit = %d, want %d", got, MaxSMSHourlyLimit)
}
}
+3
View File
@@ -274,6 +274,9 @@ func (manager *Manager) SetFlight(
if err := manager.validateActive(id, state); err != nil {
return FlightResult{}, err
}
if manager.candidateFor(state).HardwareKind == "pcsc" {
return FlightResult{PreviousMode: 4, CurrentMode: 4, FlightMode: true, RadioOff: true}, nil
}
client, err := manager.clientLocked(ctx, state, manager.candidateFor(state))
if err != nil {
manager.setResult(id, state, nil, err)
+144 -35
View File
@@ -10,6 +10,7 @@ import (
"vocat/internal/i18n"
"vocat/internal/modem"
"vocat/internal/pcsc"
)
// eUICC / eSIM (LPA, SGP.22) access over the modem's AT+CSIM APDU passthrough.
@@ -190,9 +191,11 @@ func parseCSIM(response modem.Response) ([]byte, int, error) {
// euiccChannel is an open logical channel to the eUICC's ISD-R.
type euiccChannel struct {
manager *Manager
id string
channel int
manager *Manager
id string
channel int
pcscSession *pcsc.Session
resetOnClose bool
}
// csimAPDUTimeout bounds a single AT+CSIM exchange. Loading a BoundProfilePackage
@@ -243,6 +246,15 @@ func (manager *Manager) openEuiccAID(ctx context.Context, id, aidHex string) (*e
return channel, nil
}
lastErr = err
if attempt == 0 && errors.Is(err, errNoLogicalChannel) &&
manager.releaseStaleEuiccChannel(ctx, id) {
// EC20 firmware exposes only one MANAGE CHANNEL slot. A canceled or
// interrupted APDU transaction can leave channel 1 allocated, after
// which every eSIM page load returns 6A81 until reboot. Closing the
// orphan while holding the shared UICC transaction lock makes the
// operation self-healing without disturbing an active AKA exchange.
continue
}
if !isTransientEuiccCME(err) {
return nil, err
}
@@ -259,11 +271,24 @@ func (manager *Manager) openEuiccAID(ctx context.Context, id, aidHex string) (*e
return nil, lastErr
}
func (manager *Manager) releaseStaleEuiccChannel(ctx context.Context, id string) bool {
_, sw, err := manager.csim(ctx, id, []byte{0x00, 0x70, 0x80, 0x01, 0x00})
return err == nil && sw == 0x9000
}
func (manager *Manager) openEuiccOnce(ctx context.Context, id string) (*euiccChannel, error) {
return manager.openEuiccOnceAID(ctx, id, isdRAID)
}
func (manager *Manager) openEuiccOnceAID(ctx context.Context, id, aidHex string) (*euiccChannel, error) {
state, lookupErr := manager.lookup(id)
if lookupErr != nil {
return nil, lookupErr
}
candidate := manager.candidateFor(state)
if candidate.HardwareKind == pcsc.HardwareKind {
return manager.openPCSCEuiccOnceAID(ctx, id, candidate, aidHex)
}
// MANAGE CHANNEL (open): 00 70 00 00 01 -> "<channel> 90 00". This EC20
// firmware requires the explicit one-byte expected length: Le=00 opens a
// channel but then rejects SELECT ISD-R at the AT+CSIM layer.
@@ -302,6 +327,37 @@ func (manager *Manager) openEuiccOnceAID(ctx context.Context, id, aidHex string)
return channel, nil
}
func (manager *Manager) openPCSCEuiccOnceAID(ctx context.Context, id string, candidate modem.Candidate, aidHex string) (*euiccChannel, error) {
session, err := manager.cardReaders.OpenSession(ctx, pcsc.Selector{
USBPath: candidate.USBPath, ReaderName: candidate.ReaderName,
})
if err != nil {
return nil, err
}
payload, sw, err := session.Transmit(ctx, []byte{0x00, 0x70, 0x00, 0x00, 0x01})
if err != nil || sw != 0x9000 || len(payload) != 1 {
session.Close()
if err != nil {
return nil, fmt.Errorf("esim: PC/SC MANAGE CHANNEL: %w", err)
}
return nil, errNoLogicalChannel
}
channel := &euiccChannel{manager: manager, id: id, channel: int(payload[0]), pcscSession: session}
aidHex = strings.ToUpper(strings.TrimSpace(aidHex))
aid, err := hex.DecodeString(aidHex)
if err != nil || len(aid) == 0 || len(aid) > 255 {
channel.close(context.Background())
return nil, fmt.Errorf("esim: invalid ISD-R AID %q", aidHex)
}
selectAID := append([]byte{byte(channel.channel), 0xA4, 0x04, 0x00, byte(len(aid))}, aid...)
_, selectSW, err := channel.transmit(ctx, selectAID, 0x00)
if err != nil || selectSW != 0x9000 {
channel.close(context.Background())
return nil, errNoEUICC
}
return channel, nil
}
// discoverEuiccAIDs detects eSTK multi-SE and alternate-ISD-R cards without
// changing any profile state. The vendor product applet and candidate ISD-R
// applications are selected only as read-only capability probes. Per
@@ -352,7 +408,23 @@ func isTransientEuiccCME(err error) bool {
// close releases the logical channel (MANAGE CHANNEL close).
func (channel *euiccChannel) close(ctx context.Context) {
closeAPDU := []byte{0x00, 0x70, 0x80, byte(channel.channel), 0x00}
_, _, _ = channel.manager.csim(ctx, channel.id, closeAPDU)
_, _, _ = channel.exchange(ctx, closeAPDU)
if channel.pcscSession != nil {
if channel.resetOnClose {
_ = channel.pcscSession.CloseWithReset()
} else {
_ = channel.pcscSession.Close()
}
channel.pcscSession = nil
}
}
func (channel *euiccChannel) exchange(ctx context.Context, apdu []byte) ([]byte, int, error) {
if channel.pcscSession != nil {
payload, sw, err := channel.pcscSession.Transmit(ctx, apdu)
return payload, int(sw), err
}
return channel.manager.csim(ctx, channel.id, apdu)
}
// transmit sends one APDU on the logical channel (CLA high nibble from insClass,
@@ -360,7 +432,7 @@ func (channel *euiccChannel) close(ctx context.Context) {
// and returns the assembled payload.
func (channel *euiccChannel) transmit(ctx context.Context, apdu []byte, insClass byte) ([]byte, int, error) {
apdu[0] = (apdu[0] & 0xF0) | byte(channel.channel)
payload, sw, err := channel.manager.csim(ctx, channel.id, apdu)
payload, sw, err := channel.exchange(ctx, apdu)
if err != nil {
return nil, 0, err
}
@@ -369,7 +441,7 @@ func (channel *euiccChannel) transmit(ctx context.Context, apdu []byte, insClass
for sw>>8 == 0x61 && guard < 24 {
guard++
getResponse := []byte{0x80 | byte(channel.channel), 0xC0, 0x00, 0x00, byte(sw & 0xFF)}
frag, nextSW, err := channel.manager.csim(ctx, channel.id, getResponse)
frag, nextSW, err := channel.exchange(ctx, getResponse)
if err != nil {
return nil, 0, err
}
@@ -543,8 +615,8 @@ func validProfileICCID(iccid string) bool {
// ESIMListProfiles reads the eUICC profile list via ES10c GetProfilesInfo.
func (manager *Manager) ESIMListProfiles(ctx context.Context, id string) (EsimInfo, error) {
manager.esimMu.Lock()
defer manager.esimMu.Unlock()
manager.lockESIM()
defer manager.unlockESIM()
if manager.esimRecoveryActive(id) {
if cached, ok := manager.cachedESIMInfo(id); ok {
return cached, nil
@@ -584,14 +656,14 @@ func (manager *Manager) ESIMSwitchProfile(ctx context.Context, id string, iccid
if err != nil {
return err
}
manager.esimMu.Lock()
manager.lockESIM()
if err := manager.waitForESIMRecovery(ctx, id); err != nil {
manager.esimMu.Unlock()
manager.unlockESIM()
return err
}
channel, err := manager.openEuiccAID(ctx, id, targetEuiccAID(aidHex))
if err != nil {
manager.esimMu.Unlock()
manager.unlockESIM()
return err
}
@@ -610,6 +682,7 @@ func (manager *Manager) ESIMSwitchProfile(ctx context.Context, id string, iccid
// Release the logical channel before any reset: openEuicc's csim holds
// opMu only for the duration of each APDU, so by here the lock is free.
closeContext, cancelClose := context.WithTimeout(context.Background(), csimAPDUTimeout)
channel.resetOnClose = channel.pcscSession != nil
channel.close(closeContext)
cancelClose()
if err != nil {
@@ -617,7 +690,7 @@ func (manager *Manager) ESIMSwitchProfile(ctx context.Context, id string, iccid
// detached reset is safe in either case and prevents an uncertain switch
// from leaving the modem's SIM cache unusable.
manager.startProfileSwitchRecovery(id)
manager.esimMu.Unlock()
manager.unlockESIM()
return err
}
// A transport SW 9000 only means the APDU reached the eUICC. The real outcome
@@ -626,11 +699,11 @@ func (manager *Manager) ESIMSwitchProfile(ctx context.Context, id string, iccid
result, ok := enableProfileResult(payload)
if !ok {
manager.startProfileSwitchRecovery(id)
manager.esimMu.Unlock()
manager.unlockESIM()
return fmt.Errorf("esim: unexpected EnableProfile response %s", strings.ToUpper(hex.EncodeToString(payload)))
}
if err := enableProfileResponseError(byte(result), payload); err != nil {
manager.esimMu.Unlock()
manager.unlockESIM()
return err
}
manager.markCachedProfileEnabled(id, iccid)
@@ -638,7 +711,7 @@ func (manager *Manager) ESIMSwitchProfile(ctx context.Context, id string, iccid
// a detached recovery so it survives an HTTP disconnect, but keep this API
// call pending until the live modem ICCID proves that the switch took effect.
manager.startProfileSwitchRecovery(id)
manager.esimMu.Unlock()
manager.unlockESIM()
verifyContext, cancelVerify := context.WithTimeout(context.WithoutCancel(ctx), profileSwitchVerificationTimeout(manager))
defer cancelVerify()
@@ -780,9 +853,11 @@ func (manager *Manager) renameCachedProfile(id, iccid, nickname string) {
// initiating HTTP request. EC20 commonly drops the AT port while processing
// CFUN=1,1, so the reset error is intentionally followed by discovery retries.
func (manager *Manager) recoverAfterProfileSwitch(id string) {
resetContext, cancelReset := context.WithTimeout(context.Background(), manager.longTimeout)
_ = manager.rebootForProfileSwitch(resetContext, id)
cancelReset()
if !manager.isPCSCDevice(id) {
resetContext, cancelReset := context.WithTimeout(context.Background(), manager.longTimeout)
_ = manager.rebootForProfileSwitch(resetContext, id)
cancelReset()
}
manager.refreshAfterProfileSwitch(id)
}
@@ -795,6 +870,20 @@ func (manager *Manager) recoverAfterProfileSwitch(id string) {
// the next attempt. All errors are swallowed: this is best-effort self-healing
// and setResult already records the last failure for the UI.
func (manager *Manager) refreshAfterProfileSwitch(id string) {
if manager.isPCSCDevice(id) {
time.Sleep(750 * time.Millisecond)
for attempt := 0; attempt < 10; attempt++ {
ctx, cancel := context.WithTimeout(context.Background(), manager.commandTimeout*4)
_, _ = manager.Discover(ctx)
_, err := manager.Refresh(ctx, id)
cancel()
if err == nil {
return
}
time.Sleep(time.Second)
}
return
}
const (
settle = 8 * time.Second
interval = 4 * time.Second
@@ -819,6 +908,14 @@ func (manager *Manager) refreshAfterProfileSwitch(id string) {
}
}
func (manager *Manager) isPCSCDevice(id string) bool {
state, err := manager.lookup(id)
if err != nil {
return false
}
return manager.candidateFor(state).HardwareKind == pcsc.HardwareKind
}
// enableProfileResult extracts the EnableProfile result code (tag 80) from the
// ES10c response body. ok is false when no result code is present.
func enableProfileResult(payload []byte) (int, bool) {
@@ -888,25 +985,37 @@ func (manager *Manager) verifySwitchedICCID(ctx context.Context, id, expected st
var lastICCID string
var lastErr error
for attempt := 0; attempt < attempts; attempt++ {
for _, command := range []string{"AT+CCID", "AT+QCCID"} {
commandContext, cancel := context.WithTimeout(ctx, manager.commandTimeout)
response, err := manager.ExecuteAT(commandContext, id, command)
cancel()
if err != nil {
lastErr = err
continue
if manager.isPCSCDevice(id) {
snapshot, err := manager.Refresh(ctx, id)
if err == nil {
lastICCID = strings.TrimSpace(snapshot.ICCID)
if lastICCID == expected {
return nil
}
err = fmt.Errorf("reader still reports ICCID %s", lastICCID)
}
live := parseICCIDIdentifier(response, []string{"+CCID:", "+QCCID:"}, 18, 22)
if live == "" {
lastErr = errors.New("modem response contained no valid ICCID")
continue
lastErr = err
} else {
for _, command := range []string{"AT+CCID", "AT+QCCID"} {
commandContext, cancel := context.WithTimeout(ctx, manager.commandTimeout)
response, err := manager.ExecuteAT(commandContext, id, command)
cancel()
if err != nil {
lastErr = err
continue
}
live := parseICCIDIdentifier(response, []string{"+CCID:", "+QCCID:"}, 18, 22)
if live == "" {
lastErr = errors.New("modem response contained no valid ICCID")
continue
}
lastICCID = live
if live == expected {
return nil
}
lastErr = fmt.Errorf("modem still reports ICCID %s", live)
break
}
lastICCID = live
if live == expected {
return nil
}
lastErr = fmt.Errorf("modem still reports ICCID %s", live)
break
}
if attempt+1 < attempts {
select {
+2 -2
View File
@@ -69,8 +69,8 @@ func (manager *Manager) ESIMDeleteProfile(ctx context.Context, id, iccid, aidHex
if err != nil {
return nil, err
}
manager.esimMu.Lock()
defer manager.esimMu.Unlock()
manager.lockESIM()
defer manager.unlockESIM()
if err := manager.waitForESIMRecovery(ctx, id); err != nil {
return nil, err
}
+2 -2
View File
@@ -63,8 +63,8 @@ func (manager *Manager) ESIMDisableProfile(ctx context.Context, id, iccid, aidHe
if err != nil {
return err
}
manager.esimMu.Lock()
defer manager.esimMu.Unlock()
manager.lockESIM()
defer manager.unlockESIM()
if err := manager.waitForESIMRecovery(ctx, id); err != nil {
return err
}
+6 -6
View File
@@ -48,8 +48,8 @@ func (manager *Manager) ESIMDownloadProfile(ctx context.Context, id string, para
}
}
manager.esimMu.Lock()
defer manager.esimMu.Unlock()
manager.lockESIM()
defer manager.unlockESIM()
report("preflight", "正在检查 eUICC 剩余空间...", 10)
channel, err := manager.openEuiccAID(ctx, id, targetEuiccAID(params.AIDHex))
@@ -228,8 +228,8 @@ type EsimChipInfo struct {
// ESIMChipInfo reads the eUICC's EID, EUICCInfo2, and configured addresses for
// the chip header. It takes the eSIM lock like the other card ops.
func (manager *Manager) ESIMChipInfo(ctx context.Context, id string) (*EsimChipInfo, error) {
manager.esimMu.Lock()
defer manager.esimMu.Unlock()
manager.lockESIM()
defer manager.unlockESIM()
var lastErr error
for _, aid := range manager.discoverEuiccAIDs(ctx, id) {
@@ -286,8 +286,8 @@ func readEsimChipInfo(ctx context.Context, channel *euiccChannel, aidHex string)
// the inserted card. It is entirely read-only: only SELECT, GetProfilesInfo,
// GetEuiccData, GetEuiccInfo2 and GetEuiccConfiguredAddresses are issued.
func (manager *Manager) ESIMInventory(ctx context.Context, id string) ([]EsimInventoryEntry, error) {
manager.esimMu.Lock()
defer manager.esimMu.Unlock()
manager.lockESIM()
defer manager.unlockESIM()
if manager.esimRecoveryActive(id) {
return nil, errESIMRecovering
}
+9 -1
View File
@@ -52,7 +52,7 @@ func (channel *euiccChannel) storeDataChained(ctx context.Context, derRequest []
if err != nil {
return nil, err
}
if sw != 0x9000 {
if !es10StatusOK(sw) {
return nil, fmt.Errorf("%w: SW=%04X", errESIMSW, sw)
}
assembled = append(assembled, payload...)
@@ -62,6 +62,14 @@ func (channel *euiccChannel) storeDataChained(ctx context.Context, derRequest []
return assembled, nil
}
// 91xx is a successful UICC result with a proactive SIM Toolkit command
// pending. EnableProfile commonly returns it on direct PC/SC transports because
// the requested refresh is delivered to the terminal rather than consumed by
// modem firmware. Resetting the card after the operation applies that refresh.
func es10StatusOK(sw int) bool {
return sw == 0x9000 || sw>>8 == 0x91
}
// getEUICCChallenge (ES10c, BF2E) returns the eUICC challenge bytes.
func (channel *euiccChannel) getEUICCChallenge(ctx context.Context) ([]byte, error) {
payload, err := channel.es10(ctx, []byte{0xBF, 0x2E, 0x00})
+13
View File
@@ -155,3 +155,16 @@ func TestEuiccFreeNVRAM(t *testing.T) {
t.Fatalf("expected ok=false when extCardResource absent")
}
}
func TestES10StatusAcceptsProactiveRefresh(t *testing.T) {
for _, status := range []int{0x9000, 0x9100, 0x910B, 0x91FF} {
if !es10StatusOK(status) {
t.Fatalf("status %04X should be successful", status)
}
}
for _, status := range []int{0x6A82, 0x6985, 0x9200} {
if es10StatusOK(status) {
t.Fatalf("status %04X should fail", status)
}
}
}
+4 -4
View File
@@ -295,8 +295,8 @@ func (channel *euiccChannel) deliverPendingNotifications(ctx context.Context) er
// ESIMNotifications returns the notifications retained across every eUICC
// storage exposed by the physical card.
func (manager *Manager) ESIMNotifications(ctx context.Context, id string) ([]EsimNotification, error) {
manager.esimMu.Lock()
defer manager.esimMu.Unlock()
manager.lockESIM()
defer manager.unlockESIM()
if err := manager.waitForESIMRecovery(ctx, id); err != nil {
return nil, err
}
@@ -331,8 +331,8 @@ func (manager *Manager) ESIMNotifications(ctx context.Context, id string) ([]Esi
// ESIMRetryNotification sends one retained notification and removes it from the
// eUICC only after the receiver returns the SGP.22 success acknowledgement.
func (manager *Manager) ESIMRetryNotification(ctx context.Context, id, aidHex string, sequenceNumber uint64) error {
manager.esimMu.Lock()
defer manager.esimMu.Unlock()
manager.lockESIM()
defer manager.unlockESIM()
if err := manager.waitForESIMRecovery(ctx, id); err != nil {
return err
}
+2 -2
View File
@@ -49,8 +49,8 @@ func (manager *Manager) ESIMRenameProfile(ctx context.Context, id, iccid, nickna
if err != nil {
return err
}
manager.esimMu.Lock()
defer manager.esimMu.Unlock()
manager.lockESIM()
defer manager.unlockESIM()
if err := manager.waitForESIMRecovery(ctx, id); err != nil {
return err
}
+40
View File
@@ -294,6 +294,46 @@ func TestEUICCChannelStuckWrapsTransientCME(t *testing.T) {
}
}
func TestOpenEuiccRecoversOrphanedSingleLogicalChannel(t *testing.T) {
client := &transcriptClient{steps: []clientStep{
{
command: `AT+CSIM=10,"0070000001"`,
response: okResponse(`+CSIM: 6,"006A81"`),
},
{
command: `AT+CSIM=10,"0070800100"`,
response: okResponse(`+CSIM: 4,"9000"`),
},
{
command: `AT+CSIM=10,"0070000001"`,
response: okResponse(`+CSIM: 6,"019000"`),
},
{
command: fmt.Sprintf(
`AT+CSIM=42,"01A4040010%s"`,
isdRAID,
),
response: okResponse(`+CSIM: 4,"9000"`),
},
{
command: `AT+CSIM=10,"0070800100"`,
response: okResponse(`+CSIM: 4,"9000"`),
},
}}
manager, id := newStartedTestManager(t, client)
manager.lockESIM()
channel, err := manager.openEuiccAID(context.Background(), id, isdRAID)
if err == nil {
channel.close(context.Background())
}
manager.unlockESIM()
if err != nil {
t.Fatalf("open eUICC after orphaned channel: %v", err)
}
client.assertDone(t)
}
func TestWaitForESIMRecovery(t *testing.T) {
done := make(chan struct{})
manager := &Manager{esimRecoveries: map[string]chan struct{}{"dev": done}}
+95 -4
View File
@@ -10,6 +10,7 @@ import (
"time"
"vocat/internal/modem"
"vocat/internal/pcsc"
)
type Options struct {
@@ -19,10 +20,12 @@ type Options struct {
LongTimeout time.Duration
SMSTimeout time.Duration
ScanTimeout time.Duration
CardReaders *pcsc.Service
}
type Manager struct {
mu sync.RWMutex
uiccMu sync.Mutex // serializes all multi-command UICC/APDU transactions
esimMu sync.Mutex // serializes eSIM card access (list/switch/download)
esimRecoveryMu sync.Mutex
esimRecoveries map[string]chan struct{}
@@ -34,11 +37,29 @@ type Manager struct {
longTimeout time.Duration
smsTimeout time.Duration
scanTimeout time.Duration
cardReaders *pcsc.Service
started bool
devices map[string]*managedDevice
ussdSessions map[string]ussdSession
}
// LockUICC and UnlockUICC allow another in-process UICC client (currently the
// VoWiFi AKA adapter) to share the same transaction boundary as eSIM ES10.
// Individual AT commands are already serialized per modem, but a logical-
// channel transaction spans several commands and must not be interleaved.
func (manager *Manager) LockUICC() { manager.uiccMu.Lock() }
func (manager *Manager) UnlockUICC() { manager.uiccMu.Unlock() }
func (manager *Manager) lockESIM() {
manager.esimMu.Lock()
manager.uiccMu.Lock()
}
func (manager *Manager) unlockESIM() {
manager.uiccMu.Unlock()
manager.esimMu.Unlock()
}
// ussdSession tracks an open USSD dialog on a device so a follow-up Continue or
// Cancel can be routed back to the right modem. The modem owns the actual
// network session; this map only records which device a session id belongs to.
@@ -59,6 +80,7 @@ type managedDevice struct {
discovered bool
preFlightMode *int
resetClientOnLock bool
simPIN string
}
func NewManager(options Options) (*Manager, error) {
@@ -82,6 +104,9 @@ func NewManager(options Options) (*Manager, error) {
// AT+COPS=? can take well over a minute while the modem sweeps every band.
options.ScanTimeout = 150 * time.Second
}
if options.CardReaders == nil {
options.CardReaders = pcsc.New()
}
return &Manager{
discoverer: options.Discoverer,
opener: options.Opener,
@@ -89,6 +114,7 @@ func NewManager(options Options) (*Manager, error) {
longTimeout: options.LongTimeout,
smsTimeout: options.SMSTimeout,
scanTimeout: options.ScanTimeout,
cardReaders: options.CardReaders,
devices: make(map[string]*managedDevice),
ussdSessions: make(map[string]ussdSession),
esimRecoveries: make(map[string]chan struct{}),
@@ -146,9 +172,23 @@ func (manager *Manager) Discover(ctx context.Context) ([]Device, error) {
if ctx == nil {
ctx = context.Background()
}
candidates, err := manager.discoverer.Discover(ctx)
if err != nil {
return nil, err
candidates, modemErr := manager.discoverer.Discover(ctx)
readers, readerErr := manager.cardReaders.Readers(ctx)
if readerErr == nil {
for _, reader := range readers {
candidates = append(candidates, modem.Candidate{
ID: pcsc.DeviceID(reader), HardwareKind: pcsc.HardwareKind,
ReaderName: reader.Name, USBPath: reader.USBPath,
VendorID: reader.VendorID, ProductID: reader.ProductID,
Manufacturer: reader.Manufacturer, Product: reader.Product,
})
}
}
if modemErr != nil && readerErr != nil && !errors.Is(readerErr, pcsc.ErrUnsupported) && !errors.Is(readerErr, pcsc.ErrUnavailable) {
return nil, errors.Join(modemErr, readerErr)
}
if modemErr != nil && len(candidates) == 0 {
return nil, modemErr
}
seen := make(map[string]struct{}, len(candidates))
@@ -360,6 +400,9 @@ func (manager *Manager) Refresh(ctx context.Context, id string) (Snapshot, error
return Snapshot{}, err
}
candidate := manager.candidateFor(state)
if candidate.HardwareKind == pcsc.HardwareKind {
return manager.refreshCardReader(ctx, id, state, candidate)
}
backend := manager.backendFor(state)
client, err := manager.clientLocked(ctx, state, candidate)
if err != nil {
@@ -375,11 +418,59 @@ func (manager *Manager) Refresh(ctx context.Context, id string) (Snapshot, error
return snapshot, err
}
func (manager *Manager) refreshCardReader(ctx context.Context, id string, state *managedDevice, candidate modem.Candidate) (Snapshot, error) {
result := Snapshot{
DeviceID: id, Port: candidate.ReaderName, Responsive: true,
Manufacturer: candidate.Manufacturer, Model: candidate.Product,
AccessTech: "Wi-Fi", RegistrationSource: "pcsc", OperatingMode: 4,
ModeKnown: true, FlightMode: true, RadioOff: true, UpdatedAt: time.Now().UTC(),
}
previousICCID := state.lastICCID
card, err := manager.cardReaders.Snapshot(ctx, pcsc.Selector{USBPath: candidate.USBPath, ReaderName: candidate.ReaderName}, state.simPIN)
if err != nil {
switch {
case errors.Is(err, pcsc.ErrNoCard):
result.SIMStatus = ""
err = nil
case errors.Is(err, pcsc.ErrPINRequired), errors.Is(err, pcsc.ErrPINTriesLow), errors.Is(err, pcsc.ErrPINRejected):
result.SIMStatus = "SIM PIN"
result.Warnings = []string{err.Error()}
err = nil
default:
manager.setResult(id, state, &result, err)
return result, err
}
} else {
result.SIMStatus = "READY"
result.SIMReady = true
result.ICCID = card.Identity.ICCID
result.IMSI = card.Identity.IMSI
result.SPN = card.Identity.SPN
result.SIMChanged = previousICCID != "" && !strings.EqualFold(previousICCID, result.ICCID)
state.lastICCID = result.ICCID
}
manager.setResult(id, state, &result, err)
return result, err
}
// SetSIMPin updates the in-memory PIN used for protected USIM files and AKA.
// It is deliberately never retained in runtime snapshots or logs.
func (manager *Manager) SetSIMPin(id, pin string) error {
manager.mu.Lock()
defer manager.mu.Unlock()
state := manager.devices[id]
if state == nil || !state.discovered {
return ErrNotFound
}
state.simPIN = strings.TrimSpace(pin)
return nil
}
// SetBackend selects which control plane supplies registration and data state.
// AT remains available in either mode for UICC, RF, SMS, voice and diagnostics.
func (manager *Manager) SetBackend(id, backend string) error {
backend = strings.ToLower(strings.TrimSpace(backend))
if backend != "at" && backend != "qmi" {
if backend != "at" && backend != "qmi" && backend != "pcsc" {
return fmt.Errorf("unsupported device backend %q", backend)
}
manager.mu.Lock()
+37
View File
@@ -6,8 +6,45 @@ import (
"testing"
"vocat/internal/modem"
"vocat/internal/pcsc"
)
type testPCSCBackend struct{ readers []pcsc.Reader }
func (backend testPCSCBackend) Readers(context.Context) ([]pcsc.Reader, error) {
return append([]pcsc.Reader(nil), backend.readers...), nil
}
func (testPCSCBackend) Open(context.Context, pcsc.Selector) (pcsc.Card, error) {
return nil, pcsc.ErrNoCard
}
func TestManagerDiscoversWiFiCallingOnlyReaderWithoutATPort(t *testing.T) {
manager, err := NewManager(Options{
Discoverer: staticDiscoverer{}, Opener: &staticOpener{},
CardReaders: pcsc.NewWithBackend(testPCSCBackend{readers: []pcsc.Reader{{
Name: "Alcor Link AK9563 00 00", USBPath: "1-3", Product: "AK9563",
}}}),
})
if err != nil {
t.Fatal(err)
}
if err := manager.Start(context.Background()); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = manager.Stop(context.Background()) })
items := manager.List()
if len(items) != 1 || items[0].Candidate.HardwareKind != pcsc.HardwareKind || items[0].Candidate.HasATPort() {
t.Fatalf("discovered readers = %#v", items)
}
snapshot, err := manager.Refresh(context.Background(), items[0].ID)
if err != nil {
t.Fatal(err)
}
if !snapshot.Responsive || snapshot.SIMReady || snapshot.SIMStatus != "" || !snapshot.FlightMode {
t.Fatalf("reader snapshot = %#v", snapshot)
}
}
func TestManagerRefreshBuildsEC20Snapshot(t *testing.T) {
client := &transcriptClient{steps: []clientStep{
{
+1
View File
@@ -11,6 +11,7 @@ var (
ErrNotStarted = errors.New("device manager is not started")
ErrNotFound = errors.New("device not found")
ErrNoATPort = errors.New("device has no usable AT port")
ErrUnsupportedCapability = errors.New("device does not support this capability")
ErrSMSPromptUnsupported = errors.New("device AT client does not support SMS prompt mode")
ErrSMSInvalidRecipient = errors.New("invalid SMS recipient")
ErrSMSEmpty = errors.New("SMS text is empty")
+2
View File
@@ -44,6 +44,8 @@ func (p Port) OpenPath() string {
}
type Candidate struct {
HardwareKind string `json:"hardwareKind,omitempty"`
ReaderName string `json:"readerName,omitempty"`
ID string `json:"id"`
VendorID string `json:"vendorId"`
ProductID string `json:"productId"`
+238
View File
@@ -0,0 +1,238 @@
//go:build linux && (amd64 || arm64)
package pcsc
import (
"context"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"net"
"os"
"path/filepath"
"strconv"
"strings"
"time"
)
type nativeBackend struct{}
func newNativeBackend() Backend { return &nativeBackend{} }
func (backend *nativeBackend) dial(ctx context.Context) (*pcscdClient, error) {
paths := []string{strings.TrimSpace(os.Getenv("PCSCLITE_CSOCK_NAME")), "/run/pcscd/pcscd.comm", "/var/run/pcscd/pcscd.comm"}
var failures []error
seen := make(map[string]bool)
for _, path := range paths {
if path == "" || seen[path] {
continue
}
seen[path] = true
conn, err := (&net.Dialer{Timeout: 5 * time.Second}).DialContext(ctx, "unix", path)
if err != nil {
failures = append(failures, err)
continue
}
client, err := establishPCSCD(ctx, conn)
if err == nil {
return client, nil
}
_ = conn.Close()
failures = append(failures, err)
}
return nil, fmt.Errorf("%w: pcscd socket is not reachable: %w", ErrUnavailable, errors.Join(failures...))
}
func (backend *nativeBackend) Readers(ctx context.Context) ([]Reader, error) {
client, err := backend.dial(ctx)
if err != nil {
return nil, err
}
defer client.closeContext(context.Background())
states, err := client.readers(ctx)
if err != nil {
return nil, err
}
readers := make([]Reader, 0, len(states))
for _, state := range states {
reader := Reader{
Name: state.name,
CardPresent: state.state&pcscCardPresent != 0,
ATR: strings.ToUpper(hex.EncodeToString(state.atr)),
}
if path, ok := backend.readerUSBPath(ctx, client, state.name); ok {
reader.USBPath = path
reader.VendorID = readSysfsText(path, "idVendor")
reader.ProductID = readSysfsText(path, "idProduct")
reader.Manufacturer = readSysfsText(path, "manufacturer")
reader.Product = readSysfsText(path, "product")
} else {
reader.USBPath = "pcsc:" + state.name
}
if reader.Product == "" {
reader.Product = strings.TrimSpace(strings.TrimSuffix(state.name, " 00 00"))
}
readers = append(readers, reader)
}
return readers, nil
}
func (backend *nativeBackend) readerUSBPath(ctx context.Context, client *pcscdClient, name string) (string, bool) {
card, _, err := client.connect(ctx, name, pcscShareDirect, 0)
if err != nil {
return "", false
}
disposition := uint32(pcscLeaveCard)
defer client.simpleCardCommand(context.Background(), pcscCmdDisconnect, card, &disposition)
attribute, err := client.getAttrib(ctx, card, pcscAttrChannelID)
if err != nil || len(attribute) < 4 {
return "", false
}
channel := binary.LittleEndian.Uint32(attribute[:4])
if channel>>16 != 0x0020 {
return "", false
}
bus, device := int((channel>>8)&0xff), int(channel&0xff)
entries, err := os.ReadDir("/sys/bus/usb/devices")
if err != nil {
return "", false
}
for _, entry := range entries {
if !entry.IsDir() && entry.Type()&os.ModeSymlink == 0 {
continue
}
path := filepath.Join("/sys/bus/usb/devices", entry.Name())
entryBus, busErr := readSysfsInt(path, "busnum")
entryDevice, deviceErr := readSysfsInt(path, "devnum")
if busErr == nil && deviceErr == nil && entryBus == bus && entryDevice == device {
return entry.Name(), true
}
}
return "", false
}
func (backend *nativeBackend) Open(ctx context.Context, selector Selector) (Card, error) {
readers, err := backend.Readers(ctx)
if err != nil {
return nil, err
}
reader, ok := matchReader(readers, selector)
if !ok {
return nil, ErrReaderNotFound
}
if !reader.CardPresent {
return nil, ErrNoCard
}
client, err := backend.dial(ctx)
if err != nil {
return nil, err
}
handle, protocol, err := client.connect(ctx, reader.Name, pcscShareShared, pcscProtocolAny)
if err != nil {
_ = client.closeContext(context.Background())
return nil, err
}
if err := client.simpleCardCommand(ctx, pcscCmdBeginTransaction, handle, nil); err != nil {
disposition := uint32(pcscLeaveCard)
_ = client.simpleCardCommand(context.Background(), pcscCmdDisconnect, handle, &disposition)
_ = client.closeContext(context.Background())
return nil, fmt.Errorf("pcsc: begin card transaction: %w", err)
}
return &nativeCard{client: client, handle: handle, protocol: protocol}, nil
}
type nativeCard struct {
client *pcscdClient
handle int32
protocol uint32
closed bool
}
func (card *nativeCard) Transmit(ctx context.Context, command []byte) ([]byte, uint16, error) {
if card == nil || card.client == nil || card.closed {
return nil, 0, errors.New("pcsc: card session is closed")
}
return card.transmit(ctx, append([]byte(nil), command...), 0)
}
func (card *nativeCard) TransmitRaw(ctx context.Context, command []byte) ([]byte, uint16, error) {
if card == nil || card.client == nil || card.closed {
return nil, 0, errors.New("pcsc: card session is closed")
}
response, err := card.client.transmit(ctx, card.handle, card.protocol, append([]byte(nil), command...))
if err != nil {
return nil, 0, err
}
if len(response) < 2 {
return nil, 0, errors.New("pcsc: APDU response omitted its status word")
}
last := len(response) - 2
return append([]byte(nil), response[:last]...), uint16(response[last])<<8 | uint16(response[last+1]), nil
}
func (card *nativeCard) transmit(ctx context.Context, command []byte, depth int) ([]byte, uint16, error) {
if depth > 8 {
return nil, 0, errors.New("pcsc: too many APDU continuations")
}
data, status, err := card.TransmitRaw(ctx, command)
if err != nil {
return nil, 0, err
}
sw1, sw2 := byte(status>>8), byte(status)
if sw1 == 0x6c && len(command) >= 5 {
retry := append([]byte(nil), command...)
retry[len(retry)-1] = sw2
return card.transmit(ctx, retry, depth+1)
}
if sw1 == 0x61 || sw1 == 0x9f {
more, sw, err := card.transmit(ctx, []byte{0x00, 0xc0, 0x00, 0x00, sw2}, depth+1)
if err != nil {
return nil, 0, err
}
return append(data, more...), sw, nil
}
return data, status, ctx.Err()
}
func (card *nativeCard) Close() error { return card.close(pcscLeaveCard) }
func (card *nativeCard) CloseWithReset() error { return card.close(pcscResetCard) }
func (card *nativeCard) close(disposition uint32) error {
if card == nil || card.closed {
return nil
}
card.closed = true
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
var result []error
if card.client != nil {
if err := card.client.simpleCardCommand(ctx, pcscCmdEndTransaction, card.handle, &disposition); err != nil {
result = append(result, err)
}
if err := card.client.simpleCardCommand(ctx, pcscCmdDisconnect, card.handle, &disposition); err != nil {
result = append(result, err)
}
if err := card.client.closeContext(ctx); err != nil {
result = append(result, err)
}
}
return errors.Join(result...)
}
func readSysfsText(usbPath, name string) string {
value, err := os.ReadFile(filepath.Join("/sys/bus/usb/devices", usbPath, name))
if err != nil {
return ""
}
return strings.TrimSpace(string(value))
}
func readSysfsInt(path, name string) (int, error) {
value, err := os.ReadFile(filepath.Join(path, name))
if err != nil {
return 0, err
}
return strconv.Atoi(strings.TrimSpace(string(value)))
}
+17
View File
@@ -0,0 +1,17 @@
//go:build !linux || (!amd64 && !arm64)
package pcsc
import "context"
type unsupportedBackend struct{}
func newNativeBackend() Backend { return unsupportedBackend{} }
func (unsupportedBackend) Readers(context.Context) ([]Reader, error) {
return nil, ErrUnsupported
}
func (unsupportedBackend) Open(context.Context, Selector) (Card, error) {
return nil, ErrUnsupported
}
+334
View File
@@ -0,0 +1,334 @@
package pcsc
import (
"context"
"encoding/binary"
"errors"
"fmt"
"io"
"net"
"time"
)
// pcsc-lite exposes a small, versioned protocol over its local Unix socket.
// Speaking that protocol directly keeps VoCat's Linux binaries fully static;
// loading libpcsclite through dlopen would pull a glibc interpreter into an
// otherwise CGO-free build and make it unusable on musl-based routers.
const (
pcscProtocolMajor = 4
pcscProtocolCurrentMinor = 6
pcscProtocolOldestMinor = 4
pcscCmdEstablishContext = 0x01
pcscCmdReleaseContext = 0x02
pcscCmdConnect = 0x04
pcscCmdDisconnect = 0x06
pcscCmdBeginTransaction = 0x07
pcscCmdEndTransaction = 0x08
pcscCmdTransmit = 0x09
pcscCmdGetAttrib = 0x0f
pcscCmdVersion = 0x11
pcscCmdGetReadersState = 0x12
pcscScopeSystem = 0x0002
pcscProtocolT0 = 0x0001
pcscProtocolT1 = 0x0002
pcscProtocolAny = pcscProtocolT0 | pcscProtocolT1
pcscShareShared = 0x0002
pcscShareDirect = 0x0003
pcscLeaveCard = 0x0000
pcscResetCard = 0x0001
pcscCardPresent = 0x0004
pcscAttrChannelID = 0x00020110
pcscMaxReaderName = 128
pcscMaxATR = 33
pcscMaxReaders = 16
pcscReaderStateSize = 184
pcscGetSetBodySize = 280
pcscMaxAttribute = 264
pcscMaxAPDUResponse = 65548
pcscDefaultIOTimeout = 30 * time.Second
pcscSuccess = uint32(0)
pcscNoSmartcard = uint32(0x8010000c)
pcscNoService = uint32(0x8010001d)
pcscServiceStopped = uint32(0x8010001e)
pcscNoReaders = uint32(0x8010002e)
)
type pcscdClient struct {
conn net.Conn
contextID uint32
serverMinor int32
}
type pcscdReaderState struct {
name string
state uint32
atr []byte
protocol uint32
}
func establishPCSCD(ctx context.Context, conn net.Conn) (*pcscdClient, error) {
client := &pcscdClient{conn: conn}
version := make([]byte, 12)
binary.LittleEndian.PutUint32(version[0:4], pcscProtocolMajor)
binary.LittleEndian.PutUint32(version[4:8], pcscProtocolCurrentMinor)
for {
if err := client.exchange(ctx, pcscCmdVersion, version); err != nil {
return nil, err
}
major := int32(binary.LittleEndian.Uint32(version[0:4]))
client.serverMinor = int32(binary.LittleEndian.Uint32(version[4:8]))
rv := binary.LittleEndian.Uint32(version[8:12])
if rv == pcscSuccess {
break
}
if rv != pcscServiceStopped || major != pcscProtocolMajor || client.serverMinor < pcscProtocolOldestMinor || client.serverMinor >= pcscProtocolCurrentMinor {
return nil, pcscError("negotiate protocol", rv)
}
// pcsc-lite answers a newer client's first probe with its own
// compatible minor version. Retry on the same connection with that
// value, matching libpcsclite's official fallback behavior.
binary.LittleEndian.PutUint32(version[0:4], pcscProtocolMajor)
binary.LittleEndian.PutUint32(version[4:8], uint32(client.serverMinor))
binary.LittleEndian.PutUint32(version[8:12], pcscSuccess)
}
if client.serverMinor < pcscProtocolOldestMinor {
return nil, fmt.Errorf("pcsc: unsupported pcscd protocol %d.%d", pcscProtocolMajor, client.serverMinor)
}
body := make([]byte, 12)
binary.LittleEndian.PutUint32(body[0:4], pcscScopeSystem)
if err := client.exchange(ctx, pcscCmdEstablishContext, body); err != nil {
return nil, err
}
if rv := binary.LittleEndian.Uint32(body[8:12]); rv != pcscSuccess {
return nil, pcscError("establish context", rv)
}
client.contextID = binary.LittleEndian.Uint32(body[4:8])
return client, nil
}
func (client *pcscdClient) exchange(ctx context.Context, command uint32, body []byte) error {
if client == nil || client.conn == nil {
return errors.New("pcsc: pcscd connection is closed")
}
if err := client.setDeadline(ctx); err != nil {
return err
}
header := make([]byte, 8)
binary.LittleEndian.PutUint32(header[0:4], uint32(len(body)))
binary.LittleEndian.PutUint32(header[4:8], command)
if err := writeAll(client.conn, header); err != nil {
return fmt.Errorf("pcsc: send command %02x: %w", command, err)
}
if len(body) > 0 {
if err := writeAll(client.conn, body); err != nil {
return fmt.Errorf("pcsc: send command body %02x: %w", command, err)
}
if _, err := io.ReadFull(client.conn, body); err != nil {
return fmt.Errorf("pcsc: receive command %02x: %w", command, err)
}
}
return nil
}
func (client *pcscdClient) send(ctx context.Context, command uint32, body, extra []byte) error {
if client == nil || client.conn == nil {
return errors.New("pcsc: pcscd connection is closed")
}
if err := client.setDeadline(ctx); err != nil {
return err
}
header := make([]byte, 8)
binary.LittleEndian.PutUint32(header[0:4], uint32(len(body)))
binary.LittleEndian.PutUint32(header[4:8], command)
if err := writeAll(client.conn, header); err != nil {
return err
}
if err := writeAll(client.conn, body); err != nil {
return err
}
return writeAll(client.conn, extra)
}
func (client *pcscdClient) setDeadline(ctx context.Context) error {
if err := ctx.Err(); err != nil {
return err
}
deadline := time.Now().Add(pcscDefaultIOTimeout)
if value, ok := ctx.Deadline(); ok && value.Before(deadline) {
deadline = value
}
return client.conn.SetDeadline(deadline)
}
func (client *pcscdClient) readers(ctx context.Context) ([]pcscdReaderState, error) {
if err := client.setDeadline(ctx); err != nil {
return nil, err
}
header := make([]byte, 8)
binary.LittleEndian.PutUint32(header[4:8], pcscCmdGetReadersState)
if err := writeAll(client.conn, header); err != nil {
return nil, fmt.Errorf("pcsc: request reader states: %w", err)
}
raw := make([]byte, pcscMaxReaders*pcscReaderStateSize)
if _, err := io.ReadFull(client.conn, raw); err != nil {
return nil, fmt.Errorf("pcsc: read reader states: %w", err)
}
result := make([]pcscdReaderState, 0, pcscMaxReaders)
for offset := 0; offset < len(raw); offset += pcscReaderStateSize {
state := raw[offset : offset+pcscReaderStateSize]
name := cString(state[:pcscMaxReaderName])
if name == "" {
continue
}
atrLen := int(binary.LittleEndian.Uint32(state[176:180]))
if atrLen < 0 || atrLen > pcscMaxATR {
atrLen = 0
}
result = append(result, pcscdReaderState{
name: name,
state: binary.LittleEndian.Uint32(state[132:136]),
atr: append([]byte(nil), state[140:140+atrLen]...),
protocol: binary.LittleEndian.Uint32(state[180:184]),
})
}
return result, nil
}
func (client *pcscdClient) connect(ctx context.Context, reader string, share, protocols uint32) (int32, uint32, error) {
if len(reader) >= pcscMaxReaderName {
return 0, 0, errors.New("pcsc: reader name is too long")
}
body := make([]byte, 152)
binary.LittleEndian.PutUint32(body[0:4], client.contextID)
copy(body[4:132], reader)
binary.LittleEndian.PutUint32(body[132:136], share)
binary.LittleEndian.PutUint32(body[136:140], protocols)
if err := client.exchange(ctx, pcscCmdConnect, body); err != nil {
return 0, 0, err
}
if rv := binary.LittleEndian.Uint32(body[148:152]); rv != pcscSuccess {
return 0, 0, pcscError("connect reader", rv)
}
return int32(binary.LittleEndian.Uint32(body[140:144])), binary.LittleEndian.Uint32(body[144:148]), nil
}
func (client *pcscdClient) simpleCardCommand(ctx context.Context, command uint32, card int32, disposition *uint32) error {
size := 8
if disposition != nil {
size = 12
}
body := make([]byte, size)
binary.LittleEndian.PutUint32(body[0:4], uint32(card))
if disposition != nil {
binary.LittleEndian.PutUint32(body[4:8], *disposition)
}
if err := client.exchange(ctx, command, body); err != nil {
return err
}
if rv := binary.LittleEndian.Uint32(body[size-4:]); rv != pcscSuccess {
return pcscError("card command", rv)
}
return nil
}
func (client *pcscdClient) transmit(ctx context.Context, card int32, protocol uint32, command []byte) ([]byte, error) {
body := make([]byte, 32)
binary.LittleEndian.PutUint32(body[0:4], uint32(card))
binary.LittleEndian.PutUint32(body[4:8], protocol)
binary.LittleEndian.PutUint32(body[8:12], 8)
binary.LittleEndian.PutUint32(body[12:16], uint32(len(command)))
binary.LittleEndian.PutUint32(body[16:20], pcscProtocolAny)
binary.LittleEndian.PutUint32(body[20:24], 8)
binary.LittleEndian.PutUint32(body[24:28], pcscMaxAPDUResponse)
if err := client.send(ctx, pcscCmdTransmit, body, command); err != nil {
return nil, fmt.Errorf("pcsc: transmit APDU: %w", err)
}
if _, err := io.ReadFull(client.conn, body); err != nil {
return nil, fmt.Errorf("pcsc: receive APDU result: %w", err)
}
if rv := binary.LittleEndian.Uint32(body[28:32]); rv != pcscSuccess {
return nil, pcscError("transmit APDU", rv)
}
length := binary.LittleEndian.Uint32(body[24:28])
if length > pcscMaxAPDUResponse {
return nil, errors.New("pcsc: pcscd returned an oversized APDU")
}
response := make([]byte, length)
if _, err := io.ReadFull(client.conn, response); err != nil {
return nil, fmt.Errorf("pcsc: receive APDU: %w", err)
}
return response, nil
}
func (client *pcscdClient) getAttrib(ctx context.Context, card int32, attribute uint32) ([]byte, error) {
body := make([]byte, pcscGetSetBodySize)
binary.LittleEndian.PutUint32(body[0:4], uint32(card))
binary.LittleEndian.PutUint32(body[4:8], attribute)
binary.LittleEndian.PutUint32(body[272:276], pcscMaxAttribute)
if err := client.exchange(ctx, pcscCmdGetAttrib, body); err != nil {
return nil, err
}
if rv := binary.LittleEndian.Uint32(body[276:280]); rv != pcscSuccess {
return nil, pcscError("get reader attribute", rv)
}
length := binary.LittleEndian.Uint32(body[272:276])
if length > pcscMaxAttribute {
return nil, errors.New("pcsc: pcscd returned an oversized attribute")
}
return append([]byte(nil), body[8:8+length]...), nil
}
func (client *pcscdClient) closeContext(ctx context.Context) error {
if client == nil || client.conn == nil {
return nil
}
body := make([]byte, 8)
binary.LittleEndian.PutUint32(body[0:4], client.contextID)
err := client.exchange(ctx, pcscCmdReleaseContext, body)
if err == nil {
if rv := binary.LittleEndian.Uint32(body[4:8]); rv != pcscSuccess {
err = pcscError("release context", rv)
}
}
closeErr := client.conn.Close()
client.conn = nil
return errors.Join(err, closeErr)
}
func pcscError(operation string, code uint32) error {
switch code {
case pcscNoSmartcard:
return ErrNoCard
case pcscNoService, pcscServiceStopped:
return fmt.Errorf("%w: %s failed with PC/SC status %08X", ErrUnavailable, operation, code)
case pcscNoReaders:
return ErrReaderNotFound
default:
return fmt.Errorf("pcsc: %s failed with status %08X", operation, code)
}
}
func cString(value []byte) string {
for index, current := range value {
if current == 0 {
return string(value[:index])
}
}
return string(value)
}
func writeAll(writer io.Writer, value []byte) error {
for len(value) > 0 {
written, err := writer.Write(value)
if err != nil {
return err
}
if written == 0 {
return io.ErrUnexpectedEOF
}
value = value[written:]
}
return nil
}
+127
View File
@@ -0,0 +1,127 @@
package pcsc
import (
"bytes"
"context"
"encoding/binary"
"errors"
"io"
"net"
"testing"
)
func TestPCSCDClientLifecycleAndTransmit(t *testing.T) {
clientConn, serverConn := net.Pipe()
serverDone := make(chan error, 1)
go func() {
defer serverConn.Close()
serverDone <- servePCSCDTestSession(serverConn)
}()
client, err := establishPCSCD(context.Background(), clientConn)
if err != nil {
t.Fatalf("establishPCSCD: %v", err)
}
states, err := client.readers(context.Background())
if err != nil {
t.Fatalf("readers: %v", err)
}
if len(states) != 1 || states[0].name != "VoCat Test Reader 00 00" || states[0].state&pcscCardPresent == 0 {
t.Fatalf("states = %#v", states)
}
handle, protocol, err := client.connect(context.Background(), states[0].name, pcscShareShared, pcscProtocolAny)
if err != nil {
t.Fatalf("connect: %v", err)
}
if handle != 42 || protocol != pcscProtocolT1 {
t.Fatalf("handle/protocol = %d/%d", handle, protocol)
}
if err := client.simpleCardCommand(context.Background(), pcscCmdBeginTransaction, handle, nil); err != nil {
t.Fatalf("begin: %v", err)
}
response, err := client.transmit(context.Background(), handle, protocol, []byte{0x00, 0xa4, 0x00, 0x00})
if err != nil {
t.Fatalf("transmit: %v", err)
}
if !bytes.Equal(response, []byte{0x62, 0x02, 0x90, 0x00}) {
t.Fatalf("response = %x", response)
}
disposition := uint32(pcscLeaveCard)
if err := client.simpleCardCommand(context.Background(), pcscCmdEndTransaction, handle, &disposition); err != nil {
t.Fatalf("end: %v", err)
}
if err := client.simpleCardCommand(context.Background(), pcscCmdDisconnect, handle, &disposition); err != nil {
t.Fatalf("disconnect: %v", err)
}
if err := client.closeContext(context.Background()); err != nil {
t.Fatalf("close context: %v", err)
}
if err := <-serverDone; err != nil {
t.Fatalf("fake pcscd: %v", err)
}
}
func servePCSCDTestSession(conn net.Conn) error {
for {
header := make([]byte, 8)
if _, err := io.ReadFull(conn, header); err != nil {
return err
}
size := binary.LittleEndian.Uint32(header[0:4])
command := binary.LittleEndian.Uint32(header[4:8])
body := make([]byte, size)
if _, err := io.ReadFull(conn, body); err != nil {
return err
}
switch command {
case pcscCmdVersion:
binary.LittleEndian.PutUint32(body[0:4], pcscProtocolMajor)
binary.LittleEndian.PutUint32(body[4:8], pcscProtocolCurrentMinor)
if err := writeAll(conn, body); err != nil {
return err
}
case pcscCmdEstablishContext:
binary.LittleEndian.PutUint32(body[4:8], 7)
if err := writeAll(conn, body); err != nil {
return err
}
case pcscCmdGetReadersState:
states := make([]byte, pcscMaxReaders*pcscReaderStateSize)
copy(states, "VoCat Test Reader 00 00")
binary.LittleEndian.PutUint32(states[132:136], pcscCardPresent)
copy(states[140:143], []byte{0x3b, 0x00, 0x00})
binary.LittleEndian.PutUint32(states[176:180], 3)
binary.LittleEndian.PutUint32(states[180:184], pcscProtocolT1)
if err := writeAll(conn, states); err != nil {
return err
}
case pcscCmdConnect:
binary.LittleEndian.PutUint32(body[140:144], 42)
binary.LittleEndian.PutUint32(body[144:148], pcscProtocolT1)
if err := writeAll(conn, body); err != nil {
return err
}
case pcscCmdBeginTransaction, pcscCmdEndTransaction, pcscCmdDisconnect:
if err := writeAll(conn, body); err != nil {
return err
}
case pcscCmdTransmit:
commandBody := make([]byte, binary.LittleEndian.Uint32(body[12:16]))
if _, err := io.ReadFull(conn, commandBody); err != nil {
return err
}
response := []byte{0x62, 0x02, 0x90, 0x00}
binary.LittleEndian.PutUint32(body[24:28], uint32(len(response)))
if err := writeAll(conn, body); err != nil {
return err
}
if err := writeAll(conn, response); err != nil {
return err
}
case pcscCmdReleaseContext:
return writeAll(conn, body)
default:
return errors.New("unexpected fake pcscd command")
}
}
}
+610
View File
@@ -0,0 +1,610 @@
package pcsc
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"strings"
"sync"
)
const usimAIDPrefix = "A0000000871002"
type Service struct {
mu sync.Mutex
backend Backend
}
// Session is an exclusive connection to one smart card. It is used by eUICC
// operations which must keep the same PC/SC transaction and logical channel
// alive across a sequence of APDUs.
type Session struct {
service *Service
card Card
closed bool
}
func New() *Service {
return &Service{backend: newNativeBackend()}
}
func NewWithBackend(backend Backend) *Service {
return &Service{backend: backend}
}
func DeviceID(reader Reader) string {
identity := strings.TrimSpace(reader.USBPath)
if identity == "" {
identity = strings.TrimSpace(reader.Name)
}
sum := sha256.Sum256([]byte(identity))
return "reader-" + hex.EncodeToString(sum[:8])
}
func (service *Service) Readers(ctx context.Context) ([]Reader, error) {
if service == nil || service.backend == nil {
return nil, ErrUnavailable
}
service.mu.Lock()
defer service.mu.Unlock()
return service.backend.Readers(ctx)
}
// OpenSession opens one card and holds the service lock until Close. Callers
// must close the returned session; this prevents AKA/identity reads from
// interleaving with a stateful ES10 transaction.
func (service *Service) OpenSession(ctx context.Context, selector Selector) (*Session, error) {
if service == nil || service.backend == nil {
return nil, ErrUnavailable
}
if err := selector.validate(); err != nil {
return nil, err
}
service.mu.Lock()
card, err := service.backend.Open(ctx, selector)
if err != nil {
service.mu.Unlock()
return nil, err
}
return &Session{service: service, card: card}, nil
}
// Transmit sends one raw APDU. Unlike the ordinary SIM helpers, it leaves
// 61xx continuation handling to the eUICC logical-channel implementation so
// GET RESPONSE uses the correct channel CLA.
func (session *Session) Transmit(ctx context.Context, command []byte) ([]byte, uint16, error) {
if session == nil || session.card == nil || session.closed {
return nil, 0, errors.New("pcsc: card session is closed")
}
if raw, ok := session.card.(interface {
TransmitRaw(context.Context, []byte) ([]byte, uint16, error)
}); ok {
return raw.TransmitRaw(ctx, command)
}
return session.card.Transmit(ctx, command)
}
func (session *Session) Close() error {
return session.close(false)
}
// CloseWithReset resets the card while releasing the PC/SC connection. eUICC
// EnableProfile requires this refresh boundary before the newly enabled USIM
// application and ICCID become visible to subsequent callers.
func (session *Session) CloseWithReset() error {
return session.close(true)
}
func (session *Session) close(reset bool) error {
if session == nil || session.closed {
return nil
}
session.closed = true
var err error
if resetter, ok := session.card.(interface{ CloseWithReset() error }); reset && ok {
err = resetter.CloseWithReset()
} else {
err = session.card.Close()
}
session.service.mu.Unlock()
return err
}
func (service *Service) Snapshot(ctx context.Context, selector Selector, pin string) (Snapshot, error) {
readers, err := service.Readers(ctx)
if err != nil {
return Snapshot{}, err
}
reader, ok := matchReader(readers, selector)
if !ok {
return Snapshot{}, ErrReaderNotFound
}
result := Snapshot{Reader: reader}
if !reader.CardPresent {
return result, ErrNoCard
}
identity, err := service.ReadIdentity(ctx, selector, pin)
result.Identity = identity
return result, err
}
func (service *Service) ReadIdentity(ctx context.Context, selector Selector, pin string) (Identity, error) {
if service == nil || service.backend == nil {
return Identity{}, ErrUnavailable
}
if err := selector.validate(); err != nil {
return Identity{}, err
}
service.mu.Lock()
defer service.mu.Unlock()
card, err := service.backend.Open(ctx, selector)
if err != nil {
return Identity{}, err
}
defer card.Close()
return readIdentity(ctx, card, pin)
}
func (service *Service) CheckReady(
ctx context.Context,
selector Selector,
expectedICCID string,
pin string,
) (string, error) {
if service == nil || service.backend == nil {
return "", ErrUnavailable
}
service.mu.Lock()
defer service.mu.Unlock()
card, err := service.backend.Open(ctx, selector)
if err != nil {
return "", err
}
defer card.Close()
iccid, err := readICCID(ctx, card)
if err != nil {
return "", err
}
if expected := strings.TrimSpace(expectedICCID); expected != "" && !strings.EqualFold(expected, iccid) {
return "", ErrCardChanged
}
aid, err := selectUSIM(ctx, card)
if err != nil {
return "", err
}
if err := verifyPIN(ctx, card, pin); err != nil {
return "", err
}
return strings.ToUpper(hex.EncodeToString(aid)), nil
}
func (service *Service) Authenticate(
ctx context.Context,
selector Selector,
expectedICCID string,
pin string,
challenge AKAChallenge,
) (AKAResult, error) {
if service == nil || service.backend == nil {
return AKAResult{}, ErrUnavailable
}
service.mu.Lock()
defer service.mu.Unlock()
card, err := service.backend.Open(ctx, selector)
if err != nil {
return AKAResult{}, err
}
defer card.Close()
iccid, err := readICCID(ctx, card)
if err != nil {
return AKAResult{}, err
}
if expected := strings.TrimSpace(expectedICCID); expected != "" && !strings.EqualFold(expected, iccid) {
return AKAResult{}, ErrCardChanged
}
if _, err := selectUSIM(ctx, card); err != nil {
return AKAResult{}, err
}
if err := verifyPIN(ctx, card, pin); err != nil {
return AKAResult{}, err
}
apdu := make([]byte, 0, 40)
apdu = append(apdu, 0x00, 0x88, 0x00, 0x81, 0x22, 0x10)
apdu = append(apdu, challenge.RAND[:]...)
apdu = append(apdu, 0x10)
apdu = append(apdu, challenge.AUTN[:]...)
apdu = append(apdu, 0x00)
data, sw, err := card.Transmit(ctx, apdu)
if err != nil {
return AKAResult{}, errors.New("pcsc: USIM authentication transport failed")
}
if sw == 0x9862 {
return AKAResult{}, ErrAKARejected
}
if sw != 0x9000 {
return AKAResult{}, fmt.Errorf("pcsc: USIM authentication failed with status %04X", sw)
}
return parseAKAResponse(data)
}
func matchReader(readers []Reader, selector Selector) (Reader, bool) {
path := strings.TrimSpace(selector.USBPath)
name := strings.TrimSpace(selector.ReaderName)
for _, reader := range readers {
if path != "" && reader.USBPath == path {
return reader, true
}
}
for _, reader := range readers {
if name != "" && reader.Name == name {
return reader, true
}
}
return Reader{}, false
}
func readIdentity(ctx context.Context, card Card, pin string) (Identity, error) {
identity := Identity{PINTries: -1}
iccid, err := readICCID(ctx, card)
if err != nil {
return identity, err
}
identity.ICCID = iccid
aid, err := selectUSIM(ctx, card)
if err != nil {
return identity, err
}
identity.USIMAID = append([]byte(nil), aid...)
if err := verifyPIN(ctx, card, pin); err != nil {
identity.PINRequired = errors.Is(err, ErrPINRequired) || errors.Is(err, ErrPINTriesLow)
var pinErr *PINError
if errors.As(err, &pinErr) {
identity.PINTries = pinErr.Tries
}
return identity, err
}
if err := selectFile(ctx, card, []byte{0x6F, 0x07}); err != nil {
return identity, fmt.Errorf("pcsc: select EF_IMSI: %w", err)
}
imsiData, err := readBinary(ctx, card, 9)
if err != nil {
return identity, fmt.Errorf("pcsc: read EF_IMSI: %w", err)
}
identity.IMSI, err = decodeIMSI(imsiData)
if err != nil {
return identity, err
}
if _, selectErr := selectApplication(ctx, card, aid); selectErr == nil {
if selectErr = selectFile(ctx, card, []byte{0x6F, 0xAD}); selectErr == nil {
if data, readErr := readBinary(ctx, card, 4); readErr == nil && len(data) >= 4 {
length := int(data[3] & 0x0f)
if length == 2 || length == 3 {
identity.MNCLength = length
}
}
}
}
if _, selectErr := selectApplication(ctx, card, aid); selectErr == nil {
identity.SPN = readSPN(ctx, card)
}
if _, selectErr := selectApplication(ctx, card, aid); selectErr == nil {
identity.SMSC = readSMSC(ctx, card)
}
return identity, nil
}
func readICCID(ctx context.Context, card Card) (string, error) {
if err := selectMF(ctx, card); err != nil {
return "", err
}
if err := selectFile(ctx, card, []byte{0x2F, 0xE2}); err != nil {
return "", fmt.Errorf("pcsc: select EF_ICCID: %w", err)
}
data, err := readBinary(ctx, card, 10)
if err != nil {
return "", fmt.Errorf("pcsc: read EF_ICCID: %w", err)
}
value := decodeSwappedBCD(data, false)
if len(value) < 18 || len(value) > 22 {
return "", errors.New("pcsc: card returned an invalid ICCID")
}
return value, nil
}
func selectUSIM(ctx context.Context, card Card) ([]byte, error) {
if err := selectMF(ctx, card); err != nil {
return nil, err
}
if err := selectFile(ctx, card, []byte{0x2F, 0x00}); err != nil {
return nil, fmt.Errorf("pcsc: select EF_DIR: %w", err)
}
var usimAID []byte
for record := 1; record <= 32; record++ {
data, sw, err := card.Transmit(ctx, []byte{0x00, 0xB2, byte(record), 0x04, 0x00})
if err != nil {
return nil, err
}
if sw == 0x6A83 || sw == 0x9402 {
break
}
if sw != 0x9000 {
continue
}
aid := findTLV(data, 0x4F)
if len(aid) == 0 {
continue
}
if strings.HasPrefix(strings.ToUpper(hex.EncodeToString(aid)), usimAIDPrefix) {
usimAID = append([]byte(nil), aid...)
break
}
}
if len(usimAID) == 0 {
return nil, ErrUSIMUnavailable
}
if _, err := selectApplication(ctx, card, usimAID); err != nil {
return nil, err
}
return usimAID, nil
}
func selectMF(ctx context.Context, card Card) error {
_, sw, err := card.Transmit(ctx, []byte{0x00, 0xA4, 0x00, 0x04, 0x02, 0x3F, 0x00, 0x00})
return requireStatus("select MF", sw, err)
}
func selectFile(ctx context.Context, card Card, fileID []byte) error {
if len(fileID) != 2 {
return errors.New("pcsc: invalid file identifier")
}
apdu := []byte{0x00, 0xA4, 0x00, 0x04, 0x02, fileID[0], fileID[1], 0x00}
_, sw, err := card.Transmit(ctx, apdu)
return requireStatus("select file", sw, err)
}
func selectApplication(ctx context.Context, card Card, aid []byte) ([]byte, error) {
if len(aid) == 0 || len(aid) > 32 {
return nil, errors.New("pcsc: invalid USIM AID")
}
apdu := []byte{0x00, 0xA4, 0x04, 0x04, byte(len(aid))}
apdu = append(apdu, aid...)
apdu = append(apdu, 0x00)
data, sw, err := card.Transmit(ctx, apdu)
if err := requireStatus("select USIM application", sw, err); err != nil {
return nil, err
}
return data, nil
}
func readBinary(ctx context.Context, card Card, length int) ([]byte, error) {
if length <= 0 || length > 256 {
return nil, errors.New("pcsc: invalid binary read length")
}
le := byte(length)
if length == 256 {
le = 0
}
data, sw, err := card.Transmit(ctx, []byte{0x00, 0xB0, 0x00, 0x00, le})
if err := requireStatus("read binary", sw, err); err != nil {
return nil, err
}
return data, nil
}
func verifyPIN(ctx context.Context, card Card, pin string) error {
pin = strings.TrimSpace(pin)
if pin == "" {
return nil
}
if len(pin) < 4 || len(pin) > 8 || !decimalDigits(pin) {
return errors.New("pcsc: SIM PIN must contain 4 to 8 digits")
}
_, sw, err := card.Transmit(ctx, []byte{0x00, 0x20, 0x00, 0x01, 0x00})
if err != nil {
return errors.New("pcsc: SIM PIN status check failed")
}
if sw == 0x9000 {
return nil
}
tries := -1
if sw&0xFFF0 == 0x63C0 {
tries = int(sw & 0x000F)
if tries <= 2 {
return &PINError{Kind: ErrPINTriesLow, Tries: tries}
}
}
body := bytes.Repeat([]byte{0xFF}, 8)
copy(body, []byte(pin))
apdu := append([]byte{0x00, 0x20, 0x00, 0x01, 0x08}, body...)
_, sw, err = card.Transmit(ctx, apdu)
if err != nil {
return errors.New("pcsc: SIM PIN verification transport failed")
}
if sw == 0x9000 {
return nil
}
if sw&0xFFF0 == 0x63C0 {
return &PINError{Kind: ErrPINRejected, Tries: int(sw & 0x000F)}
}
return ErrPINRejected
}
func requireStatus(operation string, sw uint16, err error) error {
if err != nil {
return fmt.Errorf("pcsc: %s transport failed", operation)
}
if sw == 0x9000 {
return nil
}
if sw == 0x6982 || sw == 0x9804 {
return &PINError{Kind: ErrPINRequired, Tries: -1}
}
return fmt.Errorf("pcsc: %s failed with status %04X", operation, sw)
}
func decodeSwappedBCD(value []byte, dropFirstNibble bool) string {
var result strings.Builder
for _, octet := range value {
for _, nibble := range []byte{octet & 0x0F, octet >> 4} {
if dropFirstNibble {
dropFirstNibble = false
continue
}
if nibble == 0x0F {
return result.String()
}
if nibble > 9 {
return ""
}
result.WriteByte('0' + nibble)
}
}
return result.String()
}
func decodeIMSI(data []byte) (string, error) {
if len(data) < 2 {
return "", errors.New("pcsc: EF_IMSI is too short")
}
length := int(data[0])
if length <= 0 || length > len(data)-1 {
return "", errors.New("pcsc: EF_IMSI has an invalid length")
}
value := decodeSwappedBCD(data[1:1+length], true)
if len(value) < 10 || len(value) > 18 || !decimalDigits(value) {
return "", errors.New("pcsc: card returned an invalid IMSI")
}
return value, nil
}
func decimalDigits(value string) bool {
if value == "" {
return false
}
for _, character := range value {
if character < '0' || character > '9' {
return false
}
}
return true
}
func findTLV(data []byte, wanted byte) []byte {
for len(data) >= 2 {
tag := data[0]
data = data[1:]
length, consumed, ok := decodeTLVLength(data)
if !ok || consumed+length > len(data) {
return nil
}
value := data[consumed : consumed+length]
if tag == wanted {
return append([]byte(nil), value...)
}
if tag&0x20 != 0 {
if nested := findTLV(value, wanted); len(nested) > 0 {
return nested
}
}
data = data[consumed+length:]
}
return nil
}
func decodeTLVLength(data []byte) (length, consumed int, ok bool) {
if len(data) == 0 {
return 0, 0, false
}
if data[0]&0x80 == 0 {
return int(data[0]), 1, true
}
count := int(data[0] & 0x7F)
if count < 1 || count > 2 || len(data) < 1+count {
return 0, 0, false
}
length = 0
for _, octet := range data[1 : 1+count] {
length = length<<8 | int(octet)
}
return length, 1 + count, true
}
func parseAKAResponse(data []byte) (AKAResult, error) {
if len(data) < 2 {
return AKAResult{}, errors.New("pcsc: USIM returned a short AKA response")
}
switch data[0] {
case 0xDB:
res, rest, ok := takeLV(data[1:])
if !ok || len(res) < 4 || len(res) > 16 {
return AKAResult{}, errors.New("pcsc: USIM returned an invalid AKA RES")
}
ck, rest, ok := takeLV(rest)
if !ok || len(ck) != 16 {
return AKAResult{}, errors.New("pcsc: USIM returned an invalid AKA CK")
}
ik, rest, ok := takeLV(rest)
if !ok || len(ik) != 16 {
return AKAResult{}, errors.New("pcsc: USIM returned an invalid AKA IK")
}
if len(rest) > 0 {
kc, tail, valid := takeLV(rest)
if !valid || len(kc) != 8 || len(tail) != 0 {
return AKAResult{}, errors.New("pcsc: USIM returned invalid trailing AKA material")
}
}
return AKAResult{RES: append([]byte(nil), res...), CK: append([]byte(nil), ck...), IK: append([]byte(nil), ik...)}, nil
case 0xDC:
auts, tail, ok := takeLV(data[1:])
if !ok || len(auts) != 14 || len(tail) != 0 {
return AKAResult{}, errors.New("pcsc: USIM returned invalid AKA synchronization evidence")
}
return AKAResult{AUTS: append([]byte(nil), auts...), SynchronizationFailure: true}, nil
default:
return AKAResult{}, errors.New("pcsc: USIM returned an unsupported AKA response")
}
}
func takeLV(data []byte) (value, rest []byte, ok bool) {
if len(data) == 0 || int(data[0]) > len(data)-1 {
return nil, data, false
}
length := int(data[0])
return data[1 : 1+length], data[1+length:], true
}
func readSPN(ctx context.Context, card Card) string {
if err := selectFile(ctx, card, []byte{0x6F, 0x46}); err != nil {
return ""
}
data, err := readBinary(ctx, card, 17)
if err != nil || len(data) < 2 {
return ""
}
return strings.TrimSpace(strings.TrimRight(string(data[1:]), "\x00\xFF"))
}
func readSMSC(ctx context.Context, card Card) string {
if err := selectFile(ctx, card, []byte{0x6F, 0x42}); err != nil {
return ""
}
data, sw, err := card.Transmit(ctx, []byte{0x00, 0xB2, 0x01, 0x04, 0x00})
if err != nil || sw != 0x9000 || len(data) < 15 {
return ""
}
sca := data[len(data)-15 : len(data)-3]
if len(sca) < 2 || sca[0] < 2 || int(sca[0]) > len(sca)-1 {
return ""
}
digits := decodeSwappedBCD(sca[2:1+int(sca[0])], false)
if !decimalDigits(digits) {
return ""
}
if sca[1]&0x70 == 0x10 {
return "+" + digits
}
return digits
}
+84
View File
@@ -0,0 +1,84 @@
package pcsc
import (
"bytes"
"context"
"errors"
"testing"
)
type scriptedReply struct {
data []byte
sw uint16
}
type scriptedCard struct {
replies []scriptedReply
calls [][]byte
}
func (card *scriptedCard) Transmit(_ context.Context, command []byte) ([]byte, uint16, error) {
card.calls = append(card.calls, append([]byte(nil), command...))
if len(card.replies) == 0 {
return nil, 0, errors.New("unexpected APDU")
}
reply := card.replies[0]
card.replies = card.replies[1:]
return append([]byte(nil), reply.data...), reply.sw, nil
}
func (*scriptedCard) Close() error { return nil }
func TestDecodeIdentifiers(t *testing.T) {
if got := decodeSwappedBCD([]byte{0x98, 0x10, 0x32, 0x54, 0xF6}, false); got != "890123456" {
t.Fatalf("ICCID BCD = %q", got)
}
imsi, err := decodeIMSI([]byte{0x08, 0x19, 0x32, 0x54, 0x76, 0x98, 0x10, 0x32, 0x54})
if err != nil {
t.Fatal(err)
}
if imsi != "123456789012345" {
t.Fatalf("IMSI = %q", imsi)
}
}
func TestVerifyPINRefusesLowAttemptCount(t *testing.T) {
card := &scriptedCard{replies: []scriptedReply{{sw: 0x63C2}}}
err := verifyPIN(context.Background(), card, "1234")
if !errors.Is(err, ErrPINTriesLow) {
t.Fatalf("error = %v", err)
}
if len(card.calls) != 1 {
t.Fatalf("APDU calls = %d, PIN must not be submitted", len(card.calls))
}
}
func TestParseAKAResponse(t *testing.T) {
data := []byte{0xDB, 0x08, 1, 2, 3, 4, 5, 6, 7, 8, 0x10}
data = append(data, bytes.Repeat([]byte{0xAA}, 16)...)
data = append(data, 0x10)
data = append(data, bytes.Repeat([]byte{0xBB}, 16)...)
result, err := parseAKAResponse(data)
if err != nil {
t.Fatal(err)
}
if len(result.RES) != 8 || len(result.CK) != 16 || len(result.IK) != 16 || result.SynchronizationFailure {
t.Fatalf("unexpected AKA result: %#v", result)
}
syncResult, err := parseAKAResponse(append([]byte{0xDC, 0x0E}, bytes.Repeat([]byte{0xCC}, 14)...))
if err != nil {
t.Fatal(err)
}
if !syncResult.SynchronizationFailure || len(syncResult.AUTS) != 14 {
t.Fatalf("unexpected sync result: %#v", syncResult)
}
}
func TestDeviceIDUsesStableUSBPath(t *testing.T) {
a := DeviceID(Reader{Name: "reader 00 00", USBPath: "1-3"})
b := DeviceID(Reader{Name: "renamed reader", USBPath: "1-3"})
if a != b || a == "" {
t.Fatalf("device IDs = %q, %q", a, b)
}
}
+107
View File
@@ -0,0 +1,107 @@
package pcsc
import (
"context"
"errors"
"fmt"
"strings"
)
const HardwareKind = "pcsc"
var (
ErrUnsupported = errors.New("pcsc: platform is not supported")
ErrUnavailable = errors.New("pcsc: service is unavailable")
ErrReaderNotFound = errors.New("pcsc: reader not found")
ErrNoCard = errors.New("pcsc: no card is inserted")
ErrPINRequired = errors.New("pcsc: SIM PIN is required")
ErrPINTriesLow = errors.New("pcsc: refusing PIN verification because too few attempts remain")
ErrPINRejected = errors.New("pcsc: SIM PIN was rejected")
ErrUSIMUnavailable = errors.New("pcsc: no usable USIM application was found")
ErrCardChanged = errors.New("pcsc: card identity changed during authentication")
ErrAKARejected = errors.New("pcsc: USIM rejected the network authentication token")
)
type Reader struct {
Name string
USBPath string
VendorID string
ProductID string
Manufacturer string
Product string
CardPresent bool
ATR string
}
type Selector struct {
USBPath string
ReaderName string
}
func (selector Selector) validate() error {
if strings.TrimSpace(selector.USBPath) == "" && strings.TrimSpace(selector.ReaderName) == "" {
return errors.New("pcsc: reader selector is empty")
}
return nil
}
type Identity struct {
ICCID string
IMSI string
MNCLength int
USIMAID []byte
SMSC string
SPN string
PINRequired bool
PINTries int
}
type Snapshot struct {
Reader Reader
Identity Identity
}
type AKAChallenge struct {
RAND [16]byte
AUTN [16]byte
}
type AKAResult struct {
RES []byte
CK []byte
IK []byte
AUTS []byte
SynchronizationFailure bool
}
type PINError struct {
Kind error
Tries int
}
func (err *PINError) Error() string {
if err == nil {
return "pcsc: SIM PIN error"
}
if err.Tries >= 0 {
return fmt.Sprintf("%v (%d attempts remain)", err.Kind, err.Tries)
}
return err.Kind.Error()
}
func (err *PINError) Unwrap() error {
if err == nil {
return nil
}
return err.Kind
}
type Card interface {
Transmit(context.Context, []byte) ([]byte, uint16, error)
Close() error
}
type Backend interface {
Readers(context.Context) ([]Reader, error)
Open(context.Context, Selector) (Card, error)
}
+95 -6
View File
@@ -83,7 +83,13 @@ func (scheduler *automaticTaskScheduler) run() {
}
func (scheduler *automaticTaskScheduler) claim() {
runs, err := scheduler.server.store.ClaimDueAutomaticTasks(scheduler.ctx, time.Now().UTC(), 50)
var runs []store.AutomaticTaskRun
var err error
if scheduler.server.developerActive(scheduler.ctx) {
runs, err = scheduler.server.store.ClaimDueAutomaticTasks(scheduler.ctx, time.Now().UTC(), 50)
} else {
runs, err = scheduler.server.store.ClaimDueAvailableAutomaticTasks(scheduler.ctx, time.Now().UTC(), 50)
}
if err != nil {
scheduler.server.logger.Warn("claim automatic tasks", "error", err)
return
@@ -127,6 +133,11 @@ func (scheduler *automaticTaskScheduler) execute(run store.AutomaticTaskRun) {
_ = scheduler.server.store.UpdateAutomaticTaskRun(context.Background(), run)
return
}
if err := validateAutomaticTaskAvailability(scheduler.server.developerActive(scheduler.ctx), task.TaskType, task.Environment); err != nil {
run.Status, run.Error, run.FinishedAt = "failed", err.Error(), time.Now().UTC()
_ = scheduler.server.store.UpdateAutomaticTaskRun(context.Background(), run)
return
}
run.Status, run.StartedAt = "running", time.Now().UTC()
_ = scheduler.server.store.UpdateAutomaticTaskRun(context.Background(), run)
var output string
@@ -175,6 +186,9 @@ func (scheduler *automaticTaskScheduler) execute(run store.AutomaticTaskRun) {
}
func (s *Server) executeAutomaticTask(ctx context.Context, task store.AutomaticTask, progress automaticTaskProgress) (output string, err error) {
if err := validateAutomaticTaskAvailability(s.developerActive(ctx), task.TaskType, task.Environment); err != nil {
return "", automaticTaskExecutionError{err: err, retryable: false}
}
progress("正在检查设备和 eSIM Profile")
config, entry, physicalID, err := s.ensureAutomaticTaskProfile(ctx, task, progress)
if err != nil {
@@ -231,6 +245,9 @@ func (s *Server) ensureAutomaticTaskProfile(ctx context.Context, task store.Auto
if err != nil {
return store.Device{}, device.Device{}, "", fmt.Errorf("read device: %w", err)
}
if err := validateAutomaticTaskDeviceCapabilities(config, task.TaskType, task.Environment); err != nil {
return store.Device{}, device.Device{}, "", err
}
entry, physicalID, present := s.physicalForConfig(config)
if !present || entry.Snapshot == nil {
return store.Device{}, device.Device{}, "", errors.New("configured device is offline")
@@ -356,9 +373,6 @@ func (s *Server) prepareAutomaticTaskEnvironment(ctx context.Context, config *st
return err
}
if task.TaskType == "public_ip" {
if !s.developerActive(ctx) {
return errors.New("roaming public IP tasks require developer mode")
}
progress("已注册蜂窝网络,正在建立数据连接")
if _, err := s.devices.SetNetwork(ctx, physicalID, s.cardNetworkRequest(ctx, physicalID, *config, policy, true)); err != nil {
return fmt.Errorf("start roaming data: %w", err)
@@ -511,6 +525,25 @@ func (s *Server) restoreAutomaticTaskEnvironment(physicalID string, snapshot aut
if err := s.store.UpsertDevice(cleanupContext, config); err != nil {
restoreErrors = append(restoreErrors, fmt.Errorf("persist device policy: %w", err))
}
if config.DeviceType == store.DeviceTypeUSBSIMReader {
if s.vowifi == nil {
return errors.Join(append(restoreErrors, errors.New("VoWiFi runtime is unavailable"))...)
}
state, stateErr := s.vowifi.State(config.ID)
if policy.VoWiFiEnabled {
if stateErr == nil && state.Enabled {
_, stateErr = s.vowifi.RequestReconnect(config.ID)
} else {
_, stateErr = s.vowifi.RequestEnabled(config.ID, true)
}
} else if stateErr == nil && (state.Enabled || state.Active) {
_, stateErr = s.vowifi.RequestEnabled(config.ID, false)
}
if stateErr != nil {
restoreErrors = append(restoreErrors, fmt.Errorf("restore reader VoWiFi: %w", stateErr))
}
return errors.Join(restoreErrors...)
}
if policy.VoWiFiEnabled {
if _, err := s.devices.SetNetwork(cleanupContext, physicalID, s.cardNetworkRequest(cleanupContext, physicalID, config, policy, false)); err != nil {
@@ -637,6 +670,15 @@ func (s *Server) handleAutomaticTasks(w http.ResponseWriter, r *http.Request) {
s.writeStoreError(w, err)
return
}
if !s.developerActive(r.Context()) {
visible := tasks[:0]
for _, task := range tasks {
if validateAutomaticTaskAvailability(false, task.TaskType, task.Environment) == nil {
visible = append(visible, task)
}
}
tasks = visible
}
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"tasks": tasks}})
case http.MethodPost:
task, err := s.decodeAutomaticTask(r, 0)
@@ -689,7 +731,14 @@ func (s *Server) handleAutomaticTaskRuns(w http.ResponseWriter, r *http.Request)
query := r.URL.Query()
limit, _ := strconv.Atoi(query.Get("limit"))
offset, _ := strconv.Atoi(query.Get("offset"))
runs, total, err := s.store.ListAutomaticTaskRunsPaginated(r.Context(), limit, offset)
var runs []store.AutomaticTaskRun
var total int
var err error
if s.developerActive(r.Context()) {
runs, total, err = s.store.ListAutomaticTaskRunsPaginated(r.Context(), limit, offset)
} else {
runs, total, err = s.store.ListAvailableAutomaticTaskRunsPaginated(r.Context(), limit, offset)
}
if err != nil {
s.writeStoreError(w, err)
return
@@ -710,6 +759,19 @@ func (s *Server) handleAutomaticTaskRunNow(w http.ResponseWriter, r *http.Reques
s.writeStoreError(w, err)
return
}
config, err := s.store.Device(r.Context(), task.DeviceID)
if err != nil {
s.writeStoreError(w, err)
return
}
if err := validateAutomaticTaskDeviceCapabilities(config, task.TaskType, task.Environment); err != nil {
writeError(w, http.StatusConflict, "wifi_calling_only_device", err.Error())
return
}
if err := validateAutomaticTaskAvailability(s.developerActive(r.Context()), task.TaskType, task.Environment); err != nil {
writeError(w, http.StatusNotFound, "task_unavailable", err.Error())
return
}
run, err := s.store.QueueAutomaticTaskNow(r.Context(), task)
if err != nil {
s.writeStoreError(w, err)
@@ -745,7 +807,8 @@ func (s *Server) decodeAutomaticTask(r *http.Request, id int64) (store.Automatic
if request.Name == "" || request.DeviceID == "" || request.ProfileICCID == "" {
return store.AutomaticTask{}, errors.New("name, device, and eSIM profile are required")
}
if _, err := s.store.Device(r.Context(), request.DeviceID); err != nil {
selectedDevice, err := s.store.Device(r.Context(), request.DeviceID)
if err != nil {
return store.AutomaticTask{}, errors.New("selected device does not exist")
}
if request.Environment != "vowifi" && request.Environment != "cellular" {
@@ -757,6 +820,12 @@ func (s *Server) decodeAutomaticTask(r *http.Request, id int64) (store.Automatic
if request.TaskType == "public_ip" && request.Environment != "cellular" {
return store.AutomaticTask{}, errors.New("public IP tasks must use cellular direct mode")
}
if err := validateAutomaticTaskAvailability(s.developerActive(r.Context()), request.TaskType, request.Environment); err != nil {
return store.AutomaticTask{}, err
}
if err := validateAutomaticTaskDeviceCapabilities(selectedDevice, request.TaskType, request.Environment); err != nil {
return store.AutomaticTask{}, err
}
if request.IntervalDays < 1 || request.IntervalDays > 365 || request.RetryCount < 0 || request.RetryCount > 10 {
return store.AutomaticTask{}, errors.New("interval_days must be 1-365 and retry_count must be 0-10")
}
@@ -796,6 +865,26 @@ func (s *Server) decodeAutomaticTask(r *http.Request, id int64) (store.Automatic
return task, nil
}
func validateAutomaticTaskAvailability(available bool, taskType, environment string) error {
if !available && (taskType == "public_ip" || environment == "cellular") {
return errors.New("unsupported task type or environment")
}
return nil
}
func validateAutomaticTaskDeviceCapabilities(config store.Device, taskType, environment string) error {
if config.DeviceType != store.DeviceTypeUSBSIMReader {
return nil
}
if environment != "vowifi" {
return errors.New("USB SIM reader tasks must use the VoWiFi environment")
}
if taskType != "sms" && taskType != "call" {
return errors.New("USB SIM readers support only VoWiFi SMS and call tasks")
}
return nil
}
func nextAutomaticRun(date, clock string, intervalDays int, now time.Time) (time.Time, error) {
location := now.Location()
start, err := time.ParseInLocation("2006-01-02 15:04", strings.TrimSpace(date)+" "+strings.TrimSpace(clock), location)
+41
View File
@@ -3,6 +3,8 @@ package server
import (
"testing"
"time"
"vocat/internal/store"
)
func TestNextAutomaticRunUsesIntervalAndLocalClock(t *testing.T) {
@@ -18,6 +20,45 @@ func TestNextAutomaticRunUsesIntervalAndLocalClock(t *testing.T) {
}
}
func TestUSBSIMReaderAutomaticTasksRequireVoWiFi(t *testing.T) {
reader := store.Device{DeviceType: store.DeviceTypeUSBSIMReader}
for _, test := range []struct {
taskType string
environment string
wantError bool
}{
{taskType: "sms", environment: "vowifi"},
{taskType: "call", environment: "vowifi"},
{taskType: "sms", environment: "cellular", wantError: true},
{taskType: "public_ip", environment: "cellular", wantError: true},
} {
err := validateAutomaticTaskDeviceCapabilities(reader, test.taskType, test.environment)
if (err != nil) != test.wantError {
t.Errorf("type=%s environment=%s error=%v", test.taskType, test.environment, err)
}
}
}
func TestAutomaticTaskAvailabilityHidesRestrictedPaths(t *testing.T) {
for _, test := range []struct {
available bool
taskType string
environment string
wantError bool
}{
{false, "sms", "vowifi", false},
{false, "call", "vowifi", false},
{false, "sms", "cellular", true},
{false, "public_ip", "cellular", true},
{true, "public_ip", "cellular", false},
} {
err := validateAutomaticTaskAvailability(test.available, test.taskType, test.environment)
if (err != nil) != test.wantError {
t.Fatalf("availability(%v, %q, %q) = %v", test.available, test.taskType, test.environment, err)
}
}
}
func TestAutomaticSMSRetrySafetyPreventsDuplicateSubmission(t *testing.T) {
unsafe := []byte(`{"data":{"parts_attempted":1,"parts_accepted":1,"retry_safe":false}}`)
if automaticSMSRetrySafe(unsafe) {
+3 -3
View File
@@ -39,14 +39,14 @@ func TestDeveloperSettingsUpdatesGlobalSMSLimit(t *testing.T) {
t.Fatal(err)
}
server := &Server{store: database, developerEnabled: true, logger: regionTestLogger(), maxRequestBodyBytes: 4096}
request := httptest.NewRequest(http.MethodPut, "/api/settings/developer", strings.NewReader(`{"sms_hourly_limit":25}`))
request := httptest.NewRequest(http.MethodPut, "/api/settings/developer", strings.NewReader(`{"sms_hourly_limit":17}`))
request.Header.Set("Content-Type", "application/json")
response := httptest.NewRecorder()
server.handleDeveloperSettings(response, request)
if response.Code != http.StatusOK {
t.Fatalf("status = %d, body=%s", response.Code, response.Body.String())
}
if got := developer.SMSHourlyLimit(ctx, database); got != 25 {
t.Fatalf("SMS hourly limit = %d, want 25", got)
if got := developer.SMSHourlyLimit(ctx, database); got != 17 {
t.Fatalf("SMS hourly limit = %d, want 17", got)
}
}
+67 -3
View File
@@ -66,6 +66,7 @@ type deviceConfigPayload struct {
USBPath string `json:"usb_path"`
AudioDevice string `json:"audio_device"`
ModemIMEI string `json:"modem_imei"`
SIMPIN string `json:"sim_pin"`
APN string `json:"apn"`
ProxyPort int `json:"proxy_port"`
BaudRate int `json:"baud_rate"`
@@ -97,6 +98,7 @@ func (payload deviceConfigPayload) toStoreDevice() store.Device {
USBPath: strings.TrimSpace(payload.USBPath),
AudioDevice: strings.TrimSpace(payload.AudioDevice),
ModemIMEI: strings.TrimSpace(payload.ModemIMEI),
SIMPIN: strings.TrimSpace(payload.SIMPIN),
APN: strings.TrimSpace(payload.APN),
ProxyPort: payload.ProxyPort,
BaudRate: payload.BaudRate,
@@ -246,6 +248,12 @@ func (s *Server) handleDevices(w http.ResponseWriter, r *http.Request) bool {
config.NetworkEnabled = false
}
fillConfigFromPhysical(&config, *selected)
if pinSetter, ok := s.devices.(interface{ SetSIMPin(string, string) error }); ok {
if err := pinSetter.SetSIMPin(selected.ID, config.SIMPIN); err != nil {
s.writeDeviceError(w, err)
return true
}
}
if selector, ok := s.devices.(interface{ SetBackend(string, string) error }); ok {
if err := selector.SetBackend(selected.ID, config.DeviceBackend); err != nil {
s.writeDeviceError(w, err)
@@ -363,6 +371,8 @@ func (s *Server) handleDiscoveredDevices(w http.ResponseWriter, r *http.Request)
}
}
result = append(result, map[string]any{
"hardware_kind": candidate.HardwareKind,
"reader_name": candidate.ReaderName,
"discovery_key": entry.ID,
"control_path": controlPath,
"net_interface": candidate.NetworkInterface,
@@ -374,10 +384,10 @@ func (s *Server) handleDiscoveredDevices(w http.ResponseWriter, r *http.Request)
"at_port": candidate.ATPort.OpenPath(),
"imei": snapshotString(entry.Snapshot, func(snapshot *device.Snapshot) string { return snapshot.IMEI }),
"mode": backendMode(candidate),
"network_capable": candidate.NetworkInterface != "" || candidate.QMIControl != "",
"network_capable": candidate.HardwareKind != "pcsc" && (candidate.NetworkInterface != "" || candidate.QMIControl != ""),
"configured": configuredID != "",
"configured_id": configuredID,
"degraded": !candidate.HasATPort(),
"degraded": candidate.HardwareKind != "pcsc" && !candidate.HasATPort(),
})
}
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"devices": result}})
@@ -459,7 +469,16 @@ func (s *Server) handleDevicePath(
if next.Name == id && strings.TrimSpace(payload.Name) == "" {
next.Name = config.Name
}
if next.SIMPIN == "" || next.SIMPIN == store.SecretMask {
next.SIMPIN = config.SIMPIN
}
if _, physicalID, present := s.physicalForConfig(next); present {
if pinSetter, ok := s.devices.(interface{ SetSIMPin(string, string) error }); ok {
if err := pinSetter.SetSIMPin(physicalID, next.SIMPIN); err != nil {
s.writeDeviceError(w, err)
return true
}
}
if selector, ok := s.devices.(interface{ SetBackend(string, string) error }); ok {
if err := selector.SetBackend(physicalID, next.DeviceBackend); err != nil {
s.writeDeviceError(w, err)
@@ -482,6 +501,16 @@ func (s *Server) handleDevicePath(
}
entry, physicalID, physicalPresent := s.physicalForConfig(config)
if config.DeviceType == store.DeviceTypeUSBSIMReader && len(tail) > 0 {
operation := strings.Join(tail, "/")
unsupported := tail[0] == "network" || tail[0] == "operator_selection" ||
operation == "actions/at" || operation == "actions/ussd" || operation == "actions/ussd/continue" ||
operation == "actions/ussd/cancel" || operation == "actions/reboot" || operation == "usbnet-mode"
if unsupported {
writeError(w, http.StatusConflict, "wifi_calling_only_device", "USB SIM readers support WiFi Calling, IMS SMS and calls only")
return true
}
}
if len(tail) > 0 && tail[0] == "esim" {
return s.handleESIM(w, r, tail[1:], physicalID, physicalPresent, config.ID)
}
@@ -1803,6 +1832,10 @@ func deviceStatus(entry device.Device) map[string]any {
}
func storedDeviceConfig(config store.Device) map[string]any {
simPIN := ""
if strings.TrimSpace(config.SIMPIN) != "" {
simPIN = store.SecretMask
}
return map[string]any{
"id": config.ID,
"name": config.Name,
@@ -1813,6 +1846,7 @@ func storedDeviceConfig(config store.Device) map[string]any {
"usb_path": config.USBPath,
"audio_device": config.AudioDevice,
"modem_imei": config.ModemIMEI,
"sim_pin": simPIN,
"apn": config.APN,
"proxy_port": config.ProxyPort,
"baud_rate": config.BaudRate,
@@ -1832,6 +1866,17 @@ func storedDeviceConfig(config store.Device) map[string]any {
func fillConfigFromPhysical(config *store.Device, entry device.Device) {
candidate := entry.Candidate
if candidate.HardwareKind == "pcsc" {
config.DeviceType = store.DeviceTypeUSBSIMReader
config.ControlDevice = candidate.ReaderName
config.ATPort = ""
config.Interface = ""
config.DeviceBackend = "pcsc"
config.ESIMTransport = "pcsc"
config.NetworkEnabled = false
config.SMSEnabled = true
config.VoWiFiEnabled = true
}
if config.Interface == "" {
config.Interface = candidate.NetworkInterface
}
@@ -1914,13 +1959,29 @@ func modemSummary(snapshot *device.Snapshot, phone string, phoneSource string) m
"reg_status": snapshot.RegistrationStatus,
"reg_status_text": registrationText(snapshot),
"ps_attached": snapshot.PSAttached,
"sim_inserted": snapshot.SIMStatus != "",
"sim_inserted": snapshotHasSIM(snapshot),
"operating_mode": snapshot.OperatingMode,
"phone_number": phone,
"phone_number_source": phoneSource,
}
}
func snapshotHasSIM(snapshot *device.Snapshot) bool {
if snapshot == nil {
return false
}
if snapshot.SIMReady || strings.TrimSpace(snapshot.ICCID) != "" || strings.TrimSpace(snapshot.IMSI) != "" {
return true
}
switch strings.ToLower(strings.TrimSpace(snapshot.SIMStatus)) {
case "", "unknown", "not_inserted", "not inserted", "absent":
return false
default:
// PIN/PUK and other explicit UICC states prove that a card is present.
return true
}
}
func idleVoWiFiRuntime(id string, snapshot *device.Snapshot) map[string]any {
iccid := ""
imsi := ""
@@ -1970,6 +2031,9 @@ func deviceName(entry device.Device) string {
}
func backendMode(candidate modem.Candidate) string {
if candidate.HardwareKind == "pcsc" {
return "pcsc"
}
if candidate.QMIControl != "" {
return "qmi"
}
+21
View File
@@ -115,3 +115,24 @@ func TestConfiguredDeviceSummaryMarksIdleRuntimeAsNotInUse(t *testing.T) {
t.Fatalf("summary = %#v", got)
}
}
func TestSnapshotHasSIMDoesNotTreatUnknownStatusAsInserted(t *testing.T) {
for _, snapshot := range []*device.Snapshot{
{IMEI: "867123456789012"},
{IMEI: "867123456789012", SIMStatus: "unknown"},
{IMEI: "867123456789012", SIMStatus: "not_inserted"},
} {
if snapshotHasSIM(snapshot) {
t.Fatalf("snapshot was reported with a SIM: %#v", snapshot)
}
}
for _, snapshot := range []*device.Snapshot{
{SIMStatus: "pin_required"},
{ICCID: "89441000400128014257"},
{SIMReady: true},
} {
if !snapshotHasSIM(snapshot) {
t.Fatalf("snapshot was reported without a SIM: %#v", snapshot)
}
}
}
+21
View File
@@ -1,11 +1,13 @@
package server
import (
"context"
"errors"
"net/http"
"strings"
"vocat/internal/exportproxy"
"vocat/internal/store"
)
func (s *Server) routeExportProxyAPI(w http.ResponseWriter, r *http.Request, cleanPath string) bool {
@@ -33,6 +35,9 @@ func (s *Server) routeExportProxyAPI(w http.ResponseWriter, r *http.Request, cle
writeError(w, http.StatusBadRequest, "invalid_request", err.Error())
return true
}
if s.rejectUnsupportedExportProxyDevice(w, r.Context(), config.DeviceID) {
return true
}
created, err := s.exportProxy.Create(r.Context(), config)
if err != nil {
s.writeExportProxyError(w, err)
@@ -71,6 +76,9 @@ func (s *Server) routeExportProxyAPI(w http.ResponseWriter, r *http.Request, cle
writeError(w, http.StatusBadRequest, "invalid_request", err.Error())
return true
}
if s.rejectUnsupportedExportProxyDevice(w, r.Context(), config.DeviceID) {
return true
}
updated, err := s.exportProxy.Update(r.Context(), id, config)
if err != nil {
s.writeExportProxyError(w, err)
@@ -90,6 +98,19 @@ func (s *Server) routeExportProxyAPI(w http.ResponseWriter, r *http.Request, cle
return true
}
func (s *Server) rejectUnsupportedExportProxyDevice(w http.ResponseWriter, ctx context.Context, deviceID string) bool {
config, err := s.store.Device(ctx, strings.TrimSpace(deviceID))
if err != nil {
s.writeStoreError(w, err)
return true
}
if config.DeviceType == store.DeviceTypeUSBSIMReader {
writeError(w, http.StatusConflict, "wifi_calling_only_device", "USB SIM readers cannot export cellular data as a proxy")
return true
}
return false
}
func (s *Server) writeExportProxyError(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, exportproxy.ErrDisabled):
@@ -0,0 +1,31 @@
package server
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"vocat/internal/store"
)
func TestExportProxyRejectsUSBSIMReader(t *testing.T) {
database, err := store.Open(context.Background(), ":memory:")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = database.Close() })
if err := database.UpsertDevice(context.Background(), store.Device{
ID: "reader-1", Name: "USB SIM Reader", DeviceType: store.DeviceTypeUSBSIMReader,
}); err != nil {
t.Fatal(err)
}
server := &Server{store: database}
response := httptest.NewRecorder()
if !server.rejectUnsupportedExportProxyDevice(response, context.Background(), "reader-1") {
t.Fatal("reader was accepted as an export-proxy device")
}
if response.Code != http.StatusConflict {
t.Fatalf("status = %d, body = %s", response.Code, response.Body.String())
}
}
+25
View File
@@ -93,3 +93,28 @@ func TestProfileProxyBindingRejectsSameICCIDOnDifferentProxy(t *testing.T) {
t.Fatalf("binding after rejected rebind = %+v, %v", binding, err)
}
}
func TestProfileProxyBindingSupportsPCSCReader(t *testing.T) {
server, database, controller := newProfileBindingTestServer(t)
readerICCID := "89104100000028106378"
if err := database.UpsertDevice(context.Background(), store.Device{
ID: "reader-1", Name: "USB SIM Reader", DeviceType: store.DeviceTypeUSBSIMReader,
}); err != nil {
t.Fatal(err)
}
controller.state = vowifi.State{DeviceID: "reader-1", ICCID: readerICCID, Enabled: true}
response := profileBindingRequest(t, server, http.MethodPost, `{
"upstream_proxy_id":"route-1",
"bindings":[{"device_id":"reader-1","iccid":"89104100000028106378","profile_name":"Reader Profile"}]
}`)
if response.Code != http.StatusOK {
t.Fatalf("POST status = %d, body = %s", response.Code, response.Body.String())
}
binding, err := database.DeviceProxyBinding(context.Background(), readerICCID)
if err != nil || binding.DeviceID != "reader-1" || binding.UpstreamProxyID != "route-1" {
t.Fatalf("reader binding = %+v, %v", binding, err)
}
if controller.reconnects != 1 {
t.Fatalf("reader reconnects = %d, want 1", controller.reconnects)
}
}
+11
View File
@@ -546,6 +546,13 @@ func (s *Server) syncModemSMS(ctx context.Context, onlyDevice string) {
if onlyDevice != "" && config.ID != onlyDevice {
continue
}
// A PC/SC USB reader has no modem storage or AT command channel. Its
// messages are delivered by the active VoWiFi IMS session, so attempting
// an AT+CMGL catch-up scan would only poison the reader's health state
// with ErrNoATPort.
if !supportsModemSMSStorage(config) {
continue
}
// Do not queue CMGL traffic on the same serial actor while VoWiFi is
// reading the SIM or running AKA. Once the session is stable, resume the
// SM/ME scan as a catch-up path: an SMS submitted while the card was
@@ -659,6 +666,10 @@ func (s *Server) syncModemSMS(ctx context.Context, onlyDevice string) {
}
}
func supportsModemSMSStorage(config store.Device) bool {
return store.NormalizeDeviceType(config.DeviceType) != store.DeviceTypeUSBSIMReader
}
func shouldDeferModemSMSSync(state vowifi.State, stateErr error) bool {
if stateErr != nil || !state.Enabled {
return false
+9
View File
@@ -108,6 +108,15 @@ func TestNormalizeSMSDeviceFilter(t *testing.T) {
}
}
func TestSupportsModemSMSStorageRejectsUSBReader(t *testing.T) {
if supportsModemSMSStorage(store.Device{DeviceType: store.DeviceTypeUSBSIMReader}) {
t.Fatal("USB SIM reader must not be polled with modem SMS AT commands")
}
if !supportsModemSMSStorage(store.Device{DeviceType: store.DeviceTypePCIeEC20EC25}) {
t.Fatal("cellular modem should retain modem SMS storage synchronization")
}
}
func TestSMSSendOutcome(t *testing.T) {
tests := []struct {
name string
+30 -3
View File
@@ -99,6 +99,16 @@ func (s *Store) DeleteAutomaticTask(ctx context.Context, id int64) error {
}
func (s *Store) ClaimDueAutomaticTasks(ctx context.Context, now time.Time, limit int) ([]AutomaticTaskRun, error) {
return s.claimDueAutomaticTasks(ctx, now, limit, false)
}
// ClaimDueAvailableAutomaticTasks excludes task types and environments that
// are not exposed in the standard product surface.
func (s *Store) ClaimDueAvailableAutomaticTasks(ctx context.Context, now time.Time, limit int) ([]AutomaticTaskRun, error) {
return s.claimDueAutomaticTasks(ctx, now, limit, true)
}
func (s *Store) claimDueAutomaticTasks(ctx context.Context, now time.Time, limit int, availableOnly bool) ([]AutomaticTaskRun, error) {
if limit <= 0 || limit > 100 {
limit = 50
}
@@ -107,8 +117,12 @@ func (s *Store) ClaimDueAutomaticTasks(ctx context.Context, now time.Time, limit
return nil, err
}
defer tx.Rollback()
availability := ""
if availableOnly {
availability = " AND task_type <> 'public_ip' AND environment <> 'cellular'"
}
rows, err := tx.QueryContext(ctx, automaticTaskSelect+`
WHERE enabled = 1 AND next_run_at <= ? ORDER BY next_run_at, id LIMIT ?`, now.Unix(), limit)
WHERE enabled = 1 AND next_run_at <= ?`+availability+` ORDER BY next_run_at, id LIMIT ?`, now.Unix(), limit)
if err != nil {
return nil, err
}
@@ -236,6 +250,19 @@ func (s *Store) ListAutomaticTaskRuns(ctx context.Context, limit int) ([]Automat
// the total run count, so the UI can page through the full history instead of
// a fixed recent window.
func (s *Store) ListAutomaticTaskRunsPaginated(ctx context.Context, limit, offset int) ([]AutomaticTaskRun, int, error) {
return s.listAutomaticTaskRunsPaginated(ctx, limit, offset, "")
}
// ListAvailableAutomaticTaskRunsPaginated omits history belonging to task
// types and environments that are not exposed in the standard product surface.
func (s *Store) ListAvailableAutomaticTaskRunsPaginated(ctx context.Context, limit, offset int) ([]AutomaticTaskRun, int, error) {
const where = ` WHERE task_id IN (
SELECT id FROM automatic_tasks WHERE task_type <> 'public_ip' AND environment <> 'cellular'
)`
return s.listAutomaticTaskRunsPaginated(ctx, limit, offset, where)
}
func (s *Store) listAutomaticTaskRunsPaginated(ctx context.Context, limit, offset int, where string) ([]AutomaticTaskRun, int, error) {
if limit <= 0 {
limit = 20
}
@@ -246,10 +273,10 @@ func (s *Store) ListAutomaticTaskRunsPaginated(ctx context.Context, limit, offse
offset = 0
}
total := 0
if err := s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM automatic_task_runs`).Scan(&total); err != nil {
if err := s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM automatic_task_runs`+where).Scan(&total); err != nil {
return nil, 0, fmt.Errorf("count automatic task runs: %w", err)
}
rows, err := s.db.QueryContext(ctx, automaticTaskRunSelect+` ORDER BY id DESC LIMIT ? OFFSET ?`, limit, offset)
rows, err := s.db.QueryContext(ctx, automaticTaskRunSelect+where+` ORDER BY id DESC LIMIT ? OFFSET ?`, limit, offset)
if err != nil {
return nil, 0, err
}
+48
View File
@@ -120,6 +120,54 @@ func TestListAutomaticTaskRunsPaginated(t *testing.T) {
}
}
func TestAvailableAutomaticTasksExcludeRestrictedTaskAndRunHistory(t *testing.T) {
ctx := context.Background()
database := openTestStore(t, filepath.Join(t.TempDir(), "automatic-task-availability.db"))
mustSaveDevice(t, database, "ec20", "EC20")
now := time.Now().UTC().Truncate(time.Second)
save := func(name, taskType, environment string) AutomaticTask {
t.Helper()
task, err := database.SaveAutomaticTask(ctx, AutomaticTask{
Name: name, Enabled: true, DeviceID: "ec20", ProfileICCID: "one",
TaskType: taskType, Environment: environment, IntervalDays: 1,
StartDate: "2026-08-10", RunTime: "12:00", Timezone: "Asia/Shanghai",
Payload: []byte(`{"phone":"10086","message":"test"}`), NextRunAt: now.Add(-time.Minute),
})
if err != nil {
t.Fatal(err)
}
return task
}
visible := save("visible", "sms", "vowifi")
hidden := save("hidden", "public_ip", "cellular")
for _, task := range []AutomaticTask{visible, hidden} {
if _, err := database.QueueAutomaticTaskNow(ctx, task); err != nil {
t.Fatal(err)
}
}
runs, total, err := database.ListAvailableAutomaticTaskRunsPaginated(ctx, 20, 0)
if err != nil {
t.Fatal(err)
}
if total != 1 || len(runs) != 1 || runs[0].TaskID != visible.ID {
t.Fatalf("available history total=%d runs=%+v", total, runs)
}
claimed, err := database.ClaimDueAvailableAutomaticTasks(ctx, now, 10)
if err != nil {
t.Fatal(err)
}
if len(claimed) != 1 || claimed[0].TaskID != visible.ID {
t.Fatalf("available claims = %+v", claimed)
}
storedHidden, err := database.AutomaticTask(ctx, hidden.ID)
if err != nil {
t.Fatal(err)
}
if storedHidden.NextRunAt.After(now) {
t.Fatalf("restricted task schedule advanced unexpectedly: %v", storedHidden.NextRunAt)
}
}
func TestRecoverAutomaticTaskRunsFailsRunningAndReturnsQueued(t *testing.T) {
ctx := context.Background()
database := openTestStore(t, filepath.Join(t.TempDir(), "automatic-task-recovery.db"))
+24 -7
View File
@@ -17,6 +17,7 @@ const (
DeviceTypeWiFi410 = "wifi_410"
DeviceTypeDJI4G = "dji_4g"
DeviceTypePCIeEC20EC25 = "pcie_ec20_ec25"
DeviceTypeUSBSIMReader = "usb_sim_reader"
)
// NormalizeDeviceType returns a stable persisted device type identifier.
@@ -27,6 +28,8 @@ func NormalizeDeviceType(value string) string {
return DeviceTypeWiFi410
case DeviceTypeDJI4G:
return DeviceTypeDJI4G
case DeviceTypeUSBSIMReader:
return DeviceTypeUSBSIMReader
case "", DeviceTypePCIeEC20EC25:
return DeviceTypePCIeEC20EC25
default:
@@ -132,16 +135,29 @@ func upsertDevice(ctx context.Context, executor contextExecer, value Device) err
value.DeviceBackend = "at"
}
value.DeviceBackend = strings.ToLower(strings.TrimSpace(value.DeviceBackend))
if value.DeviceBackend != "at" && value.DeviceBackend != "qmi" {
if value.DeviceBackend != "at" && value.DeviceBackend != "qmi" && value.DeviceBackend != "pcsc" {
return fmt.Errorf("unsupported device backend %q", value.DeviceBackend)
}
if value.ESIMTransport == "" {
value.ESIMTransport = "at"
}
value.ESIMTransport = strings.ToLower(strings.TrimSpace(value.ESIMTransport))
if value.ESIMTransport != "at" && value.ESIMTransport != "qmi" {
if value.ESIMTransport != "at" && value.ESIMTransport != "qmi" && value.ESIMTransport != "pcsc" && value.ESIMTransport != "none" {
return fmt.Errorf("unsupported eSIM transport %q", value.ESIMTransport)
}
value.SIMPIN = strings.TrimSpace(value.SIMPIN)
if value.SIMPIN != "" {
if len(value.SIMPIN) < 4 || len(value.SIMPIN) > 8 || strings.Trim(value.SIMPIN, "0123456789") != "" {
return errors.New("SIM PIN must contain 4 to 8 digits")
}
}
if value.DeviceType == DeviceTypeUSBSIMReader {
value.DeviceBackend = "pcsc"
value.ESIMTransport = "pcsc"
value.NetworkEnabled = false
value.SMSEnabled = true
value.VoWiFiEnabled = true
}
extra, err := normalizeJSONObject(value.Extra)
if err != nil {
return fmt.Errorf("normalize device extra data: %w", err)
@@ -159,12 +175,12 @@ func upsertDevice(ctx context.Context, executor contextExecer, value Device) err
_, err = executor.ExecContext(ctx, `
INSERT INTO devices (
id, name, device_type, interface, control_device, at_port, usb_path,
audio_device, modem_imei, apn, proxy_port, baud_rate,
audio_device, modem_imei, sim_pin, apn, proxy_port, baud_rate,
data_bits, stop_bits, parity, device_backend, esim_transport,
qmi_use_proxy, qmi_proxy_path, qmi_proxy_executable,
network_enabled, sms_enabled, vowifi_enabled, extra_json,
created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET
name = excluded.name,
device_type = excluded.device_type,
@@ -174,6 +190,7 @@ func upsertDevice(ctx context.Context, executor contextExecer, value Device) err
usb_path = excluded.usb_path,
audio_device = excluded.audio_device,
modem_imei = excluded.modem_imei,
sim_pin = excluded.sim_pin,
apn = excluded.apn,
proxy_port = excluded.proxy_port,
baud_rate = excluded.baud_rate,
@@ -192,7 +209,7 @@ func upsertDevice(ctx context.Context, executor contextExecer, value Device) err
updated_at = excluded.updated_at
`,
value.ID, value.Name, value.DeviceType, value.Interface, value.ControlDevice, value.ATPort,
value.USBPath, value.AudioDevice, value.ModemIMEI, value.APN,
value.USBPath, value.AudioDevice, value.ModemIMEI, value.SIMPIN, value.APN,
value.ProxyPort, value.BaudRate, value.DataBits, value.StopBits,
value.Parity, value.DeviceBackend, value.ESIMTransport,
boolInt(value.QMIUseProxy), value.QMIProxyPath, value.QMIProxyExecutable,
@@ -282,7 +299,7 @@ func (s *Store) DeleteDevice(ctx context.Context, id string) error {
const deviceSelect = `
SELECT id, name, device_type, interface, control_device, at_port, usb_path,
audio_device, modem_imei, apn, proxy_port, baud_rate, data_bits,
audio_device, modem_imei, sim_pin, apn, proxy_port, baud_rate, data_bits,
stop_bits, parity, device_backend, esim_transport, qmi_use_proxy,
qmi_proxy_path, qmi_proxy_executable, network_enabled, sms_enabled,
vowifi_enabled, extra_json, created_at, updated_at
@@ -295,7 +312,7 @@ func scanDevice(row rowScanner) (Device, error) {
var createdAt, updatedAt int64
err := row.Scan(
&value.ID, &value.Name, &value.DeviceType, &value.Interface, &value.ControlDevice,
&value.ATPort, &value.USBPath, &value.AudioDevice, &value.ModemIMEI,
&value.ATPort, &value.USBPath, &value.AudioDevice, &value.ModemIMEI, &value.SIMPIN,
&value.APN, &value.ProxyPort, &value.BaudRate, &value.DataBits,
&value.StopBits, &value.Parity, &value.DeviceBackend,
&value.ESIMTransport, &qmiUseProxy, &value.QMIProxyPath,
+25
View File
@@ -366,6 +366,31 @@ func TestDeviceStateRoundTripAndCascade(t *testing.T) {
}
}
func TestUSBSIMReaderConfigurationIsWiFiCallingOnly(t *testing.T) {
ctx := context.Background()
database := openTestStore(t, ":memory:")
err := database.UpsertDevice(ctx, Device{
ID: "reader-1", Name: "USB SIM", DeviceType: DeviceTypeUSBSIMReader,
USBPath: "1-3", ControlDevice: "Reader 00 00", SIMPIN: "1234",
DeviceBackend: "at", ESIMTransport: "at", NetworkEnabled: true,
})
if err != nil {
t.Fatal(err)
}
got, err := database.Device(ctx, "reader-1")
if err != nil {
t.Fatal(err)
}
if got.DeviceBackend != "pcsc" || got.ESIMTransport != "pcsc" || got.NetworkEnabled || !got.SMSEnabled || !got.VoWiFiEnabled || got.SIMPIN != "1234" {
t.Fatalf("reader config = %+v", got)
}
bad := got
bad.SIMPIN = "12x4"
if err := database.UpsertDevice(ctx, bad); err == nil {
t.Fatal("non-numeric SIM PIN was accepted")
}
}
func TestSMSPersistenceAndDerivedThreads(t *testing.T) {
ctx := context.Background()
database := openTestStore(t, ":memory:")
+4
View File
@@ -260,6 +260,10 @@ func migrationStatements(version int) []string {
`ALTER TABLE card_policies
ADD COLUMN custom_phone_number TEXT NOT NULL DEFAULT ''`,
}
case 16:
return []string{
`ALTER TABLE devices ADD COLUMN sim_pin TEXT NOT NULL DEFAULT ''`,
}
default:
return nil
}
+1
View File
@@ -24,6 +24,7 @@ type Device struct {
USBPath string
AudioDevice string
ModemIMEI string
SIMPIN string
APN string
ProxyPort int
BaudRate int
+3 -2
View File
@@ -13,7 +13,7 @@ import (
_ "modernc.org/sqlite"
)
const schemaVersion = 15
const schemaVersion = 16
var ErrNotFound = errors.New("store: not found")
@@ -122,7 +122,8 @@ func migrate(ctx context.Context, db *sql.DB) error {
// migration are still safe and must be applied.
duplicateAdditiveColumn := (nextVersion == 7 && strings.Contains(statement, "ADD COLUMN modem_imei")) ||
(nextVersion == 8 && strings.Contains(statement, "ADD COLUMN device_type")) ||
(nextVersion == 14 && strings.Contains(statement, "ADD COLUMN"))
(nextVersion == 14 && strings.Contains(statement, "ADD COLUMN")) ||
(nextVersion == 16 && strings.Contains(statement, "ADD COLUMN sim_pin"))
if duplicateAdditiveColumn && strings.Contains(strings.ToLower(err.Error()), "duplicate column name") {
continue
}
+32 -8
View File
@@ -184,6 +184,10 @@ func applyUpdate(ctx context.Context, logger *slog.Logger, opts Options, release
cleanup()
return fmt.Errorf("update: chmod temp binary: %w", err)
}
if err := validateExecutable(ctx, tmpPath); err != nil {
cleanup()
return err
}
if err := backupAndReplace(opts.Target, tmpPath); err != nil {
cleanup()
return err
@@ -202,10 +206,25 @@ func applyUpdate(ctx context.Context, logger *slog.Logger, opts Options, release
return nil
}
// validateExecutable catches incompatible architectures and missing dynamic
// loaders before the working installation is touched. A valid checksum alone
// cannot detect those packaging errors.
func validateExecutable(ctx context.Context, path string) error {
checkCtx, cancel := context.WithTimeout(ctx, 15*time.Second)
defer cancel()
output, err := exec.CommandContext(checkCtx, path, "version").CombinedOutput()
if err != nil {
return fmt.Errorf("update: downloaded binary cannot run on this host: %w (%s)", err, strings.TrimSpace(string(output)))
}
if !strings.Contains(strings.ToLower(string(output)), "vocat") {
return fmt.Errorf("update: downloaded binary returned an unexpected version response: %q", strings.TrimSpace(string(output)))
}
return nil
}
// backupAndReplace renames the current binary aside, then moves the verified
// temp file into place. Both renames are atomic on the same filesystem. On
// Linux the kernel holds the running binary's inode, so replacing it mid-flight
// is safe.
// temp file into place. Both renames are atomic on the same filesystem. The
// previous working binary is retained for service-level or manual rollback.
func backupAndReplace(target, tmp string) error {
backup := target + ".previous"
if _, err := os.Stat(target); err == nil {
@@ -221,16 +240,21 @@ func backupAndReplace(target, tmp string) error {
}
return fmt.Errorf("update: move new binary into place: %w", err)
}
_ = os.Remove(backup)
return nil
}
// RestartService restarts the vocat systemd unit. If systemctl is unavailable
// (non-systemd hosts, containers), it returns an error the caller surfaces as
// a non-fatal warning.
// RestartService supports both systemd hosts and OpenWrt/procd routers.
func RestartService(logger *slog.Logger) error {
if _, err := os.Stat("/etc/init.d/vocat"); err == nil {
cmd := exec.Command("/etc/init.d/vocat", "restart")
if out, err := cmd.CombinedOutput(); err != nil {
logger.Warn("OpenWrt service restart failed", "error", err, "output", string(out))
return fmt.Errorf("restart OpenWrt vocat service: %w", err)
}
return nil
}
if _, err := exec.LookPath("systemctl"); err != nil {
return fmt.Errorf("systemctl not found in PATH")
return fmt.Errorf("neither /etc/init.d/vocat nor systemctl is available")
}
// Queue the restart and let systemctl exit before systemd stops this unit.
// A blocking restart command becomes part of vocat.service's own cgroup and
+44
View File
@@ -0,0 +1,44 @@
package update
import (
"context"
"os"
"path/filepath"
"runtime"
"testing"
)
func TestValidateExecutableRejectsNonExecutableFile(t *testing.T) {
path := filepath.Join(t.TempDir(), "not-vocat")
if err := os.WriteFile(path, []byte("not an executable"), 0o755); err != nil {
t.Fatal(err)
}
if err := validateExecutable(context.Background(), path); err == nil {
t.Fatal("validateExecutable accepted invalid file")
}
}
func TestBackupAndReplaceRetainsPreviousBinary(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Linux replacement behavior")
}
directory := t.TempDir()
target := filepath.Join(directory, "vocat")
replacement := filepath.Join(directory, "replacement")
if err := os.WriteFile(target, []byte("old"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(replacement, []byte("new"), 0o755); err != nil {
t.Fatal(err)
}
if err := backupAndReplace(target, replacement); err != nil {
t.Fatal(err)
}
old, err := os.ReadFile(target + ".previous")
if err != nil {
t.Fatalf("read retained backup: %v", err)
}
if string(old) != "old" {
t.Fatalf("backup = %q", old)
}
}
+13
View File
@@ -47,6 +47,11 @@ type EC20SensitiveATExecutor interface {
ExecuteSensitiveAT(context.Context, string, string) (modem.Response, error)
}
type EC20UICCLocker interface {
LockUICC()
UnlockUICC()
}
type EC20AdapterOptions struct {
// PureAirplanePolicy reports the independent user policy. The adapter only
// changes the transactional CFUN projection used by VoWiFi and never
@@ -339,6 +344,10 @@ func (adapter *EC20Adapter) CheckReady(
// cannot insert an APDU between a 61xx response and GET RESPONSE.
adapter.apduMu.Lock()
defer adapter.apduMu.Unlock()
if locker, ok := adapter.executor.(EC20UICCLocker); ok {
locker.LockUICC()
defer locker.UnlockUICC()
}
aid, application, err := adapter.discoverAKAApplication(ctx, binding.deviceID)
if err != nil {
@@ -402,6 +411,10 @@ func (adapter *EC20Adapter) Authenticate(
adapter.apduMu.Lock()
defer adapter.apduMu.Unlock()
if locker, ok := adapter.executor.(EC20UICCLocker); ok {
locker.LockUICC()
defer locker.UnlockUICC()
}
apdu := buildUSIMAuthenticateAPDU(challenge)
var raw []byte
+8
View File
@@ -84,6 +84,14 @@ func runIPCommand(ctx context.Context, command string, operation xfrmOperation)
if message == "" {
message = err.Error()
}
if strings.Contains(strings.ToLower(message), "protocol not supported") ||
strings.Contains(strings.ToLower(message), "operation not supported") {
return fmt.Errorf(
"%s: host kernel lacks XFRM/IPsec support; install matching kmod-ipsec and kmod-ipsec4/6 (OpenWrt), or enable CONFIG_XFRM_USER and ESP in the kernel: %s",
operation.description,
message,
)
}
// Operation descriptions contain no SPI keys or subscriber identity.
return fmt.Errorf("%s: %s", operation.description, message)
}
@@ -11,6 +11,19 @@ import (
"time"
)
func TestRunIPCommandExplainsMissingKernelXFRM(t *testing.T) {
directory := t.TempDir()
command := directory + "/ip"
script := "#!/bin/sh\necho 'Cannot open netlink socket: Protocol not supported' >&2\nexit 1\n"
if err := os.WriteFile(command, []byte(script), 0o755); err != nil {
t.Fatal(err)
}
err := runIPCommand(context.Background(), command, xfrmOperation{description: "test state"})
if err == nil || !strings.Contains(err.Error(), "kmod-ipsec") || !strings.Contains(err.Error(), "CONFIG_XFRM_USER") {
t.Fatalf("error = %v", err)
}
}
func TestLinuxIPSecInstallerLifecycle(t *testing.T) {
if os.Getenv("VOCAT_NETNS_TEST") != "1" {
t.Skip("set VOCAT_NETNS_TEST=1 inside an isolated Linux network namespace")
+17
View File
@@ -24,6 +24,23 @@ type ATMapper struct {
Devices ATDeviceController
}
type uiccLocker interface {
LockUICC()
UnlockUICC()
}
func (mapper ATMapper) LockUICC() {
if locker, ok := mapper.Devices.(uiccLocker); ok {
locker.LockUICC()
}
}
func (mapper ATMapper) UnlockUICC() {
if locker, ok := mapper.Devices.(uiccLocker); ok {
locker.UnlockUICC()
}
}
func (mapper ATMapper) Get(configuredID string) (device.Device, error) {
physicalID, err := mapper.resolve(context.Background(), configuredID)
if err != nil {
+124
View File
@@ -0,0 +1,124 @@
package vowifi
import (
"context"
"errors"
"fmt"
"strings"
"sync"
"vocat/internal/pcsc"
)
type PCSCBindingResolver func(context.Context, string) (pcsc.Selector, string, error)
// PCSCAdapter uses a directly attached USB smart-card reader as the UICC for
// Wi-Fi Calling. It deliberately exposes no cellular-radio behaviour.
type PCSCAdapter struct {
service *pcsc.Service
resolve PCSCBindingResolver
mu sync.RWMutex
bindings map[string]string
}
var (
_ SIMIdentityReader = (*PCSCAdapter)(nil)
_ SMSCenterReader = (*PCSCAdapter)(nil)
_ AKAProvider = (*PCSCAdapter)(nil)
_ RadioController = (*PCSCAdapter)(nil)
)
func NewPCSCAdapter(service *pcsc.Service, resolver PCSCBindingResolver) (*PCSCAdapter, error) {
if service == nil || resolver == nil {
return nil, errors.New("vocat: PC/SC service and reader resolver are required")
}
return &PCSCAdapter{service: service, resolve: resolver, bindings: make(map[string]string)}, nil
}
func (adapter *PCSCAdapter) ReadIdentity(ctx context.Context, deviceID string) (SIMIdentity, error) {
selector, pin, err := adapter.resolve(ctx, strings.TrimSpace(deviceID))
if err != nil {
return SIMIdentity{}, err
}
identity, err := adapter.service.ReadIdentity(ctx, selector, pin)
if err != nil {
return SIMIdentity{}, fmt.Errorf("read USB SIM identity: %w", err)
}
if len(identity.IMSI) < 5 {
return SIMIdentity{}, errors.New("vocat: USB SIM reader returned an invalid IMSI")
}
adapter.mu.Lock()
adapter.bindings[identity.ICCID] = strings.TrimSpace(deviceID)
adapter.mu.Unlock()
mncLength := identity.MNCLength
if mncLength != 2 && mncLength != 3 {
if mcc, mnc, ok := assignedHomePLMN(identity.IMSI); ok {
return SIMIdentity{ICCID: identity.ICCID, IMSI: identity.IMSI, HomeMCC: mcc, HomeMNC: mnc, SMSC: identity.SMSC}, nil
}
return SIMIdentity{}, ErrEC20MNCUnavailable
}
if len(identity.IMSI) < 3+mncLength {
return SIMIdentity{}, errors.New("vocat: USB SIM IMSI is shorter than its EF_AD home PLMN")
}
return SIMIdentity{
ICCID: identity.ICCID, IMSI: identity.IMSI,
HomeMCC: identity.IMSI[:3], HomeMNC: identity.IMSI[3 : 3+mncLength],
SMSC: identity.SMSC,
}, nil
}
func (adapter *PCSCAdapter) ReadSMSCenter(ctx context.Context, deviceID string) (string, error) {
selector, pin, err := adapter.resolve(ctx, strings.TrimSpace(deviceID))
if err != nil {
return "", err
}
identity, err := adapter.service.ReadIdentity(ctx, selector, pin)
if err != nil {
return "", err
}
if strings.TrimSpace(identity.SMSC) == "" {
return "", errors.New("vocat: USB SIM does not expose a service-centre address")
}
return identity.SMSC, nil
}
func (adapter *PCSCAdapter) CheckReady(ctx context.Context, identity SIMIdentity) (AKAEvidence, error) {
selector, pin, err := adapter.resolve(ctx, adapter.deviceID(identity))
if err != nil {
return AKAEvidence{}, err
}
aid, err := adapter.service.CheckReady(ctx, selector, identity.ICCID, pin)
if err != nil {
return AKAEvidence{}, fmt.Errorf("check USB SIM AKA application: %w", err)
}
return AKAEvidence{Ready: true, Application: aid}, nil
}
func (adapter *PCSCAdapter) deviceID(identity SIMIdentity) string {
adapter.mu.RLock()
deviceID := adapter.bindings[identity.ICCID]
adapter.mu.RUnlock()
return deviceID
}
func (adapter *PCSCAdapter) Authenticate(ctx context.Context, identity SIMIdentity, challenge AKAChallenge) (AKAResult, error) {
selector, pin, err := adapter.resolve(ctx, adapter.deviceID(identity))
if err != nil {
return AKAResult{}, err
}
result, err := adapter.service.Authenticate(ctx, selector, identity.ICCID, pin, pcsc.AKAChallenge(challenge))
if err != nil {
if errors.Is(err, pcsc.ErrAKARejected) {
return AKAResult{}, errors.Join(ErrEC20AKAMACFailure, err)
}
return AKAResult{}, fmt.Errorf("authenticate with USB SIM: %w", err)
}
return AKAResult(result), nil
}
func (*PCSCAdapter) Snapshot(context.Context, string) (RadioSnapshot, error) {
return RadioSnapshot{OperatingMode: 4, PureAirplanePolicy: true}, nil
}
func (*PCSCAdapter) StopCellularData(context.Context, string) error { return nil }
func (*PCSCAdapter) EnterVoWiFiRFOff(context.Context, string) error { return nil }
func (*PCSCAdapter) Restore(context.Context, string, RadioSnapshot) error { return nil }
+224 -11
View File
@@ -1,12 +1,11 @@
#!/usr/bin/env bash
#
# vocat install / update script for binary + systemd deployments.
# vocat install / update script for systemd and OpenWrt/procd deployments.
#
# Usage:
# sudo bash install.sh [version] # install a specific version
# sudo bash install.sh # install latest release
# sudo bash install.sh --force # reinstall even at the same version
# curl -fsSL <raw url> | sudo bash # one-liner (latest)
# bash install.sh [version] # run directly when already root
# sudo bash install.sh [version] # run through sudo as a normal user
# bash install.sh --check-env # check VoWiFi host prerequisites
#
# Behavior:
# - Prompts for script language (中文 / English) as soon as it runs.
@@ -14,7 +13,9 @@
# - On first install, generates a random 32-char admin password, writes it to
# /etc/vocat/env (0600, loaded by the systemd unit), and prints it ONCE.
# - On update, preserves the existing env file and credentials.
# - (Re)writes the systemd unit and restarts the service.
# - Verifies Linux XFRM/IPsec support required by IMS; on OpenWrt it tries
# the matching opkg packages first.
# - (Re)writes a systemd or OpenWrt/procd service and restarts it.
#
# Published script: must contain no secrets, IPs, or passwords.
@@ -31,6 +32,7 @@ LINK_PATH="/usr/local/bin/vocat"
ENV_DIR="/etc/vocat"
ENV_FILE="${ENV_DIR}/env"
UNIT_PATH="/etc/systemd/system/vocat.service"
OPENWRT_INIT_PATH="/etc/init.d/vocat"
# --- Language ----------------------------------------------------------------
LANG_CHOICE=""
@@ -76,14 +78,44 @@ die() {
prompt_language
# BusyBox/OpenWrt images often omit coreutils' install(1). Provide the small
# subset used by this script so the same installer works on router firmware.
if ! command -v install >/dev/null 2>&1; then
install() {
if [ "${1:-}" = "-d" ]; then
shift
local mode="0755"
if [ "${1:-}" = "-m" ]; then
mode="$2"
shift 2
fi
mkdir -p "$@"
chmod "$mode" "$@"
return
fi
local mode="0755"
if [ "${1:-}" = "-m" ]; then
mode="$2"
shift 2
fi
[ "$#" -eq 2 ] || return 2
cp "$1" "$2"
chmod "$mode" "$2"
}
fi
# --- Parse args --------------------------------------------------------------
FORCE=0
CHECK_ENV=0
SKIP_VOWIFI_CHECK="${VOCAT_SKIP_VOWIFI_CHECK:-0}"
TARGET_VERSION=""
for arg in "$@"; do
case "$arg" in
--force) FORCE=1 ;;
--check-env) CHECK_ENV=1 ;;
--skip-vowifi-check) SKIP_VOWIFI_CHECK=1 ;;
-h|--help)
msg "用法: sudo bash install.sh [--force] [版本]" "Usage: sudo bash install.sh [--force] [version]"
msg "用法: bash install.sh [--force] [--check-env] [--skip-vowifi-check] [版本]" "Usage: bash install.sh [--force] [--check-env] [--skip-vowifi-check] [version]"
exit 0
;;
*) TARGET_VERSION="${arg#v}" ;;
@@ -110,6 +142,89 @@ resolve_target_version() {
TARGET_VERSION="${tag#v}"
}
# --- Host prerequisites ------------------------------------------------------
is_openwrt() {
[ -f /etc/openwrt_release ] || [ -x /sbin/procd ]
}
xfrm_works() {
command -v ip >/dev/null 2>&1 && ip xfrm state list >/dev/null 2>&1
}
opkg_has_package() {
opkg list "$1" 2>/dev/null | grep -q "^$1 -"
}
install_openwrt_vowifi_packages() {
msg "正在检查 OpenWrt/Kwrt 的 VoWiFi 内核组件..." "Checking OpenWrt/Kwrt VoWiFi kernel components..."
opkg update >/dev/null 2>&1 || msg \
"警告:opkg 软件源更新失败,将使用现有索引继续检查。" \
"Warning: opkg feed update failed; checking the existing index."
local packages=""
local package
for package in \
ip-full \
kmod-ipsec kmod-ipsec4 kmod-ipsec6 \
kmod-crypto-authenc kmod-crypto-cbc kmod-crypto-aes \
kmod-crypto-hmac kmod-crypto-sha1; do
if opkg_has_package "$package"; then
packages="$packages $package"
fi
done
if [ -n "$packages" ]; then
# Kernel packages must come from this firmware's own feed. opkg checks
# the kernel ABI and refuses mismatched modules; never bypass that check.
# shellcheck disable=SC2086
opkg install $packages >/dev/null 2>&1 || true
fi
}
install_linux_ip_tool() {
command -v ip >/dev/null 2>&1 && return 0
if command -v apt-get >/dev/null 2>&1; then
apt-get update -qq && apt-get install -y iproute2
elif command -v dnf >/dev/null 2>&1; then
dnf install -y iproute
elif command -v yum >/dev/null 2>&1; then
yum install -y iproute
elif command -v pacman >/dev/null 2>&1; then
pacman -Sy --noconfirm iproute2
elif command -v apk >/dev/null 2>&1; then
apk add --no-cache iproute2
fi
}
check_vowifi_environment() {
if [ "$SKIP_VOWIFI_CHECK" = "1" ]; then
msg \
"已跳过 VoWiFi 内核环境检查;IMS 通话和短信可能不可用。" \
"Skipped the VoWiFi kernel check; IMS calls and SMS may not work."
return
fi
if is_openwrt && command -v opkg >/dev/null 2>&1; then
# Install the crypto algorithms even when NETLINK_XFRM already works;
# some minimal images provide xfrm_user but omit AES-CBC/authenc.
install_openwrt_vowifi_packages
elif ! xfrm_works; then
install_linux_ip_tool
fi
if xfrm_works; then
msg "VoWiFi XFRM/IPsec 环境安装并验证成功。" "VoWiFi XFRM/IPsec environment installed and verified."
return
fi
if is_openwrt; then
die \
"当前 OpenWrt/Kwrt 内核 $(uname -r) 不支持 NETLINK_XFRM,且软件源没有匹配的 kmod-ipsec。请使用包含 kmod-ipsec、kmod-ipsec4、kmod-ipsec6、kmod-crypto-authenc、kmod-crypto-cbc、kmod-crypto-aes 和 kmod-crypto-sha1 的同版本固件;严禁安装其他内核版本的 kmod。仅使用非 VoWiFi 功能时可加 --skip-vowifi-check。" \
"The OpenWrt/Kwrt kernel $(uname -r) lacks NETLINK_XFRM and its feed has no matching kmod-ipsec. Use a firmware built with matching kmod-ipsec, kmod-ipsec4/6, crypto-authenc, CBC, AES and SHA1 modules. Never force kmods from another kernel. Use --skip-vowifi-check only for non-VoWiFi operation."
fi
die \
"当前 Linux 内核不支持 XFRM/IPsecVoWiFi IMS 无法工作。请启用 CONFIG_XFRM、CONFIG_XFRM_USER、CONFIG_INET_ESP、CONFIG_INET6_ESP、AES-CBC 和 HMAC-SHA1。" \
"This Linux kernel lacks XFRM/IPsec required by VoWiFi IMS. Enable CONFIG_XFRM, CONFIG_XFRM_USER, CONFIG_INET_ESP, CONFIG_INET6_ESP, AES-CBC and HMAC-SHA1."
}
# --- Skip if already installed at the same version ---------------------------
skip_if_equal() {
[ -x "$BINARY_PATH" ] || return 0
@@ -159,6 +274,10 @@ download_and_verify() {
[ -n "$expected" ] || die "SHA256SUMS 中找不到 $asset 的校验行。" "$asset not found in SHA256SUMS."
actual=$(sha256sum "${VOCAT_TMP}/vocat" | awk '{print $1}')
[ "$actual" = "$expected" ] || die "SHA-256 校验失败。" "SHA-256 verification failed."
chmod 0755 "${VOCAT_TMP}/vocat"
"${VOCAT_TMP}/vocat" version >/dev/null 2>&1 || die \
"Downloaded binary cannot run on this system; keeping the installed version." \
"The downloaded binary cannot run on this host; the installed version was not changed."
}
# --- Install binary ----------------------------------------------------------
@@ -218,6 +337,8 @@ TimeoutStartSec=30s
# HTTP, VoWiFi, and modem cleanup have bounded shutdown contexts totalling up
# to 30 seconds. Leave a small margin before systemd resorts to SIGKILL.
TimeoutStopSec=40s
RuntimeDirectory=vocat
RuntimeDirectoryMode=0755
AmbientCapabilities=CAP_NET_ADMIN CAP_NET_RAW
CapabilityBoundingSet=CAP_NET_ADMIN CAP_NET_RAW
@@ -246,11 +367,98 @@ EOF
chmod 0644 "$UNIT_PATH"
}
write_openwrt_init() {
cat > "$OPENWRT_INIT_PATH" <<'EOF'
#!/bin/sh /etc/rc.common
START=95
STOP=10
USE_PROCD=1
PROCD_TERM_TIMEOUT=40
PROGRAM=/opt/vocat/bin/vocat
ENV_FILE=/etc/vocat/env
start_service() {
procd_open_instance
procd_set_param command "$PROGRAM" serve
procd_set_param env VOCAT_DATABASE_PATH=/opt/vocat/data/vocat.db
if [ -r "$ENV_FILE" ]; then
while IFS='=' read -r name value; do
case "$name" in VOCAT_*) procd_append_param env "$name=$value" ;; esac
done < "$ENV_FILE"
fi
procd_set_param respawn 3600 5 5
procd_set_param stdout 1
procd_set_param stderr 1
procd_close_instance
}
service_triggers() { procd_add_reload_trigger vocat; }
EOF
chmod 0755 "$OPENWRT_INIT_PATH"
}
write_service() {
if command -v systemctl >/dev/null 2>&1 && [ -d /run/systemd/system ]; then
write_unit
return
fi
if [ -x /sbin/procd ] || [ -x /sbin/ubusd ]; then
write_openwrt_init
return
fi
die "Unsupported service manager." "Neither systemd nor OpenWrt procd was detected."
}
enable_and_start() {
if [ -x "$OPENWRT_INIT_PATH" ] && { [ -x /sbin/procd ] || [ -x /sbin/ubusd ]; }; then
"$OPENWRT_INIT_PATH" enable
# Stop explicitly before restart. Some procd/rc.common variants return
# from restart while the previous process is still inside its bounded
# VoWiFi cleanup, so the replacement can race the host-wide instance
# lock and enter a respawn cycle.
"$OPENWRT_INIT_PATH" stop || true
local stop_attempt
for stop_attempt in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40; do
if ! "$OPENWRT_INIT_PATH" running; then
break
fi
sleep 1
done
if "$OPENWRT_INIT_PATH" restart; then
# Modems may need several seconds to release and reopen their AT
# port after procd stops the previous process. Require consecutive
# healthy observations so a short-lived respawn is not mistaken for
# a successful upgrade.
local attempt stable
stable=0
for attempt in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30; do
sleep 1
if "$OPENWRT_INIT_PATH" running; then
stable=$((stable + 1))
if [ "$stable" -ge 3 ]; then
rm -f "${BINARY_PATH}.bak"
return
fi
else
stable=0
fi
done
fi
if [ -e "${BINARY_PATH}.bak" ]; then
cp -a "${BINARY_PATH}.bak" "$BINARY_PATH"
"$OPENWRT_INIT_PATH" restart || true
fi
die "OpenWrt vocat service failed to start." "The OpenWrt vocat service failed to start."
fi
systemctl daemon-reload
systemctl enable vocat
if systemctl restart vocat; then
return
local attempt
for attempt in 1 2 3 4 5; do
if systemctl is-active --quiet vocat; then
rm -f "${BINARY_PATH}.bak"
return
fi
sleep 1
done
fi
if [ -e "${BINARY_PATH}.bak" ]; then
msg "新版本启动失败,正在恢复旧二进制。" "The new version failed to start; restoring the previous binary."
@@ -261,14 +469,19 @@ enable_and_start() {
}
# --- Main --------------------------------------------------------------------
resolve_target_version
detect_arch
check_vowifi_environment
if [ "$CHECK_ENV" -eq 1 ]; then
msg "VoCat 运行环境检查完成。" "VoCat host environment check completed."
exit 0
fi
resolve_target_version
skip_if_equal
download_and_verify
install_binary
ensure_data_dir
setup_env
write_unit
write_service
enable_and_start
if [ "$FIRST_INSTALL" -eq 1 ]; then
@@ -281,7 +494,7 @@ if [ "$FIRST_INSTALL" -eq 1 ]; then
echo
msg "用户名为 admin。请立即记录此密码。" "Username is admin. Record this password now."
msg "登录后或运行以下命令修改密码:" "Change it via the web UI or run:"
echo " sudo vocat menu"
echo " vocat menu"
msg "==========================================" "=============================================="
else
echo
+30
View File
@@ -0,0 +1,30 @@
#!/bin/sh /etc/rc.common
START=95
STOP=10
USE_PROCD=1
PROCD_TERM_TIMEOUT=40
PROGRAM=/opt/vocat/bin/vocat
ENV_FILE=/etc/vocat/env
start_service() {
procd_open_instance
procd_set_param command "$PROGRAM" serve
procd_set_param env VOCAT_DATABASE_PATH=/opt/vocat/data/vocat.db
if [ -r "$ENV_FILE" ]; then
while IFS='=' read -r name value; do
case "$name" in
VOCAT_*) procd_append_param env "$name=$value" ;;
esac
done < "$ENV_FILE"
fi
procd_set_param respawn 3600 5 5
procd_set_param stdout 1
procd_set_param stderr 1
procd_close_instance
}
service_triggers() {
procd_add_reload_trigger vocat
}
+9
View File
@@ -0,0 +1,9 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128" role="img" aria-label="USB SIM reader">
<defs><linearGradient id="a" x1="0" y1="0" x2="1" y2="1"><stop stop-color="#64748b"/><stop offset="1" stop-color="#1e293b"/></linearGradient></defs>
<rect x="12" y="31" width="104" height="68" rx="14" fill="url(#a)"/>
<rect x="25" y="43" width="55" height="42" rx="7" fill="#0f172a" stroke="#94a3b8" stroke-width="2"/>
<path d="M40 51h24l8 8v18H40z" fill="#facc15"/><path d="M44 60h24M50 54v23M60 54v23" stroke="#a16207" stroke-width="2"/>
<rect x="91" y="51" width="25" height="29" rx="4" fill="#cbd5e1"/>
<path d="M98 58h11M98 65h11M98 72h11" stroke="#64748b" stroke-width="3"/>
<circle cx="101" cy="89" r="3" fill="#22c55e"/>
</svg>

After

Width:  |  Height:  |  Size: 752 B

@@ -15,9 +15,10 @@ export interface CardPolicyPanelProps {
policy: CardPolicy | null;
deviceOnline: boolean;
onPolicyChanged: () => void | Promise<void>;
wifiCallingOnly?: boolean;
}
export function CardPolicyPanel({ deviceId, iccid, policy, deviceOnline, onPolicyChanged }: CardPolicyPanelProps) {
export function CardPolicyPanel({ deviceId, iccid, policy, deviceOnline, onPolicyChanged, wifiCallingOnly = false }: CardPolicyPanelProps) {
const { t } = useI18n();
const operable = deviceOnline && !!iccid;
const currentPolicy = policy?.iccid === iccid ? policy : null;
@@ -66,7 +67,7 @@ export function CardPolicyPanel({ deviceId, iccid, policy, deviceOnline, onPolic
</div>
<div>
<div className="text-lg font-bold text-gray-900 dark:text-white">{t("卡策略")}</div>
<div className="text-xs text-gray-500 dark:text-gray-400">{t("VoWiFi / 飞行模式 开关跟着 SIM 卡走,切换即时生效")}</div>
<div className="text-xs text-gray-500 dark:text-gray-400">{wifiCallingOnly ? t("USB SIM 读卡器仅用于 WiFi Calling,策略跟随 ICCID 保存") : t("VoWiFi / 飞行模式 开关跟着 SIM 卡走,切换即时生效")}</div>
</div>
</div>
{!iccid ? (
@@ -119,7 +120,7 @@ export function CardPolicyPanel({ deviceId, iccid, policy, deviceOnline, onPolic
</div>
</div>
<div className="grid grid-cols-1 gap-3 lg:grid-cols-2">
<PolicySwitchCard
<PolicySwitchCard
title="VoWiFi"
subtitle={t("启用时强制关闭蜂窝射频;关闭 VoWiFi 后仍保持飞行模式")}
tone="orange"
@@ -129,7 +130,7 @@ export function CardPolicyPanel({ deviceId, iccid, policy, deviceOnline, onPolic
failed={toggles.vowifiFailed}
onToggle={toggles.onVoWiFiToggle}
/>
<PolicySwitchCard
{!wifiCallingOnly ? <PolicySwitchCard
title={t("飞行模式")}
subtitle={t("只有手动关闭此开关才允许设备连接基站")}
tone="indigo"
@@ -138,15 +139,15 @@ export function CardPolicyPanel({ deviceId, iccid, policy, deviceOnline, onPolic
pending={toggles.airplanePending}
failed={toggles.airplaneFailed}
onToggle={toggles.onAirplaneToggle}
/>
/> : null}
</div>
<CardPolicyAPN
{!wifiCallingOnly ? <CardPolicyAPN
deviceId={deviceId}
iccid={iccid}
policy={currentPolicy}
deviceOnline={deviceOnline}
onSaved={onPolicyChanged}
/>
/> : null}
</div>
) : null}
</div>
@@ -30,7 +30,7 @@ function isQmiMode(d?: DiscoveredDevice | null): boolean {
}
function modeLabel(d?: DiscoveredDevice | null): string {
const m = String(d?.mode || "unknown").toLowerCase();
return m === "qmi" ? "QMI" : m === "mbim" ? "MBIM" : m === "ecm" ? "ECM" : m === "rndis" ? "RNDIS" : m === "ncm" ? "NCM" : "UNKNOWN";
return m === "pcsc" ? "PC/SC" : m === "qmi" ? "QMI" : m === "mbim" ? "MBIM" : m === "ecm" ? "ECM" : m === "rndis" ? "RNDIS" : m === "ncm" ? "NCM" : "UNKNOWN";
}
function Field({ label, children }: { label: ReactNode; children: ReactNode }) {
@@ -47,6 +47,7 @@ export function DeviceAddDialog(props: DeviceAddDialogProps) {
const { addSelected, addConfig } = props;
const fixedQmi = isQmiControl(addSelected?.controlPath || addConfig?.controlDevice);
const isMbim = String(addSelected?.mode || "").toLowerCase() === "mbim";
const isReader = addSelected?.hardwareKind === "pcsc" || String(addSelected?.mode || "").toLowerCase() === "pcsc";
useEffect(() => {
if (fixedQmi && addConfig.deviceBackend !== "qmi") props.onConfigChange({ ...addConfig, deviceBackend: "qmi" });
@@ -57,7 +58,7 @@ export function DeviceAddDialog(props: DeviceAddDialogProps) {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isMbim]);
const backendOptions = [
const backendOptions = isReader ? [{ value: "pcsc", label: "PC/SC" }] : [
...(isMbim
? []
: [
@@ -161,6 +162,9 @@ export function DeviceAddDialog(props: DeviceAddDialogProps) {
<Field label={t("控制设备")}>
<Input value={addConfig.controlDevice} disabled />
</Field>
{isReader ? <Field label="SIM PIN">
<Input type="password" value={addConfig.simPin} onChange={(e) => set({ simPin: e.target.value })} maxLength={8} inputMode="numeric" placeholder={t("仅在 SIM 启用 PIN 时填写")} />
</Field> : null}
<div className="flex items-center justify-between rounded-xl border border-gray-200 bg-gray-50 p-3">
<div>
<div className="text-sm font-bold text-gray-800">{t("设备后端模式")}</div>
@@ -173,7 +177,7 @@ export function DeviceAddDialog(props: DeviceAddDialogProps) {
onChange={(v) => set({ deviceBackend: v })}
className="w-[110px]"
placeholder="AT"
disabled={fixedQmi || isMbim}
disabled={fixedQmi || isMbim || isReader}
options={backendOptions}
/>
</div>
@@ -34,13 +34,14 @@ export function DeviceConfigTab({ editConfig, deviceStatus, saving, deleting, on
const usbPath = deviceStatus?.usbPath || editConfig?.usbPath;
const isQmi = isQmiControl(controlDevice);
const isMbim = String(editConfig?.deviceBackend || "").toLowerCase() === "mbim";
const isReader = editConfig?.deviceType === "usb_sim_reader";
useEffect(() => {
if (isQmi && editConfig && editConfig.deviceBackend !== "qmi") onEditConfig({ ...editConfig, deviceBackend: "qmi" });
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isQmi]);
const backendOptions = [
const backendOptions = isReader ? [{ value: "pcsc", label: "PC/SC" }] : [
...(isMbim
? []
: [
@@ -106,6 +107,9 @@ export function DeviceConfigTab({ editConfig, deviceStatus, saving, deleting, on
<Field label={t("控制设备")}>
<Input value={controlDevice || ""} disabled placeholder={t("由系统自动探测")} />
</Field>
{isReader ? <Field label="SIM PIN">
<Input type="password" value={editConfig.simPin || ""} onChange={(e) => onEditConfig({ ...editConfig, simPin: e.target.value })} maxLength={8} inputMode="numeric" placeholder={t("留空表示不修改;仅在 SIM 启用 PIN 时填写")} />
</Field> : null}
<div className="ui-panel-muted space-y-2 p-3">
<div className="flex items-center justify-between">
<div>
@@ -123,7 +127,7 @@ export function DeviceConfigTab({ editConfig, deviceStatus, saving, deleting, on
onChange={(v) => onEditConfig({ ...editConfig, deviceBackend: v as DeviceConfig["deviceBackend"] })}
className="w-[120px]"
placeholder="AT"
disabled={isQmi || isMbim}
disabled={isQmi || isMbim || isReader}
options={backendOptions}
/>
</div>
@@ -15,6 +15,7 @@ export interface DeviceDetailHeaderProps {
onReconnectVowifi: () => void;
onRebootModem: () => void;
onOpenSms: () => void;
wifiCallingOnly?: boolean;
}
export function DeviceDetailHeader(props: DeviceDetailHeaderProps) {
@@ -42,7 +43,7 @@ export function DeviceDetailHeader(props: DeviceDetailHeaderProps) {
<Button loading={props.reconnectingVoWiFi} onClick={props.onReconnectVowifi} className="ui-glass-border !border-0" icon={<ArrowSyncRegular />}>
{t("重连 VoWiFi")}
</Button>
) : device.developerEnabled ? (
) : device.developerEnabled && !props.wifiCallingOnly ? (
<div
className="ui-glass-border flex h-8 items-center gap-2 rounded-lg px-3 text-sm text-gray-700 dark:text-gray-200"
title={t("蜂窝数据仅进入 Export Proxy 的受保护路由,不会成为主机默认出口")}
@@ -58,9 +59,9 @@ export function DeviceDetailHeader(props: DeviceDetailHeaderProps) {
/>
</div>
) : null}
<Button loading={props.rebooting} onClick={props.onRebootModem} className="ui-glass-border !border-0 hover:!text-red-600" icon={<PowerRegular />}>
{!props.wifiCallingOnly ? <Button loading={props.rebooting} onClick={props.onRebootModem} className="ui-glass-border !border-0 hover:!text-red-600" icon={<PowerRegular />}>
{t("重启模组")}
</Button>
</Button> : null}
<Button onClick={props.onOpenSms} className="ui-glass-border !border-0" icon={<ChatRegular />}>
{t("短信")}
</Button>
@@ -26,12 +26,14 @@ export function DeviceOverviewTab(props: DeviceOverviewTabProps) {
const { t } = useI18n();
const [operatorOpen, setOperatorOpen] = useState(false);
const { device } = props;
const wifiCallingOnly = device.deviceType === "usb_sim_reader";
const showNetworkDetails = !!device.developerEnabled && !wifiCallingOnly;
return (
<div className="space-y-4">
<div className="grid grid-cols-1 gap-4 lg:grid-cols-3">
<div className={`grid grid-cols-1 gap-4 ${showNetworkDetails ? "lg:grid-cols-3" : "lg:grid-cols-2"}`}>
<div className="ui-panel-muted p-4">
<div className="mb-3 text-xs font-bold uppercase tracking-wider text-gray-500">{t("运行状态")}</div>
{isVoWiFiInUse(device) ? (
{isVoWiFiInUse(device) && !(device.modem?.imei && device.modem?.simInserted === false) ? (
<OverviewVowifiCard device={device} />
) : (
<OverviewNetworkCard device={device} onOpenOperatorSelection={() => setOperatorOpen(true)} />
@@ -44,16 +46,16 @@ export function DeviceOverviewTab(props: DeviceOverviewTabProps) {
e911Starting={props.e911Starting}
onSetupE911={props.onSetupE911}
/>
<OverviewNetworkPanel
{showNetworkDetails ? <OverviewNetworkPanel
device={device}
trafficMinuteRx={props.trafficMinuteRx}
trafficMinuteTx={props.trafficMinuteTx}
trafficSpeedRx={props.trafficSpeedRx}
trafficSpeedTx={props.trafficSpeedTx}
/>
/> : null}
</div>
{device.developerEnabled && device.networkEnabled && device.id ? <OverviewTrafficChart deviceId={device.id} /> : null}
{device?.id ? (
{device?.id && !wifiCallingOnly ? (
<OperatorSelectionDialog
open={operatorOpen}
deviceId={device.id}
@@ -26,17 +26,20 @@ export function OverviewNetworkCard({ device, onOpenOperatorSelection }: { devic
const modem = device.modem;
const online = isDeviceOnline(device);
const cellularRegistered = isRegistered(device);
const simMissing = !!modem?.imei && modem?.simInserted === false;
// A persisted runtime may briefly describe the old session while disable is
// being cleaned up. Desired policy is authoritative for the overview badge.
const vowifiRegistered = !!device.vowifiEnabled && !!(device.vowifiActive || device.vowifiRuntime?.smsReady);
const registered = cellularRegistered || vowifiRegistered;
const registered = !simMissing && (cellularRegistered || vowifiRegistered);
const radioOffForVowifi = vowifiRegistered && (modem?.operatingMode === 0 || modem?.operatingMode === 4 || device.flightMode);
const tone = isRecoveringPhase(device.lifecyclePhase) ? "warning" : online ? (registered ? "success" : "warning") : "danger";
let statusText: string;
const phaseLabel = lifecycleLabel(device.lifecyclePhase);
if (phaseLabel && device.lifecyclePhase !== "online" && device.lifecyclePhase !== "offline") statusText = phaseLabel;
else if (online) {
else if (online) {
if (simMissing) statusText = t("SIM卡未插入");
else
statusText = registered
? ""
: device.registrationStateLabel === "searching"
@@ -49,7 +52,9 @@ export function OverviewNetworkCard({ device, onOpenOperatorSelection }: { devic
const level = signalLevel(modem?.signalDbm);
const sigTone = signalTone(modem?.signalDbm);
const netMode = [modem?.networkDuplex, modem?.networkMode].filter(Boolean).join(" ");
const cellularRegistrationText = modem?.regStatus === 5
const cellularRegistrationText = simMissing
? t("SIM卡未插入")
: modem?.regStatus === 5
? t("已驻网(漫游)")
: modem?.regStatus === 1
? t("已驻网")
@@ -77,11 +77,7 @@ export function OverviewNetworkPanel({ device, trafficMinuteRx, trafficMinuteTx,
: "";
if (!developerActive) {
return (
<div className="ui-panel-muted p-4">
<div className="text-xs font-bold uppercase tracking-wider text-gray-500">{t("网络")}</div>
</div>
);
return null;
}
return (
+1
View File
@@ -44,6 +44,7 @@ export interface AddDeviceForm {
atPort: string;
controlDevice: string;
deviceBackend: string;
simPin: string;
}
export interface LoadError {
@@ -38,7 +38,7 @@ export function DeviceQuotaCard({
<Input
type="number"
min={1}
max={value?.maxDeviceLimit ?? 128}
max={value?.maxDeviceLimit ?? 10}
value={Number.isFinite(limit) ? limit : ""}
disabled={loading || saving}
onChange={(event) => onLimitChange(Number(event.target.value))}
@@ -38,7 +38,7 @@ export function SMSRateLimitCard({
<Input
type="number"
min={1}
max={value?.maxSmsHourlyLimit ?? 1000}
max={value?.maxSmsHourlyLimit ?? 20}
value={Number.isFinite(limit) ? limit : ""}
disabled={loading || saving}
onChange={(event) => onLimitChange(Number(event.target.value))}
@@ -46,8 +46,8 @@ export function SMSRateLimitCard({
/>
<p className="text-xs leading-5 text-gray-500 dark:text-gray-400">
{zh
? `采用滚动一小时窗口,网页、TG Bot、自动任务、API、VoWiFi 与基站发送全部计入;接收短信不受限制。关闭开发者模式后恢复为 ${value?.defaultSmsHourlyLimit ?? 10} 条/小时。`
: `Uses a rolling one-hour window across the web UI, Telegram bot, automatic tasks, API, VoWiFi, and cellular sending. Receiving is unlimited. Disabling developer mode restores ${value?.defaultSmsHourlyLimit ?? 10} messages/hour.`}
? "采用滚动一小时窗口,网页、TG Bot、自动任务、API、VoWiFi 与基站发送全部计入;接收短信不受限制。"
: "Uses a rolling one-hour window across the web UI, Telegram bot, automatic tasks, API, VoWiFi, and cellular sending. Receiving is unlimited."}
</p>
<Button variant="primary" loading={saving} disabled={loading} onClick={onSave} className="w-full !border-0">
{zh ? "保存短信速率限制" : "Save SMS rate limit"}
+1
View File
@@ -6,6 +6,7 @@ export const DEVICE_TYPES: ReadonlyArray<{ value: DeviceType; label: string; ima
{ value: "wifi_410", label: "410 WiFi 棒(高通芯片)", image: "/410.png" },
{ value: "dji_4g", label: "大疆 4G 模块(移远芯片)", image: "/dj.png" },
{ value: "pcie_ec20_ec25", label: "PCIe EC20/EC25(移远芯片)", image: "/ec20.png" },
{ value: "usb_sim_reader", label: "USB SIM 读卡器(仅 WiFi Calling", image: "/sim-reader.svg" },
];
export function normalizeDeviceType(value?: string | null): DeviceType {
+9 -2
View File
@@ -5,6 +5,10 @@
* /
*/
export const EN_DICT: Record<string, string> = {
"USB SIM 读卡器(仅 WiFi Calling": "USB SIM Reader (WiFi Calling only)",
"仅在 SIM 启用 PIN 时填写": "Only enter this when SIM PIN is enabled",
"留空表示不修改;仅在 SIM 启用 PIN 时填写": "Leave blank to keep unchanged; only enter this when SIM PIN is enabled",
"USB SIM 读卡器仅用于 WiFi Calling,策略跟随 ICCID 保存": "The USB SIM reader is for WiFi Calling only; policy is saved per ICCID",
// Cellular APN profiles.
"蜂窝 APN": "Cellular APN",
"APN 列表和启用状态跟随当前 ICCID/Profile 保存": "APN profiles and the active selection are saved per ICCID/Profile",
@@ -153,6 +157,7 @@ export const EN_DICT: Record<string, string> = {
: "SMS Test",
: "Automatic Tasks",
"按周期切换指定 eSIM Profile,并在设备串行队列中执行短信、通话或漫游公网 IP 任务": "Switch to a selected eSIM profile on schedule, then run SMS, call, or roaming public-IP jobs in a per-device queue",
"按周期切换指定 eSIM Profile,并在设备串行队列中执行短信或通话任务": "Switch to a selected eSIM profile on schedule, then run SMS or call jobs in a per-device queue",
: "Add Task",
"设备 / Profile": "Device / Profile",
: "Environment",
@@ -189,7 +194,7 @@ export const EN_DICT: Record<string, string> = {
: "Task Type",
IP: "Enable roaming data and get the public IP once",
"基站直连(自动选网)": "Cellular (automatic network selection)",
"该任务固定使用基站直连和自动选网;执行时会开启漫游数据,并通过模块接口访问 ipinfo.io。需要开启开发者模式。": "This task always uses cellular direct mode with automatic network selection. It enables roaming data and accesses ipinfo.io through the modem interface. Developer mode is required.",
"该任务固定使用基站直连和自动选网;执行时会开启漫游数据,并通过模块接口访问 ipinfo.io。": "This task always uses cellular direct mode with automatic network selection. It enables roaming data and accesses ipinfo.io through the modem interface.",
: "First Run Date",
: "Run Time",
: "Interval",
@@ -765,7 +770,9 @@ export const EN_DICT: Record<string, string> = {
"暂无设备": "No devices",
"最后原因": "Last Reason",
"最后成功:": "Last success: ",
"未检测到 eUICC": "No eUICC detected",
"未检测到 eUICC": "No eUICC detected",
"SIM卡未插入": "No SIM card inserted",
"USB SIM读卡器仅支持VoWiFi短信和通话任务": "USB SIM readers support VoWiFi SMS and call tasks only",
"未生效": "Not in effect",
"未知": "Unknown",
"未知日期": "Unknown date",
+41 -10
View File
@@ -7,7 +7,7 @@ import {
SendClockRegular,
} from "@fluentui/react-icons";
import { api, apiMessage } from "../api";
import type { DeviceListItem, DevicesResponse } from "../types";
import type { DeviceListItem, DevicesResponse, SystemInfo } from "../types";
import type { EsimProfileGroup } from "../components/devices/types";
import {
Button,
@@ -140,6 +140,7 @@ export default function AutomaticTasksPage() {
const [runsPage, setRunsPage] = useState(1);
const [runsPageSize, setRunsPageSize] = useState(20);
const [devices, setDevices] = useState<DeviceListItem[]>([]);
const [advancedTasksAvailable, setAdvancedTasksAvailable] = useState(false);
const [profiles, setProfiles] = useState<ProfileOption[]>([]);
const [loading, setLoading] = useState(true);
const [profileLoading, setProfileLoading] = useState(false);
@@ -155,12 +156,14 @@ export default function AutomaticTasksPage() {
const load = useCallback(async (initial = false) => {
if (initial) setLoading(true);
try {
const [taskData, deviceData] = await Promise.all([
const [taskData, deviceData, systemInfo] = await Promise.all([
api<{ tasks?: AutomaticTask[] }>("/automatic-tasks"),
api<DevicesResponse>("/devices"),
api<SystemInfo>("/system/info"),
]);
setTasks(taskData.tasks || []);
setDevices(deviceData.devices || []);
setAdvancedTasksAvailable(!!systemInfo.developer);
} catch (error) {
message.error(apiMessage(error));
} finally {
@@ -251,7 +254,7 @@ export default function AutomaticTasksPage() {
function edit(task?: AutomaticTask) {
const deviceId = task?.deviceId || devices[0]?.id || "";
const next = task ? {
let next = task ? {
id: task.id,
name: task.name,
enabled: task.enabled,
@@ -269,13 +272,24 @@ export default function AutomaticTasksPage() {
message: task.payload?.message || "",
durationSeconds: task.payload?.durationSeconds || 30,
} : emptyForm(deviceId);
if (devices.find((device) => device.id === deviceId)?.deviceType === "usb_sim_reader") {
next = { ...next, taskType: next.taskType === "public_ip" ? "sms" : next.taskType, environment: "vowifi" };
}
if (!advancedTasksAvailable && (next.taskType === "public_ip" || next.environment === "cellular")) {
next = { ...next, taskType: "sms", environment: "vowifi" };
}
setForm(next);
setOpen(true);
void loadProfiles(deviceId, next.profileIccid);
}
function chooseDevice(deviceId: string) {
setForm((current) => ({ ...current, deviceId, profileIccid: "", profileAid: "" }));
const reader = devices.find((device) => device.id === deviceId)?.deviceType === "usb_sim_reader";
setForm((current) => ({
...current, deviceId, profileIccid: "", profileAid: "",
taskType: reader && current.taskType === "public_ip" ? "sms" : current.taskType,
environment: reader || !advancedTasksAvailable ? "vowifi" : current.environment,
}));
void loadProfiles(deviceId);
}
@@ -285,6 +299,7 @@ export default function AutomaticTasksPage() {
}
function chooseTaskType(taskType: TaskType) {
if ((!advancedTasksAvailable || deviceByID.get(form.deviceId)?.deviceType === "usb_sim_reader") && taskType === "public_ip") return;
setForm((current) => ({
...current,
taskType,
@@ -296,6 +311,10 @@ export default function AutomaticTasksPage() {
if (!form.name.trim()) return message.warning(t("请输入任务名称"));
if (!form.deviceId) return message.warning(t("请选择设备"));
if (!form.profileIccid) return message.warning(t("请选择 eSIM Profile"));
if (deviceByID.get(form.deviceId)?.deviceType === "usb_sim_reader" && (form.environment !== "vowifi" || form.taskType === "public_ip")) {
return message.warning(t("USB SIM读卡器仅支持VoWiFi短信和通话任务"));
}
if (!advancedTasksAvailable && (form.environment !== "vowifi" || form.taskType === "public_ip")) return;
if (form.taskType !== "public_ip" && !form.phone.trim()) return message.warning(t("请输入号码"));
if (form.taskType === "sms" && !form.message.trim()) return message.warning(t("请输入短信内容"));
setSaving(true);
@@ -377,12 +396,23 @@ export default function AutomaticTasksPage() {
const taskTypeLabel = (value: TaskType) => ({ sms: t("发送短信"), call: t("拨打电话并自动挂断"), public_ip: t("获取漫游公网 IP") })[value];
const environmentLabel = (value: TaskEnvironment) => value === "vowifi" ? "VoWiFi" : t("基站直连");
const selectedTaskDeviceIsReader = deviceByID.get(form.deviceId)?.deviceType === "usb_sim_reader";
const taskTypeOptions = [
{ value: "sms", label: t("发送短信") },
{ value: "call", label: t("拨打电话并自动挂断") },
...(advancedTasksAvailable && !selectedTaskDeviceIsReader ? [{ value: "public_ip", label: t("开启漫游流量并获取一次公网 IP") }] : []),
];
const environmentOptions = selectedTaskDeviceIsReader || !advancedTasksAvailable
? [{ value: "vowifi", label: "VoWiFi" }]
: [{ value: "vowifi", label: "VoWiFi" }, { value: "cellular", label: t("基站直连(自动选网)") }];
return (
<div className="mx-auto max-w-7xl">
<PageHeader
title={t("自动任务")}
subtitle={t("按周期切换指定 eSIM Profile,并在设备串行队列中执行短信、通话或漫游公网 IP 任务")}
subtitle={advancedTasksAvailable
? t("按周期切换指定 eSIM Profile,并在设备串行队列中执行短信、通话或漫游公网 IP 任务")
: t("按周期切换指定 eSIM Profile,并在设备串行队列中执行短信或通话任务")}
actions={<Button variant="primary" icon={<AddRegular />} onClick={() => edit()} disabled={!devices.length}>{t("添加任务")}</Button>}
/>
@@ -454,8 +484,8 @@ export default function AutomaticTasksPage() {
</tbody>
</table>
</div>
{!runs.length ? <div className="p-8 text-center text-sm text-gray-400">{t("暂无执行记录")}</div> : null}
{runsTotal > 0 ? (
{!runs.length ? <div className="p-8 text-center text-sm text-gray-400">{t("暂无执行记录")}</div> : null}
{runsTotal > 0 ? (
<div className="border-t border-gray-100 px-5 py-3 dark:border-white/10">
<Pagination
page={runsPage}
@@ -473,13 +503,14 @@ export default function AutomaticTasksPage() {
<div className="md:col-span-2"><label className={fieldLabel}>{t("任务名称")}</label><Input value={form.name} onChange={(event) => setForm({ ...form, name: event.target.value })} placeholder={t("例如:每日短信保活")} /></div>
<div><label className={fieldLabel}>{t("设备")}</label><Select value={form.deviceId} onChange={chooseDevice} options={devices.map((device) => ({ value: device.id, label: `${device.name || device.id} (${device.id})` }))} /></div>
<div><label className={fieldLabel}>{t("eSIM Profile")}</label><Select value={form.profileIccid} onChange={chooseProfile} disabled={profileLoading || !form.deviceId} placeholder={profileLoading ? t("读取 Profile 中...") : t("请选择 Profile")} options={profiles.map((profile) => ({ value: profile.iccid, label: profile.label }))} /></div>
<div><label className={fieldLabel}>{t("任务类型")}</label><Select value={form.taskType} onChange={(value) => chooseTaskType(value as TaskType)} options={[{ value: "sms", label: t("发送短信") }, { value: "call", label: t("拨打电话并自动挂断") }, { value: "public_ip", label: t("开启漫游流量并获取一次公网 IP") }]} /></div>
<div><label className={fieldLabel}>{t("执行环境")}</label><Select value={form.environment} onChange={(value) => setForm({ ...form, environment: value as TaskEnvironment })} disabled={form.taskType === "public_ip"} options={[{ value: "vowifi", label: "VoWiFi" }, { value: "cellular", label: t("基站直连(自动选网)") }]} /></div>
<div><label className={fieldLabel}>{t("任务类型")}</label><Select value={form.taskType} onChange={(value) => chooseTaskType(value as TaskType)} options={taskTypeOptions} /></div>
<div><label className={fieldLabel}>{t("执行环境")}</label><Select value={form.environment} onChange={(value) => setForm({ ...form, environment: value as TaskEnvironment })} disabled={form.taskType === "public_ip" || selectedTaskDeviceIsReader} options={environmentOptions} /></div>
{selectedTaskDeviceIsReader ? <div className="md:col-span-2 rounded-lg border border-sky-200 bg-sky-50 p-3 text-sm text-sky-700 dark:border-sky-500/20 dark:bg-sky-500/10 dark:text-sky-300">{t("USB SIM读卡器仅支持VoWiFi短信和通话任务")}</div> : null}
{form.taskType !== "public_ip" ? <div><label className={fieldLabel}>{t("号码")}</label><Input value={form.phone} onChange={(event) => setForm({ ...form, phone: event.target.value })} placeholder="+447700900123" /></div> : null}
{form.taskType === "call" ? <div><label className={fieldLabel}>{t("自动挂断")}</label><Input type="number" min={1} max={600} value={form.durationSeconds} suffix="s" onChange={(event) => setForm({ ...form, durationSeconds: Number(event.target.value) })} /></div> : null}
{form.taskType === "sms" ? <div className="md:col-span-2"><label className={fieldLabel}>{t("短信内容")}</label><Textarea rows={4} value={form.message} onChange={(event) => setForm({ ...form, message: event.target.value })} /></div> : null}
{form.taskType === "public_ip" ? <div className="md:col-span-2 rounded-lg border border-amber-200 bg-amber-50 p-3 text-sm text-amber-700 dark:border-amber-500/20 dark:bg-amber-500/10 dark:text-amber-300">{t("该任务固定使用基站直连和自动选网;执行时会开启漫游数据,并通过模块接口访问 ipinfo.io。需要开启开发者模式。")}</div> : null}
{advancedTasksAvailable && form.taskType === "public_ip" ? <div className="md:col-span-2 rounded-lg border border-amber-200 bg-amber-50 p-3 text-sm text-amber-700 dark:border-amber-500/20 dark:bg-amber-500/10 dark:text-amber-300">{t("该任务固定使用基站直连和自动选网;执行时会开启漫游数据,并通过模块接口访问 ipinfo.io。")}</div> : null}
<div><label className={fieldLabel}>{t("首次执行日期")}</label><Input type="date" value={form.startDate} onChange={(event) => setForm({ ...form, startDate: event.target.value })} /></div>
<div><label className={fieldLabel}>{t("执行时间")}</label><Input type="time" value={form.runTime} onChange={(event) => setForm({ ...form, runTime: event.target.value })} /></div>
+12 -3
View File
@@ -32,6 +32,7 @@ const EMPTY_ADD: AddDeviceForm = {
atPort: "",
controlDevice: "",
deviceBackend: "at",
simPin: "",
};
export default function DevicesPage() {
@@ -373,7 +374,8 @@ export default function DevicesPage() {
setAddSelected(d);
setAddConfig((prev) => {
const mode = String(d.mode || "").toLowerCase();
const backend = mode === "mbim" ? "mbim" : isQmiControl(d.controlPath) || (mode === "qmi" && d.controlPath) ? "qmi" : "at";
const isReader = d.hardwareKind === "pcsc" || mode === "pcsc";
const backend = isReader ? "pcsc" : mode === "mbim" ? "mbim" : isQmiControl(d.controlPath) || (mode === "qmi" && d.controlPath) ? "qmi" : "at";
return {
...prev,
interface: d.netInterface || "",
@@ -382,6 +384,8 @@ export default function DevicesPage() {
modemImei: d.imei || "",
usbPath: d.usbPath || "",
deviceBackend: backend,
deviceType: isReader ? "usb_sim_reader" : prev.deviceType,
esimTransport: isReader ? "pcsc" : backend,
};
});
}, []);
@@ -574,6 +578,10 @@ export default function DevicesPage() {
const unconfiguredDiscovered = useMemo(() => discovered.filter((d) => !d.configured), [discovered]);
const detailOnline = isDeviceOnline(detail);
const isReader = detail?.deviceType === "usb_sim_reader";
useEffect(() => {
if (isReader && ["at", "ussd"].includes(activeTab)) setActiveTab("overview");
}, [isReader, activeTab]);
const addAtLimit = deviceLimit > 0 && list.length >= deviceLimit;
const tabItems = [
{ key: "overview", label: t("概览") },
@@ -582,7 +590,7 @@ export default function DevicesPage() {
{ key: "ussd", label: t("USSD") },
{ key: "config", label: t("配置") },
{ key: "card", label: t("卡策略") },
];
].filter((tab) => !isReader || !["at", "ussd"].includes(tab.key));
const overviewNode = detail ? (
<div className="space-y-4">
@@ -673,6 +681,7 @@ export default function DevicesPage() {
onReconnectVowifi={handleReconnectVoWiFi}
onRebootModem={handleRebootModem}
onOpenSms={handleOpenSms}
wifiCallingOnly={isReader}
/>
<div className="device-detail-tabs ui-card p-6">
<Tabs tabs={tabItems} value={activeTab} onChange={handleTabChange} />
@@ -697,7 +706,7 @@ export default function DevicesPage() {
<DeviceConfigTab editConfig={editConfig} deviceStatus={detail} saving={saving} deleting={deleting} onSave={handleSaveConfig} onDelete={handleDeleteDevice} onEditConfig={setEditConfig} />
) : null}
{activeTab === "card" ? (
<CardPolicyPanel deviceId={detail.id} iccid={detail.modem?.iccid} policy={cardPolicy} deviceOnline={detailOnline} onPolicyChanged={handlePolicyChanged} />
<CardPolicyPanel deviceId={detail.id} iccid={detail.modem?.iccid} policy={cardPolicy} deviceOnline={detailOnline} onPolicyChanged={handlePolicyChanged} wifiCallingOnly={isReader} />
) : null}
</div>
</div>
+2 -2
View File
@@ -177,7 +177,7 @@ export default function SettingsPage() {
}, [lang]);
const onSaveDeviceLimit = useCallback(async () => {
const maximum = developerSettings?.maxDeviceLimit ?? 128;
const maximum = developerSettings?.maxDeviceLimit ?? 10;
if (!Number.isInteger(deviceLimit) || deviceLimit < 1 || deviceLimit > maximum) {
message.error(lang === "zh" ? `设备配额必须是 1 到 ${maximum} 的整数` : `Device quota must be an integer between 1 and ${maximum}`);
return;
@@ -196,7 +196,7 @@ export default function SettingsPage() {
}, [developerSettings, deviceLimit, lang]);
const onSaveSMSHourlyLimit = useCallback(async () => {
const maximum = developerSettings?.maxSmsHourlyLimit ?? 1000;
const maximum = developerSettings?.maxSmsHourlyLimit ?? 20;
if (!Number.isInteger(smsHourlyLimit) || smsHourlyLimit < 1 || smsHourlyLimit > maximum) {
message.error(lang === "zh" ? `短信发送限制必须是 1 到 ${maximum} 的整数` : `SMS limit must be an integer between 1 and ${maximum}`);
return;
+6 -3
View File
@@ -1,6 +1,6 @@
export type ApiStatus = "ok" | "error";
export type DeviceType = "wifi_410" | "dji_4g" | "pcie_ec20_ec25";
export type DeviceType = "wifi_410" | "dji_4g" | "pcie_ec20_ec25" | "usb_sim_reader";
export interface Session {
authenticated: boolean;
@@ -167,6 +167,8 @@ export interface DeviceStatus {
}
export interface DiscoveredDevice {
hardwareKind?: string;
readerName?: string;
discoveryKey: string;
controlPath: string;
netInterface: string;
@@ -196,14 +198,15 @@ export interface DeviceConfig {
usbPath: string;
audioDevice?: string;
modemImei?: string;
simPin?: string;
apn: string;
proxyPort: number;
baudRate: number;
dataBits: number;
stopBits: number;
parity: string;
deviceBackend: "at" | "qmi";
esimTransport: "at" | "qmi";
deviceBackend: "at" | "qmi" | "pcsc";
esimTransport: "at" | "qmi" | "pcsc" | "none";
qmiUseProxy: boolean;
qmiProxyPath?: string;
qmiProxyExecutable?: string;