Discover Ethernet routers under the board, map physical SIM slots, expose vendor controls and real telemetry, and provide packaged VPS speed tests with a live monochrome gauge. Enforce compact typography across Core and Node UI.
323 lines
10 KiB
Go
323 lines
10 KiB
Go
package routers
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/rand"
|
|
"crypto/sha256"
|
|
"crypto/tls"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"io"
|
|
"math"
|
|
"net"
|
|
"net/http"
|
|
"net/url"
|
|
"os/exec"
|
|
"regexp"
|
|
"runtime"
|
|
"strconv"
|
|
"sync"
|
|
"sync/atomic"
|
|
"syscall"
|
|
"time"
|
|
)
|
|
|
|
type speedGrant struct {
|
|
Endpoint string `json:"endpoint"`
|
|
Address string `json:"address"`
|
|
Fingerprint string `json:"fingerprint"`
|
|
Token string `json:"token"`
|
|
ExpiresAt int64 `json:"expires_at"`
|
|
ServerID string `json:"server_id"`
|
|
}
|
|
type Measurement struct {
|
|
Phase string `json:"phase"`
|
|
ServerID string `json:"server_id"`
|
|
Interface string `json:"interface"`
|
|
StartedAt int64 `json:"started_at"`
|
|
FinishedAt int64 `json:"finished_at,omitempty"`
|
|
SampledAt int64 `json:"sampled_at,omitempty"`
|
|
CurrentBPS float64 `json:"current_bps"`
|
|
DownloadBPS float64 `json:"download_bps"`
|
|
UploadBPS float64 `json:"upload_bps"`
|
|
LatencyMS float64 `json:"latency_ms"`
|
|
JitterMS float64 `json:"jitter_ms"`
|
|
Error string `json:"error,omitempty"`
|
|
}
|
|
|
|
func validSpeedtest(c Command) bool {
|
|
if c.Query != nil || c.Settings != nil || c.Username != "" || c.Password != "" || c.Policy != nil || c.ClientAPI != nil || c.ModelID != "" || c.Mode != "" || c.SIM != "" || c.Recovery != "" || len(c.Slots) != 0 || c.ExpectedBootID != "" || c.ExpectedRevision != "" {
|
|
return false
|
|
}
|
|
if c.Action == "speedtest_cancel" {
|
|
return c.Speedtest == nil && operationID.MatchString(c.SpeedtestCancel)
|
|
}
|
|
g := c.Speedtest
|
|
if c.Action != "speedtest" || c.SpeedtestCancel != "" || g == nil {
|
|
return false
|
|
}
|
|
u, e := url.Parse(g.Endpoint)
|
|
ip := net.ParseIP(g.Address)
|
|
if e != nil || u.Scheme != "https" || u.User != nil || u.Hostname() == "" || u.Path != "" || u.RawQuery != "" || u.Fragment != "" || ip == nil || ip.To4() == nil || !ip.IsGlobalUnicast() || ip.IsPrivate() || ip.IsLoopback() || ip.IsLinkLocalUnicast() {
|
|
return false
|
|
}
|
|
port, e := strconv.Atoi(u.Port())
|
|
return e == nil && port >= 1024 && port <= 65535 && regexp.MustCompile(`^[a-f0-9]{64}$`).MatchString(g.Fingerprint) && regexp.MustCompile(`^[A-Za-z0-9_-]{43}$`).MatchString(g.Token) && regexp.MustCompile(`^ls_[a-f0-9]{32}$`).MatchString(g.ServerID) && g.ExpiresAt > time.Now().Unix() && g.ExpiresAt <= time.Now().Add(95*time.Second).Unix()
|
|
}
|
|
func speedRoute(ctx context.Context, d Device, address string) error {
|
|
if runtime.GOOS != "linux" || d.Connection != "ethernet" || !d.Attached || !regexp.MustCompile(`^[a-zA-Z0-9_.-]{1,15}$`).MatchString(d.Interface) || net.ParseIP(d.LocalIP) == nil {
|
|
return errors.New("ethernet_unavailable")
|
|
}
|
|
raw, e := exec.CommandContext(ctx, "ip", "-j", "route", "get", address, "from", d.LocalIP, "oif", d.Interface).Output()
|
|
if e != nil || len(raw) > 8192 {
|
|
return errors.New("ethernet_route_unavailable")
|
|
}
|
|
var routes []struct {
|
|
Dev string `json:"dev"`
|
|
Gateway string `json:"gateway"`
|
|
Source string `json:"prefsrc"`
|
|
}
|
|
if json.Unmarshal(raw, &routes) != nil || len(routes) != 1 || routes[0].Dev != d.Interface || routes[0].Gateway != d.Address {
|
|
return errors.New("ethernet_route_unavailable")
|
|
}
|
|
return nil
|
|
}
|
|
func speedClient(g speedGrant, d Device) *http.Client {
|
|
u, _ := url.Parse(g.Endpoint)
|
|
dial := net.Dialer{Timeout: 8 * time.Second, LocalAddr: &net.TCPAddr{IP: net.ParseIP(d.LocalIP)}, Control: func(_, _ string, c syscall.RawConn) error {
|
|
var err error
|
|
if runtime.GOOS != "linux" {
|
|
return errors.New("unsupported_platform")
|
|
}
|
|
e := c.Control(func(fd uintptr) { err = syscall.SetsockoptString(int(fd), syscall.SOL_SOCKET, 25, d.Interface) }) // Linux SO_BINDTODEVICE; never changes host routes.
|
|
if e != nil {
|
|
return e
|
|
}
|
|
return err
|
|
}}
|
|
transport := &http.Transport{Proxy: nil, DisableCompression: true, MaxIdleConnsPerHost: 4, ResponseHeaderTimeout: 8 * time.Second, TLSHandshakeTimeout: 8 * time.Second,
|
|
DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
|
|
return dial.DialContext(ctx, "tcp4", net.JoinHostPort(g.Address, u.Port()))
|
|
},
|
|
TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS13, InsecureSkipVerify: true, VerifyConnection: func(cs tls.ConnectionState) error { // Explicit certificate pin replaces CA trust, before any HTTP secret.
|
|
if len(cs.PeerCertificates) == 0 {
|
|
return errors.New("certificate_rejected")
|
|
}
|
|
cert := cs.PeerCertificates[0]
|
|
sum := sha256.Sum256(cert.Raw)
|
|
if hex.EncodeToString(sum[:]) != g.Fingerprint || time.Now().Before(cert.NotBefore) || time.Now().After(cert.NotAfter) {
|
|
return errors.New("certificate_rejected")
|
|
}
|
|
return nil
|
|
}}}
|
|
return &http.Client{Transport: transport, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("redirect_rejected") }}
|
|
}
|
|
func speedRequest(ctx context.Context, client *http.Client, g speedGrant, path string, body []byte) (*http.Response, error) {
|
|
method := "GET"
|
|
if body != nil {
|
|
method = "POST"
|
|
}
|
|
req, e := http.NewRequestWithContext(ctx, method, g.Endpoint+"/v1/test/"+path, bytes.NewReader(body))
|
|
if e != nil {
|
|
return nil, e
|
|
}
|
|
req.Header.Set("Authorization", "Bearer "+g.Token)
|
|
req.Header.Set("Cache-Control", "no-store")
|
|
response, e := client.Do(req)
|
|
if e != nil {
|
|
return nil, e
|
|
}
|
|
if response.StatusCode != 200 {
|
|
response.Body.Close()
|
|
return nil, errors.New("server_rejected")
|
|
}
|
|
return response, nil
|
|
}
|
|
func measureTransfer(ctx context.Context, client *http.Client, g speedGrant, upload bool, duration time.Duration, progress func(float64)) (float64, error) {
|
|
phase, cancel := context.WithTimeout(ctx, duration)
|
|
defer cancel()
|
|
var total atomic.Int64
|
|
var failed atomic.Bool
|
|
var workers sync.WaitGroup
|
|
payload := make([]byte, 1024*1024)
|
|
if _, e := rand.Read(payload); e != nil {
|
|
return 0, e
|
|
}
|
|
started := time.Now()
|
|
for range 3 {
|
|
workers.Add(1)
|
|
go func() {
|
|
defer workers.Done()
|
|
buffer := make([]byte, 65536)
|
|
for phase.Err() == nil {
|
|
path := "download"
|
|
var body []byte
|
|
if upload {
|
|
path = "upload"
|
|
body = payload
|
|
}
|
|
response, e := speedRequest(phase, client, g, path, body)
|
|
if e != nil {
|
|
if phase.Err() == nil {
|
|
failed.Store(true)
|
|
}
|
|
return
|
|
}
|
|
for {
|
|
n, readErr := response.Body.Read(buffer)
|
|
if !upload {
|
|
total.Add(int64(n))
|
|
}
|
|
if readErr != nil {
|
|
if readErr != io.EOF && phase.Err() == nil {
|
|
failed.Store(true)
|
|
}
|
|
break
|
|
}
|
|
}
|
|
response.Body.Close()
|
|
if upload && phase.Err() == nil {
|
|
total.Add(int64(len(payload)))
|
|
}
|
|
}
|
|
}()
|
|
}
|
|
done := make(chan struct{})
|
|
go func() { workers.Wait(); close(done) }()
|
|
ticker := time.NewTicker(time.Second)
|
|
defer ticker.Stop()
|
|
waiting := true
|
|
for waiting {
|
|
select {
|
|
case <-done:
|
|
waiting = false
|
|
case <-ticker.C:
|
|
if progress != nil && phase.Err() == nil {
|
|
progress(float64(total.Load()) * 8 / time.Since(started).Seconds())
|
|
}
|
|
}
|
|
}
|
|
if ctx.Err() != nil {
|
|
return 0, ctx.Err()
|
|
}
|
|
if total.Load() == 0 || failed.Load() {
|
|
return 0, errors.New("transfer_failed")
|
|
}
|
|
return float64(total.Load()) * 8 / time.Since(started).Seconds(), nil
|
|
}
|
|
func (c *Collector) runSpeedtest(ctx context.Context, cmd Command) {
|
|
if cmd.Action == "speedtest_cancel" {
|
|
c.mu.Lock()
|
|
if c.speedOperation == cmd.SpeedtestCancel && c.speedDevice == cmd.DeviceID && c.speedCancel != nil {
|
|
c.speedCancel()
|
|
}
|
|
if _, exists := c.results[cmd.SpeedtestCancel]; !exists {
|
|
c.results[cmd.SpeedtestCancel] = Result{ID: cmd.SpeedtestCancel, DeviceID: cmd.DeviceID, Action: "speedtest", State: "complete", At: time.Now().Unix()}
|
|
c.resultTimes[cmd.SpeedtestCancel] = time.Now()
|
|
}
|
|
c.results[cmd.ID] = Result{ID: cmd.ID, DeviceID: cmd.DeviceID, Action: cmd.Action, State: "complete", At: time.Now().Unix()}
|
|
c.mu.Unlock()
|
|
return
|
|
}
|
|
record, ok := c.state.Records[cmd.DeviceID]
|
|
if !ok {
|
|
return
|
|
}
|
|
c.mu.Lock()
|
|
if c.speedCancel != nil {
|
|
c.results[cmd.ID] = Result{ID: cmd.ID, DeviceID: cmd.DeviceID, Action: cmd.Action, State: "error", Error: "router_busy"}
|
|
c.mu.Unlock()
|
|
return
|
|
}
|
|
deadline := min(cmd.Deadline, cmd.Speedtest.ExpiresAt)
|
|
test, cancel := context.WithDeadline(ctx, time.Unix(deadline, 0))
|
|
c.speedCancel = cancel
|
|
c.speedOperation = cmd.ID
|
|
c.speedDevice = cmd.DeviceID
|
|
c.mu.Unlock()
|
|
go func() {
|
|
defer cancel()
|
|
m := Measurement{Phase: "latency", ServerID: cmd.Speedtest.ServerID, Interface: record.Device.Interface, StartedAt: time.Now().Unix()}
|
|
report := func(state string) {
|
|
copy := m
|
|
c.mu.Lock()
|
|
c.results[cmd.ID] = Result{ID: cmd.ID, DeviceID: cmd.DeviceID, Action: cmd.Action, State: state, At: time.Now().Unix(), Measurement: ©}
|
|
c.mu.Unlock()
|
|
select {
|
|
case c.speedUpdates <- struct{}{}:
|
|
default:
|
|
}
|
|
}
|
|
progress := func(bps float64) { m.CurrentBPS = bps; m.SampledAt = time.Now().UnixMilli(); report("applying") }
|
|
report("applying")
|
|
e := speedRoute(test, record.Device, cmd.Speedtest.Address)
|
|
if e == nil {
|
|
client := speedClient(*cmd.Speedtest, record.Device)
|
|
defer func() {
|
|
cleanup, cancelCleanup := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer cancelCleanup()
|
|
r, err := speedRequest(cleanup, client, *cmd.Speedtest, "finish", []byte{})
|
|
if err == nil {
|
|
r.Body.Close()
|
|
}
|
|
}()
|
|
defer client.CloseIdleConnections()
|
|
var sum, jitter, previous float64
|
|
for i := 0; i < 7; i++ {
|
|
started := time.Now()
|
|
var response *http.Response
|
|
response, e = speedRequest(test, client, *cmd.Speedtest, "ping", nil)
|
|
if e != nil {
|
|
break
|
|
}
|
|
_, e = io.Copy(io.Discard, io.LimitReader(response.Body, 4096))
|
|
response.Body.Close()
|
|
if e != nil {
|
|
break
|
|
}
|
|
ms := float64(time.Since(started).Microseconds()) / 1000
|
|
sum += ms
|
|
if i > 0 {
|
|
jitter += math.Abs(ms - previous)
|
|
}
|
|
previous = ms
|
|
}
|
|
if e == nil {
|
|
m.LatencyMS = sum / 7
|
|
m.JitterMS = jitter / 6
|
|
m.Phase = "download"
|
|
report("applying")
|
|
m.DownloadBPS, e = measureTransfer(test, client, *cmd.Speedtest, false, 10*time.Second, progress)
|
|
}
|
|
if e == nil {
|
|
m.Phase = "upload"
|
|
m.CurrentBPS = 0
|
|
m.SampledAt = 0
|
|
report("applying")
|
|
m.UploadBPS, e = measureTransfer(test, client, *cmd.Speedtest, true, 10*time.Second, progress)
|
|
}
|
|
if e == nil {
|
|
e = speedRoute(test, record.Device, cmd.Speedtest.Address)
|
|
}
|
|
}
|
|
m.FinishedAt = time.Now().Unix()
|
|
m.Phase = "complete"
|
|
if e != nil {
|
|
m.Phase = "error"
|
|
m.Error = "measurement_failed"
|
|
if test.Err() == context.Canceled {
|
|
m.Phase = "cancelled"
|
|
m.Error = ""
|
|
} else if e.Error() == "ethernet_route_unavailable" || e.Error() == "ethernet_unavailable" {
|
|
m.Error = e.Error()
|
|
}
|
|
}
|
|
report("complete")
|
|
c.mu.Lock()
|
|
c.speedCancel = nil
|
|
c.mu.Unlock()
|
|
}()
|
|
}
|